diff --git "a/4787.jsonl" "b/4787.jsonl" new file mode 100644--- /dev/null +++ "b/4787.jsonl" @@ -0,0 +1,598 @@ +{"seq_id":"68815033","text":"import sys\nimport math\n\ndef distance(src,dst):\n return math.sqrt((src(1)-src(2))**2+(dst(1)-dst(2))**2)\n\n# game loop\nwhile True:\n my_ship_count = int(input()) # the number of remaining ships\n entity_count = int(input()) # the number of entities (e.g. ships, mines or cannonballs)\n barrels = []\n for i in range(entity_count):\n # Get the parameters\n entity_id, entity_type, x, y, arg_1, arg_2, arg_3, arg_4 = input().split()\n entity_id = int(entity_id)\n x = int(x)\n y = int(y)\n arg_1 = int(arg_1)\n arg_2 = int(arg_2)\n arg_3 = int(arg_3)\n arg_4 = int(arg_4)\n\n if entity_type == 'BARREL':\n barrels.append((x,y,arg_1,arg_2,arg_3,arg_4))\n\n for i in range(my_ship_count):\n\n # Write an action using print\n # To debug: print(\"Debug messages...\", file=sys.stderr)\n\n # Any valid action, such as \"WAIT\" or \"MOVE x y\"\n print(\"MOVE {} {}\".format(barrels[0][0],barrels[0][1]))\n","sub_path":"Competition/CodersOfTheCaraeeben/wood3.py","file_name":"wood3.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"516276155","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rc(\"font\", size=14)\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nimport seaborn as sns\n\nsns.set()\n\ndf = pd.read_csv('KaggleV2-May-2016.csv')\n\n# rename columns\ndf.rename(columns={\n 'PatientId': 'patient_id',\n 'AppointmentID': 'appointment_id',\n 'Gender': 'gender',\n 'ScheduledDay': 'scheduled_day',\n 'AppointmentDay': 'appointment_day',\n 'Age': 'age',\n 'Neighbourhood': 'neighborhood',\n 'Scholarship': 'scholarship',\n 'Hipertension': 'hypertension',\n 'Diabetes': 'diabetes',\n 'Alcoholism': 'alcoholism',\n 'Handcap': 'handicap',\n 'SMS_received': 'sms_received',\n 'No-show': 'no_show'\n}, inplace=True)\n\n# Remove Appointment ID\ndf.drop(['appointment_id'], axis=1, inplace=True)\n\n# Format Patient ID, Gender, and Neighborhood to a string\ndf.patient_id = df['patient_id'].apply(lambda patient: str(int(patient)))\ndf.gender = df['gender'].apply(lambda patient_gender: str(patient_gender))\ndf.neighborhood = df['neighborhood'].apply(lambda patient_neighborhood: str(patient_neighborhood))\n\n# format dates\ndf.scheduled_day = pd.to_datetime(df.scheduled_day)\ndf.appointment_day = pd.to_datetime(df.appointment_day)\n\n# delete row with age < 0\ndf = df.query('age >= 0')\n\n# Transform no-shows and gender\ndf.no_show = df['no_show'].map({'Yes': 1, 'No': 0})\ndf.gender = df['gender'].map({'M': 1, 'F': 0})\n\n\n# add columns for day of week of appointment and scheduled days\ndf['appointment_day_of_week'] = df.appointment_day.map(lambda day: day.dayofweek)\ndf['scheduled_day_of_week'] = df.scheduled_day.map(lambda day: day.dayofweek)\n\n\n# add column for days elapsed between scheduled date and appointment date\ndf['appointment_lag'] = df.appointment_day - df.scheduled_day\ndf.appointment_lag = df.appointment_lag.abs().dt.days\n\n# print(df.query('appointment_lag > 60'))\n\ngender = df.gender\nappointment_day_of_week = df.appointment_day_of_week\nscheduled_day_of_week = df.scheduled_day_of_week\nappointment_lag = df.appointment_lag\nage = df.age\nscholarship = df.scholarship\nhypertension = df.hypertension\ndiabetes = df.diabetes\nalcoholism = df.alcoholism\nhandicap = df.handicap\nsms_received = df.sms_received\nno_show = df.no_show\n\n# Create subset of df for correlation matrix\nmodel_data = pd.concat([\n gender,\n appointment_day_of_week,\n scheduled_day_of_week,\n appointment_lag,\n age,\n sms_received,\n no_show\n], axis=1)\n\n# separate features from labeled test set\nX = model_data.loc[:, model_data.columns != 'no_show']\ny = model_data.loc[:, model_data.columns == 'no_show']\n\n# Split data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=0)\n\n\n# Fit the model\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, np.ravel(y_train))\n\n# Get probability estimates for no-shows\nprobs = model.predict_proba(X_test)\nprobs = probs[:, 1]\n\n\nauc = roc_auc_score(y_test, probs)\nprint('\\n\\nArea Under Curve: %.3f' % auc)\n\n# Get false-positive rate, true-positive rate, and thresholds\nfpr, tpr, thresholds = roc_curve(y_test, probs)\n\n# # Plot the roc curve\nplt.plot([0,1], [0,1], linestyle='--')\nplt.plot(fpr, tpr, marker='.')\nplt.title('Decision Tree ROC')\nplt.show()\n\n# Perform cross-validation\nscores = cross_val_score(model, X_train, np.ravel(y_train), cv=10)\nprint(\"\\n\\nCross-validated scores:\", scores)\n\n\n# Predict logistic model test results\ny_predicted = model.predict(X_test)\nprint('\\n\\nAccuracy of model classifier on test set: {:.2f}'.format(model.score(X_test, y_test)))\n\n# Build confusion matrix\nconfusion_matrix = confusion_matrix(y_test, y_predicted)\nprint(\"\\n\\n Confusion Matrix:\\n\", confusion_matrix)\n\n# Build classification report\nprint(\"\\n\\n\", classification_report(y_test, y_predicted))","sub_path":"HW2/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"155975214","text":"# # 4. Sum Adjacent Equal Numbers\n# n, lista = input(), []\n# s = n.split(' ')\n# for k in s:\n# try:\n# lista.append(int(k))\n# except:\n# lista.append(float(k))\n#\n#\n# def calculate(lista):\n# for count, i in enumerate(lista):\n# numm = i\n# try:\n# if numm == lista[count + 1]:\n# lista[count] = numm * 2\n# lista.remove(lista[count + 1])\n# calculate(lista)\n# except:\n# break\n# return lista\n#\n#\n# result = calculate(lista)\n# for i in result:\n# print(i, end=' ')\n\n# # 5. Split by Word Casing\n# import re\n# n = input()\n# result = re.findall(r\"[\\w#]+\", n)\n# lower, uper, mixed = [], [], []\n# for i in result:\n# if i.islower():\n# lower.append(i)\n# elif i.isupper():\n# uper.append(i)\n# else:\n# mixed.append(i)\n# print('Lower-case:', end=' ')\n# for j in lower:\n# print(j, end=' ')\n# print()\n# print('Mixed-case:', end=' ')\n# for k in mixed:\n# print(k, end=' ')\n# print()\n# print('Upper-case:', end=' ')\n# for s in uper:\n# print(s, end=' ')\n\n# 8. Count Numbers\nfrom collections import Counter\nn, lista = input(), []\ns = n.split(' ')\nfor j in s:\n lista.append(int(j))\n\nresult = Counter(lista)\nseted = sorted(list(set(lista)))\n# print(result)\n# print(seted)\n\nfor i in seted:\n print('{} -> {}'.format(i, result[i]))","sub_path":"Lists-Lab.py","file_name":"Lists-Lab.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242883349","text":"\n'''\nOpen Read and Close File\nUse the match and search regex functions\n\nNotes on raw string:\nThe r prefix says to not interpret a backslash\nand the following character as a single escape character,\nbut to instead interpret them as two raw characters.\n\nIn the case of the \"\\d\" for a regex \"digit\",\nit does not collide with any of the standard string escapes.\nSo raw or not, the phone number search string behaves the same.\n\nHowever, if the \"\\b\" was used,\nit would mean a \"word boundary\" in a raw string,\nbut get interpreted as the \"BELL\" in a\nregular unicode string.\n\n'''\n\nimport re\n\n#let us get a pointer to the File\np_text = open('myText.txt',encoding='utf-8')\n\n# read the content into a variable\nv_text = p_text.read()\n\n# Ok data is in the variable, so let us close the File\np_text.close()\n\n#lets print data\n#print(v_text)\n#print(type(v_text))\n\n#matching\nv_match = r'sanjay'\nv_search = r'sonia'\n#print(re.match(v_match,v_text)) # matches only at the start of the string\n#print(re.search(v_search,v_text))\n\n# search for a word\nv_word_pattern = r'123'\n#print(re.match(v_word_pattern,v_text))\n\n#return first number\nv_pattern = r'\\d'\nprint(re.search(v_pattern,v_text))\n","sub_path":"regex1.py","file_name":"regex1.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574120677","text":"import pygame\nprint(\"Welcome to Sokoban\")\npygame.init()\nwidth=400\nheight=400\nscreen = pygame.display.set_mode((width,height))\npygame.display.set_caption('Sokoban')\ndone = False\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n \tdone=True\n screen.fill((105,105,105))\npygame.quit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"436502041","text":"from TournamentDescriptionClasses import Result\nimport random\nimport sys\nimport matplotlib.pyplot as plt\nfrom typing import List\n\nrankDeltaToResultDelta = [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 13,\n 13,\n 13,\n 13,\n 13,\n]\n\n\ndef swap(list: List[str], indexA: int, indexB: int):\n temp = list[indexA]\n list[indexA] = list[indexB]\n list[indexB] = temp\n\n\ndef calculateTotalError(currentRanking: List[str], results: List[Result]) -> float:\n lossSum = 0\n for result in results:\n rankA = currentRanking.index(result.matchUp.first)\n rankB = currentRanking.index(result.matchUp.second)\n rankDelta = rankA - rankB\n resultDelta = result.first - result.second\n predictedResultDelta = rankDeltaToResultDelta[abs(rankDelta)]\n if rankDelta > 0:\n predictedResultDelta *= -1\n lossSum += (resultDelta - predictedResultDelta)**2\n return lossSum\n\n\ndef generateNewRanking(currentRanking: List[str], results: List[Result], debug=False) -> List[str]:\n losses = []\n minimalLoss = sys.maxsize\n minimalLossRanking = currentRanking[:]\n newRanking = currentRanking[:]\n decay = 0.9999\n pAcceptWorse = 0.5 # probability to accept a worse result\n for i in range(0,1000000):\n currentLoss = calculateTotalError(newRanking, results)\n losses.append(currentLoss)\n indexA = random.randint(0, len(currentRanking)-1)\n indexB = indexA\n while indexA == indexB:\n indexB = random.randint(0, len(currentRanking)-1)\n swap(newRanking, indexA, indexB)\n newLoss = calculateTotalError(newRanking, results)\n if newLoss < minimalLoss: # save optimal solution\n minimalLoss = newLoss\n minimalLossRanking = newRanking[:]\n if newLoss > currentLoss and random.uniform(0.0, 1.0) > pAcceptWorse: # do not accept worse value\n swap(newRanking, indexA, indexB)\n pAcceptWorse *= decay\n if debug:\n for item in minimalLossRanking:\n print(item)\n print(\"loss\", minimalLoss)\n print(\"pAcceptWorse\", pAcceptWorse)\n plt.plot(losses)\n plt.show()\n return minimalLossRanking\n","sub_path":"RankingGenerator.py","file_name":"RankingGenerator.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"339874246","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n nodes = [None, None]\n count = 0\n\n def DFS(self, root):\n if not root or self.count == 2:\n return\n\n if root.left and root.left.val >= root.val:\n self.nodes[self.count] = root.left\n self.count += 1\n\n self.DFS(root.left)\n\n if root.right and root.right.val < root.val:\n self.nodes[self.count] = root.right\n self.count += 1\n\n self.DFS(root.right)\n\n def recoverTree(self, root):\n if not root:\n return\n\n self.nodes = [None, None]\n self.count = 0\n self.DFS(root)\n a = self.nodes[0].val\n self.nodes[0].val = self.nodes[1].val\n self.nodes[1].val = a\n","sub_path":"99-recovery-binary-search-tree/99.py","file_name":"99.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"400786178","text":"#/usr/bin/env python3\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QPushButton, QFileDialog, QMessageBox\nimport sys\nimport ui\nimport zlib\nimport os\n\n#\n# A tool to extract PRG and CHR ROMs, FDS Bios, and FDS QD's from TNES ROM files, and to convert from TNES ROMs to INES ROMs \n#\n\ndef readFileMagic(file):\n file.seek(0, 0)\n byte = file.read(4)\n return byte\n\ndef readTNESHeader(file):\n file.seek(4, 0)\n byte = file.read(12)\n return byte\n\ntnesRom = ''\nTNESHeaderMinusMagic = ''\n\nclass TnesUIMain(QtWidgets.QMainWindow, ui.Ui_MainWindow):\n\n\n fileName = ''\n def __init__(self, parent=None):\n super(TnesUIMain, self).__init__(parent)\n self.setupUi(self)\n\n self.OpenRom.clicked.connect(self.openRomFile)\n self.TNEStoINES.clicked.connect(self.GUI_ConvToINES)\n self.ExtractQD.clicked.connect(self.GUI_ExtractQD)\n self.ExtractPRG.clicked.connect(self.GUI_ExtractPRGROM)\n self.ExtractCHR.clicked.connect(self.GUI_ExtractCHRROM)\n self.ExtractFDSBIOS.clicked.connect(self.GUI_ExtractFDSBIOS)\n\n def openRomFile(self):\n self.clearAllFields()\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n global fileName\n fileName, _ = QFileDialog.getOpenFileName(self, \"Open TNES Rom file\", \"\",\"All Files(*)\", options=options) # Types of openable files\n\n # Check if input is a TNES rom file if not, return\n global tnesRom\n tnesRom = open(fileName, 'rb')\n \n if (readFileMagic(tnesRom) != b'TNES'): # displays error if input file is not a TNES ROM\n fileName = ''\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"Input File is not a TNES ROM file.\")\n return\n\n # Fill out rom info\n global TNESHeaderMinusMagic\n TNESHeaderMinusMagic = readTNESHeader(tnesRom)\n\n # Display Rom name in textbox\n self.DisplayRomName.insertHtml('

'+fileName+\"

\")\n self.fillOutAllInfo()\n\n return\n \n \n def clearAllFields(self):\n cleared = \"N/A\"\n global fileName\n fileName = '' # Clear the File Name\n self.DisplayRomName.setText('') # Clear text box\n global TNESHeaderMinusMagic\n TNESHeaderMinusMagic = '' # Clear the Header info\n #TNES\n self.Mapper_C.setText(cleared)\n self.PRGROMSize_C.setText(cleared)\n self.PRGROMCRC_C.setText(cleared)\n self.CHRROMSize_C.setText(cleared)\n self.CHRROMCRC_C.setText(cleared)\n self.WRAM_C.setText(cleared)\n self.Mirroring_C.setText(cleared)\n self.Battery_C.setText(cleared)\n #FDS\n self.FDSBIOSCRC_C.setText(cleared)\n self.FDSDiskCount_C.setText(cleared)\n self.FDSSidesPerDisk_C.setText(cleared)\n \n def fillOutAllInfo(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n\n if (tnesHeader.getMapper() != \"FDS\"):\n self.Mapper_C.setText(tnesHeader.getMapper())\n self.PRGROMSize_C.setText(str(tnesHeader.getPRGSize()))\n self.PRGROMCRC_C.setText(hex(zlib.crc32(extracter.extPRGRom(int(tnesHeader.getPRGSize()))))[2:])\n self.CHRROMSize_C.setText(str(tnesHeader.getCHRSize()))\n if (tnesHeader.getCHRSize() != \"No CHR rom\"): # Check if TNES ROM has a CHR ROM\n self.CHRROMCRC_C.setText(hex(zlib.crc32(extracter.extCHRRom(int(tnesHeader.getPRGSize()), int(tnesHeader.getCHRSize()))))[2:])\n self.WRAM_C.setText(tnesHeader.hasWRAM())\n self.Mirroring_C.setText(tnesHeader.getMirroring())\n self.Battery_C.setText(tnesHeader.hasBattery())\n else:\n self.FDSBIOSCRC_C.setText(tnesHeader.getFDSBioscrc32(tnesRom))\n self.FDSDiskCount_C.setText(tnesHeader.getDiskCount())\n self.FDSSidesPerDisk_C.setText(tnesHeader.getSidePerDiskCount())\n\n def GUI_ExtractPRGROM(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n if (tnesHeader.getMapper() == \"FDS\"): # Error out if Tnes contains FDS file\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"Cannot extract PRG ROM from FDS TNES file.\")\n return\n else:\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n\n global fileName # Grab file path and strip to original filename\n PRGROMout, _ = QFileDialog.getSaveFileName(self, \"Save PRG Rom file\", os.path.split(fileName)[1]+\"-PRG.bin\",\".bin\", options=options)\n \n if PRGROMout: # check if PRGROMout var was set\n extracter.saveToFile(PRGROMout, extracter.extPRGRom(tnesHeader.getPRGSize()))\n \n def GUI_ExtractCHRROM(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n if (tnesHeader.getMapper() == \"FDS\"): # Error out if TNES contains FDS file\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"Cannot extract CHR ROM from FDS TNES file.\")\n return\n if (tnesHeader.getCHRSize() == \"No CHR rom\"): # Error if TNES does not have any CHR ROM\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"TNES ROM does not have any CHR ROM.\")\n return\n else:\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n\n global fileName # Grab file path and strip to original filename\n CHRROMout, _ = QFileDialog.getSaveFileName(self, \"Save CHR Rom file\", os.path.split(fileName)[1]+\"-CHR.bin\",\".bin\", options=options)\n \n if CHRROMout: # check if CHRROMout var was set\n extracter.saveToFile(CHRROMout, extracter.extCHRRom(tnesHeader.getPRGSize(), tnesHeader.getCHRSize()))\n \n def GUI_ExtractFDSBIOS(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n if (tnesHeader.getMapper() != \"FDS\"):\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"TNES file does not contain a FDS BIOS.\")\n return\n else:\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n crc32 = tnesHeader.getFDSBioscrc32(tnesRom)\n FDSBIOSout, _ = QFileDialog.getSaveFileName(self, \"Save FDS BIOS\", crc32+\"-fds.bin\", \".bin\", options=options)\n if FDSBIOSout:\n extracter.dumpFDSBios(tnesRom, FDSBIOSout)\n \n def GUI_ExtractQD(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n global tnesRom\n if (tnesHeader.getMapper() == \"FDS\"):\n FDSQDOut, _ = QFileDialog.getSaveFileName(self, \"Save QD File\", os.path.split(fileName)[1]+\".qd\", \".qd\", options=options)\n if FDSQDOut:\n extracter.extQD(tnesRom, FDSQDOut)\n\n def GUI_ConvToINES(self):\n tnesHeader = TNESHeader()\n extracter = TNESExtractor()\n tnesConv = TNESConv()\n if (tnesHeader.getMapper() == \"FDS\"):\n errorDialog = QtWidgets.QMessageBox.warning(self, \"Error!\", \"Cannot convert FDS TNES to INES.\")\n return\n \n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n global fileName\n INESFileName = os.path.split(fileName)[1]+\".nes\"\n INESout, _ = QFileDialog.getSaveFileName(self, \"Save NES ROM\", INESFileName, \".nes\", options=options)\n if INESout:\n conv = open(INESout, \"wb\")\n conv.write(bytes(tnesConv.retINESMagic().encode(\"utf-8\")))\n conv.seek(len(tnesConv.retINESMagic()))\n #prg size\n conv.write(tnesConv.retSizeOfRomMultipleKB(tnesHeader.getPRGSize(), \"prg\"))\n #chr size\n conv.write(tnesConv.retSizeOfRomMultipleKB(tnesHeader.getCHRSize(), \"chr\"))\n\n #flag 6 - mapper, mirroring, battery\n flag6 = [0, 0, 0, 0]\n\n #handle the mappers\n mapperList = {\n 1: \"0000\",#NROM\n 2: \"0001\",#SxROM\n 3: \"1001\",#PNROM\n 4: \"0100\",#TxROM\n 5: \"1010\",#FxROM\n 6: \"0101\",#ExROM\n 7: \"0010\",#UxROM\n 8: \"0011\",#CNROM\n 9: \"0111\"}#AxROM\n\n a = int(tnesHeader.getMapper(True) + 1)\n lowerNyb = mapperList[a]\n\n #handle if the rom uses a battery backed save\n if (tnesHeader.hasBattery() == \"Yes\"):\n flag6[2] = 1\n else:\n flag6[2] = 0\n\n if (tnesHeader.getMirroring() == \"Mapper Controlled\" or tnesHeader.getMirroring() == \"Horizontal\"):\n flag6[3] = 0\n elif (tnesHeader.getMirroring() == \"Vertical\"):\n flag6[3] = 1\n\n #conv list to string\n flag6String = ''.join(str(e) for e in flag6)\n\n full = int(lowerNyb + flag6String, 2).to_bytes(1, byteorder=\"big\")\n\n conv.write(full)\n conv.write(bytes(9))\n conv.write(extracter.extPRGRom(int(tnesHeader.getPRGSize())))\n if (tnesHeader.getCHRSize() != \"No CHR rom\"):\n conv.write(extracter.extCHRRom(int(tnesHeader.getPRGSize()), int(tnesHeader.getCHRSize())))\n\n conv.close()\n\n\n\nclass TNESHeader: \n\n def getMapper(self, outputNumber=False):\n mapper = TNESHeaderMinusMagic[0]\n TNESMappers = [\"NROM\", \"SxROM\", \"PNROM\", \"TxROM\", \"FxROM\", \"ExROM\", \"UxROM\", \"CNROM\", \"AxROM\", \"FDS\"] \n if (mapper == 9):\n a = 8\n if (mapper == 100):\n a = 9\n else:\n a = mapper\n if (outputNumber == True):\n return a\n return TNESMappers[a]\n \n def getPRGSize(self):\n prgMultiple = TNESHeaderMinusMagic[1]\n if (prgMultiple == 0):\n return \"No PRG rom\"\n else:\n prgRomSize = prgMultiple * 8192\n return prgRomSize\n\n def getCHRSize(self):\n chrMultiple = TNESHeaderMinusMagic[2]\n if (chrMultiple == 0):\n return \"No CHR rom\"\n else:\n chrRomSize = chrMultiple * 8192\n return chrRomSize \n\n def hasWRAM(self):\n boolean = TNESHeaderMinusMagic[3]\n if (boolean == 0):\n return \"No\"\n if (boolean == 1):\n return \"Yes\"\n else:\n return \"Couldn't check if game uses WRAM\"\n\n def getMirroring(self):\n mirror = TNESHeaderMinusMagic[4]\n if (mirror == 0):\n return \"Mapper controlled\"\n if (mirror == 1):\n return \"Horizontal\"\n if (mirror == 2):\n return \"Vertical\"\n else:\n return \"Couldn't find mirroring type\"\n\n def hasBattery(self):\n bat = TNESHeaderMinusMagic[5]\n if (bat == 0):\n return \"No\"\n if (bat == 1):\n return \"Yes\"\n else:\n return \"Couldn't find if game uses a battery\"\n\n def getFDSBioscrc32(self, file):\n file.seek(16, 0)\n biosCRC32 = zlib.crc32(file.read(8192))\n biosCRC32 = str(hex(biosCRC32)[2:])\n return biosCRC32\n\n def getSidePerDiskCount(self):\n sides = TNESHeaderMinusMagic[6]\n mod = sides / 2\n if (((mod % 2) == 0)):\n sides = mod\n return str(int(sides))\n\n def getDiskCount(self):\n sides = int(self.getSidePerDiskCount())\n if (sides == 1):\n disks = 1.0\n if ((sides % 2) == 0):\n disks = sides / 2\n return str(disks)[:-2]\n\nclass TNESExtractor:\n def extPRGRom(self, PRGSize):\n #Seek to constant prg rom location\n tnesRom.seek(16, 0)\n\n return tnesRom.read(PRGSize)\n \n def extCHRRom(self, PRGSize, CHRSize):\n #Seek to variable chr rom location\n chrseek = PRGSize + 16\n tnesRom.seek(chrseek, 0)\n \n return tnesRom.read(CHRSize)\n \n def dumpFDSBios(self, file, fileName):\n bios = open(fileName, 'wb')\n file.seek(16, 0)\n bios.write(file.read(8192))\n bios.close\n \n def extQD(self, file, fileName):\n qd = open(fileName, 'wb')\n file.seek(8208, 0)\n qd.write(file.read())\n qd.close()\n\n def saveToFile(self, fileName, inFile):\n dump = open(fileName, 'wb')\n dump.write(inFile)\n dump.close()\n\nclass TNESConv:\n def retINESMagic(self):\n return \"NES\\x1A\"\n\n def retSizeOfRomMultipleKB(self, ROMSize, PRGorCHR):\n if (ROMSize == \"No CHR rom\" or ROMSize == \"No PRG rom\"):\n return bytes(1)\n if (PRGorCHR == \"prg\" or PRGorCHR == \"PRG\"):\n size = int(int(ROMSize) / 16000)\n elif (PRGorCHR == \"chr\" or PRGorCHR == \"CHR\"):\n size = int(int(ROMSize) / 8000)\n return size.to_bytes(1, byteorder=\"big\")\n\ndef main():\n app = QApplication(sys.argv) \n form = TnesUIMain()\n form.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()\n","sub_path":"tnes2inesGUI.py","file_name":"tnes2inesGUI.py","file_ext":"py","file_size_in_byte":13131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"167004307","text":"import time\r\nimport math\r\nstarttime = time.time()\r\nprint(\"当前时间为\",starttime)\r\ndef fibo(num):\r\n if num == 1:\r\n return 1\r\n if num == 2:\r\n return 1\r\n if num >= 3:\r\n return fibo(num-1)+fibo(num-2)\r\n\r\nprint(fibo(30))\r\n\r\nendtime = time.time()\r\nprint(\"结束时间为\",endtime)\r\ndtime = endtime - starttime\r\nprint(\"程序运行时间:%.8s s\" % dtime)\r\n\r\nstarttime1 = time.time()\r\nprint(\"当前时间为\",starttime1)\r\n\r\na=1\r\nb=1\r\n\r\nn=3000\r\nif n<=2:\r\n print(1)\r\nelse:\r\n print(1,1,end=' ')\r\n for i in range(1,n-1):\r\n a,b=b,a+b\r\n print(b,end=' ')\r\nprint()\r\n\r\nendtime1 = time.time()\r\n\r\nprint(\"结束时间为\",endtime1)\r\ndtime1 = endtime1 - starttime1\r\nprint(\"程序运行时间:%.8s s\" % dtime1)","sub_path":"shuixianhua.py","file_name":"shuixianhua.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"230526737","text":"##############################################################################\n#\n# Copyright (c) 2000-2009 Jens Vagelpohl and Contributors. All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\" LDAPUserFolder authentication tests\n\n$Id$\n\"\"\"\n\nimport unittest\n\nfrom Products.LDAPUserFolder.tests.base.testcase import LDAPTest\nfrom Products.LDAPUserFolder.tests.config import user\nug = user.get\n\nclass TestAuthentication(LDAPTest):\n\n def testAuthenticateUser(self):\n acl = self.folder.acl_users\n for role in user.get('user_roles'):\n acl.manage_addGroup(role)\n acl.manage_addUser(REQUEST=None, kwargs=user)\n user_ob = acl.authenticate( user.get(acl.getProperty('_login_attr'))\n , user.get('user_pw')\n , {}\n )\n self.failIf(user_ob is None)\n user_ob = acl.authenticate( \"%s \" % # extra space after login attr\n user.get(acl.getProperty('_login_attr'))\n , user.get('user_pw')\n , {}\n )\n self.failIf(user_ob is None)\n user_ob = acl.authenticate( \" %s\" % # extra space before login attr\n user.get(acl.getProperty('_login_attr'))\n , user.get('user_pw')\n , {}\n )\n self.failIf(user_ob is None)\n user_ob = acl.authenticate( \" %s \" % # extra spaces around login attr\n user.get(acl.getProperty('_login_attr'))\n , user.get('user_pw')\n , {}\n )\n self.failIf(user_ob is None)\n user_ob = acl.authenticate( user.get(acl.getProperty('_login_attr'))\n , ''\n , {}\n )\n self.failUnless(user_ob is None)\n user_ob = acl.authenticate( user.get(acl.getProperty('_login_attr'))\n , 'falsepassword'\n , {}\n )\n self.failUnless(user_ob is None)\n\n def testAuthenticateUserWithCache(self):\n acl = self.folder.acl_users\n for role in user.get('user_roles'):\n acl.manage_addGroup(role)\n acl.manage_addUser(REQUEST=None, kwargs=user)\n\n user_ob = acl.authenticate( user.get(acl.getProperty('_login_attr'))\n , 'falsepassword'\n , {}\n )\n\n # make sure the user could not connect\n self.failUnless(user_ob is None)\n\n # now let's try again with the right password\n user_ob = acl.authenticate( user.get(acl.getProperty('_login_attr'))\n , user.get('user_pw')\n , {}\n )\n \n # now we should be OK\n self.failIf(user_ob is None)\n\n\ndef test_suite():\n return unittest.TestSuite((\n unittest.makeSuite(TestAuthentication),\n ))\n\n","sub_path":"Products/LDAPUserFolder/tests/test_authentication.py","file_name":"test_authentication.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"389627400","text":"class Solution:\n\t\n\tdef majorityElement(self, nums):\n\t\t\"\"\"\n\t\tThe key idea is that the majority element in nums must be the majority element in at least one of the\n\t\thalves of nums. We let each halves propose their majority values then count and pick the right value.\n\t\tThis algorithm follows standard divide then merge steps.\n\t\t:type nums: List[int]\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn self.majorityElementDC(nums, 0, len(nums) - 1)\n\n\tdef majorityElementDC(self, nums, startIdx, endIdx):\n\t\tif startIdx == endIdx:\n\t\t\treturn nums[startIdx]\n\t\telse:\n\t\t\t#divide\n\t\t\tmidIdx = (startIdx + endIdx) // 2\n\t\t\tleft, right = self.majorityElementDC(nums, startIdx, midIdx), self.majorityElementDC(nums, midIdx + 1, endIdx)\n\t\t\t#merge\n\t\t\tif left == right:\n\t\t\t\treturn left\n\t\t\telse:\n\t\t\t\tleftCount = sum([1 for idx in range(startIdx, endIdx+1) if nums[idx] == left])\n\t\t\t\trightCount = sum([1 for idx in range(startIdx, endIdx+1) if nums[idx] == right])\n\t\t\t\treturn left if leftCount >= rightCount else right\n\n\ns = Solution()\nprint(s.majorityElement([6,5,5]))\n","sub_path":"divide-and-conquer/majority-element.py","file_name":"majority-element.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"636785147","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# 用于上传文件\n# upload demo\n\nimport os\nimport flask\nfrom flask import request\nfrom werkzeug import secure_filename\nfrom flask import Flask, render_template\n\napp = flask.Flask(__name__)\napp.config['UPLOAD_FOLDER'] = '/opt/uploads'\napp.config['MAX_CONTENT_LENGTH'] = 80<<100 # max upload size < 16M\n\n\n@app.route('/', )\ndef index():\n return render_template('index.html')\n\n\n@app.route('/upload/', methods=['GET'])\ndef explore():\n ''' server upload '''\n return render_template('upload.html')\n\n@app.route('/upload/', methods=['POST'])\ndef upload_file():\n file = request.files['file']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return 'upload success'\n\n@app.route('/restart_tomcat1/', )\ndef restart_tomcat1():\n os.system('/etc/init.d/tomcat 1')\n return '已经开始重启'\n\n@app.route('/restart_tomcat2/', )\ndef restart_tomcat2():\n os.system('/etc/init.d/tomcat 2')\n return '已经开始重启'\n\n@app.route('/upload_wai/', )\ndef upload_wai():\n os.system('touch 456')\n return '已经开始上传'\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',port=80, debug=True)\n","sub_path":"工具类/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"96795292","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nfrom parameters import *\n\n############### MANOUEVRE ###############\n\n\nV = np.arange(0,60.,0.01)\n\nC_Lneg_clean = -0.85\nn_min = -4\n\nadd = 35\n\nlst_V_top = []\nlst_n_pos = []\n\nfor i in range(len(V)):\n n_pos_clean= (C_Lmax_clean * 0.5* rho_0 * V[i]**2. * Wing_S)/ weight_TO\n lst_n_pos.append(n_pos_clean)\n lst_V_top.append(V[i]) \n if n_pos_clean >= n_max_struc:\n break\n \nlst_V_bottom = []\nlst_n_neg = []\n \nfor i in range(len(V)):\n n_neg_clean= (C_Lneg_clean * 0.5* rho_0 * V[i]**2. * Wing_S)/ weight_TO\n lst_n_neg.append(n_neg_clean)\n lst_V_bottom.append(V[i]) \n if n_neg_clean <= n_min:\n break\n\nn_neg_clean= (C_Lneg_clean * 0.5* rho_0 * V**2. * Wing_S)/ weight_TO\nn_pos_clean= (C_Lmax_clean * 0.5* rho_0 * V**2. * Wing_S)/ weight_TO\n\nfor i in range(len(V)):\n if n_pos_clean[i] >= 6:\n n_top_start = V[i]\n break\n\nfor i in range(len(n_neg_clean)):\n if n_neg_clean[i] <= -4:\n n_bottom_start = V[i]\n break\n \n\n\ntop_line_x = np.arange(n_top_start, V_cruise + add, 0.001)\ntop_line_y = np.ones((len(top_line_x),1)) * n_max_struc\n\nbottom_line_x = np.arange(n_bottom_start, V_cruise + add, 0.001)\nbottom_line_y = np.ones((len(bottom_line_x),1)) * n_min\n\nright_line_y = np.arange(n_min, n_max_struc, 0.001)\nright_line_x = np.ones((len(right_line_y),1)) * (V_cruise + add)\n\n############## GUST #####################\n\n\nV_gust_1 = 7.62 #gust speed [m/s]\nV_gust_2 = 15.24 #gust speed [m/s]\nV_gust_3 = 20.12 #gust speed [m/s]\nCL_alpha = ((C_L_alpha) / 180.) * np.pi #dcl/dalpha\nk = 1. \n\n#n_g_max_1 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_1 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n#n_g_max_2 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_2 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n#n_g_max_3 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_3 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n#n_g_min_1 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_1 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n#n_g_min_2 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_2 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n#n_g_min_3 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_3 * V) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n\nn_g_max_1 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_3 * V_stall) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\nn_g_max_2 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_2 * V_cruise) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\nn_g_max_3 = 1 + k * (CL_alpha * ((0.5 * rho_0 * V_gust_1 * (V_cruise + add)) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\nn_g_min_1 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_3 * V_stall) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\nn_g_min_2 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_2 * V_cruise) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\nn_g_min_3 = 1 - k * (CL_alpha * ((0.5 * rho_0 * V_gust_1 * (V_cruise + add)) / (weight_TO/Wing_S))) #EoAP - Ruijgrok\n\n\nFig = plt.figure(\"envelope\", figsize=(10,4))\nplt.plot([0,V_stall], [1,n_g_max_1], color=\"b\", label=\"Gust envelope\")\nplt.plot([V_stall,V_cruise], [n_g_max_1,n_g_max_2], color=\"b\")\nplt.plot([V_cruise, V_cruise+add], [n_g_max_2,n_g_max_3], color=\"b\")\nplt.plot([V_cruise+add,V_cruise+add], [n_g_max_3,n_g_min_3], color=\"b\")\nplt.plot([0,V_stall], [1,n_g_min_1], color=\"b\")\nplt.plot([V_stall,V_cruise], [n_g_min_1,n_g_min_2], color=\"b\")\nplt.plot([V_cruise, V_cruise+add], [n_g_min_2,n_g_min_3], color=\"b\")\n\nplt.plot(right_line_x, right_line_y, color=\"k\", label=\"Maneuver envelope\")\nplt.plot(top_line_x, top_line_y, color=\"k\")\nplt.plot(bottom_line_x, bottom_line_y, color=\"k\")\nplt.plot(lst_V_top,lst_n_pos, color=\"k\")\nplt.plot(lst_V_bottom,lst_n_neg, color=\"k\")\n\nplt.axvline(V_stall, ls=\"--\", color=\"y\")\nplt.axvline(V_cruise, ls=\"--\", color=\"y\")\n#plt.axhline(1,ls=\"--\", color=\"y\")\nplt.grid()\n\nplt.ylabel(\"Load factor [-]\")\nplt.xlabel(\"Flight speed [m/s]\")\nplt.legend(bbox_to_anchor=(0., 1.02, 1., .202), loc=3, ncol=2 , mode=\"expand\", borderaxespad=0.)\nplt.savefig(\"envelope\",bbox_inches='tight')\n\nplt.xlim((0,V_cruise+ add + 5))\nplt.ylim((n_min-1,n_max_struc+1))\nplt.show()\n","sub_path":"PP_envelope_loadfactor.py","file_name":"PP_envelope_loadfactor.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"400915122","text":"\n# This code was changed from the original for experimentation\n# purposes. The original one is found in \n# https://enlight.nyc/projects/neural-network/\n# I wanna thank Samay Shamdasani who is the initial author of the base code\n# Vinicius C. Costa\n\nimport math\nimport numpy as np\n\n# X = (hours in the gym, average sleep hours per day, average calories per day), \n# y = muscle gain factor\nX = np.array([[3, 8, 2000],\n\t\t\t [5, 9, 2500],\n\t\t\t [0, 6, 2500],\n\t\t\t [1, 7, 1800],\n\t\t\t [15, 7, 2500]], dtype=float)\n\ny = np.array([[1.1], [1.3], [0.9], [1.0], [0.8]], dtype=float)\n\nxPredicted = np.array([5, 8, 3000], dtype=float)\nxPredicted = xPredicted/np.amax(X, axis=0)\n\n\n# scale units\nX = X/np.amax(X, axis=0) # maximum of X array by column\ny = y/np.amax(y)\n\nprint(X)\nprint(y)\n\nclass Neural_Network(object):\n\tdef __init__(self):\n\t\t# parameters\n\t\tself.inputSize = 3\n\t\tself.outputSize = 1\n\t\tself.hiddenSize1 = 4\n\t\tself.hiddenSize2 = 4\n\t\t# learning rate\n\t\tself.alpha = 1\n\t\t# weights\n\t\tself.W1 = np.random.randn(self.inputSize, self.hiddenSize1) # (3x4) weight matrix from input to hidden layer 1\n\t\tself.W2 = np.random.randn(self.hiddenSize1, self.hiddenSize2) # (4x4) weight matrix from hidden layer 1 to hidden layer 2\n\t\tself.W3 = np.random.randn(self.hiddenSize2, self.outputSize) # (4x1) weight matrix from hidden layer 2 to output\n\t\t# parameter for leaky ReLU\n\t\tself.alphaReLU = 0.05\n\n\tdef sigmoid(self, s):\n\t\t# activation function 0\n\t\treturn 1/(1+np.exp(-s))\n\n\tdef sigmoidPrime(self, s):\n\t\treturn s*(1-s)\n\n\tdef tanhPrime(self, s):\n\t\t# activation function 1, the tanh function used was the build-in from numpy\n\t\treturn 1 - s**2\n\n\tdef reLU(self, s):\n\t\t# activation function 2\n\t\treturn np.where(s > 0, s, 0)\n\n\tdef reLUPrime(self, s):\n\t\treturn np.where(s > 0, 1, 0)\n\n\tdef leakyReLU(self, s):\n\t\t# activation function 3\n\t\treturn np.where(s > 0, s, s * self.alphaReLU)\n\n\tdef leakyReLUPrime(self, s):\n\t\treturn np.where(s > 0, 1, self.alphaReLU)\n\n\tdef forward(self, X):\n\t\t# forward propagation through our network\n\t\tself.z1_0 = np.dot(X, self.W1) # dot product of X (input) and first set of (3x4) weights \n\t\tself.z1_1 = self.leakyReLU(self.z1_0) # activation\n\n\t\tself.z2_0 = np.dot(self.z1_1, self.W2) # 1st hidden layer\n\t\tself.z2_1 = self.leakyReLU(self.z2_0) # activation\n\n\t\tself.z3_0 = np.dot(self.z2_1, self.W3) # 2nd hidden layer\n\t\to = np.tanh(self.z3_0) #final activation function\n\n\t\treturn o\n\n\tdef backward(self, X, y, o):\n\t\t# backpropagate through the network\n\t\tself.o_error = y - o\n\t\tself.o_delta = self.o_error*self.tanhPrime(o) # this computes how far out our z3_0 went from the ideal z3_0 \n\n\t\tself.z2_1_error = self.o_delta.dot(self.W3.T) # z2 error: how much our hidden layer weights contributed to output error\n\t\tself.z2_1_delta = self.z2_1_error*self.leakyReLUPrime(self.z2_1)\n\n\t\tself.z1_1_error = self.z2_1_delta.dot(self.W2.T)\n\t\tself.z1_1_delta = self.z1_1_error*self.leakyReLUPrime(self.z1_1)\n\n\t\tself.W1 += self.alpha*X.T.dot(self.z1_1_delta)\n\t\tself.W2 += self.alpha*self.z1_1.T.dot(self.z2_1_delta)\n\t\tself.W3 += self.alpha*self.z2_1.T.dot(self.o_delta)\n\n\tdef train(self, X, y):\n\t\to = self.forward(X)\n\t\tself.backward(X, y, o)\n\n\tdef saveWeights(self):\n\t\tnp.savetxt(\"w1.txt\", self.W1, fmt=\"%s\")\n\t\tnp.savetxt(\"w2.txt\", self.W2, fmt=\"%s\")\n\t\tnp.savetxt(\"w3.txt\", self.W3, fmt=\"%s\")\n\n\tdef predict(self):\n\t\tprint(\"Predicted data based on trained weights: \")\n\t\tprint(\"Input (scaled): \\n\" + str(xPredicted))\n\t\tprint(\"Output: \\n\" + str(self.forward(xPredicted) * 1.3)) # * np.max(y)\n\nNN = Neural_Network()\nfor i in range(10000): #train the NN 1000 times\n\tprint(\"# \" + str(i) + \"\\n\")\n\tprint(\"Input (scaled): \\n\" + str(X))\n\tprint(\"Actual Output: \\n\" + str(y))\n\tprint(\"Predicted Output: \\n\" + str(NN.forward(X)))\n\tprint(\"Loss: \\n\" + str(np.mean(np.square(y - NN.forward(X)))))\n\tprint(\"\\n\")\n\tNN.train(X,y)\n\nNN.saveWeights()\nNN.predict()\n\n\n# o = NN.forward(X)\n\n# print(\"Predicted Output: \\n\" + str(o))\n# print(\"Actual Output: \\n\" + str(y))","sub_path":"gains_predictor.py","file_name":"gains_predictor.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"271803122","text":"###################################################################################################################\n# Antonio Russo\n# Imperial College London\n# Date: 14/10/2028\n###################################################################################################################\nimport sys, os, shutil\nLibPath = os.environ['SPDE']\nsys.path.append(LibPath)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nimport pyximport\npyximport.install(setup_args={'include_dirs': np.get_include()})\n\nfrom time_integrator import time_integrator\nfrom solvers.geometric_brownian2D import geometric_brownian2D\n\n######################################################################################\n## Test\n######################################################################################\nif __name__ == '__main__':\n\n #Data\n n=2\n n_steps=1\n n_traj=1\n rho0= np.ones(n) #+ 0.1*np.random.randn(n)\n value_mu=-1.0\n value_sigma=0.5\n dt= 1* 10**(-11)\n eta=np.random.randn(n,n_steps,n_traj)\n \n P_mat = np.array([[1,1],[-1,1]])\n #Time for every method\n W= np.cumsum(np.sqrt(dt)*eta,axis=1)\n rhoTheory= rho0[0] * np.exp( value_mu*n_steps*dt - 0.5 * (value_sigma**2)*n_steps*dt + value_sigma*W )\n my_geometric_brownian= geometric_brownian2D(value_mu, value_sigma)\n\n t0 = time.time()\n rhoEM = my_geometric_brownian(rho0, eta, dt, n_steps, time_method='EM', theta=1)\n t1 = time.time()\n total_timeEM = t1-t0\n print(\"EMim:\",total_timeEM)\n\n t0 = time.time()\n rhoMI = my_geometric_brownian(rho0, eta, dt, n_steps, time_method='MI', theta=1)\n t1 = time.time()\n total_timeMI = t1-t0\n print(\"MIim:\",total_timeMI)\n\n t0 = time.time()\n rhoRK2 = my_geometric_brownian(rho0, eta, dt, n_steps, time_method='RK2')\n t1 = time.time()\n total_timeRK2 = t1-t0\n print(\"RK2:\",total_timeRK2)\n\n t0 = time.time()\n rhoRK3 = my_geometric_brownian(rho0, eta, dt, n_steps, time_method='RK3')\n t1 = time.time()\n total_timeRK3 = t1-t0\n print(\"RK3:\",total_timeRK3)\n\n \n #Weak and Strong Errors\n n_traj=5000\n def compute_weak_error(approx_sol, exact_sol): #approx_sol=[dim1] and exact_sol=[dim2]\n return abs(np.mean(approx_sol) - np.mean(exact_sol))\n \n def compute_strong_error(approx_sol, exact_sol): #approx_sol=[dim] and exact_sol=[dim]\n return np.mean(np.abs(approx_sol-exact_sol))\n \n dt_vec=2.0**(-np.asarray([3,4,5,6,7]))\n\n weak_errorEM1=np.zeros(len(dt_vec))\n weak_errorEM2=np.zeros(len(dt_vec))\n weak_errorEM3=np.zeros(len(dt_vec))\n weak_errorMI1=np.zeros(len(dt_vec))\n weak_errorMI2=np.zeros(len(dt_vec))\n weak_errorMI3=np.zeros(len(dt_vec))\n weak_errorRK2=np.zeros(len(dt_vec))\n weak_errorRK3=np.zeros(len(dt_vec))\n \n strong_errorEM1=np.zeros(len(dt_vec))\n strong_errorEM2=np.zeros(len(dt_vec))\n strong_errorEM3=np.zeros(len(dt_vec))\n strong_errorMI1=np.zeros(len(dt_vec))\n strong_errorMI2=np.zeros(len(dt_vec))\n strong_errorMI3=np.zeros(len(dt_vec))\n strong_errorRK2=np.zeros(len(dt_vec))\n strong_errorRK3=np.zeros(len(dt_vec))\n \n for i_dt in range(len(dt_vec)):\n i_steps=int(1/dt_vec[i_dt])\n eta=np.random.randn(n,i_steps,n_traj)\n W= np.cumsum(np.sqrt(dt_vec[i_dt])*eta,axis=1)\n rhoTheory= rho0[0] * np.exp( value_mu*i_steps*dt_vec[i_dt] - 0.5 * (value_sigma**2)*i_steps*dt_vec[i_dt] + value_sigma*W )\n# rhoTheory_mean= rho0[0] * np.exp( value_mu*i_steps*dt_vec[i_dt])\n my_geometric_brownian= geometric_brownian2D(value_mu, value_sigma)\n \n rhoEM1_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='EM', theta=0, n_traj=n_traj)\n rhoEM2_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='EM', theta=0.5, n_traj=n_traj)\n rhoEM3_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='EM', theta=1, n_traj=n_traj)\n rhoMI1_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='MI', theta=0, n_traj=n_traj)\n rhoMI2_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='MI', theta=0.5, n_traj=n_traj)\n rhoMI3_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='MI', theta=1, n_traj=n_traj)\n rhoRK2_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='RK2', theta=1, n_traj=n_traj)\n# rhoRK3_conv=my_geometric_brownian(rho0, eta, dt_vec[i_dt], i_steps, time_method='RK3', theta=1, n_traj=n_traj)\n\n weak_errorEM1[i_dt]=compute_weak_error(rhoEM1_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorEM2[i_dt]=compute_weak_error(rhoEM2_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorEM3[i_dt]=compute_weak_error(rhoEM3_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorMI1[i_dt]=compute_weak_error(rhoMI1_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorMI2[i_dt]=compute_weak_error(rhoMI2_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorMI3[i_dt]=compute_weak_error(rhoMI3_conv[0,-1,:],rhoTheory[0,-1,:])\n weak_errorRK2[i_dt]=compute_weak_error(rhoRK2_conv[0,-1,:],rhoTheory[0,-1,:])\n# weak_errorRK3[i_dt]=compute_weak_error(rhoRK3_conv[0,-1,:],rhoTheory[0,-1,:])\n\n strong_errorEM1[i_dt]=compute_strong_error(rhoEM1_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorEM2[i_dt]=compute_strong_error(rhoEM2_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorEM3[i_dt]=compute_strong_error(rhoEM3_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorMI1[i_dt]=compute_strong_error(rhoMI1_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorMI2[i_dt]=compute_strong_error(rhoMI2_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorMI3[i_dt]=compute_strong_error(rhoMI3_conv[0,-1,:],rhoTheory[0,-1,:])\n strong_errorRK2[i_dt]=compute_strong_error(rhoRK2_conv[0,-1,:],rhoTheory[0,-1,:])\n# strong_errorRK3[i_dt]=compute_strong_error(rhoRK3_conv[0,-1,:],rhoTheory[0,-1,:])\n\n# print(weak_errorEM)\n# print(strong_errorEM)\n #######################################################################################################################\n # Plots\n #######################################################################################################################\n fig = plt.figure()\n plt.title(r'$\\rho(x)$')\n plt.plot(rhoEM[:,-1], ls='-', label=\"Euler-Maruyama\")\n plt.plot(rhoMI[:,-1] , ls='--' ,label=\"Milstein\")\n plt.plot(rhoRK2[:,-1] , ls=':' , label=\"Runge-Kutta 2\")\n # plt.plot(rhoRK3 , ls=':' , label=\"Runge-Kutta 3\")\n plt.plot(rhoTheory[:,-1] , ls=':', label=\"Theory\")\n plt.legend()\n # plt.yscale('log')\n #plt.rc('text',usetex=True)\n #plt.rc('font',family='serif')\n plt.xlabel(r'$\\rho(x)$')\n plt.ylabel(r'x')\n plt.tight_layout()\n plt.savefig('rho.png')\n\n\n fig = plt.figure()\n plt.title(r'$\\epsilon_w$')\n plt.plot(dt_vec,weak_errorEM1, ls='-', label=\"Euler-Maruyama ex\")\n plt.plot(dt_vec,weak_errorEM2, ls='-', label=\"Euler-Maruyama cn\")\n plt.plot(dt_vec,weak_errorEM3, ls='-', label=\"Euler-Maruyama im\")\n plt.plot(dt_vec,weak_errorMI1, ls='-', label=\"Milstein ex\")\n plt.plot(dt_vec,weak_errorMI2, ls='-', label=\"Milstein cn\")\n plt.plot(dt_vec,weak_errorMI3, ls='-', label=\"Milstein im\")\n plt.plot(dt_vec,weak_errorRK2, ls='-', label=\"Runge-Kutta 2\")\n# plt.plot(dt_vec,weak_errorRK3, ls='-', label=\"Runge-Kutta 3\")\n plt.plot(dt_vec,0.1*dt_vec, ls='--', label=\"1 order line\")\n plt.plot(dt_vec,0.01*dt_vec**2, ls='--', label=\"2 order line\")\n plt.legend()\n plt.yscale('log')\n plt.xscale('log')\n #plt.rc('text',usetex=True)\n #plt.rc('font',family='serif')\n plt.xlabel(r'$\\epsilon_w$')\n plt.ylabel(r'$\\Delta \\ t $')\n plt.tight_layout()\n plt.savefig('weak.pdf')\n\n\n\n\n fig = plt.figure()\n plt.title(r'$\\epsilon_s$')\n plt.plot(dt_vec,strong_errorEM1, ls='-', label=\"Euler-Maruyama ex\")\n plt.plot(dt_vec,strong_errorEM2, ls='-', label=\"Euler-Maruyama cn\")\n plt.plot(dt_vec,strong_errorEM3, ls='-', label=\"Euler-Maruyama im\")\n plt.plot(dt_vec,strong_errorMI1, ls='-', label=\"Milstein ex\")\n plt.plot(dt_vec,strong_errorMI2, ls='-', label=\"Milstein cn\")\n plt.plot(dt_vec,strong_errorMI3, ls='-', label=\"Milstein im\")\n plt.plot(dt_vec,strong_errorRK2, ls='-', label=\"Runge-Kutta 2\")\n# plt.plot(dt_vec,strong_errorRK3, ls='-', label=\"Runge-Kutta 3\")\n plt.plot(dt_vec,0.1*dt_vec, ls='--', label=\"1 order line\")\n plt.plot(dt_vec,0.1*dt_vec**(1/2), ls='--', label=\"0.5 order line\")\n plt.legend()\n plt.yscale('log')\n plt.xscale('log')\n #plt.rc('text',usetex=True)\n #plt.rc('font',family='serif')\n plt.xlabel(r'$\\epsilon_s$')\n plt.ylabel(r'$\\Delta \\ t $')\n plt.tight_layout()\n plt.savefig('strong.pdf')\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n","sub_path":"scripts/GeometricBrownianMotion2D/geometric_brownian2DTest.py","file_name":"geometric_brownian2DTest.py","file_ext":"py","file_size_in_byte":8794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"328484095","text":"#!/usr/bin/python\n\n\"\"\"Add a new score to the database.\n\nThis code adds a players' new highscore to the database,\nrelative to the player and the level.\n\"\"\"\n\n\nimport cgi\nimport cgitb\nimport json\nimport pymysql\n\nimport processing\n\n\ndef score_empty(player_id, level_number):\n \"\"\"Check if a username does not already exist.\n\n This function checks if an entry for the given level and player\n does not already exist in the highscores database. If it doesn't\n already exist, it returns True. Otherwise, it returns False\n \"\"\"\n\n connection, cursor = processing.connect_to_database()\n # Get entry for that player and level\n cursor.execute(\"SELECT * FROM scores \"\n \"WHERE player_id=%s AND level_id=%s\", (player_id, level_number))\n scores = [(row[0], row[1]) for row in cursor.fetchall()]\n\n # Length of list is 0 if score for that player/level doesn't exist\n if len(scores) == 0:\n return True\n else:\n return False\n\n\ndef level_exists(level_number):\n \"\"\"Check if a given level number already exists.\n\n This function checks if an entry for the given level already exists\n in the database. If it does exist, it returns False, if it doesn't exist,\n it returns True.\n \"\"\"\n\n connection, cursor = processing.connect_to_database()\n # Get entry for that level number\n cursor.execute(\"SELECT * FROM levels WHERE level_id=%s\", (level_number,))\n level = [(row[0], row[1]) for row in cursor.fetchall()]\n\n # Length of list is 0 if level doesn't exist\n if len(level) == 0:\n return False\n else:\n return True\n\n\ndef add_score(player_id, level_number, score):\n \"\"\"Add a score to the database.\n\n This function adds a score for a given player and\n level to the database.\n \"\"\"\n\n connection, cursor = processing.connect_to_database()\n # Insert the score\n cursor.execute(\"INSERT INTO scores VALUES(%s, %s, %s)\", (player_id, level_number, score))\n connection.commit()\n\n\nif __name__ == \"__main__\":\n cgitb.enable()\n # Print necessary headers\n print(\"Content-Type: text/html; charset=utf-8\\n\\n\")\n\n form = cgi.FieldStorage()\n player_name = processing.get_player_name(form)\n level_number = processing.get_level_number(form)\n score = processing.get_score(form)\n\n if player_name != None and level_number != None and score != None:\n if not level_exists(level_number):\n processing.add_level(level_number)\n\n player_id = processing.get_player_id(player_name)\n if player_id != None and score_empty(player_id, level_number):\n add_score(player_id, level_number, score)\n print(json.dumps([player_name, level_number, score]))\n else:\n # If score already exists or player not in database\n print(json.dumps(None))\n\n else:\n # If player/level/score not provided\n print(json.dumps(None))","sub_path":"Client-Server Database/submitscore.py","file_name":"submitscore.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"74564095","text":"from apscheduler.schedulers.background import BackgroundScheduler\nfrom events.models import EventAttendance\nimport datetime\n\ndate = datetime.datetime.now()\n\n\ndef send_mail():\n return print('+++ Mail sent! +++')\n\n\ndef start():\n print('||||||||||||||||||||')\n scheduler = BackgroundScheduler()\n scheduler.scheduled_job(send_mail(), 'interval', seconds=3)\n scheduler.start()\n print('||||||||||||||||||||')","sub_path":"eventify/mail/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"487427252","text":"#!usr/bin/env python3\n# -*- coding: utf-8 -*-\n__author__ = \"Monkey\"\n\n\nclass BaseAdmin(object):\n \"\"\"\n 抽取Admin基类\n 自动的补充owner字段\n 过滤Queryset数据\n \"\"\"\n\n exclude = ('owner',)\n\n def save_models(self):\n \"\"\"\n 指定作者只能是当前登陆用户而不能是其他人\n \"\"\"\n self.new_obj.owner = self.request.user\n return super().save_models()\n\n def get_list_queryset(self):\n request = self.request\n qs = super().get_list_queryset()\n return qs.filter(owner=request.user)","sub_path":"djangoBlog/apps/blog/base_admin.py","file_name":"base_admin.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"445277161","text":"from progettobioinf.models import perceptron, set_shape\nfrom progettobioinf.retrieving_data import retrieving_data\nfrom progettobioinf.train import train\n\ndef test_perceptron_200_enhancers():\n models = []\n kwargs = []\n epigenomes, labels = retrieving_data('GM12878')\n set_shape(epigenomes, 'enhancers')\n model_perc, kwargs_perc = perceptron(200, 1024)\n models.append(model_perc)\n kwargs.append(kwargs_perc)\n train(epigenomes, labels, models, kwargs, 'enhancers', 'GM12878')","sub_path":"tests/test_perceptron_200_enhancers.py","file_name":"test_perceptron_200_enhancers.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"79407071","text":"import argparse\nimport asyncio\nimport copy\nimport logging\nimport os\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nimport pandas as pd\nimport yaml\n\n# from .measuring_ci.costs import fetch_all_worker_costs\n# from .measuring_ci.pushlog import scan_pushlog\nfrom taskhuddler.aio.graph import TaskGraph\n\nLOG_LEVEL = logging.INFO\n\nTASKGRAPHS = [\n \"Iel3zFH9Sc64pTH2zqgEog\", # Promote\n \"fXjUYLkoTkKZb_Uv4N2mKQ\", # Push\n \"QaL2b6JPTta4oPCIQBnBNQ\", # Ship\n]\nCI_TASKGRAPH = \"S-6-JjCzSBeDvbGOzIVlow\"\n\n\n# AWS artisinal log handling, they've already set up a handler by the time we get here\nlog = logging.getLogger()\nlog.setLevel(LOG_LEVEL)\n# some modules are very chatty\nlogging.getLogger(\"taskcluster\").setLevel(logging.INFO)\nlogging.getLogger(\"aiohttp\").setLevel(logging.INFO)\n\n\ndef fetch_worker_costs(csv_filename):\n \"\"\"Static snapshot of data from worker_type_monthly_costs table.\"\"\"\n\n df = pd.read_csv(csv_filename)\n expect_columns = {\n \"modified\",\n \"year\",\n \"month\",\n \"provider\",\n \"provisioner\",\n \"worker_type\",\n \"usage_hours\",\n \"cost\",\n }\n\n if expect_columns.symmetric_difference(df.columns):\n raise ValueError(\"Expected worker_type_monthly_costs to have a specific set of columns.\")\n\n # Sort newest first, ensures we keep current values\n df.sort_values(by=[\"year\", \"month\"], ascending=False, inplace=True)\n df.drop_duplicates('worker_type', inplace=True)\n df['unit_cost'] = df['cost'] / df['usage_hours']\n df.set_index('worker_type', inplace=True)\n return df\n\n\ndef fetch_all_worker_costs(tc_csv_filename, scriptworker_csv_filename):\n df = fetch_worker_costs(tc_csv_filename)\n if scriptworker_csv_filename:\n sw_df = fetch_worker_costs(scriptworker_csv_filename)\n df = df.append(sw_df)\n return df\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"CI Costs\")\n parser.add_argument('--project', type=str, default='mozilla-release')\n parser.add_argument('--product', type=str, default='firefox')\n parser.add_argument('--config', type=str, default='scanner.yml')\n return parser.parse_args()\n\n\ndef probably_finished(timestamp):\n \"\"\"Guess at whether a revision's CI tasks have finished by now.\"\"\"\n timestamp = datetime.fromtimestamp(timestamp)\n # Guess that if it's been over 24 hours then all the CI tasks\n # have finished.\n if datetime.now() - timestamp > timedelta(days=1) or True: # Assume finished\n return True\n return False\n\n\ndef taskgraph_cost(graph, worker_costs):\n total_wall_time_buckets = defaultdict(timedelta)\n final_task_wall_time_buckets = defaultdict(timedelta)\n for task in graph.tasks():\n key = task.json['status']['workerType']\n total_wall_time_buckets[key] += sum(task.run_durations(), timedelta(0))\n if task.completed:\n final_task_wall_time_buckets[key] += task.resolved - task.started\n\n total_cost = 0.0\n final_task_costs = 0.0\n\n for bucket in total_wall_time_buckets:\n if bucket not in worker_costs.index:\n continue\n\n hours = total_wall_time_buckets[bucket].total_seconds() / (60 * 60)\n cost = worker_costs.at[bucket, 'unit_cost'] * hours\n total_cost += cost\n\n hours = final_task_wall_time_buckets[bucket].total_seconds() / (60 * 60)\n cost = worker_costs.at[bucket, 'unit_cost'] * hours\n final_task_costs += cost\n\n return total_cost, final_task_costs\n\n\ndef find_push_by_group(group_id, project, pushes):\n return next(push for push in pushes[project] if pushes[project][push]['taskgraph'] == group_id)\n\n\nasync def _semaphore_wrapper(action, args, semaphore):\n async with semaphore:\n return await action(*args)\n\n\nasync def get_release_cost(product, config):\n \"\"\"Scan a project's recent history for complete task graphs.\"\"\"\n config = copy.deepcopy(config)\n\n semaphore = asyncio.Semaphore(10)\n tasks = list()\n\n for graph_id in TASKGRAPHS:\n log.debug(\"Examining graph %s\", graph_id)\n tasks.append(asyncio.ensure_future(\n _semaphore_wrapper(\n TaskGraph,\n args=(graph_id,),\n semaphore=semaphore,\n )))\n\n log.info('Gathering task {} graphs'.format(len(tasks)))\n taskgraphs = await asyncio.gather(*tasks)\n\n release_cost = 0.0\n release_task_count = 0\n\n log.info('Calculating costs')\n worker_costs = fetch_all_worker_costs(\n tc_csv_filename=config['costs_csv_file'],\n scriptworker_csv_filename=config.get('costs_scriptworker_csv_file'),\n )\n for graph in taskgraphs:\n full_cost, final_runs_cost = taskgraph_cost(graph, worker_costs)\n task_count = len([t for t in graph.tasks()])\n release_task_count += task_count\n release_cost += full_cost\n print()\n print(\"Release 62.0.3 cost {} over {} tasks\".format(release_cost, release_task_count))\n print()\n\n tasks = list()\n tasks.append(\n asyncio.ensure_future(\n _semaphore_wrapper(\n TaskGraph,\n args=(CI_TASKGRAPH,),\n semaphore=semaphore,\n )))\n ci_graph = await asyncio.gather(*tasks)\n full_cost, final_runs_cost = taskgraph_cost(ci_graph[0], worker_costs)\n task_count = len([t for t in ci_graph[0].tasks()])\n release_task_count += task_count\n release_cost += full_cost\n print(\"Including on-push CI Release 62.0.3 cost {} over {} tasks\".format(release_cost, release_task_count))\n print()\n\n\nasync def main(args):\n with open(args['config'], 'r') as y:\n config = yaml.load(y)\n os.environ['TC_CACHE_DIR'] = config['TC_CACHE_DIR']\n config['backfill_count'] = args.get('backfill_count', None)\n\n await get_release_cost(args['product'], config)\n\n\ndef lambda_handler(args, context):\n # assert context # not current used\n if 'config' not in args:\n args['config'] = 'scanner.yml'\n if 'product' not in args:\n args['product'] = 'firefox'\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main(args))\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=LOG_LEVEL)\n # Use command-line arguments instead of json blob if not running in AWS Lambda\n lambda_handler(vars(parse_args()), {'dummy': 1})\n","sub_path":"one_offs/get_costs_release_62.0.3.py","file_name":"get_costs_release_62.0.3.py","file_ext":"py","file_size_in_byte":6304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215310963","text":"BUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 0.001 # for soft update of target parameters\nLR = 0.0005 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n\nPRIO_ALPHA = 0.6\nPRIO_BETA = 0.4\nPRIO_EPSILON = 1e-5","sub_path":"defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"432771429","text":"# 3rd\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n# prj\nfrom controllers import base, forum, user\nfrom extensions import EXTENSIONS, db\n\n\ndef create_app(__name__):\n \"\"\"\n Application factory\n \"\"\"\n app = Flask(__name__)\n app.config.from_object('config')\n register_extensions(app)\n register_blueprints(app)\n return app\n\n\ndef register_extensions(app):\n \"\"\"Register Flask extensions.\"\"\"\n for ext in EXTENSIONS:\n ext.init_app(app)\n if isinstance(ext, SQLAlchemy):\n db.create_all(app=app)\n\n\ndef register_blueprints(app):\n \"\"\"Register Flask blueprints.\"\"\"\n app.register_blueprint(base.blueprint)\n app.register_blueprint(forum.blueprint)\n app.register_blueprint(user.blueprint)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"572059880","text":"import tkinter#from tkinter import * としてもおk tkinter.が必要なくなる\nfrom tkinter import messagebox\n\nroot = tkinter.Tk()#ウィンドウ内部開始\n\n#box中身削除定義\ndef Delete(event):\n box.delete(0, tkinter.END)\n#メッセージボックス表示\ndef check(event):\n global a1\n text=\"\"\n if a1.get() == True:\n text = \"されています\\n\"\n else:\n text = \"されていません\\n\"\n messagebox.showinfo('info', text)#表示部分タイトル,内容\ndef draw(event):\n canvas.create_oval(event.x-10, event.y-10, event.x+10, event.y+10, fill=\"red\", width=0)\n\n\nroot.title(u\"Title\")#タイトル記述\nroot.geometry(\"800x450\")#横x(エックス)縦\n#ラベル\nlabel = tkinter.Label(text=u'label', foreground='#ff0000')#文字色\nlabel.place(x=0, y=0)#指定位置配置(左上が0,0)\n#入力ボックス\nbox = tkinter.Entry(width=100)#横幅指定\nbox.insert(tkinter.END, \"default\")#デフォルトで文字挿入\nbox.pack()\nvalue = box.get()#ボックスの中身取得\n#ボタン\nbutton = tkinter.Button(root, text=u'Hello', background='#00ff00')#背景色\nbutton.bind(\"\", Delete)#(左クリック)でbox中身削除 \"\"はホイールクリック \"\"は右クリック\nbutton.pack()#位置自動\n#bool型宣言\na1 = tkinter.BooleanVar()\na1.set(True)#a1にTrue代入\n#チェックボックス\ncheckbox = tkinter.Checkbutton(text=u\"AAA\", variable=a1)#チェックボックスの初期値をTrueに(直接指定NG)\ncheckbox.pack()\n#チェック確認\nbutton0 = tkinter.Button(root, text=u\"確認\")\nbutton0.bind(\"\", check)\nbutton0.pack()\n#キャンバス作成\ncanvas = tkinter.Canvas(root, width=600, height=250, bg=\"white\")\ncanvas.place(x=100, y=100)\ncanvas.bind(\"\", draw)\ncanvas.bind(\"\", draw)\n\nroot.mainloop()#ウィンドウ内部終了\n","sub_path":"PythonApplication1/PythonApplication1.py","file_name":"PythonApplication1.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"467293364","text":"#!/usr/bin/env python\n\nimport base64\nimport datetime\nimport ecdsa\nimport hashlib\nimport json\nimport pytz\nimport requests\nimport tempfile\n\nclass CloudKitAuth(requests.auth.AuthBase):\n def __init__(self, key_id, key_file_name):\n self.key_id = key_id\n self.key_file_name = key_file_name\n\n def __call__(self, r):\n dt = datetime.datetime.now(tz=pytz.UTC)\n dt = dt.replace(microsecond=0)\n formatted_date = dt.isoformat().replace(\"+00:00\", \"Z\")\n\n r.headers = {\n 'Content-Type': \"text/plain\",\n 'X-Apple-CloudKit-Request-SignatureV1': self.make_signature(formatted_date, r.body, r.path_url),\n 'X-Apple-CloudKit-Request-KeyID': self.key_id,\n 'X-Apple-CloudKit-Request-ISO8601Date': formatted_date\n }\n return r\n\n def make_signature(self, formatted_date, body, path):\n signature = \"{}:{}:{}\".format(formatted_date, self.encode_body(body), path)\n\n with tempfile.NamedTemporaryFile() as signature_file, tempfile.NamedTemporaryFile() as body_file:\n body_file.write(signature)\n body_file.seek(0)\n\n sk = ecdsa.SigningKey.from_pem(open(self.key_file_name).read())\n signature = sk.sign(body_file.read(), hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_der)\n return base64.b64encode(signature)\n\n def encode_body(self, body):\n if body is None:\n body = \"\"\n elif type(body) != str:\n body = json.dumps(body, separators=(',', ':'))\n\n h = hashlib.sha256(body)\n return base64.b64encode(h.digest())\n\n","sub_path":"requests_cloudkit/cloudkit.py","file_name":"cloudkit.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"552382722","text":"def countWhite(img,start,end):\n #count white\n dictX = {}\n dictY = {}\n shape = img.shape\n for i in range(start[\"y\"],end[\"y\"]):\n for j in range(start[\"x\"],end[\"x\"]):\n if img[i,j] == 255:\n if str(i) not in dictX:\n dictX[str(i)] = 1\n else:\n dictX[str(i)] += 1\n if str(j) not in dictY:\n dictY[str(j)] = 1\n else:\n dictY[str(j)] += 1\n return {\n \"x\" : dictX,\n \"y\" : dictY\n }","sub_path":"createRecord/countWhite.py","file_name":"countWhite.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"494277686","text":"from odoo import models, fields, api,_\nfrom datetime import datetime, timedelta\nfrom odoo import tools\nfrom odoo.exceptions import Warning, ValidationError\nfrom odoo import SUPERUSER_ID\n\n\nHOURS_PER_DAY = 8\n\nclass hr_holidays_multiple(models.Model):\n _inherit = 'hr.holidays.multiple'\n\n check_access_group_manager = fields.Boolean('Check rule',\n default=False)\n\n @api.model\n def default_get(self, fields):\n res = super(hr_holidays_multiple, self).default_get(fields)\n res.update({\n 'state' : 'draft'\n })\n user_obj = self.env['res.groups'].search([('name', '=', 'HR Manager')]).users.ids\n if self._uid in user_obj:\n res.update({\n 'check_access_group_manager': True\n })\n return res\n\n @api.model\n def create(self, vals):\n res = super(hr_holidays, self).create(vals)\n return res\n\n\nclass hr_holidays(models.Model):\n _inherit = 'hr.holidays'\n\n state = fields.Selection([\n ('draft', 'To Submit'),\n ('cancel', 'Cancelled'),\n ('confirm', 'To Approve'),\n ('refuse', 'Rejected'),\n ('validate1', 'Second Approval'),\n ('validate', 'Approved')],default='draft')\n\n @api.model\n def default_get(self,fields):\n res = super(hr_holidays, self).default_get(fields)\n res.update({\n 'state': 'draft'\n })\n return res\n\n @api.model\n def create(self,vals):\n res = super(hr_holidays, self).create(vals)\n res.state = 'draft'\n return res\n\n @api.onchange('date_from')\n def _onchange_date_from(self):\n \"\"\" If there are no date set for date_to, automatically set one 8 hours later than\n the date_from. Also update the number_of_days.\n \"\"\"\n date_from = self.date_from\n date_to = self.date_to\n\n # No date_to set so far: automatically compute one 8 hours later\n if date_from:\n if not date_to or date_to and date_from > date_to:\n date_to_with_delta = fields.Datetime.from_string(date_from) + timedelta(hours=HOURS_PER_DAY)\n self.date_to = str(date_to_with_delta)\n date_to = self.date_to\n\n # Compute and update the number of days\n if (date_to and date_from) and (date_from <= date_to):\n self.number_of_days_temp = self._get_number_of_days(date_from, date_to, self.employee_id.id)\n else:\n self.number_of_days_temp = 0\n\n def _check_user_is_hr_manager(self):\n user_ids = []\n user_ids.append(SUPERUSER_ID)\n group_ids = self.env['res.groups'].search([('name','in',('CFO','HR Manager','HR Executive'))])\n for group_id in group_ids:\n if group_id.users:\n for user in group_id.users:\n user_ids.append(user.id)\n if self._uid in user_ids:\n return False\n else:\n return True\n\n @api.model\n def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):\n res = super(hr_holidays, self).fields_view_get(view_id, view_type, toolbar=toolbar, submenu=False)\n action_id = self.env.ref('hr_holidays.open_company_allocation').id\n if self._context.get('params') and self._context.get('params').get('action') and action_id == self._context.get('params').get('action'):\n if view_type != 'form':\n if view_type == 'tree':\n check_user = self._check_user_is_hr_manager()\n if check_user == True:\n if 'arch' in res:\n data = res.get('arch').split('\\n')\n modify_edit_str = 'create=\"0\" delete=\"0\"'\n\n arch_data = '' % (\n modify_edit_str)\n for n in range(1, len(data)):\n arch_data += '\\n%s' % (data[n])\n res['arch'] = arch_data\n return res\n else:\n return res\n if view_type == 'form':\n check_user = self._check_user_is_hr_manager()\n if check_user == True:\n if 'arch' in res:\n data = res.get('arch').split('\\n')\n modify_edit_str = 'edit=\"0\" create=\"0\" copy=\"0\" delete=\"0\"'\n\n arch_data = '
' % (modify_edit_str)\n for n in range(1, len(data)):\n arch_data += '\\n%s' % (data[n])\n res['arch'] = arch_data\n return res\n else:\n return res\n\n @api.model\n def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):\n action_id = self.env.ref('hr_holidays.open_company_allocation').id\n if self._context.get('params') and self._context.get('params').get('action') and action_id == self._context.get(\n 'params').get('action'):\n cfo_group_id = self.env.ref('beumer_modifier_access_right.cfo_group')\n hr_manager_group_id = self.env.ref('beumer_modifier_access_right.hr_manager_group')\n hr_executive_group_id = self.env.ref('beumer_modifier_access_right.hr_executive_group')\n if self._uid not in cfo_group_id.users.ids and self._uid not in hr_manager_group_id.users.ids and self._uid not in hr_executive_group_id.users.ids:\n if domain:\n domain.append(('user_id', '=', self._uid))\n else:\n domain = [('user_id', '=', self._uid)]\n res = super(hr_holidays, self).read_group(domain, fields, groupby, offset=offset, limit=limit,\n orderby=orderby, lazy=lazy)\n return res\n\n @api.model\n def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):\n action_id = self.env.ref('hr_holidays.open_company_allocation').id\n if self._context.get('params') and self._context.get('params').get('action') and action_id == self._context.get('params').get('action'):\n cfo_group_id = self.env.ref('beumer_modifier_access_right.cfo_group')\n hr_manager_group_id = self.env.ref('beumer_modifier_access_right.hr_manager_group')\n hr_executive_group_id = self.env.ref('beumer_modifier_access_right.hr_executive_group')\n if self._uid not in cfo_group_id.users.ids and self._uid not in hr_manager_group_id.users.ids and self._uid not in hr_executive_group_id.users.ids:\n if domain:\n domain.append(('user_id', '=', self._uid))\n else:\n domain = [('user_id', '=', self._uid)]\n res = super(hr_holidays, self).search_read(domain=domain, fields=fields, offset=offset,\n limit=limit, order=order)\n return res\n\n\nclass hr_public_holiday(models.Model):\n _inherit = 'hr.holiday.public'\n\n # fields_view = fields.Boolean(compute='_load_view')\n #\n # def _load_view(self):\n # self._context['params'].update({\n # 'view_type' : 'form',\n # '_push_me' : False ,\n # 'model' : 'hr.holiday.public',\n # 'id' : self.id\n # })\n # self.fields_view_get(view_id=None,view_type='form', toolbar=True, submenu=False)\n # self.open_new_view()\n # return True\n #\n # def open_new_view(self):\n # return {\n # 'name': ('Load Form Again'),\n # 'view_type': 'form',\n # 'view_mode': 'form',\n # 'res_model': 'hr.holiday.public',\n # 'type': 'ir.actions.act_window',\n # 'res_id' : self.id ,\n # 'view_id': self.env.ref('sg_hr_holiday.hr_holiday_public_form').id,\n # }\n #\n # @api.model\n # def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):\n # res = super(hr_public_holiday, self).fields_view_get(view_id, view_type, toolbar=toolbar, submenu=False)\n # if view_type == 'form':\n # if 'params' in self._context and 'id' in self._context.get('params') or self.id:\n # holiday_public_id = self._context.get('params').get('id')\n # holiday_public_id = self.browse(holiday_public_id) or self\n # if holiday_public_id.state == 'confirmed':\n # if 'arch' in res:\n # data = res.get('arch').split('\\n')\n # modify_edit_str = 'edit=\"0\" delete=\"0\"'\n #\n # arch_data = '' % (modify_edit_str)\n # for n in range(1, len(data)):\n # arch_data += '\\n%s' % (data[n])\n # res['arch'] = arch_data\n # return res\n\n @api.multi\n def setstate_validate(self):\n '''\n Sets state to validated\n '''\n file_name = 'HolidayList' # Name of report file\n attachments = []\n email_body = '' # To store email body text specified for each employee\n mail_obj = self.env[\"ir.mail_server\"]\n data_obj = self.env['ir.model.data']\n for self_rec in self:\n mail_server_ids = self.env['ir.mail_server'].search([])\n if mail_server_ids and mail_server_ids.ids:\n mail_server_id = mail_server_ids[0]\n if not self_rec.email_body:\n raise ValidationError(_('Please specify email body!'))\n result_data = data_obj._get_id('hr', 'group_hr_manager')\n model_data = data_obj.browse(result_data)\n group_data = self.env['res.groups'].browse(model_data.res_id)\n work_email = []\n user_ids = [user.id for user in group_data.users]\n if 1 in user_ids:\n user_ids.remove(1)\n emp_ids = self.env['hr.employee'\n ].search([('user_id', 'in', user_ids)])\n for emp in emp_ids:\n if not emp.work_email:\n if emp.user_id.email and \\\n emp.user_id.email not in work_email:\n work_email.append(str(user.email))\n else:\n raise ValidationError(_('Email must be configured \\\n in %s HR manager !') % (emp.name))\n elif emp.work_email not in work_email:\n work_email.append(str(emp.work_email))\n if not work_email:\n raise ValidationError(_('No Hr Manager found!'))\n # Create report. Returns tuple (True,filename) if successfuly\n # executed otherwise (False,exception)\n report_name = 'sg_hr_holiday.employee_public_holiday_report'\n report = self.create_report(report_name, file_name)\n if report[0]:\n # Inserting file_data into dictionary with file_name as a key\n attachments.append((file_name, report[1]))\n email_body = self_rec.email_body\n specific_email_body = email_body\n message_app = mail_obj.build_email(\n email_from=mail_server_id.smtp_user,\n email_to=work_email,\n subject='Holiday list',\n body=specific_email_body or '',\n body_alternative=specific_email_body or '',\n email_cc=None,\n email_bcc=None,\n reply_to=None,\n attachments=attachments,\n references=None,\n object_id=None,\n subtype='html',\n subtype_alternative=None,\n headers=None)\n mail_obj.send_email(message=message_app,\n mail_server_id=mail_server_id.id)\n self_rec.write({'state': 'validated'})\n return True\n\n\n","sub_path":"beta-dev1/beumer_modifier_fields/models/hr_hoiliday.py","file_name":"hr_hoiliday.py","file_ext":"py","file_size_in_byte":12625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"400443065","text":"from django.shortcuts import render\r\nfrom django.views.generic import DetailView, CreateView\r\nfrom braces.views import LoginRequiredMixin\r\nfrom pacientes.models import Paciente\r\nfrom .models import Odontograma, Patologia\r\nfrom atenciones.models import DatoAtencion, DatoMultiatencion\r\nfrom django.http import HttpResponseRedirect\r\nfrom datetime import *\r\nfrom .forms import FormImagen\r\nimport datetime\r\n\r\nclass Crear(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/nuevo.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(Crear, self).get_context_data(**kwargs)\r\n\t\tcontext['verodontograma'] = True\r\n\t\ttry:\r\n\t\t\tOdontograma.objects.get(paciente=context['object'])\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\tdef post(self, request, *args, **kwargs):\r\n\t\tmipaciente = Paciente.objects.get(dni=kwargs['slug'])\r\n\t\tfin = False\r\n\t\ti = 1\r\n\t\tnodontograma = Odontograma()\r\n\t\tnodontograma.paciente = Paciente.objects.get(dni=kwargs['slug'])\r\n\t\tnodontograma.medico = self.request.user\r\n\t\tnodontograma.especificaciones = request.POST['especificaciones']\r\n\t\tnodontograma.observaciones = request.POST['observaciones']\r\n\t\t#nodontograma.foto = request.POST['foto']\r\n\t\tnodontograma.save()\r\n\t\twhile (fin == False):\r\n\t\t\ttry:\r\n\t\t\t\trequest.POST['item'+str(i)]\r\n\t\t\t\tnpatologia = Patologia()\r\n\t\t\t\tnpatologia.paciente = mipaciente\r\n\t\t\t\tnpatologia.medico = request.user\r\n\t\t\t\tnpatologia.nomenclatura = request.POST['item'+str(i)]\r\n\t\t\t\tnpatologia.diente = request.POST['diente'+str(i)]\r\n\t\t\t\tnpatologia.tipo = request.POST['tipo'+str(i)]\r\n\t\t\t\tnpatologia.desde = request.POST['desde'+str(i)]\r\n\t\t\t\tnpatologia.hasta = request.POST['hasta'+str(i)]\r\n\t\t\t\tnpatologia.estado = request.POST['estado'+str(i)]\r\n\t\t\t\tnpatologia.save()\r\n\t\t\t\ti = i + 1\r\n\t\t\texcept:\r\n\t\t\t\tfin = True\r\n\t\treturn HttpResponseRedirect('../../../paciente/'+kwargs['slug'])\r\n\r\nclass Inicial(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/ver.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(Inicial, self).get_context_data(**kwargs)\r\n\t\tcontext['verodontograma'] = True\r\n\t\ttry:\r\n\t\t\tcontext['odontogramainfo'] = Odontograma.objects.get(paciente = context['object'])\r\n\t\t\tcontext['patologia'] = Patologia.objects.filter(paciente = context['object'],inicial = True)\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\t\tcontext['muestramodificacion'] = True\r\n\t\t\tcontext['inicial'] = True\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\r\nclass Actual(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/ver.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(Actual, self).get_context_data(**kwargs)\r\n\t\tcontext['verodontograma'] = True\r\n\t\ttry:\r\n\t\t\tcontext['odontogramainfo'] = Odontograma.objects.get(paciente = context['object'])\r\n\t\t\tcontext['patologia'] = Patologia.objects.filter(paciente = context['object'],borrado = False)\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\t\tcontext['inicial'] = False\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\r\nclass ImprimirI(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/imprimir.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(ImprimirI, self).get_context_data(**kwargs)\r\n\t\tnombrestadosc = {'A': \"Soltero\", 'B': \"Casado\", 'C': \"Conviviente\", 'D': \"Viudo\", 'E':\"Divorciado\"}\r\n\t\tcontext['verodontograma'] = True\r\n\t\tmipaciente = Paciente.objects.get(dni=self.kwargs['slug'])\r\n\t\tdiff = (datetime.date.today() - mipaciente.nacimiento).days\r\n\t\tcontext['years'] = str(int(diff/365))\r\n\t\tcontext['estadoc'] = nombrestadosc[mipaciente.estadocivil]\r\n\t\ttry:\r\n\t\t\tcontext['odontogramainfo'] = Odontograma.objects.get(paciente = context['object'])\r\n\t\t\tcontext['patologia'] = Patologia.objects.filter(paciente = context['object'],inicial = True)\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\t\tcontext['inicial'] = True\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\r\nclass ImprimirA(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/imprimir.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(ImprimirA, self).get_context_data(**kwargs)\r\n\t\tnombrestadosc = {'A': \"Soltero\", 'B': \"Casado\", 'C': \"Conviviente\", 'D': \"Viudo\", 'E':\"Divorciado\"}\r\n\t\tcontext['verodontograma'] = True\r\n\t\tmipaciente = Paciente.objects.get(dni=self.kwargs['slug'])\r\n\t\tdiff = (datetime.date.today() - mipaciente.nacimiento).days\r\n\t\tcontext['years'] = str(int(diff/365))\r\n\t\tcontext['estadoc'] = nombrestadosc[mipaciente.estadocivil]\r\n\t\ttry:\r\n\t\t\tcontext['odontogramainfo'] = Odontograma.objects.get(paciente = context['object'])\r\n\t\t\tcontext['patologia'] = Patologia.objects.filter(paciente = context['object'],borrado = False)\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\t\tcontext['inicial'] = False\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\r\nclass Editar(LoginRequiredMixin, DetailView):\r\n\ttemplate_name = \"odontogramas/editar.html\"\r\n\tmodel = Paciente\r\n\tcontext_object_name = 'paciente'\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(Editar, self).get_context_data(**kwargs)\r\n\t\t#poder editar odontograma\r\n\t\thoy = date.today()\r\n\t\tvalor = DatoAtencion.objects.filter(fecha__date = hoy, medico = self.request.user)\r\n\t\ttry:\r\n\t\t\tfor dato in valor:\r\n\t\t\t\tif dato.atencion.paciente == context['object']:\r\n\t\t\t\t\tcontext['editarodontograma'] = True\r\n\t\texcept:\r\n\t\t\tpass\r\n\t\tvalor2 = DatoMultiatencion.objects.filter(fecha__date = hoy, medico = self.request.user)\r\n\t\ttry:\r\n\t\t\tfor dato2 in valor2:\r\n\t\t\t\tif dato2.multiatencion.presupuesto.paciente == context['object']:\r\n\t\t\t\t\tcontext['editarodontograma'] = True\r\n\t\texcept:\r\n\t\t\tpass\r\n\t\tcontext['verodontograma'] = True\r\n\t\t#fin editar odontograma\r\n\t\ttry:\r\n\t\t\tcontext['odontogramainfo'] = Odontograma.objects.get(paciente = context['object'])\r\n\t\t\tcontext['patologia'] = Patologia.objects.filter(paciente = context['object'],borrado = False)\r\n\t\t\tcontext['puedecrear'] = False\r\n\t\t\tcontext['odontograma'] = True\r\n\t\texcept:\r\n\t\t\tcontext['puedecrear'] = True\r\n\t\treturn context\r\n\tdef post(self, request, *args, **kwargs):\r\n\t\tmipaciente = Paciente.objects.get(dni=kwargs['slug'])\r\n\t\tahora = datetime.datetime.now()\r\n\t\tif request.POST['nr'] == \"3\":\r\n\t\t\teodontograma = Odontograma.objects.get(paciente=mipaciente)\r\n\t\t\teodontograma.especificaciones = request.POST['especificaciones']\r\n\t\t\teodontograma.observaciones = request.POST['observaciones']\r\n\t\t\teodontograma.modificacion = ahora\r\n\t\t\teodontograma.save()\r\n\t\telif request.POST['nr'] == \"2\":\r\n\t\t\tepatologia = Patologia.objects.get(id=request.POST['id'])\r\n\t\t\tepatologia.borrado = True\r\n\t\t\tepatologia.save()\r\n\t\t\teodontograma = Odontograma.objects.get(paciente=mipaciente)\r\n\t\t\teodontograma.modificacion = ahora\r\n\t\t\teodontograma.save()\r\n\t\telse:\r\n\t\t\tnpatologia = Patologia()\r\n\t\t\tnpatologia.paciente = mipaciente\r\n\t\t\tnpatologia.medico = request.user\r\n\t\t\tnpatologia.nomenclatura = request.POST['nomenclatura']\r\n\t\t\tnpatologia.diente = request.POST['diente']\r\n\t\t\tnpatologia.tipo = request.POST['tipo']\r\n\t\t\tnpatologia.desde = request.POST['desde']\r\n\t\t\tnpatologia.hasta = request.POST['hasta']\r\n\t\t\tif request.POST['nomenclatura'] == \"Caries\" or request.POST['nomenclatura'] == \"Restauracion_Definitiva\":\r\n\t\t\t\tsumas = \"\"\r\n\t\t\t\tfor x in range(1,5):\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tsumas = sumas + request.POST['ubicacion'+str(x)]\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\r\n\t\t\t\tnpatologia.estado = sumas\r\n\t\t\telse:\r\n\t\t\t\tnpatologia.estado = request.POST['estado']\r\n\t\t\tnpatologia.inicial = False\r\n\t\t\tnpatologia.borrado = False\r\n\t\t\tnpatologia.save()\r\n\t\t\teodontograma = Odontograma.objects.get(paciente=mipaciente)\r\n\t\t\teodontograma.modificacion = ahora\r\n\t\t\teodontograma.save()\r\n\t\treturn HttpResponseRedirect('../editar')\r\n\r\nclass Imagen(LoginRequiredMixin, CreateView):\r\n\ttemplate_name = \"odontogramas/cargaimagen.html\"\r\n\tmodel = Odontograma\r\n\tform_class = FormImagen\r\n\tslug_field = 'dni'\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(Imagen, self).get_context_data(**kwargs)\r\n\t\tcontext['paciente'] = Paciente.objects.get(dni=self.kwargs['slug'])\r\n\t\treturn context\r\n\tdef get_success_url(self):\r\n\t\tpaciente = Paciente.objects.get(dni=self.kwargs['slug'])\r\n\t\turl = '/paciente/'+paciente.dni\r\n\t\treturn url\r\n\tdef form_valid(self, form):\r\n\t\tpaciente = Paciente.objects.get(dni=self.kwargs['slug'])\r\n\t\tform.instance.paciente = paciente\r\n\t\tform.instance.medico = self.request.user\r\n\t\treturn super(Imagen, self).form_valid(form)\r\n\tdef form_invalid(self, form):\r\n\t\t#print \"invalido\"\r\n\t\treturn super(Imagen, self).form_invalid(form)","sub_path":"odontogramas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"230322334","text":"from flask import render_template\nfrom flask.ext.sqlalchemy import get_debug_queries\nfrom app import app\nfrom config import DATABASE_QUERY_TIMEOUT\n\n\n@app.after_request\ndef after_request(response):\n for query in get_debug_queries():\n if query.duration >= DATABASE_QUERY_TIMEOUT:\n app.logger.warning(\n \"SLOW QUERY: {}\\nParameters: {}\\nDuration: {0:.2f}s\\nContext: {}\\n\".format(\n query.statement, query.parameters, query.duration, query.context\n ))\n return response\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n return render_template('index.html')\n","sub_path":"app_template/app/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"37742799","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nimgname1 = 'data/012-204.jpg'\nimgname2 = 'data/013-221.jpg'\n\nsift = cv2.xfeatures2d.SIFT_create()\n\n# FLANN 参数设计\nFLANN_INDEX_KDTREE = 0\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks=50)\nflann = cv2.FlannBasedMatcher(index_params,search_params)\n\nimg1 = cv2.imread(imgname1)\ngray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #灰度处理图像\nkp1, des1 = sift.detectAndCompute(img1,None)#des是描述子\n\nimg2 = cv2.imread(imgname2)\ngray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\nkp2, des2 = sift.detectAndCompute(img2,None)\n\nhmerge = np.hstack((gray1, gray2)) #水平拼接\ncv2.imshow(\"gray\", hmerge) #拼接显示为gray\ncv2.waitKey(0)\n\nimg3 = cv2.drawKeypoints(img1,kp1,img1,color=(255,0,255))\nimg4 = cv2.drawKeypoints(img2,kp2,img2,color=(255,0,255))\n\nhmerge = np.hstack((img3, img4)) #水平拼接\ncv2.imshow(\"point\", hmerge) #拼接显示为gray\ncv2.waitKey(0)\nmatches = flann.knnMatch(des1,des2,k=2)\nmatchesMask = [[0,0] for i in range(len(matches))]\n\ngood = []\nfor m,n in matches:\n if m.distance < 0.4*n.distance:\n good.append([m])\n\nimg5 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)\ncv2.imshow(\"FLANN\", img5)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n# 1.**特征提取:SIFT(KD树)\n# 2.**图像缝合:RANSAC、匹配验证概率模型\n# 3.**捆绑调整:旋转变换图像实现最合适缝合\n# 4.*自动全景校正:拉伸图像为水平\n# 5.*增益补偿:统一光线\n# 6.*多波段混合:平滑过渡\n\n\n","sub_path":"tt.py","file_name":"tt.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"489727169","text":"import re\nfrom pprint import pprint\n\nimport requests\nfrom sign import get_as_cp, get_signature\n\n\ndef get_user_id_by_url(url):\n m = re.search(r\"/user/(\\d+)/\", url)\n if m:\n return m.group(1)\n else:\n return None\n\n\ndef get_user_articles(url):\n user_id = get_user_id_by_url(url)\n if not user_id:\n print(\"无效的用户链接\")\n return\n else:\n max_behot_time = 0\n as_, cp = get_as_cp()\n signature = get_signature(user_id + str(max_behot_time))\n r = requests.get(\n f\"https://www.toutiao.com/c/user/article/?page_type=1&user_id={user_id}&max_behot_time={max_behot_time}&count=20&as={as_}&cp={cp}&_signature={signature}\",\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\",\n \"Referer\": url,\n },\n )\n pprint(r.json())\n\n\nif __name__ == \"__main__\":\n get_user_articles(\n \"https://www.toutiao.com/c/user/69873738239/#mid=1585366346372110\"\n )\n","sub_path":"toutiao/get_user_articles.py","file_name":"get_user_articles.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"405131335","text":"import matplotlib.pyplot as plt\nimport sys\nimport math\nepoch = 0\nstep = 0.0173333\nz = []\ny = []\ncount = 0\nfor line in sys.stdin:\n\tepoch += step\n\tperp = [float(x.split('=')[1]) for x in line.split() if x.split('=')[0] == 'perplexity'][0]\n\t#if perp > 20:\n\t\t#perp = 20\n\t#if count%5 == 0:\n\tz.append(epoch)\n\ty.append(math.log(perp))\n\tcount += 1\nplt.plot(z,y)\nplt.show()\n","sub_path":"mtsystem/oracle/utils/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"13103328","text":"N=int(input()) #ログの行数を表す変数 N \ndistance=[]\nans=0\nd=1 #現在にいる階層を表す\nf_d=0\n#止まった階を入力してもらい、リストに格納\nfor i in range(N):\n f=int(input())\n distance.append(f)\n\n\nfor i in distance:\n f_d=abs(d-i)#現在いる階層を移動先の階層で引くことで移動した階層を計算する。\n ans=ans+f_d #変数に足していく\n d=i#移動先を現在の階層にする。\nprint(ans)\n","sub_path":"Rank_C/C049エレベーター.py","file_name":"C049エレベーター.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"381789253","text":"# 解けてない\n\ncompressed_chars = [48 + i for i in range(10)]\n\n\ndef is_compressed_str(ch3):\n return ord(ch3[0]) in compressed_chars and ord(ch3[1]) in compressed_chars and ord(ch3[2]) in compressed_chars\n\n\ndef compressed_str_idx(s):\n for i in range(len(s) - 2):\n if is_compressed_str(s[i: i + 3]):\n return i\n return -1\n\n\ndef create_dict(line):\n d = dict()\n for i in range(len(line) - 5):\n key = line[i: i + 6]\n if d.get(key) is None:\n d[key] = str(i).zfill(3)\n return d\n\n\ndef compress(dic, line):\n i = 0\n s = ''\n while i < len(line):\n if i + 5 >= len(line):\n s += line[i]\n i += 1\n elif dic.get(line[i: i + 6]) is None:\n s += line[i]\n i += 1\n elif int(dic[line[i: i + 6]]) == i:\n s += line[i]\n i += 1\n else:\n s += dic[line[i: i + 6]]\n i += 6\n return s\n\n\ndef decompress(line):\n i = 0\n s = ''\n while i < len(line):\n if is_compressed_str(line[i: i + 3]):\n s += decompress_part(i, line)\n i += 3\n else:\n s += line[i]\n i += 1\n return s\n\n\ndef decompress_part(i, line):\n ref = int(line[i: i + 3])\n s = line[ref: ref + 6]\n index = compressed_str_idx(s)\n if index == -1:\n return s\n else:\n return (s[:index] * 6)[0: 6]\n\n\ndef decompress_nested(s, line):\n index = compressed_str_idx(s)\n if index == -1:\n return s\n return (line[:index] * 6)[0: 6]\n\n\ndef main():\n with open('data/s1.txt', mode='r') as f:\n l = f.readline()\n d = create_dict(l)\n s = compress(d, l)\n print(decompress(s))\n\n\nmain()\n","sub_path":"2011_summer/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"103954950","text":"# Python modules\n\n# 3rd party modules\nimport wx\n\n# Our modules\nimport vespa.common.util.ppm as util_ppm\n\nfrom vespa.analysis.constants import GisoDefaultFixedT2\nfrom vespa.analysis.constants import GisoDynMetabolite\n\nfrom wx.lib.agw.floatspin import FloatSpin, EVT_FLOATSPIN, FS_LEFT, FS_RIGHT, FS_CENTRE, FS_READONLY\nfrom vespa.common.wx_gravy.widgets.floatspin_multiplier.floatspin_multiplier_base import FloatSpinMultiplier\n\n\n\n\nclass DynamicListGisoMetabolite(object):\n\n def __init__(self, _inner_notebook, tab, GridSizer, dataset, external_event_handler):\n \n self.tab = tab\n self.dataset = dataset\n self._inner_notebook = _inner_notebook\n \n self.external_event_handler = external_event_handler\n \n self._list_lines = []\n\n # We follow the wx CamelCaps naming convention for this wx object.\n self.GridSizer = GridSizer\n\n\n def event_handler(self, event):\n self.external_event_handler(event)\n\n\n def get_values(self, only_checked=True):\n checks = []\n names = []\n area_scales = []\n peak_ppms = []\n search_ppms = []\n db_ppms = []\n fix_t2 = []\n search_ph0 = []\n \n lines = [self._get_line_values(line) for line in self._list_lines]\n\n for i,line in enumerate(lines):\n if not only_checked or line['checkbox']:\n checks.append(line['checkbox'])\n names.append(self.full_names[i])\n area_scales.append(line['scale']) \n peak_ppms.append(line['shift'])\n search_ppms.append(line['width'])\n db_ppms.append(line['dbppm'])\n fix_t2.append(line['fixt2'])\n search_ph0.append(line['phas0'])\n \n if only_checked:\n return names, area_scales, peak_ppms, search_ppms, db_ppms, fix_t2, search_ph0\n else:\n return checks, names, area_scales, peak_ppms, search_ppms, db_ppms, fix_t2, search_ph0\n\n\n def select_all(self): \n for line in self._list_lines: \n line[\"checkbox\"].SetValue(True) \n \n \n def set_new_values(self, respect_current=True, preset=False):\n \"\"\"\n Tells this control to grab new values from the block. If\n respect_current is True, the state of existing selections will \n be applied to the new values if possible.\n \"\"\" \n if respect_current:\n tmp = self.get_values(False)\n prev_checks = tmp[0]\n prev_names = tmp[1] \n prev_area_scales = tmp[2] \n prev_peak_ppms = tmp[3]\n prev_search_ppms = tmp[4]\n prev_db_ppms = tmp[5]\n prev_fix_t2 = tmp[6]\n prev_search_ph0 = tmp[7]\n\n prior = self.tab.block.set.prior\n self.full_names = sorted(prior.basis_set_names)\n\n # Set up default values from prior or calculations\n # We sort the list of metab names.\n \n area_scales = [1.0] * len(self.full_names)\n checks = [False] * len(self.full_names)\n search_ppms = [0.10] * len(self.full_names) \n peak_ppms = [prior.basis_set[name].peak_ppm for name in self.full_names]\n db_ppms = [False] * len(self.full_names)\n fix_t2 = [1000.0] * len(self.full_names)\n search_ph0 = [0.0] * len(self.full_names)\n all_ppms = [prior.basis_set[name].all_ppms for name in self.full_names]\n \n if preset:\n for i, name in enumerate(list(self.tab.block.set.prior_list)):\n if name in self.full_names:\n index = self.full_names.index(name)\n checks[index] = True\n area_scales[index] = self.tab.block.set.prior_area_scale[i]\n peak_ppms[index] = self.tab.block.set.prior_peak_ppm[i]\n search_ppms[index] = self.tab.block.set.prior_search_ppm[i]\n db_ppms[index] = self.tab.block.set.prior_db_ppm[i]\n fix_t2[index] = self.tab.block.set.prior_fix_t2[i]\n search_ph0[index] = self.tab.block.set.prior_search_ph0[i]\n\n\n # if loading a new prior file on an existing one then we need to\n # maintain existing user set parameters if metabolites in both sets\n if respect_current:\n if not len(prev_checks):\n # we are initializing for first time, take values from block\n prev_names = list(self.tab.block.set.prior_list)\n prev_checks = [True] * len(prev_names)\n prev_area_scales = list(self.tab.block.set.prior_area_scale)\n prev_peak_ppms = list(self.tab.block.set.prior_peak_ppm)\n prev_search_ppms = list(self.tab.block.set.prior_search_ppm)\n prev_db_ppms = self.tab.block.set.prior_db_ppm\n prev_fix_t2 = self.tab.block.set.prior_fix_t2\n prev_search_ph0 = list(self.tab.block.set.prior_search_ph0)\n \n for i, name in enumerate(prev_names):\n if name in self.full_names:\n index = self.full_names.index(name)\n checks[index] = prev_checks[i]\n area_scales[index] = prev_area_scales[i]\n peak_ppms[index] = prev_peak_ppms[i]\n search_ppms[index] = prev_search_ppms[i]\n db_ppms[index] = prev_db_ppms[i]\n fix_t2[index] = prev_fix_t2[i]\n search_ph0[index] = prev_search_ph0[i]\n\n self._remove_all_rows()\n\n for arguments in zip(self.full_names, checks, area_scales, peak_ppms, search_ppms, db_ppms, fix_t2, search_ph0):\n self._add_row(*arguments)\n\n\n ##################################################################\n #\n # Internal use/private functions \n #\n \n def _add_row(self, full_name, flag, mult, pkppm, wid, dbflag, t2val, ph0val):\n '''Adds a row to the end of the list.'''\n # helper calcs\n maxppm = self.dataset.pts2ppm(0)\n minppm = self.dataset.pts2ppm(self.dataset.spectral_dims[0]-1)\n\n self.GridSizer.SetRows(self.GridSizer.GetRows() + 1)\n\n # create widgets to go into the line\n list_line = { }\n\n checkbox = wx.CheckBox(self._inner_notebook, -1, full_name)\n \n scale = FloatSpinMultiplier(self._inner_notebook, \n increment=1.25, \n digits=5, \n style=wx.SP_ARROW_KEYS|wx.SP_WRAP|wx.TE_PROCESS_ENTER, \n agwStyle=FS_LEFT\n )\n shift = FloatSpin(self._inner_notebook, agwStyle=FS_LEFT)\n width = FloatSpin(self._inner_notebook, agwStyle=FS_LEFT)\n dbppm = wx.CheckBox(self._inner_notebook, -1, '')\n fixt2 = FloatSpin(self._inner_notebook, agwStyle=FS_LEFT)\n phas0 = FloatSpin(self._inner_notebook, agwStyle=FS_LEFT)\n \n # keep a copy of panel and widgets to access later\n line = { \"checkbox\" : checkbox, \n \"scale\" : scale, \n \"shift\" : shift,\n \"width\" : width,\n \"dbppm\" : dbppm,\n \"fixt2\" : fixt2,\n \"phas0\" : phas0 }\n\n # Add the controls to the grid sizer\n self.GridSizer.Add(line[\"checkbox\"], 0, wx.ALIGN_CENTER_VERTICAL)\n for key in (\"scale\", \"shift\", \"width\"):\n self.GridSizer.Add(line[key], 0, wx.ALIGN_CENTER_VERTICAL)\n self.GridSizer.Add(line[\"dbppm\"], 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_CENTER_HORIZONTAL)\n for key in (\"fixt2\", \"phas0\"):\n self.GridSizer.Add(line[key], 0, wx.ALIGN_CENTER_VERTICAL)\n \n # Configure the controls I just created\n checkbox.SetValue(flag)\n\n # All of the floatspins have the same size. \n floatspin_size = wx.Size(70, -1)\n\n # Note. On these Spin and FloatSpin widgets, if the value you want to\n # set is outside the wxGlade standard range, you should make the \n # call to reset the range first and then set the value you want.\n scale.multiplier = GisoDynMetabolite.AREA_SCALE_MULT\n scale.SetDigits(GisoDynMetabolite.AREA_SCALE_DIGITS)\n scale.SetIncrement(GisoDynMetabolite.AREA_SCALE_INCR)\n scale.SetRange(GisoDynMetabolite.AREA_SCALE_MIN,GisoDynMetabolite.AREA_SCALE_MAX)\n scale.SetValue(mult)\n scale.SetMinSize(floatspin_size)\n \n shift.SetDigits(GisoDynMetabolite.SEARCH_CENTER_DIGITS)\n shift.SetIncrement(GisoDynMetabolite.SEARCH_CENTER_INCR)\n shift.SetRange(minppm,maxppm)\n shift.SetValue(pkppm)\n shift.SetMinSize(floatspin_size) \n\n width.SetDigits(GisoDynMetabolite.SEARCH_WIDTH_DIGITS)\n width.SetIncrement(GisoDynMetabolite.SEARCH_WIDTH_INCR)\n width.SetRange(GisoDynMetabolite.SEARCH_WIDTH_MIN,GisoDynMetabolite.SEARCH_WIDTH_MAX)\n width.SetValue(wid)\n width.SetMinSize(floatspin_size) \n\n dbppm.SetValue(dbflag)\n\n fixt2.SetDigits(GisoDefaultFixedT2.DIGITS)\n fixt2.SetIncrement(GisoDefaultFixedT2.INCR)\n fixt2.SetRange(GisoDefaultFixedT2.MIN,GisoDefaultFixedT2.MAX)\n fixt2.SetValue(t2val)\n fixt2.SetMinSize(floatspin_size) \n\n phas0.SetDigits(GisoDynMetabolite.SEARCH_PHASE0_DIGITS)\n phas0.SetIncrement(GisoDynMetabolite.SEARCH_PHASE0_INCR)\n phas0.SetRange(GisoDynMetabolite.SEARCH_PHASE0_MIN,GisoDynMetabolite.SEARCH_PHASE0_MAX)\n phas0.SetValue(ph0val)\n phas0.SetMinSize(floatspin_size) \n\n\n self._list_lines.append(line)\n\n self._inner_notebook.Bind(wx.EVT_CHECKBOX, self.event_handler, checkbox)\n self._inner_notebook.Bind(EVT_FLOATSPIN, self.event_handler, scale)\n self._inner_notebook.Bind(EVT_FLOATSPIN, self.event_handler, shift)\n self._inner_notebook.Bind(EVT_FLOATSPIN, self.event_handler, width)\n self._inner_notebook.Bind(wx.EVT_CHECKBOX, self.event_handler, dbppm)\n self._inner_notebook.Bind(EVT_FLOATSPIN, self.event_handler, fixt2)\n self._inner_notebook.Bind(EVT_FLOATSPIN, self.event_handler, phas0)\n \n self.tab.PanelMetabolite.Layout()\n \n \n def _remove_all_rows(self):\n for line in self._list_lines:\n for control in list(line.values()):\n control.Destroy()\n \n self._list_lines = [ ]\n \n # There's always one row that contains the headings.\n self.GridSizer.SetRows(1)\n self.GridSizer.Layout()\n\n \n def _get_line_values(self, line):\n # Returns a dict containing values of the controls in the line.\n return { \"checkbox\" : line[\"checkbox\"].GetValue(),\n \"scale\" : line[\"scale\"].GetValue(),\n \"shift\" : line[\"shift\"].GetValue(),\n \"width\" : line[\"width\"].GetValue(),\n \"dbppm\" : line[\"dbppm\"].GetValue(),\n \"fixt2\" : line[\"fixt2\"].GetValue(),\n \"phas0\" : line[\"phas0\"].GetValue()\n }\n\n","sub_path":"vespa/analysis/dynamic_list_giso_metabolite.py","file_name":"dynamic_list_giso_metabolite.py","file_ext":"py","file_size_in_byte":11364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"289325047","text":"#!/usr/bin/env python-2.4.3\n#\n# December 2009, Panchalingesh Konannavar\n#\n# Copyright (c) 2009-2010 by cisco Systems, Inc.\n# All rights reserved.\n#\nimport sys, os, pdb\nos.environ['PY_XRUT_ROOT'] = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))\nsys.path[1:1] = [os.environ.get('PY_XRUT_ROOT') + '/modules']\nimport xrut, re, stdut, ut\nfrom xrut import routers\n#\n# area 0\n#\n# [ rtrA ] -------- [ rtrB ] \n# | linkAB1 | \n# | |\n# linkAD1 | | linkBC1\n# | |\n# | linkCD1 |\n# [ rtrD ] -------- [ rtrC ]\n#\n#\ntopology = xrut.topology_t('vt_rsvpmib',\n { 'alpha' : ( 'rtrA.GE0', 'rtrB.GE0' ),\n 'beta' : ( 'rtrB.GE1', 'rtrC.GE1' ),\n 'gamma' : ( 'rtrA.GE1', 'rtrD.GE1' ),\n 'delta' : ( 'rtrC.GE0', 'rtrD.GE0' ),\n 'epsilon' : ( 'rtrA.GE2', 'linux.ether0' ),\n 'zeta' : ( 'rtrB.GE2', 'linux.ether1' ),\n 'eta' : ( 'rtrC.GE2', 'linux.ether2' ),\n 'theta' : ( 'rtrD.GE2', 'linux.ether3' ), \n })\n\n#\ntopology.connect()\n\n","sub_path":"X-COPY/infra/test/xrut/rsvp/connect-rsvpmib_ut.py","file_name":"connect-rsvpmib_ut.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"522366709","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport json\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom collections import OrderedDict \n\n\n# bring in the condensed dataset \nwith open('../../Datasets/Created:Modified/att_data_condensed.json', 'r') as fp:\n obj = json.load(fp)\n\n\n# df/dataframe created from json file\ndf = pd.DataFrame(obj)\n\n\ndf.head(2)\n\n\ndef getPercentage(x, y):\n total = x + y\n return round(x / total * 100, 2)\n\n\ndef getAverageAttendance(dataframe):\n present = 0\n absent = 0\n for idx, x in enumerate(dataframe['Status']):\n if(x in ['P','PDG']):\n present += 1\n elif(x in ['U','ABS','AA']):\n absent += 1\n averageAttendance = getPercentage(present, absent)\n return averageAttendance\n\n\ndef getAttendanceTrendsByAge(dataframe):\n presentAge = {}\n absentAge = {}\n for idx, x in enumerate(dataframe['Status']):\n age = dataframe.loc[idx]['Age']\n if(x in ['P','PDG']):\n if age in presentAge:\n presentAge[age] += 1\n else:\n presentAge.update({age:1})\n elif(x in ['U','ABS','AA']):\n if age in absentAge:\n absentAge[age] += 1\n else:\n absentAge.update({age:1}) \n attendanceByAge = {'present':presentAge, 'absent':absentAge}\n\n return attendanceByAge\n\n\ndef getAttendanceTrendsByWeek(dataframe):\n presentWeek = {}\n absentWeek = {}\n for idx, x in enumerate(dataframe['Status']):\n weekNum = dataframe.loc[idx]['WeekNum']\n if(x in ['P','PDG']):\n if weekNum in presentWeek:\n presentWeek[weekNum] += 1\n else:\n presentWeek.update({weekNum:1})\n elif(x in ['U','ABS','AA']):\n if weekNum in absentWeek:\n absentWeek[weekNum] += 1\n else:\n absentWeek.update({weekNum:1}) \n attendanceWeekly = {'present':presentWeek, 'absent':absentWeek}\n\n return attendanceWeekly\n\n\ndef getAttendanceTrendsByCourse(dataframe):\n presentCourse = {}\n absentCourse = {}\n courses = {}\n for idx, x in enumerate(dataframe['Status']):\n course = dataframe.loc[idx]['CourseCode']\n if(x in ['P','PDG']):\n if course in presentCourse:\n presentCourse[course] += 1\n else:\n presentCourse.update({course:1})\n elif(x in ['U','ABS','AA']):\n if course in absentCourse:\n absentCourse[course] += 1\n else:\n absentCourse.update({course:1})\n if(course in courses):\n courses[course] += 1\n else:\n courses.update({course:1})\n attendanceByCourse = {'present':presentCourse, 'absent':absentCourse}\n counts = Counter(courses)\n mostRepCse = dict(counts.most_common(3))\n return attendanceByCourse\n# also does most rep courses, mostRepCse\n\n\nattendanceTrendsByCourse = getAttendanceTrendsByCourse(df)\nattendanceTrendsByWeek = getAttendanceTrendsByWeek(df)\nattendanceTrendsByAge = getAttendanceTrendsByAge(df)\n\n\n\ndf_temp = pd.DataFrame(attendanceTrendsByCourse)\ndf_temp.to_csv(r'infographic-by-course.csv', index=True, header=True)\n\n\ndf_temp = pd.DataFrame(attendanceTrendsByWeek)\ndf_temp.to_csv(r'infographic-by-week.csv', index=True, header=True)\n\n\ndf_temp = pd.DataFrame(attendanceTrendsByAge)\ndf_temp.to_csv(r'infographic-by-age.csv', index=True, header=True)\n\n\nattStatus = data.groupby(['ID'])['Status'].max()\ncounts = Counter(attStatus)\nstatusCount = dict(counts.most_common())\n\nprint('Attendance by Status:', statusCount)\n\n\ndf.head(2)\n\n\ndef getAttendanceTrendsByGender(dataframe):\n presentGender = {}\n absentGender = {}\n for idx, x in enumerate(dataframe['Status']):\n gender = dataframe.loc[idx]['Gender']\n if(x in ['P','PDG']):\n if gender in presentGender:\n presentGender[gender] += 1\n else:\n presentGender.update({gender:1})\n elif(x in ['U','ABS','AA']):\n if gender in absentGender:\n absentGender[gender] += 1\n else:\n absentGender.update({gender:1}) \n attendanceGender = {'present':presentGender, 'absent':absentGender}\n\n return attendanceGender\n\n\nattendanceByGender = getAttendanceTrendsByGender(df)\n\n\ndf_temp = pd.DataFrame(attendanceByGender)\ndf_temp.to_csv(r'infographic-by-gender.csv', index=True, header=True)\n\n\ndef getAttendanceTrendsByPostalArea(dataframe):\n presentPostalArea = {}\n absentPostalArea = {}\n for idx, x in enumerate(dataframe['Status']):\n postal = dataframe.loc[idx]['PostalArea']\n if(x in ['P','PDG']):\n if postal in presentPostalArea:\n presentPostalArea[postal] += 1\n else:\n presentPostalArea.update({postal:1})\n elif(x in ['U','ABS','AA']):\n if postal in absentPostalArea:\n absentPostalArea[postal] += 1\n else:\n absentPostalArea.update({postal:1}) \n attendancePostalArea = {'present':presentPostalArea, 'absent':absentPostalArea}\n\n return attendancePostalArea\n\n\nattPostalArea = getAttendanceTrendsByPostalArea(df)\n\n\nattendPostCode = pd.DataFrame(attPostalArea)\n\n\ndf_temp = pd.DataFrame(attendPostCode)\ndf_temp.to_csv(r'infographic-by-postal.csv', index=True, header=True)\n\n","sub_path":"ScriptCreatingDatasetsForInfographicCSVs - Attendance Insights.py","file_name":"ScriptCreatingDatasetsForInfographicCSVs - Attendance Insights.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"411569265","text":"__author__ = 'lauro'\n\n\nfrom Geotiff import readFile, writeFile, writeGeotiffSingleBand, readFile_withNoData\nfrom collections import Counter\nfrom osgeo import gdal, gdalconst, ogr\nimport os, sys, csv, getopt\nimport matplotlib.pylab as plt\nimport numpy as np\nfrom rasterRegrid import rasterRegrid\nimport datetime\nimport random\n\n#os.system(gdal_translate -a_srs EPSG:32736 -outsize 25% 25% -of GTiff -co COMPRESS=DEFLATE /Users/lauro/Documents/PROJECTS/FP7_H2020/RASOR_2012/MALAWI/crop/annual_crop_MW.tif /Users/lauro/Documents/PROJECTS/FP7_H2020/RASOR_2012/MALAWI/crop/annual_crop_60m.tif)\n\ndef log_print(s):\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \" - \" + s)\n\ndef non_unique (array):\n log_print (\"Making unique values...\")\n uniq_val = []\n for elem in array:\n if elem != 0 and not np.isnan (elem):\n #print(elem)\n elem = elem + random.random() * 0.01\n uniq_val.append(elem)\n return uniq_val\n\ndef plot_image(data):\n fig = plt.figure()\n cax = plt.imshow(data, cmap='Blues')\n plt.colormaps()\n #plt.clim(0,400)\n cbar = fig.colorbar(cax, orientation='vertical')\n #cbar.ax.set_yticklabels(['< -1', '0', 1, 2,'> 10'])# vertically oriented colorbar\n plt.show()\n\ndef get_crop (sFileMapSpamLowRes):\n return (os.path.basename(sFileMapSpamLowRes).split('_total')[0]).split('production_')[1]\n\ndef get_country (sFileMask):\n return (os.path.basename(sFileMask).split('_crops')[0])\n\ndef readPrice (sFileIn):\n\n #a1sInputName=[]\n #a1sInputValue=[]\n cropPrice = {}\n\n#np.loadtxt(inputfilename, comments='#', delimiter=' ',dtype='string', ndmin=2)\n\n with open(sFileIn, 'r') as filePar:\n\n for line in filePar:\n try:\n if \"#\" in line:\n (line1,line2) = line.split('#',1)\n else:\n line1=line\n #print line1\n (sVarName,sVarValue) = line1.replace(' ','\\t').split('\\t',1)\n if sVarName.strip() =='' and sVarValue.strip()=='':\n continue\n else:\n cropPrice[sVarName.strip()] = sVarValue.strip()\n #a1sInputName.append(sVarName.strip())\n #a1sInputValue.append(sVarValue.strip())\n\n except:\n print ('File: '+sFileIn)\n print ('Skipping line: '+line)\n\n #return a1sInputName, a1sInputValue\n return cropPrice\n\ndef downscale_crop (sFileMapSpamLowResTot,sFileMask, sFileClipper, sFilePrice):\n\n sCropType = get_crop (sFileMapSpamLowResTot)\n\n sCountry = get_country (sFileMask)\n\n print ('\\n')\n log_print('Crop type: '+sCropType)\n\n #making dir out \n dir_out = os.path.join(os.path.dirname(sFileMapSpamLowResTot),sCountry+\"_outputs\")\n if not os.path.exists(dir_out):\n os.mkdir(dir_out)\n\n sFileMapSpamLowRes = os.path.join(dir_out, os.path.basename(sFileMapSpamLowResTot.split('.')[0] + \"_\"+sCountry+\".tif\"))\n\n warp = '''gdalwarp -co \"COMPRESS=DEFLATE\" -dstnodata {noDataValue} -crop_to_cutline -overwrite -cutline {clipper} \"{infile}\" \"{outfile}\"'''.format(\n noDataValue=-9999, clipper=sFileClipper, infile=sFileMapSpamLowResTot, outfile=sFileMapSpamLowRes)\n #print (warp)\n os.system (warp)\n\n [xsize_orig, ysize_orig, geotransform, geoproj, data_low] = readFile_withNoData(sFileMapSpamLowRes)\n log_print (\"Original MAPSPAM map size: (\"+str(ysize_orig)+\",\"+str(xsize_orig)+\") (rows,cols)\")\n\n #TODO verify\n total_exposure = np.nansum(data_low);\n \n #making unique values\n data_low=np.reshape(non_unique (data_low.ravel()), data_low.shape)\n\n writeGeotiffSingleBand(sFileMapSpamLowRes, geotransform, geoproj, data_low)\n\n if bDisplayImages: plot_image(data_low)\n\n log_print(\"Total original production for crop type=\"+sCropType+\": %.2f\" % np.nansum(data_low))\n\n del data_low\n\n sFileMapSpamHiRes = os.path.join(dir_out, sFileMapSpamLowRes.split('.')[0] + \"_regrid.tif\")\n\n match_geotrans, match_proj = rasterRegrid(sFileMapSpamLowRes, sFileMask, sFileMapSpamHiRes ,\"nearest\")\n\n [xsize, ysize, geotransform_high, geoproj_high, data_high] = readFile_withNoData(sFileMapSpamHiRes)\n [xsize, ysize, geotransform_high, geoproj_high, data_mask] = readFile_withNoData(sFileMask)\n\n data_high [np.isnan (data_high)] = 0\n data_mask [np.isnan (data_mask)] = 0\n\n data_high_masked = data_high * data_mask\n\n if bDisplayImages:\n plot_image(data_mask)\n plot_image(data_high)\n plot_image(data_high_masked)\n\n data_high_masked [np.isnan (data_high_masked) ] = 0\n\n #debug\n #plot_image(data_high_masked)\n\n log_print (\"Starting counting...\")\n dictCounter = Counter(data_high_masked.ravel())\n log_print (\"Data counted\")\n\n data_mask_spam=np.copy(data_high)\n ratio = abs ((geotransform[1]*geotransform[5]) / (geotransform_high[1]*geotransform_high[5])) #number of high res pixels in low res pixel\n\n i=0\n data_gar_excluded = []\n #non posso leggere data low perche cambia nel salvarli\n data_high_unique=np.unique(data_high.ravel())\n for key in data_high_unique:\n if key not in dictCounter.keys() and key != 0:\n dictCounter[key] = ratio\n data_mask_spam[data_mask_spam==key]=-9999\n data_gar_excluded.append(key)\n excluded_exposure = sum(data_gar_excluded)\n log_print (\"MAPSPAM production not overlapping mask: %.2f (%.1f %%)\" % (excluded_exposure , excluded_exposure/total_exposure*100))\n\n #building mask (union of the original mask + non-zero values from MapSpam)\n data_mask_spam[data_mask_spam!=-9999]=0\n data_mask_spam[data_mask_spam==-9999]=1\n data_mask = data_mask_spam + data_mask\n data_mask[data_mask>0] = 1\n data_high_masked = data_high * data_mask\n\n del data_mask, data_high, data_mask_spam\n\n if bVerbose: log_print (\"Counter length: \"+str(dictCounter.__len__()))\n if bVerbose: log_print (\"Unique length: \"+str(len(np.unique(data_high_masked))))\n\n for key,value in dictCounter.items():\n data_high_masked [data_high_masked==key] = key/value\n if bVerbose: print ('Amount of pixel for crop' + str(key) + ': ' + str(value))\n\n if bDisplayImages:\n fig = plt.figure()\n cax = plt.imshow(data_high_masked[:, :])\n plt.colormaps()\n cbar = fig.colorbar(cax, orientation='vertical') # vertically oriented colorbar\n #cbar.ax.set_yticklabels(['< -1', '0', 1, 2,'> 10'])\n plt.show()\n\n log_print(\"Total downscaled production value for crop type=\"+sCropType+\": %.2f\" % np.nansum(data_high_masked))\n\n #from production to economic value\n cropPrice = readPrice(sFilePrice)\n data_high_masked = data_high_masked * float(cropPrice[sCropType])\n\n log_print ('Price of '+ sCropType +' = '+cropPrice[sCropType]+' [USD]')\n\n sFileDownscaled = os.path.join(dir_out, sCountry+\"_\"+sCropType+\"_HighRes.tif\")\n\n description = 'Production value for ' + sCropType + ' [USD]'\n bandMetadata = {}\n bandMetadata[('unit', '1')] = 'USD'\n iNbands=1;\n\n writeFile(sFileDownscaled, match_geotrans, match_proj, data_high_masked, bandMetadata, description, {'Crop type': sCropType},iNbands)\n log_print (\"Exposure downscaled. Final result save in file: \" + sFileDownscaled)\n \n################################\n############# START ############\n################################\n\nbDisplayImages = 0\nbVerbose = 0 \n\nsFileMask = '/Users/silvia/Documents/AFRICA_DATA/Guinea_Bissau/GW_agrM_ESA_90m_20180628.tif'\nsFileBoundary = '/Users/silvia/Documents/AFRICA_DATA/Guinea_Bissau/GW_bou_GAUL_admin0_20180901/GW_bou_GAUL_admin0_20180901.shp'\nsFilePrice = '/Users/silvia/Documents/AFRICA_DATA/Guinea_Bissau/CropsPrice.txt'\n\ncropPrice = readPrice (sFilePrice)\n\n# crop production directory\ndirIn = '/Users/silvia/Documents/AFRICA_DATA/Guinea_Bissau/Crops'\n\nfor file in os.listdir(dirIn):\n if file.startswith('spam') and file.endswith('tiff'):\n downscale_crop(os.path.join(dirIn,file),sFileMask, sFileBoundary, sFilePrice)\n","sub_path":"scriptAfrica/crop_raster_price.py","file_name":"crop_raster_price.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"391305693","text":"from grano.core import db\nfrom grano.model import Attribute\n\n\ndef save(data):\n \"\"\" Create or update an attribute. \n CAUTION: This does not, on its own, validate any data.\"\"\"\n\n schema = data.get('schema')\n name = data.get('name')\n obj = Attribute.by_schema_and_name(schema, name)\n if obj is None:\n obj = Attribute()\n obj.name = name\n obj.label = data.get('label')\n obj.hidden = data.get('hidden')\n obj.description = data.get('description')\n obj.datatype = data.get('datatype')\n obj.schema = schema\n db.session.add(obj)\n return obj\n\n\ndef to_index(attribute):\n return {\n 'name': attribute.name,\n 'label': attribute.label,\n 'datatype': attribute.datatype\n }\n\n\ndef to_rest(attribute):\n data = to_index(attribute)\n data['id'] = attribute.id\n data['hidden'] = attribute.hidden\n if attribute.description:\n data['description'] = attribute.description\n return data\n\n\ndef to_dict(attribute):\n data = to_index(attribute)\n data['id'] = attribute.id\n data['hidden'] = attribute.hidden\n data['description'] = attribute.description\n return data\n","sub_path":"grano/logic/attributes.py","file_name":"attributes.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"262714471","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis modules provides classes to construct HTML5 source strings.\n\nThe classes Element and Text to build trees of Node objects. These HTML5 trees\nare build 'by hand' using the constructors and the append_child and\nset_attribute methods of the Element class. This module is intended for\nproviding a simple, small facility to build small HTML5 strings dynamically.\nFirst the tree is created. Then, either the pretty_print method is called on\nthe root element or the root element is passed to str().\n\"\"\"\n# TODO: add html sanitation to Text and Element.set_attribute\n\nclass Node:\n \"\"\"\n Base class for the Element and Text classes.\n \"\"\"\n pass\n\n\nclass Element(Node):\n \"\"\"\n Element node of an HTML5 tree.\n \"\"\"\n _ROOT_ELEMENT = [u'html']\n\n _META_DATA_ELEMENTS = [u'head', u'title', u'base', u'link', u'meta',\n u'style']\n\n _SCRIPTING_ELEMENTS = [u'script', u'noscript']\n\n _SECTION_ELEMENTS = [u'body', u'article', u'section', u'nav', u'aside',\n u'h1', u'h2', u'h3', u'h4', u'h5', u'h6',\n u'hgroup', u'header', u'footer', u'address']\n\n _GROUPING_ELEMENTS = [u'p', u'hr', u'pre', u'blockquote', u'ol', u'ul',\n u'li', u'dl', u'dt', u'dd', u'figure', u'figcaption',\n u'div']\n\n _TEXT_LEVEL_ELEMENTS = [u'a', u'em', u'strong', u'small', u's', u'cite',\n u'q', u'dfn', u'abbr', u'time', u'code', u'var',\n u'samp', u'kbd', u'sub', u'sup', u'i', u'b', u'u',\n u'mark', u'ruby', u'rt', u'rp', u'bdi', u'bdo',\n u'span', u'br', u'wbr']\n\n _EDIT_ELEMENTS = [u'ins', u'del']\n\n _EMBEDDING_ELEMENTS = [u'img', u'iframe', u'embed', u'object', u'param',\n u'video', u'audio', u'source', u'track', u'canvas',\n u'map', u'area']\n\n _TABULAR_ELEMENTS = [u'table', u'caption', u'colgroup', u'col', u'tbody',\n u'thead', u'tfoot', u'tr', u'td', u'th']\n\n _FORM_ELEMENTS = [u'form', u'fieldset', u'legend', u'label', u'input',\n u'button', u'select', u'datalist', u'optgroup', u'option',\n u'textarea', u'keygen', u'output', u'progress', u'meter']\n\n _INTERACTIVE_ELEMENTS = ['details', u'summary', u'command', u'menu',\n u'dialog']\n\n _ALL_ELEMENTS = (_ROOT_ELEMENT + _META_DATA_ELEMENTS +\n _SCRIPTING_ELEMENTS + _SECTION_ELEMENTS +\n _GROUPING_ELEMENTS + _TEXT_LEVEL_ELEMENTS +\n _EDIT_ELEMENTS + _EMBEDDING_ELEMENTS +\n _TABULAR_ELEMENTS + _FORM_ELEMENTS +\n _INTERACTIVE_ELEMENTS)\n\n _VOID_ELEMENTS = [u'area', u'base', u'br', u'col', u'command', u'embed',\n u'hr', u'img', u'input', u'keygen', u'link', u'meta',\n u'param', u'source', u'track', u'wbr']\n\n _NO_LINE_BREAK_AROUND = _TEXT_LEVEL_ELEMENTS + _EDIT_ELEMENTS\n\n def __init__(self, name):\n \"\"\"\n Create an Element.\n\n Args:\n name: The name of the HTML5 element as a Unicode string.\n \"\"\"\n name = unicode(name)\n assert name in Element._ALL_ELEMENTS, (\"Element parameter name has to \"\n \"be a valid HTML5 element name.\")\n self._name = name\n self._children = []\n self._attributes = {}\n\n self._void_element = self._name in Element._VOID_ELEMENTS\n self._line_break_around = (not self._name in\n Element._NO_LINE_BREAK_AROUND)\n\n def __str__(self):\n \"\"\"\n Get a string representation of this Element.\n\n Returns:\n A Unicode string representing the Element object and its\n descendants. A minimal amount of whitespace will be used.\n \"\"\"\n start_tag = u'<%s%s>' % (self._name, self._attribute_string())\n\n if self._void_element:\n return start_tag\n\n children_string = u''.join(map(str, self._children))\n\n return u'%s%s' % (start_tag, children_string, self._name)\n\n def append_child(self, node):\n \"\"\"\n Appends a child node to this Element.\n\n Args:\n node: An object of type Node.\n \"\"\"\n self._children.append(node)\n\n def set_attribute(self, name, value):\n \"\"\"\n Sets an attribute of the Element.\n\n Args:\n name: Unicode string containing the name of the attribute.\n value: Unicode string containing the value of the attribute.\n \"\"\"\n self._attributes[name] = value\n\n def pretty_print(self, base_indentation = 0, line_break_before = False):\n \"\"\"\n Get an indented string representation of this Element.\n\n Each child gets indented by 2 spaces relative to its parent if it is\n indented at all.\n\n Args:\n base_indentation: An integer defining the base indentation. Defaults\n to 0.\n line_break_before: A boolean indicating whether the output should\n be formated as if there were a line break before it.\n Defaults to True and is for internal use while recursing.\n Returns:\n A Unicode string representing the element and its descendants\n indented with a base indentation as specified by the arguments.\n \"\"\"\n prefix_whitespace = u''\n if self._line_break_around and not line_break_before:\n prefix_whitespace += u'\\n'\n\n if self._line_break_around or line_break_before:\n prefix_whitespace += u' ' * base_indentation\n base_indentation += 2\n\n start_tag = u'<%s%s>' % (self._name, self._attribute_string())\n\n if self._void_element:\n return u'%s%s' % (prefix_whitespace, start_tag)\n\n children_strings = []\n if self._children:\n line_break_before = False\n\n do_line_breaks_inside = False\n for child in self._children:\n if isinstance(child, Text):\n continue\n if child._name in Element._NO_LINE_BREAK_AROUND:\n continue\n do_line_breaks_inside = True\n break\n\n for child in self._children:\n if do_line_breaks_inside:\n children_strings.append(u'\\n')\n line_break_before = True\n child_string = child.pretty_print(base_indentation=base_indentation,\n line_break_before=line_break_before)\n children_strings.append(child_string)\n\n if do_line_breaks_inside:\n children_strings.append(u'\\n')\n if self._line_break_around:\n base_indentation -= 2\n if do_line_breaks_inside:\n children_strings.append(' ' * base_indentation)\n\n return u'%s%s%s' % (prefix_whitespace, start_tag,\n u''.join(children_strings), self._name)\n\n def _attribute_string(self):\n \"\"\"Get the string representation of the attributes.\"\"\"\n attribute_strings = []\n for name, value in self._attributes.items():\n attribute_strings.append(u' %s=\"%s\"' % (name, value))\n return u''.join(attribute_strings)\n\n\nclass Text(Node):\n def __init__(self, text):\n \"\"\"\n Create a Text object.\n \"\"\"\n self._text = text\n\n def __str__(self):\n \"\"\"\n Get the _text attribte.\n\n Returns:\n The Unicode string attribute _text.\n \"\"\"\n return self._text\n\n def pretty_print(self, base_indentation, line_break_before):\n \"\"\"\n Get an indented string representation of this Text.\n\n Args:\n indent: The number of spaces to indent the text by.\n line_break_before: Boolean indicating whether there was a line break\n before the element gets printed.\n\n Returns:\n Just _text attribute unless line_break_before is indicated in which\n case the text gets indented according to the argument and a line\n break is inserted after the text.\n \"\"\"\n if line_break_before:\n return u'%s%s\\n' % (u' ' * base_indentation, self._text)\n else:\n return self._text\n","sub_path":"html5.py","file_name":"html5.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"331588493","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n- This is a program that watches a chosen directory and searches\n the text for a \"magic\" word.\n- Log when magic word is found.\n\"\"\"\n\n__author__ = \"Shaquon with help from Piero\"\n\nimport time\nimport argparse\nimport signal\nimport logging\nimport os\n\nlogging.basicConfig(\n format='%(asctime)s.%(msecs)03d %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.DEBUG\n)\nexit_flag = False\nlogger = logging.getLogger(__file__)\ntracking_dict = {}\n\n\ndef watch_directory(dir_to_watch, file_ext, search_text):\n dir_files = os.listdir(dir_to_watch)\n for file in dir_files:\n if file.endswith(file_ext) and file not in tracking_dict:\n tracking_dict[file] = 0\n logger.info(\"Now tracking {}\".format(file))\n\n for file in list(tracking_dict):\n if file not in dir_files:\n logger.info(\"{} removed from watchlist.\".format(file))\n del tracking_dict[file]\n\n for file in tracking_dict:\n tracking_dict[file] = find_magic(\n os.path.join(dir_to_watch, file),\n tracking_dict[file],\n search_text\n )\n\n\ndef find_magic(file, start_pos, magic_word):\n line_number = 0\n with open(file) as f:\n for line_number, line in enumerate(f):\n if line_number >= start_pos:\n if magic_word in line:\n new_line = line_number + 1\n logger.info(\n \"{}: found '{}' on line {}\".format(\n file, magic_word, new_line)\n )\n return line_number+1\n\n\ndef signal_handler(sig_num, frame):\n \"\"\"\n This is a handler for SIGTERM and SIGINT. Other signals can be mapped here as well (SIGHUP?)\n Basically it just sets a global flag, and main() will exit it's loop if the signal is trapped.\n :param sig_num: The integer signal number that was trapped from the OS.\n :param frame: Not used\n :return None\n \"\"\"\n # log the associated signal name (the python3 way)\n logger.warn('Received ' + signal.Signals(sig_num).name)\n # log the signal name (the python2 way)\n signames = dict((k, v) for v, k in reversed(\n sorted(signal.__dict__.items()))\n if v.startswith('SIG') and not v.startswith('SIG_'))\n logger.warn('Received ' + signames[sig_num])\n global exit_flag\n exit_flag = True\n\n\ndef create_parser():\n \"\"\"Creates parser and setup cmd line options\"\"\"\n parser = argparse.ArgumentParser(\n description='Watch directory for file changes')\n parser.add_argument(\"-i\", \"--interval\", default=1,\n help=\"polling interval, defaults to 1 second\")\n parser.add_argument(\"-d\", \"--dir\", default=\".\",\n help=\"directory to be watched, defaults to '.'\")\n parser.add_argument(\"-e\", \"--ext\", default='.txt',\n help=\"extension to be watched, defaults to .txt\")\n parser.add_argument(\"magic\", help=\"magic word to be found\")\n return parser\n\n\ndef main():\n parser = create_parser()\n args = parser.parse_args()\n\n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n\n start_time = time.time()\n\n logger.info(\n '\\n'\n '-------------------------------------------------------------------\\n'\n ' Running {0}\\n'\n ' Started on {1}\\n'\n '-------------------------------------------------------------------\\n'\n .format(__file__, start_time)\n )\n logger.info(\n 'Scanning path: {}, '\n 'for files with extension: {},'\n 'that contain the magic word: {}'\n .format(args.dir, args.ext, args.magic)\n )\n\n while not exit_flag:\n try:\n watch_directory(args.dir, args.ext, args.magic)\n except OSError:\n logger.error(\"Dir not found:\".format(watch_directory))\n time.sleep(5.0)\n except Exception as e:\n logger.error('{} Unhandled Exception'.format(str(e)))\n\n time.sleep(int(args.interval))\n\n end_time = time.time()\n\n logger.info(\n '\\n'\n '----------------------------------------------------\\n'\n 'Stopped watching\\n'\n 'Uptime was ' + str(int(end_time-start_time)) + ' seconds\\n'\n '----------------------------------------------------\\n'\n )\n\n logging.shutdown()\n\n\nif __name__ == '__main__':\n print('file is being run directly')\n main()\nelse:\n print('file is being imported')\n","sub_path":"dirwatcher.py","file_name":"dirwatcher.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"225781100","text":"# coding: utf-8\nimport sqlite3\n\nimport requests\n\n\n# 我用的是 Firefox\nDATABASE = 'cookies.sqlite'\n\n\ndef get_cookies():\n host = '.jd.com'\n sql = 'select name, value from moz_cookies where host = ?;'\n db = sqlite3.connect(DATABASE)\n cookies = db.execute(sql, (host,))\n cookies = cookies.fetchall()\n cookies = dict(cookies)\n return cookies\n\n\ndef is_login():\n url = 'https://home.m.jd.com/'\n cookies = get_cookies()\n r = requests.get(url, cookies=cookies, allow_redirects=False)\n # 如果没有登录就会重定向到登录页\n return r.headers['Location'].startswith(url)\n\n\ndef sign():\n url = 'https://api.m.jd.com/client.action?functionId=fBankSign&client=ld'\n cookies = get_cookies()\n r = requests.get(url, cookies=cookies)\n return r.json()\n\n\nif __name__ == '__main__':\n assert is_login(), 'Not logged in!'\n print(sign())\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"362170331","text":"#!/usr/bin/env python3\r\n#\r\n# written by Zaphron / Harold Seefeld GCI2014\r\n# https://www.google-melange.com/gci/task/view/google/gci2014/4995638496329728\r\n\r\nfrom xml.etree.ElementTree import ElementTree\r\n\r\nfrom xml.etree.ElementTree import Element\r\n\r\nimport xml.etree.ElementTree as etree\r\n\r\nimport xml.dom.minidom as minidom\r\n\r\nimport codecs\r\n\r\nfrom html.parser import HTMLParser\r\n\r\nh = HTMLParser()\r\n\r\n\r\n\r\n# Documentation:\r\n\r\n# - The .rtf dictionary was converted to a .txt file using http://document.online-convert.com/convert-to-txt\r\n\r\n# - The dictionary .rtf and .txt can be found in \"tatar-turkish translation.zip\".\r\n\r\n# - The .txt version of the dictionary should be named to \"dictionary.txt\" and placed in the same directory as the script for the python script to work.\r\n\r\n\r\n\r\n\r\n\r\n# Set Dictionary XML Elements\r\n\r\nroot = Element(\"dictionary\")\r\n\r\ntree = ElementTree(root)\r\n\r\nsection = etree.SubElement(root, \"section\")\r\n\r\nsection.set(\"id\", \"main\")\r\n\r\nsection.set (\"type\", \"standard\")\r\n\r\n\r\n\r\n# Tatar unique letters\r\n\r\nuniqueLetters = [\"А\", \"Ә\", \"Б\", \"В\", \"Г\", \"Д\", \"Е\", \"Ё\", \"Ж\", \"Җ\", \"З\", \"И\", \"Й\", \"К\", \"Л\", \"М\", \"Н\", \"Ң\", \"О\", \"Ө\", \"П\", \"Р\", \"С\", \"Т\", \"У\", \"Ү\", \"Ф\", \"Х\", \"Һ\", \"Ц\", \"Ч\", \"Ш\", \"Щ\", \"Ъ\", \"Ы\", \"Ь\", \"Э\", \"Ю\", \"Я\"]\r\n\r\n# Turkish Unique Letters\r\n\r\nunique2Letters = [\"D\", \"E\", \"F\", \"G\", \"Ğ\", \"I\", \"J\", \"K\", \"L\", \"N\", \"Ö\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Z\", \"Ş\", \"І\",\"Ç\"]\r\n\r\n\r\n\r\n# Letters to use for the prefix and suffix\r\n\r\nlanguageFix1 = \"ta\"\r\n\r\nlanguageFix2 = \"tr\"\r\n\r\n\r\n\r\n# Get file name of translation data\r\n\r\nfilename = \"dictionary.txt\"\r\n\r\n\r\n\r\n# Translation Data\r\n\r\ntxtData = codecs.open(filename, 'r', 'UTF-8').readlines()\r\n\r\ntxtSplitData = []\r\n\r\ntxtValidData = []\r\n\r\n\r\n\r\n# Split Extended Lines\r\n\r\nfor x in txtData:\r\n \r\n x = x.replace(\"O\", \"\") \r\n\r\n start = x.find( '(' )\r\n\r\n end = x.find( ')' )\r\n\r\n if start != -1 and end != -1:\r\n\r\n x = x[start:end]\r\n\r\n\r\n\r\n start = x.find( '{' )\r\n\r\n end = x.find( ')' )\r\n\r\n if start != -1 and end != -1:\r\n\r\n x = x[start:end]\r\n\r\n # Remove Whitespace\r\n\r\n x = x.lstrip()\r\n\r\n x = x.rstrip()\r\n\r\n txtSplitData.append(x)\r\n\r\n\r\n\r\n# Filter out all of the miscellaneous data\r\n\r\nfor x in txtSplitData: \r\n\r\n if x == \"n\":\r\n\r\n continue\r\n\r\n if x == \" \":\r\n\r\n continue\r\n\r\n if x == \"\":\r\n\r\n continue\r\n\r\n if \"[\" not in x:\r\n\r\n if \"]\" not in x:\r\n\r\n continue\r\n\r\n continue\r\n\r\n if \"]\" not in x:\r\n\r\n if \"[\" not in x:\r\n\r\n continue\r\n\r\n continue\r\n\r\n\r\n\r\n # Check lines that have 2 or more translations\r\n\r\n if x.count(\"[\") >= 2:\r\n\r\n x = x.replace(\" \", \" \")\r\n\r\n x = x.replace(\" \", \" \")\r\n\r\n newWords = x.split(\" \")\r\n passedWords = 0\r\n\r\n b = []\r\n\r\n hasBroken = False\r\n\r\n for l in newWords:\r\n\r\n tatarWord = False\r\n\r\n for y in uniqueLetters:\r\n\r\n l = l.upper()\r\n\r\n if y in l:\r\n\r\n tatarWord = True\r\n\r\n if tatarWord and passedWords >= 1:\r\n\r\n txtValidData.append(' '.join(b).lower())\r\n\r\n b = []\r\n\r\n b.append(l.lower().replace(\"<\", \"\")) \r\n\r\n passedWords = 0\r\n\r\n hasBroken = True\r\n\r\n break\r\n\r\n if not tatarWord:\r\n\r\n b.append(l.lower().replace(\"<\", \"\"))\r\n\r\n passedWords += 1\r\n\r\n elif tatarWord and hasBroken:\r\n\r\n hasBroken = False\r\n\r\n else:\r\n\r\n b.append(l.lower())\r\n\r\n continue\r\n\r\n\r\n\r\n \r\n\r\n # If the x passes all the tests append it to valid data\r\n\r\n txtValidData.append(x)\r\n\r\n\r\n\r\nfor x in txtValidData:\r\n\r\n x = x.strip()\r\n\r\n \r\n\r\n if x.startswith(\"[\"):\r\n\r\n continue\r\n \r\n if \":\" in x:\r\n continue\r\n\r\n\r\n\r\n x = x.replace(\"/\", \"\")\r\n\r\n x = x.replace(\")\", \"\")\r\n\r\n x = x.replace(\"(\", \"\")\r\n\r\n x = x.replace(\"{\", \"\")\r\n\r\n x = x.replace(\"❖\", \"\")\r\n\r\n x = x.replace(\"<\", \"\")\r\n\r\n x = x.replace(\"&\", \"\")\r\n\r\n x = x.replace(\" \", \"\")\r\n\r\n # Handle multiple definitions\r\n\r\n language1words = x.split(\"[\")\r\n\r\n language2words = x.split(\"]\")\r\n\r\n\r\n language1words1 = language1words[0].split(\",\")\r\n\r\n \r\n try:\r\n\r\n for language1word in language1words1:\r\n\t\t\r\n definitions = language2words[1].replace(',', \";\").replace('.', ';').split(\";\")\r\n\r\n if \":\" in language1word:\r\n\r\n continue\r\n\r\n # Remove Whitespace\r\n\r\n language1word = language1word.lstrip()\r\n\r\n language1word = language1word.rstrip()\r\n\r\n language1word = language1word.replace(\" II\", \"\")\r\n\r\n language1word = language1word.replace(\" I\", \"\")\r\n\r\n language1word = language1word.replace(\" ii\", \"\")\r\n\r\n language1word = language1word.replace(\" ii\", \"\")\r\n\r\n language1word = language1word.strip().replace(\" \", \"\")\r\n\r\n\r\n\r\n\r\n for definition in definitions:\r\n\r\n # Replace Filter Characters\r\n\r\n definition = definition.replace(\"[\", \"\")\r\n\r\n definition = definition.replace(\"]\", \"\")\r\n\r\n definition = definition.replace(\"1\", \"\")\r\n\r\n definition = definition.replace(\"2\", \"\")\r\n\r\n definition = definition.replace(\"3\", \"\")\r\n\r\n definition = definition.replace(\"4\", \"\")\r\n\r\n definition = definition.replace(\";\", \"\")\r\n\r\n definition = definition.replace(\",\", \"\")\r\n\r\n definition = definition.replace(\".\", \"\")\r\n\r\n definition = definition.replace(\" vb\", \"\")\r\n\r\n\r\n # Remove Whitespace\r\n\r\n definition = definition.lstrip()\r\n\r\n definition = definition.rstrip()\r\n\r\n if definition.endswith(''):\r\n definition = definition.strip()[:-4]\r\n\r\n if definition.startswith(''):\r\n definition = definition.strip()[4:]\r\n\r\n if language1word.endswith(''):\r\n language1word = language1word.strip()[:-4]\r\n\r\n if language1word.startswith(''):\r\n language1word = language1word.strip()[4:]\r\n\r\n definition = definition.rstrip()\r\n\r\n oldCount = len(language1word)\r\n\r\n language1word = language1word.strip(\"-\").strip(\"-\")\r\n\r\n newCount = len(language1word)\r\n\r\n if oldCount != newCount:\r\n if definition.endswith('-mek'):\r\n definition = definition.strip()[:-4]\r\n\r\n if definition.endswith('mek'):\r\n definition = definition.strip()[:-3]\r\n\r\n if definition.endswith('-mak'):\r\n definition = definition.strip()[:-4]\r\n\r\n if definition.endswith('mak'):\r\n definition = definition.strip()[:-3]\r\n\r\n language1word = language1word.strip(\"--\")\r\n language1word = language1word.strip(\"-\")\r\n\r\n definition = definition.strip(\"-\")\r\n\r\n definition = definition.strip().replace(\" \", \"\")\r\n\r\n successfulInitialWord = False\r\n\r\n for yxl in uniqueLetters:\r\n\r\n if yxl in language1word.upper():\r\n\r\n successfulInitialWord = True\r\n\r\n\r\n if not successfulInitialWord:\r\n\r\n continue\r\n\r\n\r\n if (language1word.replace(\"\", \"\").strip() == \"\" or definition.replace(\"\", \"\").strip() == \"\"):\r\n\r\n continue\r\n\r\n definition = definition.lower()\r\n\r\n language1word = language1word.lower()\r\n\r\n \r\n\r\n successfulInitialWord = True\r\n\r\n for yxl in uniqueLetters:\r\n\r\n if yxl in definition.upper():\r\n\r\n successfulInitialWord = False\r\n \r\n\r\n if not successfulInitialWord:\r\n\r\n continue\r\n\r\n for yxl in unique2Letters:\r\n\r\n if yxl in language1word.upper():\r\n\r\n successfulInitialWord = False\r\n \r\n\r\n if not successfulInitialWord:\r\n\r\n continue\r\n\r\n if (language1word.replace(\"\", \"\") == \"\" or definition.replace(\"\", \"\") == \"\"):\r\n\r\n continue\r\n\r\n definition = definition.strip(\"-\").strip(\"--\")\r\n\r\n if oldCount != newCount:\r\n\r\n etree.SubElement(section, \"e>\" + \"

\" + \"\" + language1word + '' + \"\" + \"\" + definition + '' + \"\" + \"

\" + \"\")\r\n\r\n continue\r\n\r\n shouldContinue = False\r\n \r\n for bl in txtSplitData:\r\n if language1word.capitalize() in bl and definition.capitalize() in bl:\r\n etree.SubElement(section, \"e>\" + \"

\" + \"\" + language1word.capitalize() + '' + \"\" + \"\" + definition.capitalize() + '' + \"\" + \"

\" + \"\")\r\n shouldContinue = True\r\n break\r\n elif language1word.capitalize() in bl and definition.capitalize() not in bl: \r\n shouldContinue = True\r\n etree.SubElement(section, \"e>\" + \"

\" + \"\" + language1word.capitalize() + '' + \"\" + \"\" + definition + '' + \"\" + \"

\" + \"\")\r\n break\r\n \r\n if shouldContinue == True:\r\n continue\r\n\r\n etree.SubElement(section, \"e>\" + \"

\" + \"\" + language1word + '' + \"\" + \"\" + definition + '' + \"\" + \"

\" + \"\")\r\n\r\n except IndexError:\r\n pass\r\n\r\n\r\n\r\n\r\n\r\ntranslationXML = codecs.open(\"translation.dix\", \"w\", \"UTF-8\")\r\n\r\nxml = etree.tostring(root)\r\n\r\nxml = h.unescape(str(xml))\r\n\r\nxml = xml.replace(\" />\", \"\")\r\n\r\nxml = xml.replace(\"\", \"\")\r\n\r\nxml = xml.replace(\"\\\\\", \"\")\r\n\r\nxml = xml.replace(\" \",\"\")\r\n\r\nxml = xml.replace(\"b'\", \"\")\r\n\r\nxml = xml.replace(\"'\", \"\")\r\n\r\nxml = xml.replace(\"<<\", \"\")\r\n\r\nxml = xml.replace(\"­\", \"\")\r\n\r\nxml = xml.replace(\"vb.\", \"\")\r\n\r\nxml = xml.replace(\"+\", \"\")\r\n\r\nxml = xml.replace(\"\", \"\").replace(\"\", \"\").replace(\"\", \"\").replace(\"\", \"\")\r\n\r\nxml = xml.replace(\"\", \"\")\r\n\r\nxml = xml.replace(\"409\", \"\")\r\n\r\nxml = xml.replace(\",,\",\"\")\r\n\r\nxml = xml.replace(\",\", \"\")\r\n\r\nxml = xml.replace(\";\", '')\r\n\r\nxml = xml.replace(\"-\", \"\").replace(\"-\", \"\").replace(\"\", \"\").replace(\"\", \"\").replace(\"<\", \"<\").replace(\">\", \">\")\r\n\r\n\r\nxml = minidom.parseString(xml).toprettyxml()\r\n\r\n \r\n\r\ntranslationXML.write(str(xml))\r\n\r\ntranslationXML.close()\r\n\r\n\r\n\r\nprint (\"Dictionary \" + languageFix1 + \"-\" + languageFix2 + \" written to 'translation.dix'.\")\r\n","sub_path":"apertium-tools/dixscrapers/tatar-turkish.py","file_name":"tatar-turkish.py","file_ext":"py","file_size_in_byte":11276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"114931238","text":"import torch.nn as nn\n\nimport mask\n\nclass Encoder(nn.Module):\n def __init__(self):\n super().__init__()\n\n # 定义编码层\n encoder_layer = nn.TransformerEncoderLayer(d_model=256,\n nhead=4,\n dim_feedforward=256,\n dropout=0.2,\n activation='relu')\n\n # 定义规范化层\n norm = nn.LayerNorm(normalized_shape=256, elementwise_affine=True)\n\n # 定义编码器\n self.encoder = nn.TransformerEncoder(encoder_layer=encoder_layer,\n num_layers=3,\n norm=norm)\n\n def forward(self, x, mask_x):\n # 转换成torch要求的格式\n # [b, 60, 256] -> [60, b, 256]\n x = x.permute(1, 0, 2)\n\n # 编码层计算\n # [60, b, 256] -> [60, b, 256]\n out = self.encoder(src=x, mask=mask.attn_mask, src_key_padding_mask=mask_x)\n\n # 转换回自己的格式\n # [60, b, 256] -> [b, 60, 256]\n out = out.permute(1, 0, 2)\n\n return out\n","sub_path":"13.bert/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"555289286","text":"import iris.coord_categorisation\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport numpy as np\nimport scipy.stats as stats\nfrom cf_units import Unit\nstyle.use(\"seaborn\")\n\n##### region Parse\n\n# Pull in data from file\neastward_wind = iris.load('u_component_of_wind.nc')[0]\nnorthward_wind = iris.load('v_component_of_wind.nc')[0]\ngeopotential = iris.load('geopotential.nc')[0]\n\n# Find the wind speed\nwind_speed_squared = eastward_wind ** 2 + northward_wind ** 2\nwind_speed_squared.standard_name = \"wind_speed\"\nwind_speed_squared.long_name = \"Wind Speed Squared\"\nwind_speed_squared.var_name = \"V\"\n\n# Find the altitude from geopotential\naltitude = geopotential / 9.80665\naltitude.standard_name = \"altitude\"\naltitude.long_name = \"Altitude\"\naltitude.var_name = \"h\"\naltitude.units = Unit(\"meters\")\n\n# Clear memory\n# del eastward_wind\n# del northward_wind\n# del geopotential\n# del Unit\n\n# Debug: Plot\n# qplt.contourf(wind_speed[0,0,:,:])\n# qplt.show()\n\n# Display info\nprint(\"\\nOriginal Data:\")\nprint(wind_speed_squared.summary())\nprint(altitude.summary())\n\n# Take a small sampling just to test # TODO remove for full analysis\ndims = wind_speed_squared.shape\ntimes_to_use = np.arange(0, 1968, 24) #np.round(np.linspace(0, dims[0]-1, 82)).astype(int)\npressure_levels_to_use = 8#np.round(np.linspace(0, dims[1]-1, 5)).astype(int)\nlats_to_use = 46 #np.round(np.linspace(0, dims[2]-1, 100)).astype(int)\nlons_to_use = np.round(np.linspace(0, dims[2]-1, 100)).astype(int)\n\nwind_speed_squared = wind_speed_squared[\n times_to_use,\n pressure_levels_to_use,\n lats_to_use,\n lons_to_use\n]\naltitude = altitude[\n times_to_use,\n pressure_levels_to_use,\n lats_to_use,\n lons_to_use\n]\n\n# Add time categorization\n\niris.coord_categorisation.add_hour(wind_speed_squared, 'time', name='hour_of_day')\niris.coord_categorisation.add_hour(altitude, 'time', name='hour_of_day')\n\n# Display info\nprint(\"\\nData to use:\")\nprint(wind_speed_squared.summary())\nprint(altitude.summary())\n\n# endregion\n\n##### region Analyze\n\n# plt.scatter(wind_speed.data.reshape(-1), altitude.data.reshape(-1))\n# plt.show()\n\n# Regression\n\n\n# data = wind_speed.data\nprint(\"Reshaping data...\")\ndata = wind_speed_squared.data.reshape(-1)\nprint(\"Data reshaped!\")\n\nimport time\n\nstart = time.time()\n\n### Method 3\nparams = stats.ncx2.fit(\n data,\n 2, # Degrees of freedom\n 0.25, # Noncentrality parameter\n fix_df=2, # 2 DoF\n floc=0, # centered at zero\n scale=40 # scale\n # fscale=1 # scale\n)\n\nprint(\"Fit Parameters:\\n\", params)\nprint(\"Fit Runtime:\\n\", time.time() - start)\n\n# Visualize distribution\nstyle.use('fivethirtyeight')\nx = np.linspace(0, np.max(data),400)\nplt.figure()\nplt.plot(x, stats.ncx2.pdf(x, *params), label=\"Model\")\nplt.hist(data, bins=120, density=True, label=\"Data\")\nplt.xlabel(\"Wind Speed Squared [(m/s)^2]\")\nplt.ylabel(\"Probability Distribution Function\")\nplt.title(\"Wind Speed over CONUS, Summer\\n5 kPa PL (~20908 m, ~68596 ft.)\")\nplt.legend()\nplt.grid(True)\nplt.tight_layout()\nplt.savefig(\"fit.png\", dpi=600)\nplt.savefig(\"fit.svg\")\nplt.show()\n\n# Print percentiles\nprint(\"Data Wind Speed 99th percentile: \", np.sqrt(np.percentile(data, 99)))\nprint(\"Fit Wind Speed 99th percentile: \", np.sqrt(stats.ncx2.ppf(0.99, *params)))\n# endregion\n","sub_path":"CONUS/Winds/analyze_data.py","file_name":"analyze_data.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"499691316","text":"import os\nimport glob\nimport pandas as pd\nimport numpy as np\nimport math\nfrom datetime import date\n\ncombined_fundamentals_files = os.listdir('./combined-fund')\n\nfor file in os.listdir('./technicals-processed'):\n if file in combined_fundamentals_files:\n print(file)\n fundamental_data = pd.read_csv('./combined-fund/' + file)\n technical_data = pd.read_csv('./technicals-processed/' + file)\n \n \n cols = technical_data.columns[0:].tolist() + fundamental_data.columns[1:].tolist()\n df = pd.DataFrame(columns=cols)\n \n# print(df)\n for i in range(len(technical_data)):\n tech_date = technical_data.iloc[i][0]\n# print(tech_date)\n\n indices = fundamental_data.date[fundamental_data.date >= tech_date].index.tolist()\n# print(fundamental_data.iloc[index].tolist())\n# print(indices)\n \n if len(indices) > 0:\n index = indices[-1]\n \n if index != -1:\n fun_date = fundamental_data.iloc[index][0]\n if str(date(int(fun_date[0:4]), int(fun_date[5:7]), int(fun_date[8:])) - date(int(tech_date[0:4]), int(tech_date[5:7]), int(tech_date[8:]))) > '92':\n break\n \n combined_row = technical_data.iloc[i].tolist() + fundamental_data.iloc[index].tolist()[1:]\n df.loc[len(df)+1] = combined_row\n \n \n df.to_csv('./combined-all/' + file, index = False)\n print('Done writing to ' + file)","sub_path":"data processing/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"222765825","text":"\"\"\"\nCopyright (c) 2019 Red Hat, Inc\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license. See the LICENSE file for details.\n\"\"\"\n\nfrom io import BytesIO\nimport os\n\nimport pytest\n\nfrom atomic_reactor.utils.omps import OMPS, OMPSError\n\n\nclass TestOMPS(object):\n\n token = \"supersecrettoken\"\n omps_url = 'https://omps.example.com'\n omps_namespace = 'test_namespace'\n\n def test_from_config(self, tmpdir):\n \"\"\"Test creation of OMPS instance from config\"\"\"\n config = {\n 'omps_url': self.omps_url,\n 'omps_namespace': self.omps_namespace,\n 'omps_secret_dir': str(tmpdir)\n }\n\n token_path = os.path.join(str(tmpdir), 'token')\n with open(token_path, 'w') as f:\n f.write(self.token)\n f.flush()\n\n omps = OMPS.from_config(config)\n assert omps\n assert omps.organization == self.omps_namespace\n assert omps.url == self.omps_url\n assert omps._token == self.token\n\n def test_push_archive(self, requests_mock):\n \"\"\"Test pushing manifest zipfile to omps service\"\"\"\n omps_res = {'omps': 'answer'}\n requests_mock.register_uri(\n 'POST',\n \"{}/v2/{}/zipfile\".format(self.omps_url, self.omps_namespace),\n request_headers={'Authorization': self.token},\n json=omps_res\n )\n omps = OMPS(self.omps_url, self.omps_namespace, self.token)\n fb = BytesIO(b'zip file')\n res = omps.push_archive(fb)\n assert res == omps_res\n\n def test_push_archive_failure(self, requests_mock):\n \"\"\"Test failure when pushing manifest zipfile to omps service\"\"\"\n error = 'ErrorCode'\n emsg = 'Detailed message'\n status_code = 400\n # keep here only one entry to testing, to keep order deterministic\n # after str() call\n validation_info = {'errors': ['CSV is incorrect']}\n\n omps_res = {\n 'error': error, 'message': emsg,\n 'validation_info': validation_info}\n requests_mock.register_uri(\n 'POST',\n \"{}/v2/{}/zipfile\".format(self.omps_url, self.omps_namespace),\n request_headers={'Authorization': self.token},\n json=omps_res,\n status_code=status_code,\n )\n omps = OMPS(self.omps_url, self.omps_namespace, self.token)\n fb = BytesIO(b'zip file')\n with pytest.raises(OMPSError) as exc:\n omps.push_archive(fb)\n assert exc.value.status_code == status_code\n assert exc.value.response == omps_res\n assert '(validation errors: {})'.format(validation_info) in str(exc.value)\n\n def test_push_archive_server_error(self, requests_mock):\n \"\"\"Service running behind HAProxy may return 503 error without json.\n Test if this case is handled gracefully\"\"\"\n status_code = 503\n requests_mock.register_uri(\n 'POST',\n \"{}/v2/{}/zipfile\".format(self.omps_url, self.omps_namespace),\n request_headers={'Authorization': self.token},\n text='Service unavailable',\n status_code=status_code,\n )\n omps = OMPS(self.omps_url, self.omps_namespace, self.token)\n fb = BytesIO(b'zip file')\n with pytest.raises(OMPSError) as exc:\n omps.push_archive(fb)\n assert exc.value.status_code == status_code\n assert exc.value.response == {}\n","sub_path":"tests/utils/test_omps.py","file_name":"test_omps.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"508221622","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport random\nimport csv\nfrom datetime import timedelta, datetime\nfrom graphication import FileOutput, Series, SeriesSet, Label, SimpleScale, css, default_css as style\nfrom graphication.scales.date import AutoWeekDateScale, AutoDateScale\nfrom graphication.wavegraph import WaveGraph\n\ndef colorgen():\n colours = (\n \"#4D8963\",\n \"#69A583\",\n \"#E1B378\",\n \"#E0CC97\",\n \"#EC799A\",\n \"#9F0251\")\n\n while 1:\n for c in colours: yield c\n\ncolour_loop = colorgen()\n\nseries_set = SeriesSet()\nfor filename in sys.argv[1:]:\n data = []\n for row in csv.reader(open(filename)):\n data.append((datetime.strptime(row[0], '%m-%d-%Y'), int(row[1])))\n\n name = os.path.splitext(filename)[0]\n series_set.add_series(Series(name, dict(data), colour_loop.next()))\n\noutput = FileOutput()\nscale = AutoWeekDateScale(series_set)\n#scale = AutoDateScale(series_set)\n\nwg = WaveGraph(series_set, scale, None, label_curves=True)\nlb = Label(', '.join(map(lambda x: x.title, series_set)), None)\n\nwidth = 20*len(series_set.keys())\noutput.add_item(lb, x=10, y=5, width=width-20, height=20)\noutput.add_item(wg, x=0, y=30, width=width, height=500)\n\nfilename = \"_\".join(map(lambda x: x.title, series_set))\n\noutput.write(\"png\", (\"%s.png\" % filename))\noutput.write(\"pdf\", (\"%s.pdf\" % filename))\n","sub_path":"twitter_dreams/streamgraph.py","file_name":"streamgraph.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"539501388","text":"import socket\n\n\n# 创建套接字对象\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# 连接服务器\nclient.connect(('127.0.0.1', 8000))\nwhile True:\n # 接收信息\n data = client.recv(1024)\n print(f'收到信息:{data.decode()}')\n s = input('输入信息:')\n if s == 'q':\n client.close()\n break\n # 发送信息\n client.sendall(s.encode())\n\n","sub_path":"练习/client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"276407763","text":"from tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import models\nimport numpy as np\n\nmodel = models.load_model(filepath=MODEL_SAVE_PATH)\n\n# model.summary()\n\nnp_handler = np.load(\"test_plp_data_and_label.npz\")\n\nfor key in np_handler.keys():\n print(key)\n\ntest_data, test_label = np_handler['plp_data'], np_handler['plp_label']\n\nprint(\"shape of test_data\", np.shape(test_data))\nprint(\"shape of test_label\", np.shape(test_label))\n\ntest_label = to_categorical(test_label)\n\nloss, acc = model.evaluate(test_data, test_label)\nprint(\"복원된 모델의 정확도: {:5.2f}%\".format(100 * acc))\n","sub_path":"Voice similarity/Voice similarity (rasta-plp)/model_testing.py","file_name":"model_testing.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"174567785","text":"#from import_util import PowDagSim\nfrom PowDagSim.task import Task\nfrom PowDagSim.app_file_handler import load_task_file\n\n\"\"\"\ndef get_pace_tasks(toposorted_tasks):\n all_pace_tasks = {}\n pace_sorted_dag = []\n pace_tasks_by_dag_index = {}\n\n for dictionary in toposorted_tasks:\n group = []\n for index, tasks in dictionary.items():\n app_id = tasks[0].index\n pace_task = get_pace(tasks)\n if app_id not in all_pace_tasks:\n all_pace_tasks[app_id] = pace_task\n if index not in pace_tasks_by_dag_index:\n pace_tasks_by_dag_index[index] = pace_task\n group.append(pace_task)\n pace_sorted_dag.append(group)\n\n return pace_sorted_dag, all_pace_tasks, pace_tasks_by_dag_index\n\"\"\"\n\n\n\ndef get_pace_tasks_of_all_applications(applications, power_cap):\n pace_tasks = [None] * len(applications)\n\n for index, app in applications.items():\n pace_tasks[index] = get_pace(app.tasks, power_cap)\n\n return pace_tasks\n\n\n\ndef get_pace(taskFile, power_cap):\n highestTask = None\n maxVal = -1\n for task in taskFile:\n if power_cap >= task.power > 0:\n ratio = task.speed/(task.power)\n else:\n ratio = 0\n if(ratio >= maxVal):\n maxVal = ratio\n highestTask = task\n\n maxSpeed = 0\n #if there are multiple configs matching pace, pick the task with higher speed\n for task in taskFile:\n if power_cap >= task.power > 0:\n ratio = task.speed/(task.power)\n else:\n ratio = 0\n if ratio == maxVal:\n if task.speed >= maxSpeed:\n maxSpeed = task.speed\n highestTask = task\n\n return highestTask\n\n\n\ndef get_race(taskFile, power_cap):\n highestTask = None\n maxVal = -1\n for task in taskFile:\n if power_cap >= task.power > 0:\n speed = task.speed\n else:\n speed = 0\n if(speed >= maxVal):\n maxVal = speed\n highestTask = task\n curPower = highestTask.power\n #if there are multiple configs matching speed, pick the task with lower power\n for task in taskFile:\n if power_cap >= task.power > 0:\n speed = task.speed\n else:\n speed = 0\n if speed == maxVal:\n if task.power < curPower:\n curPower = task.power\n highestTask = task\n return highestTask\n\n\n\n\n\n\n\ndef get_corresponding_tasks_of_all_applications(applications, power_estimate):\n corresponding_tasks = [None] * len(applications)\n\n for index, app in applications.items():\n for i in range(1,1000):\n corresponding_tasks[index] = min((task for task in app.tasks if power_estimate*(10-i)/10 <= task.power <= power_estimate*(10+i)/10), key = lambda x: x.time, default = None)\n if corresponding_tasks[index] is not None:\n break\n\n return corresponding_tasks\n","sub_path":"straggleroptimize/PowDagSim/pace.py","file_name":"pace.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"645129364","text":"#CLASSE FILA =====================================\r\n\r\nclass Fila:\r\n def __init__ (self):\r\n self.fila = []\r\n\r\n\r\n def enqueue (self):\r\n valor = int(input(\"Digite o valor a ser adcionado na Fila:\"))\r\n self.fila.append(valor)\r\n\r\n\r\n def dequeue (self):\r\n if not (self.isEmpty()):\r\n self.fila.pop(0)\r\n \r\n \r\n\r\n def isEmpty (self):\r\n return len(self.fila)== 0\r\n\r\n\r\n def Length (self):\r\n return len(self.fila)\r\n\r\n#===============================================\r\n\r\n\r\n#CLASSE PILHA==================================\r\n\r\nclass Pilha():\r\n#===================Construtor======================\r\n\r\n def __init__(self):\r\n self.pilha = []\r\n\r\n#=======Adciona Um Elemento ao Topo da Pilha========\r\n\r\n def Push(self,elemento):\r\n self.pilha.append(elemento)\r\n\r\n\r\n#=======Retira Um Elemento do Topo da Pilha=========\r\n \r\n def Pop(self):\r\n if (len(self.pilha)==0):\r\n print(\"Não Há Elementos na Sua Pilha!\")\r\n else: \r\n self.pilha.pop()\r\n\r\n\r\n#==========Verifica se a Pilha está Vazia============\r\n \r\n def IsEmpty(self):\r\n if len(self.pilha) == 0:\r\n print(\"Sua Pilha Esta Vazia\")\r\n else:\r\n print(\"Sua Pilha Contem Elementos\")\r\n\r\n#===========Verifica o Topo da Pilha=================\r\n \r\n def Peek(self):\r\n topo = self.pilha[-1]\r\n print(\"O Topo da Pilha é o\",topo)\r\n\r\n #========Verifica o Tamanho da Pilha=============== \r\n def Length(self):\r\n tamanho = (len(self.pilha))\r\n if tamanho >1:\r\n print(\"Sua Pilha Contem %d Elementos\"%(tamanho))\r\n elif tamanho ==1:\r\n print(\"Sua Pilha Contem 1 Elemento!\")\r\n else:\r\n print(\"Sua Pilha Não Contem Nenhum Elemento!\")\r\n\r\n\r\nfila = Fila()\r\n\r\nfila.enqueue()\r\nfila.enqueue()\r\nfila.enqueue()\r\nfila.enqueue()\r\nfila.enqueue()\r\n\r\nprint(\"Sua Fila:\",fila.fila)\r\n\r\nlista_auxiliar = Pilha()\r\n\r\naux_2 = 0\r\n\r\nfor i in range (len(fila.fila)-1):\r\n aux_2 = fila.fila[0]\r\n fila.dequeue()\r\n lista_auxiliar.Push(aux_2)\r\n\r\nprint(lista_auxiliar.pilha)\r\nprint(fila.fila)\r\n\r\nlista_final = []\r\n\r\naux_3 = 0\r\n\r\nlista_final.append(fila.fila[0])\r\n\r\nfor i in range(len(lista_auxiliar.pilha)):\r\n \r\n aux_3 = lista_auxiliar.pilha[-1]\r\n\r\n lista_final.append(aux_3)\r\n\r\n lista_auxiliar.Pop()\r\n\r\n\r\nprint(\"Lista Final:\",lista_final)\r\n","sub_path":"Questão_1.py","file_name":"Questão_1.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"380435604","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import NumericProperty, ReferenceListProperty\nfrom kivy.properties import ObjectProperty\nfrom kivy.vector import Vector\nfrom kivy.clock import Clock\nimport random\nfrom kivy.graphics import Color, Ellipse, Line, InstructionGroup\nfrom kivy.core.image import Image\nfrom kivy.graphics.texture import Texture\n\n\nclass Block(Widget):\n def __init__(self, i, j):\n super().__init__()\n self.ans = i\n self.now = j\n\n\nclass Game(Widget):\n def set(self):\n self.blocks = list()\n self.now_move = -1\n ran = [i for i in range(16)]\n random.shuffle(ran)\n for i in range(16):\n self.blocks.append(Block(i, ran[i]))\n self.add_widget(self.blocks[i])\n\n def on_touch_move(self, touch):\n for block in self.blocks:\n if block.collide_point(touch.x, touch.y):\n if block.ans != 15:\n self.now_move = block.ans\n elif self.now_move != -1:\n old_pos = block.now\n block.now = self.blocks[self.now_move].now\n self.blocks[self.now_move].now = old_pos\n\n\nclass PuzzleApp(App):\n def build(self):\n game = Game()\n game.set()\n return game\n\n\nif __name__ == '__main__':\n PuzzleApp().run()\n","sub_path":"puzzle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"329416423","text":"from neo4j import GraphDatabase\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"OWL_file_url\")\nargs = parser.parse_args()\n\nconf = \"https://raw.githubusercontent.com/VirtualFlyBrain/neo4j2owl/\" \\\n \"master/src/test/resources/minimal-config.yaml\"\n\ndriver = GraphDatabase.driver(\"bolt://localhost:7687\", auth=(\"neo4j\", \"neo4j\"))\nstatement = \"CALL ebi.spot.neo4j2owl.owl2Import('%s','%s')\" % (args.OWL_file_url, conf)\n\nprint()\nwith driver.session() as session:\n session.run(statement)\n r = session.run(\"MATCH (c:Class) return c.label limit 1\")\n print(r.single()[0])","sub_path":"src/load_db.py","file_name":"load_db.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"151356592","text":"\n\n#calss header\nclass _DISCRETION():\n\tdef __init__(self,): \n\t\tself.name = \"DISCRETION\"\n\t\tself.definitions = [u'the ability to behave without causing embarrassment or attracting too much attention, especially by keeping information secret: ', u'the right or ability to decide something: ']\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/_discretion.py","file_name":"_discretion.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"603290745","text":"import argparse\nimport textwrap\nfrom dataclasses import dataclass, fields\n\nfrom .testutils import *\n\n\ndef test_tuple_any_becomes_string():\n @dataclass\n class Container(TestSetup):\n strings: Tuple = (64, 128, 256, 512)\n\n c = Container.setup(\"\")\n assert c.strings == (64, 128, 256, 512)\n c = Container.setup(\"--strings 12 24 36\")\n assert c.strings == (\"12\", \"24\", \"36\")\n\n\ndef test_tuple_with_n_items_takes_only_n_values():\n @dataclass\n class Container(TestSetup):\n ints: Tuple[int, int] = (1, 5)\n\n c = Container.setup(\"\")\n assert c.ints == (1, 5)\n with raises_unrecognized_args(\"6\", \"7\", \"8\"):\n c = Container.setup(\"--ints 4 5 6 7 8\")\n\n\ndef test_tuple_elipsis_takes_any_number_of_args():\n @dataclass\n class Container(TestSetup):\n ints: Tuple[int, ...] = (1, 2, 3)\n c = Container.setup(\"\")\n assert c.ints == (1, 2, 3)\n c = Container.setup(\"--ints 4 5 6 7 8\")\n assert c.ints == (4, 5, 6, 7, 8)\n\ndef test_tuple_with_ellipsis_help_format():\n @dataclass\n class Container(TestSetup):\n ints: Tuple[int, ...] = (1, 2, 3)\n\n assert_help_output_equals(Container.get_help_text(), f\"\"\"\n usage: pytest [-h] [--ints int [int, ...]]\n \n optional arguments:\n -h, --help show this help message and exit\n \n test_tuple_with_ellipsis_help_format..Container ['container']:\n Container(ints: Tuple[int, ...] = (1, 2, 3))\n \n --ints int [int, ...]\n \"\"\")\n\ndef test_each_type_is_used_correctly():\n \n @dataclass\n class Container(TestSetup):\n \"\"\" A container with mixed items in a tuple. \"\"\"\n mixed: Tuple[int, str, bool, float] = (1, \"bob\", False, 1.23)\n \n c = Container.setup(\"\")\n assert c.mixed == (1, \"bob\", False, 1.23)\n \n c = Container.setup(\"--mixed 1 2 0 1\")\n assert c.mixed == (1, \"2\", False, 1.0)\n \n assert_help_output_equals(Container.get_help_text(), \"\"\"\n usage: pytest [-h] [--mixed int str bool float]\n\n optional arguments:\n -h, --help show this help message and exit\n\n test_each_type_is_used_correctly..Container ['container']:\n A container with mixed items in a tuple. \n\n --mixed int str bool float\n \"\"\")\n\n\ndef test_issue_29():\n from simple_parsing import ArgumentParser\n @dataclass\n class MyCli:\n asdf: Tuple[str, ...]\n\n parser = ArgumentParser()\n parser.add_arguments(MyCli, dest=\"args\")\n args = parser.parse_args(\"--asdf asdf fgfh\".split())\n assert args.args == MyCli(asdf=(\"asdf\", \"fgfh\"))\n","sub_path":"test/test_tuples.py","file_name":"test_tuples.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"344739281","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras import optimizers\nimport random\nimport pandas as pd\nimport math\nimport numpy as np\nfrom keras.layers import LeakyReLU\nfrom keras.models import load_model\nfrom keras.models import save_model\nimport ta\n\n\n\nclass Neu_Net:\n ogren = 0\n testt= 1\n\n output_size=2\n\n def offline_data(self,rows,skiprows):\n if skiprows>0:\n self.ohlc = pd.read_csv(\"btc_1h_last.csv\", skiprows=range(1, skiprows), nrows=rows)\n else:\n self.ohlc = pd.read_csv(\"btc_1h_last.csv\", nrows=rows,header=0,usecols=[\"open\",\"high\",\"low\",\"close\"])\n return self.ohlc\n\n def s_w(self,w1):\n self.model_fifteen.set_weights(w1)\n\n def __init__(self,l1,l2,l3,alpha,lr,csv_length,episode):\n self.t_length = 3300\n self.csv_length=csv_length\n self.input_length = 10\n self.ind_length = 200\n self.iteration = csv_length\n self.episode=episode\n\n self.indicators = ta.Ta()\n\n self.states = self.offline_data(rows=self.t_length,skiprows=0)\n\n self.model_fifteen = Sequential()\n self.model_fifteen.add(Dense(int(l1), input_dim=self.input_length))\n self.model_fifteen.add(LeakyReLU(alpha=alpha))\n self.model_fifteen.add(Dense(int(l2)))\n self.model_fifteen.add(LeakyReLU(alpha=alpha))\n self.model_fifteen.add(Dense(int(l3)))\n self.model_fifteen.add(LeakyReLU(alpha=alpha))\n self.model_fifteen.add(Dense(self.output_size, activation='linear'))\n adm = optimizers.SGD(lr=lr)\n self.model_fifteen.compile(loss='mse', optimizer=adm)\n\n def normalisse(self, inp):\n # mn = inp.min()\n # mx = inp.max()\n mx = max(inp)\n mn = min(inp)\n outp = (inp - mn) / (mx - mn)\n outp = np.array(outp).reshape(-1, self.input_length)\n return outp\n\n\n def inputer(self,pos,pls):\n state = pd.read_csv(\"training_data.csv\")\n\n state = state[\"0\"][pos - (self.ind_length - 1)].replace('[', ' ')\n state = state.replace(']', ' ')\n state = state.split(',')\n for i in range(len(state)):\n state[i] = float(state[i])\n\n state = np.asarray(state)\n return state\n\n\n def main_loop(self):\n for episode in range(self.episode):\n print(\"Episode : \"+str(episode))\n epsilon=1\n\n if self.ogren==1:\n for i in range(self.ind_length-1,self.csv_length-20,1): #5\n\n rand=random.random()\n if rand <= 0.5 :\n action=1\n elif rand >0.5:\n action=2\n\n rand = random.random()\n print(rand)\n if rand > 0.7:\n\n # 1. network\n state_now = self.inputer(i, 1)\n next_state = self.inputer(i + 1, 1)\n inp_state = self.normalisse(state_now)\n inp_next_s = self.normalisse(next_state)\n reward = np.array(0.95 * self.model_fifteen.predict(inp_next_s)).reshape(-1, self.output_size)\n\n if action == 1:\n tgt = self.states[\"close\"][i + 1]\n noww = self.states[\"close\"][i]\n rew = math.log(tgt / noww)\n reward[0][0] = reward[0][0] + rew\n elif action == 2:\n tgt = self.states[\"close\"][i + 1]\n noww = self.states[\"close\"][i]\n rew = math.log(tgt / noww)\n reward[0][1] = reward[0][1] - rew\n\n self.model_fifteen.fit(inp_state, reward, epochs=1, verbose=0)\n\n self.model_fifteen.save('y_srma.h5')\n\n if self.testt == 1:\n\n self.model_fifteen = load_model('yne.h5')\n\n issay = 0\n act_pos = 0\n cash = 1000\n amount = 0\n max_percent=1\n\n\n\n for i in range(self.ind_length - 1, self.csv_length -20):\n\n state_now = self.inputer(i, 1)\n\n inp_state = self.normalisse(state_now) # GEÇİCİ\n\n test1 = np.array(0.95 * self.model_fifteen.predict(inp_state)).reshape(-1, self.output_size)\n is_nan=math.isnan(test1[0][1]) #test3 yap\n if is_nan==False:\n res = np.where(test1 == np.amax(test1)) #test3 yap\n result = res[1][0]\n else:\n\n continue\n\n #if self.states[\"close\"][i+1]>self.states[\"close\"][i]:\n # max_percent = max_percent*(self.states[\"close\"][i+1]/self.states[\"close\"][i])\n\n\n if result == 0 and act_pos < 1:\n\n issay = issay + 1\n act_pos = 1\n c_p = self.states[\"close\"][i]\n amount = cash / c_p\n cash = cash - (amount * c_p)\n elif (act_pos == 1 and result == 1):\n issay = issay + 1\n act_pos = -1\n c_p = self.states[\"close\"][i]\n cash = amount * c_p\n amount = amount - (cash / c_p)\n\n\n print(\"Final Cash 1 : \" + str(cash))\n print(\"Final Cash 2 :\" + str(amount * self.states[\"close\"][i]))\n print(\"issay : \"+str(issay))\n print(\"Max Value : \"+str(max_percent*1000))\n #return (cash + amount * self.states[\"close\"][i])\n\n\n\n","sub_path":"offline_trainer.py","file_name":"offline_trainer.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"606772779","text":"#!usr/bin/python\nfrom pymongo import Connection\n\nglobal con\ncon = Connection(\"mongo.stuycs.org\")\n#not using lobbies anymore, setting them all to -1.\nglobal db\nglobal col\n\ndef startup():\n\tglobal db\n\tdb = con.admin\n\tglobal res\n\tres = db.authenticate(\"ml7\",\"ml7\")\n\tdb = con[\"macguffin\"]\n\tglobal col\n\tcol = db[\"matches\"]\n\ndef inprogress():#checks if a game has been set up\n\tglobal col\n\treturn len([x for x in col.find({\"type\":\"g\"})]) == 1\n\ndef setupgame(game, _map, lobby=-1):#makes game\n\tif inprogress():\n\t\treturn False\n\tglobal col\n\tgame = {\"type\" : \"g\", \"game\": str(game), \"map\": int(_map), \"lobby\": lobby}\n\tcol.insert(game)\n\ndef logout(pname=\"\"):\n\ts = [x[\"spot\"] for x in col.find({\"type\":\"p\",\"pname\":pname})][0]\n\twhile len([x for x in col.find({\"type\":\"p\",\"spot\":int(s+1)})]) != 0:\n\t\tcol.update({\"type\" : \"p\", \"spot\":int(s+1)}, {\"$set\": {\"spot\":int(s)}})\n\t\ts+= 1\n\tcol.remove({\"type\":\"p\",\"pname\":pname})\n\treturn True\n\ndef getgame(lobby=-1):#returns tuple of game, map, and lobby number(should always be -1).\n\tglobal col\n\tres = [(str(x[\"game\"]), int(x[\"map\"]), int(x[\"lobby\"])) for x in col.find({\"type\":\"g\", \"lobby\":lobby})]\n\tif len(res) == 0:\n\t\treturn False\n\treturn res[0]\n\ndef closegame(lobby=-1):#logs everyone out too, they'll have an option to log back in\n\tglobal col\n\tlob = col.find({\"lobby\": lobby})\n\tcol.drop()\n\ndef addplayer(pname):\n\tglobal col\n\tr = col.find({\"type\" : \"p\", \"pname\":str(pname)})\n\tfor p in r:\n\t\treturn False\n\tplayer = {\"type\" : \"p\", \"team\":int(-1), \"pname\": str(pname), \"pos\": [-1, -1], \"lobby\": -1, \"items\": int(0), \"spot\" : len([x for x in col.find({\"type\":\"p\"})])}\n\tcol.insert(player)\n\treturn True\n\ndef addmacguffin(x,y):\n\tglobal col\n\tmacg = {\"type\" : \"m\", \"pos\": [x, y], \"lobby\": -1}\n\tcol.insert(macg)\n\ndef remmacguffin(x,y):\n\tglobal col\n\tmacg = {\"type\" : \"m\", \"pos\": [x, y], \"lobby\": -1}\n\tcol.remove(macg)\n\ndef retmacguffin():\n\tglobal col\n\tif len([x for x in col.find({\"type\":\"m\"})]) > 0:\n\t\treturn [x[\"pos\"] for x in col.find({\"type\":\"m\"})]\n\treturn []\n\n\"\"\"b4 col.rem\n\tres = col.find({\"lobby\":lobby, \"type\" : \"p\"})\n\tfor p in res:\n\t\tif int(p[\"spot\"]) > int(player[\"spot\"]):\n\t\t\tp[\"spot\"] = p[\"spot\"] - 1\ndef removeplayer(pname, lobby=-1):#not used\n\tglobal col\n\tplayer = col.find({\"type\" : \"p\",\"pname\":pname})\n\tcol.remove(player)\n\n\n\"\"\"\n\ndef getplayer(pname):#returns tuple of players name, position, and spot\n\tglobal col\n\tres = [(str(x[\"pname\"]), x[\"pos\"], int(x[\"spot\"]), int(x[\"items\"]), int(x[\"team\"])) for x in col.find({\"type\" : \"p\",\"pname\":pname})]\n\tif len(res) == 1:\t\n\t\treturn res[0]\n\treturn False#if the player doesn't exist\n\ndef placeteam(pname,t=-1):\n\tglobal col\n\tcol.update({\"type\" : \"p\", \"pname\":pname}, {\"$set\": {\"team\":int(t)}})\n\ndef moveplayer(pname, x=-1, y=-1, item=-1):\n\tglobal col\n\tx2 = float(x)\n\ty2 = float(y)\n\titem2 = int(item)\n\tif item == -1:\n\t\tres = [z[\"items\"] for z in col.find({\"type\" : \"p\",\"pname\":pname})]\n\t\titem2 = int(res[0])\n\tif x == -1:\n\t\tres = [z[\"pos\"] for z in col.find({\"type\" : \"p\",\"pname\":pname})]\n\t\tx2 = float(res[0][0])\n\tif y == -1:\n\t\tres = [z[\"pos\"] for z in col.find({\"type\" : \"p\",\"pname\":pname})]\n\t\ty2 = float(res[0][1])\n\tpos = [x2,y2]\n\tcol.update({\"type\" : \"p\", \"pname\":pname}, {\"$set\": {\"pos\": pos, \"items\":item2}})\n\t\n\ndef get_players_in_lobby(lobby=-1):#returns list of tuples of names and positions of players in game \n\tres = col.find({\"lobby\":lobby, \"type\" : \"p\"})\n\treturn [[str(x[\"pname\"]), x[\"pos\"], int(x[\"items\"]), int(x[\"team\"])] for x in res if int(x[\"spot\"]) < 4]\n\n","sub_path":"macguffin/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215391261","text":"import logging\n\nspider_to_friendly_name = None\n\n\ndef load_friendly_spider_names():\n \"\"\"\n Returns a dictionary which maps the Spider's name to its \"friendly\" name.\n\n e.g., merlin_spider --> Merlin, br_rss_spider --> Bayerischer Rundfunk\n\n Based on https://stackoverflow.com/questions/46871133/get-all-spiders-class-name-in-scrapy\n\n Author: Ioannis Koumarelas, ioannis.koumarelas@hpi.de, Schul-Cloud, Content team.\n \"\"\"\n from scrapy.utils import project\n from scrapy import spiderloader\n\n settings = project.get_project_settings()\n spider_loader = spiderloader.SpiderLoader.from_settings(settings)\n\n spider_names = spider_loader.list()\n spider_classes = [spider_loader.load(name) for name in spider_names]\n\n spider_name_to_friendly_name = {}\n for spider in spider_classes:\n spider_name_to_friendly_name[spider.name] = spider.friendlyName\n\n return spider_name_to_friendly_name\n\n\ndef get_spider_friendly_name(spider_name):\n \"\"\"\n Given the spider's name, returns its friendly name.\n \"\"\"\n\n global spider_to_friendly_name\n if spider_to_friendly_name is None:\n spider_to_friendly_name = load_friendly_spider_names()\n\n if spider_name in spider_to_friendly_name:\n return spider_to_friendly_name[spider_name]\n else:\n if spider_name is not None:\n logging.info(\"Friendly name for spider \" + spider_name + \" has not been found.\")\n return spider_name\n\n\nif __name__ == '__main__':\n load_friendly_spider_names()","sub_path":"converter/spiders/utils/spider_name_converter.py","file_name":"spider_name_converter.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"369513138","text":"from wowAuction.celery import app\r\n#import pymongo\r\nimport datetime\r\nimport redis\r\nimport requests\r\nimport time\r\nfrom time import sleep\r\nfrom wowAuction.models import s_data\r\n\r\n#REGION=['us','eu','tw','kr']\r\nREGION='us'\r\nREALM='medivh'\r\nLOCALE='en_US'\r\nAPIKEY='v3rwfezdh3vxj7wpwh644vugkbuemyfz'\r\n\r\n'''\r\nclass wowAuction():\r\n def __init__(self):\r\n self.baseUrl=\"https://%s.api.battle.net/wow/auction/data/\"%REGION\r\n self.auctionUrl=self.baseUrl+\"%s?locale=%s&apikey=%s\"%(REALM,LOCALE,APIKEY)\r\n self.datetime=time.strftime(\"%Y%m%d%H\",time.localtime())\r\n self.con=pymongo.MongoClient('127.0.0.1',27017)\r\n #print self.auctionUrl\r\n\r\n def getDataUrl(self):\r\n html=requests.get(self.auctionUrl)\r\n return html.json()['files'][0]['url']\r\n\r\n def getData(self):\r\n coll=self.con['wowAuction'][REGION]\r\n data_url=self.getDataUrl()\r\n res=requests.get(data_url)\r\n data=res.json()\r\n data['time'] = self.datetime\r\n coll.insert(data)\r\n self.itemlist=coll.distinct(\"auctions.item\")\r\n\r\n def analyse(self):\r\n coll1=self.con['wowAuction'][REGION]\r\n coll2=self.con['wowAuction'][REGION+\"_stat\"]\r\n data1=coll1.find({\"time\":self.datetime})[0]['auctions']\r\n data2={\"time\":self.datetime}\r\n for i in self.itemlist:\r\n data2[str(i)]=[]\r\n for d in data1:\r\n if d['item']==i:\r\n data2[str(i)].append(d['buyout'])\r\n data2[str(i)]=sorted(data2[str(i)])\r\n coll2.insert(data2)\r\n'''\r\n\r\nclass wowAuction():\r\n def __init__(self):\r\n self.baseUrl=\"https://%s.api.battle.net/wow/auction/data/\"%REGION\r\n self.auctionUrl=self.baseUrl+\"%s?locale=%s&apikey=%s\"%(REALM,LOCALE,APIKEY)\r\n self.datetime=time.strftime(\"%Y%m%d%H\",time.localtime())\r\n #print self.auctionUrl\r\n\r\n def getDataUrl(self):\r\n html=requests.get(self.auctionUrl)\r\n return html.json()['files'][0]['url']\r\n\r\n def getData(self):\r\n #coll=raw_data.objects.all()\r\n data_url=self.getDataUrl()\r\n res=requests.get(data_url)\r\n self.data=res.json()\r\n #coll.insert(data)\r\n #raw_data.objects.create(time=self.datetime,realms=data['realms'],auctions=data['auctions'])\r\n self.itemlist = set([i['item'] for i in self.data['auctions']])\r\n\r\n def analyse(self):\r\n #coll1=self.con['wowAuction'][REGION]\r\n #coll2=self.con['wowAuction'][REGION+\"_stat\"]\r\n #data1=coll1.find({\"time\":self.datetime})[0]['auctions']\r\n data1=self.data['auctions']\r\n data2={}\r\n for i in self.itemlist:\r\n data2[str(i)]=[]\r\n for d in data1:\r\n if d['item']==i:\r\n data2[str(i)].append(d['buyout'])\r\n data2[str(i)]=sorted(data2[str(i)])\r\n #coll2.insert(data2)\r\n s_data.objects.create(time=self.datetime,data=data2)\r\n\r\n@app.task\r\ndef wow_auction_task():\r\n wa=wowAuction()\r\n wa.getData()\r\n sleep(10)\r\n wa.analyse()\r\n sleep(10)\r\n\r\n@app.task\r\ndef getGraphData(item,region,NDATAS):\r\n #con = pymongo.MongoClient('127.0.0.1', 27017)\r\n #coll = con['wowAuction']['%s_stat' % region]\r\n\r\n timenow = datetime.datetime.now()\r\n data = {\"x\": [], \"y\": []}\r\n #取多少个小时\r\n for i in range(NDATAS):\r\n time = timenow + datetime.timedelta(hours=-i)\r\n time = time.strftime(\"%Y%m%d%H\")\r\n data['x'].append(time)\r\n data['x'] = sorted(data['x'])\r\n #print(item,region,data['x'][0])\r\n for j in range(len(data['x'])):\r\n t = data['x'][j]\r\n try:\r\n #p = coll.find({\"time\": t.strip()})[0]\r\n p=s_data.objects.filter(time=t.strip()).values_list('data')[0][0]\r\n price = p[str(item)] #取该时间下的价格列表\r\n except Exception as e:\r\n price = []\r\n try:\r\n while price.index(0): #去掉0值\r\n price.pop(price.index(0))\r\n except:\r\n pass\r\n if len(price) != 0:\r\n minprice = (min(price) / 10000)\r\n data['y'].append(minprice)\r\n else:\r\n data['y'].append(0)\r\n #print(data['y'])\r\n data_y=data['y']\r\n try:\r\n while data_y.index(0): # 去掉0值\r\n data_y.pop(data_y.index(0))\r\n except:\r\n pass\r\n y_aver = sum(data_y) / (len(data_y) + 1)\r\n #print(data_y,y_aver)\r\n '''\r\n for n in range(len(data_y)): #去掉偏差过大的值,赋给它前一个数的值\r\n if data_y[n] > 2 * y_aver:\r\n N=data['y'].index(data_y[n])\r\n if N!=0:\r\n data['y'][N]=data['y'][N-1]\r\n else:\r\n data['y'][0] = 0\r\n '''\r\n\r\n for i in range(len(data['y'])):\r\n data['y'][i]=data['y'][i] if data['y'][i]!=0 else '' #将0值转为null\r\n\r\n r=redis.Redis()\r\n while r.llen(item)!=0:\r\n r.lpop(item)\r\n\r\n r.rpush(item,timenow.strftime(\"%Y%m%d%H\"))\r\n for y in data['y']:\r\n r.rpush(item,y)\r\n\r\n sleep(5)\r\n #print (data['y'])\r\n return data['y']\r\n","sub_path":"wowAuction/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"288271350","text":"import sys, getopt\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom halton import halton_sequence\nfrom scipy.spatial import cKDTree\nfrom array import array\n\nfrom random import random\n\ndef halton(n):\n inner_nodes = halton_sequence(1,n,2).T\n inner_nodes = [(np.sqrt(x)*np.cos(2*np.pi*y), \n np.sqrt(x)*np.sin(2*np.pi*y)) \n for (x,y) in inner_nodes]\n return inner_nodes\n\ndef vogel(n):\n theta_hat = np.pi*(3-np.sqrt(5))\n inner_nodes = [ (np.sqrt(i/n)*np.cos(i*theta_hat), \n np.sqrt(i/n)*np.sin(i*theta_hat)) for i in range(1,n+1)]\n return inner_nodes\n\n\ndef boundary_param(t):\n return (np.cos(2*np.pi*t), np.sin(2*np.pi*t))\n\n\ndef gen_points(n, n_boundary, dist='vogel', boundary_dist='vogel', sorting='x'):\n if dist == 'vogel':\n inner_nodes = vogel(n)\n elif dist == 'halton':\n inner_nodes = halton(n)\n elif dist == 'random':\n inner_nodes = [(random(), random()) for i in range(n)]\n inner_nodes = [(np.sqrt(x)*np.cos(2*np.pi*y), \n np.sqrt(x)*np.sin(2*np.pi*y)) \n for (x,y) in inner_nodes]\n else:\n raise ValueError('dist=' + dist + ' not recognized')\n\n if boundary_dist=='equal':\n boundary_nodes = [\n (np.cos(t), np.sin(t))\n for t in \n np.linspace(0, 2*np.pi, n_boundary, endpoint=False)]\n elif boundary_dist=='vogel':\n theta_hat = np.pi*(3-np.sqrt(5))\n boundary_nodes = [\n (np.cos(i*theta_hat), np.sin(i*theta_hat))\n for i in range(n+1, n+1 + n_boundary)]\n else:\n raise ValueError('boundary_dist=' + boundary_dist + ' not recognized')\n\n if sorting==None:\n pass\n elif sorting=='x':\n #sort by x value\n if type(inner_nodes)==np.ndarray:\n inner_nodes.sort(axis=0)\n else:\n inner_nodes.sort(key=lambda x: x[0])\n\n if type(boundary_nodes)==np.ndarray:\n boundary_nodes.sort(axis=0)\n else:\n boundary_nodes.sort(key=lambda x: x[0])\n else:\n raise ValueError('sorting=' + sorting + ' not recognized')\n\n return inner_nodes, boundary_nodes\n\ndef write_points_to_file(inner, boundary, stencil_size, filename=None):\n # generate nearest neighbors\n nodes = inner + boundary\n tree = cKDTree(np.array(nodes))\n nn = [tree.query(node, stencil_size)[1] for node in nodes]\n\n if filename==None:\n filename = ('n'+ str(len(inner)) + '_nb' + \n str(len(boundary)) + '_l' + \n str(stencil_size) +'.dat')\n \n\n f = open( 'point_sets/' + filename, 'wb')\n\n # write n, nb, l\n n = len(inner)\n f.write(n.to_bytes(4,'little'))\n nb = len(boundary)\n f.write(nb.to_bytes(4,'little'))\n f.write(stencil_size.to_bytes(4,'little'))\n \n # write two dummy ints for compatability with read mat\n fakeint = int(0)\n f.write(fakeint.to_bytes(4,'little'))\n f.write(fakeint.to_bytes(4,'little'))\n\n # write xs\n my_array = array('d', [node[0] for node in nodes])\n my_array.tofile(f)\n\n # write ys\n my_array = array('d', [node[1] for node in nodes])\n my_array.tofile(f)\n\n my_array = array('i', [v for row in nn for v in row])\n my_array.tofile(f)\n \n f.close()\n\ndef gen_points_file(\n n, n_boundary, stencil_size, dist='vogel', \n boundary_dist='equal', sorting='x', \n filename=None):\n \n inner, boundary = gen_points(\n n, n_boundary, dist=dist, \n boundary_dist=boundary_dist, sorting=sorting)\n write_points_to_file(inner, boundary, stencil_size, filename)\n\ndef read_points(filename):\n f = open(filename, 'rb')\n n = int.from_bytes(f.read(4), 'little')\n nb = int.from_bytes(f.read(4), 'little')\n l_max = int.from_bytes(f.read(4), 'little')\n l = int.from_bytes(f.read(4), 'little')\n deg = int.from_bytes(f.read(4), 'little')\n \n xs = np.fromfile(f, dtype='d', count=n+nb)\n ys = np.fromfile(f, dtype='d', count=n+nb)\n nn = np.fromfile(f, dtype='i', count=n*l).reshape((n, l_max))\n \n #return xs, ys, nn\n nodes = [(x,y) for x,y in zip(xs,ys)]\n inner = nodes[:n]\n boundary = nodes[n:]\n return inner, boundary\n\ndef read_matrix(filename):\n f = open(filename, 'rb')\n n = int.from_bytes(f.read(4), 'little')\n nb = int.from_bytes(f.read(4), 'little')\n l_max = int.from_bytes(f.read(4), 'little')\n l = int.from_bytes(f.read(4), 'little')\n deg = int.from_bytes(f.read(4), 'little')\n pdim = (deg+1)*(deg+2)//2\n\n #print(n, nb, l_max, l, deg)\n \n xs = np.fromfile(f, dtype='d', count=n+nb)\n ys = np.fromfile(f, dtype='d', count=n+nb)\n nn = np.fromfile(f, dtype='i', count=n*l_max).reshape((n, l_max))\n weights = np.fromfile(f, dtype='d', count=n*(l+pdim)).reshape((n,l+pdim))\n\n row_index = [r for r in range(n) for c in range(l)]\n col_index = nn[:, :l].ravel()\n C = sp.csc_matrix((weights[:,:l].ravel(), (row_index, col_index)),shape=(n,n+nb))\n #print(len(row_index), len(col_index), len(weights))\n \n #return xs, ys, C\n nodes = [(x,y) for x,y in zip(xs,ys)]\n inner = nodes[:n]\n boundary = nodes[n:]\n return inner, boundary, C, l, pdim\n\nif __name__ == '__main__':\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"n:b:l:\")\n except getopt.GetoptError:\n print('GetOptError')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-n':\n n = int(arg)\n elif opt == \"-b\":\n nb = int(arg)\n elif opt == \"-l\":\n l = int(arg)\n filename = 'point_sets/n' + str(n) + '_' + 'nb' + str(nb) + '_' + 'l' + str(l) + '.dat'\n gen_points_file(n, nb, l, filename=filename)\n \n \n\n","sub_path":"old-rbf/articles/node_selection/gen_points.py","file_name":"gen_points.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"110367061","text":"#!/usr/bin/env python\n\nimport sys, os\nsys.path.append(os.getcwd() + \"/../models\")\nsys.path.append(os.getcwd() + \"/../configs/static\")\n\nimport web\nimport product\nimport GeoipTable, localies, GlobalFunctions, TranslationsTable\n\n\nLANG = TranslationsTable.getLanguage()\n\n\nurls = (\n \"/product\", product.app_product,\n \"/(.*)\", \"index\"\n)\n\n\n\n\n\napp = web.application(urls, locals())\nsession = web.session.Session(app, web.session.HTStore('ses'),initializer = {'test': 'wooSESSIONS VALUEFOR TESTt', 'foo':''})\n\ndef session_hook():\n web.ctx.session = session\n web.template.Template.globals['session'] = session\n\napp.add_processor(web.loadhook(session_hook))\n\n\n\n\n\n\nclass index:\n def GET(self, path):\n global LANG\n return \"hello \" + path + \" \"+ str(localies.country_LANG[GeoipTable.getCountry()]) + \" \" + str(GlobalFunctions.GetURLdata()) + \" \" + TranslationsTable.getText(\"Hello\", LANG)\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"APP/public/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"253117448","text":"\nclass Vector2D:\n def __init__(self, x, y):\n self.X = x\n self.Y = y\n\nclass Tile:\n def __init__(self, x, y):\n self.Position = Vector2D(x, y)\n self.Up = None\n self.Right = None\n self.Down = None\n self.Left = None\n\n self.Area = None\n\ndef setup_tiles():\n # NOT A NODE-LIST. tiles themselves contain refs to the other tiles (Up, Right, Down, Left)\n starting_tile = None\n above_node = None\n prev_node = None\n for y in range(1, 37): \n for x in range(1, 37):\n # create new tile and assign x and y to it\n node = Tile(x, y)\n\n # assign .Area and .GeoType to the new tile\n # Swamp\n if (1 <= x <= 14 and 1 <= y <= 10) or (1 <= x <= 12 and 11 <= y <= 12) or (1 <= x <= 10 and 13 <= y <= 14): node.Area = 'S'\n elif (23 <= x <= 36 and 1 <= y <= 10) or (25 <= x <= 36 and 11 <= y <= 12) or (27 <= x <= 36 and 13 <= y <= 14): node.Area = 'I'\n elif (15 <= x <= 22 and 15 <= y <= 22): node.Area = 'G'\n elif (1 <= x <= 14 and 27 <= y <= 36) or (1 <= x <= 12 and 25 <= y <= 26) or (1 <= x <= 10 and 23 <= y <= 24): node.Area = 'D'\n elif (23 <= x <= 36 and 27 <= y <= 36) or (25 <= x <= 36 and 25 <= y <= 26) or (27 <= x <= 36 and 23 <= y <= 24): node.Area = 'F'\n else: node.Area = 'W'\n\n # prepare tile\n if y == 1 and x == 1:\n starting_tile = node\n if x == 1:\n prev_node = node\n else:\n prev_node.Right = node\n node.Left = prev_node\n prev_node = node\n if y > 1:\n node.Up = above_node\n above_node.Down = node\n above_node = above_node.Right\n \n while prev_node.Left != None:\n prev_node = prev_node.Left\n above_node = prev_node\n return starting_tile\n\n","sub_path":"Code/Donald/Donald Project2 Code V2/Donald Project Code V2/class_Tile.py","file_name":"class_Tile.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"486237836","text":"from datetime import datetime\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils import timezone\n\nfrom twitter.forms import LoginForm, AvatarUploadForm\nfrom twitter.models import Tweet, Profile\n\n\ndef no_auth_please(v):\n def wrapper(request, *a, **k):\n user = request.user\n if user.is_authenticated():\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return v(request, *a, **k)\n return wrapper\n\n@login_required(login_url=reverse_lazy(\"sign_in\"))\ndef sign_out(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"sign_in\"))\n \n\n@login_required(login_url=reverse_lazy(\"sign_in\"))\ndef q(request):\n return HttpResponse(\"CLASSIFIED\")\n\n@login_required(login_url=reverse_lazy(\"sign_in\"))\ndef index(request):\n return render(\n request, \n \"twitter/index.html\",\n {\n \"user\": request.user.username,\n \"tweets\" : Tweet.objects.filter(user=request.user).order_by(\"-p_date\")\n }\n )\n\n\ndef process(request):\n tweet = request.POST[\"tweet\"]\n t = Tweet(\n text=tweet,\n p_date=timezone.now(),\n user=request.user\n )\n t.save()\n return HttpResponseRedirect(reverse('index'))\n\n@no_auth_please\ndef sign_in(request):\n if request.POST:\n f = LoginForm(request.POST)\n if f.is_valid():\n user = authenticate(\n username=f.cleaned_data[\"username\"],\n password=f.cleaned_data[\"password\"]\n )\n if user:\n login(request, user)\n if request.GET.has_key(\"next\"):\n return HttpResponseRedirect(request.GET[\"next\"])\n else:\n return HttpResponseRedirect(reverse('index'))\n else:\n return HttpResponseRedirect(reverse('sign_in'))\n else:\n f = LoginForm()\n context = {\"f\": f}\n if request.GET.has_key(\"next\"):\n context[\"next\"] = request.GET[\"next\"]\n return render(request, \"twitter/sign_in.html\", context)\n\n\ndef edit_avatar(request):\n p = Profile.objects.filter(user=request.user)\n if request.method == 'POST':\n if p.exists():\n form = AvatarUploadForm(request.POST, request.FILES, instance=p[0])\n else:\n form = AvatarUploadForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n\n if p.exists():\n form = AvatarUploadForm(instance=p[0])\n else:\n form = AvatarUploadForm()\n return render(\n request,\n \"twitter/edit_avatar.html\",\n {\n \"form\" : form,\n 'image' : p[0].avatar\n }\n )\n","sub_path":"2014-11-14 media, static/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"636593964","text":"#!/usr/bin/env python\n\nfrom matplotlib.pyplot import figure, show\nimport futils\n\nalt = futils.utils.alt_grid(250, 60, 0.5, 4)\n\nax = figure().gca()\nax.plot(alt, marker=\".\", linestyle=\"none\")\nax.set_xlabel(\"index\")\nax.set_ylabel(\"altitude\")\nax.legend()\nshow()\n","sub_path":"archive/PlotFuncs.py","file_name":"PlotFuncs.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"317217701","text":"#!/usr/bin/python3\n\nimport threading\n\narg = 0\n\n# Define a function for the thread\ndef add():\n for i in range(1000000):\n global arg\n arg += 1\n\ndef sub():\n for i in range(1000000):\n global arg\n arg -= 1\n\n# Create two threads as follows\n\ntry:\n t1 = threading.Thread(target=add)\n t2 = threading.Thread(target=sub)\n \n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\nexcept:\n print (\"Error: unable to start thread\")\n\n\nprint(arg)\n\n","sub_path":"Exercises/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"191257705","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response, redirect\nfrom django.template import RequestContext\nimport django.contrib.auth.forms\nfrom django.contrib.auth.forms import UserCreationForm\n\n\ndef home(request):\n return render_to_response('home.html', context_instance=RequestContext(request))\n\ndef help(request):\n return render_to_response('help.html', context_instance=RequestContext(request))\n \ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n return render(request, 'register.html', {\n 'form': form,\n })\n else:\n form = UserCreationForm()\n return render(request, 'register.html', {\n 'form': form,\n })\n \n","sub_path":"ui/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"543806070","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\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#\nimport webapp2\nimport cgi\nimport jinja2\nimport os\n\nfrom google.appengine.ext import db\n\n# set up jinja\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\\\n autoescape=True)\n\n# Create a database (table) called Blog ...\nclass Blog(db.Model):\n title=db.StringProperty(required=True)\n blog=db.TextProperty(required=True)\n created=db.DateTimeProperty(auto_now_add=True)\n\nclass BaseHandler(webapp2.RequestHandler):\n \"\"\" Base RequestHandler class for the app.\n The other handlers inherit from this one.\n \"\"\"\n def renderError(self,error_code,msg):\n \"\"\" Sends HTTP error code and error detail supplied by the app \"\"\"\n self.error(error_code)\n self.response.write(msg)\n\nclass RootHandler(BaseHandler):\n#class MainHandler(Handler):\n \"\"\" Handles requests coming in to '/' \"\"\"\n\n def get(self):\n title=\"\"\n blog=\"\"\n error=\"\"\n # Create an instance for retrieving from the database ...\n blogs=db.GqlQuery(\"SELECT * FROM Blog ORDER BY created DESC\")\n t = jinja_env.get_template(\"front-page.html\")\n\n content=t.render(blogs=blogs)\n\n self.response.write(content)\n\n def post(self):\n title=self.request.get(\"title\")\n blog=self.request.get(\"blog\")\n\n if title and blog:\n a=Blog(title=title,blog=blog) # Create an instance of Blog ...\n a.put()\n\n self.redirect(\"/\")\n else:\n incomplete_err = \"we need both a title and some blog contents!\"\n\n t = jinja_env.get_template(\"base.html\")\n\n content = t.render(title=title,blog=blog,error=incomplete_err)\n self.response.write(content)\n\nclass ListBlogs(BaseHandler):\n \"\"\" Handles requests coming in to /list \"\"\"\n\n def get(self):\n blogs=db.GqlQuery(\"SELECT * FROM Blog ORDER BY created DESC LIMIT 5\")\n t = jinja_env.get_template(\"list.html\")\n\n content=t.render(blogs=blogs)\n\n self.response.write(content)\n\n def post(self):\n pass\n\nclass AddBlogs(BaseHandler):\n def get(self):\n t = jinja_env.get_template(\"post-new.html\")\n\n content=t.render()\n\n self.response.write(content)\n\n def post(self):\n title=\"\"\n blog=\"\"\n title=self.request.get(\"title\")\n blog=self.request.get(\"blog\")\n\n if title and blog:\n good_msg=\"Your blog has been added to the database.\"\n a=Blog(title=title,blog=blog) # Create an instance of Blog ...\n a.put()\n # Add the blog.key().id() here ...\n k=Blog.key(a).id()\n if not k:\n self.response.write(\"Object k was not established\")\n else:\n #self.response.write(\"Object k was established\")\n self.redirect(\"/blog/\"+str(int(k)))\n else:\n incomplete_err = \"we need both a title and some blog contents!\"\n t = jinja_env.get_template(\"post-new.html\")\n content = t.render(title=title,blog=blog,error=incomplete_err)\n self.response.write(content)\n\nclass ViewBlog(BaseHandler):\n def get(self, id):\n #instance=Blog.get_by_id(int('5770237022568448'),Parent=None)\n rec=Blog.get_by_id(int(id))\n if rec:\n t = jinja_env.get_template('blog-detail.html')\n content=t.render(blog=rec)\n self.response.write(content)\n else:\n self.renderError(404,\"Record Not Found !\")\n\napp = webapp2.WSGIApplication([\n ('/', RootHandler),\n ('/list', ListBlogs),\n ('/add', AddBlogs),\n webapp2.Route('/blog/', ViewBlog)\n ], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"629961159","text":"class MaxHeap:\n def __init__(self, a):\n self.arr = a\n self.size = len(a) - 1\n\n def make_heap(self):\n # heap size is number of elements in heap (1 to length)\n self.size = len(self.arr) - 1\n # from middle node to first node check if it is greater than each child node\n for i in range(int(self.size / 2), 0, -1):\n # take ith element into temp variable & also take child index of ith node\n temp = self.arr[i]\n ci = i * 2\n # find appropriate location for temp variable.\n while ci <= self.size:\n # check if right child is available & is greater than left child\n if (ci + 1) <= self.size and self.arr[ci + 1] > self.arr[ci]:\n ci = ci + 1\n # if temp is greater than max child (ci)\n if temp > self.arr[ci]:\n break\n # if child is greater than temp, promote child to its parent location\n self.arr[int(ci / 2)] = self.arr[ci]\n # check if its child is valid location for temp?\n ci = ci * 2\n # insert temp as parent of ci\n self.arr[int(ci / 2)] = temp\n\n def delete_max(self):\n # max node is always self.arr[1]\n val = self.arr[1]\n # take last node into temp variable\n temp = self.arr[self.size]\n # decrement self.size of heap by 1\n self.size = self.size - 1\n # find approrpiate position for temp.\n ci = 2 # child of self.arr[1]\n while ci <= self.size:\n # check if right child is available & is greater than left child\n if (ci + 1) <= self.size and self.arr[ci + 1] > self.arr[ci]:\n ci = ci + 1\n # if temp is greater than max child (ci)\n if temp > self.arr[ci]:\n break\n # if child is greater than temp, promote child to its parent location\n self.arr[int(ci / 2)] = self.arr[ci]\n # check if its child is valid location for temp?\n ci = ci * 2\n # insert temp as parent of ci\n self.arr[int(ci / 2)] = temp\n # return deleted node\n return val\n\n def print(self):\n print(\"Heap: \", end='')\n for i in range(1, self.size + 1):\n print(self.arr[i], end=\", \")\n print()\n\n\n# O(k log n)\ndef kth_highest_element(arr, k):\n h = MaxHeap(arr)\n h.make_heap()\n val = 0\n for i in range(1, k + 1):\n val = h.delete_max()\n return val\n\n\n# O(n log n)\ndef heap_sort(arr):\n h = MaxHeap(arr)\n h.make_heap()\n for i in range(1, len(arr)):\n val = h.delete_max()\n arr[len(arr) - i] = val\n print()\n\n\ndef main():\n arr = [0, 20, 12, 35, 15, 10, 80, 30, 17, 2, 1]\n print(arr)\n heap_sort(arr)\n print(arr)\n\n\n# h = MaxHeap(arr)\n# h.print()\n# h.make_heap()\n# h.print()\n# val = h.delete_max()\n# print(\"deleted element: \" + str(val))\n# h.print()\n# val = h.delete_max()\n# print(\"deleted element: \" + str(val))\n# h.print()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"101431959","text":"import re\nimport logging\nfrom subprocess import check_output, CalledProcessError\n\n\n\ndef docker_image_clean(image_name):\n # Remove all excess whitespaces on edges, split on spaces and grab the first word.\n # Wraps in double quotes so bash cannot interpret as an exec\n image_name = '\"{}\"'.format(image_name.strip().split(' ')[0])\n # Regex acts as a whitelist here. Only alphanumerics and the following symbols are allowed: / . : -.\n # If any not allowed are found, replaced with second argument to sub.\n image_name = re.sub('[^0-9a-zA-Z/.:-]+', '', image_name)\n return image_name\n\n\ndef do_docker_pull(image_name, task_id, secret):\n logging.info(\"Running docker pull for image: {}\".format(image_name))\n cmd = ['docker', 'pull', image_name]\n docker_pull = check_output(cmd)\n logging.info(\"Docker pull complete for image: {0} with output of {1}\".format(\n image_name, docker_pull))\n\n","sub_path":"codalabworker/docker_util.py","file_name":"docker_util.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"145590905","text":"# $Header: //depot/cs/s/nav_tile_pages.wsgi#4 $\nfrom db.Exceptions import SupportSessionExpired\nfrom db.Support import SupportSession\nfrom werkzeug.utils import redirect\nfrom werkzeug.wrappers import Response\nfrom p.DTemplate import DTemplate\nfrom p.DRequest import DRequest\nfrom db.NavTilePage import get_landing_pages\nimport db.Db as Db\n\ndef application(environ, start_response):\n \"\"\"Edit and manage nav tile pages\"\"\"\n\n request = DRequest(environ)\n\n try :\n Db.start_transaction()\n request.add_vars({ 'landing_pages': get_landing_pages() })\n support = SupportSession(key=request.support_key())\n t = DTemplate(request, 'nav_tile_pages.html')\n resp = Response(t.render(request.get_vars()))\n Db.finish_transaction()\n except SupportSessionExpired:\n Db.cancel_transaction()\n resp = redirect('/s/login', 307)\n return resp(environ, start_response)\n except Exception as e:\n Db.cancel_transaction()\n import traceback\n traceback.print_exc()\n t = DTemplate(request, 'error.html')\n resp = Response(t.render({'message': 'Internal Error'}))\n\n request.cookie_freshen(resp)\n resp.headers['content-type'] = 'text/html; charset=utf-8'\n resp.headers['content-length'] = len(resp.data)\n\n return resp(environ, start_response)\n","sub_path":"s/nav_tile_pages.wsgi","file_name":"nav_tile_pages.wsgi","file_ext":"wsgi","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"647765134","text":"'''\nSubmit from master02.cluster as spark user:\n\nspark-submit \\\n--master yarn --deploy-mode client \\\n--num-executors 2 --executor-cores 1 \\\n--executor-memory 5g --driver-memory 4g \\\n--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.3.0 \\\n--conf spark.sql.hive.thriftServer.singleSession=true \\\n/vagrant/spark-streaming-console.py\n\n* The application reads data from Kafka topic, parses Kafka messages, processes it, and outputs the results in console\n* `TipsInConsole` query writes the streaming results to stdout of the Spark Driver\n\n'''\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import expr\nfrom pyspark.sql.functions import avg\nfrom pyspark.sql.functions import window\n\ndef isPointInPath(x, y, poly):\n \"\"\"check if point x, y is in poly\n poly -- a list of tuples [(x, y), (x, y), ...]\"\"\"\n num = len(poly)\n i = 0\n j = num - 1\n c = False\n for i in range(num):\n if ((poly[i][1] > y) != (poly[j][1] > y)) and \\\n (x < poly[i][0] + (poly[j][0] - poly[i][0]) * (y - poly[i][1]) /\n (poly[j][1] - poly[i][1])):\n c = not c\n j = i\n return c\n\ndef parse_data_from_kafka_message(sdf, schema):\n from pyspark.sql.functions import split\n assert sdf.isStreaming == True, \"DataFrame doesn't receive treaming data\"\n col = split(sdf['value'], ',') #split attributes to nested array in one Column\n #now expand col to multiple top-level columns\n for idx, field in enumerate(schema): \n sdf = sdf.withColumn(field.name, col.getItem(idx).cast(field.dataType))\n return sdf.select([field.name for field in schema])\n \nspark = SparkSession.builder \\\n .appName(\"Spark Structured Streaming from Kafka\") \\\n .getOrCreate()\n\nsdfRides = spark \\\n .readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"master02.cluster:6667\") \\\n .option(\"subscribe\", \"taxirides\") \\\n .option(\"startingOffsets\", \"latest\") \\\n .load() \\\n .selectExpr(\"CAST(value AS STRING)\") \n\nsdfFares = spark \\\n .readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"master02.cluster:6667\") \\\n .option(\"subscribe\", \"taxifares\") \\\n .option(\"startingOffsets\", \"latest\") \\\n .load() \\\n .selectExpr(\"CAST(value AS STRING)\")\n \ntaxiFaresSchema = StructType([ \\\n StructField(\"rideId\", LongType()), StructField(\"taxiId\", LongType()), \\\n StructField(\"driverId\", LongType()), StructField(\"startTime\", TimestampType()), \\\n StructField(\"paymentType\", StringType()), StructField(\"tip\", FloatType()), \\\n StructField(\"tolls\", FloatType()), StructField(\"totalFare\", FloatType())])\n \ntaxiRidesSchema = StructType([ \\\n StructField(\"rideId\", LongType()), StructField(\"isStart\", StringType()), \\\n StructField(\"endTime\", TimestampType()), StructField(\"startTime\", TimestampType()), \\\n StructField(\"startLon\", FloatType()), StructField(\"startLat\", FloatType()), \\\n StructField(\"endLon\", FloatType()), StructField(\"endLat\", FloatType()), \\\n StructField(\"passengerCnt\", ShortType()), StructField(\"taxiId\", LongType()), \\\n StructField(\"driverId\", LongType())])\n\nsdfRides = parse_data_from_kafka_message(sdfRides, taxiRidesSchema)\nsdfFares = parse_data_from_kafka_message(sdfFares, taxiFaresSchema)\n\n# Data cleaning\nLON_EAST, LON_WEST, LAT_NORTH, LAT_SOUTH = -73.7, -74.05, 41.0, 40.5\nsdfRides = sdfRides.filter( \\\n sdfRides[\"startLon\"].between(LON_WEST, LON_EAST) & \\\n sdfRides[\"startLat\"].between(LAT_SOUTH, LAT_NORTH) & \\\n sdfRides[\"endLon\"].between(LON_WEST, LON_EAST) & \\\n sdfRides[\"endLat\"].between(LAT_SOUTH, LAT_NORTH))\nsdfRides = sdfRides.filter(sdfRides[\"isStart\"] == \"END\") #Keep only finished!\n\n# Apply watermarks on event-time columns\nsdfFaresWithWatermark = sdfFares \\\n .selectExpr(\"rideId AS rideId_fares\", \"startTime\", \"totalFare\", \"tip\") \\\n .withWatermark(\"startTime\", \"30 minutes\") # maximal delay\n\nsdfRidesWithWatermark = sdfRides \\\n .selectExpr(\"rideId\", \"endTime\", \"driverId\", \"taxiId\", \\\n \"startLon\", \"startLat\", \"endLon\", \"endLat\") \\\n .withWatermark(\"endTime\", \"30 minutes\") # maximal delay\n\n# Join with event-time constraints and aggregate\nsdf = sdfFaresWithWatermark \\\n .join(sdfRidesWithWatermark, \\\n expr(\"\"\" \n rideId_fares = rideId AND \n endTime > startTime AND\n endTime <= startTime + interval 2 hours\n \"\"\"))\n\n# Feature engineering neighborhoods\nnbhds_df = spark.read.json(\"file:///vagrant/NYC_neighborhoods/nbhd.jsonl\") # nbhd.jsonl file has to be available!\nlookupdict = nbhds_df.select(\"name\",\"coord\").rdd.collectAsMap()\nbroadcastVar = spark.sparkContext.broadcast(lookupdict) #use broadcastVar.value from now on\nmanhattan_bbox = [[-74.0489866963,40.681530375],[-73.8265135518,40.681530375],[-73.8265135518,40.9548628598],[-74.0489866963,40.9548628598],[-74.0489866963,40.681530375]]\nfrom pyspark.sql.functions import udf\ndef find_nbhd(lon, lat):\n '''takes geo point as lon, lat floats and returns name of neighborhood it belongs to\n needs broadcastVar available'''\n if not isPointInPath(lon, lat, manhattan_bbox) : return \"Other\"\n for name, coord in broadcastVar.value.items():\n if isPointInPath(lon, lat, coord):\n return str(name) #cast unicode->str\n return \"Other\" #geo-point not in neighborhoods\nfind_nbhd_udf = udf(find_nbhd, StringType())\nsdf = sdf.withColumn(\"stopNbhd\", find_nbhd_udf(\"endLon\", \"endLat\"))\nsdf = sdf.withColumn(\"startNbhd\", find_nbhd_udf(\"startLon\", \"startLat\"))\n\n# Aggregate\ntips = sdf \\\n .groupBy(\n window(\"endTime\", \"30 minutes\", \"10 minutes\"),\n \"stopNbhd\") \\\n .agg(avg(\"tip\").alias(\"avgtip\"))\n\n# Write streaming results in console\ntips.writeStream \\\n .queryName(\"TipsInConsole\") \\\n .outputMode(\"append\") \\\n .format(\"console\") \\\n .option(\"truncate\", False) \\\n .start() \\\n .awaitTermination()\n","sub_path":"spark-streaming-console.py","file_name":"spark-streaming-console.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"67831776","text":"#\nfrom tqdm import tqdm\nimport logging\nimport sys\n#\nfrom torch import optim\nimport torch.nn as nn \nimport torch\n# \nfrom networks import unet_vgg\nimport configs, utils_ai\nimport datasets\n\n\nif __name__ == '__main__':\n args = configs.get_args()\n # device = torch.device('cuda' if torch.cuda.is_available() )\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(f'Using deveice {device}')\n ###\n net = unet_vgg.UNet_VGG11()\n device_ids = list(map(int, args.device_ids.split(',')))\n model = nn.DataParallel(model, device_ids=device_ids).cuda()\n loss = Loss()\n\n if args.load:\n net.load_state_dict(\n torch.load(args.load, map_location=device)\n )\n logging.info(f'Model loaded from {args.load}')\n\n net.to(device=device)\n # faster convolutions, but more memory\n # cudnn.benchmark = True\n\n try:\n utils_ai.train(\n init_optimizer=lambda lr: Adam(model.parameters(), lr=lr),\n args=args,\n model=net,\n criterion=loss,\n train_loader=train_loader,\n valid_loader=valid_loader,\n validation=validation,\n fold=args.fold\n ) \n except KeyboardInterrupt:\n torch.save(net.state_dict(), 'INTERRUPTED.pth')\n logging.info('Saved interrupt')\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)","sub_path":"Image_Segmentation/src/TernausNet/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131778545","text":"import cv2\nimport sys\n\n\nclass Im2coe(object):\n def __init__(self, filename, size):\n\n self.filename = filename\n self.size = size\n\n self.colormap = [((0, 0, 0), 0x00), # Schwarz (R, G, B)\n ((144, 212, 42), 0x01), # Hell Gruen\n ((49, 58, 66), 0x02), # Dunkel Gruen\n ((255, 255, 255), 0x03)] # Weiss\n\n self.magic_value = 25\n\n self.run()\n\n def run(self):\n im = cv2.imread(self.filename)\n\n hg, wd, _ = im.shape\n scale_x = self.size[0] / float(wd)\n scale_y = self.size[1] / float(hg)\n\n im = cv2.resize(im, (0, 0), fx=scale_x, fy=scale_y)\n im_old = im\n\n im_new = [0 for _ in range(0, self.size[0] * self.size[1])]\n\n for y in range(0, self.size[1]):\n for x in range(0, self.size[0]):\n for c in range(0, len(self.colormap)):\n r, g, b = self.colormap[c][0]\n name = self.colormap[c][1]\n if im[y][x][0] in range(b - self.magic_value, b + self.magic_value):\n if im[y][x][1] in range(g - self.magic_value, g + self.magic_value):\n if im[y][x][2] in range(r - self.magic_value, r + self.magic_value):\n im_new[y * self.size[0] + x] = name\n\n\n count = 0\n for e in im_new:\n count += 1\n sys.stdout.write(\"%02x,\" % e)\n if count == self.size[0]:\n count = 0\n sys.stdout.write(\"\\n\")\n\n\nif __name__ == \"__main__\":\n Im2coe(\"hg.png\", (320, 240))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"64732522","text":"#http://symfoware.blog68.fc2.com/blog-entry-885.html\nimport logging\nimport logging.config\n# 設定ファイル読み込み\nlogging.config.fileConfig('logging_TimedRotatingFileHandler.conf')\n# rootロガーを取得\nlog = logging.getLogger('sub2')\nlog.debug('debugメッセージ')\nlog.info('infoメッセージ')\nlog.warn('warnメッセージ')\nlog.error('errorメッセージ')\nlog.critical('criticalメッセージ')\n","sub_path":"26/00/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"501113699","text":"import sqlite3 as lite\n\n#class bernieDAO():\n# def __init__(self):\n# con = lite.connect(\"bernie.db\")\n# self.cursor = con.cursor()\n\n\ndef addPerson(firstName, lastName, county, phone, email, committed, volunteer):\n con = lite.connect(\"bernie.db\")\n cur = con.cursor()\n try:\n with con:\n cur.execute(\"INSERT INTO tracking ('firstName', 'lastName', 'county', 'phone', 'email', 'committed', 'volunteer') VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s');\" % (firstName, lastName, county, phone, email, committed, volunteer))\n print(\"successfully added\")\n except:\n print(\"something went wrong.\")\n cur.close()\n\n# Build select statements to get information here.\ndef getInfo(county='', committed='', volunteer=''):\n con = lite.connect(\"bernie.db\")\n cur = con.cursor()\n #SELECT email,phone FROM tracking where committed is 'yes';\n selectR = []\n if len(county) > 0:\n selectR.append(\"county is '%s'\" % county)\n if len(committed) > 0:\n selectR.append(\"committed is '%s'\" % committed)\n if len(volunteer) > 0:\n selectR.append(\"volunteer is '%s'\" % volunteer)\n \n newStatement = ' and '.join(selectR)\n\n myQuery = (\"SELECT * FROM tracking where %s;\" % newStatement)\n \n cur.execute(myQuery)\n items = cur.fetchall()\n return items\n \n cur.close()\n #print(\"SELECT * FROM Tracking where %s\")\n\n\n\n","sub_path":"bernieDAO.py","file_name":"bernieDAO.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514643547","text":"import yaml\nimport os\nimport glob\nfrom pathlib import Path\nfrom datetime import datetime\n\ndef load_conf(filepath) -> dict:\n \"\"\"Load a YAML configuration file\n\n Args:\n filepath (str): The filepath of the conf YAML file. \n \"\"\"\n with open(filepath, 'r') as infile:\n return yaml.load(infile, Loader=yaml.FullLoader)\n\ndef get_closest_value(values, value) -> int:\n \"\"\"Get the closest value\n\n In a list of values get the closest one\n\n Args:\n values (list): The list to get the closest. \n value (int): The value we would like to come close to>\n\n Return:\n (int): The closest value\n \"\"\"\n return min(values, key=lambda x:abs(x-value))\n\ndef build_index(filepath=os.path.join('kameramera', 'data', 'index.yml')):\n \"\"\"Build the index file\n\n List all YAML files in data directory and create an index file\n\n Args:\n filepath (str): Filepath of the index output file. \n Default: \"kameramera\\data\\index.yml\"\n \"\"\"\n print('Building INDEX')\n camera_filepath = os.path.join('kameramera', 'data', 'camera', '*.yml')\n cameras = []\n nb_cameras = len(glob.glob(camera_filepath))\n\n print(' - Building camera index | nb of cameras {}'.format(nb_cameras))\n\n for camera in glob.glob(camera_filepath):\n cameras.append(\n {\n 'manufacturer': load_conf(camera)['general']['manufacturer'],\n 'name': load_conf(camera)['general']['name'],\n 'id': Path(camera).stem,\n 'path': camera\n }\n )\n\n data = {\n 'last_update': datetime.now(),\n 'cameras': cameras\n }\n\n print('Writing into file : {}'.format(filepath))\n with open(filepath, 'w') as outfile:\n yaml.dump(data, outfile, default_flow_style=False)","sub_path":"kameramera/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"526774808","text":"#-*- encoding: utf-8 -*-\nimport sys\nimport os\nimport threading\nimport MD5sum\nimport logger\nimport globalFunc\nimport globalData\nimport revFileProg\nimport sendFile\nimport msgLog\n#复制粘贴第三方库\nimport pyperclip\n\nreload(sys)\nc=sys.getdefaultencoding()\nsys.setdefaultencoding('utf-8') #被发送文件名中带有汉字的文件\n\ndef errorFunc(*pl):\n logger.log.debug('errorFunc test!')\ndef shellServ(*pl):\n praList,rsList,addrFrom,msgUuid=pl\n #praList为shell命令,\n #rsList为在数据库中自定义的本次执行任务需要的全局资源\n #rsList[0]全局结果字典,msgUuid本次消息结果在全局消息结果的key\n #rsList[1]是本次接收本次消息的socket连接,可通过其将shell命令结果发送至socket对端\n #addrFrom socket消息地址\n cmdStr = praList\n #resultDic = rsList[0]\n #执行shell命令\n try:\n resultStr = os.popen(cmdStr).read()\n rsList[0][msgUuid]['result'] = resultStr\n rsList[0][msgUuid]['finished'] = 1\n except Exception as e:\n rsList[0][msgUuid]['result'] = str(e)\n rsList[0][msgUuid]['finished'] = 2\n logger.log.debug('shellServ test!')\n #回显执行结果\n rsList[1].send(rsList[0][msgUuid]['result'])\n logger.log.info(str(rsList[0][msgUuid]))\ndef recvFileThread(filePras,globalsignal):\n #启动revFile线程\n addr=('0.0.0.0',52115)\n sendBuffSize=globalData.sendBuffSize\n listenNum=globalData.listenNum\n pra={'sendBuffSize':sendBuffSize,'listenNum':listenNum}\n revFileTh=revFileProg.revFileProg(addr,pra,filePras,globalsignal)\n revFileTh.setDaemon(True)\n revFileTh.start()\n\n\ndef rvFile(*pl):\n logger.log.info('\\n#############File Recv Start...s################')\n logger.log.debug('revFile pra %s'%str(pl)) \n praList,rsList,addrFrom,msgUuid=pl\n fileName,fileSizeStr,blockSizeStr=praList\n filePra={'toFileDir':globalData.toFileDir,'fileName':fileName,'fileSize':int(fileSizeStr),'blockSize':int(blockSizeStr)}\n logger.log.debug('filePra:%s'%filePra)\n #此处应弹窗提示是否要接收来自addr的文件,地址文件名。\n \n #确定接收的文件后,先给recvFile线程填充参数\n filePras=rsList[0]\n \n #revCondition=rsList[1]\n #revCondition.acquire()\n filePras[MD5sum.dataMD5(fileName)]=filePra\n \n logger.log.debug('filePras:%s'%str(filePras))\n #revCondition.release()\n #然后发送文件文件MD5至对端,等待对端发送确定后的文件。\n rsList[1].send(MD5sum.dataMD5(fileName))\n logger.log.debug('recvFile func end!')\n'''\nsendFile的参数形式:[[[file1,file2,...],addr1],[[file1,file2,...],addr2],...]\n测试时参数形式为[filepath,addr]\n'''\ndef sdFile(ip,filePath):\n sfile=sendFile.sendFile(ip,filePath)\n sfile.transferFile()\n#带进度提示\ndef sdFileProg(ip,filePath,prog,sendID):\n sfile=sendFile.sendFile(ip,filePath)\n sfile.transferFileProg(prog=prog,sendid=sendID)\ndef sFile(*pl):\n logger.log.info('\\n#############File Send Start...################')\n logger.log.debug(pl)\n #测试阶段先完成单个文件单个地址的情况,\n #后续完成其它情况\n \n praList,rsList,addrFrom,msgUuid=pl\n #将要发送的文件摘要信息发往对端,并等待对端进行确认\n ip,filePath=praList\n #filePath=''.join(x.decode('utf-8') for x in filePath.split())\n #(filePwd,fileName,fileSize)=globalFunc.getFilePrefile(filePath)\n #从全局资源中获取进度变量地址20161213\n prog=rsList[0]\n #为每次发送任务标号,自动加1\n rsList[1][0]+=1\n sendID=rsList[1][0]\n #设置进度相关信息\n filePwd,fileName,fileSize=globalFunc.getFilePrefile(filePath)\n #停止阻塞进度线程\n rsList[2].set()\n prog[sendID]={'taskfrom':'127.0.0.1','taskpath':filePwd,'filename':fileName,'filesize':fileSize,'sendsize':0}\n sendth=threading.Thread(target=sdFileProg,args=(ip,filePath,prog,rsList[1][0]))\n sendth.setDaemon(True)\n sendth.start()\n logger.log.debug('#############Task Start!################')\n#revmsg='003'+'*'+'len(revmsg)'{预留10位}+msgcontent\ndef revMsg(*pl):\n praList,rsList,addrFrom,msgUuid=pl\n #在此服务内,praList为单值消息\n size,msg=praList\n \n #将文本消息复制到系统粘贴板\n pyperclip.copy(msg.decode('utf-8'))\n msgLog.msg.info('----From:'+addrFrom[0]+'\\n'+msg.decode('utf-8')+'\\n***********************')\ndef sendMsg(*pl):\n praList,rsList,addrFrom,msgUuid=pl\n ip,msg=praList\n sizeStr=str(len(msg)+14)\n if len(sizeStr) <= 10:\n for i in range(len(sizeStr),10):\n sizeStr='0'+sizeStr\n msgStr='003'+'*'+sizeStr+'$'+msg\n try:\n globalFunc.sendMsg('TCP',(ip,52113),msgStr,len(msg)+14)\n msgLog.msg.info('----to:'+ip+'\\n'+msg+'\\n***********************')\n except Exception as e:\n logger.log.debug('senMsg exception:%s'%str(e))\nsysServDic={'000':shellServ,'001':rvFile,'002':sFile,'003':revMsg,'004':sendMsg}\n \n","sub_path":"systemService.py","file_name":"systemService.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"344528925","text":"import virtool.uploads.db\n\n\nasync def test_finish_upload(mocker, dbi):\n app = {\n \"db\": dbi,\n \"settings\": {\n \"data_path\": \"/foo\"\n }\n }\n\n stats = {\n \"size\": 2048\n }\n\n await dbi.files.insert_one({\n \"_id\": \"bar\",\n \"ready\": False\n })\n\n mocker.patch(\"virtool.utils.file_stats\", return_value=stats)\n\n await virtool.uploads.db.finish_upload(app, \"bar\")\n\n assert await dbi.files.find_one() == {\n \"_id\": \"bar\",\n \"size\": 2048,\n \"ready\": True\n }\n\n\n","sub_path":"tests/uploads/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"412320872","text":"#!/usr/bin/env python2\nimport os\nimport sys\nimport unittest\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../../..\"))\n\nfrom playground.gp.tree import Tree\nfrom playground.gp.tree import Node\nfrom playground.gp.tree import NodeType\nfrom playground.gp.tree.parser import TreeParser\n\n\nclass NodeTests(unittest.TestCase):\n def setUp(self):\n self.left_node = Node(NodeType.CONSTANT, value=1.0)\n self.left_node_2 = Node(NodeType.CONSTANT, value=1.0)\n\n self.right_node = Node(NodeType.CONSTANT, value=2.0)\n self.right_node_2 = Node(NodeType.CONSTANT, value=2.0)\n\n self.binary_node = Node(\n NodeType.FUNCTION,\n arity=2,\n branches=[self.left_node, self.right_node]\n )\n\n def test_has_value_node(self):\n # assert left branch\n res = self.binary_node.has_value_node(self.left_node)\n self.assertEquals(res, 0)\n\n # assert right branch\n res = self.binary_node.has_value_node(self.right_node)\n self.assertEqual(res, 1)\n\n # assert fail left branch\n res = self.binary_node.has_value_node(self.left_node_2)\n self.assertFalse(res)\n\n # assert fail right branch\n res = self.binary_node.has_value_node(self.right_node_2)\n self.assertFalse(res)\n\n def test_equal(self):\n term_node = Node(NodeType.CONSTANT, value=2)\n\n # assert UNARY_OP node\n unary_node = Node(NodeType.FUNCTION, name=\"SIN\")\n self.assertTrue(unary_node.equals(unary_node))\n self.assertFalse(unary_node.equals(term_node))\n\n # assert BINARY_OP node\n binary_node = Node(NodeType.FUNCTION, name=\"ADD\")\n self.assertTrue(binary_node.equals(binary_node))\n self.assertFalse(binary_node.equals(term_node))\n\n # assert TERM node\n term_node_2 = Node(NodeType.CONSTANT, value=1.0)\n self.assertTrue(term_node_2.equals(term_node_2))\n self.assertFalse(term_node_2.equals(term_node))\n\n # assert INPUT node\n input_node = Node(NodeType.INPUT, name=\"x\")\n self.assertTrue(input_node.equals(input_node))\n self.assertFalse(input_node.equals(term_node))\n\n\nclass TreeTests(unittest.TestCase):\n def setUp(self):\n self.config = {\n \"max_population\": 10,\n\n \"tree_generation\": {\n \"method\": \"FULL_METHOD\",\n \"initial_max_depth\": 4\n },\n\n \"function_nodes\": [\n {\"type\": \"FUNCTION\", \"name\": \"ADD\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"SUB\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"MUL\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"DIV\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"COS\", \"arity\": 1},\n {\"type\": \"FUNCTION\", \"name\": \"SIN\", \"arity\": 1}\n ],\n\n \"terminal_nodes\": [\n {\"type\": \"CONSTANT\", \"value\": 1.0},\n {\"type\": \"INPUT\", \"name\": \"x\"},\n {\"type\": \"INPUT\", \"name\": \"y\"},\n {\"type\": \"INPUT\", \"name\": \"z\"}\n ],\n\n \"input_variables\": [\n {\"name\": \"x\"},\n {\"name\": \"y\"},\n {\"name\": \"z\"}\n ]\n }\n\n self.t_parser = TreeParser()\n self.tree = Tree()\n\n node_x = Node(NodeType.INPUT, name=\"x\")\n node_y = Node(NodeType.INPUT, name=\"y\")\n node_z = Node(NodeType.INPUT, name=\"z\")\n\n self.tree.input_nodes.append(node_x)\n self.tree.input_nodes.append(node_y)\n self.tree.input_nodes.append(node_z)\n\n def test_valid(self):\n # assert valid\n res = self.tree.valid(self.config[\"input_variables\"])\n self.assertTrue(res)\n\n # assert fail valid\n self.tree.input_nodes.pop()\n res = self.tree.valid(self.config[\"input_variables\"])\n self.assertFalse(res)\n\n def test_get_linked_node(self):\n # setup\n del self.tree.input_nodes[:]\n left_node = Node(NodeType.INPUT, name=\"x\")\n right_node = Node(NodeType.INPUT, name=\"y\")\n add_func = Node(\n NodeType.FUNCTION,\n name=\"ADD\",\n arity=2,\n branches=[left_node, right_node]\n )\n self.tree.root = add_func\n self.tree.program = self.t_parser.post_order_traverse(self.tree.root)\n\n # pass test\n linked_node = self.tree.get_linked_node(left_node)\n self.assertTrue(linked_node is add_func)\n linked_node = self.tree.get_linked_node(right_node)\n self.assertTrue(linked_node is add_func)\n\n # fail test\n random_node = Node(NodeType.INPUT, name=\"z\")\n linked_node = self.tree.get_linked_node(random_node)\n self.assertFalse(linked_node is add_func)\n\n def test_replace_node(self):\n # setup\n node_x = Node(NodeType.INPUT, name=\"x\")\n node_y = Node(NodeType.INPUT, name=\"y\")\n add_func = Node(\n NodeType.FUNCTION,\n name=\"ADD\",\n arity=2,\n branches=[node_x, node_y]\n )\n\n # build tree\n tree = Tree()\n tree.root = add_func\n tree.update_program()\n\n # replace input node\n new_node = Node(NodeType.INPUT, name=\"z\")\n before_replace = list(tree.program)\n tree.replace_node(node_x, new_node)\n after_replace = list(tree.program)\n\n # assert\n self.assertTrue(before_replace == before_replace)\n self.assertTrue(after_replace == after_replace)\n self.assertFalse(before_replace == after_replace)\n self.assertTrue(add_func.branches[0] is new_node)\n\n def test_equal(self):\n # create nodes\n left_node_1 = Node(NodeType.CONSTANT, value=1.0)\n right_node_1 = Node(NodeType.CONSTANT, value=2.0)\n\n left_node_2 = Node(NodeType.CONSTANT, value=3.0)\n right_node_2 = Node(NodeType.CONSTANT, value=4.0)\n\n cos_func_1 = Node(\n NodeType.FUNCTION,\n name=\"COS\",\n arity=1,\n branches=[left_node_1]\n )\n sin_func_1 = Node(\n NodeType.FUNCTION,\n name=\"SIN\",\n arity=1,\n branches=[right_node_1]\n )\n\n cos_func_2 = Node(\n NodeType.FUNCTION,\n name=\"COS\",\n arity=1,\n branches=[left_node_2]\n )\n sin_func_2 = Node(\n NodeType.FUNCTION,\n name=\"SIN\",\n arity=1,\n branches=[right_node_2]\n )\n\n add_func = Node(\n NodeType.FUNCTION,\n name=\"ADD\",\n arity=2,\n branches=[cos_func_1, sin_func_1]\n )\n\n sub_func = Node(\n NodeType.FUNCTION,\n name=\"SUB\",\n arity=2,\n branches=[sin_func_2, cos_func_2]\n )\n\n # create tree_1\n tree_1 = Tree()\n tree_1.root = add_func\n tree_1.update()\n\n # create tree_2\n tree_2 = Tree()\n tree_2.root = sub_func\n tree_2.update()\n\n self.assertTrue(tree_1.equals(tree_1))\n self.assertFalse(tree_1.equals(tree_2))\n self.assertTrue(tree_2.equals(tree_2))\n self.assertFalse(tree_2.equals(tree_1))\n\n def test_str(self):\n # setup\n del self.tree.input_nodes[:]\n left_node = Node(NodeType.INPUT, name=\"x\")\n right_node = Node(NodeType.INPUT, name=\"y\")\n add_func = Node(\n NodeType.FUNCTION,\n name=\"ADD\",\n arity=2,\n branches=[left_node, right_node]\n )\n self.tree.root = add_func\n self.tree.program = self.t_parser.post_order_traverse(self.tree.root)\n\n # assert\n self.assertEquals(str(self.tree), \"(x ADD y)\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/gp/tree/tree_tests.py","file_name":"tree_tests.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"450935292","text":"#!/usr/bin/env python3\n\nimport random, textwrap\n\ndef is_match(number, guess, it):\n if number == guess:\n if number == 42:\n print('The answer to the ultimate question of life, the universe and everything is 42.')\n print(f'You won in {it} attempts!') if it > 1 else print(f'Congratulations! You got it on your first try!')\n return True\n print('Too high!') if number > guess else print('Too low')\n return False\n\ndef main():\n guess = random.randint(1, 99)\n it = 0\n print(textwrap.dedent(\"\"\"\n This is an interactive guessing game!\n You have to enter a number between 1 and 99 to find out the secret number.\n Type 'exit' to end the game.\n Good luck!\n \"\"\"))\n while True:\n number = input(\"What's your guess between 1 and 99?\\n\")\n if number == 'exit':\n print('Goodbye!')\n break\n elif not number.isdecimal():\n print(\"That's not a number.\")\n elif is_match(int(number), guess, it):\n break\n it += 1\n\nif __name__ == '__main__':\n main()","sub_path":"module00/ex09/guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"437721251","text":"# Catalogo URLS\n\nfrom django.conf.urls import url\nfrom catalogo import views\n\nurlpatterns = [\n url(r'^$', \"catalogo.views.catalogo_home\"), \n url(r'^(?P\\d+)/', \"catalogo.views.detalhe_do_post\", name=\"detalhe\"),\n url(r'^lista/', \"catalogo.views.lista_de_posts\"),\n]\n","sub_path":"catalogo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"256292724","text":"# Xingchen Wan | 2018\n# Generation of the test functions that are made from Gaussian mixture for evaluation of the quality of integration\n# of various numerical integration techniques. Due to the use of Gaussian mixtures these integrals are analytically\n# tractable; these exact values form the benchmark of comparison.\n\n\nimport numpy as np\nfrom scipy.stats import norm, multivariate_normal\nimport matplotlib.pyplot as plt\nfrom typing import Union\nfrom bayesquad.priors import Prior\nfrom scipy.integrate import quad\n\n\nclass TrueFunctions:\n \"\"\"Abstract class for True Functions\"\"\"\n def __init__(self, ):\n self.dimensions = None\n\n def sample(self, x: Union[np.ndarray, float, list]) -> np.ndarray:\n pass\n\n def log_sample(self, x:Union[np.ndarray, float, list]) -> np.ndarray:\n return np.log(self.sample(x))\n\n def _sample_test(self, x: Union[np.ndarray, float, list]):\n x = np.asarray(x)\n if x.ndim == 0 or x.ndim == 1:\n assert self.dimensions == 1, \"Scalar input is only permitted if the function is of dimension!\"\n else:\n # If plotting a list of points, the ndim of the supplied x np array must be 2\n assert x.ndim == 2\n assert x.shape[1] == self.dimensions, \"Dimension of function is of\" + str(self.dimensions) + \\\n \" ,but the dimension of input is \" + str(x.shape[1])\n return x\n\n def plot(self, plot_range: tuple = (-3., 0.01, 3.), **matplot_options):\n assert self.dimensions <= 2, \"Plotting higher dimension functions are not supperted!\"\n range_min, range_step, range_max = plot_range[0], plot_range[1], plot_range[2]\n plot_x = np.arange(range_min, range_max, range_step + 0.0)\n plot_y = np.array(self.sample(plot_x))\n plt.plot(plot_x, plot_y, **matplot_options)\n\n\nclass ProductOfGaussianMixture(TrueFunctions):\n \"\"\"\n A test function that is product of n Gaussian mixtures (defined below)\n \"\"\"\n def __init__(self, *gauss_mixtures: TrueFunctions):\n super(ProductOfGaussianMixture, self).__init__()\n gauss_mixtures_dims = []\n for each_mixture in gauss_mixtures:\n assert isinstance(each_mixture, GaussMixture), \"Invalid Type: GaussMixture object(s) expected\"\n gauss_mixtures_dims.append(each_mixture.dimensions)\n assert len(set(gauss_mixtures_dims)) == 1, \"There are different dimensions in the GaussMixture objects!\"\n self.dimensions = gauss_mixtures_dims[0]\n self.gauss_mixtures = gauss_mixtures\n self.gauss_mixtures_count = len(gauss_mixtures)\n\n def sample(self, x: Union[np.ndarray, float, list]):\n x = self._sample_test(x)\n if x.ndim <= 1:\n y_s = np.array([each_mixture.sample(x) for each_mixture in self.gauss_mixtures])\n print(y_s)\n return np.prod(y_s)\n else:\n y_s = []\n for j in range(x.shape[0]):\n y_s.append([each_mixture.sample(x[j]) for each_mixture in self.gauss_mixtures])\n y_s = np.asarray(y_s)\n return np.prod(y_s, axis=1)\n\n\nclass GaussMixture(TrueFunctions):\n \"\"\"\n A test function consists of a mixture (summation) of Gaussians (so used because it allows the evaluation of\n the integration exactly as a benchmark for other quadrature methods.\n \"\"\"\n def __init__(self, means: Union[np.ndarray, float, list], covariances: Union[np.ndarray, float, list],\n weights: Union[np.ndarray, list, float]=None):\n super(GaussMixture, self).__init__()\n\n self.means = np.asarray(means)\n self.covs = np.asarray(covariances)\n self.mixture_count = len(self.means)\n\n if self.means.ndim == 1:\n self.dimensions = 1\n else:\n self.dimensions = self.means.shape[1]\n if weights is None:\n # For unspecified weights, each individual Gaussian distribution within the mixture will receive\n # an equal weight\n weights = np.array([1./self.mixture_count]*self.mixture_count)\n self.weights = np.asarray(weights)\n assert self.means.shape[0] == self.covs.shape[0], \"Mean and Covariance List mismatch!\"\n assert self.means.shape[0] == self.weights.shape[0]\n assert self.weights.ndim <= 1, \"Weight vector must be a 1D array!\"\n\n def sample(self, x: Union[np.ndarray, float, list], ):\n \"\"\"\n Sample from the true function either with one query point or a list of points\n :param x: the coordinate(s) of the query point(s)\n :return: the value of the true function evaluated at the query point(s)\n \"\"\"\n x = self._sample_test(x)\n if x.ndim <= 1:\n y = 0\n for i in range(self.mixture_count):\n if self.dimensions == 1:\n y += self.weights[i] * self.one_d_normal(x, self.means[i], self.covs[i])\n else:\n y += self.weights[i] * self.multi_d_gauss(x, self.means[i], self.covs[i])\n else:\n x = np.squeeze(x, axis=1)\n y = np.zeros((x.shape[0], ))\n for i in range(self.mixture_count):\n if self.dimensions == 1:\n y += self.weights[i] * self.one_d_normal(x, self.means[i], self.covs[i])\n else:\n y += self.weights[i] * self.multi_d_gauss(x, self.means[i], self.covs[i])\n return y\n\n @staticmethod\n def one_d_normal(x: np.ndarray, mean, var) -> np.ndarray:\n assert x.ndim == 1\n return np.array([norm.pdf(x[i], mean, var) for i in range(x.shape[0])])\n\n @staticmethod\n def multi_d_gauss(x: np.ndarray, mean, cov) -> np.ndarray:\n assert x.ndim == 2\n return np.array([multivariate_normal.pdf(x[i], mean=mean, cov=cov) for i in range(x.shape[0])])\n\n def add_gaussian(self, means: Union[np.ndarray, float], var: Union[np.ndarray, float], weight: Union[np.ndarray, float]):\n assert means.shape == self.means.shape[1:]\n assert var.shape == self.covs.shape[1:]\n self.means = np.append(self.means, means)\n self.covs = np.append(self.covs, var)\n self.weights = np.append(self.weights, weight)\n\n def _rebase_weight(self):\n self.weights = self.weights / np.sum(self.weights)\n\n\ndef evidence_integral(gauss_mix: GaussMixture,\n prior_mean: Union[np.ndarray,float], prior_var: Union[np.ndarray, float]):\n \"\"\"\n Returns the analytical integral of the evidence integral given by the mixture (sum) of Gaussian multiplied\n by a Gaussian prior.\n :param gauss_mix: an instance of Gaussian Mixture defined in the GaussMixture instance\n :param prior_mean: :param prior_var: mean and covariance of the prior (Gaussian) distribution\n :return: the *exact* integral of the gaussian mixture by analytical methods\n \"\"\"\n prior_var = np.asarray(prior_var)\n prior_mean = np.asarray(prior_mean)\n if prior_mean.ndim == 0:\n assert gauss_mix.dimensions == 1\n else:\n assert prior_mean.shape[0] == gauss_mix.dimensions\n res = 0.\n for i in range(gauss_mix.mixture_count):\n mu = gauss_mix.means[i]\n sigma = gauss_mix.covs[i]\n weight = gauss_mix.weights[i]\n _, _, scaling_factor = gauss_product(mu, prior_mean, sigma, prior_var)\n res += scaling_factor * weight\n return res\n\n\ndef predictive_integral(gauss_mix_1: GaussMixture, gauss_mix_2: GaussMixture,\n prior_mean: Union[np.ndarray, float], prior_var: Union[np.ndarray, float]):\n \"\"\"\n Return the analytical integral of the posterior integral given by the two mixture of Guassians multipled by a\n Gaussian prior.\n :param gauss_mix_1:\n :param gauss_mix_2:\n :param prior_mean:\n :param prior_var:\n :return:\n \"\"\"\n prior_mean = np.asarray(prior_mean)\n prior_var = np.asarray(prior_var)\n if prior_mean.ndim == 0:\n # Supplied argument is number\n assert gauss_mix_1.dimensions == 1 and gauss_mix_2.dimensions == 1\n else:\n assert prior_mean.shape[0] == gauss_mix_1.dimensions\n assert gauss_mix_1.dimensions == gauss_mix_2.dimensions\n res = 0.\n for i in range(gauss_mix_1.mixture_count):\n mu1 = gauss_mix_1.means[i]\n sigma1 = gauss_mix_1.covs[i]\n weight1 = gauss_mix_1.weights[i]\n for j in range(gauss_mix_2.mixture_count):\n mu2 = gauss_mix_2.means[j]\n sigma2 = gauss_mix_2.covs[j]\n weight2 = gauss_mix_2.weights[j]\n mu_product, sigma_product, scale_product = gauss_product(mu1, mu2, sigma1, sigma2)\n _, _, scale_with_prior = gauss_product(mu_product, prior_mean, sigma_product, prior_var)\n res += scale_with_prior * scale_product * weight1 * weight2\n return res\n\n\ndef gauss_product(mean1: Union[np.ndarray, float], mean2: Union[np.ndarray, float],\n cov1: Union[np.ndarray, float], cov2: Union[np.ndarray, float]):\n \"\"\"\n Given the mean and variance/covariance matrices of two Gaussian distribution, this function computes the mean,\n variance/covariance matrix of the resultant product (which is a scaled version of another Gaussian distribution).\n The scaling factor is also returned to normalise the product to a proper pdf\n :param mean1 :param mean2: Means\n :param cov1: :param cov2: Variance/Covariance Matrices\n :return: resultant mean, variance/covariance matrix, scaling factor\n \"\"\"\n # Cast float (if any) data types to numpy arrays\n mean1 = np.asarray(mean1)\n mean2 = np.asarray(mean2)\n cov1 = np.asarray(cov1)\n cov2 = np.asarray(cov2)\n\n # Sanity Checks\n assert mean1.shape == mean2.shape, \"mean1 has shape \"+str(mean1.shape)+\", but mean2 has shape \"+str(mean2.shape)\n assert cov1.shape == cov2.shape, \"cov1 has shape \"+str(cov1.shape)+\", but cov2 has shape \"+str(cov2.shape)\n try:\n dim = mean1.shape[0]\n except IndexError:\n # Input is a number\n dim = 1\n\n # Multivariate Gaussian - Use Matrix Algebra\n if dim > 1:\n # Precision matrices\n precision1 = np.linalg.inv(cov1)\n precision2 = np.linalg.inv(cov2)\n\n # Product Covariance Matrix\n product_cov = np.linalg.inv(precision1 + precision2)\n product_mean = product_cov @ (precision1 @ mean1 + precision2 @ mean2)\n scaling_factor = (2 * np.pi) ** (-dim / 2) * np.linalg.det(cov1 + cov2) ** -0.5 * \\\n np.exp(-0.5 * np.transpose(mean1 - mean2) @ np.linalg.inv(cov1 + cov2) @ (mean1 - mean2))\n\n # Univariate Gaussian - Simply use number operations\n elif dim == 1:\n product_cov = 1 / (1/cov1 + 1/cov2)\n product_mean = product_cov * (mean1/cov1 + mean2/cov2)\n scaling_factor = 1 / np.sqrt(2 * np.pi * (cov1 + cov2)) * np.exp(- ((mean1 - mean2) ** 2) /\n (2 * (cov1 + cov2)))\n else:\n raise ValueError(\"Invalid input shape\")\n return product_mean, product_cov, scaling_factor\n\n\ndef approx_integrals(p: Prior, q: TrueFunctions, r: TrueFunctions) -> tuple:\n def pr(x: float) -> float:\n x = np.array([[x]])\n return np.asscalar(p(x) * r.sample(x))\n\n def pqr(x: float) -> float:\n x = np.array([[x]])\n return np.asscalar(p(x) * q.sample(x) * r.sample(x))\n\n integral_pr = quad(pr, -10, 10, )\n integral_pqr = quad(pqr, -10, 10, )\n ratio = integral_pqr[0]/integral_pr[0]\n print(\"Denominator Integral:\", str(integral_pr))\n print('Numerator Integral: ', str(integral_pqr))\n print('Ratio: ',str(ratio))\n return integral_pqr[0], integral_pr[0], ratio\n","sub_path":"ratio_extension/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":11666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"374059912","text":"\"\"\"exam_answers URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/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\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nfrom ExamAnswers import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', views.index, name='index'),\n url(r'^question/(?P[0-9]+)/$', views.view_question, name=\"question\"),\n url(r'^exam/(?P[0-9]+)/$', views.view_exam, name='exam'),\n url(r'^(?P[A-Za-z]+)/(?P.+)/(?P.+)/(?P.+)/$',\n views.view_course, name=\"course\"),\n url(r'^(?P[A-Za-z]+)/(?P.+)/(?P.+)/$', views.view_subject, name=\"subject\"),\n url(r'^(?P[A-Za-z]+)/(?P.+)/$', views.view_institution, name=\"institution\"),\n url(r'^(?P[A-Za-z]+)/$', views.view_country, name=\"country\"),\n]\n","sub_path":"exam_answers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"255096429","text":"import abc\nimport asyncio\nimport inspect\nfrom typing import (\n Awaitable,\n Callable,\n Dict,\n List,\n Optional,\n Tuple,\n)\nfrom warnings import warn\n\nfrom bleak.backends.device import BLEDevice\n\n\nclass AdvertisementData:\n \"\"\"\n Wrapper around the advertisement data that each platform returns upon discovery\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Args:\n local_name (str): The name of the ble device advertising\n manufacturer_data (dict): Manufacturer data from the device\n service_data (dict): Service data from the device\n service_uuids (list): UUIDs associated with the device\n platform_data (tuple): Tuple of platform specific advertisement data\n \"\"\"\n # The local name of the device\n self.local_name: Optional[str] = kwargs.get(\"local_name\", None)\n\n # Dictionary of manufacturer data in bytes\n self.manufacturer_data: Dict[int, bytes] = kwargs.get(\"manufacturer_data\", {})\n\n # Dictionary of service data\n self.service_data: Dict[str, bytes] = kwargs.get(\"service_data\", {})\n\n # List of UUIDs\n self.service_uuids: List[str] = kwargs.get(\"service_uuids\", [])\n\n # Tuple of platform specific data\n self.platform_data: Tuple = kwargs.get(\"platform_data\", ())\n\n def __repr__(self) -> str:\n kwargs = []\n if self.local_name:\n kwargs.append(f\"local_name={repr(self.local_name)}\")\n if self.manufacturer_data:\n kwargs.append(f\"manufacturer_data={repr(self.manufacturer_data)}\")\n if self.service_data:\n kwargs.append(f\"service_data={repr(self.service_data)}\")\n if self.service_uuids:\n kwargs.append(f\"service_uuids={repr(self.service_uuids)}\")\n return f\"AdvertisementData({', '.join(kwargs)})\"\n\n\nAdvertisementDataCallback = Callable[\n [BLEDevice, AdvertisementData],\n Optional[Awaitable[None]],\n]\n\nAdvertisementDataFilter = Callable[\n [BLEDevice, AdvertisementData],\n bool,\n]\n\n\nclass BaseBleakScanner(abc.ABC):\n \"\"\"\n Interface for Bleak Bluetooth LE Scanners\n\n Args:\n **detection_callback (callable or coroutine):\n Optional function that will be called each time a device is\n discovered or advertising data has changed.\n **service_uuids (List[str]):\n Optional list of service UUIDs to filter on. Only advertisements\n containing this advertising data will be received. Required on\n macOS 12 and later.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BaseBleakScanner, self).__init__()\n self._callback: Optional[AdvertisementDataCallback] = None\n self.register_detection_callback(kwargs.get(\"detection_callback\"))\n self._service_uuids: Optional[List[str]] = (\n [u.lower() for u in kwargs[\"service_uuids\"]]\n if \"service_uuids\" in kwargs\n else None\n )\n\n async def __aenter__(self):\n await self.start()\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.stop()\n\n @classmethod\n async def discover(cls, timeout=5.0, **kwargs) -> List[BLEDevice]:\n \"\"\"Scan continuously for ``timeout`` seconds and return discovered devices.\n\n Args:\n timeout: Time to scan for.\n\n Keyword Args:\n **kwargs: Implementations might offer additional keyword arguments sent to the constructor of the\n BleakScanner class.\n\n Returns:\n\n \"\"\"\n async with cls(**kwargs) as scanner:\n await asyncio.sleep(timeout)\n devices = scanner.discovered_devices\n return devices\n\n def register_detection_callback(\n self, callback: Optional[AdvertisementDataCallback]\n ) -> None:\n \"\"\"Register a callback that is called when a device is discovered or has a property changed.\n\n If another callback has already been registered, it will be replaced with ``callback``.\n ``None`` can be used to remove the current callback.\n\n The ``callback`` is a function or coroutine that takes two arguments: :class:`BLEDevice`\n and :class:`AdvertisementData`.\n\n Args:\n callback: A function, coroutine or ``None``.\n\n \"\"\"\n if callback is not None:\n error_text = \"callback must be callable with 2 parameters\"\n if not callable(callback):\n raise TypeError(error_text)\n\n handler_signature = inspect.signature(callback)\n if len(handler_signature.parameters) != 2:\n raise TypeError(error_text)\n\n if inspect.iscoroutinefunction(callback):\n\n def detection_callback(s, d):\n asyncio.ensure_future(callback(s, d))\n\n else:\n detection_callback = callback\n\n self._callback = detection_callback\n\n @abc.abstractmethod\n async def start(self):\n \"\"\"Start scanning for devices\"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n async def stop(self):\n \"\"\"Stop scanning for devices\"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def set_scanning_filter(self, **kwargs):\n \"\"\"Set scanning filter for the BleakScanner.\n\n Args:\n **kwargs: The filter details. This will differ a lot between backend implementations.\n\n \"\"\"\n raise NotImplementedError()\n\n @property\n @abc.abstractmethod\n def discovered_devices(self) -> List[BLEDevice]:\n \"\"\"Gets the devices registered by the BleakScanner.\n\n Returns:\n A list of the devices that the scanner has discovered during the scanning.\n \"\"\"\n raise NotImplementedError()\n\n async def get_discovered_devices(self) -> List[BLEDevice]:\n \"\"\"Gets the devices registered by the BleakScanner.\n\n .. deprecated:: 0.11.0\n This method will be removed in a future version of Bleak. Use the\n :attr:`.discovered_devices` property instead.\n\n Returns:\n A list of the devices that the scanner has discovered during the scanning.\n\n \"\"\"\n warn(\n \"This method will be removed in a future version of Bleak. Use the `discovered_devices` property instead.\",\n FutureWarning,\n stacklevel=2,\n )\n return self.discovered_devices\n\n @classmethod\n async def find_device_by_address(\n cls, device_identifier: str, timeout: float = 10.0, **kwargs\n ) -> Optional[BLEDevice]:\n \"\"\"A convenience method for obtaining a ``BLEDevice`` object specified by Bluetooth address or (macOS) UUID address.\n\n Args:\n device_identifier (str): The Bluetooth/UUID address of the Bluetooth peripheral sought.\n timeout (float): Optional timeout to wait for detection of specified peripheral before giving up. Defaults to 10.0 seconds.\n\n Keyword Args:\n adapter (str): Bluetooth adapter to use for discovery.\n\n Returns:\n The ``BLEDevice`` sought or ``None`` if not detected.\n\n \"\"\"\n device_identifier = device_identifier.lower()\n return await cls.find_device_by_filter(\n lambda d, ad: d.address.lower() == device_identifier,\n timeout=timeout,\n **kwargs,\n )\n\n @classmethod\n async def find_device_by_filter(\n cls, filterfunc: AdvertisementDataFilter, timeout: float = 10.0, **kwargs\n ) -> Optional[BLEDevice]:\n \"\"\"A convenience method for obtaining a ``BLEDevice`` object specified by a filter function.\n\n Args:\n filterfunc (AdvertisementDataFilter): A function that is called for every BLEDevice found. It should return True only for the wanted device.\n timeout (float): Optional timeout to wait for detection of specified peripheral before giving up. Defaults to 10.0 seconds.\n\n Keyword Args:\n adapter (str): Bluetooth adapter to use for discovery.\n\n Returns:\n The ``BLEDevice`` sought or ``None`` if not detected.\n\n \"\"\"\n found_device_queue = asyncio.Queue()\n\n def apply_filter(d: BLEDevice, ad: AdvertisementData):\n if filterfunc(d, ad):\n found_device_queue.put_nowait(d)\n\n async with cls(detection_callback=apply_filter, **kwargs):\n try:\n return await asyncio.wait_for(found_device_queue.get(), timeout=timeout)\n except asyncio.TimeoutError:\n return None\n","sub_path":"bleak/backends/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209498887","text":"# -*- coding: utf-8 -*-\n# sample dialog\n\nimport wx\nimport globalVars\nimport views.ViewCreator\nfrom logging import getLogger\nfrom views.baseDialog import *\n\nclass Dialog(BaseDialog):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.result = \"\"\n\n\tdef Initialize(self):\n\t\tself.identifier=\"converted result dialog\"#このビューを表す文字列\n\t\tself.log=getLogger(self.identifier)\n\t\tself.log.debug(\"created\")\n\t\tsuper().Initialize(self.app.hMainView.hFrame,_(\"認識結果\"))\n\t\tself.InstallControls()\n\t\treturn True\n\n\tdef InstallControls(self):\n\t\t\"\"\"いろんなwidgetを設置する。\"\"\"\n\t\tself.creator=views.ViewCreator.ViewCreator(self.viewMode,self.panel,self.sizer,wx.VERTICAL,20)\n\t\tself.resultView,static = self.creator.inputbox(\"認識結果\", x=800,defaultValue=self.result, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP)\n\t\tself.bOk=self.creator.okbutton(_(\"OK\"), None)\n\n\tdef Destroy(self, events = None):\n\t\tself.log.debug(\"destroy\")\n\t\tself.wnd.Destroy()\n\n\t#def GetData(self):\n\t#\treturn self.iText.GetLineText(0)\n","sub_path":"views/converted.py","file_name":"converted.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551451244","text":"import re\r\nimport os\r\nimport glob\r\nimport docx\r\n\r\ntarget = \"*.txt\"\r\n\r\ndef header_footer(document, testname):\r\n section = document.sections[0]\r\n header = section.header\r\n heading = header.paragraphs[0]\r\n heading.text = testname + \"\\t\\tName:_______________________\"\r\n \r\n footer = section.footer\r\n footing = footer.paragraphs[0]\r\n run = footing.add_run()\r\n run.font.size = docx.shared.Pt(8)\r\n footing.text = \"\\tCopyright ©2020 Cyber Innovation Center\\n\\tAll Rights Reserved. Not for Distribution.\"\r\n \r\ndef question(document, ques_number, ques_text, answers, correct):\r\n text = str(ques_number)+ \". \" + ques_text\r\n para = document.add_paragraph(text)\r\n \r\n tab_stops = para.paragraph_format.tab_stops\r\n tab_stops.add_tab_stop(docx.shared.Inches(0.5))\r\n answer_counter = 65\r\n for answer in answers:\r\n answer_text = \"\\n\\t\"+chr(answer_counter)+\". \"+answer\r\n para.add_run(answer_text)\r\n answer_counter += 1\r\n \r\n #correct:\r\n if (len(correct) > 1):\r\n correct = \",\".join(correct)\r\n para.add_run(\"\\n\\nAnswer: \"+correct.upper())\r\n else:\r\n para.add_run(\"\\n\\nAnswer: \"+correct[0].upper())\r\n\r\n#-------------------------------------------------------------------------------\r\n\r\nfor filename_orig in glob.glob(target):\r\n file_orig = open(filename_orig, \"r+\", encoding=\"utf8\", errors=\"ignore\")\r\n filename_new = re.sub(r\"(\\d+\\.\\d+\\.\\d+|Appendix [A-Z])\",r\"\\1 - key\", filename_orig)\r\n filename_new = re.sub(r\".txt\",r\".docx\", filename_new)\r\n testname = re.sub(r\"(\\d+\\.\\d+\\.\\d+) - \",\"\", filename_orig)\r\n testname = re.sub(\" - Key\", \"\", testname)\r\n testname = re.sub(\".txt\", \"\", testname)\r\n #print(filename_new)\r\n \r\n #DOCUMENT SETUP\r\n document = docx.Document()\r\n font = document.styles['Normal'].font\r\n font.name = \"Arial\"\r\n font.size = docx.shared.Pt(10)\r\n \r\n header_footer(document, testname)\r\n \r\n question_text = \"\"\r\n question_number = 1\r\n answers = []\r\n correct = []\r\n #line_num = 0\r\n \r\n for line in file_orig:\r\n #line_num+=1\r\n line = line.strip()\r\n try:\r\n line = line.encode('ascii','ignore').decode()\r\n except:\r\n pass\r\n #print(line_num, line)\r\n if re.match(\"^True\", line):\r\n answers.append(\"True\")\r\n continue\r\n if re.match(\"^False\", line):\r\n answers.append(\"False\")\r\n continue\r\n if re.match(\"^\\*True\", line):\r\n answers.append(\"True\")\r\n correct.append(\"A\")\r\n continue\r\n if re.match(\"^\\*False\", line):\r\n answers.append(\"False\")\r\n correct.append(\"B\")\r\n continue\r\n if re.match(\"^\\*[A-Za-z]{1}\", line):\r\n option = re.split(\"\\)|\\.|\\ \", line, 1)\r\n #print(option)\r\n answers.append(str(option[1].strip()))\r\n correct.append( str(re.sub(\"\\*\",\"\", option[0])) )\r\n continue\r\n if re.match(\"^[A-Za-z]{1}\", line):\r\n option = re.split(\"\\)|\\.|\\ \", line, 1)\r\n #print(option)\r\n answers.append(str(option[1].strip()))\r\n continue\r\n #QUESTION TEXT\r\n if re.match(\"^[0-9]\", line):\r\n text = line.split(\". \", 1)\r\n question_text = str(text[1])\r\n #print(text[1])\r\n continue\r\n if re.match(\"\", line):\r\n #print(\"#\"+ str(question_number) +\": \", question_text,\"\\n\", answers,\"\\n\", correct)\r\n #XML output\r\n if (len(question_text)>0) and (len(answers)>0) and (len(correct)>0):\r\n question(document, str(question_number), question_text, answers, correct)\r\n question_number += 1\r\n question_text = \"\"\r\n answers = []\r\n correct = []\r\n #print(\"---\")\r\n \r\n document.save(filename_new)\r\n print(filename_new , \"created\")\r\n \r\n file_orig.close()\r\n print(\"\\n\")","sub_path":"create-key.py","file_name":"create-key.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"58949194","text":"# _*_ coding: utf-8 _*_\nfrom Tkinter import*\n\nmaster = Tk() # 创建一个根窗口\nscrollbar = Scrollbar(master, orient = VERTICAL) # 创建垂直方向滚动条,注意第一个参数\nlistbox = Listbox(master, yscrollcommand = scrollbar.set) # 创建带有y轴控制的滚动条\n\n\nfor item in range(0,5): # 输出列表元素,与本次任务吻合\n\tlistbox.insert(END, item) \n\n\nscrollbar.config(command = listbox.yview) # 让滚动条在y轴上滚动\nscrollbar.pack(side = RIGHT, fill = Y) # 将滚动条设置在右边\nlistbox.pack(side=LEFT,fill = BOTH, expand = 1) # 让文本框内容显示在左边\n\nmainloop() # 消息循环,记得要输入\n","sub_path":"_src/om2py2w/2wex0/scrollbar.py","file_name":"scrollbar.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"444837974","text":"def collatz(number):\n number = int(number)\n while number != 1: \n if number % 2 == 0:\n return number / 2 \n else:\n return 3 * number + 1\n\nfor i in range(6):\n n = input(\"Number: \")\n print(collatz(n))\n","sub_path":"ATBS/collatz.py","file_name":"collatz.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"144172246","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 27 12:16:26 2017\n\n@author: Anand A Joshi, Divya Varadarajan\n\"\"\"\n\nimport glob\nfrom os import system\nfrom os.path import isfile\nfrom multiprocessing import Pool\nfrom contextlib import closing\nimport configparser\nimport sys\n\nconfig_file = '/big_disk/ajoshi/ABIDE2.old/study.cfg'\n\nConfig = configparser.ConfigParser()\nConfig.read(config_file)\nConfig.sections()\n\nSTUDY_DIR = Config.get('CSESVREG', 'STUDY_DIR')\nNPROC = int(Config.get('CSESVREG', 'NPROC'))\n\nBST_INSTALL = Config.get('CSESVREG', 'BST_INSTALL')\nSVREG_ATLAS = Config.get('CSESVREG', 'SVREG_ATLAS')\nSVREG_FLAGS = Config.get('CSESVREG', 'SVREG_FLAGS')\n\nCSE_EXE = Config.get('CSESVREG', 'CSE_EXE')\nSVREG_EXE = Config.get('CSESVREG', 'SVREG_EXE')\n\nsublist = lst = glob.glob(STUDY_DIR+'/*')\n\n\nind = 0\ncmdln1 = []\ncmdln2 = []\nfor sub in sublist:\n\n img = sub + '/anat/t1.nii.gz'\n# print img\n if not isfile(img):\n continue\n\n# Compose commands for CSE and SVReg\n\n imgpial = sub + '/anat/t1.right.pial.cortex.dfs'\n imgstats = sub + '/anat/t1.roiwise.stats.txt'\n\n # Check if the workflow has already been run\n if not isfile(imgpial): \n cmdln1.append(CSE_EXE + ' ' + img)\n \n if not isfile(imgstats): \n cmdln2.append(SVREG_EXE + ' ' + img[:-7] + ' ' + SVREG_ATLAS + ' ' +\n SVREG_FLAGS)\n ind += 1\n\n# Run CSE\nwith closing(Pool(NPROC)) as p:\n print(cmdln1)\n p.map(system, cmdln1)\n p.terminate()\n\n# Run SVReg\nwith closing(Pool(NPROC)) as p:\n p.map(system, cmdln2)\n print(cmdln2)\n p.terminate()\n\nprint(\"Surface extractions and SVReg done\")\n","sub_path":"process_T1.py","file_name":"process_T1.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"540212235","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom tensorflow.keras.preprocessing import image\nimport os\nimport glob\nimport PIL\n\n#PIL.Image.MAX_IMAGE_PIXELS = 933120000\nimages = \"F:/Datasets/DigestPath/mask_npy\"\noutfolder = \"F:/Datasets/DigestPath/masks\"\n\npaths = glob.glob(os.path.join(images,\"*.npy\"))\n\nif not os.path.exists(outfolder):\n os.makedirs(outfolder)\nws = []\nhs = []\n\ndef extract_image(path):\n imname = os.path.split(path)[1]\n imname = imname.split(\".\")[0]+\".png\"\n image = np.load(path)\n print(image.shape)\n w,h = image.shape\n matplotlib.image.imsave(os.path.join(outfolder,imname), image)\n ws.append(w)\n hs.append(h)\n\nfor path in paths:\n if(\"neg\" in path):\n print(path)\n extract_image(path)","sub_path":"DigestPath/collect_image_data.py","file_name":"collect_image_data.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"77004632","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n'''\nIn the previous exercise we saved information about famous scientists’ names and birthdays to disk.\nIn this exercise, load that JSON file from disk, extract the months of all the birthdays, \nand count how many scientists have a birthday in each month.\n'''\n\nimport json\nfrom collections import Counter\n\n#define json contents\nbirthdays = {\n \"Albert Einstein\": \"14/03/1879\",\n \"Stephen Hawking\": \"08/01/1942\",\n \"Isaac Newton\": \"04/01/1643\",\n \"Galileo Galilei\": \"15/02/1564\"\n}\n\n#write json file to disk\nwith open(\"info.json\", \"w\") as f:\n json.dump(birthdays, f)\n\n# open json file and read dictionary items\nwith open(\"info.json\", \"r\") as f:\n info = json.load(f)\n # put dictionary values in a list to be able to slice only month references\n c = list(info.values())\n # create empty list for all month references\n month_list = []\n # define for loop to append all month references to list\n for i in c:\n month_list.append(i[3:5])\n # count all instances of separate months with Counter() function\n c = Counter(month_list)\n # print how many scientists have their birthday in a given month using values of c\n print(\"There are {} scientists with a birthday in January, {} in February and {} in March\".format(c[\"01\"], c[\"02\"], c[\"03\"]))\n\n","sub_path":"practice python exercise 35.py","file_name":"practice python exercise 35.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"478245063","text":"\"\"\"\n This file captures all the map logic and representation.\n\"\"\"\nimport numpy as np\nfrom collections import defaultdict\nfrom gridenvs.utils import Point, Direction\n\ncheck_collision = {\n #direction is taken from the point of reference of the first parameter (e.g. second parameter is South/North/... of first parameter)\n #direction = None checks superposition\n None: lambda obj_bb, other_bb: obj_bb[0].x < other_bb[1].x and obj_bb[1].x > other_bb[0].x and obj_bb[0].y < other_bb[1].y and obj_bb[1].y > other_bb[0].y,\n Direction.N: lambda obj_bb, other_bb: obj_bb[0].y == other_bb[1].y and obj_bb[0].x < other_bb[1].x and obj_bb[1].x > other_bb[0].x,\n Direction.S: lambda obj_bb, other_bb: obj_bb[1].y == other_bb[0].y and obj_bb[0].x < other_bb[1].x and obj_bb[1].x > other_bb[0].x,\n Direction.E: lambda obj_bb, other_bb: obj_bb[1].x == other_bb[0].x and obj_bb[0].y < other_bb[1].y and obj_bb[1].y > other_bb[0].y,\n Direction.W: lambda obj_bb, other_bb: obj_bb[0].x == other_bb[1].x and obj_bb[0].y < other_bb[1].y and obj_bb[1].y > other_bb[0].y,\n Direction.NE: lambda obj_bb, other_bb: obj_bb[0].y <= other_bb[1].y and obj_bb[1].x >= other_bb[0].x and obj_bb[0].y > other_bb[0].y and obj_bb[1].x < other_bb[1].x,\n Direction.SE: lambda obj_bb, other_bb: obj_bb[1].y >= other_bb[0].y and obj_bb[1].x >= other_bb[0].x and obj_bb[1].y < other_bb[1].y and obj_bb[1].x < other_bb[1].x,\n Direction.NW: lambda obj_bb, other_bb: obj_bb[0].y <= other_bb[1].y and obj_bb[0].x <= other_bb[1].x and obj_bb[0].y > other_bb[0].y and obj_bb[0].x > other_bb[0].x,\n Direction.SW: lambda obj_bb, other_bb: obj_bb[1].y >= other_bb[0].y and obj_bb[0].x <= other_bb[1].x and obj_bb[1].y < other_bb[1].y and obj_bb[0].x > other_bb[0].x,\n}\n\nclass GridObject:\n def __init__(self, name, pos, rgb=(255,0,0), render_preference=0):\n \"\"\"\n :param name:\n :param pos: (x, y)\n :param rgb: (r, g, b) 0 to 255\n :param render_preference: Bigger number will be rendered latter than others\n \"\"\"\n\n self.pos = Point(pos)\n self.rgb = rgb\n self.name = name\n self.render_preference = render_preference\n\n @property\n def bounding_box(self):\n return (self.pos, self.pos+1)\n\n def collides_with(self, other, direction=None):\n return other is not self and check_collision[direction](self.bounding_box, other.bounding_box)\n\n def render_rgb(self, grid):\n grid[self.pos.y][self.pos.x] = self.rgb\n return grid\n\n def render_rgb_hex(self, grid):\n grid[self.pos.y][self.pos.x] = rgb_to_hex(self.rgb)\n return grid\n\n def render_char(self, grid):\n grid[self.pos.y][self.pos.x] = self.name[0].capitalize()\n return grid\n\nclass GridObjectGroup(GridObject):\n def __init__(self, name, objects, pos, render_preference=0):\n \"\"\"\n It takes a list of objects and groups them together. The position of the group object is given by the pos\n parameter. The positions of all objects of the groupneed to be relative to this position: e.g. if group obj has\n position (1,3), an object of this group with position (2,4) will be rendered at grid position (3,7). Render\n preferences of objects of a group will only be taken into account if two objects are at the same position.\n :param name:\n :param objects:\n :param pos:\n :param render_preference:\n \"\"\"\n self.pos = Point(pos)\n self.name = name\n self.objects = objects\n self.render_preference = render_preference\n self.compute_bounding_box()\n\n def compute_bounding_box(self):\n self._bb_min = Point(self.objects[0].pos)\n self._bb_max = Point(self.objects[0].pos)\n for obj in self.objects[1:]:\n if obj.pos.x > self._bb_max.x:\n self._bb_max.x = obj.pos.x\n if obj.pos.x < self._bb_min.x:\n self._bb_min.x = obj.pos.x\n if obj.pos.y > self._bb_max.y:\n self._bb_max.y = obj.pos.y\n if obj.pos.y < self._bb_min.y:\n self._bb_min.y = obj.pos.y\n\n @property\n def bounding_box(self):\n return (self._bb_min + self.pos, self._bb_max + self.pos + 1)\n\n #TODO: be able to move objects of the group (recompute bounding box)\n\n def render_rgb(self, grid):\n for obj in get_render_ordered_objects(self.objects):\n grid[self.pos.y + obj.pos.y][self.pos.x + obj.pos.x] = obj.rgb\n return grid\n\n def render_rgb_hex(self, grid):\n for obj in get_render_ordered_objects(self.objects):\n grid[self.pos.y + obj.pos.y][self.pos.x + obj.pos.x] = rgb_to_hex(obj.rgb)\n return grid\n\n def render_char(self, grid):\n for obj in get_render_ordered_objects(self.objects):\n grid[self.pos.y + obj.pos.y][self.pos.x + obj.pos.x] = obj.name[0].capitalize()\n return grid\n\ndef rgb_to_hex(rgb):\n return \"0x\" + hex(rgb[0])[2:].zfill(2) + hex(rgb[1])[2:].zfill(2) + hex(rgb[2])[2:].zfill(2)\n\ndef get_render_ordered_objects(objects):\n return sorted(objects, key=lambda a: a.render_preference)\n\nclass GridWorld:\n def __init__(self, grid_size):\n try:\n size_x, size_y = grid_size\n except TypeError:\n size_x = size_y = grid_size\n self.grid_size = Point(size_x, size_y)\n self.reset()\n\n def get_colors(self):\n grid = np.array([[\"0x000000\"] * self.grid_size.y] * self.grid_size.x)\n for obj in self.objects:\n obj.render_rgb_hex(grid)\n return grid\n\n def get_char_matrix(self):\n grid = np.array([['·'] * self.grid_size.y] * self.grid_size.x)\n for obj in self.objects:\n obj.render_char(grid)\n return grid\n\n def __str__(self):\n return \"\\n\".join([\" \".join(row) for row in self.get_char_matrix()])\n\n def __repr__(self):\n return self.__str__()\n\n def add_object(self, game_object):\n \"\"\"\n :return: reference to object\n \"\"\"\n self.objects.append(game_object)\n return game_object\n\n def remove_object(self, obj):\n self.objects.remove(obj)\n\n def reset(self):\n self.objects = []\n\n def get_objects_by_position(self):\n res = defaultdict(list)\n for obj in self.objects:\n res[obj.pos].append(obj)\n return dict(res)\n\n def get_objects_by_names(self, name_or_names, objects=None):\n \"\"\"\n :param names: Single name or list / tuple\n :return:\n \"\"\"\n if objects is None:\n objects = self.objects\n if type(name_or_names) is str:\n name_or_names = (name_or_names,)\n return [o for o in objects if o.name in name_or_names]\n\n def collisions(self, obj:GridObject, direction=None, objects=None, return_names=False):\n \"\"\"\n\n :param obj:\n :param direction: None (check superposition of objects) or Direction\n :param objects: None (all objects) or iterable of GridObjects or their names (strings)\n :return: list of objects that are neighbors with obj at the specified direction\n \"\"\"\n if objects is None:\n objects = self.objects # With all objects\n\n neighbor_objs = []\n if len(objects) > 0:\n if type(objects[0]) is str:\n objects = self.get_objects_by_names(objects, self.objects)\n for other in objects:\n if obj.collides_with(other, direction):\n neighbor_objs.append(other)\n\n if return_names:\n neighbor_objs = list(set([obj.name for obj in neighbor_objs]))\n return neighbor_objs\n\n def all_collisions(self, obj:GridObject, objects=None, return_names=False):\n if objects is None:\n objects = self.objects # With all objects\n\n neighbor_objs = dict([(d, []) for d in Direction.all() + [None]])\n if len(objects) > 0:\n if type(objects[0]) is str:\n objects = self.get_objects_by_names(objects, self.objects)\n\n for direction in Direction.all()+[None]:\n for other in objects:\n if obj.collides_with(other, direction):\n neighbor_objs[direction].append(other)\n\n if return_names:\n for d in neighbor_objs.keys():\n neighbor_objs[d] = list(set([obj.name for obj in neighbor_objs[d]]))\n return neighbor_objs\n\n def render(self):\n grid = np.zeros([self.grid_size.y, self.grid_size.x, 3], dtype=np.uint8)\n for obj in get_render_ordered_objects(self.objects):\n grid = obj.render_rgb(grid)\n return grid\n","sub_path":"gridenvs/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":8659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"46416193","text":"import fitsio as fi\nimport treecorr\nimport numpy as np\nimport os\nimport argparse\nimport yaml\nfrom halotools_ia.correlation_functions import ii_plus_projected\n\nperiod={'massiveblackii':100, 'illustris':75}\ncolour_split_params = {99 : (0.045, 1.84), 78: (0.045, 1.84), 62: (0.055, 1.95), 50: (0.022, 1.19)}\n\nauto=True\n\ndef compute(options, binning, snapshot, ijk):\n\n\n\tshapefile = options['shapes'].replace(r'${SNAPSHOT}', '%d'%snapshot)\n\n\tprint('Shape data : %s'%shapefile)\n\n\tshapes = fi.FITS(shapefile)[-1].read()\n\tsplit_type, shapes = split_catalogue(shapes, options, snapshot, 1)\n\n\tif auto:\n\t\tshapes2 = shapes\n\t\tsplit_type2 = split_type\n\telse:\n\t\tshapes2 = fi.FITS(shapefile)[-1].read()\n\t\tsplit_type2, shapes2 = split_catalogue(shapes2, options, snapshot, 0)\n\t\tprint('Warning: using hacked cross correlation mode')\n\n\tif (ijk>-1):\n\t\tsmask = get_jk_mask(ijk, options['njk'], options['box_size'], shapes)\n\telse:\n\t\tsmask = np.ones(shapes.size).astype(bool)\n\n\n\tif ('use_weights' in options):\n\t\tif options['use_weights']:\n\n\t\t\tprint('Applying weights from file:')\n\t\t\tbase = os.path.dirname(shapefile.replace('/fits/','/txt/') )\n\t\t\tsim, s, _, _, _ = os.path.basename(shapefile).split('_')\n\t\t\tweightsfile = base + '/%s_%s_weights.dat'%(sim,s)\n\t\t\tprint(weightsfile)\n\n\t\t\twts1 = np.loadtxt(weightsfile)\n\t\t\twts2 = np.loadtxt(weightsfile)\n\t\t\twts1/=np.sum(wts1)\n\t\t\twts1 *= len(wts1)\n\t\t\twts2/=np.sum(wts2)\n\t\t\twts2 *= len(wts2)\n\t\t\tapply_weights = True\n\t\telse:\n\t\t\tapply_weights = False\n\telse:\n\t\tapply_weights = False\n\n\tif (not apply_weights):\n\t\twts1 = np.ones_like(shapes2['x'])\n\t\twts2 = np.ones_like(shapes['x'])\n\t\tapply_weights=False\n\n\n\trpbins = np.logspace(np.log10(options['rlim'][0]), np.log10(options['rlim'][1]), binning+1)\n\n\tprint('Setting up correlations')\n\n\t# don't need randoms here if we know the period of the box\n\tprint('Computing correlation functions.')\n\t#import pdb ; pdb.set_trace()\n\n\tc0c0 = compute_ii(shapes[smask], shapes2, options, rpbins=rpbins, period=options['box_size'], nbins=binning, weights1=wts1, weights2=wts2[smask])\n\n\tfilename = '%s/wpp_%d%s%s.txt'%(options['savedir'],snapshot,split_type2,split_type)\n\tif (ijk>-1):\n\t\tfilename = filename.replace('.txt', '-jk%d.txt'%ijk)\n\n\tif os.path.exists(filename):\n\t\tprint('file exists: %s'%filename)\n\t\treturn None\n\n\texport_array(filename, rpbins, c0c0)\n\t\t\n\tprint('Done')\n\n\n\ndef compute_ii(cat1, cat2, options, period=100., rpbins=None, nbins=6, weights1=None, weights2=None):\n\n\taname = 'av_%c'\n\tename = 'e%d'\n\n\tavec1 = np.vstack((cat1[aname%'x'], cat1[aname%'y'])).T\n\tavec2 = np.vstack((cat2[aname%'x'], cat2[aname%'y'])).T\n\tpvec1 = np.vstack((cat1['x'], cat1['y'], cat1['z'])).T\n\tpvec2 = np.vstack((cat2['x'], cat2['y'], cat2['z'])).T\n\tevec1 = np.sqrt(cat1[ename%1]*cat1[ename%1] + cat1[ename%2]*cat1[ename%2])\n\tevec2 = np.sqrt(cat2[ename%1]*cat2[ename%1] + cat2[ename%2]*cat2[ename%2])\n\n\t\n\trpbins = np.logspace(np.log10(options['rlim'][0]), np.log10(options['rlim'][1]), nbins+1)\n\t\n\tpi_max = options['rlim'][1]\n\n\tmask1=avec1.T[0]!=0.0\n\tmask2=avec2.T[0]!=0.0\n\n\tii = ii_plus_projected(pvec2[mask2], avec2[mask2], evec2[mask2], pvec1[mask1], avec1[mask1], evec1[mask1], rpbins, pi_max, period=period, num_threads=1, weights1=weights1[mask1], weights2=weights2[mask2]) \n\n\treturn ii\n\ndef export_array(path, edges, result):\n\tx = np.sqrt(edges[:-1]*edges[1:])\n\tout = np.vstack((x, result))\n\tprint('Exporting to %s'%path)\n\tnp.savetxt(path, out.T)\n\n\n\ndef get_jk_mask(ijk, njk, box_size, catalogue):\n\tj = 0\n\tlabels = np.zeros_like(catalogue['x'])\n\tpatch_size = box_size/njk\n\n\tfor ix in range(njk):\n\t\txmask = (catalogue['x'] >= patch_size*ix) & (catalogue['x'] < patch_size*(ix+1)) \n\t\tfor iy in range(njk):\n\t\t\tymask = (catalogue['y'] >= patch_size*iy) & (catalogue['y'] < patch_size*(iy+1)) \n\t\t\tfor iz in range(njk):\n\t\t\t\tzmask = (catalogue['z'] >= patch_size*iz) & (catalogue['z'] < patch_size*(iz+1)) \n\t\t\t\tmask_tot = xmask & ymask & zmask\n\t\t\t\tlabels[mask_tot] = j\n\t\t\t\tj+=1\n\n\tmask = (labels!=ijk)\n\tprint('mask excludes %d/%d'%(labels[np.invert(mask)].size, labels.size))\n\n\treturn mask\n\ndef split_catalogue(cat, options, snapshot, i):\n\n\tif (not ('split_type' in options.keys())):\n\t\treturn '', cat\n\telse:\n\t\ts = options['split_type'].split()[i]\n\n\tif (s=='central'):\n\t\tmask = (cat['gal_id']==cat['central_id'])\n\telif (s=='satellite'):\n\t\tmask = np.invert(cat['gal_id']==cat['central_id'])\n\n\telif (s=='stellar_mass_high'):\n\t\tMs = np.median(cat['stellar_mass_all'])\n\t\tmask = (cat['stellar_mass_all']>=Ms)\n\n\telif (s=='stellar_mass_low'):\n\t\tMs = np.median(cat['stellar_mass_all'])\n\t\tmask = (cat['stellar_mass_all']=(m0*cat['rmag']+c0))\n\telif (s=='blue'):\n\t\tm0,c0 = colour_split_params[snapshot]\n\t\tgi = cat['gmag']-cat['imag']\n\t\tmask = (gi<(m0*cat['rmag']+c0))\n\n\n\telif (s=='high_mass_red'):\n\t\tm0,c0 = colour_split_params[snapshot]\n\t\tgi = cat['gmag']-cat['imag']\n\t\tMs = np.median(cat['stellar_mass_all'])\n\t\tmask = (gi>=(m0*cat['rmag']+c0)) & (cat['stellar_mass_all']>=Ms)\n\telif (s=='high_mass_blue'):\n\t\tm0,c0 = colour_split_params[snapshot]\n\t\tgi = cat['gmag']-cat['imag']\n\t\tMs = np.median(cat['stellar_mass_all'])\n\t\tmask = (gi<(m0*cat['rmag']+c0)) & (cat['stellar_mass_all']>=Ms)\n\n\telif (s=='low_mass_red'):\n\t\tm0,c0 = colour_split_params[snapshot]\n\t\tgi = cat['gmag']-cat['imag']\n\t\tMs = np.median(cat['stellar_mass_all'])\n\t\tmask = (gi>=(m0*cat['rmag']+c0)) & (cat['stellar_mass_all']=edges[3])\n\n\t\tmask = bmask & imask\n\n\t\tprint('rmag=%2.3f'%cat['rmag'][mask].mean())\n\n\telif (s=='blue1'):\n\t\tm0,c0 = colour_split_params[snapshot]\n\t\tgi = cat['gmag']-cat['imag']\n\t\t#import pdb ; pdb.set_trace()\n\t\tbmask = (gi<(m0*cat['rmag']+c0))\n\n\t\tedges = find_bin_edges(cat['imag'][bmask],4)\n\t\timask = (cat['imag']>=edges[2]) & (cat['imag']=edges[1]) & (cat['imag']=edges[0]) & (cat['imag']ww:\n r[j]=x[i[l]]\n ist=l\n break\n else:\n for l in xrange(k[j],0,-1):\n w0-=w[i[l]]\n if w0ww:\n r[j]=x[i[k-1]]\n ist[j]=k\n break\n\n r[0]=x[i[0]]\n r[-1]=x[i[-1]]\n\n return r","sub_path":"src/twopoint/calculate_wpp.py","file_name":"calculate_wpp.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"74927871","text":"import xlrd, re\n\n\n# 读取excel表格,并转化成json格式\n# data_json = ReadExcel(r\".\\***.xls\", \"Page1\").read_excel()\nclass ReadExcel:\n\n def __init__(self, fileName, sheetName):\n \"\"\"\n new_data是最后返回的值\n :param fileName: excel文件名,sheet名称\n :param sheetName:\n \"\"\"\n self.fileName = fileName\n self.sheetName = sheetName\n # 读取excel\n self.book = xlrd.open_workbook(self.fileName)\n self.sheet0 = self.book.sheet_by_name(self.sheetName)\n # 获取第一列数据\n self.col_value = self.sheet0.col_values(0) # 第一列\n self.new_data = {}\n\n def data_type(self, test_type, test_value):\n \"\"\"\n 判断从excel单元格中获取的数据类型\n 1 string(text), 2 number, 3 date, 4 boolean\n :param test_type: 类型\n :param test_value: 值\n :return:\n \"\"\"\n if test_type == 1:\n \"\"\"字符串\"\"\"\n return test_value\n\n elif test_type == 2:\n if '.0' in str(test_value):\n \"\"\"整数\"\"\"\n return int(test_value)\n else:\n \"\"\"浮点\"\"\"\n return test_value\n\n elif test_type == 3:\n \"\"\"日期\"\"\"\n date = xlrd.xldate_as_datetime(test_value, 0).strftime('%Y-%m-%d')\n return date\n\n elif test_type == 4:\n \"\"\"布尔类型\"\"\"\n if test_value == 1:\n return True\n elif test_value == 0:\n return False\n\n def write_list(self, value):\n \"\"\"\n 取出某一行的值,将其写入一个新的字典\n :param value: self.col_value.index 是一个列表(第一列的值),self.col_value.index(value)是判断value这个值是在列表中的第几位\n :return: 新建的字典\n \"\"\"\n test_data = {}\n for j in range(1, self.sheet0.ncols):\n test_type = self.sheet0.cell_type(self.col_value.index(value), j) # 单元格数据类型\n test_value = self.sheet0.cell_value(self.col_value.index(value), j) # 单元格数据值\n result = self.data_type(test_type, test_value)\n test_data[self.sheet0.row_values(0)[j]] = result\n return test_data\n\n def read_excel(self):\n \"\"\"\n 读取excel表中数据\n :return: 字典格式\n \"\"\"\n # 遍历将相同类型的用例分在一起\n for i in self.col_value[1:]:\n m = re.findall(\"_\\d+_\", i) # 按照固定格式匹配,用于判断用例是否是相同的类型\n if len(m) == 0:\n test_data = self.write_list(i)\n self.new_data[i] = test_data\n else:\n n = re.findall(\"(.+_\\d+?)_\\d+\", i)[-1] # 按照固定格式匹配,提取相同的字符\n if n not in self.new_data.keys():\n test_data = self.write_list(i)\n self.new_data[n] = [test_data]\n else:\n test_data = self.write_list(i)\n self.new_data[n].append(test_data)\n return self.new_data","sub_path":"Coupons/Automatically-grab-coupons/application_one/ReadExcel.py","file_name":"ReadExcel.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"497191220","text":"from typing import Dict, List\n\nimport yaml\n\n\ndef _convert_covenant_to_empire(covenant_dict: Dict, file_path: str):\n empire_yaml = {\n \"name\": covenant_dict[\"Name\"],\n \"authors\": _convert_convenant_authors_to_empire([covenant_dict[\"Author\"]]),\n \"description\": covenant_dict[\"Description\"],\n \"language\": covenant_dict[\"Language\"].lower(),\n \"compatible_dot_net_versions\": covenant_dict[\"CompatibleDotNetVersions\"],\n \"script\": covenant_dict[\"Code\"],\n \"options\": _convert_covenant_options_to_empire(\n covenant_dict[\"Options\"],\n covenant_dict.get(\"Empire\", {}).get(\"options\", []),\n covenant_dict[\"CompatibleDotNetVersions\"],\n ),\n \"compiler_yaml\": yaml.dump([covenant_dict], sort_keys=False),\n }\n\n if \"advanced\" in covenant_dict.get(\"Empire\", {}):\n empire_yaml[\"advanced\"] = covenant_dict[\"Empire\"][\"advanced\"]\n\n return empire_yaml\n\n\ndef _convert_convenant_authors_to_empire(covenant_authors: List[Dict]):\n empire_authors = []\n for author in covenant_authors:\n empire_authors.append(\n {\n \"handle\": author[\"Handle\"],\n \"name\": author[\"Name\"],\n \"link\": author[\"Link\"],\n }\n )\n return empire_authors\n\n\ndef _convert_covenant_options_to_empire(\n covenant_options: List[Dict],\n empire_options: List[Dict],\n compatible_versions: List[str],\n):\n empire_options.append(\n {\n \"name\": \"Agent\",\n \"value\": \"\",\n \"description\": \"Agent to run module on.\",\n \"required\": True,\n \"suggested_values\": [],\n }\n )\n empire_options.append(\n {\n \"name\": \"DotNetVersion\",\n \"value\": compatible_versions[0],\n \"description\": \".NET version to compile against\",\n \"required\": True,\n \"suggested_values\": compatible_versions,\n \"strict\": True,\n }\n )\n\n for option in covenant_options:\n empire_options.append(\n {\n \"name\": option[\"Name\"],\n \"value\": option[\"Value\"],\n \"description\": option[\"Description\"],\n \"required\": not option[\"Optional\"],\n \"suggested_values\": option[\"SuggestedValues\"],\n }\n )\n\n return empire_options\n","sub_path":"empire/server/common/converter/load_covenant.py","file_name":"load_covenant.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"498635230","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport subprocess\n\nfrom lib import ansible\n\n\ndef run_cmd(cmds):\n print(' '.join(cmds))\n os.environ['ANSIBLE_FORCE_COLOR'] = '1'\n proc = subprocess.Popen(\n cmds,\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,)\n while True:\n line = proc.stdout.readline()\n if not line:\n break\n print(line.rstrip())\n proc.wait()\n return proc.returncode\n\n\ndef ansible_playbook(hosts_f, playbook_f):\n cmd = [\"ansible-playbook\", \"-e\", \"ANSIBLE_HOST_KEY_CHECKING=False\",\n \"-i\", hosts_f, playbook_f]\n return run_cmd(cmd)\n\n\ndef start(config_file):\n root = os.path.dirname(os.path.realpath(__file__))\n config = ansible.load_config(config_file)\n playbook_f = os.path.join( root, \"onecloud/zz_generated.site.yml\")\n hosts_f = os.path.join(root, \"onecloud/zz_generated.hosts\")\n config.generate_hosts_file(hosts_f)\n config.generate_site_file(playbook_f)\n returncode = ansible_playbook(hosts_f, playbook_f)\n if returncode is not None and returncode != 0:\n return returncode\n login_info = config.get_login_info()\n if login_info is None:\n return 0\n print(\"\"\"Initialized successfully!\nWeb page: https://%s\nUser: %s\nPassword: %s\n\"\"\" % (login_info[0], login_info[1], login_info[2])\n)\n return 0\n\n\ndef show_usage():\n usage = '''\nUsage: %s .yml\n''' % __file__\n print(usage)\n\n\ndef main():\n if len(sys.argv) != 2:\n show_usage()\n sys.exit(1)\n return start(sys.argv[1])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100941866","text":"# in fact + adds an image / adds a new row or a new col in fact --> good idea\n# should I have two figs --> one horiz and one vertical does that make sense and is that useful ??? think about it\n\n#https://docs.python.org/2/library/operator.html\n\n# TODO try remove row if possible to only handle panels\n# in a way a figure can be a panel of panels --> if so the I would just have one element --> in fact that would really simplify things like crazy\n# pas mal mais du coup faudrait pas packer par defaut ou bien si sauf si l'utilisateur veut pas\n# peut être plus flexible --> supress fig and row just keep panel and make it more flexible\n# faire un stacker(horizontal or vertical)\n# that may work in a way\n# seule difference est que le panel ne doit contenir que des images de même taille alors que la row non mais en gros la row est un panel de panel\n# puis je appliquer la regle des rows aux panels\n# --> j'ai besoin d'une orientation des le depart\n# est ce que ça peut marcher --> peut etre\n# should I put a warning if they don't have the same size initially --> ? think about it\n# should I have linear panel and 2D panel and give them different rules panel1D panel2D #dans panel2D ttes les images doivent avoir la meme taille. Panel1D --> c'est un peu une row en fait\n\n# panel1D --> orientation --> hor/ver\n# panel2D --> more stuff and same size required\n\nfrom epyseg.draw.shapes.image2d import Image2D\nfrom epyseg.draw.shapes.rect2d import Rect2D\nfrom PyQt5.QtCore import QPointF, QRectF\n# logger\nfrom epyseg.tools.logger import TA_logger\nlogger = TA_logger()\n\n# keep this in mind: https://stackoverflow.com/questions/34827132/changing-the-order-of-operation-for-add-mul-etc-methods-in-a-custom-c\n\n# do rows and columns and no need to take images --> they just pack horiz or vertically and that's it each image or stuff handles itslef\n# a row like that cannot be appended another row or can it --> yes in fact just add to it\n\n\n\nclass Column(Rect2D):\n\n def __init__(self, *args, space=3, height=None):\n self.images = []\n for img in args:\n # if isinstance(img, Column):\n # self.images += img.images\n # else:\n self.images.append(img)\n # init super empty\n super(Rect2D, self).__init__()\n self.isSet = True # required to allow dragging\n self.space = space\n self.sameWidth(space=space)\n self.heightInPixel = height\n self.setToHeight(height)\n\n def __or__(self, other):\n if isinstance(other, Column):\n pos = self.get_P1()\n other_pos = other.get_P1()\n self.set_P1(other_pos)\n other.set_P1(pos)\n else:\n logger.error('swapping not implemented yet for ' + str(type(other)))\n\n def __add__(self, other):\n # from epyseg.figure.panel import Panel\n if isinstance(other, Image2D):\n self.images.append(other)\n self.sameWidth(space=self.space)\n self.setToHeight(self.heightInPixel)\n # elif isinstance(other, Panel):\n # self.images.append(other)\n # self.sameHeight(space=self.space)\n # self.setToWidth(self.widthInPixel)\n elif isinstance(other, Column):\n # print(self.images)\n # print(len(self.images))\n # print(other.images)\n # print(len(other.images))\n self.images = self.images + other.images\n self.sameWidth(space=self.space)\n self.setToHeight(self.heightInPixel)\n return self\n\n def __sub__(self, other):\n if other in self.images:\n self.images.remove(other)\n self.setToHeight(self.heightInPixel)\n return self\n\n def is_empty(self):\n if self.images is None or not self.images:\n return True\n return False\n\n def __truediv__(self, other):\n from epyseg.figure.row import Row\n return Row(self, other, space= self.space)\n\n def __len__(self):\n if self.images is None:\n return 0\n return len(self.images)\n\n def setWidthInPixel(self, heightInPixel):\n self.heightInPixel = heightInPixel\n self.packY()\n\n def packX(self, space=3):\n last_x = 0\n last_y = 0\n\n for i in range(len(self.images)):\n img = self.images[i]\n if i != 0:\n last_x += space\n img.set_P1(last_x, img.get_P1().y())\n last_x = img.boundingRect().x() + img.boundingRect().width()\n\n self.updateBoudingRect()\n\n def packY(self, space=3):\n last_x = 0\n last_y = 0\n\n for i in range(len(self.images)):\n img = self.images[i]\n if i != 0:\n last_y += space\n img.set_P1(img.get_P1().x(), last_y)\n # get all the bounding boxes and pack them with desired space in between\n # get first point and last point in x\n x = img.boundingRect().x()\n y = img.boundingRect().y()\n last_x = img.boundingRect().x() + img.boundingRect().width()\n last_y = img.boundingRect().y() + img.boundingRect().height()\n self.updateBoudingRect()\n\n def updateBoudingRect(self):\n '''updates the image bounding rect depending on content'''\n x = None\n y = None\n x2 = None\n y2 = None\n for img in self:\n topLeft = img.get_P1()\n if x is None:\n x = topLeft.x()\n if y is None:\n y = topLeft.y()\n x = min(topLeft.x(), x)\n y = min(topLeft.y(), y)\n\n print(img, img.boundingRect(), type(img))\n print(img, img.boundingRect(), type(img), img.boundingRect().height())\n\n if x2 is None:\n x2 = topLeft.x() + img.boundingRect().width()\n if y2 is None:\n y2 = topLeft.y() + img.boundingRect().height()\n x2 = max(topLeft.x() + img.boundingRect().width(), x2)\n y2 = max(topLeft.y() + img.boundingRect().height(), y2)\n\n self.setX(x)\n self.setY(y)\n self.setWidth(x2 - x)\n self.setHeight(y2 - y)\n\n def setOrigin(self, *args):\n self.set_P1(*args)\n\n def set_P1(self, *args):\n curP1 = self.get_P1()\n Rect2D.set_P1(self, *args)\n newP1 = self.get_P1()\n for img in self:\n img.translate(newP1.x() - curP1.x(), newP1.y() - curP1.y())\n\n self.updateBoudingRect()\n\n def translate(self, *args):\n if len(args)==1:\n point = args[0]\n QRectF.translate(self, point.x(), point.y())\n for img in self:\n img.translate(point.x(), point.y())\n else:\n QRectF.translate(self, args[0], args[1])\n for img in self:\n img.translate(QPointF(args[0], args[1]))\n\n def draw(self, painter, draw=True):\n if draw:\n painter.save()\n if draw:\n for img in self:\n img.draw(painter, draw=draw)\n painter.restore()\n\n def fill(self, painter, draw=True):\n if self.fill_color is None:\n return\n if draw:\n painter.save()\n if draw:\n for img in self:\n img.fill(painter, draw=draw)\n painter.restore()\n\n def drawAndFill(self, painter):\n painter.save()\n self.draw(painter, draw=True)\n painter.restore()\n\n def __iter__(self):\n ''' Returns the Iterator object '''\n self._index = -1\n return self\n\n def __next__(self):\n '''' Returns the next image or panel in the row '''\n self._index += 1\n if self._index < len(self.images):\n return self.images[self._index]\n # End of Iteration\n raise StopIteration\n\n def __lshift__(self, other):\n # move image left with respect to self\n if isinstance(other, Image2D):\n # swap the position of the two images and repack\n if other in self.images:\n pos = self.images.index(other)\n if pos - 1 >= 0:\n self.images[pos-1], self.images[pos] = self.images[pos], self.images[pos-1]\n else:\n return self\n self.packX(self.space)\n return self\n else:\n logger.error('not implemented yet swapping two objects '+ str(type(other)))\n\n def __rshift__(self, other):\n # move image left with respect to self\n if isinstance(other, Image2D):\n # swap the position of the two images and repack\n if other in self.images:\n pos = self.images.index(other)\n if pos + 1 < len(self.images):\n self.images[pos + 1], self.images[pos] = self.images[pos], self.images[pos + 1]\n else:\n return self\n self.packX(self.space)\n return self\n else:\n logger.error('not implemented yet swapping two objects ' + str(type(other)))\n\n def sameWidth(self, space):\n if space is None:\n space = 0\n max_width = None\n for img in self:\n if max_width is None:\n # print('TUTU',img)\n # print('TUTA',img, img.boundingRect(), img.boundingRect().height)\n # print('TOTO',img, img.boundingRect(), img.boundingRect().height())\n max_width = img.boundingRect().width()\n max_width = max(img.boundingRect().width(), max_width)\n for img in self:\n img.setToWidth(max_width)\n\n self.packY(space)\n self.alignLeft(updateBounds=False)\n self.updateBoudingRect()\n\n #Aligns objects within the block\n def arrangeRow(self):\n self.alignLeft()\n\n # Align vectorial objects to the top\n # in fact should align in y\n def alignLeft(self, updateBounds=False):\n first_left = None\n for img in self:\n cur_pos = img.get_P1()\n if first_left is None:\n first_left = cur_pos\n img.set_P1(first_left.x(), cur_pos.y())\n if updateBounds:\n self.updateMasterRect()\n\n # Forces the block to be of width (width_in_px)\n def setToHeight(self, height_in_px):\n if height_in_px is None:\n return\n nb_cols = len(self)\n pure_image_height = (self.boundingRect().height()) - (nb_cols - 1.) * self.space - self.getIncompressibleHeight()\n # print(width_in_px, self.getIncompressibleWidth(), (nb_cols - 1.) * self.space )\n height_in_px -= self.getIncompressibleHeight() + (nb_cols - 1.) * self.space\n ratio = height_in_px / pure_image_height\n for img in self:\n img.setToHeight(img.boundingRect().height() * ratio)\n self.packY(self.space)\n self.updateBoudingRect()\n\n def setToWidth(self, width_in_px):\n if width_in_px is None:\n return\n # nb_cols = len(self)\n pure_image_width = (self.boundingRect().width()) - self.getIncompressibleHeight()\n # print(width_in_px, self.getIncompressibleWidth(), (nb_cols - 1.) * self.space )\n width_in_px -= self.getIncompressibleHeight()\n ratio = width_in_px / pure_image_width\n for img in self:\n img.setToWidth(img.boundingRect().width() * ratio)\n self.packY(self.space)\n self.updateBoudingRect()\n\n\n # @return the block incompressible width\n def getIncompressibleHeight(self):\n extra_space = 0\n return extra_space\n\nif __name__ == '__main__':\n\n img1 = Image2D('/media/D/Sample_images/sample_images_PA/trash_test_mem/counter/00.png')\n img2 = Image2D('/media/D/Sample_images/sample_images_PA/trash_test_mem/counter/01.png')\n img3 = Image2D('/media/D/Sample_images/sample_images_PA/trash_test_mem/counter/02.png')\n img4 = Image2D('/media/D/Sample_images/sample_images_PA/trash_test_mem/counter/03.png')\n result = img1 + img2\n\n print(result)\n\n","sub_path":"epyseg/figure/column.py","file_name":"column.py","file_ext":"py","file_size_in_byte":11998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"364562170","text":"# coding=utf-8\n# Copyright 2014 Foursquare Labs Inc. All Rights Reserved.\n\nfrom __future__ import (\n absolute_import,\n division,\n generators,\n nested_scopes,\n print_function,\n unicode_literals,\n with_statement,\n)\n\nfrom pants.backend.jvm.targets.java_tests import JavaTests\nfrom pants.backend.jvm.targets.scala_library import ScalaLibrary\n\nfrom fsqio.pants.buildgen.core.buildgen_task import BuildgenTask\n\n\nclass BuildgenScala(BuildgenTask):\n @classmethod\n def prepare(cls, options, round_manager):\n super(BuildgenScala, cls).prepare(options, round_manager)\n round_manager.require_data('java_source_to_exported_symbols')\n round_manager.require_data('scala')\n round_manager.require_data('scala_library_to_used_addresses')\n round_manager.require_data('scala_source_to_exported_symbols')\n round_manager.require_data('scala_source_to_used_symbols')\n\n @classmethod\n def product_types(cls):\n return [\n 'buildgen_scala',\n ]\n\n @property\n def types_operated_on(self):\n return (ScalaLibrary, JavaTests)\n\n @property\n def _scala_library_to_used_addresses(self):\n return self.context.products.get_data('scala_library_to_used_addresses')\n\n def buildgen_target(self, scala_target):\n addresses_used_by_target = set(\n self.context.build_graph.get_target(addr).concrete_derived_from.address\n for addr in self._scala_library_to_used_addresses[scala_target]\n )\n filtered_addresses_used_by_target = set(\n addr for addr in addresses_used_by_target\n if addr != scala_target.address\n )\n self.adjust_target_build_file(scala_target, filtered_addresses_used_by_target)\n","sub_path":"src/python/fsqio/pants/buildgen/jvm/scala/buildgen_scala.py","file_name":"buildgen_scala.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"222220997","text":"\"\"\"\nHere is a factory that produces toasters.\nThere are multiple machines, each with different characteristics\n\"\"\"\nfrom scipy.stats import poisson\nfrom machine import Machine\nfrom inventory import Inventory\nfrom numpy.random import choice\n\n\nclass Factory(object):\n \"\"\"\n A class to represent a factory\n \"\"\"\n SN_FORMAT = \"{:09d}\"\n\n def __init__(self, name, machines, product):\n \"\"\"\n Build a factory\n :param str name: unique name of this factory\n :param int machines: how many machines?\n :param ProductModel product: class object representing which product is produced at this factory\n \"\"\"\n self.name = name\n self.product = product\n self.machines = []\n self.purchase_machines(machines, xskew=0)\n self.inventory = Inventory()\n self._mean_production_rate = 50 # units per week per machine\n\n def purchase_machines(self, n, **fixedparams):\n \"\"\"\n Purchase n machines\n :param n: integer\n :return: None\n \"\"\"\n for _ in range(n):\n machine = Machine(\n product=self.product,\n machine_id=self.next_machine_id(),\n **fixedparams\n )\n self.machines.append(machine)\n\n def break_machine(self, machine_id=None):\n \"\"\"\n Cause a machine to break (change its distributional parameters)\n :param int machine_id: which machine broke?\n :return: None\n \"\"\"\n if machine_id is None:\n machine_id = self.rand_machine_index\n self.machines[machine_id].change_meta_params()\n\n def random_part(self):\n \"\"\"\n pick a random sample of parts part (doesn't pop)\n :return: ProductModel instance\n \"\"\"\n sn = choice(self.inventory.serial_numbers)\n return self.inventory[sn]\n\n @property\n def machine_ids(self):\n return [machine.machine_id for machine in self.machines]\n\n def next_machine_id(self):\n try:\n return max(self.machine_ids) + 1\n except ValueError:\n return 0\n\n @property\n def mean_production_rate(self):\n \"\"\"\n Mean production rate in units per week (all machines combined)\n :return:\n \"\"\"\n return self._mean_production_rate * self.n_machines # can add randomization here\n\n @property\n def n_machines(self):\n \"\"\"\n How many machines in factory?\n :return: int\n \"\"\"\n return len(self.machines)\n\n def run(self, weeks):\n \"\"\"\n Run the factory to produce desired number of units\n :param weeks: how long to run, in weeks\n :return: RunReport object\n \"\"\"\n expected_units = self.mean_production_rate * weeks\n units = poisson.rvs(expected_units)\n sn_list = self.new_sn_block(units)\n for sn in sn_list:\n m = self.rand_machine_index\n machine = self.machines[m]\n product = machine.produce(sn)\n self.inventory.add_item(product)\n\n @property\n def last_sn(self):\n \"\"\"\n Return the largest serial number in the inventory\n :return: int\n \"\"\"\n try:\n last_sn = self.inventory.serial_numbers[-1]\n return int(last_sn)\n except IndexError:\n return 0\n\n def new_sn_block(self, units):\n \"\"\"\n Supply the next batch of serial numbers\n :return:\n \"\"\"\n a = self.last_sn + 1\n sn_block = [self.SN_FORMAT.format(sn)\n for sn in range(a, a + units)]\n return sn_block\n\n @property\n def rand_machine_index(self):\n \"\"\"\n Randomly choose a machine\n :return: index of the machine chosen\n \"\"\"\n return choice(range(len(self.machines)))\n","sub_path":"factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"502309074","text":"books = []\nexist = False\n\ndef store_status(book):\n for book in books:\n exist = True\n print(\"Just noticed that there's a lot of books in there!\")\n break\n else:\n print(\"How dare they don't have any books?\")\n","sub_path":"Source/syntax_practice/iterator_with_else.py","file_name":"iterator_with_else.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"290530997","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: /Users/duranton/Documents/CERFACS/CODES/arnica/src/arnica/solvers_2d/boundary.py\n# Compiled at: 2020-03-30 05:30:51\n# Size of source mod 2**32: 7482 bytes\n\"\"\"\nContains class and functions necessary to handle boundary conditions\n\"\"\"\nimport numpy as np\nimport scipy.sparse as spsp\nfrom arnica.solvers_2d.core_fd import set_row_csr\n\nclass Boundary2d:\n __doc__ = '\\n *Class containing Boundary Condition information*\\n '\n\n def __init__(self, boundary_param):\n \"\"\"\n Constructor of boundary class\n \"\"\"\n self.boundary_params = boundary_param\n print('\\n\\t\\t Boundary2D:\\t _set_periodicity()')\n self._set_periodicity()\n\n def _set_periodicity(self):\n \"\"\"\n Set the periodicity to North/South if periodic and check for the\n consistency of the definition of the BC\n \"\"\"\n bc_n = self.boundary_params['North']['type']\n bc_w = self.boundary_params['West']['type']\n bc_s = self.boundary_params['South']['type']\n bc_e = self.boundary_params['East']['type']\n self.periodic_we = False\n self.periodic_ns = False\n if not bc_n == 'Periodic':\n if bc_s == 'Periodic':\n if bc_n == bc_s:\n self.periodic_ns = True\n else:\n raise IOError('Both \"North\" and \"South\" Boundary Conditions need to be defined as \"Periodic\" for the periodic treatment to be applied')\n if bc_w == 'Periodic' or bc_e == 'Periodic':\n if bc_w == bc_e:\n self.periodic_we = True\n else:\n raise IOError('Both \"West\" and \"East\" Boundary Conditions need to be defined as \"Periodic\" for the periodic treatment to be applied')\n\n\ndef apply_bc(lhs, rhs, metric, boundaries):\n \"\"\"\n Give the altered version of LHS matrix and RHS vector to apply boundary\n conditions\n\n Parameters\n ----------\n lhs: left-hand side matrix (A in AX=B)\n rhs: right-hand side matrix (B in AX=B)\n metric: an instance of class Metrics2d containing gradient operators\n boundaries: dictionary with boundary data\n\n Returns\n -------\n lhs: modified left-hand side matrix\n rhs: modified right-hand side matrix\n \"\"\"\n for boundary_name, bc_dict in boundaries.items():\n if bc_dict['type'] == 'Robin':\n a_value, b_value, c_value = bc_dict['bc_values']\n nodes = metric.bnd_nodes[boundary_name]\n grad_n = metric.grad_n_bc\n bc_robin(lhs, rhs, nodes, grad_n, a_value, b_value, c_value)\n else:\n if bc_dict['type'] == 'Neumann':\n continue\n if bc_dict['type'] == 'Dirichlet':\n dirichlet_value = bc_dict['bc_values']\n nodes = metric.bnd_nodes[boundary_name]\n grad_n = metric.grad_n_bc\n bc_dirichlet(lhs, rhs, nodes, grad_n, dirichlet_value)\n else:\n if bc_dict['type'] == 'Periodic':\n continue\n raise NotImplementedError('The only available boundary conditions are \"Robin\", \"Neumann\", \"Dirichlet\" and \"Periodic\".')\n\n return (\n lhs, rhs)\n\n\ndef bc_robin_csr(matrix_lhs, matrix_rhs, positions, grad_n_bc, a_val, b_val, c_val):\n \"\"\"\n Function to enforce the Boundary Condition in the Robin formalism:\n\n a * (df / dn) + b * f + c = O\n\n Parameters\n ----------\n matrix_lhs: [CSR] Left Hand Side square matrix\n (shape (size_i_w * size_j_ns)^2)\n matrix_rhs: [ndarray] Right Hand Side vector\n (shape (size_i_w * size_j_ns))\n positions: indices of lines corresponding to the patch being processed\n grad_n_bc: [CSR] normal gradient to boundary nodes\n a_val: value of the \"a\" Robin parameter\n b_val: value of the \"b\" Robin parameter\n c_val: value of the \"a\" Robin parameter\n\n Returns\n -------\n Altered left-hand side matrix and right-hand side vector\n \"\"\"\n for row in positions:\n if grad_n_bc.count_nonzero():\n new_row = a_val * grad_n_bc.getrow(row).toarray().ravel()\n set_row_csr(matrix_lhs, row, new_row)\n diag_bc = np.zeros(matrix_rhs.shape)\n diag_bc[row] = b_val\n mat_bc_b_csr = spsp.csr_matrix(np.diag(diag_bc))\n matrix_lhs = matrix_lhs + mat_bc_b_csr\n\n matrix_rhs[positions] = -c_val\n return (\n matrix_lhs, matrix_rhs)\n\n\ndef bc_robin(matrix_lhs, matrix_rhs, positions, grad_n_bc, a_val, b_val, c_val):\n \"\"\"\n Function to enforce the Boundary Condition in the Robin formalism:\n\n a * (df / dn) + b * f + c = O\n\n Parameters\n ----------\n matrix_lhs: Left Hand Side square matrix (shape (size_i_w * size_j_ns)^2)\n matrix_rhs: Right Hand Side vector (shape (size_i_w * size_j_ns))\n positions: indices of lines corresponding to the patch being processed\n grad_n_bc: normal gradient to boundary nodes\n a_val: value of the \"a\" Robin parameter\n b_val: value of the \"b\" Robin parameter\n c_val: value of the \"a\" Robin parameter\n\n Returns\n -------\n Altered left-hand side matrix and right-hand side vector\n \"\"\"\n for row in positions:\n if grad_n_bc.count_nonzero():\n matrix_lhs[row, :] = a_val * grad_n_bc[row, :]\n matrix_lhs[(row, row)] += b_val\n\n matrix_rhs[positions] = -c_val\n return (\n matrix_lhs, matrix_rhs)\n\n\ndef bc_neumann(matrix_lhs, matrix_rhs, positions, grad_n_bc, target_gradient):\n \"\"\"\n Function to enforce the Neumann Boundary Condition in the Robin formalism:\n\n a * (df / dn) + b * f + c = O\n\n Parameters\n ----------\n grad_n_bc\n target_gradient\n matrix_lhs : Left Hand Side square matrix (shape (size_i_w * size_j_ns)^2)\n matrix_rhs : Right Hand Side vector (shape (size_i_w * size_j_ns))\n positions : indices of lines corresponding to the patch being processed\n\n Returns\n -------\n Altered left-hand side matrix and right-hand side vector\n \"\"\"\n lhs_out, rhs_out = bc_robin(matrix_lhs, matrix_rhs, positions, grad_n_bc, 1.0, 0.0, -target_gradient)\n return (\n lhs_out, rhs_out)\n\n\ndef bc_dirichlet(matrix_lhs, matrix_rhs, positions, grad_n_bc, target_value):\n \"\"\"\n Function to enforce Dirichlet Boundary Condition in the Robin formalism:\n\n a * (df / dn) + b * f + c = O\n\n Parameters\n ----------\n target_value\n matrix_lhs : Left Hand Side square matrix (shape (size_i_w * size_j_ns)^2)\n matrix_rhs : Right Hand Side vector (shape (size_i_w * size_j_ns))\n positions : indices of lines corresponding to the patch being processed\n\n Returns\n -------\n Altered left-hand side matrix and right-hand side vector\n \"\"\"\n print('Dirichlet bc target -->', target_value)\n lhs_out, rhs_out = bc_robin(matrix_lhs, matrix_rhs, positions, grad_n_bc, 0.0, 1.0, -target_value)\n return (\n lhs_out, rhs_out)","sub_path":"pycfiles/arnica-1.5.6-py3-none-any/boundary.cpython-37.py","file_name":"boundary.cpython-37.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"597431027","text":"'''\nFile: MPG_calculator.py\nAuthor: Zhengchao Yu\nDate: September 15, 2014\nSection: 4\nE-Mail: zy3@umbc.edu\nAssignment Description: Lab 2: A Simple Program\n\nMPG Calculator\nTo Calculate a car's MPG you will need two things.\n\n * Distance the car traveled\n * Amount of gas used\n'''\n\n# This line will print program greeting. \nprint(\"This program will calculate MPG\")\n\n# Assign two int variables\n# Prompt the user to enter the distance tracelled. \ndistanceTravelled = int(input(\"Enter distance travelled: \"))\n# Prompt user to enter the number of gallons traveled. \ngallonsUsed = int(input(\"Enter gallons used: \")) \n\n# This line will cast the inputs into a variable. \nMPG = int(((distanceTravelled) / (gallonsUsed))) # This function will calculate MPG\n\n# This line will print MPG calculation. \nprint(\"The MPG is: \" + str(MPG))\n","sub_path":"Lab02/MPG_calculator.py","file_name":"MPG_calculator.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"598665812","text":"# # Loading packages\n# import warnings\n# warnings.filterwarnings('ignore')\n\nimport pandas as pd\n# import sklearn as sk\n# import sklearn.model_selection\n\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport plotly.plotly as py\nimport plotly\nfrom plotly.graph_objs import *\nimport dash\n\nimport numpy as np\n\n# from sklearn.linear_model import LogisticRegression\n# from sklearn import svm\nfrom sklearn.metrics import fbeta_score, make_scorer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import cross_val_score\n# from sklearn.naive_bayes import GaussianNB\n\n\ndata = pd.read_csv(\"claims.csv\")\n\n#We want to extract the Fraud indicator variable \"FraudFound_P\" and assign it to the variable Y_train.\nX_train = data.drop('FraudFound_P', axis=1)\nY_train = data[\"FraudFound_P\"]\n\n#We have to create dummy variables of our categorical variables.\nX_train = pd.get_dummies(X_train)\n\n### HELPER FUNCTIONS ######\n\ndef generate_table(dataframe, max_rows=15):\n return html.Table(\n # Header\n [html.Tr([html.Th(col) for col in dataframe.columns])] +\n\n # Body\n [html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))]\n )\n\n### END HELPER FUNCTONS\n\napp = dash.Dash(__name__)\n\napp.layout = html.Div(\n\n html.Div([\n\n html.H4('Insurance Fraudulent Claims Detection'),\n\n dcc.RangeSlider(\n id='range-slider',\n min=0,\n max=400,\n value=[0, 100]),\n\n html.Div(id='table-container')\n\n ])\n)\n\n@app.callback(\n dash.dependencies.Output('table-container', 'children'),\n [dash.dependencies.Input('range-slider', 'value')])\ndef update_figure2(value):\n\n n_estimators = 50 # Positive integer\n max_depth = value # Positive integer\n max_features = 10 # Positive integer\n class_weight = 'balanced' # {0:x, 1:y} for integers x,y, or, 'balanced'\n\n min_samples_split = 2\n max_leaf_nodes = None\n\n clf_RF = RandomForestClassifier(n_estimators=n_estimators, min_samples_split=min_samples_split,\n max_features=max_features, max_depth=max_depth, class_weight=class_weight)\n clf_RF.fit(X_train, Y_train)\n\n # Set values for the scoring metric. F-Score with beta = 0.5 is set to match the scoring metric used in the Kaggle.\n ftwo_scorer = make_scorer(fbeta_score, beta=0.5)\n\n # Cross-validation score for Fscore metric\n\n # This cross-validation uses the models we trained fitted before\n\n auc_roc_LR = np.mean(cross_val_score(clf_LR, X_train, Y_train, cv=10, scoring=ftwo_scorer))\n auc_roc_RF = np.mean(cross_val_score(clf_RF, X_train, Y_train, cv=10, scoring=ftwo_scorer))\n LR = str(auc_roc_LR)\n RF = str(auc_roc_RF)\n print(\"Cross-validation F-score for Logistic Regression Model: \" + LR)\n\n print(\"\")\n print(\"Cross-validation F-score for Random Forest Model: \" + RF)\n\n return generate_table(confusion_matrix)\n\n@app.callback(\n dash.dependencies.Output('table-container', 'children'),\n [dash.dependencies.Input('range_slider', 'value')])\ndef update_table(value):\n\n ## GIVE CORRELATION MATRIX WITH FP TP FN TN AS PD DATAFRAME\n\n\n return generate_table(dff2)\n\n\n\napp.css.append_css({\n 'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'\n})\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"248380848","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n \n def helper(self, preorder, inorder, inStart, inEnd):\n \n if inStart > inEnd:\n return None\n \n r = preorder[self.I]\n self.I += 1\n \n for i in range(inStart, inEnd + 1):\n if inorder[i] == r:\n break\n\n root = TreeNode(r)\n root.left = self.helper(preorder, inorder, inStart, i - 1)\n root.right = self.helper(preorder, inorder, i + 1, inEnd)\n return root\n \n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n self.I = 0\n return self.helper(preorder, inorder, 0, len(inorder)-1)\n ","sub_path":"Python/Binary Trees/Construct Binary Tree from Preorder and Inorder Traversal.py","file_name":"Construct Binary Tree from Preorder and Inorder Traversal.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"219318174","text":"# -*- coding: utf-8 -*-\n\n# Use either location_ids or locations (or neither)\n# If location_ids (one or more) are provided, locations will be ignored.\n# If neither is provided, all areas will be retured in search result.\n\nsearch = {\n 'location_ids': [], # Array[string]: ['17744', '17755'] look at webpage source for codes\n 'locations': \t[], # Array[string]: ['Stockholm', 'Malmö kommun'] locations by string will be looked up and the first search result will be returned (if any)\n 'type': \t\t[], # Array[string]: options: 'all', 'fritidshus', 'villa', 'tomt', 'radhus', 'gard', 'other'\n 'min_size': \t'', # String (m2) : '60'\n 'min_price': \t'', # string (SEK) : '1000000'\n 'max_price': \t'', # string (SEK) : '3000000'\n 'min_rooms': \t'', # string : '3'\n 'max_fee': \t\t'', # string (SEK) : '4000'\n 'keywords': \t'' # string : 'balkong, kakelugn'\n}\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91412907","text":"import pandas as pd\nimport quandl\nimport math\nimport numpy as np\nfrom sklearn import preprocessing, cross_validation, svm\nfrom sklearn.linear_model import LinearRegression\n\ndf = quandl.get('wiki/googl')\ndf = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]\ndf['HL_PCT'] = ((df['Adj. High'] - df['Adj. Close']) / df['Adj. Close']) * 100\ndf['PCT_change'] = ((df['Adj. High'] - df['Adj. Open']) / df['Adj. Open']) * 100\n\ndf = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]\nforecast_col = 'Adj. Close'\n\ndf.fillna(-99999, inplace = True)\nforecast_out = int(math.ceil(0.01*len(df)))\nprint(forecast_out)\n\n# Shifting columns negatively\ndf['label'] = df[forecast_col].shift(-forecast_out)\ndf.dropna(inplace=True)\n\n# Feature\nX = np.array(df.drop(['label'],1))\n# Label\ny = np.array(df['label'])\n\nX = preprocessing.scale(X)\ny = np.array(df['label'])\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.2)\n\n# clf = svm.SVR(kernel = 'poly')\n# returns a much lower decimal, so we won't use it here\nclf = LinearRegression(n_jobs = 10)\n\n# clf = LinearRegression(n_jobs = -1)\n# will run as many jobs as possible\nclf.fit(X_train, y_train)\naccuracy = clf.score(X_test, y_test)\nprint(accuracy)\n","sub_path":"regression-testing-and-training.py","file_name":"regression-testing-and-training.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"145120747","text":"from subprocess import Popen, PIPE\nimport os\nfrom pathlib import Path\nfrom shlex import quote\nimport shutil\nimport sys\nfrom typing import Optional, Sequence\nfrom .base import PoeExecutor\n\n\nclass PoetryExecutor(PoeExecutor):\n \"\"\"\n A poe task executor implementation that executes inside a poetry managed dev\n environment\n \"\"\"\n\n def execute(self, cmd: Sequence[str], input: Optional[bytes] = None) -> int:\n \"\"\"\n Execute the given cmd as a subprocess inside the poetry managed dev environment\n \"\"\"\n\n if bool(os.environ.get(\"POETRY_ACTIVE\")) or self.context.poe_active == \"poetry\":\n # We're already inside a poetry shell or a recursive poe call so we can\n # execute the command unaltered\n return self._execute_cmd(cmd, input)\n\n if self.context.multistage:\n # This run involves multiple executions so it's worth trying to avoid\n # repetative (and expensive) calls to `poetry run` if we can\n poetry_env = self._get_poetry_virtualenv()\n if sys.prefix == poetry_env:\n # poetry environment is already activated\n return self._execute_cmd(cmd, input)\n\n # Find the virtualenv activate script and execute the cmd in a shell\n # with with the virtualenv\n # This doesn't work on windows (though maybe it could be made to).\n activate_script = self._get_activate_script(poetry_env)\n if activate_script:\n # Activate the virtualenv before running the task. This is much faster\n # than poetry run\n return self._execute_cmd(\n \" \".join(\n (\n \"source\",\n quote(activate_script),\n \"&&\",\n *(quote(token) for token in cmd),\n )\n ),\n input,\n shell=True,\n )\n\n return self._execute_cmd((self._poetry_cmd(), \"run\", *cmd), input)\n\n def _execute_cmd(\n self, cmd: Sequence[str], input: Optional[bytes] = None, shell: bool = False\n ) -> int:\n return self._exec_via_subproc(\n cmd, input=input, env=dict(self.env, POE_ACTIVE=\"poetry\"), shell=shell\n )\n\n def _get_activate_script(self, poetry_env: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Try locate the appropriate poetry virtualenv activate script\n This doesn't work on windows (though maybe it could be made to).\n \"\"\"\n exec_cache = self.context.exec_cache\n result = exec_cache.get(\"poetry_activate_script\")\n if \"poetry_activate_script\" in exec_cache:\n return result\n\n if os.name == \"posix\":\n shell_name = Path(os.environ.get(\"SHELL\", \"\")).stem\n if shell_name:\n poetry_env = poetry_env or self._get_poetry_virtualenv()\n\n if \"fish\" == shell_name:\n suffix = \".fish\"\n elif \"csh\" == shell_name:\n suffix = \".csh\"\n elif \"tcsh\" == shell_name:\n suffix = \".csh\"\n else:\n suffix = \"\"\n\n activate_path = (\n Path(poetry_env).resolve().joinpath(\"bin\", \"activate\" + suffix)\n )\n if activate_path.is_file():\n result = str(activate_path)\n\n # result might be None but we still want to cache it to avoid trying again\n exec_cache[\"poetry_activate_script\"] = result\n return result\n\n def _get_poetry_virtualenv(self):\n \"\"\"\n Ask poetry where it put the virtualenv for this project.\n This is a relatively expensive operation so uses the context.exec_cache\n \"\"\"\n if \"poetry_virtualenv\" not in self.context.exec_cache:\n self.context.exec_cache[\"poetry_virtualenv\"] = (\n Popen((self._poetry_cmd(), \"env\", \"info\", \"-p\"), stdout=PIPE)\n .communicate()[0]\n .decode()\n .strip()\n )\n return self.context.exec_cache[\"poetry_virtualenv\"]\n\n def _poetry_cmd(self):\n return shutil.which(\"poetry\") or \"poetry\"\n","sub_path":"poethepoet/executor/poetry.py","file_name":"poetry.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"49304165","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport sys, math\nimport tweepy,datetime\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport serial\nimport serial.tools.list_ports\nPORT = 'COM3'\n\nGraph_Flag=2\nendtime=20\nxsize=800\nysize=300\nfilename='foo.png'\nsubject = 'Hello!'\nemail_send=''#Email\n\n\n# Bounds for Profile\n\n\n\n\n\n \ndef data_gen():\n t = data_gen.t\n while True:\n t+=1\n #val=100.0*math.sin(t*2.0*3.1415/100.0)\n strin = ser.readline();\n y= float (strin);\n yield t, y\n\ndef run(data):\n # update the data\n t,y = data\n\n # Update Graph\n if t>-1:\n xdata.append(t)\n ydata.append(y)\n b = ydata[0]\n\n # Allow Graph Scrolling\n if t>xsize: # Scroll to the left.\n ax.set_xlim(t-xsize, t)\n\n # Plot Graph 2 - piecewise function\n if (0 < t < 110): #Preheat\n bdata.append((160-b)/(110)*t+b) \n elif (110 <= t < 210): #Soak\n bdata.append(150)\n elif (210 <= t < 310): #Ramp2Peak\n bdata.append((230-23)/(1333)*t+22)\n elif (310 <= t < 350): #Reflow\n bdata.append(240)\n else: #Cooling\n bdata.append((np.exp(-10*t + 240)))\n \n line.set_data(xdata, ydata) \n line1.set_data(xdata, bdata)\n print(t,y)\n \n \n if t==endtime:\n fig.savefig('foo.png')\n if t==endtime+1:\n email_helper(filename,subject,email_send) \n twitter_helper()\n \n return line, line1\n \ndef on_close_figure(event):\n sys.exit(0)\n \ndef twitter_helper():\n try:\n CONSUMER_KEY = 'Voy7bttxw8rKpC18wALNaKvup'#keep the quotes, replace this with your consumer key\n CONSUMER_SECRET = 'wmg6HtRGs5Bnpohmp4ys6GoEAfsVRvc5N9mP2prm9w7MSsXj3G'#keep the quotes, replace this with your consumer secret key\n ACCESS_KEY = '962464172695941120-STGTA2nI6DFz26yVAv61oDdGk5pr5ZM'#keep the quotes, replace this with your access token\n ACCESS_SECRET = 'PaakHuSWYmFaA35jKmOdUDBecvYayOGzqV0vt3L9bFlSp'#keep the quotes, replace this with your access token secret\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\n api = tweepy.API(auth)\n \n filename=open('TwitterBot.txt','r')\n f=filename.readlines()\n filename.close()\n for line in f:\n api.update_status(status=line) \n except:\n print('Tweet Failed to send')\n \n \ndef email_helper(filename,subject,email_send):\n try: \n email_user = ''#Your Email\n email_password = ''#Your Password\n \n \n msg = MIMEMultipart()\n msg['From'] = email_user\n msg['To'] = email_send\n msg['Subject'] = subject\n \n currentDT = str(datetime.datetime.now()) \n ShortDate = currentDT[:-7]\n body = 'Sending this email from Python! Your Reflow was completed at'+ShortDate\n msg.attach(MIMEText(body+ShortDate,'plain'))\n \n \n attachment =open(filename,'rb')\n \n part = MIMEBase('application','octet-stream')\n part.set_payload((attachment).read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition',\"attachment; filename= \"+filename)\n \n msg.attach(part)\n text = msg.as_string()\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.starttls()\n server.login(email_user,email_password)\n \n \n server.sendmail(email_user,email_send,text)\n server.quit()\n print('Email Sent!')\n \n except:\n print('Email Failed to send')\n \ndef SPI_init():\n\n try:\n ser.close();\n except:\n print();\n try:\n ser = serial.Serial(PORT, 115200, timeout=100)\n except:\n print ('Serial port %s is not available' % PORT); portlist=list(serial.tools.list_ports.comports())\n print('Trying with port %s' % portlist[0][0]);\n ser = serial.Serial(portlist[0][0], 115200, timeout=100)\n ser.isOpen()\n return ser \n#==============================================================================\n# Top Level \n#==============================================================================\n#ser=SPI_init()\ncount=0 \nparamters_array=[] \n\n \ntry:\n ser.close();\nexcept:\n print();\ntry:\n ser = serial.Serial(PORT, 115200, timeout=100)\nexcept:\n print ('Serial port %s is not available' % PORT); portlist=list(serial.tools.list_ports.comports())\n print('Trying with port %s' % portlist[0][0]);\n ser = serial.Serial(portlist[0][0], 115200, timeout=100)\n ser.isOpen()\n \nhandshake=ser.readline()\nhandshake.decode('ascii')\nwhile Graph_Flag==2:\n handshake= (ser.readline())\n #handshake.decode('ascii')\n print(handshake.decode('ascii'));\n #print(type(handshake.decode('ascii')));\n fat= int (handshake)\n if fat==1:\n Graph_Flag=0\n \nwhile (Graph_Flag==0): #Gets parameters for the 2nd graph\n \n paramters_array.append(ser.readline()) ; \n print(paramters_array[count].decode('ascii')); #Testing to see if right paramters are beng sent \n print('nice')\n \n fat= int(paramters_array[count])\n if fat==0:\n Graph_Flag=1\n\n \n count+=1\n \nprint (paramters_array)\nsoak_time = int(paramters_array[1]) - int(paramters_array[0])\nsoak_temp = int(paramters_array[2])\nreflow_time = int(paramters_array[3])\nreflow_temp = int(paramters_array[4])\n\n\nwhile (Graph_Flag==1) :#BELOW HERE, IMPLEMENT THE GRAPH\n strin = (ser.readline());\n print(strin.decode('ascii'));\n\n \n \n data_gen.t = -1\n fig = plt.figure()\n fig.canvas.mpl_connect('close_event', on_close_figure)\n ax = fig.add_subplot(111)\n line, = ax.plot([], [], lw=2)\n line1, = ax.plot([], [], 'g--', lw=2)\n ax.set_ylim(-5, 300)\n ax.set_xlim(0, xsize)\n ax.grid()\n xdata, ydata, bdata = [], [], []\n plt.xlabel('Time (s)')\n plt.ylabel('Temperature (C) ')\n plt.title('Reflow Oven Temperature')\n\n # Important: Although blit=True makes graphing faster, we need blit=False to prevent\n # spurious lines to appear when resizing the stripchart.\n ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=100, repeat=False)\n plt.show()\n","sub_path":"Project1Files/Assembly/active/EmailSender.py","file_name":"EmailSender.py","file_ext":"py","file_size_in_byte":6579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"78643992","text":"#!/usr/bin/env python3\n#\n#\n#列表切割\n#1,如果从列表开头开始切割,那么忽略start位的0 ,例如 list[:4] \n#2,如果一直切到列表尾部,则忽略end位的0,例如 list[3:]\n#3,切割列表时,即便start或end索引越界也不会有问题\n#4,列表切片不会改变原列表,索引都留空时,会生成一份原列表的拷贝\n\na = [1,2,3,4,5,6,7,8]\n\nb = a[:]\n\nassert b == a and b is not a \n\n# 列表推导试\n# 使用列表推导式来取代map和filter\n# \n# use map\n#\nsquares = map(lambda x: x ** 2,a)\nprint(squares)\n#use list comprehension\n#\nsquares = [x ** 2 for x in a ]\nprint(squares)\n#\n#一个很大的好处就是列表推导式可以对值进行判断比如\nsquares = [x ** 2 for x in a if x % 2 == 0]\nprint(squares)\n#这种情况如果 用map或filter写的话会多写一下函数\n\n\n#不要使用含有两个以上的表达式的列表推导式\n#\n#有一个嵌套的列表,现在要把它里面的所有的元素扁平化输出\nlist = [[[1,2,3],[4,5,6]]]\n#使用列表推导式\nflat_list = [x for list0 in list for list1 in list0 for x in list1]\nprint(flat_list)\n#\n#但是这种写法可读性太差了,易出错,建议使用普通的循环\nflat_list = []\nfor list0 in list:\n for list1 in list0:\n flat_list.extend(list1)\nprint(flat_list)\n#\n#\n#数据多的时候,列表推导式会消耗大量的��存,此时建议使用生成器表达式\n#列表推导式在推导额时候,对于输入序列的每个值来说,都可能会创建仅含一个元素的全新列表,因此数量大时会消耗很大性能\n#使用生成器表达式\nlist = (x ** 2 for x in range(0,100))\n#生成器表达式返回的迭代器,只有在每次调用时才生成值,从而避免了内存占用\nprint(list)\nfor item in list:\n print(item)\n\n","sub_path":"Pythonic_tip.py","file_name":"Pythonic_tip.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"365391022","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: Ldc.py\n@time: 2019/9/16 20:33\n@desc: ldc系列指令从运行时常量池中加载常量值,并把它推入操作数栈。\nldc和ldc_w指令用于加载int、float和字符串常量,java.lang.Class实例或者MethodType和MethodHandle实例。\nldc2_w指令用于加载long和double常量。\n\"\"\"\nfrom ch10.instructions.base.Instruction import Index8Instruction, Index16Instruction\nfrom ch10.rtda.Frame import Frame\nfrom ch10.rtda.heap.CpClassRef import ClassRef\nfrom ch10.rtda.heap.StringPool import j_string\n\n\ndef _ldc(frame: Frame, index):\n stack = frame.operand_stack\n clazz = frame.method.get_class()\n c = clazz.constant_pool.get_constant(index)\n\n if isinstance(c, int):\n stack.push_numeric(c)\n elif isinstance(c, float):\n stack.push_float(c)\n elif isinstance(c, str):\n # 从运行时常量池中加载字符串常量,先通过常量拿到python字符串,然后把它转成Java字符串实例\n interned_str = j_string(clazz.loader, c)\n # 把引用推入操作数栈顶\n stack.push_ref(interned_str)\n elif isinstance(c, ClassRef):\n class_obj = c.resolved_class().j_class\n stack.push_ref(class_obj)\n else:\n raise RuntimeError(\"todo: ldc!\")\n\n\nclass LDC(Index8Instruction):\n def execute(self, frame):\n _ldc(frame, self.index)\n\n\nclass LDC_W(Index16Instruction):\n def execute(self, frame):\n _ldc(frame, self.index)\n\n\nclass LDC2_W(Index16Instruction):\n def execute(self, frame: Frame):\n stack = frame.operand_stack\n cp = frame.method.get_class().constant_pool\n c = cp.get_constant(self.index)\n\n if isinstance(c, int):\n stack.push_numeric(c)\n elif isinstance(c, float):\n stack.push_double(c)\n else:\n raise RuntimeError(\"java.lang.ClassFormatError\")\n","sub_path":"src/ch10/instructions/constants/Ldc.py","file_name":"Ldc.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68150585","text":"import json\nfrom collections import defaultdict\nimport numpy as np\nimport random\nimport copy\n\nclass obj_size:\n def __init__(self, filename):\n with open(filename, 'r') as f:\n self.sz_dst = json.load(f)\n \n self.n_sz_dst = defaultdict(lambda : 0)\n self.obj_sizes = []\n\n for k in self.sz_dst:\n k1 = int(k.decode())\n k1 = k1/30000000\n self.n_sz_dst[k1] += int(self.sz_dst[k])\n\n self.obj_sizes = list(self.n_sz_dst.keys())\n self.obj_sizes.sort()\n self.obj_size_cnts = []\n\n for o in self.obj_sizes:\n self.obj_size_cnts.append(self.n_sz_dst[o])\n\n footprint = sum(self.obj_sizes)\n\n self.obj_size_cnts = [float(x)/footprint for x in self.obj_sizes]\n self.obj_size_cnts = np.cumsum(self.obj_size_cnts)\n\n\n def sample(self):\n z = np.random.random()\n\n sz = self.obj_sizes[-1]\n pr = 0\n\n for i in range(len(self.obj_size_cnts)): \n if self.obj_size_cnts[i] > z:\n sz, pr = self.obj_sizes[i], (self.obj_size_cnts[i] - self.obj_size_cnts[i-1])\n break\n\n return sz, pr\n\n\nclass obj_size_uniform:\n def __init__(self, min_sz, max_sz):\n self.min_sz = min_sz\n self.max_sz = max_sz\n\n def get_objects(self, no_obj): \n\n obj_sz = []\n obj_size_dst = defaultdict(lambda : 0) \n\n for i in range(no_obj):\n sz = random.randint(self.min_sz, self.max_sz)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n obj_sizes = list(obj_size_dst.keys())\n obj_sizes.sort()\n dst = []\n\n for sz in obj_sizes:\n dst.append(obj_size_dst[sz])\n \n sum_dst = sum(dst)\n \n dst = [float(x)/sum_dst for x in dst]\n\n return obj_sz, dst\n\n\nclass obj_size_two_distribution:\n def __init__(self, r1_min, r1_max, r2_min, r2_max, p1):\n self.r1_min = r1_min\n self.r1_max = r1_max\n self.r2_min = r2_min\n self.r2_max = r2_max\n self.p = p1\n\n def get_objects(self, no_obj):\n \n obj_sz = []\n obj_size_dst = defaultdict(lambda : 0) \n\n no_obj1 = int(self.p * no_obj)\n\n for i in range(no_obj1):\n sz = random.randint(self.r1_min, self.r1_max)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n no_obj2 = int((1 - self.p)*no_obj)\n for i in range(no_obj2):\n sz = random.randint(self.r2_min, self.r2_max)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n obj_sizes = list(obj_size_dst.keys())\n obj_sizes.sort()\n dst = []\n\n for sz in obj_sizes:\n dst.append(obj_size_dst[sz])\n \n sum_dst = sum(dst)\n \n dst = [float(x)/sum_dst for x in dst]\n\n return obj_sz, dst\n\n\n\nclass obj_size_three_distribution:\n def __init__(self, r1_min, r1_max, r2_min, r2_max, r3_min, r3_max, p1, p2, p3):\n self.r1_min = r1_min\n self.r1_max = r1_max\n self.r2_min = r2_min\n self.r2_max = r2_max\n self.r3_min = r3_min\n self.r3_max = r3_max\n self.p1 = p1\n self.p2 = p2\n self.p3 = p3\n\n def get_objects(self, no_obj):\n \n obj_sz = []\n obj_size_dst = defaultdict(lambda : 0) \n\n no_obj1 = int(self.p1 * no_obj)\n no_obj2 = int(self.p2 * no_obj)\n no_obj3 = int(self.p3 * no_obj)\n\n for i in range(no_obj1):\n sz = random.randint(self.r1_min, self.r1_max)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n for i in range(no_obj2):\n sz = random.randint(self.r2_min, self.r2_max)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n for i in range(no_obj3):\n sz = random.randint(self.r3_min, self.r3_max)\n obj_sz.append(sz)\n obj_size_dst[sz] += 1\n\n random.shuffle(obj_sz)\n\n obj_sizes = list(obj_size_dst.keys())\n obj_sizes.sort()\n dst = []\n\n for sz in obj_sizes:\n dst.append(obj_size_dst[sz])\n \n sum_dst = sum(dst)\n \n dst = [float(x)/sum_dst for x in dst]\n\n return obj_sz, dst\n\n\n\n\n\n\n","sub_path":"real_trace/obj_size_dst.py","file_name":"obj_size_dst.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29981147","text":"from math import sqrt\nfrom math import isnan\n\n\n# Each function call represents an elf doing his work \ndef recurse(sql_query, conn):\n # Worker elf doing his work\n catalog = sqlio.read_sql_query(sql_query, conn)\n if len(catalog) > 0 and len(catalog) < 50:\n catalog = catalog[0]\n return catalog\n\n # Manager elf doing his work\n else:\n mid = len(catalog) // 2\n first_half = catalog[:mid]\n second_half = catalog[mid:]\n\n # Divides his work among two elves\n recurse(first_half)\n recurse(second_half)\n\n\ndef get_coordinates(row, df):\n try:\n row_ra = df['ra_deg'].iloc[row]\n row_dec = df['dec_deg'].iloc[row]\n return [row_ra, row_dec]\n except KeyError:\n try:\n row_ra = df['ra'].iloc[row]\n row_dec = df['dec'].iloc[row]\n return [row_ra, row_dec]\n except KeyError:\n try:\n row_ra = df['ra'].iloc[row]\n row_dec = df['decl'].iloc[row]\n return [row_ra, row_dec]\n except KeyError:\n print('coordinates error')\n pass\n\n\ndef distance(r1, r2):\n d = sqrt((r2[0] - r1[0])**2 + (r2[1] - r1[1])**2)\n return d\n\n\ndef circle_with_r(r_i, radius, df):\n points_in_circle = []\n if len(df) > 1:\n r = get_coordinates(r_i, df)\n points_in_circle = [j for j in range(len(df)) if distance(\n r, get_coordinates(j, df)) <= radius]\n return points_in_circle\n\n\ndef circle_without_r(r_i, radius, df):\n r = get_coordinates(r_i, df)\n points_in_circle = [j for j in range(len(df)) if distance(r, get_coordinates(\n j, df)) <= radius and distance(r, get_coordinates(j, df)) > 0]\n return points_in_circle\n\n\ndef circle_intercepts(r, radius):\n ra_pos = r[0] + radius\n dec_pos = r[1] + radius\n ra_neg = r[0] - radius\n dec_neg = r[1] - radius\n return [ra_neg, ra_pos, dec_neg, dec_pos]\n\n\ndef RA_DEC_convert_to_Degrees(x):\n try:\n if isnan(x):\n return x\n except TypeError:\n y = x.split()\n\n if len(y) == 3:\n z = float(y[0]) + 0.0166667 * float(y[1]) + \\\n 0.000277778 * float(y[2])\n elif len(y) == 2:\n z = float(y[0]) + 0.0166667 * float(y[1])\n else:\n z = float(y[0])\n return z\n","sub_path":"labeled_data/simbad_functions.py","file_name":"simbad_functions.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"622446637","text":"import codecs, time\nfrom headers import get_headers\n\ndef create_file(feed_name, permission, headers_array):\n if permission == 'a':\n f = codecs.open(feed_name, permission, 'utf-8')\n else:\n f = codecs.open(feed_name+'_%s_000.csv'%(time.strftime('%Y%m%d')), permission, 'utf-8')\n headers = get_headers(headers_array)\n f.write('|'.join(headers) + '\\n')\n return f\n \n","sub_path":"script_template/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"219838536","text":"import pytest\nfrom aiokea.errors import DuplicateResourceError\n\nfrom app.infrastructure.common.filters.filters import Filter\nfrom app.infrastructure.common.filters.operators import EQ, NE\nfrom app.usecases.resources.user import User\nfrom tests import db_setup\n\n\nasync def test_get_where(db, user_pg_client):\n stub_count = len(db_setup.stub_users)\n # No filters\n results = await user_pg_client.get_where()\n assert len(results) == stub_count\n\n # Filters\n result_equal_to = await user_pg_client.get_where([Filter(\"username\", EQ, \"brian\")])\n result_not_equal_to = await user_pg_client.get_where(\n [Filter(\"username\", NE, \"brian\")]\n )\n assert len(result_equal_to) + len(result_not_equal_to) == stub_count\n\n\n# async def test_get_where_paginated(db, user_pg_client):\n# db_count = len(await user_pg_client.get_where())\n# retrieved_records = 0\n# page = 0\n# page_size = 1\n# while retrieved_records < db_count:\n# results = await user_pg_client.get_where(page=page, page_size=page_size)\n# retrieved_records += len(results)\n# assert retrieved_records == (page * page_size) + len(results)\n# page += 1\n# assert retrieved_records == db_count\n\n\nasync def test_create(db, user_pg_client):\n old_user_count = len(await user_pg_client.get_where())\n\n new_user = User(username=\"test\", email=\"test\")\n createed_user = await user_pg_client.create(new_user)\n assert createed_user.id == new_user.id\n\n new_user_count = len(await user_pg_client.get_where())\n assert new_user_count == old_user_count + 1\n\n\nasync def test_create_duplicate_error(db, user_pg_client):\n old_user_count = len(await user_pg_client.get_where())\n\n new_user = User(username=\"test\", email=\"test\")\n await user_pg_client.create(new_user)\n with pytest.raises(DuplicateResourceError):\n await user_pg_client.create(new_user)\n\n new_user_count = len(await user_pg_client.get_where())\n assert new_user_count == old_user_count + 1\n\n\nasync def test_update(db, user_pg_client):\n # Get an existing user\n roman: User = await user_pg_client.get_first_where(\n [Filter(\"username\", EQ, \"roman\")]\n )\n roman.username = \"bigassforehead\"\n # Update the user\n await user_pg_client.update(roman)\n\n # Check that the user has been updated\n updated_roman: User = await user_pg_client.get_first_where(\n [Filter(\"id\", EQ, roman.id)]\n )\n assert updated_roman.username == \"bigassforehead\"\n\n\n# async def test_update_where(db, user_pg_client):\n# # Get baseline\n# user_count = len(await user_pg_client.get_where())\n# old_disabled_user_count = len(\n# await user_pg_client.get_where([Filter(\"is_enabled\", EQ, False)])\n# )\n# assert old_disabled_user_count != user_count\n#\n# # Update users\n# await user_pg_client.update_where(\n# set_values={\"is_enabled\": False}, filters=[Filter(\"is_enabled\", EQ, True)]\n# )\n#\n# # Check all users are now disabled\n# new_disabled_user_count = len(\n# await user_pg_client.get_where([Filter(\"is_enabled\", EQ, False)])\n# )\n# assert new_disabled_user_count == user_count\n","sub_path":"tests/test_infrastructure/test_datastore/test_postgres/test_clients/test_user_client.py","file_name":"test_user_client.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"124088440","text":"\"\"\"3.40 Foi feita uma estatística em cinco cidades brasileiras para coletar dados sobre acidentes de trânsito.\nForam obtidos os seguintes dados:\na. Código da cidade;\nb. Número de veículos de passeio (em 1999);\nc. Número de acidentes de trânsito com vítimas (em 1999).\nDeseja-se saber:\nd. Qual o maior e menor índice de acidentes de transito e a que cidade pertence;\ne. Qual a média de veículos nas cinco cidades juntas;\nf. Qual a média de acidentes de trânsito nas cidades com menos de 2.000 veículos de passeio.\"\"\"\n\nindexcodigos, indexcidades, indexveiculos, indexacidentes = 0, 1, 2, 3\n\nmaior = menor = i = 0\n\ncodigos = []\ncidades = []\nveiculos = []\nacidentes = []\n\nj = int(input('Quantas cidades serão analisadas? '))\n\n\ndef entrada(string, n, lista):\n if lista == cidades:\n saida = input(f'Digite o {string} da {n}ª cidade: ').strip().title()\n else:\n saida = int(input(f'Digite o {string} da {n}ª cidade: '))\n if lista == codigos or lista == cidades:\n while saida in lista:\n saida = input(f'Uma chave primária não pode se repetir\\nDigite novamente o {string} da {n}ª cidade: ')\n lista.append(saida)\n\n\ndef verifica(lista, index):\n i = indicemaior = indicemenor = soma = maiortaxa = menortaxa = 0\n while i < j:\n item = lista[i][index]\n item2 = lista[i][index-1]\n if i == 0 and index == 3:\n taxa = item/item2\n maiortaxa = menortaxa = taxa*100\n indicemaior = indicemenor = i\n if i != 0 and index == 3:\n taxa = item/item2\n if taxa*100 > maiortaxa:\n maiortaxa = taxa*100\n indicemaior = i\n if taxa*100 < menortaxa:\n menortaxa = taxa*100\n indicemenor = i\n if index == 2:\n soma += item\n i += 1\n return maiortaxa, menortaxa, soma, indicemaior, indicemenor\n\n\nfor c in range(1, j+1):\n print('-'*35)\n entrada('código', c, codigos)\n entrada('nome', c, cidades)\n entrada('número de veículos', c, veiculos)\n entrada('acidentes', c, acidentes)\n\nbd = list(zip(codigos, cidades, veiculos, acidentes))\nprint('-'*45)\nprint('{:~^45}'.format('BANCO DE DADOS'))\nprint('-'*45)\nprint('{:<12}' '{:<12}' '{:<12}' '{:<12}'.format('Código', 'Cidade', 'Veículos', 'Acidentes'))\n\nfor c in range(j):\n for h in range(j+1):\n print('{:<12}'.format(bd[c][h]), end=' ')\n print('\\n')\n\ngeralAcidentes = verifica(bd, indexacidentes)\ngeralVeiculos = verifica(bd, indexveiculos)\nmaiortaxa, menortaxa, soma, indicemaior, indicemenor = 0, 1, 2, 3, 4\nprint(f'\\nSomatório de veículos em todas as cidades: {geralVeiculos[soma]}.')\nprint(f'Média de veículos por cidade: {geralVeiculos[soma]/j:.2f}')\nprint(f'\\nMaior taxa de acidentes: {geralAcidentes[maiortaxa]:.2f}% - Em {bd[geralAcidentes[indicemaior]][1]}.')\nprint(f'Menor taxa de acidentes: {geralAcidentes[menortaxa]:.2f}% - Em {bd[geralAcidentes[indicemenor]][1]}.')\n\n\n\n\n","sub_path":"python/python-brasil/03-estruturas-repeticao/ex40_veiculos.py","file_name":"ex40_veiculos.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"449332738","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n__title__ = disk_cache.py\r\n__author__ = Hughe\r\n__time__ = 2017-04-08 17:19\r\n\"\"\"\r\n\r\nimport os\r\nimport re\r\nimport urlparse\r\nimport pickle\r\nimport zlib\r\nfrom datetime import datetime,timedelta\r\nclass DiskCache:\r\n #加入默认30天周期的清理过期检查 expires\r\n def __init__(self,cache_dir='cache',expires=timedelta(seconds=5)):\r\n self.cache_dir=cache_dir\r\n self.expires=expires\r\n #self.max_length=max_length\r\n\r\n #应用了文件名限制\r\n def url_to_path(self,url):\r\n #解析url\r\n components=urlparse.urlsplit(url)\r\n path=components.path\r\n if not path:\r\n path='index.html'\r\n elif path.endswith('/'):\r\n path+='index.html'\r\n filename=components.netloc+path+components.query\r\n filename=re.sub('[^/0-9a-zA-Z\\-.,;_]','_',filename)\r\n filename='/'.join(segment[:255] for segment in filename.split('/'))\r\n return os.path.join(self.cache_dir,filename)\r\n\r\n #get cache[url]\r\n def __getitem__(self,url):\r\n path=self.url_to_path(url)\r\n if os.path.exists(path):\r\n with open(path,'rb') as fp:\r\n result,timestamp= pickle.loads(zlib.decompress(fp.read()))\r\n if self.has_expires(timestamp):\r\n raise KeyError(url+'has expired')\r\n return result\r\n\r\n \"\"\" 加入时间戳之前版本:\r\n #加入解压 原版本:return pickle.load(fp)\r\n return pickle.loads(zlib.decompress(fp.read()))\"\"\"\r\n else:\r\n raise KeyError(url+'does not exist')\r\n\r\n #set result=cache[url]\r\n def __setitem__(self, url, result):\r\n path=self.url_to_path(url)\r\n folder=os.path.dirname(path)\r\n timestamp=datetime.utcnow()\r\n data=pickle.dumps((result,timestamp))\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n with open(path,'wb') as fp:\r\n #加入压缩 原版本:fp.write(pickle.dumps(result))\r\n fp.write(zlib.compress(data))\r\n\r\n #检查是否过期\r\n def has_expires(self,timestamp):\r\n return datetime.utcnow()>timestamp+self.expires\r\nif __name__ == '__main__':\r\n link_crawler('http://example.webscraping.com/', '/(index|view)', cache=DiskCache())\r\n\r\n\r\n\r\n","sub_path":"CH4/disk_cache.py","file_name":"disk_cache.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"435275703","text":"#semaphore.py\nfrom multiprocessing import Semaphore,Process\nfrom time import sleep,ctime\nimport os\n\n#创建信号量\nsem = Semaphore(3)\n\ndef fun():\n print(\"%d 想执行事件\"%os.getgid())\n #想执行事件必须得到信号量资源\n sem.acquire()\n print(\"%s抢到了一个信号量,可以执行操作\"%os.getpid())\n sleep(3)\n print(\"%d执行完事件再增加信号量\"%os.getpid())\n sem.release()\njobs = []\nprint(ctime())\nfor i in range(5):\n p = Process(target=fun)\n jobs.append(p)\n p.start()\n\nfor i in jobs:\n i.join()\nprint(sem.get_value())\nprint(ctime())\n\n\n\n\n","sub_path":"pythonNet/semaphore.py","file_name":"semaphore.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"5203271","text":"import numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport pandas as pd\ndata = pd.read_csv('C:\\\\Users\\\\Kelsey\\\\Downloads\\\\CodeExerc\\\\codes\\\\fastGold.csv')\nprint(\"\\n Given Data Set:\\n\\n\", data)\n\n#Function to calculate the entropy of probaility of observations\n# -p*log2*p\n\ndef entropy(probs): \n import math\n return sum( [-prob*math.log(prob, 2) for prob in probs] )\n\n###################################Function to calulate the entropy of the given Data Sets/List with respect to target attributes#######################\n\ndef entropy_of_list(a_list): \n from collections import Counter\n cnt = Counter(x for x in a_list) # Counter calculates the propotion of class\n # print(\"\\nClasses:\",cnt)\n #print(\"No and Yes Classes:\",a_list.name,cnt)\n num_instances = len(a_list)*1.0 # = 14\n print(\"\\n Number of Instances of the Current Sub Class is {0}:\".format(num_instances ))\n probs = [x / num_instances for x in cnt.values()] # x means no of YES/NO\n print(\"\\n Classes:\",min(cnt),max(cnt))\n print(\" \\n Probabilities of Class {0} is {1}:\".format(min(cnt),min(probs)))\n print(\" \\n Probabilities of Class {0} is {1}:\".format(max(cnt),max(probs)))\n return entropy(probs) # Call Entropy :\n \n# The initial entropy of the YES/NO attribute for our dataset.\nprint(\"\\n INPUT DATA SET FOR ENTROPY CALCULATION:\\n\", data['Fast'])\n\ntotal_entropy = entropy_of_list(data['Fast'])\n\nprint(\"\\n Total Entropy of Fast Data Set:\",total_entropy)\n\n#####################################################calculating information Gain#######################################################\n\ndef information_gain(df, split_attribute_name, target_attribute_name, trace=0):\n print(\"Information Gain Calculation of \",split_attribute_name)\n '''\n Takes a DataFrame of attributes, and quantifies the entropy of a target\n attribute after performing a split along the values of another attribute.\n '''\n # Split Data by Possible Vals of Attribute:\n df_split = df.groupby(split_attribute_name)\n # Calculate Entropy for Target Attribute, as well as\n # Proportion of Obs in Each Data-Split\n nobs = len(df.index) * 1.0\n \n df_agg_ent = df_split.agg({target_attribute_name : [entropy_of_list, lambda x: len(x)/nobs] })[target_attribute_name]\n \n df_agg_ent.columns = ['Entropy', 'PropObservations']\n #if trace: # helps understand what fxn is doing:\n \n # Calculate Information Gain:\n new_entropy = sum( df_agg_ent['Entropy'] * df_agg_ent['PropObservations'] )\n old_entropy = entropy_of_list(df[target_attribute_name])\n return old_entropy - new_entropy\n\n\nprint('Info-gain for FuelEco is :'+str( information_gain(data, 'FuelEco', 'Fast')),\"\\n\")\nprint('\\n Info-gain for Engine is: ' + str( information_gain(data, 'Engine', 'Fast')),\"\\n\")\nprint('\\n Info-gain for Turbo is:' + str( information_gain(data, 'Turbo', 'Fast')),\"\\n\")\nprint('\\n Info-gain for Weight is:' + str( information_gain(data, 'Weight','Fast')),\"\\n\")\n\n######################################ID3 Algorithm#########################################################################################\n\ndef id3(df, target_attribute_name, attribute_names, default_class=None):\n \n ## Tally target attribute:\n from collections import Counter\n cnt = Counter(x for x in df[target_attribute_name])# class of YES /NO\n \n ## First check: Is this split of the dataset homogeneous?\n if len(cnt) == 1:\n return next(iter(cnt)) # next input data set, or raises StopIteration when EOF is hit.\n \n ## Second check: Is this split of the dataset empty?\n # if yes, return a default value\n elif df.empty or (not attribute_names):\n return default_class # Return None for Empty Data Set\n \n ## Otherwise: This dataset is ready to be devied up!\n else:\n # Get Default Value for next recursive call of this function:\n default_class = max(cnt.keys()) #No of YES and NO Class\n # Compute the Information Gain of the attributes:\n gainz = [information_gain(df, attr, target_attribute_name) for attr in attribute_names] #\n index_of_max = gainz.index(max(gainz)) # Index of Best Attribute\n # Choose Best Attribute to split on:\n best_attr = attribute_names[index_of_max]\n \n # Create an empty tree, to be populated in a moment\n tree = {best_attr:{}} # Iniiate the tree with best attribute as a node \n remaining_attribute_names = [i for i in attribute_names if i != best_attr]\n \n # Split dataset\n ############ ##################On each split, recursively call this algorithm.########################\n # populate the empty tree with subtrees, which\n # are the result of the recursive call\n \n for attr_val, data_subset in df.groupby(best_attr):\n subtree = id3(data_subset,\n target_attribute_name,\n remaining_attribute_names,\n default_class)\n tree[best_attr][attr_val] = subtree\n return tree\n\n# Get Predictor Names (all but 'class')\nattribute_names = list(data.columns)\nprint(\"List of Attributes:\", attribute_names) \nattribute_names.remove('Fast') #Remove the class attribute \nprint(\"Predicting Attributes:\", attribute_names)\n\n# Run Algorithm:\nfrom pprint import pprint\ntree = id3(data,'Fast',attribute_names)\nprint(\"\\n\\nThe Resultant Decision Tree is :\\n\")\npprint(tree)\nattribute = next(iter(tree))\n\n#####################network x draw tree###############\nG = nx.Graph()\nnodes=[\"Weight\",\"Average\",\"Heavy\",\"Light\",\"Engine\",\n \"Turbo\",\"Large\",\"Small\",\"No\",\"Yes\",\" No\",\" Yes\",\"No \",\"Yes \",\"yes\"]\n\nG.add_nodes_from(nodes)\nG.nodes()\n\nG.add_edge(\"Weight\",\"Average\")\nG.add_edge(\"Weight\",\"Heavy\")\nG.add_edge(\"Weight\",\"Light\")\nG.add_edge(\"Average\",\"Engine\")\nG.add_edge(\"Heavy\",\"Turbo\")\nG.add_edge(\"Light\",\"yes\")\nG.add_edge(\"Turbo\",\" No\")\nG.add_edge(\"Turbo\",\" Yes\")\nG.add_edge(\" No\",\"No\")\nG.add_edge(\" Yes\",\"Yes\")\nG.add_edge(\"Engine\",\"Large\")\nG.add_edge(\"Engine\",\"Small\")\nG.add_edge(\"Large\",\"Yes \")\nG.add_edge(\"Small\",\"No \")\n\nG.node[\"Weight\"]['pos']=(0,0)\nG.node[\"Average\"]['pos']=(-3,-2)\nG.node[\"Heavy\"]['pos']=(0,-2)\nG.node[\"Light\"]['pos']=(2,-2)\nG.node[\"Engine\"]['pos']=(-3,-4)\nG.node[\"Turbo\"]['pos']=(0,-4)\nG.node[\"yes\"]['pos']=(2,-4)\nG.node[\"Large\"]['pos']=(-4,-6)\nG.node[\"Small\"]['pos']=(-2,-6)\nG.node[\" No\"]['pos']=(-1,-6)\nG.node[\" Yes\"]['pos']=(1,-6)\nG.node[\"No \"]['pos']=(-2,-7)\nG.node[\"Yes \"]['pos']=(-4,-7)\nG.node[\"No\"]['pos']=(-1,-7)\nG.node[\"Yes\"]['pos']=(1,-7)\n\n\nnode_pos = nx.get_node_attributes(G, 'pos')\n\nnx.draw_networkx(G, node_pos, node_color='darkturquoise', node_size=450)\nnx.draw_networkx_edges(G, node_pos, width=2, edge_color='peru')\nplt.axis('off')\nplt.show()\n","sub_path":"id3.py","file_name":"id3.py","file_ext":"py","file_size_in_byte":6866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"78643853","text":"import os\nimport sys\nimport shutil\nimport pydicom\n\n\nclass DicomLoader():\n def __init__(self, opt):\n self.input_dir = opt.input_dir\n self.output_dir = opt.output_dir\n self.n_slices = opt.n_slices\n self.files = sorted([os.path.join(self.input_dir, i) for i in os.listdir(self.input_dir)\n if os.path.isfile(os.path.join(self.input_dir, i))])\n self.renamed_files = []\n self.is_navi = opt.is_navi\n\n def preprocess(self):\n # Load DICOMs and rename files\n self.rename_files()\n\n if self.is_navi:\n print('Navigators: Set spacing between slices to 1')\n self.set_spacing_between_slices()\n else:\n print('Data files: Sort data slices according to their slice position')\n self.sort_dats()\n\n def rename_files(self):\n for i, file in enumerate(self.files):\n dcm = pydicom.read_file(self.files[i])\n\n if self.is_navi and ('ImageComments' in dcm and dcm.ImageComments == 'Navigator'):\n new_file = os.path.join(self.output_dir, 'navi%05d.dcm' % dcm.InstanceNumber)\n else:\n new_file = os.path.join(self.output_dir, 'data%05d.dcm' % dcm.InstanceNumber)\n\n shutil.copyfile(file, new_file)\n self.renamed_files.append(new_file)\n\n def set_spacing_between_slices(self):\n for i, file in enumerate(self.renamed_files):\n dcm = pydicom.read_file(self.renamed_files[i])\n\n if dcm.SpacingBetweenSlices == 0:\n dcm.SpacingBetweenSlices = 1\n dcm.save_as(self.renamed_files[i])\n\n def sort_dats(self):\n n_images = len(self.renamed_files)\n n_sweeps = int(n_images/self.n_slices)\n\n if not (n_images % self.n_slices) == 0:\n sys.exit('Number of slice positions is not correct')\n\n for p in range(0, self.n_slices):\n dest_dir = os.path.join(self.output_dir, 'sorted', 'slice%02d' % (p+1))\n os.makedirs(dest_dir, exist_ok=True)\n\n for i in range(0, n_sweeps):\n shutil.copy2(self.renamed_files[p+i*self.n_slices], dest_dir)\n\n def get_files(self):\n return self.files\n\n def get_files_renamed(self):\n return self.renamed_files\n","sub_path":"scripts/data/dicom_loader.py","file_name":"dicom_loader.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"223535001","text":"##!/usr/bin/python\n\nimport numpy as np\nimport pylab as plt\nimport seaborn as sns \n\nsns.set_context('poster')\n\nplt.subplot(1,1,1)\ndata = np.genfromtxt(fname='energy.dat') \n#data = np.loadtxt('traj.dat')\n#for x in range(1,data.shape[-1]):\nplt.plot(data[:,0],data[:,1],label='kinetic')\nplt.plot(data[:,0],data[:,2],label='potential')\nplt.plot(data[:,0],data[:,3],label='quantum potential')\nplt.plot(data[:,0],data[:,4],label='total')\n\n#plt.figure(1) \n#plt.plot(x,y1,'-')\n#plt.plot(x,y2,'g-')\nplt.xlabel('time')\nplt.ylabel('$x_i$')\n#plt.title('traj')\nplt.legend() \n\n\nplt.show() \n\n","sub_path":"GWP/2D/1.0.0/en.py","file_name":"en.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"178784701","text":"from __future__ import print_function\n\nimport os\nimport json\nimport sys\n\nfrom glob import glob\n\nthis_file = os.path.realpath(__file__)\nthis_dir = os.path.dirname(this_file)\nroot = os.path.realpath(os.path.join(this_dir, '../'))\n\npaths = {'environment': 'environment.json',\n 'static_in': '../../static.in',\n 'build_static_in': 'static.in',\n 'extended_python_path': '../../lib',\n 'static_out': 'static',\n 'update_symlink': '../../current',\n 'debug_if_exists': '../../DEBUG',\n 'persistent_media_root': '../../MEDIA_ROOT',\n 'secret_key': '../../SECRET_KEY',\n 'pre_wsgi': 'pre-wsgi.py-fragment',\n 'post_wsgi': 'post-wsgi.py-fragment',\n 'build_lib': 'lib',\n 'aux': 'aux',\n 'root': '.'\n }\n\npathfiles_glob = os.path.join(root, 'paths.d/*.json')\n\npathfiles = [open(p) for p in glob(pathfiles_glob)]\n\nfor pathfile in pathfiles:\n new_paths = json.load(pathfile)\n paths.update(new_paths)\n pathfile.close()\n\n\ndef get_path(name):\n relpath = paths[name]\n if relpath is not None and bool(relpath) is True:\n joined = os.path.join(root, relpath)\n return os.path.normpath(joined)\n else:\n raise KeyError('no path found for %s' % name)\n\ndef get_path_if_exists(name):\n path = get_path(name)\n if os.path.exists(path):\n return path\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(\"Lookup paths in a drama-free-django\"\n \" release\")\n\n parser.add_argument('key')\n\n args = parser.parse_args()\n\n try:\n print(get_path(args.key))\n except KeyError:\n print(\"we have no path named: \", args.key, file=sys.stderr)\n","sub_path":"no_drama/build_skel/lib/dfd.py","file_name":"dfd.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"594799874","text":"#coding=utf-8\nfrom __future__ import absolute_import\n\nfrom flask import Blueprint, request, current_app\nfrom .models import Order, Item\nfrom .routes import urlpatterns\nfrom errors.base_errors import APIError\nfrom utils.base_utils import make_json_response, route_inject\nfrom utils.bp_users_utils import verify_token\nfrom utils.bp_groups_utils import verify_member_permission, verify_owner_permission\n\nbp_name = \"order\"\n\n\nmember_permission_endpoints = [\n \"{}.get_order\".format(bp_name),\n \"{}.add_order\".format(bp_name),\n \"{}.update_order\".format(bp_name),\n \"{}.delete_order\".format(bp_name)]\n\nowner_permission_endpoints = []\n\n\nblueprint = Blueprint(bp_name, __name__)\n\nroute_inject(blueprint, urlpatterns)\n\nmodel_list = [Order, Item]\n\n\n@blueprint.before_app_first_request\ndef before_first_request():\n current_app.mongodb_database.register(model_list)\n return\n\n\n@blueprint.before_request\ndef before_request():\n\n verify_token()\n\n if request.endpoint in member_permission_endpoints:\n verify_member_permission()\n if request.endpoint in owner_permission_endpoints:\n verify_owner_permission()\n return\n\n\n@blueprint.errorhandler(APIError)\ndef blueprint_api_err(err):\n return make_json_response(err)\n","sub_path":"server_py/blueprints/order/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"437024091","text":"#Bar plots are used to represent comparision between the data points using the bars \n#either horizontally or vertically\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(4)\nmoney = [1, 2, 5, 6]\n\nplt.ylabel('Millions')\nplt.xlabel('Top Tycoons')\nplt.title('Richest in the World')\n\nplt.bar(x, money)\nplt.xticks(x, ('Gates', 'Warren', 'Mittal', 'Ambani'))\nplt.show()\n\n#-------------\n#import sys\n#y=range(100000)\n#sys.getsizeof(y)\n#z=np.arange(100000)\n#sys.getsizeof(z)\n\n","sub_path":"Class/Bar plot.py","file_name":"Bar plot.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"30904227","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport os\nimport astropy.units as u\n\nimport gwent\nimport gwent.binary as binary\nimport gwent.detector as detector\nimport gwent.snr as snr\n\ncurrent_path = os.path.abspath(gwent.__path__[0])\nload_directory = os.path.join(current_path,'LoadFiles/InstrumentFiles/')\n# Constants and Initial Parameters\n\n'''\nVariables:\n GLOBAL:\n 'T_obs' - Observation Time\n SOURCE:\n 'M' - Mass (Solar Units)\n 'q' - Mass Ratio\n 'chi1' - Spin1\n 'chi2' - Spin2\n 'z' - Redshift\n LISA ONLY:\n 'L' - Armlength\n 'A_acc' - Acceleration Noise\n 'A_IMS' - Optical Metrology\n 'f_acc_break_low'\n 'f_acc_break_high'\n 'f_IMS_break'\n PTAs ONLY:\n 'N_p' - Number of Pulsars\n 'sigma' - Timing Error RMS\n 'cadence' - cadence\n'''\n\nvar_y = 'z' #Variable on y-axis\n\nsampleRate_y = 50 #Number of SNRMatrix rows\n\nvar_x = 'M' #Variable on x-axis\n\nsampleRate_x = 50 #Number of SNRMatrix columns\n\n#Selects which noise curve:\n#\t\t\t\t\t\t\t0 is Einstein Telescope,\n#\t\t\t\t\t\t\t1 is aLIGO,\n#\t\t\t\t\t\t\t2 is NANOGrav 15yr,\n#\t\t\t\t\t\t\t3 is SKA (2030s),\n#\t\t\t\t\t\t\t4 is Neil Cornish's,\n#\t\t\t\t\t\t\tanything else is the L3 proposal\n\n\n# Source Selection\n\ndef Get_Source(model):\n if model == 0 or model == 1:\n #M = m1+m2 Total Mass\n M = 1e2\n M_min = 1e0\n M_max = 1e5\n elif model == 2 or model == 3:\n #M = m1+m2 Total Mass\n M = 1e8\n M_min = 1e7\n M_max = 1e11\n else:\n #M = m1+m2 Total Mass\n M = 1e6\n M_min = 1e1\n M_max = 1e10\n\n #q = m2/m1 reduced mass\n q = 1.0\n q_min = 1.0\n q_max = 18.0\n\n #Chi = S_i*L/m_i**2, spins of each mass i\n chi1 = 0.0 #spin of m1\n chi2 = 0.0 #spin of m2\n chi_min = -0.85 #Limits of PhenomD for unaligned spins\n chi_max = 0.85\n\n z = 3.0 #Redshift\n z_min = 1e-2\n z_max = 1e3\n\n source = binary.BBHFrequencyDomain(M,q,chi1,chi2,z)\n source.M = [M,M_min,M_max]\n source.q = [q,q_min,q_max]\n source.chi1 = [chi1,chi_min,chi_max]\n source.chi2 = [chi2,chi_min,chi_max]\n source.z = [z,z_min,z_max]\n\n return source\n\n\n# Model Selection\n\ndef Get_Instrument(model):\n if model == 0: #Einstein Telescope\n load_name = 'ET_D_data.txt'\n load_location = load_directory + 'EinsteinTelescope/StrainFiles/' + load_name\n\n T_obs = 4*u.yr #Observing time in years\n T_obs_min = 1*u.yr\n T_obs_max = 10*u.yr\n\n instrument = detector.GroundBased('ET',T_obs,load_location=load_location,I_type='A')\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n\n elif model == 1: #aLIGO\n load_name = 'aLIGODesign.txt'\n load_location = load_directory + 'aLIGO/StrainFiles/' + load_name\n\n T_obs = 4*u.yr #Observing time in years\n T_obs_min = 1*u.yr\n T_obs_max = 10*u.yr\n\n instrument = detector.GroundBased('aLIGO',T_obs,load_location=load_location,I_type='A')\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n\n elif model == 2: #NANOGrav 15 yr\n ###############################################\n #NANOGrav calculation using 11.5yr parameters https://arxiv.org/abs/1801.01837\n T_obs = 15*u.yr #Observing time in years\n T_obs_min = 10*u.yr\n T_obs_max = 30*u.yr\n\n sigma = 100*u.ns.to('s')*u.s #rms timing residuals in seconds\n\n N_p = 18 #Number of pulsars\n\n cadence = 1/(2*u.wk.to('yr')*u.yr) #Avg observation cadence of 1 every 2 weeks in num/year\n\n instrument = detector.PTA('NANOGrav',T_obs,N_p,sigma,cadence)\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n\n\n elif model == 3: #SKA (2030s)\n ###############################################\n #SKA calculation using parameters and methods from arXiv:0804.4476 section 7.1\n T_obs = 15*u.yr #Observing time (years)\n T_obs_min = 10*u.yr\n T_obs_max = 30*u.yr\n\n sigma = 10*u.ns.to('s')*u.s #rms timing residuals in nanoseconds\n\n N_p = 20 #Number of pulsars\n\n cadence = 1/(u.wk.to('yr')*u.yr) #Avg observation cadence of 1 every week in num/year\n\n instrument = detector.PTA('SKA',T_obs,N_p,sigma,cadence)\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n\n elif model == 4: #Robson,Cornish,and Liu 2018, LISA (https://arxiv.org/pdf/1803.01944.pdf)\n T_obs = 4*u.yr #Observing time in years\n T_obs_min = 1*u.yr\n T_obs_max = 10*u.yr\n\n L = 2.5e9*u.m #armlength in meters\n L_min = 1.0e7*u.m\n L_max = 1.0e11*u.m\n\n A_acc = 3e-15*u.m/u.s/u.s #M/s**2\n A_IMS = 1.5e-11*u.m\n f_IMS_break = 2.*u.mHz.to('Hz')*u.Hz\n f_acc_break_low = .4*u.mHz.to('Hz')*u.Hz\n f_acc_break_high = 8.*u.mHz.to('Hz')*u.Hz\n Background = False\n\n instrument = detector.SpaceBased('LISA_Alt',\n T_obs,L,A_acc,f_acc_break_low,\n f_acc_break_high,A_IMS,f_IMS_break,\n Background=Background,T_type='A')\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n instrument.L = [L,L_min,L_max]\n\n else: #L3 proposal\n #Default Params!\n T_obs = 4*u.yr #Observing time in years\n T_obs_min = 1*u.yr\n T_obs_max = 10*u.yr\n\n L = 2.5e9*u.m #armlength in meters\n L_min = 1.0e7*u.m\n L_max = 1.0e11*u.m\n\n f_acc_break_low = .4*u.mHz.to('Hz')*u.Hz\n f_acc_break_high = 8.*u.mHz.to('Hz')*u.Hz\n f_IMS_break = 2.*u.mHz.to('Hz')*u.Hz\n A_acc = 3e-15*u.m/u.s/u.s\n A_IMS = 10e-12*u.m\n Background = False\n\n instrument = detector.SpaceBased('LISA_ESA',\n T_obs,L,A_acc,f_acc_break_low,\n f_acc_break_high,A_IMS,f_IMS_break,\n Background=Background,T_type='N')\n instrument.T_obs = [T_obs,T_obs_min,T_obs_max]\n instrument.L = [L,L_min,L_max]\n\n return instrument\n\n#Whole Hog Creation of SNR Matrices and Samples\n\nmodels = [0,1,2,3,4,5]\nfor model in models:\n instrument = Get_Instrument(model)\n source = Get_Source(model)\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source,instrument,var_x,\n sampleRate_x,var_y,\n sampleRate_y)\n","sub_path":"tests/test_calcSNR.py","file_name":"test_calcSNR.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"553224143","text":"def specialPythagoreanTriplet():\n #digit must be between 1 and 1000\n for a in range(1,1000):\n \"\"\"\n -assuming its a special triplet no a,b,c value will be the same\n -so we can assume a scenario where our b-value has to be greater than the a value\n \"\"\"\n for b in range(a, 1000):\n #special rule of triangles, side c must be less than the sum of the other two sides\n for c in range(0, a+b):\n if(a+b+c==1000):\n if((a*a)+(b*b)==(c*c)):\n return a*b*c\n\nprint(specialPythagoreanTriplet())\n","sub_path":"python/Euler9.py","file_name":"Euler9.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"354601503","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for Huaban project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# https://doc.scrapy.org/en/latest/topics/settings.html\n# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html\n# https://doc.scrapy.org/en/latest/topics/spider-middleware.html\n\nBOT_NAME = 'Huaban'\n\nSPIDER_MODULES = ['Huaban.spiders']\nNEWSPIDER_MODULE = 'Huaban.spiders'\n\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'Huaban (+http://www.yourdomain.com)'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = True\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n#CONCURRENT_REQUESTS = 32\n\n# Configure a delay for requests for the same website (default: 0)\n# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\nDOWNLOAD_DELAY = 3\n# The download delay setting will honor only one of:\n# CONCURRENT_REQUESTS_PER_DOMAIN = 16\n# CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\n#COOKIES_ENABLED = False\n\n# Disable Telnet Console (enabled by default)\n#TELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\nDEFAULT_REQUEST_HEADERS = {\n 'X-Requested-With': 'XMLHttpRequest'\n}\n\n# Enable or disable spider middlewares\n# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html\n#SPIDER_MIDDLEWARES = {\n# 'Huaban.middlewares.HuabanSpiderMiddleware': 543,\n#}\n\n# Enable or disable downloader middlewares\n# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html\nDOWNLOADER_MIDDLEWARES = {\n 'Huaban.middlewares.HuabanDownloaderMiddleware': 543,\n 'Huaban.middleware.customProxy.RandomProxy': 300,\n # 'Huaban.middlewares.customUserAgent.RandomUserAgent': 543,\n # 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,\n # 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 400,\n}\n\n# Enable or disable extensions\n# See https://doc.scrapy.org/en/latest/topics/extensions.html\n#EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n#}\n\n# Configure item pipelines\n# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n 'Huaban.pipelines.HuabanPipeline': 300,\n}\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See https://doc.scrapy.org/en/latest/topics/autothrottle.html\n#AUTOTHROTTLE_ENABLED = True\n# The initial download delay\n#AUTOTHROTTLE_START_DELAY = 5\n# The maximum download delay to be set in case of high latencies\n#AUTOTHROTTLE_MAX_DELAY = 60\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\n#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\n#AUTOTHROTTLE_DEBUG = False\n\n# Enable and configure HTTP caching (disabled by default)\n# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n#HTTPCACHE_ENABLED = True\n#HTTPCACHE_EXPIRATION_SECS = 0\n#HTTPCACHE_DIR = 'httpcache'\n#HTTPCACHE_IGNORE_HTTP_CODES = []\n#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n\nMYSQL_URI = 'localhost'\nMYSQL_DATABASE = 'myproject'\nMYSQL_USER = 'root'\nMYSQL_PASSWORD = '12345'\n\nALL = '2588800336'\nFAVORITE = '2458976609'\nFOOD = '2589180968'\nTRAVEL = '2585640987'\nDIY = '2580700032'\nFITNESS = '2554750227'\nKIDS = '2584732752'\nPETS= '2585670295'\nQUOTES = '258758150'\nPEOPLE = '2587062426'\nBEAUTY = '2587250709'\nDESIRE = '2458976609'\nGEEK = '2566073958'\nANIME = '2584023522'\nARCHITECTURE = '2580688070'\nART = '2575024052'\nDATA_PRESENTATION = '2585277827'\nGAMES = '2585597004'\nCARS_MOTORCYCLES = '2588151149'\nFILM_MUSIC_BOOKS = '258874531'\nTIPS = '2469491725'\nEDUCATION = '2584388492'\nSPORTS = '2581699414'\nFUNNY = '2584281189'\n","sub_path":"Huaban/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394677635","text":"from datetime import datetime\n\n# Create your views here.\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils import timezone\nfrom django.template import loader\nfrom django.template.loader import get_template\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import login as do_login\nfrom django.contrib.auth import logout\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.template import Context\n\nfrom django.db.models import Sum, Count, Q, Case, When, Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils.translation import gettext_lazy as _\n\n#from urllib import request\nimport urllib.request\n\nfrom .forms import RegistrationForm, PagUsForm, AlimForm, ComentarioForm, UploadImageForm\nfrom .models import PagUsuario, tamano, estilous, Alimentador, Item, Comentario, Like\nfrom .ytalim import YTChannel\nfrom .redalim import SubReddit\nfrom .fmalim import FMArtista\nfrom .crear_docs import XML_create, JSON_create\n\n# Create your views here.\n\narchivo_like={1: ['like_sel.jpg', 'dis.jpg'],\n 0: ['like.jpg', 'dis.jpg'],\n -1: ['like.jpg', 'dis_sel.jpg'],\n}\n\ndef devolver_404(request, url, context):\n resp = render(request, url, context)\n resp.status_code = 404\n return resp\n\ndef info(request):\n return render(request, 'miscosas/info.html', {'nav_info': \"active\", 'recurso_us': \"/informacion\"})\n\ndef procesar_docs_users(request, lista):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_users(lista)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_users(lista)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/usuarios'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef usuarios(request):\n lista = PagUsuario.objects.all()\n if 'format' in request.GET.keys():\n return procesar_docs_users(request, lista)\n context = {'lista': lista, 'recurso_us': \"/usuarios\", 'nav_users': 'active'}\n return render(request, 'miscosas/usuarios.html', context)\n\ndef procesar_docs_alims(request, lista):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_alims(lista)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_alims(lista)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/alimentadores'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef alimentadores(request):\n lista = Alimentador.objects.all()\n if 'format' in request.GET.keys():\n return procesar_docs_alims(request, lista)\n context = {'lista': lista, 'recurso_us': \"/alimentadores\", 'nav_alims': 'active'}\n return render(request, 'miscosas/alimentadores.html', context)\n\ndef nombre_persona(user):\n #funcion que devuelve el nombre del usuario si esta registrado\n #o el codigo de la cookie en caso de no estarlo\n if user.is_authenticated:\n return user\n else:\n return \"\"\n\ndef guardar_us_enalim(user, id):\n #funcion que guarda el usuario al que le ha dado a elegir al alimentador\n alim = Alimentador.objects.get(id=id)\n if nombre_persona(user) != \"\":\n alim.usuario.add(nombre_persona(user))\n\ndef leer_xml(tipo, nombre):\n if tipo == \"yt\":\n id = YTChannel(nombre).id_canal()\n elif tipo == \"reddit\":\n id = SubReddit(nombre).id_reddit()\n elif tipo == \"fm\":\n id = FMArtista(nombre).id_artista()\n return id\n\ndef gestionar_alims(request):\n form = AlimForm(request.POST)\n if not form.is_valid():\n return -1\n\n tipo = form.cleaned_data['tipo_alimentador']\n nombre = form.cleaned_data['identificador_o_nombre']\n\n return leer_xml(tipo, nombre)\n#if 'enviar' in request.GET:\n #return redirect('/alimentador/'+str(alim.id))\n#un solo boton\n#elegio = False --> elegido= True, #añado a la lista de usuarios, actualizar datos\n#elegido = True--> elegido = False,\ndef procesar_docs_alim(request, alim):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_alim(alim)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_alim(alim)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/alimentador'+str(alim.id)}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef alimentador(request, id=-1):\n if request.method == \"POST\":\n id = gestionar_alims(request)\n if id == -1:\n context = {'error': _(\"No se ha podido encontrar la URL para ese alimentador\"),\n 'recurso_us': '/'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n else:\n guardar_us_enalim(request.user, id)\n return redirect('/alimentador/'+str(id))\n\n try:\n alim = Alimentador.objects.get(id=id)\n except ObjectDoesNotExist:\n context = {'error': _(\"El alimentador pedido no se encuentra\"),\n 'recurso_us': '/'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\n if 'format' in request.GET.keys():\n return procesar_docs_alim(request, alim)\n\n context = {'alim': alim, 'recurso_us': '/alimentador/'+str(alim.id)}\n return render(request, 'miscosas/alimentador.html', context)\n\ndef gestionar_voto(action, request, item):\n if action == \"like\":\n num = 1\n elif action == \"dislike\":\n num = -1\n try:\n voto = Like.objects.get(usuario=request.user, item=item)\n if voto.boton != num:\n voto.boton = num\n voto.fecha = datetime.now()\n except ObjectDoesNotExist:\n voto = Like(usuario=request.user, item=item, boton=num)\n voto.save()\n\ndef gestionar_comen(request, item):\n form = ComentarioForm(request.POST, request.FILES)\n if form.is_valid():\n comen = Comentario(texto= form.cleaned_data['texto'], usuario=request.user,\n item=item, foto=form.cleaned_data['foto'])\n comen.save()\n\ndef iluminar_voto(request, item):\n if request.user.is_authenticated:\n try:\n valor = request.user.like_set.get(item=item).boton\n except ObjectDoesNotExist:\n valor = 0\n else:\n valor = 0\n\n return archivo_like[valor][0], archivo_like[valor][1]\n\ndef procesar_docs_item(request, item):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_item(item)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_item(item)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/alimentador'+str(item.id)}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef mostrar_item(request, id):\n try:\n item = Item.objects.get(id=id)\n except ObjectDoesNotExist:\n context = {\"error\": _(\"El item pedido no existe\"), 'recurso_us': '/'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\n if request.method == \"POST\":\n action = request.POST['action']\n if action==\"comentario\":\n gestionar_comen(request, item)\n elif action==\"like\" or action ==\"dislike\":\n gestionar_voto(action, request, item)\n\n if 'format' in request.GET.keys():\n return procesar_docs_item(request, item)\n\n boton_like, boton_dislike = iluminar_voto(request, item)\n lista = Comentario.objects.filter(item=item)\n context = {'item': item, 'recurso_us': '/item/'+str(item.id),\n 'lista': lista, 'user': request.user, 'form': ComentarioForm(),\n 'boton_like': boton_like, 'boton_dislike': boton_dislike}\n return render(request, 'miscosas/item.html', context)\n\ndef add_boton_voto(top, request):\n for it in top:\n it.boton_like, it.boton_dislike = iluminar_voto(request, it)\n\ndef procesar_post_index(request):\n action = request.POST['action']\n if action == \"elegir\":\n alim = Alimentador.objects.get(id=request.POST['alim'])\n id = leer_xml(alim.tipo, alim.id_canal)\n alim.elegido = True\n alim.save()\n if id != -1:\n guardar_us_enalim(request.user, id)\n return redirect('/alimentador/'+str(alim.id))\n elif action == \"eliminar\":\n alim = Alimentador.objects.get(id=request.POST['alim'])\n alim.elegido = False\n alim.save()\n if 'enviar' in request.GET:\n return redirect('/alimentador/'+str(alim.id))\n elif action == \"like\" or action == \"dislike\":\n item = Item.objects.get(id=request.POST['item'])\n gestionar_voto(action, request, item)\n\n return redirect('/')\n\ndef procesar_docs(request, top10, top5, lista):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_index(top10, top5, lista)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_index(top10, top5, lista)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef index(request):\n #visto en: https://stackoverflow.com/questions/18198977/django-sum-a-field-based-on-foreign-key\n # y en: https://docs.djangoproject.com/en/3.0/topics/db/aggregation/\n #https://martinpeveri.wordpress.com/2018/06/24/la-funcion-coalesce-en-django/\n if request.method == \"POST\":\n return procesar_post_index(request)\n\n top10 = Item.objects.annotate(npos=Count('like', filter=Q(like__boton=1)),\n nneg= Count('like', filter=Q(like__boton=-1)),\n nlikes=Coalesce(Sum('like__boton'), Value(0))).order_by('-nlikes')[0:10]\n top5 = []\n if request.user.is_authenticated:\n add_boton_voto(top10, request)\n items_user = Item.objects.filter(like__usuario = request.user)\n fixed_date = datetime(2000, 1, 1)\n top5 = items_user.annotate(nueva_fecha=\n Coalesce('like__fecha', Value(fixed_date))).order_by('-nueva_fecha')[0:5]\n add_boton_voto(top5, request)\n\n lista = Alimentador.objects.all().filter(elegido=True)\n if 'format' in request.GET.keys():\n return procesar_docs(request, top10, top5, lista)\n\n #print(User.objects.get(username=\"daniel\").alimentador_set.all())\n\n context = {'user': request.user, 'recurso_us': '/', 'form': AlimForm(),\n 'nav_index': 'active', 'top10': top10, 'top5': top5, 'alims': lista}\n return render(request, 'miscosas/index.html', context)\n\n\ndef logout_view(request):\n logout(request)\n if 'recurso' in request.GET:\n recurso_us = request.GET['recurso']\n else:\n recurso_us = '/'\n return redirect(recurso_us)\n\n\ndef login_view(request):\n if 'recurso' in request.GET:\n recurso_us = request.GET['recurso']\n else:\n recurso_us = '/'\n\n if request.method == \"POST\":\n action = request.POST['action']\n request.POST = request.POST.copy()\n if action==\"Registrar\":\n request.POST['password1'] = request.POST['password']\n form = RegistrationForm(data=request.POST)\n msg = _(\"Informacion de autenticacion no valida, o el usuario ya tiene cuenta\")\n else:\n form = AuthenticationForm(data=request.POST)\n msg = _(\"El usuario o la contraseña no son correctos\")\n if form.is_valid():\n if action==\"Registrar\":\n user = form.save()\n pagUs = PagUsuario(usuario = user)\n pagUs.save()\n else:\n # Verificamos las credenciales del usuario\n user = authenticate(username=form.cleaned_data['username'],\n password=form.cleaned_data['password'])\n # Si existe un usuario con ese nombre y contraseña, o se crea correctamente\n if user is not None:\n do_login(request, user)\n else:\n context = {'recurso_us': recurso_us, 'error': msg, 'recurso_us': '/'}\n return render(request, 'miscosas/pag_error.html', context)\n\n return redirect(recurso_us)\n\ndef procesar_post_pagus(request):\n action = request.POST['action']\n pagUsEstilo = PagUsuario.objects.get(usuario=request.user)\n\n if action == \"foto\":\n form = UploadImageForm(request.POST, request.FILES)\n if form.is_valid():\n pagUsEstilo.foto = form.cleaned_data['foto']\n elif action == \"formato\":\n form = PagUsForm(request.POST)\n if form.is_valid():\n pagUsEstilo.tamLetra = form.cleaned_data['tamano']\n pagUsEstilo.estilo = form.cleaned_data['estilo']\n pagUsEstilo.save()\n\ndef procesar_docs_us(request, pag_us):\n doc = request.GET['format']\n if doc == \"xml\":\n return HttpResponse(XML_create().xml_us(pag_us)\n , content_type=\"text/xml\")\n elif doc == \"json\":\n return HttpResponse(JSON_create().json_us(pag_us)\n , content_type=\"application/json\")\n else:\n context = {'error': _(\"No se soporta ese tipo de documento\"), 'recurso_us': '/'+pag_us.usuario.username}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\ndef cuenta_usuario(request, us):\n if request.method == 'POST':\n procesar_post_pagus(request)\n\n try:\n usuario = User.objects.get(username=us)\n pagUsEstilo = PagUsuario.objects.get(usuario=usuario)\n except ObjectDoesNotExist:\n context = {'error': _(\"El usuario pedido no existe\"), 'recurso_us': '/'}\n return devolver_404(request, 'miscosas/pag_error.html', context)\n\n if 'format' in request.GET.keys():\n return procesar_docs_us(request, pagUsEstilo)\n\n lista_vot = Item.objects.filter(like__usuario=usuario)\n lista_comen = Item.objects.filter(comentario__usuario=usuario).distinct()\n lista_sel = Alimentador.objects.filter(usuario=usuario)\n context = {'form_estilo': PagUsForm(), 'usuario': usuario, 'recurso_us': '/usuario/'+us,\n 'pag_us': pagUsEstilo, 'form_foto': UploadImageForm(),\n 'us_log': request.user, 'lista_vot': lista_vot,\n 'lista_comen': lista_comen, 'lista_sel': lista_sel}\n return render(request, 'miscosas/usuario.html', context)\n\n\ndef procesar_css(request):\n template = get_template(\"miscosas/micss.css\")\n try:\n username = request.user.get_username()\n pag_usuario = PagUsuario.objects.get(usuario__username=username)\n estilo = estilous[pag_usuario.estilo]\n tam = tamano[pag_usuario.tamLetra]\n except ObjectDoesNotExist:\n estilo = estilous['ligero']\n tam = tamano['mediana']\n tam.update(estilo)\n context = Context(tam)\n return HttpResponse(template.render(tam), content_type=\"text/css\")\n","sub_path":"proyecto/miscosas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"197482066","text":"import functions as f\nimport params as p\n# if you are executing the code from your raspberry with a cam module and a SenseHat connected set simulation = False, otherwise use the simulation mode\nsimulation_mode = False\n\nfrom imutils.video import VideoStream\nimport numpy as np\nimport cv2\nimport numpy as np\nimport time\nif not simulation_mode:\n from sense_hat import SenseHat\nelse:\n from sense_emu import SenseHat\n \nsense = SenseHat()\nsense.clear()\n\nvs = VideoStream(usePiCamera = not simulation_mode).start()\ntime.sleep(1.0)\n\ncv2.namedWindow(\"ROV\", cv2.WINDOW_NORMAL) \ncv2.resizeWindow('ROV', 600,600)\n\nauto = False\nuse_keyboard = True\nuse_controller = False\n\n\n\n\n \ntelemetry_dict = {'light' : 'OFF'} \n \nif auto:\n yaw_abs = sense.get_accelerometer()['yaw']\n press_abs = sense.get_pressure()\ndict_sensors = 0\n\n\n\ndirection = ''\nwhile True:\n telemetry_dict['direction'] = direction\n frame = vs.read()\n dict_sensors = f.get_dict_sensors(sense, telemetry_dict)\n f.display_telemetry(frame, dict_sensors)\n cv2.imshow(\"ROV\", frame)\n direction = ''\n key = cv2.waitKey(1) & 0xFF\n if auto:\n if 0 < gyro['yaw'] < 180:\n f.motor_react(p.motor_back_dx, p.green)\n f.motor_react(p.motor_back_sx, p.red)\n elif 180 < gyro['yaw'] < 360:\n f.motor_react(p.motor_back_sx, p.green)\n f.motor_react(p.motor_back_dx, p.red)\n if press > press_abs:\n f.motor_react(p.motor_vert, p.green)\n elif press < press_abs:\n f.motor_react(p.motor_vert, p.red)\n if use_keyboard:\n if key == 27:\n print('[INFO] Programma interrotto')\n break\n if key == 32:\n print('[INFO] Pause')\n cv2.waitKey(0)\n\n # MOVEMENTS \n # right pad\n if key == ord('e'):\n direction = 'forward'\n f.motor_react(p.motor_back_dx, p.green)\n f.motor_react(p.motor_back_sx, p.red)\n if key == ord('d'):\n direction = 'backward'\n if key == ord('f'):\n direction = 'right'\n if key == ord('s'):\n direction = 'left'\n # left pad\n if key == 112:\n direction = 'up'\n if key == 210:\n direction = 'down'\n if key == ord('l'):\n direction = 'shift_left'\n if key == 192:\n direction = 'shift_right'\n if key == ord('k'):\n direction = 'roll_left'\n if key == 217:\n direction = 'roll_right'\n\n # LIGHTS\n if key == ord('n'):\n dict_sensors['light'] = 'ON'\n f.lights(True)\n if key == ord('m'):\n dict_sensors['light'] = 'OFF'\n f.lights(False)\n\ncv2.destroyAllWindows()\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"598018500","text":"#!/usr/bin/env python\n\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom interpreter.msg import direction_signals\nimport os, copy, sys, math\nimport rospy as rp\nimport numpy as np\nimport cv2\n\n'''\nManages rate at which images are released to the driving nodes.\n'''\nclass ImageManager(object):\n\n def __init__(self):\n self.incoming = rp.Subscriber('/mv_26806920/image_raw', Image, self.on_incoming)\n self.outgoing = rp.Publisher('/released_images', Image, queue_size=10)\n self.im_counter = 0\n\n self.image = None\n \n '''\n New image recieved.\n '''\n def on_incoming(self, image_msg):\n self.image = image_msg\n\n '''\n Release the most recent image.\n '''\n def release_image(self, image):\n self.outgoing.publish(image)\n\n\nif __name__ == '__main__':\n rp.init_node('image_gate', anonymous=True)\n try:\n gate = ImageManager()\n rate = rp.Rate(3) # 6\n while not rp.is_shutdown():\n if not gate.image is None:\n gate.im_counter += 1\n gate.release_image(gate.image)\n rate.sleep()\n\n except KeyboardInterrupt:\n print('Termination triggered.')\n \n cv2.destroyAllWindows()\n print('-- Done --')","sub_path":"src/Interpreter/src/camera_gate.py","file_name":"camera_gate.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"13688527","text":"\"\"\"\n# @Time : 2020/8/26\n# @Author : Jimou Chen\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport requests\nfrom urllib.parse import urljoin\n\n\nclass Crawler:\n def __init__(self):\n self.queue = set() # 存放抓取的url\n self.processed = set() # 存放已经处理过的url\n\n def crawl(self, url):\n if url not in self.processed:\n resp = requests.get(url)\n soup = BeautifulSoup(resp.content.decode('UTF-8'), 'html.parser')\n # 第一页的\n for i in soup.find('div', {'class': 'listList'}).find_all('li'):\n print('{}: {}'.format(i.find_all('span')[1].text, i.a.text))\n # 其他页的\n for i in soup.find_all('span', {'class': 'p_no'}):\n self.queue.add(urljoin(url, i.a.get('href')))\n self.processed.add(url)\n\n def run(self, url):\n self.queue.add(url)\n while self.queue:\n self.crawl(self.queue.pop())\n\n\nif __name__ == '__main__':\n Crawler().run('http://www.dgut.edu.cn/xwzx/ggyw.htm')","sub_path":"PythonLearning/Crawler/多页爬虫.py","file_name":"多页爬虫.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"197348920","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\n\"\"\" Plot top 10 biggest gained and 10 biggest lost coins\nLeft: gain\nRight: Lose\n\"\"\"\ndef top10_subplot(volatility_series,title):\n fig,axes=plt.subplots(1,2,figsize=(10, 6))# 1 rows, 2 col\n # Top 10 loses\n ax=volatility_series[:10].plot(ax=axes[0],kind=\"bar\",color=\"darkred\",x=\"id\")\n ax.set_title(\"Losers\"+title)\n ax.set_ylabel(\"% change\")\n ax.set_xlabel(\"\")\n # Top 10 gain\n ax=volatility_series[-10:].plot(ax=axes[1],kind=\"bar\",color=\"darkblue\",x=\"id\")\n ax.set_title(\"Gainers\" + title)\n ax.set_ylabel(\"% change\")\n ax.set_xlabel(\"\")\n fig.suptitle(title)\n plt.show()\n\n\n\n\n\n\n# To load files. dirname can be created by 2 ways:\n# 1.\ndirname = os.path.dirname(__file__)# Get the path of current script\n# 2. dirname=os.path.dirname(os.path.abspath(__file__))\n\ncsvfilename = os.path.join(dirname, 'coinmarketcap_06122017.csv')\ndec6=pd.read_json(csvfilename)\nmarket_cap_raw = dec6[[\"id\",\"market_cap_usd\"]]\nprint(market_cap_raw.count())\n# Count() has axis=0 as default, means row-wise. This means a row which not contain any NaN will be count.\n\n\n# Filtering rows with market_cap_usd >0\ncap = market_cap_raw.query(\"market_cap_usd > 0\")\nprint(cap.head())\nprint(cap.count())\n\n\"\"\" Visualize top 10 cryptocurrencies\n\"\"\"\n#Select 10 coins and set index to id\ncap10=cap[:10].set_index(\"id\")\n# Calculate percentage of market capitalization for each coin by\n# creating a new column using assign()\ncap10=cap10.assign(market_cap_perc=lambda x: (x.market_cap_usd/cap.market_cap_usd.sum())*100)\n# Ploting bar plot using numpy function\nax=cap10[\"market_cap_perc\"].plot.bar()\nax.set_title(\"Top 10 market capitalization\")\nax.set_ylabel(\"% of total cap\")\n\n\"\"\" Make plot easier to read and informative: \n1. group coins into group and color\n2. change y scale to log\n\"\"\"\nCOLORS = ['orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'silver', 'orange', 'red', 'green']\nax1=cap10[\"market_cap_perc\"].plot.bar(color=COLORS,logy=True)\nax1.set_title(\"Top 10 market capitalization (enhanced)\")\nax1.set_ylabel(\"USD\")\nax1.set_xlabel(\"\")\n\n\"\"\" Prove that cryptocurrencies is volatility \n\"\"\"\nvolatility=dec6[[\"id\",\"percent_change_24h\",\"percent_change_7d\"]]\n# Drop row which contains any NaN\nvolatility.dropna(axis=0,how=\"any\")\nvolatility.index=volatility[\"id\"]\n\n\"\"\" Plot 10 losers and gainers in 24h\n\"\"\"\n# Sort, now using sort_values, default is ascending\nvolatility.sort_values([\"percent_change_24h\"])\nprint(volatility.head())\ntop10_subplot(volatility.percent_change_24h, \"24h\")\n\n\"\"\"Plot 10 losers and gainers in weeks\n\"\"\"\nvolatility.sort_values([\"percent_change_7d\"])\nprint(volatility.head())\ntop10_subplot(volatility.percent_change_7d,\"7d\")\n","sub_path":"bitcoin.py","file_name":"bitcoin.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"523884787","text":"import logging\nfrom logging.handlers import RotatingFileHandler\n\nimport time\nimport os\n\nfrom egovbench_scorer import TwitterScorer\nfrom egovbench_mongo import TwitterMongoConnector\n\n\nclass TwitterTrigger():\n\n def createdirectory(self, path):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n\n def __init__(self):\n\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n if not logger.handlers:\n\n logpath = '/home/addi/egovbench/logs/twitter/egovbench_twittertrigger.log'\n\n try:\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n\n fh = RotatingFileHandler(logpath, maxBytes=20971520, backupCount=5)\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n except FileNotFoundError:\n self.createdirectory(logpath)\n\n self.tmc = TwitterMongoConnector()\n\n def prompt(self, texts):\n logging.info('[EGOVBENCH_TWITTERTRIGGER]>' + ' ' + texts)\n\n def launch(self):\n\n self.prompt('Launching trigger . . .')\n\n self.tmc.resetTemp()\n\n counter = 0\n\n while True:\n\n cursor = self.tmc.activateTailableCursor()\n\n while cursor.alive:\n try:\n message = cursor.next()\n self.prompt('(account_id: {}) Message received!'.format(message['id']))\n\n self.pushAccountResult(message['id'])\n\n self.prompt('===================================================================')\n\n counter += 1\n\n if counter % 100 == 0:\n self.pushPostTypeResult()\n\n except StopIteration:\n time.sleep(1)\n\n def pushPostTypeResult(self):\n\n ts = TwitterScorer(None)\n\n ts.getPostTypeStatisticDocument()\n\n ts.getPostTypeScoreDocument()\n\n def pushAccountResult(self, value):\n\n filter_dict = {'account_id': value}\n\n ts = TwitterScorer(filter_dict)\n\n accountStatisticDocument = ts.getAccountStatisticDocument()\n self.tmc.updateAccountResult(accountStatisticDocument)\n\n accountScoreDocument = ts.getAccountScoreDocument()\n self.tmc.updateAccountResult(accountScoreDocument)\n\n accountPostTypeScoreDocument = ts.getAccountPostTypeScoreDocument()\n self.tmc.updateAccountResult(accountPostTypeScoreDocument)\n\n self.tmc.updatePemdaScores(value)\n\n\nif __name__ == '__main__':\n trigger = TwitterTrigger()\n trigger.pushPostTypeResult()\n trigger.launch()\n","sub_path":"egovbench_twittertrigger.py","file_name":"egovbench_twittertrigger.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"277093152","text":"\n\nfrom xai.brain.wordbase.verbs._expel import _EXPEL\n\n#calss header\nclass _EXPELLED(_EXPEL, ):\n\tdef __init__(self,): \n\t\t_EXPEL.__init__(self)\n\t\tself.name = \"EXPELLED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"expel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_expelled.py","file_name":"_expelled.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"622904060","text":"from rest_framework import serializers\n\nfrom .models import League, Schedule, Team, TeamRecord, Player, Roster\n\nclass LeagueSerializer(serializers.Serializer):\n pk = serializers.IntegerField(read_only=True)\n name = serializers.CharField(max_length=255)\n schedule = serializers.SerializerMethodField()\n team_list = serializers.SerializerMethodField()\n\n def get_team_list(self, obj):\n team_list = list(map(lambda x: {\"name\": x.name, \"tid\": x.tid}, obj.league.all()))\n return team_list\n\n def get_schedule(self, obj):\n return obj.schedule.pk\n\n\n def validate_name(self, value):\n \"\"\"\n Check if name is unique\n \"\"\"\n league = League.objects.filter(name=value)\n\n if league:\n raise serializers.ValidationError(\"League '{}' already exists\".format(value))\n return value\n\n def create(self, validated_data):\n schedule = Schedule()\n schedule.save()\n league = League.objects.create(schedule=schedule, **validated_data)\n return league\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.save()\n return instance\n\nclass Custom_LeagueSerializer(serializers.Serializer):\n pk = serializers.IntegerField()\n name = serializers.CharField(max_length=255, read_only=True)\n\n def validate_pk(self, value):\n league = League.objects.filter(pk=value)\n\n if not league:\n raise serializers.ValidationError(\"Invalid PK for League\")\n return value\n\n\n\n\n'''\nRoster\n'''\nclass Custom_PlayerSerializer(serializers.Serializer):\n pid = serializers.CharField(max_length=255)\n first_name = serializers.CharField(max_length=255, read_only=True)\n last_name = serializers.CharField(max_length=255, read_only=True)\n\n\nclass RosterSerializer(serializers.ModelSerializer):\n # player_list = serializers.SerializerMethodField()\n #\n # def get_player_list(self, obj):\n # return Custom_PlayerSerializer(obj.players.all(), many=True).data\n\n players = Custom_PlayerSerializer(many=True)\n\n class Meta:\n model = Roster\n fields = (\"pk\", \"editable\", 'players')\n extra_kwargs = {\n 'pk': {\n 'read_only': True\n }\n }\n\n\n def update(self, instance, validated_data):\n all_players = instance.roster.team.player.all()\n print (all_players)\n\n if \"players\" in validated_data:\n\n new_players = []\n for player in validated_data[\"players\"]:\n player_obj = Player.objects.filter(pid=player[\"pid\"]).first()\n if player_obj in all_players:\n new_players.append(player_obj)\n else:\n raise serializers.ValidationError(\"Invalid PID\")\n\n instance.players.clear()\n instance.players.add(*new_players)\n\n instance.save()\n return instance\n\n\n'''\nTeam\n'''\nclass Custom_TeamRecordSerializer(serializers.ModelSerializer):\n class Meta:\n model = TeamRecord\n #fields = ('play', 'win', 'lose', 'draw', 'point', 'goal_for', 'goal_against', 'goal_difference', 'yellow', 'red')\n fields = ('pk',)\n\nclass TeamSerializer(serializers.ModelSerializer):\n league = Custom_LeagueSerializer(many=True, required=False)\n tid = serializers.CharField(read_only=True, max_length=255)\n team_record = Custom_TeamRecordSerializer(many=True, read_only=True)\n player = Custom_PlayerSerializer(many=True, read_only=True)\n\n class Meta:\n model = Team\n fields = ('tid', 'name', 'league', \"team_record\", \"player\")\n\n def create(self, validated_data):\n league_data = None\n if 'league' in validated_data:\n league_data = validated_data.pop('league')\n\n team = Team.objects.create(**validated_data)\n\n if league_data:\n for league in league_data:\n obj, created = League.objects.get_or_create(**league)\n team.league.add(obj)\n team_roster = Roster()\n team_roster.save()\n team_record = TeamRecord(team=team, roster=team_roster, league=obj)\n team_record.save()\n return team\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n\n pk_list = []\n\n if \"league\" in validated_data:\n for league in validated_data[\"league\"]:\n pk_list.append(league['pk'])\n\n if not League.objects.filter(pk=league['pk']):\n raise serializers.ValidationError(\"Team doesn't exist\")\n\n instance.league.clear()\n\n for league in validated_data[\"league\"]:\n league = League.objects.filter(pk=league['pk']).first()\n instance.league.add(league)\n\n #Check existing records and remove unnecessary ones\n for record in instance.team_record.all():\n if record.league.pk in pk_list:\n pk_list.remove(record.league.pk)\n else:\n record.delete()\n\n #Create new record\n for pk in pk_list:\n team_roster = Roster()\n team_roster.save()\n team_record = TeamRecord(team=instance, roster=team_roster, league=League.objects.get(pk=pk))\n team_record.save()\n\n instance.save()\n return instance\n\n\n\n'''\nTeam Record\n'''\nclass TeamRecordSerializer(serializers.ModelSerializer):\n team = TeamSerializer(read_only=True)\n league = LeagueSerializer(read_only=True)\n # roster = RosterSerializer(read_only=True)\n roster_info = serializers.SerializerMethodField()\n\n def get_roster_info(self, obj):\n return {\n 'pk': obj.roster.pk,\n \"league\":obj.league.name\n }\n\n class Meta:\n model = TeamRecord\n fields = ('pk', 'team','league', 'play', 'win', 'lose', 'draw', 'point', 'goal_for', 'goal_against', 'goal_difference', 'yellow', 'red', 'roster_info')\n extra_kwargs={\n 'pk':{\n 'read_only':True\n }\n }\n\n def update(self, instance, validated_data):\n instance.play = validated_data.get('play', instance.play)\n instance.win = validated_data.get('win', instance.win)\n instance.lose = validated_data.get('lose', instance.lose)\n instance.draw = validated_data.get('draw', instance.draw)\n instance.point = validated_data.get('point', instance.point)\n instance.goal_for = validated_data.get('addgoal_forress', instance.goal_for)\n instance.goal_against = validated_data.get('goal_against', instance.goal_against)\n instance.goal_difference = validated_data.get('goal_difference', instance.goal_difference)\n instance.yellow = validated_data.get('yellow', instance.yellow)\n instance.red = validated_data.get('red', instance.red)\n\n instance.save()\n\n return instance\n\n\n\n\n\n'''\nPlayer\n'''\nclass Custom_TeamSerializer(serializers.Serializer):\n name = serializers.CharField(max_length=255, read_only=True)\n tid = serializers.CharField(max_length=255)\n\n def validate_name(self, value):\n team = Team.objects.filter(name=value)\n\n if not team:\n raise serializers.ValidationError(\"Team doesn't exist\")\n return value\n\nclass PlayerSerializer(serializers.ModelSerializer):\n team = Custom_TeamSerializer()\n\n class Meta:\n model = Player\n fields = ('pid', 'first_name', 'last_name', 'email', 'dob', 'phone', 'address', 'team')\n extra_kwargs={\n 'pid':{\n 'read_only':True\n }\n }\n\n def get_serialzer_context(self):\n return self.context\n\n\n def create(self, validated_data):\n # tid = self.get_serialzer_context().get('tid', None)\n #\n # team = Team.objects.filter(tid=tid)\n\n team = validated_data.pop('team')\n team = Team.objects.filter(tid=team['tid'])\n\n if team:\n player = Player.objects.create(team=team.first(), **validated_data)\n else:\n raise serializers.ValidationError(\"Team doesn't exist\")\n\n return player\n\n def update(self, instance, validated_data):\n if 'team' in validated_data:\n team = Team.objects.filter(tid=validated_data[\"team\"]['tid']).first()\n if not team:\n raise serializers.ValidationError(\"Team doesn't exist\")\n else:\n instance.team = team\n\n instance.first_name = validated_data.get('first_name', instance.first_name)\n instance.last_name = validated_data.get('last_name', instance.last_name)\n instance.email = validated_data.get('email', instance.email)\n instance.dob = validated_data.get('dob', instance.dob)\n instance.phone = validated_data.get('phone', instance.phone)\n instance.address = validated_data.get('address', instance.address)\n\n instance.save()\n return instance","sub_path":"backend/league_manager/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":9060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"338641275","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom django.views import View\nfrom django.utils import timezone\n\nfrom .models import Video, comment\nfrom django.shortcuts import render, get_object_or_404, redirect\n# Create your views here.\n\ndef get(request, Video_id):\n get_video = Video.objects.get(pk=Video_id)\n return JsonResponse({\n 'subject':get_video.subject,\n 'content':get_video.content,\n 'create_date':get_video.create_date\n })\n\ndef delete(request, Video_id):\n delete_video = Video.objects.get(pk=Video_id)\n delete_video.delete()\n return redirect('/my_app/')\n\ndef update(request, Video_id):\n update_video = Video.objects.get(pk=Video_id)\n update_video.subject = request.POST.get('subject')\n update_video.content = request.POST.get('content')\n update_video.save()\n return redirect('/my_app/')\n\ndef edit(request, Video_id):\n edit_video = Video.objects.get(pk=Video_id)\n context = {'edit_video':edit_video}\n return render(request, 'my_app/Video_edit.html', context)\n\ndef list(request):\n Video_list = Video.objects.order_by('-create_date')\n context = {'Video_list':Video_list}\n return render(request, 'my_app/Video_list.html', context) # render 함수는 context 에 있는 데이터를\n #video_list.html파일에 적용하여 html 코드로 변환한다. 장고에서는 video_list.html 같은 파일을 템플릿이라고 한다.\n\ndef detail(request, Video_id):\n OneVideo = get_object_or_404(Video, pk=Video_id)\n context = {'OneVideo':OneVideo}\n return render(request, 'my_app/Video_detail.html', context)\n \ndef comment_create(request, Video_id):\n video = get_object_or_404(Video, pk=Video_id)\n new_comment = comment(subject=video, content=request.POST.get('content'), create_date=timezone.now())\n new_comment.save()\n return redirect('my_app:detail', Video_id=video.id)\n\n\"\"\"\n@api_view(['GET','POST'])\ndef index(request):\n return Response({\n 'status' : status.HTTP_200_OK,\n 'req_method' : request.method\n })\n\"\"\"\n\n\"\"\"\ndef detail(request, Video_id):\n vVideo = get_object_or_404(Video, pk=Video_id)\n context = {'vVideo': vVideo}\n return render(request, 'my_app/Video_detail.html', context)\n\n\ndef video(request):\n return HttpResponse(\"

비디오 쭈루룩 있는 화면

\")\n\"\"\"\n","sub_path":"backend/assignment1/my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"402232524","text":"#!/usr/bin/env python\n# PySys System Test Framework, Copyright (C) 2006-2018 M.B.Grieve\n\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n\n# This library 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 GNU\n# Lesser General Public License for more details.\n\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n# Contact: moraygrieve@users.sourceforge.net\n\nfrom __future__ import print_function\nimport time, threading\n\nfrom pysys.constants import *\n\n\nclass ProcessMonitor(object):\n\t\"\"\"Process monitor for the logging of process statistics.\n\t\n\tThe process monitor uses either the win32pdh module (windows systems) or the ps command line utility \n\t(unix systems) to obtain and log to file statistics on a given process as determined by the process id. \n\tUsage of the class is to create an instance specifying the process id, the logging interval and the log \n\tfile. Once created, the process monitor is started and stopped via its L{start} and L{stop} methods. \n\tProcess monitors are started as a separate thread, so control passes back to the caller of the start method \n\timmediately.\n\t\n\tOn windows systems, statistics obtained include the CPU usage (%), the working set (memory pages allocated), \n\tthe virtual bytes (virtual address space including shared memory segments), the private bytes (virtual \n\taddress space not including shared memory segments), the number of process threads and the number of \n\thandles. All memory values are quoted in KBytes and the CPU precentage represents the usage over all available \n\tprocessors. A CPU usage of 100% represents a single CPU fully utilized; it is therefore possible to obtain CPU \n\tusage figures of over 100% on multi-core processors. The format of the log file is tab separated, with \n\ttimestamps used to denote the time each measurement was obtained, e.g. ::\t\t\n\t\n\t\tTime CPU Working Virtual Private Threads Handles\n\t\t------------------------------------------------------------------------\n\t\t09/16/08 14:20:44 80 125164 212948 118740 44 327\n\t\t09/16/08 14:20:49 86 125676 213972 120128 44 328\n\t\t09/16/08 14:20:54 84 125520 212948 119116 44 328\n\t\t09/16/08 14:20:59 78 125244 212948 119132 44 328\n\n\n\tOn unix systems, statistics obtained include the CPU usage (%), the resident memory (via the rss format specifier\n\tto ps), and the virtual memory (via the vsz format spepcifier to ps). All memory values are quoted in KBytes and \n\tthe CPU precentage represents the usage over all available processors. A CPU usage of 100% represents a single \n\tCPU fully utilized; it is therefore possible to obtain CPU usage figures of over 100% on multi-core processors. \n\tThe format of the log file is tab separated, with timestamps used to denote the time each measurement was obtained, \n\te.g. ::\t\t\n\n\t\tTime CPU Resident Virtual\n\t\t----------------------------------------------------\n\t\t09/16/08 14:24:10 69.5 89056 1421672\n\t\t09/16/08 14:24:20 73.1 101688 1436804\n\t\t09/16/08 14:24:30 82.9 102196 1436516\n\t\t09/16/08 14:24:40 89.1 102428 1436372\n\t\t09/16/08 14:24:50 94.2 104404 1438420\n\n\n\tBoth windows and unix operating systems support the numProcessors argument in the variable argument list in order \n\tto normalise the CPU statistics gathered by the number of available CPUs.\n\n\t\"\"\"\n\t\t\n\tdef __init__(self, pid, interval, file=None, **kwargs):\n\t\t\"\"\"Construct an instance of the process monitor.\n\t\t\n\t\t@param pid: The process id to monitor\n\t\t@param interval: The interval in seconds to record the process statistics\n\t\t@param file: The full path to the file to log the process statistics\n\t\t@param kwargs: Keyword arguments to allow platform specific configurations\n\t\t\n\t\t\"\"\"\n\t\tself.pid = pid\n\t\tself.interval = interval\n\t\tif file:\n\t\t\tself.file = open(file, 'w')\n\t\telse:\t\n\t\t\tself.file = sys.stdout\t\t\n\t\n\t\t# normalise the CPU readings by the supplied factor\n\t\tself.numProcessors=1\n\t\tif \"numProcessors\" in kwargs: \n\t\t\tself.numProcessors = int(kwargs[\"numProcessors\"])\n\t\t\n\t\t\n\tdef __findChildren(self, psList, parentPid):\n\t\tchildren = []\n\t\tchildren.append(int(parentPid))\n\t\t\n\t\tfor i in range(1, len(psList)):\n\t\t\tpid = int(psList[i].split()[0])\n\t\t\tppid = int(psList[i].split()[1])\n\t\t\tif ppid == parentPid:\n\t\t\t\tchildren[len(children):] = self.__findChildren(psList, pid)\n\t\t\t\t\n\t\treturn children\n\n\n\tdef __linuxLogProfile(self, pid, interval, file, includeChildren=True):\n\t\t# sleep - fixes weird problem of thread hanging?\n\t\ttime.sleep(1)\n\t\t\n\t\t# get the child process tree for this process\n\t\tif (includeChildren):\n\t\t\tfp = os.popen(\"ps -o pid,ppid\")\n\t\t\tpsList = fp.readlines()\n\t\t\tfp.close()\n\t\t\tpidTree = self.__findChildren(psList, pid)\n\t\telse:\n\t\t\tpidTree = [pid]\n\t\t\n\t\t# perform the repeated collection of data for the profile. \n\t\ttry:\n\t\t\twhile self.active:\n\t\t\t\tdata = [0, 0, 0]\n\t\t\t\tfp = os.popen(\"ps -o pid,pcpu,rss,vsz\")\n\t\t\t\tinfo = fp.readlines()\n\t\t\t\tfp.close()\n\t\t\t\t\n\t\t\t\tfor i in range(1, len(info)):\n\t\t\t\t\tif int(info[i].split()[0]) in pidTree:\n\t\t\t\t\t\tdata[0] = data[0] + float(info[i].split()[1])\n\t\t\t\t\t\tdata[1] = int(info[i].split()[2])\n\t\t\t\t\t\tdata[2] = int(info[i].split()[3])\n\t\n\t\t\t\tcurrentTime = time.strftime(\"%m/%d/%y %H:%M:%S\", time.gmtime(time.time()))\n\t\t\t\tfile.write( \"%s\\t%f\\t%d\\t%d\\n\" % (currentTime, float(data[0])/self.numProcessors, data[1], data[2]) )\n\t\t\t\tfile.flush()\n\t\t\t\ttime.sleep(interval)\n\t\n\t\t\t# clean up\t\t\t\n\t\tfinally:\n\t\t\tif file != sys.stdout: file.close()\n\t\t\tself.active = 0\n\n\n\tdef __solarisLogProfile(self, pid, interval, file):\t\n\t\t# perform the repeated collection of data for the profile. \n\t\tdata = [-1, -1, -1]\n\t\ttry:\n\t\t\twhile self.active:\n\t\t\t\ttry:\n\t\t\t\t\tfp = os.popen(\"ps -p %s -o pcpu,rss,vsz\" % (pid))\n\t\t\t\t\tinfo = fp.readlines()[1]\n\t\t\t\t\tfor i in range(len(data)):\n\t\t\t\t\t\tdata[i] = info[i].split()\n\t\t\t\t\tfp.close()\n\t\t\t\texcept Exception:\n\t\t\t\t\tfp.close()\n\t\t\t\tcurrentTime = time.strftime(\"%m/%d/%y %H:%M:%S\", time.gmtime(time.time()))\n\t\t\t\tfile.write( \"%s\\t%s\\t%s\\t%s\\n\" % (currentTime, float(data[0])/self.numProcessors, data[1], data[2]) )\n\t\t\t\tfile.flush()\n\t\t\t\ttime.sleep(interval)\n\t\tfinally:\n\t\t\tif file != sys.stdout: file.close()\n\t\t\tself.active = 0\n\n\n\t# public methods to start and stop a process monitor thread\n\tdef running(self):\n\t\t\"\"\"Return the running status of the process monitor.\n\t\t\n\t\t@return: The running status (True | False)\n\t\t@rtype: integer\n\t\t\"\"\"\n\t\treturn self.active\n\t\n\t\n\tdef start(self):\n\t\t\"\"\"Start the process monitor.\n\t\t\n\t\t\"\"\"\n\t\tself.active = 1\n\t\t\n\t\tif PLATFORM == 'sunos':\n\t\t\tt = threading.Thread(target=self.__solarisLogProfile, args=(self.pid, self.interval, self.file))\n\t\telse:\n\t\t\tt = threading.Thread(target=self.__linuxLogProfile, args=(self.pid, self.interval, self.file))\n\t\tt.start()\n\t\t\n\n\n\tdef stop(self):\n\t\t\"\"\"Stop the process monitor.\n\t\t\n\t\t\"\"\"\n\t\tself.active = 0\n\t\t\n\n\n\n# used to run class from the command line\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 5:\n\t\tprint(\"Usage: monprocess.py \")\n\telse:\n\t\ttry: \n\t\t\tpid = int(sys.argv[1])\n\t\t\tinterval = int(sys.argv[2])\n\t\t\tduration = int(sys.argv[3])\n\t\t\tfile = sys.argv[4]\n\t\texcept Exception: \n\t\t\tprint(\"Process ID, interval and duration should be valid integers\")\n\t\t\tsys.exit(-1)\t\n\t\t\n\t\tmonitor = ProcessMonitor(pid, interval, file)\n\t\tmonitor.start()\n\t\ttime.sleep(duration)\n\t\tmonitor.stop()\n\n","sub_path":"pysys/process/plat-unix/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"445448179","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport contextlib\nimport os\nimport re\nimport signal\nimport tempfile\nimport time\nimport urllib2\n\nfrom devops.helpers import helpers\nfrom fuelweb_test.helpers import checkers\nfrom fuelweb_test.helpers import os_actions\nfrom fuelweb_test import logger\nfrom proboscis import asserts\nfrom stacklight_tests.helpers import remote_ops\nfrom stacklight_tests import settings as conf\n\n\nPLUGIN_PACKAGE_RE = re.compile(r'([^/]+)-(\\d+\\.\\d+)-(\\d+\\.\\d+\\.\\d+)')\n\n\nclass NotFound(Exception):\n pass\n\n\nclass TimeoutException(Exception):\n pass\n\n\ndef get_plugin_name(filename):\n \"\"\"Extract the plugin name from the package filename.\n\n :param filename: the plugin's filename.\n :type filename: str\n :returns: the plugin's name or None if not found\n :rtype: str\n \"\"\"\n m = PLUGIN_PACKAGE_RE.search(filename or '')\n if m:\n return m.group(1)\n else:\n return None\n\n\ndef get_plugin_version(filename):\n \"\"\"Extract the plugin version from the package filename.\n\n :param filename: the plugin's filename.\n :type filename: str\n :returns: the plugin's version or None if not found\n :rtype: str\n \"\"\"\n m = PLUGIN_PACKAGE_RE.search(filename or '')\n if m:\n return m.group(3)\n else:\n return None\n\n\ndef get_fixture(name):\n \"\"\"Return the full path to a fixture.\"\"\"\n path = os.path.join(os.environ.get(\"WORKSPACE\", \"./\"), \"fixtures\", name)\n if not os.path.isfile(path):\n raise NotFound(\"File {} not found\".format(path))\n return path\n\n\ndef mos7_get_ssh_for_nailgun_node(target, node):\n return target.environment.d_env.get_ssh_to_remote(node['ip'])\n\n\ndef mos7_upload_plugin(plugin, source=None):\n with source.get_admin_remote() as remote:\n checkers.upload_tarball(\n remote, plugin, \"/var\")\n\n\ndef mos7_install_plugin(plugin_file_name, source=None):\n with source.get_admin_remote() as remote:\n checkers.install_plugin_check_code(\n remote, plugin=plugin_file_name)\n\n\nclass PluginHelper(object):\n \"\"\"Class for common help functions.\"\"\"\n\n def __init__(self, env):\n self.env = env\n self.fuel_web = self.env.fuel_web\n # This method does not exist in MOS 7.0\n # Using Monkey-patching on class. The benefit is that the code\n # modifications required to get everything to work properly\n # on every supported version os MOS is located here and there is no\n # need to modify any other existing code in the test suite\n wtype = type(self.fuel_web)\n if not hasattr(wtype, 'get_ssh_for_nailgun_node'):\n wtype.get_ssh_for_nailgun_node = mos7_get_ssh_for_nailgun_node\n self._cluster_id = None\n self.nailgun_client = self.fuel_web.client\n self._os_conn = None\n\n @property\n def cluster_id(self):\n if self._cluster_id is None:\n try:\n self._cluster_id = self.fuel_web.get_last_created_cluster()\n except urllib2.URLError:\n raise EnvironmentError(\"No cluster was created.\")\n return self._cluster_id\n\n @cluster_id.setter\n def cluster_id(self, value):\n self._cluster_id = value\n\n @property\n def os_conn(self):\n if self._os_conn is None:\n self._os_conn = os_actions.OpenStackActions(\n self.fuel_web.get_public_vip(self.cluster_id))\n return self._os_conn\n\n def prepare_plugin(self, plugin_path):\n \"\"\"Upload and install plugin by path.\"\"\"\n # This method does not exist in MOS 7.0\n if not hasattr(self.env.admin_actions, 'upload_plugin'):\n mos7_upload_plugin(plugin=plugin_path, source=self.env.d_env)\n mos7_install_plugin(\n plugin_file_name=os.path.basename(plugin_path),\n source=self.env.d_env)\n else:\n self.env.admin_actions.upload_plugin(plugin=plugin_path)\n self.env.admin_actions.install_plugin(\n plugin_file_name=os.path.basename(plugin_path))\n\n def get_plugin_setting(self, plugin, parameter):\n \"\"\"Return the given parameter's value for the plugin.\n\n :param plugin: name of the plugin.\n :type plugin: str\n :param parameter: name of the parameter.\n :type parameter: str\n :returns: parameter's value\n \"\"\"\n asserts.assert_true(\n self.fuel_web.check_plugin_exists(self.cluster_id, plugin),\n \"Plugin {0} isn't found.\".format(plugin))\n\n attributes = self.nailgun_client.get_cluster_attributes(\n self.cluster_id)\n attributes = attributes['editable'][plugin]\n\n value = None\n for item in attributes['metadata']['versions']:\n if (parameter in item and\n item['metadata']['plugin_id'] ==\n attributes['metadata']['chosen_id']):\n value = item[parameter]['value']\n break\n asserts.assert_is_not_none(\n value, \"Could not find parameter {0} for plugin {1}\".format(\n parameter, plugin))\n return value\n\n def activate_plugin(self, name, version, options=None, strict=False):\n \"\"\"Enable and configure a plugin for the cluster.\n\n :param name: name of the plugin.\n :type name: str\n :param version: version of the plugin.\n :type name: str\n :param options: configuration of the plugin (optional).\n :type options: dict\n :param strict: whether or not to fail when setting an unknown option\n (default: False).\n :type strict: boolean\n :returns: None\n \"\"\"\n if options is None:\n options = {}\n msg = \"Plugin {0} isn't found.\".format(name)\n asserts.assert_true(\n self.fuel_web.check_plugin_exists(self.cluster_id, name),\n msg)\n\n logger.info(\"Updating settings for plugin {0} ({1}): {2}\".format(\n name, version, options))\n attributes = self.nailgun_client.get_cluster_attributes(\n self.cluster_id)\n attributes = attributes['editable'][name]\n\n plugin_data = None\n # This key does not exist in MOS 7.0\n if 'versions' in attributes['metadata']:\n for item in attributes['metadata']['versions']:\n if item['metadata']['plugin_version'] == version:\n plugin_data = item\n break\n asserts.assert_is_not_none(\n plugin_data,\n \"Plugin {0} ({1}) is not found\".format(\n name, version))\n else:\n plugin_data = attributes\n\n attributes['metadata']['enabled'] = True\n for option, value in options.items():\n path = option.split(\"/\")\n for p in path[:-1]:\n if p in plugin_data:\n plugin_option = plugin_data[p]\n else:\n msg = \"Plugin option {} not found\".format(option)\n if strict:\n raise NotFound(msg)\n logger.warn(msg)\n plugin_option = None\n break\n\n if plugin_option is not None:\n plugin_option[path[-1]] = value\n\n self.nailgun_client.update_cluster_attributes(self.cluster_id, {\n \"editable\": {name: attributes}\n })\n\n def get_vip_address(self, vip_name):\n \"\"\"Get the virtual IP address.\n\n :param vip_name: name of the VIP.\n :type vip_name: str\n :returns: the VIP address in dotted-decimal notation\n :rtype: str\n \"\"\"\n networks = self.nailgun_client.get_networks(self.cluster_id)\n vip = networks.get('vips').get(vip_name, {}).get('ipaddr', None)\n asserts.assert_is_not_none(\n vip, \"Failed to get the IP of {} server\".format(vip_name))\n\n logger.debug(\"VIP '{0}': {1}\".format(vip_name, vip))\n return vip\n\n def get_all_ready_nodes(self):\n return [node for node in\n self.nailgun_client.list_cluster_nodes(self.cluster_id)\n if node[\"status\"] == \"ready\"]\n\n def create_cluster(self, name=None, settings=None):\n \"\"\"Create a cluster.\n\n :param name: name of the cluster.\n :type name: str\n :param settings: optional dict containing the cluster's configuration.\n :type settings: dict\n :returns: the cluster's id\n :rtype: str\n \"\"\"\n if not name:\n name = self.__class__.__name__\n # For MOS 7.0 as default network is Nova\n # The global environment variables should have been set via openrc file\n if hasattr(conf, 'NEUTRON_ENABLE') and conf.NEUTRON_ENABLE:\n if settings is None:\n settings = {}\n settings[\"net_provider\"] = \"neutron\"\n settings[\"net_segment_type\"] = conf.NEUTRON_SEGMENT_TYPE\n self._cluster_id = self.env.fuel_web.create_cluster(\n name=name,\n settings=settings,\n mode='ha_compact')\n return self._cluster_id\n\n def deploy_cluster(self, nodes_roles, verify_network=False,\n update_interfaces=True, check_services=True,\n timeout=getattr(conf, 'DEPLOYMENT_TIMEOUT', 7800)):\n \"\"\"Assign roles to nodes and deploy the cluster.\n\n :param nodes_roles: nodes to roles mapping.\n :type nodes_roles: dict\n :param verify_network: whether or not network verification should be\n run before the deployment (default: False).\n :type verify_network: boolean\n :param update_interfaces: whether or not interfaces should be updated\n before the deployment (default: True).\n :type update_interfaces: boolean\n :param check_services: whether or not OSTF tests should run after the\n deployment (default: True).\n :type check_services: boolean\n :param timeout: deployment timeout: after run out of it\n deployment process will be stopped with exception.\n :type timeout: int\n :returns: None\n \"\"\"\n self.fuel_web.update_nodes(self.cluster_id, nodes_roles,\n update_interfaces=update_interfaces)\n if verify_network:\n self.fuel_web.verify_network(self.cluster_id)\n self.fuel_web.deploy_cluster_wait(self.cluster_id,\n check_services=check_services,\n timeout=timeout)\n\n def run_ostf(self, *args, **kwargs):\n \"\"\"Run the OpenStack health checks.\"\"\"\n self.fuel_web.run_ostf(self.cluster_id, *args, **kwargs)\n\n def run_single_ostf(self, test_sets, test_name, *args, **kwargs):\n \"\"\"Run a subset of the OpenStack health checks.\"\"\"\n self.fuel_web.run_single_ostf_test(self.cluster_id, test_sets,\n test_name, *args, **kwargs)\n\n def add_nodes_to_cluster(self, nodes, redeploy=True, check_services=False):\n \"\"\"Add nodes to the cluster.\n\n :param nodes: list of nodes with their roles.\n :type: nodes: dict\n :param redeploy: whether to redeploy the cluster (default: True).\n :type redeploy: boolean\n :param check_services: run OSTF after redeploy (default: False).\n :type check_services: boolean\n \"\"\"\n self.fuel_web.update_nodes(\n self.cluster_id,\n nodes,\n )\n if redeploy:\n self.fuel_web.deploy_cluster_wait(self.cluster_id,\n check_services=check_services)\n\n def remove_nodes_from_cluster(self, nodes, redeploy=True,\n check_services=False):\n \"\"\"Remove nodes from the cluster.\n\n :param nodes: list of nodes to remove from the cluster.\n :type nodes: dict\n :param redeploy: whether to redeploy the cluster (default: True).\n :type redeploy: boolean\n :param check_services: run OSTF after redeploy (default: False).\n :type check_services: boolean\n \"\"\"\n self.fuel_web.update_nodes(\n self.cluster_id,\n nodes,\n pending_addition=False, pending_deletion=True,\n )\n if redeploy:\n self.fuel_web.deploy_cluster_wait(self.cluster_id,\n check_services=check_services)\n\n def get_master_node_by_role(self, role_name, excluded_nodes_fqdns=()):\n \"\"\"Return the node running as the Designated Controller (DC).\n \"\"\"\n nodes = self.fuel_web.get_nailgun_cluster_nodes_by_roles(\n self.cluster_id, role_name)\n nodes = [node for node in nodes\n if node['fqdn'] not in set(excluded_nodes_fqdns)]\n with self.fuel_web.get_ssh_for_nailgun_node(nodes[0]) as remote:\n stdout = remote.check_call(\n 'pcs status cluster | grep \"Current DC:\"')[\"stdout\"][0]\n for node in nodes:\n if node['fqdn'] in stdout:\n return node\n\n @staticmethod\n def get_vip_resource_name(vip_name):\n \"\"\"Return the name of the VIP resource.\n \"\"\"\n return \"\".join([\"vip__\", vip_name])\n\n def get_node_with_vip(self, role_name, vip, exclude_node=None):\n nailgun_nodes = self.fuel_web.get_nailgun_cluster_nodes_by_roles(\n self.cluster_id, role_name)\n lma_nodes = self.fuel_web.get_devops_nodes_by_nailgun_nodes(\n nailgun_nodes)\n lma_node = None\n if exclude_node:\n for node in lma_nodes:\n if node.name != exclude_node.name:\n lma_node = node\n break\n else:\n lma_node = lma_nodes[0]\n return self.fuel_web.get_pacemaker_resource_location(\n lma_node.name, vip)[0]\n\n def wait_for_vip_migration(self, old_master, role_name, vip,\n timeout=5 * 60):\n logger.info('Waiting for the migration of VIP {}'.format(vip))\n msg = \"VIP {0} has not been migrated away from {1}\".format(\n vip, old_master)\n helpers.wait(\n lambda: old_master != self.get_node_with_vip(\n role_name, vip, exclude_node=old_master),\n timeout=timeout, timeout_msg=msg)\n\n def power_off_node(self, node):\n \"\"\"Power off a node.\n\n :param node: Devops node.\n :type node: devops node instance\n \"\"\"\n msg = 'Node {0} has not become offline after hard shutdown'.format(\n node.name)\n logger.info('Power off node %s', node.name)\n node.destroy()\n logger.info('Wait a %s node offline status', node.name)\n helpers.wait(lambda: not self.fuel_web.get_nailgun_node_by_devops_node(\n node)['online'], timeout=60 * 5, timeout_msg=msg)\n\n def emulate_whole_network_disaster(self, delay_before_recover=5 * 60,\n wait_become_online=True):\n \"\"\"Simulate a full network outage for all nodes.\n\n :param delay_before_recover: outage interval in seconds (default: 300).\n :type delay_before_recover: int\n :param wait_become_online: whether to wait for nodes to be back online.\n :type wait_become_online: bool\n \"\"\"\n nodes = [node for node in self.env.d_env.get_nodes()\n if node.driver.node_active(node)]\n\n networks_interfaces = nodes[1].interfaces\n\n for interface in networks_interfaces:\n interface.network.block()\n\n time.sleep(delay_before_recover)\n\n for interface in networks_interfaces:\n interface.network.unblock()\n\n if wait_become_online:\n self.fuel_web.wait_nodes_get_online_state(nodes[1:])\n\n def uninstall_plugin(self, plugin_name, plugin_version, exit_code=0,\n msg=None):\n \"\"\"Remove a plugin.\n\n :param plugin_name: plugin's name.\n :type plugin_name: str\n :param plugin_version: plugin's version.\n :type plugin_version: str\n :param exit_code: expected exit code.\n :type exit_code: int\n :param msg: message in case of error.\n :type msg: str\n \"\"\"\n logger.info(\"Trying to uninstall {name}({version}) plugin\".format(\n name=plugin_name,\n version=plugin_version))\n msg = msg or \"Plugin {0} deletion failed: exit code is {1}\"\n with self.env.d_env.get_admin_remote() as remote:\n exec_res = remote.execute(\"fuel plugins --remove\"\n \" {0}=={1}\".format(plugin_name,\n plugin_version))\n asserts.assert_equal(\n exit_code, exec_res['exit_code'],\n msg.format(plugin_name, exec_res['exit_code']))\n\n def check_plugin_cannot_be_uninstalled(self, plugin_name, plugin_version):\n \"\"\"Check that the plugin cannot be uninstalled.\n\n :param plugin_name: plugin's name.\n :type plugin_name: str\n :param plugin_version: plugin's version.\n :type plugin_version: str\n \"\"\"\n self.uninstall_plugin(\n plugin_name=plugin_name, plugin_version=plugin_version,\n exit_code=1,\n msg='{name}({version}) plugin deletion must not be allowed '\n 'when it is deployed'.format(name=plugin_name,\n version=plugin_version))\n\n def get_hostname_by_node_name(self, changed_node):\n node = self.fuel_web.get_nailgun_node_by_base_name(changed_node)\n if node is None:\n raise NotFound(\"Nailgun node with '{}' in name not found\".format(\n changed_node))\n return node['hostname']\n\n def fuel_createmirror(self, option=\"\", exit_code=0):\n cmd = \"fuel-createmirror {0}\".format(option)\n logger.info(\"Executing '{}' command.\".format(cmd))\n with self.env.d_env.get_admin_remote() as remote:\n exec_res = remote.execute(cmd)\n asserts.assert_equal(\n exit_code, exec_res['exit_code'],\n 'fuel-createmirror failed: {0}'.format(exec_res['stderr']))\n\n def replace_ubuntu_mirror_with_mos(self):\n cmds = [\"fuel-mirror create -P ubuntu -G mos\",\n \"fuel-mirror apply --replace -P ubuntu -G mos\"]\n logger.info(\"Executing '{}' commands.\".format('\\n'.join(cmds)))\n with self.env.d_env.get_admin_remote() as remote:\n for cmd in cmds:\n remote.check_call(cmd)\n\n def fuel_create_repositories(self, nodes):\n \"\"\"Start task to setup repositories on provided nodes.\n\n :param nodes: list of nodes to run task on them\n :type nodes: list\n \"\"\"\n nodes_ids = [str(node['id']) for node in nodes]\n cmd = (\n \"fuel --env {env_id} \"\n \"node --node-id {nodes_ids} \"\n \"--tasks setup_repositories\".format(\n env_id=self.cluster_id,\n nodes_ids=' '.join(nodes_ids))\n )\n logger.info(\n \"Executing {cmd} command.\".format(cmd=cmd))\n with self.env.d_env.get_admin_remote() as remote:\n remote.check_call(cmd)\n\n def run_tasks(self, nodes, tasks=None, start=None, end=None,\n timeout=10 * 60):\n \"\"\"Run a set of tasks on nodes and wait for completion.\n\n The list of tasks is provided using the 'tasks' parameter and it can\n also be specified using the 'start' and/or 'end' parameters. In the\n latter case, the method will compute the exact set of tasks to be\n executed.\n\n :param nodes: list of nodes that should run the tasks\n :type nodes: list\n :param tasks: list of tasks to run.\n :param tasks: list\n :param start: the task from where to start the deployment.\n :param start: str\n :param end: the task where to end the deployment.\n :param end: str\n :param timeout: number of seconds to wait for the tasks completion\n (default: 600).\n :param timeout: int\n \"\"\"\n task_ids = []\n if tasks is not None:\n task_ids += tasks\n if start is not None or end is not None:\n task_ids += [\n t[\"id\"] for t in self.nailgun_client.get_end_deployment_tasks(\n self.cluster_id, end=end or '', start=start or '')]\n node_ids = \",\".join([str(node[\"id\"]) for node in nodes])\n logger.info(\"Running tasks {0} for nodes {1}\".format(\n \",\".join(task_ids), node_ids))\n result = self.nailgun_client.put_deployment_tasks_for_cluster(\n self.cluster_id, data=task_ids, node_id=node_ids)\n self.fuel_web.assert_task_success(result, timeout=timeout)\n\n def apply_maintenance_update(self):\n \"\"\"Method applies maintenance updates on whole cluster.\"\"\"\n logger.info(\"Applying maintenance updates on master node\")\n self.env.admin_install_updates()\n\n logger.info(\"Applying maintenance updates on slaves\")\n slaves_mu_script_url = (\n \"https://github.com/Mirantis/tools-sustaining/\"\n \"raw/master/scripts/mos_apply_mu.py\")\n\n path_to_mu_script = \"/tmp/mos_apply_mu.py\"\n\n with self.env.d_env.get_admin_remote() as remote:\n remote.check_call(\"wget {uri} -O {path}\".format(\n uri=slaves_mu_script_url,\n path=path_to_mu_script)\n )\n\n remote.check_call(\n \"python {path} \"\n \"--env-id={identifier} \"\n \"--user={username} \"\n \"--pass={password} \"\n \"--tenant={tenant_name} --update\".format(\n path=path_to_mu_script,\n identifier=self.cluster_id,\n **conf.KEYSTONE_CREDS\n )\n )\n\n controllers = self.fuel_web.get_nailgun_cluster_nodes_by_roles(\n self.cluster_id, roles=['controller', ])\n\n computes = self.fuel_web.get_nailgun_cluster_nodes_by_roles(\n self.cluster_id, roles=['compute', ])\n\n logger.info(\"Restarting all OpenStack services\")\n\n logger.info(\"Restarting services on controllers\")\n ha_services = (\n \"p_heat-engine\",\n \"p_neutron-plugin-openvswitch-agent\",\n \"p_neutron-dhcp-agent\",\n \"p_neutron-metadata-agent\",\n \"p_neutron-l3-agent\")\n non_ha_services = (\n \"heat-api-cloudwatch\",\n \"heat-api-cfn\",\n \"heat-api\",\n \"cinder-api\",\n \"cinder-scheduler\",\n \"nova-objectstore\",\n \"nova-cert\",\n \"nova-api\",\n \"nova-consoleauth\",\n \"nova-conductor\",\n \"nova-scheduler\",\n \"nova-novncproxy\",\n \"neutron-server\",\n )\n for controller in controllers:\n with self.fuel_web.get_ssh_for_nailgun_node(\n controller) as remote:\n for service in ha_services:\n remote_ops.manage_pacemaker_service(remote, service)\n for service in non_ha_services:\n remote_ops.manage_service(remote, service)\n\n logger.info(\"Restarting services on computes\")\n compute_services = (\n \"neutron-plugin-openvswitch-agent\",\n \"nova-compute\",\n )\n for compute in computes:\n with self.fuel_web.get_ssh_for_nailgun_node(compute) as remote:\n for service in compute_services:\n remote_ops.manage_service(remote, service)\n\n @staticmethod\n def wait_for_resource_status(resource_client, resource, expected_status,\n timeout=180, interval=30):\n start = time.time()\n finish = start + timeout\n while start < finish:\n curr_state = resource_client.get(resource).status\n if curr_state == expected_status:\n return\n else:\n logger.debug(\n \"Instance is not in {} status\".format(expected_status))\n time.sleep(interval)\n start = time.time()\n raise TimeoutException(\"Timed out waiting to become {}\".format(\n expected_status))\n\n def get_fuel_release(self):\n version = self.nailgun_client.get_api_version()\n return version.get('release')\n\n def check_pacemaker_resource(self, resource_name, role, is_ha=True):\n \"\"\"Check that the pacemaker resource is started on nodes with given\n role.\n :param resource_name: the name of the pacemaker resource\n :type resource_name: str\n :param role: the role of node when pacemaker is running\n :type role: str\n :returns: None\n \"\"\"\n n_ctrls = self.fuel_web.get_nailgun_cluster_nodes_by_roles(\n self.cluster_id, [role])\n d_ctrls = self.fuel_web.get_devops_nodes_by_nailgun_nodes(n_ctrls)\n pcm_nodes = ' '.join(self.fuel_web.get_pcm_nodes(\n d_ctrls[0].name, pure=True)['Online'])\n logger.info(\"pacemaker nodes are {0}\".format(pcm_nodes))\n resource_nodes = self.fuel_web.get_pacemaker_resource_location(\n d_ctrls[0].name, \"{}\".format(resource_name))\n if is_ha:\n for resource_node in resource_nodes:\n logger.info(\"Check resource [{0}] on node {1}\".format(\n resource_name, resource_node.name))\n config = self.fuel_web.get_pacemaker_config(resource_node.name)\n asserts.assert_not_equal(\n re.search(\n \"Clone Set: clone_{0} \\[{0}\\]\\s+Started: \\[ {1} \\]\".\n format(resource_name, pcm_nodes), config), None,\n 'Resource [{0}] is not properly configured'.format(\n resource_name))\n else:\n asserts.assert_true(len(resource_nodes), 1)\n config = self.fuel_web.get_pacemaker_config(resource_nodes[0].name)\n logger.info(\"Check resource [{0}] on node {1}\".format(\n resource_name, resource_nodes[0].name))\n asserts.assert_not_equal(\n re.search(\"{0}\\s+\\(ocf::fuel:{1}\\):\\s+Started\".format(\n resource_name, resource_name.split(\"_\")[1]), config), None,\n 'Resource [{0}] is not properly configured'.format(\n resource_name))\n\n def update_neutron_advanced_configuration(self, option, value):\n \"\"\"Method updates current cluster neutron advanced configuration option\n with provided value.\n\n :param option: option to set\n :type option: str\n :param value: value to set\n :type value: any\n :return: None\n \"\"\"\n attributes = self.nailgun_client.get_cluster_attributes(\n self.cluster_id)\n nac_subdict = attributes['editable']['neutron_advanced_configuration']\n nac_subdict[option]['value'] = value\n self.nailgun_client.update_cluster_attributes(\n self.cluster_id, attributes)\n\n def create_image(self):\n\n with tempfile.TemporaryFile() as fp:\n fp.write('Test')\n fp.seek(0)\n image = self.os_conn.create_image(name='Redis',\n container_format='bare',\n disk_format='qcow2',\n data=fp)\n return image\n\n @staticmethod\n def verify(secs, func, step='', msg='', action='', duration=1000,\n sleep_for=10, *args, **kwargs):\n \"\"\"Arguments:\n :secs: timeout time;\n :func: function to be verified;\n :step: number of test step;\n :msg: message that will be displayed if an exception occurs;\n :action: action that is performed by the method.\n \"\"\"\n logger.info(\"STEP:{0}, verify action: '{1}'\".format(step, action))\n now = time.time()\n time_out = now + duration\n try:\n with timeout(secs, action):\n while now < time_out:\n result = func(*args, **kwargs)\n if result or result is None:\n return result\n logger.info(\n \"{} is failed. Will try again\".\n format(action)\n )\n time.sleep(sleep_for)\n now = time.time()\n except Exception as exc:\n logger.exception(exc)\n if type(exc) is AssertionError:\n msg = str(exc)\n raise AssertionError(\n \"Step {} failed: {} Please refer to OpenStack logs for more \"\n \"details.\".format(step, msg)\n )\n else:\n return result\n\n @contextlib.contextmanager\n def make_logical_db_unavailable(self, db_name, controller):\n \"\"\"Context manager that renames all tables in provided database\n to make it unavailable and renames it back on exit.\n\n :param db_name: logical database name\n :type db_name: str\n :param controller: controller with MySQL database\n :type controller: nailgun node\n :returns: None, works as context manager\n \"\"\"\n cmd = (\n \"mysql -AN -e \"\n \"\\\"select concat(\"\n \"'rename table {db_name}.', table_name, ' \"\n \"to {db_name}.' , {method}(table_name) , ';') \"\n \"from information_schema.tables \"\n \"where table_schema = '{db_name}';\"\n \"\\\" | mysql\")\n\n with self.fuel_web.get_ssh_for_nailgun_node(controller) as remote:\n remote.check_call(cmd.format(db_name=db_name, method=\"upper\"))\n\n yield\n\n with self.fuel_web.get_ssh_for_nailgun_node(controller) as remote:\n remote.check_call(cmd.format(db_name=db_name, method=\"lower\"))\n\n\ndef _raise_TimeOut(sig, stack):\n raise TimeoutException()\n\n\nclass timeout(object):\n \"\"\"Timeout context that will stop code running within context\n if timeout is reached\n\n >>with timeout(2):\n ... requests.get(\"http://msdn.com\")\n \"\"\"\n\n def __init__(self, timeout, action):\n self.timeout = timeout\n self.action = action\n\n def __enter__(self):\n signal.signal(signal.SIGALRM, _raise_TimeOut)\n signal.alarm(self.timeout)\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n signal.alarm(0) # disable the alarm\n if exc_type is not TimeoutException:\n return False # never swallow other exceptions\n else:\n logger.info(\"Timeout {timeout}s exceeded for {call}\".format(\n call=self.action,\n timeout=self.timeout\n ))\n msg = (\"Time limit exceeded while waiting for {call} to \"\n \"finish.\").format(call=self.action)\n raise AssertionError(msg)\n","sub_path":"stacklight_tests/helpers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":31572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"125653532","text":"from operator import itemgetter\r\n\r\nimport requests\r\n\r\nurl = 'https://hacker-news.firebaseio.com/v0/topstories.json'\r\nr = requests.get(url)\r\nprint(f\"Status code: {r.status_code}\")\r\n\r\n#Process information about each submission.\r\nsubmission_ids = r.json()\r\nsubmission_dicts = []\r\nfor submission_id in submission_ids[:16]:\r\n #Different API call for each submission.\r\n url = f\"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json\"\r\n r = requests.get(url)\r\n print(f\"id {submission_id}\\status: {r.status_code}\")\r\n response_dict = r.json()\r\n\r\n #Create dictionary for each article.\r\n submission_dict = {\r\n 'title': response_dict['title'],\r\n 'hn_links': f\"http://news.ycombinator.com/item?id={submission_id}\",\r\n 'comments': response_dict['descendants'],\r\n }\r\n submission_dicts.append(submission_dict)\r\nsubmission_dicts = sorted(submission_dicts, key=itemgetter('comments'), reverse=True)\r\n\r\nfor submission_dict in submission_dicts:\r\n print(f\"\\nTitle: {submission_dict['title']}\")\r\n print(f\"Discussion link: {submission_dict['hn_links']}\")\r\n print(f\"Comments: {submission_dict['comments']}\")\r\n\r\n\r\n\r\n","sub_path":"hs_submited.py","file_name":"hs_submited.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"347168241","text":"# ENUMS IN PYTHON\n\n# example bools if they didn't exist\nfalse, true = range(2)\nmy_bool = true\n#print(false, true,'\\n')\nx = 1\nwhile(my_bool):\n\tif x >= 10:\n\t\tmy_bool = false # this wont break until next iteration, therefore x is incremented\n\tprint(x)\n\tx += 1\n\n# enumerate a list example\nsome_list = ['A','B','C','D']\nenum_list = enumerate(some_list,start = 2) # will return a tuple of pairs of tuples with numbers\n\nfor j in enum_list: # starts enum at 2\n\tprint(j)\n\n\nfor i in enumerate(some_list,start=1): # starts the enum at 1\n\tprint(i)\n\n#(1, 'A')\n#(2, 'B')\n#...\n#...\n\n#enums and classes\nfrom enum import Enum\nclass My_Enum_Class(Enum):\n\tRED = 0\n\tBLUE = 1\n\tGREEN = 2\n\nfor i in My_Enum_Class:\n\tprint(i)\n\n# My_Enum_Class.RED\n# My_Enum_Class.BLUE\n# My_Enum_Class.GREEN\n\ntry:\n\tassert 1 == 0, 'the message' # will print the message if it is false\nexcept Exception as err:\n\tprint(err) # this will print the message\n\n\n\n\n\n\n","sub_path":"enums_in_python.py","file_name":"enums_in_python.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"190705880","text":"#!/usr/bin/env python\n\nimport sys\n\nimport regex\n\n\ndef get_defect_number(line):\n \"\"\"Get defect description from line, ignoring defect description.\"\"\"\n words = line.split()\n match = regex.DEFECT_NUMBER_RE.search(words[0])\n reply_number_str = match.group(1)\n return int(reply_number_str)\n\n\ndef get_defect_body(line):\n \"\"\"Get defect description from line, ignoring defect number.\"\"\"\n return regex.DEFECT_DESCRIPTION_RE.search(line).group(1)\n\n\ndef get_reply_number_range(line):\n \"\"\"Get reply number range from line, ignoring defect description.\n\n Note some replies correspond to multiple defects in a single paragraph,\n and mention a range of multiple defect numbers.\n\n For example: '2-4. bla bla bla' will fetch [\"2\", \"4\"]\n and means this reply corresponds to defects #2,#3,#4\n \"\"\"\n words = line.split()\n match = regex.DEFECT_REPLY_NUMBER_RE.search(words[0])\n defect_number_start_str = match.group(1)\n try:\n # process defect number range end if found\n second_number_end_str = match.group(2)\n except IndexError:\n second_number_end_str = None\n return int(defect_number_start_str), second_number_end_str\n\n\ndef get_reply_body(line):\n \"\"\"Get defect reply from line, ignoring defect number.\n\n Note we're using the same regex as in get_defect_body().\n This is intentional since the text structure is similiar.\n \"\"\"\n return regex.DEFECT_DESCRIPTION_RE.search(line).group(1)\n","sub_path":"prime-minister/followup.py","file_name":"followup.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"56466065","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef matrix(x,y,n):\n Y = []\n i = 0\n while i < n:\n X = []\n j = 0\n while j' + models.User.name_regex + r')/$', views.user, name='user'),\n url(r'^(?P' + models.User.name_regex + r')/(?P[0-9]+)/$', views.schedule, name='schedule'),\n url(r'^test-image/$', views.image, name='image'),\n]\n","sub_path":"src/schedu/schedule_builder/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"377167285","text":"import cv2\nimport logging\nfrom zeamage.verbose import verbose, verbose_view\n\nlogger = logging.getLogger(__name__)\n\n\n@verbose(logger=logger, fun=verbose_view)\ndef skeletonize(img):\n \"\"\" OpenCV function to return a skeletonized version of img, a Mat object\n\n hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/\n \"\"\"\n img = img.copy() # don't clobber original\n skel = img.copy()\n\n skel[:, :] = 0\n kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n\n while True:\n eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)\n temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)\n temp = cv2.subtract(img, temp)\n skel = cv2.bitwise_or(skel, temp)\n img[:, :] = eroded[:, :]\n if cv2.countNonZero(img) == 0:\n break\n\n return skel\n\n\ndef skeleton_line_recursive(img, erode_iter):\n simg = cv2.erode(img, (3, 3), iterations=erode_iter)\n logger.debug(erode_iter)\n if cv2.countNonZero(simg) < 50 and not erode_iter <= 1:\n erode_iter -= 1\n return skeleton_line_recursive(img, erode_iter)\n\n return simg\n\n\n@verbose(logger=logger, fun=verbose_view)\ndef skeleton_line(mask, erode_iter=4):\n simg = skeletonize(mask)\n return skeleton_line_recursive(simg, erode_iter)\n\n\n# class ObjectDetector:\n# def __init__(self, img, ctn):\n# self.image = img\n# self.contour = ctn\n# self.object_type = \"unidentified\"\n\n# def detect(self):\n# \"\"\"Discriminate reference object and ears and then\n# beteween normal ear and curved ears\n# \"\"\"\n# # initialize the shape name and approximate the contour\n# peri = cv2.arcLength(self.contour, True)\n# approx = cv2.approxPolyDP(self.contour, 0.04 * peri, True)\n\n# # if the shape has 4 vertices, it is either a square or\n# # a rectangle\n# if len(approx) == 4:\n# # compute the bounding box of the contour and use the\n# # bounding box to compute the aspect ratio\n# (x, y, w, h) = cv2.boundingRect(approx)\n# ar = w / float(h)\n\n# # a square will have an aspect ratio that is approximately\n# # equal to one, otherwise, the shape is a rectangle\n# if ar >= 0.95 and ar <= 1.05:\n# self.object_type = \"square\"\n# else:\n# self.object_type = \"rectangle\"\n# elif len(approx) > 4:\n# logger.info(\"!ear\")\n\n# def measure(self):\n# pass\n\n# def shape(self):\n# \"\"\"Return the shape of the detected object.\n# Object to be measured.\n# Shape is defined from the contour approx polygone,\n\n# see: http://www.codepasta.com/site/vision/segmentation/\n# \"\"\"\n# pass\n\n# def mask(self):\n# \"\"\"Return the mask of the detected object.\"\"\"\n# mask = np.zeros_like(\n# self.image\n# ) # Create mask where white is what we want, black otherwise\n# cv2.drawContours(mask, [self.contour], 0, 255, -1)\n# return mask\n\n# def skeletonize(self):\n# \"\"\" OpenCV function to return a skeletonized version of img, a Mat object\n\n# Voir aussi medial axis from scikit image\n\n# \"\"\"\n\n# # http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/\n\n# img = self.image.copy() # don't clobber original\n# skel = self.image.copy()\n\n# skel[:, :] = 0\n# kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n\n# while True:\n# eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)\n# temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)\n# temp = cv2.subtract(img, temp)\n# skel = cv2.bitwise_or(skel, temp)\n# img[:, :] = eroded[:, :]\n# if cv2.countNonZero(img) == 0:\n# break\n\n# return skel\n","sub_path":"zeamage/detector/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"540629658","text":"# 컬렉션 형태의 데이터를 특정 키 값에 해당하는 그룹화 된 합계 리스트\n\nclass Record():\n def __init__(self, name, quantity):\n self.name = name # 상품명\n self.quantity = quantity # 수량\n \ndef main():\n # input\n records = [ Record(\"Radio\", 3), Record(\"TV\", 1), Record(\"Radio\", 2), Record(\"DVD\", 4) ]\n groups = [ ]\n N = len(records)\n\n # process # Sort -> Sum -> Group\n\n # Sort # Selection Sort\n for i in range(0, N - 1):\n for j in range(i + 1, N):\n if (records[i].name > records[j].name):\n temp = records[i]\n records[i] = records[j]\n records[j] = temp\n\n # Group\n sum = 0 # 합계\n for i in range(N):\n sum += records[i].quantity # 같은 상품명의 수량을 합침\n if (i + 1) == N or records[i].name != records[i + 1].name:\n # 한 그룹의 key 지정 및 합침\n groups.append(Record(records[i].name, sum)) # 하나의 그룹 저장\n sum = 0 # 하나의 그룹이 저장되면 합계 초기화\n\n # output\n print(\"[1] 원본 데이터\")\n for r in records:\n print(f\"{r.name.rjust(6)} - {r.quantity}\")\n \n print(\"[2] 이름으로 그룹화 된 데이터\")\n for g in groups:\n print(f\"{g.name.rjust(6)} - {g.quantity}\")\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"src/python/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"200251784","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n\r\n\r\n\r\ndef getTry(n,k): # draw n graph Xbar\r\n\r\n\tsumArr = [0 for i in range(10*n)]\r\n\tinstance = [0 for j in range(n)]\r\n\tax = (1,2,3,4,5,6,7,8,9,10)\r\n\tcount = 0\r\n\tinstance = np.random.choice(10, n) #choose n number in 10\r\n\tsumX = np.sum(instance) # put sum of (choosed n number) in int sumX\r\n\tfor k in range(45):\r\n\t\r\n\t\tfor m in range(20):\r\n\t\t\tif sumX == k:\r\n\t\t\r\n\t\t\t\tcount = count + 1 # 중복되는 sumX만큼 count \r\n\t\t\r\n\t\r\n\tvalueY = instance / count \r\n\tsumArr.append(valueY)\r\n\t\r\n\treturn sumArr\r\n\r\n\r\n\r\ndef showGraph(n):\r\n\r\n\tuniArr = [0 for i in range(n)] # uniform probability\r\n\ttryNum = (1,2,3,4,5,6,7,8,9,10) # how many try\r\n\tfor i in range(n):\r\n\t\r\n\t\tuniArr[i] = 1/n\r\n\t\r\n\r\n\tx_name = (tryNum)\r\n\ty_value = getTry(2,1000)\r\n\tn_name = len(x_name)\r\n\tindex = np.arange(n_name)\r\n\r\n\tplt.scatter()\r\n\r\n\tplt.xlabel('try number')\r\n\tplt.ylabel('probability of uniform')\r\n\tplt.title('uniform distribution')\r\n\tplt.xlim(-1, n_name)\r\n\tplt.ylim(0,1)\r\n\tplt.show()\r\n\r\n\r\ndef main():\r\n\tshowGraph(10)\r\n \r\n #step = int(sys.argv[2])\r\n \r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\nplt.show()\r\n\r\n#arr[]*num\r\n","sub_path":"CLT.py","file_name":"CLT.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"321665610","text":"from __future__ import division\n\nimport matplotlib\nimport matplotlib.cm as cmx\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n__author__ = \"Jimeno A. Fonseca\"\n__copyright__ = \"Copyright 2017, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Jimeno A. Fonseca\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"cea@arch.ethz.ch\"\n__status__ = \"Production\"\n\ndef plot_day(data, output_path, labelx, labely, save_to_disc, show_in_screen, show_legend):\n\n plt.rcParams.update({'font.size': 18})\n\n #create figure\n fig = plt.figure()\n ax = data.plot(grid=True, legend=show_legend)\n ax.set_xlabel(labelx)\n ax.set_ylabel(labely)\n if show_legend:\n ax.legend(loc='upper right', prop={'size':12}, ncol=2)\n\n # get formatting\n plt.tight_layout()\n if save_to_disc:\n plt.savefig(output_path)\n if show_in_screen:\n plt.show()\n plt.close(fig)","sub_path":"cea/plots/old/clusters_plot.py","file_name":"clusters_plot.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"52928252","text":"import cv2\nimport numpy as numpy\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\nimport tensorflow as tf \nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n\nMODEL = '/home/john/PycharmProjects/ec-autonav/final_model.h5'\n\nARROWS = '/home/john/Pictures/Arrow Trainingset/'\nNOT = '/home/john/Pictures/Others trainingset2/'\n\n#test_this = '/home/john/Pictures/Arrow Testset'\ntest_this = '/home/john/Pictures/nn_stuff/test'\n\ntrain_data = '/home/john/Pictures/nn_stuff/train'\ntest_data = '/home/john/Pictures/nn_stuff/test'\n\n\"\"\" def rename_files():\n i = 0\n\n for filename in os.listdir(NOT):\n name = NOT + 'not.' + str(i) + '.png'\n src = NOT + filename\n os.rename(src,name)\n i += 1 \"\"\"\n\ndef one_hot_label(img):\n label = img.split('.')[0]\n if label == 'arrow':\n ohl = np.array([1,0])\n elif label == 'not':\n ohl = np.array([0,1])\n return ohl\n\n\n\ndef label_dataset(direct):\n dataset = []\n for i in tqdm(os.listdir(direct)):\n path = os.path.join(direct,i)\n img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (34,34))\n dataset.append([np.array(img),one_hot_label(i)])\n shuffle(dataset)\n return dataset\n\ndef load_datasets():\n train_images = label_dataset(train_data)\n test_images = label_dataset(train_data)\n return train_images, test_images\n\n # define cnn model\ndef define_model():\n model = Sequential()\n model.add(InputLayer(input_shape=[34,34,1]))\n model.add(Conv2D(filters=32,kernel_size=5,strides=1,padding='same',activation='relu'))\n model.add(MaxPool2D(pool_size=5,padding='same'))\n\n model.add(Conv2D(filters=50,kernel_size=5,strides=1,padding='same',activation='relu'))\n model.add(MaxPool2D(pool_size=5,padding='same'))\n \n model.add(Conv2D(filters=80,kernel_size=5,strides=1,padding='same',activation='relu'))\n model.add(MaxPool2D(pool_size=5,padding='same'))\n \n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(rate=0.5))\n model.add(Dense(2, activation='softmax'))\n optimizer = Adam(lr=1e-3)\n model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n return model\n\ndef predict(model):\n count = 0\n for i in tqdm(os.listdir(test_this)):\n path = os.path.join(test_this,i)\n #img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)\n #img = cv2.resize(img,(64,64))\n #image.reshape(1,64,64,1)\n img = load_img(path,grayscale=True,target_size=(34,34))\n img = img_to_array(img)\n img = img.reshape(1,34,34,1)\n output = model.predict_classes(img)\n if output[0] == 1:\n count += 1\n accuracy = (27-count)/27.0\n print('predictor is ' + str(accuracy) + '% accurate')\n\ntraining_images, testing_images = load_datasets()\n\ntr_img_data = np.array([i[0] for i in training_images]).reshape(-1,34,34,1)\ntr_lbl_data = np.array([i[1] for i in training_images])\ntst_img_data = np.array([i[0] for i in testing_images]).reshape(-1,34,34,1)\ntst_lbl_data = np.array([i[1] for i in testing_images])\n\nmodel = define_model()\nmodel.fit(x=tr_img_data,y=tr_lbl_data,epochs=50,batch_size=100)\nmodel.summary()\nmodel.save('final_model.h5')\n#model = load_model(MODEL)\npredict(model)\n\n\n# fig = plt.figure(figsize=(14,14))\n\n# for cnt, data in enumerate(testing_images[10:40]):\n\n# y = fig.add_subplot(6,5,cnt+1)\n# img = data[0]\n# data = img.reshape(1,64,64,1)\n# model_out = model.predict([data])\n\n# if np.argmax(model_out) == 1:\n# str_label = 'arrow'\n# else:\n# str_label = 'not'\n \n# y.imshow(img, cmap='gray')\n# plt.title(str_label)\n# y.axes.get_xaxis().set_visible(False)\n# y.axes.get_yaxis().set_visible(False)\n\n","sub_path":"trainNet.py","file_name":"trainNet.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"372225597","text":"from django.urls import path\nfrom fileindex import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n \n #path('projects/', views.ProjectListView.as_view(), name='projects'),\n #path('projects/', views.ProjectDetailView.as_view(), name='project-detail'),\n \n path('projects/', views.project_list, name='projects'),\n path('projects/', views.project_detail, name='project-detail'),\n path('projects/addnew/', views.project_addnew, name='project-addnew'),\n path('projects/update/', views.project_update, name='project-update'),\n \n path('reports/', views.ReportListView.as_view(), name='reports'),\n path('reports/', views.ReportDetailView.as_view(), name='report-detail'),\n \n path('study_plans/', views.StudyPlanListView.as_view(), name='study-plans'),\n path('study_plans/', views.StudyPlanDetailView.as_view(), name='studyplan-detail'),\n \n path('study_plans//update', views.studyplan_update, name='studyplan-update'),\n\n]","sub_path":"fileindex/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"518599139","text":"import tensorflow as tf\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--input',\n nargs='+',\n help='Input model'\n )\n parser.add_argument(\n '--output',\n nargs='+',\n help='Output model'\n )\n\n args, _ = parser.parse_known_args()\n\n converter = tf.lite.TFLiteConverter.from_keras_model_file(args.input[0])\n tflite_model = converter.convert()\n open(args.output[0], \"wb+\").write(tflite_model)","sub_path":"utils/LiteModelConverter.py","file_name":"LiteModelConverter.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"376677420","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit\nfrom PyQt5.QtWidgets import QLabel, QLCDNumber\n\n\nclass Focus(QWidget):\n def __init__(self):\n super().__init__()\n\n self.setGeometry(600, 400, 520, 170)\n self.setWindowTitle('Миникалькулятор')\n\n self.l1 = QLabel(self)\n self.l1.move(10, 15)\n self.l1.setText('Первое число(целое):')\n\n self.l2 = QLabel(self)\n self.l2.move(10, 85)\n self.l2.setText('Второе число(целое):')\n\n self.st1 = QLineEdit(self)\n self.st1.move(10, 40)\n self.st1.resize(130, 30)\n\n self.st2 = QLineEdit(self)\n self.st2.move(10, 110)\n self.st2.resize(130, 30)\n\n self.btn = QPushButton(self)\n self.btn.setText('->')\n self.btn.setGeometry(150, 75, 130, 30)\n self.btn.clicked.connect(self.conv)\n\n self.c1 = QLCDNumber(self)\n self.c1.move(370, 10)\n self.c1.resize(130, 30)\n\n self.c2 = QLCDNumber(self)\n self.c2.move(370, 50)\n self.c2.resize(130, 30)\n\n self.c3 = QLCDNumber(self)\n self.c3.move(370, 90)\n self.c3.resize(130, 30)\n\n self.c4 = QLCDNumber(self)\n self.c4.move(370, 130)\n self.c4.resize(130, 30)\n\n self.l3 = QLabel(self)\n self.l3.move(330, 20)\n self.l3.setText('Сумма:')\n\n self.l4 = QLabel(self)\n self.l4.move(315, 60)\n self.l4.setText('Разность:')\n\n self.l5 = QLabel(self)\n self.l5.move(290, 100)\n self.l5.setText('Произведение:')\n\n self.l6 = QLabel(self)\n self.l6.move(320, 140)\n self.l6.setText('Частное:')\n\n self.n = 0\n\n def conv(self):\n self.c1.display(int(int(self.st1.text()) + int(self.st2.text())))\n self.c2.display(int(int(self.st1.text()) - int(self.st2.text())))\n self.c3.display(int(int(self.st1.text()) * int(self.st2.text())))\n if int(self.st2.text()) != 0:\n self.c4.display(int(self.st1.text()) / int(self.st2.text()))\n else:\n self.c4.display(\"Error\")\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Focus()\n ex.show()\n sys.exit(app.exec())\n","sub_path":"2nd_year/4/class/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242887765","text":"# %load q01_load_data_tfidf/build.py\n# Default imports\n\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Write your solution here :\n\ndef q01_load_data_tfidf(path,max_df=0.95,min_df=2,no_features=1000):\n variable1=pd.read_csv(path)\n tf_vect=TfidfVectorizer(stop_words='english',max_df=max_df,min_df=min_df,max_features=no_features)\n variable2=tf_vect.fit_transform(variable1['talkTitle'])\n variable3=tf_vect.get_feature_names()\n return variable1,variable2,variable3\n\n\n","sub_path":"q01_load_data_tfidf/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"84546908","text":"\"\"\"\nhttps://leetcode.com/problems/sqrtx/\n\nImplement int sqrt(int x).\n\nCompute and return the square root of x.\n\"\"\"\nclass Solution(object):\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x == 0:\n return 0\n left, right = 1, x\n while True:\n mid = left + (right - left) / 2 # avoid overflow\n # make sure not to go beyond x because we just return the truncated int of the sqrt\n # avoid overflow, too\n if mid > x / mid:\n right = mid - 1\n elif mid + 1 > x / (mid + 1): # if (mid+1)^2 is greater than x and mid^2 <= x, we've found our result\n return mid\n else:\n left = mid + 1\n","sub_path":"lc/sqrt.py","file_name":"sqrt.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"156058104","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport yaml\nimport json\nimport requests\nimport exceptions\n\n\ndef read_config(config_file):\n try:\n cf = open(config_file, 'r')\n config = yaml.safe_load(cf)\n return config\n except FileNotFoundError as err:\n print(\"Config file not found:\\n{}\".format(err))\n return False\n except yaml.YAMLError as err:\n print(\"Could not read yaml:\\n{}\".format(err))\n return False\n\n\ndef create_cache_dir(cdir):\n if not os.path.isdir(cdir):\n try:\n os.mkdir(cdir, 0o700)\n return True\n except:\n return False\n\n return True\n\n\ndef write_cache(cache_file, data):\n with open(cache_file, 'w') as cf:\n cf.write(json.dumps(data))\n\n\ndef get_external_ip():\n try:\n response = requests.get(url=\"https://api.ipify.org\")\n external_ip = response.text\n if response.status_code != 200:\n raise exceptions.GetExternalIPError\n\n return external_ip\n\n except (requests.exceptions.RequestException, exceptions.GetExternalIPError):\n print('External IP HTTP Request failed')\n sys.exit(1)\n\n\ndef get_zone_id(config):\n try:\n zcache = config[\"cache_dir\"] + \"/zone.json\"\n zcf = open(zcache, 'r')\n zone = json.loads(zcf.read())\n\n # Check if cache is stale and we have old/different\n # zone data\n if config[\"zone_name\"] != zone[\"name\"]:\n raise exceptions.StaleCacheError\n\n print('{:<12} {}'.format(\"Zone ID:\", zone[\"id\"]))\n return zone[\"id\"]\n\n except (FileNotFoundError, exceptions.StaleCacheError):\n try:\n response = requests.get(\n url=config[\"zones_api_url\"],\n headers={\"Auth-API-Token\": config[\"access_token\"]},\n )\n zones = json.loads(response.content)[\"zones\"]\n\n for zone in zones:\n if zone[\"name\"] == config[\"zone_name\"]:\n print('{:<12} {}'.format(\"Zone ID:\", zone[\"id\"]))\n write_cache(zcache, zone)\n return (zone[\"id\"])\n\n return False\n\n except requests.exceptions.RequestException:\n print('Zone HTTP Request failed')\n sys.exit(1)\n\n # except json unmarshall error?\n\n\ndef get_record(config):\n try:\n rcache = config[\"cache_dir\"] + \"/record.json\"\n rcf = open(rcache, 'r')\n record = json.loads(rcf.read())\n print('{:<12} {}'.format(\"Record ID:\", record[\"id\"]))\n\n # Check if cache is stale/we (have a new record name and\n # an old cache)\n if config[\"record_name\"] != record[\"name\"]:\n raise exceptions.StaleCacheError\n\n if config[\"zone_id\"] != record[\"zone_id\"]:\n raise exceptions.StaleCacheError\n\n return record[\"id\"], record[\"value\"]\n\n except exceptions.StaleCacheError:\n return False, False\n\n except FileNotFoundError:\n try:\n response = requests.get(\n url=config[\"records_api_url\"],\n params={\"zone_id\": config[\"zone_id\"]},\n headers={\"Auth-API-Token\": config[\"access_token\"]},\n )\n\n records = json.loads(response.content)[\"records\"]\n\n for record in records:\n if record[\"name\"] == config[\"record_name\"]:\n print('{:<12} {}'.format(\"Record ID:\", record[\"id\"]))\n write_cache(rcache, record)\n return record[\"id\"], record[\"value\"]\n\n return False, False\n\n except requests.exceptions.RequestException:\n print('Record HTTP Request failed')\n sys.exit(1)\n\n\ndef update_record(config):\n print(\"Updating record with new external IP {}:\".format(\n config[\"external_ip\"]))\n\n try:\n response = requests.put(\n url=config[\"records_api_url\"] + \"/\" + config[\"record_id\"],\n headers={\"Auth-API-Token\": config[\"access_token\"]},\n data=json.dumps({\n \"value\": config[\"external_ip\"],\n \"ttl\": config[\"record_ttl\"],\n \"type\": \"A\",\n \"name\": config[\"record_name\"],\n \"zone_id\": config[\"zone_id\"]\n })\n )\n\n if response.status_code != 200:\n print(\"Update failed with http_status_code: {}.\".format(\n response.status_code))\n print(\"Response HTTP Response Body: {}\".format(response.content))\n return response.status_code\n\n return 0\n\n except requests.exceptions.RequestException:\n print('Record put HTTP Request failed')\n sys.exit(1)\n\n\ndef create_record(config):\n print(\"CREATE\")\n return 0\n\n\ndef main():\n # Check if we have a config file as argument\n if len(sys.argv) > 1:\n config_file = sys.argv[1]\n # Default config file\n else:\n config_file = \"config.yaml\"\n\n config = read_config(config_file)\n if config:\n config[\"external_ip\"] = get_external_ip()\n else:\n sys.exit(1)\n\n if not create_cache_dir(config[\"cache_dir\"]):\n sys.exit(1)\n\n config[\"zone_id\"] = get_zone_id(config)\n config[\"record_id\"], config[\"record_ip\"] = get_record(config)\n\n print('{:<12} {}'.format(\"External IP:\", config[\"external_ip\"]))\n print('{:<12} {}'.format(\"Record IP:\", config[\"record_ip\"]))\n\n if config[\"external_ip\"] == config[\"record_ip\"]:\n print(\"Nothing to do.\")\n sys.exit(0)\n\n if config[\"record_id\"]:\n rt = update_record(config)\n else:\n rt = create_record(config)\n\n sys.exit(rt)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hetzner-dyndns.py","file_name":"hetzner-dyndns.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"416782279","text":"def onHear(event):\n message = event.message\n if message == \"North\":\n pet.say(\"Htron\")\n if message == \"South\":\n pet.say(\"Htuos\")\n if message == \"East\":\n pet.say(\"Tsae\")\n\n\npet.on(\"hear\", onHear);\n\nwhile True:\n enemy = hero.findNearestEnemy()\n if enemy and enemy.type != \"brawler\":\n hero.attack(enemy)\n","sub_path":"7_Sarven_Desert/338-Pet_Translator/pet_translator.py","file_name":"pet_translator.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"293253382","text":"# -*- encoding:UTF-8 -*-\nimport wx\nimport logging\nimport Base\nfrom libs.Config import Font\nfrom libs.Config import Color\nfrom libs.Config import String\nfrom libs import Utility\n\nlogger = logging.getLogger(__name__)\n\n\nclass Switch(Base.TestPage):\n def __init__(self, parent, type):\n Base.TestPage.__init__(self, parent=parent, type=type)\n self.AUTO = True\n self.timer = wx.Timer(self) # 创建定时器\n self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) # 绑定一个定时器事件\n\n def OnTimer(self, event):\n comm = self.get_communicate()\n result = comm.is_button_clicked()\n if result is None:\n self.timer.Stop()\n if comm.reconnect():\n self.timer.Start(200)\n else:\n self.Parent.Parent.Parent.disconnect(error_msg=u\"连接异常,请手动尝试重新连接\")\n elif result == \"True\":\n self.EnablePass()\n\n def init_test_sizer(self):\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.desc = wx.StaticText(self, wx.ID_ANY, u\"请按下按键\", wx.DefaultPosition, wx.DefaultSize, 0)\n self.desc.SetFont(Font.DESC)\n self.desc.SetBackgroundColour(Color.LightSkyBlue1)\n sizer.Add(self.desc, 1, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, 1)\n return sizer\n\n def before_test(self):\n super(Switch, self).before_test()\n comm = self.get_communicate()\n comm.reset_button_click()\n\n def start_test(self):\n self.FormatPrint(info=\"Started\")\n self.timer.Start(200)\n\n def stop_test(self):\n self.timer.Stop()\n self.FormatPrint(info=\"Stop\")\n\n def append_log(self, msg):\n self.LogMessage(msg)\n wx.CallAfter(self.output.AppendText, u\"{time}\\t{message}\\n\".format(time=Utility.get_time(), message=msg))\n\n @staticmethod\n def GetName():\n return u\"按键测试\"\n\n @staticmethod\n def GetFlag(t):\n if t == \"PCBA\":\n return String.SWITCH_PCBA\n elif t in [\"MACHINE\", u\"整机\"]:\n return String.SWITCH_MACH\n","sub_path":"libs/UserInterface/TestPages/SwitchTest.py","file_name":"SwitchTest.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"98552475","text":"class Astronaut:\n \"\"\"\n Nowy astronauta\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n\n def say_hello(self, lang='en'):\n \"\"\"\n wyświetla przywitanie w zalezności od języka\n\n >>> Astronaut(name='José Jiménez').say_hello(lang='es')\n ¡hola José Jiménez!\n\n >>> Astronaut(name='Иван Иванович').say_hello(lang='ru')\n здраствуйте Иван Иванович!\n \"\"\"\n if lang == 'en':\n print(f'hello {self.first_name}')\n elif lang == 'es':\n print(f'¡hola {self.first_name}!')\n elif lang == 'ru':\n print(f'здраствуйте {self.first_name}!')\n else:\n print(f'witaj {self.first_name}!')\n\n\nastronaut = Astronaut(name='José Jiménez')\n","sub_path":"good-engineering-practice/src/debugging-docstring.py","file_name":"debugging-docstring.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"90281677","text":"__author__ = 'Hank'\n\n\nimport numpy as np\nimport cv2\n\nimg = np.zeros((512, 512, 3), np.uint8)\n\n\n#image x-y\n# 0-0 5-0 10-0\n\n\n# 0-5 5-5 10-5\n\n\n# 0-10 5-10 10-10\n\n#image, point1, point2, BGR (are you fucking kidding me?), thickness pixel\ncv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)\n\n#image, top left, bottom right, color, thickness pixel\ncv2.rectangle(img, (100, 100), (200, 500), (0, 100, 0), 5)\n\n\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"DrawTest.py","file_name":"DrawTest.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"397238488","text":"import os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nWTF_CSRF_ENABLED = True\nSECRET_KEY = os.environ['FLASK_SECRET_KEY']\n\nif os.environ.get('DATABASE_URL') is None:\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\nelse:\n SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']\n\nSQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\nENV = os.environ.get('ENV', 'PROD')\n\n\nLOCAL_OAUTH_CREDENTIALS = {\n 'google': {\n 'id': os.environ.get('LOCAL_GO_OAUTH_ID'),\n 'secret': os.environ.get('LOCAL_GO_OAUTH_SECRET'),\n },\n 'facebook': {\n 'id': '',\n 'secret': '',\n },\n 'slack': {\n 'id': '',\n 'secret': '',\n }\n}\n\n\nPROD_OAUTH_CREDENTIALS = {\n 'facebook': {\n 'id': os.environ['FB_OAUTH_ID'],\n 'secret': os.environ['FB_OAUTH_SECRET'],\n },\n 'google': {\n 'id': os.environ['GO_OAUTH_ID'],\n 'secret': os.environ['GO_OAUTH_SECRET'],\n },\n 'slack': {\n 'id': os.environ['SL_OAUTH_ID'],\n 'secret': os.environ['SL_OAUTH_SECRET'],\n }\n}\n\nOAUTH_CREDENTIALS = {\n 'LOCAL': LOCAL_OAUTH_CREDENTIALS,\n 'PROD': PROD_OAUTH_CREDENTIALS,\n}","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"377246934","text":"\n\"\"\"Under Construction \"\"\"\n# 2重のmultiprocessingでエラー\n\nimport os\nimport numpy as np\nimport json\nfrom datetime import datetime as dt\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import KFold\nfrom sklearn.externals import joblib\nfrom sklearn.base import clone\nimport multiprocessing as mp\n\nfrom collections import OrderedDict\n\nfrom .utility import create_log\n\n\ndef argwrapper(args):\n return args[0](**args[1])\n\n\ndef learning_batch(r, clf, X, y, multilabel, split):\n # - Constructs a new estimator with the same parameters.\n yy__, nz__ = np.array([]), np.array([])\n if multilabel:\n cv = KFold(n_splits=split, shuffle=True, random_state=r)\n ind = [i for _, i in cv.split(X)]\n else:\n cv = StratifiedKFold(n_splits=split, shuffle=True,\n random_state=r)\n ind = [i for _, i in cv.split(X, y)]\n for i in range(len(ind)-1):\n clf.fit(X[ind[i]], y[ind[i]])\n yy__ = np.append(yy__,\n 1-clf.score(X[ind[i+1]], y[ind[i+1]]))\n nz__ = np.append(nz__, clf.coef_.count_nonzero())\n return yy__, nz__, clf\n\n\ndef LearningCurve01(X, y, classifiers,\n rounds=1, split=10, path=\"\", key=None, n_jobs=1):\n if key is None:\n path = path + dt.today().isoformat().replace(\":\", \"-\")\n else:\n path = path + key\n if not os.path.exists(path):\n os.makedirs(path)\n logger = create_log(\"%s/logger.log\" % path)\n logger.info(\"Path: %s\" % path)\n logger.info(\"X shape: %i, %i\" % X.shape)\n logger.info(\"y shape: %i\" % y.shape[0])\n logger.info(\"train size: %0.2f\" % (y.shape[0]*(1-1/split)))\n if y.ndim > 1:\n multilabel = True\n logger.info(\"multilabel\")\n else:\n multilabel = False\n yy, nz = OrderedDict(), OrderedDict()\n try:\n for name, clf in classifiers:\n logger.info(\" training %s\" % name)\n job = mp.Pool(n_jobs)\n func_args = [(learning_batch,\n {'r': r, 'y': y, 'X': X,\n 'multilabel': multilabel, 'split': split,\n 'clf': clone(clf)})\n for r in range(rounds)]\n re = job.map(argwrapper, func_args)\n yy_ = np.vstack([re[i][0] for i in range(rounds)])\n nz_ = np.vstack([re[i][1] for i in range(rounds)])\n yy[name] = {'mean': list(yy_.mean(0)), 'std': list(yy_.std(0))}\n nz[name] = {'mean': list(nz_.mean(0)), 'std': list(nz_.std(0))}\n joblib.dump(re[0][2], \"%s/%s.pkl\" % (path, name))\n job.close()\n job.join()\n logger.info(\" save data\")\n with open(\"%s/%s.json\" % (path, \"error\"), \"w\") as f:\n json.dump(yy, f)\n with open(\"%s/%s.json\" % (path, \"nonzero\"), \"w\") as f:\n json.dump(nz, f)\n with open(\"%s/%s.json\" % (path, \"simulation_setting\"), \"w\") as f:\n json.dump({\"split\": split,\n \"data_classes\": len(np.unique(y)),\n \"data_size\": X.shape[0], \"data_order\": X.shape[1]}, f)\n except Exception as err:\n logger.exception(\"%s\", err)\n return path\n","sub_path":"stochastic_optimizer/framework/_learning_curve_with_multprocessing.py","file_name":"_learning_curve_with_multprocessing.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551398203","text":"from curlometer import curlometer\nimport numpy\n\n\ndef runTest():\n file = \"posmagdata.txt\"\n n = 2\n file = \"posmag4.txt\"\n n = 4\n # set as an array of 16 columns of size n\n# f = open(file, 'r')\n magData = numpy.zeros((16, n))\n posData = numpy.empty((16, n))\n# x = f.readline()\n x = numpy.loadtxt(file)\n# print(x.shape, x)\n# print(magData.shape, posData.shape)\n for i in range(n):\n magData[:, i] = x[i, :16]\n posData[:, i] = x[i, 16:]\n# print(posData[:, i])\n current, curlB, qf = curlometer(magData, posData)\n print(current.shape)\n print(current)\n print(curlB.shape)\n print(qf.shape)\n\nif __name__ == \"__main__\":\n runTest()\n","sub_path":"MMSMagPy/current/curltest.py","file_name":"curltest.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"441741651","text":"#!/usr/bin/env python3\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport os\nimport sys\n\nimport requests\nimport yaml\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '-p', '--projects',\n default='./reference/projects.yaml',\n help='projects.yaml file path (%(default)s)',\n)\nparser.add_argument(\n '-g', '--gerrit',\n default=('http://git.openstack.org/cgit/openstack-infra/project-config/'\n 'plain/gerrit/projects.yaml'),\n help=('URL for gerrit project list, ignored if --project-config is set or '\n 'when running in Zuul'),\n)\nparser.add_argument(\n '-c', '--project-config',\n default=('/home/zuul/src/git.openstack.org/openstack-infra/project-config'),\n help='Local path of project-config',\n)\nargs = parser.parse_args()\n\nwith open(args.projects, 'r', encoding='utf-8') as f:\n projects = yaml.safe_load(f.read())\n\n\nif os.path.exists(args.project_config):\n projects_yaml = '%s/gerrit/projects.yaml' % args.project_config\n with open(projects_yaml) as gerrit_projects:\n gerrit_data = yaml.safe_load(gerrit_projects)\nelse:\n response = requests.get(args.gerrit)\n gerrit_data = yaml.safe_load(response.text)\ngerrit_projects = set(\n entry.get('project')\n for entry in gerrit_data\n)\n\nerrors = 0\nfor team_name, team_data in projects.items():\n deliverables = team_data.get('deliverables')\n for deliverable_name, deliverable_data in deliverables.items():\n for repo_name in deliverable_data.get('repos', []):\n if repo_name not in gerrit_projects:\n print('Unknown repository {} as part of {} in {}'.format(\n repo_name, deliverable_name, team_name))\n errors += 1\n\nsys.exit(1 if errors else 0)\n","sub_path":"tools/validate_repositories.py","file_name":"validate_repositories.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"502193713","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport sys\nimport codecs\nimport django\nfrom openpyxl import load_workbook\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mysite.settings\")\ndjango.setup()\nfrom mysite.parts.models import *\ndef show_row(row):\n r=\"\"\n for c in row:\n r+=c.value\n print(r)\ndef treatOne(rows,fn,at):\n logging.info(rows)\n r=None\n beizhu=rows[3][3].value\n print(beizhu)\n if beizhu[:2]==\"CS\" or beizhu[:2]==\"ON\" or beizhu[:2]==\"NH\" or beizhu[:3]==\"DON\" or beizhu[:3]==\"DCS\":\n name=beizhu+\"_\"+str(at)+\"_\"+fn\n d=Pack.objects.filter(name=name)\n logging.info(d)\n if len(d)>0:\n pass\n else:\n d=Pack()\n d.name=name\n d.save()\n n=len(rows)\n items_xls=rows[6:n]\n for i in items_xls:\n show_row(i)\n input(\"show\")\n if i[0].value==\"\":\n break\n items=Item.objects.filter(bh=i[0].value).all()\n if len(items)>1:\n item=items[0]\n else:\n item=Item()\n item.bh=i[0].value\n item.name=i[1].value\n item.danwei=i[2].value\n item.save()\n di=PackItem()\n di.pack=d\n di.item=item\n di.ct=i[4].value\n di.save()\n r={\"id\":d.id,\"name\":d.name}\n return r\n\ndef readStandardFile(book,filename):\n table=book.worksheets[0]\n begin=False\n dan=[]\n for i in table.rows:\n cells=i\n print(cells[0].value)\n if cells[0].value==\"库存其它入库单\":\n if not begin:\n begin=True\n onedan=[]\n else:\n #finish\n dan.append(onedan)\n onedan=[]\n else:\n if begin:\n onedan.append(cells)\n else:\n pass\n logging.info(onedan)\n if len(onedan)>0:\n dan.append(onedan)\n rs=[]\n at=1\n for one in dan:\n r=treatOne(one,filename,at)\n if r!=None: \n rs.append(r)\n at+=1\n return rs\n\ndef standard():\n filename = r\"C:\\Users\\Administrator\\Desktop\\2021.2.23.xlsx\"\n xlBook = load_workbook(filename = filename)\n packs=readStandardFile(xlBook,filename)\n print(packs)\nif __name__==\"__main__\" :\n standard()","sub_path":"i.py","file_name":"i.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"145872745","text":"#!/usr/bin/env python3\n# coding: utf-8\nimport unittest\n\n\nclass Solution:\n def inorderTraversal(self, root):\n if not root:\n return []\n\n res = []\n stack = [root]\n while stack:\n node = stack.pop()\n if not node.left and not node.right:\n res.append(node.val)\n else:\n if node.right:\n stack.append(node.right)\n node.right = None\n stack.append(node)\n if node.left:\n stack.append(node.left)\n node.left = None\n\n return res\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self):\n self.test_cases = []\n\n def test_inorderTraversal(self):\n s = Solution()\n for i, e in self.test_cases:\n self.assertEqual(s.inorderTraversal(i), e)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n\n","sub_path":"Trees/inorder.py","file_name":"inorder.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"369102193","text":"#!/usr/bin/env python\n\nimport sys\n\nqapa_results_file=open(sys.argv[1],'r')\nqapa_results_file.readline()\nqapa_quant_bed=open(sys.argv[2],'w')\nheader_fields=['chrom','chromStart','chromEnd','name','score','strand']\nqapa_quant_bed.write('\\t'.join(header_fields)+'\\n')\nfor ln in qapa_results_file:\n ln=ln.strip().split('\\t')\n fields=[ln[4],ln[8],ln[9],ln[0],ln[13],ln[7]]\n qapa_quant_bed.write('\\t'.join(fields)+'\\n')\nqapa_quant_bed.close()\n","sub_path":"execution_workflows/QAPA/bin/make_quant_bed.py","file_name":"make_quant_bed.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"348011432","text":"'''\nPractice using\n\n assertTrue\n assertFalse\n assertIsNone\n assertIsNotNone\n assertIn\n assertNotIn\n\n'''\n\nfrom studentlists import ClassList, StudentError\nfrom unittest import TestCase\n\nclass TestStudentLists(TestCase):\n\n def test_add_student_check_student_in_list(self):\n test_class = ClassList(2)\n test_class.add_student('Test Student')\n self.assertIn('Test Student', test_class.class_list)\n\n test_class.add_student('Another Test Student')\n self.assertIn('Test Student', test_class.class_list)\n self.assertIn('Another Test Student', test_class.class_list)\n\n\n def test_add_student_already_in_list(self):\n test_class = ClassList(2)\n test_class.add_student('Test Student')\n with self.assertRaises(StudentError):\n test_class.add_student('Test Student')\n\n\n ## TODO write a test that adds and removes a student, and asserts the student is removed. Use assertNotIn\n def test_add_and_remove_student(self):\n test_class = ClassList(2)\n test_class.add_student('Hazel')\n test_class.remove_student('Hazel')\n self.assertNotIn('Hazel', test_class.class_list)\n\n ## TODO write a test that adds some example students, then removes a student not in the list, and asserts a StudentError is raised\n def test_remove_student_that_is_not_in_list(self):\n test_class = ClassList(3)\n test_class.add_student('Marco')\n test_class.add_student('Sophie')\n test_class.add_student('Petricore')\n with self.assertRaises(StudentError):\n test_class.remove_student('Gus')\n\n ## TODO write a test that removes a student from an empty list, and asserts a StudentError is raised\n def test_remove_student_from_empty_list(self):\n test_class = ClassList(3)\n with self.assertRaises(StudentError):\n test_class.remove_student('Alana')\n\n\n def test_is_enrolled_when_student_present(self):\n test_class = ClassList(2)\n test_class.add_student('Snoop Dogg')\n test_class.add_student('Martha Stewart')\n self.assertTrue(test_class.is_enrolled('Snoop Dogg'))\n self.assertTrue(test_class.is_enrolled('Martha Stewart'))\n\n\n def test_is_enrolled_empty_class_list(self):\n test_class = ClassList(2)\n self.assertFalse(test_class.is_enrolled('Snoop Dogg'))\n\n\n ## TODO write a test that adds some example students to a test class,\n ## then, call is_enrolled for a student who is not enrolled. use assertFalse to verify is_enrolled returns False.\n def test_check_enrollment_for_student_not_enrolled(self):\n test_class = ClassList(2)\n test_class.add_student('The Will')\n test_class.add_student('The Stalk')\n self.assertFalse(test_class.is_enrolled('The Brand'))\n\n def test_string_with_students_enrolled(self):\n test_class = ClassList(2)\n test_class.add_student('Taylor Swift')\n test_class.add_student('Kanye West')\n self.assertEqual('Taylor Swift, Kanye West', str(test_class))\n\n\n def test_string_empty_class(self):\n test_class = ClassList(2)\n self.assertEqual('', str(test_class))\n\n\n def test_index_of_student_student_present(self):\n test_class = ClassList(3)\n test_class.add_student('Harry')\n test_class.add_student('Hermione')\n test_class.add_student('Ron')\n\n self.assertEqual(1, test_class.index_of_student('Harry'))\n self.assertEqual(2, test_class.index_of_student('Hermione'))\n self.assertEqual(3, test_class.index_of_student('Ron'))\n\n # This assert passes, but it's redundant - the first assert statement will fail if\n # the method call returns None\n self.assertIsNotNone(test_class.index_of_student('Harry'))\n\n\n \n ## TODO write a test for index_of_student when the class_list list is empty. \n # Assert index_of_student returns None for a student if the list is empty. use assertIsNone.\n def test_empty_list_returns_none_for_index(self):\n test_class = ClassList(2)\n self.assertIsNone(test_class.index_of_student('Oswald'))\n \n ## TODO write another test for index_of_student. In the case when the list is not empty but \n # assert that searching for a student name that is not in the list, returns None.\n def test_index_student_not_in_list(self):\n test_class = ClassList(2)\n test_class.add_student('Barr')\n self.assertIsNone(test_class.index_of_student('Klara'))\n \n ## TODO write a test for your new is_class_full method when the class is full. use assertTrue.\n def test_return_true_for_class_is_full(self):\n test_class = ClassList(2)\n test_class.add_student('Prince Robot')\n test_class.add_student('Princeling')\n self.assertTrue(test_class.is_class_full())\n \n ## TODO write a test for your new is_class_full method for when is empty, and when it is not full. Use assertFalse.\n def test_for_class_not_full(self):\n test_class = ClassList(3)\n test_class.add_student('Missy')\n test_class.add_student('Yuma')\n self.assertFalse(test_class.is_class_full())","sub_path":"student_lists/test_studentlists.py","file_name":"test_studentlists.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"507879890","text":"from kea.axi_lite_registers import Registers, axi_lite_handler\nfrom kea.axi import AxiLiteInterface, AxiLiteMasterBFM\n\nimport random\n\nfrom myhdl import *\nimport myhdl\n\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\n\nregister_names = [\n 'control', 'counter_reset_value', 'status']\n\n@block\ndef counter_block(clock, axil_resetn, axi_lite_bus):\n\n register_types = {\n 'control': 'axi_write_only',\n 'counter_reset_value': 'axi_read_write',\n 'status': 'axi_read_only'}\n\n register_initial_values = {\n 'counter_reset_value': 100}\n\n registers = Registers(\n register_names, register_types,\n initial_values=register_initial_values)\n\n counter = Signal(intbv(0)[32:])\n\n @always(clock.posedge)\n def do_counter():\n\n if registers.control[0]:\n # Reset\n counter.next = 0\n\n elif counter >= registers.counter_reset_value:\n counter.next = 0\n\n else:\n counter.next = counter + 1\n\n @always_comb\n def status_connector():\n registers.status.next = counter\n\n register_handler = axi_lite_handler(\n clock, axil_resetn, axi_lite_bus, registers)\n\n return do_counter, status_connector, register_handler\n\n@block\ndef clock_source(clock, period):\n\n if not isinstance(clock, myhdl._Signal._Signal):\n raise ValueError('The passed clock signal is not a signal')\n\n even_period = period//2\n odd_period = period - even_period\n\n start_val = int(clock.val)\n not_start_val = int(not clock.val)\n\n clock_state = Signal(clock.val)\n\n @instance\n def clockgen():\n\n while True:\n yield(delay(even_period))\n clock.next = not clock_state\n clock_state.next = not clock_state\n yield(delay(odd_period))\n clock.next = not clock_state\n clock_state.next = not clock_state\n\n return clockgen\n\n\n@block\ndef top():\n '''A simple test example that controls a counter through a register\n interface, using the BFM.\n\n With some probability, the counter is either reset, the value is changed\n or the counter is read.\n '''\n data_width = 32\n addr_width = 4\n\n bfm = AxiLiteMasterBFM()\n\n axi_lite_interface = AxiLiteInterface(\n data_width, addr_width, use_AWPROT=False, use_ARPROT=False,\n use_WSTRB=False)\n\n axil_resetn = Signal(True)\n clock = Signal(False)\n\n period = 10\n clock_gen = clock_source(clock, period)\n counter = counter_block(clock, axil_resetn, axi_lite_interface)\n\n bfm_inst = bfm.model(clock, axil_resetn, axi_lite_interface)\n\n t_test_states = enum('IDLE', 'READING', 'WRITING')\n test_state = Signal(t_test_states.IDLE)\n\n @always(clock.posedge)\n def test_driver():\n\n if test_state == t_test_states.IDLE:\n random_val = random.random()\n\n # Remember, the list index should be multiplied by 4 to get the\n # byte address\n\n if random_val < 0.1:\n # Reset the counter\n print('Resetting the counter')\n bfm.add_write_transaction(\n register_names.index('control') * 4, 1)\n\n test_state.next = t_test_states.WRITING\n\n elif random_val < 0.2:\n upper_val = random.randrange(40, 150)\n # change the counter upper value\n print('Changing the upper value to %d' % upper_val)\n bfm.add_write_transaction(\n register_names.index('counter_reset_value') * 4,\n upper_val)\n test_state.next = t_test_states.WRITING\n\n elif random_val < 0.6:\n print('Reading the current counter value')\n bfm.add_read_transaction(register_names.index('status') * 4)\n test_state.next = t_test_states.READING\n\n elif test_state == t_test_states.WRITING:\n\n try:\n response = bfm.write_responses.get(block=False)\n print('Response: %d' % response['wr_resp'])\n test_state.next = t_test_states.IDLE\n\n except queue.Empty:\n pass\n\n elif test_state == t_test_states.READING:\n try:\n response = bfm.read_responses.get(block=False)\n print('Response: %d' % response['rd_data'])\n test_state.next = t_test_states.IDLE\n\n except queue.Empty:\n pass\n\n\n return clock_gen, counter, bfm_inst, test_driver\n\ndef runner():\n\n top_inst = top()\n top_inst.run_sim()\n\nif __name__ == '__main__':\n runner()\n","sub_path":"examples/register_example.py","file_name":"register_example.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"480459962","text":"# -*- coding: utf-8 -*-\n\"\"\"some helper functions.\"\"\"\nimport numpy as np\n\ndef standardize(x):\n \"\"\"Standardize the original data set.\"\"\"\n mean_x = np.mean(x, axis=0)\n x = x - mean_x\n std_x = np.std(x, axis=0)\n x = x / std_x\n return x\n\ndef clean_data(x, col=None):\n \"\"\" Remove -999 values and replace by mean of feature.\n May remove col features.\n \"\"\"\n if col is not None:\n x=np.delete(x,col,1)\n x[x==-999]=np.nan\n meanX=np.nanmean(x,axis=0)\n indsX = np.where(np.isnan(x))\n x[indsX]=np.take(meanX,indsX[1])\n return x\n \ndef transform_data(x):\n \"\"\"\n Transform the data in a log way if possible\n (and if data is skewed)\n \"\"\"\n for i in range(x.shape[1]):\n if(not np.any(x[:,i]<=0)):\n x[:,i]=np.log(x[:,i])\n return x\n\ndef reject_outliers(data, m=10):\n \"\"\"reject outliers if outside m*std\"\"\"\n newData=np.copy(data)\n ind=abs(data - np.mean(data,axis=0)) > m * np.std(data,axis=0)\n newData[ind]=0\n return newData\n \n\ndef batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):\n \"\"\"\n Generate a minibatch iterator for a dataset.\n Takes as input two iterables (here the output desired values 'y' and the input data 'tx')\n Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.\n Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.\n Example of use :\n for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):\n \n \"\"\"\n data_size = len(y)\n\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_y = y[shuffle_indices]\n shuffled_tx = tx[shuffle_indices]\n else:\n shuffled_y = y\n shuffled_tx = tx\n for batch_num in range(num_batches):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n if start_index != end_index:\n yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n","sub_path":"files/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"112167879","text":"import pygame\nfrom pygame.locals import *\n\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nfrom GridClass import GridClass\n\nclass GameClass():\n\n def __init__(self, window_w, window_h):\n\n pygame.init()\n self.display = (window_w, window_h)\n pygame.display.set_mode(self.display, DOUBLEBUF | OPENGL)\n pygame.display.set_caption(\"MEMO3D\")\n glEnable(GL_DEPTH_TEST)\n\n self.win = False\n\n self.game = GridClass(2.5)\n\n def eventLoopProcessing(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n quit()\n if event.key == pygame.K_r:\n self.game = GridClass(2.5)\n self.win = False\n if event.key == pygame.K_UP and self.win == False:\n self.game.moveUp()\n if event.key == pygame.K_DOWN and self.win == False:\n self.game.moveDown()\n if event.key == pygame.K_RIGHT and self.win == False:\n self.game.moveRight()\n if event.key == pygame.K_LEFT and self.win == False:\n self.game.moveLeft()\n if event.key == pygame.K_SPACE and self.win == False:\n self.game.update()\n\n def checkWinCondition(self):\n if self.win == False:\n self.win = self.game.checkWin()\n\n def drawGame(self):\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n gluPerspective(45, (self.display[0] / self.display[1]), 0.1, 50.0)\n glTranslate(0.0, 0.0, -20.0)\n\n self.game.draw()\n\n pygame.display.flip()\n\n","sub_path":"MEMO3D/GameClass.py","file_name":"GameClass.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"344162697","text":"import pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndf = pd.read_csv(\"TCGA-COAD_cancer_normal.tsv\", sep=\"\\t\", index_col=0)\ngl = pd.read_csv(\"gene_lengths.tsv\", sep=\"\\t\", index_col=0).sort_index()\nsize_factors = [0.35219656, 0.39439086, 0.73057344, 1.66138079, 1.60002838, 1.48313616, 1.28046971, 0.92434274, 1.59306799, 1.34997698]\n\nRPK = df.div(gl[\"Length\"] / 10**3, axis=0)\nTPM = RPK.div(RPK.sum(axis=0) / 10**6, axis=1)\n\nRPM = df.div(df.sum(axis=0) / 10**6, axis=1)\nRPKM = RPM.div(gl[\"Length\"] / 10**3, axis=0)\n\nTPM = TPM.div(size_factors, axis=1)\nRPKM = RPKM.div(size_factors, axis=1)\n\nRPKM = np.log2(RPKM + 1)\nRPKM = RPKM.loc[RPKM.max(axis=1) > 0]\n\nRPKM[\"median\"] = RPKM.median(axis=1)\nRPKM = RPKM.sort_values(\"median\", ascending=False)\nRPKM = RPKM.iloc[:10000]\n\nRPKM[\"fold change\"] = RPKM.iloc[:, :5].mean(axis=1) - RPKM.iloc[:, 5:10].mean(axis=1)\nRPKM[\"abs fold change\"] = np.abs(RPKM[\"fold change\"])\nRPKM = RPKM.sort_values(\"abs fold change\", ascending=False)\n\nRPKM_tumor = RPKM.iloc[:5, :5].T\nRPKM_normal = RPKM.iloc[:5, 5:10].T\n\nRPKM_tumor = RPKM_tumor.melt(var_name=\"Gene\", value_name=\"Expression\")\nRPKM_tumor[\"Type\"] = \"Tumor\"\nRPKM_normal = RPKM_normal.melt(var_name=\"Gene\", value_name=\"Expression\")\nRPKM_normal[\"Type\"] = \"Normal\"\nRPKM = pd.concat([RPKM_tumor, RPKM_normal])\n\nsns.barplot(data=RPKM, x=\"Gene\", y=\"Expression\", hue=\"Type\")\nplt.tight_layout()\nplt.savefig(\"test.pdf\")\n","sub_path":"seminar7/classwork.py","file_name":"classwork.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"312498738","text":"import keyword\nfrom kaa.filetype.default import defaultmode, theme\nfrom kaa.highlight import Tokenizer, Keywords, Span\nfrom kaa.theme import Theme, Style\n\nPythonTheme = Theme('python', [\n Style('default', 'default', 'default', False, False),\n Style('statement', 'magenta', 'default'),\n Style('string', 'red', 'default'),\n Style('bytes', 'blue', 'default'),\n])\n\nclass PythonMode(defaultmode.DefaultMode):\n def init_theme(self):\n self.theme = PythonTheme\n\n def init_tokenizers(self):\n self.tokenizers = [Tokenizer([\n Keywords('python-statement', 'statement', keyword.kwlist),\n\n Span('python-string31', 'string', 'r?\"\"\"', '\"\"\"', escape='\\\\'),\n Span('python-string32', 'string', \"r?'''\", \"'''\", escape='\\\\'),\n Span('python-string11', 'string', 'r?\"', '\"', escape='\\\\'),\n Span('python-string12', 'string', \"r?'\", \"'\", escape='\\\\'),\n\n Span('python-bytes31', 'bytes', '(br?|r?b)\"\"\"', '\"', escape='\\\\'),\n Span('python-bytes32', 'bytes', \"(br?|r?b)'''\", \"'''\", escape='\\\\'),\n Span('python-bytes11', 'bytes', '(br?|r?b)\"', '\"', escape='\\\\'),\n Span('python-bytes12', 'bytes', \"(br?|r?b)'\", \"'\", escape='\\\\'),\n ])]\n\n","sub_path":"kaa/filetype/python/pythonmode.py","file_name":"pythonmode.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346207455","text":"import random\r\n\r\nfrom wikipedia.exceptions import RedirectError\r\n\r\n\r\ndef get_category():\r\n with open(\"content_generator/categories.txt\") as f:\r\n file_data = f.read()\r\n\r\n categories = file_data.split('\\n')\r\n categories.pop(-1)\r\n\r\n random_index = random.randint(0, len(categories)-1)\r\n\r\n return categories[random_index]\r\n\r\n\r\ndef create_life_generator_input_csv(category):\r\n print('Creating CSV file to request data from Life Generator')\r\n f = open('requested_data.csv', 'w')\r\n\r\n # Insert .csv header\r\n f.write('Content generator requests data on the following category:\\n')\r\n f.write('toys,')\r\n f.write(category)\r\n f.write(',1\\n')\r\n\r\n\r\ndef read_life_generator_output():\r\n print('Reading data sent by Life Generator')\r\n f = open('output.csv', 'r')\r\n f.readline()\r\n result = f.readline().split(',')\r\n if(len(result) > 3):\r\n result.pop(2)\r\n result.pop(2)\r\n result.pop(-1)\r\n else:\r\n result = ['No luck this time. Try again...']\r\n result.append(result[0])\r\n result.append(result[0])\r\n\r\n print('\\n')\r\n return result\r\n\r\n# if __name__ == '__main__':\r\n\r\n# x = get_category()\r\n# print(x)\r\n# create_life_generator_input_csv(x)\r\n# read_life_generator_output()\r\n","sub_path":"Content_Generator/communication.py","file_name":"communication.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"649054666","text":"#! /usr/bin/python3\nclass Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n s = str(abs(x))[::-1]\n s_int = int(s)\n if s_int > 2147483647:\n return 0\n if x < 0:\n \treturn s_int*-1\n else:\n \treturn s_int\n","sub_path":"reverse_integer/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"549406855","text":"import requests\n\nurl = 'http://10.99.99.99:8010/cgi-bin/webauth/ajax_webauth'\nheader = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',\n 'Referer': 'http://47.98.217.40/',\n }\n\n# 参数自己改\n\ndata = {\n \"action\": \"login\", \n \"user\": \"账号\", \n \"pwd\": \"密码\", \n \"usrmac\": \"设备mac\", \n \"ip\": \"设备ip\", \n \"success\": \"http://10.99.99.99:8080/webauth/success.html#\", \n \"fail\": \"http://10.99.99.99:8080/webauth/fail.html#\", \n \"clear\": \"http://10.99.99.99:8080/webauth/clear.html#\"\n}\n\nmes = requests.post(url, headers=header, data=data)\n# 返回的结果\nprint(str(1)+str(mes.status_code)+':'+str(mes.text))","sub_path":"其他自用脚本/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"645596994","text":"import os\n\ndef build(apps):\n app_id = 0\n base_address = 0x80400000\n step = 0x20000\n linker = 'src/linker.ld'\n for app in apps:\n lines = []\n lines_before = []\n with open(linker, 'r') as f:\n for line in f.readlines():\n lines_before.append(line)\n line = line.replace(hex(base_address), hex(base_address+step*app_id))\n lines.append(line)\n with open(linker, 'w+') as f:\n f.writelines(lines)\n os.system('cargo build --bin %s --release' % app)\n print('[build.py] application %s start with address %s' %(app, hex(base_address+step*app_id)))\n with open(linker, 'w+') as f:\n f.writelines(lines_before)\n app_id = app_id + 1\n\nif __name__ == '__main__':\n apps = os.listdir('src/bin')\n apps.sort()\n base, yield_, stride = [], [], []\n for app in apps:\n app = app[:app.find('.')]\n if app.startswith('ch2') or app.startswith('ch3_0') or app.startswith('ch3t'):\n base.append(app)\n elif app.startswith('ch3_1'):\n yield_.append(app)\n elif app.startswith('ch3_2'):\n stride.append(app)\n build(base)\n build(yield_)\n build(stride)\n\n","sub_path":"user/ch3-build.py","file_name":"ch3-build.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"241867261","text":"import numpy\n\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.utils import np_utils\nfrom keras.layers import Dense, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.layers import Dropout\n\n\nnumpy.random.seed(42)\n\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n\n# Нормальизация данных(либо 1, либо 0)\nX_train = X_train.astype('float32') / 255.\nX_test = X_test.astype('float32') / 255.\nX_train = numpy.reshape(X_train, (len(X_train), 28, 28, 1))\nX_test = numpy.reshape(X_test, (len(X_test), 28, 28, 1))\n\n# Приводим массив с ответами к категориальному типу\nY_train = np_utils.to_categorical(Y_train, 10)\nY_test = np_utils.to_categorical(Y_test, 10)\n\n# Последовательная модель(слои друг за другом)\nmodel = Sequential()\n\nmodel.add(Convolution2D(16, 3, 3, border_mode='same',\n input_shape=(28, 28, 1),\n activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Convolution2D(32, 3, 3, activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Convolution2D(64, 3, 3, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=\"SGD\",\n metrics=['accuracy'])\nprint(model.summary())\n\nmodel.fit(X_train, Y_train,\n batch_size=32,\n nb_epoch=10,\n validation_split=0.1,\n shuffle=True)\n\nscores = model.evaluate(X_test, Y_test, verbose=0)\n\nprint(\" \")\nprint(\"Точность работы на тестовых данных %.2f\" % (scores[1]*100))\nmodel.save(\"/home/batya/Project/PycharmProjects/NeuralNetwork/model_dig_conv.h5\")\n","sub_path":"Digits_Conv.py","file_name":"Digits_Conv.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164335381","text":"from models import AppScript\nfrom cgi import escape\n\n#########\nimport urllib\nimport json\nfrom base64 import b64decode, b64encode, urlsafe_b64decode\n\nfrom appinmail_sso_client import AppinmailClient\nfrom appinmail_sso_utils import Utils\n\nimport ProAdmin\nfrom promail_eac import EACContent\nfrom promail_eac_helper import eacviewer_authenticated, process_vdomxml_resources\n\n\ndef process_wholexml(wholexml):\n eac = EACContent(wholexml) # EACContent(decode_wholexml(wholexml))\n wholedata = eac.wholedata\n login = wholedata['api']['methods'].get('login', None)\n get = wholedata['api']['methods'].get('get', None)\n post = wholedata['api']['methods'].get('post', None)\n pattern = get.get('pattern', '') if get else ''\n if pattern:\n pattern = json.dumps(pattern)\n pattern_post = post.get('pattern', '') if post else ''\n if pattern_post:\n pattern_post = json.dumps(pattern_post)\n return {\n 'session_token': wholedata['global'].get('SessionToken', ''),\n 'login_container': login['container'] if login else '',\n 'login_action': login['action'] if login else '',\n 'get_container': get['container'] if get else '',\n 'get_action': get['action'] if get else '',\n 'pattern': pattern,\n 'post_container': post['container'] if post else '',\n 'post_action': post['action'] if post else '',\n 'pattern_post': pattern_post,\n 'app_id': wholedata['api']['appID'],\n 'server': wholedata['api']['server'],\n 'vdomxml': wholedata['vdom'],\n 'events': wholedata['events'],\n 'static': '1' if eac.is_static() else ''\n }\n\n\n#########\n\n\n\nscript_id = request.arguments.get('script_id', '')\ncommand = request.arguments.get('command', 'update')\n\napp_script = AppScript.get(guid=script_id)\n\nif app_script:\n\tif command == 'wholexml':\n\n\t\tinput_params = {\n\t\t\t'eac_token': True,\n\t\t\t'session_token': False,\n\t\t\t'login_container': False,\n\t\t\t'login_action': False,\n\t\t\t'get_container': False,\n\t\t\t'get_action': False,\n\t\t\t'post_container': False,\n\t\t\t'post_action': False,\n\t\t\t'app_id': False,\n\t\t\t'server': False,\n\t\t\t'attachments': False,\n\t\t\t'pattern': False,\n\t\t\t'pattern_post': False,\n\t\t\t'email': True,\n\t\t\t'vdomxml': False,\n\t\t\t'events': False,\n\t\t\t'static': False,\n\t\t}\n\n\t\t# parameters to apply base64 encoding\n\t\tenc = ['pattern', 'pattern_post']\n\t\t# parameters that won't be saved in shared variables\n\t\tskip = ['vdomxml', 'events', 'static']\n\n\t\tparams = {}\n\n\t\twholexml = app_script.source\n\t\tif wholexml:\n\t\t\tparams = process_wholexml(wholexml)\n\n\t\tfor arg in input_params:\n\t\t\tvalue = request.arguments.get(arg, None)\n\t\t\tif value is not None or arg not in params:\n\t\t\t\tparams[arg] = value\n\t\t\tif not params[arg] and input_params[arg]:\n\t\t\t\traise ValueError(arg)\n\n\t\tfor arg in params:\n\t\t\tif arg in skip:\n\t\t\t\tcontinue\n\t\t\tif params[arg] and arg in enc:\n\t\t\t\tresponse.shared_variables[arg] = b64encode(params[arg])\n\t\t\telse:\n\t\t\t\tresponse.shared_variables[arg] = params[arg]\n\n\t\tif params['static'] and params['static'] != '0':\n\t\t\tself.eactimer.active = \"0\"\n\t\telse:\n\t\t\tself.eactimer.active = \"1\"\n\t\tif params['vdomxml']:\n\t\t\tself.dialog_preview.eacviewer.vdomxml = process_vdomxml_resources(\n\t\t\t\tvdomxml=params['vdomxml'],\n\t\t\t\tserver=params['server'])\n\t\t\tif params['events']:\n\t\t\t\tself.dialog_preview.eacviewer.vdomactions = params['events']\n\n\n########\n#\t\tself.dialog_preview.hypertext1.htmlcode = escape(str(params))\n\t\tself.dialog_preview.show = '1'\n\n\telif command == 'play':\n\t\tfrom VEE_tools import \tcompile, execute, PythonCompilationError, VScriptComlipationError,\\\n\t\t\t\t\t\tPythonExecutionError, VScriptExecutionError, StopExecutionError, \\\n\t\t\t\t\t\tVScriptInternalError\n\t\tfrom VEE_vmacro_dispatcher import STD_ENV_DICT\n\n\t\tcompiled_code, debug_info = compile(app_script.source, dict(STD_ENV_DICT))\n\n\t\ttry:\n\t\t\texecute( compiled_code, debug_info)\n\n\t\texcept VScriptInternalError as error:\n\t\t\treport = u\"\\n{}\".format(error.report) if getattr(error, \"report\", None) else \"\"\n\t\t\traise Exception(unicode(error) + report)\n\n\t\texcept VScriptExecutionError as error:\n\t\t\traise Exception(\"VScript Execution Error\")\n\n\t\texcept StopExecutionError as error:\n\t\t\tpass\n\t\texcept PythonExecutionError as error:\n\t\t\ttry:\n\t\t\t\tfrom utils.tracing import format_exception_trace\n\t\t\t\traise Exception(u\"Python Execution Error: \" + format_exception_trace(locals=True))\n\t\t\texcept ImportError:\n\t\t\t\tfrom vdom_trace import Trace\n\t\t\t\tmsg = [ u\"Python Execution Error:\" ]\n\t\t\t\tmsg.extend( Trace.print_traceback() )\n\t\t\t\tmsg.append( u\"Exception: {0}\".format( error.message ) )\n\t\t\t\traise Exception( u\" --> \".join( msg ) )\n\n\t\tself.growl.action(\"show\", [\"Launched\", \"Script successfully launched\" ] )\n\n\telse:\n\n\t\tdisabled = '2' if command == 'delete' else '0'\n\n\t\tform = self.dialog_update.form_update\n\n\t\tform.tab_script_detail.tab_params.input_title.value = app_script.name\n\t\tform.tab_script_detail.tab_params.input_title.mode = disabled\n\t\tform.tab_script_detail.tab_params.application_id.value = app_script.application_id\n\t\tform.tab_script_detail.tab_params.script_id.value = app_script.guid\n\t\tform.tab_script_detail.tab_params.command.value = command\n\n\t\tform.tab_script_detail.tab_source.input_source.value = escape(app_script.source or \"\")\n\t\tform.tab_script_detail.tab_source.input_source.mode = disabled\n\n\t\tself.dialog_update.form_update.btn_update.label = command.title()\n\t\tself.dialog_update.form_update.tab_script_detail.tab_params.error_name.value = ''\n\t\tform.btn_update.action( \"setClass\", [ 'btn btn-danger' if command == 'delete' else 'btn btn-success' ] )\n\t\tself.dialog_update.title = 'Script {}'.format(command.title())\n\t\tself.dialog_update.show = '1'\n","sub_path":"Pages/application/tab_app/tab_script/cnt_script/Actions-cnt_script/script_dialog_fill.py","file_name":"script_dialog_fill.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"1049588","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport requests\nimport http.cookiejar\n\ncj = http.cookiejar.CookieJar()\nlink = 'https://testkrok.org.ua/?test=775'\ncook = dict(\n # меняетса динамически, без времени окончания\n sys_session='rovnq7b47evsi6455d810nmk90',\n # Мова: 1 > укр, 2 > рус, 3 > англ\n savestate_0=1,\n # Екзамен: 1-К1, 2-К2, 3-К3, 4- Крок М, 5-Крок Б\n savestate_1=3,\n # Спеціальність: 1-Стоматологія, 2-Ліквальна справа\n savestate_2=2,\n # Джерело:\n # 1 - Буклети\n # 2 - Бази 2010\n # 3 - Бази 2012\n # 4 - Бази 2013 Весна\n # 5 - Бази 2013 Осінь\n # 6 - Бази 2014 Осінь\n savestate_3=6,\n # Бази 2014 по темам:\n # Акушерство і гінекологія: 1 - 2\n # Інфекційні хвороби: 3 - 4\n # Педіатрія: 5 - 9\n # Терапія: 10 - 17\n # Хірургія: 18 - 22\n savestate_4=5)\ncj = http.cookiejar.CookieJar(cook)\n\nr = requests.get(link, cookies=cj)\nprint(cj)\n","sub_path":"sandBox/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"248681276","text":"'''\r\nCreated on 2015-08-18\r\n\r\n@author: Magee_yang\r\n'''\r\n\r\n\r\nimport sys\r\nimport wx\r\nimport gui.mainFrame\r\nfrom gui.viewColumn import ViewColumn\r\n\r\nfrom gui.cachingImageList import CachingImageList\r\n\r\nclass Display(wx.ListCtrl):\r\n def __init__(self,parent,size=wx.DefaultSize,style =0):\r\n wx.ListCtrl.__init__(self,parent,size=size,style=wx.LC_REPORT | style)\r\n \r\n self.imageList = CachingImageList(16,16)\r\n self.SetImageList(self.imageList,wx.IMAGE_LIST_SMALL)\r\n self.columnsMinWidth = []\r\n self.activeColumns = []\r\n \r\n \r\n i = 0\r\n \r\n for colName in self.DEFAULT_COLS:\r\n # col = ViewColumn.getColumn(colName)(self, None)\r\n self.addColumn(i, colName)\r\n self.columnsMinWidth.append(self.GetColumnWidth(i))\r\n i += 1\r\n \r\n info = wx.ListItem()\r\n info.m_mask = wx.LIST_MASK_WIDTH\r\n self.InsertColumnInfo(i,info)\r\n self.SetColumnWidth(i,0)\r\n \r\n def addColumn(self, i, col):\r\n self.activeColumns.append(col)\r\n info = wx.ListItem()\r\n info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT\r\n info.m_image = -1\r\n info.m_text = col\r\n info.m_format = wx.LIST_FORMAT_LEFT\r\n #self.InsertColumnInfo(i, info)\r\n self.InsertColumn(i,col)\r\n \r\n self.SetColumnWidth(i, 100)\r\n \r\n def update(self, stuff):\r\n self.populate(stuff)\r\n self.refresh(stuff)\r\n \r\n def populate(self, stuff):\r\n\r\n if stuff is not None:\r\n listItemCount = self.GetItemCount()\r\n stuffItemCount = len(stuff)\r\n\r\n if listItemCount < stuffItemCount:\r\n for i in xrange(stuffItemCount - listItemCount):\r\n index = self.InsertStringItem(sys.maxint, \"\")\r\n\r\n if listItemCount > stuffItemCount:\r\n if listItemCount - stuffItemCount > 20 and stuffItemCount < 20:\r\n self.DeleteAllItems()\r\n for i in xrange(stuffItemCount):\r\n index = self.InsertStringItem(sys.maxint, \"\")\r\n else:\r\n for i in xrange(listItemCount - stuffItemCount):\r\n self.DeleteItem(self.getLastItem())\r\n self.Refresh()\r\n\r\n\r\n def refresh(self, stuff):\r\n if stuff == None:\r\n return\r\n\r\n item = -1\r\n for id, st in enumerate(stuff):\r\n\r\n item = self.GetNextItem(item)\r\n\r\n for i, col in enumerate(self.activeColumns):\r\n colItem = self.GetItem(item, i)\r\n if i==0:\r\n colItem.SetText(\"\")\r\n elif i==1:\r\n colItem.SetText(st.name)\r\n else:\r\n colItem.SetText(\"\")\r\n self.SetItem(colItem)\r\n self.SetItemData(item, id)\r\n\r\n\r\n def getLastItem( self, state = wx.LIST_STATE_DONTCARE):\r\n lastFound = -1\r\n while True:\r\n index = self.GetNextItem(\r\n lastFound,\r\n wx.LIST_NEXT_ALL,\r\n state,\r\n )\r\n if index == -1:\r\n break\r\n else:\r\n lastFound = index\r\n\r\n return lastFound \r\n","sub_path":"src/gui/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"639264408","text":"#! /usr/bin/env python\nimport argparse\nimport itertools\nimport json\nfrom datetime import datetime\nfrom decimal import Decimal\n\nimport dateutil.parser\nimport psycopg2\nfrom flask import Flask, abort, g, make_response, request\nfrom flask.ext.cors import CORS\n\nfrom server.db import fetchall_dict, fetchone_dict\n\n\napp = Flask(__name__)\napp.config.from_envvar('MONEY_SETTINGS')\nCORS(app)\n\n\n@app.route('/api/v1.0/accounts', methods=['GET'])\n@app.route('/api/v1.0/accounts/', methods=['GET'])\ndef get_accounts(account_id=None):\n c = g.db.cursor()\n c.execute('''\n select\n *,\n current_balance + (\n select coalesce(sum(av2.current_balance), 0)\n from accounts_view av2\n where av.id = any(av2.ancestor_ids)\n ) as total_current_balance\n from accounts_view av\n where %(account_id)s is null or id = %(account_id)s\n ''', {'account_id': account_id})\n accounts = fetchall_dict(c)\n if account_id is None:\n return jsonify(accounts)\n elif not accounts:\n abort(404)\n else:\n assert len(accounts) == 1\n a = accounts[0]\n a['recent_transactions'] = get_recent_transactions(c, 8, a)\n return jsonify(a)\n\n\ndef get_recent_transactions(c, count, account):\n account_id = account['id']\n trs = get_transactions_with_splits(c, count=count,\n before_timestamp=datetime.now(),\n account_id=account_id)\n augment_transactions_for_account(trs, account)\n trs.reverse()\n return trs\n\n\ndef get_transactions_with_splits(c, count=100, before_timestamp=None,\n before_transaction_id=None, account_id=None):\n c.execute('''\n select * from get_transactions_with_splits(\n %(count)s,\n %(before_timestamp)s,\n %(before_transaction_id)s,\n %(account_id)s\n )\n ''', {'count': count, 'before_timestamp': before_timestamp,\n 'before_transaction_id': before_transaction_id,\n 'account_id': account_id})\n trs = groupby_dict(fetchall_dict(c),\n keys=('transaction_id', 'date', 'description'),\n children_name='splits')\n for tr in trs:\n tr['id'] = tr.pop('transaction_id')\n tr['simple'] = len(tr['splits']) == 2\n tr['tags'] = uniquify(flatten(s['tags'] or [] for s in tr['splits']))\n for s in tr['splits']:\n s['id'] = s.pop('split_id')\n return trs\n\n\ndef is_of_account(s, aid):\n return s['account_id'] == aid or aid in s['account_ancestor_ids']\n\n\ndef augment_transactions_for_account(trs, account):\n if not trs: return\n aid = account['id']\n for tr in trs:\n ss = [s for s in tr['splits'] if s['account_id'] == aid]\n tss = [s for s in tr['splits'] if is_of_account(s, aid)]\n tr['amount'] = sum(s['amount'] for s in ss)\n tr['total_amount'] = sum(s['amount'] for s in tss)\n if account['currency'] is not None:\n tr['account_amount'] = sum(s['account_amount'] for s in ss)\n if tr['simple']:\n i = 0 if is_of_account(tr['splits'][1], aid) else 1\n if not is_of_account(tr['splits'][i], aid):\n s = tr['splits'][i]\n for k in ('id', 'name', 'type', 'currency'):\n tr['opposite_account_{}'.format(k)] = s['account_{}'.format(k)]\n bs = account['balance_sign']\n trs.sort(key=lambda tr: (tr['date'], tr['amount'] * -bs), reverse=True)\n set_balance(trs, account['current_balance'])\n set_balance(trs, account['total_current_balance'], 'total_balance', 'total_amount')\n if account['currency'] is not None:\n set_balance(trs, account['current_account_balance'],\n 'account_balance', 'account_amount')\n\n\ndef set_balance(trs, current_balance, balance='balance', amount='amount'):\n trs[0][balance] = current_balance\n for i in range(1, len(trs)):\n tr = trs[i - 1]\n trs[i][balance] = tr[balance] - tr[amount]\n\n\n@app.route('/api/v1.0/transactions', methods=['GET'])\ndef get_transactions():\n c = g.db.cursor()\n count = get_typed_arg('count', int, 100)\n before_timestamp = get_typed_arg('before_timestamp', dateutil.parser.parse)\n before_transaction_id = get_typed_arg('before_transaction_id', int)\n account_id = get_typed_arg('account', int)\n trs = get_transactions_with_splits(c, count=count,\n before_timestamp=datetime.now(),\n account_id=account_id)\n if account_id is not None:\n c.execute('''\n select\n *,\n current_balance + (\n select coalesce(sum(current_balance), 0)\n from accounts_view\n where %(id)s = any(ancestor_ids)\n ) as total_current_balance\n from accounts_view\n where id = %(id)s\n ''', {'id': account_id})\n account = fetchone_dict(c)\n augment_transactions_for_account(trs, account)\n trs.reverse()\n return jsonify(trs)\n\n\ndef get_typed_arg(k, t, default=None):\n v = request.args.get(k)\n if not v:\n return default\n try:\n return t(v)\n except ValueError:\n abort(404)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({'error': 'not found'}, 404)\n\n\n@app.before_request\ndef before_request():\n g.db = psycopg2.connect(app.config['DATABASE_URI'])\n g.db.cursor().execute('set schema %s', ['money'])\n\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n\ndef groupby_dict(d, keys, children_name):\n ret = []\n for row, g in itertools.groupby(d, lambda r: {k: r[k] for k in keys}):\n row[children_name] = [{k: r[k] for k in r.keys() if k not in row}\n for r in g]\n ret.append(row)\n return ret\n\n\ndef jsonify(obj, response_code=200):\n indent = 2 if app.config['DEBUG'] else None\n resp = make_response(json.dumps(obj, indent=indent, default=json_serial),\n response_code)\n resp.mimetype='application/json'\n return resp\n\n\ndef json_serial(obj):\n if isinstance(obj, datetime):\n return obj.isoformat()\n if isinstance(obj, Decimal):\n return str(obj)\n raise TypeError('{!r} is not JSON serializable'.format(obj))\n\n\ndef flatten(seq):\n return list(itertools.chain(*seq))\n\n\ndef uniquify(seq):\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--debug', action='store_true')\n parser.add_argument('--host', default='localhost')\n parser.add_argument('--port', type=int, default=5000)\n args = parser.parse_args()\n app.run(debug=args.debug, host=args.host, port=args.port)\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"538529964","text":"import platform\nimport sys\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import HttpResponseServerError\nfrom django.shortcuts import redirect, render\nfrom django.template import loader\nfrom django.template.exceptions import TemplateDoesNotExist\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import requires_csrf_token\nfrom django.views.defaults import ERROR_500_TEMPLATE_NAME, page_not_found\nfrom django.views.generic import View\nfrom packaging import version\nfrom sentry_sdk import capture_message\n\nfrom circuits.models import Circuit, Provider\nfrom dcim.models import (\n Cable, ConsolePort, Device, DeviceType, Interface, PowerPanel, PowerFeed, PowerPort, Rack, Site,\n)\nfrom extras.models import ObjectChange\nfrom extras.tables import ObjectChangeTable\nfrom ipam.models import Aggregate, IPAddress, IPRange, Prefix, VLAN, VRF\nfrom netbox.constants import SEARCH_MAX_RESULTS\nfrom netbox.forms import SearchForm\nfrom netbox.search import SEARCH_TYPES\nfrom tenancy.models import Tenant\nfrom virtualization.models import Cluster, VirtualMachine\nfrom wireless.models import WirelessLAN, WirelessLink\n\n\nclass HomeView(View):\n template_name = 'home.html'\n\n def get(self, request):\n if settings.LOGIN_REQUIRED and not request.user.is_authenticated:\n return redirect(\"login\")\n\n connected_consoleports = ConsolePort.objects.restrict(request.user, 'view').prefetch_related('_path').filter(\n _path__is_complete=True\n )\n connected_powerports = PowerPort.objects.restrict(request.user, 'view').prefetch_related('_path').filter(\n _path__is_complete=True\n )\n connected_interfaces = Interface.objects.restrict(request.user, 'view').prefetch_related('_path').filter(\n _path__is_complete=True\n )\n\n def build_stats():\n org = (\n (\"dcim.view_site\", \"Sites\", Site.objects.restrict(request.user, 'view').count),\n (\"tenancy.view_tenant\", \"Tenants\", Tenant.objects.restrict(request.user, 'view').count),\n )\n dcim = (\n (\"dcim.view_rack\", \"Racks\", Rack.objects.restrict(request.user, 'view').count),\n (\"dcim.view_devicetype\", \"Device Types\", DeviceType.objects.restrict(request.user, 'view').count),\n (\"dcim.view_device\", \"Devices\", Device.objects.restrict(request.user, 'view').count),\n )\n ipam = (\n (\"ipam.view_vrf\", \"VRFs\", VRF.objects.restrict(request.user, 'view').count),\n (\"ipam.view_aggregate\", \"Aggregates\", Aggregate.objects.restrict(request.user, 'view').count),\n (\"ipam.view_prefix\", \"Prefixes\", Prefix.objects.restrict(request.user, 'view').count),\n (\"ipam.view_iprange\", \"IP Ranges\", IPRange.objects.restrict(request.user, 'view').count),\n (\"ipam.view_ipaddress\", \"IP Addresses\", IPAddress.objects.restrict(request.user, 'view').count),\n (\"ipam.view_vlan\", \"VLANs\", VLAN.objects.restrict(request.user, 'view').count)\n\n )\n circuits = (\n (\"circuits.view_provider\", \"Providers\", Provider.objects.restrict(request.user, 'view').count),\n (\"circuits.view_circuit\", \"Circuits\", Circuit.objects.restrict(request.user, 'view').count),\n )\n virtualization = (\n (\"virtualization.view_cluster\", \"Clusters\", Cluster.objects.restrict(request.user, 'view').count),\n (\"virtualization.view_virtualmachine\", \"Virtual Machines\", VirtualMachine.objects.restrict(request.user, 'view').count),\n\n )\n connections = (\n (\"dcim.view_cable\", \"Cables\", Cable.objects.restrict(request.user, 'view').count),\n (\"dcim.view_consoleport\", \"Console\", connected_consoleports.count),\n (\"dcim.view_interface\", \"Interfaces\", connected_interfaces.count),\n (\"dcim.view_powerport\", \"Power Connections\", connected_powerports.count),\n )\n power = (\n (\"dcim.view_powerpanel\", \"Power Panels\", PowerPanel.objects.restrict(request.user, 'view').count),\n (\"dcim.view_powerfeed\", \"Power Feeds\", PowerFeed.objects.restrict(request.user, 'view').count),\n )\n wireless = (\n (\"wireless.view_wirelesslan\", \"Wireless LANs\", WirelessLAN.objects.restrict(request.user, 'view').count),\n (\"wireless.view_wirelesslink\", \"Wireless Links\", WirelessLink.objects.restrict(request.user, 'view').count),\n )\n sections = (\n (\"Organization\", org, \"domain\"),\n (\"IPAM\", ipam, \"counter\"),\n (\"Virtualization\", virtualization, \"monitor\"),\n (\"Inventory\", dcim, \"server\"),\n (\"Circuits\", circuits, \"transit-connection-variant\"),\n (\"Connections\", connections, \"cable-data\"),\n (\"Power\", power, \"flash\"),\n (\"Wireless\", wireless, \"wifi\"),\n )\n\n stats = []\n for section_label, section_items, icon_class in sections:\n items = []\n for perm, item_label, get_count in section_items:\n app, scope = perm.split(\".\")\n url = \":\".join((app, scope.replace(\"view_\", \"\") + \"_list\"))\n item = {\n \"label\": item_label,\n \"count\": None,\n \"url\": url,\n \"disabled\": True,\n \"icon\": icon_class,\n }\n if request.user.has_perm(perm):\n item[\"count\"] = get_count()\n item[\"disabled\"] = False\n items.append(item)\n stats.append((section_label, items, icon_class))\n\n return stats\n\n # Compile changelog table\n changelog = ObjectChange.objects.restrict(request.user, 'view').prefetch_related(\n 'user', 'changed_object_type'\n )[:10]\n changelog_table = ObjectChangeTable(changelog, user=request.user)\n\n # Check whether a new release is available. (Only for staff/superusers.)\n new_release = None\n if request.user.is_staff or request.user.is_superuser:\n latest_release = cache.get('latest_release')\n if latest_release:\n release_version, release_url = latest_release\n if release_version > version.parse(settings.VERSION):\n new_release = {\n 'version': str(release_version),\n 'url': release_url,\n }\n\n return render(request, self.template_name, {\n 'search_form': SearchForm(),\n 'stats': build_stats(),\n 'changelog_table': changelog_table,\n 'new_release': new_release,\n })\n\n\nclass SearchView(View):\n\n def get(self, request):\n form = SearchForm(request.GET)\n results = []\n\n if form.is_valid():\n\n # If an object type has been specified, redirect to the dedicated view for it\n if form.cleaned_data['obj_type']:\n object_type = form.cleaned_data['obj_type']\n url = reverse(SEARCH_TYPES[object_type]['url'])\n return redirect(f\"{url}?q={form.cleaned_data['q']}\")\n\n for obj_type in SEARCH_TYPES.keys():\n\n queryset = SEARCH_TYPES[obj_type]['queryset'].restrict(request.user, 'view')\n filterset = SEARCH_TYPES[obj_type]['filterset']\n table = SEARCH_TYPES[obj_type]['table']\n url = SEARCH_TYPES[obj_type]['url']\n\n # Construct the results table for this object type\n filtered_queryset = filterset({'q': form.cleaned_data['q']}, queryset=queryset).qs\n table = table(filtered_queryset, orderable=False)\n table.paginate(per_page=SEARCH_MAX_RESULTS)\n\n if table.page:\n results.append({\n 'name': queryset.model._meta.verbose_name_plural,\n 'table': table,\n 'url': f\"{reverse(url)}?q={form.cleaned_data.get('q')}\"\n })\n\n return render(request, 'search.html', {\n 'form': form,\n 'results': results,\n })\n\n\nclass StaticMediaFailureView(View):\n \"\"\"\n Display a user-friendly error message with troubleshooting tips when a static media file fails to load.\n \"\"\"\n def get(self, request):\n return render(request, 'media_failure.html', {\n 'filename': request.GET.get('filename')\n })\n\n\ndef handler_404(request, exception):\n \"\"\"\n Wrap Django's default 404 handler to enable Sentry reporting.\n \"\"\"\n capture_message(\"Page not found\", level=\"error\")\n\n return page_not_found(request, exception)\n\n\n@requires_csrf_token\ndef server_error(request, template_name=ERROR_500_TEMPLATE_NAME):\n \"\"\"\n Custom 500 handler to provide additional context when rendering 500.html.\n \"\"\"\n try:\n template = loader.get_template(template_name)\n except TemplateDoesNotExist:\n return HttpResponseServerError('

Server Error (500)

', content_type='text/html')\n type_, error, traceback = sys.exc_info()\n\n return HttpResponseServerError(template.render({\n 'error': error,\n 'exception': str(type_),\n 'netbox_version': settings.VERSION,\n 'python_version': platform.python_version(),\n }))\n","sub_path":"netbox/netbox/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"180629143","text":"\"\"\"\n\n@author: bdbaus\n\"\"\"\n\ndef prime_check(n):\n if(n==0 or n==1):\n return False\n #added this, would not work for 2 otherwise\n elif(n==2):\n return True\n else:\n for ii in range(3,n):\n if(n%ii==0 or n%2 == 0):\n return False\n return True\n \n \ndef find_prime(m):\n\n primelist=[]\n firstp=2\n #will stop at the Mth number of the list\n while(len(primelist)' % obj.url.url)\n else:\n return 'No Image Found'\n\n recomend_img.allow_tags = True\n recomend_img.short_description = 'Фотография рекомендации'\n\n list_display = ('title', 'recomend_img', 'year')\n","sub_path":"cleanok/recomend/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"208910234","text":"''' SpreadsheettoJSON.py\n\nThis script is designed to produce a JSON file for use with the WAB Local Layer Widget\nusing values from an Excel table.\nUtilizes openpyxl, available here: https://openpyxl.readthedocs.org/en/latest/\nTested using Python 3.4, might be backward compatible?\nTorrin Hultgren, October 2015\n\n********** Need to update popup configuration, community layers are not HUC 12s **********\n'''\nimport sys, json, csv, openpyxl\n\n# This is the spreadsheet that contains all the content\nrootpath = r\"C:\\inetpub\\wwwroot\\EnviroAtlas\\scripts\\\\\"\ninputSpreadsheet = rootpath + r\"EAWAB4JSON.xlsx\"\n# Just in case there are rows to ignore at the top - header is row 1\nstartingRow = 2\n# This should be a csv table that maps spreadsheet column headers to json elements\n# no great reason it needs to be in a standalone file rather than embedded in this\n# script as a dictionary.\nmapTablePath = rootpath + r\"jsonfieldmap.csv\"\n# Output json file\noutputFileName = rootpath + r\"config.json\"\nerrorLogFile = rootpath + r\"errors.log\"\n\n# Empty rows cause python problems, remove them\ndef removeEmptyRows(rows):\n rowsToKeep = []\n for row in rows:\n rowEmpty = True\n for cell in row:\n if cell.value is not None:\n # If any non-null value in the row, flag this as a row to keep\n rowEmpty = False\n break\n if rowEmpty == False:\n rowsToKeep.append(str(cell.row))\n return rowsToKeep\n\ndef main(_argv):\n # Open the Excel spreadsheet\n inputWorkbook = openpyxl.load_workbook(filename = inputSpreadsheet,data_only=True)\n # Get the worksheet titled \"EA_main\"\n inputWorksheet = inputWorkbook[\"EA_main\"]\n # Compile a dictionary of Spreadsheet field headers\n mapTable = open(mapTablePath)\n mapTableReader = csv.DictReader(mapTable,delimiter=',')\n mapDictionary = dict([(row['jsonElem'], row['Column']) for row in mapTableReader])\n\n # Create a dictionary of field titles to column letters\n fieldsToColumns = dict([(cell.value, cell.column) for cell in inputWorksheet[1]])\n\n # Map the dictionary of csv titles to columns letters via the intermediate dictionary\n key = dict([(key, fieldsToColumns[mapDictionary[key]]) for key in mapDictionary.keys()])\n\n # Get row index numbers for non-empty rows:\n rowsToKeep = removeEmptyRows(inputWorksheet[startingRow:len(inputWorksheet[\"A\"])])\n\n # Nothing is being piped to the error file right now\n validationErrors = open(errorLogFile,'w+')\n\n # Root structure of the JSON file\n fullJSON = {\"layers\": {\"layer\": []}}\n\n for rowID in rowsToKeep:\n name = inputWorksheet[key[\"name\"]+rowID].value\n layerJSON = {\"opacity\": 0.6,\n \"visible\": False}\n if (inputWorksheet[key[\"serviceType\"]+rowID].value == \"feature\"):\n layerJSON[\"type\"] =\"FEATURE\"\n layerJSON[\"autorefresh\"] = 0\n layerJSON[\"mode\"] = \"ondemand\"\n else:\n if (inputWorksheet[key[\"serviceType\"]+rowID].value == \"dynamic\" or inputWorksheet[key[\"serviceType\"]+rowID].value == \"image\"):\n layerJSON[\"type\"] = \"DYNAMIC\"\n if (inputWorksheet[key[\"serviceType\"]+rowID].value == \"tile\"):\n layerJSON[\"type\"] = \"TILED\"\n ### code for reading in saved json files with layer/popup definitions.\n #with open(rootpath + inputWorksheet.cell(key[\"popupDefinition\"]+rowID).value) as json_data:\n # layerJSON[\"layers\"] = json.load(json_data)\n ### the excel spreadsheet should include a relative path to a json file containing the layer/popup definition, which should be a JSON array of layer objects.\n layerJSON[\"name\"] = name\n layerJSON[\"url\"] = inputWorksheet[key[\"url\"]+rowID].value\n # Convert the plain text popupJSON into Python Dictionary for loading\n popupTxt = inputWorksheet[key[\"popupDefinition\"]+rowID].value\n if popupTxt != None:\n try:\n popupDefinition = json.loads(popupTxt)\n layerJSON.update(popupDefinition)\n except:\n print(\"This layer had invalid JSON for the popup: \" + name)\n print(popupTxt)\n stringList = [\"eaID\",\"eaScale\",\"eaDescription\",\"eaMetric\",\"eaDfsLink\",\"eaLyrNum\",\"eaMetadata\",\"eaBC\",\"eaCA\",\"eaCPW\",\"eaCS\",\"eaFFM\",\"eaNHM\",\"eaRCA\",\"eaPBS\",\"eaTopic\",\"tileLink\",\"tileURL\",\"numDecimal\",\"IsSubLayer\",\"SubLayerNames\",\"SubLayerIds\",\"sourceType\"]\n for elem in stringList:\n cell = inputWorksheet[key[elem]+rowID]\n if cell.value != None:\n cellValue = cell.value\n if cellValue == 'x':\n cellValue = True\n layerJSON[elem] = cellValue\n arrayList = [(\"eaTags\",\",\"),(\"eaBCSDD\",\";\"),(\"SubLayerNames\", \",\"), (\"SubLayerIds\", \";\")]\n for elem,separator in arrayList:\n if inputWorksheet[key[elem]+rowID].value:\n fullString = inputWorksheet[key[elem]+rowID].value\n cleanString = fullString.strip(separator+' ')\n fullArray = cleanString.split(separator)\n cleanArray = [elemVal.strip() for elemVal in fullArray]\n layerJSON[elem] = cleanArray\n fullJSON[\"layers\"][\"layer\"].append(layerJSON)\n\n validationErrors.close()\n outputFile = open(outputFileName,'w+')\n json.dump(fullJSON,outputFile,indent=4)\n outputFile.close()\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"scripts/SpreadsheettoJSON.py","file_name":"SpreadsheettoJSON.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"127423657","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n# author: wangxiaogang02@baidu.com\n\nimport io\nimport sys\nimport time\nimport re\nimport os\nimport _winreg\nimport datetime\n\ndef getIpFromRegion(region):\n if (region == '') or (region == 'shanghai') or (\"上海\" in region):\n print(\"region is shanghai\")\n return '0'\n else:\n try:\n TIME_FORMAT = '%Y%m%d_%H'\n currentHour = datetime.datetime.now()\n lastHour = currentHour - datetime.timedelta(hours = 1)\n fileAfterPath = \"proxyList/all/proxyListAfter.\" \\\n + currentHour.strftime(TIME_FORMAT)\n if not os.path.exists(fileAfterPath):\n print(\"Use last hour proxy list\")\n fileAfterPath = \"proxyList/all/proxyListAfter.\" \\\n + lastHour.strftime(TIME_FORMAT)\n \n readFile = open(fileAfterPath,\"r\")\n \n for eachLine in readFile:\n lineArray = eachLine.split('\\t')\n if region in eachLine:\n readFile.close()\n print(lineArray[0])\n return lineArray[0]\n return 'IpNotFonud'\n except Exception as e:\n print(\"ERROR: \" + str(e.args))\n finally:\n readFile.close()\n\ndef enableProxy(proxy):\n xpath = \"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\"\n try:\n key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, xpath, 0, _winreg.KEY_WRITE)\n _winreg.SetValueEx(key, \"ProxyEnable\", 0, _winreg.REG_DWORD, 1)\n _winreg.SetValueEx(key, \"ProxyServer\", 0, _winreg.REG_SZ, proxy)\n except Exception as e:\n print(\"ERROR: \" + str(e.args))\n finally:\n None\n\ndef disableProxy():\n proxy = \"\"\n xpath = \"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\"\n try:\n key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, xpath, 0, _winreg.KEY_WRITE)\n _winreg.SetValueEx(key, \"ProxyEnable\", 0, _winreg.REG_DWORD, 0)\n _winreg.SetValueEx(key, \"ProxyServer\", 0, _winreg.REG_SZ, proxy)\n except Exception as e:\n print(\"ERROR: \" + str(e.args))\n finally:\n None\n\n# 刷新使得注册表的改变生效,就不需要重启IE了\ndef refresh():\n import ctypes\n\n INTERNET_OPTION_REFRESH = 37\n INTERNET_OPTION_SETTINGS_CHANGED = 39\n\n internet_set_option = ctypes.windll.Wininet.InternetSetOptionW\n\n internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)\n internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)\n\ndef setProxy(proxy):\n if proxy == \"0\":\n try:\n disableProxy()\n refresh()\n print(\"disableProxy\")\n except Exception as e:\n print(\"ERROR: \" + str(e.args))\n finally:\n pass\n else:\n try:\n print(\"set property: \" + proxy)\n disableProxy()\n enableProxy(proxy)\n refresh()\n except Exception as e:\n print(\"ERROR: \" + str(e.args))\n finally:\n pass\n\n\ndef main():\n proxy = sys.argv[1]\n setProxy(proxy)\n\nif __name__ == '__main__':\n main()","sub_path":"flashshot/ipProxy.py","file_name":"ipProxy.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"201184674","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Useful functions (needs refactoring)\n\n# In[28]:\n\n\nimport os, sys\nroot_dir, _ = os.path.split(os.getcwd())\nscript_dir = os.path.join(root_dir, 'scripts')\nsys.path.append(script_dir)\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n\n# In[31]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport pprint\n\n\n# In[ ]:\n\n\nfrom hparams import hparams\n\n\n# ## Dataset loading\n\n# In[ ]:\n\n\nsound_feature_description = {\n \"wav\": tf.io.FixedLenFeature([], tf.string)\n}\n\ndef _parse_sound_function(example_proto):\n x = tf.io.parse_single_example(example_proto, sound_feature_description)\n x['wav'] = tf.io.parse_tensor(x['wav'], out_type=hparams['ftype']) \n return x\n\nlong_sound_feature_description = {\n \"wav\": tf.io.FixedLenFeature([], tf.string),\n \"path\": tf.io.FixedLenFeature([], tf.string),\n \"number_of_slices\": tf.io.FixedLenFeature([], tf.string)\n}\n\ndef _parse_long_sound_function(example_proto):\n x = tf.io.parse_single_example(example_proto, long_sound_feature_description)\n x['wav'] = tf.io.parse_tensor(x['wav'], out_type=hparams['ftype'])\n x['path'] = tf.io.parse_tensor(x['path'], out_type=tf.string)\n x['number_of_slices'] = tf.io.parse_tensor(x['number_of_slices'], out_type=tf.int32) \n return x\n\n\n# In[ ]:\n\n\ndef load_single_file_tfrecords(record_file):\n raw_sound_dataset = tf.data.TFRecordDataset(record_file)\n parsed_sound_dataset = raw_sound_dataset.map(_parse_sound_function)\n return parsed_sound_dataset\n\ndef load_long_audio_tfrecords(record_file):\n raw_sound_dataset = tf.data.TFRecordDataset(record_file)\n parsed_sound_dataset = raw_sound_dataset.map(_parse_long_sound_function)\n return parsed_sound_dataset\n\ndef load_training_files_tfrecords(record_pattern):\n record_files = tf.data.TFRecordDataset.list_files(\n file_pattern=record_pattern)\n raw_sound_dataset = record_files.interleave(\n tf.data.TFRecordDataset,\n cycle_length=1,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n parsed_sound_dataset = raw_sound_dataset.map(\n _parse_sound_function,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n \n training_dataset = parsed_sound_dataset.shuffle(\n buffer_size=hparams['buffer_size']).batch(\n hparams['train_batch_size'],\n drop_remainder=True).prefetch(\n buffer_size=tf.data.experimental.AUTOTUNE)\n \n return training_dataset\n\n\n# ## Optimizer compatibility with tf.float16 (Not working yet)\n\n# In[ ]:\n\n\ndef get_optimizer(hparams):\n \"\"\"\n Return optimizer instance based on hparams\n \n Wrap the optimizer to avoid underflow if ftype=tf.float16\n \"\"\"\n if hparams['optimizer'] == \"Adam\":\n if hparams['learning_rate_decay']:\n lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n hparams['learning_rate'],\n decay_steps=200000,\n decay_rate=0.99,\n staircase=True)\n optimizer = tf.keras.optimizers.Adam(\n learning_rate=lr_schedule)\n else:\n optimizer = tf.keras.optimizers.Adam(\n learning_rate=hparams[\"learning_rate\"])\n\n elif hparams['optimizer'] == \"Adadelta\":\n assert(hparams[\"learning_rate\"] == 1.0), \"Set learning_rate to 1.0\"\n optimizer = tf.keras.optimizers.Adadelta(\n learning_rate=hparams['learning_rate'])\n else:\n raise ValueError(\"Supported Optimizer is either Adam or Adadelta\")\n \n if hparams[\"mixed_precision\"]:\n return tf.train.experimental.enable_mixed_precision_graph_rewrite(\n optimizer, \"dynamic\")\n else:\n return optimizer\n\n\n# ## Discrete Logistic Mixture Helpers\n\n# In[ ]:\n\n\ndef log_sum_exp(x):\n \"\"\" numerically stable log_sum_exp implementation that prevents overflow \"\"\"\n axis = len(x.shape)-1\n m = tf.reduce_max(x, axis)\n m2 = tf.reduce_max(x, axis, keepdims=True)\n return m + tf.math.log(tf.reduce_sum(tf.math.exp(x-m2), axis))\n\ndef log_prob_from_logits(x):\n \"\"\" numerically stable log_softmax implementation that prevents overflow \"\"\"\n axis = len(x.shape)-1\n m = tf.reduce_max(x, axis, keepdims=True)\n return x - m - tf.math.log(tf.reduce_sum(tf.math.exp(x-m), axis, keepdims=True))\n\n\n# ## Straight-through estimator\n\n# In[ ]:\n\n\n@tf.custom_gradient\ndef round_ste(x):\n def grad(dy):\n return dy\n return tf.round(x), grad\n\n\n# ## Integer values\n\n# In[ ]:\n\n\n\n\n","sub_path":"scripts/training_utils.py","file_name":"training_utils.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"482330539","text":"from n41 import load_nekocabocha_chunk\nfrom n42 import chunk2str\nfrom n43 import chunk_include_pos\n\ndef extract_dependency_path():\n for chunks in load_nekocabocha_chunk():\n for chunk in chunks:\n if not chunk_include_pos(chunk, \"名詞\"):\n continue\n if chunk.dst == -1:\n continue\n path_to_root = chunk2str(chunk)\n while chunk.dst != -1:\n chunk = chunks[chunk.dst]\n path_to_root += f\" -> {chunk2str(chunk)}\"\n print(path_to_root)\n\nif __name__ == \"__main__\":\n extract_dependency_path()\n","sub_path":"c5/n49.py","file_name":"n49.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"183895750","text":"from selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport random\r\n\r\nhotel_ff = pd.DataFrame(pd.read_csv(\"Frankfurt hotel links.csv\"))\r\nlinks = hotel_ff.hotel_link\r\nnumbers= random.sample(range(1,len(hotel_ff.hotel_link)),80)\r\nnumbers.sort()\r\nk=0\r\n\r\nd = {'hotel_name': [],'name': [], 'overall_rating': [],'overall_review': [],'location_and_surrounding_review': [],'location_and_surrounding_rating': [],\r\n 'room_review': [],'room_rating': [],'service_review': [], 'service_rating': [], 'gastronomy_review': [],'gastronomy_rating': [],\r\n 'sports_and_entertainment_review': [],'sports_and_entertainment_rating': [],'hotel_review': [],\r\n 'hotel_rating': [],'traveled_as':[],'children':[],'duration':[],'reason_for_travel':[],'age_group':[],'reviews_written':[]}\r\n\r\nreview_df = pd.DataFrame(data=d)\r\n\r\n\r\nhotel = len(hotel_ff.name)\r\n\r\n # i refers to total no. of hotels\r\ni=1\r\nwhile i<= len(numbers):\r\n scrapelink = links[numbers[i]]\r\n wd = webdriver.Firefox()\r\n wd.get(scrapelink)\r\n \r\n # Wait for the dynamically loaded elements to show up\r\n WebDriverWait(wd, 10).until(\r\n EC.visibility_of_element_located((By.CLASS_NAME, \"navigation-bar-item-content\")))\r\n\r\n # And grab the page HTML source\r\n html_page = wd.page_source\r\n wd.quit()\r\n\r\n soup = BeautifulSoup(html_page,\"html.parser\")\r\n \r\n for max_page in soup.find_all('a', {'class': 'navigation-bar-item-content'}):\r\n reviews_link = max_page['href']\r\n \r\n if reviews_link.find(\"bewertungen\"):\r\n \r\n reviews_link = \"https://www.holidaycheck.de\" + reviews_link\r\n \r\n break\r\n \r\n \r\n #print(reviews_link)\r\n \r\n \r\n #grab the HTML page source for reveiws page of each hotel\r\n wd = webdriver.Firefox()\r\n wd.get(reviews_link)\r\n \r\n WebDriverWait(wd,10).until(\r\n EC.visibility_of_element_located((By.CLASS_NAME,'text-and-link-container')))\r\n \r\n html_page= wd.page_source\r\n wd.quit()\r\n \r\n soup = BeautifulSoup(html_page,\"html.parser\")\r\n \r\n #get total no. of reviews\r\n \r\n for h2text in soup.find_all('h2',{'class':'hotelReview-list-headline'}):\r\n numbers_rev = h2text.text.split()\r\n number_reviews=int(numbers_rev[0])\r\n #print(number_reviews) --------- Prints the total no. of reviews\r\n \r\n for review_page in soup.find_all('div',{'class':'text-and-link-container row'}):\r\n link_get = review_page.find('a')\r\n reviews_individual_link = \"https://www.holidaycheck.de\"+link_get['href']\r\n #print(reviews_individual_link) -------- Prints the link to individual reviews \r\n break\r\n \r\n j=0 # j keeps a count of total reviews to be scrapped for a particular hotel\r\n \r\n while j<=number_reviews:\r\n \r\n wd = webdriver.Firefox()\r\n wd.get(reviews_individual_link)\r\n\r\n\r\n\r\n\r\n content = wd.find_element_by_class_name('hotelReviewHeader-firstName')\r\n review_df.ix[k,'hotel_name'] = hotel_ff['name'].iloc[numbers[i]]\r\n review_df.ix[k,'name'] = content.text\r\n \r\n \r\n\r\n average_text_rating = wd.find_element_by_class_name('average-text-rating')\r\n average_rating_overall = average_text_rating.text.split('/')\r\n print(average_rating_overall[0])\r\n \r\n review_df.ix[k,'overall_rating'] = float(average_rating_overall[0].replace(',','.'))\r\n \r\n\r\n general_comment = wd.find_element_by_class_name('general-content')\r\n review_df.ix[k,'overall_review'] = general_comment.text\r\n \r\n\r\n group_label_list = []\r\n average_rating_element = wd.find_elements_by_class_name('aspect-group-label')\r\n for y in average_rating_element:\r\n group_label_list.append(y.text)\r\n print(group_label_list)\r\n \r\n individual_rating_list = []\r\n average_rating = wd.find_elements_by_class_name('average-rating')\r\n for x in average_rating:\r\n individual_rating_list.append(float(x.text.replace(',','.')))\r\n print(individual_rating_list)\r\n \r\n individual_review_list = []\r\n text_reviews = wd.find_elements_by_class_name('text-reviews')\r\n for m in text_reviews:\r\n individual_review_list.append(m.text)\r\n print(individual_review_list)\r\n \r\n if len(individual_review_list) != 0:\r\n for x,y,z in zip(group_label_list,individual_review_list,individual_rating_list):\r\n if x == \"Lage & Umgebung\":\r\n review_df.ix[k,'location_and_surrounding_review'] = y\r\n review_df.ix[k,'location_and_surrounding_rating'] = z\r\n elif x == \"Zimmer\":\r\n review_df.ix[k,'room_review'] = y\r\n review_df.ix[k,'room_rating'] = z\r\n elif x == \"Service\":\r\n review_df.ix[k,'service_review'] = y\r\n review_df.ix[k,'service_rating'] = z\r\n elif x == \"Gastronomie\":\r\n review_df.ix[k,'gastronomy_review'] = y\r\n review_df.ix[k,'gastronomy_rating'] = z\r\n elif x == \"Sport & Unterhaltung\":\r\n review_df.ix[k,'sports_and_entertainment_review'] = y\r\n review_df.ix[k,'sports_and_entertainment_rating'] = z\r\n else:\r\n review_df.ix[k,'hotel_review'] = y\r\n review_df.ix[k,'hotel_rating'] = z\r\n else:\r\n for x,z in zip(group_label_list,individual_rating_list):\r\n if x == \"Lage & Umgebung\":\r\n \r\n review_df.ix[k,'location_and_surrounding_rating'] = z\r\n elif x == \"Zimmer\":\r\n \r\n review_df.ix[k,'room_rating'] = z\r\n elif x == \"Service\":\r\n \r\n review_df.ix[k,'service_rating'] = z\r\n elif x == \"Gastronomie\":\r\n \r\n review_df.ix[k,'gastronomy_rating'] = z\r\n elif x == \"Sport & Unterhaltung\":\r\n \r\n review_df.ix[k,'sports_and_entertainment_rating'] = z\r\n else:\r\n \r\n review_df.ix[k,'hotel_rating'] = z\r\n \r\n #collecting information about trip and reviewer\r\n info_about_trip = []\r\n info_about_reviewer = []\r\n information = []\r\n \r\n additional_info = wd.find_elements_by_tag_name('tr')\r\n for d in additional_info:\r\n information.append(d.text)\r\n info_about_trip = information[1:information.index(\"Infos zum Bewerter\")]\r\n info_about_reviewer = information[information.index(\"Infos zum Bewerter\")+1:]\r\n print(info_about_trip)\r\n print(info_about_reviewer)\r\n \r\n \r\n \r\n \r\n for a in info_about_trip:\r\n a_new = a.split(': ')\r\n if a_new[0] == \"Verreist als\":\r\n review_df.ix[k,'traveled_as'] = a_new[1]\r\n elif a_new[0] == \"Kinder\":\r\n review_df.ix[k,'children'] = a_new[1]\r\n elif a_new[0] == \"Dauer\":\r\n review_df.ix[k,'duration'] = a_new[1]\r\n else:\r\n review_df.ix[k,\"reason_for_travel\"] = a_new[1]\r\n \r\n for b in info_about_reviewer:\r\n b_new = b.split(': ')\r\n if b_new[0] == \"Alter\":\r\n review_df.ix[k,'age_group'] = b_new[1]\r\n elif b_new[0] == \"Bewertungen\":\r\n review_df.ix[k,'reviews_written'] = b_new[1]\r\n \r\n \r\n \r\n review_df.to_csv('information.csv')\r\n if j != number_reviews-1:\r\n checklist = wd.find_elements_by_class_name(\"next\")\r\n if len(checklist) !=0:\r\n WebDriverWait(wd,10).until(\r\n EC.visibility_of_element_located((By.CLASS_NAME,'next')))\r\n\r\n html_page= wd.page_source\r\n wd.quit()\r\n soup = BeautifulSoup(html_page,\"html.parser\")\r\n for next_page in soup.find_all('div',{'class':'next'}):\r\n link_get = next_page.find('a')\r\n\r\n next_page_link = \"https://www.holidaycheck.de\"+link_get['href']\r\n print(next_page_link)\r\n break\r\n reviews_individual_link = next_page_link\r\n else:\r\n wd.quit()\r\n else:\r\n wd.quit()\r\n \r\n k=k+1\r\n j=j+1\r\n i=i+1\r\n\r\n \r\n #Open the first review html page on new browser\r\n \r\n\t\r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"hotelreviews.py","file_name":"hotelreviews.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"473977754","text":"\"\"\"\nA script for scraping job posting information.\n\"\"\"\n\nimport os\nimport csv\nimport time\nimport argparse\nimport urllib.request\nimport urllib.error\nfrom bs4 import BeautifulSoup\n\nPREFIX = 'https://www.indeed.com'\nNEXT = '&start='\n\n\ndef parse_args():\n \"\"\"\n Parses input arguments.\n\n :return: An argparse object.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"A script to scrape job postings from Indeed.com.\")\n parser.add_argument('--job_title', default=\"software engineer\", nargs=\"?\",\n const='1', help=\"The job title to search for.\")\n parser.add_argument('--limit', default=\"20\", nargs=\"?\", const='1',\n help=\"The number of pages to scan.\")\n parser.add_argument('--verbose', default=\"0\", nargs=\"?\",\n const='1', help=\"Controls print statements.\")\n arguments = parser.parse_args()\n return arguments\n\n\ndef text_hunter(txt):\n \"\"\"\n Parses through a website's source code for text elements.\n Toggles recording status based on the most recent tag.\n\n :param txt: A string representing a website's source code.\n :return writeup: A string containing the site's text data.\n \"\"\"\n record = False\n writeup = []\n txt = txt.split('\\n')\n for line in txt:\n if '

' in line:\n record = True\n\n elif '

' in line:\n record = False\n\n elif '
  • ' in line:\n record = True\n\n elif '
  • ' in line:\n record = False\n\n # Cuts out non-text elements\n elif ('<' in line and '>' in line) or '\\r' in line:\n pass\n\n elif record:\n writeup.append(line)\n\n return ('\\n').join(writeup)\n\n\ndef link_translator(job_links, prefix, verbose=True):\n \"\"\"\n Sifts through a list of links, parsing the corresponding websites\n for textual data.\n\n :param job_links: A list of strings, containing url's for websites.\n :param prefix: A string representing the website domain.\n :param verbose: Prints errors when true.\n :return job_writeups: A list of strings, containing text data from the websites.\n \"\"\"\n job_writeups = []\n for link in job_links:\n try:\n p = urllib.request.urlopen(prefix + link)\n soup = BeautifulSoup(p, \"lxml\")\n txt = soup.prettify()\n output = text_hunter(txt)\n if len(output) > 0:\n job_writeups.append(output)\n except Exception as e:\n if verbose:\n print('>>>' + str(e) + ' ||| ' + link)\n return job_writeups\n\n\ndef get_job_links(target):\n \"\"\"\n Scans through the target website for links to job postings.\n\n :param target: Website URL.\n :return: A list of url suffixes.\n \"\"\"\n page = urllib.request.urlopen(target)\n soup = BeautifulSoup(page, \"lxml\")\n\n all_links = soup.find_all(\"a\")\n links = [link.get('href') for link in all_links]\n job_links = []\n # Pick a few common headers and roll with it\n for link in links:\n if link and ('pagead' in link or 'rc/' in link or 'company/' in link):\n job_links.append(link)\n return job_links\n\n\ndef run(job_title, limit=30, verbose=False, prefixes=''):\n prefixes = prefixes.split()\n prefixes.append('')\n for pref in prefixes:\n full_job_title = f'{pref} {job_title}'.strip('.').strip()\n job = full_job_title.replace(' ', '+')\n output_filename = full_job_title.lower().replace(' ', '_') + '.csv'\n query = '/jobs?q=' + job\n pages = int(limit)\n\n if verbose:\n print(full_job_title)\n print('Scraping data...')\n output = []\n for i in range(0, pages * 10, 10):\n print('On section ' + str(i) + ' of ' + str(pages * 10) + '...')\n joblinks = get_job_links(PREFIX + query + NEXT + str(i))\n output += link_translator(joblinks, PREFIX)\n # Try not to accidentally DOS the target...\n time.sleep(1)\n\n if verbose:\n print('Converting to csv...')\n output_path = os.path.join(os.getcwd(),\n 'ScrapedData/' + output_filename)\n with open(output_path, 'w') as csvfile:\n writ = csv.writer(csvfile, delimiter=\",\")\n for row in output:\n writ.writerow([row])\n\n if verbose:\n print('Done!')\n\n\nif __name__ == '__main__':\n args = parse_args()\n run(args.job_title, args.limit, args.verbose, args.prefixes)\n\n","sub_path":"job_scraper.py","file_name":"job_scraper.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"82604767","text":"#!/usr/bin/env python3\n# LULZ Gé tou trièèè léé def com' ci on lencèè le gramepro de labitchetoitmémetulesé\n#!/usr/bin/env python3\n# PROJET FINAL \n\nfrom random import *\n\n### Fonction Manuel ###\ndef Manuel() :\n print(\"Bonjour, voici le manuel du Tic-Tac-Toe aussi connu sous le nom de 'Morpion'\")\n print(\"CETTE VERSION NE FONCTIONNE QU'EN 1 CONTRE 1\")\n print(\"Principe \\n Du \\n Jeu \")\n print(\"Vous allez vous affronter sur un plateau de 3x3 cases.\")\n print(\"A chaque tour vous devez remplir une case de la grille, avec le symbole qui vous a été attribué en début de partie.\")\n print(\"La partie est gagnée quand des joueurs a réussi à aligner 3 symboles de façon horizontale, verticale ou en diagonale.\")\n print(\"Bon Jeux =)\")\n return()\n\ndef cls():\n print(\" \\n \" * 100)\n return()\ndef accord():\n A=input (\"Quand vous voulez commencer, appuyez sur la touche Y : \")\n return(A)\n\n### Choix un joueur ###\n\ndef changementJoueur(gagnee): #\n x = randint(0,1)\n while gagnee==False:\n if x%2 == 0:\n gagnee=player1(T)\n if x%2 == 1:\n gagnee=player2(T)\n x = x+1\n return(gagnee)\n\n##### Placement du signe ####\n\ndef player1(T): #Pour placer le rond #(t0,t1,t2,t3,gagnee)\n gagnee=False\n coup_joue=False\n t1 = T[1]\n t2 = T[2]\n t3 = T[3]\n while coup_joue == False:\n coup = int(input(\"Svp Joueur n°1, quel est votre coup ? \"))\n \n if coup == 1 and t3[0] == \" \":\n t3[0] = \"O\"\n coup_joue = True\n elif coup == 2 and t3[1] == \" \":\n t3[1] = \"O\"\n coup_joue = True\n elif coup == 3 and t3[2] == \" \":\n t3[2] = \"O\"\n coup_joue = True\n elif coup == 4 and t2[0] == \" \":\n t2[0] = \"O\"\n coup_joue = True\n elif coup == 5 and t2[1] == \" \":\n t2[1] = \"O\"\n coup_joue = True\n elif coup == 6 and t2[2] == \" \":\n t2[2] = \"O\"\n coup_joue = True\n elif coup == 7 and t1[0] == \" \":\n t1[0] = \"O\"\n coup_joue = True\n elif coup == 8 and t1[1] == \" \":\n t1[1] = \"O\"\n coup_joue = True\n elif coup == 9 and t1[2] == \" \":\n t1[2] = \"O\"\n coup_joue = True\n else :\n print (\"Pourquoi placer un pion sur une place déjà prise ? Recommencez s'il vous plaît. \")\n print (\" \",t0) # Afficher tableau\n print (\"1\",t1)\n print (\"2\",t2)\n print (\"3\",t3)\n gagnee = coupDeGagnant(T,gagnee)\n return(gagnee)\n\ndef player2(T): #Pour placer la Croix\n gagnee = False\n coup_joue=False\n t1 = T[1]\n t2 = T[2]\n t3 = T[3]\n while coup_joue == False:\n coup = int(input(\"Svp Joueur n°2, quel est votre coup ? \"))\n if coup == 1 and t3[0] == \" \":\n t3[0] = \"X\"\n coup_joue = True\n elif coup == 2 and t3[1] == \" \":\n t3[1] = \"X\"\n coup_joue = True\n elif coup == 3 and t3[2] == \" \":\n t3[2] = \"X\"\n coup_joue = True\n elif coup == 4 and t2[0] == \" \":\n t2[0] = \"X\"\n coup_joue = True\n elif coup == 5 and t2[1] == \" \":\n t2[1] = \"X\"\n coup_joue = True\n elif coup == 6 and t2[2] == \" \":\n t2[2] = \"X\"\n coup_joue = True\n elif coup == 7 and t1[0] == \" \":\n t1[0] = \"X\"\n coup_joue = True\n elif coup == 8 and t1[1] == \" \":\n t1[1] = \"X\"\n coup_joue = True\n elif coup == 9 and t1[2] == \" \":\n t1[2] = \"X\"\n coup_joue = True\n else :\n print (\"Pourquoi placer un pion sur une place déjà prise ? Recommencez s'il vous plaît. \")\n print (\" \",t0) # Afficher tableau\n print (\"1\",t1)\n print (\"2\",t2)\n print (\"3\",t3)\n gagnee = coupDeGagnant(T,gagnee)\n return(gagnee)\n\n### Verification du coup joué ###\n\ndef coupDeGagnant(T,gagnee): # Détecte si les conditions pour gagner sont réunies\n t1 = T[1]\n t2 = T[2]\n t3 = T[3]\n if t1[0]==t1[1]==t1[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t2[0]==t2[1]==t2[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t3[0]==t3[1]==t3[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t1[0]==t2[0]==t3[0]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t1[1]==t2[1]==t3[1]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t1[2]==t2[2]==t3[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t1[0]==t2[1]==t3[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n elif t3[0]==t2[1]==t1[2]!=\" \":\n gagnee=True\n finDePartieGagnée()\n else:\n gagnee=False\n return(gagnee)\n\n### Arrêt de la partie ###\n\ndef finDePartieGagnée():\n print(\"Gagné par ...\")\n finDePartie()\n return()\n\ndef finDePartie():\n print(\"Fin de partie !\")\n gag1=False\n return(gag1)\n\n####### CEUX QUI NE SERVENT PAS A GRAND CHOSE MAIS QU'ON GARDE QUAND MÊME #######\ndef finDePartieEgalitee():\n print(\"Égalitée !\")\n finDePartie()\n return()\n\ndef finDePartieDiasp():\n if gagnee==True:\n finDePartieGagnée()\n gag1=False\n return(gag1)\n\n ##########################################\n ############################################\n################## PROGRAMMME ##################\n ############################################\n ##########################################\n\n\n### Création du tableau ###\nt0 = [\"A\",\"B\",\"C\"]\nt1 = [\" \"]*3\nt2 = [\" \"]*3\nt3 = [\" \"]*3\n\nT=[t0,t1,t2,t3]\n\n### Affichage du Manuel ###\n\nManuel()\nreponse = accord()\nif reponse == y :\n cls()\n\n### Affichage du tableau ###\n\nprint(\"Voici le plateau du jeu : \")\nprint(\"\")\nprint (t0)\nprint (t1)\nprint (t2)\nprint (t3)\nprint(\"\")\n\n### Programme en lui-même ###\n\ngagnee=False\n\nwhile gagnee==False:\n gagnee=changementJoueur(gagnee)\n","sub_path":"fonctions/final_test_v1.py","file_name":"final_test_v1.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"70258546","text":"import sqlite3\nimport json\n\nclass user:\n\t'''\n\tdef __init__(self, firstname, lastname):\n\t\tself.firstname = firstname\n\t\tself.lastname = lastname\n\t\tself.displayname = lastname + \", \" + firstname\n\t\tself.userid = firstname[0:1] + lastname\n\t'''\n\t@staticmethod\n\tdef create(firstname, lastname):\n\t\tconn = sqlite3.connect('./Python_API/idm.db')\n\t\tconn.execute(\"INSERT INTO users (firstname,lastname,displayname,userid) \\\n\t\tVALUES (?,?,?,?);\",(firstname, lastname, lastname + \", \" + firstname, firstname[0:1] + lastname))\n\t\tconn.commit()\n\n\t@staticmethod\n\tdef get(username):\n\t\tconn = sqlite3.connect('./Python_API/idm.db')\n\t\tcursor = conn.cursor()\n\t\tcursor.execute('SELECT * FROM users WHERE userid LIKE ?;',(username,))\n\t\tresults = cursor.fetchall()\n\t\treturn results\n\n#x = user(\"Joseph\",\"Hanson\")\n#x.create(\"Joseph\",\"Hanson\")\nuser.create(\"Joe\",\"Hanson\")\ni=user.get(\"j%\")\nprint(json.dumps(i))","sub_path":"dbtest.py","file_name":"dbtest.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"620523570","text":"from freenect import sync_get_depth as get_depth, sync_get_video as get_video\nfrom freenect import DEPTH_MM\nimport numpy as np\nimport sys\n\nn_frames = 1000\nif len(sys.argv) > 1:\n n_frames = int(sys.argv[1])\n\nif __name__ == \"__main__\":\n ''' Record data from Kinect device to use for mocking the device'''\n depth_images = []\n color_images = []\n print('start')\n for i in range(n_frames):\n print(f\"Step {i} of {n_frames}, please wait...\")\n (depth, _) = get_depth(format=DEPTH_MM)\n (rgb, _) = get_video()\n depth_images.append(np.copy(depth))\n color_images.append(np.copy(rgb))\n\n print('finished, saving')\n\n depth_images = np.array(depth_images)\n color_images = np.array(color_images)\n np.save(\"kinect_data.npy\", depth_images)\n np.save(\"color_kinect_data.npy\", color_images)\n print('done')\n","sub_path":"client/kinectlib/record_kinect.py","file_name":"record_kinect.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"351912532","text":"#2.7 水仙花数\n'''\n问题描述\n  153是一个非常特殊的数,它等于它的每位数字的立方和,即153=1*1*1+5*5*5+3*3*3。编程求所有满足这种条件的三位十进制数。\n输出格式\n  按从小到大的顺序输出满足条件的三位十进制数,每个数占一行。\n'''\nimport time\nstart = time.time()\ndef judge_shuixian(n):\n a = n % 10 #个位\n b = int(n%100 / 10) #十位\n c = int(n / 100)#注意:python中的除法会得到浮点数\n if n == a**3 + b**3 + c**3:\n print(n)\n\nfor i in range(100, 1000):\n judge_shuixian(i)\n\nend = time.time()\nprint(end-start)","sub_path":"CompetitionCode/LanQiaoBei/LianXi/JiChu_Sheet/ji_chu_2_7.py","file_name":"ji_chu_2_7.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"148148006","text":"import os, time\nimport numpy as np\nimport h5py\nimport scipy\nimport scipy.stats\nimport math\nfrom libs.RSdatamanager import filemanager as fm \nfrom multiprocessing import Pool, Lock, Value\nfrom functools import partial\nfrom pandas.core.common import flatten\nfrom skimage.measure import block_reduce\n\nfrom pydtw import dtw1d\nfrom pydtw import dtw2d\n\n\n#---------------------------------------------------------------------------------------------------#\n\"\"\"\nClasses:\n1 artificial\n2 bareland\n3 grassland\n4 crops\n5 broadleaves\n6 conifers\n7 snow\n8 water\n9 shrub\n\"\"\"\n#---------------------------------------------------------------------------------------------------#\ndef manager(tile, **kwargs):\n #SETUP DEFAULT OPTIONS \n info = kwargs.get('info', True)\n years = kwargs.get('years', None)\n outpath = kwargs.get('outpath', None)\n savepath = fm.check_folder(outpath, tile, 'LCTraining_DTW')\n\n blocksize = kwargs.get('blocksize', 500)\n n_classes = kwargs.get('n_classes', 9)\n multiprocessing = kwargs.get('multiprocessing', True)\n weekly = kwargs.get('weekly', True)\n\n singlefeaturedtw = kwargs.get('singlefeaturedtw', False)\n featureselection = kwargs.get('featureselection', False)\n multifeatureDTW = kwargs.get('multifeatureDTW', False)\n similarity = kwargs.get('similarity', False)\n classprototypes = kwargs.get('classprototypes', False)\n\n DTW_max_samp = kwargs.get('DTW_max_samp', 15) # max number of samples of DTW\n\n col_nPIXEL = 0\n col_nCLASS = 1\n col_nBAND = 2\n col_DATA = 3\n\n\n ###############################\n # GET INFO AND INITIALIZATION #\n ###############################\n for rootname, _, filenames in os.walk(outpath):\n for f in filenames:\n if (f.endswith('.tif')):\n loadpath = fm.joinpath(rootname, f) \n img = fm.readGeoTIFFD(loadpath, metadata=False)\n width, height, totfeature = img.shape\n\n for rootname, _, filenames in os.walk(outpath):\n for f in filenames:\n if (f.endswith('ts.h5')):\n loadpath = fm.joinpath(rootname, f)\n \n with h5py.File(loadpath, 'r') as hf:\n NDI_ = np.array(hf[\"ts\"])\n \n\n #Get classes intervals\n class_int = np.zeros(n_classes)\n class_int_mask = np.unique(NDI_[:,col_nCLASS]).astype(int).tolist()\n for n in class_int_mask:\n class_int[n-1] = n\n class_int = class_int.astype(int).tolist()\n\n #Get number of seeds\n n_seeds = len(np.unique(NDI_[:,col_nPIXEL]))\n \n #Get number of features\n n_features = totfeature\n\n #Get number of seeds per class and class seeds mask\n n_seeds_c = np.zeros(n_classes)\n for nc in class_int:\n n_seeds_c[nc-1] = np.size(NDI_[NDI_[:,col_nCLASS]==nc, :], axis=0)\n n_seeds_c = n_seeds_c.astype(int).tolist()\n\n seed_class_mask = NDI_[:,col_nCLASS]\n\n #Define blocksize\n nseeds_b = blocksize\n \n #Space of analysis parameters\n min_perc_samp_V = np.arange(1, 0.64, -0.03).tolist() # minimum percentage of total used samples\n min_perc_samp_mod_V = np.ones(12, dtype=float)/np.arange(1,13) # minimum percentage of used samples per model\n min_perc_samp_mod_V = min_perc_samp_mod_V.tolist()\n \n sepa_b_vs_b = np.zeros((12,12,n_features))\n\n\n ##########################################\n # SINGLE FEATURE DTW SIMILARITY MATRICES #\n ##########################################\n if singlefeaturedtw:\n\n for feature in range(n_features):\n if info:\n t_start = time.time()\n print('Computing DTW feature %i/%i...' % ( (feature+1), n_features ), end='\\r') \n\n path = fm.check_folder(savepath, \"Singlefeature\", 'DTW_matrix_B'+str(feature+1))\n\n for b1 in range(0, n_seeds, nseeds_b):\n Seeds_B_B1 = load_block(tile, b1, feature, col_DATA, **kwargs)\n for b2 in range(0, n_seeds, nseeds_b):\n Seeds_B_B2 = load_block(tile, b2, feature, col_DATA, **kwargs)\n singledtw(Seeds_B_B1, Seeds_B_B2, b1, b2, nseeds_b, n_seeds, path, **kwargs)\n \n if info:\n t_end = time.time()\n print('\\nMODULE 4: calculating DTW for %ith feature..Took %i' % (feature+1 , (t_end-t_start)/60), 'min')\n\n\n #Single feature DTW maximum distance\n DTW_max_d_B = np.zeros(n_features)\n\n for feature in range(n_features):\n path = fm.check_folder(savepath, \"Singlefeature\", 'DTW_matrix_B'+str(feature+1))\n filename = fm.joinpath(path, 'DTW_matrix_B.h5')\n\n max_d = 0\n for b1 in range(0, n_seeds, nseeds_b):\n for b2 in range(0, n_seeds, nseeds_b):\n with h5py.File(filename, 'r') as hf:\n block = np.array(hf[\"DTW_matrix_B\"][b1:b1+nseeds_b, b2:b2+nseeds_b])\n max_d_block = np.nanmax(block[block != np.inf])\n if max_d_block > max_d:\n max_d = max_d_block\n \n DTW_max_d_B[feature] = max_d\n\n\n ######################################################\n # FEATURE SPACE ANALYSIS AND FEATURE SPACE REDUCTION #\n ######################################################\n if featureselection:\n\n for feature in range(n_features):\n if info:\n t_start = time.time()\n print('Feature %i/%i...' % ( (feature+1), n_features ), end='\\r')\n\n sepa_c_vs_c = np.zeros((12,12))\n sepa_c_vs_c_N = np.zeros((12,12))\n \n for i, nc in enumerate(class_int_mask):\n c_r = np.delete(class_int_mask, i).tolist()\n for nc1 in c_r:\n simi_c_W, simi_c_C = load_block_DTW(seed_class_mask, feature, DTW_max_d_B[feature], nc, nc1, savepath)\n \n for col_i, min_perc_samp in enumerate(min_perc_samp_V):\n for row_i, min_perc_samp_mod in enumerate(min_perc_samp_mod_V):\n sepa_mea = np.zeros(n_seeds_c[nc-1])\n for nsc in range(n_seeds_c[nc-1]):\n simi_c_C_s = simi_c_C[:,nsc]\n simi_c_C_s = simi_c_C_s[~np.isnan(simi_c_C_s)]\n simi_c_C_s = sorted(simi_c_C_s, reverse=True)\n simi_c_C_s = simi_c_C_s[0:math.ceil(n_seeds_c[nc-1]*min_perc_samp_mod*min_perc_samp)]\n simi_c_W_s = simi_c_W[:,nsc]\n simi_c_W_s = sorted(simi_c_W_s, reverse=True)\n simi_c_W_s = simi_c_W_s[0:math.ceil(n_seeds_c[nc-1]*min_perc_samp_mod*min_perc_samp)]\n pd_C_mu, pd_C_sigma = scipy.stats.distributions.norm.fit(simi_c_C_s)\n pd_W_mu, pd_W_sigma = scipy.stats.distributions.norm.fit(simi_c_W_s)\n if pd_C_mu <= pd_W_mu:\n sepa_mea[nsc] = np.nan\n else:\n sepa_mea[nsc] = (pd_C_mu - pd_W_mu)/(pd_C_sigma + pd_W_sigma)\n\n if (sepa_mea[~np.isnan(sepa_mea)]).size/(n_seeds_c[nc-1]) >= min_perc_samp:\n sepa_c_vs_c[row_i,col_i] = sepa_c_vs_c[row_i,col_i] + np.mean(sepa_mea[~np.isnan(sepa_mea)])\n sepa_c_vs_c_N[row_i,col_i] = sepa_c_vs_c_N[row_i,col_i] + 1\n \n sepa_b_vs_b[...,feature] = sepa_c_vs_c * sepa_c_vs_c_N\n\n if info:\n t_end = time.time()\n print('\\nMODULE 4: feature selection for %i th feature..Took %i' % (feature+1 , t_end-t_start/60), 'min' )\n\n np.save(fm.joinpath(savepath, \"sepa_b_vs_b.npy\"), sepa_b_vs_b)\n\n\n #Search for Class Cluster Parameters\n # select_bands = np.load(fm.joinpath(savepath, \"select_bands.npy\"))\n sepa_b_vs_b = np.load(fm.joinpath(savepath, \"sepa_b_vs_b.npy\"))\n # select_bands = select_bands.astype(int).tolist()\n sepa_FS = np.zeros((12,12))\n for nb in range(n_features):\n sepa_FS = sepa_FS + sepa_b_vs_b[:,:,nb]\n\n mean_sepa_FS = np.mean(sepa_FS, axis=1)\n max_sepa_pos_samp_x_mod_FS = np.argmax(mean_sepa_FS)\n mean_sepa_max_v_FS = sepa_FS[max_sepa_pos_samp_x_mod_FS,:]\n mean_sepa_max_v_derivate_FS = np.diff(mean_sepa_max_v_FS)\n mean_sepa_max_v_derivate_FS = mean_sepa_max_v_derivate_FS/np.max(mean_sepa_max_v_derivate_FS)\n mean_sepa_max_v_derivate_FS = mean_sepa_max_v_derivate_FS * mean_sepa_max_v_FS[1 :]\n\n max_sepa_pos_perc_samp_FS = np.argmax(mean_sepa_max_v_derivate_FS)\n max_sepa_pos_perc_samp_FS = max_sepa_pos_perc_samp_FS + 1\n\n min_perc_samp = min_perc_samp_V[max_sepa_pos_perc_samp_FS]\n min_perc_samp_mod = min_perc_samp_V[max_sepa_pos_perc_samp_FS]*min_perc_samp_mod_V[max_sepa_pos_samp_x_mod_FS]\n max_mod_class = np.round(min_perc_samp_V[max_sepa_pos_perc_samp_FS]/min_perc_samp_mod)\n\n \n #######################################\n # MULTI FEATURE DTW SIMILARITY MATRIX #\n #######################################\n if multifeatureDTW:\n\n if info:\n t_start = time.time()\n print('Computing multifeature DTW ...', end='\\r') \n\n # select_bands = np.load(fm.joinpath(savepath, \"select_bands.npy\"))\n # select_bands = select_bands.astype(int).tolist()\n\n path = fm.check_folder(savepath, 'Multifeature')\n\n for b1 in range(0, n_seeds, nseeds_b):\n Seeds_B1 = load_block_multifeature(tile, b1, n_features, col_DATA, **kwargs)\n for b2 in range(0, n_seeds, nseeds_b):\n Seeds_B2 = load_block_multifeature(tile, b1, n_features, col_DATA, **kwargs)\n multidtw(Seeds_B1, Seeds_B2, b1, b2, nseeds_b, n_seeds, path, **kwargs)\n\n if info:\n t_end = time.time()\n print('\\nMODULE 4: calculating multifeature DTW ...Took %i' % ((t_end-t_start)/60), 'min')\n\n\n #Multi feature DTW maximum distance\n path = fm.check_folder(savepath, 'Multifeature')\n filename = fm.joinpath(path, 'DTW_matrix.h5')\n\n DTW_max_d = 0\n for b1 in range(0, n_seeds, nseeds_b):\n for b2 in range(0, n_seeds, nseeds_b):\n with h5py.File(filename, 'r') as hf:\n block = np.array(hf[\"DTW_matrix\"][b1:b1+nseeds_b, b2:b2+nseeds_b])\n max_d_block = np.nanmax(block[block != np.inf])\n if max_d_block > DTW_max_d:\n DTW_max_d = max_d_block\n\n \n #######################\n # SIMILARITY ANALYSIS #\n #######################\n if similarity:\n\n simi_high = kwargs.get('simi_high', 1) # high similarity measure\n simi_decr = kwargs.get('simi_decr', 0.001) # decrese value of similarity measure\n\n min_c_vs_c = np.zeros((len(class_int_mask), len(class_int_mask)-1))\n max_c_vs_c = np.zeros((len(class_int_mask), len(class_int_mask)-1))\n mean_c_vs_c = np.zeros((len(class_int_mask), len(class_int_mask)-1))\n simi_low = np.zeros((len(class_int_mask)))\n\n for i, nc in enumerate(class_int_mask):\n c_r = np.delete(class_int_mask, i).tolist()\n for n, nc1 in enumerate(c_r):\n simi_c_W, simi_c_C = load_block_DTW_multi(seed_class_mask, DTW_max_d, nc, nc1, savepath)\n\n min_c_s = np.zeros((n_seeds_c[nc-1]))\n max_c_s = np.zeros((n_seeds_c[nc-1]))\n for nsc in range(n_seeds_c[nc-1]):\n simi_c_C_s = simi_c_C[:,nsc]\n simi_c_C_s = simi_c_C_s[~np.isnan(simi_c_C_s)]\n simi_c_C_s = sorted(simi_c_C_s, reverse=True)\n simi_c_C_s = simi_c_C_s[0:math.ceil(n_seeds_c[nc-1]*min_perc_samp_mod*min_perc_samp)]\n simi_c_W_s = simi_c_W[:,nsc]\n simi_c_W_s = sorted(simi_c_W_s, reverse=True)\n simi_c_W_s = simi_c_W_s[0:math.ceil(n_seeds_c[nc-1]*min_perc_samp_mod*min_perc_samp)]\n pd_C_mu, pd_C_sigma = scipy.stats.distributions.norm.fit(simi_c_C_s)\n pd_W_mu, pd_W_sigma = scipy.stats.distributions.norm.fit(simi_c_W_s)\n if pd_C_mu <= pd_W_mu:\n min_c_s[nsc] = np.nan\n else:\n a = scipy.stats.norm(pd_C_mu, pd_C_sigma).pdf(np.arange(0, 1, simi_decr))\n b = scipy.stats.norm(pd_W_mu, pd_W_sigma).pdf(np.arange(0, 1, simi_decr))\n for int_mu in np.int64(np.arange(np.floor(pd_W_mu*(1/simi_decr)), (math.ceil(pd_C_mu*(1/simi_decr))+1), 1000*simi_decr)): \n if(round(b[int_mu-1],1)-round(a[int_mu-1],1) <= 0):\n min_c_s[nsc] = int_mu*simi_decr\n break\n else:\n min_c_s[nsc] = np.nan\n \n for int_mu in np.flipud(np.int64(np.arange(np.floor(pd_W_mu*(1/simi_decr)), (math.ceil(pd_C_mu*(1/simi_decr))+1), 1000*simi_decr))):\n if(round(a[int_mu-1],1)-round(b[int_mu-1],1) <= 0):\n max_c_s[nsc] = int_mu*simi_decr\n break\n else:\n max_c_s[nsc] = np.nan\n\n min_c_vs_c[i,n] = np.mean(min_c_s[~np.isnan(min_c_s)])\n max_c_vs_c[i,n] = np.mean(max_c_s[~np.isnan(max_c_s)])\n mean_c_vs_c[i,n] = min_c_vs_c[i,n] #mean([min_c_vs_c(nc,nc1) max_c_vs_c(nc,nc1)])\n\n simi_low[i] = np.max(mean_c_vs_c[i,:])\n\n np.save(fm.joinpath(savepath, \"simi_low.npy\"), simi_low)\n \n\n ###############################\n # CLASS PROTOTYPES GENERATION #\n ###############################\n if classprototypes:\n \n pass_table = np.zeros(n_classes) # array of pass/no pass\n models_C = [None]*9 # variable that contains the models seeds\n used_models = np.zeros(n_classes) # array of number of model used per class\n used_samples_perc = np.zeros(n_classes) # array of used samples per class\n used_simi = np.zeros(n_classes) # array of used similarity per class\n\n for i, nc in enumerate(class_int_mask):\n max_s = 1 # set max similarity = 1\n min_s = 0 #simi_low(nc); # set min similarity\n\n while pass_table[nc-1]==0:\n _, dist_simi_c = load_block_DTW_multi(seed_class_mask, DTW_max_d, nc, nc, savepath)\n\n count_simi_c = (dist_simi_c > max_s) # check class seed with a similarity major then the threshold\n mean_simi_c = np.empty((n_seeds_c[nc-1])) * np.nan # initializate the similarity mean value\n\n # compute the mean similarity value per seed for each accepted other seed\n for nsc in range(n_seeds_c[nc-1]):\n mean_simi_c[nsc] = np.mean(dist_simi_c[count_simi_c[:,nsc],nsc])\n \n # form a matrix with [seed ID | number of accepted seeds | mean similarity for accepted seeds]\n simi_order = np.column_stack([np.arange(0,n_seeds_c[nc-1],1), np.sum(count_simi_c, axis=0), mean_simi_c])\n \n # order the seeds\n simi_order = simi_order[np.argsort(-simi_order[:, 0])]\n simi_order = np.array(simi_order[np.argsort(-simi_order[:, 0])], dtype=int)\n #simi_order = sorted(simi_order, key=lambda x : x[0], reverse=True)\n\n models = [] # initialize the models\n \n for nsc in range(n_seeds_c[nc-1]):\n n_mod = len(models) #number of exist models\n \n if n_mod == 0: # if the number of models is zero, just insert the initial seed\n models.append(simi_order[nsc,0])\n \n else: # else check if any model can accept the new seed\n simi = np.zeros((n_mod,3)) #initialize the similarity matrix\n \n # for each model check if all seed can accept the new one\n for nm in range(n_mod):\n seed_int = models[nm] # get seed ID interval\n # form a matrix with [model ID | acceptance value | mean similarity between new seed and model seeds]\n simi[nm,:] = [nm, \n np.sum((dist_simi_c[simi_order[nsc,0],seed_int] > max_s)*1)>=(np.ceil(np.size(seed_int)*1)),\n np.mean(dist_simi_c[simi_order[nsc,0],seed_int])]\n \n # sort the similarity matrix to get the most similar model\n simi = np.array(simi[np.argsort(-simi[:,2])], dtype=int)\n \n if simi[0,1]==1: # if the first model can accept the new seed, insert it \n models[simi[0,0]] = list(flatten([models[simi[0,0]], simi_order[nsc,0]]))\n \n else: # otherwise create a new model and insert the seed\n models.append(simi_order[nsc,0])\n \n n_mod = np.size(models,0) # get number of models\n # delete models with a percentage of seed lower than the threshold\n for nm in range(n_mod):\n if np.size(models[nm]) < math.ceil(n_seeds_c[nc-1]*min_perc_samp_mod):\n models[nm] = []\n\n models = list(filter(None, models))\n \n u_models = len(models) # get number of used models\n u_samples = np.zeros(u_models) # initialized the percentage of used seeds\n # compute the percentage of used seeds\n for um in range(u_models):\n u_samples[um] = np.size(models[um])\n u_samples = (np.sum(u_samples))/(n_seeds_c[nc-1])\n \n # if the pass condition are respected update the output matrixes\n if ((u_models <= max_mod_class) and (bool(u_samples >= min_perc_samp))):\n pass_table[nc-1] = 1\n models_C[nc-1] = models\n used_models[nc-1] = u_models\n used_samples_perc[nc-1] = u_samples\n used_simi[nc-1] = max_s\n else:\n if ((max_s > min_s) and (max_s > simi_decr)): # otherwise decrease the similarity threshold\n max_s = max_s - simi_decr\n print(max_s)\n else: # or if not possible put in the pass table a false value\n pass_table[nc-1] = 2\n \n\n # class prototypes creation\n models = [[[] for _ in range(len(n_features))] for _ in range(n_classes)]\n for nc in (class_int_mask):\n for nb_o, nb in enumerate(n_features):\n n_mod = np.size(models_C[nc-1])\n Seeds_FR, Seeds_F = load_Seeds_FR(tile, nb, col_DATA, **kwargs)\n m1 = Seeds_F[:,col_nCLASS]==nc\n m2 = Seeds_F[:,col_nBAND]==nb\n m3 = np.logical_and(m1, m2)\n TABLE_cb = Seeds_FR[m3,:]\n for nm in range(n_mod):\n TABLE_cbm = TABLE_cb[models_C[nc-1][nm],:]\n traj = np.mean(TABLE_cbm,0)\n models[nc-1][nb_o].append(traj)\n\n # prototypes vs samples\n _, col = Seeds_FR.shape\n Traj1 = np.zeros((len(n_features),col)) \n sampleVSmodels = np.zeros((n_seeds,n_classes+3)) \n\n for ns in range(n_seeds):\n for n, nb in enumerate(n_features):\n Seeds_FR, Seeds_F = load_Seeds_FR(tile, nb, col_DATA, **kwargs)\n Traj1[n,:] = Seeds_FR[ns,:]\n \n sample_simi = [ns, Seeds_F[ns,col_nCLASS], 0]\n for nc in (class_int):\n if nc == 0:\n max_simi = 0\n else: \n n_mod = len(models[nc-1])\n max_simi = 0\n for nm in range(n_mod):\n Traj2 = models[nc-1][nm]\n simi = ((DTW_max_d - distance_fast(Traj1, Traj2, max_step=DTW_max_samp))/DTW_max_d)\n max_simi = np.max([max_simi, simi])\n \n sample_simi.append(max_simi)\n \n max_v = max(sample_simi[3:])\n max_p = sample_simi[3:].index(max_v)\n sample_simi[2] = max_p+1\n sampleVSmodels[ns,:] = sample_simi\n \n #confusion matrix between training samples and prototypes\n CM_S = confusion_matrix(sampleVSmodels[:,1], sampleVSmodels[:,2]) \n\n\n#---------------------------------------------------------------------------------------------------#\ndef counterinit(c):\n global counter\n counter = c\n\n#---------------------------------------------------------------------------------------------------#\n#DTW\n\ndef singledtw(Seeds_B_B1, Seeds_B_B2, b1, b2, nseeds_b, n_seeds, path, **kwargs):\n #SETUP OPTIONS\n info = kwargs.get('info', True)\n DTW_max_samp = kwargs.get('DTW_max_samp', 15)\n multiprocessing = kwargs.get('multiprocessing', True)\n\n #ALLOC VARIABLE\n DTW_matrix_B = np.zeros((nseeds_b, nseeds_b))\n\n if b2>> u = Uniform(Sobol(2,seed=7),lower_bound=1,upper_bound=2)\n >>> u\n Uniform (TrueMeasure Object)\n lower_bound [1 1]\n upper_bound [2 2]\n >>> u.gen_samples(n_min=4,n_max=8)\n array([[1.882, 1.932],\n [1.035, 1.071],\n [1.569, 1.418],\n [1.474, 1.593]])\n >>> u.set_dimension(4)\n >>> u\n Uniform (TrueMeasure Object)\n lower_bound [1 1 1 1]\n upper_bound [2 2 2 2]\n >>> u.gen_samples(n_min=4,n_max=8)\n array([[1.882, 1.932, 1.573, 1.07 ],\n [1.035, 1.071, 1.379, 1.6 ],\n [1.569, 1.418, 1.036, 1.889],\n [1.474, 1.593, 1.982, 1.422]])\n >>> u2 = Uniform(Sobol(2),lower_bound=[-.5,0],upper_bound=[1,3])\n >>> u2\n Uniform (TrueMeasure Object)\n lower_bound [-0.5 0. ]\n upper_bound [1 3]\n >>> u2.pdf([0,1])\n 0.2222222222222222\n \"\"\"\n\n parameters = ['lower_bound', 'upper_bound']\n \n def __init__(self, distribution, lower_bound=0., upper_bound=1.):\n \"\"\"\n Args:\n distribution (DiscreteDistribution): DiscreteDistribution instance\n lower_bound (float): a for Uniform(a,b)\n upper_bound (float): b for Uniform(a,b)\n \"\"\"\n self.distribution = distribution\n self.d = self.distribution.dimension\n if isscalar(lower_bound):\n lower_bound = tile(lower_bound,self.d)\n if isscalar(upper_bound):\n upper_bound = tile(upper_bound,self.d)\n self.lower_bound = array(lower_bound)\n self.upper_bound = array(upper_bound)\n if len(self.lower_bound)!=self.d or len(self.upper_bound)!=self.d:\n raise DimensionError('upper bound and lower bound must be of length dimension')\n super(Uniform,self).__init__()\n \n def pdf(self,x):\n \"\"\" See abstract class. \"\"\"\n return 1./( prod(self.upper_bound-self.lower_bound) )\n\n def _tf_to_mimic_samples(self, samples):\n \"\"\"\n Transform samples to appear Uniform\n \n Args:\n samples (ndarray): samples from a discrete distribution\n \n Return:\n ndarray: samples from the DiscreteDistribution transformed to mimic Uniform.\n \"\"\"\n if self.distribution.mimics == 'StdGaussian':\n # CDF then stretch\n mimic_samples = norm.cdf(samples) * (self.upper_bound - self.lower_bound) + self.lower_bound\n elif self.distribution.mimics == \"StdUniform\":\n # stretch samples\n mimic_samples = samples * (self.upper_bound - self.lower_bound) + self.lower_bound\n else:\n raise TransformError(\\\n 'Cannot transform samples mimicing %s to Uniform'%self.distribution.mimics)\n return mimic_samples\n\n def _transform_g_to_f(self, g):\n \"\"\" See abstract method. \"\"\"\n def f(samples, *args, **kwargs):\n z = self._tf_to_mimic_samples(samples)\n y = g(z, *args, **kwargs)\n return y\n return f\n\n def gen_samples(self, *args, **kwargs):\n \"\"\" See abstract method. \"\"\"\n samples = self.distribution.gen_samples(*args,**kwargs)\n mimic_samples = self._tf_to_mimic_samples(samples)\n return mimic_samples\n \n def set_dimension(self, dimension):\n \"\"\" See abstract method. \"\"\"\n l = self.lower_bound[0]\n u = self.upper_bound[0]\n if not (all(self.lower_bound==l) and all(self.upper_bound==u)):\n raise DimensionError('In order to change dimension of uniform measure the '+\\\n 'lower bounds must all be the same and the upper bounds must all be the same')\n self.distribution.set_dimension(dimension)\n self.d = dimension\n self.lower_bound = tile(l,self.d)\n self.upper_bound = tile(u,self.d)\n \n def plot(self, dim_x=0, dim_y=1, n=2**7, point_size=5, color='c', show=True, out=None):\n \"\"\"\n Make a scatter plot from samples. Requires dimension >= 2. \n\n Args:\n dim_x (int): index of first dimension to be plotted on horizontal axis. \n dim_y (int): index of the second dimension to be plotted on vertical axis.\n n (int): number of samples to draw as self.gen_samples(n)\n point_size (int): ax.scatter(...,s=point_size)\n color (str): ax.scatter(...,color=color)\n show (bool): show plot or not? \n out (str): file name to output image. If None, the image is not output\n\n Return: \n tuple: fig,ax from `fig,ax = matplotlib.pyplot.subplots(...)`\n \"\"\"\n if self.dimension < 2:\n raise ParameterError('Plotting a Uniform instance requires dimension >=2. ')\n x = self.gen_samples(n)\n from matplotlib import pyplot\n pyplot.rc('font', size=16)\n pyplot.rc('legend', fontsize=16)\n pyplot.rc('figure', titlesize=16)\n pyplot.rc('axes', titlesize=16, labelsize=16)\n pyplot.rc('xtick', labelsize=16)\n pyplot.rc('ytick', labelsize=16)\n fig,ax = pyplot.subplots()\n x_low = self.lower_bound[dim_x]\n x_high = self.upper_bound[dim_x]\n y_low = self.lower_bound[dim_y]\n y_high = self.upper_bound[dim_y]\n ax.set_xlim([x_low,x_high])\n ax.set_xticks([x_low,x_high])\n ax.set_ylim([y_low,y_high])\n ax.set_yticks([y_low,y_high])\n ax.set_xlabel('$x_{i,%d}$'%dim_x)\n ax.set_ylabel('$x_{i,%d}$'%dim_y)\n ax.scatter(x[:,dim_x],x[:,dim_y],color=color,s=point_size)\n s = '$2^{%d}$'%log2(n) if log2(n)%1==0 else '%d'%n\n ax.set_title(s+' Uniform Samples')\n fig.tight_layout()\n if out: pyplot.savefig(out,dpi=250)\n if show: pyplot.show()\n return fig,ax\n","sub_path":"qmcpy/true_measure/uniform.py","file_name":"uniform.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"405820719","text":"import time\n\ncommand = str()\nstatus = False\n\nclass Repeat:\n\tdef question(self):\n\t\tglobal command\n\t\tcommand = raw_input(\"\\n What would you like to do: \")\n\tdef flipStatus(bool):\n\t\tglobal status\n\t\tif(status == True):\n\t\t\tstatus = False\n\t\telse:\n\t\t\tstatus = True\n\nsession = Repeat()\nprint(\"Welcome to Metaria. \\n You're in a dimly lit forest and you seem to have forgotten your memory.\")\nsession.question()\nwhile(status == False):\n\tif (command == \"Look around\"):\n\t\tprint(\"The forest is filled with ancient trees. \\n The underbrush is thick but you see a beaten path\")\n\t\tsession.question()\n\t\tsession.flipStatus(status)\n\t\n\n\n\n\n\n\n\n\n","sub_path":"metaria.py","file_name":"metaria.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"345398251","text":"\nimport subprocess\nimport unittest\nfrom . import osbuildtest\n\n\nclass TestBoot(osbuildtest.TestCase):\n def test_boot(self):\n _, output_id = self.run_osbuild(\"test/pipelines/f30-boot.json\")\n\n r = subprocess.run([\"qemu-system-x86_64\",\n \"-snapshot\",\n \"-m\", \"1024\",\n \"-accel\", \"kvm:hvf:tcg\",\n\n # be silent\n \"-nographic\",\n \"-monitor\", \"none\",\n \"-serial\", \"none\",\n\n # create /dev/vport0p1\n \"-chardev\", \"stdio,id=stdio\",\n \"-device\", \"virtio-serial\",\n \"-device\", \"virtserialport,chardev=stdio\",\n\n f\"{self.get_path_to_store(output_id)}/f30-boot.qcow2\"\n ], encoding=\"utf-8\", stdout=subprocess.PIPE, check=True)\n\n self.assertEqual(r.stdout.strip(), \"running\")\n","sub_path":"test/test_boot.py","file_name":"test_boot.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"319666442","text":"#!python\n\n# Hint: use string.ascii_letters (all letters in ASCII character set)\nimport string\n\n\ndef is_palindrome(text):\n \"\"\"A string of characters is a palindrome if it reads the same forwards and\n backwards, ignoring punctuation, whitespace, and letter casing\"\"\"\n # implement is_palindrome_iterative and is_palindrome_recursive below, then\n # change this to call your implementation to verify it passes all tests\n assert isinstance(text, str)\n # return is_palindrome_iterative(text)\n return is_palindrome_recursive(text)\n\n\ndef is_palindrome_iterative(text):\n # changing all the characters to lowercase\n text = text.lower()\n # replacing whitespaces with no space\n text = text.replace(\" \", \"\")\n # removing the punctionations\n text = text.translate(None, string.punctuation)\n # check if the text is empty\n if len(text) <= 1:\n return True\n # getting half of the length\n half = len(text) / 2\n # left half\n left = 0\n # right half\n right = -1\n # loops through the text\n for index in range(0, half):\n print(index)\n # first letter in the string\n first_letter = text[left]\n print(first_letter)\n # last letter in the string\n last_letter = text[right]\n print(last_letter)\n # check if the first and last letter are the same\n if first_letter is not last_letter:\n return False\n # incrimenting the left to iterate to the next letter\n print(left)\n left += 1\n # decrementing the right to iterate to the next letter\n print(right)\n right -= 1\n return True\n\n '''\n P.S: Four liner solution\n\n text = text.lower()\n if str(text) == str(text)[::-1]:\n return True\n return False\n\n Explanation:\n - We're checking if the string representation of n equals\n the inverted string representation of n\n - The [::-1] slice takes care of inverting the string\n - After that, we compare for equality using ==\n '''\n\n\ndef is_palindrome_recursive(text, left=None, right=None):\n '''\n return text[0] == text[-1] and is_palindrome_recursive(text[1:-1])\n This is inefficient because the slicing method is copying the string\n over and over again.\n '''\n if left is None and right is None:\n # changing all the characters to lowercase\n text = text.lower()\n # replacing whitespaces with no space\n text = text.replace(\" \", \"\")\n # removing the punctionations\n text = text.translate(None, string.punctuation)\n left = 0\n right = len(text) - 1\n if left >= right:\n return True\n if text[left] is text[right]:\n return is_palindrome_recursive(text, (left + 1), (right - 1))\n return False\n\n\ndef main():\n import sys\n args = sys.argv[1:] # Ignore script file name\n if len(args) > 0:\n for arg in args:\n is_pal = is_palindrome(arg)\n result = 'PASS' if is_pal else 'FAIL'\n str_not = 'a' if is_pal else 'not a'\n print('{}: {} is {} palindrome'.format(result, repr(arg), str_not))\n else:\n print('Usage: {} string1 string2 ... stringN'.format(sys.argv[0]))\n print(' checks if each argument given is a palindrome')\n\n\nif __name__ == '__main__':\n main()\n # print(is_palindrome_iterative('Bb'))\n","sub_path":"source/palindromes.py","file_name":"palindromes.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574385618","text":"from logica import sessao\n\ndef imprimir_sessao(sessao):\n print (\"Código: \", sessao [0])\n print (\"Código do filme: \", sessao[1])\n print (\"Código da sala: \", sessao[2])\n print (\"Horário: \", sessao[3])\n print ()\n\ndef menu_criar():\n print (\"\\nCriar SESSÃO: \\n\")\n cod_filme = int (input(\"Código Filme: \"))\n cod_sala = int(input(\"Código da sala: \"))\n horario = int(input(\"Horário: \"))\n sessao.criar_sessao(cod_filme,cod_sala,horario)\n print (\"Sessão criada \")\n\ndef menu_recuperar():\n print (\"\\nRecuperar SESSÃO \\n\")\n cod = int(input(\"Código: \"))\n c = sessao.recuperar_sessao(cod)\n if (c == None):\n print (\"Sessão não encontrada\")\n else:\n imprimir_sessao(c)\n\ndef menu_verificar_lotacao():\n print(\"\\nVerificar Loração \\n\")\n cod = int(input(\"Entre com o codigo da sessão: \"))\n s = sessao.verificar_lotacao(cod)\n print(s)\n \n\ndef menu_listar():\n print (\"\\nListar SESSÕES \\n\")\n sessoes = sessao.listar_sessoes()\n for s in sessoes:\n imprimir_sessao(s)\n\ndef menu_remover():\n print (\"\\nRemover SESSÃO \\n\")\n cod_sessao = int(input(\"Codigo Sessão: \"))\n s = sessao.remover_sessao(cod_sessao)\n if (s == False):\n print (\"Sessão não encontrada\")\n else:\n print (\"Sessão removido\")\n\ndef mostrar_menu():\n run_sessao = True\n menu = (\"\\n----------------\\n\"+\n \"(1) Criar uma sessão \\n\" +\n \"(2) Recuperar uma sessao \\n\" +\n \"(3) Verificar lotação \\n\" +\n \"(4) Listar sessões \\n\" +\n \"(5) Remover Sessao \\n\" +\n \"(0) Voltar\\n\"+\n \"----------------\")\n \n while(run_sessao):\n print (menu)\n op = int(input(\"Digite sua escolha: \"))\n\n if (op == 1):\n menu_criar()\n elif(op == 2):\n menu_recuperar()\n elif(op == 3): \n menu_verificar_lotacao()\n elif (op == 4):\n menu_listar()\n elif (op == 5):\n menu_remover()\n elif (op == 0):\n run_sessao = False\n","sub_path":"gui/menu_sessao.py","file_name":"menu_sessao.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"300650457","text":"# Copyright 2018-2020 Abien Fred Agarap\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\"\"\"TensorFlow 2.0 implementation of a neural network\"\"\"\nimport tensorflow as tf\n\n__author__ = \"Abien Fred Agarap\"\n__version__ = \"1.0.0\"\n\n\nclass NeuralNet(tf.keras.Model):\n def __init__(self, **kwargs):\n super(NeuralNet, self).__init__()\n self.hidden_layer_1 = tf.keras.layers.Dense(\n units=kwargs[\"units\"][0],\n activation=kwargs[\"activation\"],\n kernel_initializer=kwargs[\"initializer\"],\n )\n self.hidden_layer_2 = tf.keras.layers.Dense(\n units=kwargs[\"units\"][1],\n activation=kwargs[\"activation\"],\n kernel_initializer=kwargs[\"initializer\"],\n )\n self.output_layer = tf.keras.layers.Dense(units=kwargs[\"num_classes\"])\n self.optimizer = tf.optimizers.SGD(learning_rate=3e-4, momentum=9e-1)\n\n @tf.function\n def call(self, features):\n activation = self.hidden_layer_1(features)\n activation = self.hidden_layer_2(activation)\n output = self.output_layer(activation)\n return output\n\n\ndef loss_fn(logits, labels):\n softmax_loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n return tf.reduce_mean(softmax_loss)\n\n\ndef train_step(model, loss, features, labels):\n with tf.GradientTape() as tape:\n logits = model(features)\n train_loss = loss(logits=logits, labels=labels)\n gradients = tape.gradient(train_loss, model.trainable_variables)\n model.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return train_loss\n\n\ndef train(model, loss_fn, dataset, epochs):\n epoch_accuracy = []\n epoch_loss = []\n for epoch in range(epochs):\n train_accuracy = []\n train_loss = 0\n for batch_features, batch_labels in dataset:\n batch_features += tf.random.normal(\n stddev=(1.0 / (1.0 + epoch) ** 0.55), shape=batch_features.shape\n )\n loss = train_step(model, loss_fn, batch_features, batch_labels)\n\n accuracy = tf.metrics.Accuracy()\n predictions = tf.nn.softmax(model(batch_features))\n accuracy(tf.argmax(predictions, 1), tf.argmax(batch_labels, 1))\n\n train_loss += loss\n train_accuracy.append(accuracy.result())\n\n epoch_loss.append(tf.reduce_mean(train_loss))\n epoch_accuracy.append(tf.reduce_mean(train_accuracy))\n\n if (epoch != 0) and ((epoch + 1) % 50 == 0):\n print(\n \"epoch {}/{} : mean loss = {}, mean accuracy = {}\".format(\n epoch + 1,\n epochs,\n tf.reduce_mean(train_loss),\n tf.reduce_mean(train_accuracy),\n )\n )\n return epoch_accuracy, epoch_loss\n","sub_path":"notebooks/fashion-mnist/neural_net.py","file_name":"neural_net.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"107063225","text":"#!/usr/bin/python\n#title : rofi wrapper\n\nimport subprocess\nimport sys, fileinput\nfrom random import randint\n\ndef append_new_line( string ):\n if '\\n' not in string:\n string += '\\n'\n return string\n\ndef rofi( args, stdin=[] ):\n if len( args ) > 1:\n cmd = '-dmenu ' + ' '.join( args )\n stdin = list( map( append_new_line, stdin ) )\n stdin = ''.join( stdin )\n else:\n cmd = '-modi drun -show drun'\n\n colours = [\"#b8bb26\", \"#fabd2f\", \"#fb4934\", \"#83a598\", \"#d3869b\", \"#8ec07c\", \"#fe8019\"]\n colour_str = \"-color-normal 'argb:00232221, #a2a2a2, argb:00232221, {}, #14161f'\".format(colours[randint(0,len(colours)-1)]) \n\n proc = subprocess.Popen('rofi -font \"Operator Mono 18\" {} {}'.format(colour_str, cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n proc.stdin.write(stdin.encode())\n out, err = proc.communicate()\n\n return out.decode().replace('\\n', '')\n \n\n\nif __name__ == \"__main__\":\n sys.stdout.write( rofi( sys.argv[1:], sys.stdin ) )\n sys.stdout.flush()\n sys.exit(0)\n","sub_path":"rofi/rofi.py","file_name":"rofi.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"48952043","text":"# -*- encoding:utf-8 -*-\nimport collections\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n#2.树,二叉树\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\n #3.N叉树的后序遍历 左右根\n def postorder(self, root: 'Node'):\n #解法一:递归解法 从左往右分别加入子节点的值,最后加入根节点的值\n # if not root:\n # return []\n # res = []\n # for child in root.children:\n # res.extend(self.postorder(child))\n # res.append(root.val)\n # return res\n\n #解法二:迭代解法 使用栈,前序遍历为根左右 入栈的时候从左到右,则出栈即为根右左,将顺序进行逆序即为左右根\n if not root:\n return []\n res,stack = [],[root]\n while stack:\n cur = stack.pop()\n res.append(cur.val)\n stack.extend(cur.children)\n return res[::-1]\n\n # 3.N叉树的前序遍历\n def preorder(self, root: 'Node'):\n # 解法一:递归 根左右的方式加入结果列表\n # if not root:\n # return []\n # res = [root.val]\n # for child in root.children:\n # res.extend(child.val)\n # return res\n\n # 解法二:迭代 使用栈 将子节点采用从右到左的方向入栈 则出栈为左右\n if not root:\n return []\n res, stack = [], [root]\n while stack:\n cur = stack.pop()\n res.append(cur.val)\n stack.extend(cur.children[::-1])\n return res\n\n #7.N叉树的层序遍历\n def levelOrder(self, root: 'Node'):\n #使用队列进行\n if not root:\n return []\n res = []\n queue = collections.deque([root])\n while queue:\n level = []\n for _ in range(len(queue)):\n node = queue.popleft()\n res.append(node.val)\n queue.extend(node.children)\n res.append(level)\n return res\n\n#1.最小的k个数\nimport heapq\ndef getLeastNumbers(arr, k):\n #通过堆来实现 要求的是最小的K个值,那么需要每次将较大的元素替换出去,因此需要维护一个大根堆\n #python 默认的是小根堆 因此需要取相反数\n #每个元素插入删除的时间复杂度都是O(logk) 总的时间复杂度为O(nlogk)\n if k == 0:\n return []\n #取数组里面前k个元素的相反数\n arr = [-x for x in arr[:k]]\n #构建最小堆\n hp = heapq.heapify(arr)\n for i in range(k,len(arr)):\n if -hp[0] > arr[i]:\n heapq.heappop(hp)\n heapq.heappush(hp,-arr[i])\n #最后取出堆上的元素\n res = [-x for x in hp]\n return res\n\n#2.滑动窗口最大值 双端队列\ndef maxSlidingWindow(nums,k):\n #解法一:采用双端队列 新插入的元素和队尾值比较,大于队尾值,则删除队尾值,加入新的元素,小于则直接加入,队列始终是从大到小排列的\n if len(nums) < 2:\n return nums\n #构建双端队列\n queue = collections.deque()\n #初始化结果列表\n res = []\n #遍历所有的元素下标\n for i in range(len(nums)):\n #新加入的元素和队尾比较,小于则删除\n while queue and nums[queue[-1]] < nums[i]:\n queue.pop()\n #上面情况不满足,则直接加入元素\n queue.append(i)\n\n #判断队首元素是否在当前窗口内,不是的话需要删除队首元素\n if queue[0] <= i - k:\n queue.popleft()\n\n #取出满足条件的值 下标从0开始 只有i+1 >= k 才能形成窗口\n if i - k + 1 >= 0:\n res.append(nums[queue[-1]])\n return res\n\n\n#本周作业\n#1.有效的字母异位词(每个字母出现的次数是一样的,但是位置不一样)\ndef isAnagram(s, t):\n #解法一:直接通过字符串排序进行判断 时间复杂度为O(nlogn)\n # s_sorted = ''.join(sorted(s))\n # t_sorted = ''.join(sorted(t))\n # if s_sorted == t_sorted:\n # return True\n # else:\n # return False\n\n #解法二:直接统计每个字符出现的次数\n # return collections.Counter(s) == collections.Counter(t)\n\n #解法三:使用哈希表统计每个字符串里面字符出现的次数\n if len(s) != len(t):\n return False\n counter = {}\n for char in s:\n if char in counter:\n counter[char] += 1\n else:\n counter[char] = 1\n\n for char1 in t:\n if char1 in counter:\n counter[char1] -= 1\n else:\n return False\n\n for value in counter.values():\n if value != 0:\n return False\n return True\n\n#2.两数之和\ndef twoSum(nums, target):\n #思路:采用哈希表,哈希表查找元素的时间复杂度为O(1)\n hash_dict = {}\n for i,num in enumerate(nums):\n if (target - num) in hash_dict:\n return [hash_dict[target-num],i]\n hash_dict[num] = i\n\n#4.字母异位词分组\ndef groupAnagrams(strs):\n #解法一:对字符串排序后分组 对字符串排序后转成tuple得到不可变对象作为字典的键\n # res_dict = {}\n # for s in strs:\n # res_dict[tuple(sorted(s))].append(s)\n # return res_dict.values()\n\n #解法二:通过将字符转为0-26之间的数字,然后记录每个数字出现的次数序列作为键\n res_dict = {}\n for s in strs:\n count = [0] * 26\n #遍历每个字符,统计每个字符出现的次数\n for c in s:\n count[ord(c) - ord('a')] += 1\n #将该字符串出现的次数序列转化位tuple作为键\n res_dict[tuple(count)].append(s)\n return res_dict.values()\n\n\n#5.二叉树的中序遍历\nclass Solution:\n def inorderTraversal(self, root: TreeNode):\n #解法一:递归解决 时间复杂度为O(n) n为节点个数 空间复杂度为O(h) h为树的深度\n # if not root:\n # return []\n # return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)\n\n #解法二:迭代 使用栈先进后出,中序遍历需要先找到最左边的叶子节点,然后采用左中右的方式进行出栈,指针指向当前出栈节点的右子节点\n if not root:\n return []\n\n #初始化当前指针,结果列表和栈\n cur,res,stack = root,[],[]\n while cur or stack:\n #找到最左边的叶子节点\n while cur:\n #依次将遇到的节点加入栈\n stack.append(cur)\n #指向下一个左子节点\n cur = cur.left\n #找到最左边的叶子节点后开始进行出栈操作,并记录出栈的节点\n tmp = stack.pop()\n #将栈顶元素加入结果列表\n res.append(tmp.val)\n #将当前指针指向栈顶节点的右子节点\n cur = tmp.right\n return res\n\n\n #6.二叉树的前序遍历\n def preorderTraversal(self, root: TreeNode):\n #解法一:递归解法\n # if not root:\n # return []\n # return [root.val] + preorderTraversal(root.left) + preorderTraversal(root.right)\n\n #解法二:迭代解法 加入根节点的值,然后依次将右子节点和左子节点入栈\n if not root:\n return []\n\n res,stack = [],[root]\n while stack:\n #获取栈顶元素\n cur = stack.pop()\n res.append(cur.val)\n #依次将右子节点和左子节点入栈\n if cur.right:\n stack.append(cur.right)\n if cur.left:\n stack.append(cur.left)\n return res\n\n#8.丑数\ndef nthUglyNumber(n):\n #使用动态规划 相当于从小到大合并三个数组\n dp = [1] * n\n a,b,c = 0,0,0\n for i in range(1,n):\n n2,n3,n5 = dp[a] * 2,dp[b] * 3,dp[c] * 5\n dp[i] = min(n2,n3,n5)\n if dp[i] == n2:\n a += 1\n if dp[i] == n3:\n b += 1\n if dp[i] == n5:\n c += 1\n return dp[-1]\n\n#9.前K个高频元素\ndef topKFrequent(nums, k):\n #解法一:使用python自带的计数器实现\n # return [x[0] for x in collections.Counter(nums).most_common(k)]\n\n #解法二:构建最小堆来实现\n dict1 = collections.Counter(nums)\n hp,res = [],[]\n for key in dict1.keys():\n #将频次和数添加到堆上 python构建的是最小堆 使用频次的相反数,频次最大的为根节点\n heapq.heappush(hp,(-dict1[key],key))\n\n #依次取出堆顶的K个元素\n for _ in range(k):\n res.append(heapq.heappop(hp)[1])\n return res\n\n","sub_path":"Week_02/week_02.py","file_name":"week_02.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"404078380","text":"#from __future__ import unicode_literals\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.http import HttpResponse\n#from django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import JsonResponse\nfrom django.core import serializers\nimport ast\nimport json\nfrom config.settings import *\nimport nltk\n\nclass DataBounding():\n\tdef __init__(self,sentence,pos_list):\n\t\tself.sentence \t\t\t= sentence\n\t\tself.postags = pos_list\n\n\n@csrf_exempt\ndef postag(request):\n\t#import pdb;pdb.set_trace()\n\tpos_list = list()\n\tcsrfContext = RequestContext(request)\n\tif request.method == 'POST':\n\n\t\ttry:\n\t\t\tjson_data = json.loads(request.body)\n\t\t\ttext = json_data.get('sentence')\n\t\t\t\n\t\texcept:\n\t\t\ttext = []\n\t\tif text:\n\t\t\tpos_list = nltk.pos_tag(nltk.word_tokenize(text))\n\t\t\tdataBounding = DataBounding(text,pos_list)\n\t\t\tresponse_string = ''\n\t\t\tfor item in pos_list:\n\t\t\t\tvalue = ' '+'Token : '+str(item[0].encode('utf8'))+' | POS Tag : '+str(item[1])+'
    '\n\t\t\t\tresponse_string += value\n\t\t\tstring_json ={}\n\t\t\tstring_json['postags'] = response_string\n\n\t\telse:\n\t\t\tpass\n\t\t\t#extracted_list.update({'Error':'Error occured at service response.'})\n\treturn JsonResponse(string_json,safe=False)","sub_path":"textanalytics/server/postag/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"66788687","text":"# 读取Excel文件\n\nimport xlrd\n\ndef excel(path):\n try:\n ExcelFile = xlrd.open_workbook(path)\n except Exception as e:\n return\n\n data = ExcelFile.sheet_by_name(ExcelFile.sheet_names()[0])\n title = data.row_values(0)\n for i in range(len(title)):\n if title[i].startswith('2'):\n if len(title[i]) == 8:\n title[i] = title[i].replace('.', '-0')\n else:\n title[i] = title[i].replace('.', '-')\n title[i] = title[i][0:5] +'0' +title[i][5:]\n\n re = {}\n buff = {}\n for i in range(1, (data.nrows-1)):\n for index, j in enumerate(data.row_values(i)[2:]):\n if j == '总数':\n break\n if j!= ' ' and j!='':\n buff[title[index+2]] = int(j)\n else:\n buff[title[index + 2]] = 0\n\n if buff:\n re[data.row_values(i)[0]] = buff\n buff = {}\n return re\n\n# f = read_excel('../files/2018.7.30.xls')\n\n# r = excel('nums.xlsx')\n# print(len(r))\n# print(r)\n\n# def put(request):\n# if request.method == 'GET':\n# data = excel('nums.xlsx')\n# for i in data:\n# for j in data[i]:\n# print(i,j,data[i][j])\n# models.WebsiteInputdata.objects.create(username=i, time=j, data=data[i][j])\n# # print(data)\n# return HttpResponse(\"OK\")","sub_path":"service_input.py","file_name":"service_input.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"599687455","text":"import functools\n\nfrom sqlalchemy.orm import Query\n\n\ndef _serialize(obj, pagination=False, filtering=False, sorting=False, type_=None):\n\n if isinstance(obj, Query):\n\n if not type_:\n raise ValueError('The `model_class` keyword argument is not provided')\n\n if filtering:\n obj = type_.filter_by_request(obj)\n\n if sorting:\n obj = type_.sort_by_request(obj)\n\n if pagination:\n obj = type_.paginate_by_request(obj)\n\n obj = [o.to_dict() for o in obj]\n\n return obj\n\n\ndef jsonify(*a, **options):\n\n def decorator(func):\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n return _serialize(func(*args, **kwargs), **options)\n\n return wrapper\n\n return decorator(a[0]) if a and callable(a[0]) else decorator\n","sub_path":"restfulpy/marshalling.py","file_name":"marshalling.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"259900754","text":"import requests\r\nimport threading\r\nimport xlrd #输出文件\r\nfrom xlwt import * #输入文件\r\nimport hashlib\r\n\r\nbook = xlrd.open_workbook(r\"C:\\Users\\阿苗\\Desktop\\报告\\网站状态码.xls\") #打开本地目录\r\nsheet = book.sheet_by_name(u'Sheet1') #列表\r\nbiao = [sheet.col_values(1)][0]\r\nming = [sheet.col_values(0)][0]\r\nbook_n = Workbook(encoding='utf-8') #打开一个新文件,以中文写入\r\nsheet_n = book_n.add_sheet('Sheet1') #创建一个新表格\r\n\r\ndef duo(s):\r\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}\r\n for i in range(s*19,(s+1)*19):\r\n try:\r\n response = requests.get(biao[i],headers=header,timeout=20)\r\n zhuangtai = response.status_code\r\n a = ''\r\n print(zhuangtai)\r\n if zhuangtai != 404 and zhuangtai != 403:\r\n response.encoding = 'utf-8'\r\n response = response.text\r\n # 加密\r\n md = hashlib.md5() # 构造一个MD5\r\n md.update(response.encode())\r\n a = md.hexdigest()\r\n print(a)\r\n #按位置写入\r\n for r in range(0, 4):\r\n if r == 0:\r\n sheet_n.write(i, r, ming[i])\r\n elif r == 1:\r\n sheet_n.write(i, r, biao[i])\r\n elif r == 2:\r\n sheet_n.write(i, r, str(zhuangtai))\r\n elif r == 3:\r\n sheet_n.write(i, r, str(a))\r\n book_n.save('C:\\python\\d\\md.xls') #保存地址\r\n\r\n except requests.exceptions.ConnectionError as j: #报错处理\r\n print('Error',j.args)\r\n\r\n\r\n\r\ndef main():\r\n for s in range(6): # 6个线程\r\n t = threading.Thread(target=duo, args=(s,))\r\n t.start()\r\n\r\n\r\nmain()","sub_path":"网页md5值.py","file_name":"网页md5值.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"161810285","text":"import numpy as np\nfrom tqdm import tqdm\nfrom utils import *\nfrom loss import *\nimport warnings\nimport os\nimport numpy as np\nwarnings.filterwarnings(\"ignore\")\n# from IQA_pytorch import SSIM\nfrom torch.utils.data import TensorDataset, DataLoader\nimport time\n\nfrom model.IMUTransformer import *\nfrom model.DenoiseRNN import *\n\ntorch.multiprocessing.set_start_method('spawn', force=True)\n\nimport visdom\n\ndef train():\n #window_size = 200 # 200\n src_win_sz = 200\n tgt_win_sz = 2\n hidden_dim = 256\n\n num_epochs = 500\n batch_size = 256\n lr_drop = 300\n learning_rate = 1e-4\n weight_decay = 1e-5\n\n dtype = torch.FloatTensor\n\n vis = visdom.Visdom()\n plot_all = vis.line(Y=torch.tensor([0]), X=torch.tensor([0]), opts=dict(title='All Loss'))\n\n start = time.time()\n print(\"Training\")\n #model definition\n IMUTransformer = IMU_Transformer_noisy(window_sz=src_win_sz, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6, dropout=0.2).cuda()\n IMUTransformer = nn.DataParallel(IMUTransformer).cuda()\n optimizer_IMU = torch.optim.AdamW(IMUTransformer.parameters(), lr=learning_rate, weight_decay=weight_decay)\n lr_scheduler_optimizer1 = torch.optim.lr_scheduler.StepLR(optimizer_IMU, lr_drop)\n\n DenoiseRNN = Denoise_RNN(inp_sz=256, hidden_sz=2, num_layers=4, dropout=0.1, bidirectional=True)\n DenoiseRNN = nn.DataParallel(DenoiseRNN).cuda()\n optimizer_Denoise = torch.optim.AdamW(DenoiseRNN.parameters(), lr=learning_rate, weight_decay=weight_decay)\n lr_scheduler_optimizer2 = torch.optim.lr_scheduler.StepLR(optimizer_Denoise, lr_drop)\n\n #load ckpt\n load_ckpt = \"/home/jsk/IMUlocalization/ckpt/train_model.pth\"\n if os.path.exists(load_ckpt):\n print(\"-----Loading Checkpoint-----\")\n checkpoint = torch.load(load_ckpt)\n IMUTransformer.module.load_state_dict(checkpoint['IMUTransformer'])\n DenoiseRNN.module.load_state_dict(checkpoint['DenoiseRNN'])\n optimizer_IMU.load_state_dict(checkpoint['optimizer_IMU'])\n optimizer_Denoise.load_state_dict(checkpoint['optimizer_Denoise'])\n lr_scheduler_optimizer1.load_state_dict(checkpoint['lr_scheduler_optimizer1'])\n lr_scheduler_optimizer2.load_state_dict(checkpoint['lr_scheduler_optimizer2'])\n\n dataset = my_dataset_gyroz(window_size=src_win_sz)\n train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, num_workers=0, pin_memory=True)\n get_loss = pos_loss()\n\n #SaveLossTxt = open(\"MyLoss.txt\", 'w')\n\n for epoch in tqdm(range(num_epochs)):\n running_loss = 0\n for i, data in enumerate(tqdm(train_loader)):\n cur_imu, cur_trg = data #(b,10,3)\n\n #src = cur_imu.cuda()*9.8 #m/s^2\n src = cur_imu.cuda() #m/s^2\n trg = cur_trg[:, cur_trg.shape[1]-1-tgt_win_sz:cur_trg.shape[1]-1, :].cuda() * 0.001 #mm -> m\n gt = cur_trg[:, cur_trg.shape[1]-tgt_win_sz:cur_trg.shape[1], :].cuda() * 0.001 #mm -> m\n\n noisy_xy = IMUTransformer(src, trg) #(2,256)\n p_noisy_xy = noisy_xy.permute(1, 0, 2)\n xy_pos = DenoiseRNN(p_noisy_xy)\n\n loss = get_loss(xy_pos, gt)\n print(\"My loss\", '%.8f' % loss.item())\n\n optimizer_IMU.zero_grad()\n loss.backward()\n #loss.backward()\n torch.autograd.set_detect_anomaly(True)\n optimizer_IMU.step()\n\n running_loss = running_loss + loss\n\n #np.savetxt(SaveLossTxt, running_loss)\n torch.save({\n 'IMUTransformer': IMUTransformer.module.state_dict(),\n 'optimizer_IMU': optimizer_IMU.state_dict(),\n 'lr_scheduler_optimizer1': lr_scheduler_optimizer1.state_dict(),\n }, \"/home/jsk/IMUlocalization/ckpt/train_10_square_dropout0.3/\" + \"js_ans2_\" + str(epoch) + \".pth\")\n\n vis.line(Y=[running_loss.detach().cpu().numpy()], X=np.array([epoch]), win=plot_all, update='append')\n print('epoch [{}/{}], loss:{:.4f} '.format(epoch + 1, num_epochs, running_loss))\n\ndef test():\n print(\"Testing\")\n src_win_sz = 200\n tgt_win_sz = 2\n\n GTtxt = open(\"GT.txt\", 'w')\n XYtxt = open(\"XY.txt\", 'w')\n\n #model definition\n IMUTransformer = IMU_Transformer(window_sz=src_win_sz, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6, dropout=0).cuda()\n #IMUTransformer = IMU_Transformer(window_sz=window_size, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6, dropout=False).cuda()\n IMUTransformer = nn.DataParallel(IMUTransformer).cuda()\n\n #MyCKPT = \"/home/jsk/IMUlocalization/ckpt/train_10_square_dropout0.2/js_ans2_64.pth\"\n #MyCKPT = \"/home/jsk/IMUlocalization/ckpt/train_10_square_dropout0.2/js_ans2_143.pth\"\n MyCKPT = \"/home/jsk/IMUlocalization/ckpt/train_10_square_dropout0.3/js_ans2_64.pth\"\n #MyCKPT = \"/home/jsk/IMUlocalization/ckpt/train_5_test_1.pth\"\n #MyCKPT = \"/home/jsk/IMUlocalization/ckpt/train_5_test_1_square/js_ans2_40.pth\"\n #checkpoint save\n #if os.path.exists(\"/home/jsk/IMUlocalization/ckpt/train_5_test_1.pth\"):\n #if os.path.exists(\"/home/jsk/IMUlocalization/ckpt/train_5_test_1_square/js_ans2_100.pth\"):\n #if os.path.exists(\"/home/jsk/IMUlocalization/ckpt/train_10_square/js_ans2_85.pth\"):\n if os.path.exists(MyCKPT):\n print(\"-----Loading Checkpoint-----\")\n print(MyCKPT)\n #checkpoint = torch.load(\"/home/jsk/IMUlocalization/ckpt/train_5_test_1.pth\")\n #checkpoint = torch.load(\"/home/jsk/IMUlocalization/ckpt/train_5_test_1_square/js_ans2_100.pth\")\n checkpoint = torch.load(MyCKPT)\n IMUTransformer.module.load_state_dict(checkpoint['IMUTransformer'])\n\n #imu_file = \"/home/jsk/IMUlocalization/data/test/IMU/imu_1cycle_01.txt\"\n #vicon_file = \"/home/jsk/IMUlocalization/data/test/Vicon/vicon_1cycle_01.txt\"\n\n #imu_file = \"/home/jsk/IMUlocalization/data_5_1/test/IMU/imu_1cycle_01.txt\"\n #vicon_file = \"/home/jsk/IMUlocalization/data_5_1/test/Vicon/vicon_1cycle_01.txt\"\n\n #imu_file = \"/home/jsk/IMUlocalization/triangle_data/test/IMU/imu_tri_2cycle_04.txt\"\n #vicon_file = \"/home/jsk/IMUlocalization/triangle_data/test/Vicon/vicon_tri_2cycle_04.txt\"\n\n #imu_file = \"/home/jsk/IMUlocalization/pattern_data/test/IMU/imu_pattern_02.txt\"\n #vicon_file = \"/home/jsk/IMUlocalization/pattern_data/test/Vicon/vicon_pattern_02.txt\"\n\n imu_file = \"/home/jsk/IMUlocalization/data_1_5/test/IMU/imu_5cycle_01.txt\"\n vicon_file = \"/home/jsk/IMUlocalization/data_1_5/test/Vicon/vicon_5cycle_01.txt\"\n\n #dataset = my_test_dataset(imu_file=imu_file, vicon_file=vicon_file, window_size=window_size)\n #dataset = my_test_dataset_modified(imu_file=imu_file, vicon_file=vicon_file, window_size=window_size)\n dataset = my_test_dataset_gyroz(imu_file=imu_file, vicon_file=vicon_file, window_size=src_win_sz)\n #dataset = my_test_dataset_modified_inp6(imu_file=imu_file, vicon_file=vicon_file, window_size=window_size)\n #dataset = my_dataset(imu_file=imu_file, vicon_file=vicon_file, window_size=window_size)\n test_loader = DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0, pin_memory=True)\n\n test_loss = 0\n final_gt = []\n final_xy = []\n get_loss = pos_loss()\n\n with torch.no_grad():\n for i, data in enumerate(tqdm(test_loader)):\n cur_imu, cur_trg = data\n\n #src = cur_imu.cuda()\n #trg = cur_trg[:, 0:cur_trg.shape[1] - 1, :].cuda() * 0.001 # mm -> m (1~199)\n #gt = cur_trg[:, 1:cur_trg.shape[1], :].cuda() * 0.001 # mm -> m (2~200)\n\n src = cur_imu.cuda() # m/s^2\n trg = cur_trg[:, cur_trg.shape[1] - 1 - tgt_win_sz:cur_trg.shape[1] - 1, :].cuda() * 0.001 # mm -> m\n gt = cur_trg[:, cur_trg.shape[1] - tgt_win_sz:cur_trg.shape[1], :].cuda() * 0.001 # mm -> m\n\n #xy_pos = IMUTransformer(src, trg)\n #xy_pos_pre = torch.cat([trg[:, 1:trg.shape[1], :], xy_pos[:, -1, :].unsqueeze(1)], dim=1)\n\n if(i==0):\n xy_pos = IMUTransformer(src, trg)\n #xy_pos_pre = xy_pos\n xy_pos_pre = torch.cat([trg[:, 1:trg.shape[1], :], xy_pos[:, -1, :].unsqueeze(1)], dim=1)\n\n else:\n xy_pos = IMUTransformer(src, xy_pos_pre)\n xy_pos_pre = torch.cat([xy_pos_pre[:, 1:xy_pos_pre.shape[1], :], xy_pos[:, -1, :].unsqueeze(1)], dim=1)\n #xy_pos_pre = xy_pos\n\n #xy_pos_pre = IMUTransformer(src, trg)\n #xy_pos_pre = xy_pos\n loss = get_loss(xy_pos_pre, gt)\n #loss = get_loss(xy_pos, gt)\n print(\"My loss\", '%.8f' % loss.item())\n\n if (i == 0):\n final_gt.append(gt)\n final_xy.append(xy_pos_pre)\n else:\n final_gt.append(gt[:, -1, :])\n final_xy.append(xy_pos_pre[:, -1, :])\n\n #result = '{:.4f} \\t{:.4f} \\t{:.4f}\\t{:.4f} \\t{:.4f}\\t{:.4f}\\n'.format()\n\n for j in range(len(final_gt)):\n final_gt[j] = final_gt[j].detach().cpu().numpy()\n final_xy[j] = final_xy[j].detach().cpu().numpy()\n\n if(j==0):\n np.savetxt(GTtxt, final_gt[j][0])\n np.savetxt(XYtxt, final_xy[j][0])\n else:\n np.savetxt(GTtxt, final_gt[j])\n #np.savetxt(GTtxt, final_gt[j])\n np.savetxt(XYtxt, final_xy[j])\n #np.savetxt(XYtxt, final_xy[j])\n\n print(\"Test Finished Let's check the result!\")\n\nif __name__=='__main__':\n torch.cuda.empty_cache()\n\n print(\"IMU localization with Transformer\")\n #train()\n test()","sub_path":"train/train_RNN.py","file_name":"train_RNN.py","file_ext":"py","file_size_in_byte":9599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"537261555","text":"import cv2\nimport numpy as np\nimport libIpxCameraApiPy as IpxCameraApiPy\n\n\nclass Camera:\n def __init__(self):\n \"\"\"\n Camera class for initializing, connecting to and operating the camera\n \"\"\"\n\n # Initiating IpxCamera and connecting to device on network\n self.ipx_system = IpxCameraApiPy.PyIpxSystem()\n self.camera = self.__select_device()\n self.params = self.camera.GetCameraParameters()\n\n # Recording video\n # self._fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n # self._out = cv2.VideoWriter('sample_video.mp4', 0x7634706d, 10.0, (img_width, img_height), 0)\n\n def __select_device(self):\n \"\"\"\n Select camera device to connect to\n \"\"\"\n network_interfaces = self.ipx_system.GetInterfaceList()\n active_devices = list()\n dev_id = 0\n for interface in network_interfaces:\n devices = interface.GetDeviceInfoList()\n for dev in devices:\n active_devices.append(dev)\n print('[', dev_id, '] ', dev.GetModel(), 'at', interface.GetDescription())\n dev_id += 1\n if not network_interfaces or not active_devices:\n print('No devices found')\n return None\n\n while True:\n dv_select = input('Please select the camera number to connect to: \\n')\n if not dv_select.isnumeric():\n print('Please input a valid integer \\n')\n continue\n dv_select = int(dv_select)\n if dv_select > dev_id:\n print(f'No device with ID: {dv_select} \\n')\n continue\n return self.__establish_connection(active_devices[dv_select])\n\n @staticmethod\n def __establish_connection(device):\n \"\"\"\n Connects to camera using device info passed\n :param obj device: Device object to connect to\n \"\"\"\n print('connecting to ', device.GetDisplayName())\n device = IpxCameraApiPy.PyIpxCreateDevice(device)\n return device if device.GetNumStreams() >= 1 else None\n\n def start_acquisition(self):\n \"\"\"\n Starts capturing images from the camera\n \"\"\"\n try:\n img_height = self.params.GetInt('Height').GetValue()[1]\n img_width = self.params.GetInt('Width').GetValue()[1]\n\n camera_model = self.camera.GetInfo().GetModel()\n\n # create Stream object\n stream = self.camera.GetStreamByIndex(0)\n print(camera_model, ': Stream created')\n\n # create buffers queue\n buf_size = stream.GetBufferSize()\n min_num_buffers = stream.GetMinNumBuffers()\n sb_lst = [];\n for x in range(min_num_buffers + 1):\n sb_lst.append(stream.CreateBuffer(buf_size))\n print(camera_model, ': Buffers queue created ')\n\n self.params.SetIntegerValue(\"TLParamsLocked\", 1)\n stream.StartAcquisition()\n self.params.ExecuteCommand(\"AcquisitionStart\")\n\n while True:\n buffer = stream.GetBuffer(-1)\n image = np.frombuffer(buffer.GetBufferPtr(), dtype=np.uint8).reshape((img_height,\n img_width))\n\n # Use DL to check if the current frame has start of a truck rail\n # If it does, start recording images\n\n cv2.imshow('Cam Stream', image)\n # self._out.write(image)\n cv2.waitKey(1)\n stream.QueueBuffer(buffer)\n\n except KeyboardInterrupt:\n # self._out.release()\n if self.params.ExecuteCommand(\"AcquisitionStop\") != 0:\n self.params.ExecuteCommand(\"AcquisitionAbort\")\n stream.StopAcquisition(1);\n self.params.SetIntegerValue(\"TLParamsLocked\", 0)\n stream.FlushBuffers(stream.Flush_AllDiscard)\n for b in sb_lst:\n stream.RevokeBuffer(b);\n\n # release the stream and camera\n print(camera_model, ': Closing stream')\n stream.Release()\n\n return 0\n\n\ncam = Camera()\n\ncam.params.SetIntegerValue(\"Width\", 1240)\ncam.params.SetIntegerValue(\"Height\", 720)\ncam.params.SetEnumValue(\"ExposureMode\", 2)\ncam.params.SetFloatValue(\"ExposureTime\", 100000.000000)\ncam.params.SetBooleanValue(\"AcquisitionFrameRateEnable\", True)\ncam.params.SetFloatValue(\"AcquisitionFrameRate\", 10)\n\ncam.start_acquisition()","sub_path":"cam_control.py","file_name":"cam_control.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"364367182","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.0'\n\nsetup(name='deploying-openstack-slideshow',\n version=version,\n description=\"\",\n author='Florent',\n author_email='florent@toopy.org',\n url='toopy.org',\n license='MIT',\n packages=find_packages('.'),\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"328651054","text":"# Return a left rotation n times\r\nuseless,n=input().split()\r\nn=int(n)\r\narr=[int(x) for x in input().split()]\r\n\r\n#for x in range(int(n)):\r\n# arr=arr[1:]+arr[:1]\r\n# #print(arr)\r\nprint(*arr[n:]+arr[:n],sep=' ')\r\n ","sub_path":"Datastructures/Arrays/array-left-rotation.py","file_name":"array-left-rotation.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"253178450","text":"\"\"\"\r\n#简单定义一个函数 、 传递列表 、禁止函数修改列表 、传递任意数量的实参 、使用任意数量的关键字实参(函数,键值对)\r\n导入函数模块 函数默认值\r\n\"\"\"\r\n\r\n# #简单定义一个函数\r\n\"\"\"\r\ndef greet_user(username='q',age='w'): #给形参设置默认值的时候,等号两边不要有空格\r\n print(username.title()+\" is \"+age+\" years old\")\r\n all=username+' '+age\r\n return all\r\n\r\ngreet_user(age='18',username='steve') #字符,可以改变顺序\r\n\r\nA=greet_user(age='18',username='steve') #打印返回值\r\nprint(A)\r\n\"\"\"\r\n\r\n# 传递列表 结果是Hello Aa !Hello Bb !Hello Cc ! 相当于遍历\r\n\"\"\"\r\ndef greet(names):\r\n for name in names:\r\n mas=\"Hello \"+name.title()+\" !\"\r\n print(mas)\r\nusernames=['aa','bb','cc']\r\ngreet(usernames)\r\n\"\"\"\r\n\r\n# 禁止函数修改列表 (将列表的副本传递给函数)\r\n\"\"\"\r\ndef show_magicians(new_magicians): # 打印函数\r\n #显示打印好的元素\r\n print(\"\\nThe following : \")\r\n for magician in new_magicians: # 遍历列表\r\n print(magician.title())\r\n\r\n\r\ndef make_great(magicians, new_magicians): # 对列表修改的函数\r\n while magicians:\r\n current_magician = magicians.pop() # 删除原列表中的元素\r\n current_magician = \"The Great \" + current_magician\r\n new_magicians.append(current_magician)\r\n\r\n\r\nmagicians = ['tom', 'jack', 'marry'] # 创建魔术师列表\r\nnew_magicians = [] # 用于保存修改后的列表元素\r\nmake_great(magicians[:], new_magicians) # 传递列表副本 #切片表示法[:]穿件列表的副本\r\nshow_magicians(new_magicians) # 调用show_magician()函数\r\nshow_magicians(magicians)\r\n\"\"\"\r\n\r\n# 传递任意数量的实参\r\n\"\"\"\r\ndef make_pizza(*toppings): #形参名*toppings中的星号是让Python穿件一个名为toppings的元组,并将所收到的所有值都封装带这个元组中\r\n for topping in toppings: \r\n print(\"-\"+topping) \r\nmake_pizza('abc') \r\nmake_pizza('a a','b b','c c') #这个样子表示def make_pizza(size,*toppings):\r\n\"\"\"\r\n\r\n# #使用任意数量的关键字实参(函数,键值对)\r\n\"\"\"\r\ndef build_profile(first, last, **user_info): #**user_info表示键值对\r\n #Build a dictionary containing everything we know about a user.\r\n profile = {}\r\n profile['first_name'] = first #打印的时候用'first_name'\r\n profile['last_name'] = last\r\n for key, value in user_info.items():\r\n profile[key] = value\r\n return profile\r\n\r\nuser_profile = build_profile('albert', 'einstein',\r\n location='princeton',\r\n field='physics')\r\nprint(user_profile) #结果是{'last_name': 'einstein',\r\n #'location': 'princeton','field': 'physics',\r\n # 'first_name': 'albert'}\r\n\"\"\"\r\n\r\n# #导入函数模块\r\n\"\"\"\r\nimport _08my_sample #导入扩展名为.py的文件(导入的是_08my_sample整个模块)\r\n_08my_sample.Write('xiaoming', '16') #必须加单引号\r\n\r\n\r\nfrom _08my_sample import Write #导入特定的函数\r\nWrite('xiaoming','17')\r\n\r\nfrom _08my_sample import Write as A #导入特定的函数 并改名\r\nA('xiaoming','18')\r\n\r\n#如果导入的.py的文件里面有多个的函数,可以from my_sample import a,b,c\r\n#(a,b,c都是函数),这个样子来导入函数\r\n\"\"\"\r\n\r\n\r\n# 函数默认值\r\ndef a(ma=\"ma\"):\r\n b = ma\r\n return b\r\n\r\n\r\nprint(a())\r\nprint(a(\"a\"))","sub_path":"_08function_hanshu.py","file_name":"_08function_hanshu.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"41250649","text":"\n\nfrom xai.brain.wordbase.nouns._crooner import _CROONER\n\n#calss header\nclass _CROONERS(_CROONER, ):\n\tdef __init__(self,): \n\t\t_CROONER.__init__(self)\n\t\tself.name = \"CROONERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"crooner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_crooners.py","file_name":"_crooners.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"494573581","text":"import socket\nimport threading\nimport time\nimport group\nimport sys\n\nHOST = str(socket.gethostbyname(socket.gethostname()))\nPORT = 44444\nIS_RUNNING = True\nGROUPS = []\nKNOWN_CLIENTS = []\n\ndef main():\n print(\"initializing socket\")\n SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"trying to bind\")\n try:\n SOCK.bind((HOST, PORT))\n print(\"bound!\")\n except Exception as msg:\n print(\"Please run this server as root.\")\n print(\"Bind failed. Error Code : \" + str(msg[0]) + \" Message \" + msg[1])\n SOCK.close()\n sys.exit()\n print(\"listening\")\n SOCK.listen(10)\n while IS_RUNNING:\n conn, addr = SOCK.accept()\n print(\"Connected to \" + addr[0] + \":\" + str(addr[1]))\n client = {\n \"ADDR\" : addr,\n \"CONN\" : conn\n }\n KNOWN_CLIENTS.append(client)\n thread = threading.Thread(None, listen_for_messages, None, (client,))\n thread.start()\n\ndef listen_for_messages(client):\n try:\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n while IS_RUNNING:\n data_str = recv_to_end(conn)\n msg_arr = data_str.split(\"\\r\\n\")\n if msg_arr[0] == \"dslp/1.2\":\n if msg_arr[1] == \"request time\":\n print(\"--- request time\")\n client_response_time(client)\n elif msg_arr[1] == \"group join\":\n client_group_join(msg_arr[2], client)\n print(\"--- \" + str(client[\"ADDR\"]) + \" group join \" + msg_arr[2])\n elif msg_arr[1] == \"group leave\":\n client_group_leave(msg_arr[2], client)\n print(\"--- \" + str(client[\"ADDR\"]) + \" group leave \" + msg_arr[2])\n elif msg_arr[1] == \"group notify\":\n client_group_notify(msg_arr[2], msg_arr[3], client)\n print(\"--- \" + str(client[\"ADDR\"]) + \" group notify \" + msg_arr[2])\n elif msg_arr[1] == \"peer notify\":\n client_peer_notify(msg_arr[2], msg_arr[3], client)\n print(\"--- \" + str(client[\"ADDR\"]) + \" peer notify \" + msg_arr[2])\n else:\n send_error(\"Not a valid message type.\", client)\n else:\n send_error(\"Invalid Protocol. Protocol used: \" + msg_arr[0], client)\n # connection with client broke up\n except BrokenPipeError as msg:\n client[\"CONN\"].close()\n # remove clients from known clients\n for known_client in KNOWN_CLIENTS:\n if client[\"ADDR\"] == known_client[\"ADDR\"]:\n KNOWN_CLIENTS.remove(client)\n # remove client from groups\n for group in GROUPS:\n group.remove_member(client[\"CONN\"], client[\"ADDR\"])\n # kill client thread\n print(\"client \" + str(client[\"ADDR\"]) + \" disconnected.\")\n sys.exit()\n\ndef recv_to_end(CONN):\n ended = False\n all_data_str = \"\"\n while not ended:\n data = bytearray()\n try:\n data = CONN.recv(4096)\n except:\n continue\n #print(\"No new packages.\")\n data_str = data.decode(\"utf-8\")\n all_data_str += data_str\n protocol_lines = data_str.split(\"\\r\\n\")\n for line in protocol_lines:\n if line == (\"dslp/end\"):\n ended = True\n break\n return all_data_str\n\ndef client_response_time(client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n date_time = time.time()\n # yyyy-MM-dd'T'HH:mm:ssX\n date_str = time.strftime(\"%Y-%m-%dT%H:%M:%S%Z\", time.gmtime(date_time))\n message = \"dslp/1.2\\r\\n\" + \"response time\\r\\n\" + date_str + \"\\r\\n\" + \"dslp/end\\r\\n\"\n conn.sendall(message.encode(\"utf-8\"))\n\ndef client_group_join(group_name, client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n group_exists = False\n group_is_member = False\n group_index = 0\n for group_i in GROUPS:\n if group_name == group_i.get_group_name():\n group_exists = True\n for member in group_i.get_members():\n if conn == member[\"CONN\"]:\n group_is_member = True\n break\n if group_is_member == False:\n group_i.add_member(conn, addr)\n break\n if not group_exists:\n new_group = group.group(group_name)\n new_group.add_member(conn, addr)\n GROUPS.append(new_group)\n if group_is_member:\n message = \"User is already member of this group. You can't join a group that you're already a member of.\"\n send_error(message, client)\n\n\"\"\"\nif the group exists,\nthe client is known,\nthe client is member of the group,\nnotify all other clients of this group with the message attached\n\"\"\"\ndef client_group_leave(group_name, client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n group_exists = False\n group_is_member = False\n group_index = 0\n for group_i in GROUPS:\n if group_name == group_i.get_group_name():\n group_exists = True\n for member in group_i.get_members():\n if conn == member[\"CONN\"]:\n group_is_member = True\n group_i.remove_member(conn, addr)\n break\n if not group_exists:\n message = \"The specified group doesn't exist.\"\n send_error(message, client)\n if not group_is_member:\n message = \"User is not member of the specified group. You can't leave a group that you're not a member of.\"\n send_error(message, client)\n\n\"\"\"\nif the client is member of the group,\nnotify all other clients of this group with the message attached\n\"\"\"\ndef client_group_notify(group_name, msg, client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n group_exists = False\n group_is_member = False\n for group_i in GROUPS:\n\n if group_name == group_i.get_group_name():\n group_exists = True\n for member in group_i.get_members():\n if conn == member[\"CONN\"]:\n print(\"-|- user is member of the group!\")\n group_is_member = True\n group_i.notify(msg)\n if not group_exists:\n message = \"The specified group doesn't exist\"\n send_error(message, client)\n if not group_is_member:\n message = \"User is not member of the specified group. You can't send a message to a group that you're not a member of.\"\n send_error(message, client)\n\ndef client_peer_notify(peer, msg, client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n client_is_known = False\n IS_RUNNING = False\n for client_i in KNOWN_CLIENTS:\n if addr == client_i[\"ADDR\"]:\n client_is_known = True\n message = \"dslp/1.2\\r\\n\" + \"peer notify\\r\\n\" + peer + \"\\r\\n\" + msg + \"\\r\\n\" + \"dslp/end\\r\\n\"\n client_i[\"CONN\"].sendall(message.encode(\"utf-8\"))\n if not client_is_known:\n message = \"The peer you're trying to send a message to has not connected to the server yet.\"\n send_error(message, client)\n\ndef send_error(error, client):\n conn = client[\"CONN\"]\n addr = client[\"ADDR\"]\n message = \"dslp/1.2\\r\\n\" + \"error\\r\\n\" + str(error) + \"\\r\\n\" + \"dslp/end\\r\\n\"\n conn.sendall(message.encode(\"utf-8\"))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"task10/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"53765979","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nSoapbox is a SOAP library for Python capable of generating Python modules from\nWSDL documents and providing a dispatcher for the Django framework.\n'''\n\n\nfrom setuptools import setup, find_packages\n\nimport soapbox\n\n\ndef get_requires(filename):\n return [r.strip() for r in open(filename).readlines() if r[:3] != '-r ' and r.strip()]\n\n\nsetup(\n name='soapbox-bsd',\n version=soapbox.__version__,\n author=soapbox.__author__,\n author_email=soapbox.__email__,\n url='https://github.com/FelixSchwarz/soapbox-bsd',\n description='A SOAP library for Python',\n long_description=open('README.md').read() + open('CHANGES').read() + open('TODO').read(),\n download_url='',\n license='New BSD License',\n packages=find_packages(exclude=(\"examples\", \"tests\",)),\n include_package_data=True,\n install_requires=get_requires('requirements.txt'),\n tests_require=get_requires('dev_requirements.txt'),\n test_suite='nose.collector',\n entry_points={\n 'console_scripts': [\n 'py2wsdl=soapbox.py2wsdl:main',\n 'py2xsd=soapbox.py2xsd:main',\n 'wsdl2py=soapbox.wsdl2py:main',\n 'xsd2py=soapbox.xsd2py:main',\n ],\n },\n platforms=['OS Independent'],\n keywords=['SOAP', 'WSDL', 'web service'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"176845349","text":"#!/usr/bin/env python\n# Copyright (C) 2012-2013 Bastian Kleineidam\n\"\"\"\nScript to get a list of creators.com comics and save the info in a JSON file for further processing.\n\"\"\"\nfrom __future__ import print_function\nimport re\nimport sys\nimport os\nimport requests\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\nfrom dosagelib.util import getPageContent, asciify, unescape, tagre\nfrom scriptutil import contains_case_insensitive, capfirst, save_result, load_result, truncate_name\n\njson_file = __file__.replace(\".py\", \".json\")\n\nurl_matcher = re.compile(tagre(\"a\", \"href\", r'(/comics/[^/]+)\\.html') + r'([^<]+)')\n\n# names of comics to exclude\nexclude_comics = [\n]\n\ndef handle_url(url, session, res):\n \"\"\"Parse one search result page.\"\"\"\n print(\"Parsing\", url, file=sys.stderr)\n try:\n data, baseUrl = getPageContent(url, session)\n except IOError as msg:\n print(\"ERROR:\", msg, file=sys.stderr)\n return\n for match in url_matcher.finditer(data):\n url = match.group(1)\n name = unescape(match.group(2))\n name = asciify(name.replace('&', 'And').replace('@', 'At'))\n name = capfirst(name)\n if name in exclude_comics:\n continue\n if contains_case_insensitive(res, name):\n # we cannot handle two comics that only differ in case\n print(\"INFO: skipping possible duplicate\", repr(name), file=sys.stderr)\n continue\n res[name] = url\n\n\ndef get_results():\n \"\"\"Parse all search result pages.\"\"\"\n # store info in a dictionary {name -> shortname}\n res = {}\n session = requests.Session()\n handle_url('http://www.creators.com/comics/cat-seeall.html', session, res)\n save_result(res, json_file)\n\n\ndef print_results(args):\n \"\"\"Print comics.\"\"\"\n for name, url in sorted(load_result(json_file).items()):\n if name in exclude_comics:\n continue\n print(\"add(%r, %r)\" % (str(truncate_name(name)), str(url)))\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n print_results(sys.argv[1:])\n else:\n get_results()\n","sub_path":"scripts/creators.py","file_name":"creators.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438936809","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom models import *\nfrom copy import deepcopy\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n# prepare raw data\nfrom common.PSNR import PSNR\nfrom common.SSIM import SSIM\n\ntransform_train = transforms.Compose([\n # noise train datasets\n # transforms.RandomCrop(32, padding=4),\n # transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n # normalize each channel value .Normalize([channel1.mean, ..., ...], [channel1.std, ..., ...])\n # transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n # transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\nBATCH = 100\ntrainset = torchvision.datasets.CIFAR10(root='../data', train=True, download=True, transform=transform_train)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH, shuffle=False, num_workers=2, drop_last = True)\n\ntestset = torchvision.datasets.CIFAR10(root='../data', train=False, download=True, transform=transform_test)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=BATCH, shuffle=False, num_workers=2, drop_last = True)\nclass_ifiar = [['vgg19']]\n\ndef load_classifiar(classifiar_name = 'vgg19'):\n if classifiar_name not in class_ifiar:\n TypeError('classifiar not exist')\n if classifiar_name == 'vgg19':\n net = torch.load('../checkpoint/vgg19_net.pkl')\n return net\n\nclass Env():\n def __init__(self, train_dataset = trainloader, test_dataset = testloader, mode = 'train', classifier_name = 'vgg19'):\n self.train_data = list(train_dataset)\n self.test_data = list(test_dataset)\n self._data_mode = mode\n self.classifier = load_classifiar(classifier_name)\n\n def reset(self):\n if self._data_mode == 'train':\n batch_index = np.random.randint(low=0,high=len(self.train_data))\n extract_index = np.random.randint(low=0,high=BATCH)\n self._state, self._ground_truth_label = self.train_data[batch_index]\n self._ground_truth_label = self._ground_truth_label[extract_index]\n self._state = self._state[extract_index]\n self.ground_truth_image = deepcopy(self._state)\n return self._state\n elif self._data_mode == 'test':\n batch_index = np.random.randint(low=0,high=len(self.test_data))\n extract_index = np.random.randint(low=0,high=BATCH)\n self._state,self._ground_truth_label = self.test_data[batch_index]\n self._ground_truth_label = self._ground_truth_label[extract_index]\n self._state = self._state[extract_index]\n self.ground_truth_image = deepcopy(self._state)\n else:\n ValueError('mode not exist')\n # return random minibatch\n\n def step(self, action):\n done = 0\n hight_index = action // self._state.size(1)\n width_index = action % self._state.size(1)\n new_state = self._state\n\n new_state[0,hight_index-1,width_index-1] = 1\n new_state[1, hight_index-1, width_index-1] = 1\n new_state[2, hight_index-1, width_index-1] = 1\n\n _, new_label = self.classifier(new_state.unsqueeze(0)).max(1)\n new_label = new_label.detach().cpu().data[0]\n disjudge_reward = 0\n if not bool(new_label == self._ground_truth_label):\n disjudge_reward = 1\n done = 1\n psnr_reward = PSNR(self.ground_truth_image, new_state, MAX_PIXEL_VALUE=1) - 40\n if bool(psnr_reward > 100):\n psnr_reward = 0\n\n\n reward = disjudge_reward + psnr_reward * 0.1\n\n self._state = new_state\n\n return new_state, reward, done\n\n def render(self):\n pass\n\ndef save_image(image,filename):\n if image.size(0) == 3:\n temp = transforms.ToPILImage()(image).convert('RGB')\n temp.save('./save/{}.png'.format(filename))\n return\n for i in range(image.size(0)):\n temp = transforms.ToPILImage()(image[i]).convert('RGB')\n temp.save('./save/{}{}.png'.format(filename,i))\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n env = Env()\n state = env.reset()\n psnr = PSNR(state,state,MAX_PIXEL_VALUE=1)\n\n\n\n\n","sub_path":"adversarial_attacks_images/cifar_env.py","file_name":"cifar_env.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"603096958","text":"def scrape_data():\n # Import all the necessary modules\n from selenium import webdriver\n from selenium.webdriver.support.ui import Select\n from selenium.webdriver.common.keys import Keys\n import requests\n from bs4 import BeautifulSoup\n import pandas as pd\n \n chrome_path = \"C:/Users/Victor/OneDrive/Desktop/Diseratie/chromedriver.exe\"\n MAIN_LINK = \"https://play.google.com/store/apps\"\n\n # Open Chrome Browser and get to the main page\n browser = webdriver.Chrome(chrome_path)\n browser.get(MAIN_LINK)\n # Find the \"Categories\" Button and click it\n browser.find_element_by_xpath('//*[@id=\"action-dropdown-parent-Categories\"]').click()\n\n # Get the content of the main page and create a BeautifulSoup object from it\n play_store_page = requests.get(MAIN_LINK)\n soup = BeautifulSoup(play_store_page.content, \"html.parser\")\n \n APPS, PACKAGE_NAMES = [], []\n\n all_categories = soup.find_all(class_ = \"KZnDLd\")\n\n for elem in all_categories:\n each_category = [a[\"href\"] for a in elem.find_all(\"a\", href = True)]\n each_category_link = \"https://play.google.com\" + each_category[0]\n\n # Get the Apps related to each category\n print(\"Getting Apps for {}...\".format(each_category_link.split(\"/\")[-1]))\n\n category_page = requests.get(each_category_link)\n category_soup = BeautifulSoup(category_page.content, \"html.parser\")\n\n # Find the \"See More\" button to see more applications from the same category.\n # Use find to get the first found element.\n # Use find_all to get all the elements on the page.\n # For testing purposes, we'll stick to the first element found on the page for now.\n see_more_apps = category_soup.find_all(class_ = \"W9yFB\")\n\n # From there, we will need the link (href) which leads to the \"See more apps\" from each category\n\n for elem in see_more_apps:\n see_more_apps_link = [a[\"href\"] for a in elem.find_all(\"a\", href = True)]\n\n # With the link scraped, we will combine it with \"https://play.google.com\"\n # to get to the \"See more # apps\" pages.\n see_more_apps_link = \"https://play.google.com\" + see_more_apps_link[0]\n # print(\"\\nComplete 'See More' Button Link: \", see_more_apps_link)\n\n # With the obtained link, we will request the content of each\n # page and create a BS4 object from it.\n see_more_apps_page = BeautifulSoup(requests.get(see_more_apps_link).content, \"html.parser\")\n\n # Now we got to the \"See More\" applications page. \n # From here, we will need to scrape through each page and obtain the following informations:\n # - Application name - we will store it in global variable APPS\n # - The 'href' link of every application, which contains the package name \n # - we will store it in global variable PACKAGE_NAMES\n\n # All the apps displayed in the page are stored under classes named \"ImZGtf mpg5gc\"\n for item in see_more_apps_page.find_all(class_ = \"ImZGtf mpg5gc\"):\n title = item.find(class_ = \"WsMG1c nnK0zc\").get_text()\n APPS.append(title)\n # We'll get the application link by splitting the elements found\n app_link = str(item.find(class_ = \"wXUyZd\").find(href = True))\n app_link = app_link.split(\"id=\")[1].split('\"')[0]\n PACKAGE_NAMES.append(app_link)\n # print(\"{}: {}\".format(title, app_link))\n \n GOOGLE_PLAY_DATA = pd.DataFrame(\n {\n \"Application\": APPS,\n \"App ID\": PACKAGE_NAMES\n }\n )\n \n return GOOGLE_PLAY_DATA","sub_path":"Google Play Scraper/FullCategoryApps.py","file_name":"FullCategoryApps.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"27262643","text":"import logging\nfrom typing import Any, Optional, Dict\n\nfrom bitcoinx import int_to_be_bytes, PublicKey\n\nfrom electrumsv_hosting.connection import HandshakeNotification,Message, Packet, ServerSession\nfrom electrumsv_hosting.messagebox import MessageType\n\nfrom server.handlers import BaseAPI, PublicAPI, RestrictedAPI\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(\"example-mailbox_server\")\n\npublic_api = PublicAPI()\nrestricted_api = RestrictedAPI()\n\n\nclass IncomingClientSession(ServerSession):\n \"\"\"A TCP Server that connects to a bitcoin wallet client via WP42 tunneling\"\"\"\n\n client_identity_pubkey: Optional[PublicKey] = None\n client_identity_id: Optional[int] = None\n\n def __init__(self, app: 'ServerApplication', *args, **kwargs) -> None:\n self.app = app\n super().__init__(*args, **kwargs)\n logger.debug('connection from %s', self.remote_address())\n\n def send_batch(self, raise_errors=False):\n raise NotImplementedError\n\n async def connection_lost(self) -> None:\n await super().connection_lost()\n logger.debug(f'{self.remote_address()} disconnected')\n\n async def handle_message(self, message: Message) -> Any:\n logger.debug(\"handle_request:enter '%s'\", message.message_type)\n api: BaseAPI = public_api if self.client_identity_id is None else restricted_api\n response_message = await api.dispatch_message(self, message)\n logger.debug(\"handle_request:exit\")\n return response_message\n\n async def get_shared_secret(self, client_identity_public_key: PublicKey,\n message_bytes: bytes) -> bytes:\n shared_secret_public_key = self.app.server_private_key.shared_secret(\n client_identity_public_key, message_bytes)\n return int_to_be_bytes(shared_secret_public_key.to_point()[0])\n\n async def process_handshake(self, message: HandshakeNotification) -> None:\n await super().process_handshake(message)\n\n self.client_identity_pubkey = message.remote_public_key\n self.client_identity_id = self.app.dbapi.get_id_for_identity(\n message.remote_public_key)\n\n async def on_register_identity(self, identity_id: int) -> None:\n self.client_identity_id = identity_id\n\n","sub_path":"examples/application/server/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"462765302","text":"import math\nfrom skpy import SkypeNewMessageEvent, SkypeEditMessageEvent\n\nfrom Core.PluginBase import PluginBase\nfrom .Command import Command\n\n\nclass PizzaPlugin(PluginBase):\n def __init__(self, skype):\n super(PizzaPlugin, self).__init__(skype=skype)\n self._orders = []\n self._started_by = None\n self._NUMBER_OF_PIZZA_SLICES = 8\n\n def friendly_name(self):\n return 'Pizza plugin'\n\n def version(self):\n return '0.2'\n\n def keywords(self):\n return ['pizza']\n\n def handle(self, event):\n if not isinstance(event, SkypeNewMessageEvent) and not isinstance(event, SkypeEditMessageEvent):\n return\n\n message = event.msg\n command = Command.parse(message=message.markup)\n\n if self._process_if_help_command(message=message, command=command):\n return\n\n self._ensure_exactly_one_command_is_given(command=command)\n\n if command.start:\n self._handle_start(message=message, command=command)\n elif command.stop:\n self._handle_stop(message=message, command=command)\n elif command.number_of_slices is not None:\n self._handle_number_of_slices(message=message, command=command)\n elif command.status:\n self._handle_status(message=message, command=command)\n\n\n def help_message(self):\n return \"\"\"{friendly_name} v{version}\n\nKeywords: {keywords}\nCommands:\n #help\n #start\n #stop\n #status\n NUMBER_OF_SLICES\n\"\"\".format(friendly_name=self.friendly_name(),\n version=self.version(),\n keywords=','.join(['#' + keyword for keyword in self.keywords()])\n )\n\n def _process_if_help_command(self, message, command):\n if command.help:\n self._skype.contacts[message.userId].chat.sendMsg(self.help_message())\n\n return command.help\n\n @staticmethod\n def _ensure_exactly_one_command_is_given(command):\n commands_number = 0\n commands_number += 1 if command.start else 0\n commands_number += 1 if command.stop else 0\n commands_number += 1 if command.number_of_slices is not None else 0\n commands_number += 1 if command.status else 0\n\n if commands_number != 1:\n raise Exception(\"You have to specify exactly one command at once\")\n\n def _handle_start(self, message, command):\n if self._started_by:\n raise Exception(\"Exactly one #pizza can be started at the same time\")\n\n self._orders = []\n self._started_by = message.user\n\n self._skype.contacts[message.user.id].chat.sendMsg(\n \"You've started #pizza at {time} UTC. Please remember to #pizza #stop\".format(time=str(message.time.replace(microsecond=0)))\n )\n\n message.chat.sendMsg(\"#pizza started by {user_name} ({user_id})\".format(user_name=self._started_by.name, user_id=self._started_by.id))\n\n def _handle_stop(self, message, command):\n if not self._started_by:\n raise Exception(\"No #pizza is currently started\")\n\n if self._started_by.id != message.userId:\n raise Exception(\"Only user which started #pizza can stop it\")\n\n final_order = list(self._orders)\n total_ordered_slices = sum(order[1] for order in final_order)\n number_of_pizzas = int(total_ordered_slices / self._NUMBER_OF_PIZZA_SLICES)\n slices_overflow = total_ordered_slices % self._NUMBER_OF_PIZZA_SLICES\n\n if slices_overflow:\n for idx, order in reversed(list(enumerate(self._orders))):\n if order[1] <= slices_overflow:\n final_order.pop(idx)\n slices_overflow -= order[1]\n self._skype.contacts[order[0].id].chat.sendMsg(\n \"Sorry, you were removed from #pizza order, because of rounding to whole #pizza(s) :(\"\n )\n else:\n new_slices = final_order[idx][1] - slices_overflow\n final_order[idx] = (final_order[idx][0], new_slices)\n slices_overflow = 0\n self._skype.contacts[order[0].id].chat.sendMsg(\n \"Sorry, your #pizza order was reduced to {slices} slice(s), because of rounding to whole #pizza(s) :(\".format(slices=new_slices)\n )\n\n if not slices_overflow:\n break\n\n orders_summaries = [\"{user_name} ({user_id}) - {slices}\".format(user_name=order[0].name, user_id=order[0].id, slices=order[1]) for order in final_order]\n\n self._skype.contacts[message.userId].chat.sendMsg(\n \"\"\"You've stopped #pizza at {time} UTC.\n \nSummary:\n#pizza(s) to order: {pizzas}\n{orders_summaries}\n\"\"\".format(time=str(message.time.replace(microsecond=0)),\n pizzas=number_of_pizzas,\n orders_summaries=\"\\n\".join(orders_summaries))\n )\n\n message.chat.sendMsg(\"\"\"Summary for #pizza started by {user_name} ({user_id}):\n#pizza(s) to order: {pizzas}\n\n{orders_summaries}\"\"\".format(\n user_name=self._started_by.name, user_id=self._started_by.id,\n pizzas=number_of_pizzas,\n orders_summaries=\"\\n\".join(orders_summaries)))\n\n self._orders = []\n self._started_by = None\n\n def _handle_number_of_slices(self, message, command):\n if not self._started_by:\n raise Exception(\"No #pizza is currently started\")\n\n existing_idx = [idx for idx, order in enumerate(self._orders) if order[0].id == message.userId]\n\n if existing_idx:\n self._orders.pop(existing_idx[0])\n\n if command.number_of_slices > 0:\n self._orders.append((message.user, command.number_of_slices))\n\n total_ordered_slices = sum(order[1] for order in self._orders)\n missing_slices = self._NUMBER_OF_PIZZA_SLICES - total_ordered_slices % self._NUMBER_OF_PIZZA_SLICES\n pizzas_to_order = total_ordered_slices // self._NUMBER_OF_PIZZA_SLICES\n\n self._skype.contacts[message.userId].chat.sendMsg(\"You've registered for {no_slices} #pizza slice(s)\".format(no_slices=command.number_of_slices))\n message.chat.sendMsg(\"{pizzas_to_order} #pizza(s) to order, {missing_slices} slice(s) are missing for the next #pizza\".format(pizzas_to_order=pizzas_to_order, missing_slices=missing_slices))\n\n def _handle_status(self, message, command):\n if not self._started_by:\n raise Exception(\"No #pizza is currently started\")\n\n final_order = list(self._orders)\n overflow_order = list()\n total_ordered_slices = sum(order[1] for order in final_order)\n number_of_pizzas = int(total_ordered_slices / self._NUMBER_OF_PIZZA_SLICES)\n missing_slices = self._NUMBER_OF_PIZZA_SLICES - total_ordered_slices % self._NUMBER_OF_PIZZA_SLICES\n slices_overflow = total_ordered_slices % self._NUMBER_OF_PIZZA_SLICES\n\n if slices_overflow:\n for idx, order in reversed(list(enumerate(self._orders))):\n if order[1] <= slices_overflow:\n final_order.pop(idx)\n slices_overflow -= order[1]\n overflow_order.append(order)\n else:\n new_slices = final_order[idx][1] - slices_overflow\n final_order[idx] = (final_order[idx][0], new_slices)\n overflow_order.append((final_order[idx][0], slices_overflow))\n slices_overflow = 0\n\n if not slices_overflow:\n break\n\n overflow_order = reversed(overflow_order)\n orders_summaries = [\"{user_name} ({user_id}) - {slices}\".format(user_name=order[0].name, user_id=order[0].id, slices=order[1]) for order in final_order]\n overflow_summaries = [\"{user_name} ({user_id}) - {slices}\".format(user_name=order[0].name, user_id=order[0].id, slices=order[1]) for order in overflow_order]\n\n chat_message = \"\"\"Started by {user_name} ({user_id})\nTotal #pizza(s) to order: {number_of_pizzas}\nSlice(s) missing for the next #pizza: {missing_slices}\n\n#pizza participants:\n{orders_summaries}\n\n#pizza reserve list:\n{overflow_summaries}\n\"\"\".format(user_name=self._started_by.name,\n user_id=self._started_by.id,\n number_of_pizzas=number_of_pizzas,\n missing_slices=missing_slices,\n orders_summaries=\"\\n\".join(orders_summaries) if len(orders_summaries) else \"¯\\_(ツ)_/¯\",\n overflow_summaries=\"\\n\".join(overflow_summaries) if len(overflow_summaries) else \"¯\\_(ツ)_/¯\",\n )\n\n message.chat.sendMsg(chat_message)\n","sub_path":"Plugins/Pizza/PizzaPlugin.py","file_name":"PizzaPlugin.py","file_ext":"py","file_size_in_byte":8588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"112220722","text":"\"\"\"\nLandon Buell\nAlejandro Hausner\nCS 417.01\n31 August 2020\n\"\"\"\n\n #### IMPORTS ####\n\nimport numpy as np\n\n #### CLASS DEFINITIONS ####\n\nclass Task02:\n \"\"\" Execution Object For Assignment01 - Question 2 \"\"\"\n\n def UserInput(self):\n \"\"\" Accept and Process User Input at the Command Line \"\"\"\n while True:\n try:\n n = int(input('Number terms in series? '))\n if n < 1:\n raise ValueError(\"n_terms must be integer >= 1\")\n else:\n break\n except:\n raise ValueError(\"n_terms must be integer\")\n return n\n\n def LeibnitzFormula(self,n_terms):\n \"\"\" Compute first n_terms of Leibnitz' Approx of PI \"\"\"\n approximation = 0 # initialize Approximation\n for i in range (0,n_terms):\n newTerm = (-1)**i / (2*i + 1)\n approximation += newTerm\n approximation *= 4 # multiply by 4\n return approximation # return the approximation\n\n \n\n #### MAIN EXECUTABLE ####\n\nif __name__ == '__main__':\n\n Executable = Task02() # create exectuabe\n n_terms = Executable.UserInput() # get user input\n piApprox = Executable.LeibnitzFormula(n_terms) # find approximation\n print(\"Liebnitz's appoximation of pi to\",n_terms,\"terms is:\",piApprox)\n","sub_path":"Assignment1/Assignment01/q2-pi_approx.py","file_name":"q2-pi_approx.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"39409406","text":"class Solution:\n # @param triangle, a list of lists of integers\n # @return an integer\n def minimumTotal(self, triangle):\n from collections import defaultdict\n d = defaultdict(dict)\n try:\n d[0][0] = triangle[0][0]\n except:\n return 0\n l = len(triangle)\n inf = float('inf')\n for line in range(l-1):\n for i in range(len(triangle[line])):\n d[line+1][i] = min(d[line+1].get(i, inf), d[line][i] + triangle[line+1][i])\n d[line+1][i+1] = min(d[line+1].get(i+1, inf), d[line][i] + triangle[line+1][i+1])\n return min(a for a in d[l-1].values())\n\n","sub_path":"LeetCode/algorithms/Triangle/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"239345100","text":"\nimport networkx as nx\nimport numpy as np\nfrom collections import OrderedDict\nfrom sklearn.utils import shuffle\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom scipy.sparse import csr_matrix\nfrom sklearn.svm import SVC\nfrom scipy.spatial.distance import squareform\nfrom scipy.spatial.distance import pdist\nfrom scipy.spatial.distance import cdist\nimport sys\nimport warnings\nfrom sklearn.exceptions import DataConversionWarning\nwarnings.filterwarnings(action='ignore', category=DataConversionWarning)\n\n\n_score_types = ['micro', 'macro']\n\n\ndef detect_number_of_communities(nxg):\n # It is assumed that the labels of communities starts from 0 to K-1\n max_community_label = -1\n communities = nx.get_node_attributes(nxg, \"community\")\n # for node in nxg.nodes():\n for node in communities:\n comm_list = communities[node]\n if type(comm_list) is int:\n comm_list = [comm_list]\n\n c_max = max(comm_list)\n if c_max > max_community_label:\n max_community_label = c_max\n return max_community_label + 1\n\ndef read_embedding_file(embedding_file_path, nodelist):\n # Read the the embeddings\n\n with open(embedding_file_path, 'r') as f:\n # Read the first line\n N, dim = (int(v) for v in f.readline().strip().split())\n node2embedding=[[] for _ in range(len(nodelist))]\n mapping = {node: nodeIdx for nodeIdx, node in enumerate(nodelist)}\n # Read embeddings\n for line in f.readlines():\n tokens = line.strip().split()\n if int(tokens[0]) in nodelist:\n node2embedding[mapping[int(tokens[0])]] = [float(value) for value in tokens[1:]]\n\n return np.asarray(node2embedding)\n\ndef read_binary_emb_file(file_path, nodelist=None):\n\n def _int2boolean(num):\n\n binary_repr = []\n for _ in range(8):\n\n binary_repr.append(True if num % 2 else False )\n num = num >> 1\n\n return binary_repr[::-1]\n\n embs = [[] for _ in range(len(nodelist))]\n mapping = {node: nodeIdx for nodeIdx, node in enumerate(nodelist)}\n with open(file_path, 'rb') as f:\n\n num_of_nodes = int.from_bytes(f.read(4), byteorder='little')\n dim = int.from_bytes(f.read(4), byteorder='little')\n\n #print(\"{} {}\".format(num_of_nodes, dim));\n dimInBytes = int(dim / 8)\n\n for i in range(num_of_nodes):\n # embs.append(int.from_bytes( f.read(dimInBytes), byteorder='little' ))\n emb = []\n for _ in range(dimInBytes):\n emb.extend(_int2boolean(int.from_bytes(f.read(1), byteorder='little')))\n #emb.extend(np.asarray( _int2boolean(int.from_bytes(f.read(1), byteorder='little') ), dtype=bool) )\n #print(len(emb))\n if i in nodelist:\n embs[mapping[i]] = emb\n\n #print(\"=\", len(embs[0]))\n return np.asarray(embs, dtype=bool)\n\n\ndef get_node2community(nxg):\n\n node2community = nx.get_node_attributes(nxg, name='community')\n\n # for node in nxg.nodes():\n for node in node2community:\n comm = node2community[node]\n if type(comm) == int:\n node2community[node] = [comm]\n\n return node2community\n\ndef evaluate(graph_path, embedding_file, number_of_shuffles, training_ratios, classification_method, file_type=\"binary\"):\n #print(\"Basladi\")\n cache_size = 10240\n\n g = nx.read_gml(graph_path)\n\n node2community = get_node2community(g)\n\n # N = g.number_of_nodes()\n K = detect_number_of_communities(g)\n #print(\"K: {}\".format(K))\n # nodelist = [node for node in g.nodes()]\n nodelist = [int(node) for node in node2community]\n #nodelist.sort()\n\n N = len(nodelist)\n #print(\"N: {}\".format(N))\n #print(\"--------\", x.shape\n\n if file_type == \"binary\":\n x = read_binary_emb_file(file_path=embedding_file, nodelist=nodelist)\n else:\n x = read_embedding_file(embedding_file, nodelist=nodelist)\n #print(\"Basladi 2\")\n\n\n label_matrix = [[1 if k in node2community[str(node)] else 0 for k in range(K)] for node in nodelist]\n label_matrix = csr_matrix(label_matrix)\n\n results = {}\n\n for score_t in _score_types:\n results[score_t] = OrderedDict()\n for ratio in training_ratios:\n results[score_t].update({ratio: []})\n\n\n print(\"+ Similarity matrix is begin computed!\")\n if classification_method == \"svm-hamming\":\n sim = 1.0 - cdist(x, x, 'hamming')\n elif classification_method == \"svm-cosine\":\n sim = 1.0 - cdist(x, x, 'cosine')\n elif classification_method == \"svm-chisquare\":\n print(x.shape)\n dist = cdist(x, x, 'hamming')\n dist[dist>0.5] = 0.5\n sim = 1.0 - np.sqrt( 2.0 - 2.0*np.cos(dist*np.pi) )\n else:\n raise ValueError(\"Invalid classification method name: {}\".format(classification_method))\n\n #print(\"\\t- Completed!\")\n \n\n for train_ratio in training_ratios:\n\n for shuffleIdx in range(number_of_shuffles):\n\n print(\"Current train ratio: {} - shuffle: {}/{}\".format(train_ratio, shuffleIdx+1, number_of_shuffles))\n\n # Shuffle the data\n shuffled_idx = np.random.permutation(N)\n shuffled_sim = sim[shuffled_idx, :]\n shuffled_sim = shuffled_sim[:, shuffled_idx]\n shuffled_labels = label_matrix[shuffled_idx]\n\n # Get the training size\n train_size = int(train_ratio * N)\n # Divide the data into the training and test sets\n train_sim = shuffled_sim[0:train_size, :]\n train_sim = train_sim[:, 0:train_size]\n train_labels = shuffled_labels[0:train_size]\n\n test_sim = shuffled_sim[train_size:, :]\n test_sim = test_sim[:, 0:train_size]\n test_labels = shuffled_labels[train_size:]\n\n # Train the classifier\n ovr = OneVsRestClassifier(SVC(kernel=\"precomputed\", cache_size=cache_size, probability=True))\n\n ovr.fit(train_sim, train_labels)\n\n # Find the predictions, each node can have multiple labels\n test_prob = np.asarray(ovr.predict_proba(test_sim))\n y_pred = []\n for i in range(test_labels.shape[0]):\n k = test_labels[i].getnnz() # The number of labels to be predicted\n pred = test_prob[i, :].argsort()[-k:]\n y_pred.append(pred)\n\n # Find the true labels\n y_true = [[] for _ in range(test_labels.shape[0])]\n co = test_labels.tocoo()\n for i, j in zip(co.row, co.col):\n y_true[i].append(j)\n\n mlb = MultiLabelBinarizer(range(K))\n for score_t in _score_types:\n score = f1_score(y_true=mlb.fit_transform(y_true),\n y_pred=mlb.fit_transform(y_pred),\n average=score_t)\n\n results[score_t][train_ratio].append(score)\n\n return results\n\n\ndef get_output_text(results, shuffle_std=False, detailed=False):\n\n num_of_shuffles = len(list(list(results.values())[0].values())[0])\n train_ratios = [r for r in list(results.values())[0]]\n percentage_title = \" \".join(\"{0:.0f}%\".format(100 * r) for r in list(results.values())[0])\n\n output = \"\"\n for score_type in _score_types:\n if detailed is True:\n for shuffle_num in range(1, num_of_shuffles + 1):\n output += \"{} score, shuffle #{}\\n\".format(score_type, shuffle_num)\n output += percentage_title + \"\\n\"\n for ratio in train_ratios:\n output += \"{0:.5f} \".format(results[score_type][ratio][shuffle_num - 1])\n output += \"\\n\"\n\n output += \"{} score, mean of {} shuffles\\n\".format(score_type, num_of_shuffles)\n output += percentage_title + \"\\n\"\n for ratio in train_ratios:\n output += \"{0:.5f} \".format(np.mean(results[score_type][ratio]))\n output += \"\\n\"\n\n if shuffle_std is True:\n output += \"{} score, std of {} shuffles\\n\".format(score_type, num_of_shuffles)\n output += percentage_title + \"\\n\"\n for ratio in train_ratios:\n output += \"{0:.5f} \".format(np.std(results[score_type][ratio]))\n output += \"\\n\"\n\n return output\n\n\ndef print_results(results, shuffle_std, detailed=False):\n output = get_output_text(results=results, shuffle_std=shuffle_std, detailed=detailed)\n print(output)\n\n\ndef save_results(results, output_file, shuffle_std, detailed=False):\n\n with open(output_file, 'w') as f:\n output = get_output_text(results=results, shuffle_std=shuffle_std, detailed=detailed)\n f.write(output)\n\nif __name__ == \"__main__\":\n\n graph_path = sys.argv[1]\n\n embedding_file = sys.argv[2]\n\n output_file = sys.argv[3]\n\n number_of_shuffles = int(sys.argv[4])\n\n if sys.argv[5] == \"large\":\n training_ratios = [i for i in np.arange(0.1, 1, 0.1)]\n elif sys.argv[5] == \"all\":\n training_ratios = [i for i in np.arange(0.01, 0.1, 0.01)] + [i for i in np.arange(0.1, 1, 0.1)]\n elif sys.argv[5] == \"custom\":\n training_ratios = [0.1, 0.5, 0.9]\n elif sys.argv[5] == \"custom-small\":\n training_ratios = [0.1, 0.5]\n elif sys.argv[5] == \"custom-big\":\n training_ratios = [ 0.9]\n else:\n raise ValueError(\"Invalid training ratio\")\n\n classification_method = sys.argv[6]\n\n file_type = sys.argv[7]\n\n print(\"---------------------------------------\")\n print(\"Graph path: {}\".format(graph_path))\n print(\"Emb path: {}\".format(embedding_file))\n print(\"Output path: {}\".format(output_file))\n print(\"Num of shuffles: {}\".format(number_of_shuffles))\n print(\"Training ratios: {}\".format(training_ratios))\n print(\"Classification method: {}\".format(classification_method))\n print(\"File type {}\".format(file_type))\n print(\"---------------------------------------\")\n\n results = evaluate(graph_path, embedding_file, number_of_shuffles, training_ratios, classification_method, file_type=file_type)\n\n print_results(results=results, shuffle_std=False, detailed=False)\n save_results(results, output_file, shuffle_std=False, detailed=False)\n","sub_path":"tools/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":10309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"370596566","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\n\nfrom elastic_recheck import elasticRecheck\nfrom elastic_recheck import tests\n\n\nclass TestSuppressNotifcation(tests.TestCase):\n\n def setUp(self):\n super(TestSuppressNotifcation, self).setUp()\n self.classifier = elasticRecheck.Classifier(\n \"./elastic_recheck/tests/unit/suppressed_queries\")\n\n @mock.patch('elastic_recheck.query_builder.single_patch')\n @mock.patch('elastic_recheck.results.SearchEngine.search')\n def test_basic_parse(self, mock1, mock2):\n self.classifier.classify(None, None, None)\n self.assertFalse(mock1.called)\n self.assertFalse(mock2.called)\n","sub_path":"elastic_recheck/tests/unit/test_suppress_notifications.py","file_name":"test_suppress_notifications.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"337007671","text":"from __future__ import division\nimport numpy as np\nimport glob, os, json, pickle\nimport matplotlib.pyplot as plt\nimport scipy.linalg as sl\n\nimport libstempo as libs\nimport libstempo.plot as libsplt\n\nimport enterprise\nfrom enterprise.pulsar import Pulsar\nfrom enterprise.signals import parameter\nfrom enterprise.signals import white_signals\nfrom enterprise.signals import utils\nfrom enterprise.signals import gp_signals\nfrom enterprise.signals import signal_base\n\nimport corner\nfrom PTMCMCSampler.PTMCMCSampler import PTSampler as ptmcmc\n\n#NEED TO CHANGE FILE ON DIFFERENT RUNS (ie full_run_1 -> full_run_2)\nrunname = '/pulsar_noise_runs'\ngroup = '/group2'\ndataset = '/dataset_2'\n\ntopdir = os.getcwd()\n#Where the original data is\norigdatadir = topdir + '/mdc2' + group + dataset\n#Where the json noise file is\nnoisefile = topdir + '/mdc2' + '/group1' + '/challenge1_psr_noise.json'\n#Where the dataset files are located\ndatadir = topdir + dataset\n#Where the refit par files are saved to\npardir = datadir + '/corrected_pars/'\n#Where the everything should be saved to (chains, cornerplts, histograms, etc.)\noutdir = datadir + runname\n#Where we save figures n stuff\nfigdir = datadir + '/Cornerplts/'\n#The new json file we made\nupdatednoisefile = datadir + 'fit_psr_noise.json'\n#The pickled pulsars\npsr_obj_file = datadir + '/psr_objects.pickle'\n\nif os.path.exists(datadir) == False:\n os.mkdir(datadir)\nif os.path.exists(outdir) == False:\n os.mkdir(outdir)\n\ndef Refit_pars(origdir,newdir):\n orig_parfiles = sorted(glob.glob(origdir + '/*.par'))\n orig_timfiles = sorted(glob.glob(origdir + '/*.tim'))\n #Load all of the Pulsars into libstempo\n orig_libs_psrs = []\n for p, t in zip(orig_parfiles, orig_timfiles):\n orig_libs_psr = libs.tempopulsar(p, t)\n orig_libs_psrs.append(orig_libs_psr)\n\n #Fit the par files again\n #Save them to new directory (Overwrites ones currently used in newdatadir)\n if os.path.exists(newdir) == False:\n os.mkdir(newdir)\n for new_libs_psr in orig_libs_psrs:\n new_libs_psr['DM'].fit = False\n new_libs_psr['DM1'].fit = False\n new_libs_psr['DM2'].fit = False\n try:\n new_libs_psr.fit(iters=3)\n except:\n print('Cannot refit Pulsar: ' + new_libs_psr.name)\n continue\n new_libs_psr.savepar(newdir + new_libs_psr.name + '.par')\n\n\n#Load all the pulsars if no pickle file\ntry:\n #Load pulsars from pickle file\n with open(psr_obj_file,'rb') as psrfile:\n psrs = pickle.load(psrfile)\n psrfile.close()\nexcept:\n #If no pickle file, load and save pulsars\n\n #Load refit par files if they exist, else fit them and save them\n if os.path.exists(pardir) == True:\n parfiles = sorted(glob.glob(pardir + '/*.par'))\n else:\n #Refit par files using libstempo\n Refit_pars(origdatadir,pardir)\n parfiles = sorted(glob.glob(pardir + '/*.par'))\n\n #Loading tim files into enterprise Pulsar class\n timfiles = sorted(glob.glob(origdatadir + '/*.tim'))\n\n psrs = []\n for p, t in zip(parfiles,timfiles):\n psr = Pulsar(p, t)\n psrs.append(psr)\n #Save 9yr pulsars to a pickle file\n with open(psr_obj_file,'wb') as psrfile:\n pickle.dump(psrs,psrfile)\n psrfile.close()\n\n# find the maximum time span to set GW frequency sampling\ntmin = [p.toas.min() for p in psrs]\ntmax = [p.toas.max() for p in psrs]\nTspan = np.max(tmax) - np.min(tmin)\n\n##### parameters and priors #####\n\n# Uniform prior on EFAC and EQUAD\nefac = parameter.Uniform(0.1, 5.0)\nlog10_equad = parameter.Uniform(-10.0,-4.0)\n\n# red noise parameters\n# Uniform in log10 Amplitude and in spectral index\nlog10_A = parameter.Uniform(-18,-12)\ngamma = parameter.Uniform(0,7)\n\n##### Set up signals #####\n\n# white noise\nef = white_signals.MeasurementNoise(efac=efac)\neq = white_signals.EquadNoise(log10_equad = log10_equad)\n\n# red noise (powerlaw with 30 frequencies)\npl = utils.powerlaw(log10_A=log10_A, gamma=gamma)\nrn = gp_signals.FourierBasisGP(spectrum=pl, components=30)\n\n# timing model\ntm = gp_signals.TimingModel()\n\n# full model is sum of components\nmodel = ef + rn + tm + eq\n\npsr_dict = {}\n\nfor psr in psrs:\n\tprint('Working on ' + psr.name)\n\tpsroutdir = outdir + '/' + psr.name + '/'\n\tif not os.path.exists(psroutdir):\n\t\tos.mkdir(psroutdir)\n\n\t# initialize PTA\n\tpta = signal_base.PTA([model(psr)])\n\n\t#Pick random initial sampling\n\txs = {par.name: par.sample() for par in pta.params}\n\n\t# dimension of parameter space\n\tndim = len(xs)\n\n\t# initial jump covariance matrix\n\tcov = np.diag(np.ones(ndim) * 0.01**2)\n\n\t# Now we figure out which indices the red noise parameters have\n\trn_idx1 = pta.param_names.index(psr.name + '_red_noise_log10_A')\n\trn_idx2 = pta.param_names.index(psr.name + '_red_noise_gamma')\n\n\t# set up jump groups by red noise groups\n\tndim = len(xs)\n\tgroups = [range(0, ndim)]\n\tgroups.extend([[rn_idx1,rn_idx2]])\n\n\t# intialize sampler\n\tsampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir=psroutdir)\n\n\t# sampler for N steps\n\tN = int(1e6)\n\tx0 = np.hstack(p.sample() for p in pta.params)\n\tsampler.sample(x0, N, SCAMweight=30, AMweight=15, DEweight=50)\n\n\tchain = np.loadtxt(psroutdir + 'chain_1.txt')\n\tpars = sorted(xs.keys())\n\tburn = int(0.25 * chain.shape[0])\n\n\t#make dictionary of pulsar parameters from these runs\n\tpsr_dict[psr.name] = {}\n\tfor idx,param_name in enumerate(pars):\n\t\tpsr_dict[psr.name][param_name] = np.median(chain[burn:,idx])\n\t#Save to json file\n\twith open(psroutdir + '/fit_psr_noise.json','w') as paramfile:\n\t\tjson.dump(psr_dict[psr.name],paramfile,sort_keys = True,indent = 4)\n\t\tparamfile.close()\n\n# Now we want to save this all as a json file\nwith open(outdir+\"/all_fit_psr_noise.json\", 'w') as fpn:\n json.dump(psr_dict, fpn ,sort_keys = True,indent = 4)\n fpn.close()","sub_path":"MDC2/MDC2_g2_d2_pulsar_noise.py","file_name":"MDC2_g2_d2_pulsar_noise.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"74910677","text":"# -*- coding: utf-8 -*-\n# ©2016 Jean-Hugues Roy. GNU GPL v3.\n\n#C'est pourri Gilles. \n\nimport requests, json, csv\n\nfichier = \"concordia.csv\"\n\ndef romain(val):\n\ttotal = 0\n\tvaleurs = {\n\t\t'i': 1,\n\t\t'v': 5,\n\t\t'x': 10,\n\t\t'l': 50,\n\t\t'c': 100\n\t}\n\n\tvalAvant = 0\n\n\tfor car in val:\n\t\tif valeurs[car] > valAvant:\n\t\t\ttotal -= valAvant\n\t\telse:\n\t\t\ttotal += valAvant\n\n\t\tvalAvant = valeurs[car]\n\n\ttotal += valAvant\n\treturn total\n\n###########################################\n########## SOURCES ##########\n###########################################\n#\n# CONCORDIA\n# http://spectrum.library.concordia.ca/\n#\n# http://spectrum.library.concordia.ca/cgi/exportview/year/2012/JSON/2012.js\n\ntout = []\n\nfor a in range(1999,2000):\n\turl = \"http://spectrum.library.concordia.ca/cgi/exportview/year/{0}/JSON/{0}.js\".format(a)\n\t# print(url)\n\tr = (requests.get(url)).json()\n\tnb = 0\n\tfor i in r:\n\n\t\tif i[\"type\"] == \"thesis\":\n\n\t\t\tthese = {}\n\t\t\tthese[\"01. Université\"] = \"Concordia\"\n\n\t\t\tif \"date\" in i:\n\t\t\t\tthese[\"02. Année\"] = i[\"date\"]\n\t\t\telse:\n\t\t\t\tthese[\"02. Année\"] = \"?\"\n\n\t\t\tif \"thesis_type\" in i:\n\t\t\t\tthese[\"03. Type\"] = i[\"thesis_type\"]\n\t\t\telse:\n\t\t\t\tthese[\"03. Type\"] = \"?\"\n\n\t\t\tif \"department\" in i:\n\t\t\t\tthese[\"04. Dépt\"] = i[\"department\"]\n\t\t\telse:\n\t\t\t\tthese[\"04. Dépt\"] = \"?\"\n\n\t\t\tif \"title\" in i:\n\t\t\t\tthese[\"09. Titre\"] = i[\"title\"]\n\t\t\t\tthese[\"10. Long titre\"] = len(i[\"title\"])\n\t\t\telse:\n\t\t\t\tthese[\"09. Titre\"] = \"?\"\n\t\t\t\tthese[\"10. Long titre\"] = None\n\n\t\t\tif \"pages\" in i:\n\t\t\t\tpages = i[\"pages\"]\n\t\t\t\tthese[\"07. Nb pages\"] = pages\n\t\t\t\tthese[\"08. Pages (debug)\"] = pages\n\n\t\t\ttry:\n\n\t\t\t\tif \"pages_aacr\" in i:\n\t\t\t\t\tpages = i[\"pages_aacr\"]\n\t\t\t\t\tthese[\"08. Pages (debug)\"] = pages\n\t\t\t\t\tprint(pages)\n\t\t\t\t\tlim = 0\n\t\t\t\t\tp = 0\n\t\t\t\t\tautres = 0\n\t\t\t\t\tif pages.startswith((\"i\",\"v\",\"x\",\"l\")):\n\t\t\t\t\t\tlim = pages[0:pages.index(\",\")]\n\t\t\t\t\t\tlim = lim.strip()\n\t\t\t\t\t\tlim = romain(lim)\n\t\t\t\t\t\tif \"leaves\" in pages:\n\t\t\t\t\t\t\tp = pages[pages.index(\",\")+1:pages.index(\"leaves\")]\n\t\t\t\t\t\t\tif \"[\" in p:\n\t\t\t\t\t\t\t\tautres = p[p.index(\"[\")+1:p.index(\"]\")]\n\t\t\t\t\t\t\t\tautres = int(autres)\n\t\t\t\t\t\t\t\tp = p[0:p.index(\",\")]\n\t\t\t\t\t\t\t\tp = int(p)\n\t\t\t\t\t\t\telif \",\" in p:\n\t\t\t\t\t\t\t\tautres = p[p.index(\",\")+1:-1]\n\t\t\t\t\t\t\t\tautres = int(autres)\n\t\t\t\t\t\t\t\tp = p[0:p.index(\",\")]\n\t\t\t\t\t\t\t\tp = int(p)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tautres = 0\n\t\t\t\t\t\t\t\tp = int(p)\n\t\t\t\t\telif pages.startswith(\"[\"):\n\t\t\t\t\t\tp = pages[pages.index(\"[\")+1:pages.index(\"]\")]\n\t\t\t\t\t\tp = int(p)\n\t\t\t\t\telif pages[1].isdigit():\n\t\t\t\t\t\tp = pages[0:pages.index(\"leaves\")]\n\t\t\t\t\t\tp = int(p)\n\t\t\t\tthese[\"12. Erreur\"] = 0\n\n\t\t\texcept:\n\t\t\t\tthese[\"08. Pages (debug)\"] = i[\"pages_aacr\"]\n\t\t\t\tprint(\"POUET\")\n\t\t\t\tprint(\"===\")\n\t\t\t\tthese[\"12. Erreur\"] = 1\n\t\t\t\tlim =0\n\t\t\t\tp = 0\n\t\t\t\tautres = 0\n\n\t\t\tprint(lim, \"+\", p, \"+\", autres)\n\t\t\tpages = lim + p + autres\n\t\t\tthese[\"07. Nb pages\"] = pages\n\t\t\tprint(pages)\n\n\t\t\tif \"documents\" in i:\n\n\t\t\t\tif \"language\" in i[\"documents\"][0]:\n\t\t\t\t\tthese[\"05. Langue\"] = i[\"documents\"][0][\"language\"]\n\t\t\t\telse:\n\t\t\t\t\tthese[\"05. Langue\"] = \"?\"\n\n\t\t\t\tif \"uri\" in i[\"documents\"][0][\"files\"][0]:\n\t\t\t\t\tthese[\"11. URL\"] = i[\"documents\"][0][\"files\"][0][\"uri\"]\n\t\t\t\telse:\n\t\t\t\t\tthese[\"11. URL\"] = \"?\"\n\n\t\t\t\tif \"filesize\" in i[\"documents\"][0][\"files\"][0]:\n\t\t\t\t\tthese[\"06. Octets\"] = i[\"documents\"][0][\"files\"][0][\"filesize\"]\n\t\t\t\telse:\n\t\t\t\t\tthese[\"06. Octets\"] = None\n\n\t\t\telse:\n\t\t\t\tthese[\"06. Octets\"] = None\n\t\t\t\tthese[\"11. URL\"] = \"?\"\n\t\t\t\tthese[\"05. Langue\"] = \"?\"\n\n\t\t\tnb += 1\n\n\t\t\tprint(these)\n\t\t\ttout.append(these)\n\t\t\tprint(\"===\")\n\t\t\t# print(these.keys())\n\n\tprint(\"En {0}({1}) on a {2} thèses\".format(a,i[\"date\"],nb))\n\n# print(tout)\n# print(tout[0].keys())\nentetes = tout[0].keys()\nentetes = sorted(entetes)\n\nx = 0\n\nfor ligne in tout:\n\twith open(fichier, 'a') as f:\n\t\tw = csv.DictWriter(f, entetes)\n\t\tif x == 0:\n\t\t\tw.writeheader()\n\t\tw.writerow(ligne)\n\tx += 1\n","sub_path":"devoir1-essai1-raté-je-l-admets-humblement.py","file_name":"devoir1-essai1-raté-je-l-admets-humblement.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"341613008","text":"from django.shortcuts import render,redirect,get_object_or_404,get_list_or_404\nimport requests \nfrom django.contrib import messages\nfrom .models import User, Product, Category, Cart, Order, ContactUs, Wish, subcategory, BillingAddress\nfrom django.utils import timezone\nfrom .forms import loginForm, SignUpForm, CartForm, ProductForm, BillingForm, ContactUsForm\nfrom django.contrib.auth import authenticate\nfrom django.urls import reverse_lazy\nfrom django.views.generic import View, UpdateView\nfrom food.forms import SignUpForm\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\nfrom django.template.loader import render_to_string\nfrom food.tokens import account_activation_token\nfrom django.utils.encoding import force_text\nfrom django.utils.http import urlsafe_base64_decode\nfrom django.contrib.auth import authenticate, login as dj_login\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom django.views.decorators.http import require_POST\nfrom django.http import HttpResponseRedirect\n#from django.contrib.auth import login\n#from django.contrib.auth import login as auth_login\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n# def contact_us(request):\n# cus = ContactUs(name=request.GET['name'],\n# email=request.POST['email'], \n# enquiry=request.POST['enquiry'])\n# cus.save()\n# return redirect('food/contact.html')\n\ndef contact_us(request):\n cus = ContactUs.objects.all()\n if request.method =='POST':\n form = ContactUsForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('product_list')\n else:\n form = ContactUsForm()\n return render(request, 'food/contact.html', {'form':form})\n\ndef pro_category(request):\n food=subcategory.objects.filter(Q(category__title='f'))\n veg=subcategory.objects.filter(Q(category__title='v'))\n ext=subcategory.objects.filter(Q(category__title='e'))\n\n return render(request, 'food/category.html', {'food': food, 'veg':veg, 'ext':ext})\n\n\ndef about_us(request):\n return render(request, 'food/about-us.html')\n\ndef privacy_policy(request):\n return render(request,'registration/privacy_policy.html')\n\ndef user_list(request):\n posts2 = User.objects.filter(first_name=request.user)\n return render(request,'food/user_profile.html',{'posts2': posts2})\n\ndef user_del(requet, pk):\n post = get_object_or_404(User, pk=pk)\n post.delete()\n return redirect('user_list')\n\ndef user_edit(request, pk):\n post = get_object_or_404(User, pk=pk)\n if request.method == \"POST\":\n form = SignUpForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save()\n post.author = request.user\n post.save()\n return redirect('user_list')\n else:\n form = SignUpForm(instance=post)\n return render(request, 'food/user_edit.html', {'form': form})\n\ndef search(request):\n query = request.GET['query']\n if len(query) > 50:\n allpost= Product.objects.none()\n else:\n allpost=Product.objects.filter(Q(name__icontains=query)|\n Q(category__name__icontains=query)|\n Q(detail_text__icontains=query))\n if allpost.count() == 0:\n messages.error(request,'can not found')\n return render(request,'food/search.html',{'allpost':allpost, 'query':query})\n\n\ndef product_pg(request, pk):\n prd= get_object_or_404(Product, pk=pk)\n return render(request,'food/product.html', {'prd':prd})\n\n@login_required\ndef product_byuser(request):\n posts = Product.objects.filter(Q(author=request.user))\n #print(posts.query)\n return render(request, 'food/product_list.html',{'posts':posts})\n\ndef product_del(requet, pk):\n post = get_object_or_404(Product, pk=pk)\n post.delete()\n return redirect('product_list')\n\ndef product_edit(request, pk):\n post = get_object_or_404(Product, pk=pk)\n if request.method == \"POST\":\n form = ProductForm(request.POST, request.FILES, instance=post)\n if form.is_valid():\n post = form.save()\n post.author = request.user\n post.save()\n return redirect('product_list')\n else:\n form = ProductForm(instance=post)\n return render(request, 'food/product_edit.html', {'form': form})\n\ndef product_list(request):\n Products = Product.objects.filter(published=True)\n return render(request,'food/index.html',{'Products': Products})\n\ndef product_list_base(request):\n fru_base = Product.objects.filter(Q(category__title__icontains=\"f\")) & Product.objects.filter(published='True') \n veg_base = Product.objects.filter(Q(category__title__icontains=\"v\")) & Product.objects.filter(published='True') \n ext_base = Product.objects.filter(Q(category__title__icontains=\"e\")) & Product.objects.filter(published='True') \n return render(request, 'food/index.html',{'fru_base':fru_base,'veg_base':veg_base,'ext_base':ext_base})\n\ndef product_publish(request,pk):\n post =Product.objects.get(pk=pk)\n if post.published== 0:\n post.published= 1\n post.save()\n messages.info(request,'product is published')\n elif post.published== 1:\n post.published= 0\n post.save()\n messages.info(request,'product is unpublished')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n@login_required\ndef add_product(request):\n if request.method == \"POST\":\n form = ProductForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n return redirect('product_list')\n else:\n form = ProductForm()\n return render(request, 'food/add_product.html', {'form': form})\n\ndef fruit_list(request):\n fru = Product.objects.filter(Q(category__title__icontains=\"f\")) & Product.objects.filter(published='True') \n print(fru.query)\n return render(request,'food/fruit_index.html',{'fru': fru})\n\ndef veg_list(request):\n veg = Product.objects.filter(Q(category__title__contains=\"v\")) & Product.objects.filter(published='True') \n return render(request,'food/veg_index.html',{'veg': veg})\n\ndef ext_list(request):\n ext = Product.objects.filter(Q(category__title__contains=\"e\")) & Product.objects.filter(published='True') \n return render(request,'food/extra_index.html',{'ext': ext})\n\n@login_required\ndef remove_wish(request,pk):\n item=get_object_or_404(Product,pk=pk)\n remove_list=Wish.objects.filter(item=item.pk,user=request.user)\n remove_list.delete()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n@login_required\ndef wishlist_view(request):\n user=request.user\n productw=Product.objects.filter(author=user, price=False)\n wishs=Wish.objects.filter(user=user) \n if wishs.exists():\n if wishs.exists():\n wish=wishs[0]\n return render(request,'food/wishlist.html', {'productw':productw, 'wishs':wishs})\n else:\n messages.warning(request, \"You do not have any item in your Cart\")\n return redirect(\"product_list\")\n else:\n messages.warning(request, \"You do not have any item in your Cart\")\n return redirect(\"product_list\")\n\n return render(request, 'food/wishlist.html',{'wishs':wishs})\n\n@login_required\ndef cart_view(request):\n user=request.user\n carts=Cart.objects.filter(user=user, price=False)\n orders=Order.objects.filter(user=user, ordered=False)\n if carts.exists():\n if orders.exists():\n order=orders[0]\n return render(request,'food/cart.html', {'carts':carts, 'order':order})\n else:\n messages.warning(request, \"You do not have any item in your wishlist\")\n return redirect(\"product_list\")\n else:\n messages.warning(request, \"You do not have any item in your wishlist\")\n return redirect(\"product_list\")\n\n return render(request, 'food/cart.html',{'carts':carts})\n\n\ndef add_to_wishlist(request,pk):\n user=request.user\n items = get_object_or_404(Product,pk=pk)\n wished_item,created = Wish.objects.get_or_create(item=items,\n pk = items.pk,\n user = user,)\n\n messages.info(request,'The item was added to your wishlist')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n@login_required\ndef add_to_cart(request, pk):\n item=get_object_or_404(Product, pk=pk)\n order_item, created=Cart.objects.get_or_create(item=item,user=request.user)\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n #check if the order item is in the order\n if order.orderitems.filter(item=item.pk).exists():\n order_item.quantity += 1\n order_item.save()\n messages.info(request,f\"{item.name} quantity has update.\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n order.orderitems.add(order_item)\n messages.info(request, f\"{item.name} has added to your cart.\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n order=Order.objects.create(user=request.user)\n order.orderitems.add(order_item)\n messages.info(request, f\"{item.name} has added to your cart. \")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\ndef delete_cart(request, pk):\n item=get_object_or_404(Product, pk=pk)\n order_qs=Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order=order_qs[0]\n #check if the order item is the order\n if order.orderitems.filter(item=item.pk).exists():\n order_item=Cart.objects.filter(item=item, user=request.user)[0]\n order.orderitems.remove(order_item)\n order_item.delete()\n messages.warning(request, f\"{item.name} has removed from your cart.\")\n messages.info(request, f\"{item.name} quantity has updated.\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n messages.info(request, f\"{item.name} Your item is not delete\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\ndef decreaseCart(request, pk):\n item = get_object_or_404(Product, pk=pk)\n order_qs=Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n #check if the order item is in the order\n if order.orderitems.filter(item=item.pk).exists():\n order_item=Cart.objects.filter(item=item, user=request.user)[0]\n if order_item.quantity > 1:\n order_item.quantity -= 1\n order_item.save()\n else:\n order.orderitems.remove(order_item)\n order_item.delete()\n messages.warning(request, f\"{item.name} has removed frpm your cart.\")\n messages.info(request, f\"{item.name} quantity has updated.\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n messages.info(request, f\"{item.name} quantity has updated.\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n messages.info(request, \"You do not have an active order\")\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\ndef checkout(request):\n \n form = BillingForm\n \n order_qs = Order.objects.filter(user= request.user, ordered=False)\n order_items = order_qs[0].orderitems.all()\n order_total = order_qs[0].all_total() \n get_total = order_qs[0].get_totals() \n get_perse = order_qs[0].get_percentage() \n\n context = {\"form\": form, \n \"order_items\": order_items,\n \"order_total\": order_total,\n \"get_total\":get_total,\n \"get_perse\":get_perse\n }\n\n # Getting the saved saved_address\n saved_address = BillingAddress.objects.filter(user = request.user)\n if saved_address.exists():\n savedAddress = saved_address.first()\n context = {\"form\": form, \n \"order_items\": order_items,\n \"order_total\": order_total, \n \"savedAddress\": savedAddress\n }\n\n if request.method == \"POST\":\n saved_address = BillingAddress.objects.filter(user = request.user)\n if saved_address.exists():\n\n savedAddress = saved_address.first()\n form = BillingForm(request.POST, instance=savedAddress)\n if form.is_valid():\n billingaddress = form.save(commit=False)\n billingaddress.user = request.user\n billingaddress.save()\n else:\n form = BillingForm(request.POST)\n if form.is_valid():\n billingaddress = form.save(commit=False)\n billingaddress.user = request.user\n billingaddress.save()\n \n return render(request, 'food/checkout.html', context)\n\ndef payment(request):\n key = settings.STRIPE_PUBLISHABLE_KEY\n order_qs = Order.objects.filter(user= request.user, ordered=False)\n order_total = order_qs[0].all_total() \n totalCents = float(order_total * 100);\n total = round(totalCents, 2)\n if request.method == 'POST':\n charge = stripe.Charge.create(amount=total,\n currency='usd',\n description=order_qs,\n source=request.POST['stripeToken'])\n print(charge)\n \n return render(request, 'food/payment.html', {\"key\": key, \"total\": total})\n\ndef filter(request):\n #print(request.GET[\"filter_type\"])\n if 'filter_type' in request.GET and request.GET[\"filter_type\"] == \"low\":\n Products = Product.objects.filter().order_by('price')\n else:\n Products = Product.objects.filter().order_by('-price')\n #print(Products.query)\n return render(request, 'food/index.html',{'Products': Products})\n\nclass SignUpView(View):\n form_class = SignUpForm\n template_name = 'registration/register.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST, request.FILES)\n if form.is_valid():\n\n user = form.save(commit=False)\n user.is_active = False # Deactivate account till it is confirmed\n user.save()\n\n current_site = get_current_site(request)\n subject = 'Activate Your MySite Account'\n message = render_to_string('registration/account_activation_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n user.email_user(subject, message)\n\n messages.success(request, ('Please Confirm your email to complete registration.'))\n\n return redirect('login')\n\n return render(request, self.template_name, {'form': form})\n\nclass ActivateAccount(View):\n\n def get(self, request, uidb64, token, *args, **kwargs):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.profile.email_confirmed = True\n user.save()\n dj_login(request, user)\n messages.success(request, ('Your account have been confirmed.'))\n return redirect('product_list')\n else:\n messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))\n return redirect('product_list') \n\n#def signup(request):\n# posts = User.objects.all()\n# if request.method =='POST':\n# form = SignUpForm(request.POST, request.FILES)\n# if form.is_valid():\n# form.save()\n# username = form.cleaned_data.get('username')\n# raw_password = form.cleaned_data.get('password')\n# #user = authenticate(username=username, password=raw_password)\n# login(request)\n# return redirect('product_list')\n# else:\n# form = SignUpForm()\n# return render(request, 'registration/register.html', {'form':form})\n\n\n# def login(request):\n# if request.method =='POST':\n# form = loginForm(request.POST, request.FILES)\n# if form.is_valid():\n# form.save()\n# username = form.cleaned_date.get('username')\n# raw_password = form.cleaned_date.get('password')\n# #user = authenticate(username=username, password=raw_password)\n# login(request, user)\n# return redirect('post_list')\n# else: \n# form = loginForm()\n# return render(request, 'templates/food/login.html', {'form':form})","sub_path":"food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"601636380","text":"#Copyright 2019 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# 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\"\"\"\nRecursively extracts the text from a Google Doc.\n\"\"\"\nfrom __future__ import print_function\n\nfrom apiclient import discovery\nfrom httplib2 import Http\nfrom oauth2client import client\nfrom oauth2client import file\nfrom oauth2client import tools\n\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\nDISCOVERY_DOC = 'https://docs.googleapis.com/$discovery/rest?version=v1'\n\ndef initiate_doc_api(DOCUMENT_ID):\n \"\"\"Shows basic usage of the Docs API.\n Prints the title of a sample document.\n \"\"\"\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('reminders/token.pickle'):\n with open('reminders/token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'reminders/credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('reminders/token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('docs', 'v1', credentials=creds)\n\n # Retrieve the documents contents from the Docs service.\n document = service.documents().get(documentId=DOCUMENT_ID).execute()\n print('The title of the document is: {}'.format(document.get('title')))\n return service\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth 2.0 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n store = file.Storage('reminders/token.json')\n credentials = store.get()\n\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets('reminders/credentials.json', SCOPES)\n credentials = tools.run_flow(flow, store)\n return credentials\n\ndef read_paragraph_element(element):\n \"\"\"Returns the text in the given ParagraphElement.\n\n Args:\n element: a ParagraphElement from a Google Doc.\n \"\"\"\n text_run = element.get('textRun')\n if not text_run:\n return ''\n return text_run.get('content')\n\ndef read_strucutural_elements(elements):\n \"\"\"Recurses through a list of Structural Elements to read a document's text where text may be\n in nested elements.\n\n Args:\n elements: a list of Structural Elements.\n \"\"\"\n text = ''\n for value in elements:\n if 'paragraph' in value:\n elements = value.get('paragraph').get('elements')\n for elem in elements:\n text += read_paragraph_element(elem)\n elif 'table' in value:\n # The text in table cells are in nested Structural Elements and tables may be\n # nested.\n table = value.get('table')\n for row in table.get('tableRows'):\n cells = row.get('tableCells')\n for cell in cells:\n text += read_strucutural_elements(cell.get('content'))\n elif 'tableOfContents' in value:\n # The text in the TOC is also in a Structural Element.\n toc = value.get('tableOfContents')\n text += read_strucutural_elements(toc.get('content'))\n return text\n\n\ndef get_text(DOCUMENT_ID):\n \"\"\"Uses the Docs API to print out the text of a document.\"\"\"\n # DOCUMENT_ID= '1RJaBqKsLOjJuHhwWyo7IQ5QKv_0I_JEforjZwAyRQgA'\n credentials = get_credentials()\n http = credentials.authorize(Http())\n docs_service = discovery.build(\n 'docs', 'v1', http=http, discoveryServiceUrl=DISCOVERY_DOC)\n doc = docs_service.documents().get(documentId=DOCUMENT_ID).execute()\n doc_content = doc.get('body').get('content')\n return read_strucutural_elements(doc_content)\n\ndef clear_doc(document_id):\n requests = [\n {\n 'deleteContentRange': {\n 'range': {\n 'startIndex': 10,\n 'endIndex': 15,\n }\n\n }\n\n },\n ]\n result = initiate_doc_api(document_id).documents().batchUpdate(\n documentId=document_id, body={'requests': requests}).execute()\n \n\nreminders_completed = get_text(\"1RJaBqKsLOjJuHhwWyo7IQ5QKv_0I_JEforjZwAyRQgA\")\nreminders_completed = reminders_completed.splitlines()\n\n\n\n\n\n\n","sub_path":"reporter/reminders/get_document.py","file_name":"get_document.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"269264440","text":"#!/usr/local/bin/python\n\nfrom PIL import Image, ImageFilter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \n\nim = Image.open('face.png')\n\nwidth = im.size[0]\nheight = im.size[1]\n\nprint (\"Width of image is %d, Height of image is %d\" % (width,height))\nprint (\" \")\n\npx = im.load()\n\n# split image into 50 x 50 grid\n\nthreshold = 200\nnxbins = 100\nnybins = 100\nxsize = int(width/nxbins)\nysize = int(height/nybins)\nx_pixelstart = int((width - xsize*nxbins)/2)\ny_pixelstart = int((height - ysize*nybins)/2)\n\nprint (\"X Grid Size = %d, Y Grid Size = %d\" % (xsize,ysize))\nprint (\"X Pixel Start = %d, Y Pixel Start = %d\" % (x_pixelstart,y_pixelstart))\n\nxwhite =[0 for x in range(nxbins)]\nywhite =[0 for x in range(nybins)]\nwhitecount = [[0 for x in range(nybins)] for x in range(nxbins)]\n\nfor icount in range(nxbins):\n xwhite[icount]=icount\n xstartpixel=icount*xsize+x_pixelstart\n xendpixel=xstartpixel+xsize\n for jcount in range(nybins):\n ywhite[jcount]=jcount\n ystartpixel=jcount*ysize+y_pixelstart\n yendpixel=ystartpixel+ysize\n for xcount in range(xstartpixel,xendpixel):\n for ycount in range(ystartpixel,yendpixel):\n# print (\"XPixel = %d, YPixel = %d, Pixel Value = %s\" % (xcount,ycount,px[xcount,ycount]))\n if (px[xcount,ycount][0] > threshold) and (px[xcount,ycount][1] > threshold) and (px[xcount,ycount][2] > threshold):\n whitecount[icount][jcount] = whitecount[icount][jcount]+1\n# print (\"I = %d, J = %d, WhiteCount = %d\" % (icount,jcount,whitecount[icount][jcount]))\n\nfig = plt.figure()\nax1 = fig.add_subplot(111,projection='3d')\n\ndata_array = np.array(whitecount)\nx_data, y_data = np.meshgrid(xwhite,ywhite )\n\nx_data = x_data.flatten()\ny_data = y_data.flatten()\nz_data = data_array.flatten()\nax1.bar3d( x_data, y_data, np.zeros(len(z_data)),1,1,z_data )\n\nplt.show()\n","sub_path":"JupyterNotebooks/Fitting/pixel_count_color.py","file_name":"pixel_count_color.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"226760281","text":"# class A:\n# age=18\n# def fun(self):\n# print(self.age)\n# print(A.age)\n#\n#\n# a=A()\n# # a.fun()\n#\n# print(a.age) # 类属性\n# # print(A.age) # 类属性\n#\n# b=A()\n# print(b.age)\n#\n# a.age=20\n# print(a.age) # 20 实例属性\n# print(b.age) # 18 类属性\n#\n# A.age=25\n# print(a.age) # 20\n# print(b.age) # 25\n\n\n#\n#\n# class A:\n# age=18\n#\n# def hehe(hehe):\n# a.hehe=100\n# print(a.age)\n#\n#\n# a=A()\n# a.hehe() # self自动传递当前对象 a.hehe(a)\n# a.age\n# a.hehe=100\n\n\n\n# print(a.age) # age: 类属性\n# print(a.__dict__)\n# print(A.__dict__)\n#\n# a.age=20\n# print(a.__dict__)\n# print(A.__dict__)\n\n\n\n# class A:\n# age=18\n# def hehe(self):\n# print('123')\n# print(self.age)\n#\n# a=A()\n# print(a.__dict__)\n# print(A.__dict__)\n\n\n# import MySQLdb\n#\n# conn=MySQLdb.Connect(host='localhost',port=3306,\n# user='root',password='123456',\n# db='crawler',charset='utf8')\n# cursor=conn.cursor()\n#\n# cursor.execute('select ip,port,types from xici where status=1')\n# print(cursor.fetchone())\n#\n#\n#\n\n\n\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\nsched=BlockingScheduler()\ndef hehe():\n print('123')\nsched.add_job(hehe,'cron',second='*/2')\nsched.start()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"IP代理池/测试.py","file_name":"测试.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"422929061","text":"\nimport pyblish.api\nfrom reveries.maya.plugins import MayaSelectInvalidInstanceAction\n\n\nclass SelectInvalid(MayaSelectInvalidInstanceAction):\n\n label = \"Select Not Versioned\"\n\n\nclass ValidateVersionedTextures(pyblish.api.InstancePlugin):\n \"\"\"All surface node in scene should be part of versioned subset\n\n Should be containerized or instance that is going to be published\n\n \"\"\"\n\n order = pyblish.api.ValidatorOrder\n hosts = [\"maya\"]\n label = \"Has Versioned Textures\"\n families = [\n \"reveries.standin\",\n ]\n\n actions = [\n pyblish.api.Category(\"Select\"),\n SelectInvalid,\n ]\n\n @classmethod\n def get_invalid(cls, instance):\n from maya import cmds\n\n files = set(instance.data[\"fileNodes\"])\n root = instance.data[\"relativeRoot\"]\n\n has_versioned = set()\n for node in files:\n file_path = cmds.getAttr(node + \".fileTextureName\")\n if all(key in file_path for key in root):\n # As long as the texture file path starts with project\n # env vars, consider it's been published.\n has_versioned.add(node)\n\n not_versioned = files - has_versioned\n\n return list(not_versioned)\n\n def process(self, instance):\n invalid = self.get_invalid(instance)\n if invalid:\n for i in invalid:\n self.log.error(i)\n raise Exception(\"Texture node not versioned.\")\n","sub_path":"plugins/maya/publish/validate_versioned_textures.py","file_name":"validate_versioned_textures.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"356198678","text":"\"\"\"\nDeveloped by Projeto Continentais and Petrobras\nauthor: Rudi César Comiotto Modena\nemail: rmodena@unisinos.br\ndate: July, 2020\n\"\"\"\nfrom continentalfuzzy.service.sugeno.operators.NotMethod import NotMethod\n\n\nclass MinAndMethod:\n @classmethod\n def calculate_min_and(cls, inputs, values):\n is_first = True\n min_value = 0\n for r_input in inputs:\n result = r_input.rule_func(values[r_input.name],\n **r_input.params)\n\n if r_input.var_not:\n result = NotMethod.calculate_not(result)\n if is_first:\n min_value = result\n is_first = False\n elif min_value > result:\n min_value = result\n\n elif is_first:\n min_value = result\n is_first = False\n elif min_value > result:\n min_value = result\n\n return min_value\n","sub_path":"continentalfuzzy/service/sugeno/operators/MinAndMethod.py","file_name":"MinAndMethod.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"408113508","text":"#!/usr/bin/python3\nfrom sys import stdin\nfrom collections import defaultdict\nfrom bisect import bisect\n\ndef main ():\n read = stdin.readline\n t = int (read ())\n for t_ in range (t):\n n, m = map (int, read ().split ())\n s = read ().rstrip ()\n e = defaultdict (list)\n for i in range (n):\n c = s [i]\n e [c].append (i)\n # e ... dict of chars with positions minus index in position list\n # to get from differences only count of chars to change\n for c in e:\n e [c] = [p - ipl for ipl, p in enumerate (e [c])]\n mx = 0\n for c in e:\n #print (c, e [c])\n fi, lii = -1, 0\n ln = len (e [c])\n while lii < ln:\n fii = bisect (e [c], fi)\n fi = e [c][fii]\n lii = bisect (e [c], m + fi)\n new = lii - fii + m\n #if c == \"A\": print (\"fi lii fii new\", fi, lii, fii, new, end = \" \")\n if new > mx: mx = new\n if mx > n: mx = n\n print (mx)\n\nif __name__ == \"__main__\": main ()\n","sub_path":"_monk_and_chocolates.py","file_name":"_monk_and_chocolates.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"301522444","text":"#!/usr/bin/env python\n# coding:utf-8\n\n'''\nauto dag\n'''\n\n# **********************************************************\n# * Author : xfzheng\n# * Email : 329472010@qq.com\n# * Create time : 2019-03-29 15:36\n# * Last modified : 2019-03-29 15:36\n# * Filename : adag.py\n# * Description :\n# **********************************************************\n\nfrom __future__ import print_function\n# import logging\nimport os\nimport time\nimport sys\nimport argparse\n\nfrom build_dag import build_dag\nfrom build_pyfile import build_pyfile\nfrom parse_sql import parse_depends\n\n\ndef auto_dag():\n '''\n auto dag\n '''\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--sql-path', dest='sql_path',\n help='需要解析的sql文件路径', nargs='?', default=\".\", required=True)\n\n parser.add_argument('-d', '--dag-id', dest='dagID',\n help='唯一的dag id', nargs='?', default=\"\", required=True)\n\n parser.add_argument('-i', '--interval', dest='interval',\n help='设置任务运行的时间;类似crontab 每天10点[0 10 * * *]', nargs='?', default=\"\", required=True)\n\n parser.add_argument('-p', '--package', dest='package',\n help='保存的文件路径', nargs='?', default=\"\", required=True)\n\n parser.add_argument('-y', '--yes', dest='ifyes',\n help='是否需要确认', nargs='?', default=\"False\", required=False)\n\n args = parser.parse_args()\n\n if not args.ifyes:\n inp = input(\"dagID={},sql_path={},interval={},package={}\\n(Are you sure? Y or N):\".format(\n args.dagID, args.sql_path, args.interval, args.package))\n if not inp or inp in ('N', 'n', 'no', 'NO', 'no'):\n sys.exit()\n\n depends_res = parse_depends(args.sql_path)\n\n cur_path= os.path.dirname(os.path.abspath(__file__))\n class_path = os.path.join(cur_path, \"../template/class_template.tp\")\n build_pyfile(depends_res, args.package, class_path)\n\n depends = [sub_item for item in depends_res for sub_item in item['depends']]\n object_table = set([item['obj_table'] for item in depends_res])\n depends_final = []\n for item in depends:\n it0, it1 = item.split('>>')\n if it0.strip(' ') not in object_table or it0.strip(' ') == it1.strip(' '):\n print(it0, it1)\n else:\n depends_final.append(item)\n\n imports = ['from {}.{} import {}'.format(args.package, item, item.replace('_','').lower().capitalize())\n for item in object_table]\n\n operators = [(item, item.replace('_','').lower().capitalize()) for item in object_table]\n # operators = object_table\n\n dag_id = '{}_{}'.format(args.dagID, time.strftime('%Y%m%d%H', time.localtime()))\n\n if args.package.find('.') >= 0:\n folder_p = args.package.split('.')[0]\n dag_file_name = '{}/{}'.format(folder_p, dag_id + '.py')\n else:\n dag_file_name = dag_id +'.py'\n\n params = {\n 'imports': imports,\n 'start_date':'datetime(2019,01,01)',\n 'email_on_failure':'True',\n 'email_on_retry':'True',\n 'dag_id':dag_id,\n 'interval':args.interval,\n 'operators':operators,\n 'depends':depends_final,\n }\n\n build_dag(args.package, dag_file_name, params)\n\nif __name__ == '__main__':\n auto_dag()\n","sub_path":"bin/adag.py","file_name":"adag.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"176538090","text":"# -*- coding: utf-8 -*-\n\"\"\"\nVarious utility functions, also used in the simplifed version of the module.\n\"\"\"\nfrom datetime import date\nimport re\nimport warnings\nfrom xml.etree.ElementTree import SubElement\n# noinspection PyPep8Naming\nimport xml.etree.ElementTree as ET\nimport zipfile\n\n# These media should be added to the zip file uncompressed\n_NO_COMPRESS = [\"image/png\", \"image/jpeg\", \"image/jpeg\", \"image/gif\"]\n\n\ndef create_epub_file(directory, resources):\n\t\"\"\"\n\tCreation of the epub file itself, ie, the zipped archive, following the specification in EPUB,\n\n\t:param str directory: name of the directory to be packaged\n\t:param resources: set of resources, other then the package file, the mimetype and the container, that has to be added\n\t:type resources: array of (name, media-type) tuples\n\t\"\"\"\n\twith zipfile.ZipFile(directory + '.epub', 'w', zipfile.ZIP_DEFLATED) as book:\n\t\t# First the regular files, generated for all ebooks\n\t\tbook.write(directory + '/mimetype', 'mimetype', zipfile.ZIP_STORED)\n\t\tbook.write(directory + '/META-INF/container.xml', 'META-INF/container.xml')\n\t\tbook.write(directory + '/package.opf', 'package.opf')\n\t\tfor (href, media_type) in resources:\n\t\t\t# These resources should be added to the zip file\n\t\t\t# Images should not be compressed, just stored\n\t\t\tcompress = zipfile.ZIP_STORED if media_type in _NO_COMPRESS else zipfile.ZIP_DEFLATED\n\t\t\tbook.write(directory + \"/\" + href, href, compress)\n\n\ndef package_epub_directory(directory):\n\t\"\"\"\n\tPackage the directory as a zip file for epub. This utility is only used with the option to generate\n\tthe file from the directory directly, without any preceding steps; it extracts the resources\n\tby parsing the package file. It then calls the :py:func:`.create_epub_file` function.\n\n\t:param str directory: name of the directory to be packaged\n\n\t\"\"\"\n\t# Find the directory package file; this relies on the particular structure created by the package\n\tpackagefile = directory + \"/package.opf\"\n\topf = ET.parse(packagefile)\n\n\tresources = []\n\t# Find the list of resources that must be put into the file\n\tfor item in opf.findall(\".//{http://www.idpf.org/2007/opf}item\"):\n\t\tresources.append((item.get(\"href\"), item.get(\"media-type\")))\n\n\tcreate_epub_file(directory, resources)\n\n\n# Generic utility functions to extract information from a W3C TR document...\n# noinspection PyUnusedLocal,PyPep8\ndef get_document_properties(html, target):\n\t\"\"\"\n\t\tFind the extra manifest properties that must be added to the HTML resource in the opf file.\n\n\t\tSee the `IDPF documentation `_ for details\n\n\t\t:param html: the object for the whole document\n\t\t:type html: :py:class:`xml.etree.ElementTree.ElementTree`\n\t\t:param set target: set collecting all possible property values\n\n\t\"\"\"\n\t# If instead. Just adding\n\t# an extra space to a possible link does the trick.\n\tfor script in html.findall(\".//script[@src]\"):\n\t\tif script.text is None:\n\t\t\tscript.text = \" \"\n\treturn html\n\n# noinspection PyPep8Naming\ndef change_DOM(html):\n\t\"\"\"\n\t Changes on the DOM to ensure a proper interoperability of the display among EPUB readers. At the moment, the\n\t following actions are done:\n\n\t 1. Due to the rigidity of the iBook reader, the DOM tree has to change: all children of the ```` should be\n\t encapsulated into a top level block element (we use ``
    ``). This is because iBook imposes\n\t a zero padding on the body element, and that cannot be controlled by the user; the introduction of the top level\n\t block element allows for suitable CSS adjustments.\n\n\t The CSS adjustment is done as follows: the :py:data:`.templates.BOOK_CSS` is extended with the exact\n\t padding values; these are retrieved (depending on the document type) from :py:data:`.config.DOCTYPE_INFO`. The\n\t expansion of :py:data:`.templates.BOOK_CSS` itself happens in the :py:meth:`.doc2epub.DocWrapper.process` method.\n\n\t Note that using simply a \"main\" element as a top level encapsulation is not a good approach, because some files (e.g., generated by\n\t bikeshed) already use that element, and there can be only one of those...\n\n\t 2. If a ``
    `` element has the class name ``highlight``, the Readium extension to\n\t Chrome goes wild. That class name is used only for an internal processing of ReSpec; it is\n\t unused in the various, default CSS content. As a an emergency measure this class name is simply removed from the code, although,\n\t clearly, this is not the optimal way:-( But hopefully this will disappear and this hack can be\n\t removed, eventually.\n\n\t **Note**: this is an `acknowledged bug in Readium `__.\n\t When a newer release of Readium is deployed, this hack should be removed from the code.\n\n\t 3. Some readers *require* to have a ``type=\"text/css\"`` on the the link element for a CSS; otherwise the CSS\n\t is ignored. It is added (doesn't do any harm...)\n\n\t:param html: the object for the whole document\n\t:type html: :py:class:`xml.etree.ElementTree.ElementTree`\n\t\"\"\"\n\n\t# Hack #1\n\tbody = html.find(\".//body\")\n\n\tif len(html.findall(\".//div[@main='role']\")) == 0:\n\t\tmain = SubElement(body, \"div\")\n\t\tmain.set(\"role\", \"main\")\n\n\t\t# All children of body, except for main, should be re-parented to main and removed from body\n\t\t# Note: this is a workaround around what seems to be a bug in the html5parser. Indeed,\n\t\t# the direct creation of an Element object does not work; the SubElement method must be used\n\t\t# but this means that element should be avoided in the cycle below. Sigh...\n\t\tfor child in [x for x in body.findall(\"*\") if not (x.tag == \"div\" and x.get(\"role\", None) == \"main\")]:\n\t\t\tmain.append(child)\n\t\t\tbody.remove(child)\n\n\t# Hack #2\n\t# Change the \"highlight\" class name\n\t# noinspection PyShadowingNames\n\tdef _change_name(x):\n\t\treturn x if x != \"highlight\" else \"book_highlight\"\n\n\tfor pre in html.findall(\".//pre[@class]\"):\n\t\t# there may be several class names\n\t\tcl_names = pre.get(\"class\").split()\n\t\tnew_cl_names = map(_change_name, cl_names)\n\t\tpre.set(\"class\", \" \".join(new_cl_names))\n\n\t# Hack #3\n\t# Add the type=\"text/css\" for stylesheet elements\n\tfor lnk in html.findall(\".//link[@rel='stylesheet']\"):\n\t\tif \"type\" not in lnk.keys():\n\t\t\tlnk.set(\"type\", \"text/css\")\n\n","sub_path":"tr2epub/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"504110363","text":"#coding=utf-8\nimport tornado.web\nfrom handler.basehandler import BaseHandler\nfrom bin import base\n\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nclass EditProjectExperienceHandler(BaseHandler):\n    @tornado.web.authenticated\n    def post(self):\n        job_id = self.get_argument(\"id\", \"\")\n        project_name = self.get_argument(\"project_name\", \"\")\n        project_starttime = self.get_argument(\"project_starttime\", \"\")\n        project_endtime = self.get_argument(\"project_endtime\", \"\")\n        project_detail = self.get_argument(\"project_detail\", \"\")\n        values = dict(project_name=project_name,\n                      project_starttime=project_starttime,\n                      project_endtime=project_endtime,\n                      project_detail=project_detail\n                      )\n\n        from optsql.updateMySQL import update_one_project_experience\n        result = update_one_project_experience(id=job_id, values=values)\n        if result:\n            rtinfo = dict(status=0, result=result)\n        else:\n            rtinfo = dict(status=1, result=\"更改失败!\")\n        self.write(base.get_json(rtinfo))","sub_path":"handler/project_experience/edit_project_experienct.py","file_name":"edit_project_experienct.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"482286741","text":"#공원id(p_id) -> 해당 공원에 있는 운동기구list를 가져오는 appi\nfrom flask_restx import Resource, reqparse\nfrom sqlalchemy.sql.type_api import NULLTYPE\nfrom ._m_equip import Mequip\nimport app\nfrom sqlalchemy import text\n\n\nparser = reqparse.RequestParser()\nparser.add_argument('id', help='공원 ID', type=int, required=True)\n\n@Mequip.route('/p_e_list')\nclass P_E_List(Resource):\n    @Mequip.expect(parser)\n    @Mequip.response(200, 'Success')\n    @Mequip.response(500, 'Internal Server Error')\n    def get(self):\n        args = parser.parse_args()\n        id = args['id']\n\n        sql = 'SELECT * FROM equip WHERE p_id=:id'\n        query = {\n            'id': id\n        }\n        rows = app.app.database.execute(text(sql), query).fetchall()\n        \n        #쿼리 결과가 null\n        if not rows:\n            return {\n                'code': 'error',\n                'message': '(no query results) error'\n            }, 500\n            \n        retVal = [] \n        for row in rows: \n            r = {        \n                    'e_id'     : row['e_id'],\n                    'p_id'     : row['p_id'],\n                    'e_name'   : row['e_name'],\n                    'category' : row['category']\n                }\n            retVal.append(r)\n        \n\n        return {                 \n            'code':'successs',   \n            'message':'',\n            'response': {\n                'List': retVal\n            }\n        }, 200\n\n        \n        \n        \n","sub_path":"socien_api_server/route/__m_equip/p_e_list.py","file_name":"p_e_list.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"610103283","text":"\"\"\"Generic, basic gates (such as AND gates).\n\nThis is implemented as a set of callables which maintain their enumerated\nstate, and return a LUT object with the proper look up table for their function\nand number of bits (inputs).\"\"\"\n\n\nfrom .base import staticvariable\nfrom . import lut\n\n\n@staticvariable('cnt', 0)\ndef AND(bits=2, name=None):\n    if not name:\n        name = 'AND' + str(AND.cnt)\n        AND.cnt += 1\n\n    return lut.LUT(lut.generate_AND(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef OR(bits=2, name=None):\n    if not name:\n        name = 'OR' + str(OR.cnt)\n        OR.cnt += 1\n\n    return lut.LUT(lut.generate_OR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef NOR(bits=2, name=None):\n    if not name:\n        name = 'NOR' + str(NOR.cnt)\n        NOR.cnt += 1\n\n    return lut.LUT(lut.generate_NOR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef NAND(bits=2, name=None):\n    if not name:\n        name = 'NAND' + str(NAND.cnt)\n        NAND.cnt += 1\n\n    return lut.LUT(lut.generate_NAND(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef XOR(bits=2, name=None):\n    if not name:\n        name = 'XOR' + str(XOR.cnt)\n        XOR.cnt += 1\n\n    return lut.LUT(lut.generate_XOR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef XNOR(bits=2, name=None):\n    if not name:\n        name = 'XNOR' + str(XNOR.cnt)\n        XNOR.cnt += 1\n\n    return lut.LUT(lut.generate_XNOR(bits), name=name)\n","sub_path":"logic/gate.py","file_name":"gate.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"337172591","text":"#!/usr/bin/python3.6\n\nimport sys\nfrom itertools import groupby\nfrom operator import itemgetter\n\n\ndef read_mapper_output(file, separator='\\t'):\n    for line in file:\n        yield line.rstrip().split(separator, 1)\n\n\ndef main(separator='\\t'):\n    hashtable={}; # maintain dictionary  to store count of word\n    # input comes from STDIN (standard input)\n    data = read_mapper_output(sys.stdin, separator=separator)\n\n    for current_word, group in groupby(data, itemgetter(0)):\n        try:\n            total_count = sum(int(count) for current_word, count in group)\n            if current_word not in hashtable:\n                hashtable[current_word] = total_count;\n            else:\n                hashtable[current_word] += total_count;\n        except ValueError:\n            # count was not a number, so silently discard this item\n            pass\n\n    sortedTuple = sorted(hashtable.items(), key=itemgetter(1),reverse=True);  # sort hashtable by word occurence count\n    for tuples in sortedTuple:\n        print(\"%s%s%d\" % (tuples[0], separator, tuples[1]));\n\nif __name__ == \"__main__\":\n    main()","sub_path":"part3/Word_Co-occurenc_Sports/Code/reducer_latest.py","file_name":"reducer_latest.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"461054858","text":"import allure\n\nfrom unittest import TestCase\nfrom library.httpclient import HttpClient\n\n\n@allure.feature('Test Weather api')\nclass Weather(TestCase):\n    \"\"\"Weather api test cases\"\"\"\n\n    def setUp(self):\n        \"\"\"Setup of the test\"\"\"\n\n        self.host = 'http://www.weather.com.cn'\n        self.ep_path = '/data/cityinfo'\n        self.client = HttpClient()\n\n    @allure.story('Test of HangZhou')\n    @allure.severity(allure.severity_level.NORMAL)\n    def test_weather_hangzhou(self):\n        city_code = '101210101'\n        exp_city = '杭州'\n        self._test(city_code, exp_city)\n\n    @allure.story('Test of FuYang')\n    @allure.severity(allure.severity_level.MINOR)\n    def test_weather_fuyang(self):\n        city_code = '101220801'\n        exp_city = '阜阳'\n        self._test(city_code, exp_city)\n\n    @allure.story('Test of NingBo')\n    def test_weather_ningbo(self):\n        city_code = '101210401'\n        exp_city = '宁波'\n        self._test(city_code, exp_city)\n\n    @allure.story('Test of ShangHai')\n    @allure.severity(allure.severity_level.BLOCKER)\n    def test_weather_shanghai(self):\n        city_code = '101020100'\n        exp_city = '上海'\n        self._test(city_code, exp_city)\n\n    @allure.story('Test of GuiYang')\n    @allure.severity(allure.severity_level.TRIVIAL)\n    def test_weather_guiyang(self):\n        city_code = '101260101'\n        exp_city = '贵阳'\n        self._test(city_code, exp_city)\n\n    def _test(self, city_code, exp_city):\n        url = f'{self.host}{self.ep_path}/{city_code}.html'\n        response = self.client.Get(url=url)\n        act_city = response.json()['weatherinfo']['city']\n        print(f'Expect city = {exp_city}, while actual city = {act_city}')\n        # self.assertEqual(exp_city, act_city, f'Expect city = {exp_city}, while actual city = {act_city}')\n        self.assertEqual(exp_city, act_city)","sub_path":"test/weather_test.py","file_name":"weather_test.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"639801791","text":"#pip install playsound\nfrom os import listdir\nfrom os.path import isfile, join\nimport random\nfrom playsound import playsound\nimport winsound\n\nclass musicPlayer:\n    wavname = None\n    def Player():\n        global wavname\n        yes = list()\n        audiofiles = [f for f in listdir(r'./audio') if isfile(join(r'./audio', f))]\n        for af in audiofiles:\n            inter = af.split('.')\n            yes.append(int(inter[0]))\n        playnum = random.randint(0,max(yes))\n        wavname = r'./audio/'+str(playnum)+'.wav'\n        winsound.PlaySound(wavname, winsound.SND_ASYNC | winsound.SND_ALIAS )\n    def Stop():\n        winsound.PlaySound(None, winsound.SND_ASYNC)\n","sub_path":"musicPlayer.py","file_name":"musicPlayer.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"520528153","text":"# https://www.interviewbit.com/problems/noble-integer/\n\n# gt := greater than\n# ge := greater than or equal to\n\nclass Solution:\n    # @param A : list of integers\n    # @return an integer\n    def solve(self, nums):\n        \n        nums.sort()\n        nums.reverse()\n        \n        # nums are in descending order\n        #  there are 0 numbers ge nums[0]\n        #  there is  1 number  ge nums[1], the number  at nums[0]\n        #  there are 2 numbers ge nums[2], the numbers at nums[:2]\n        #  there are 3 numbers ge nums[3], the numbers at nums[:3]\n        #  etc...\n        prev_num = None\n        for i, num in enumerate(nums):\n            if num == i:\n                if num != prev_num:\n                    # prev_num > num\n                    # in fact\n                    # nums[:i] > num\n                    # meaning there are\n                    # i = num numbers in nums gt num\n                    return 1\n            prev_num = num\n        return -1\n\n# gotcha:\n# getting rid of duplicates before doing sort() and reverse() does not work\n# \n# for example, given the following list\n# \n# [ 1, 2, 7, 0, 9, 3, 6, 0, 6 ]\n# \n# [ 1, 2, 7, 0, 9, 3, 6 ] # after removing duplicates\n# \n# [ 0, 1, 2, 3, 6, 7, 9 ] # after sorting\n# \n#   0  1  2  3  4  5  6\n# [ 9, 7, 6, 3, 2, 1, 0 ] # after reversing\n# \n# while it is true that there are 3 unique numbers\n# (9, 7, 6) that are gt 3, there are actually\n# 4 numbers that are gt 3 in the original list\n# (9, 7, 6, 6)","sub_path":"interviewbit.com/Arrays/noble_integer.py","file_name":"noble_integer.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"194867085","text":"#coding:utf-8\nimport numpy as np\nimport pandas as pd\nnp.random.seed(2)\nnums = np.random.randn(3)\nprint(nums)\nseries = pd.Series(nums)\nresult = series.pct_change(periods=2)\nprint(result)\n# -0.47302468\n# -2.19246293\n\n# 4.125749","sub_path":"study_pandas/study_ewm.py","file_name":"study_ewm.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"93160242","text":"#!/usr/bin/python3  \n# -*- coding: utf-8 -*-\n# @File    : test_20201011_6周_陈宝顺.py\n# @Author  : Baoshun.Chin\n# @Time    : 2020-10-11 22:32\n# @Site    : \n# @version : V1.0\n\n# 一、作业:\n# 1.使用pytest编写5条商城接口测试case\n\nimport pytest\nimport requests\n# import yaml\n\nip = 'http://121.42.15.146:9090'\n\nclass Test_mtx_case():\n    def setup_class(self):\n        print('开始执行case')\n\n    # 注册case\n    # 1.未注册的账号:符合规范的用户&密码\n    # 2.用户名不正确,密码符合规范\n    # 3.已注册的账号,再次注册\n    # @pytest.mark.skip\n    @pytest.mark.parametrize('accounts,pwd,type,is_agree_agreement,result',\n                             [\n                                 ('chin123', 'abc123456', 'username', '1', '注册成功'),\n                                 ('s', '123456', 'username', '1', '用户名格式由 字母数字下划线 2~18 个字符'),\n                                 ('_abc', '12345', 'username', '1', '账号已存在')\n                             ])\n    def test_register(self, accounts, pwd, type, is_agree_agreement, result):\n        # 注册接口\n        url = ip + '/mtx/index.php?s=/index/user/reg.html'\n        headers = {\n            'X-Requested-With': 'XMLHttpRequest'\n        }\n        data = {\n            'accounts': accounts,\n            'pwd': pwd,\n            'type': type,\n            'is_agree_agreement': is_agree_agreement\n        }\n        res = requests.post(url=url, data=data, headers=headers)\n        r = res.json()\n        print(r)\n        print(r['msg'])\n        assert result == r['msg']\n\n    # 登录case\n    # 1.正确的用户名和密码登录\n    # 2.正确的用户名和错误的密码登录\n    # 3.错误的用户名和错误的密码\n    # 4.未注册的账号登录\n    # @pytest.mark.skip\n    @pytest.mark.parametrize('accounts,pwd,result',\n                             [\n                                 ('1234', '123456', '登录成功'),\n                                 ('1234', '!123478@', '密码错误'),\n                                 ('123A', '123456L', '帐号不存在'),\n                                 ('@12345', 'abcdefg', '帐号不存在')])\n    def test_login(self, accounts, pwd, result):\n        # 登录接口\n        url = ip + '/mtx/index.php?s=/index/user/login.html'\n        headers = {\n            'X-Requested-With': 'XMLHttpRequest',\n        }\n        data = {\n            'accounts': accounts,\n            'pwd': pwd\n        }\n        res = requests.post(url=url, data=data, headers=headers)\n        # print(res.text)\n        r = res.json()\n        print(r)\n        assert result == r['msg']\n\n    def teardown_class(self):\n        print('case执行完毕')\n\nif __name__ == '__main__':\n    pytest.main('test_20201011_6周_陈宝顺.py')","sub_path":"Course0823/Week06/task/test_20201011_6周_陈宝顺.py","file_name":"test_20201011_6周_陈宝顺.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"443798853","text":"\"\"\"\n    tests.tests_dratf04\n    ~~~~~~~~~~~~~~~~~~~~~~\n\n    Test against `Common test suite`_.\n\n    .. _`Common test suite`:: https://github.com/json-schema/JSON-Schema-Test-Suite\n\"\"\"\n\nfrom jsonspec.validators import load, ValidationError, CompilationError\nfrom jsonspec.reference.providers import SpecProvider, ProxyProvider\nfrom jsonspec import driver as json\n\nimport io\nimport os\nimport pytest\nimport logging\nfrom pathlib import Path\nfrom six import PY2\nlogger = logging.getLogger(__name__)\nhere = os.path.dirname(os.path.abspath(__file__))\n\n\ndef contents(*paths):\n    fullpath = os.path.join(here, 'suite', *paths)\n    d = len(fullpath)\n    for filepath in Path(fullpath).glob('**/*.json'):\n        with filepath.open('r', encoding='utf-8') as file:\n            yield json.load(file), filepath.as_posix()[d:].lstrip('/')\n\n\nprovider = ProxyProvider(SpecProvider())\nfor data, src in contents('remotes'):\n    provider[os.path.join('http://localhost:1234', src)] = data\n\n\ndef scenarios(draft):\n    # no ECMA 262 regex parser\n    skip = ['optional/jsregex.json']\n    if PY2:\n        # json module cannot handle well unicode strings\n        skip.extend(('minLength.json', 'maxLength.json'))\n\n    for data, src in contents('tests', draft):\n        if src in skip:\n            continue\n\n        for block in data:\n            for test in block['tests']:\n                yield (block['schema'], test['description'],\n                       test['data'], test['valid'], src)\n\n\n@pytest.mark.parametrize('schema, description, data, valid, src',\n                         scenarios('draft3'))\ndef test_common(schema, description, data, valid, src):\n    try:\n        load(schema, provider=provider,\n             spec='http://json-schema.org/draft-03/schema#').validate(data)\n        if not valid:\n            assert False, description\n    except (ValidationError, CompilationError) as error:\n        if valid:\n            logger.exception(error)\n            assert False, description\n","sub_path":"tests/test_draft03.py","file_name":"test_draft03.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"543984491","text":"# -*- coding: utf-8 -*-\nimport re\nimport urllib\nfrom urlparse import urljoin\nimport scrapy\nimport requests\nimport json\n\n## 用開放資料比對議員性別\nr = requests.get(\"http://cand.moi.gov.tw/of/ap/cand_json.jsp?electkind=0200000\")\nnamejson = json.loads(r.content.strip(' \\s\\n\\r'))\ndef GetGender(json,name):\n    for i in json:\n        s = re.sub(u'[\\s ]', '', i['idname'])\n        if(s==name):\n            return i['sex']\n\n## 轉換年月日格式\ndef GetDate(text):\n    matchTerm = re.search(u'''\n        (?P[\\d]+)[\\s]*年[\\s]*\n        (?P[\\d]+)[\\s]*月[\\s]*\n        (?P[\\d]+)\n    ''', text, re.X)\n    if matchTerm:\n        return '%04d-%02d-%02d' % (int(matchTerm.group('year'))+1911, int(matchTerm.group('month')), int(matchTerm.group('day')))\n    else:\n        return None\n\nclass Spider(scrapy.Spider):\n    name = \"councilors\"\n    allowed_domains = [\"www.kmc.gov.tw\"]\n    start_urls = [\"http://www.kmc.gov.tw/index.php/kmc-info/%E8%AD%B0%E5%93%A1%E8%B3%87%E8%A8%8A\",]\n    download_delay = 0.5\n\n    def parse(self, response):\n        nodes = response.xpath(u'//a[re:test(@title, \"議(員|長)$\")]')\n        for node in nodes:\n            item = {}\n            item['election_year'] = '2014'\n            item['in_office'] = True\n            item['term_start'] = '%s-12-25' % item['election_year']\n            item['term_end'] = {'date': '2018-12-24'}\n            item['name'], item['title'] = node.xpath('@title').extract_first().split()\n            item['gender'] = GetGender(namejson, item['name'])\n            item['county'] = u'基隆市'\n            item['district'] = node.xpath('normalize-space(string(ancestor::tr/td[1]))').extract_first()\n            yield scrapy.Request(urljoin(response.url, node.xpath('@href').extract_first()), callback=self.parse_profile, meta={'item': item})\n\n    def parse_profile(self, response):\n        global namejson\n        item = response.meta['item']\n        item['image'] = response.xpath('//img[contains(@src, \"/member/\")]/@src').extract_first()\n        item['links'] = [{'url': response.url, 'note': u'議會個人官網'}]\n        item['constituency'] = response.xpath('//td/text()').re(u'選區:\\s*(.+)')[0].strip()\n        item['party'] = response.xpath('//td/text()').re(u'政黨:\\s*(.+)')[0].strip()\n        item['birth'] = GetDate(response.xpath('//td/text()').re(u'出生日期:\\s*(.+)')[0]).strip()\n        website = response.xpath('//td/text()').re(u'網站連結:\\s*(.+)')\n        if website:\n            item['links'].append({'url': website[0].strip(), 'note': u'個人網站'})\n        item['contact_details'] = []\n        contact_mappings = {\n            u'連絡電話': 'voice',\n            u'傳真號碼': 'fax',\n            u'服務處': 'address',\n            u'電子郵件': 'email'\n        }\n        for label, name in contact_mappings.items():\n            values = [x.strip() for x in response.xpath(u'//td[re:test(., \"%s:\")]/text()' % '\\s*'.join(label)).re(u'%s:\\s*(.+)\\s*' % label) if x.strip()]\n            for value in values:\n                item['contact_details'].append({\n                    'label': label,\n                    'type': name,\n                    'value': value\n                })\n        item['experience'] = [x.strip() for x in response.xpath(u'//img[contains(@src, \"speaker0\")]')[1].xpath('ancestor::tr/following-sibling::tr[1]//tr/td[1]/text()').extract() if x.strip()]\n        item['platform'] = [x.strip() for x in response.xpath(u'//img[contains(@src, \"speaker0\")]')[2].xpath('ancestor::tr/following-sibling::tr[1]//tr/td[1]/text()').extract() if x.strip()]\n        yield item\n","sub_path":"crawler/kmc/councilors.py","file_name":"councilors.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"509200731","text":"import os\n\nimport numpy as np\nimport numpy.testing as npt\nimport tensorflow as tf\nfrom monty import data\n\ntf.enable_eager_execution()\n\nTEST_FILE_PATH = 'resources/PBMC_test.csv'\n\n\ndef test_download_file_not_present(mocker):\n    try:\n        os.remove(TEST_FILE_PATH)\n    except OSError:\n        pass\n    mocked_s3 = mocker.patch('s3fs.S3FileSystem.get')\n\n    assert data.download_if_not_present(local_file_path=TEST_FILE_PATH) == TEST_FILE_PATH\n    mocked_s3.assert_called_once_with('pbmcasinglecell/PBMC.csv', TEST_FILE_PATH)\n\n\ndef test_download_file_present(mocker):\n    try:\n        os.remove(TEST_FILE_PATH)\n    except OSError:\n        pass\n    dataset = open(TEST_FILE_PATH, 'w')\n    dataset.write(' ')\n    mocked_s3 = mocker.patch('s3fs.S3FileSystem.get')\n\n    assert data.download_if_not_present(local_file_path=TEST_FILE_PATH) == TEST_FILE_PATH\n    assert mocked_s3.call_count == 0\n    os.remove(TEST_FILE_PATH)\n\n\ndef test_create_dataset():\n    iterator = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None).batch(2).make_one_shot_iterator()\n    npt.assert_array_equal(iterator.get_next(), np.array([[2, 1, 0, 1, 0], [0, 0, 0, 0, 0]], dtype=np.float32))\n\n\ndef test_drop_outliers():\n    dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None)\n    non_outliers = data.drop_outliers(dataset, minimum_expressed_genes=1, minimum_library_size=100)\n    iterator = non_outliers.batch(2).make_one_shot_iterator()\n    first_batch = iterator.get_next()\n\n    npt.assert_array_equal(first_batch, np.array([[41, 42, 43, 44, 45]], dtype=np.float32))\n    assert first_batch.shape == (1, 5)\n\n\ndef test_normalize_data():\n    dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None) \\\n        .batch(1)\n    dataset = data.normalize_dataset(dataset)\n    iterator = dataset.make_one_shot_iterator()\n    npt.assert_allclose(iterator.get_next()[0], np.vectorize(lambda x: np.log(x + 1))([2, 1, 0, 1, 0]))\n\n\ndef test_denormalize_data():\n    dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None) \\\n        .batch(1)\n    dataset = data.denormalize_dataset(dataset)\n    iterator = dataset.make_one_shot_iterator()\n    npt.assert_allclose(iterator.get_next()[0], np.vectorize(lambda x: np.exp(x) - 1)([2, 1, 0, 1, 0]))\n\n\ndef test_denormalize_normalize_data():\n    assert [data.denormalize_op(data.normalize_op(x)).numpy() for x in [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]] \\\n           == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]\n","sub_path":"tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"565982646","text":"import pytest, json, jsonpath, requests\n\ndef test_addNew_data():\n    API_url=\"http://thetestingworldapi.com/api/studentsDetails\"\n    f= open('E:/TestFiles/API/requestJson.json', 'r')\n    request_json=json.loads(f.read())\n    response=requests.post(API_url, request_json)\n    print(response.text)\n    print(response.status_code)\n    id=jsonpath.jsonpath(response.json(), 'id')\n    print(\"ID:\", id[0])\n\n    tech_url=\"http://thetestingworldapi.com/api/technicalskills\"\n    f= open('E:/TestFiles/API/techDetails.json', 'r')\n    request_json=json.loads(f.read())\n    request_json['id']=id[0]\n    request_json['st_id']=int(id[0])\n    response=requests.post(tech_url, request_json)\n    print(response.text)\n\n    address_api=\"http://thetestingworldapi.com/api/addresses\"\n    f = open('E:/TestFiles/API/address.json', 'r')\n    request_json = json.loads(f.read())\n    request_json['stId']=id[0]\n    response = requests.post(address_api, request_json)\n    print(response.content)\n    #\n    # finalDetails1=\"http://thetestingworldapi.com/api/FinalStudentDetails/\"+str(id[0])\n    # response=requests.get(finalDetails1)\n    # print(response.text)\n\n","sub_path":"test_end2end.py","file_name":"test_end2end.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"196161580","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 14 19:38:09 2016\n\n@author: vinay.benny\n\"\"\"\n\nimport numpy as  np;\nimport pandas as pd;\nimport os;\nfrom sklearn.feature_selection import VarianceThreshold;\nimport itertools;\nfrom sklearn.decomposition import PCA;\nfrom sklearn.preprocessing import StandardScaler;\nfrom matplotlib import pyplot as plt;\nfrom sklearn.pipeline import Pipeline;\nfrom sklearn.linear_model import LogisticRegression;\nfrom sklearn.grid_search import GridSearchCV;\nfrom sklearn.cross_validation import cross_val_score;\n\n\ndef rem_constant_feat(pd_dataframe):\n    selector = VarianceThreshold();\n    selector.fit(pd_dataframe);\n    variant_indices = selector.get_support(indices=True);\n    all_indices = np.arange(pd_dataframe.columns.size);\n    nonvariant_indices = np.delete(all_indices, variant_indices);\n    pd_dataframe = pd_dataframe.drop(labels=pd_dataframe[nonvariant_indices], axis=1);\n    print(\"  - Deleted %s / %s features (~= %.1f %%)\" % (nonvariant_indices.size, \n          all_indices.size ,100.0 * (np.float(nonvariant_indices.size) / all_indices.size)));\n    return pd_dataframe, nonvariant_indices;\n    \ndef rem_identical_feat(pd_dataframe):\n    delete_feats = [];\n    n_features = pd_dataframe.shape[1]\n    for feat1, feat2 in itertools.combinations(iterable=pd_dataframe.columns, r=2):\n        if np.array_equal(pd_dataframe[feat1], pd_dataframe[feat2]):\n            delete_feats.append(feat2);\n        \n    delete_feats = np.unique(delete_feats);\n    pd_dataframe = pd_dataframe.drop(labels=delete_feats, axis=1);\n    print(\"  - Deleted %s / %s features (~= %.1f %%)\" % (\n    len(delete_feats), n_features,\n    100.0 * (np.float(len(delete_feats)) / n_features)))\n    return pd_dataframe, delete_feats;\n    \ndef apply_norm_feat(pd_dataframe):    \n    normalizer = StandardScaler();    \n    norm_xtrain = normalizer.fit_transform(xtrain); \n    print(\"  - Normalized the training dataset\");\n    return norm_xtrain, normalizer;\n\ndef apply_PCA(xtrain):    \n       \n    pca = PCA(n_components=100);\n    #logistic = LogisticRegression();\n    #pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]); \n    \n    #n_components = [100, 150, 200];\n    #Cs=np.logspace(-4, 4, 3);\n    #estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, logistic__C=Cs), verbose=2);\n    #estimator.fit(xtrain, ytrain);\n    xtrain_comps = pca.fit_transform(xtrain);\n    print(\"  - Applied PCA on the training dataset\");\n    return xtrain_comps, pca;\n    \ndef pca_visualize(pca, xtrain, ytrain):\n    \n    classes = np.sort(np.unique(ytrain))\n    labels = [\"Satisfied customer\", \"Unsatisfied customer\"]\n    fig = plt.figure(figsize=(10, 7))\n    ax = fig.add_subplot(1, 1, 1)\n    colors = [(0.0, 0.63, 0.69), 'black']\n    markers = [\"o\", \"D\"]\n    for class_ix, marker, color, label in zip(\n            classes, markers, colors, labels):\n        ax.scatter(xtrain[np.where(ytrain == class_ix), 0],\n                   xtrain[np.where(ytrain == class_ix), 1],\n                   marker=marker, color=color, edgecolor='whitesmoke',\n                   linewidth='1', alpha=0.9, label=label)\n        ax.legend(loc='best')\n    plt.title(\n        \"Scatter plot of the training data examples projected on the \"\n        \"2 first principal components\")\n    plt.xlabel(\"Principal axis 1 - Explains %.1f %% of the variance\" % (\n        pca.explained_variance_ratio_[0] * 100.0))\n    plt.ylabel(\"Principal axis 2 - Explains %.1f %% of the variance\" % (\n        pca.explained_variance_ratio_[1] * 100.0))\n    plt.show();\n    return;\n    \n    \ndef make_submission(clf, xtest, ids, name='submission_test.csv'):\n    y_prob = clf.predict_proba(xtest)\n    with open(name, 'w') as f:\n        f.write('ID')\n        f.write(',TARGET')\n        f.write('\\n')\n        for id, probs in zip(ids, y_prob):\n            probas = ','.join([id] + map(str, probs.tolist()))\n            f.write(probas)\n            f.write('\\n')\n    print(\"Wrote submission to file {}.\".format(name))    \n\nif __name__ == \"__main__\":    \n    np.random.seed(93);    \n    os.chdir(\"C:/Users/vinay.benny/Documents/Kaggle/Santader\");\n    train = pd.DataFrame.from_csv(\"train.csv\");\n    test = pd.DataFrame.from_csv(\"test.csv\");\n    \n    #Remove constant features in train, and drop the same in test    \n    train, indices = rem_constant_feat(train);\n    test = test.drop(labels=test[indices], axis=1);\n    \n    #Remove identical features in training datasets, and drop the same in test\n    train, feats = rem_identical_feat(train);\n    test = test.drop(labels=feats, axis=1);\n    \n    # Apply normalization to training data, and use the normalizer on test\n    ytrain = train[\"TARGET\"];\n    xtrain = train.drop(labels=\"TARGET\", axis=1);        \n    norm_xtrain, normalizer = apply_norm_feat(xtrain);\n    norm_xtest = normalizer.transform(test);\n    \n    #Apply principal components analysis on training, and transform the test data \n    #xtrain_comps, pcaest = apply_PCA(norm_xtrain);\n    pca = PCA();\n    #xtest_comps = pcaest.transform(norm_xtest);\n    #pca_visualize(pcaest, xtrain_comps, ytrain);\n    \n    #Apply logistic regression on training data\n    logistic = LogisticRegression(); \n    #param_grid_vals = {'C':np.logspace(-4, 4, 3)}\n    pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]);\n    #estimator = GridSearchCV(logistic, param_grid=param_grid_vals, verbose=2);\n    n_components = [100];\n    Cs=np.logspace(-5, -1, 5);\n    estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, logistic__C=Cs), verbose=2);\n    estimator.fit(norm_xtrain, ytrain);\n    \n    ytest_prob = make_submission(estimator, norm_xtest, test.index.values.astype(str));\n    \n    \n    \n    \n    \n    \n    \n    \n       ","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"474193719","text":"\n\nimport math\nimport sys\nimport csv\n\nignore = []\nArrayOfNumObj = []\nArrayOfSymObj = []\n\nclass Tbl():\n    def __init__(self):\n        self.rows = []\n        self.spec = []\n        self.goals = [] \n        self.less = []\n        self.more = []\n        self.name = []\n        self.nums = []\n        self.syms = []\n        self.weight = []\n        global ignore           # holds the indeces of the columns that should be ignored\n        self.all = []               # holds all the categories \n        self.x = []                 # holds all independent columns\n        self.y = []                 # holds all dependent columns\n        \n        \n    def categories(self,i,txt):\n        if txt == \"$\":\n            self.nums.append(i)\n            self.weight.append(1)\n            self.x.append(i)\n            self.all.append(i)\n            \n        elif txt == \"<\":\n            self.nums.append(i)\n            self.weight.append(-1)\n            self.y.append(i)\n            self.all.append(i)\n            self.goals.append(i)\n            self.less.append(i)\n            \n        elif txt == \">\":\n            self.nums.append(i)\n            self.weight.append(1)\n            self.y.append(i)\n            self.all.append(i)\n            self.goals.append(i)\n            self.more.append(i)\n            \n        elif txt == \"!\":\n            self.syms.append(i)\n            self.weight.append(1)\n            self.y.append(i)\n            self.all.append(i)\n                \n        elif txt == \"?\":\n            self.ignore.append(i)\n        \n        else:\n            self.syms.append(i)\n            self.weight.append(1)\n            self.x.append(i)\n            self.all.append(i)\n        \n        return self.nums, self.syms, self.all, self.x, self.y, self.weight\n    \n    def TblUpdate(self,row):\n        self.items = []\n        for i in range(len(row)):\n            self.items.append(row[i])\n        self.rows.append(self.items)\n        \n        return self.rows\n        \n############################################ \n\nclass num():\n    def __init__(self):\n        self.n = 0\n        self.mu = 0\n        self.m2 = 0\n        self.sd = 0\n        self.hi = (-math.exp(32))\n        self.lo = (math.exp(32)) \n        self.w = 1\n        pass\n    \n    def NumUpdate(self,i,x):\n        if i not in ignore:       \n            self.n = self.n + 1\n            if float(x) < self.lo:\n                self.lo = float(x)\n            if float(x) > self.hi:\n                self.hi = float(x)\n            delta = float(x) - self.mu\n            self.mu = self.mu + delta / self.n\n            self.m2 = self.m2 + delta * (float(x) - self.mu)\n            if self.n > 1:\n                self.sd = (self.m2 / (self.n - 1))**0.5\n        \n            return self\n    \n    def norm(self,i,x):\n        if i in ignore:\n            return x\n        else:\n            return (float(x) - self.lo)/(self.hi - self.lo + math.exp(-32))\n            \n############################################ \n\nclass sym():\n    def __init__(self):\n        self.n = 0\n        self.nk = 0\n        self.counts = []\n        self.strings = []\n        self.most = 0\n        self.mode = None\n        self._ent = None\n        pass\n    \n    def SymUpdate(self,i,x):\n        if i not in ignore:\n            self.n = self.n + 1\n            self._ent = None\n            if str(x) not in self.strings:\n                index = len(self.counts)\n                self.strings.append(str(x))\n                self.counts.append(1)\n                \n            else:\n                index = self.strings.index(str(x))\n                self.counts[index] = self.counts[index] + 1 \n                \n            \n            if self.counts[index] > self.most:\n                self.most = self.counts[index]\n                self.mode = str(x)\n        return self\n                \n    def norm(self,i,x):\n        return x\n    \n################################################\n\ndef dominate1(i,j,t, Num):\n    e = 2.71828\n    n = len(t.goals)\n    sum1 = 0\n    sum2 = 0\n    temp_i = 0\n    \n    for index in range(len(t.goals)):\n        ind = t.goals[index]\n        w = t.weight[ind]\n        x = Num[ind].norm(ind, t.rows[i][ind])\n        y = Num[ind].norm(ind, t.rows[j][ind])\n        sum1 = sum1 - e**(w * (float(x)-float(y))/n)\n        sum2 = sum2 - e**(w * (float(y)-float(x))/n) \n        if sum1/n < sum2/n:\n            temp_i = temp_i + 1       # shows how many times i dominates j\n    return sum1/n < sum2/n\n\n################################################\ndef Unsupervised(TableColumn):\n    data = TableColumn\n    n = len(data)\n    data = sorted(data)\n    epsilon = 0.2*(np.std(data))\n    rangeSize = n**0.5\n    binSize = math.ceil(rangeSize)\n    binIndeces = []\n    i = int(binSize)\n    startIndex = 0\n    counter = 1\n    while i < n-1:\n        while span(data,startIndex,i) < epsilon:\n            if i+1 > n-1:\n                break\n            else:\n                i = i + 1\n        binIndeces.append(i)\n        \n        if (i + int(binSize) - 1) < n-1:\n            print (\"%d:\"%counter, \"Range size = %d\" %(i-startIndex), \", span = %f\" %span(data,startIndex,i), \", lo = %.10f\" % min(data[startIndex:i]), \", hi = %.10f\" % max(data[startIndex:i]))\n            counter = counter + 1\n            startIndex = i \n            i = i + int(binSize) \n        else: \n            print (\"%d:\"%counter, \"Range size = %d\" %(len(data)-startIndex), \", span = %f\" %span(data,startIndex,i), \", lo = %.10f\" % min(data[startIndex:i]), \", hi = %.10f\" % max(data[startIndex:i]))\n            break\n            \n        \n    return binIndeces,data\n\n###############################################################\n\ndef supervised(data,labels):\n    ranges = []\n    for i in range(len(labels)+1):\n        globals()['range%s' % str(i+1)] = []\n    number = 2\n    i = 0\n    for j in range(len(labels)):\n    \n        while j==0 and data[i] < labels[j]:\n            range1.append(data[i])\n            i = i + 1\n            if i > len(data)-1:\n                break\n        if j == 0:\n            ranges.append(range1)\n                \n        while i < len(data)-1 and j < len(labels)-1 and labels[j] <= data[i] and data[i] < labels[j+1]:\n            globals()['range%s' % str(number)].append(data[i])\n            i = i + 1\n            if i > len(data)-1:\n                    break \n        if number < len(labels) + 1:     \n            ranges.append(globals()['range%s' % str(number)])\n            number = number + 1\n            \n        while j == len(labels) - 1 and data[i] >= labels[j]:\n            globals()['range%s' % str(number)].append(data[i])\n            i = i + 1\n            if i > len(data)-1:\n                break\n\n    ranges.append(globals()['range%s' % str(number)])\n    counter = 1\n    for i in range(len(ranges)):\n        print (\"Label = %d:\"%counter, \"most = %.10f\" %ranges[i][len(ranges[i])-1])\n        counter = counter + 1\n        \n    return ranges\n\n\ndef span(data,startingIndex, endIndex):\n    delta = max(data[startingIndex:endIndex]) - min(data[startingIndex:endIndex])\n    return delta\n####################################################################################\n\ndef sortDom(domHolder,Table,features):\n    dom = 0\n    temp = Table\n    for i in range(len(Table.rows)):\n         if dominate1(dom,i,Table, features):   \n            dom = i\n    domHolder.append(dom)        \n    del temp[dom]\n    sortDom(domHolder,temp,features)\n\n    return domHolder        \n            \n#####################################################################################            \nTable = Tbl()\n\n#FileName = sys.argv[-1]\nFileName = 'auto.csv'\nrow_counter = 0\nNum_objectHolder = []\nSym_objectHolder = []\nwith open(FileName, 'rb') as csvfile:\n    reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n    #print(reader)\n    for row in reader:\n        if row_counter == 0:\n            print (row)\n            for i in range (len(row)):\n                txt = row[i][0]\n                Table.categories(i,txt)\n            for j in range(len(Table.nums)):\n                globals()['Num%s' % Table.nums[j]] = num()\n                        \n            for j in range(len(Table.syms)):\n                globals()['Sym%s' % Table.syms[j]] = sym()\n            row_counter = 1\n        \n        else:\n            if '?' in row:   # ignoring those rows with missing value\n                continue   \n                \n            else:\n                if i in Table.nums:\n                    index = Table.nums.index(i)\n                    Num_objectHolder.append(globals()['Num%s' % Table.nums[index]].NumUpdate(i, row[i]))\n\n               \n                if i in Table.syms:\n                    index = Table.syms.index(i)\n                    Sym_objectHolder.append(globals()['Sym%s' % Table.syms[index]].SymUpdate(i, row[i]))\n            Table.TblUpdate(row)\n            \n\ndomHolder = []\nsortDom(domHolder,Table, Num_objectHolder)\n \n\n","sub_path":"HW4/HW4.py","file_name":"HW4.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"516194632","text":"# compressing text using static huffman algorithm\n# static huffman algorithm:\n# step 1: calculate frequency of each character\n# step 2: build an huffman tree base on frequency of each character\n# step 3: assign bit value to each branches\n\nclass StaticHuffman:\n    def __init__(self, string=None, path=None):\n        self.__string = string\n        self.__path = path  # for input file (will implement later)\n        self.__codes = {}  # storing binary encode of each characters\n\n    class HuffmanNode:\n        def __init__(self, char, freq, left=None, right=None):\n            self.char = char\n            self.freq = freq\n            self.left = left\n            self.right = right\n\n    # generate frequency dictionary for building huffman tree\n    def gen_frequency_dict(self):\n        frequency = {}\n        string = self.__string\n        for char in string:\n            if not char in frequency:\n                frequency[char] = 0\n            frequency[char] += 1\n\n        return frequency\n\n    # generate huffman tree's root with child\n    def __gen_huffman_tree(self):\n\n        # support method for generating huffman tree\n        def get_two_min_node(node_list):\n            lst = sorted(node_list, key = lambda x: x.freq, reverse=False)\n\n            first_min_node = lst[0]\n            second_min_node = lst[1]\n\n            return [first_min_node, second_min_node]\n\n        huffman_list = []\n        frequency_dict = self.gen_frequency_dict()\n\n        for char in frequency_dict:\n            node = self.HuffmanNode(char, frequency_dict[char])\n            huffman_list.append(node)\n\n        # keep removing two smallest frequency node and\n        # adding the sum of frequency as an new node\n        # to the node list until getting the root of the tree\n        while (len(huffman_list) > 1):\n            first_node, second_node = get_two_min_node(huffman_list)\n            huffman_list.remove(first_node)\n            huffman_list.remove(second_node)\n\n            node = self.HuffmanNode(None, first_node.freq + second_node.freq, first_node, second_node)\n            huffman_list.append(node)\n\n        return huffman_list[0]\n\n    # support method to assign binary number to branch\n    def __gen_code_helper(self, root, current_code):\n        if (root == None):\n            return\n\n        if root.char != None:\n            self.__codes[root.char] = current_code\n            return\n\n        self.__gen_code_helper(root.left, current_code + \"0\")\n        self.__gen_code_helper(root.right, current_code + \"1\")\n\n    def gen_code(self):\n        root = self.__gen_huffman_tree()\n        current_code = \"\"\n        self.__gen_code_helper(root, current_code)\n        return self.__codes\n\n\n# =================== END OF STATIC HUFFMAN CLASS ============================\n\nif __name__ == '__main__':\n    string = \"abbc\"\n    static_huffman = StaticHuffman(string)\n    print(static_huffman.gen_frequency_dict())\n    print(static_huffman.gen_code())","sub_path":"HW/HW-06/static_huffman.py","file_name":"static_huffman.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"465589396","text":"import pyrealsense2 as rs\nimport numpy as np\nimport cv2\n\n\n#Abrimos\npipeline = rs.pipeline()\nconfig = rs.config()\n\nconfig.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30)\n\n# Iniciamos el stream\npipeline.start(config)\n\n\ndef DibujarContornos(imagen,contornos,color,Palabra):\n    for c in contornos:\n        M = cv2.moments(c)\n        if (M[\"m00\"]==0):M[\"m00\"]=1\n        x = int(M[\"m10\"] / M[\"m00\"])\n        y = int(M[\"m01\"] / M[\"m00\"])\n        cv2.drawContours(imagen,[c],0,color,2)\n        epsilon = 0.1*cv2.arcLength(c,True)\n        approx = cv2.approxPolyDP(c,epsilon,True)\n        cv2.drawContours(imagen,approx,0,color,2)\n        cv2.putText(imagen,str(Palabra),(x,y),1,2,(0,0,0),2)\n\n\ntry:\n    while True:\n        frames = pipeline.wait_for_frames()#Obtiene frame\n        color = frames.get_color_frame()\n        if not color:\n            continue\n        color_image = np.asanyarray(color.get_data())\n        hsv_image = cv2.cvtColor(color_image,cv2.COLOR_BGR2HSV)#Convertimos BGR  a HSV para deteccion de colores\n\n\n        #Comenzamos a definir los limites del color rojo\n        Red_Min = (165,90,80)#HSV\n        Red_Max = (180,255,255)#HSV\n\n        #Comenzamos a definir los limites del color Azul\n        BLue_Min = (90,90,80)#HSV\n        Blue_Max = (135,255,255)#HSV\n        #Hacemos la discriminacion de valores que no pertenecen al rojo\n        mascaraR = cv2.inRange(hsv_image,Red_Min,Red_Max)#verifica cuales pixeles  estan dentro del rango, los que no esten los hace negros\n        Red_Output = cv2.bitwise_and(color_image,color_image,mask=mascaraR)#la imagen de entrada se filtra con la mascara y se genera la salida (entrada,salida,mascara)\n\n\n        #SECCION DEL AZUL\n        mascaraB = cv2.inRange(hsv_image,BLue_Min,Blue_Max)#verifica cuales pixeles  estan dentro del rango, los que no esten los hace negros\n        Blue_Output = cv2.bitwise_and(color_image,color_image,mask=mascaraB)#la imagen de entrada se filtra con la mascara y se genera la salida (entrada,salida,mascara)\n\n        #Contornos Rojos\n        ContornoRojo = cv2.findContours(mascaraR,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]\n        DibujarContornos(color_image,ContornoRojo,(255,255,255),\"Equipo\")\n        #Contornos Azules\n        ContornoAzul = cv2.findContours(mascaraB,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]\n        DibujarContornos(color_image,ContornoAzul,(255,255,255),\"Enemigo\")\n\n\n        cv2.imshow('RGB', color_image)\n        cv2.imshow('Rojo', Red_Output)\n        cv2.imshow('Azul', Blue_Output)\n\n\n        cv2.waitKey(1)#muestra la imagen en N milisegundos\n\nfinally:\n    pipeline.stop()\n","sub_path":"Contornos.py","file_name":"Contornos.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"189648452","text":"import os\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\nclass L2Norm(nn.Module):\n    def __init__(self,n_channels, scale):\n        super(L2Norm,self).__init__()\n        self.n_channels = n_channels\n        self.gamma = scale or None\n        self.eps = 1e-10\n        self.weight = nn.Parameter(torch.Tensor(self.n_channels))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        init.constant(self.weight,self.gamma)\n\n    def forward(self, x):\n        norm = x.pow(2).sum(dim=1, keepdim=True).sqrt()+self.eps\n        #x /= norm\n        x = torch.div(x,norm)\n        # print('weight L2:',self.weight.size(),self.weight[0],x.size())\n        out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x) * x\n        return out\n\nclass VGG(object):\n    def __init__(self,batch_norm=False):\n        self.layer1 = self.block(2,3,64,maxp=False)\n        self.layer2 = self.block(2,64,128)\n        self.layer3 = self.block(3,128,256)\n        self.layer4 = self.block(3,256,512,mmode=True)\n        self.layer5 = self.block(3,512,512)\n        self.layer6 = nn.Conv2d(512,1024,kernel_size=3,padding=6,dilation=6)\n        self.layer7 = nn.Conv2d(1024,1024,kernel_size=1)\n        self.relu = nn.ReLU(inplace=True)\n        self.maxpool1 = nn.MaxPool2d(kernel_size=2,stride=2)\n\n    def conv2(self,kernel_in,kernel_out,k_size,padd=1,bnorm=False):\n        conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd)\n        norm = nn.BatchNorm2d(kernel_out)\n        relu = nn.ReLU(inplace=True)\n        if bnorm :\n            layers = [conv,norm,relu]\n        else:\n            layers = [conv,relu]\n        return layers\n    def maxpool(self,km_size=2,step=2,mode=False):\n        return [nn.MaxPool2d(kernel_size=km_size,stride=step,ceil_mode=mode)]\n\n    def block(self,n,filter_in,filter_out,batch_norm=False,mmode=False,maxp=True):\n        layers = []\n        if maxp:\n            layers.extend(self.maxpool(mode=mmode))\n        layers+=(self.conv2(filter_in,filter_out,3,bnorm=batch_norm))\n        for i in range(1,n):\n            layers.extend(self.conv2(filter_out,filter_out,3,bnorm=batch_norm))\n        return layers\n\n    def forward(self):\n        layers = []\n        layers+=self.layer1\n        layers.extend(self.layer2)\n        layers.extend(self.layer3)\n        layers.extend(self.layer4)\n        layers.extend(self.layer5)\n        layers.extend([self.maxpool1])\n        layers.extend([self.layer6])\n        layers.extend([self.relu])\n        layers.extend([self.layer7])\n        layers.extend([self.relu])\n        return layers\n\nclass ExtractLayers(object):\n    def __init__(self,filter_in):\n        self.layer1 = self.conv2(filter_in,256,1,0)\n        self.layer2 = self.conv2(256,512,3,1,2)\n        self.layer3 = self.conv2(512,128,1,0)\n        self.layer4 = self.conv2(128,256,3,1,2)\n\n    def conv2(self,kernel_in,kernel_out,k_size,padd=1,step=1,bnorm=False):\n        conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd,stride=step)\n        norm = nn.BatchNorm2d(kernel_out)\n        relu = nn.ReLU(inplace=True)\n        if bnorm :\n            layers = [conv,norm,relu]\n        else:\n            # layers = [conv,relu]\n            layers = [conv]\n        return layers\n    def forward(self):\n        layers = []\n        layers += self.layer1\n        layers.extend(self.layer2)\n        layers.extend(self.layer3)\n        layers.extend(self.layer4)\n        return layers\n\nclass Multibox(object):\n    def __init__(self,num_classes,prior_num=1):\n        anchors = prior_num*4\n        cls_num = num_classes * prior_num\n        self.regress_layer1 = self.conv2(256,anchors,3)\n        self.regress_layer2 = self.conv2(512,anchors,3)\n        self.regress_layer3 = self.conv2(512,anchors,3)\n        self.regress_layer4 = self.conv2(1024,anchors,3)\n        self.regress_layer5 = self.conv2(512,anchors,3)\n        self.regress_layer6 = self.conv2(256,anchors,3)\n        self.confidence_layer1 = self.conv2(256,3+(cls_num-1),3)\n        self.confidence_layer2 = self.conv2(512,cls_num,3)\n        self.confidence_layer3 = self.conv2(512,cls_num,3)\n        self.confidence_layer4 = self.conv2(1024,cls_num,3)\n        self.confidence_layer5 = self.conv2(512,cls_num,3)\n        self.confidence_layer6 = self.conv2(256,cls_num,3)\n\n    def conv2(self,kernel_in,kernel_out,k_size,padd=1,dilate=1,bnorm=False):\n        conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd,dilation=dilate)\n        norm = nn.BatchNorm2d(kernel_out)\n        if bnorm :\n            layers = [conv,norm]\n        else:\n            layers = [conv]\n        return layers\n    def forward(self):\n        loc = list()\n        conf = list()\n        loc += self.regress_layer1\n        loc.extend(self.regress_layer2)\n        loc.extend(self.regress_layer3)\n        loc.extend(self.regress_layer4)\n        loc.extend(self.regress_layer5)\n        loc.extend(self.regress_layer6)\n        conf += self.confidence_layer1\n        conf.extend(self.confidence_layer2)\n        conf.extend(self.confidence_layer3)\n        conf.extend(self.confidence_layer4)\n        conf.extend(self.confidence_layer5)\n        conf.extend(self.confidence_layer6)\n        return conf,loc\n\nclass S3FD(nn.Module):\n    def __init__(self,class_num,num_anchor=1):\n        super(S3FD,self).__init__()\n        #self.lo = nn.Sequential(*vgg(cfg,3))\n        net = VGG()\n        add_layers = ExtractLayers(1024) \n        Head = Multibox(class_num,num_anchor)\n        head0,head1 = Head.forward()\n        self.num_classes = class_num\n        self.vgg = nn.ModuleList(net.forward())\n        self.extras = nn.ModuleList(add_layers.forward())\n        self.conf = nn.ModuleList(head0)\n        self.loc = nn.ModuleList(head1)\n        self.L2Norm3_3 = L2Norm(256, 10)\n        self.L2Norm4_3 = L2Norm(512, 8)\n        self.L2Norm5_3 = L2Norm(512, 5)\n        self.softmax = nn.Softmax(dim=-1)\n        # self.num_anchors = 34125\n        self.num_anchor = num_anchor\n        self.fpn_sizes = [25600,6400,1600,400,100,25]\n        #self.extracts = nn.ModuleList(add_extras(extras_cfg,1024))\n    def forward(self,x):\n        fpn = list()\n        loc = list()\n        conf = list()\n        iou = list()\n        # x = x.permute(0,3,1,2)\n        for idx in range(16):\n            x = self.vgg[idx](x)\n        s = self.L2Norm3_3(x)\n        fpn.append(s)\n        for idx in range(16,23):\n            x = self.vgg[idx](x)\n        s = self.L2Norm4_3(x)\n        fpn.append(s)\n        for idx in range(23,30):\n            x = self.vgg[idx](x)\n        s = self.L2Norm5_3(x)\n        fpn.append(s)\n        for idx in range(30,len(self.vgg)):\n            x = self.vgg[idx](x)\n        fpn.append(x)\n        for idx,tmp in enumerate(self.extras):\n            x = tmp(x)\n            x = F.relu(x, inplace=True)\n            if idx == 1 or idx==3:\n                fpn.append(x)\n        #calcu the class_score and location_regress\n        loc_x = self.loc[0](fpn[0])\n        conf_x = self.conf[0](fpn[0])\n        max_conf, _ = torch.max(conf_x[:, 0:3, :, :], dim=1, keepdim=True)\n        conf_x = torch.cat((max_conf, conf_x[:, 3:, :, :]), dim=1)\n        loc.append(loc_x.permute(0, 2, 3, 1).contiguous())\n        conf.append(conf_x.permute(0, 2, 3, 1).contiguous())\n        for i in range(1, len(fpn)):\n            x = fpn[i]\n            # tmpx = self.conf[i](x)\n            # tmpy = self.loc[i](x)\n            # N,A,H,W = tmpx.shape\n            conf.append(self.conf[i](x).permute(0, 2, 3, 1).contiguous())\n            loc.append(self.loc[i](x).permute(0, 2, 3, 1).contiguous())\n            # tmpx = tmpx.view(N,-1,self.num_classes,H,W)\n            # conf.append(tmpx.permute(0,3,4,1,2))\n\n        # loc = torch.cat([layer_tmp.view(layer_tmp.size(0), -1) for layer_tmp in loc], 1)\n        # conf = torch.cat([layer_tmp.view(layer_tmp.size(0), -1) for layer_tmp in conf], 1)\n        loc = torch.cat([layer_tmp.view(-1,self.fpn_sizes[idx]*4*self.num_anchor) for idx,layer_tmp in enumerate(loc)],1)\n        conf = torch.cat([layer_tmp.view(-1,self.fpn_sizes[idx]*self.num_anchor*self.num_classes) for idx,layer_tmp in enumerate(conf)],1)\n        # output = (loc.view(loc.size(0), -1, 4),self.softmax(conf.view(conf.size(0), -1,self.num_classes)))\n        # output = (loc.view(-1,self.num_anchors,4),self.softmax(conf.view(-1,self.num_anchors,self.num_classes)))\n        # output = (loc,conf)\n        output = (loc.view(loc.size(0), -1, 4),conf.view(conf.size(0), -1, self.num_classes))\n        return output\n\n    def weights_init(self, m):\n        if isinstance(m, nn.Conv2d):\n            self.xavier(m.weight.data)\n            m.bias.data.zero_()\n    def xavier(self, param):\n        init.xavier_uniform(param)\n\n\nif __name__==\"__main__\":\n    a = torch.ones([1,3,640,640])\n    net = S3FD(2)\n    print(net)\n    c= net(a)","sub_path":"src/network/vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":8879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"561944153","text":"\r\nimport cv2\r\nimport numpy as np\r\n\r\nclass palletHandler(object):\r\n    pass\r\n    def __init__(self, window_name, mode = \"RGB\", h = 150, w = 500):\r\n        self.mode = mode # RGB, BGR, HSV\r\n        self.h, self.w = h, w\r\n        self.color = np.zeros((h, w, 3), np.uint8)\r\n        self.a, self.b, self.c = 0,0,0\r\n        self.wind = window_name\r\n        cv2.namedWindow(self.wind)\r\n        \r\n        if self.mode == \"RGB\":\r\n            cv2.createTrackbar('R', self.wind, 0, 127, self.na)\r\n            cv2.createTrackbar('G', self.wind, 0, 127, self.na)\r\n            cv2.createTrackbar('B', self.wind, 0, 127, self.na)\r\n        elif self.mode == \"HSV\":\r\n            cv2.createTrackbar('H', self.wind, 0, 180, self.na)\r\n            cv2.createTrackbar('S', self.wind, 0, 127, self.na)\r\n            cv2.createTrackbar('V', self.wind, 0, 127, self.na)\r\n\r\n    def update(self):\r\n        \"\"\"Returns the pallet RGB\"\"\"\r\n        cv2.imshow(self.wind, self.color)\r\n        if self.mode == \"RGB\":\r\n            self.a = cv2.getTrackbarPos('R', self.wind) * 2\r\n            self.b = cv2.getTrackbarPos('G', self.wind) * 2\r\n            self.c = cv2.getTrackbarPos('B', self.wind) * 2\r\n            self.color[:] = [self.c, self.b, self.a]\r\n        elif self.mode == \"HSV\":\r\n            self.a = cv2.getTrackbarPos('H', self.wind)\r\n            self.b = cv2.getTrackbarPos('S', self.wind) * 2\r\n            self.c = cv2.getTrackbarPos('V', self.wind) * 2\r\n            self.color[:] = cv2.cvtColor(np.uint8([[[self.a, self.b, self.c]]]), cv2.COLOR_HSV2RGB)[0][0]\r\n\r\n        return self.a, self.b, self.c\r\n\r\n    def set_values(self, v1, v2, v3):\r\n        if self.mode == \"RGB\":\r\n            cv2.setTrackbarPos('R', self.wind, v1)\r\n            cv2.setTrackbarPos('G', self.wind, v2)\r\n            cv2.setTrackbarPos('B', self.wind, v3)\r\n        elif self.mode == \"HSV\":\r\n            cv2.setTrackbarPos('H', self.wind, v1)\r\n            cv2.setTrackbarPos('S', self.wind, v2)\r\n            cv2.setTrackbarPos('V', self.wind, v3)\r\n\r\n    def na(*_, **__):\r\n        pass\r\n","sub_path":"prob1_Tracking/Old/palletHandler.py","file_name":"palletHandler.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"432988486","text":"# -*- coding: utf-8 -*-\n# 爬取网易悦图上的图片  (财经类)\nimport requests\nimport re\nimport json\nimport os\nimport time\nfrom bs4 import BeautifulSoup\nimport pymysql\nimport pymysql.cursors\nfrom yuntu import YunTu\nimport jieba\n\n\nprint('连接到mysql服务器...')\ndb = pymysql.connect(\"localhost\",\"root\",\"123456\",\"specialthing\",charset=\"utf8\")\nprint('连接上了!')\ncursor = db.cursor()\ncursor.execute(\"DROP TABLE IF EXISTS EVENT\")\n\nsql1 = \"\"\"CREATE TABLE EVENT(\n        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n        title VARCHAR(100) DEFAULT NULL,\n        tag VARCHAR(100) DEFAULT NULL,\n        description VARCHAR(500) DEFAULT NULL,\n        article VARCHAR(10000) DEFAULT NULL)\"\"\"\n\ncursor.execute(sql1)\nprint('================')\n\nprint('请输入事件:')\nsearchEvent = input(\"searchEvent:\")\nheaders = {\n    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',\n}\n\n\ndata = []\ndata2 = ''\n\n# i为页数,可以设置大一点\nfor i in range(1, 10):\n    url = 'http://api.search.sina.com.cn/?c=news&t=&q=%s&page=%d&sort=rel&num=10&ie=utf-8&qq-pf-to=pcqq.c2c' % (searchEvent, i)\n\n    r = requests.get(url, headers=headers)\n    # print(r.text)\n    # 匹配所有的url,'.{3,200}' 为url为长度控制\n    temp = re.findall(r'\"url\":\"(http:.{3,200}.shtml)\",', r.text, re.S)\n    # print(temp)\n    # print(len(temp))\n    # 去掉url里面的'\\',这样request就不会出错。\n    for j in temp:\n        j = j.replace('\\\\', '')\n        data.append(j)\nprint(data)\nprint(len(data))\n\n# 遍历data里面的url,逐个网页获取我们要的内容,并存进数据库。   有些文章的article形式不统一,所以会出现一些空的article\nfor url in data:\n    r = requests.get(url)\n    r.encoding = ('utf-8')\n    # 非常致命的一点,如果html代码开头就有注释的话,BeautifulSoup是找不到想要的标签的!!!! 所以破坏掉前面的注释!\n    html = r.text.replace('', '')\n    # html = open('1.html', 'r', encoding='utf-8').read().replace('', '')\n    # print(html)\n    title = []\n    tag = []\n    description = []\n    article = []\n\n    try:\n        soup = BeautifulSoup(html, \"html5lib\")  # 配置soup  'html5lib'优点:最好的容错性,以浏览器的方式解析文档,生成HTML5格式的文档  缺点:速度慢,不依赖外部扩展\n\n        # title = re.findall(r'', html, re.S)[0]  # 有缺陷,meta是写给浏览器和爬虫看的,没有这个也不会影响内容,所有尽量后body里面的属性\n        # keywords = re.findall(r'', html, re.S)[0]\n        tag = re.findall(r'', html, re.S)[0]  # 但是非title属性一般都会在mata里面有,方便浏览器检索。\n        description = re.findall(r'', html, re.S)[0]\n        # article = re.findall(r'
    ', html, re.S)[0]\n\n # BeautifulSoup去掉特定标签及内容的方法!!!! 对象为 soup对象\n [s.extract() for s in soup('script')]\n [s.extract() for s in soup('style')]\n\n # print(soup.find_all(\"div\", class_='article'))\n\n title = soup.find_all(class_='main-title')[0] # 寻找 'main-title'类的内容\n title = re.sub(r'<[^>]*>', \"\", str(title)) # 去标签!\n article = soup.find_all(\"div\", class_='article')[0]\n article = re.sub(r'<[^>]*>', \"\", str(article)) # 去掉所有的html标签!! 剩下的基本上都是文本内容。\n data2 += article # 字符串拼接,后面传给 wordcloud\n except:\n pass\n # article = re.sub(r'<[^>]*>', \"\", str(article))\n\n # 存入数据库,由于id设置为主键自增,所以这里不需要写id的值 原始数据!!!\n sql = \"INSERT INTO EVENT(title, tag, description, article) VALUES('%s', '%s', '%s', '%s')\" % (title, tag, description, article)\n try:\n cursor.execute(sql)\n db.commit()\n except:\n pass\n\na = []\nprint(data2) # 分词前\nwords = list(jieba.cut(data2)) # 分词后\nfor word in words:\n if len(word) > 1:\n a.append(word)\ntxt = r' '.join(a)\nprint(txt)\nYunTu.wordcloudplot(txt)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cp_specialThing2.py","file_name":"cp_specialThing2.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"150955230","text":"from fabric.api import task, sudo, cd, env, execute\nfrom fabric.utils import warn\nfrom fabkit.common.utils import TRUE_ARGS\n\n\ndef _pre_deploy():\n execute('db.backup')\n\n\n@task\ndef deploy(pre_deploy=True, post_deploy=True):\n \"\"\" Deployment via git pull directly on the server. For use on the older sites\"\"\"\n if pre_deploy in TRUE_ARGS:\n _pre_deploy()\n\n with cd(env.project_root):\n sudo('git pull --rebase', user=env.run_as)\n\n if post_deploy in TRUE_ARGS:\n _post_deploy()\n\n\ndef _post_deploy():\n \"\"\" Some of the older websites may not have django static files\"\"\"\n \n execute('website.app.pip_install')\n execute('website.app.syncdb')\n execute('website.app.migrate')\n\n if env.get('run_collectstatic', True):\n execute('website.app.collectstatic')\n else:\n warn(\"collectstatic skipped\")\n\n execute('website.reload')\n\n custom_post_deploy = env.get('post_deploy', None)\n if custom_post_deploy:\n execute(custom_post_deploy)","sub_path":"fabkit/website/legacy.py","file_name":"legacy.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"73255560","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/breilly/git/fm-orchestrator/module_build_service/db_session.py\n# Compiled at: 2019-12-12 15:53:56\nimport sqlalchemy.event\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.pool import NullPool\nfrom module_build_service import conf\nfrom module_build_service.models import session_before_commit_handlers\n__all__ = ('db_session', )\n\ndef _setup_event_listeners(db_session):\n \"\"\"\n Starts listening for events related to the database session.\n \"\"\"\n if not sqlalchemy.event.contains(db_session, 'before_commit', session_before_commit_handlers):\n sqlalchemy.event.listen(db_session, 'before_commit', session_before_commit_handlers)\n from module_build_service.monitor import db_hook_event_listeners\n db_hook_event_listeners(db_session.bind.engine)\n\n\ndef apply_engine_options(conf):\n options = {'configuration': {'sqlalchemy.url': conf.sqlalchemy_database_uri}}\n if conf.sqlalchemy_database_uri.startswith('sqlite://'):\n options.update({'connect_args': {'check_same_thread': False}, 'poolclass': NullPool})\n else:\n pool_options = {}\n\n def apply_mbs_option(mbs_config_key, sa_config_key):\n value = getattr(conf, mbs_config_key, None)\n if value is not None:\n pool_options[sa_config_key] = value\n return\n\n apply_mbs_option('sqlalchemy_pool_size', 'pool_size')\n apply_mbs_option('sqlalchemy_pool_timeout', 'pool_timeout')\n apply_mbs_option('sqlalchemy_pool_recycle', 'pool_recycle')\n apply_mbs_option('sqlalchemy_max_overflow', 'max_overflow')\n options.update(pool_options)\n return options\n\n\nengine_opts = apply_engine_options(conf)\nengine = sqlalchemy.engine_from_config(**engine_opts)\nsession_factory = sessionmaker(bind=engine)\ndb_session = scoped_session(session_factory)\n_setup_event_listeners(db_session)","sub_path":"pycfiles/module-build-service-3.1.0.tar/db_session.py","file_name":"db_session.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"329063296","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@authors: Vanderlei Pereira, Thiago Maurici\r\n\"\"\"\r\n\r\nimport asyncio\r\nimport random\r\nimport websockets\r\n\r\nPORT = 50008\r\nHOST = '127.0.0.1'\r\n\r\nasync def a_plus_b(websocket, path):\r\n while True:\r\n n1 = float(input(\"Número A: \"))\r\n n2 = float(input(\"Número B: \"))\r\n await websocket.send(str(n1+n2))\r\n await asyncio.sleep(random.random() * 3)\r\n\r\n\r\nstart_server = websockets.serve(a_plus_b, HOST, PORT)\r\nasyncio.get_event_loop().run_until_complete(start_server)\r\nasyncio.get_event_loop().run_forever()","sub_path":"WebSockets/websocket_server.py","file_name":"websocket_server.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"533024666","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Bullet(Sprite):\n \"\"\"子弹类,由飞船进行发射\"\"\"\n def __init__(self,ai_settings,screen,ship):\n \"\"\"飞船所处的位置创建一个子弹对象\"\"\"\n # 确保父类正确的初始化\n super().__init__() \n #self.ai_settings=ai_settings\n self.screen=screen\n # 设置子弹矩形\n self.rect=pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)\n # 子弹位置由飞船决定\n self.rect.centerx=ship.rect.centerx\n self.rect.top=ship.rect.top\n\n # 设置子弹位置,颜色\n self.y=float(self.rect.y)\n self.color=ai_settings.bullet_color\n self.speed_factor=ai_settings.bullet_speed_factor\n\n def update(self):\n \"\"\"子弹向上运动\"\"\"\n # 更新子弹位置\n self.y -=self.speed_factor\n\n # 子弹rect位置\n self.rect.y=self.y\n \n def draw_bullet(self):\n \"\"\"屏幕上绘制子弹\"\"\"\n pygame.draw.rect(self.screen,self.color,self.rect)","sub_path":"bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"17362563","text":"# https://atcoder.jp/contests/dp/tasks/dp_a\n\nn=int(input())\nh=list(map(int, input().split()))\n\ndp=[10**9 for i in range(n)]\ndp[0]=0\nfor i in range(n):\n if i+1\", outfile)\n\n dat = read.data(infile, file_format=P.intype, cfg=cfg, xg=xg)\n\n write.data(outfile, dat, file_format=P.format, xg=xg)\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"scripts/convert_data.py","file_name":"convert_data.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"404898628","text":"import argparse\nfrom app.core.main import Worker\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--s', help='source file', type=str)\n parser.add_argument('--d', help='target file', type=str)\n parser.add_argument('--m', help='method, possible variants '\n '(transpose,sum,determinant)', type=str)\n args = parser.parse_args()\n worker = Worker(args.s, args.d, args.m)\n worker.run()\n","sub_path":"app/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"50530967","text":"import json, re\nfrom numbers import Number\n\nTAB_INDENT = ' '\nregion_regex = re.compile('(us|eu|ap|sa)-(east|west|south|northeast|southeast|central)-(1|2)')\nspace = re.compile('\\s')\nregion_path = ''\n\ndef get_info(data):\n request_headers = data['request_headers']\n request_body = data['request_body']\n warning = True\n\n host = request_headers['Host'].split('.')\n service = host[-3]\n if region_regex.findall(service):\n service = host[-4]\n\n with open('objectidmap.json') as fl:\n object_map = json.load(fl)\n for s in object_map:\n if s != 'default' and service in object_map[s]['serviceNames']:\n service = s\n warning = False\n\n action = request_body['Action']\n\n return service, warning, action\n\ndef codify_json(data):\n '''\n Return HTML
     block representing a json object. The portions of\n    the html corresponding to key/values will contain specfic data-json\n    attributes to aid with front-end traversal.\n    '''\n    def span(c, v, sel=''):\n        if sel:\n            return '%s' % (c, sel, v)\n        else:\n            return '%s' % (c, v)\n\n    def dquote(s):\n        return '\"%s\"' % s\n\n    def tab(n):\n        return TAB_INDENT * n\n\n    def apply_attrs(d, sel='', depth=0):\n        global region_path\n        ################################\n        # Handle the terminal cases\n        ################################\n        if d is None:\n            return span('value', span('literal', 'null', sel))\n\n        if isinstance(d, bool):\n            return span('value', span('literal', str(d).lower(), sel))\n\n        if isinstance(d, basestring):\n            # if we have a region, save its path\n            if region_regex.findall(d) and not space.findall(d) and region_path == '':\n                region_path = sel\n            return span('value', dquote(span('string', d, sel)))\n\n        if isinstance(d, Number):\n            return span('value', span('number', d, sel))\n\n        ################################\n        # Now for the recursive steps\n        ################################\n        elif isinstance(d, dict):\n            num_keys = len(d)\n\n            # Don't bother creating a new line and indenting for an empty dict\n            if num_keys == 0:\n                s = '{}'\n            else:\n                s = '{\\n'\n                for i, (k,v) in enumerate(d.iteritems()):\n                    # The current selector for this key is where we are plus\n                    # ['key']\n                    this_sel = sel + '%s,' % k\n\n                    # Indent for formatting\n                    s += tab(depth+1)\n\n                    # Add an attribute span around the key name\n                    s += dquote(span('attribute', k)) + ': '\n\n                    # Append the formatted value\n                    s += apply_attrs(v, this_sel, depth+1)\n\n                    # Add commas and newlines as needed\n                    if i :rotating_light: Race called in *{}*\".format(\n                payload.division.upper()\n            ),\n            \"mrkdwn_in\": [\"fields\"],\n            \"author_name\": \"Elections Bot\",\n            \"author_icon\": \"https://pbs.twimg.com/profile_images/998954486205898753/gbb2psb__400x400.jpg\",  # noqa\n            \"title\": \"Winner for {}\".format(payload.office),\n            \"title_link\": payload.page_url,\n            \"text\": WINNING,\n            \"footer\": \"Associated Press\",\n            \"fields\": [\n                {\n                    \"title\": \"Winning vote\",\n                    \"value\": \"{}% | {:,} votes\".format(\n                        int(round(float(payload.vote_percent) * 100)),\n                        int(payload.vote_count),\n                    ),\n                    \"short\": True,\n                },\n                {\n                    \"title\": \"Precincts reporting\",\n                    \"value\": \"{}%\".format(\n                        int(round(float(\n                            payload.precincts_reporting_percent\n                        ) * 100))\n                    ),\n                    \"short\": True,\n                },\n            ],\n            \"ts\": int(time.time()),\n        }\n    ]\n\n    client = get_client()\n\n    if app_settings.AWS_S3_BUCKET == \"interactives.politico.com\":\n        bot_channel = \"#elections-bot\"\n    else:\n        bot_channel = \"#elections-bot-stg\"\n\n    client.chat.post_message(\n        bot_channel,\n        \"\",\n        attachments=bot_attachment_data,\n        as_user=False,\n        username=\"Elections Bot\",\n    )\n","sub_path":"aploader/tasks/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"219586745","text":"import csv\n\ndef asList(filepath):\n    \n    #as a list\n    with open(filepath,'rt')as f:\n        data = csv.reader(f)\n        print(data)\n        count = 0\n        for row in data:\n          print(row)\n          count = count+1\n    print(count)    \n\ndef asDict(filepath):\n    \n    #as a dictionary\n    reader = csv.DictReader(open(filepath))\n    print(reader)\n    for raw in reader:\n        print(raw)\n\n\nfilepath = './Social_Network_Ads.csv'\nasList(filepath)\nasDict(filepath)","sub_path":"Class Work/Day 9 - Files/socialFileRead.py","file_name":"socialFileRead.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"647500612","text":"import sys\nsys.stdin = open('7465.txt')\n\ndef find(n):\n    if n == p[n]:\n        return n\n    else:\n        return find(p[n])\n\ndef union(s, e):\n    n1, n2 = find(s), find(e)\n    if n1 > n2:\n        p[n1] = n2\n    else:\n        p[n2] = n1\n\nT = int(input())\nfor t in range(1, T + 1):\n    N, M = map(int, input().split())\n    num = [list(map(int, input().split())) for _ in range(M)]\n    p = list(range(N + 1))\n\n    for i in range(M):\n        s, e = num[i][0], num[i][1]\n        union(s, e)\n    \n    ans = set()\n    for i in p:\n        ans.add(find(i))\n\n    print('#{} {}'.format(t, len(ans) - 1))","sub_path":"algorithm/0423/7465_창용마을무리의개수.py","file_name":"7465_창용마을무리의개수.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"373327375","text":"import os, sys, csv, argparse, re\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SQLContext, HiveContext, SparkSession\n\ndef identifyByHeader(f,colDel):\n  return len(next(csv.reader(f, delimiter=colDel)))\n\ndef parseData(f,colDel):\n  arr={}\n  for rec in csv.reader(f, delimiter=colDel):\n    arr[len(rec)]=arr.setdefault(len(rec),0)+1\n  return max(arr,key=arr.get)\n\ndef adjustNewline(wh,reader,numOfAttr,colDel,recDel,ignoreHdr):\n  jnval=':jn:'\n  jn=[jnval]\n  hdrLine=next(reader) if ignoreHdr else reader\n  for rec in reader:\n    irec=rec\n    while len(irec)?/'*&^%$#@!|\\~`\\\"]\",\"\",w).replace(removeChar,'') for w in row])\n  sqlContext = SQLContext(sc)\n  sqlContext.sql(\"drop table IF EXISTS \"+dataBase+\".temptable_\"+hiveTable)\n  df = getDataFrame(sqlContext,dataList,headerExist)\n  df.write.mode('overwrite').saveAsTable(dataBase+\".temptable_\"+hiveTable)\n  \n\ndef main(args, sc, hc):\n  absFile=args.fileToClean\n  hdrBool=args.headerAvail\n  colDel=args.delimiter\n  ignoreHdr=args.ignoreHeader\n  tmpFile=args.outFile\n  recDel='\\n'\n  dataBase='bbiuserdb'\n  hiveTable='departments'\n  fh=open(absFile,'rb')\n  numOfAttr=identifyByHeader(fh,colDel) if hdrBool else parseData(fh,colDel)\n  readCSVWriteHive(sc, fh, 1.6, colDel=colDel, headerExist=hdrBool, dataBase=dataBase, hiveTable=hiveTable) \n  #wh.close()\n  fh.close()\n\ndef parseArguments(parser):\n    # Positional mandatory arguments\n    parser.add_argument(\"-f\", \"--fileToClean\", help=\"Absolute FileName - File to be cleansed\")\n    parser.add_argument(\"-t\", \"--headerAvail\", help=\"True/False - Data to be cleansed contains header record (Attribute Names)\")\n    parser.add_argument(\"-d\", \"--delimiter\", help=\"[,:|] Column Delimiter of the data file\")\n    # Optional arguments\n    parser.add_argument(\"-o\", \"--outFile\", help=\"Output File\", default='tmp_file')\n    parser.add_argument(\"-i\", \"--ignoreHeader\", help=\"Ignore the First Record\", default=True)\n    # Print version\n    parser.add_argument(\"--version\", action=\"version\", version='%(prog)s - Version 1.0')\n    # Parse arguments\n    args = parser.parse_args()\n    return args\n\nif __name__ == '__main__':\n    # Parse the arguments\n    parser = argparse.ArgumentParser(\"Perform Cleansing of data specific to Client\")\n    args = parseArguments(parser)\n\n    # Raw print arguments\n    print(\"You are running the script with arguments: \")\n    for a in args.__dict__:\n        if args.__dict__[a]:\n           print(\"Values provided for : \"+ str(a) + \": \" + str(args.__dict__[a]))\n        else:\n           parser.print_help()\n           sys.exit(0)\n    sc = SparkContext()\n    hc = SparkSession.builder.enableHiveSupport().getOrCreate()\n\n    main(args,sc,hc)\n","sub_path":"genericProcess/spark/PySpark/GenericProcesses/cleanse.py","file_name":"cleanse.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"214926109","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom bs4 import BeautifulSoup\nimport traceback, sys\nfrom datetime import datetime, timedelta\nimport re\nfrom dateutil.parser import parse as date_parser\nfrom scraper.items import NewsItem\nimport json\nfrom .redis_spiders import RedisSpider\nimport datetime\n\n# from scrapy_redis.spiders import RedisSpider\n\n# class LtnSpider(RedisSpider):\nclass Ltn_keywordsSpider(scrapy.Spider):\n    name = \"ltn_keywords\"\n    \n\n    def start_requests(self):\n            \n        if isinstance(self, RedisSpider):\n            return\n        \n        # url\n        requests=[{\n            \"url\": 'https://www.myip.com/',\n            \"url_pattern\":\"https://search.ltn.com.tw/list?keyword={}&type=all&sort=date&start_time={}&end_time={}&sort=date&type=all&page=1\",\n            \"keywords_list\": ['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'],\n            \"interval\": 3600 * 2,\n            \"days_limit\": 3600 * 24 * 2,\n            \"media\": \"ltn\",\n            \"name\": \"ltn_keywords\",\n            \"scrapy_key\": \"ltn_keywords:start_urls\",\n            \"priority\": 1,\n            \"search\": False,\n            \"enabled\": True,\n        }]\n        \n        for request in requests:\n            yield scrapy.Request(request['url'],\n                    meta=request,\n                    dont_filter=True,\n                    callback=self.parse)\n                \n    def parse(self, response):\n        meta = response.meta\n        meta['page'] = 1\n        #搜尋時間範圍      \n        now=datetime.datetime.now()\n        end_time=now.strftime(\"%Y%m%d\")\n        time_delta=datetime.timedelta(days=2) \n        start_time=(now-time_delta).strftime(\"%Y%m%d\")\n        for keyword in meta['keywords_list']:\n            url=meta['url_pattern'].format(keyword,start_time,end_time)\n            yield scrapy.Request(url,\n                    meta=meta,\n                    dont_filter=True,\n                    callback=self.parse_list)\n        \n\n    def parse_list(self, response):\n        meta = response.meta\n        soup = BeautifulSoup(response.body, 'html.parser')\n        if(len(soup.findAll(class_=\"cont\"))!=0):\n            for s in soup.findAll(class_=\"cont\"):\n                url = s.find('a').get('href')\n                if 'ec.ltn.com.tw' in url: \n                    yield response.follow(url,\n                    meta=meta,\n                    callback=self.parse_article_ec)      \n                elif ('news.ltn.com.tw' in url):\n                    yield response.follow(url,\n                    meta=meta,\n                    callback=self.parse_article_news)\n                \n            current_page = re.search(\"page=(\\d+)\", response.url).group(1)\n            next_page = re.sub(\"page=(\\d+)\", \"page={}\".format(int(current_page) + 1), response.url)\n        \n            yield scrapy.Request(next_page,\n                    dont_filter=True,\n                    meta=meta,\n                    callback=self.parse_list)\n            \n    def parse_article_ec(self, response):\n        meta = response.meta\n        soup = BeautifulSoup(response.body, 'html.parser')\n          \n        metadata = {'category':'','image_url':[]}\n        \n        content, author, metadata['image_url'] = self.parse_content_author_image_ec(soup)\n        \n        title=soup.find(class_=\"whitecon boxTitle boxText\").find('h1').string \n        metadata['category'] = '自由財經'\n       \n        item = NewsItem()\n        item['url'] = response.url\n        item['article_title'] = title\n        item['author'] = author\n        item['author_url'] = []\n        item['comment'] = []\n        item['date'] = self.parse_datetime(soup)\n        item['content'] = content\n        item['metadata'] = metadata\n        item['content_type'] = 0\n        item['media'] = 'ltn'\n        item['proto'] = 'LTN_PARSE_ITEM'\n        return item\n\n    def parse_article_news(self, response):\n        meta = response.meta\n        soup = BeautifulSoup(response.body, 'html.parser')\n          \n        metadata = {'category':'','image_url':[]}\n        \n        content, author, metadata['image_url'] = self.parse_content_author_image_news(soup)\n        \n        if 'title' in meta and 'tagText' in meta:\n            title = meta['title']\n            metadata['category'] = meta.get('tagText', \"\")\n        else:\n            title, metadata['category'] = self.parse_title_metadata(soup)\n       \n        item = NewsItem()\n        item['url'] = response.url\n        item['article_title'] = title\n        item['author'] = author\n        item['author_url'] = []\n        item['comment'] = []\n        item['date'] = self.parse_datetime(soup)\n        item['content'] = content\n        item['metadata'] = metadata\n        item['content_type'] = 0\n        item['media'] = 'ltn'\n        item['proto'] = 'LTN_PARSE_ITEM'\n        return item\n\n\n    def parse_datetime(self,soup):\n        date = soup.find('meta', {'name':'pubdate'})\n        if date:\n            return date['content'].replace('Z', '+0800')\n        \n        date = soup.find('span', {'class':'time'})\n        if date:\n            return date_parser(date.text).strftime('%Y-%m-%dT%H:%M:%S+0800')\n\n        date = soup.find('div', {'class':'article_header'})\n        if date:\n            return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S+0800')\n        \n        date = soup.find('div', {'class':'writer'})\n        if date:\n            return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800')\n\n    def parse_title_metadata(self,soup):        \n        title = soup.find('title').text.replace(' - 自由時報電子報', '').replace(' 自由電子報', '')\n        title_ = title.split('-')\n        if not title_[-1]:\n            del title_[-1]\n        if len(title_) > 2:\n            category = title_[-1]\n            del title_[-1]\n            ti = ''.join(x for x in title_)\n            return ti.strip(), category.strip()\n        elif len(title_) == 2:\n            category = title_[1]\n            ti = title_[0]\n            return ti.strip(), category.strip()\n        elif '3C科技' in title_[0]:\n            category = '3C科技'\n            ti = title_[0].replace('3C科技', '')\n            return ti.strip(), category\n        elif '玩咖Playing' in title_[0]:                \n            category = '玩咖Playing'\n            ti = title_[0].replace('玩咖Playing', '')            \n            return ti.strip(), category\n        else:\n            category = ''\n            ti = title_[0]\n            return ti.strip(), category\n            \n    \n    def find_author(self,list_text):\n        list_text = [x for x in list_text if x!='文']\n        tmp = [x for x in list_text if '記者' in x]\n        if tmp:\n            author = tmp[0].replace('記者', '').replace('攝影', '').strip()                \n        else:\n            author = min(list_text, key=len)\n        return author\n    \n    def parse_content_author_image_ec(self,soup): \n        \n        # content\n        content=''\n        for text in soup.find(class_=\"text\").findAll('p')[1:4]:\n            content=content+text.get_text()\n        for text in soup.find(class_=\"text\").findAll('p')[5:-2]:\n            content=content+text.get_text()\n            \n        # author\n        au = ''\n        author_text=soup.find(class_='text').findAll('p')[1].get_text()\n        begin=author_text.rfind('〔')\n        end=author_text.find('/')\n        if begin!=-1 & end!=-1:\n            au=author_text[begin+1:end]\n            if '記者' in au:\n                au=au.replace('記者', '')\n        \n        # image\n        image_url = []\n        image_url.append(soup.find(class_='text').find(class_=\"lazy_imgs_ltn\")['data-src'])\n\n        return content, au, image_url\n\n    def parse_content_author_image_news(self,soup): \n        content = soup.find('div',{'itemprop':'articleBody'})\n\n        # image\n        image_url = []\n        for photo in content.find_all('div','photo boxTitle'):\n            image_url.append(photo.find('img')['src'])\n\n        # content\n        for appE1121 in content.find_all('p','appE1121'):\n            appE1121.clear()\n        for photo in content.find_all('div','photo boxTitle'):\n            photo.clear()\n        for photo in content.find_all('span','ph_b ph_d1'):\n            photo.clear()\n        for tag in content.find_all('script'):\n            tag.clear()\n        content = ''.join(x.text for x in content.find_all('p') if x.text!='爆')\n        content = ''.join(content.split())\n\n        #author\n        au = ''\n        reg = re.compile(r'([\\D*/\\D*]|〔\\D*/\\D*〕)', re.VERBOSE)\n        author_reg = reg.findall(content)\n        if author_reg:\n            au = author_reg[0].split('/')[0].replace('〔', '').replace('[', '').replace('記者', '').replace('編譯', '')\n\n        if not au:\n            author = soup.find('div', {'class':'writer boxTitle'})\n            if author: \n                au = author.find('a')['data-desc']\n        if not au:\n            author = soup.find('p', {'class':'auther'})\n            if author:\n                tmp = author.find('span').text.split('/')\n                au = self.find_author(tmp)\n        if not au:        \n            author = soup.find('p', {'class':'writer'})\n            if author:\n                tmp = author.find('span').text.split('/')\n                au = self.find_author(tmp)\n        if not au:        \n            author = soup.find('div', {'class':'writer'})\n            if author:\n                tmp = author.find('span').text.split('/')\n                au = self.find_author(tmp)\n        if not au: \n            author = soup.find('div', {'class':'conbox_tit boxTitle'})\n            if author:\n                au = author.find('a')['data-desc']\n        if not au:\n            author = soup.find('div', {'class':'article_header'})\n            if author:\n                tmp = author.find('span').text.split('/')\n                au = self.find_author(tmp)\n        if not au:\n            try:\n                author = soup.find('div', {'itemprop':'articleBody'}).find('p')\n            except:\n                author = ''\n            if author:\n                if '/' in author.text:\n                    tmp = author.text.split('/')\n                    au = self.find_author(tmp)\n                if author.find('strong'):\n                    au = author.find('strong').text.split('◎')[1].replace('記者', '').replace('攝影', '').strip()\n                if '■' in author.text:\n                    au = author.text.replace('■', '')\n        if not au:\n            try:\n                author = soup.find('div', {'itemprop':'articleBody'}).find('span', {'class':'writer'})\n            except:\n                author = ''\n            if author:\n                if '/' in author.text:\n                    tmp = author.text.split('/')\n                    au = self.find_author(tmp)\n        if not au:\n            try:\n                author = soup.find('div', {'itemprop':'articleBody'}).find('h4')\n            except:\n                author = ''\n            if author:\n                if '/' in author.text:\n                    tmp = author.text.split('/')\n                    au = self.find_author(tmp)\n                elif '◎' in author.text:\n                    au = author.text.replace('◎', '')\n        return content, au, image_url","sub_path":"info-scraper-master/scraper/scraper/spiders/ltn_keywords.py","file_name":"ltn_keywords.py","file_ext":"py","file_size_in_byte":11485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"384746653","text":"## from config import Config as Config\r\n\r\nimport xbmc,xbmcaddon,xbmcplugin,os\r\n_addon_id=\"plugin.program.RepositoriesBrowser\"; _addon_name=\"Repository Highway\"; \r\n_addon=xbmcaddon.Addon(id=_addon_id); \r\n\r\ndef gAI(t):\r\n\ttry: return _addon.getAddonInfo(t)\r\n\texcept: \r\n\t\t#if t==\"name\": return _addon_name\r\n\t\t#else: return \"\"\r\n\t\treturn \"\"\r\n\r\nclass Config:\r\n\taddon_id=_addon_id\r\n\t#name='Repositories Browser'\r\n\taddon=_addon\r\n\thandle=0\r\n\tname=gAI('name'); \r\n\t#name=\"XBMCHUB Repositories Browser\"; \r\n\tpath=gAI('path'); \r\n\t#profile=xbmc.translatePath(gAI('profile'))\r\n\tdisclaimer=gAI('disclaimer'); description=gAI('description'); summary=gAI('summary'); \r\n\ticon=gAI('icon'); fanart=gAI('fanart'); \r\n\taddon_type=gAI('type'); author=gAI('author'); version=gAI('version'); stars=gAI('stars'); changelog=gAI('changelog'); \r\n\t\r\n\tartPath=xbmc.translatePath(os.path.join(path,'art'))\r\n\t\r\n\t\r\n\tACTION_PREVIOUS_MENU \t\t=  10\t## ESC action\r\n\tACTION_NAV_BACK \t\t\t\t=  92\t## Backspace action\r\n\tACTION_MOVE_LEFT \t\t\t\t=   1\t## Left arrow key\r\n\tACTION_MOVE_RIGHT \t\t\t=   2\t## Right arrow key\r\n\tACTION_MOVE_UP \t\t\t\t\t=   3\t## Up arrow key\r\n\tACTION_MOVE_DOWN \t\t\t\t=   4\t## Down arrow key\r\n\tACTION_MOUSE_WHEEL_UP \t= 104\t## Mouse wheel up\r\n\tACTION_MOUSE_WHEEL_DOWN = 105\t## Mouse wheel down\r\n\tACTION_MOUSE_DRAG \t\t\t= 106\t## Mouse drag\r\n\tACTION_MOUSE_MOVE \t\t\t= 107\t## Mouse move\r\n\tdef gSetting(self,setting):\r\n\t\ttry: return self.addon.getSetting(setting)\r\n\t\texcept: return \"\"\r\n\tdef set_setting(self,setting,value):\r\n\t\tself.addon.setSetting(id=setting,value=value)\r\n\tdef get_string(self, string_id):\r\n\t\ttry: return self.addon.getLocalizedString(string_id)\r\n\t\texcept: return \"\"\r\n\tdef get_id(self):\r\n\t\ttry: return self.addon.getAddonInfo('id')\r\n\t\texcept: return self.addon_id\r\n\tdef note(self,title='',msg='',delay=5000,image='http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/US_99_%281961%29.svg/40px-US_99_%281961%29.svg.png'):\r\n\t\txbmc.executebuiltin('XBMC.Notification(\"%s\",\"%s\",%d,\"%s\")' % (title,msg,delay,image))\r\n\tdef show_settings(self): self.addon.openSettings()\r\n\tdef eod(self):\r\n\t\txbmcplugin.endOfDirectory(self.handle)\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t","sub_path":"Netxeon/plugin.program.RepositoriesBrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"171126496","text":"'''\n3D Printer: POE Lab 2\n\nThis script pulls data sent over USB\nby the Ardino and saves it to be plotted\nby numpy\n\nauthors: mpatil99, awenstrup\n'''\n#Import statements\nimport serial\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Variable definitions\n\nport = '/dev/ttyACM0'\nbaudRate = 9600\n\na = 8442\nb = -0.9307\n\nvalues = list()\n\n\n\n#Setup\nserialPort = serial.Serial(port=port, baudrate=9600, timeout=None)\n\n\ndef adc_to_dist(num):\n    if num > 0:\n        return a * (num ** b)\n    else:\n        return 150\n\ndef input_to_scatter(l, xres, yres):\n    format_list(l)\n    array = np.array(l).reshape(yres, xres)\n    print(array)\n    print(array.shape)\n    return array\n\ndef format_list(l):\n    for i, n in enumerate(l):\n        if n > 150:\n            l[i] = 150\n        if n < 15:\n            l[i] = 15\n\n    return l.reverse()\n\ndef test_plot():\n    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n    scatter = input_to_scatter(l, 4, 3)\n\n    # make these smaller to increase the resolution\n    dx, dy = 2, 2\n\n    x = range(0, 8 + dx, dx)\n    y = range(0, 6 + dy, dy)\n\n    print(x)\n    print(y)\n\n    plt.pcolormesh(x, y, scatter)\n    plt.xlabel(\"Theta (degrees)\")\n    plt.ylabel(\"Phi (degrees)\")\n    plt.title(\"3D Scan of letter 'A'\")\n    plt.show()\n\ntime.sleep(1)\n\n#Loop\nrunning = True\nwhile running:\n\n    line = serialPort.readline()\n    if len(line) > 0:\n        dist = adc_to_dist(int(line.decode().strip()))\n        print('Distance is ', dist)\n        values.append(dist)\n        print()\n\n    if len(values) == 600:\n        running = False\n\n        x = range(0, 60 + 2, 2)\n        y = range(0, 40 + 2, 2)\n\n        plt.pcolormesh(x, y, input_to_scatter(values, 30, 20))\n        plt.xlabel(\"Theta (degrees)\")\n        plt.ylabel(\"Phi (degrees)\")\n        plt.title(\"3D Scan of letter 'A'\")\n        plt.show()\n","sub_path":"Firmware/pulldata.py","file_name":"pulldata.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"38206454","text":"import altair as alt\nfrom vega_datasets import data\n\ndef make_static_chart():\n    '''\n    '''\n    return alt.Chart(data=data.cars.url).mark_circle(size=60).encode(\n        x='Horsepower:Q',\n        y='Miles_per_Gallon:Q',\n        color='Origin:N'\n    ).interactive()\n\ndef make_interactive_chart():\n    '''\n    '''\n    pts = alt.selection(type=\"single\", encodings=['x'])\n\n    rect = alt.Chart(data.movies.url).mark_rect().encode(\n        alt.X('IMDB_Rating:Q', bin=True),\n        alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),\n        alt.Color('count()',\n            scale=alt.Scale(scheme='greenblue'),\n            legend=alt.Legend(title='Total Records')\n        )\n    )\n\n    circ = rect.mark_point().encode(\n        alt.ColorValue('grey'),\n        alt.Size('count()',\n            legend=alt.Legend(title='Records in Selection')\n        )\n    ).transform_filter(\n        pts\n    )\n\n    bar = alt.Chart(data.movies.url).mark_bar().encode(\n        x='Major_Genre:N',\n        y='count()',\n        color=alt.condition(pts, alt.ColorValue(\"steelblue\"), alt.ColorValue(\"grey\"))\n    ).properties(\n        selection=pts,\n        width=550,\n        height=200\n    )\n\n    return alt.vconcat(\n        rect + circ,\n        bar\n    ).resolve_legend(\n        color=\"independent\",\n        size=\"independent\"\n    )\n","sub_path":"src/altair.py","file_name":"altair.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"190564665","text":"import logging\nfrom unittest import TestCase\n\nfrom icon_azure_ad_admin.actions import GetUserInfo\nfrom icon_azure_ad_admin.connection import Connection\n\nimport json\n\n\nclass TestGetUserInfo(TestCase):\n    def test_get_user_info(self):\n        log = logging.getLogger(\"TestLogger\")\n\n        test_connection = Connection()\n        test_get_user_info = GetUserInfo()\n\n        test_connection.logger = log\n        test_get_user_info.logger = log\n\n        with open(\"../tests/get_user_info.json\") as file:\n            data = json.load(file)\n            connection_params = data.get(\"body\").get(\"connection\")\n\n        action_params = {\n            \"user_id\": \"user@example.com\"\n        }\n\n        test_connection.connect(connection_params)\n        test_get_user_info.connection = test_connection\n\n        result = test_get_user_info.run(action_params)\n        expected = {'user_information': {'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',\n                                         'businessPhones': [], 'displayName': 'Joey McAdams', 'givenName': 'Joey',\n                                         'jobTitle': 'Sr. Software Engineer', 'mail': '', 'mobilePhone': '',\n                                         'officeLocation': '', 'preferredLanguage': '', 'surname': 'McAdams',\n                                         'userPrincipalName': 'user@example.com',\n                                         'id': '08290005-23ba-46b4-a377-b381d651a2fb', 'accountEnabled': True}}\n        self.assertEqual(result, expected)\n","sub_path":"azure_ad_admin/unit_test/test_get_user_info.py","file_name":"test_get_user_info.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"348708868","text":"# -*- coding: utf-8 -*-\n\"\"\"Test suite for repos bootstrapping (install).\"\"\"\nimport os\nimport sys\nfrom collections import namedtuple\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nimport appdirs\nimport pytest\n\nfrom igniter.bootstrap_repos import BootstrapRepos\nfrom igniter.bootstrap_repos import PypeVersion\nfrom pype.lib import OpenPypeSettingsRegistry\n\n\n@pytest.fixture\ndef fix_bootstrap(tmp_path, pytestconfig):\n    bs = BootstrapRepos()\n    bs.live_repo_dir = pytestconfig.rootpath / 'repos'\n    bs.data_dir = tmp_path\n    return bs\n\n\ndef test_pype_version():\n    v1 = PypeVersion(1, 2, 3)\n    assert str(v1) == \"1.2.3\"\n\n    v2 = PypeVersion(1, 2, 3, client=\"x\")\n    assert str(v2) == \"1.2.3-x\"\n    assert v1 < v2\n\n    v3 = PypeVersion(1, 2, 3, variant=\"staging\")\n    assert str(v3) == \"1.2.3-staging\"\n\n    v4 = PypeVersion(1, 2, 3, variant=\"staging\", client=\"client\")\n    assert str(v4) == \"1.2.3-client-staging\"\n    assert v3 < v4\n    assert v1 < v4\n\n    v5 = PypeVersion(1, 2, 3, variant=\"foo\", client=\"x\")\n    assert str(v5) == \"1.2.3-x\"\n    assert v4 < v5\n\n    v6 = PypeVersion(1, 2, 3, variant=\"foo\")\n    assert str(v6) == \"1.2.3\"\n\n    v7 = PypeVersion(2, 0, 0)\n    assert v1 < v7\n\n    v8 = PypeVersion(0, 1, 5)\n    assert v8 < v7\n\n    v9 = PypeVersion(1, 2, 4)\n    assert v9 > v1\n\n    v10 = PypeVersion(1, 2, 2)\n    assert v10 < v1\n\n    v11 = PypeVersion(1, 2, 3, path=Path(\"/foo/bar\"))\n    assert v10 < v11\n\n    assert v5 == v2\n\n    sort_versions = [\n        PypeVersion(3, 2, 1),\n        PypeVersion(1, 2, 3),\n        PypeVersion(0, 0, 1),\n        PypeVersion(4, 8, 10),\n        PypeVersion(4, 8, 20),\n        PypeVersion(4, 8, 9),\n        PypeVersion(1, 2, 3, variant=\"staging\"),\n        PypeVersion(1, 2, 3, client=\"client\")\n    ]\n    res = sorted(sort_versions)\n\n    assert res[0] == sort_versions[2]\n    assert res[1] == sort_versions[6]\n    assert res[2] == sort_versions[1]\n    assert res[-1] == sort_versions[4]\n\n    str_versions = [\n        \"5.5.1\",\n        \"5.5.2-client\",\n        \"5.5.3-client-strange\",\n        \"5.5.4-staging\",\n        \"5.5.5-staging-client\",\n        \"5.6.3\",\n        \"5.6.3-staging\"\n    ]\n    res_versions = []\n    for v in str_versions:\n        res_versions.append(PypeVersion(version=v))\n\n    sorted_res_versions = sorted(res_versions)\n\n    assert str(sorted_res_versions[0]) == str_versions[0]\n    assert str(sorted_res_versions[-1]) == str_versions[5]\n\n    with pytest.raises(ValueError):\n        _ = PypeVersion()\n\n    with pytest.raises(ValueError):\n        _ = PypeVersion(major=1)\n\n    with pytest.raises(ValueError):\n        _ = PypeVersion(version=\"booobaa\")\n\n    v11 = PypeVersion(version=\"4.6.7-client-staging\")\n    assert v11.major == 4\n    assert v11.minor == 6\n    assert v11.subversion == 7\n    assert v11.variant == \"staging\"\n    assert v11.client == \"client\"\n\n\ndef test_get_main_version():\n    ver = PypeVersion(1, 2, 3, variant=\"staging\", client=\"foo\")\n    assert ver.get_main_version() == \"1.2.3\"\n\n\ndef test_get_version_path_from_list():\n    versions = [\n        PypeVersion(1, 2, 3, path=Path('/foo/bar')),\n        PypeVersion(3, 4, 5, variant=\"staging\", path=Path(\"/bar/baz\")),\n        PypeVersion(6, 7, 8, client=\"x\", path=Path(\"boo/goo\"))\n    ]\n    path = BootstrapRepos.get_version_path_from_list(\n        \"3.4.5-staging\", versions)\n\n    assert path == Path(\"/bar/baz\")\n\n\ndef test_search_string_for_pype_version(printer):\n    strings = [\n        (\"3.0.1\", True),\n        (\"foo-3.0\", False),\n        (\"foo-3.0.1\", True),\n        (\"3\", False),\n        (\"foo-3.0.1-client-staging\", True),\n        (\"foo-3.0.1-bar-baz\", True)\n    ]\n    for ver_string in strings:\n        printer(f\"testing {ver_string[0]} should be {ver_string[1]}\")\n        assert PypeVersion.version_in_str(ver_string[0])[0] == ver_string[1]\n\n\n@pytest.mark.slow\ndef test_install_live_repos(fix_bootstrap, printer):\n    pype_version = fix_bootstrap.create_version_from_live_code()\n    sep = os.path.sep\n    expected_paths = [\n        f\"{pype_version.path}{sep}repos{sep}avalon-core\",\n        f\"{pype_version.path}{sep}repos{sep}avalon-unreal-integration\",\n        f\"{pype_version.path}\"\n    ]\n    printer(\"testing zip creation\")\n    assert os.path.exists(pype_version.path), \"zip archive was not created\"\n    fix_bootstrap.add_paths_from_archive(pype_version.path)\n    for ep in expected_paths:\n        assert ep in sys.path, f\"{ep} not set correctly\"\n\n    printer(\"testing pype imported\")\n    del sys.modules[\"pype\"]\n    import pype  # noqa: F401\n\n    # test if pype is imported from specific location in zip\n    assert \"pype\" in sys.modules.keys(), \"Pype not imported\"\n    assert sys.modules[\"pype\"].__file__ == \\\n        f\"{pype_version.path}{sep}pype{sep}__init__.py\"\n\n\ndef test_find_pype(fix_bootstrap, tmp_path_factory, monkeypatch, printer):\n\n    test_pype = namedtuple(\"Pype\", \"prefix version suffix type valid\")\n\n    test_versions_1 = [\n        test_pype(prefix=\"foo-v\", version=\"5.5.1\",\n                  suffix=\".zip\", type=\"zip\", valid=False),\n        test_pype(prefix=\"bar-v\", version=\"5.5.2-client\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"baz-v\", version=\"5.5.3-client-strange\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"bum-v\", version=\"5.5.4-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"zum-v\", version=\"5.5.5-client-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"fam-v\", version=\"5.6.3\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"5.6.3-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"fim-v\", version=\"5.6.3\",\n                  suffix=\".zip\", type=\"zip\", valid=False),\n        test_pype(prefix=\"foo-v\", version=\"5.6.4\",\n                  suffix=\".txt\", type=\"txt\", valid=False),\n        test_pype(prefix=\"foo-v\", version=\"5.7.1\",\n                  suffix=\"\", type=\"dir\", valid=False),\n    ]\n\n    test_versions_2 = [\n        test_pype(prefix=\"foo-v\", version=\"10.0.0\",\n                  suffix=\".txt\", type=\"txt\", valid=False),\n        test_pype(prefix=\"lom-v\", version=\"7.2.6\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"bom-v\", version=\"7.2.7-client\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"woo-v\", version=\"7.2.8-client-strange\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"loo-v\", version=\"7.2.10-client-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"kok-v\", version=\"7.0.1\",\n                  suffix=\".zip\", type=\"zip\", valid=True)\n    ]\n\n    test_versions_3 = [\n        test_pype(prefix=\"foo-v\", version=\"3.0.0\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"goo-v\", version=\"3.0.1\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"hoo-v\", version=\"4.1.0\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"4.1.2\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"3.0.1-client\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"3.0.1-client-strange\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"3.0.1-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"3.0.1-client-staging\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"foo-v\", version=\"3.2.0\",\n                  suffix=\".zip\", type=\"zip\", valid=True)\n    ]\n\n    test_versions_4 = [\n        test_pype(prefix=\"foo-v\", version=\"10.0.0\",\n                  suffix=\"\", type=\"dir\", valid=True),\n        test_pype(prefix=\"lom-v\", version=\"11.2.6\",\n                  suffix=\".zip\", type=\"dir\", valid=False),\n        test_pype(prefix=\"bom-v\", version=\"7.2.7-client\",\n                  suffix=\".zip\", type=\"zip\", valid=True),\n        test_pype(prefix=\"woo-v\", version=\"7.2.8-client-strange\",\n                  suffix=\".zip\", type=\"txt\", valid=False)\n    ]\n\n    def _create_invalid_zip(path: Path):\n        with ZipFile(path, \"w\") as zf:\n            zf.writestr(\"test.foo\", \"test\")\n\n    def _create_valid_zip(path: Path, version: str):\n        with ZipFile(path, \"w\") as zf:\n            zf.writestr(\n                \"pype/version.py\", f\"__version__ = '{version}'\\n\\n\")\n\n    def _create_invalid_dir(path: Path):\n        path.mkdir(parents=True, exist_ok=True)\n        with open(path / \"invalid\", \"w\") as fp:\n            fp.write(\"invalid\")\n\n    def _create_valid_dir(path: Path, version: str):\n        pype_path = path / \"pype\"\n        version_path = pype_path / \"version.py\"\n        pype_path.mkdir(parents=True, exist_ok=True)\n        with open(version_path, \"w\") as fp:\n            fp.write(f\"__version__ = '{version}'\\n\\n\")\n\n    def _build_test_item(path, item):\n        test_path = path / \"{}{}{}\".format(item.prefix,\n                                           item.version,\n                                           item.suffix)\n        if item.type == \"zip\":\n            if item.valid:\n                _create_valid_zip(test_path, item.version)\n            else:\n                _create_invalid_zip(test_path)\n        elif item.type == \"dir\":\n            if item.valid:\n                _create_valid_dir(test_path, item.version)\n            else:\n                _create_invalid_dir(test_path)\n        else:\n            with open(test_path, \"w\") as fp:\n                fp.write(\"foo\")\n\n    # in PYPE_PATH\n    e_path = tmp_path_factory.mktemp(\"environ\")\n\n    # create files and directories for test\n    for test_file in test_versions_1:\n        _build_test_item(e_path, test_file)\n\n    # in pypePath registry\n    p_path = tmp_path_factory.mktemp(\"pypePath\")\n    for test_file in test_versions_2:\n        _build_test_item(p_path, test_file)\n\n    # in data dir\n    d_path = tmp_path_factory.mktemp(\"dataPath\")\n    for test_file in test_versions_2:\n        _build_test_item(d_path, test_file)\n\n    # in provided path\n    g_path = tmp_path_factory.mktemp(\"providedPath\")\n    for test_file in test_versions_3:\n        _build_test_item(g_path, test_file)\n\n    # dir vs zip preference\n    dir_path = tmp_path_factory.mktemp(\"dirZipPath\")\n    for test_file in test_versions_4:\n        _build_test_item(dir_path, test_file)\n\n    printer(\"testing finding Pype in given path ...\")\n    result = fix_bootstrap.find_pype(g_path, include_zips=True)\n    # we should have results as file were created\n    assert result is not None, \"no Pype version found\"\n    # latest item in `result` should be latest version found.\n    expected_path = Path(\n        g_path / \"{}{}{}\".format(\n            test_versions_3[3].prefix,\n            test_versions_3[3].version,\n            test_versions_3[3].suffix\n        )\n    )\n    assert result, \"nothing found\"\n    assert result[-1].path == expected_path, \"not a latest version of Pype 3\"\n\n    monkeypatch.setenv(\"PYPE_PATH\", e_path.as_posix())\n\n    result = fix_bootstrap.find_pype(include_zips=True)\n    # we should have results as file were created\n    assert result is not None, \"no Pype version found\"\n    # latest item in `result` should be latest version found.\n    expected_path = Path(\n        e_path / \"{}{}{}\".format(\n            test_versions_1[5].prefix,\n            test_versions_1[5].version,\n            test_versions_1[5].suffix\n        )\n    )\n    assert result, \"nothing found\"\n    assert result[-1].path == expected_path, \"not a latest version of Pype 1\"\n\n    monkeypatch.delenv(\"PYPE_PATH\", raising=False)\n\n    # mock appdirs user_data_dir\n    def mock_user_data_dir(*args, **kwargs):\n        return d_path.as_posix()\n\n    monkeypatch.setattr(appdirs, \"user_data_dir\", mock_user_data_dir)\n    fix_bootstrap.registry = OpenPypeSettingsRegistry()\n    fix_bootstrap.registry.set_item(\"pypePath\", d_path.as_posix())\n\n    result = fix_bootstrap.find_pype(include_zips=True)\n    # we should have results as file were created\n    assert result is not None, \"no Pype version found\"\n    # latest item in `result` should be latest version found.\n    expected_path = Path(\n        d_path / \"{}{}{}\".format(\n            test_versions_2[3].prefix,\n            test_versions_2[3].version,\n            test_versions_2[3].suffix\n        )\n    )\n    assert result, \"nothing found\"\n    assert result[-1].path == expected_path, \"not a latest version of Pype 2\"\n\n    result = fix_bootstrap.find_pype(e_path, include_zips=True)\n    assert result is not None, \"no Pype version found\"\n    expected_path = Path(\n        e_path / \"{}{}{}\".format(\n            test_versions_1[5].prefix,\n            test_versions_1[5].version,\n            test_versions_1[5].suffix\n        )\n    )\n    assert result[-1].path == expected_path, \"not a latest version of Pype 1\"\n\n    result = fix_bootstrap.find_pype(dir_path, include_zips=True)\n    assert result is not None, \"no Pype versions found\"\n    expected_path = Path(\n        dir_path / \"{}{}{}\".format(\n            test_versions_4[0].prefix,\n            test_versions_4[0].version,\n            test_versions_4[0].suffix\n        )\n    )\n    assert result[-1].path == expected_path, \"not a latest version of Pype 4\"\n","sub_path":"tests/igniter/test_bootstrap_repos.py","file_name":"test_bootstrap_repos.py","file_ext":"py","file_size_in_byte":13417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"23251431","text":"'''\nXMBC Script - IMDB Watched-Sync\n\nMarks movies or series rated on your IMDB account as 'watched' in XBMC's library.\n\nCreated on 16 apr 2014\n@author: Anton Jansson\n'''\n\nimport imdb\nimport json\nimport settings\nimport xbmc\nimport xbmcaddon\nimport xbmcgui\n\n__addon__ = xbmcaddon.Addon()\n__addonname__ = __addon__.getAddonInfo('name')\n__addonid__ = __addon__.getAddonInfo('id')\n__icon__ = __addon__.getAddonInfo('icon')\n\nNOTIFICATION_TIME = 5000\n\nRPC_GET_UNWATCHED_MOVIES = {\n    \"jsonrpc\": \"2.0\",\n    \"id\": \"libMovies\",\n    \"method\": \"VideoLibrary.GetMovies\",\n    \"params\": { \n        \"filter\": {\n            \"field\": \"playcount\",\n            \"operator\": \"is\",\n            \"value\": \"0\"\n        },\n        \"properties\" : [\"imdbnumber\"] \n    }\n}\nRPC_SET_MOVIE_WATCHED = {\n    \"jsonrpc\": \"2.0\",\n    \"id\": \"setWatched\",\n    \"method\": \"VideoLibrary.SetMovieDetails\",\n    \"params\": {\n        \"movieid\" : 0,\n        \"playcount\": 1\n    }\n}\n\ndef executeJSONRPC(query):\n    return json.loads(xbmc.executeJSONRPC(json.dumps(query)))\n\ndef getIMDBWatched():\n    response = imdb.loadRatedItems(settings.getIMDBUser())\n    if (response['success']):\n        return response['result']\n    else:\n        xbmcgui.Dialog().ok(__addonname__, \n            __addon__.getLocalizedString(32101) + '[CR]' +\n            response['error'],\n            '',\n            __addon__.getLocalizedString(32102))\n        return []\n\ndef getUnwatchedMovies():\n    response = executeJSONRPC(RPC_GET_UNWATCHED_MOVIES)\n    return response.get('result', {}).get('movies', [])\n\ndef getMovieIdsToUpdate():\n    \"\"\"Returns an array of movieIds that are rated (watched) on IMDB.\"\"\"\n    localUnwatched = getUnwatchedMovies()\n    imdbWatched = getIMDBWatched()\n    \n    localWatched = [x['movieid'] for x in localUnwatched if x['imdbnumber'] in imdbWatched]\n    \n    return localWatched\n\ndef setWatched(movieid):\n    RPC_SET_MOVIE_WATCHED['params']['movieid'] = movieid\n    executeJSONRPC(RPC_SET_MOVIE_WATCHED)\n\ndef showNotification(text):\n    xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__, text, NOTIFICATION_TIME, __icon__))\n\ndef updateLibrary():\n    if (not settings.check()):\n        xbmc.executebuiltin('Addon.OpenSettings(%s)'%(__addonid__))\n        return\n        \n    movieIds = getMovieIdsToUpdate()\n    for movie in movieIds:\n        setWatched(movie)\n     \n    showNotification(str(len(movieIds)) + \" movies were marked as watched\")","sub_path":"resources/lib/watched_sync.py","file_name":"watched_sync.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"223950068","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import HTTPError\n\nNCAAF_URL=\"https://www.espn.com/college-football/teams\"\n\ndef fetch_ncaaf_teams(url=NCAAF_URL):\n    \"\"\"Fetch the list of ncaa football teams\n    \n    Args:\n        url (string): the url of the web page for ncaa football teams \n    \n    Returns:\n            \n    \"\"\"\n    teams = []\n    \n    response = requests.get(url)\n    html = response.content\n    soup = BeautifulSoup(html, 'html.parser')\n    \n    conferences = soup.find_all(\"div\", class_=\"headline\")\n    for conference in conferences:\n        conference_name = conference.get_text()\n        team_links = conference.parent.find_all(\"a\", class_=\"AnchorLink\")\n        for team_link in team_links:\n            if team_link.find(\"h2\"):\n                team_url = team_link['href']\n                team_name = team_link.get_text()\n                team_id = int(team_url.split(\"/\")[-2])\n                teams.append({\"id\": team_id, \"name\": team_name, \"conference\": conference_name, \"url\": team_url})\n    return teams\n","sub_path":"assignment/cpsc6300-001/ps01/espn.py","file_name":"espn.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"31377977","text":"import tensorflow as tf\nimport numpy as np \nimport cPickle as pickle \n#import tf_util\nimport argparse\nimport os\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu', type=int, default=2, help='GPU to use [default: GPU 0]')\n#parser.add_argument('--model', default='lanenet', help='Model name: pointnet_cls or pointnet_cls_basic [default: pointnet_cls]')\nparser.add_argument('--max_epoch', type=int, default=1000000, help='Epoch to run [default: 100]')\nparser.add_argument('--batch_size', type=int, default=5000, help='Batch Size during training [default: 32]')\nparser.add_argument('--log_dir', default='log', help='Log dir [default: log]')\nparser.add_argument('--learning_rate', type=float, default=0.001, help='Initial learning rate [default: 0.001]')\nparser.add_argument('--decay_step', type=int, default=200000, help='Decay step for lr decay [default: 50000]')\nparser.add_argument('--decay_rate', type=float, default=0.7, help='Decay rate for lr decay [default: 0.8]')\nFLAGS = parser.parse_args()\n\nBATCH_SIZE = FLAGS.batch_size\nMAX_EPOCH = FLAGS.max_epoch\nBASE_LEARNING_RATE = FLAGS.learning_rate\nGPU_INDEX = FLAGS.gpu\nDECAY_STEP = FLAGS.decay_step\nDECAY_RATE = FLAGS.decay_rate\nLOG_DIR = FLAGS.log_dir\n\nnum_feat = 271\nnum_mid = 10\n\nbatch_size = BATCH_SIZE\n\nif not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR)\nos.system('cp pm.py %s' % (LOG_DIR))\nLOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w')\nLOG_FOUT.write(str(FLAGS)+'\\n')\n\ndef log_string(out_str):\n    LOG_FOUT.write(out_str+'\\n')\n    LOG_FOUT.flush()\n    print(out_str)\n\ndef get_learning_rate(batch):\n    learning_rate = tf.train.exponential_decay(\n                        BASE_LEARNING_RATE,  # Base learning rate.\n                        batch * BATCH_SIZE,  # Current index into the dataset.\n                        DECAY_STEP,          # Decay step.\n                        DECAY_RATE,          # Decay rate.\n                        staircase=True)\n    learing_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\n    return learning_rate    \n\ndef shuffle_data(data, labels):\n    idx = np.arange(len(labels))\n    np.random.shuffle(idx)\n    return data[idx, ...], labels[idx], idx\n\n\ndef optim(loss, category, lr=0.0001, beta1=0.9, beta2=0.99):\n    optim = tf.train.AdamOptimizer(learning_rate=lr, beta1=beta1, beta2=beta2)\n\n    var_list = [t for t in tf.trainable_variables() if t.name.startswith(category)]\n    gradient = optim.compute_gradients(loss, var_list = var_list)\n\n    global_step = tf.Variable(0, name='global_step', trainable=False)\n    return optim.apply_gradients(gradient, global_step=global_step), global_step\n\ndef placeholder_input(batch_size, num_feat):\n    place_input = tf.placeholder(tf.float32, shape=(batch_size, num_feat))\n    place_output = tf.placeholder(tf.float32, shape=(batch_size, 1))\n    return place_input, place_output\n\ndef cal_loss(gt, loss):\n    num_all = gt.get_shape()[0].value\n    num_pos = tf.reduce_sum(gt)\n    num_neg = num_all - num_pos\n    #loss_weight = gt * ((num_neg) / (num_pos) - 1) + 1.0\n    loss_weight = gt * (10 - 1) + 1.0\n    loss_f = tf.reduce_sum(loss*loss_weight)\n    #tf.Print(num_pos, data)\n    return loss_f\n\ndef get_model(input_ph, gt_ph):\n    batch_size = input_ph.get_shape()[0].value\n    with tf.variable_scope('main_net'):        \n        weight_l1 = tf.get_variable('weight_l1', [num_feat, num_mid])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n        layer_1 = tf.tanh(tf.matmul(input_ph, weight_l1))\n\n        weight_o = tf.get_variable('weight_o', [num_mid, 1])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n        layer_o = tf.sigmoid(tf.matmul(layer_1, weight_o))\n\n        weight_sum = tf.reduce_sum(tf.abs(weight_l1))\n\n        #loss_rc_raw = (layer_o-gt_ph)*(layer_o-gt_ph)\n        loss_rc_raw = -(gt_ph * tf.log(layer_o) + (1-gt_ph) * tf.log(1-layer_o))\n        loss_rc = cal_loss(gt_ph, loss_rc_raw)\n\n    with tf.variable_scope('pm_net'):\n        shut_mat = tf.constant(1 - np.eye(num_mid), dtype = np.float32)\n        weight_dict = {}\n        pm_dict = {}\n        #pm_out_dict = {}\n        pm_loss_dict = {}\n        loss_pm_sum = tf.Variable(0.0, trainable=False)\n        for i in range(num_mid):\n            weight_dict['weight_pm_'+str(i)] = tf.get_variable('weight_pm_'+str(i), [num_mid,1])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n            pm_dict['pm_dict_'+str(i)] = tf.matmul(layer_1*shut_mat[i], weight_dict['weight_pm_'+str(i)])\n            pm_loss_dict['pm_loss' + str(i)] = tf.reduce_mean((pm_dict['pm_dict_'+str(i)] - layer_1[i])*(pm_dict['pm_dict_'+str(i)] - layer_1[i])) \n            loss_pm_sum += pm_loss_dict['pm_loss' + str(i)]\n    loss_main = loss_rc + 0.15* weight_sum - loss_pm_sum#/num_mid\n    tf.summary.scalar('loss_main', loss_main)\n    tf.summary.scalar('loss_pm', loss_pm_sum)\n    tf.summary.scalar('loss_rc', loss_rc)\n    tf.summary.scalar('loss_l1', weight_sum)\n    tf.summary.histogram('weight_dis', weight_l1)\n    return loss_main, loss_pm_sum, layer_o, layer_1\n\ndef train_one_epoch(input_data, gt_data, sess, ops, train_writer):\n    \"\"\" ops: dict mapping from string to tf ops \"\"\"\n    #is_training = True\n    \n    # Shuffle train files\n    #train_file_idxs = np.arange(0, len(TRAIN_FILES))\n    #np.random.shuffle(train_file_idxs)\n    \n    log_string('----' + str('Hahahahaha') + '-----')\n    current_data, current_label, _ = shuffle_data(input_data, gt_data)            \n    #current_label = np.squeeze(current_label)\n    \n    file_size = current_data.shape[0]\n    num_batches = file_size / BATCH_SIZE\n    \n    for batch_idx in range(num_batches):\n        start_idx = batch_idx * BATCH_SIZE\n        end_idx = (batch_idx+1) * BATCH_SIZE\n\n        in_data = current_data[start_idx:end_idx, :, :]\n        in_gt = current_label[start_idx:end_idx, :, :]\n\n        summary, step, _, loss_val,l_matrix,t_matrix = sess.run([ops['merged'], ops['step'],\n            ops['train_op'], ops['loss'], ops['matrix'],ops['trans_ma']], feed_dict=feed_dict)\n        train_writer.add_summary(summary, step)\n        loss_sum += loss_val\n\n\n    log_string('loss: %f' % (loss_sum/num_batches))\n\n\nwith tf.Graph().as_default():\n    with tf.device('/gpu:'+str(GPU_INDEX)):\n        input_ph, gt_ph = placeholder_input(batch_size, num_feat)\n\n        loss_main, loss_pm_sum, layer_o, layer_1 = get_model(input_ph, gt_ph)\n\n\n        train_main, main_global_step = optim(loss_main, category = 'main_net')\n        train_pm, pm_global_step = optim(loss_pm_sum, category = 'pm_net')\n\n        init = tf.global_variables_initializer()\n        saver = tf.train.Saver()\n\n        config = tf.ConfigProto()\n        config.gpu_options.allow_growth = True\n        config.allow_soft_placement = True\n        config.log_device_placement = False\n\n        sess = tf.Session(config = config)\n\n        merged = tf.summary.merge_all()\n        train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'), sess.graph)\n        test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'))\n\n        #input_data = pickle.load()\n        #gt_data = pickle.load()\n        #input_data = np.random.random((400,280))\n        #gt_data = np.random.random((400,1))\n        data_all = np.load('./data/data.npy')\n        input_data = data_all[0:1400000, 0:-1]\n        gt_data = np.reshape(data_all[0:1400000, -1],(-1, 1))\n\n        input_test = data_all[-148208:, 0:-1]\n        gt_test = np.reshape(data_all[-148208:, -1],(-1, 1))\n        file_size = input_data.shape[0]\n        num_batches = file_size / BATCH_SIZE\n        sess.run(init)\n        for epoch in range(MAX_EPOCH):\n            log_string('**** EPOCH %03d ****' % (epoch))\n            sys.stdout.flush()\n            \n            current_data, current_label, _ = shuffle_data(input_data, gt_data)            \n            \n            file_size = current_data.shape[0]\n            num_batches = file_size / BATCH_SIZE\n            loss_sum = 0\n            for batch_idx in range(num_batches):\n                start_idx = batch_idx * BATCH_SIZE\n                end_idx = (batch_idx+1) * BATCH_SIZE\n\n                in_data = current_data[start_idx:end_idx, ...]\n                in_gt = current_label[start_idx:end_idx, ...]\n                \n                _, main_step, loss_val = sess.run([train_main, main_global_step, loss_main], feed_dict={input_ph: in_data, gt_ph: in_gt})\n                _, pm_step, summary = sess.run([train_pm, pm_global_step, merged], feed_dict={input_ph: in_data, gt_ph: in_gt})\n                #summary  = sess.run([merged])\n\n\n                train_writer.add_summary(summary, main_step)\n                loss_sum += loss_val\n            ind_test = np.random.randint(0, 148208 - batch_size)\n            re_test = sess.run([layer_o], feed_dict={input_ph: input_test[ind_test:ind_test+batch_size, ...], gt_ph: gt_test[ind_test:ind_test+batch_size, ...]})\n\n            for ind_loop in range(batch_size):\n                print [re_test[0][ind_loop], gt_test[ind_test + ind_loop]]\n            #print re_test\n            #print gt_test[ind_test:ind_test+100, ...]\n\n\n            log_string('loss: %f' % (loss_sum/num_batches))\n\n            \n            # Save the variables to disk.\n            if epoch % 10 == 0:\n                save_path = saver.save(sess, os.path.join(LOG_DIR, \"model.ckpt\"))\n                log_string(\"Model saved in file: %s\" % save_path)\n\n\n","sub_path":"pm.py","file_name":"pm.py","file_ext":"py","file_size_in_byte":9373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"420826718","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pandas as pd, numpy as np\nimport unicodedata\nimport math\nimport string\nfrom bs4 import BeautifulSoup\nfrom gensim import corpora\nfrom gensim import models\nimport MeCab\n\n\n\n# MeCabの辞書にNEologdを指定。\n# mecabは携帯素解析用、wakatiは分かち書き用\nmecab = MeCab.Tagger('-d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd/')\nwakati = MeCab.Tagger(\"-Owakati -d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd/\")\n\n# 形態素解析を行う関数を定義\n# ファイルを入力するとファイルを出力し、文字列を渡すと文字列を返します。引数fileで変更します。\n# 単に分かち書きしたいだけの場合は引数にmecab=wakatiとすると実現できます。\ndef MecabMorphologicalAnalysis(path='./text.txt', output_file='wakati.txt', mecab=mecab, file=False):\n    mecab_text = ''\n    if file:\n        with open(path) as f:\n            for line in f:\n                mecab_text += mecab.parse(line)\n        with open(output_file, 'w') as f:\n            print(mecab_text, file=f)\n    else:\n        for path in path.split('\\n'):\n            mecab_text += mecab.parse(path)\n        return mecab_text\n\n\n\n# 記号文字は分析をするにあたって邪魔になるため、記号を取り除く関数を定義します。\n# 下のYahooNews関数で使用します。\ndef symbol_removal(soup):\n    soup = unicodedata.normalize(\"NFKC\", soup)\n    exclusion = \"「」『』【】〈〉《》≪≫、。・◇◆■●\" + \"\\n\" + \"\\r\" + \"\\u3000\" # 除去する記号文字を指定\n    soup = soup.translate(str.maketrans(\"\", \"\", string.punctuation  + exclusion))\n    return soup\n\n\n\n# 青空文庫の情報をスクレイピングして、テーブルデータに整形する処理を行う関数を定義します。  \n# 引数に指定した数のタイトルを出力します。(デフォルトは30)  \n# 中でsymbol_removal関数を使用しています。\ndef Aozora_table(n=30):\n    url = \"https://www.aozora.gr.jp/access_ranking/2019_xhtml.html\"\n    res = requests.get(url)\n    res.encoding = 'shift-jis'\n    soup = BeautifulSoup(res.content, \"html.parser\")\n\n    url_list = [url[\"href\"] for i, url in enumerate(soup.find_all(\"a\", target=\"_blank\")) if i < n]\n\n    title = []\n    category = []\n    text = []\n    for url in url_list:\n        res = requests.get(url)\n        url_start = url[:37]\n        res.encoding = 'shift-jis'\n        soup = BeautifulSoup(res.content, \"html.parser\")\n        for i, a in enumerate(soup.find_all(\"a\")):\n            if i == 7:\n                url_end = a[\"href\"][1:]\n        url = url_start + url_end\n        res = requests.get(url)\n        res.encoding = 'shift-jis'\n        soup = BeautifulSoup(res.content, \"html.parser\")\n        title.append(soup.find(\"h1\").string)\n        category.append(soup.find(\"h2\").string)\n        for tag in soup.find_all([\"rt\", \"rp\"]):\n            tag.decompose()\n        soup = soup.find(\"div\",{'class': 'main_text'}).get_text()\n        text.append(symbol_removal(soup))\n    df = pd.DataFrame({'title': title, 'category': category, 'text': text})\n    return df\n\n\n# Yahooニュースをスクレイピングする関数です。\n# 引数で指定した数の記事をとってきてデータフレームを返します。\ndef YahooNews(n=30):\n    url = \"https://news.yahoo.co.jp/topics/top-picks\"\n    URL = \"https://news.yahoo.co.jp/\"\n    res = requests.get(url)\n    soup = BeautifulSoup(res.text, \"html.parser\")\n    all_page_links = []\n    all_page_links.append(url)\n    all_links = []\n    while True:\n        try:\n            next = soup.find(\"li\", class_=\"pagination_item-next\").find(\"a\")[\"href\"]\n            next_link = URL + next\n            all_page_links.append(next_link)\n            next_res = requests.get(next_link)\n            soup = BeautifulSoup(next_res.text, \"html.parser\")\n        except:\n            break\n            \n    title_list = []\n    category_list = []\n    text_list = []\n    for url in all_page_links: # all_page_links: 全てのニュースのリスト\n            res = requests.get(url) # url: 25個分のニュースのリスト\n            soup = BeautifulSoup(res.text, \"html.parser\")\n            page_soup = soup.find_all(\"a\", class_=\"newsFeed_item_link\")\n            for href in page_soup:\n                link = href[\"href\"] # link: 一つのニュースのリンク(本文は一部のみ)\n                all_links.append(link)\n    \n    if len(all_links) <= n:\n        n = len(all_links)\n    \n    i = 0\n    for link in all_links:\n        link_res = requests.get(link)\n        href_soup = BeautifulSoup(link_res.text, \"html.parser\")\n        try:\n            title = href_soup.find(\"h1\", class_=re.compile(\"^sc\")).string\n        except:\n            continue\n        title_link = href_soup.find(\"a\", class_=\"sc-fUKxqW\")[\"href\"] # title_link: 本文\n        res = requests.get(title_link)\n        soup = BeautifulSoup(res.text, \"html.parser\")\n\n        category = soup.find_all(\"li\", class_=\"current\")\n        try:\n            category = category[1].string\n        except:\n            continue\n        else:\n            for tag in soup.find_all([\"a\"]):\n                tag.decompose()\n            try:\n                soup = soup.find(\"div\", class_=\"article_body\").get_text()\n                soup = symbol_removal(soup)\n                \n                text_list.append(soup)\n                title_list.append(title)\n                category_list.append(category)\n                i += 1 # 本文が正常に保存できたことをトリガーにしてカウントを一つ増やすことにします。\n                pro_bar = ('=' * math.ceil(i / (n / 20))) + (' ' * int((n / (n / 20)) - math.ceil(i / (n / 20))))\n                print('\\r[{0}] {1}記事'.format(pro_bar, i), end='')\n                if i >= n:\n                    df = pd.DataFrame({'title': title_list, 'category': category_list, 'text': text_list})\n                    return df\n            except:\n                continue\n    df = pd.DataFrame({'title': title_list, 'category': category_list, 'text': text_list})\n    return df\n\n\n\n# 分かち書きされた2階層の単語のリストを渡すことで、TF-IDFでソートされたユニークな単語のリストを得る。\ndef sortedTFIDF(sentences):\n    \n    # 単語にIDを添付します。\n    dictionary = corpora.Dictionary(sentences)\n    \n    # 作品ごとの単語の出現回数をカウント\n    corpus = list(map(dictionary.doc2bow, sentences))\n    \n    # 単語ごとにTF-IDFを算出\n    test_model = models.TfidfModel(corpus)\n    corpus_tfidf = test_model[corpus]\n    \n    # ID:TF-IDF → TF-IDF:単語 に変換。TF-IDFを左に持ってくることで、sortedを用いてTF-IDFを基準にソートすることができます。\n    texts_tfidf = []\n    for doc in corpus_tfidf:\n        text_tfidf = []\n        for word in doc:\n            text_tfidf.append([word[1], dictionary[word[0]]])\n        texts_tfidf.append(text_tfidf)\n    \n    # TF-IDFを基準にソートを行います。\n    sorted_texts_tfidf = []\n    for text in texts_tfidf:\n        sorted_text = sorted(text, reverse=True)\n        sorted_texts_tfidf.append(sorted_text)\n\n    return sorted_texts_tfidf\n\n\n\n# v1とv2のコサイン類似度を出力します。\ndef cos_sim(v1, v2):\n    return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))","sub_path":"work/analysis/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":7405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"4254071","text":"def triangle(n):\n    import random\n    count = 0\n    for i in range(n):\n        first_line = random.random()\n        random_number = random.random()\n        second_line = (1-first_line) * random_number\n        third_line = 1 - first_line - second_line\n        numbers = [first_line, second_line, third_line]\n        numbers.sort()\n        if numbers[0]+ numbers[1] > numbers[2]:\n            count += 1\n    if count == 0:\n        return 0\n    else:\n        return count/n\n\n\ndef expectation(n,m):\n    mean = 0\n    for i in range(m):\n        mean += triangle(n)\n    print( mean / m)\n\nexpectation(500,20)\nexpectation(1000,20)   \nexpectation(10000,20)\n\n\n\n\n\n\n","sub_path":"semester1/프로그래밍/codes/make_triangle_assignment.py","file_name":"make_triangle_assignment.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"249574148","text":"from django.db import models\nfrom datetime import datetime, timedelta\nfrom django.shortcuts import reverse, redirect\nfrom django.utils import timezone as tmz\n\nclass Company(models.Model):\n    name = models.CharField('Company name', max_length=30)\n    size_limit = models.DecimalField('Traffic limit for a month(in TB)', max_digits=10, decimal_places=2)\n    \n    def __str__(self):\n        return self.name\n\n    class Meta:\n        verbose_name = 'Company'\n        verbose_name_plural = 'Companies'\n\nclass Users(models.Model):\n    full_name = models.CharField('Full name', max_length=40)\n    email = models.EmailField('Email', null=True, blank=True)\n    company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='Company')\n\n    def __str__(self):\n        return 'User {} || company {}'.format(self.full_name, self.company)\n    \n    class Meta:\n        verbose_name = 'User'\n        verbose_name_plural = 'Users'\n\nclass TransferLogs(models.Model):\n    user = models.ForeignKey(Users, on_delete=models.CASCADE, verbose_name='User')\n    date = models.DateTimeField('Date n time of transfer', default=tmz.now())\n    recource = models.CharField('Recourse', max_length=40)\n    transferred = models.BigIntegerField('Was transferred(in bytes)')\n\n    \n    def __str__(self):\n        return 'User {} transferred {} into {}'.format(self.user.full_name, self.transferred, self.recource)\n     \n\n    class Meta:\n        verbose_name = 'Transfer log'\n        verbose_name_plural = 'Transfer logs'\n\nclass Report(models.Model):\n    company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='Company')\n    traffic_used = models.DecimalField('Was used (in TB)', default=0, max_digits=10, decimal_places=2)\n    date_start = models.DateField('Date start of using traffic', default=datetime.now())\n    date_end = models.DateField('Date end of using traffic', default=datetime.now()+timedelta(days=30))\n    exceeding_limit = models.DecimalField('Exceeding the limit for', max_digits=6, decimal_places=2, default=0,)\n    more_than_limit = models.BooleanField('Whether the limit was exceeded', default=False)\n\n    def __str__(self):\n        return self.company.name\n            \n    \n    class Meta:\n        verbose_name = 'Report'\n        verbose_name_plural = 'Reports'\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"601245701","text":"from DDQN_Model import ddqnTrainer\r\nfrom get_environment import GetEnv\r\nfrom gather_training_points import readReward\r\nimport pyautogui\r\nfrom time import sleep\r\n\r\n\r\nFrames = 4\r\nOutFrameSize = 80\r\nInFrameDim = (556, 838, 449, 786)\r\nInputShape = (Frames, InFrameDim[1]-InFrameDim[0], InFrameDim[3] - InFrameDim[2])\r\nTotalStepLimit = 5000000\r\nActionSpace = 5\r\n\r\n\r\nclass Environment:\r\n    def __init__(self):\r\n        self.env = GetEnv(inDim=InFrameDim, outDim=(OutFrameSize, OutFrameSize))\r\n        self.out = []\r\n        for i in range(5):\r\n            self.out.append(self.env.takeImage(4, \"None\"))\r\n        while True:\r\n            self.out.append(self.env.takeImage(4, \"None\"))\r\n            self.out.pop(0)\r\n\r\n    def getEnvironment(self):\r\n        return self.out\r\n\r\n    def step(self, action):\r\n        print(f\"action: {action}\")\r\n        if action == 0:\r\n            pyautogui.press('left')\r\n        elif action == 1:\r\n            pyautogui.press('up')\r\n        elif action == 2:\r\n            pyautogui.press('down')\r\n        elif action == 3:\r\n            pyautogui.press('right')\r\n        elif action == 4:\r\n            pyautogui.press('enter')\r\n        else:\r\n            sleep(1 / 28)\r\n\r\n\r\ndef main():\r\n    run = 0\r\n    total_step = 0\r\n    game_model = ddqnTrainer(InputShape, ActionSpace)\r\n    prev_score = 0\r\n    while True:\r\n        run += 1\r\n        env = Environment()\r\n        current_state = env.getEnvironment()\r\n        step = 0\r\n        score = readReward()\r\n        while total_step <= TotalStepLimit:\r\n            total_step += 1\r\n            step += 1\r\n            print(f\"Step: {total_step}\")\r\n            action = game_model.move(current_state)\r\n            env.step(action)\r\n            next_state = env.getEnvironment()\r\n            current_score = score.mainLoop()\r\n            reward = current_score - prev_score\r\n            print(reward)\r\n            prev_score = current_score\r\n            game_model.remember(current_state, action, reward, next_state)\r\n            game_model.step_update(total_step)\r\n\r\n\r\nmain()\r\n","sub_path":"Main_Pacman_Bot.py","file_name":"Main_Pacman_Bot.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"419115211","text":"from django.forms import ModelForm,Textarea,TextInput\nfrom .models import Contact,Subscriber\nfrom django import forms\nfrom captcha.fields import ReCaptchaField\n\n\nclass ContactForm(ModelForm):\n    captcha = ReCaptchaField()\n\n    class Meta:\n        model = Contact\n        fields = ('name','email','subject','message','captcha')\n        labels = {\n            'name': 'Your name (optional):',\n            'email': 'Email:',\n            'subject': 'Subject:',\n            'message': 'Message:',\n        }\n        widgets = {\n            'message': Textarea(attrs={\n              'cols': 80,\n              'rows': 20,\n              'class': 'materialize-textarea',\n              }),\n        }\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.fields['captcha'].label = ''\n       \n\n\nclass UnSubscriberForm(forms.Form):\n    email = forms.EmailField(required=False,widget=forms.TextInput(attrs={\n        \"class\":\"unsub-form-style\",\n    }))\n\n  \n\n        ","sub_path":"pages/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"305590481","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom contextlib import contextmanager\nfrom distutils.version import LooseVersion\n\nfrom tensorflow.contrib.framework import arg_scope\nfrom tensorflow.python.framework import ops\n\nfrom .imagenet_utils import *\nfrom .keras_utils import *\nfrom .layers import conv2d\n\n\n__outputs__ = 'outputs'\n\n\ndef print_collection(collection, scope):\n    if scope is not None:\n        print(\"Scope: %s\" % scope)\n    for x in tf.get_collection(collection, scope=scope):\n        name = x.name\n        if scope is not None:\n            name = name[len(scope)+1:]\n        print(\"%s %s\" % (name, x.shape))\n\n\ndef parse_scopes(inputs):\n    if not isinstance(inputs, list):\n        inputs = [inputs]\n    outputs = []\n    for scope_or_tensor in inputs:\n        if isinstance(scope_or_tensor, tf.Tensor):\n            outputs.append(scope_or_tensor.aliases[0])\n        elif isinstance(scope_or_tensor, str):\n            outputs.append(scope_or_tensor)\n        else:\n            outputs.append(None)\n    return outputs\n\n\ndef print_outputs(scopes=None):\n    scopes = parse_scopes(scopes)\n    for scope in scopes:\n        print_collection(__outputs__, scope)\n\n\ndef print_weights(scopes=None):\n    scopes = parse_scopes(scopes)\n    for scope in scopes:\n        print_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope)\n\n\ndef print_summary(scopes=None):\n    scopes = parse_scopes(scopes)\n    for scope in scopes:\n        if scope is not None:\n            print(\"Scope: %s\" % scope)\n        weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n        names = [w.name for w in weights]\n        starts = [n.rfind('/') + 1 for n in names]\n        ends = [n.rfind(':') for n in names]\n\n        layers = sum([n[s:e] == 'weights'\n                      for (n, s, e) in zip(names, starts, ends)])\n        parameters = sum([w.shape.num_elements() for w in weights])\n        print(\"Total layers: %d\" % layers)\n        print(\"Total weights: %d\" % len(weights))\n        print(\"Total parameters: {:,}\".format(parameters))\n\n\ndef get_outputs(scope=None):\n    scope = parse_scopes(scope)[0]\n    return tf.get_collection(__outputs__, scope=scope)\n\n\ndef get_weights(scope=None):\n    scope = parse_scopes(scope)[0]\n    return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n\n\ndef crop_idx(total_size, crop_size, crop_loc, crop_grid):\n    if isinstance(total_size, int):\n        total_size = (total_size, total_size)\n    if isinstance(crop_size, int):\n        crop_size = (crop_size, crop_size)\n    if crop_loc > -1:\n        row_loc = crop_loc // crop_grid[0]\n        col_loc = crop_loc % crop_grid[1]\n        row_start = row_loc * (total_size[0] - crop_size[0]) // 2\n        col_start = col_loc * (total_size[1] - crop_size[1]) // 2\n    else:\n        row_start = np.random.randint(0, total_size[0] - crop_size[0], 1)[0]\n        col_start = np.random.randint(0, total_size[1] - crop_size[1], 1)[0]\n    return row_start, col_start\n\n\ndef crop(img, crop_size, crop_loc=4, crop_grid=(3, 3)):\n    r, c = crop_idx(img.shape[1:3], crop_size, crop_loc, crop_grid)\n    return img[:, r:r+crop_size, c:c+crop_size, :]\n\n\ndef init(scopes):\n    sess = tf.get_default_session()\n    assert sess is not None, 'The default session should be given.'\n\n    if not isinstance(scopes, list):\n        scopes = [scopes]\n\n    for scope in scopes:\n        sess.run(tf.variables_initializer(get_weights(scope)))\n\n\ndef var_scope(name):\n    def decorator(func):\n        def wrapper(*args, **kwargs):\n            scope = kwargs.get('scope', None)\n            reuse = kwargs.get('reuse', None)\n            with tf.variable_scope(scope, name, reuse=reuse):\n                return func(*args, **kwargs)\n        return wrapper\n    return decorator\n\n\ndef ops_to_outputs(func):\n    def wrapper(*args, **kwargs):\n        x = func(*args, **kwargs)\n        ops.add_to_collection(__outputs__, x)\n        return x\n    return wrapper\n\n\n@contextmanager\ndef arg_scopes(l):\n    for x in l:\n        x.__enter__()\n    yield\n\n\ndef set_args(largs, conv_bias=True):\n    def real_set_args(func):\n        def wrapper(*args, **kwargs):\n            is_training = kwargs.get('is_training', False)\n            layers = sum([x for (x, y) in largs(is_training)], [])\n            layers_args = [arg_scope(x, **y) for (x, y) in largs(is_training)]\n            if not conv_bias:\n                layers_args += [arg_scope([conv2d], biases_initializer=None)]\n            with arg_scope(layers, outputs_collections=__outputs__):\n                with arg_scopes(layers_args):\n                    return func(*args, **kwargs)\n        return wrapper\n    return real_set_args\n\n\ndef set_weights(weights, values):\n    sess = tf.get_default_session()\n    assert sess is not None, 'The default session should be given.'\n\n    if len(weights) > len(values):  # excluding weights in Optimizer\n        weights = weights[:len(values)]\n\n    assert len(weights) == len(values), 'The sizes of symbolic and ' \\\n                                        'actual weights do not match.' \\\n\n    ops = [w.assign(v) for (w, v) in zip(weights[:-2], values[:-2])]\n    if weights[-1].shape != values[-1].shape:  # for transfer learning\n        ops += [w.initializer for w in weights[-2:]]\n    else:\n        ops += [w.assign(v) for (w, v) in zip(weights[-2:], values[-2:])]\n    sess.run(ops)\n\n\ndef load_weights(scopes, weights_path):\n    scopes = parse_scopes(scopes)\n\n    data = np.load(weights_path, encoding='bytes')\n    values = data['values']\n\n    if LooseVersion(tf.__version__) > LooseVersion('1.3.0'):\n        for (i, name) in enumerate(data['names']):\n            if '/beta' in name:\n                values[i], values[i+1] = values[i+1], values[i]\n\n    for scope in scopes:\n        weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n        set_weights(weights, values)\n\n\ndef load_torch_weights(scopes, weights_path, move_rules=None):\n    try:\n        import torch\n        import torch.nn as nn\n        import torch.nn.functional as F\n    except ImportError:\n        torch = None\n    assert torch is not None, '`load_torch_weights` requires `torch`.'\n\n    scopes = parse_scopes(scopes)\n\n    model = torch.load(weights_path)\n    names = list(model.keys())\n    if move_rules is not None:\n        if isinstance(move_rules, list):\n            for (name, loc) in move_rules:\n                idx = names.index(name)\n                names.insert(idx + loc, names.pop(idx))\n\n    for (i, name) in enumerate(names):\n        if 'running_mean' in name:\n            names[i-1], names[i-2] = names[i-2], names[i-1]\n\n    values = []\n    for name in names:\n        val = model[name].numpy()\n        if val.ndim == 4:\n            val = np.transpose(val, [2, 3, 1, 0])\n        if val.ndim == 2:\n            val = np.transpose(val, [1, 0])\n        if val.ndim == 4:\n            groups = val.shape[3] // val.shape[2]\n            if (groups == 32) or (groups == 64):\n                values += np.split(val, groups, axis=3)\n            else:\n                values.append(val)\n        else:\n            values.append(val)\n\n    for scope in scopes:\n        weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n        set_weights(weights, values)\n\n\ndef remove_utils(module_name, exceptions):\n    import sys\n    from . import utils\n    module = sys.modules[module_name]\n    for util in dir(utils):\n        if not ((util.startswith('_')) or (util in exceptions)):\n            try:\n                delattr(module, util)\n            except:\n                None\n    delattr(module, 'keras_utils')\n","sub_path":"tensornets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"174205722","text":"# (c) Copyright [2021] Micro Focus or one of its affiliates.\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# This is a script for re-ip local Vertica node in Kubernetes Init Container\n# and restart local Vertica node in Kubernetes Vertica app container\n# the script is expected to be simple and lightweight\nimport sys\nimport subprocess\nimport os\nimport configparser\nimport argparse\n\ndef checkAdmintoolsConfExists(atConfFilePath):\n    return os.path.isfile(atConfFilePath)\n\ndef getCommandResult(args, label):\n    proc = subprocess.Popen(args, stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE, shell=True)\n    result, error = proc.communicate()\n    if proc.returncode != 0:\n        print(f\"Error in running command {label}: {error.decode(sys.stdout.encoding)}\")\n    return result.decode(sys.stdout.encoding)\n\ndef getActiveDB():\n    activeDb = \"\"\n    args = \"/opt/vertica/bin/admintools -t show_active_db\"\n    activeDbStr = getCommandResult(args, \"get active db\").rstrip()\n    if not activeDbStr:\n        return \"\"\n    # split output by \" \", following the output format of show_active_db\n    activeDb = activeDbStr.split(\" \")[0]\n    print(f\"active database is: {activeDb}\")\n    return activeDb\n\ndef getLocalVerticaNodeName(dbName, atConfFilePath):\n    localVNodeName = \"\"\n    if atConfFilePath is None or not os.path.isfile(atConfFilePath) or os.stat(atConfFilePath).st_size <= 0:\n        return False, localVNodeName\n\n    atConfig = configparser.ConfigParser()\n    try:\n        atConfig.read(atConfFilePath)\n    except configparser.Error as err:\n        print(f\"Error during reading admintools.conf: {err}\")\n        return False, localVNodeName\n\n    if not atConfig.has_section('Nodes'):\n        return False, localVNodeName\n\n    # important assumption: all nodes have the same catalog path\n    templateNodeInfo = atConfig.items('Nodes')[0]\n    catalogPath = templateNodeInfo[1].split(\",\")[1]\n\n    # get local vertica node name by checking catalog directory on local pod\n    args = f\"ls {catalogPath}/{dbName}/ | grep '^v_.*_catalog$' | head -1 | sed 's/_[^_]*$//'\"\n\n    localVNodeName = getCommandResult(args, \"get local Vertica node name\").rstrip()\n    if not localVNodeName:\n        return False, localVNodeName\n    return True, localVNodeName\n\ndef getLocalPodIp():\n    return os.environ['POD_IP']\n\ndef getDbAdminPwd():\n    getPwdArgs = \"cat /etc/podinfo/superuser-passwd 2> /dev/null || :\"\n    dbadminPwd = getCommandResult(getPwdArgs, \"get dbadmin secret\").rstrip()\n    return dbadminPwd\n\ndef reIpLocalNodeClusterUp(activeDb, atConfFilePath, localVNodeName):\n    localVNodeNewIp = getLocalPodIp()\n\n    if not localVNodeNewIp:\n        return False, \"Failed to get IP address of local Pod.\"\n\n    # get dbadmin password\n    dbadminPwd = getDbAdminPwd()\n    args = \"\"\n    # call AT db_change_node_ip to re-ip the local Vertica node\n    passOpts = \" -p {}\".format(dbadminPwd) if dbadminPwd else \"\"\n    args = f\"/opt/vertica/bin/admintools -t db_change_node_ip -d {activeDb} -s {localVNodeName} --new-host-ips {localVNodeNewIp}{passOpts}\"\n\n    print(f\"Updating IP address of local Vertica node {localVNodeName} to be {localVNodeNewIp} ...\")\n    nodeReIpResult = getCommandResult(args, \"update IP address of local Vertica node\")\n\n    # check if the node has been re-iped successfully\n    nodeReIpMsg = \"IP addresses of nodes have been updated successfully\"\n    nodeNoIpChangeMsg = \"Skip updating IP addresses: all nodes have up-to-date addresses\"\n    if nodeReIpMsg in nodeReIpResult or nodeNoIpChangeMsg in nodeReIpResult:\n        return True, \"\"\n    else:\n        return False, \"Failed to update IP address for local Vertica node, check admintools.log for more information.\"\n\ndef restartLocalNode(activeDb, atConfFilePath, localVNodeName):\n    # get dbadmin password\n    dbadminPwd = getDbAdminPwd()\n    args = \"\"\n    # call AT restart_node to restart the local Vertica node\n    passOpts = \" -p {}\".format(dbadminPwd) if dbadminPwd else \"\"\n    args = f\"/opt/vertica/bin/admintools -t restart_node -d {activeDb} -s {localVNodeName}{passOpts}\"\n\n    print(f\"Restarting local Vertica node {localVNodeName} ...\")\n    restartResult = getCommandResult(args, \"restart local Vertica node\")\n\n    # check if the node has been restarted successfully\n    nodeRestartMsg = f\"{localVNodeName}: (UP)\"\n    if nodeRestartMsg in restartResult:\n        return True, \"\"\n    else:\n        return False, \"Failed to restart local Vertica node, check admintools.log for more information.\"\n\ndef main():\n    argParser = argparse.ArgumentParser()\n    argParser.add_argument(\"--re-ip-node\",\n                           action = 'store_true',\n                           dest = \"reIpNode\",\n                           help = \"Update IP address of local Vertica node\")\n    argParser.add_argument(\"--restart-node\",\n                           action = 'store_true',\n                           dest = \"restartNode\",\n                           help = \"Restart local Vertica node\")\n    args = argParser.parse_args()\n    atConfFilePath = \"/opt/vertica/config/admintools.conf\"\n    # step 1: check if there is an admintools.conf, if no, then local host does not belong to a Vertica cluster\n    atConfExists = checkAdmintoolsConfExists(atConfFilePath)\n    if not atConfExists:\n        print(\"The host does not belong to a Vertica cluster.\")\n        sys.exit(0)\n\n    # step 2: check if there's an UP database, if not then we need to first bring up the database\n    # we do not handle bringing up database in this script\n    activeDb = getActiveDB()\n    if activeDb == \"\":\n        print(\"There is no UP database to restart the node, try start the database first.\")\n        sys.exit(0)\n\n    # find local vertica node name\n    (succeeded, localVNodeName) = getLocalVerticaNodeName(activeDb, atConfFilePath)\n    if not succeeded:\n        print(\"Local Vertica node does not belong to a Vertica database.\")\n        sys.exit(0)\n\n    if args.reIpNode:\n        # re-ip the local Vertica node. When a Pod dies, it could take a short while for the Vertica node in that Pod\n        # to switch to status DOWN. Therefore, this step may fail due to that the Vertica node is not DOWN yet, but Init\n        # Container will retry this script, so no retry needed in this script.\n        (succeeded, msg) = reIpLocalNodeClusterUp(activeDb, atConfFilePath, localVNodeName)\n        if not succeeded:\n            print(f\"Error in updating IP address for local Vertica node: {msg}\")\n            sys.exit(1)\n        else:\n            print(\"IP address of local Vertica node has been updated successfully.\")\n            sys.exit(0)\n    elif args.restartNode:\n        (succeeded, msg) = restartLocalNode(activeDb, atConfFilePath, localVNodeName)\n        if not succeeded:\n            print(f\"Error in restarting local Vertica node: {msg}\")\n            sys.exit(1)\n        else:\n            print(\"Local Vertica node has been restarted successfully.\")\n            sys.exit(0)\n\nif __name__ == '__main__':\n    main()\n","sub_path":"docker-vertica/re-ip-node.py","file_name":"re-ip-node.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"108444826","text":"import cli.app\nimport logging\n\nfrom stockpredict.training import TrainingManager\nfrom stockpredict.network import StockNeuralNetwork\n\nlogger = logging.getLogger()\nlogging.basicConfig(level=logging.DEBUG)\n\n\n@cli.app.CommandLineApp\ndef train(app):\n    \"\"\"\n    Trains a network with a CSV file data\n    :param app: \n    :return: \n    \"\"\"\n    # # Set log level\n    # assert app.params.log_level in ['DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']\n    # logger.debug(\"DEBUG\")\n    # logger.info(\"INFO\")\n    # logger.warn(\"WARN\")\n    # logger.error(\"ERROR\")\n    # logger.critical(\"CRITICAL\")\n    # logging.basicConfig(level=getattr(logging, app.params.log_level))\n\n    # Choose Trainer\n    trainer = TrainingManager()\n\n    # Choose network for or create new one\n    logger.info(\"Setting up network.\")\n    net = StockNeuralNetwork(previous=int(app.params.previous) or 50, future=int(app.params.future) or 3)\n    trainer.set_network(net)\n\n    # Run training\n    logger.info(\"Starting training from {} file.\".format(app.params.input_csv))\n    trainer.train_from_csv(csv_path=app.params.input_csv, col_dict={\n        'DATE': 'Data',\n        'OPEN': 'Otwarcie',\n        'CLOSE': 'Zamkniecie',\n        'LOW': 'Najnizszy',\n        'HIGH': 'Najwyzszy',\n        'VOLUME': 'Wolumen'\n    })\n    # Data,Otwarcie,Najwyzszy,Najnizszy,Zamkniecie,Wolumen\n\n\ntrain.add_param(\"-c\", \"--input-csv\", help=\"Input csv file with stock data\", required=True, action=\"store\")\ntrain.add_param(\"-p\", \"--previous\", help=\"Number of previous sessions (analyzed)\", required=False, action=\"store\")\ntrain.add_param(\"-f\", \"--future\", help=\"Number of future sessions (predicted)\", required=False, action=\"store\")\ntrain.add_param(\"-l\", \"--log-level\", help=\"Log level (default is WARN)\", required=False, default='WARN', action=\"store\")\n\nif __name__ == \"__main__\":\n    train.run()\n","sub_path":"scli.py","file_name":"scli.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"120198748","text":"#!/usr/bin/env python3\nfrom middlewared.client import Client\n\nimport asyncio\nimport inspect\nimport os\nimport setproctitle\n\nfrom . import logger\nfrom .common.environ import environ_update\nfrom .utils import LoadPluginsMixin\nfrom .utils.io_thread_pool_executor import IoThreadPoolExecutor\nimport middlewared.utils.osc as osc\nfrom .utils.run_in_thread import RunInThreadMixin\n\nMIDDLEWARE = None\n\n\nclass FakeMiddleware(LoadPluginsMixin, RunInThreadMixin):\n    \"\"\"\n    Implements same API from real middleware\n    \"\"\"\n\n    def __init__(self, overlay_dirs):\n        super().__init__(overlay_dirs)\n        self.client = None\n        self.logger = logger.Logger('worker')\n        self.logger.getLogger()\n        self.logger.configure_logging('console')\n        self.loop = asyncio.get_event_loop()\n        self.run_in_thread_executor = IoThreadPoolExecutor('IoThread', 1)\n\n    async def _call(self, name, serviceobj, methodobj, params=None, app=None, pipes=None, io_thread=False, job=None):\n        try:\n            with Client('ws+unix:///var/run/middlewared-internal.sock', py_exceptions=True) as c:\n                self.client = c\n                job_options = getattr(methodobj, '_job', None)\n                if job and job_options:\n                    params = list(params) if params else []\n                    params.insert(0, FakeJob(job['id'], self.client))\n                if asyncio.iscoroutinefunction(methodobj):\n                    return await methodobj(*params)\n                else:\n                    return methodobj(*params)\n        finally:\n            self.client = None\n\n    async def _run(self, name, args, job=None):\n        service, method = name.rsplit('.', 1)\n        serviceobj = self.get_service(service)\n        methodobj = getattr(serviceobj, method)\n        return await self._call(name, serviceobj, methodobj, params=args, job=job)\n\n    async def call(self, method, *params, timeout=None, **kwargs):\n        \"\"\"\n        Calls a method using middleware client\n        \"\"\"\n        return self.client.call(method, *params, timeout=timeout, **kwargs)\n\n    def call_sync(self, method, *params, timeout=None, **kwargs):\n        \"\"\"\n        Calls a method using middleware client\n        \"\"\"\n        return self.client.call(method, *params, timeout=timeout, **kwargs)\n\n    async def call_hook(self, name, *args, **kwargs):\n        with Client(py_exceptions=True) as c:\n            return c.call('core.call_hook', name, args, kwargs)\n\n    def send_event(self, name, event_type, **kwargs):\n        with Client(py_exceptions=True) as c:\n            return c.call('core.event_send', name, event_type, kwargs)\n\n\nclass FakeJob(object):\n\n    def __init__(self, id, client):\n        self.id = id\n        self.client = client\n        self.progress = {\n            'percent': None,\n            'description': None,\n            'extra': None,\n        }\n\n    def set_progress(self, percent, description=None, extra=None):\n        self.progress['percent'] = percent\n        if description:\n            self.progress['description'] = description\n        if extra:\n            self.progress['extra'] = extra\n        self.client.call('core.job_update', self.id, {'progress': self.progress})\n\n\ndef main_worker(*call_args):\n    global MIDDLEWARE\n    loop = asyncio.get_event_loop()\n    coro = MIDDLEWARE._run(*call_args)\n    try:\n        res = loop.run_until_complete(coro)\n    except SystemExit:\n        raise RuntimeError('Worker call raised SystemExit exception')\n    # TODO: python cant pickle generator for obvious reasons, we should implement\n    # it using Pipe.\n    if inspect.isgenerator(res):\n        res = list(res)\n    return res\n\n\ndef receive_events():\n    c = Client('ws+unix:///var/run/middlewared-internal.sock', py_exceptions=True)\n    c.subscribe('core.environ', lambda *args, **kwargs: environ_update(kwargs['fields']))\n    c.subscribe('core.reconfigure_logging', lambda *args, **kwargs: logger.reconfigure_logging())\n\n    environ_update(c.call('core.environ'))\n\n\ndef worker_init(overlay_dirs, debug_level, log_handler):\n    global MIDDLEWARE\n    MIDDLEWARE = FakeMiddleware(overlay_dirs)\n    os.environ['MIDDLEWARED_LOADING'] = 'True'\n    MIDDLEWARE._load_plugins()\n    os.environ['MIDDLEWARED_LOADING'] = 'False'\n    setproctitle.setproctitle('middlewared (worker)')\n    osc.die_with_parent()\n    logger.setup_logging('worker', debug_level, log_handler)\n    receive_events()\n","sub_path":"src/middlewared/middlewared/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"620546493","text":"import os\nimport requests\nimport datetime\n\ndef do_ping():\n  os.system('fping -e -a -r 0 output.txt')\n\ndef load_hosts():\n  global hosts\n  hosts = set()\n  f = open('hosts.txt')\n  for line in f:\n    hosts.add(line.strip())\n\ndef parse_output():\n  global output\n  output = {}\n  global hosts\n  output = { k:None for k in hosts }\n  f = open('output.txt')\n  for line in f:\n    terms = line.strip().split()\n    host = terms[0]\n    time = terms[1][1:]\n    output[host] = time\n\ndef full():\n  time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n  do_ping()\n  parse_output()\n  global output\n  print(output)\n  for k in output:\n    v = output[k]\n    url = os.getenv('STORE_URL')\n    print('url:', url)\n    success = 'false' if v is None else 'true'\n    payload = '{\"origin\":\"raspi2a\", \"target\":\"%s\", \"success\":\"%s\", \"rtt\":\"%s\", \"time\":\"%s\"}' % (k, success, v, time)\n    # print('payload:', payload)\n    h = {'Content-type': 'application/json'}\n    r = requests.post(url, data=payload, headers=h)\n    print(r, r.text)\n\n\nload_hosts()\nfull()\nprint('done!')\n\n","sub_path":"p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"483102570","text":"import pynbody\nimport numpy as np\nimport sys\n\ntime = str(sys.argv[1])\nhalo = int(sys.argv[2])\n\nsim = pynbody.load('/nobackup/nnsanche/pioneer50h243GM7.1536gst1bwK1BH/pioneer50h243GM7.1536gst1bwK1BH.00'+time)\n#sim = pynbody.load('/nobackup/nnsanche/NO_BHs/pioneer50h243GM7.1536gst1bwK1/pioneer50h243GM7.1536gst1bwK1.00'+time)\n#sim = pynbody.load('/nobackup/nnsanche/NO_BHs/pioneer50h243GM4.1536gst1bwK1/pioneer50h243GM4.1536gst1bwK1.00'+time)\nh   = sim.halos()\nsat = h[halo]\nsat_iords = sat.g['iord']\nprint('Number of particles in the satellite',str(halo),' at timestep',time,':',len(sat_iords))\nprint('Saving in text file')\nnp.savetxt('GM7_h'+str(halo)+'iords_'+time+'.txt',sat_iords)\n","sub_path":"Sanchez2018_plots/profiles_plot7/exclude_iords.py","file_name":"exclude_iords.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"450948091","text":"\"\"\"spider_django URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n    https://docs.djangoproject.com/en/1.8/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. Add an import:  from blog import urls as blog_urls\n    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n    url(r'^admin/', include(admin.site.urls)),\n    url(r'^$', 'spider.views.index'),\n    url(r'^index/', 'spider.views.index', name='index'),\n    url(r'^handle1/', 'spider.views.handle1', name='handle1'),\n    url(r'^handle2/', 'spider.views.handle2', name='handle2'),\n    url(r'^handle3/', 'spider.views.handle3', name='handle3'),\n    url(r'^handle4/', 'spider.views.handle4', name='handle4'),\n    url(r'^handle5/', 'spider.views.handle5', name='handle5'),\n    url(r'^handle6/', 'spider.views.handle6', name='handle6'),\n    url(r'^handle7/', 'spider.views.handle7', name='handle7'),\n    url(r'^handle8/', 'spider.views.handle8', name='handle8'),\n    url(r'^handle9/', 'spider.views.handle9', name='handle9'),\n    url(r'^sentiment/', 'spider.views.sentiment', name='sentiment'),\n    url(r'^sentiment2/', 'spider.views.sentiment2', name='sentiment2'),\n    url(r'^deleteCommentFile/', 'spider.views.deleteCommentFile', name='deleteCommentFile'),\n    url(r'^deleteUserFile/', 'spider.views.deleteUserFile', name='deleteUserFile'),\n    url(r'^deleteGlobalVar/', 'spider.views.deleteGlobalVar', name='deleteGlobalVar'),\n    url(r'^test/', 'spider.views.test', name='test'),\n]\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"spider_django/spider_django/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"624786811","text":"import sys\r\nsys.path.insert(0, './resnet')\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\n#from resnet152 import get_resnet\r\n# from convert2 import load_image\r\nfrom generator_v3 import combine_embeddings, generator_me\r\nfrom discriminator import discriminator\r\nfrom rnn_module import rnn_module\r\nfrom get_data_v2 import load_data, get_training_batch\r\n\r\n\r\n######## CONSTANTS #######\r\nloss_vals = []\r\nacc_vals = []\r\nvocabulary_size = 15881\r\ninput_embedding_size = 200\r\nrnn_size = 512\r\nrnn_layer = 2\r\ndim_hidden = 2048\r\nepsilon = 1e-3\r\n##########################\r\n\r\nsess = tf.InteractiveSession()\r\n\r\nload_weights = False\r\nsave_ver = '2_nonoise'\r\nimport_weight_file = 'weights_g_v1.npy'\r\n\r\nif load_weights:\r\n   weights = np.load(import_weight_file).item()\r\n\r\n   var_dict = {\r\n      'cefcW1': tf.Variable(tf.truncated_normal([4096,4096])),\r\n      'cefcb1': tf.Variable(tf.constant(0.1, shape=[4096])),\r\n      'gfcW1': tf.Variable(weights['gfcW1']),\r\n      'gfcb1': tf.Variable(weights['gfcb1']),\r\n      'gfcW2': tf.Variable(weights['gfcW2']),\r\n      'gfcb2': tf.Variable(weights['gfcb2']),\r\n      'gfcW3': tf.Variable(weights['gfcW3']),\r\n      'gfcb3': tf.Variable(weights['gfcb3']),\r\n      'gfcW4': tf.Variable(weights['gfcW4']),\r\n      'gfcb4': tf.Variable(weights['gfcb4']),\r\n      'rnnqW': tf.Variable(weights['rnnqW'], name='embed_ques_W'),\r\n      'rnnsW': tf.Variable(weights['rnnsW'], name='embed_state_W'),\r\n      'rnnsb': tf.Variable(weights['rnnsb'], name='embed_state_b'),\r\n      'rnnoutbeta': tf.Variable(weights['rnnoutbeta']),\r\n      'rnnoutscale': tf.Variable(weights['rnnoutscale']),\r\n      'cnnoutbeta': tf.Variable(weights['cnnoutbeta']),\r\n      'cnnoutscale': tf.Variable(weights['cnnoutscale']),\r\n      'featbeta': tf.Variable(weights['featbeta']),\r\n      'featscale': tf.Variable(weights['featscale']),\r\n   }\r\n\r\n   #batch_no = weights['batch_no']\r\n   batch_no = 0\r\nelse:\r\n   weights = np.load(import_weight_file).item()\r\n\r\n   var_dict = {\r\n      'cemcnnfcW1': tf.Variable(weights['cemcnnfcW1']),\r\n      'cemcnnfcb1': tf.Variable(weights['cemcnnfcb1']),\r\n      'ceacnnfcW1': tf.Variable(weights['ceacnnfcW1']),\r\n      'ceacnnfcb1': tf.Variable(weights['ceacnnfcb1']),\r\n      'cemrnnfcW1': tf.Variable(weights['cemrnnfcW1']),\r\n      'cemrnnfcb1': tf.Variable(weights['cemrnnfcb1']),\r\n      'cearnnfcW1': tf.Variable(weights['cearnnfcW1']),\r\n      'cearnnfcb1': tf.Variable(weights['cearnnfcb1']),\r\n      'gfcW1': tf.Variable(tf.truncated_normal([4096, 4096])),\r\n      'gfcb1': tf.Variable(tf.constant(0.1, shape=[4096])),\r\n      'gfcW2': tf.Variable(tf.truncated_normal([4096, 4096*1])),\r\n      'gfcb2': tf.Variable(tf.constant(0.1, shape=[4096*1])),\r\n      'gfcW3': tf.Variable(tf.truncated_normal([4096*1, 3500])),\r\n      'gfcb3': tf.Variable(tf.constant(0.1, shape=[3500])),\r\n      'gfcW4': tf.Variable(tf.truncated_normal([3500, 3000])),\r\n      'gfcb4': tf.Variable(tf.constant(0.1, shape=[3000])),\r\n      'rnnqW': tf.Variable(weights['rnnqW'], name='embed_ques_W'),\r\n      'rnnsW': tf.Variable(weights['rnnsW'], name='embed_state_W'),\r\n      'rnnsb': tf.Variable(weights['rnnsb'], name='embed_state_b'),\r\n      'rnnoutbeta': tf.Variable(weights['rnnoutbeta']),\r\n      'rnnoutscale': tf.Variable(weights['rnnoutscale']),\r\n      'cnnoutbeta': tf.Variable(weights['cnnoutbeta']),\r\n      'cnnoutscale': tf.Variable(weights['cnnoutscale']),\r\n      'featbeta': tf.Variable(tf.zeros([4096])),\r\n      'featscale': tf.Variable(tf.ones([4096])),\r\n      'gbeta': tf.Variable(tf.zeros([3000])),\r\n      'gscale': tf.Variable(tf.ones([3000]))\r\n   }\r\n\r\n   batch_no = 0\r\n\r\n\r\n# placeholder for noise variable to be passed into generator\r\nnoise = tf.placeholder(tf.float32, (None, 4096))\r\n\r\n# answer placeholrder\r\nanswers_true = tf.placeholder(tf.float32, (None, 3000))\r\ncnn_out_true = tf.placeholder(tf.float32, (None, 2048))\r\n\r\n\r\n# load nlp portion\r\nwith tf.variable_scope(\"rnn_module1\"):\r\n   rnn_out_true, questions_true = rnn_module(var_dict)  \r\n\r\ncnn_mean, cnn_var = tf.nn.moments(cnn_out_true, [0])\r\ncnn_out_true_n = tf.nn.batch_normalization(cnn_out_true,cnn_mean,cnn_var,var_dict['cnnoutbeta'],\r\n   var_dict['cnnoutscale'],epsilon)\r\n\r\nrnn_mean, rnn_var = tf.nn.moments(rnn_out_true, [0])\r\nrnn_out_true_n = tf.nn.batch_normalization(rnn_out_true,rnn_mean,rnn_var,var_dict['rnnoutbeta'],\r\n   var_dict['rnnoutscale'],epsilon)\r\n\r\n# combine features from image and question\r\nfeatures_true = combine_embeddings(cnn_out_true_n, rnn_out_true_n, var_dict)\r\n\r\n#features = tf.add(features_true, noise)\r\nfeatures = features_true\r\n#feat_mean, feat_var = tf.nn.moments(features_true, [0])\r\n#features_true_n = tf.nn.batch_normalization(features_true,feat_mean,feat_var,var_dict['featbeta'],\r\n#   var_dict['featscale'],epsilon)\r\n\r\n# load generator network\r\ng_true = generator_me(features, var_dict)\r\n\r\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=g_true, labels=answers_true))\r\n\r\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\nwith tf.control_dependencies(update_ops):\r\n   train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)\r\n\r\n# init variables\r\nsess.run(tf.global_variables_initializer())\r\n\r\n\r\n\r\n\r\nprint('loading data...\\n\\n')\r\nqa_data = load_data()\r\nprint('done loading data...\\n\\n')\r\n#batch_no = 0\r\nbatch_size = 50\r\n#while batch_no*batch_size < len(qa_data['training']):\r\nwhile batch_no < 4000:\r\n   print('batch = ' + str(batch_no))\r\n   (questions_in_true, answer_in_true, im_feat_true) = get_training_batch(batch_no, batch_size, qa_data)\r\n\r\n   noise_in = np.random.normal(scale=0.3, size=[batch_size,4096])\r\n\r\n   train_step.run(feed_dict={\r\n      noise: noise_in, \r\n      answers_true: answer_in_true,\r\n      cnn_out_true: im_feat_true,\r\n      questions_true: questions_in_true,\r\n   })\r\n\r\n   loss_val = sess.run(loss, feed_dict={\r\n      noise: noise_in, \r\n      answers_true: answer_in_true,\r\n      cnn_out_true: im_feat_true,\r\n      questions_true: questions_in_true,\r\n   })\r\n\r\n   g_out = sess.run(g_true, feed_dict={     \r\n      noise: noise_in, \r\n      answers_true: answer_in_true,\r\n      cnn_out_true: im_feat_true,\r\n      questions_true: questions_in_true,\r\n   })\r\n\r\n   print('loss = ' + str(loss_val))\r\n   loss_vals.append(loss_val)\r\n   np.save('loss_vals_g_v' + save_ver, loss_vals)\r\n   #print(loss_val)\r\n\r\n   answers_out = np.argmax(g_out, axis=1)\r\n   answers_idx_true = np.argmax(answer_in_true, axis=1)\r\n   error = float(np.sum(answers_out == answers_idx_true)) / float(batch_size)\r\n   acc_vals.append(error)\r\n   np.save('acc_vals_g_v' + save_ver, acc_vals)\r\n   print('error = ' + str(error))\r\n\r\n   if batch_no % 25 == 0:\r\n      weights_save = {}\r\n      for key in var_dict:\r\n         weights_save[key] = var_dict[key].eval()\r\n      weights_save['batch_no'] = batch_no\r\n      np.save('weights_g_v' + save_ver, weights_save)\r\n\r\n   batch_no += 1\r\n\r\n  ","sub_path":"train_g_v2_nonoise.py","file_name":"train_g_v2_nonoise.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"324930501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 16 17:45:00 2019\n\n@author: TAPAN\n\"\"\"\n\n\n\nimport pandas as pd\nfrom selenium import webdriver\nfrom collections import OrderedDict\n\n\n\n\nsource = \"https://bidplus.gem.gov.in/bidlists\"\n\n\n#driver = webdriver.Firefox(executable_path=r'C:/Users/hp/Downloads/geckodriver')\ndriver = webdriver.Chrome(r\"D:\\Forsk\\Day 08\\Work\\chromedriver.exe\")\n\ndriver.get(source)    # Opening the submission url\n\n\n\n\nright_table=driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[1]')\n\n\n#//*[@id=\"pagi_content\"]/div[1]/div[1]/p[1]/a\n#//*[@id=\"pagi_content\"]/div[2]/div[1]/p[1]/a\n\n#//*[@id=\"pagi_content\"]/div[1]/div[2]/p[1]/span\n#//*[@id=\"pagi_content\"]/div[2]/div[2]/p[1]/span\n\n\n#//*[@id=\"pagi_content\"]/div[1]/div[2]/p[2]/span\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[3]/p[2]\n#\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[4]/p[1]/span\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[4]/p[2]/span\n\n\nbid_id=[]\nitem=[]\nquantity=[]\ndept_name_address=[]\nstart_date=[]\nend_date=[]\nstart_time=[]\nend_time=[]\n\n\nfor val in range(1,11):\n    bid_id.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[1]/p[1]/a'.format(val)).text)\n    item.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[2]/p[1]/span'.format(val)).text)\n    quantity.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[2]/p[2]/span'.format(val)).text)\n    dept_name_address.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[3]/p[2]'.format(val)).text)\n    start_date.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[4]/p[1]/span'.format(val)).text)\n    end_date.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[4]/p[2]/span'.format(val)).text)\n    \n\nstart_date_list=[i[:i.find(' ')] for i in start_date]\nstart_time=[i[i.find(' ') + 1:] for i in start_date]\n\nend_date_list=[i[:i.find(' ')] for i in end_date]\nend_time=[i[i.find(' ') + 1:] for i in end_date]\n\n\n    \ncol_name = [\"Bid No.\",\"Item\",\"Quantity\",\"Dept name & address\",\"Start Date\",\"End Date\",\"Start Time\",\"End Time\"]\ncol_data = OrderedDict(zip(col_name,[bid_id,item,quantity,dept_name_address,start_date_list,end_date_list,start_time,end_time]))\n\n\n\nprint(bid_id)\nprint(item)\nprint(quantity)\nprint(start_time)\nprint (end_time)\n\n\n\n\nimport mysql.connector \n# connect to  MySQL server along with Database name\n\nconn = mysql.connector.connect(user='CUQQMCS80b', password='TRLKYhvlac',\n                              host='remotemysql.com', database = 'CUQQMCS80b')\n#, database = 'forsk_test'\n\n# creating cursor\nc = conn.cursor()\n\n# STEP 0\n#c.execute(\"DROP DATABASE employee;\")\n\n# STEP 1\n#c.execute(\"CREATE DATABASE GeM;\")\n\n# STEP 2\n#c.execute(\"DROP Table dat;\")\n\n\n# STEP 3\nc.execute (\"\"\"CREATE TABLE dat(\n          Bid_id TEXT,\n          item  TEXT,\n          Quantity INTEGER,\n          Dept_name_address TEXT,\n          Start_Date TEXT,\n          End_Date TEXT,\n          Start_Time TEXT,\n          End_Time TEXT\n          )\"\"\")\n\n\nfor i in range(10):\n    c.execute(\"INSERT INTO dat VALUES ('{}','{}',{},'{}','{}','{}','{}','{}')\".format (bid_id[i],item[i],quantity[i],dept_name_address[i],start_date[i],end_date[i],start_time[i],end_time[i]))\n\n\n\n\n\n\n# c.execute(\"INSERT INTO employee VALUES ({},'{}', '{}', {})\".format(idd, first,last,pay))\n\n\nc.execute(\"SELECT * FROM dat\")\n\nconn.commit()\nconn.close()\n\n# STEP 5\n# returns one or otherwise None as a tuple\n#print ( c.fetchone()) \n#\n## returns one or otherwise None as a tuple\n#print ( c.fetchmany(2)) \n#\n## returns a list of tuples\n#print ( c.fetchall() )\n#\n#\n## Since now the cursor has read all the rows and we are at End\n## So again fetching the records from the database\n#c.execute(\"SELECT * FROM employees\")\n#\n#\n## STEP 6\n#df = DataFrame(c.fetchall())  # putting the result into Dataframe\n#df.columns = [\"id\",\"first\",\"last\",\"pay\"]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Day 09/bid_plus_db.py","file_name":"bid_plus_db.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
    +{"seq_id":"296769950","text":"# -*- coding: utf-8 -*-\n\nfrom plugin import Plugin\n\nfrom flask import jsonify, abort\n\nclass LangsPlugin(Plugin):\n    name = \"langs\"\n\n    def __init__(self, *args, **kwargs):\n        super(Plugin, self).__init__(*args, **kwargs)\n\n    def on_get_all(self, request):\n        langs = self.system['mongo'].db.langs\n        output = []\n        for lang in langs.find():\n            output.append({'id' : lang['id']})\n        return jsonify(output), 200, {\"X-Total-Count\": str(len(output)), \n                                                                     \"Content-Type\": \"application/json; charset=utf-8\",\n                                                                     \"Access-Control-Expose-Headers\": \"X-Total-Count\"}\n\n    def on_get(self, id, request):\n        langs = self.system['mongo'].db.langs\n        lang = langs.find_one({'id' : id})\n        if lang:\n            output = {'id' : lang['id']}\n        else:\n            abort(404)\n        return jsonify(output)\n\n    def on_create(self, request):\n        langs = self.system['mongo'].db.langs\n        id = request.json['id']\n        lang_id = langs.insert({'id': id})\n        new_lang = langs.find_one({'_id': lang_id })\n        output = {'id' : new_lang['id']}\n        return jsonify(output)\n\n    def on_update(self, id, request):\n        output = {'id' : id}\n        return jsonify(output)\n\n    def on_delete(self, id, request):\n        langs = self.system['mongo'].db.langs\n        lang = langs.delete_one({'id' : id})\n        if lang:\n            output = {'id' : id}\n        else:\n            abort(404)\n        return jsonify(output)\n","sub_path":"docker-images/bot/plugins/langs.py","file_name":"langs.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"514433389","text":"# \n\n# Minimal CGI script for Online Python Tutor (v3).\n\nimport cgi\nimport json\nimport pg_logger\nimport sys\n\n\ndef cgi_finalizer(input_code, output_trace):\n  \"\"\"Write JSON output for js/pytutor.js as a CGI result.\"\"\"\n  ret = dict(code=input_code, trace=output_trace)\n  json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr\n  print(\"Content-type: text/plain; charset=iso-8859-1\\n\")\n  print(json_output)\n\n\nif len(sys.argv) > 1:\n  user_script = open(sys.argv[1]).read()\nelse:\n  form = cgi.FieldStorage()\n  user_script = form['user_script'].value\n  # convert from string to a Python boolean ...\n  cumulative_mode = (form['cumulative_mode'].value == 'true')\n\npg_logger.exec_script_str(user_script, cumulative_mode, cgi_finalizer)\n","sub_path":"PyTutorGAE/web_exec.py","file_name":"web_exec.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"121816204","text":"from typing import (\n    Iterable,\n    List,\n    Literal,\n    Optional,\n    Set,\n    Union,\n    TypeVar,\n    Type,\n    get_args,\n)\n\n\nclass Fmi2CoSim:\n    def __init__(self) -> None:\n        pass\n\n\nT = TypeVar(\"T\", float, int, bool, str)\n_variability_all = Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"]\n_causality_all = Literal[\"exact\", \"approx\", \"calculated\"]\n\n\nclass Fmi2Variable:\n    def __init__(\n        self,\n        name: str,\n        type: Type[T],\n        causality: Literal[\n            \"parameter\",\n            \"calculated_parameter\",\n            \"input\",\n            \"output\",\n            \"local\",\n            \"independent\",\n        ],\n        variability: _variability_all,\n        initial: _causality_all,\n        description: str = None,\n        declared_type: str = None,\n        quantity: str = None,\n        unit: str = None,\n        display_unit: str = None,\n        relative_quantity: bool = None,\n        min: T = None,\n        max: T = None,\n        nominal: T = None,\n        unbounded: bool = None,\n        start: T = None,\n        derivative: int = None,\n        reinit: bool = None,\n    ) -> None:\n\n        if type not in get_args(T):\n            raise ValueError(\n                f\"Invalid data type for variable: {name}, choices are: '{get_args(T)}', got: {type}\"\n            )\n        # TODO add validation logic here\n\n        self.name = name\n        self.type = type\n        self.description = description\n        self.causality = causality\n        self.variability = variability\n        self.initial = initial\n        self.declared_type = declared_type\n        self.quantity = quantity\n        self.unit = unit\n        self.display_unit = display_unit\n        self.relative_quantity = relative_quantity\n        self.min = min\n        self.max = max\n        self.nominal = nominal\n        self.unbounded = unbounded\n        self.start = start\n        self.derivative = derivative\n        self.reinit = reinit\n\n\nclass Fmi2FMU:\n    def __init__(\n        self,\n        model_name: str,\n        fmi2_version: str = None,\n        guid: str = None,\n        description: str = None,\n        author: str = None,\n        version: str = None,\n        copyright: str = None,\n        license: str = None,\n        generation_tool: str = None,\n        generation_data_and_time: str = None,\n        variable_naming_convention: Literal[\"flat\", \"structured\"] = None,\n        number_of_event_indicators=None,\n    ) -> None:\n        self._variables: List[Fmi2Variable] = []\n\n    def define_model_exchange(self):\n        raise NotImplementedError(\"currently only co-sim is supported\")\n\n    def define_cosimulation(\n        self,\n        model_identifier: str,\n        needs_execution_tool: bool = None,\n        can_handle_variable_communication_step_size: bool = None,\n        can_interpolate_inputs: bool = None,\n        max_output_derivative_order: int = None,\n        can_run_asynchronuously: bool = None,\n        can_be_instantiated_only_once_per_process: bool = None,\n        can_not_use_memory_management_functions: bool = None,\n        can_get_and_set_fmu_state: bool = None,\n        can_serialize_fmu_state: bool = None,\n        provides_directional_derivative: bool = None,\n    ):\n        pass\n\n    def define_log_categories(self, categories: Iterable[str]):\n        pass\n\n    def define_unit_definitions(self):\n        pass\n\n    def define_default_experiment(self):\n        pass\n\n    def define_vendor_annotations(self):\n        pass\n\n    def _add_variable(\n        self,\n        name: str,\n        type: Type[T],\n        causality: Literal[\n            \"parameter\",\n            \"calculated_parameter\",\n            \"input\",\n            \"output\",\n            \"local\",\n            \"independent\",\n        ],\n        variability: Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"],\n        initial: Literal[\"exact\", \"approx\", \"calculated\"],\n        declared_type=None,\n        quantity: str = None,\n        unit: str = None,\n        display_unit: str = None,\n        relative_quantity: bool = None,\n        min: T = None,\n        max: T = None,\n        nominal: T = None,\n        unbounded: bool = None,\n        start: T = None,\n        derivative: int = None,\n        reinit: bool = None,\n        description: str = None,\n    ):\n        self._variables.append(\n            Fmi2Variable(\n                name=name,\n                type=type,\n                causality=causality,\n                variability=variability,\n                initial=initial,\n                declared_type=declared_type,\n                quantity=quantity,\n                unit=unit,\n                display_unit=display_unit,\n                relative_quantity=relative_quantity,\n                min=min,\n                max=max,\n                nominal=nominal,\n                unbounded=unbounded,\n                start=start,\n                derivative=derivative,\n                reinit=reinit,\n                description=description,\n            )\n        )\n\n    def add_parameter(\n        self,\n        name: str,\n        type: Type[T],\n        variability: Literal[\"fixed\", \"tunable\"],\n        start: T,\n        description: str = None,\n    ):\n        self._add_variable(\n            name=name,\n            type=type,\n            variability=variability,\n            causality=\"parameter\",\n            initial=\"exact\",\n            start=start,\n            description=description,\n        )\n\n    def add_calculated_parameter(\n        self,\n        name: str,\n        type: Type[T],\n        variability: Literal[\"fixed\", \"tunable\"],\n        initial=Literal[\"approx\", \"calculated\"],\n        description: str = None,\n    ):\n        pass\n\n    def add_input(\n        self,\n        name: str,\n        type: Type[T],\n        variability: Literal[\"discrete\", \"continuous\"],\n        start: T = None,\n        min: T = None,\n        max: T = None,\n        description: str = None,\n    ):\n        pass\n\n    def add_output(\n        self,\n        name: str,\n        type: Type[T],\n        variability: Literal[\"constant\", \"discrete\", \"continuous\"],\n        initial: Literal[\"exact\", \"calculated\"],\n        start: T = None,\n        description: str = None,\n    ):\n        pass\n\n    def add_local_variable(\n        self,\n        name: str,\n        type: Type[T],\n        variability: Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"],\n        initial: Literal[\"exact\", \"approx\", \"calculated\"],\n        description: str = None,\n    ):\n        pass\n\n    def add_independent_variable(\n        self, name: str, description: str = None,\n    ):\n        pass\n\n\nclass Fmi3FMU:\n    pass\n\n\nif __name__ == \"__main__\":\n\n    cosim = Fmi2CoSim()\n\n    adder = Fmi2FMU(\"adder\")\n    adder.add_input(\"real_a\", type(float), \"continuous\", start=0.0)\n    adder.add_input(\"real_b\", type(float), \"continuous\", start=0.0)\n    adder.add_output(\n        \"real_c\", type(float), variability=\"continuous\", initial=\"calculated\",\n    )\n\n    adder.add_input(\"integer_c\", int, \"discrete\")\n    adder.add_input(\"integer_b\", int, \"discrete\")\n    adder.add_output(\n        \"integer_c\", int, \"discrete\", initial=\"calculated\",\n    )\n\n    adder.add_input(\"boolean_c\", bool, \"discrete\")\n    adder.add_input(\"boolean_b\", bool, \"discrete\")\n    adder.add_output(\n        \"boolean_c\", bool, \"discrete\", initial=\"calculated\",\n    )\n\n    adder.add_input(\"integer_c\", str, \"discrete\")\n    adder.add_input(\"integer_b\", str, \"discrete\")\n    adder.add_output(\n        \"integer_c\", str, \"discrete\", initial=\"calculated\",\n    )\n\n    # adder.export(outdir=\"...\", language=\"python\")\n\n","sub_path":"tool/unifmu/authoring.py","file_name":"authoring.py","file_ext":"py","file_size_in_byte":7564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"188193834","text":"import re\nfrom copy import deepcopy\n\n\ndef _has_mod(mod):\n    return lambda n: any(map(\n        lambda m: m.kind == mod.kind(), n.modifiers\n    )) if n is not None else False\n\n\nclass CBSelect:\n    def __init__(self, *selects, asname=None):\n        self.selects = list(selects)\n        self.as_name = asname\n        self.label = None\n\n    def __mod__(self, other):\n        if isinstance(other, CBSelect):\n            self.selects.extend(other.selects)\n            self.label = other.label\n            self.as_name = (\n                other.as_name if other.as_name is not None else self.as_name\n            )\n        else:\n            self.label = other\n        return self\n\n    def __rmod__(self, other):\n        if isinstance(other, CBSelect):\n            self.selects.extend(other.selects)\n            self.label = other.label\n            self.as_name = (\n                other.as_name if other.as_name is not None else self.as_name\n            )\n        else:\n            self.label = other\n        return self\n\n\nclass CB:\n    _depth = 0\n\n    def __init__(self, init=None):\n        self.kind = 'Python.Code.Root'\n\n        self.label = None\n        self.selects = []\n        self.select_as = None\n        self.type = init\n        self.children = []\n        self.constraints = []\n        self.modifiers = []\n\n        self.last = self\n        self.parent = None\n\n        self.merge_key_l = None\n        self.merge_key_r = None\n\n        self.id = 0\n\n    def idify(self):\n        idx = 0\n        worklist = [ self ]\n        while len(worklist) > 0:\n            idx += 1\n            current = worklist.pop()\n            current.id = idx\n            for child in current.children:\n                worklist.append(child)\n\n    def part_of_merge(self):\n        return (\n            self.merge_key_l is not None \n            or self.merge_key_r is not None\n        )\n\n    def remove_mod(self, mod):\n        self.modifiers = [\n            x for x in self.modifiers if x.kind != mod.kind()\n        ]\n        return self\n\n    def without_mods(self):\n        self.modifiers = []\n        return self\n\n    def with_mods(self, *args):\n        self.modifiers = list(args)\n        return self\n\n    def with_mod(self, mod):\n        self.modifiers.append(mod)\n        return self\n\n    def with_constraints(self, *args):\n        self.constraints = list(args)\n        return self\n\n    def add_constraints(self, *args):\n        self.constraints.extend(list(args))\n        return self\n\n    def with_constraint(self, constraint):\n        self.constraints.append(constraint)\n        return self\n\n    def is_merge(self, lkey, rkey):\n        assert len(self.children) == 1\n        self.merge_key_l = lkey\n        self.children[0].merge_key_r = rkey\n        return self\n\n    def with_labels_from(self, other):\n        self.label = other.label\n        return self\n\n    def without_labels(self):\n        self.label = None\n        return self\n\n    #############################################################################\n    # TREE-PATH-EXPR CONVERSION\n    #############################################################################\n    \n    def to_path(self):\n        if self.type.startswith('$'):\n            return '' # Virtual nodes have no contribution (at this level)\n\n        # Handle \"normal\" nodes\n        as_path = self.type if '$' not in self.type else ''\n        for con in sorted(self.constraints, key=lambda c: c.precedence):\n            as_path = con.to_path(as_path)\n        return as_path\n    \n    #############################################################################\n    # QUERY CONSTRUCTION (merge/bubbleup/nest)\n    #############################################################################\n\n    def bubbleup(self):\n        self.last = self.last.parent\n        return self\n\n    def nest(self, other):\n        other.parent = self.last\n        self.last.children.append(other)\n        self.last = other\n        return self\n\n    def merge(self, other):\n        self.parent = other.parent\n        self.last.type = other.type\n        self.last.label = other.label\n        self.last.children += other.children\n        self.last.constraints += other.constraints\n        self.last.modifiers += other.modifiers\n        self.last.selects = other.selects\n        self.last.select_as = other.select_as\n        return self\n\n    def insert_and(self):\n        new_root = deepcopy(self)\n        old_children = new_root.children\n        new_root.children = []\n        new_root.last = new_root\n\n        the_and = CB('$and')\n        for child in old_children:\n            the_and.nest(child).bubbleup()\n        \n        return new_root.nest(the_and)\n\n    #############################################################################\n    # TREE WALK/EDIT\n    #############################################################################\n\n    def has_mod(self, mod):\n        if _has_mod(mod)(self):\n            return True\n\n        return False\n\n    def get_con(self, con):\n        for c in self.constraints:\n            if c.kind == con.kind():\n                return c\n\n        return None\n\n    def rewrite(self, selector, rewriter):\n        if selector(self):\n            return rewriter(self)\n\n        new_children = []\n        for child in self.children:\n            new_children.append(\n                child.rewrite(selector, rewriter)\n            )\n        self.children = new_children\n        return self\n    \n    def rewrite_mods(self, mods):\n        changed = self\n        for mod in mods:\n            changed = changed.rewrite(_has_mod(mod), mod.rewrite)\n        return changed\n\n    def rewrite_all_mods(self):\n        for mod in CB.ALL_MODS:\n            while self.has_mod(mod):\n                self = self.rewrite_mods([mod])\n        return self\n\n    #############################################################################\n    # LABEL ASSIGN (via %)\n    # - usage CB(..) % 'label'\n    #############################################################################\n\n    def __mod__(self, other):\n        if isinstance(other, CBSelect):\n            self.selects = other.selects\n            self.label = other.label\n            self.select_as = other.as_name\n        else:\n            self.label = other\n        return self\n\n    def __rmod__(self, other):\n        if isinstance(other, CBSelect):\n            self.selects = other.selects\n            self.label = other.label\n            self.select_as = other.as_name\n        else:\n            self.label = other\n        return self\n\n    #############################################################################\n    # DISPLAY (str/debug methods)\n    #############################################################################\n\n    def __str__(self):\n        indent = ' ' * CB._depth\n        res = '{}(\\n'.format(indent)\n\n        # Render our props \n        if self.merge_key_l:\n            res += '{}  MERGE (L) key=`{}`\\n'.format(indent, self.merge_key_l)\n        if self.merge_key_r:\n            res += '{}  MERGE (R) key=`{}`\\n'.format(indent, self.merge_key_r)\n        if self.type is not None:\n            if hasattr(self, 'id'):\n                res += '{}  type ({})=`{}`\\n'.format(indent, self.id, self.type)\n            else:\n                res += '{}  type=`{}`\\n'.format(indent, self.type)\n        if len(self.modifiers) > 0:\n            res += '{}  mods={{{}}}\\n'.format(indent,\n                                              ';'.join(map(str, self.modifiers)))\n        if len(self.constraints) > 0:\n            res += '{}  cons={{{}}}\\n'.format(indent,\n                                              ';'.join(map(str, self.constraints)))\n        if self.label is not None:\n            res += '{}  label=`{}`\\n'.format(indent, self.label)\n        \n        # Render children (indent/dedent)\n        CB._depth += 2\n        res += '{}  children=[\\n'.format(indent)\n        res += (','.join(map(str, self.children)) +\n                '\\n') if len(self.children) > 0 else ''\n        CB._depth -= 2\n        \n        res += '{}  ]\\n'.format(indent)\n        res += '{})'.format(indent)\n\n        # Fixup (make prettier)\n        res = re.sub(r'\\)\\n *\\]', ')]', res)\n        res = re.sub(r'\\[\\n *\\(', '[(', res)\n        res = re.sub(r'\\[\\n *\\n? *\\]', '[ ]', res)\n        res = re.sub(r'\\), +\\(', '), (', res)\n        return res\n\n    #############################################################################\n","sub_path":"applications/jupyter-extension/nteract_on_jupyter/notebooks/codebookold/python/querybuilder.py","file_name":"querybuilder.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"446182879","text":"class STModule:\n    def __init__(self):\n        self.name = 'ipy/persistence'\n        self.language = 'ipy'\n        self.description = 'Set a new value in HKCU\\...\\Run registry key to get a session each time the user connects (works only with msbuild)'\n        self.author = '@maximemf'\n        self.options = {\n            'Path': {\n                'Description'   :   'Path to the stager file',\n                'Required'      :   True,\n                'Value'         :   \"C:\\\\\\\\WINDOWS\\\\\\\\Temp\\\\\\\\msbuild.xml\"\n            }\n        }\n\n    def payload(self):\n        with open('modules/ipy/src/persistence.py', 'r') as module_src:\n            src = module_src.read()\n            src = src.replace('PATH', self.options['Path']['Value'])\n            return src\n","sub_path":"Server/modules/ipy/persistence.py","file_name":"persistence.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"264546222","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom ast import literal_eval\nwith open('config.py', encoding='utf-8') as f:\n    text = f.read()\n    exec(text)\n\n\ndef get_all_config_options(text):\n    result = []\n    N = len(text)\n    for i in range(N):\n        current = text[i]\n        if current == '\\n':\n            if i + 1 < N:\n                next_character = text[i + 1]\n                if next_character.isalpha():\n                    inds = text[i + 1:].index('=') - 1\n                    current_config_options = text[i + 1:i + 1 + inds]\n                    result.append(current_config_options)\n    return result\n\n\ndef change(var, new, is_str=True):\n    text = open('config.py', encoding='utf-8').read()\n    text_ls = list(text)\n    var_len = len(var) + 1\n    var_ind = text.index('\\n' + var + ' ') + var_len\n    next_line = text[var_ind:].index('\\n')\n    if is_str:\n        text_ls[var_ind:var_ind + next_line] = f\" = '{new}'\"\n    else:\n        text_ls[var_ind:var_ind + next_line] = f\" = {new}\"\n    with open('config.py', 'w', encoding='utf-8') as f:\n        f.write(''.join(text_ls))\n\n\nclass Root(Tk):\n    def __init__(self):\n        super(Root, self).__init__()\n        self.title(\"Settings\")\n        self.minsize(800, 600)\n        self.wm_iconbitmap('piano.ico')\n        self.config_options_bar = Scrollbar(self)\n        self.config_options_bar.place(x=235, y=120, height=170, anchor=CENTER)\n        self.choose_config_options = Listbox(\n            self, yscrollcommand=self.config_options_bar.set)\n        self.choose_config_options.bind('<>',\n                                        self.show_current_config_options)\n        all_config_options = get_all_config_options(text)\n        self.options_num = len(all_config_options)\n        self.all_config_options = all_config_options\n        for k in all_config_options:\n            self.choose_config_options.insert(END, k)\n        self.choose_config_options.place(x=0, y=30, width=220)\n        self.config_options_bar.config(\n            command=self.choose_config_options.yview)\n        self.config_name = ttk.Label(self, text='')\n        self.config_name.place(x=300, y=20)\n        self.config_contents = Text(self,\n                                    undo=True,\n                                    autoseparators=True,\n                                    maxundo=-1)\n        self.config_contents.bind('', self.config_change)\n        self.config_contents.place(x=350, y=50, width=400, height=400)\n        self.choose_filename_button = ttk.Button(self,\n                                                 text='choose filename',\n                                                 command=self.choose_filename)\n        self.choose_directory_button = ttk.Button(\n            self, text='choose directory', command=self.choose_directory)\n        self.choose_filename_button.place(x=0, y=250)\n        self.choose_directory_button.place(x=0, y=320)\n        self.save = ttk.Button(self, text=\"save\", command=self.save_current)\n        self.save.place(x=0, y=400)\n        self.saved_text = ttk.Label(text='saved')\n        self.search_text = ttk.Label(self, text='search for config options')\n        self.search_text.place(x=0, y=450)\n        self.search_contents = StringVar()\n        self.search_contents.trace_add('write', self.search)\n        self.search_entry = Entry(self, textvariable=self.search_contents)\n        self.search_entry.place(x=0, y=480)\n        self.search_inds = 0\n        self.up_button = ttk.Button(\n            self,\n            text='up',\n            command=lambda: self.change_search_inds(-1),\n            width=8)\n        self.down_button = ttk.Button(\n            self,\n            text='down',\n            command=lambda: self.change_search_inds(1),\n            width=8)\n        self.up_button.place(x=170, y=480)\n        self.down_button.place(x=250, y=480)\n        self.search_inds_list = []\n        self.value_dict = {i: str(eval(i)) for i in self.all_config_options}\n\n    def config_change(self, e):\n        try:\n            current = self.config_contents.get('1.0', 'end-1c')\n            current = literal_eval(current)\n            if type(current) == str:\n                current = f\"'{current}'\"\n            current_config = self.choose_config_options.get(ANCHOR)\n            exec(f'{current_config} = {current}', globals())\n        except:\n            pass\n\n    def change_search_inds(self, num):\n        self.search_inds += num\n        if self.search_inds < 0:\n            self.search_inds = 0\n        if self.search_inds_list:\n            search_num = len(self.search_inds_list)\n            if self.search_inds >= search_num:\n                self.search_inds = search_num - 1\n            first = self.search_inds_list[self.search_inds]\n            self.choose_config_options.selection_clear(0, END)\n            self.choose_config_options.selection_set(first)\n            self.choose_config_options.selection_anchor(first)\n            self.choose_config_options.see(first)\n            self.show_current_config_options(0)\n\n    def search(self, *args):\n        current = self.search_contents.get()\n        all_config_options = self.all_config_options\n        self.search_inds_list = [\n            i for i in range(self.options_num)\n            if current in all_config_options[i]\n        ]\n        if self.search_inds_list:\n            self.search_inds = 0\n            first = self.search_inds_list[self.search_inds]\n            self.choose_config_options.selection_clear(0, END)\n            self.choose_config_options.selection_set(first)\n            self.choose_config_options.selection_anchor(first)\n            self.choose_config_options.see(first)\n            self.show_current_config_options(0)\n        else:\n            self.choose_config_options.selection_clear(0, END)\n\n    def show_current_config_options(self, e):\n        current_config = self.choose_config_options.get(ANCHOR)\n        self.config_name.configure(text=current_config)\n        self.config_contents.delete('1.0', END)\n        current_config_value = eval(current_config)\n        if type(current_config_value) == str:\n            current_config_value = f\"'{current_config_value}'\"\n        else:\n            current_config_value = str(current_config_value)\n        self.config_contents.insert(END, current_config_value)\n\n    def choose_filename(self):\n        filename = filedialog.askopenfilename(initialdir='.',\n                                              title=\"choose filename\",\n                                              filetype=((\"all files\",\n                                                         \"*.*\"), ))\n        self.config_contents.delete('1.0', END)\n        self.config_contents.insert(END, f\"'{filename}'\")\n        self.config_change(0)\n\n    def choose_directory(self):\n        directory = filedialog.askdirectory(\n            initialdir='.',\n            title=\"choose directory\",\n        )\n        self.config_contents.delete('1.0', END)\n        self.config_contents.insert(END, f\"'{directory}'\")\n        self.config_change(0)\n\n    def show_saved(self):\n        self.saved_text.place(x=140, y=400)\n        self.after(1000, self.saved_text.place_forget)\n\n    def save_current(self):\n        changed = False\n        for each in self.all_config_options:\n            current_value = eval(each)\n            current_value_str = str(current_value)\n            before_value = self.value_dict[each]\n            if current_value_str != before_value:\n                change(each, current_value_str, type(current_value) == str)\n                self.value_dict[each] = current_value_str\n                changed = True\n        if changed:\n            self.show_saved()\n\n\nroot = Root()\nroot.mainloop()\n","sub_path":"change_settings.pyw","file_name":"change_settings.pyw","file_ext":"pyw","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"206560982","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nclass CPU:\n    \"\"\"Main CPU class.\"\"\"\n\n    def __init__(self):\n        \"\"\"Construct a new CPU.\"\"\"\n        self.ram = [0] * 256  # memory with 256 bytes\n        self.reg = [0] * 8    # 8 general-purpose registers\n        self.pc = 0           # program counter, pointing at current command\n        self.sp = self.reg[7] # stack pointer, reg[7] reserved position\n        self.fl_l = False     # 00000LGE\n        self.fl_g = False\n        self.fl_e = False\n\n    def load(self):\n        \"\"\"Load a program into memory.\"\"\"\n\n        address = 0\n\n        try:\n            with open(sys.argv[1]) as f:\n                for line in f:\n                    comment_split = line.split(\"#\") # splits each line or comment into a list of strings\n                    num = comment_split[0].strip() # removes spaces, ignores second index\n                    if num == '': # ignore blank lines\n                        continue\n                    val = int(num, 2) # binary\n                    self.ram[address] = val\n                    address += 1\n        except FileNotFoundError:\n            print(f\"{sys.argv[0]}: {sys.argv[1]} not found\")\n            sys.exit(2)\n\n    def alu(self, op, reg_a, reg_b):\n        \"\"\"ALU operations.\"\"\"\n\n        if op == \"ADD\":\n            self.reg[reg_a] += self.reg[reg_b]\n        elif op == \"SUB\":\n            self.reg[reg_a] -= self.reg[reg_b]\n        elif op == \"MUL\":\n            self.reg[reg_a] *= self.reg[reg_b]\n        elif op == \"DIV\":\n            self.reg[reg_a] /= self.reg[reg_b]\n        elif op == \"CMP\":\n            if self.reg[reg_a] == self.reg[reg_b]:\n                # set equal flag E to 1, else 0\n                self.fl_e = True\n            if self.reg[reg_a] < self.reg[reg_b]:\n                # set lass flag L to 1, else 0\n                self.fl_l = True\n            if self.reg[reg_a] > self.reg[reg_b]:\n                # set greater flag G to 1, else 0\n                self.fl_g = True\n        else:\n            raise Exception(\"Unsupported ALU operation\")\n\n    def trace(self):\n        \"\"\"\n        Handy function to print out the CPU state. You might want to call this\n        from run() if you need help debugging.\n        \"\"\"\n\n        print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n            self.pc,\n            #self.fl,\n            #self.ie,\n            self.ram_read(self.pc),\n            self.ram_read(self.pc + 1),\n            self.ram_read(self.pc + 2)\n        ), end='')\n\n        for i in range(8):\n            print(\" %02X\" % self.reg[i], end='')\n\n        print()\n\n    def ram_read(self, address):\n        '''Should accept an address and return the stored value in the ram'''\n        return self.ram[address]\n    \n    def ram_write(self, address, value):\n        '''Should accept an address and value and write the value to that place in ram'''\n        self.ram[address] = value\n\n    def run(self):\n        \"\"\"Run the CPU.\"\"\"\n        LDI = 0b10000010\n        PRN = 0b01000111\n        MUL = 0b10100010\n        ADD = 0b10100000\n        PUSH = 0b01000101\n        POP = 0b01000110\n        HLT = 0b00000001\n        CAL = 0b01010000\n        RET = 0b00010001\n        CMP = 0b10100111\n        JMP = 0b01010100\n        JEQ = 0b01010101\n        JNE = 0b01010110\n\n        running = True\n\n        while running:\n            # instruction = self.ram[self.pc]\n            instruction = self.ram_read(self.pc)\n            reg_a = self.ram_read(self.pc+1)\n            reg_b = self.ram_read(self.pc+2)\n\n            if instruction == LDI: # save the value to reg\n                # +1 is an register address, +2 is a value\n                self.reg[reg_a] = reg_b\n                self.pc += 3\n            elif instruction == HLT: # HLT - halt\n                running = False\n                self.pc += 1\n            elif instruction == PRN: # print\n                # get value from +1 (address at register)\n                value = self.reg[reg_a]\n                print(value)\n                self.pc += 2\n            elif instruction == MUL:\n                self.alu('MUL', reg_a, reg_b)\n                self.pc += 3\n            elif instruction == ADD:\n                self.alu('ADD', reg_a, reg_b)\n                self.pc += 3\n            elif instruction == PUSH: # push value given to register\n                # get value from register address\n                value = self.reg[reg_a]\n                # decrement stack pointer\n                self.sp -= 1\n                self.ram_write(self.sp, value)\n                self.pc += 2\n            elif instruction == POP: # return value given to register\n                # get value from top of stack\n                value = self.ram_read(self.sp)\n                # set value to register address given\n                self.reg[reg_a] = value\n                # decrement stack pointer and add to program counter\n                self.sp -= 1\n                self.pc += 2\n            elif instruction == CAL: # jumps to address given\n                # compute return address after call finishes\n                return_address = self.pc + 2\n                # push return address on the stack\n                self.reg[self.sp] -= 1\n                self.ram[self.reg[self.sp]] = return_address\n                # set pc to value in given register\n                self.pc = self.reg[reg_a]\n            elif instruction == RET:\n                # pop return address from top of stack\n                return_address = self.ram[self.reg[self.sp]]\n                self.reg[self.sp] += 1\n                # set pc\n                self.pc = return_address\n            \n            # SPRINT\n            elif instruction == CMP: # compare reg_a and reg_b\n                self.alu('CMP', reg_a, reg_b)\n                self.pc += 3\n            elif instruction == JMP: # jump to given reg address\n                # set pc to the given register address\n                self.pc = self.reg[reg_a]\n            elif instruction == JEQ: # if E is 1, jump to given address\n                if self.fl_e == True:\n                    self.pc = self.reg[reg_a]\n                else:\n                    self.pc += 2\n            elif instruction == JNE: # if E is 0, jump to stored given address\n                if self.fl_e == False:\n                    self.pc = self.reg[reg_a]\n                else:\n                    self.pc += 2\n\n            else:\n                print('Unknown Instruction:', instruction)\n                sys.exit(1)","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"557091220","text":"# coding=utf-8\nimport numpy as np\n\nfrom pypint.problems import IInitialValueProblem, HasExactSolutionMixin, HasDirectImplicitMixin\nfrom pypint.utilities import assert_condition, assert_is_instance, class_name, assert_named_argument\nfrom pypint.solvers.cores.implicit_sdc_core import ImplicitSdcCore\n\n\nclass OneDimensionalHeatEquation(IInitialValueProblem, HasExactSolutionMixin, HasDirectImplicitMixin):\n    \"\"\":math:`u'(t, \\\\phi_t) = \\\\alpha \\\\laplace u(t, \\\\phi_t)`\n\n    Describes the following first-order ODE initial value problem:\n\n    .. math::\n\n        \\\\begin{align}\n            u'(t, \\\\phi_t) &= \\\\alpha \\\\laplace u(x, \\\\phi_t) \\\\\\\\\n                   u(x, 0) &= u_0 (x)\n        \\\\end{align}\n\n    With an exact solution.\n\n    Parameters\n    ----------\n    alpha : :py:class:`float`\n        *(optional)*\n        Coefficient :math:`\\\\lambda`\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        super(OneDimensionalHeatEquation, self).__init__(*args, **kwargs)\n        HasExactSolutionMixin.__init__(self, *args, **kwargs)\n        HasDirectImplicitMixin.__init__(self, *args, **kwargs)\n\n        if self.time_start is None:\n            self.time_start = 0.0\n        if self.time_end is None:\n            self.time_end = 1.0\n        if self.initial_value is None:\n            self.initial_value = complex(1.0, 0.0) * np.ones(self.dim)\n\n        if \"alpha\" not in kwargs:\n            kwargs[\"alpha\"] = 1.0\n        self.alpha = kwargs[\"alpha\"]\n\n        if isinstance(self.alpha, complex):\n            self.numeric_type = np.complex\n\n        # self.exact_function = lambda phi_of_time: self.initial_value * np.exp(self.lmbda * phi_of_time)\n\n        self._strings[\"rhs\"] = r\"\\alpha \\laplace u(x,t)\"\n        self._strings[\"exact\"] = r\"derivable using Fourier transformation\"\n\n        # multigrid stuff needed\n\n\n    def evaluate(self, time, phi_of_time, partial=None):\n        super(OneDimensionalHeatEquation, self).evaluate(time, phi_of_time, partial)\n        if partial is not None and isinstance(self.lmbda, complex):\n            if isinstance(partial, str) and partial == \"impl\":\n                return self.lmbda.imag * phi_of_time\n            elif partial == \"expl\":\n                return self.lmbda.real * phi_of_time\n        else:\n            return self.lmbda * phi_of_time\n\n    def direct_implicit(self, *args, **kwargs):\n        \"\"\"Direct Implicit Formula for :math:`u'(t, \\\\phi_t) &= \\\\lambda u(t, \\\\phi_t)`\n        \"\"\"\n        assert_is_instance(self.lmbda, complex,\n                           message=\"Direct implicit formula only valid for imaginay lambda: NOT %s\"\n                                   % class_name(self.lmbda),\n                           checking_obj=self)\n\n        assert_named_argument('phis_of_time', kwargs, checking_obj=self)\n        assert_named_argument('delta_node', kwargs, checking_obj=self)\n        assert_named_argument('integral', kwargs, checking_obj=self)\n\n        _phis = kwargs[\"phis_of_time\"]\n        assert_is_instance(_phis, list, message=\"Direct implicit formula needs multiple phis.\", checking_obj=self)\n        assert_condition(len(_phis) == 3, ValueError, message=\"Need exactly three different phis.\", checking_obj=self)\n\n        # _phis[0] : previous iteration -> previous step\n        # _phis[1] : previous iteration -> current step\n        # _phis[2] : current iteration -> previous step\n\n        _dn = kwargs[\"delta_node\"]\n        # TODO: make this numerics check more advanced (better warning for critical numerics)\n        assert_condition(_dn * self.lmbda.real != 1.0,\n                         ArithmeticError, \"Direct implicit formula for lambda={:f} and dn={:f} not valid. \"\n                                          .format(self.lmbda, _dn) + \"Try implicit solver.\",\n                         self)\n        _int = kwargs[\"integral\"]\n\n        if 'core' in kwargs and isinstance(kwargs['core'], ImplicitSdcCore):\n            return (_phis[2] - _dn * self.lmbda * _phis[1] + _int) / (1 - self.lmbda * _dn)\n        else:\n            return \\\n                (_phis[2]\n                 + _dn * (complex(0, self.lmbda.imag) * (_phis[2] - _phis[0]) - self.lmbda.real * _phis[1])\n                 + _int) \\\n                / (1 - self.lmbda.real * _dn)\n\n    @property\n    def lmbda(self):\n        return self._lmbda\n\n    @lmbda.setter\n    def lmbda(self, lmbda):\n        self._lmbda = lmbda\n\n    def print_lines_for_log(self):\n        _lines = super(LambdaU, self).print_lines_for_log()\n        _lines['Coefficients'] = '\\lambda = {}'.format(self.lmbda)\n        return _lines\n\n    def __str__(self):\n        str = super(LambdaU, self).__str__()\n        str += r\", \\lambda={}\".format(self.lmbda)\n        return str\n","sub_path":"examples/problems/one_dimensional_heatequation.py","file_name":"one_dimensional_heatequation.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"507973430","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nfrom numpy import savez_compressed\nfrom tqdm import tqdm_notebook as tqdm\nfrom numpy import load\n\nsize = (180,120)\n\ndef save_tarin_images_as_list(train_files, images_path, y_dict, size):\n    data_list = list()\n    label_list = list()\n    for file in tqdm(train_files):\n        path = images_path + file\n        pixels = load_img(path, target_size= size)\n        pixels = img_to_array(pixels)\n        data_list.append(pixels)\n        label_list.append(y_dict[file.split(\".\")[0]])\n    return [data_list,label_list]\n\nimages_path = \"./images/\"\nfiles = os.listdir(images_path)\n\ntrain_files = [i for i in files if \"Train\" in i]\n\ntrain_df = pd.read_csv(\"train.csv\")\n\nprint(\"Total: \", len(train_df))\nprint(\"Healthy: \",len(train_df[train_df[\"healthy\"] == 1]))\nprint(\"Diseased: \",len(train_df[train_df[\"healthy\"] == 0]))\n\ny_dict = train_df.set_index('image_id')['healthy'].to_dict()\n\ndata = save_tarin_images_as_list(train_files, images_path, y_dict, size)\n\nX = data[0]\ny = data[1]\n\nfilename = 'PestData_Train.npz'\nsavez_compressed(filename, X, np.array([[i] for i in y]))\nprint('Saved dataset: ', filename)\n","sub_path":"Make_data.py","file_name":"Make_data.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"437797925","text":"import os\n\ndef doWork(file, lineEnding):\n    print(file)\n    fileObj = open(file, \"rb\")\n    fileText = fileObj.read()\n    current = 0;\n    new = 0;\n\n    if lineEnding is \"CRLF\":\n        new = b\"\\r\\n\"\n    elif lineEnding is \"CR\":\n        new = b\"\\r\"\n    elif lineEnding is \"LF\":\n        new = b\"\\n\"\n        \n    if fileText.find(b\"\\r\\n\") >= 0:\n        current = b\"\\r\\n\"\n    elif fileText.find(b\"\\r\") >= 0:\n        current = b\"\\r\"\n    elif fileText.find(b\"\\n\") >= 0:\n        current = b\"\\n\"\n\n    fileObj.close()\n    if current != 0:\n\n        print(current)\n        print(new)\n        newText = fileText.replace(current, new)\n\n        fileObj = open(file, \"wb\")\n        fileObj.write(newText)\n        fileObj.close()\n\ndef Run(fileType, lineEnding):\n    entries = os.listdir()\n    for filename in entries:\n        if filename.find(\".\") >= 0:\n            array = filename.split(\".\")\n            if(array[1] == fileType):\n                doWork(filename, lineEnding)\n\nRun(\"h\", \"CRLF\")\nRun(\"cpp\", \"CRLF\")\ninput('Done!')\n","sub_path":"Frameworks/OpenGL Framework/data/source/ClassCreatorTool/pyLineEndings.py","file_name":"pyLineEndings.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"197253392","text":"import math\nfrom settings import *\nfrom app.utils import *\nfrom app.container import Container\nfrom app.cell import Cell\nfrom app.room import Room\nfrom .entity import Entity\n\n\nclass Grid(Entity):\n    \"\"\" Represent the grid that contains rooms and cells \"\"\"\n\n    def __init__(self):\n        self.object = type(self).__name__\n        Container.add_children('grid', self)\n        self.w = SIZE['LAYOUT']['W']\n        self.h = SIZE['LAYOUT']['H']\n        self.matrix = self.load_matrix()\n        self.rooms = []\n\n    @property\n    def columns_nb(self):\n        return math.floor(self.w / SIZE['CELL']['W'])\n\n    @property\n    def lines_nb(self):\n        return math.floor(self.h / SIZE['CELL']['H'])\n\n    @property\n    def cells_nb(self):\n        return self.columns_nb * self.lines_nb\n\n    @property\n    def first_empty_cell(self):\n        cell_id = sorted(self.empty_cells_list)[0]\n        return self.get_cell(get_pos(cell_id)[0], get_pos(cell_id)[1])\n\n    @property\n    def empty_cells(self):\n        empty_cells = []\n        for line in range(0, self.lines_nb):\n            for col in range(0, self.columns_nb):\n                if self.matrix[line][col].char == CHAR['EMPTY']:\n                    empty_cells.append(self.matrix[line][col])\n        return empty_cells\n\n    @property\n    def empty_cells_list(self):\n        return [cell.id for cell in self.empty_cells]\n\n    @property\n    def rooms_nb(self):\n        return len(self.rooms)\n\n    def load_matrix(self):\n        matrix = {}\n        for line in range(0, self.lines_nb):\n            matrix[line] = {}\n            for col in range(0, self.columns_nb):\n                matrix[line][col] = Cell(col, line)\n        return matrix\n\n    def get_cell(self, cx, cy):\n        if cx <= self.columns_nb and cx >= 0 and cy <= self.lines_nb and cy >= 0:\n            return self.matrix[cy][cx]\n        return None\n\n    def add_room(self, cells):\n        assert (int(cells) >= SIZE['MIN_ROOM_CELLS'])\n        assert (int(cells) <= SIZE['MAX_ROOM_CELLS'])\n        assert (int(cells) % 2 == 0)\n        cell = self.first_empty_cell\n        room = Room(cell.cx, cell.cy, cells)\n        self.rooms.append(room)\n        return room\n\n    def get_room(self, room_id):\n        for room in self.rooms:\n            if room_id == room.id:\n                return room\n","sub_path":"app/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"625387330","text":"import urllib2\nimport os\n \n#Openin the CS department page.\n\nreq = urllib2.Request(url=\"http://www.iitkgp.ac.in/department/CS\")\n\n#Creating a directory for storing the faculty HTML files.\n\nos.mkdir('facultyInfo2')\n\nfor line in urllib2.urlopen(req).readlines():\n\tif \"/department/CS/faculty/cs\" in line:\n\n\t\t#Getting the faculty HTML page.\n\t\t\n\t\tlink = line[line.find(\"href=\") + 6 : line.find(\";\")]\n\t\treq = urllib2.Request(url = 'http://www.iitkgp.ac.in' + link)\n\n\t\t#Storing the page in an HTML file.\n\n\t\tf = open('facultyInfo2/' + 'cs-' + link.split(';')[0].split('-')[1] + '.html', \"w\")\n\t\tf.write(urllib2.urlopen(req).read())\n\n\t\t#Closing the file.\n\n\t\tf.close()","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
    +{"seq_id":"536908021","text":"##################################################################################################\n# This is a flask application that provides api end points for the weather data in Hawaii\n# The home page specifies various end points. The end points returns a json response of the \n# requested data as per the endpoint url. All the data is taken from the SQLite database\n# \"hawaii.sqlite\" in the Resources folder.\n##################################################################################################\n\n# import dependencies\nfrom flask import Flask, jsonify\nimport datetime as dt\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nStations = Base.classes.stations\nMeasurements = Base.classes.measurements\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\n# Initializing the Flask app\napp = Flask(__name__)\n\n#################################################\n# Flask Routes\n#################################################\n\n# This is the home page of the application. It will list all the valid end points\n@app.route(\"/\")\ndef home():\n    print(\"Server received request for 'Home' page...\")\n    text = \"Welcome to the Surf API page!

    \\\n Below are some of the api endpoints that you can use to get the weather data for Hawaii:

    \\\n * /api/v1.0/precipitation - To get the precipitation data for the last year
    \\\n * /api/v1.0/temperature - To get the temperature data for the last year
    \\\n * /api/v1.0/stations - To get the stations list
    \\\n * /api/v1.0/start-date - To get the min, max and avg temperatures for all days starting the specified date
    \\\n * /api/v1.0/start-date/end-date - To get the min, max and avg temperatures for all days between the specified dates\"\n return text\n\n# This end point lists all the precipitation data for all the days for the last year i.e. starting a year ago\n@app.route(\"/api/v1.0/precipitation\")\ndef get_precipitation():\n\n # server logging\n print(\"Server received request for precipitation page...\")\n\n prev_year_date = dt.date.today() - dt.timedelta(days=365)\n\n # query precipitation data for the previous year\n results = session.query(Measurements.station_id, Measurements.date, Measurements.precipitation).\\\n filter(Measurements.date >= prev_year_date).\\\n order_by(Measurements.date)\n\n precipitation_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n p_dict = {}\n\n p_dict[\"date\"]=row.date \n p_dict[\"station_id\"]=row.station_id\n p_dict[\"precipitation\"]=row.precipitation\n precipitation_data.append(p_dict)\n\n # return the json representation of the data\n return jsonify(precipitation_data)\n\n# This end point lists all the temperature data for all the days for the last year i.e. starting a year ago\n@app.route(\"/api/v1.0/temperature\")\ndef get_temperature():\n\n # server logging\n print(\"Server received request for temperature page...\")\n\n prev_year_date = dt.date.today() - dt.timedelta(days=365)\n\n # query temperature data for the previous year\n results = session.query(Measurements.station_id, Measurements.date, Measurements.temperature).\\\n filter(Measurements.date >= prev_year_date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n\n t_dict[\"date\"]=row.date \n t_dict[\"station_id\"]=row.station_id\n t_dict[\"temperature\"]=row.temperature\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n# This end point lists all the station data\n@app.route(\"/api/v1.0/stations\")\ndef get_stations():\n\n # server logging\n print(\"Server received request for stations page...\")\n\n results = session.query(Stations).all()\n \n # Create a dictionary from the row data and append to a list of stations\n all_stations = []\n\n for station in results:\n station_dict = {}\n\n station_dict[\"station_id\"] = station.station_id\n station_dict[\"station_name\"] = station.station_name\n station_dict[\"latitude\"] = station.latitude\n station_dict[\"longitude\"] = station.longitude\n station_dict[\"elevation\"] = station.elevation\n all_stations.append(station_dict)\n\n # return the json representation of the data\n return jsonify(all_stations)\n\n# This end point lists the min, max and avg temperatures for all days starting \n# from the start date specified in the end point\n@app.route(\"/api/v1.0/\")\ndef get_weather_start(start):\n\n # server logging\n print(\"Server received request for start page...\")\n \n try:\n start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()\n except:\n return \"Invalid endpoint value: {}

    Please enter start date in the format YYYY-MM-DD\".format(start)\n \n results = session.query(Measurements.date, func.min(Measurements.temperature).label(\"tmin\"), \\\n func.max(Measurements.temperature).label(\"tmax\"), \\\n func.avg(Measurements.temperature).label(\"tavg\")).\\\n filter(Measurements.date >= start_date).\\\n group_by(Measurements.date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n\n t_dict[\"date\"]=row.date \n t_dict[\"min temperature\"]=row.tmin\n t_dict[\"max temperature\"]=row.tmax\n t_dict[\"avg temperature\"]=round(row.tavg,2)\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n# This end point lists the min, max and avg temperatures for all days \n# between the start date and end date specified in the end point\n@app.route(\"/api/v1.0//\")\ndef get_weather_start_end(start, end):\n\n # server logging\n print(\"Server received request for start-end page...\")\n try:\n start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()\n end_date = dt.datetime.strptime(end, '%Y-%m-%d').date()\n except:\n return \"Invalid endpoint value: {}/{}

    Please enter start and end dates in the format YYYY-MM-DD\".format(start, end)\n \n results = session.query(Measurements.date, func.min(Measurements.temperature).label(\"tmin\"), \\\n func.max(Measurements.temperature).label(\"tmax\"), \\\n func.avg(Measurements.temperature).label(\"tavg\")).\\\n filter(Measurements.date >= start_date).\\\n filter(Measurements.date <= end_date).\\\n group_by(Measurements.date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n \n t_dict[\"date\"]=row.date \n t_dict[\"min temperature\"]=row.tmin\n t_dict[\"max temperature\"]=row.tmax\n t_dict[\"avg temperature\"]=round(row.tavg,2)\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n\n#################################################\n# Flask Run App\n#################################################\nif __name__ == \"__main__\":\n # Run the app\n app.run(debug=True)","sub_path":"surf/surf_api.py","file_name":"surf_api.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"5842487","text":"import datetime\nimport os\nfrom urllib.parse import urlparse\n\nimport pytest\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.conf import settings\n\nfrom peterbecom.plog.models import BlogItem, BlogComment, Category\n\n\n@pytest.mark.django_db\ndef test_homepage_cache_rendering(client, tmpfscacheroot):\n url = reverse(\"home\")\n\n blog1 = BlogItem.objects.create(\n title=\"TITLE1\",\n text=\"BLABLABLA\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=10),\n )\n BlogComment.objects.create(\n oid=\"c1\", comment=\"textext\", blogitem=blog1, approved=True\n )\n\n BlogComment.objects.create(\n oid=\"c2\", comment=\"tuxtuxt\", blogitem=blog1, approved=True\n )\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TITLE1\" in content\n assert \"2 comments\" in content\n\n blog1.title = \"TUTLE1\"\n blog1.save()\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TUTLE1\" in content\n\n blog2 = BlogItem.objects.create(\n oid=\"t2\",\n title=\"TATLE2\",\n text=\"BLEBLE\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=1),\n )\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TATLE2\" in content\n assert \"0 comments\" in content\n assert \"TUTLE1\" in content\n assert \"2 comments\" in content\n\n # by categories only\n cat1 = Category.objects.create(name=\"CATEGORY1\")\n cat2 = Category.objects.create(name=\"CATEGORY2\")\n blog1.categories.add(cat1)\n blog1.save()\n blog2.categories.add(cat2)\n blog2.save()\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" in content\n assert \"CATEGORY2\" in content\n\n url = reverse(\"only_category\", args=[\"CATEGORY2\"])\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" not in content\n assert \"CATEGORY2\" in content\n\n url = reverse(\"only_category\", args=[\"CATEGORY1\"])\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" in content\n assert \"CATEGORY2\" not in content\n\n bulk = []\n for i in range(2, 21):\n bulk.append(\n BlogItem(\n oid=\"t-{}\".format(i),\n title=\"TITLE-{}\".format(i),\n text=\"BLEBLE\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=20 + i),\n )\n )\n BlogItem.objects.bulk_create(bulk)\n\n url = reverse(\"home\")\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"/p2\" in content\n visible_titles = []\n not_visible_titles = []\n for item in BlogItem.objects.all():\n if item.title in content:\n visible_titles.append(item.title)\n else:\n not_visible_titles.append(item.title)\n\n url = reverse(\"home_paged\", args=(2,))\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n batch_size = settings.HOMEPAGE_BATCH_SIZE\n for each in visible_titles[:batch_size]:\n assert each not in content\n for each in not_visible_titles[:batch_size]:\n assert each in content\n assert \"/p3\" in content\n\n\n@pytest.mark.django_db\ndef test_about_page_fs_cached(client, tmpfscacheroot):\n fs_path = os.path.join(tmpfscacheroot, \"about\", \"index.html\")\n assert not os.path.isfile(fs_path)\n url = reverse(\"about\")\n response = client.get(url)\n assert response.status_code == 200\n assert os.path.isfile(fs_path)\n\n\n@pytest.mark.django_db\ndef test_about_page_with_newline_request_path(client, tmpfscacheroot):\n url = reverse(\"about\")\n response = client.get(url + \"\\n\")\n assert response.status_code == 301\n assert urlparse(response[\"location\"]).path == url\n","sub_path":"peterbecom/homepage/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"284248373","text":"from __future__ import print_function\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchsummary import summary\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\ndef getTransformer():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n return transform\n\ndef trainset():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n return trainset\n\ndef testset():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n return testset\n\ndef getclasses():\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n return classes\n\n\n\n# functions to show an image\n\n\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n\n\n# get some random training images\n\n#trainset = trainset()\n#testset = testset()\n#trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n# shuffle=True, num_workers=2)\n#testloader = torch.utils.data.DataLoader(testset, batch_size=4,\n# shuffle=False, num_workers=2)\n\n#dataiter = iter(trainloader)\n#images, labels = dataiter.next()\n\n# show images\n#imshow(torchvision.utils.make_grid(images))\n# print labels\n#classes = getclasses()\n#print(' '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n\ndropout_value = 0.1\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # Input Block\n self.convblock1 = nn.Sequential(\n nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=2, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=2, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 36 , RF= 5*5\n\n self.pool1 = nn.MaxPool2d(2, 2) # output_size = 18, RF= 6*6\n\n # CONVOLUTION BLOCK 1\n self.convblock2 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=2, groups=128 , bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 20 , RF= 14*14\n self.pool2 = nn.MaxPool2d(2, 2) # output_size = 10, RF= 16*16\n \n # CONVOLUTION BLOCK 2\n self.convblock3 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=3, dilation = 3, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=256, out_channels=10, kernel_size=3, padding=2, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 12, RF= 48*48\n self.pool3 = nn.MaxPool2d(2, 2) # output_size = 6, RF= 56*56\n \n # OUTPUT BLOCK\n self.gap = nn.Sequential(\n nn.AvgPool2d(kernel_size=4)\n ) # output_size = 1\n\n self.convblock5 = nn.Sequential(\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n ) \n\n\n self.dropout = nn.Dropout(dropout_value)\n\n def forward(self, x):\n x = self.convblock1(x)\n x = self.pool1(x)\n x = self.convblock2(x)\n x = self.pool2(x)\n x = self.convblock3(x)\n x = self.pool3(x)\n #print(x.shape) \n x = self.gap(x) \n x = self.convblock5(x)\n \n x = x.view(-1, 10)\n return F.log_softmax(x, dim=-1)\n\ndef getDevice():\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n return device\n\n\n\ndef getOptimizer():\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n return optimizer\n\n\n\ndef testImages(testloader):\n dataiter = iter(testloader)\n images, labels = dataiter.next()\n\n# print images\n imshow(torchvision.utils.make_grid(images))\n print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))\n return images\n\n","sub_path":"Session7/CNNNetUtility.py","file_name":"CNNNetUtility.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336660252","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 14 16:27:14 2022\n\n@author: bdobson\n\"\"\"\n\nfrom wsimod.nodes.nodes import Node\nfrom wsimod.core import constants \n\ndef decorate_leakage_set(self, f):\n \"\"\"Decorator to extend the functionality of `f` by introducing leakage. \n This is achieved by adjusting the volume of the request (vqip) to include\n anticipated leakage, calling the original function `f`, and then \n distributing the leaked amount to groundwater.\n\n Args:\n self (instance of Distribution class): The Distribution object to be \n extended\n f (function): The function to be extended. Expected to be the \n Distribution object's pull_set function.\n\n Returns:\n pull_set (function): The decorated function which includes the \n original functionality of `f` and additional leakage operations.\n \"\"\"\n def pull_set(vqip, **kwargs):\n vqip['volume'] /= (1 - self.leakage)\n \n reply = f(vqip, **kwargs)\n \n amount_leaked = self.v_change_vqip(reply, \n reply['volume'] * self.leakage)\n \n reply = self.extract_vqip(reply, amount_leaked)\n \n unsuccessful_leakage = self.push_distributed(amount_leaked, of_type = 'Groundwater')\n if unsuccessful_leakage['volume'] > constants.FLOAT_ACCURACY:\n print('warning, distribution leakage not going to GW in {0} at {1}'.format(self.name, self.t))\n reply = self.sum_vqip(reply, unsuccessful_leakage)\n \n return reply\n return pull_set\n \ndef decorate_leakage_check(self, f):\n \"\"\"Decorator to extend the functionality of `f` by introducing leakage. \n This is achieved by adjusting the volume of the request (vqip) to include\n anticipated leakage and then calling the original function `f`.\n\n Args:\n self (instance of Distribution class): The Distribution object to be \n extended\n f (function): The function to be extended. Expected to be the \n Distribution object's pull_set function.\n\n Returns:\n pull_check (function): The decorated function which includes the \n original functionality of `f` and additional leakage operations.\n \"\"\"\n def pull_check(vqip, **kwargs):\n if vqip is not None:\n vqip['volume'] /= (1 - self.leakage)\n reply = f(vqip, **kwargs)\n amount_leaked = self.v_change_vqip(reply, \n reply['volume'] * self.leakage)\n \n reply = self.extract_vqip(reply, amount_leaked)\n return reply\n return pull_check\n\nclass Distribution(Node):\n def __init__(self, leakage = 0, **kwargs):\n \"\"\"A Node that cannot be pushed to. Intended to pass calls to FWTW - \n though this currently relies on the user to connect it properly\n \n Args:\n leakage (float, optional): 1 > float >= 0 to express how much \n water should be leaked to any attached groundwater nodes. This\n number represents the proportion of total flow through the node\n that should be leaked. \n Defaults to 0.\n \n Functions intended to call in orchestration:\n None\n \n Key assumptions:\n - No distribution processes yet represented, this class is just \n for conveyance.\n \n Input data and parameter requirements:\n - None\n \"\"\"\n self.leakage = leakage\n super().__init__(**kwargs)\n #Update handlers \n self.push_set_handler['default'] = self.push_set_deny\n self.push_check_handler['default'] = self.push_check_deny\n \n if leakage > 0:\n self.pull_set_handler['default'] = decorate_leakage_set(self, \n self.pull_set_handler['default'])\n self.pull_check_handler['default'] = decorate_leakage_check(self, \n self.pull_check_handler['default'])\n \nclass UnlimitedDistribution(Distribution):\n def __init__(self,**kwargs):\n \"\"\"A distribution node that provides unlimited water while tracking pass \n balance\n\n Functions intended to call in orchestration:\n None\n \n Key assumptions:\n - Water demand is always satisfied.\n \n Input data and parameter requirements:\n - None\n \"\"\"\n super().__init__(**kwargs)\n #Update handlers \n self.pull_set_handler['default'] = self.pull_set_unlimited\n self.pull_check_handler['default'] = lambda x : self.v_change_vqip(self.empty_vqip(), constants.UNBOUNDED_CAPACITY)\n \n #States\n self.supplied = self.empty_vqip()\n \n self.mass_balance_in.append(lambda : self.supplied)\n \n def pull_set_unlimited(self, vqip):\n \"\"\"Respond that VQIP was fulfilled and update state variables for mass balance\n\n Args:\n vqip (dict): A VQIP amount to request\n\n Returns:\n vqip (dict): A VQIP amount that was supplied\n \"\"\"\n #TODO maybe need some pollutant concentrations?\n vqip = self.v_change_vqip(self.empty_vqip(), vqip['volume'])\n self.supplied = self.sum_vqip(self.supplied, vqip)\n return vqip\n \n def end_timestep(self):\n \"\"\"Update state variables\n \"\"\"\n self.supplied = self.empty_vqip()","sub_path":"wsimod/nodes/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"150754925","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.index, name='index'),\n path('about', views.about, name='about'),\n path('menu', views.menu, name='menu'),\n path('login', views.login, name='login'),\n path('register', views.register, name='register'),\n path('cart', views.cart, name='cart'),\n path('settings', views.settings, name='settings'),\n path('user_orders', views.user_orders, name='user_orders'),\n path('order', views.order, name='order'),\n path('no_js', views.no_js, name='no_js'),\n path('cookie_disabled', views.cookie_disabled, name='cookie_disabled'),\n path('logout', views.logout, name='logout'),\n path('confirm_account/',\n views.confirm_account, name='confirm_account'),\n path('update_cart', views.update_cart, name='update_cart'),\n path('change_email', views.change_email, name='change_email'),\n path('confirm_email_change/',\n views.confirm_email_change, name='confirm_email_change'),\n path('change_password', views.change_password, name='change_password'),\n]\n","sub_path":"core_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"289519102","text":"from keras.models import Model\nimport numpy as np\nimport gzip, struct, random\nfrom keras.models import load_model\nimport matplotlib.pylab as plt\nfrom keras.utils import to_categorical\n\n# load the data from the files\n\nwith gzip.open('t10k-labels-idx1-ubyte.gz') as f:\n magic, num = struct.unpack(\">II\", f.read(8))\n test_labels = np.fromstring(f.read(), dtype=np.int8)\n\nwith gzip.open('t10k-images-idx3-ubyte.gz') as f:\n magic, num, rows, cols = struct.unpack(\">IIII\", f.read(16))\n test_images = np.fromstring(f.read(), dtype=np.uint8).reshape(num, rows, cols, 1)\n\n# Normalize and encode the labeling of data set\ntest_labels_encoded = to_categorical(test_labels)\ntest_images = test_images / 255\nn = int(len(test_images) / 2)\nX_valid, y_valid = test_images[:n], test_labels_encoded[:n]\nX_test, y_test = test_images[n:], test_labels_encoded[n:]\n\n# load the model form the saved model\ncnn_model = load_model('my_model.h5')\n\n\n# Evaluate the model\ncnn_scores = cnn_model.evaluate(X_test, y_test, verbose=0)\n\nprint(\"CNN Scores: \", (cnn_scores))\nprint(\"CNN Error: %.2f%%\" % (100 - cnn_scores[1] * 100))\n\nplt.figure(figsize=(14, 5))\nplt.plot(cnn_history.history['categorical_accuracy'][3:], '-o', label='train')\nplt.plot(cnn_history.history['val_categorical_accuracy'][3:], '-o', label='test')\nplt.legend()\nplt.title('CNN Accuracy');\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"600832038","text":"import compute\nimport pyopencl\nimport numpy\n\nclass Stimuli:\n def __init__(self, cs = None, numStimulus=None):\n if not isinstance(cs, compute.ComputeSystem):\n raise ValueError(\"[stimuli] Expected cs to be of type: {}, but got: {}\".format(type(ComputeSystem), type(cs)))\n self.cs = cs\n\n if not isinstance(numStimulus, int):\n raise ValueError(\"[Stimuli] Expected numStimulus to be of type {} but got: {}\".format(type(int), type(numStimulus)))\n self.numS = numStimulus\n\n self._numbytesSStates = numpy.uint32().nbytes * self.numS\n\n self.bufferSStates = pyopencl.Buffer(cs.getContext(), pyopencl.mem_flags.READ_WRITE, size=self._numbytesSStates)\n\n self.clearStates()\n\n def clearStates(self):\n pyopencl.enqueue_fill_buffer(self.cs.getQueue(), self.bufferSStates, numpy.uint32(0), 0, self._numbytesSStates)\n\n def setStates(self, states = []):\n pyopencl.enqueue_copy(self.cs.getQueue(), self.bufferSStates, states)\n #pyopencl.enqueue_write_buffer(self.cs.getQueue(), self.bufferSStates, numpy.uint32(0), self._numbytesSStates, states)\n\n def getStates(self):\n vecStates = None\n pyopencl.enqueue_read_buffer(self.cs.getQueue(), True, 0, self._numbytesSStates, vecStates)\n return vecStates\n\n def printStates(self):\n vecStates = None\n pyopencl.enqueue_read_buffer(self.cs.getQueue(), True, 0, self._numbytesSStates, vecStates)\n for i in xrange(self.numS):\n print(\"{} \".format(vecStates[i]))\n\nif __name__ == \"__main__\":\n cs = compute.ComputeSystem(devicetype=compute.GPU)\n s = Stimuli(cs=cs, numStimulus=4)\n","sub_path":"htm/cortex/stimuli.py","file_name":"stimuli.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316475498","text":"# Exercise 17: More Files\n\n# -*- coding: utf-8 -*-\n\nfrom os.path import exists\nfrom sys import argv\n\nscript, from_file, to_file = argv\n\nprint(\"Copying from %s to %s\" % (from_file, to_file))\n\n# we could do these two on one line too, how?\nin_file = open(from_file)\nin_data = in_file.read()\n# in_data = open(from_file).read()\n\nprint(\"The input file is %d bytes long\" % len(in_data))\n\nprint(\"Does the output file exist? %r\" % exists(to_file))\nprint(\"Ready, hit RETURN to continue, CTRL-C to abort.\")\ninput()\n\nout_file = open(to_file, 'w')\nout_file.write(in_data)\n\nprint(\"Alright, all done.\")\n# open(to_file, 'w').write(open(from_file).read())\nout_file.close()\nin_file.close()\n","sub_path":"ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32212510","text":"def hcf(x,y):\n if x>y:\n small=y\n else:\n small=x\n for i in range(1,small+1):\n if x%i==0 and y%i==0:\n re=i\n return re\n\ns=list(input())\ns.remove(\"[\")\ns.remove(\"]\")\ns=\"\".join(s)\ncard=sorted(s.split(\",\"))\nnum=[]\ntemp=1\nfor i in range(0,len(card)-1):\n if card[i]==card[i+1]:\n temp+=1\n else:\n num.append(temp)\n temp=1\n if i==len(card)-1:\n num.append(temp)\nnum=sorted(num)\nif max(num)<2:\n print(False)\nelif len(num)==1:\n print(True)\nelse:\n temp=hcf(num[0],num[1])\n for i in range(2,len(num)):\n temp=hcf(temp,num[i])\n if temp<2:\n print(False)\n else:\n print(True)","sub_path":"Code/CodeRecords/2325/60787/245021.py","file_name":"245021.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"559054824","text":"import cv2\nimport numpy as np\nfrom lailib.image.resize import resize_height_keep_ratio\nfrom math import sin, cos, ceil, pi\nfrom skimage import morphology\nfrom PIL import ImageFont, ImageDraw, Image\nimport os\nimport math\nimport random\nfrom skimage.filters import threshold_sauvola\nfrom scipy.ndimage import interpolation\nimport pdb\n\n\ndef savola(img):\n thresh_sauvola = threshold_sauvola(img, window_size=25)\n binary_sauvola = img > thresh_sauvola\n ret_sauvola = binary_sauvola.astype(np.uint8) * 255\n return ret_sauvola\n\n\ndef otsu_thresh(im):\n '''\n binarize image with otsu algorithm\n :param im: uint8 numpy array\n :return: binarized image as uint8 numpy array\n '''\n to_binarize = np.copy(np.uint8(im))\n ret2, th2 = cv2.threshold(to_binarize, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n return th2\n\n\ndef hor_crop(im, binarized):\n '''\n\n crop image only on horizontal direction\n\n Args:\n im: uint8ndarray\n input image to be cropped\n binarized: uint8ndarray\n binarized version of im,\n at least this binarized image should have\n the same shape as im\n Returns:\n cropped image\n '''\n\n row_sums = np.sum(binarized, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n\n cropped = im[:, col_start:col_end]\n\n return cropped\n\n\ndef resize_on_long_aixs(full_im, cropped_im):\n full_h, full_w = full_im.shape\n cropped_h, cropped_w = cropped_im.shape\n full_ratio = full_h / full_w\n cropped_ratio = cropped_h / cropped_w\n if full_ratio > cropped_ratio:\n # based on w\n cropped_im = cv2.resize(cropped_im, (full_w, int(full_w / cropped_w * cropped_h)))\n else:\n # based on h\n cropped_im = cv2.resize(cropped_im, (int(full_h / cropped_h * cropped_w), full_h))\n return cropped_im\n\n\ndef resize_image(image_cv, new_height, **kwargs):\n '''\n resize image with given height, keep ratio\n :param image_cv: image to be resized\n :param new_height: new height of the output image\n :param inte_method: interpolation method\n :return: resized image\n '''\n (height, width) = image_cv.shape\n new_width = int(float(width) * new_height / float(height))\n image_cv = cv2.resize(image_cv, (new_width, new_height), **kwargs)\n return image_cv\n\n\ndef crop_and_padding(image_cv, padding=0, new_height=None, binarized=False):\n '''\n crop and padding an image, may resize image to a height\n :param image_cv: input image, uint8 numpy array, assumed to be gray scale\n (if binarized set to true, image will be kept binarized)\n :param padding: padding to each side\n :param new_height: new_height of image if required\n :return: cropped and potentially padded and resized image (uint8)\n '''\n col_sums = np.sum(image_cv, axis=1)\n row_start = np.where(col_sums)[0][0]\n rev_col_sum = np.flip(col_sums, axis=0)\n rev_end = np.where(rev_col_sum)[0][0]\n row_end = col_sums.shape[0] - rev_end\n\n row_sums = np.sum(image_cv, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n\n cropped = image_cv[row_start:row_end, col_start:col_end]\n\n # TODO add rand noise to height\n if new_height:\n cropped = resize_image(cropped, new_height)\n if binarized:\n ret2, cropped = cv2.threshold(cropped, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n height, width = cropped.shape\n final_out = cropped\n if padding:\n final_out = np.zeros((height + 2 * padding, width + 2 * padding))\n final_out[padding:-padding, padding:-padding] = cropped\n return final_out\n\n\ndef process_thin_img(im):\n kernel = np.ones((3, 3), np.uint8)\n im = np.pad(im, ((3, 3), (3, 3)), 'maximum')\n im = 255 - ((255 - im) * 0.8).astype(np.uint8)\n im = cv2.erode(im, kernel, iterations=10)\n im = blur_image(im)\n return im\n\n\ndef blur_image(im):\n kernel = np.ones((5, 5), np.float32) / 25\n dst = cv2.filter2D(im, -1, kernel)\n return dst\n\n\ndef flip_tuple(coord):\n return (coord[1], coord[0])\n\n\ndef erode_plus(orig_img, target_thickness=2):\n orig_img = otsu_thresh(orig_img)\n orig_img = 255 - orig_img\n orig_img_copy = orig_img.copy()\n element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n skel = morphology.skeletonize(orig_img > 0)\n erode_baseline = None\n thickness = 0\n\n while True:\n # does not support 0 or 1 thickness yet\n thickness += 1\n orig_sum = np.sum(orig_img > 0)\n # erode but keep skel\n orig_img = cv2.dilate(orig_img, element, iterations=1)\n orig_img = cv2.erode(orig_img, element, iterations=2)\n orig_img = cv2.bitwise_or(np.array(skel, dtype=np.uint8) * 255, orig_img)\n # calcualte erode rate, if too little, it means it's almost skel already\n erode_rate = orig_sum - np.sum(orig_img > 0)\n if erode_baseline is None:\n erode_baseline = erode_rate\n else:\n if (erode_rate < erode_baseline / 2) or (erode_rate < 10):\n break\n # print(thickness)\n orig_img = orig_img_copy.copy()\n if thickness - target_thickness + 1 < 0:\n return orig_img, thickness\n # raise NotImplementedError(\"wait\")\n # print(thickness - target_thickness + 1)\n for i in range(thickness - target_thickness + 1):\n orig_img = cv2.dilate(orig_img, element, iterations=1)\n orig_img = cv2.erode(orig_img, element, iterations=2)\n orig_img = cv2.bitwise_or(np.array(skel, dtype=np.uint8) * 255, orig_img)\n # orig_img = blur_image(255 - orig_img)\n orig_img = 255 - orig_img\n return orig_img, thickness\n\n\ndef fix_lr_boundary(image_cv, padding=15):\n '''\n fix left and right padding for an image\n :param image_cv: input image, uint8 numpy array, assumed to be gray scale\n (if binarized set to true, image will be kept binarized)\n :return: cropped and potentially padded and resized image (uint8)\n '''\n up_padding = 10\n down_padding = 15\n _, binarized = cv2.threshold(image_cv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n im_h, im_w = image_cv.shape\n col_sums = np.sum(binarized, axis=1)\n row_start = np.where(col_sums)[0][0]\n rev_col_sum = np.flip(col_sums, axis=0)\n rev_end = np.where(rev_col_sum)[0][0]\n row_end = col_sums.shape[0] - rev_end\n row_sums = np.sum(binarized, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n if (row_end - row_start) > 0.3 * im_h:\n cropped = image_cv[row_start:row_end, col_start:col_end]\n else:\n cropped = image_cv[:, col_start:col_end]\n height, width = cropped.shape\n rel_up_padding = ceil(up_padding * height / 75)\n rel_down_padding = ceil(down_padding * height / 75)\n rel_lr_padding = ceil(padding * height / 75)\n final_out = cropped\n if padding:\n if (row_end - row_start) > 0.3 * im_h:\n final_out = np.zeros((height + rel_up_padding + rel_down_padding, width + 2 * rel_lr_padding))\n final_out[rel_up_padding:-rel_down_padding, rel_lr_padding:-rel_lr_padding] = cropped\n else:\n final_out = np.zeros((height, width + 2 * rel_lr_padding))\n final_out[:, rel_lr_padding:-rel_lr_padding] = cropped\n return final_out\n\n\ndef estimate_skew_angle(image, angles):\n \"\"\"estimate skew angle \"\"\"\n estimates = []\n for a in angles:\n v = np.mean(interpolation.rotate(image, a, order=0, mode='constant'), axis=1)\n v = np.var(v)\n estimates.append((v, a))\n _, a = max(estimates)\n return a\n\n\ndef estimate_skew(flat, bignore, maxskew, skewsteps):\n ''' estimate skew angle and rotate'''\n d0, d1 = flat.shape\n o0, o1 = int(bignore * d0), int(bignore * d1)\n flat = 1 - flat\n est = flat[o0:d0 - o0, o1:d1 - o1]\n ma = maxskew\n ms = int(2 * maxskew * skewsteps)\n angle = estimate_skew_angle(est, np.linspace(-ma, ma, ms + 1))\n flat = interpolation.rotate(flat, angle, mode='constant', reshape=0)\n flat[flat < 0] = 0.\n flat = 1 - flat\n return flat, angle\n\n\ndef deskew(image):\n bignore = 0.1\n maxskew = 2\n skewsteps = 8\n image = image.copy() / 255.0\n image, angle = estimate_skew(image, bignore, maxskew, skewsteps)\n return (image * 255).astype(np.uint8)\n\n\ndef pad2square(im):\n h, w = im.shape\n if h > w:\n pad_w = h - w\n left_pad = pad_w // 2\n right_pad = pad_w - left_pad\n im = np.pad(im, ((0, 0), (left_pad, right_pad)), constant_values=((255, 255), (255, 255)))\n else:\n pad_h = w - h\n up_pad = pad_h // 2\n down_pad = pad_h - up_pad\n im = np.pad(im, ((up_pad, down_pad), (0, 0)), constant_values=((255, 255), (255, 255)))\n return im\n","sub_path":"src/util/image_util.py","file_name":"image_util.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"329654465","text":"import time\n\nfrom rammi import _\nfrom rammi.interface import DictableInstance\n\nimport settings\n\n\nclass Course(DictableInstance):\n _fields = (\n 'title',\n 'description',\n 'price',\n 'price_description',\n 'time_description',\n 'is_free',\n 'credits',\n 'link_source',\n 'link_registration',\n\n #\n # Keys:\n # job_title\n # name\n # website\n #\n 'teacher',\n\n #\n # Keys:\n # category_id: []\n #\n 'categories',\n\n #\n # List of dicts with keys:\n # epoch -- seconds since Jan 1, 1970\n # duration -- in seconds\n #\n 'schedules',\n\n 'user_id',\n 'epoch_created'\n )\n\n _required_fields = (\n 'title',\n 'description',\n 'price',\n 'credits',\n 'link_source',\n\n 'user_id'\n )\n\n teacher_default = lambda self: {}\n categories_default = lambda self: {}\n schedules_default = lambda self: []\n\n @property\n def categories_trans(self):\n result = {}\n\n for category_id, subcategories in self.categories.iteritems():\n result[category_id] = [_(subcategory) for subcategory in subcategories]\n\n return result\n\n def validate(self, *args, **kwargs):\n errors = super(Course, self).validate(*args, **kwargs)\n required_msg = _('%s is required')\n\n if not getattr(self, 'teacher', None):\n errors.append({\n 'field' : 'teacher',\n 'message': required_msg % 'teacher',\n })\n elif not self.teacher.get('name'):\n errors.append({\n 'field' : 'teacher.name',\n 'message': required_msg % 'teacher.name',\n })\n\n if getattr(self, 'is_free', None) is None:\n errors.append({\n 'field' : 'is_free',\n 'message': required_msg % 'is_free',\n })\n\n\n if not getattr(self, 'schedules', None):\n errors.append({\n 'field' : 'schedules',\n 'message' : required_msg % 'schedules',\n })\n\n if errors:\n errors.append({\n 'field' : None,\n 'message': _('Please Fill All Required Fields'),\n })\n\n return errors\n\n def to_dict(self, format=None, *args, **kwargs):\n result = super(Course, self).to_dict(*args, **kwargs)\n\n if format == 'ajax':\n result.update({\n 'categories_trans': self.categories_trans\n })\n\n # add date string in schedule\n for schedule in result.get('schedules', []):\n if 'datetime' not in schedule or 'duration' not in schedule:\n continue\n\n starttime = time.gmtime(schedule.get('datetime'))\n endtime = time.gmtime(schedule.get('datetime') + schedule.get('duration'))\n\n schedule.update({\n 'startdate_string': time.strftime(settings.FORMAT_DATE, starttime),\n 'starttime_string': time.strftime(settings.FORMAT_TIME, starttime),\n 'enddate_string' : time.strftime(settings.FORMAT_DATE, endtime),\n 'endtime_string' : time.strftime(settings.FORMAT_TIME, endtime),\n })\n\n\n return result\n\n\nclass CourseCategory(DictableInstance):\n _fields = (\n 'title',\n 'subcategories'\n )\n\n def get_translated_title(self):\n return _(self.title)\n\n def get_translated_subcategories(self):\n return [_(subcategory) for subcategory in self.subcategories]\n\n def to_dict(self, format=None, *args, **kwargs):\n result = super(CourseCategory, self).to_dict(*args, **kwargs)\n\n if format == 'ajax':\n result.update({\n 'title_trans': self.get_translated_title(),\n 'subcategories_trans': self.get_translated_subcategories()\n })\n\n return result\n","sub_path":"conted/courses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"532627251","text":"import cv2\nimport numpy as np\n\n\n# SIFT based correction - functions\n\ndef enhance(image, clip_limit=5):\n # convert image to LAB color model\n image_lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n\n # split the image into L, A, and B channels\n l_channel, a_channel, b_channel = cv2.split(image_lab)\n\n # apply CLAHE to lightness channel\n clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(8, 8))\n cl = clahe.apply(l_channel)\n\n # merge the CLAHE enhanced L channel with the original A and B channel\n merged_channels = cv2.merge((cl, a_channel, b_channel))\n\n # convert image from LAB color model back to RGB color model\n final_image = cv2.cvtColor(merged_channels, cv2.COLOR_LAB2BGR)\n return final_image \n\n\ndef find_matches_and_homography(imageL, imageR, MIN_MATCH_COUNT=11, GOOD_PERC=0.7, FLANN_INDEX_KDTREE=0):\n\n sift = cv2.KAZE_create()\n img1 = enhance(imageL)\n img2 = enhance(imageR)\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks = 50)\n\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n good = []\n for m,n in matches:\n if m.distance < GOOD_PERC*n.distance:\n good.append(m)\n if len(good)>=MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1, 1 ,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1, 1, 2)\n H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n matchesMask = mask.ravel().tolist()\n else:\n print(\"Not enough matches are found - %d/%d\" % (len(good),MIN_MATCH_COUNT))\n matchesMask = None\n\n return good, matchesMask, H, kp1, kp2\n\n\ndef adjust_keypoints(keypoints, H):\n left_keypoints_crop = {item['keypointType']: [item['xCrop'], item['yCrop']] for item in keypoints['leftCrop']}\n right_keypoints_crop = {item['keypointType']: [item['xCrop'], item['yCrop']] for item in keypoints['rightCrop']}\n\n # adjust left and right keypoints\n left_keypoints_crop_adjusted, right_keypoints_crop_adjusted = [], []\n for i, bp in enumerate([item['keypointType'] for item in keypoints['leftCrop']]):\n kpL = left_keypoints_crop[bp]\n ptx = np.array([kpL[0], kpL[1], 1])\n zx = np.dot(H, ptx)\n kpL2R = [zx[0] / zx[2], zx[1] / zx[2]]\n\n kpR = right_keypoints_crop[bp]\n pty = np.array([kpR[0], kpR[1], 1])\n zy = np.dot(np.linalg.inv(H), pty)\n kpR2L = [zy[0] / zy[2], zy[1] / zy[2]]\n\n kpL_adjusted = [(kpL[0] + kpR2L[0]) / 2.0, (kpL[1] + kpR2L[1]) / 2.0]\n kpR_adjusted = [(kpR[0] + kpL2R[0]) / 2.0, (kpR[1] + kpL2R[1]) / 2.0]\n item_left = keypoints['leftCrop'][i]\n item_right = keypoints['rightCrop'][i]\n\n new_item_left = {\n 'keypointType': bp,\n 'xCrop': kpL_adjusted[0],\n 'xFrame': item_left['xFrame'] - item_left['xCrop'] + kpL_adjusted[0],\n 'yCrop': kpL_adjusted[1],\n 'yFrame': item_left['yFrame'] - item_left['yCrop'] + kpL_adjusted[1]\n }\n left_keypoints_crop_adjusted.append(new_item_left)\n\n new_item_right = {\n 'keypointType': bp,\n 'xCrop': kpR_adjusted[0],\n 'xFrame': item_right['xFrame'] - item_right['xCrop'] + kpR_adjusted[0],\n 'yCrop': kpR_adjusted[1],\n 'yFrame': item_right['yFrame'] - item_right['yCrop'] + kpR_adjusted[1]\n }\n right_keypoints_crop_adjusted.append(new_item_right)\n\n adjusted_keypoints = {\n 'leftCrop': left_keypoints_crop_adjusted,\n 'rightCrop': right_keypoints_crop_adjusted\n }\n return adjusted_keypoints\n\n\n\n \n","sub_path":"alok/biomass_estimation/archive/production_data_analysis_v3/template_matching.py","file_name":"template_matching.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"24229703","text":"#\n# @lc app=leetcode.cn id=2 lang=python3\n#\n# [2] 两数相加\n#\n# https://leetcode-cn.com/problems/add-two-numbers/description/\n#\n# algorithms\n# Medium (32.69%)\n# Total Accepted: 86.8K\n# Total Submissions: 265.7K\n# Testcase Example: '[2,4,3]\\n[5,6,4]'\n#\n# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。\n#\n# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。\n#\n# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。\n#\n# 示例:\n#\n# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)\n# 输出:7 -> 0 -> 8\n# 原因:342 + 465 = 807\n#\n#\n#\n# Definition for singly-linked list.\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n\n def chain_table_to_int(self, x: ListNode):\n s = ''\n while x:\n s += str(x.val)\n x = x.next\n if s:\n print(s)\n return int(s[::-1])\n else:\n return 0\n\n def addTwoNumbers(self, l1: ListNode, l2: ListNode):\n\n return [int(x) for x in str(self.chain_table_to_int(l1) + self.chain_table_to_int(l2))[::-1]]\n\n# class Solution:\n#\n# def chain_table_to_int(self, x: ListNode):\n# s = ''\n# while x and x.next:\n# s += str(x.val)\n# x = x.next\n# if s:\n# return int(s[::-1])\n# else:\n# return 0\n#\n# def addTwoNumbers(self, l1: ListNode, l2: ListNode):\n#\n# return [int(x) for x in str(self.chain_table_to_int(l1) + self.chain_table_to_int(l2))[::-1]]\n","sub_path":"vs_leetcode/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483240228","text":"# Copyright 2019 The Casbin Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nfrom werkzeug.wrappers import Request\r\nfrom werkzeug.exceptions import Forbidden\r\nfrom apps.libs.error_code import my_Forbidden\r\nfrom flask_jwt import jwt\r\nfrom apps.api.model.model import Users\r\n\r\n\r\nclass CasbinMiddleware:\r\n def __init__(self, app, enforcer):\r\n self.app = app\r\n self.enforcer = enforcer\r\n\r\n def __call__(self, environ, start_response):\r\n request = Request(environ)\r\n\r\n # 检查每个请求的权限。\r\n if not self.check_permission(request):\r\n # 未授权,返回http 403错误。\r\n return my_Forbidden()(environ, start_response)\r\n # return Forbidden()(environ, start_response)\r\n\r\n # 权限已通过,请转到下一个模块\r\n return self.app(environ, start_response)\r\n\r\n def check_permission(self, request):\r\n # 根据您的身份验证方法对其进行自定义。\r\n user = None\r\n try:\r\n token = str(request.headers.get('Authorization')).split(' ')[1]\r\n id = jwt.decode(token, \"pangyd\", algorithms=['HS256'])['identity']\r\n user = Users.get(id).username\r\n except Exception:\r\n user = None\r\n if user is None:\r\n user = 'anonymous'\r\n path = request.path\r\n method = request.method\r\n return self.enforcer.enforce(user, path, method)\r\n","sub_path":"apps/rbac/authz/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"47032114","text":"import numpy as np\nnp.random.seed(1337)\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten\nfrom keras.optimizers import Adam\n\nmnist_data = np.load('mnist.npz')\nX_train,y_train = mnist_data['x_train'],mnist_data['y_train']\nX_test,y_test = mnist_data['x_test'],mnist_data['y_test']\n\nprint('数据大小:',X_train.shape)\nprint('原始数据标签:',y_train[0:10])\nprint('-'*50)\n\nX_train = X_train.reshape(-1,1,28,28)/255.\nX_test = X_test.reshape(-1,1,28,28)/255.\ny_train = np_utils.to_categorical(y_train,num_classes = 10)\ny_test = np_utils.to_categorical(y_test, num_classes = 10)\n\nprint('转换成one-hot后的数据标签:',y_train[0:10])\nprint('-'*19+'data加载完毕'+'-'*19)\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(batch_input_shape=(None,1,28,28),\n\tfilters=32,\n\tkernel_size=5,\n\tstrides=1,\n\tpadding='same',\n\tdata_format='channels_first',))\n\nmodel.add(Activation('relu'))\n\nmodel.add(MaxPooling2D(pool_size=2,\n\tstrides=2,\n\tpadding='same',\n\tdata_format='channels_first'))\n\nmodel.add(Convolution2D(batch_input_shape=(None,1,28,28),\n\tfilters=64,\n\tkernel_size=5,\n\tstrides=1,\n\tpadding='same',\n\tdata_format='channels_first',))\n\nmodel.add(Activation('relu'))\n\nmodel.add(MaxPooling2D(pool_size=2,\n\tstrides=2,\n\tpadding='same',\n\tdata_format='channels_first'))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024))\nmodel.add(Activation('relu'))\n\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nadam = Adam(lr=1e-4)\n\nmodel.compile(optimizer=adam,\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nprint('数据训练中......')\nmodel.fit(X_train, y_train, epochs=10, batch_size=64,)\nprint('数据训练完毕.')\n\nprint('开始测试模型......')\nloss, accuracy = model.evaluate(X_test, y_test)\nprint('\\nTest Loss: ', loss)\nprint('\\nTest Accuracy: ', accuracy)\n\n\n\n\n\n\n","sub_path":"深度学习/Templet/Train_Nets/Keras/Mnist/sample_cnn.py","file_name":"sample_cnn.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"206215229","text":"#!/usr/bin/env python3\n\nimport os\nimport cv2\nimport numpy as np\nfrom glob import glob\nimport tensorflow as tf\n\nfrom config import cfg\nfrom celeba import CelebA\nfrom generators import generator_tf as G\nfrom discriminators import discriminator_tf as D\n\n\ndef model_inputs(w, h, c, z_dim):\n # Input for the model, image\n _i = tf.placeholder(tf.float32, [None, w, h, c], 'real_input_images')\n _z = tf.placeholder(tf.float32, [None, z_dim], 'input_z')\n return _i, _z\n\ndef model_loss(inp_real, inp_z, out_channel, alpha=0.2, smooth_factor=0.1):\n # Loss from the real image for G and D\n d_model_real, d_logits_real = D(inp_real, alpha=alpha)\n d_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_real,\n labels=tf.ones_like(d_model_real) * (1 - smooth_factor)))\n\n # Loss from the fake image for G and D\n inp_fake = G(inp_z, out_channel, alpha=alpha)\n d_model_fake, d_logits_fake = D(inp_fake, reuse=True, alpha=alpha)\n d_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_fake,\n labels=tf.zeros_like(d_model_fake)))\n\n g_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_fake,\n labels=tf.ones_like(d_model_fake)))\n\n return d_loss_real + d_loss_fake, g_loss\n\ndef model_opt(d_loss, g_loss, lr, beta1):\n # Optimization operations for the losses of D and G\n # Get weights and bias to update\n t_vars = tf.trainable_variables()\n d_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n g_vars = [var for var in t_vars if var.name.startswith('generator')]\n\n # Optimize\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n d_train_opt = tf.train.AdamOptimizer(lr, beta1=beta1)\\\n .minimize(d_loss, var_list=d_vars)\n g_train_opt = tf.train.AdamOptimizer(lr, beta1=beta1)\\\n .minimize(g_loss, var_list=g_vars)\n\n return d_train_opt, g_train_opt\n\ndef show_generator_output(sess, n_img, inp_z, out_channel, img_mode='RGB'):\n # Show the output from the generator\n cmap = None if img_mode == 'RGB' else 'gray'\n z_dim = inp_z.get_shape().as_list()[-1]\n example_z = np.random.uniform(-1, 1, size=[n_img, z_dim])\n\n samples = sess.run(G(inp_z, out_channel, False), feed_dict={inp_z: example_z})\n\n images_grid = helper.images_square_grid(samples, image_mode)\n return images_grid\n\ndef train(nb_epochs, batch_size, z_dim, lr, beta1, get_batches, data_shape,\n data_img_mode, print_every=10, show_every=100):\n # Train method for the GAN\n inp_real, inp_z = model_inputs(*data_shape, z_dim)\n d_loss, g_loss = model_loss(inp_real, inp_z, data_shape[2])\n d_train_opt, g_train_opt = model_opt(d_loss, g_loss, lr, beta1)\n\n saver = tf.train.Saver()\n sample_z = np.random.uniform(-1, 1, size=(72, z_dim))\n\n samples, losses = [], []\n\n steps = 0\n count = 0\n with tf.Session() as sess:\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n\n # continue training\n save_path = saver.save(sess, \"/tmp/model.ckpt\")\n ckpt = tf.train.latest_checkpoint('./model/')\n saver.restore(sess, save_path)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n os.mkdir('output')\n for epoch_i in range(nb_epochs):\n os.mkdir('output/'+ str(epoch_i))\n for batch_images in get_batches(batch_size):\n steps += 1\n batch_images *= 2.0\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))\n \n # Run optimizers\n sess.run(d_train_opt, feed_dict={inp_real: batch_images, input_z: batch_z})\n sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n if steps % print_every == 0:\n # At the end of each epoch, get the losses and print them out\n train_loss_d = d_loss.eval({inp_real: batch_images, inp_z: batch_z})\n train_loss_g = g_loss.eval({inp_z: batch_z})\n print(\"Epoch {}/{} Step {}...\".format(epoch_i+1, nb_epochs, steps),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g))\n # Save losses for viewing after training\n losses.append((train_loss_d, train_loss_g))\n\n if steps % show_every == 0:\n count = count +1\n iterr = count*show_every\n # Show example output for the generator\n images_grid = show_generator_output(sess, 25, inp_z, data_shape[2], data_img_mode)\n dst = os.path.join(\"output\", str(epoch_i), str(iterr)+\".png\")\n pyplot.imsave(dst, images_grid)\n \n # saving the model\n if epoch_i % 10 == 0:\n if not os.path.exists('./model/'):\n os.makedirs('./model')\n saver.save(sess, './model/' + str(epoch_i))\n\n# Get the data in a readable format\ndataset = CelebA()\n\n# Tensorflow\nwith tf.Graph().as_default():\n train(cfg.NB_EPOCHS, cfg.BATCH_SIZE, cfg.SIZE_G_INPUT, cfg.LEARNING_RATE,\n cfg.BETA1, dataset.get_batches, dataset.shape, dataset.image_mode)\n\n\nfor f in glob(\"output/**/*.png\"):\n image = cv2.imread(f)\n # cv2.imshow('my_image', image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n large = cv2.resize(image, (0,0), fx=3, fy=3)\n cv2.imwrite(f, large)","sub_path":"GAN_experiments/celebrities_face_generator/test_tf.py","file_name":"test_tf.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"378156528","text":"from functools import partial\n\nfrom pyschieber.stich import Stich\nfrom pyschieber.trumpf import Trumpf\n\nUNDER = 11\nNAELL = 9\n\n\ndef stich_obe_unde(played_cards, operation, trumpf):\n suit = played_cards[0].card.suit\n (_, index) = operation(\n [(played_card.card.value, i) for i, played_card in enumerate(played_cards) if played_card.card.suit == suit])\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n\n\ndef stich_trumpf(played_cards, trumpf):\n trumpfs = [(played_card.card.value, i) for i, played_card in enumerate(played_cards) if\n played_card.card.suit.name == trumpf.name]\n if trumpfs:\n values = [trumpf[0] for trumpf in trumpfs]\n if UNDER in values: # Under\n index = trumpfs[values.index(UNDER)][1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n if NAELL in values:\n index = trumpfs[values.index(NAELL)][1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n index = max(trumpfs)[1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n else:\n return stich_obe_unde(played_cards=played_cards, operation=max, trumpf=trumpf)\n\n\nstich_rules = {\n Trumpf.OBE_ABE: partial(stich_obe_unde, operation=max, trumpf=Trumpf.OBE_ABE),\n Trumpf.UNDE_UFE: partial(stich_obe_unde, operation=min, trumpf=Trumpf.UNDE_UFE),\n}\n\nfor trumpf in filter(lambda x: x != Trumpf.OBE_ABE and x != Trumpf.UNDE_UFE and x != Trumpf.SCHIEBEN, Trumpf):\n stich_rules[trumpf] = partial(stich_trumpf, trumpf=trumpf)\n\n\ndef card_allowed(first_card, chosen_card, hand_cards, trumpf):\n chosen_suit = chosen_card.suit\n if chosen_card not in hand_cards:\n return False\n if first_card is None:\n return True\n first_suit = first_card.suit\n if first_suit == chosen_suit or chosen_suit.name == trumpf.name:\n return True\n else:\n if trumpf not in [Trumpf.OBE_ABE, Trumpf.UNDE_UFE]:\n hand_suits = [hand_card.suit for hand_card in hand_cards if\n hand_card.suit.name != trumpf.name and hand_card.value != UNDER]\n else:\n hand_suits = [hand_card.suit for hand_card in hand_cards]\n if first_suit in hand_suits:\n return False\n else:\n return True\n\n\ndef allowed_cards(hand_cards, table_cards, trumpf):\n cards = []\n if len(table_cards) > 0:\n for card in hand_cards:\n if card_allowed(table_cards[0], card, hand_cards, trumpf):\n cards.append(card)\n else:\n cards += hand_cards\n return cards\n","sub_path":"pyschieber/rules/stich_rules.py","file_name":"stich_rules.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"418623582","text":"import requests\n\nheaders = {\n \"User-Agent\": \"User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\"\n\n}\n\nurl = 'https://hr.tencent.com/position.php?keywords=python&tid=87&lid=2218'\n\ndata ={\n'keywords': 'python',\n'tid': 87,\n'lid': 2218,\n}\n\nresponse =requests.post(url,data=data,headers=headers)\n\nprint(response)","sub_path":"requests_tengxun.py","file_name":"requests_tengxun.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"438531364","text":"import math\n\ndef get_g_month_length(g_month, g_year):\n if g_month != 2:\n return [None, 31, None, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][g_month]\n else:\n return 28 + (g_year % 4 == 0 and (\n g_year % 100 != 0 or g_year % 400 == 0))\n\ndef get_ts_total_seasons(ts_season, ts_year):\n return (ts_season - 1) + 4 * (ts_year - 1)\n\ndef get_ts_equinox_length(ts_total_seasons):\n c1 = ts_total_seasons % 3 == 0\n c2 = ts_total_seasons % 44 == 0\n return 1 + c1 - c2\n\ndef get_ts_lunar_equinox_length(ts_total_seasons):\n c1 = ts_total_seasons % 3 == 0\n c2 = ts_total_seasons % int(math.log(2, 10) * 1024) == 0\n return 1 - c1 + c2\n\ndef next_day(g_day, g_month, g_year, ts_day, ts_month, ts_equinox, ts_season,\nts_year, ts_lun_day, ts_lun_count, ts_lun_year):\n # simple\n if g_day != get_g_month_length(g_month, g_year):\n r_g_day = g_day + 1\n r_g_month = g_month\n r_g_year = g_year\n elif g_month != 12:\n r_g_day = 1\n r_g_month = g_month + 1\n r_g_year = g_year\n else:\n r_g_day = 1\n r_g_month = 1\n r_g_year = g_year + 1\n # complicated\n if ts_equinox:\n lun_day_jump = get_ts_lunar_equinox_length(get_ts_total_seasons(\n ts_season, ts_year)) / 2\n if ts_day != get_ts_equinox_length(get_ts_total_seasons(\n ts_season, ts_year)):\n r_ts_day = ts_day + 1\n r_ts_month = ts_month\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n r_ts_day = 1\n r_ts_month = 1\n r_ts_equinox = False\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n if ts_day != 30:\n lun_day_jump = 1\n r_ts_day = ts_day + 1\n r_ts_month = ts_month\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n elif ts_month != 3:\n lun_day_jump = 1\n r_ts_day = 1\n r_ts_month = ts_month + 1\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n skip_equinox = get_ts_equinox_length(get_ts_total_seasons(\n ts_season + 1, ts_year)) == 0\n new_year = ts_season == 4\n lun_day_jump = get_ts_lunar_equinox_length(get_ts_total_seasons(\n ts_season + 1, ts_year)) / (1 if skip_equinox else 2)\n r_ts_day = 1\n r_ts_month = 1 if skip_equinox else None\n r_ts_equinox = not skip_equinox\n r_ts_season = 1 if new_year else ts_season + 1\n r_ts_year = ts_year + 1 if new_year else ts_year\n r_ts_lun_day = (ts_lun_day + lun_day_jump) % 29\n if r_ts_lun_day < ts_lun_day:\n if r_ts_year == ts_lun_year:\n r_ts_lun_count = ts_lun_count + 1\n r_ts_lun_year = ts_lun_year\n else:\n r_ts_lun_count = 1\n r_ts_lun_year = r_ts_year\n else:\n r_ts_lun_count = ts_lun_count\n r_ts_lun_year = ts_lun_year\n return r_g_day, r_g_month, r_g_year, r_ts_day, r_ts_month, \\\n r_ts_equinox, r_ts_season, r_ts_year, r_ts_lun_day, r_ts_lun_count, \\\n r_ts_lun_year\n\ndef main():\n # d = 13, 12, 2012, 23, 3, False, 4, 0, 0.0, 13, 0\n # the below is equivalent to the above\n d = 26, 12, 2011, 4, 1, False, 1, 0, 0.0, 1, 0\n desc = ('day', 'month', 'year', 'day', 'month', 'equinox?',\n 'season', 'year', 'lunar day', 'lunar month', 'lunar year')\n while True:\n '''\n if (d[3], d[4], d[6]) == (30, 3, 4) and d[-4] % 77 == 0 and d[-4] % 3 != 0 and d[-3] == 28:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n if (d[3], d[4], d[6]) == (1, 1, 1) and d[-4] % 77 == 1 and d[-4] % 3 != 1 and d[-3] == 1:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n if d[-3] in (28.5, 0.5) and 840 > d[-4] > 630:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n '''\n if d[2] in (2017, 2018):\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n d = next_day(*d)\n\nif __name__ == '__main__':\n main()\n","sub_path":"internarrative_commit_system_test/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137526464","text":"# -*- coding:utf8 -*-\n# File : data_provider_discogan.py\n# Author : Jiayuan Mao\n# Email : maojiayuan@gmail.com\n# Date : 4/2/17\n# \n# This file is part of TensorArtist\n\nimport os.path as osp\n\nimport numpy as np\nimport tqdm\n\nfrom tartist import image\nfrom tartist.app import gan\nfrom tartist.core import get_env\nfrom tartist.core.utils.thirdparty import get_tqdm_defaults\nfrom tartist.data import flow, kvstore\n\n\nclass DiscoGANSplitDataFlow(flow.SimpleDataFlowBase):\n def __init__(self, kva, kvb):\n super().__init__()\n self._kva = kva\n self._kvb = kvb\n self._img_shape = get_env('dataset.img_shape', (64, 64))\n\n def _crop_and_resize(self, img):\n img = image.imdecode(img)\n img = image.resize(img, self._img_shape)\n return img\n\n def _gen(self):\n ita = iter(self._kva)\n itb = iter(self._kvb)\n while True:\n res = dict(\n img_a=self._crop_and_resize(next(ita)),\n img_b=self._crop_and_resize(next(itb))\n )\n yield res\n\n\ndef _make_dataflow(batch_size=1, use_prefetch=False):\n img_shape = get_env('dataset.img_shape', (64, 64))\n\n data_dir = get_env('dir.data')\n db_a = osp.join(data_dir, get_env('dataset.db_a'))\n db_b = osp.join(data_dir, get_env('dataset.db_b'))\n\n dfs = []\n dfa = flow.KVStoreRandomSampleDataFlow(lambda: kvstore.LMDBKVStore(db_a))\n dfb = flow.KVStoreRandomSampleDataFlow(lambda: kvstore.LMDBKVStore(db_b))\n df = DiscoGANSplitDataFlow(dfa, dfb)\n df = flow.BatchDataFlow(df, batch_size, sample_dict={\n 'img_a': np.empty(shape=(batch_size, img_shape[0], img_shape[1], 3), dtype='float32'),\n 'img_b': np.empty(shape=(batch_size, img_shape[0], img_shape[1], 3), dtype='float32'),\n })\n if use_prefetch:\n df = flow.MPPrefetchDataFlow(df, nr_workers=2)\n return df\n\n df = gan.GANDataFlow(dfs[0], dfs[1],\n get_env('trainer.nr_g_per_iter', 1), get_env('trainer.nr_d_per_iter', 1))\n\n\ndef make_dataflow_train(env):\n batch_size = get_env('trainer.batch_size')\n dfs = [_make_dataflow(batch_size, use_prefetch=True) for i in range(2)]\n\n df = gan.GANDataFlow(dfs[0], dfs[1], \n get_env('trainer.nr_g_per_iter', 1), get_env('trainer.nr_d_per_iter', 1))\n\n return df\n\n\ndef make_dataflow_demo(env):\n return _make_dataflow(1)\n\n\ndef demo(feed_dict, results, extra_info):\n img_a, img_b = feed_dict['img_a'][0], feed_dict['img_b'][0]\n img_ab, img_ba = results['img_ab'][0] * 255, results['img_ba'][0] * 255\n img_aba, img_bab = results['img_aba'][0] * 255, results['img_bab'][0] * 255\n\n img = np.vstack([\n np.hstack([img_a, img_ab, img_aba]), \n np.hstack([img_b, img_ba, img_bab])\n ])\n img = img.astype('uint8')\n img = image.resize_minmax(img, 512, 2048)\n\n image.imshow('demo', img)\n\n","sub_path":"examples/generative-model/data_provider_discogan.py","file_name":"data_provider_discogan.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"64181017","text":"\"\"\"\nFunctions and data to use for formatting Pathoscope and NuVs analysis document. Formatted documents are destined for\nAPI responses or CSV/Excel formatted file downloads.\n\n\"\"\"\nimport asyncio\nimport csv\nimport io\nimport json\nimport statistics\nfrom collections import defaultdict\n\nimport aiofiles\nimport openpyxl.styles\n\nimport virtool.analyses.db\nimport virtool.analyses.utils\nimport virtool.db.core\nimport virtool.db.utils\nimport virtool.history.db\nimport virtool.otus.db\nimport virtool.otus.utils\n\nCSV_HEADERS = (\n \"OTU\",\n \"Isolate\",\n \"Sequence\",\n \"Length\",\n \"Weight\",\n \"Median Depth\",\n \"Coverage\"\n)\n\n\ndef calculate_median_depths(document: dict) -> dict:\n \"\"\"\n Calculate the median depth for all hits (sequences) in a Pathoscope result document.\n\n :param document: the pathoscope analysis document to calculate depths for\n :return: a dict of median depths keyed by hit (sequence) ids\n\n \"\"\"\n depths = dict()\n\n for hit in document[\"results\"]:\n depths[hit[\"id\"]] = statistics.median(hit[\"align\"])\n\n return depths\n\n\nasync def create_pathoscope_coverage_cache(db, document):\n cache = defaultdict(lambda: defaultdict(lambda: dict()))\n\n for hit in document[\"results\"]:\n for isolate in hit[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n otu_id = hit[\"id\"]\n isolate_id = isolate[\"id\"]\n sequence_id = sequence[\"id\"]\n\n if sequence.get(\"align\"):\n cache[otu_id][isolate_id][sequence_id] = virtool.analyses.utils.transform_coverage_to_coordinates(sequence[\"align\"])\n\n document = {\n \"analysis\": {\n \"id\": document[\"_id\"]\n },\n \"cache\": cache\n }\n\n await db.coverage.insert_one(document)\n\n return document\n\n\nasync def ensure_pathoscope_coverage_cache(db, document):\n cache = await db.coverage.find_one({\"analysis.id\": document[\"_id\"]})\n\n if cache is None:\n cache = await create_pathoscope_coverage_cache(db, document)\n\n for hit in document[\"results\"]:\n for isolate in hit[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n otu_id = hit[\"id\"]\n isolate_id = isolate[\"id\"]\n sequence_id = sequence[\"id\"]\n\n if sequence.get(\"align\"):\n sequence[\"align\"] = cache[\"cache\"][otu_id][isolate_id][sequence_id]\n\n\nasync def load_results(settings: dict, document: dict) -> dict:\n \"\"\"\n Load the analysis results. Hide the alternative loading from a `results.json` file. These files are only\n generated if the analysis data would have exceeded the MongoDB size limit (16mb).\n\n The document is returned unmodified if loading from file is not required.\n\n :param settings: the application settings\n :param document: the document to load results for\n :return: a complete analysis document\n\n \"\"\"\n if document[\"results\"] == \"file\":\n path = virtool.analyses.utils.join_analysis_json_path(\n settings[\"data_path\"],\n document[\"_id\"],\n document[\"sample\"][\"id\"]\n )\n\n async with aiofiles.open(path, \"r\") as f:\n data = json.loads(await f.read())\n return {\n **document,\n \"results\": data\n }\n\n return document\n\n\nasync def format_aodp(app, document):\n patched_otus = await gather_patched_otus(app, document[\"results\"])\n\n hits = defaultdict(list)\n\n for hit in document[\"results\"]:\n hits[hit[\"sequence_id\"]].append(hit)\n\n for otu in patched_otus.values():\n otu[\"id\"] = otu.pop(\"_id\")\n\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n sequence[\"hits\"] = hits[sequence[\"_id\"]]\n sequence[\"id\"] = sequence.pop(\"_id\")\n\n return {\n **document,\n \"results\": list(patched_otus.values())\n }\n\n\nasync def format_pathoscope(app, document):\n document = await load_results(\n app[\"settings\"],\n document\n )\n\n patched_otus = await gather_patched_otus(app, document[\"results\"])\n\n formatted = dict()\n\n for hit in document[\"results\"]:\n\n otu_id = hit[\"otu\"][\"id\"]\n\n otu_document = patched_otus[otu_id]\n\n max_ref_length = 0\n\n for isolate in otu_document[\"isolates\"]:\n max_ref_length = max(max_ref_length, max([len(s[\"sequence\"]) for s in isolate[\"sequences\"]]))\n\n otu = {\n \"id\": otu_id,\n \"name\": otu_document[\"name\"],\n \"version\": otu_document[\"version\"],\n \"abbreviation\": otu_document[\"abbreviation\"],\n \"isolates\": otu_document[\"isolates\"],\n \"length\": max_ref_length\n }\n\n formatted[otu_id] = otu\n\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n if sequence[\"_id\"] == hit[\"id\"]:\n sequence.update(hit)\n sequence[\"length\"] = len(sequence[\"sequence\"])\n\n del sequence[\"otu\"]\n del sequence[\"otu_id\"]\n del sequence[\"isolate_id\"]\n\n document[\"results\"] = [formatted[otu_id] for otu_id in formatted]\n\n for otu in document[\"results\"]:\n for isolate in list(otu[\"isolates\"]):\n if not any((key in sequence for sequence in isolate[\"sequences\"]) for key in (\"pi\", \"final\")):\n otu[\"isolates\"].remove(isolate)\n continue\n\n for sequence in isolate[\"sequences\"]:\n if \"final\" in sequence:\n sequence.update(sequence.pop(\"final\"))\n del sequence[\"initial\"]\n if \"pi\" not in sequence:\n sequence.update({\n \"pi\": 0,\n \"reads\": 0,\n \"coverage\": 0,\n \"best\": 0,\n \"length\": len(sequence[\"sequence\"])\n })\n\n sequence[\"id\"] = sequence.pop(\"_id\")\n del sequence[\"sequence\"]\n\n await ensure_pathoscope_coverage_cache(app[\"db\"], document)\n\n return document\n\n\nasync def format_nuvs(app, document):\n document = await load_results(\n app[\"settings\"],\n document\n )\n\n hit_ids = list({h[\"hit\"] for s in document[\"results\"] for o in s[\"orfs\"] for h in o[\"hits\"]})\n\n cursor = app[\"db\"].hmm.find({\"_id\": {\"$in\": hit_ids}}, [\"cluster\", \"families\", \"names\"])\n\n hmms = {d.pop(\"_id\"): d async for d in cursor}\n\n for sequence in document[\"results\"]:\n for orf in sequence[\"orfs\"]:\n for hit in orf[\"hits\"]:\n hit.update(hmms[hit[\"hit\"]])\n\n return document\n\n\nasync def format_analysis_to_excel(app, document):\n depths = calculate_median_depths(document)\n\n formatted = await format_analysis(app, document)\n\n output = io.BytesIO()\n\n wb = openpyxl.Workbook()\n ws = wb.active\n\n ws.title = f\"Pathoscope for {document['sample']['id']}\"\n\n header_font = openpyxl.styles.Font(name=\"Calibri\", bold=True)\n\n for index, header in enumerate(CSV_HEADERS):\n col = index + 1\n cell = ws.cell(column=col, row=1, value=header)\n cell.font = header_font\n\n rows = list()\n\n for otu in formatted[\"results\"]:\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n row = [\n otu[\"name\"],\n virtool.otus.utils.format_isolate_name(isolate),\n sequence[\"accession\"],\n sequence[\"length\"],\n sequence[\"pi\"],\n depths.get(sequence[\"id\"], 0),\n sequence[\"coverage\"]\n ]\n\n assert len(row) == len(CSV_HEADERS)\n\n rows.append(row)\n\n for row_index, row in enumerate(rows):\n row_number = row_index + 2\n for col_index, value in enumerate(row):\n ws.cell(column=col_index + 1, row=row_number, value=value)\n\n wb.save(output)\n\n return output.getvalue()\n\n\nasync def format_analysis_to_csv(app, document):\n depths = calculate_median_depths(document)\n\n formatted = await format_analysis(app, document)\n\n output = io.StringIO()\n\n writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)\n\n writer.writerow(CSV_HEADERS)\n\n for otu in formatted[\"results\"]:\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n row = [\n otu[\"name\"],\n virtool.otus.utils.format_isolate_name(isolate),\n sequence[\"accession\"],\n sequence[\"length\"],\n sequence[\"pi\"],\n depths.get(sequence[\"id\"], 0),\n sequence[\"coverage\"]\n ]\n\n writer.writerow(row)\n\n return output.getvalue()\n\n\nasync def format_analysis(app, document: dict) -> dict:\n \"\"\"\n Format an analysis document to be returned by the API.\n\n :param app: the application object\n :param document: the analysis document to format\n :return: a formatted document\n\n \"\"\"\n workflow = document.get(\"workflow\")\n\n if workflow:\n if workflow == \"nuvs\":\n return await format_nuvs(app, document)\n\n if \"pathoscope\" in workflow:\n return await format_pathoscope(app, document)\n\n if workflow == \"aodp\":\n return await format_aodp(app, document)\n\n raise ValueError(\"Could not determine analysis workflow\")\n\n\nasync def gather_patched_otus(app, results):\n # Use set to only id-version combinations once.\n otu_specifiers = {(hit[\"otu\"][\"id\"], hit[\"otu\"][\"version\"]) for hit in results}\n\n patched_otus = await asyncio.gather(*[\n virtool.history.db.patch_to_version(\n app,\n otu_id,\n version\n ) for otu_id, version in otu_specifiers\n ])\n\n return {patched[\"_id\"]: patched for _, patched, _ in patched_otus}\n","sub_path":"virtool/analyses/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":9988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"35808396","text":"class Player:\n def __init__(self, name):\n self.name = name;\n self.steps = []\n self.choose = True\n\n def players_turn(self):\n self.choose = True\n try:\n while self.choose:\n a = int(input(\"Player's turn\\n\"))\n if self.steps.count(a) == 0:\n if a < 9 and a >= 0:\n self.steps.append(a)\n return a\n except:\n print('Something went wrong. '\n 'Write to the developer... ivandubovtsov@gmail.com')\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"80465653","text":"from util_class import ListNode\nclass Solution:\n \"\"\"\n @param head: The first node of linked list\n @param x: An integer\n @return: A ListNode\n \"\"\"\n def partition(self, head, x):\n # write your code here\n if not head:\n return None\n \n dummy = ListNode(0)\n dummy.next = head\n small_head = ListNode(0) \n big_head = ListNode(0)\n s_head, b_head = small_head, big_head\n while head:\n tmp = head.next\n head.next = None\n if head.val < x:\n s_head.next = head\n s_head = s_head.next\n else:\n b_head.next = head\n b_head = b_head.next\n head = tmp \n \n s_head.next = big_head.next\n \n return small_head.next","sub_path":"96_partition-list/partition-list.py","file_name":"partition-list.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"395522256","text":"# sudo lsof -iTCP -sTCP:LISTEN -n -P\n# https://dreamfit01.herokuapp.com/ | https://git.heroku.com/dreamfit01.git\n\n# heroku\thttps://git.heroku.com/dreamfit01.git (fetch)\n# heroku\thttps://git.heroku.com/dreamfit01.git (push)\n# origin\thttps://github.com/donaldvallejo/CarsCloud.git (fetch)\n# origin\thttps://github.com/donaldvallejo/CarsCloud.git (push)\n\nimport os\nfrom datetime import datetime\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nhost = os.environ.get('MONGODB_URI', 'mongodb://localhost:27017/cars')\nclient = MongoClient(host=f'{host}?retryWrites=false')\ndb = client.get_default_database()\ncars = db.cars\ncomments = db.comments\n\napp = Flask(__name__)\n\n@app.route('/')\ndef cars_index():\n \"\"\"Show all cars\"\"\"\n return render_template('cars_index.html', cars=cars.find())\n\n@app.route('/home')\ndef home():\n \"\"\"Show Home page\"\"\"\n return render_template('home.html')\n\n@app.route('/finance')\ndef finance():\n \"\"\"Show Finance page\"\"\"\n return render_template('finance.html')\n\n@app.route('/cars/new')\ndef cars_new():\n \"\"\"Create cars\"\"\"\n return render_template('cars_new.html', car = {}, title='New Cars')\n\n@app.route('/cars', methods=['POST'])\ndef cars_submit():\n \"\"\"Submit cars to database\"\"\"\n car = {\n 'Make': request.form.get('Make'),\n 'Model': request.form.get('Model'),\n 'Description': request.form.get('Description'),\n 'Color': request.form.get('Color'),\n 'Price': request.form.get('Price'),\n 'Image': request.form.get('Image'),\n 'created_at': datetime.now()\n }\n\n car_id = cars.insert_one(car).inserted_id\n print(\"Check to see if Data is even happening \\n\", car_id, car)\n return redirect(url_for('cars_show', car_id=car_id))\n\n@app.route('/cars/')\ndef cars_show(car_id):\n \"\"\"Show a single car.\"\"\"\n car = cars.find_one({'_id': ObjectId(car_id)})\n car_comments = comments.find({'car_id': ObjectId(car_id)})\n return render_template('cars_show.html', car=car, comments=car_comments)\n\n@app.route('/cars//edit')\ndef cars_edit(car_id):\n \"\"\"Show the edit form for a car.\"\"\"\n car = cars.find_one({'_id': ObjectId(car_id)})\n return render_template('cars_edit.html', car=car, title='Edit Car')\n\n@app.route('/search', methods=['POST'])\ndef search():\n searched_cars = cars.find()\n search = request.form.get('search')\n search_items = []\n for car in searched_cars:\n if search.lower() in car['Make'].lower():\n search_items.append(car)\n elif search.lower() in car['Model'].lower():\n search_items.append(car)\n elif search.lower() in car['Color'].lower():\n search_items.append(car)\n elif search.lower() in car['Price'].lower():\n search_items.append(car)\n else:\n print('how did you break this?')\n return render_template('cars_index.html', cars=search_items)\n\n@app.route('/cars/', methods=['POST'])\ndef cars_update(car_id):\n \"\"\"Submit an edited cars\"\"\"\n updated_car = {\n 'Make': request.form.get('Make'),\n 'Model': request.form.get('Model'),\n 'Description': request.form.get('Description'),\n 'Color': request.form.get('Color'),\n 'Price': request.form.get('Price'),\n 'Image': request.form.get('Image'),\n }\n cars.update_one(\n {'_id': ObjectId(car_id)},\n {'$set': updated_car})\n return redirect(url_for('cars_show', car_id=car_id))\n\n@app.route('/cars//delete', methods=['POST'])\ndef cars_delete(car_id):\n \"\"\"Delete one car.\"\"\"\n cars.delete_one({'_id': ObjectId(car_id)})\n return redirect(url_for('cars_index'))\n\n@app.route('/cars/comments', methods=['POST'])\ndef comments_new():\n \"\"\"Submit a new comment.\"\"\"\n comment = {\n 'title': request.form.get('title'),\n 'content': request.form.get('content'),\n 'car_id': ObjectId(request.form.get('car_id'))\n }\n comment_id = comments.insert_one(comment).inserted_id\n return redirect(url_for('cars_show', car_id=request.form.get('car_id')))\n\n@app.route('/cars/comments/', methods=['POST'])\ndef comments_delete(comment_id):\n \"\"\"Action to delete a comment.\"\"\"\n comment = comments.find_one({'_id': ObjectId(comment_id)})\n comments.delete_one({'_id': ObjectId(comment_id)})\n return redirect(url_for('cars_show', car_id=comment.get('car_id')))\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=os.environ.get('PORT', 5000))","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"414983189","text":"import arcpy\r\n\r\nfrom code_library.common.geospatial import geometry\r\nfrom code_library.common import log\r\n\r\nlog.init_log(arc_script = True)\r\n\r\np1 = arcpy.GetParameterAsText(0)\r\np2 = arcpy.GetParameterAsText(1)\r\n\r\ncen_dist,out_table,out_points = geometry.simple_centroid_distance(p1,p2,spatial_reference = p1,dissolve=True,return_file=True)\r\n\r\n\r\nlog.warning(\"Centroid Distance: %s\" % cen_dist)\r\nlog.warning(\"Points representing the centroids and a table with the distances have been returned to the TOC\")\r\n\r\narcpy.SetParameterAsText(2,out_points)\r\narcpy.SetParameterAsText(3,out_table)","sub_path":"releases/cws_toolbox/current/cws_toolbox/simple_centroid_distance/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"4524678","text":"#!/bin/python3\n# Copyright 2019-2020 CSIRO Land and Water\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\"\"\"\nThis example gets some Sensor Observations from a given Cosmoz station\n\"\"\"\n\nfrom urllib.request import Request, urlopen\nfrom urllib.parse import urljoin, urlencode\nfrom datetime import datetime, timezone\nimport json\n\nCOSMOZ_API_URL = \"https://esoil.io/cosmoz-data-pipeline/rest/\" # Keep the trailing slash on here\n\nSTATION_NUMBER = 21\nPROCESSING_LEVEL = 4 # Choose processing level 1, 2, 3, 4, or 0 (for Raw)\n\n# Endpoint to get a station's observations is \"pipeline/rest/stations/{id}/observations\"\nstations_endpoint = urljoin(COSMOZ_API_URL, \"stations/\")\nstation_endpoint = urljoin(stations_endpoint, \"{}/\".format(str(STATION_NUMBER)))\nstation_obs_endpoint = urljoin(station_endpoint, \"observations\")\n\n# Time Period Start Date\nstart_date = datetime(2019, 1, 1, tzinfo=timezone.utc)\nstart_date_str = start_date.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\") # ISO8601 Format\n# Time Period End Date\nend_date = datetime(2019, 1, 31, tzinfo=timezone.utc)\nend_date_str = end_date.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\") # ISO8601 Format\n# Add request query params\nquery_params = {\n \"processing_level\": PROCESSING_LEVEL,\n \"startdate\": start_date_str,\n \"enddate\": end_date_str,\n}\nquery_params = urlencode(query_params)\nstation_obs_url = \"{}?{}\".format(station_obs_endpoint, query_params)\n\n# Add a header to specifically ask for JSON output\nrequest_headers = {\"Accept\": \"application/json\"}\n\n# Construct a GET request, with that URL and those headers\nstation_obs_request = Request(station_obs_url, method=\"GET\", headers=request_headers)\n# Execute the request, and wait for the response.\nwith urlopen(station_obs_request) as http_response:\n try:\n response = http_response.read()\n except Exception:\n raise RuntimeError(\"Cannot read HTTP Response\")\n try:\n payload = json.loads(response)\n except Exception:\n raise RuntimeError(\"Invalid JSON response\")\nprint(\"Got Observations Meta:\")\nfor k, v in payload['meta'].items():\n print(\"\\t{}: {}\".format(str(k), str(v)))\n\ncount = payload['meta']['count']\nsite = payload['meta']['site_no']\nprint(\"Showing {} Observations for station {}.\".format(str(count), str(site)))\nfor i, o in enumerate(payload['observations']):\n print(\"Observation {} of {}:\".format(i+1, count))\n for k, v in o.items():\n print(\"\\t{}: {}\".format(str(k), str(v)))\n","sub_path":"example4_station_observations.py","file_name":"example4_station_observations.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"105791512","text":"from numpy.random import *\n\npopulation = ['M']*20000 + ['F']*20000 + ['m']\ndef nextGen(population):\n\tnewGen = []\n\tif population.count('F')==0:\n\t\treturn newGen\n\twhile len(newGen) < population.count('M') + population.count('F'):\n\t\tA = population[randint(len(population))]\n\t\tB = population[randint(len(population))]\n\t\tif A.lower() != B.lower():\n\t\t\tif A == 'm' or B == 'm':\n\t\t\t\tnewGen.append('m')\n\t\t\telse:\n\t\t\t\tif randint(2)==0:\n\t\t\t\t\tnewGen.append('M')\n\t\t\t\telse:\n\t\t\t\t\tnewGen.append('F')\n\treturn newGen\n\ndef simulate(initalPopulation, generations):\n\tresults = []\n\tcP = initalPopulation\n\tfor i in range(generations):\n\t\tresults.append([cP.count('M'), cP.count('F'), cP.count('m')])\n\t\tcP = nextGen(cP)\n\treturn results","sub_path":"Bio/mucke.py","file_name":"mucke.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"410657790","text":"import json\nfrom sqlalchemy import exc, or_\nfrom marshmallow import ValidationError\nfrom flask import request, Response, make_response, current_app\nfrom flask_classful import FlaskView\nfrom app import db\n\n\ndef output_json(data, code, headers=None):\n \"\"\" Form api responses as JSON\n \"\"\"\n\n content_type = 'application/json'\n\n dumped = json.dumps(data)\n\n if headers:\n headers.update({'Content-Type': content_type})\n else:\n headers = {'Content-Type': content_type}\n\n response = make_response(dumped, code, headers)\n\n return response\n\n\nclass APIError(Exception):\n \"\"\" Exception to raise when API call errors\n\n Attributes:\n error_code -- HTML response error code to pass back.\n error_source -- value where the error occured.\n \"\"\"\n\n def __init__(self, error_code, error_source):\n self.error_code = error_code\n self.error_source = error_source\n\n\nclass ApiView(FlaskView):\n trailing_slash = False\n\n excluded_methods = ['filter_query', 'unique_filter']\n\n representations = {'application/json': output_json}\n\n def __init__(self,):\n super().__init__()\n self.model = None\n self.schema = None\n # Unique filters to check, Post, Put and Patch requets\n self.update_filter = None \n # Use tablename, otherwise overwite this for messages.\n self.model_str = None\n\n\n def filter_query(self, query, raw_filters):\n \"\"\"\n Modified version of accpeted answer from:\n https://stackoverflow.com/questions/14845196/dynamically-constructing-filters-in-sqlalchemy\n\n 1 - Split the desired filters out from filters url argument\n 2 - split each filter into the Column corresponding to the Model.Column, the filter operator and the search value\n 3 - using a lambda funciton create corresponding SQLAlchemy ORM Internal\n - https://docs.sqlalchemy.org/en/13/orm/internals.html\n 4 - Create and chain the filter(s) to the query.\n\n Example:\n import requests\n r = requests.get('http://server/api/user?filters=FirstName eq \"Jimmy\" AND LastName eq \"Bob\")\n \"\"\"\n\n for filter_ in raw_filters.split(' AND '):\n try:\n key, op, value = filter_.split(' ', maxsplit=2)\n except ValueError:\n raise APIError(400, f'Invalid filter: {filter_}')\n\n value = value.strip(\"'\")\n value = value.strip('\"')\n\n column = getattr(self.model, key, None)\n if not column:\n raise APIError(400, f'Invalid field: {key}')\n\n if op == 'in':\n values = value.split(',')\n values = [v.strip(' ') for v in values]\n filt = column.in_(values)\n else:\n try:\n attr = list(filter(lambda e: hasattr(column, f\"{e}\"), [f'{op}', f'{op}_', f'__{op}__']))[0]\n except IndexError:\n raise APIError(400, f'Invalid operation: {op}')\n if value == 'null':\n value = None\n\n filt = getattr(column, attr)(value)\n query = query.filter(filt)\n return query\n\n\n def unique_filter(self, filter_dict: dict):\n \"\"\" Create a single or set of filter for Unique fields on a model.\n\n Keyword Arguments;\n\n filter_dict: contains Model Column and value in key:value pair.\n\n If there are mulitple Unqiue fields, will return tuple in \n \n \"\"\"\n _return_filter = []\n for key,value in filter_dict.items():\n column = getattr(self.model, key)\n _filter = getattr(column, '__eq__')(value)\n _return_filter.append(_filter)\n \n if not _return_filter:\n # Always True filter to return if filter_dict fails to produce a filter\n _return_filter = (1 == 1)\n else:\n # Create an SQL 'OR' Filter for multiple fields \n if len(_return_filter) > 1:\n _return_filter = or_(*_return_filter)\n \n return _return_filter\n\n\n def index(self,) -> Response:\n \"\"\" Index route to provide list of Users \"\"\"\n args = {\n 'filters': request.args.get('filters', ''),\n 'pageSize': request.args.get('pageSize', 25),\n 'page': request.args.get('page', 1)\n }\n\n current_app.logger.info('logger test')\n if args['filters']:\n try:\n data = self.filter_query(\n query=db.session.query(self.model),\n raw_filters=args['filters'])\n except APIError as err:\n return {\"message\": err.error_source}, err.error_code\n else:\n data = db.session.query(self.model)\n \n return self.schema(many=True).jsonify(data)\n\n\n def get(self, pk_id: int) -> Response:\n \"\"\" Get method to retrieve specific record.\n \n Keyword arguments:\n pk_id -- Primary Key value of Model\n\n \"\"\"\n data = db.session.\\\n query(\n self.model).\\\n filter(\n (self.model.ID == pk_id)).\\\n first()\n \n return self.schema().jsonify(data)\n\n\n def post(self,) -> Response:\n \"\"\" POST method to create record. \"\"\"\n\n json_data = request.get_json()\n\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n\n try:\n data = self.schema().load(json_data)\n except ValidationError as err:\n return err.messages, 422\n\n update_dict = {f\"{f}\": data[f] for f in self.update_filter}\n _unq_filter = self.unique_filter(update_dict)\n\n record = db.session.\\\n query(\n self.model).\\\n filter(\n _unq_filter ).\\\n first()\n\n if record is None:\n record = self.model(\n **data)\n try:\n db.session.add(record)\n db.session.commit()\n data, response = {\"message\": f\"Created {self.model_str}\"}, 200\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n current_app.logger.exception(e)\n data, response = {\"message\": f\"Could not create {self.model_str}\"}, 200\n else:\n data, response = {\"message\": f\"{self.model_str} already exists.\"}, 200\n\n return data, response\n\n\n def put(self, pk_id) -> Response:\n \"\"\" PUT method to Update entire Record\n\n Keyword arguments:\n pk_id -- Primary Key value of record Model\n\n Note: Primary Key is created by Database Sequence, therefore\n PUT method only works when record already exists.\n Similar functionality to PATCH, but whole record needs to be\n sent in request.\n \"\"\"\n\n record_query = db.session.query(self.model).get(pk_id)\n\n # User agent should know target resource via GET request.\n if not record_query:\n return {\"message\": \"Record not found\"}, 404\n\n json_data = request.get_json()\n\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n\n try:\n data = self.schema().load(json_data)\n except ValidationError as err:\n return err.messages, 422\n\n try:\n for k, v in data.items():\n setattr(record_query, k, v)\n db.session.commit()\n data, code = {'message': f\"{self.model_str} updated.\"}, 200\n except (exc.SQLAlchemyError, TypeError):\n db.session.rollback()\n data, code = {\"message\": f\"{self.model_str} record could not be updated.\"}, 500\n\n return data, code\n\n\n def patch(self, pk_id) -> Response:\n \"\"\" Patch method to update part(s) of record model.\n\n Keyword arguments:\n pk_id -- Primary Key value of record Model\n\n Inspired by ConnectWise API.\n Patch body needs to be an array containing dict(s) of update instruction.\n Example:\n import requests\n patch = [\n {\n 'op': 'replace',\n 'path': 'FirstName',\n 'value': 'Jimmy'\n }\n ]\n\n requets.patch('http://server/api/user/1', json=patch)\n\n Update occurs similiary to PUT method, however patch doesn't require\n whole record in request. Allows for reduce bandwidth requests for larger models.\n \"\"\"\n record_query = db.session.query(self.model).filter((self.model.ID == pk_id)).first()\n\n # User agent should know target resource via GET request.\n if not record_query:\n return {\"message\": \"Record not found\"}, 404\n \n request_data = request.get_json(force=True, silent=True)\n if not request_data:\n return {'message': 'No content provided.'}, 400\n\n # Build patch from supplied data\n apply_patch = {}\n allowed_operations = (\"replace\",)\n for patch_data in request_data:\n try:\n if patch_data.get(\"op\").lower() not in allowed_operations:\n return {'message': f'Operation \"{patch_data.get(\"op\")}\" not supported.'}, 400\n except AttributeError:\n return {'message': f'Invalid operation {patch_data.get(\"op\")}.'}, 400\n\n apply_patch.update({patch_data.get('path'): patch_data.get(\"value\")})\n\n # Validate request data\n try:\n self.schema().load(apply_patch)\n except ValidationError as err:\n return {'message': err.messages}, 400\n\n try:\n for k, v in apply_patch.items():\n setattr(record_query, k, v)\n db.session.commit()\n data, code = {'message': f\"{self.model_str} updated.\"}, 200\n except (exc.SQLAlchemyError, TypeError):\n db.session.rollback()\n data, code = {\"message\": f\"{self.model_str} record could not be updated.\"}, 500\n\n return data, code\n\n \n def delete(self, pk_id) -> Response: \n \"\"\" Delete method to remove specific record.\n \n Keyword arguments:\n pk_id -- Primary Key value of Model\n\n \"\"\"\n record = db.session.query(self.model).filter((self.model.ID == pk_id)).first()\n\n if record:\n try:\n db.session.delete(record)\n db.session.commit()\n data, response = {\"message\": f\"{self.model_str} record deleted.\"}, 200\n except exc.SQLAlchemyError:\n db.session.rollback()\n data, response = {\"message\": f\"{self.model_str} record could not be deleted.\"}, 500\n else:\n data, response = {\"message\": f\"No matching {self.model_str} record.\"}, 404\n \n return data, response\n","sub_path":"app/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"491423640","text":"from youtube.face_evoLVe_PyTorch.align.YTPredictor import YTPredictor\nimport os\nimport cv2\n\n\ncurrent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))\nabsPath_to_youtube = os.path.abspath(os.path.join(current_dir, 'youtube'))\nytPredictor = YTPredictor(absPath_to_youtube=absPath_to_youtube, \\\ncast_length=8, compress_width=400, skip_frames=12, frame_range=[0,400])\n\nf = open(os.path.join(current_dir,'trailer_list.txt'),'r')\nlist_of_trailer = f.read().splitlines()\nf.close()\nprint(list_of_trailer)\ncast_list=[]\nweight_list=[]\n\nfor i in range(len(list_of_trailer)):\n path_to_video = os.path.join(current_dir, \"videos/\"+list_of_trailer[i])\n result = ytPredictor.__call__(yt_url=None, path_to_video=path_to_video)\n cast_ = [result[i][0] for i in range(len(result))]\n freq_ = [result[i][1][0] for i in range(len(result))]\n weight_ = [float(itm)/sum(freq_list) for itm in freq_]\n cast_list.append(cast_)\n weight_list.append(weight_)\n if i>2:\n break","sub_path":"code/models/test_for_video.py","file_name":"test_for_video.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"359814224","text":"import Adafruit_DHT\r\nimport datetime\r\nimport json\r\n\r\n\r\n\"Reading Data of Temperature and Humidity\"\r\n\r\nclass DHT11_Reader(object):\r\n\r\n def __init__(self):\r\n\r\n self.humidity = 0\r\n self.temperature = 0\r\n\r\n def sensorData(self):\r\n\r\n try:\r\n self.humidity, self.temperature = Adafruit_DHT.read_retry(11, 27)\r\n \"Reading Data of sensor DHT11 on PIN 27 of Raspberry\"\r\n except:\r\n print(\"ReadingDHT: ERROR IN READING THE SENSOR\")\r\n if self.humidity is not None and self.temperature is not None:\r\n get_time = datetime.datetime.now()\r\n current_time = get_time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n print('Time: ',current_time,'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(self.temperature, self.humidity))\r\n \"put all the data in a Json\"\r\n OutputJson = json.dumps({\"temperature\": self.temperature, \"humidity\": self.humidity ,\"time\":current_time})\r\n\r\n return OutputJson\r\n else:\r\n print('ReadingDHT: ERROR IN SENDING JSON')\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n \"this is for testing we use this class in the PublishTempHum class\"\r\n data_of_DHT = DHT11_Reader()\r\n while True:\r\n data_of_DHT.sensorData()\r\n","sub_path":"Progetto/Raspberry/TempandHumidity.py","file_name":"TempandHumidity.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"63075358","text":"import pandas as pd \nimport numpy as np \n\n#Set seed:\nnp.random.seed(301200)\n\n#Files:\nfolder='/gpfs3/well/win-fmrib-analysis/users/lhw539/ixi/'\nfilenames=['ixi_train','ixi_val','ixi_test']\n\nfor filename in filenames:\n filepath=folder+filename\n df=pd.read_csv(filepath+'.csv')\n \n df_female=df[df[\"Sex\"]==0]\n df_male=df[df[\"Sex\"]==1]\n\n n_female=df_female.shape[0]\n n_male=df_male.shape[0]\n \n print(\"Original data set: number of female: \", n_female)\n print(\"Original data set: number of male: \", n_male)\n\n factor=n_female/n_male\n factor_int=np.floor(factor).astype(int)\n random_share=factor-factor_int\n n_rand_choice=np.round(random_share*n_male).astype(int)\n rand_subset=np.random.permutation(n_male)[:n_rand_choice].astype(int)\n df_balanced=pd.concat([df_male.iloc[rand_subset]]+[df_male for it in range(factor_int)]+[df_female])\n print(\"Balanced values: \", np.unique(df_balanced[\"Sex\"],return_counts=True))\n new_file_path=filepath+'_balanced_'+'sex'+'.csv'\n df_balanced.to_csv(new_file_path)\n print(\"Saved to: \", new_file_path)","sub_path":"data/ixi/oversample.py","file_name":"oversample.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"283516958","text":"#!/usr/bin/env python\n# coding: utf-8\n#\n# Author: Kazuto Nakashima\n# URL: https://kazuto1011.github.io\n# Date: 07 January 2019\n\nfrom __future__ import absolute_import, division, print_function\n\nimport json\nimport multiprocessing\nimport os\nfrom pathlib import Path\n\nimport click\nimport joblib\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom omegaconf import OmegaConf\nfrom PIL import Image\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchnet.meter import MovingAverageValueMeter\nfrom tqdm import tqdm\n\nfrom libs.datasets import get_dataset\nfrom libs.models import DeepLabV2_ResNet101_MSC\nfrom libs.utils import scores\n\n\ndef makedirs(dirs):\n if not os.path.exists(dirs):\n os.makedirs(dirs)\n\n\ndef get_device(cuda):\n cuda = cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if cuda else \"cpu\")\n if cuda:\n print(\"Device:\")\n for i in range(torch.cuda.device_count()):\n print(\" {}:\".format(i), torch.cuda.get_device_name(i))\n else:\n print(\"Device: CPU\")\n return device\n\n\ndef get_params(model, key):\n # For Dilated FCN\n if key == \"1x\":\n for m in model.named_modules():\n if \"layer\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n for p in m[1].parameters():\n yield p\n # For conv weight in the ASPP module\n if key == \"10x\":\n for m in model.named_modules():\n if \"aspp\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n yield m[1].weight\n # For conv bias in the ASPP module\n if key == \"20x\":\n for m in model.named_modules():\n if \"aspp\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n yield m[1].bias\n\n\ndef resize_labels(labels, size):\n \"\"\"\n Downsample labels for 0.5x and 0.75x logits by nearest interpolation.\n Other nearest methods result in misaligned labels.\n -> F.interpolate(labels, shape, mode='nearest')\n -> cv2.resize(labels, shape, interpolation=cv2.INTER_NEAREST)\n \"\"\"\n new_labels = []\n for label in labels:\n label = label.float().numpy()\n label = Image.fromarray(label).resize(size, resample=Image.NEAREST)\n new_labels.append(np.asarray(label))\n new_labels = torch.LongTensor(new_labels)\n return new_labels\n\n\n@click.command()\n@click.option(\n \"-c\",\n \"--config-path\",\n type=click.File(),\n help=\"Dataset configuration file in YAML\",\n)\n@click.option(\n \"-m\",\n \"--model-path\",\n type=click.Path(exists=True),\n required=True,\n help=\"PyTorch model to be loaded\",\n)\n@click.option(\n \"--img-dir\", \"--img_dir\",\n type=click.Path(exists=True),\n required=True,\n help=\"Image directory\",\n)\n@click.option(\n \"--seg-dir\", \"--seg_dir\",\n type=click.Path(exists=True),\n required=True,\n help=\"Segmentation directory\",\n)\n@click.option(\n \"--cuda/--cpu\", default=True, help=\"Enable CUDA if available [default: --cuda]\"\n)\ndef main(config_path, model_path, cuda, img_dir, seg_dir):\n \"\"\"\n Evaluation on validation set\n \"\"\"\n config_path = Path(os.path.dirname(os.path.realpath(__file__))) /'cocostuff164k.yaml'\n # Configuration\n CONFIG = OmegaConf.load(config_path)\n device = get_device(cuda)\n torch.set_grad_enabled(False)\n\n # Dataset\n dataset = get_dataset(CONFIG.DATASET.NAME)(\n root=CONFIG.DATASET.ROOT,\n split=CONFIG.DATASET.SPLIT.VAL,\n ignore_label=CONFIG.DATASET.IGNORE_LABEL,\n mean_bgr=(CONFIG.IMAGE.MEAN.B, CONFIG.IMAGE.MEAN.G, CONFIG.IMAGE.MEAN.R),\n augment=False,\n img_dir=img_dir,\n seg_dir=seg_dir,\n )\n print(dataset)\n\n # DataLoader\n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=CONFIG.SOLVER.BATCH_SIZE.TEST,\n num_workers=CONFIG.DATALOADER.NUM_WORKERS,\n shuffle=False,\n )\n\n # Model\n model = eval(CONFIG.MODEL.NAME)(n_classes=CONFIG.DATASET.N_CLASSES)\n state_dict = torch.load(model_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(state_dict)\n model = nn.DataParallel(model)\n model.eval()\n model.to(device)\n\n # Path to save logits\n logit_dir = os.path.join(\n CONFIG.EXP.OUTPUT_DIR,\n \"features\",\n CONFIG.EXP.ID,\n CONFIG.MODEL.NAME.lower(),\n CONFIG.DATASET.SPLIT.VAL,\n \"logit\",\n )\n makedirs(logit_dir)\n print(\"Logit dst:\", logit_dir)\n\n # Path to save scores\n save_dir = os.path.join(\n CONFIG.EXP.OUTPUT_DIR,\n \"scores\",\n CONFIG.EXP.ID,\n CONFIG.MODEL.NAME.lower(),\n CONFIG.DATASET.SPLIT.VAL,\n )\n makedirs(save_dir)\n save_path = os.path.join(save_dir, \"scores.json\")\n print(\"Score dst:\", save_path)\n\n preds, gts = [], []\n for image_ids, images, gt_labels in tqdm(\n loader, total=len(loader), dynamic_ncols=True\n ):\n # Image\n images = images.to(device)\n\n # Forward propagation\n logits = model(images)\n\n # Save on disk for CRF post-processing\n for image_id, logit in zip(image_ids, logits):\n filename = os.path.join(logit_dir, image_id + \".npy\")\n np.save(filename, logit.cpu().numpy())\n\n # Pixel-wise labeling\n _, H, W = gt_labels.shape\n logits = F.interpolate(\n logits, size=(H, W), mode=\"bilinear\", align_corners=False\n )\n probs = F.softmax(logits, dim=1)\n labels = torch.argmax(probs, dim=1)\n\n preds += list(labels.cpu().numpy())\n gts += list(gt_labels.numpy())\n # Pixel Accuracy, Mean Accuracy, Class IoU, Mean IoU, Freq Weighted IoU\n score = scores(gts, preds, n_class=CONFIG.DATASET.N_CLASSES)\n\n with open(save_path, \"w\") as f:\n json.dump(score, f, indent=4, sort_keys=True)\n print(score)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"deeplab/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"136540224","text":"import argparse\n\n### Setup argument parser ###\n\nparser = argparse.ArgumentParser(description=\"\"\"\nWelcome to CYAMESE: training a model that learns an individual's cytometry\nfingerprint. This is a program made as a rotation project by George\nHartoularos in Atul Butte's lab at University of California, San Francisco.\n\nThe input is a series of studies done at Stanford in Mark Davis' group in \nwhich CYTOF data was collected from the peripheral blood cells of patients \nbefore being vaccinated for influenza. Because it is pre-vaccination, this\nrepresents a patient in their \"healthy\" state. The idea is that by treating\nthese flow cytometry data as \"images\" of a person, we can learn what that\nindividual looks like simply based on their cytometry profile.\n\nRight now the program only takes in those studies as input, but will \neventually generalize to any flow/gene expression data. The program is still\nbeing developed and is not ready to make accurate predictions.\n\nThis is made for python2 and uses the Keras machine learning framework \nwith TensorFlow as backend.\n\n\"\"\", formatter_class=argparse.RawTextHelpFormatter)\n\nparser.add_argument('f', metavar='pathtofcs', type=str,\n help='location of fcs files with metadata pickle')\n\nparser.add_argument('-o',metavar='output_file',type=str, default=None,\n help='name of output folder with pickled datasets' + \n ' (default=results)')\n\nparser.add_argument('-s', metavar='subset', type=int, default=-1,\n help='random subset of files to use for training ' + \n '(default: use all)')\n\nparser.add_argument('-e', metavar='epochs', type=int, default=100,\n help='number of epochs to train (default=100) ')\n\nparser.add_argument('-nc', metavar='numcells', type=int, default=1500,\n help='number of cells per \"image\" of individual ' + \n '(default=1500)')\n\nparser.add_argument('-tr', metavar='trainloops', type=int, default=300,\n help='number of image pairs per subject for training ' + \n '(defaults=300)')\n\nparser.add_argument('-te', metavar='testloops', type=int, default=300,\n help='number of image pairs per subject for testing ' + \n '(defaults=300)')\n\nparser.add_argument('--lb', action='store_false', default=True,\n help='option to print loading bar (default: on)')\n\nparser.add_argument('--gpu', action='store_true', default=False,\n help='option if running on GPU (default: off)')\n\n\nargs = parser.parse_args() # Parse arguments\n\npathtofcs = args.f\noutput = args.o\nrand_subset = args.s\nepochs = args.e\nnumcells = args.nc\ntrainloops = args.tr\ntestloops = args.te\nloadbar = args.lb\ngpu_switch = args.gpu\n\n'''\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~TODO:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSprinkle exceptions throughout all scripts to catch inputs if they are\nnot of the right type.\n\nFigure out why I'm getting the:\nUserWarning: text in segment does not start and end with delimiter\nwarning from fcm when I use all of the data; occurs towards the beginning\n\nMake a separate script for just acquiring the data that uses the API.\n\nEventually, make the testing be only from a new subject, see if it can be \nused to recognize new patients off the bat. There will be two testing sets.\nOne asks can we recognize the same subject from the training. The other, \ncooler more important question: can we recognize a new patient that \nwasn't even trained on at all?\n\n\n'''\n\n# Imports\nimport itertools as it\nimport os\nimport cPickle as pkl\nprint(\"Welcome to CYAMESE: training a model that learns an individual's\\\n cytometry fingerprint. Beginning program.\")\n\nimport tensorflow as tf\n\nfrom metautils import makemeta\nfrom markers import setmarkers\nfrom createpairs import generatedicts, pairandsplit, testpairs\n\n###########################################################################\n'''\nQuick input check\n'''\nif pathtofcs[-1] != '/': # add the forward slash if it's not there\n pathtofcs += '/'\nif not os.path.exists(pathtofcs): # Confirm that meta path exists\n print('Supplied pathtofcs does not exist. Try again.')\n raise SystemExit\n'''\nThe training regimen is only using data from Mark Davis' study\nfrom Stanford. The chosen studies are shown below. Despite the \nnumbering, they are in chronological order. The dictionary\n\"studdict\" is used to index the studies according to chronology.\nThe \"split\" variable splits the studies into training and testing.\nThe training data is based *only* on the first two years, while the\ntesting data uses all three years.\n\nSplit is a tuple of exactly two tuples that dictates what data will \nbe used for training and testing. The first tuple is training and the\nsecond is testing. Training tuple will compare two different studies\nto eachother to create positive pairs (the same subject in SDY311 and\nSDY112) and negative pairs (different subjects in the same or different \nstudies).\n'''\n\nstudies = ['SDY311', 'SDY112', 'SDY315']\nstuddict = dict(zip(range(3),studies))\nsplit = (('SDY311', 'SDY112'), ('SDY315',))\n\n'''\nThe \"TIME\" channel in the flow data is an irrelevant parameter, not\nso much a phenotype of the cells but only useful for troubleshooting\nexperimentation. It will be ignored.\n'''\n\nignorechan = ['TIME'] # images will not contain this channel\n\n'''\nmakemeta takes the metadata file (a pickled pandas dataframe) located\nin the directory created from the apidownload script, and unpickles it.\nIf a random number of subjects has been specified, it only extracts the\ndata from those subjects.\n'''\nprint(\"Making meta data file.\")\nmeta, numsubs = makemeta(pathtofcs, studies, studdict, rand_subset)\n\nfiles = list(meta['filename'])\n\n'''\nsetmarkers makes a set of unique markers common to all the flow cytometry\ndata files. It will ignore any channels fed in by ignorechan and also \ncheck that there are at least 20 markers to learn from.\n'''\nprint(\"Extracting out common markers from flow data.\")\nmarkerset = setmarkers(pathtofcs, files, ignorechan=ignorechan)\n\n'''\ngeneratedicts generates dictionaries that have subject/study pairs as\nkeys and a numpy array of the cells x markers data as the value. It ensures\nthat the flow data have the markers all in the same order. It also splits\nthe data into train and test such that, although data from the same\nsubject/study might be used in both training and testing, that the same data\nfrom an individual cell is not reused.\n'''\nprint(\"Generating dictionaries with the data.\")\nalltrain, alltest = generatedicts(studies, numsubs, files, pathtofcs, \n markerset, split, loadbar)\n\n'''\npairandsplit is the main workhorse of the data formatting. It takes random \nimages from a person's flow data and pairs it with either the same person's \nflow data from a different study (positive pair) or a different person's flow \ndata from the same or different year (negative pair). Depending on how many\nloops are used, it might need to reuse cells; it does this in such a way that\nit never reuses the same cell before using all others first. The most \nimportant part is that it doesnt not bias the training towards any one \nindividual or class: there is a roughly equal representation of positive and\nnegative pairs, of individuals, of studies, and of cells.\n'''\npairandsplit(alltrain, alltest, numcells, \n trainloops, testloops, split, loadbar)\n","sub_path":"cyamese_scripts/generatepkls.py","file_name":"generatepkls.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"345361548","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\n#from config import remote_db_endpoint, remote_db_port\n#from config import remote_gwsis_dbname, remote_gwsis_dbuser, remote_gwsis_dbpwd\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\n\nfrom flask import Flask, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\nremote_db_endpoint=os.environ['remote_db_endpoint']\nremote_db_port=os.environ['remote_db_port']\nremote_gwsis_dbname=os.environ['remote_gwsis_dbname']\nremote_gwsis_dbuser=os.environ['remote_gswis_dbuser']\nremote_gwsis_dbpwd=os.environ['remote_gwsis_dbpwd']\napiKey=os.environ['quandlkey']\nAPI_KEY=os.environ['mapboxkey']\n\napp = Flask(__name__)\n\n\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"mysql+pymysql://root:{remote_gwsis_dbpwd}@codingbootcamp.ctxjv3tnsa2p.us-east-2.rds.amazonaws.com/gwsis\"\ndb = SQLAlchemy(app)\n\nBase = automap_base()\nBase.prepare(db.engine, reflect=True)\n\ndata_base_table = Base.classes.earnings\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/map\")\ndef map_visual():\n return render_template(\"map.html\")\n\n@app.route(\"/charts\")\ndef chart_visual():\n return render_template(\"charts.html\")\n \n@app.route(\"/data\")\ndef table():\n return render_template(\"data.html\")\n\n@app.route(\"/regression\")\ndef regression():\n return render_template(\"regression.html\")\n\n@app.route(\"/x\")\ndef samples():\n \n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n data = df.to_dict()\n\n return (\n jsonify(data)\n )\n\n@app.route(\"/list\")\ndef list_data():\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n data_list = {\n \"Index\": df.level_0.values.tolist(),\n \"Stock\": df['Stock Name'].values.tolist(),\n \"Reported Date\": df['Reported Date'].values.tolist(),\n \"Earnings Per Share\": df['Earnings Per Share'].values.tolist(),\n \"Forecasted Earnings Per Share\": df['Forecasted Earnings Per Share'].values.tolist(),\n \"% Surprise\": df['% Surprise'].values.tolist()\n }\n return (\n jsonify(data_list)\n )\n\n@app.route(\"/dict\")\ndef list_dict():\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n list_dict = []\n for index, row in df.iterrows():\n x = {\"Index\": row['level_0'],\n \"Stock Name\": row['Stock Name'],\n \"Reported Date\": row['Reported Date'],\n \"Earnings Per Share\": row['Earnings Per Share'],\n \"Forecasted Earnings Per Share\": row['Forecasted Earnings Per Share'],\n \"% Surprise\": row['% Surprise'],}\n list_dict.append(x)\n\n return(jsonify(list_dict))\n\n@app.route(\"/names\")\ndef names():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n return jsonify(list(df.columns)[2:])\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"364579740","text":"from tkinter import *\nimport members as members\nimport books as books\n\nroot = Tk()\n\nclass Welcome():\n\n def __init__(self, master):\n\n ## master setting\n self.master=master\n self.master.geometry('850x650+400+200')\n self.master.title('Welcome')\n\n ## menu pannel\n self.menu_pannel=Frame(self.master, width=20, height=100)\n self.menu_pannel.grid(row=0,column=0, sticky=N)\n\n self.label1=Label(self.menu_pannel, text='하정글방 관리 프로그램 for Dad', fg='green').grid(row=0, column=1, padx=3, pady=3)\n\n self.button_list=[]\n self.button1 = Button(self.menu_pannel, text='회원관리',fg='blue', height=3, width=15, command=self.gotoMembers)\n self.button1.grid(row=1,column=1, padx=3, pady=10)\n self.button_list.append(self.button1)\n\n self.button2 = Button(self.menu_pannel, text='도서관리',fg='blue', height=3, width=15, command=self.gotoBooks)\n self.button2.grid(row=2,column=1,padx=3, pady=10)\n self.button_list.append(self.button2)\n\n self.button3 = Button(self.menu_pannel, text='대여관리',fg='blue', height=3, width=15)\n self.button3.grid(row=3,column=1,padx=3, pady=10)\n self.button_list.append(self.button3)\n\n self.button4 = Button(self.menu_pannel, text='끝내기',fg='blue', height=3, width=15, command=self.finish)\n self.button4.grid(row=4, column=1,padx=3, pady=10)\n self.button_list.append(self.button4)\n\n ## function pannel\n self.function_pannel=Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n\n def set_button_free(self):\n for button in self.button_list:\n button.configure(relief=RAISED)\n\n def gotoMembers(self):\n self.set_button_free()\n self.button1.configure(relief=SUNKEN)\n\n self.function_pannel.grid_forget()\n self.function_pannel.destroy()\n self.function_pannel=Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n myGUI=members.Members(self.function_pannel)\n\n\n def gotoBooks(self):\n self.set_button_free()\n self.button2.configure(relief=SUNKEN)\n\n self.function_pannel.grid_forget()\n self.function_pannel.destroy()\n self.function_pannel = Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n myGUI=books.Books(self.function_pannel)\n\n\n def finish(self):\n self.master.destroy()\n\ndef main():\n myGUIWelcome=Welcome(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"441197804","text":"import unittest\nfrom Model.DatabaseConfiguration import TestConnection\nimport psycopg2\nimport Controller.TableTransformer as transformer\n\n#This file contains tests for TableTransformer that specifically creates new tables when transforming. This tests data manipulation methods of TableTransformer\n#For the tests on data manipulation methods of TableTransformer that don't copy but overwrite the tables refer to \"test_TableTransformer.py\"\n\nclass TestTransformerCopy(unittest.TestCase):\n db_connection = None\n engine = None\n test_object = None\n\n @classmethod\n def setUpClass(cls):\n cls.db_connection = TestConnection().get_db()\n cls.engine = TestConnection().get_engine()\n cls.test_object = transformer.TableTransformer(0, cls.db_connection, cls.engine, False, False)\n cur = cls.db_connection.cursor()\n cur.execute('CREATE SCHEMA IF NOT EXISTS \"0\"')\n cls.db_connection.commit()\n creation_query = \"\"\"CREATE TABLE \"0\".test_table (\n string VARCHAR(255) NOT NULL,\n number INTEGER NOT NULL,\n date_time VARCHAR(255) NOT NULL,\n garbage VARCHAR(255));\"\"\"\n creation_query1 = 'CREATE TABLE \"0\".test_table1 AS TABLE \"0\".test_table'\n creation_query2 = 'CREATE TABLE \"0\".test_table2 AS TABLE \"0\".test_table'\n #In some cases the test fails in a way that tearDownClass is not called and the table still exists\n #Sadly we can't confirm if the table is still correct, because of transformations performed on it\n try:\n cur.execute(creation_query)\n\n except psycopg2.ProgrammingError:\n #If it was still present in the database we better drop the schema and rebuild it\n cls.db_connection.rollback()\n cur.execute('DROP SCHEMA \"0\" CASCADE')\n cur.execute('CREATE SCHEMA \"0\"')\n cls.db_connection.commit()\n cur.execute(creation_query)\n cls.db_connection.commit()\n \n \n values = [('C-Corp', 1, '08/08/1997'), ('Apple', 22, '01/04/1976'), ('Microsoft', 8, '04/04/1975') , ('Nokia', 18, '12/05/1865') ,\n ('Samsung', 7, '01/03/1938'),('Huawei', 10, '15/09/1987'), ('Razer', 3, '01/01/1998'),\n ('Imagine Breakers', 14, '21/09/1996'), ('Sony', 9, '07/05/1946'), ('Asus', 12, '02/04/1989'),\n ('Hewlett-Packard', 5, '01/01/1939'), ('Toshiba', 8, '01/07/1975'), ('LG Electronics', -3, '01/10/1958'),\n ('Nintendo', 21, '23/09/1989'), ('Elevate ltd', 41, '08/08/1997'), ('Dummy', -17, '01/07/1975')]\n\n for v in values:\n cur.execute('INSERT INTO \"0\".test_table VALUES(%s, %s, %s)', v)\n\n cur.execute(creation_query1)\n cur.execute(creation_query2)\n cur.execute('UPDATE \"0\".test_table1 SET number = null WHERE number > 40')\n\n \n cls.db_connection.commit()\n\n @classmethod\n def tearDownClass(cls):\n cls.db_connection.cursor().execute('DROP SCHEMA \"0\" CASCADE')\n cls.db_connection.commit()\n #Close database connection\n cls.db_connection.close()\n\n\n def __test_table_exists(self, tablename):\n \"\"\"Test whether a table exists in the test schema after performing a operation that should create new table in the schema.\"\"\"\n cur = self.db_connection.cursor()\n cur.execute('SELECT table_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s ', ['0', tablename])\n result = cur.fetchone()\n if result is None:\n return False\n else:\n return True\n \n\n def test_delete_attribute(self):\n \"\"\"Test to see if TableTransformer can correctly delete an attribute resulting in a new table.\"\"\"\n self.test_object.delete_attribute('test_table', 'garbage', 'new_table1') #Delete attribute \"garbage\"\n #Now the only attributes should be \"string\", \"number\", \"date_time\"\n cur = self.db_connection.cursor()\n result = self.__test_table_exists('new_table1')\n self.assertTrue(result)\n #Let's see if we can find the deleted attribute\n cur.execute(\"\"\"SELECT column_name FROM information_schema.columns WHERE table_schema = '0'\n AND table_name = 'new_table1'\"\"\")\n tablenames = cur.fetchall()\n found = False\n for name in tablenames:\n if name[0] == 'garbage':\n found = True\n\n #Assert if it is in fact not found amongst remaining tablenames\n self.assertEqual(found, False)\n self.db_connection.commit()\n\n def test_find_and_replace(self):\n \"\"\"A test for the find and replace method resulting in a new table.\"\"\"\n self.test_object.find_and_replace('test_table','string', 'C-Corp', 'Replacement', new_name='new_table2')\n result = self.__test_table_exists('new_table2')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table2 WHERE string = 'Replacement'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 1)\n self.assertEqual(result[2], '08/08/1997')\n self.db_connection.commit()\n\n def test_find_and_replace_string(self):\n \"\"\"A test for find and replace method but for finding substrings resulting in a new table.\"\"\"\n #Find a word with substring Sam and replace the whole word with Foobar\n self.test_object.find_and_replace('test_table', 'string', 'Sam', 'Foobar', False, True, 'new_table3')\n result = self.__test_table_exists('new_table3')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table3 WHERE string = 'Foobar'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 7)\n self.assertEqual(result[2], '01/03/1938')\n\n #Find a word with substring To and replace the substring only with Waka\n self.test_object.find_and_replace('test_table', 'string', 'To', 'Waka', False, False, 'new_table4')\n result = self.__test_table_exists('new_table1')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table4 WHERE string = 'Wakashiba'\")\n result = cur.fetchone()\n #We found Toshiba but replaced To with Waka to get Wakashiba\n self.assertEqual(result[1], 8)\n self.assertEqual(result[2], '01/07/1975')\n\n def test_regex_find_and_replace(self):\n \"\"\"A test for the method of TableTransformer that uses regular expressions. This will result in a new table.\"\"\"\n #Use a regular expression to find Nintendo and replace it with SEGA\n self.test_object.regex_find_and_replace('test_table', 'string', 'Nin.*', 'SEGA', False, 'new_table5')\n result = self.__test_table_exists('new_table5')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table5 WHERE string = 'SEGA'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 21)\n self.assertEqual(result[2], '23/09/1989')\n\n #Use the regex to find a word without case sensitivity\n self.test_object.regex_find_and_replace('new_table5', 'string', 'sega', 'SEGA', False, 'new_table6')\n result = self.__test_table_exists('new_table6')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table6 WHERE string = 'SEGA'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 21)\n self.assertEqual(result[2], '23/09/1989')\n\n #Use the regex to find a word with case sensitivity\n self.test_object.regex_find_and_replace('new_table6', 'string', 'sega', 'Ethereal', True, 'new_table7')\n result = self.__test_table_exists('new_table7')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table7 WHERE string = 'Ethereal'\")\n result = cur.fetchone()\n self.assertIsNone(result) #Shouldn't be able to find out due the difference in case\"\"\"\n\n def test_numeric_conversion(self):\n \"\"\"Test the conversion of numeric types (INTEGER, FLOAT). This will result in a new table.\"\"\"\n #From integer to float\n self.test_object.change_attribute_type('test_table', 'number', 'FLOAT', new_name='new_table8')\n result = self.__test_table_exists('new_table8')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table8\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'double precision')\n #From float to integer\n self.test_object.change_attribute_type('new_table8', 'number', 'INTEGER', new_name='new_table9')\n result = self.__test_table_exists('new_table9')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table9\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'integer')\n #From integer to VARCHAR(255)\n self.test_object.change_attribute_type('test_table', 'number', 'VARCHAR(255)', new_name='new_table10')\n result = self.__test_table_exists('new_table10')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table10\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'character varying')\n\n def test_character_conversion(self):\n \"\"\"Test the conversion of character types. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n #Make it into a varchar for testing purposes\n self.test_object.change_attribute_type('test_table', 'number', 'VARCHAR(255)', new_name='new_table11')\n result = self.__test_table_exists('new_table11')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table11\")\n result = cur.fetchone()[0]\n self.assertEqual(result,'character varying')\n\n self.test_object.change_attribute_type('new_table11', 'number', 'FLOAT', new_name='new_table12')\n result = self.__test_table_exists('new_table12')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table12\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'double precision')\n \n #Change to varchar(30)\n self.test_object.change_attribute_type('new_table12', 'number', 'VARCHAR(n)', \"\", '30', new_name='new_table13')\n result = self.__test_table_exists('new_table13')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table13\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'character varying')\n \n def test_datetime_conversion(self):\n \"\"\"Test the conversion of an attribute to a date/time type. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n #Convert date_string column to actual DATE type\n self.test_object.change_attribute_type('test_table', 'date_time', 'DATE', 'DD/MM/YYYY', new_name='new_table14')\n result = self.__test_table_exists('new_table14')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(date_time) FROM \"0\".new_table14')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'date')\n self.db_connection.commit()\n #Convert the same column to a timestamp\n self.test_object.change_attribute_type('test_table', 'date_time', 'TIMESTAMP', 'DD/MM/YYYY TIME', new_name='new_table15')\n result = self.__test_table_exists('new_table15')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(date_time) FROM \"0\".new_table15')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'timestamp without time zone')\n self.db_connection.commit()\n #Set date_string of another to a time string and try to convert it\n query_1 = 'UPDATE \"0\".test_table SET garbage = \\'08:42 PM\\' WHERE garbage is NULL'\n cur.execute(query_1)\n self.test_object.change_attribute_type('test_table', 'garbage', 'TIME', 'HH12:MI AM/PM', new_name='new_table16')\n result = self.__test_table_exists('new_table16')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(garbage) FROM \"0\".new_table16')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'time without time zone')\n self.db_connection.commit()\n\n def test_one_hot_encode(self):\n \"\"\"Test the one-hot-encoding method for a column with unique and duplicate values. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.one_hot_encode('test_table', 'string', 'new_table17')\n result = self.__test_table_exists('new_table17')\n self.assertTrue(result)\n #Query to get all columns from the encoded table\n query = (\"SELECT column_name FROM information_schema.columns \"\n \"WHERE table_schema = '0' AND table_name = 'new_table17'\")\n cur.execute(query)\n all_columns = cur.fetchall()\n #This should be all the columns\n expected = ['number', 'date_time', 'garbage', 'Apple', 'Asus', 'Dummy', 'Elevate ltd',\n 'Hewlett-Packard', 'Huawei', 'Imagine Breakers', 'LG Electronics', 'Microsoft', 'Nintendo', 'Nokia', 'Razer',\n 'C-Corp', 'Samsung', 'Sony', 'Toshiba']\n \n for element in expected: #Test if expected elements are part of the table\n test_result = (element,) in all_columns\n self.assertTrue(test_result)\n #There should 22 columns, 3 previous one + 16 unique categories \n self.assertEqual(len(all_columns), 19)\n self.db_connection.commit()\n\n def test_equidistant_discretization(self):\n \"\"\"Test the equidistant discretization method. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.discretize_using_equal_width('test_table', 'number', 4, 'new_table18')\n result = self.__test_table_exists('new_table18')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table18')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n #There should be 3 buckets.\n self.assertEqual(len(all_values), 4)\n all_values = sorted(all_values)\n expected_values = ['[-17 , -2[', '[-2 , 13[', '[13 , 28[', '[28 , 43[']\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < -2 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -2[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < 13 AND number > -2 '\n 'AND number_categorical <> \\'[-2 , 13[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < 43 AND number > 28 '\n 'AND number_categorical <> \\'[28 , 43[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n def test_equifrequent_discretization(self):\n \"\"\"Test the equifrequent discretization method. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.discretize_using_equal_frequency('test_table', 'number', 'new_table19')\n result = self.__test_table_exists('new_table19')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table19')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , 4[', '[15 , 42[', '[4 , 9[', '[9 , 15[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < -4 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -4[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < 9 AND number > 4 '\n 'AND number_categorical <> \\'[4 , 9[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < 42 AND number > 15 '\n 'AND number_categorical <> \\'[15 , 42[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n def test_discretization_with_custom_ranges(self):\n \"\"\"Test the discretization with custom ranges method. This will result in a new table.\"\"\"\n #Let's simulate equidistant discretization with our custom bins.\n cur = self.db_connection.cursor()\n ranges = [-17, -2, 13, 28, 43]\n #self.test_object.set_to_overwrite()\n self.test_object.discretize_using_custom_ranges('test_table', 'number', ranges, True, 'new_table20')\n result = self.__test_table_exists('new_table20')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table20')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , -2[', '[-2 , 13[', '[13 , 28[', '[28 , 43[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table20 WHERE number < -2 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -2[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table20 WHERE number < 43 AND number > 28 '\n 'AND number_categorical <> \\'[28 , 43[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n #Let's simulate equifrequent discretization with our custom bins.\n ranges = [-17, 4, 9, 15, 42]\n self.test_object.discretize_using_custom_ranges('test_table', 'number', ranges, True, 'new_table21')\n result = self.__test_table_exists('new_table21')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table21')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , 4[', '[15 , 42[', '[4 , 9[', '[9 , 15[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n cur.execute('SELECT * FROM \"0\".new_table21 WHERE number < -4 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -4[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table21 WHERE number < 42 AND number > 15 '\n 'AND number_categorical <> \\'[15 , 42[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n \n def test_delete_outliers(self):\n \"\"\"Test the method of TableTransformer to delete outliers. This will result in a new table.\"\"\"\n #Test outliers larger than presented value\n cur = self.db_connection.cursor()\n self.test_object.delete_outliers('test_table', 'number', True, 40, 0, 'new_table22')\n result = self.__test_table_exists('new_table22')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table22 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n self.test_object.delete_outliers('test_table', 'number', True, 20, 0, 'new_table23')\n result = self.__test_table_exists('new_table23')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table23 WHERE number > 20')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n #Test outliers smaller than presented value\n self.test_object.delete_outliers('test_table', 'number', False, -15, 0, 'new_table24')\n result = self.__test_table_exists('new_table24')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table24 WHERE number < -15')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n self.test_object.delete_outliers('test_table', 'number', False, 0, 0, 'new_table25')\n result = self.__test_table_exists('new_table25')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table25 WHERE number < 0')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n \n def test_fill_nulls_with_mean(self):\n \"\"\"Test the method of TableTransformer that fills null values with the mean. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_mean('test_table1', 'number', 'new_table26')\n result = self.__test_table_exists('new_table26')\n self.assertTrue(result)\n #Test if it's really set to null\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n #Test whether any nulls are left open\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number is null')\n result = cur.fetchone()\n self.assertIsNone(result)\n #The mean by excluding values > 40 is 10 (cast to int), let's check if the value is here\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number = 10 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n self.assertEqual(1,1)\n \n def test_fill_nulls_with_median(self):\n \"\"\"Test the method of TableTransformer that fills null values with the median. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_median('test_table1', 'number', 'new_table27')\n result = self.__test_table_exists('new_table27')\n self.assertTrue(result)\n #Test if it's really set to null\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n #Test whether any nulls are left open\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number is null')\n result = cur.fetchone()\n self.assertIsNone(result)\n #The median by excluding values > 40 is 9, let's check if the value is here\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number = 9 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n \n def test_fill_nulls_with_custom_value(self):\n \"\"\"Test the method of TableTransformer that fills null values with a custom value.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_custom_value('test_table1', 'number', 10000, 'new_table28')\n result = self.__test_table_exists('new_table28')\n self.assertTrue(result)\n #The value we used should correspond to the row with string = 'Dummy'\n cur.execute('SELECT * FROM \"0\".new_table28 WHERE number = 10000 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n \n def test_delete_rows_using_conditions(self):\n \"\"\"Test method of TableTransformer deletes rows by using provided predicates. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n predicate1 = ['string', '=', 'C-Corp']\n self.test_object.delete_rows_using_predicate_logic('test_table', predicate1, 'new_table29')\n result = self.__test_table_exists('new_table29')\n self.assertTrue(result)\n query = \"SELECT * FROM \\\"0\\\".new_table29 WHERE string = 'C-Corp'\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNone(result)\n\n predicate2 = ['string', '=', 'Nokia', 'AND', 'number', '=', '18', 'AND', 'date_time', '!=', '01/01/2001']\n self.test_object.delete_rows_using_predicate_logic('test_table', predicate2, 'new_table30')\n result = self.__test_table_exists('new_table30')\n self.assertTrue(result)\n query = \"SELECT * FROM \\\"0\\\".new_table30 WHERE string = 'Nokia' AND number = 18\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNone(result)\n \n def test_datetime_extraction(self):\n \"\"\"This one is for testing the extraction of parts of the date/time done by TableTransformer. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n cur.execute('ALTER TABLE \"0\".test_table2 ALTER COLUMN date_time TYPE DATE USING to_date(date_time , \\'DD/MM/YYYY\\')')\n self.test_object.extract_part_of_date('test_table2', 'date_time', 'MONTH', 'new_table31')\n result = self.__test_table_exists('new_table31')\n self.assertTrue(result)\n #Get all the column names for the table\n query = (\"SELECT column_name FROM information_schema.columns \"\n \"WHERE table_schema = '0' AND table_name = 'new_table31'\")\n cur.execute(query)\n all_columns = cur.fetchall()\n result = False\n \n for elem in all_columns:\n if elem[0] == 'date_time_part':\n result = True\n\n self.assertTrue(result)\n\n query = \"SELECT * FROM \\\"0\\\".new_table31 WHERE number = 21 AND date_time_part = 'September'\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNotNone(result)\n self.assertEqual(result[0], 'Nintendo')\n","sub_path":"client/unit_tests/test_TableTransformerCopy.py","file_name":"test_TableTransformerCopy.py","file_ext":"py","file_size_in_byte":26409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"158403572","text":"from datetime import datetime;\nfrom os.path import isfile as isFile;\n\nclass Logger:\n\n def __init__(self, log_filename_postfix = \"log\", log_filename_extension = \"log\", path_to_log = \".\"):\n\n self.log_filename_postfix = log_filename_postfix;\n self.log_filename_extension = log_filename_extension;\n self.path_to_log = path_to_log;\n self.initLogFile();\n\n return None;\n\n def initLogFile(self, log_filename_postfix = None, \\\n log_filename_extension = None, \\\n path_to_log = None):\n \"\"\" PRIVATE \"\"\"\n\n if not log_filename_postfix:\n log_filename_postfix = self.log_filename_postfix;\n\n if not log_filename_extension:\n log_filename_extension = self.log_filename_extension;\n\n if not path_to_log:\n path_to_log = self.path_to_log;\n\n self.the_day = self.timeStamp()[:10];\n self.log_file_name = \"{}/{}_{}.{}\".\\\n format(\n path_to_log,\n self.the_day,\n log_filename_postfix,\n log_filename_extension\n );\n if not isFile(self.log_file_name):\n self.writeDown(\"The log file created. \\n ----------------------------------------------- \\n\\n\");\n\n def timeStamp(self, digits_after_dot = 2):\n \"\"\" PRIVATE \"\"\"\n full_string_of_time_stamp = str(datetime.now());\n\n if digits_after_dot >= 6:\n string_of_time_stamp = full_string_of_time_stamp;\n else:\n if digits_after_dot <=0:\n cut_mark = -7;\n else:\n cut_mark = digits_after_dot - 6;\n string_of_time_stamp = full_string_of_time_stamp[:cut_mark];\n\n return string_of_time_stamp;\n\n def writeDown(self, message_string):\n\n the_timestamp = self.timeStamp();\n the_day = the_timestamp[:10];\n if the_day != self.the_day:\n self.initLogFile();\n\n log_string = \"{}: {} \\n\\n\".\\\n format(\n self.timeStamp(),\n message_string\n );\n\n print(log_string);\n with open(self.log_file_name, \"a\") as log_file:\n log_file.write(log_string);\n\n return None;\n","sub_path":"rhythmic/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573262261","text":"import configparser,tweepy,string\n\nclass tweets_dld:\n #global variables for twitter API authentication \n c_key = ''\n c_secret = ''\n a_token = ''\n a_secret = ''\n query_hashtags = ''\n\n def __init__(self):\n #read auth variables from config file\n config = configparser.RawConfigParser()\n config.read('auth_secrets.properties')\n global c_key,c_secret,a_token,a_secret,query_hashtags\n '''c_key = config.get('OAUTH_SECRETS FOR TWITTER DEV','CONSUMER_KEY')\n c_secret = config.get('OAUTH_SECRETS FOR TWITTER DEV','CONSUMER_SECRET') \n a_token = config.get('OAUTH_SECRETS FOR TWITTER DEV','ACCESS_TOKEN')\n a_secret = config.get('OAUTH_SECRETS FOR TWITTER DEV','ACCESS_SECRET')\n\n #hashtags or twitter handles to be searched for \n query_hashtags = config.get('INPUTS FOR COMMAND_LINE','TWITTER_HASHTAGS')'''\n c_key = 'VasRnWFD11likduxgFlMVDtbb'\n c_secret = 'fhMWY43TKctq9F75FjUF132kDOdlNpxDPRdYUSl0hB4gHJWXFL'\n a_token = '1193177629-XCk9qe8vvazKzL5dx6tJWoOU8uNfftJWczD3n2x'\n a_secret = 'yTZi285mwLZJ2LJjh51c6AvkcnfbptJxgjQUQjBKgY8jW'\n \n query_hashtags = '#sunRail OR ExpandSunRail OR sunRail OR Sunrailriders OR RideSunRail OR #RideSunRail OR #Ridesunrail +exclude:retweets'\n\n def gather_tweets(self):\n #print('reached tweet download')\n #authenticate twitter API access using the credentials populated above\n auth = tweepy.auth.OAuthHandler(c_key, c_secret)\n auth.set_access_token(a_token, a_secret)\n api = tweepy.API(auth)\n\n # initialize a list to hold all the tweepy Tweets\n alltweets = []\n\n # make initial request for most recent tweets (200 is the maximum allowed count)\n new_tweets = api.search(q=query_hashtags, count=10)\n #print(new_tweets)\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # save the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n # keep grabbing tweets until there are no tweets left to grab\n while len(new_tweets) > 0:\n #print(\"getting tweets before %s\" % (oldest))\n\n # all subsiquent requests use the max_id param to prevent duplicates\n new_tweets = api.search(q=query_hashtags, max_id=oldest)\n #print(new_tweets)\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # update the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n #print(\"...%s tweets downloaded so far\" % (len(alltweets)))\n\n #list of tweets with selected attributes like URLs, Hashtags, text etc.\n #outtweets = [[tweet.id, ascii(tweet.text), tweet.created_at, tweet.retweet_count, tweet.entities['urls'], tweet.entities['hashtags']] for tweet in alltweets]\n\n outtweets = {}\n tweetObjList = []\n for tweet in alltweets:\n tweetObjMap = {}\n tweetObjMap['tweet_id'] = tweet.id\n tweetObjMap['text'] = ascii(tweet.text)\n tweetObjMap['created_at'] = tweet.created_at\n tweetObjMap['retweet_count'] = tweet.retweet_count\n tweetObjMap['urls'] = tweet.entities['urls']\n tweetObjMap['hashtags'] = tweet.entities['hashtags']\n tweetObjList.append(tweetObjMap)\n\n outtweets['tweetObj'] = tweetObjList\n return outtweets\n \n","sub_path":"WebContent/Tweepy-Client/TweetDld.py","file_name":"TweetDld.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"282631925","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 20 14:12:25 2018\n\n@author: Donghyun Kang\n\"\"\"\nimport pytest\n\ndef operate(a, b, oper):\n \"\"\"Apply an arithmetic operation to a and b.\"\"\"\n if type(oper) is not str:\n raise TypeError(\"oper must be a string\")\n elif oper == '+':\n return a + b\n elif oper == '-':\n return a - b\n elif oper == '*':\n return a * b\n elif oper == '/':\n if b == 0:\n raise ZeroDivisionError(\"division by zero is undefined\")\n return a / b\n raise ValueError(\"oper must be one of '+', '/', '-', or '*'\")\n \ndef test_operate():\n with pytest.raises(TypeError) as typeinfo:\n operate(1, 1, 2)\n assert typeinfo.value.args[0] == \"oper must be a string\"\n\n with pytest.raises(TypeError) as typeinfo:\n operate(1, 1, [1,2])\n assert typeinfo.value.args[0] == \"oper must be a string\"\n\n assert operate(4, 3, \"+\") == 7\n assert operate(4, 3, \"-\") == 1\n assert operate(4, 3, \"*\") == 12\n assert operate(12, 3, \"/\") == 4\n \n with pytest.raises(ZeroDivisionError) as zero:\n operate(12, 0, \"/\") == 4 \n assert zero.value.args[0] == \"division by zero is undefined\" \n \n with pytest.raises(ValueError) as v_err:\n operate(1, 2, \"a\")\n assert v_err.value.args[0] == \"oper must be one of '+', '/', '-', or '*'\"\n \n \n \n \n \n","sub_path":"Assignments/A7/P3_test.py","file_name":"P3_test.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"67639721","text":"# Method could be a function\n# pylint: disable=R0201\n# Too many public methods\n# pylint: disable=R0904\n# Missing docstring\n# pylint: disable=C0111\n\nfrom tempfile import NamedTemporaryFile\nimport unittest\n\nfrom ete3 import Tree\n\n\nfrom variation.clustering import (do_tree, get_subtrees, annotate_tree,\n write_tree_to_nexus_file, FigtreeConfig)\n\n\nclass ClusteringTest(unittest.TestCase):\n def test_upgma(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"upgma\")\n newick_tree = \"((((H,C):0.73,G):0.77,O):1.49,R):3.69;\"\n expected_tree = Tree(newick_tree)\n result = expected_tree.compare(tree)\n assert result[\"source_edges_in_ref\"] - 1 < 0.00001\n assert result[\"ref_edges_in_source\"] - 1 < 0.00001\n\n def test_nj(self):\n dists = [5, 9, 10, 9, 10, 8, 8, 9, 7, 3]\n labels = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n tree = do_tree(dists, labels, method=\"nj\")\n newick_tree = \"(C:2,((A:2,B:3):3,(D:2,E:1):2):2);\"\n expected_tree = Tree(newick_tree)\n result = expected_tree.compare(tree, unrooted=True)\n assert result[\"source_edges_in_ref\"] - 1 < 0.00001\n assert result[\"ref_edges_in_source\"] - 1 < 0.00001\n\n def test_cluster_selection_by_cutoff(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n ultrametric_length = 10\n tree = do_tree(dists, labels, method=\"upgma\")\n tree.convert_to_ultrametric(tree_length=ultrametric_length)\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=4)}\n assert leaves == {frozenset({'O'}), frozenset({'C', 'H', 'G'}),\n frozenset({'R'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=0)}\n assert leaves == {frozenset({'C', 'H', 'G', 'O', 'R'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=15)}\n assert not leaves\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=7)}\n assert leaves == {frozenset({'R'}), frozenset({'G'}),\n frozenset({'C', 'H'}), frozenset({'O'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=8)}\n assert leaves == {frozenset({'R'}), frozenset({'C'}),\n frozenset({'H'}), frozenset({'O'}),\n frozenset({'G'})}\n\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"nj\")\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=4)}\n assert leaves == {frozenset({'R'})}\n\n def test_draw_figtree(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"nj\")\n leaf_annotations = {\"R\": {\"group1\": \"A\", \"group2\": \"C\", \"group3\": \"A\"},\n \"O\": {\"group1\": \"A\", \"group2\": \"A\", \"group3\": \"A\"},\n \"H\": {\"group1\": \"B\", \"group2\": \"B\", \"group3\": \"B\"},\n \"C\": {\"group1\": \"B\", \"group2\": \"A\", \"group3\": \"B\"},\n \"G\": {\"group1\": \"C\", \"group2\": \"D\", \"group3\": \"B\"}\n }\n annotate_tree(tree, leaf_annotations)\n figtree_config = FigtreeConfig(branch_color_attribute=\"group1\",\n leaf_label_color_attribute=\"group2\",\n )\n with NamedTemporaryFile(mode=\"w\") as test_fhand:\n write_tree_to_nexus_file(tree, test_fhand,\n figtree_config=figtree_config)\n test_fhand.flush()\n fhand = open(test_fhand.name, \"r\")\n test_string = fhand.read()\n fhand.close()\n tree_string = test_string.split(\";\")[5]\n leaves = tree_string.split(\"],\")\n assert \"H:0.71[&\" in leaves[0]\n assert \"group1=B\" in leaves[0]\n assert \"G:0.755[&\" in leaves[2]\n assert \"group1=C\" in leaves[2]\n assert \"set appearance.branchColorAttribute=\\\"group1\\\";\" in test_string\n assert \"set tipLabels.colorAttribute=\\\"group2\\\";\" in test_string\n\n figtree_config = FigtreeConfig(branch_color_attribute=\"group1\")\n chosen_features = [\"group1\", \"group2\"]\n with NamedTemporaryFile(mode=\"w\") as test_fhand:\n write_tree_to_nexus_file(tree, test_fhand,\n figtree_config=figtree_config,\n chosen_features=chosen_features)\n test_fhand.flush()\n fhand = open(test_fhand.name, \"r\")\n test_string = fhand.read()\n fhand.close()\n tree_string = test_string.split(\";\")[5]\n leaves = tree_string.split(\"],\")\n assert \"group1=A\" in leaves[2]\n assert \"set appearance.branchColorAttribute=\\\"group1\\\";\" in test_string\n assert \"set tipLabels.colorAttribute=\\\"group2\\\";\" not in test_string\n assert \"group3\" not in leaves[0]\n assert \"group3\" not in leaves[2]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_clustering.py","file_name":"test_clustering.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"555663007","text":"import re,glob\n\ndef change_file(file):\n\tprint(file);\n\tfp = open(file, 'r');\n\tdata = [];\n\tfor line in fp:\n\t\tmatch = re.search('#import.*\"(?P
    .+)\"', line);\n\t\tif match:\n\t\t\theader = match.group('header');\n\t\t\tif header == 'cocos2d.h':\n\t\t\t\tcontinue;\n\t\t\tdata.append('#include \"{0}\"\\n'.format(header));\n\t\t\tcontinue;\n\n\t\tmatch = re.search('@interface *(?P\\S+)\\s*:\\s*(?P\\S+)\\s*{*', line);\n\t\tif match:\n\t\t\tclass_name = match.group('class');\n\t\t\tbase_name = match.group('base');\n\t\t\tif base_name == 'NSObject':\n\t\t\t\tbase_name = 'CCObject';\n\t\t\tdata.append('class {0} : public {1}\\n'.format(class_name, base_name));\n\t\t\tdata.append('{\\n');\n\t\t\tcontinue;\n\t\tif re.search('@end', line):\n\t\t\tdata.append('};\\n');\n\t\t\tcontinue;\n\n\t\tmatch = re.search('-\\((?P\\w+)\\)\\s*(?P\\w+);', line);\n\t\tif match:\n\t\t\treturn_value = match.group('return');\n\t\t\tfunc = match.group('func');\n\t\t\tdata.append('\t{0} {1}();\\n'.format(return_value, func));\n\t\t\tcontinue;\n\t\tdata.append(line);\n\tfp.close();\n\n\tfpw = open(file, 'w');\n\tfpw.writelines(data);\n\tfpw.close();\n\ndef change_all(path):\n\tfile_list = glob.glob(\"./*.h\");\n\tfor file in file_list:\n\t\tchange_file(file);\n\t\tbreak;\n\n\nchange_all('');","sub_path":"ccfd/Classes/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"352199085","text":"\"\"\"\n驗證單字是否有拼錯\n\"\"\"\n\nfrom googletrans import Translator\nimport csv\nimport sys\nimport xlrd\n\n\ndef readExcel(filename):\n workbook = xlrd.open_workbook(filename)\n sheet = workbook.sheet_by_index(0)\n card_lst = []\n for rowx in range(sheet.nrows):\n cols = sheet.row_values(rowx)\n print(cols)\n card_lst.append(cols)\n return card_lst\n\n\nankitxtfile = 'Feb.4.xlsx'\n\nif not len(sys.argv) < 2:\n ankitxtfile = sys.argv[1]\n\nif ankitxtfile.find('xls') > 1:\n pkgname = ankitxtfile.replace('.xlsx', '').replace('.xls', '')\n card_lst = readExcel(ankitxtfile)\nelse:\n pkgname = ankitxtfile.replace('.txt', '')\n with open(ankitxtfile, 'r', encoding='utf8') as f:\n cardstr = f.read()\n card_lst = list(csv.reader(cardstr.splitlines(), delimiter='\\t'))\n\ntranslator = Translator()\n\nfor c in card_lst:\n c.append(translator.translate(c[0], dest='zh-TW').text)\n\nwith open('verification_' + pkgname + '.csv', mode='w', encoding='utf-8-sig', newline='') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerows(card_lst)\n","sub_path":"anki01/GetTranslation.py","file_name":"GetTranslation.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"77942797","text":"''' Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:\n\n– IMC abaixo de 18,5: Abaixo do Peso\n\n– Entre 18,5 e 25: Peso Ideal\n\n– 25 até 30: Sobrepeso\n\n– 30 até 40: Obesidade\n\n– Acima de 40: Obesidade Mórbida '''\n\npeso = float(input('Peso em kg: (Exemplo: 78.5) '))\naltura = float(input('Altura em m: (Exemplo: 1.75) '))\nimc = peso / (altura * altura)\nif imc < 18.5:\n faixa = 'ABAIXO DO PESO'\nelif imc >= 18.5 and imc < 25:\n faixa = 'PESO IDEAL'\nelif imc >= 25 and imc < 30:\n faixa = 'SOBREPESO'\nelif imc >= 30 and imc < 40:\n faixa = 'OBESIDADE'\nelse:\n faixa = 'OBESIDADE MÓRBIDA'\nprint(f'''Seu peso é {peso:.1f} kg e sua altura é {altura:.2f} m. \nO IMC é {imc:.1f} e sua faixa é: {faixa}.''')\n","sub_path":"exercicio043.py","file_name":"exercicio043.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"346963336","text":"from __future__ import annotations\n\nimport contextlib\nimport csv\nimport os\nfrom typing import TYPE_CHECKING\n\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.template import loader\n\nfrom hunt.hint_request import maybe_release_hint, prepare_next_hint, request_hint\nfrom hunt.level_mgr import upload_new_level\nfrom hunt.levels import list_levels, look_for_level, maybe_load_level\nfrom hunt.models import AppSetting, HuntEvent\nfrom hunt.utils import max_level, no_players_during_lockout\n\nif TYPE_CHECKING:\n from django.http.request import HttpRequest\n\n from hunt.utils import AuthenticatedHttpRequest\n\n\n# Send users to the hunt and admins to management.\n@login_required\n@no_players_during_lockout\ndef go_home(request: AuthenticatedHttpRequest) -> HttpResponse:\n if request.user.is_staff:\n return redirect(\"/mgmt\")\n\n return redirect(\"/home\")\n\n\n# Admin-only page to download hunt event logs.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef get_hunt_events(_request: HttpRequest) -> HttpResponse:\n meta = HuntEvent._meta\n field_names = [field.name for field in meta.fields]\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = f\"attachment; filename={meta}.csv\"\n writer = csv.writer(response)\n\n writer.writerow(field_names)\n\n queryset = HuntEvent.objects.all()\n for obj in queryset:\n writer.writerow([getattr(obj, field) for field in field_names])\n\n return response\n\n\n# Hunt homepage.\n@login_required\n@no_players_during_lockout\ndef home(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"welcome.html\")\n\n # Staff can see all levels.\n user = request.user\n team_level = max_level() if user.is_staff else user.huntinfo.level\n\n context = {\"display_name\": user.get_username(), \"team_level\": team_level}\n return HttpResponse(template.render(context, request))\n\n\n# Level page.\n@login_required\n@no_players_during_lockout\ndef level(request: AuthenticatedHttpRequest, level: int) -> HttpResponse:\n # Release a hint, if appropriate.\n user = request.user\n maybe_release_hint(user)\n\n # Prepare the next hint, if appropriate.\n hunt_info = user.huntinfo\n if hunt_info.next_hint_release is None:\n prepare_next_hint(hunt_info)\n\n # Show the level.\n return HttpResponse(maybe_load_level(request, level))\n\n\n# Error page.\n@login_required\n@no_players_during_lockout\ndef oops(request: AuthenticatedHttpRequest) -> HttpResponse:\n # Shouldn't be here. Show an error page.\n template = loader.get_template(\"oops.html\")\n context = {\"team_level\": request.user.huntinfo.level}\n\n # Return the rendered template.\n return HttpResponse(template.render(context, request))\n\n\n# Map (or alt map).\n@login_required\n@no_players_during_lockout\ndef map(request: AuthenticatedHttpRequest) -> HttpResponse:\n # If we're configured to use the alt map, do so.\n settings = None\n with contextlib.suppress(AppSetting.DoesNotExist):\n settings = AppSetting.objects.get(active=True)\n\n use_alternative_map = False if settings is None else settings.use_alternative_map\n if use_alternative_map:\n return alt_map(request)\n\n # If we don't have a Google Maps API key, use the alt map.\n gm_api_key = os.environ.get(\"GM_API_KEY\")\n if gm_api_key is None:\n return alt_map(request)\n\n # Use the Google map.\n template = loader.get_template(\"google-map.html\")\n context = {\"api_key\": gm_api_key, \"lvl\": request.GET.get(\"lvl\")}\n\n return HttpResponse(template.render(context, request))\n\n\n# Alt map.\n@login_required\n@no_players_during_lockout\ndef alt_map(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"alternate-map.html\")\n arcgis_api_key = os.environ.get(\"ARCGIS_API_KEY\")\n context = {\"api_key\": arcgis_api_key, \"lvl\": request.GET.get(\"lvl\")}\n return HttpResponse(template.render(context, request))\n\n\n# Level list.\n@login_required\n@no_players_during_lockout\ndef levels(request: AuthenticatedHttpRequest) -> HttpResponse:\n return HttpResponse(list_levels(request))\n\n\n# Search request endpoint.\n@login_required\n@no_players_during_lockout\ndef do_search(request: AuthenticatedHttpRequest) -> HttpResponse:\n return redirect(look_for_level(request))\n\n\n# Coordinate search page.\n@login_required\n@no_players_during_lockout\ndef search(request: AuthenticatedHttpRequest) -> HttpResponse:\n lvl = request.GET.get(\"lvl\")\n\n template = loader.get_template(\"search.html\")\n context = {\"lvl\": lvl}\n\n return HttpResponse(template.render(context, request))\n\n\n# Nothing here.\n@login_required\n@no_players_during_lockout\ndef nothing(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"nothing.html\")\n\n team_level = request.user.huntinfo.level\n lvl = request.GET.get(\"lvl\")\n search_level = None if lvl is None else int(lvl)\n\n context = {\"team_level\": team_level, \"search_level\": search_level}\n return HttpResponse(template.render(context, request))\n\n\n# Request a hint.\n@login_required\n@no_players_during_lockout\ndef hint(request: AuthenticatedHttpRequest) -> HttpResponse:\n return redirect(request_hint(request))\n\n\n# Management home.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef mgmt(request: HttpRequest) -> HttpResponse:\n template = loader.get_template(\"mgmt.html\")\n\n context = {\"success\": request.GET.get(\"success\")}\n return HttpResponse(template.render(context, request))\n\n\n# Level uploader page.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef level_mgmt(request: HttpRequest) -> HttpResponse:\n template = loader.get_template(\"level-mgmt.html\")\n next_level = request.GET.get(\"next\", 1)\n\n context = {\"success\": request.GET.get(\"success\"), \"next\": next_level}\n return HttpResponse(template.render(context, request))\n\n\n# Upload level endpoint.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef add_new_level(request: HttpRequest) -> HttpResponse:\n return redirect(upload_new_level(request))\n","sub_path":"hunt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"35887260","text":"import os\nimport sys\n\nimport environ\n\nfrom django.utils.translation import gettext_lazy as _\n\nbase_dir = environ.Path(__file__) - 3\nlive_dir = base_dir.path('.live')\n\nPROJECT_ALIAS = 'project'\nPROJECT_DISPLAY_NAME = 'Project'\n\n# Defaults\nenv = environ.Env(\n DEBUG=(bool, False),\n EMAIL_BACKEND=(str, 'django.core.mail.backends.smtp.EmailBackend'),\n EMAIL_HOST=(str, 'localhost'),\n EMAIL_HOST_USER=(str, ''),\n EMAIL_HOST_PASSWORD=(str, ''),\n EMAIL_PORT=(int, 25),\n EMAIL_USE_TLS=(bool, False),\n EMAIL_USE_SSL=(bool, False),\n SERVER_EMAIL=(str, 'root@localhost'),\n DEFAULT_FROM_EMAIL=(str, 'info@localhost'),\n EMAIL_SUBJECT_PREFIX=(str, PROJECT_DISPLAY_NAME),\n DATABASE_HOST=(str, 'localhost'),\n DATABASE_PORT=(str, ''),\n DATABASE_MAX_CONNS=(int, 20),\n ADMINS=(list, []),\n SHOW_DEBUG_TOOLBAR=(bool, False),\n LOAD_EXTERNAL_REFS=(bool, True),\n)\n\nenviron.Env.read_env(base_dir('.env'))\nsys.path.append(base_dir('apps'))\n\nDEBUG = env('DEBUG')\nSECRET_KEY = env('SECRET_KEY')\nALLOWED_HOSTS = ['*']\nINTERNAL_IPS = (\n '127.0.0.1',\n '0.0.0.0',\n)\nSITE_ID = 1\n\n# Follow this convention, but ignore in corner cases:\n# 1. Django\n# 2. Debug/testing\n# 3. Third party\n# 4. Local\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\n 'debug_toolbar',\n 'hijack',\n 'compat',\n\n 'corsheaders',\n 'parler',\n 'sekizai',\n\n 'users',\n 'common',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\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 'django.middleware.locale.LocaleMiddleware',\n 'htmlmin.middleware.HtmlMinifyMiddleware',\n 'htmlmin.middleware.MarkRequestMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\n\n# =============================================================================\n# Templates\n# =============================================================================\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n base_dir('templates'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'sekizai.context_processors.sekizai',\n ],\n 'debug': DEBUG,\n },\n },\n]\n\nALLOWABLE_TEMPLATE_SETTINGS = ('DEBUG', 'LOAD_EXTERNAL_REFS', 'PROJECT_DISPLAY_NAME')\n\nHTML_MINIFY = not DEBUG\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': lambda req: (\n req.environ.get('SERVER_NAME', None) != 'testserver' and\n req.META.get('REMOTE_ADDR', None) in INTERNAL_IPS and\n DEBUG and\n env('SHOW_DEBUG_TOOLBAR')\n ),\n}\n\n\n# =============================================================================\n# Database\n# =============================================================================\n\n# CONN_MAX_AGE must be set to 0, or connections will never go back to the pool\nDATABASES = {\n 'default': {\n 'ENGINE': 'django_db_geventpool.backends.postgresql_psycopg2',\n 'NAME': env('DATABASE_NAME'),\n 'USER': env('DATABASE_USER'),\n 'PASSWORD': env('DATABASE_PASSWORD'),\n 'HOST': env('DATABASE_HOST'),\n 'PORT': env('DATABASE_PORT'),\n 'ATOMIC_REQUESTS': False,\n 'CONN_MAX_AGE': 0,\n 'OPTIONS': {\n 'MAX_CONNS': env('DATABASE_MAX_CONNS'),\n },\n }\n}\n\n\n# =============================================================================\n# Auth\n# =============================================================================\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nAUTH_USER_MODEL = 'users.User'\nLOGIN_REDIRECT_URL = '/'\n\n\n# =============================================================================\n# i18n/l10n\n# =============================================================================\n\nLANGUAGE_CODE = 'en'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nLANGUAGES = [\n ('en', _('English')),\n]\n\nLOCALE_PATHS = [base_dir('locale')]\n\nPARLER_LANGUAGES = {\n SITE_ID: (\n {'code': 'en',},\n ),\n}\n\n\n# =============================================================================\n# Static and media\n# =============================================================================\n\nSTATICFILES_DIRS = [\n base_dir('static'),\n]\n\nSTATIC_ROOT = live_dir('static')\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = live_dir('media')\nMEDIA_URL = '/media/'\n\nif not DEBUG:\n # Add WhiteNoiseMiddleware immediately after SecurityMiddleware.\n # Avoid using whitenoise. Configure a server to provide static.\n # Use whitenoise only in corner cases or for debugging purposes.\n index = MIDDLEWARE.index('django.middleware.security.SecurityMiddleware')\n MIDDLEWARE.insert(index + 1, 'whitenoise.middleware.WhiteNoiseMiddleware')\n\nLOAD_EXTERNAL_REFS = env('LOAD_EXTERNAL_REFS')\n\n\n# =============================================================================\n# Mailing\n# =============================================================================\n\nEMAIL_BACKEND = env('EMAIL_BACKEND')\nEMAIL_HOST = env('EMAIL_HOST')\nEMAIL_HOST_USER = env('EMAIL_HOST_USER')\nEMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')\nEMAIL_PORT = env('EMAIL_PORT')\nEMAIL_USE_TLS = env('EMAIL_USE_TLS')\nEMAIL_USE_SSL = env('EMAIL_USE_SSL')\nSERVER_EMAIL = env('SERVER_EMAIL') # Email to send error messages\nDEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL')\nEMAIL_SUBJECT_PREFIX = env('EMAIL_SUBJECT_PREFIX')\n\n\n# =============================================================================\n# Caches\n# =============================================================================\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}\n\n\n# =============================================================================\n# Hijack\n# =============================================================================\n\nHIJACK_LOGIN_REDIRECT_URL = '/admin/'\nHIJACK_LOGOUT_REDIRECT_URL = HIJACK_LOGIN_REDIRECT_URL\nHIJACK_ALLOW_GET_REQUESTS = True\n\n\n# =============================================================================\n# Fixtures\n# =============================================================================\n\nFIXTURE_DIRS = [\n base_dir('fixtures'),\n]\n\n\n# See apps/common/management/commands/pushfixtures.py\nFIXTURES = [\n# 'file.json',\n]\n\n\n# =============================================================================\n# Others\n# =============================================================================\n\nROOT_URLCONF = 'core.urls'\nWSGI_APPLICATION = 'core.wsgi.application'\n\nCORS_ORIGIN_ALLOW_ALL = True\n\nADMINS = []\nadmins = env('ADMINS')\nfor admin in admins:\n ADMINS.append(admin.split(':'))\n","sub_path":"{{cookiecutter.project_slug}}/core/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"86073947","text":"# Copyright 2020 kubeflow.org.\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\nimport os\nimport pytest\nfrom lgbserver import LightGBMModelRepository\n\nmodel_dir = os.path.join(os.path.dirname(__file__), \"example_model\")\ninvalid_model_dir = os.path.join(os.path.dirname(__file__), \"model_not_exist\", \"model\")\n\n\n@pytest.mark.asyncio\nasync def test_load():\n repo = LightGBMModelRepository(model_dir=model_dir, nthread=1)\n model_name = \"model\"\n await repo.load(model_name)\n assert repo.get_model(model_name) is not None\n assert repo.is_model_ready(model_name)\n\n\n@pytest.mark.asyncio\nasync def test_load_fail():\n repo = LightGBMModelRepository(model_dir=model_dir, nthread=1)\n model_name = \"model\"\n with pytest.raises(Exception):\n await repo.load(model_name)\n assert repo.get_model(model_name) is None\n assert not repo.is_model_ready(model_name)\n","sub_path":"python/lgbserver/lgbserver/test_lightgbm_model_repository.py","file_name":"test_lightgbm_model_repository.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"363128828","text":"from typing import TypeVar\n\nfrom aiohttp.web import Application, RouteTableDef\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom nekitdev.constants import ROOT_ROUTE, STATIC, STATIC_NAME, TEMPLATES\n\n__all__ = (\"environment\", \"routes\", \"setup_app\")\n\nenvironment = Environment(\n loader=FileSystemLoader(TEMPLATES),\n trim_blocks=True,\n lstrip_blocks=True,\n enable_async=True,\n)\n\nroutes = RouteTableDef()\n\nroutes.static(ROOT_ROUTE + STATIC_NAME, STATIC)\n\n\nA = TypeVar(\"A\", bound=Application)\n\n\ndef setup_app(app: A) -> A:\n app.add_routes(routes)\n\n return app\n","sub_path":"nekitdev/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"412382196","text":"from django.conf.urls import patterns, url\n\nfrom .views import *\n\nurlpatterns = patterns(\n '',\n url(r'^callback/$', CallBackFormView.as_view(), name='callback'),\n url(r'^appointment/$', AppointmentFormView.as_view(), name='appointment'),\n url(r'^email/$', EmailFormView.as_view(), name='email'),\n url(r'^confirmation/$', Confirmation.as_view(), name='confirmation'),\n)\n","sub_path":"mailchimp_forms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"612475621","text":"from __future__ import division\n\nfrom ml.rbm.config import TrainingConfiguration\nfrom math import sqrt\n\nimport ml.rbm.orrbm\n\n# RBM configuration\nn_vis=784\nn_hid=5000\nrbm_cfg = TrainingConfiguration(dataset='mnistv',\n n_vis=n_vis, n_hid=n_hid,\n batch_size=20,\n n_gibbs_steps=15,\n epochs=30,\n step_rate=0.1,\n use_pcd=True,\n binarize_data='round',\n initial_momentum=0, final_momentum=0, \n use_final_momentum_from_epoch=0,\n weight_cost=0,\n init_method='uniform', \n init_weight_sigma=4 * sqrt(6. / (n_hid + n_vis)), \n init_bias_sigma=0,\n seed=1)\n\n# Classifier\nclassifier='mlp'\n\n# ORRBM\nn_samples = 10000\niters = 20\nk = 10\nbeta = 2\n\n# dataset\nby = ml.rbm.orrbm.base_y\noverlaps = [(0, by), (5, by), (10, by), (15, by)]\n\n\n\n","sub_path":"ml/apps/orrbm_shiftstat/basic/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"557539959","text":"from flask import Flask\nfrom datastore import db\nfrom flask_restful import Api\nfrom handlers import *\nfrom models import *\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom handlers.generate_prediction import *\n\n\ndef _init_app():\n app = Flask(__name__)\n app.config.from_pyfile(\"config.py\")\n app.secret_key = \"secret123\"\n return app\n\n\napp = _init_app()\n\n\ndef _init_db(app):\n db.init_app(app)\n with app.app_context():\n db.create_all()\n # Ensure FOREIGN KEY for sqlite3\n if 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:\n def _fk_pragma_on_connect(dbapi_con, con_record): # noqa\n dbapi_con.execute('pragma foreign_keys=ON')\n\n with app.app_context():\n from sqlalchemy import event\n event.listen(db.engine, 'connect', _fk_pragma_on_connect)\n\n\ndef _init_routes():\n api = Api(app)\n api.add_resource(Home, \"/\", methods=[\"GET\"])\n api.add_resource(Login, \"/login\", methods=[\"GET\", \"POST\"])\n api.add_resource(Register, \"/register\", methods=[\"GET\", \"POST\"])\n api.add_resource(PHCDashboard, \"/phcdashboard\", methods=[\"GET\"])\n api.add_resource(UploadCSV, \"/uploadcsv\", methods=[\"GET\", \"POST\"])\n api.add_resource(Logout, \"/logout\", methods=[\"GET\"])\n api.add_resource(Reports, \"/reports\", methods=[\"GET\"])\n api.add_resource(Output, \"/output/\", methods=[\"GET\"])\n api.add_resource(GenRep, \"/gen\", methods=[\"GET\"]) # Manual Report generation trigger\n # Generate report for non-default algorithms. Default is ARIMA\n api.add_resource(Algo, \"/algo\", methods=[\"GET\"])\n api.add_resource(DownloadTemplate, \"/download_template\", methods=[\"GET\", \"POST\"])\n api.add_resource(Admin, \"/admin\", methods=[\"GET\", \"POST\"])\n api.add_resource(CoronavirusHandler, \"/coronavirus\", methods=[\"GET\", \"POST\"])\n api.add_resource(About, \"/about\", methods=[\"GET\"])\n api.add_resource(AdminLogin, \"/admin_login\", methods=[\"GET\",\"POST\"])\n\n\nif __name__ == \"__main__\":\n scheduler = BackgroundScheduler(daemon=True)\n scheduler.add_job(generate_report, trigger='cron', day_of_week='mon-sun', hour='0', minute='0')\n scheduler.add_job(train_all_models,trigger='cron',day_of_week='sun',hour='0' ,minute='0')\n scheduler.start()\n _init_routes()\n _init_db(app)\n app.run(debug=False,threaded=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"103138867","text":"\"\"\"Tests for the base DTA record\"\"\"\n\nfrom unittest.mock import patch\n\nfrom swissdta.records.record import DTARecord\n\n\n@patch('swissdta.records.header.DTAHeader.validate')\ndef test_validate_header(mocker):\n \"\"\"Verifies that the record validation triggers the header validation.\"\"\"\n record = DTARecord()\n assert not mocker.called, \"header validation should not be called before record validation is triggered\"\n record.validate()\n assert mocker.call, \"header validation should be called when record validation is triggered\"\n","sub_path":"tests/test_record.py","file_name":"test_record.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"98079956","text":"#-*- coding:utf-8 -*-\n# @Time : 2017/7/21 17:46\n# @Author : Sml2h3\n# @Site : www.ydyd.me\n# @File : Clawer.py\n# @Software: PyCharm\nimport sys\nsys.setrecursionlimit(110000)\nimport requests\nimport time\nfrom Logger.Logger import Logger\nfrom gevent import monkey\nfrom Login.Login import Login\nmonkey.patch_socket()\nfrom lxml import etree\nimport gevent\nfrom gevent.pool import Pool\n# import pymysql\nfrom Config.DB import *\nLogger = Logger('Clawer')\n\n\nclass Clawer(object):\n def __init__(self, config, cookies):\n self.conn = config.conn\n self.cookies = cookies\n self.page = 1\n self.ckvalid = True\n\n def _run_master(self):\n if self.check_j_token():\n gevent.spawn(self.clawer_master).join()\n else:\n self._run_master()\n\n def _run_slaver(self):\n if self.check_j_token():\n pool = Pool(2)\n while True:\n urls = [ self.conn.spop(\"urls\") for i in range(5) ]\n result = pool.map(self.clawer_slaver, urls)\n\n else:\n self._run_slaver()\n\n def check_j_token(self):\n # 判断是否第一次访问\n Logger.info(\"正在判断是否需要生成j_token\")\n result = requests.get(\"http://openlaw.cn/search/judgement/type?causeId=a3ea79cf193f4e07a27a900e29585dbb&page=1\",\n cookies=self.cookies)\n if result and result.status_code == 200:\n if 'wch3116@hotmail.com' in result.text:\n # 需要\n Logger.info(\"需要生成j_token,即将开始进入j_token计算\")\n v = self.txt_wrap_by('window.v=\"', '\"', result.text)\n j_token = self.__get_j_token(v)\n self.cookies = requests.utils.add_dict_to_cookiejar(self.cookies, {\"j_token\": j_token})\n else:\n # 不需要\n Logger.info(\"不需要生成j_token\")\n return True\n else:\n Logger.warning(\"判断失败,休息一会重新判断~\")\n time.sleep(5)\n return False\n\n def clawer_slaver(self, url):\n header = {\n 'Host': 'openlaw.cn',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36',\n 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Referer': url,\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n }\n result = requests.get(url, cookies=self.cookies, headers=header)\n if result and result.status_code == 200:\n\n html = etree.HTML(result.text)\n #判决时间\n time_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[1]/text()')\n if len(time_tem) > 0:\n time = time_tem[0].rstrip().replace(\" \", '')\n else:\n time = \"0\"\n #判决标题\n title_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/h2/text()')\n if len(title_tem) > 0:\n title = title_tem[0]\n else:\n title = \"\"\n if title == \"\":\n self.clawer_slaver(url)\n return\n Logger.info(title)\n #判决法院\n fy_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[2]/a/text()')\n if len(fy_tem) > 0:\n fy = fy_tem[0]\n else:\n fy = \"\"\n #案号\n ah_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[3]/text()')\n if len(ah_tem) > 0:\n ah = ah_tem[0]\n else:\n ah = \"\"\n #控告人和控诉人\n content = html.xpath('//*[@id=\"Litigants\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n litigants = c\n content = html.xpath('//*[@id=\"Explain\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n explain = c\n #诉讼程序\n content = html.xpath('//*[@id=\"Procedure\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n procedure = c\n #观点\n content = html.xpath('//*[@id=\"Opinion\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n option = c\n #裁定\n content = html.xpath('//*[@id=\"Verdict\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n verdict = c\n #通知\n content = html.xpath('//*[@id=\"Inform\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n info = c\n #结束语\n content = html.xpath('//*[@id=\"Ending\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n end = c\n Logger.info(title)\n # conn = pymysql.connect(host='rm-2ze7441de5149074.redis.rds.aliyuncs.com', port=3306, user='root', passwd='CSDNb405', db='openlaw', charset='utf8')\n # cursor = conn.cursor()\n # result = cursor.execute('insert into law(title, litigants, explain, procedure, opinion, verdict, inform, ending, time, fy, an) vaules(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',(str(title), str(litigants), str(explain), str(procedure), str(option), str(verdict), str(info), str(end), str(time), str(fy), str(ah)))\n # conn.commit()\n # cursor.close()\n # conn.close()\n session = DBSession()\n # 创建新User对象:\n new_user = Law(title=title, litigants=litigants, explain=explain, procedure=procedure, opinion=option, verdict=verdict, inform=info, ending=end, time=time, fy=fy, an=ah)\n # 添加到session:\n session.add(new_user)\n # 提交即保存到数据库:\n session.commit()\n session.close()\n # 关闭session:\n Logger.info(\"任务:\"+ url + \"完成\")\n\n def clawer_master(self, url=\"\"):\n if url == \"\":\n page = self.page\n self.page += 1\n url = \"http://openlaw.cn/search/judgement/type?causeId=a3ea79cf193f4e07a27a900e29585dbb&page=\"\n url += str(page)\n # 代理服务器\n proxyHost = \"proxy.abuyun.com\"\n proxyPort = \"9020\"\n\n # 代理隧道验证信息\n proxyUser = \"H4871716T867Q1LD\"\n proxyPass = \"CCAE03DE2E35FBA2\"\n\n proxyMeta = \"http://%(user)s:%(pass)s@%(host)s:%(port)s\" % {\n \"host\": proxyHost,\n \"port\": proxyPort,\n \"user\": proxyUser,\n \"pass\": proxyPass,\n }\n\n proxy_handler = {\n \"http\": proxyMeta,\n \"https\": proxyMeta,\n }\n\n header = {\n 'Host': 'openlaw.cn',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36',\n 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Referer': url,\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n }\n Logger.info(\"正在抓取的页数为\" + str(page))\n result = requests.get(url, cookies=self.cookies, headers=header, proxies=proxy_handler)\n if result and result.status_code == 200:\n if \"抱歉不能为您显示更多的内容!\" in result.text:\n Logger.info(\"Cookies已经失效需要重新登录\")\n self.cookies = Login()._run()\n html = etree.HTML(result.text)\n href = html.xpath('//*[@id=\"ht-kb\"]/article/h3/a/@href')\n #//*[@id=\"ht-kb\"]/article[2]/h3/a\n if len(href)>0:\n urls = [ 'http://openlaw.cn'+i for i in href ]\n Logger.info(\"第\" + str(page) + \"页成功爬取到文书链接,数据量为\" + str(len(urls)) + \"条\")\n Logger.info(\"正在将任务上传至Redis服务器,等待从机进行下一步操作\")\n for url in urls:\n self.conn.sadd('urls', url)\n Logger.info(\"上传至Redis服务器成功,即将开始爬去第二页的内容\")\n else:\n Logger.info(\"本页未爬取到链接\")\n self.clawer_master()\n\n else:\n Logger.warning(\"访问出错,休息一会吧~\")\n time.sleep(3)\n self.clawer_master(url)\n\n def txt_wrap_by(self, start_str, end, html):\n start = html.find(start_str)\n if start >= 0:\n start += len(start_str)\n end = html.find(end, start)\n if end >= 0:\n return html[start:end].strip()\n\n def __get_j_token(self, str):\n cookie = str[2: 4] + 'n' + str[0: 1] + 'p' + str[4: 8] + 'e' + str[1: 2] + str[16: len(str) - 1] + str[8: 16]\n return cookie\n","sub_path":"Clawer/Clawer.py","file_name":"Clawer.py","file_ext":"py","file_size_in_byte":9190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215232640","text":"from direct.distributed.PyDatagram import *\nimport urlparse\nfrom src.otp.distributed.OtpDoGlobals import *\nfrom src.otp.distributed.DistributedDirectoryAI import DistributedDirectoryAI\nfrom src.toontown.distributed.ToontownInternalRepository import ToontownInternalRepository\nimport src.toontown.minigame.MinigameCreatorAI\nfrom src.otp.otpbase import BackupManager\n\nif config.GetBool('want-rpc-server', False):\n from src.toontown.rpc.ToontownRPCServer import ToontownRPCServer\n from src.toontown.rpc.ToontownRPCHandler import ToontownRPCHandler\n\nclass ToontownUberRepository(ToontownInternalRepository):\n def __init__(self, baseChannel, serverId):\n ToontownInternalRepository.__init__(self, baseChannel, serverId, dcSuffix='UD')\n\n self.notify.setInfo(True)\n\n def handleConnected(self):\n ToontownInternalRepository.handleConnected(self)\n rootObj = DistributedDirectoryAI(self)\n rootObj.generateWithRequiredAndId(self.getGameDoId(), 0, 0)\n\n if config.GetBool('want-rpc-server', False):\n endpoint = config.GetString('rpc-server-endpoint', 'http://localhost:8080/')\n self.rpcServer = ToontownRPCServer(endpoint, ToontownRPCHandler(self))\n self.rpcServer.start(useTaskChain=True)\n\n self.backups = BackupManager.BackupManager(\n filepath=self.config.GetString('backups-filepath', 'backups/'),\n extension=self.config.GetString('backups-extension', '.json'))\n\n self.createGlobals()\n self.notify.info('Done.')\n\n def createGlobals(self):\n \"\"\"\n Create \"global\" objects.\n \"\"\"\n\n self.csm = simbase.air.generateGlobalObject(OTP_DO_ID_CLIENT_SERVICES_MANAGER, 'ClientServicesManager')\n self.chatAgent = simbase.air.generateGlobalObject(OTP_DO_ID_CHAT_MANAGER, 'ChatAgent')\n self.friendsManager = simbase.air.generateGlobalObject(OTP_DO_ID_ttcy_FRIENDS_MANAGER, 'ttcyFriendsManager')\n self.globalPartyMgr = simbase.air.generateGlobalObject(OTP_DO_ID_GLOBAL_PARTY_MANAGER, 'GlobalPartyManager')\n self.groupManager = simbase.air.generateGlobalObject(OPT_DO_ID_GROUP_MANAGER, 'GroupManager')\n self.megaInvasionManager = simbase.air.generateGlobalObject(\n OTP_DO_ID_MEGA_INVASION_MANAGER, 'MegaInvasionManager')\n","sub_path":"src/toontown/uberdog/ToontownUberRepository.py","file_name":"ToontownUberRepository.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"491418218","text":"#!/usr/bin/env python3\n\nround=0\nanswer=\" \"\n\nwhile round<3 and answer !='Brian':\n round=round+1\n answer=input('Finish the movie title, \"Monty Python\\'s The Life of ______\": ')\n \n if answer.lower()=='brian':\n print('Correct')\n break\n elif answer.lower()=='shrubbery':\n print('You gave the super secret answer!')\n break\n elif round==3:\n print('Sorry, the answer was Brian.')\n else:\n print('Sorry! Try again!')\n\n","sub_path":"montypython/monty_python2.py","file_name":"monty_python2.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164465180","text":"# v1 -> Pickle dataframes read with pandas - \"Load data\" section\n# v2 -> Splits LSTM into 2 (LSTM and case)\n# v3 -> Uses FastText embeddings\n# v4 -> Conversion to token IDs, prunning and padding moved to preprocessing\n# v5 -> Splits cases in 5 different LSTMs\n# v6 -> Sigmoid function introduced.\n# Loss function changed from nn.BCEWithLogitsLoss() to nn.BCE()\n# Dropout added to LSTMS\n# v7 -> Test function added\n# Metric computations added\n# Saves model and results history\n# v8 -> Adds attention layers\n# v9 -> Adds flexible attention and hidden dims to global initialization\n# v10 -> Article text removed from model\n# v11 -> Article text added to model\n# v12 -> Encodes case passages in for loop\n\n#%% Imports\n\nimport os\nimport torch\nimport pickle\nimport pandas as pd\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_auc_score, roc_curve\n\n# Function definition\n#%% DataClass definition\n\nclass ECHR_dataset(Dataset):\n def __init__(self, data_df):\n self.article_tensor = torch.LongTensor(data_df['article_text'].to_list())\n self.cases_tensor = torch.LongTensor(data_df['case_texts'].to_list())\n self.outcome_tensor = torch.Tensor(data_df['outcome'].to_list())\n \n def __len__(self):\n return self.outcome_tensor.size()[0]\n \n def __getitem__(self, idx):\n X_article = self.article_tensor[idx, :]\n X_cases = self.cases_tensor[idx, :]\n Y = self.outcome_tensor[idx]\n \n return X_article, X_cases, Y\n\n#%% Model definition\n\nclass ECHR_model(nn.Module):\n \n def __init__(self, input_size, hidden_dim, ouput_size, pretrained_embeddings,\n att_dim, dropout):\n super(ECHR_model, self).__init__()\n\n self.input_size = input_size\n self.hidden_dim = hidden_dim\n self.output_size = output_size\n self.dropout = dropout\n self.num_layers = 1\n self.num_passages = 5 #300\n self.seq_len = 512\n\n # Embedding\n self.embed = nn.Embedding.from_pretrained(pretrained_embeddings)\n \n # Dropout\n self.drops = nn.Dropout(self.dropout)\n \n # Encode article\n self.lstm_art = nn.LSTM(input_size = self.input_size,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True) \n \n # Encode case senteces\n self.lstm_case_sent = nn.LSTM(input_size = self.input_size,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True)\n \n # Encode case document\n self.lstm_case_doc = nn.LSTM(input_size = self.hidden_dim * 2,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True)\n \n # Fully connected\n self.fc_1 = nn.Linear(in_features = self.hidden_dim * 2 * 2,\n out_features = self.output_size)\n \n # Sigmoid\n self.sigmoid = nn.Sigmoid()\n \n def forward(self, X_art, X_case):\n # Embedding\n x_art = self.embed(X_art) # batch_size x seq_len x embed_dim\n x_case = self.embed(X_case) # batch_size x (seq_len x n_passages) x embed_dim\n \n # Article encoding\n x_art = self.lstm_art(x_art) # Tuple (len = 2)\n x_art_fwd = x_art[0][:, -1, 0:64] # batch_size x hidden_dim\n x_art_bkwd = x_art[0][:, 0, 64:128] # batch_size x hidden_dim\n x_art = torch.cat((x_art_fwd, x_art_bkwd), dim = 1) # batch_size x (hidden_dim x 2)\n x_art = self.drops(x_art) # batch_size x (hidden_dim x 2) \n \n # Case sentence encoding\n #x_case_sent = torch.FloatTensor()\n x_case_sent = torch.FloatTensor().to(device)\n \n for idx in range(0, self.num_passages):\n span_b = self.seq_len * idx\n span_e = self.seq_len * (idx + 1)\n x_aux = self.lstm_case_sent(x_case[:, span_b:span_e, :]) # Tuple (len = 2)\n x_aux_fwd = x_aux[0][:, -1, 0:64] # batch_size x hidden_dim\n x_aux_bkwd = x_aux[0][:, 0, 64:128] # batch_size x hidden_dim\n x_aux = torch.cat((x_aux_fwd, x_aux_bkwd), dim = 1) # batch_size x (hidden_dim x 2)\n x_aux = self.drops(x_aux) # batch_size x (hidden_dim x 2)\n x_aux = x_aux.unsqueeze(1) # batch_size x 1 x (hidden_dim x 2)\n x_case_sent = torch.cat((x_case_sent, x_aux), dim=1) # batch_size x n_passages x (hidden_dim x 2)\n \n # Case document encoding\n x_case_doc = self.lstm_case_doc(x_case_sent) # Tuple (len = 2)\n x_case_doc_fwd = x_case_doc[0][:, -1, 0:64] # batch_size x hidden_dim\n x_case_doc_bkwd = x_case_doc[0][:, 0, 64:128] # batch_size x hidden_dim\n x_case_doc = torch.cat((x_case_doc_fwd, x_case_doc_bkwd),\n dim = 1) # batch_size x (hidden_dim x 2)\n x_case_doc = self.drops(x_case_doc) # batch_size x (hidden_dim x 2)\n \n # Concatenate article and passage encodings\n x = torch.cat((x_art, x_case_doc), dim = 1) # batch size x (hidden_dim x 2 x 2)\n \n # Fully connected layer\n x = self.fc_1(x) # batch size x output_size\n \n # Sigmoid function\n x = self.sigmoid(x) # batch size x output_size\n \n return x\n\n#%% Train function\n\ndef train_epoch_func(model, criterion, optimizer, train_dl, train_loss_history):\n model.train()\n train_acc = 0\n total_entries = 0\n sum_train_loss = 0\n \n for X_art, X_case, Y in tqdm(train_dl, total = len(train_dl)):\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Zero gradients\n optimizer.zero_grad()\n \n #Forward + backward + optimize\n pred = model(X_art, X_case).view(-1)\n loss = criterion(pred, Y)\n \n # Backpropagate\n loss.backward()\n \n # Update model\n optimizer.step() \n \n # Book-keeping\n current_batch_size = X_art.size()[0]\n total_entries += current_batch_size\n sum_train_loss += (loss.item() * current_batch_size)\n \n avg_train_loss = sum_train_loss / total_entries\n train_loss_history.append(avg_train_loss)\n \n return avg_train_loss, train_loss_history\n\n#%% Validation function\n\ndef val_epoch_func(model, criterion, dev_dl, val_loss_history):\n model.eval()\n val_acc = 0\n sum_correct = 0\n sum_val_loss = 0\n total_entries = 0\n\n for X_art, X_case, Y in dev_dl:\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Compute predictions:\n with torch.no_grad():\n pred = model(X_art, X_case).view(-1)\n loss = criterion(pred, Y)\n \n # Book-keeping\n current_batch_size = X_art.size()[0]\n total_entries += current_batch_size\n sum_val_loss += (loss.item() * current_batch_size)\n pred = torch.round(pred.view(pred.shape[0]))\n sum_correct += (pred == Y).sum().item() \n \n avg_loss = sum_val_loss / total_entries\n accuracy = sum_correct / total_entries\n val_loss_history.append(avg_loss)\n print(\"valid loss %.3f and accuracy %.3f\" % (avg_loss, accuracy))\n \n return avg_loss, accuracy, val_loss_history\n\n#%% Test function\n\ndef test_func(model, test_dl):\n model.eval()\n Y_predicted_score = []\n Y_predicted_binary = []\n Y_ground_truth = []\n\n for X_art, X_case, Y in test_dl:\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Compute predictions and append\n with torch.no_grad():\n pred_batch_score = model(X_art, X_case).view(-1)\n pred_batch_binary = torch.round(pred_batch_score.view(pred_batch_score.shape[0]))\n Y_predicted_score += pred_batch_score.tolist()\n Y_predicted_binary += pred_batch_binary.tolist()\n Y_ground_truth += Y.tolist()\n \n return Y_predicted_score, Y_predicted_binary, Y_ground_truth\n\n#%% Path definition\n\nrun_folder = os.path.join(os.path.split(os.getcwd())[0], '01_data', '02_runs', '14_art_5_50_pass') \npath_model_train = os.path.join(run_folder, 'model_train.pkl')\npath_model_dev = os.path.join(run_folder, 'model_dev.pkl')\npath_model_test = os.path.join(run_folder, 'model_test.pkl')\noutput_path_model = os.path.join(run_folder, 'model.pt')\noutput_path_results = os.path.join(run_folder, 'results.pkl')\ninput_path_id_2_embed = os.path.join(os.path.split(os.getcwd())[0], '01_data', '01_preprocessed', 'id_2_embed_dict.pkl')\n\n\"\"\"\nrun_folder = 'C:/Users/siban/Dropbox/CSAIL/Projects/12_Legal_Outcome_Predictor/01_data/02_runs/12_art_6_300_pass'\npath_model_train = os.path.join(run_folder, 'model_train.pkl')\npath_model_dev = os.path.join(run_folder, 'model_dev.pkl')\npath_model_test = os.path.join(run_folder, 'model_test.pkl')\noutput_path_model = os.path.join(run_folder, 'model.pt')\noutput_path_results = os.path.join(run_folder, 'results.pkl')\ninput_path_id_2_embed = 'C://Users//siban//Dropbox//CSAIL//Projects//12_Legal_Outcome_Predictor//01_data/01_preprocessed//id_2_embed_dict.pkl'\n\"\"\"\n\n#%% Global initialization\n\nseed = 1234\nn_epochs = 20\nbatch_size = 500\nlearning_rate = 0.001\ndropout = 0.4\nmomentum = 0.9\nwd = 0.00001\nuse_cuda = True\ndevice = torch.device('cuda:1')\n\nembed_dim = 200\ninput_size = embed_dim\nhidden_dim = 64\natt_dim = 100\noutput_size = 1\npad_idx = 0\n\n#%% Load data\n\nprint('Loading data')\nwith open(input_path_id_2_embed, 'rb') as fr:\n id_2_embed = pickle.load(fr)\n\nmodel_train = pd.read_pickle(path_model_train)\nmodel_dev = pd.read_pickle(path_model_dev)\nmodel_test = pd.read_pickle(path_model_test)\nprint('Done')\n\n\"\"\"\n#-------------------------------- FOR DEBUGGING -------\nmodel_train = model_train[0:50]\nmodel_dev = model_dev[0:int(50 * 0.2)]\nmodel_test = model_test[0:int(50 * 0.2)]\n#------------------------------------------------------\n\"\"\"\n\n#%% Instantiate dataclasses\n\nprint('Instantiating dataclases')\ntrain_dataset = ECHR_dataset(model_train)\ndev_dataset = ECHR_dataset(model_dev)\ntest_dataset = ECHR_dataset(model_test)\nprint('Done')\n\n#%% Instantiate dataloaders\n\nprint('Instantiating dataloaders')\ntrain_dl = DataLoader(train_dataset, batch_size = batch_size, shuffle = True)\ndev_dl = DataLoader(dev_dataset, batch_size = batch_size * 2, shuffle = False)\ntest_dl = DataLoader(test_dataset, batch_size = batch_size * 2, shuffle = False)\nprint('Done')\n\n#%% Instantiate model\n\npretrained_embeddings = torch.FloatTensor(list(id_2_embed.values()))\nmodel = ECHR_model(input_size, hidden_dim, output_size, pretrained_embeddings,\n att_dim, dropout)\n\n# Move to cuda\nif use_cuda and torch.cuda.is_available():\n print('Moving model to cuda')\n model = model.to(device)\n print('Done')\n\nprint(model)\n\n#%% Instantiate optimizer & criterion\n\noptimizer = torch.optim.Adam(model.parameters(), lr = learning_rate,\n weight_decay = wd)\n#optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate,\n# momentum = momentum)\ncriterion = nn.BCELoss()\n\n#%% Training\n\ntrain_loss_history = []\nval_loss_history = []\n\nfor epoch in tqdm(range(0, n_epochs), desc = 'Training'):\n train_loss, train_loss_history = train_epoch_func(model, criterion,\n optimizer, train_dl, train_loss_history)\n print(\"training loss: \", train_loss)\n _, _, val_loss_history = val_epoch_func(model, criterion, dev_dl, val_loss_history)\n\n#%% Testing\n\nY_predicted_score, Y_predicted_binary, Y_ground_truth = test_func(model, test_dl)\n\n#%% Compute Metrics\n\ntn, fp, fn, tp = confusion_matrix(Y_ground_truth, Y_predicted_binary).ravel()\n\nprecision = tp / (tp + fp)\nrecall = tp / (tp + fn)\nf1 = 2 * (precision * recall) / (precision + recall)\n\nauc = roc_auc_score(Y_ground_truth, Y_predicted_score)\n\nprint(f'Precision: {precision:.3f}')\nprint(f'Recall: {recall:.3f}')\nprint(f'F1: {f1:.3f}\\n')\nprint(f'AUC: {auc:.3f}\\n')\n\n#%% Save model and results\n\ntorch.save(model, output_path_model)\nresults = {'training_loss': train_loss_history,\n 'validation_loss': val_loss_history,\n 'Y_test_ground_truth': Y_ground_truth,\n 'Y_test_prediction_scores': Y_predicted_score,\n 'Y_test_prediction_binary': Y_predicted_binary}\nwith open(output_path_results, 'wb') as fw:\n pickle.dump(results, fw) \n","sub_path":"00_old_versions/08_model_full_case_no_att/05_model_v12.py","file_name":"05_model_v12.py","file_ext":"py","file_size_in_byte":13914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"34196652","text":"\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib.colors import LogNorm\nimport numpy as np\nfrom copy import deepcopy as copy\nfrom astropy.io import fits\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass GC():\n def __init__(self, ID, x, y, ra, dec, SNR=0, g=np.nan, z=np.nan, wave=None, spec=None, bg_spec=None, v=0, dv=0, m=0, dm=0, r=0, galaxy='FCC47', g_MUSE=0,\n z_MUSE=0, age=0, dage=0, m_age=0, dm_age=0, m_miles=0, dm_miles=0, m_amiles=0, dm_amiles=0, m_CaT=0, dm_CaT=0, m_ssp=0, dm_ssp=0, dm_b=0, m_b=0):\n self.ID = ID\n self.x = x\n self.y = y\n self.ra = ra\n self.dec = dec\n self.SNR = SNR\n self.g = g\n self.z = z\n self.r = r\n self.wave = wave\n spec[np.isinf(spec)] = 0.0\n spec[np.isnan(spec)] = 0.0\n self.spec = spec\n bg_spec[np.isinf(bg_spec)] = 0.0\n bg_spec[np.isnan(bg_spec)] = 0.0\n self.bg_spec = bg_spec\n self.v = v\n self.dv = dv\n self.m = m\n self.dm = dm\n self.g_MUSE = g_MUSE # process_spec(self.wave, self.spec, 'F475W')\n self.z_MUSE = z_MUSE # process_spec(self.wave, self.spec, 'F850LP')\n self.galaxy = galaxy\n self.age = age\n self.dage = dage\n self.m_age = m_age\n self.dm_age = dm_age\n self.m_miles = m_miles\n self.dm_miles = dm_miles\n self.m_amiles = m_amiles\n self.dm_amiles = dm_amiles\n self.m_CaT = m_CaT\n self.dm_CaT = dm_CaT\n self.m_b = m_b\n self.dm_b = dm_b\n self.m_ssp = m_CaT\n self.dm_ssp = dm_CaT\n\n def set_v(self, v=0, dv=0):\n self.v = v\n self.dv = dv\n\n def set_ra_dec(self, ra=0, dec=0):\n self.ra = np.round(ra, 7)\n self.dec = np.round(dec, 7)\n\n def set_m(self, m=0, dm=0):\n self.m = m\n self.dm = dm\n\n def set_ID(self, ID=0):\n self.ID = int(ID)\n\n def get_MUSE_mag(self):\n self.g_MUSE = process_spec(self.wave, self.spec, 'F475W')\n self.z_MUSE = process_spec(self.wave, self.spec, 'F850LP')\n\n def set_r(self, r=0):\n self.r = r\n\n\ndef get_rad(x_pix, y_pix, xc=207, yc=387):\n '''\n Simple routine to calculate the projected distance in arcsec\n '''\n rs = np.zeros(len(x_pix))\n for i in range(len(x_pix)):\n rs[i] = np.sqrt((x_pix[i] - xc)**2 + (y_pix[i] - yc)**2) # in pixel coords\n return rs * 0.2 # in arcsec\n\n\ndef create_catalog(GCs, output_directory='./', galaxy='FCC47'):\n '''\n Creates the MUSE catalog as a fits file in the output directory\n '''\n # the spectra\n wave = GCs[0].wave\n\n filename = '{0}_GC_catalog.fits'.format(galaxy)\n print(\"- Writing: \" + output_directory + filename)\n cols = []\n cols.append(fits.Column(name='GC_ID', format='D', array=[GCs[i].ID for i in range(len(GCs))]))\n cols.append(fits.Column(name='X_PIX', format='D', array=[GCs[i].x for i in range(len(GCs))]))\n cols.append(fits.Column(name='Y_PIX', format='D', array=[GCs[i].y for i in range(len(GCs))]))\n cols.append(fits.Column(name='SNR', format='D', array=[GCs[i].SNR for i in range(len(GCs))]))\n cols.append(fits.Column(name='RA', format='D', array=[GCs[i].ra for i in range(len(GCs))]))\n cols.append(fits.Column(name='DEC', format='D', array=[GCs[i].dec for i in range(len(GCs))]))\n cols.append(fits.Column(name='g', format='D', array=[GCs[i].g for i in range(len(GCs))]))\n cols.append(fits.Column(name='z', format='D', array=[GCs[i].z for i in range(len(GCs))]))\n cols.append(fits.Column(name='v', format='D', array=[GCs[i].v for i in range(len(GCs))]))\n cols.append(fits.Column(name='dv', format='D', array=[GCs[i].dv for i in range(len(GCs))]))\n cols.append(fits.Column(name='m', format='D', array=[GCs[i].m for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm', format='D', array=[GCs[i].dm for i in range(len(GCs))]))\n cols.append(fits.Column(name='r', format='D', array=[GCs[i].r for i in range(len(GCs))]))\n cols.append(fits.Column(name='age', format='D', array=[GCs[i].age for i in range(len(GCs))]))\n cols.append(fits.Column(name='g_MUSE', format='D',\n array=[GCs[i].g_MUSE for i in range(len(GCs))]))\n cols.append(fits.Column(name='z_MUSE', format='D',\n array=[GCs[i].z_MUSE for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_miles', format='D',\n array=[GCs[i].m_miles for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_miles', format='D',\n array=[GCs[i].dm_miles for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_amiles', format='D',\n array=[GCs[i].m_amiles for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_amiles', format='D',\n array=[GCs[i].dm_amiles for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_CaT', format='D',\n array=[GCs[i].m_CaT for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_CaT', format='D',\n array=[GCs[i].dm_CaT for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_b', format='D',\n array=[GCs[i].m_b for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_b', format='D',\n array=[GCs[i].dm_b for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_ssp', format='D',\n array=[GCs[i].m_ssp for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_ssp', format='D',\n array=[GCs[i].dm_ssp for i in range(len(GCs))]))\n cols.append(fits.Column(name='galaxy', format='A6',\n array=[GCs[i].galaxy for i in range(len(GCs))]))\n tbhdu = fits.BinTableHDU.from_columns(fits.ColDefs(cols))\n\n dwave = wave[1] - wave[0]\n wave0 = wave[0]\n wave1 = wave[-1]\n hdr = fits.Header()\n hdr['wave0'] = np.round(wave0, 4)\n hdr['wave1'] = np.round(wave1 + dwave, 4)\n hdr['dwave'] = dwave\n hdr['galaxy'] = galaxy\n\n hdu = fits.PrimaryHDU(header=hdr)\n hdu1 = fits.ImageHDU([GCs[i].spec + GCs[i].bg_spec for i in range(len(GCs))])\n hdu2 = fits.ImageHDU([GCs[i].bg_spec for i in range(len(GCs))])\n hdulist = fits.HDUList([hdu, tbhdu, hdu1, hdu2])\n if os.path.isfile(output_directory + filename):\n os.remove(output_directory + filename)\n hdulist.writeto(output_directory + filename)\n\n\ndef read_fits(file, i=1):\n hdulist = fits.open(file)\n data = hdulist[i].data\n # print(hdulist[i].header)\n return data, hdulist[i].header\n\n\ndef initialize_catalog(file, already_fitted=False, galaxy='FCC47'):\n GC_cat_table = read_fits(file, i=1)[0]\n GC_specs_unsubtracted = read_fits(file, i=2)[0]\n GC_specs_bg = read_fits(file, i=3)[0]\n header = read_fits(file, i=0)[1]\n wave = np.arange(header['wave0'], np.round(header['wave1'], 4), header['dwave'])\n if len(wave) == len(GC_specs_unsubtracted[0]) + 1:\n wave = wave[:-1]\n GCs = []\n miles = False\n amiles = False\n CaT = False\n get_ages = False\n best_ssp = False\n # print(GC_cat_table.names)\n if 'm_miles' in GC_cat_table.names:\n miles = True\n if 'm_amiles' in GC_cat_table.names:\n amiles = True\n if 'm_CaT' in GC_cat_table.names:\n CaT = True\n if 'm_ssp' in GC_cat_table.names:\n best_ssp = True\n if 'm_b' in GC_cat_table.names:\n balmer_met = True\n else:\n balmer_met = False\n if 'm_age' in GC_cat_table.names:\n get_ages = True\n for i, ID in enumerate(GC_cat_table.field('GC_ID')):\n xpix, ypix = GC_cat_table.field('X_PIX')[i], GC_cat_table.field('Y_PIX')[i]\n ra, dec = GC_cat_table.field('RA')[i], GC_cat_table.field('DEC')[i]\n SNR = GC_cat_table.field('SNR')[i]\n g = GC_cat_table.field('g')[i]\n z = GC_cat_table.field('z')[i]\n spec = GC_specs_unsubtracted[i] - GC_specs_bg[i]\n bg_spec = GC_specs_bg[i]\n galaxy = GC_cat_table.field('galaxy')[i]\n if already_fitted:\n v = GC_cat_table.field('v')[i]\n dv = GC_cat_table.field('dv')[i]\n m = GC_cat_table.field('m')[i]\n dm = GC_cat_table.field('dm')[i]\n r = GC_cat_table.field('r')[i]\n g_MUSE = GC_cat_table.field('g_MUSE')[i]\n z_MUSE = GC_cat_table.field('z_MUSE')[i]\n if miles:\n m_miles = GC_cat_table.field('m_miles')[i]\n dm_miles = GC_cat_table.field('dm_miles')[i]\n else:\n m_miles = 0\n dm_miles = 0\n if amiles:\n m_amiles = GC_cat_table.field('m_amiles')[i]\n dm_amiles = GC_cat_table.field('dm_amiles')[i]\n else:\n m_amiles = 0\n dm_amiles = 0\n if CaT:\n m_CaT = GC_cat_table.field('m_CaT')[i]\n dm_CaT = GC_cat_table.field('dm_CaT')[i]\n else:\n m_CaT = 0\n dm_CaT = 0\n if best_ssp:\n m_ssp = GC_cat_table.field('m_ssp')[i]\n dm_ssp = GC_cat_table.field('dm_ssp')[i]\n else:\n m_ssp = 0\n dm_ssp = 0\n if balmer_met:\n m_b = GC_cat_table.field('m_b')[i]\n dm_b = GC_cat_table.field('dm_b')[i]\n else:\n m_b = 0\n dm_b = 0\n if get_ages:\n age = GC_cat_table.field('age')[i]\n dage = GC_cat_table.field('dage')[i]\n m_age = GC_cat_table.field('m_age')[i]\n dm_age = GC_cat_table.field('dm_age')[i]\n else:\n age, dage, m_age, dm_age = 0, 0, 0, 0\n GCs.append(GC(ID, xpix, ypix, ra, dec, SNR=SNR, g=g, z=z, wave=wave, spec=spec, bg_spec=bg_spec, galaxy=galaxy,\n v=v, dv=dv, m=m, dm=dm, r=r, g_MUSE=g_MUSE, z_MUSE=z_MUSE, m_miles=m_miles, dm_miles=dm_miles,\n m_CaT=m_CaT, dm_CaT=dm_CaT, m_ssp=m_ssp, dm_ssp=dm_ssp, m_amiles=m_amiles, dm_amiles=dm_amiles, m_b=m_b, dm_b=dm_b,\n age=age, dage=dage, dm_age=dm_age, m_age=m_age))\n else:\n GCs.append(GC(ID, xpix, ypix, ra, dec, SNR=SNR, g=g, z=z,\n wave=wave, spec=spec, bg_spec=bg_spec, galaxy=galaxy))\n return GCs\n\n\ndef remove_from_cat(remove_file, GCs):\n IDs_to_remove = np.loadtxt(remove_file)\n\n new_GCs = []\n for i, GCi in enumerate(GCs):\n if GCi.ID in IDs_to_remove:\n print('Will remove GC {0}'.format(i))\n else:\n new_GCs.append(GCi)\n print('The new catalog contains {} GCs!'.format(len(new_GCs)))\n return new_GCs\n\n\ndef get_statistics_from_dist(array, lims=[1000, 2000], use_lims=False):\n if use_lims:\n mask = (array > lims[0]) & (array < lims[1])\n array = array[mask]\n med = np.percentile(array, 50)\n err_p = np.percentile(array, 100-16.84) - med\n err_m = med - np.percentile(array, 16.84)\n err = 0.5 * (np.round(err_p, 2) + np.round(err_m, 2))\n return np.round(med, 2), err\n\n\ndef der_snr(flux):\n \"\"\"\n REFERENCES * ST-ECF Newsletter, Issue #42:\n www.spacetelescope.org/about/further_information/newsletters/html/newsletter_42.html\n * Software:\n www.stecf.org/software/ASTROsoft/DER_SNR/\n AUTHOR Felix Stoehr, ST-ECF\n 24.05.2007, fst, initial import\n 01.01.2007, fst, added more help text\n 28.04.2010, fst, return value is a float now instead of a numpy.float64\n \"\"\"\n flux = np.array(flux[np.isfinite(flux)])\n # Values that are exactly zero (padded) or NaN are skipped\n flux = flux[(flux != 0.0) & np.isfinite(flux)]\n n = len(flux)\n # For spectra shorter than this, no value can be returned\n if n > 4:\n signal = np.median(flux)\n noise = 0.6052697 * np.median(np.abs(2.0 * flux[2:n-2] - flux[0:n-4] - flux[4:n]))\n return float(signal / noise)\n else:\n return 0.0\n\n\nclass host_galaxy():\n def __init__(self, name, xc=0, yc=0, PA=0, eps=0, vsys=0, Reff=0, mB=0, xoffset=0, yoffset=0, fwhm=0.8, mc=0):\n self.name = name\n self.xc = xc\n self.yc = yc\n self.PA = PA\n self.eps = eps\n self.vsys = vsys\n self.Reff = Reff\n self.mB = mB\n self.xoffset = xoffset\n self.yoffset = yoffset\n self.fwhm = fwhm/0.2\n self.mc = mc\n\n\ndef dist_circle(xc, yc, s):\n \"\"\"\n Returns an array in which the value of each element is its distance from\n a specified center. Useful for masking inside a circular aperture.\n\n The (xc, yc) coordinates are the ones one can read on the figure axes\n e.g. when plotting the result of my find_galaxy() procedure.\n\n FROM MGEFIT\n \"\"\"\n x, y = np.ogrid[:s[0], :s[1]] - np.array([yc, xc]) # note yc before xc\n rad = np.sqrt(x**2 + y**2)\n return rad\n\n\ndef get_galaxy_info(galaxy, file='/Users/kfahrion/Documents/Data_clean/MUSE_Data/galaxies.dat'):\n f = open(file)\n for line in f.readlines()[1:]: # skip header:\n columns = line.strip().split()\n gal_name = columns[0]\n if gal_name == galaxy:\n xc = int(columns[1])\n yc = int(columns[2])\n PA = float(columns[3])\n eps = float(columns[4])\n vsys = float(columns[5])\n Reff = float(columns[6])\n mB = float(columns[7])\n xoffset = float(columns[8])\n yoffset = float(columns[9])\n fwhm = float(columns[10])\n m_c = float(columns[11])\n try:\n return host_galaxy(galaxy, xc=xc, yc=yc, PA=PA, eps=eps, vsys=vsys, Reff=Reff, mB=mB, xoffset=xoffset, yoffset=yoffset, fwhm=fwhm, mc=m_c)\n except:\n print('{} not found in galaxies.dat!'.format(galaxy))\n return host_galaxy(galaxy)\n","sub_path":"GC_support.py","file_name":"GC_support.py","file_ext":"py","file_size_in_byte":14088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"251559776","text":"import tensorflow as tf\n\n\n# def scale_l2(x, eps=1e-3):\n# # shape(x) = (batch, num_timesteps, d)\n# # Divide x by max(abs(x)) for a numerically stable L2 norm.\n# # 2norm(x) = a * 2norm(x/a)\n# # Scale over the full sequence, dims (1, 2)\n# alpha = tf.reduce_max(tf.abs(x), (1, 2), keep_dims=True) + 1e-12\n# l2_norm = alpha * tf.sqrt(\n# tf.reduce_sum(tf.pow(x / alpha, 2), (1, 2), keep_dims=True) + 1e-6)\n# x_unit = x / l2_norm\n# return eps * x_unit\n\ndef scale_l2(x, eps=1e-3):\n # scale over the full batch\n return eps * tf.nn.l2_normalize(x, dim=[0, 1, 2])\n\ndef mask_by_length(t, length):\n \"\"\"Mask t, 3-D [batch, time, dim], by length, 1-D [batch,].\"\"\"\n maxlen = t.get_shape().as_list()[1]\n\n # Subtract 1 from length to prevent the perturbation from going on 'eos'\n mask = tf.sequence_mask(length, maxlen=maxlen)\n mask = tf.expand_dims(tf.cast(mask, tf.float32), -1)\n # shape(mask) = (batch, num_timesteps, 1)\n return t * mask\n\ndef logsoftmax(x):\n xdev = x - tf.reduce_max(x, 1, keep_dims=True)\n lsm = xdev - tf.log(tf.reduce_sum(tf.exp(xdev), 1, keep_dims=True))\n return lsm\n\ndef normalize_embed(self, emb, vocab_freqs):\n vocab_freqs = tf.constant(\n vocab_freqs, dtype=tf.float32, shape=[self.vocab_size, 1])\n weights = vocab_freqs / tf.reduce_sum(vocab_freqs)\n mean = tf.reduce_sum(weights * emb, 0, keep_dims=True)\n var = tf.reduce_sum(weights * tf.pow(emb - mean, 2.), 0, keep_dims=True)\n stddev = tf.sqrt(1e-6 + var)\n return (emb - mean) / stddev\n\ndef adv_example(inputs, loss):\n grad, = tf.gradients(\n loss,\n inputs,\n aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)\n grad = tf.stop_gradient(grad)\n perturb = scale_l2(grad)\n\n return inputs + perturb\n\ndef kl_divergence_with_logits(q_logit, p_logit):\n # https://github.com/takerum/vat_tf\n q = tf.nn.softmax(q_logit)\n qlogq = tf.reduce_mean(tf.reduce_sum(q * logsoftmax(q_logit), 1))\n qlogp = tf.reduce_mean(tf.reduce_sum(q * logsoftmax(p_logit), 1))\n kl = qlogq - qlogp\n return kl\n\ndef virtual_adversarial_loss(logits, length, sentence, pos1, pos2, pcnn_mask, logits_fn,\n lexical=None, num_iter=1, small_coef=1e-6):\n # Stop gradient of logits. See https://arxiv.org/abs/1507.00677 for details.\n logits = tf.stop_gradient(logits)\n\n # Initialize perturbation with random noise.\n d_sent = tf.random_normal(shape=tf.shape(sentence))\n\n # Perform finite difference method and power iteration.\n # See Eq.(8) in the paper http://arxiv.org/pdf/1507.00677.pdf,\n # Adding small noise to input and taking gradient with respect to the noise\n # corresponds to 1 power iteration.\n agg_method = tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N\n for _ in range(num_iter):\n d_sent = scale_l2(mask_by_length(d_sent, length), small_coef) \n vadv_sent = sentence + d_sent\n d_logits = logits_fn(vadv_sent, pos1, pos2, pcnn_mask)\n\n kl = kl_divergence_with_logits(logits, d_logits)\n d_sent, = tf.gradients(kl, d_sent, aggregation_method=agg_method)\n d_sent = tf.stop_gradient(d_sent)\n\n vadv_sent = sentence + scale_l2(d_sent)\n vadv_logits = logits_fn(vadv_sent, pos1, pos2, pcnn_mask)\n\n return kl_divergence_with_logits(logits, vadv_logits)","sub_path":"src-pcnn/models/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"542374496","text":"from twython import Twython, TwythonError\nimport time\n#Api info goes here\nAPP_KEY = 'XXXXX'\nAPP_SECRET = 'XXXXX'\nOAUTH_TOKEN = 'XXXXX'\nOAUTH_TOKEN_SECRET = 'XXXXX'\n#Use Twython to set up api access to twitter\napi = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\n#Read the things we need to tweet\nwith open('tweets.txt', 'r+') as tweetsfile:\n\ttweets = tweetsfile.readlines()\n\n#Loop through all the tweets\nfor line in tweets[:]: \n\ttry:\n\t\t\t#What are we tweeting\n\t\t\tprint (\"Trying to tweet:\\n\" + line)\n\t\t\t#DEBUG\n\t\t\t#length = str(len(line))\n\t\t\t#print (\"Line length: \" + length)\n\t\t\t#Attempt to send the tweet - exception will show & we'll move on.\n\t\t\tapi.update_status(status=line)\n\t\t\t#Debug\n\t\t\tprint(\"Successfully tweeted:\\n\" + line) \n\t#OHNOES!\n\texcept TwythonError as e:\n\t\t#in case it didn't work\n\t\terror = str(e)\n\t\tprint(\"Something went wrong :( \\nError message: \" + error + \"\\n\")\n\t\tpass\n\t#Rate limit \n\ttime.sleep(5)\n#Yey it worked\nprint (\"I have tweeted AllTheThings fit to tweet!\")\n\t","sub_path":"tweetbot.py","file_name":"tweetbot.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"465500787","text":"import threading\nfrom time import sleep, time\nfrom typing import Callable, Dict, List\n\nfrom basic_speech_to_text import speech_to_text, is_keyword_said, is_wake_up_word_said\nfrom plant_intent_recognizer.detect_intent import RasaIntent, Intent\n\nCALLBACK_INTENTS: Dict[Intent, List[Callable[[], None]]] = {}\n\n\ndef register_function_for_intent(intent: Intent):\n \"\"\"Register a function to be called every time an intent is detected by VoiceController\"\"\"\n def inner_decorator(f):\n def wrapped(*args, **kwargs):\n response = f(*args, **kwargs)\n return response\n\n print(f\"Registering {f} for intent: {intent.value}\")\n functions = CALLBACK_INTENTS.get(intent, [])\n functions.append(f)\n CALLBACK_INTENTS[intent] = functions\n return wrapped\n\n return inner_decorator\n\n\ndef _trigger_function_on_intent(intent: Intent):\n \"\"\"Trigger all function registered for this intent\"\"\"\n if intent not in CALLBACK_INTENTS:\n return\n functions = CALLBACK_INTENTS[intent]\n for f in functions:\n f()\n\n\nclass VoiceController:\n\n def __init__(self, active_time_delay=10):\n \"\"\"\n :param active_time_delay time in seconds after the keyword was said before being not \"active\"\n \"\"\"\n self._rasa_intent = RasaIntent()\n self.active = False\n self._stop = False\n self.active_time_delay = active_time_delay\n self.last_active_time = None\n\n self._thread = threading.Thread(target=self.run, args=())\n self._thread.daemon = True # Daemonize thread\n\n def stop(self):\n \"\"\"Stopping gracefully, might take a few seconds\"\"\"\n self._stop = True\n self._thread.join()\n\n def start(self):\n self._thread.start() # Call run()\n\n def run(self):\n self._stop = False\n while not self._stop:\n if self.active: # We actively listen to user command\n text = speech_to_text()\n print(f\"text: {text}\", flush=True)\n if text:\n intent = self._rasa_intent.detect_intent(text)\n print(f\"intent: {intent}\\n\", flush=True)\n _trigger_function_on_intent(intent)\n self.last_active_time = time()\n elif time() - self.last_active_time > self.active_time_delay:\n print(\"SLEEP MODE\", flush=True)\n self.active = False\n elif is_wake_up_word_said():\n print(\"ACTIVE MODE\", flush=True)\n self.active = True\n self.last_active_time = time()\n else:\n print(\"😴\", end='', flush=True) # Still in sleep mode\n\n\nif __name__ == '__main__':\n \"\"\"Example on how to use the register_function_for_intent wrapper\"\"\"\n @register_function_for_intent(intent=Intent.GREET)\n def greeting():\n print(\"Hello !\")\n\n @register_function_for_intent(intent=Intent.GREET)\n def greeting2():\n print(\"Hello 2 !\")\n\n @register_function_for_intent(intent=Intent.GOODBYE)\n def goodbye():\n print(\"goodbye !\")\n\n vc = VoiceController()\n vc.start()\n print(\"I can continue to do stuff\")\n sleep(60)\n print(\"Time to stop\")\n vc.stop()\n","sub_path":"voice_controller.py","file_name":"voice_controller.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"422244424","text":"#!/usr/bin/env python\n\nimport json\nfrom collections import namedtuple\nimport os\nimport re\nimport sys\n\n\nDevice = namedtuple('Device', ('major', 'minor'))\n\ndef get_container_block_file(ctid):\n \"\"\"Get the device file information for /dev/vdb in the container.\"\"\"\n\n device_info = os.stat('/var/lib/vz/private/{0}/dev/vdb'.format(ctid))\n return Device(\n major=os.major(device_info.st_rdev),\n minor=os.minor(device_info.st_rdev)\n )\n\n\ndef get_device_mappings(ctid):\n \"\"\"Get all devices mapped in the vz config file.\"\"\"\n\n device_line = \"\"\n with open('/etc/vz/conf/{0}.conf'.format(ctid), 'r') as f:\n for line in f:\n if line.startswith('DEVICES'):\n device_line = line\n break\n else:\n raise ValueError(\"No DEVICES line found in vz conf.\")\n\n return tuple(\n Device(major=int(m[0]), minor=int(m[1]))\n for m in re.findall('b:(\\d+):(\\d+)', device_line)\n )\n\n\ndef get_iscsi_device(ctid):\n \"\"\"Get device info for the actual iscsi mount point on the host.\n\n This uses the Cinder data stored in the ext_storage json file.\n \"\"\"\n\n iscsi_data = None\n with open('/etc/vz/conf/{0}.ext_storage'.format(ctid), 'r') as f:\n iscsi_data = json.loads(f.read())\n\n symlink = \"/dev/disk/by-path/ip-{0}-iscsi-{1}-lun-{2}\".format(\n iscsi_data['vdb']['data']['target_portal'],\n iscsi_data['vdb']['data']['target_iqn'],\n iscsi_data['vdb']['data']['target_lun'],\n )\n final_path = os.path.realpath(symlink)\n device_info = os.stat(final_path)\n return Device(\n major=os.major(device_info.st_rdev),\n minor=os.minor(device_info.st_rdev)\n )\n\nif __name__ == '__main__':\n\n for ctid in os.listdir('/var/lib/vz/private'):\n # Ignore any dirs that aren't integer CTID's (like . or ..).\n try:\n int(ctid)\n except:\n continue\n try:\n bf = get_container_block_file(ctid)\n dms = get_device_mappings(ctid)\n iscsi = get_iscsi_device(ctid)\n sys.stdout.write('Container Block File: {0}\\n'.format(bf))\n sys.stdout.write('Container Device Mappings: {0}\\n'.format(dms))\n sys.stdout.write('ISCSI Device: {0}\\n'.format(iscsi))\n if bf not in dms or bf != iscsi:\n sys.stderr.write('FAIL: Devices do not match for {0}!\\n'.format(ctid))\n sys.exit(-1)\n\n sys.stdout.write('PASS: Devices match for {0}.\\n'.format(ctid))\n except Exception as e:\n sys.stderr.write('SKIPPING: {0}. Something went wrong. {1}\\n'.format(ctid, e))\n","sub_path":"DBaaS/check_volume.py","file_name":"check_volume.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215012038","text":"import woodwork as ww\nfrom woodwork.accessor_utils import _is_koalas_series\nfrom woodwork.logical_types import (\n Boolean,\n BooleanNullable,\n Categorical,\n Datetime,\n Double,\n EmailAddress,\n Integer,\n IntegerNullable,\n LogicalType,\n Timedelta,\n Unknown,\n)\nfrom woodwork.tests.testing_utils import to_pandas\nfrom woodwork.utils import import_or_none\n\nUNSUPPORTED_KOALAS_DTYPES = [\n \"int32\",\n \"intp\",\n \"uint8\",\n \"uint16\",\n \"uint32\",\n \"uint64\",\n \"uintp\",\n \"float_\",\n \"object\",\n \"category\",\n]\n\nks = import_or_none(\"databricks.koalas\")\n\n\ndef get_koalas_dtypes(dtypes):\n return [dtype for dtype in dtypes if dtype not in UNSUPPORTED_KOALAS_DTYPES]\n\n\ndef test_integer_inference(integers):\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in integers:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Integer)\n\n\ndef test_double_inference(doubles):\n dtypes = [\"float\", \"float32\", \"float64\", \"float_\"]\n if _is_koalas_series(doubles[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in doubles:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Double)\n\n\ndef test_boolean_inference(bools):\n dtypes = [\"bool\", \"boolean\"]\n\n for series in bools:\n for dtype in dtypes:\n cast_series = series.astype(dtype)\n inferred_type = ww.type_system.infer_logical_type(cast_series)\n if to_pandas(cast_series).isnull().any():\n assert isinstance(inferred_type, BooleanNullable)\n else:\n assert isinstance(inferred_type, Boolean)\n\n\ndef test_datetime_inference(datetimes):\n dtypes = [\"object\", \"string\", \"datetime64[ns]\"]\n if _is_koalas_series(datetimes[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in datetimes:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Datetime)\n\n\ndef test_email_inference(emails):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(emails[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in emails:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, EmailAddress)\n\n\ndef test_email_inference_failure(bad_emails):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(bad_emails[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in bad_emails:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert not isinstance(inferred_type, EmailAddress)\n\n\ndef test_categorical_inference(categories):\n dtypes = [\"object\", \"string\", \"category\"]\n if _is_koalas_series(categories[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in categories:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_inference_based_on_dtype(categories_dtype):\n \"\"\"\n This test specifically targets the case in which a series can be inferred\n to be categorical strictly from its pandas dtype, but would otherwise be\n inferred as some other type.\n \"\"\"\n inferred_type = ww.type_system.infer_logical_type(categories_dtype[\"cat\"])\n assert isinstance(inferred_type, Categorical)\n\n inferred_type = ww.type_system.infer_logical_type(categories_dtype[\"non_cat\"])\n assert not isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_integers_inference(integers):\n with ww.config.with_options(numeric_categorical_threshold=0.5):\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in integers:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_double_inference(doubles):\n with ww.config.with_options(numeric_categorical_threshold=0.5):\n dtypes = [\"float\", \"float32\", \"float64\", \"float_\"]\n if _is_koalas_series(doubles[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in doubles:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_timedelta_inference(timedeltas):\n dtypes = [\"timedelta64[ns]\"]\n for series in timedeltas:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Timedelta)\n\n\ndef test_unknown_inference(strings):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(strings[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in strings:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Unknown)\n\n\ndef test_unknown_inference_all_null(nulls):\n dtypes = [\"object\", \"string\", \"category\", \"datetime64[ns]\"]\n if _is_koalas_series(nulls[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in nulls:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n inferred_type.transform(series)\n assert isinstance(inferred_type, Unknown)\n\n\ndef test_pdna_inference(pdnas):\n expected_logical_types = [\n Unknown,\n IntegerNullable,\n BooleanNullable,\n ]\n\n for index, series in enumerate(pdnas):\n inferred_type = ww.type_system.infer_logical_type(series)\n assert isinstance(inferred_type, expected_logical_types[index])\n\n\ndef test_updated_ltype_inference(integers, type_sys):\n inference_fn = type_sys.inference_functions[ww.logical_types.Integer]\n type_sys.remove_type(ww.logical_types.Integer)\n\n class Integer(LogicalType):\n primary_dtype = \"string\"\n\n type_sys.add_type(Integer, inference_function=inference_fn)\n\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in integers:\n for dtype in dtypes:\n inferred_type = type_sys.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Integer)\n assert inferred_type.primary_dtype == \"string\"\n","sub_path":"woodwork/tests/type_system/test_ltype_inference.py","file_name":"test_ltype_inference.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"508745341","text":"class queue:\n def __init__(self,n):\n self.arr=[0]*n\n self.head=0\n self.tail=-1\n def enqueue(self,k):\n self.tail+=1\n self.arr[self.tail]=k\n def dequeue(self):\n t=self.arr[self.head]\n self.head+=1\n return t\n def empty(self):\n return self.head-self.tail==1\n\nclass node:\n def __init__(self,val):\n self.val=val\n self.link=None\n\ndef adjacent(G,v):\n arr=[]\n ptr=G[v]\n while(ptr):\n arr.append(ptr.val)\n ptr=ptr.link\n return arr\n\nn=int(input('No. of nodes: '))\nG=[None]*n\nfor i in range(n):\n a=int(input('No. of adjacent nodes of node ' + str(i) +': '))\n for j in range(a):\n an=node(int(input()))\n an.link=G[i]\n G[i]=an\n\nindegree=[0]*n\nfor i in range(n):\n for w in adjacent(G,i):\n indegree[w]+=1\n\nq=queue(n)\nfor i in range(n):\n if(indegree[i]==0):\n q.enqueue(i)\n\nprint('Topological sorted order: ')\nfor i in range(n): #Topological sort\n e=q.dequeue()\n indegree[e]=-1\n print(e,end=' ')\n for w in adjacent(G,e):\n indegree[w]-=1\n if(indegree[w]==0):\n q.enqueue(w)","sub_path":"Graph/Topological_sort.py","file_name":"Topological_sort.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"474623690","text":"from os.path import join, dirname\n\nfrom nmigen import Fragment, Module, ClockSignal, DomainRenamer\n\nfrom cores.axi import AxiEndpoint\nfrom cores.axi.axi_lite_peripheral_connector import AxiLitePeripheralConnector\nfrom cores.axi.full_to_lite import AxiFullToLiteBridge\nfrom cores.axi.interconnect import AxiInterconnect\nfrom soc.memorymap import Address\nfrom soc.soc_platform import SocPlatform\nfrom cores.primitives.xilinx_s7.ps7 import PS7\nfrom .program_bitstream_ssh import program_bitstream_ssh\n\n\nclass ZynqSocPlatform(SocPlatform):\n base_address = Address(0x4000_0000, 0, (0x7FFF_FFFF - 0x4000_0000) * 8)\n pydriver_memory_accessor = open(join(dirname(__file__), \"memory_accessor_devmem.py\")).read()\n\n def __init__(self, platform):\n super().__init__(platform)\n self.ps7 = PS7(here_is_the_only_place_that_instanciates_ps7=True)\n self.final_to_inject_subfragments.append((self.ps7, \"ps7\"))\n\n def peripherals_connect_hook(platform, top_fragment: Fragment, sames):\n if platform.peripherals:\n m = Module()\n platform.ps7.fck_domain(domain_name=\"axi_lite\", requested_frequency=100e6)\n if not hasattr(platform, \"is_sim\"): # we are not in a simulation platform\n axi_full_port: AxiEndpoint = platform.ps7.get_axi_gp_master(ClockSignal(\"axi_lite\"))\n axi_lite_bridge = m.submodules.axi_lite_bridge = DomainRenamer(\"axi_lite\")(\n AxiFullToLiteBridge(axi_full_port)\n )\n axi_lite_master = axi_lite_bridge.lite_master\n else: # we are in a simulation platform\n axi_lite_master = AxiEndpoint(addr_bits=32, data_bits=32, master=True, lite=True)\n self.axi_lite_master = axi_lite_master\n interconnect = m.submodules.interconnect = DomainRenamer(\"axi_lite\")(\n AxiInterconnect(axi_lite_master)\n )\n\n for peripheral in platform.peripherals:\n controller = DomainRenamer(\"axi_lite\")(AxiLitePeripheralConnector(peripheral))\n m.d.comb += interconnect.get_port().connect_slave(controller.axi)\n m.submodules += controller\n platform.to_inject_subfragments.append((m, \"axi_lite\"))\n self.prepare_hooks.append(peripherals_connect_hook)\n\n def pack_bitstream_fatbitstream(self, builder):\n self.add_file(\"to_raw_bitstream.py\", open(join(dirname(__file__), \"to_raw_bitstream.py\")).read())\n builder.append_host(\"python3 to_raw_bitstream.py {{name}}.bit > {{name}}.bin\")\n builder.append_self_extracting_blob_from_file(\"{{name}}.bin\", \"/usr/lib/firmware/{{name}}.bin\")\n builder.append_command(\"echo {{name}}.bin > /sys/class/fpga_manager/fpga0/firmware\\n\")\n\n def toolchain_program(self, *args, **kwargs):\n program_bitstream_ssh(self, *args, **kwargs)","sub_path":"src/soc/platforms/zynq/zynq_soc_platform.py","file_name":"zynq_soc_platform.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"7732303","text":"import socket\nimport sys\n\n#---- INIT ----\nif len(sys.argv) < 2 :\n\tip = '0.0.0.0'\n\tport = 10000\n\n\nelif len(sys.argv) < 3 :\n\tip = sys.argv[1]\n\tport = 10000\n\nelse :\n\tip = sys.argv[1]\n\tport = int(sys.argv[2])\n\n\n# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect the client\n# client.connect((target, port))\nclient.connect((ip, port))\n\n# send some data \nclient.send('TEST')\n\n# receive the response data (4096 is recommended buffer size)\nresponse = client.recv(4096)\n\nprint(response)","sub_path":"test/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"623863813","text":"import pandas as pd\nimport csv\nimport json\nimport os\n\nPATH = '../json_data_dump_2/'\nO_PATH = '../scrutiny-thresh-1.0-2-samples/'\ngrp_id = 'grp0'\nprint('finding file names')\nfile_names = os.listdir(PATH)\n\ncnt_histogram = {\n 2:0,\n 3:0,\n 4:0,\n 5:0,\n 6:0\n }\n\nranking = []\ncnt = 0\nfor name in file_names:\n cnt += 1\n data_path = PATH + name\n print(\"Currently on \" + str(cnt) + \"th file\")\n with open(data_path) as infile:\n final_dump = {}\n data = json.load(infile)\n n_nodes = len(data['nodes'])\n cnt_histogram[n_nodes] += 1\n\n if len(data['nodes']) == 2:\n\n d_fuv = abs(data['nodes'][0]['fuv_mag']-data['nodes'][1]['fuv_mag'])\n d_nuv = abs(data['nodes'][0]['nuv_mag']-data['nodes'][1]['nuv_mag'])\n if (d_fuv > 1.0 or d_nuv > 1.0):\n outlier_rec = [['ID', 'RA', 'DEC'],\n [data['nodes'][0]['obsid'],\n data['nodes'][0]['ra'],\n data['nodes'][0]['dec']],\n [data['nodes'][1]['obsid'],\n data['nodes'][1]['ra'],\n data['nodes'][1]['dec']]]\n\n with open(O_PATH + data['lvl1_grp_id'] +'.csv', \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(outlier_rec)\n\n if d_fuv > d_nuv:\n attr = d_fuv\n else:\n attr = d_nuv\n\n ranking.append([attr, data['lvl1_grp_id']])\n\nprint(cnt_histogram)\nranking.sort()\n\nwith open(O_PATH + 'ranking.csv', \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(ranking)\n","sub_path":"finding-outliers.py","file_name":"finding-outliers.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"166897426","text":"import matplotlib.image as mpimg\nimport numpy.testing as npt\nimport os\nimport numpy as np\nimport matplotlib.image as mpimg\nimport re\nfrom PIL import Image\n\n# Helper functions\ndef load_image(infilename):\n data = mpimg.imread(infilename)\n return data\n\ndef img_float_to_uint8(img):\n rimg = img - np.min(img)\n rimg = (rimg / np.max(rimg) * 255).round().astype(np.uint8)\n return rimg\n\n# Concatenate an image and its groundtruth\ndef concatenate_images(img, gt_img):\n nChannels = len(gt_img.shape)\n w = gt_img.shape[0]\n h = gt_img.shape[1]\n if nChannels == 3:\n cimg = np.concatenate((img, gt_img), axis=1)\n else:\n gt_img_3c = np.zeros((w, h, 3), dtype=np.uint8)\n gt_img8 = img_float_to_uint8(gt_img) \n gt_img_3c[:,:,0] = gt_img8\n gt_img_3c[:,:,1] = gt_img8\n gt_img_3c[:,:,2] = gt_img8\n img8 = img_float_to_uint8(img)\n cimg = np.concatenate((img8, gt_img_3c), axis=1)\n return cimg\n\ndef make_img_overlay(img, predicted_img):\n w = img.shape[0]\n h = img.shape[1]\n color_mask = np.zeros((w, h, 3), dtype=np.uint8)\n color_mask[:,:,0] = predicted_img*255\n\n img8 = img_float_to_uint8(img)\n background = Image.fromarray(img8, 'RGB').convert(\"RGBA\")\n overlay = Image.fromarray(color_mask, 'RGB').convert(\"RGBA\")\n new_img = Image.blend(background, overlay, 0.2)\n return new_img\n\nforeground_threshold = 0.25 # percentage of pixels > 1 required to assign a foreground label to a patch\n\n# assign a label to a patch\ndef patch_to_label(patch):\n df = np.mean(patch)\n if df > foreground_threshold:\n return 1\n else:\n return 0\n\n\ndef mask_to_submission_strings(im, img_number):\n \"\"\"Reads a single image and outputs the strings that should go into the submission file\"\"\"\n patch_size = 16\n for j in range(0, im.shape[1], patch_size):\n for i in range(0, im.shape[0], patch_size):\n patch = im[i:i + patch_size, j:j + patch_size]\n label = patch_to_label(patch)\n yield(\"{:03d}_{}_{},{}\".format(img_number, j, i, label))\n\n\ndef masks_to_submission(submission_filename, *images):\n \"\"\"Converts images into a submission file\"\"\"\n with open(submission_filename, 'w') as f:\n f.write('id,prediction\\n')\n for index, image in enumerate(images[0:]):\n f.writelines('{}\\n'.format(s) for s in mask_to_submission_strings(image, index+1))\n\n# Extract patches from a given image\ndef img_crop_(im, w, h):\n list_patches = []\n imgwidth = im.shape[0]\n imgheight = im.shape[1]\n is_2d = len(im.shape) < 3\n \n for i in range(0, imgheight, h):\n i0 = i\n \n for j in range(0, imgwidth, w):\n j0 = j\n \n j_plus_w = j+w-1\n i_plus_h = i+h-1\n \n if i_plus_h >= imgheight:\n i_plus_h = imgheight-1\n i0= imgheight - h\n \n if j_plus_w >= imgwidth:\n j_plus_w = imgwidth-1\n j0 = imgwidth - w\n \n if is_2d:\n im_patch = im[i0:i_plus_h+1, j0:j_plus_w+1]\n else:\n im_patch = im[i0:i_plus_h+1, j0:j_plus_w+1, :]\n \n list_patches.append(im_patch)\n\n return list_patches\n\ndef build_from_patches(list_patches, h, w):\n patch_width = list_patches[0].shape[0]\n patch_height = list_patches[0].shape[1]\n is_2d = len(list_patches[0].shape) < 3\n rebuild_img = np.zeros((h, w))\n \n npt.assert_equal(is_2d == True, True)\n npt.assert_equal(len(list_patches) == 4, True)\n \n for i in range(0, patch_height):\n for j in range(0, patch_width):\n rebuild_img[i,j] = list_patches[0][i,j]\n \n width_begin = patch_width-(w%patch_width)\n for i in range(0, patch_height):\n for j in range(width_begin, patch_width):\n rebuild_img[i,patch_width+j-width_begin] = list_patches[1][i,j]\n \n height_begin = patch_height-(h%patch_height)\n for i in range(height_begin, patch_height):\n for j in range(0, patch_width):\n rebuild_img[patch_height+i-height_begin,j] = list_patches[2][i,j]\n \n for i in range(patch_height-(h%patch_height), patch_height):\n for j in range(0, patch_width):\n rebuild_img[patch_height+i-height_begin,patch_width+j-width_begin] = list_patches[3][i,j]\n \n return rebuild_img\n\ndef predict(image_input, model):\n patches = img_crop_(image_input, 400, 400)\n patches = np.array(patches)\n patch_predictions = model.predict(patches, verbose=1)\n patch_predictions = np.squeeze(patch_predictions)\n img = build_from_patches(patch_predictions, 608, 608)\n return img","sub_path":"playground/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"295630192","text":"from pathlib import Path\nfrom diot import Diot\nfrom bioprocs.utils import shell2 as shell\nfrom bioprocs.utils.reference import bamIndex\nfrom bioprocs.utils.tsvio2 import TsvReader, TsvWriter\n\ninfile = {{i.infile | quote}}\noutdir = Path({{o.outdir | quote}})\noutfile = {{o.outfile | quote}}\nsample = {{i.infile | stem2 | quote}}\nhla_la = {{args.hla_la | quote}}\npicard = {{args.picard |quote}}\nbwa = {{args.bwa | quote}}\njava = {{args.java | quote}}\nsamtools = {{args.samtools | quote}}\nnthread = {{args.nthread | repr}}\nparams = {{args.params | repr}}\n\nbamIndex(infile, samtools = samtools)\nshell.load_config(hla_la = hla_la)\n\nparams.picard_sam2fastq_bin = shell.which(picard)\nparams.bwa_bin = shell.which(bwa)\nparams.samtools_bin = shell.which(samtools)\nparams.java_bin = shell.which(java)\nparams.maxThreads = nthread\nparams.workingDir = outdir.parent\nparams.sampleID = sample\nparams.BAM = infile\nparams.graph = 'PRG_MHC_GRCh38_withIMGT'\n\nshell.fg.hla_la(**params)\n\nhlafile = outdir.joinpath('hla', 'R1_bestguess_G.txt')\nreader = TsvReader(hlafile)\nwriter = TsvWriter(outfile)\nwriter.cnames = ['Type', 'Allele', 'Reported'] + [cname for cname in reader.cnames if cname != 'Allele']\nwriter.writeHead()\n\nhits = []\nfor r in reader:\n\tif r.Locus not in hits:\n\t\thits.append(r.Locus)\n\t\tr.Type = r.Locus + ('_' if len(r.Locus) > 1 else '') + '1'\n\telse:\n\t\tr.Type = r.Locus + ('_' if len(r.Locus) > 1 else '') + '2'\n\tr.Reported = r.Allele\n\tr.Allele = 'HLA-' + r.Allele\n\twriter.write(r)\n","sub_path":"bioprocs/scripts/imtherapy/pHLA_LA.py","file_name":"pHLA_LA.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"431067506","text":"from __future__ import division, print_function, absolute_import\r\nimport os\r\nfrom tabula import read_pdf\r\nimport shutil\r\nimport pypyodbc\r\n\r\nstrDirectory=\"PDFs\\\\\"\r\nlMonths=['Jan?17','Feb?17','Mar?17','Apr?17','May?17','Jun?17','Jul?17','Aug?17','Sep?17','Oct?17','Nov?17','Dec?17']\r\nmonth_dict = {\"Jan?17\":\"01\",\"Feb?17\":\"02\",\"Mar?17\":\"03\",\"Apr?17\":\"04\", \"May?17\":\"05\", \"Jun?17\":\"06\",\"Jul?17\":\"07\",\"Aug?17\":\"08\",\"Sep?17\":\"09\",\"Oct?17\":\"10\",\"Nov?17\":\"11\",\"Dec?17\":\"12\"}\r\nconnection = pypyodbc.connect(r'Driver={SQL Server};Server=DEFR2DB61\\GTT;Database=YE_Mapping;Trusted_Connection=yes;')\r\ncursor = connection.cursor()\r\nSQLCommand = (\"INSERT INTO TS_TAX_RECEIVED \"\r\n \"(GID, Period, Payment_name_detail,AmountHome,Rate, CurrencyHost, id_file) \"\r\n\"VALUES (?,?,?,?,?,?,?) select SCOPE_IDENTITY()\")\r\ndef to_dict(name):\r\n return month_dict[name]\r\n\r\ndef ConvertPdfToExcel(sPath):\r\n dfPDF=read_pdf(sPath, pages=\"1\")\r\n dfPDF=dfPDF.dropna(axis=0,how='all')\r\n #countColumn=len(dfPDF.columns) - 1\r\n #dfPDF.drop(dfPDF.columns[[0,countColumn]], axis=1,inplace=True)\r\n dfPDF.columns.values[1] = 'Concept'\r\n bColumnHeaderCorrect=(True in dfPDF.columns.isin(lMonths))\r\n print(dfPDF)\r\n if (bColumnHeaderCorrect==True):\r\n sGID = os.path.splitext(sPath)[0][-8:]\r\n print(sPath)\r\n print(sGID)\r\n iterdfPDF = iter(dfPDF)\r\n next(iterdfPDF)\r\n for column in iterdfPDF:\r\n sServiceMonth=\"2017\" + to_dict(column)\r\n print(sServiceMonth)\r\n dfRev = dfPDF.loc[dfPDF.Component == \"Total Compensation (EUR)\"]\r\n sTotal_Revenues=dfRev[column].tolist()[0]\r\n fTotal_Revenues=float(sTotal_Revenues.replace(' ', '').replace(',', '.'))\r\n dfDed = dfPDF.loc[dfPDF.Component == \"Social Security Contributions\"]\r\n sTotal_Deduction=dfDed[column].tolist()[0]\r\n fTotal_Deduction=float(sTotal_Deduction.replace(' ', '').replace(',', '.'))\r\n dfExch = dfPDF.loc[dfPDF.Component == \"Exchange rate\"]\r\n sExchange_Rate = dfExch[column].tolist()[0]\r\n fExchange_Rate=float(sExchange_Rate.replace(' ', '').replace(',', '.'))\r\n Values = [sGID, sServiceMonth, 'TOTAL REVENUES',fTotal_Revenues,fExchange_Rate,'CLP', 1158]\r\n Values1 = [sGID, sServiceMonth, 'TOTAL DEDUCTIONS',fTotal_Deduction,fExchange_Rate,'CLP', 1158]\r\n #cursor.execute(SQLCommand, Values)\r\n #cursor.execute(SQLCommand, Values1)\r\n #connection.commit()\r\n print(dfPDF.to_string())\r\n else:\r\n print(\"Failed: \" + sPath)\r\n shutil.copy(rootpath1+ sPath,\r\n rootpath2+ os.path.basename(sPath))\r\n\r\n\r\n\r\nfor root, dirs, files in os.walk(strDirectory):\r\n for filename in files:\r\n #try:\r\n ConvertPdfToExcel(strDirectory + \"\\\\\" + filename)\r\n #except:\r\n #print(\"Failed: \" + filename)\r\n #shutil.copy(rootpath1+strDirectory+filename, rootpath2+\"Failed\\\\\"+filename)","sub_path":"Python/convert-pdf.py","file_name":"convert-pdf.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"112577508","text":"from django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.core import signing\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\n\nfrom . import constants as c\n\n\nclass Verifier():\n email_subject_template = 'email/verify_subject.txt'\n email_body_template_html = 'email/verify_body.html'\n email_body_template_txt = 'email/verify_body.txt'\n\n def __init__(self, user):\n self.user = user\n\n def get_email_context(self, verification_key):\n url = reverse('accounts:verify', kwargs={'verification_key': verification_key})\n return {\n 'domain': Site.objects.get_current().domain,\n 'url': url,\n 'user': self.user,\n }\n\n def send_verify_email(self):\n verification_key = self.get_verification_key()\n context = self.get_email_context(verification_key)\n subject = render_to_string(\n template_name=self.email_subject_template,\n context=context,\n )\n # Force subject to a single line to avoid header-injection issues\n subject = ''.join(subject.splitlines())\n message = render_to_string(\n template_name=self.email_body_template_txt,\n context=context,\n )\n html_message = render_to_string(\n template_name=self.email_body_template_html,\n context=context,\n )\n self.user.email_user_alternative(subject, message, from_email=settings.VERIFICATION_FROM_EMAIL,\n html_message=html_message, bcc=[settings.VERIFICATION_FROM_EMAIL])\n\n def get_verification_key(self):\n return signing.dumps(\n obj=self.user.get_username(),\n salt=settings.VERIFICATION_SALT,\n )\n\n\nclass VerificationError(Exception):\n pass\n\n\ndef send_manually_verify_email(user):\n ctx = {'user': user}\n subject = c.VERIFY_MANUALLY_EMAIL_SUBJECT\n email_body_template_html = 'email/verify_manual_body.html'\n email_body_template_txt = 'email/verify_manual_body.txt'\n\n message = render_to_string(\n template_name=email_body_template_txt,\n context=ctx,\n )\n html_message = render_to_string(\n template_name=email_body_template_html,\n context=ctx,\n )\n\n user.email_user_alternative(subject, message, from_email=settings.VERIFICATION_FROM_EMAIL,\n html_message=html_message, bcc=[settings.VERIFICATION_FROM_EMAIL])\n","sub_path":"Maco/accounts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"56298063","text":"# -*- coding: utf-8 -*-\n\n#################################################\n# tf.contrib.learn Quickstart\n#################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\n\n# Data sets\nIRIS_TRAINING = \"iris_training.csv\"\nIRIS_TEST = \"iris_test.csv\"\n\n#################################################\n# エントリーポイント\n# [Args]:\n#################################################\nif __name__ == '__main__':\n\n # Load datasets.\n training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,\n target_dtype=np.int)\n test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,\n target_dtype=np.int)\n\n # Specify that all features have real-value data0\n # 萼片の幅、萼片の高さ、花弁の幅、花弁の高さの4次元データ\n # (sepal width, sepal height, petal width, and petal height)\n feature_columns = [tf.contrib.layers.real_valued_column(\"\", dimension=4)]\n\n # Build 3 layer DNN with 10, 20, 10 units respectively.\n classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,\n hidden_units=[10, 20, 10],\n n_classes=3,\n model_dir=\"/tmp/iris_model\")\n\n # Fit model.\n print('--------------------------------------------------')\n print('Start fitting.')\n classifier.fit(x=training_set.data,\n y=training_set.target,\n steps=2000)\n\n # Evaluate accuracy.\n accuracy_score = classifier.evaluate(x=test_set.data,\n y=test_set.target)[\"accuracy\"]\n print('--------------------------------------------------')\n print('Accuracy: {0:f}'.format(accuracy_score))\n\n # Classify two new flower samples.\n # 新しい2サンプルを判定。正解は[1 2]らしい。\n new_samples = np.array(\n [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)\n y = classifier.predict(new_samples)\n print('--------------------------------------------------')\n print('Predictions: {}'.format(str(y)))","sub_path":"09.tf_contrib_learn/quick_start.py","file_name":"quick_start.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"332501474","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# Messy Things project organizer for Blender.\n# Copyright (C) 2017-2019 Mikhail Rachinskiy\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\nfrom bpy.types import Operator\nfrom bpy.props import BoolProperty\n\nfrom .cleanup_obj import cleanup_objects\nfrom .cleanup_mod import cleanup_modifiers\nfrom .cleanup_mat import cleanup_materials\nfrom .cleanup_gp import cleanup_gpencil\n\n\nclass SCENE_OT_messythings_cleanup(Operator):\n bl_label = \"Messy Things Cleanup\"\n bl_description = \"Remove redundant or purge all datablocks of set type\"\n bl_idname = \"scene.messythings_cleanup\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n use_cleanup_objects: BoolProperty(\n name=\"Objects\",\n description=(\n \"Remove lattice, curve and empty mesh objects that are not in use by \"\n \"modifiers, constraints, curve Bevel Object and Taper Object properties\"\n ),\n )\n use_cleanup_modifiers: BoolProperty(\n name=\"Modifiers\",\n description=\"Remove Curve, Lattice, Boolean and Shrinkwrap modifiers with empty Object or Target fields\",\n )\n use_cleanup_materials: BoolProperty(\n name=\"Materials (Purge)\",\n description=\"Purge all materials from file, additionally remove material slots from objects\",\n )\n use_cleanup_gpencil: BoolProperty(\n name=\"Annotations\",\n description=\"Remove redundant (Blender 2.7x) grease pencil object data from non grease pencil objects\"\n )\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False\n\n col = layout.column(align=True)\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_objects\")\n row.label(icon=\"OBJECT_DATA\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_modifiers\")\n row.label(icon=\"MODIFIER_DATA\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_materials\")\n row.label(icon=\"MATERIAL\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_gpencil\")\n row.label(icon=\"OUTLINER_OB_GREASEPENCIL\")\n\n def execute(self, context):\n msgs = []\n\n if self.use_cleanup_objects:\n curve, lat, mesh = cleanup_objects(context)\n msgs.append(f\"{curve} curve\")\n msgs.append(f\"{lat} lattice\")\n msgs.append(f\"{mesh} mesh\")\n\n if self.use_cleanup_modifiers:\n mod = cleanup_modifiers(context)\n msgs.append(f\"{mod} modifiers\")\n\n if self.use_cleanup_materials:\n mat = cleanup_materials(context)\n msgs.append(f\"{mat} materials\")\n\n if self.use_cleanup_gpencil:\n gp = cleanup_gpencil(context)\n msgs.append(f\"{gp} grease pencil\")\n\n if not msgs:\n return {\"CANCELLED\"}\n\n msg = \"Removed: \" + \", \".join(msgs)\n self.report({\"INFO\"}, msg)\n\n return {\"FINISHED\"}\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n","sub_path":"All_In_One/addons/messythings/op_cleanup/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"420430673","text":"import torch\nimport numpy as np\nimport argparse\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nimport os,copy\nimport matplotlib.pyplot as plt\nimport _pickle as cPickle\nfrom transformer_imputation_helper import *\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True\ntorch.manual_seed(1)\ntorch.cuda.manual_seed(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-d', '--device', type=int,help='device')\nparser.add_argument('-o', '--out-dir', type=str,help='dir to save checkpoints')\nparser.add_argument('-t', '--test', action='store_true',help='test')\nparser.add_argument('-w', '--warm-start', action='store_true',help='warm_start')\nparser.add_argument('-f', '--test-file', type=str,help='test-file')\nparser.add_argument('-e', '--start-epoch', type=int,help='checkpoint')\nparser.add_argument('-n', '--expname', type=str,help='checkpoint')\nparser.add_argument('-l', '--load-epoch', type=int,help='checkpoint')\nargs = parser.parse_args()\n\n\nlog_file = 'transformer_janta_%d_%s'%(args.load_epoch,args.expname)\n\nargs.device = 0\nargs.out_dir = '/mnt/infonas/blossom/pbansal/dump'\ndevice = torch.device('cuda:%d'%args.device)\nbatch_size = 64\nlr = 1e-4\n\ntrain_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_train_examples.npy')\nval_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_test_examples.npy')\nupdate_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_all_examples.npy')\n\ntrain_loader = torch.utils.data.DataLoader(train_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\nval_loader = torch.utils.data.DataLoader(val_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\nupdate_loader = torch.utils.data.DataLoader(update_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\n\nif (args.expname == 'both' or args.expname == 'both2'):\n model = OurModel(sizes=[76,28],ninp=32,embedding_size=16,nhid=32,nlayers=4,nhead=2,other_residuals=True).to(device)\nelse :\n model = OurModel(sizes=[76,28],ninp=32,embedding_size=16,nhid=32,nlayers=4,nhead=2,other_residuals=False).to(device)\n \nbest_state_dict = model.state_dict()\nbest_loss = float('inf')\nwriter = SummaryWriter(os.path.join('runs',log_file))\n\n\nprint (\"Starting Stage 1\")\n\noptim = torch.optim.Adam(model.parameters(),lr=lr)\n\nmax_epoch = 200\nswitch_epoch = args.load_epoch\niteration = int((args.load_epoch*len(train_set))/batch_size)\nstart_epoch = args.load_epoch\n\nfor epoch in range(start_epoch,max_epoch):\n print (\"Starting Epoch : %d\"%epoch)\n\n if (epoch == switch_epoch):\n print (\"Starting Stage 2\")\n model_dict = model.state_dict()\n best_state_dict = torch.load('best_janta_%depochs'%args.load_epoch)\n best_state_dict = {k: v for k, v in best_state_dict.items() if k not in ['outlier_layer1.weight','outlier_layer1.bias'] }\n model_dict.update(best_state_dict)\n model.load_state_dict(model_dict)\n residuals = torch.zeros(update_set.feats.shape).to(device)\n other_residuals = torch.zeros(update_set.feats.shape).to(device)\n means = torch.zeros(update_set.feats.shape).to(device)\n stds = torch.zeros(update_set.feats.shape).to(device)\n with torch.no_grad():\n for inp_,context_info in update_loader :\n out_,y_pred,sigma_pred = model.core(inp_.to(device),context_info)\n temp = (out_.to(device)-y_pred)/torch.exp(sigma_pred/2)\n if (args.expname == 'both'):\n other_residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = temp.to(device) # change here\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n elif (args.expname == 'both2'):\n other_residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = (out_.to(device)-y_pred) # change here\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n elif (args.expname == 'residuals'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = temp.to(device) # change here\n elif (args.expname == 'residuals2'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = (out_.to(device)-y_pred) # change here\n elif (args.expname == 'normalised'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n else :\n raise Exception\n means[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = y_pred\n stds[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = sigma_pred\n if (args.expname == 'both' or args.expname == 'both2'):\n model.other_residuals = other_residuals\n model.residuals = residuals\n model.means = means\n model.stds = stds\n model.switch()\n optim.zero_grad()\n \n if (epoch % 1 == 0):\n loss_mre_num,loss_mre_den,loss_crps = 0,0,0\n with torch.no_grad():\n for inp_,context_info in val_loader :\n loss = model.validate(inp_.to(device),context_info)\n loss_mre_num += loss['mae']*inp_.shape[0]\n loss_mre_den += loss['sum']*inp_.shape[0]\n loss_crps += loss['crps']*inp_.shape[0]\n writer.add_scalar('validation/mre_loss',loss_mre_num/loss_mre_den,iteration)\n writer.add_scalar('validation/mae_loss',loss_mre_num/len(val_set),iteration)\n writer.add_scalar('validation/crps_loss',loss_crps/len(val_set),iteration)\n \n if ((not model.stage2) and loss_crps < best_loss):\n best_loss = loss_crps\n best_state_dict = model.state_dict()\n \n print ('done validation')\n \n for inp_,context_info in train_loader :\n loss = model(inp_.to(device),context_info)\n optim.zero_grad()\n loss['nll'].backward()\n optim.step()\n iteration += 1\n writer.add_scalar('training/nll_loss',loss['nll'],iteration)\n writer.add_scalar('training/mae_loss',loss['mae'],iteration)\n\n\n\n\n","sub_path":"Transformer1Stage/transformer_imputation_ablation.py","file_name":"transformer_imputation_ablation.py","file_ext":"py","file_size_in_byte":6666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"153283788","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 11 11:42:19 2016\n\n@author: aaa34169\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport scipy as sp\nfrom scipy import signal\nimport btk\nimport pdb\n\nsys.path.append('C:\\\\Users\\\\AAA34169\\\\Documents\\\\Programming\\\\API\\\\pyCGA\\\\')\nimport core.tools as ct\n\nimport core.cgmModel as cgm\nimport core.modelFilters as cmf\nimport core.modelDecorator as cmd\nimport core.bodySegmentParameters as cbsp\nimport core.forceplates as cpf\nimport core.enums as cenum\nimport core.signal_processing as csip\nimport core.analysis as can\nimport core.cycle as cc\n\n\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \nplt.close(\"all\")\n\n\n\n\n\nclass GaitAnalysisTest(): \n\n @classmethod\n def viconCGM1(cls):\n \"\"\"\n \n \"\"\"\n\n MAIN_PATH = \"C:\\\\Users\\\\AAA34169\\\\Documents\\\\VICON DATA\\\\pyCGA-Data\\\\CGM1\\\\PIG standard\\\\basic-filtered\\\\\"\n \n \n kinematicAcqs=[]\n for gaitKinematicFilename in [\"MRI-US-01, 2008-08-08, 3DGA 12.c3d\" , \"MRI-US-01, 2008-08-08, 3DGA 13.c3d\",\"MRI-US-01, 2008-08-08, 3DGA 14.c3d\"]:\n acqGaitKinematics = ct.smartReader(str(MAIN_PATH + gaitKinematicFilename))\n kinematicAcqs.append(acqGaitKinematics)\n\n kineticAcqs=[] # To \n for gaitKineticFilename in [\"MRI-US-01, 2008-08-08, 3DGA 12.c3d\" , \"MRI-US-01, 2008-08-08, 3DGA 13.c3d\"]:\n acqGaitKinetics = ct.smartReader(str(MAIN_PATH + gaitKineticFilename))\n kineticAcqs.append(acqGaitKinetics)\n\n # -------------\n # CYCLE ANALYSIS\n #-------------\n # cycle builder\n cyclesBuilder = cc.GaitAnalysisCyclesBuilder(spatioTemporalAcquisitions=None, \n kinematicAcquisitions=kinematicAcqs,\n kineticAcquisitions= kineticAcqs,\n emgAcquisitions=None\n ) \n \n\n # cycle filter \n cf = cc.CyclesFilter()\n cf.setBuilder(cyclesBuilder) \n cyclesAnalysis = cf.getCyclesAnalysis()\n \n # -------------\n # GAIT ANALYSIS\n #-------------\n\n # dictionnaries \n subject={\"ipp\": \"000\",\n \"firstname\": \"NA\",\n \"surname\": \"NA\",\n \"sex\": \"M\",\n \"dob\": \"-\"\n }\n \n experimental={ \n \"date\": \"NA\",\n \"doctor\": \"NA\",\n \"context\": \"Research\",\n \"task\": \"S\",\n \"shoe\": \"N\",\n \"orthosis Prothesis\": \"N\",\n \"external Device\": \"N\",\n \"person assistance\": \"N\",\n \"nerve-block left\": \"NA\",\n \"nerve-block right\": \"NA\"\n } \n \n kinematicLabelsDict ={ 'Left': [\"LHipAngles\",\"LKneeAngles\",\"LAnkleAngles\"],\n 'Right': [\"RHipAngles\",\"RKneeAngles\",\"RAnkleAngles\"] }\n\n kineticLabelsDict ={ 'Left': [\"LHipMoment\",\"LKneeMoment\",\"LAnkleMoment\", \"LHipPower\",\"LKneePower\",\"LAnklePower\"],\n 'Right': [\"RHipMoment\",\"RKneeMoment\",\"RAnkleMoment\", \"RHipPower\",\"RKneePower\",\"RAnklePower\"]}\n\n \n \n # analysis Builder\n analysisBuilder = can.ConcreteGaitAnalysisBuilder(cyclesAnalysis,\n kinematicLabelsDict,\n kineticLabelsDict,\n modelLabel = \"NA\",\n subjectInfos = subject,\n experimentalInfos = experimental)\n \n # Filter\n af = can.AnalysisFilter()\n af.setBuilder(analysisBuilder)\n af.construct()\n stats = af.getStats() \n\n #af.exportDataFrame(\"fileOut\")\n\n\nif __name__ == \"__main__\":\n \n GaitAnalysisTest.viconCGM1()\n","sub_path":"tests/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"56239463","text":"import gdal\nimport gdalconst\nimport struct\n\nclass GeoTiffHandler:\n\n def __init__(self, file_name):\n self._fmttypes = {\n\t gdalconst.GDT_Byte: 'B',\n\t gdalconst.GDT_Int16: 'h',\n\t gdalconst.GDT_UInt16: 'H',\n\t gdalconst.GDT_Int32: 'i',\n\t gdalconst.GDT_UInt32: 'I',\n\t gdalconst.GDT_Float32: 'f',\n\t gdalconst.GDT_Float64: 'f'\n\t }\n self.ds = gdal.Open(file_name, gdalconst.GA_ReadOnly)\n if self.ds is None:\n raise FileNotFoundError(file_name)\n self.transf = self.ds.GetGeoTransform()\n self.cols = self.ds.RasterXSize\n self.rows = self.ds.RasterYSize\n self.bands = self.ds.RasterCount\n self.transfInv = gdal.InvGeoTransform(self.transf)\n\n def _pt2fmt(self, pt):\n return self._fmttypes.get(pt, 'x')\n\n def get_value_at_position(self, lat, lon, raster_band=1):\n band = self.ds.GetRasterBand(raster_band)\n bandtype = gdal.GetDataTypeName(band.DataType)\n px, py = gdal.ApplyGeoTransform(self.transfInv, lon, lat)\n if px > self.cols or py > self.rows:\n return None\n structval = band.ReadRaster(int(px), int(py), 1, 1,\n buf_type=band.DataType)\n fmt = self._pt2fmt(band.DataType)\n value = struct.unpack(fmt, structval)\n if value[0] == band.GetNoDataValue():\n if fmt == 'f':\n return float('nan')\n else:\n return None\n else:\n result = value[0]\n return value[0]\n\n def get_values_at_position(self, lat, lon):\n results = []\n for raster_band in range(1, self.bands+1):\n results.append(self.get_value_at_position(lat, lon, raster_band))\n return results\n","sub_path":"surface_map/geotiff_handler.py","file_name":"geotiff_handler.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"78673863","text":"from dlcliche.image import *\nfrom lib_fat2019 import *\n\nAPPNAME = 'final'\n\nconf.DURATION = 8\nconf.AUG_LEVEL = 1\nconf.CV = 1\nconf.RELABEL = ''\n\nconf.DATA = Path('/mnt/dataset/freesound-audio-tagging-2019')\nconf.ROOT = Path('/mnt/dataset/fat2019_files')\nconf.WORK = Path('/mnt/dataset/work/fat2019')\n\nconf.MODEL = 'specgram'\nconf.PRETRAINED_MODEL = 'base_models/base_36_specgram_6s_l1_best2.pth' # 'base_models/base_16_specgram_best.pth'\n\nconf.RESAMPLE = False\nconf.RESAMPLE_SIZES = None\n\nconf.USE_NOISY = True\nconf.NOISY_DATA = 'NOISY_SINGLE'\nconf.NOISY_SAMPLE_SIZES = None\n\nconf.NOISY_REMOVE_NG = ['Bus', 'Run',\n 'Male_speech_and_man_speaking',\n 'Cricket',\n 'Race_car_and_auto_racing',\n 'Printer',\n 'Church_bell',\n 'Crowd',\n 'Gong',\n 'Mechanical_fan',\n 'Traffic_noise_and_roadway_noise',\n 'Waves_and_surf']\n\nconf.noisy_OKs = ['Accelerating_and_revving_and_vroom', 'Accordion', 'Acoustic_guitar', 'Applause', 'Bark',\n 'Bass_drum', 'Bass_guitar', 'Bathtub_(filling_or_washing)', 'Bicycle_bell', 'Burping_and_eructation',\n 'Buzz', 'Car_passing_by', 'Cheering', 'Chewing_and_mastication', 'Child_speech_and_kid_speaking',\n 'Chink_and_clink', 'Chirp_and_tweet', 'Clapping', 'Computer_keyboard', 'Crackle',\n 'Cupboard_open_or_close', 'Cutlery_and_silverware','Dishes_and_pots_and_pans', 'Drawer_open_or_close', 'Drip',\n 'Electric_guitar', 'Fart', 'Female_singing', 'Female_speech_and_woman_speaking', 'Fill_(with_liquid)',\n 'Finger_snapping', 'Frying_(food)', 'Gasp', 'Glockenspiel', 'Gurgling',\n 'Harmonica', 'Hi-hat', 'Hiss', 'Keys_jangling', 'Knock',\n 'Male_singing', 'Marimba_and_xylophone', 'Meow', 'Microwave_oven', 'Motorcycle',\n 'Purr', 'Raindrop', 'Scissors', 'Screaming', 'Shatter',\n 'Sigh', 'Sink_(filling_or_washing)', 'Skateboard', 'Slam', 'Sneeze',\n 'Squeak', 'Stream', 'Strum', 'Tap', 'Tick-tock',\n 'Toilet_flush', 'Trickle_and_dribble', 'Walk_and_footsteps', 'Water_tap_and_faucet', 'Whispering',\n 'Writing', 'Yell', 'Zipper_(clothing)']\n\nconf.FORCE_SINGLE_LABEL = True\nconf.SUPER_MIXUP = True\n\nupdate_conf(conf)\nset_fastai_random_seed()\n\nbest_weight = f'{conf.NAME}_{APPNAME}'\n\ndf, X_train, learn, data = fat2019_initialize_training(conf)\n\nlearn.fit_one_cycle(8, 1e-1)\nlearn.fit_one_cycle(10, 1e-2)\nlearn.unfreeze()\nlearn.fit_one_cycle(20, 1e-2)\nlearn.fit_one_cycle(20, 1e-2)\nlearn.fit_one_cycle(20, 1e-2)\n\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(300, slice(1e-4, 1e-2), callbacks=get_saver_callbacks(conf, learn, best_weight))\n\nprint(f'Writing {best_weight}.csv ...')\ndf = evaluate_weight(conf, f'{best_weight}', for_what='train')\ndf.to_csv(f'work/models/{best_weight}.csv')\nprint('lwlrap', df_lwlrap_sum(df))\nprint(df[:10])\n","sub_path":"app-final-sp1s_8s.py","file_name":"app-final-sp1s_8s.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"457203188","text":"###########################################\n\n## Author : Divyesh Mehta\n## Type : Algorithm\n## Name : Dining Philosopher Problem\n## Language : Python\n\n###########################################\n\n#This program is an implementation of Dining Philosopher Problem\n\nimport threading\nimport random\nimport time\n\nclass Philosopher(threading.Thread):\n process = True\n\n def __init__(self, name, rfork, lfork):\n threading.Thread.__init__(self)\n self.name = name\n self.lfork = rfork\n self.rfork = lfork\n\n def run(self):\n while (self.process):\n time.sleep(random.uniform(1, 10))\n print(\"{} is hungry\".format(self.name))\n self.eat()\n\n def eat(self):\n fork1, fork2 = self.lfork, self.rfork\n\n while self.process:\n fork1.acquire(True)\n locked = fork2.acquire(False)\n if locked:\n break\n fork1.release()\n print(\"{} is swapping forks\".format(self.name))\n fork1, fork2 = fork2, fork1\n else:\n return\n\n self.eating()\n fork2.release()\n fork1.release()\n\n def eating(self):\n print(\"{} starts eating\".format(self.name))\n time.sleep(random.uniform(1, 10))\n print(\"{} started thinking\".format(self.name))\n\n\ndef DiningPhilosophers():\n forks = [threading.Lock() for n in range(5)]\n philosopher_names = ['Binod', 'Rashi', 'Gopi', 'Riya', 'Mike']\n\n philosophers = [Philosopher(philosopher_names[i], forks[i % 5], forks[(i + 1) % 5]) \\\n for i in range(5)]\n\n random.seed(100)\n Philosopher.process = True\n for p in philosophers:\n p.start()\n time.sleep(100)\n Philosopher.process = False\n print(\"Process Finished :)\")\n return\n\nDiningPhilosophers()\n","sub_path":"Python/dining_philosopher_problem.py","file_name":"dining_philosopher_problem.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"388673093","text":"\"\"\"\n\n------------------SENTIMENT ANALYSIS---------------------\n\n\n\"\"\"\n\nkey = \"c268c7f360854a62ae033b75205b916c\"\nendpoint = \"https://openbooknlp.cognitiveservices.azure.com/\"\n\n# from azure.ai.textanalytics import single_analyze_sentiment\n# from azure.ai.textanalytics import single_detect_language\n# from azure.ai.textanalytics import single_recognize_entities\n\nfrom azure.ai.textanalytics import TextAnalyticsClient, TextAnalyticsApiKeyCredential\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=TextAnalyticsApiKeyCredential(key))\n\ndocuments = [\n \"I did not like the restaurant. The food was too spicy. I had such a horrible time there I feel depressed as I was lonely.\",\n \"I feel amazeballs today. Such a wonderful time at these hackathons! Happiest day of my life!\",\n \"Mala kahich mahit nahi kay challay ithe?\"\n]\ndef detect_language(documents):\n # [START batch_detect_language]\n result = text_analytics_client.detect_language(documents)\n text = []\n for idx, doc in enumerate(result):\n if not doc.is_error:\n text.append(\"Document text: {}\".format(documents[idx]))\n text.append(\"Language detected: {}\".format(doc.primary_language.name))\n text.append(\"ISO6391 name: {}\".format(doc.primary_language.iso6391_name))\n text.append(\"Confidence score: {}\\n\".format(doc.primary_language.score))\n if doc.is_error:\n text.append(doc.id)\n text.append(doc.error)\n return \"
    \".join(text)\n # [END batch_detect_language]\n\ndef extract_key_phrases(documents):\n # [START batch_extract_key_phrases]\n \n text = []\n result = text_analytics_client.extract_key_phrases(documents)\n for doc in result:\n if not doc.is_error:\n text.append(\" \\n\".join(doc.key_phrases))\n elif doc.is_error:\n text.append('')\n # text.append(doc.error) \n\n return \",\".join(text)\n\ndef analyze_sentiment(documents):\n # [START batch_analyze_sentiment]\n result = text_analytics_client.analyze_sentiment(documents)\n docs = [doc for doc in result if not doc.is_error]\n sentiments = []\n sad_sentiments = []\n text = []\n for idx, doc in enumerate(docs):\n text.append(\"{}\".format(documents[idx]))\n text.append(\"sentiment: {} \\n\".format(doc.sentiment))\n sentiments.append(doc.sentiment)\n text.append(\" positive {0:.3f}; neutral {1:.3f}; negative {2:.3f} \\n\".format(\n doc.sentiment_scores.positive,\n doc.sentiment_scores.neutral,\n doc.sentiment_scores.negative,\n ))\n sad_sentiments.append(doc.sentiment_scores.negative)\n\n # for idx, sentence in enumerate(doc.sentences):\n # text.append(\"Sentence {} sentiment: {}\".format(idx+1, sentence.sentiment))\n # text.append(\"Sentence score: positive={0:.3f}; neutral={1:.3f}; negative={2:.3f}\".format(\n # sentence.sentiment_scores.positive,\n # sentence.sentiment_scores.neutral,\n # sentence.sentiment_scores.negative,\n # ))\n text.append(\"\\n\\n\\n\\n\\n\")\n \n top_sentiment = [[sentiments.count(i), i ] for i in set(sentiments)]\n top_sentiment.sort()\n top_sentiment = top_sentiment[-1][1]\n sad_avg = sum(sad_sentiments)/len(sad_sentiments)\n advice = 'keep up the mood'\n if sad_avg> 0.60 :\n advice = 'Hey are you okay? Talking to someone will make it better. Open your mind to a similar person or consult a profession in the chat section.'\n \n print('\\n\\n\\n\\n\\n',sad_avg,top_sentiment,sad_sentiments)\n return \"\\n\".join(text), top_sentiment, advice\n\n\"\"\"\n\n----------FLASK APP FROM HERE---------------------\n\n\n\"\"\"\nfrom flask import Flask\nfrom datetime import datetime\nfrom flask import render_template, request\nimport re\nimport os\nfrom ocr import return_ocr\nimport json\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\",result_string='',date=datetime.now(),txt_entry='')\n\n\n@app.route('/result',methods = ['POST'])\ndef result():\n if request.method == 'POST':\n result = request.form.get('paragraph_text')\n documents = result.split('.')\n result_string, top_sentiment, advice = analyze_sentiment(documents) \n phrases = extract_key_phrases(documents)\n dict_to_send = {\n \"01\":{\"tags\":phrases}\n }\n print(dict_to_send)\n with open('result.json', 'w') as fp:\n json.dump(dict_to_send, fp)\n return render_template(\"home.html\",result_string=result_string,date=datetime.now(),txt_entry=result,\n phrases=phrases, top_sentiment=top_sentiment, advice=advice)\n\n\n@app.route('/ocr',methods = ['POST','GET'])\ndef ocr():\n if request.method == 'POST':\n APP_ROOT = os.getcwd()\n target = os.path.join(APP_ROOT, 'static\\image')\n if not os.path.isdir(target):\n os.mkdir(target)\n for file in request.files.getlist(\"file\"):\n filename = file.filename\n destination = \"\\\\\".join([target, filename])\n file.save(destination)\n text, lines = return_ocr(destination)\n\n return render_template(\"home.html\",txt_entry=text,date=datetime.now())\n\n@app.route(\"/test\")\n\ndef test():\n sen = request.args.get('sen')\n confidence = request.args.get('confidence')\n\n return \"your sentiment is {} with confidence score {}\".format(sen,confidence)\n\n\n# @app.route(\"/new\")\n# def new():\n# journal = request.args.get('Param')\n# documents=[journal]\n# print (documents)\n# return analyze_sentiment(documents) + extract_key_phrases(documents) #+ detect_language(documents)\n\n # extract_key_phrases(documents)\n # analyze_sentiment(documents)\n # detect_language(documents)\n # print (journal)\n \n\n# New functions\n@app.route(\"/about/\")\ndef about():\n return render_template(\"about.html\")\n\n@app.route(\"/contact/\")\ndef contact():\n return render_template(\"contact.html\")\n\n\n@app.route(\"/search/\")\ndef search():\n with open('result.json') as json_file:\n user = json.load(json_file)\n tags = user[\"01\"][\"tags\"]\n tags = tags.split(',')\n\n with open('site/data.json') as json_file:\n users = json.load(json_file)\n user_tags = [users[i][\"tags\"] for i in users.keys()]\n user_tags = [x.split(',') for x in user_tags]\n \n return render_template(\"search.html\",len = len(tags), tags = tags, users = users, len_users = len(users) )\n\nif __name__ == '__main__':\n app.run(debug=True)\n# '127.0.0.1', port=8080,\n\n# @app.route(\"/api/data\")\n# def get_data():\n# return app.send_static_file(\"data.json\")","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"613511670","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:copyright: Copyright 2016-2020 Sphinx Confluence Builder Contributors (AUTHORS)\n:license: BSD-2-Clause (LICENSE)\n\"\"\"\n\nfrom bs4 import CData\nfrom tests.lib import build_sphinx\nfrom tests.lib import parse\nfrom tests.lib import prepare_conf\nimport os\nimport unittest\n\nclass TestConfluenceSphinxCodeblock(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.config = prepare_conf()\n test_dir = os.path.dirname(os.path.realpath(__file__))\n self.dataset = os.path.join(test_dir, 'datasets', 'common')\n\n def test_storage_sphinx_codeblock_caption(self):\n out_dir = build_sphinx(self.dataset, config=self.config,\n filenames=['code-block-caption'])\n\n with parse('code-block-caption', out_dir) as data:\n title_param = data.find('ac:parameter', {'ac:name': 'title'})\n self.assertIsNotNone(title_param)\n self.assertEqual(title_param.text, 'code caption test')\n\n def test_storage_sphinx_codeblock_default(self):\n out_dir = build_sphinx(self.dataset, config=self.config,\n filenames=['code-block'])\n\n with parse('code-block', out_dir) as data:\n code_macros = data.find_all('ac:structured-macro')\n self.assertIsNotNone(code_macros)\n self.assertEqual(len(code_macros), 3)\n\n for code_macro in code_macros:\n self.assertTrue(code_macro.has_attr('ac:name'))\n self.assertEqual(code_macro['ac:name'], 'code')\n\n # python block\n python_block = code_macros.pop(0)\n\n python_block_lang = python_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(python_block_lang)\n self.assertEqual(python_block_lang.text, 'python')\n\n python_block_linenumbers = python_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(python_block_linenumbers)\n self.assertEqual(python_block_linenumbers.text, 'true')\n\n python_block_body = python_block.find('ac:plain-text-body')\n python_block_cdata = next(python_block_body.children, None)\n self.assertIsNotNone(python_block_cdata)\n self.assertTrue(isinstance(python_block_cdata, CData))\n\n # sql block\n sql_block = code_macros.pop(0)\n\n sql_block_lang = sql_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(sql_block_lang)\n self.assertEqual(sql_block_lang.text, 'sql')\n\n sql_block_linenumbers = sql_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(sql_block_linenumbers)\n self.assertEqual(sql_block_linenumbers.text, 'false')\n\n sql_block_body = sql_block.find('ac:plain-text-body')\n sql_block_cdata = next(sql_block_body.children, None)\n self.assertIsNotNone(sql_block_cdata)\n self.assertTrue(isinstance(sql_block_cdata, CData))\n\n # ruby block\n ruby_block = code_macros.pop(0)\n\n ruby_block_lang = ruby_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(ruby_block_lang)\n self.assertEqual(ruby_block_lang.text, 'ruby')\n\n ruby_block_linenumbers = ruby_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(ruby_block_linenumbers)\n self.assertEqual(ruby_block_linenumbers.text, 'false')\n\n ruby_block_body = ruby_block.find('ac:plain-text-body')\n ruby_block_cdata = next(ruby_block_body.children, None)\n self.assertIsNotNone(ruby_block_cdata)\n self.assertTrue(isinstance(ruby_block_cdata, CData))\n\n # (check at least one code block's content)\n self.assertEqual(ruby_block_cdata,\n \"puts 'this is a print statement!'\")\n","sub_path":"tests/unit-tests/test_sphinx_codeblock.py","file_name":"test_sphinx_codeblock.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"138835117","text":"from django.conf.urls import url\r\nfrom django.urls import path\r\n\r\nfrom blog.views import FeedView, TogglePersonalFeedView, ReadPostView, SubscribeView, PostNewView, PostDetailView\r\n\r\nurlpatterns = [\r\n url(r'^user/(?P[0-9]+)/subscribe', SubscribeView.as_view(), name='subscribe'),\r\n url(r'^personalize', TogglePersonalFeedView.as_view(), name='personalize'),\r\n path(r'post/', PostDetailView.as_view(), name='post_detail'),\r\n url(r'^post/new', PostNewView.as_view(), name='new_post'),\r\n url(r'^post/(?P[0-9]+)/read', ReadPostView.as_view(), name='read_post'),\r\n url('^$', FeedView.as_view(), name='feed'),\r\n\r\n]\r\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"295756466","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 26 20:39:58 2017\r\n\r\n@author: Richard祥\r\n\"\"\"\r\n\r\ndef read_data(filename):\r\n lin = []\r\n with open(filename,'r',encoding='utf-8') as f :\r\n for line in f:\r\n lines = list(line.replace('\\n','').split(' '))\r\n print(lines)\r\n if lines :\r\n for i in range(len(lines)): \r\n lin.append(lines[i])\r\n else :\r\n continue\r\n return lin\r\ndef main():\r\n file=input('Write the filename: ')\r\n result=read_data(file)\r\n with open('Data.txt','w') as files:\r\n if result :\r\n for i in range(len(result)) :\r\n files.write(result[i])\r\n files.write('\\n')\r\n else : \r\n pass\r\nmain()","sub_path":"读取TXT文件数据.py","file_name":"读取TXT文件数据.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"181705370","text":"#!/usr/bin/env python\nimport xml.etree.ElementTree as etree\ntry: import urllib.request as urllib # py3\nexcept: import urllib # py2\n\ndef parse_rss(url):\n\tns = \"\"\n\tout = {}\n\t\n\trss = etree.parse(urllib.urlopen(url)).getroot()\n\tif len(rss.tag.split(\"}\")) > 1:\n\t\tns = rss.tag.split(\"}\")[0] + \"}\"\n\t\n\tif ns == \"{http://www.w3.org/2005/Atom}\":\n\t\tfor item in rss.getiterator(ns + \"entry\"):\n\t\t\tout[item.find(ns + \"title\").text] = item.find(ns + \"link\").attrib['href']\n\n\telse:\n\t\tfor item in rss.getiterator(ns + \"item\"):\n\t\t\tout[item.find(ns + \"title\").text] = item.find(ns + \"link\").text\n\t\n\treturn out\n\nif __name__ == \"__main__\":\n\timport sys\n\tif len(sys.argv) > 1:\n\t\tfor k, v in parse_rss(sys.argv[1]).items():\n\t\t\tprint(\"%s: %s\" % (k, v))\n\telse:\n\t\tprint(\"Usage: %s url\" % sys.argv[0])\n\n","sub_path":"apertium-tools/scraper/rssfucker.py","file_name":"rssfucker.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"367881535","text":"from _collections import deque\nimport sys\nqueue = deque()\nN = int(sys.stdin.readline())\n\nfor _ in range(N):\n tmpList = sys.stdin.readline().split()\n if tmpList[0] == \"push\":\n queue.appendleft(tmpList[1])\n elif tmpList[0] == \"top\":\n if len(queue) > 0:\n print(queue[-1])\n else:\n print(-1)\n elif tmpList[0] == \"size\":\n print(len(queue))\n elif tmpList[0] == \"empty\":\n if len(queue) > 0:\n print(0)\n else:\n print(1)\n elif tmpList[0] == \"pop\":\n if len(queue) > 0:\n print(queue.pop())\n else:\n print(-1)\n elif tmpList[0] == \"front\":\n if len(queue) > 0:\n print(queue[-1])\n else:\n print(-1)\n elif tmpList[0] == \"back\":\n if len(queue) > 0:\n print(queue[0])\n else:\n print(-1)","sub_path":" 200 - 자료구조 1/큐.py","file_name":"큐.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"245686404","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 13 16:13:02 2016\r\n\r\n@author: huliqun\r\n\"\"\"\r\nimport logging\r\n\r\nfrom workserver.util import LogUtil\r\nfrom workserver.util import SysUtil\r\n\r\n\r\nclass BatchBase(object):\r\n db = None\r\n dbr = None\r\n\r\n def __init__(self):\r\n className = self.__class__.__name__\r\n LogUtil.initLogBatch(className)\r\n SysUtil.global_init()\r\n self.engine = SysUtil.get_engine_handle()\r\n self.db = SysUtil.get_db_handle()\r\n self.logger = logging.getLogger('batchLog_' + className)\r\n\r\n def initialize(self):\r\n self.session = self.db()\r\n\r\n def release(self):\r\n self.session.close()\r\n\r\n def errorReturn(self):\r\n self.session.rollback()\r\n self.session.close()\r\n","sub_path":"workserver/batch/BatchBase.py","file_name":"BatchBase.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"597707672","text":"from app import models\nfrom app.app import mm_driver, config\nfrom app.app import app\nfrom flask import current_app\nfrom flask_apscheduler import APScheduler\nimport atexit\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import date, timedelta\n\nDICT_NEWS_KEY = \"dict_news\"\nSTANDARD_HEADERS = {\"User-Agent\": \"Zeus-Scraper/1.0 (+https://zeus.ugent.be/contact/)\"}\n\nDICT_NEWS_URL_BASE = \"https://helpdesk.ugent.be/nieuws/\"\n\nHYDRA_API_RESTO_BASE = \"https://hydra.ugent.be/api/2.0/resto/menu/nl/\"\n\nscheduler = APScheduler()\n\n\ndef get_dict_news():\n r = requests.get(DICT_NEWS_URL_BASE, headers=STANDARD_HEADERS)\n soup = BeautifulSoup(r.text, \"html.parser\")\n result = []\n for table in soup.find_all(\"table\", [\"table-newsoverview\"]):\n for row in table.find_all(\"tr\"):\n date = row.find(\"td\", [\"date\"]).find(\"span\").text\n link_element = row.find(\"a\")\n link_id = int(link_element.get(\"href\").split(\"?id=\")[-1])\n link = DICT_NEWS_URL_BASE + link_element.get(\"href\")\n message = link_element.text\n result.append(\n {\"id\": link_id, \"date\": date, \"message\": message, \"link\": link}\n )\n return result\n\n\ndef post_dict_news(n):\n message = f'**DICT NIEUWS** op {n[\"date\"]}: [{n[\"message\"]}]({n[\"link\"]})'\n print(f\"Posting {message}\")\n mm_driver.posts.create_post(\n options={\"channel_id\": config.sysadmin_channel_id, \"message\": message}\n )\n\n\n@scheduler.task(\"interval\", id=\"dict_news_task\", minutes=5)\ndef dict_news_task():\n with app.app_context():\n dict_config = models.KeyValue.query.filter_by(\n keyname=DICT_NEWS_KEY\n ).first() or models.KeyValue(DICT_NEWS_KEY, \"111\")\n news_items = get_dict_news()\n current_maxseen = int(dict_config.value)\n for news_item in get_dict_news():\n if news_item[\"id\"] > current_maxseen:\n current_maxseen = news_item[\"id\"]\n post_dict_news(news_item)\n dict_config.value = str(current_maxseen)\n dict_config.save()\n\n\ndef render_menu(menu_json):\n rendered = f\"#### Menu voor {menu_json['date']}\\n\"\n\n render_item = lambda i: f\" - {i['name']}\"\n\n soups = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"kind\"] == \"soup\", menu_json[\"meals\"]),\n )\n )\n mains = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"type\"] == \"main\", menu_json[\"meals\"]),\n )\n )\n colds = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"type\"] == \"cold\", menu_json[\"meals\"]),\n )\n )\n\n rendered += f\"##### Soep\\n{soups}\\n##### Hoofdgerecht\\n{mains}\\n##### Koud\\n{colds}\"\n return rendered\n\n\n@scheduler.task(\"cron\", id=\"resto_menu_task\", hour=4)\ndef resto_menu_task():\n today = date.today()\n today_url = f\"{HYDRA_API_RESTO_BASE}{today.year}/{today.month}/{today.day}.json\"\n try:\n today_json = requests.get(today_url).json()\n assert today_json['open']\n except:\n today_json = None\n\n tomorrow = today + timedelta(days=1)\n tomorrow_url = (\n f\"{HYDRA_API_RESTO_BASE}{tomorrow.year}/{tomorrow.month}/{tomorrow.day}.json\"\n )\n try:\n tomorrow_json = requests.get(tomorrow_url).json()\n assert tomorrow_json['open']\n except:\n tomorrow_json = None\n\n today_repr = render_menu(today_json) if today_json is not None else \"\"\n tomorrow_repr = render_menu(tomorrow_json) if tomorrow_json is not None else \"\"\n\n if (today_json is not None) or (tomorrow_json is not None):\n requests.post(\n config.resto_voedsels_webhook,\n json={\"text\": \"\\n\\n\".join([today_repr, tomorrow_repr])},\n )\n\n\nscheduler.api_enabled = True\nscheduler.init_app(app)\nscheduler.start()\n","sub_path":"app/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"446643928","text":"# -*- coding: utf-8 -*-\n\nfrom ze.spiders import ZeSpider\n\nclass FolhaDeSaoPauloSpider(ZeSpider):\n\n name = 'folhadesp'\n allowed_domains = ['folha.uol.com.br']\n parses = [{\n \"ze.items.creativework.ArticleItem\": {\n \"fields\": { \n \"name\": [ \n \"[itemprop=name]::text\", \n \"[itemprop=alternativeHeadline]::attr(content)\", \n \"article header h1::text\" \n ], \n \"image\": [ \n \"[itemprop=image]::attr(content)\", \n \"[property='og:image']::attr(content)\" \n ], \n \"description\": [ \n \"[itemprop=description]::text\", \n \".documentDescription::text\" \n ], \n \"author\": [\n \"[itemprop=author]::text\", \n \".author p::text\"\n ], \n \"datePublished\": [\n \"[itemprop=datePublished]::text\",\n \"article time::text\"\n ], \n \"dateModified\": [\n \"[itemprop=dateModified]::text\"\n ], \n \"articleBody\": [\n \"[itemprop=articleBody]\",\n \".content\" \n ], \n \"keywords\": [\n \"[itemprop=keywords]::text\", \n \"[itemprop=keywords]::attr(content)\"\n ]\n }\n }\n }]\n","sub_path":"ze/spiders/folhadesp.py","file_name":"folhadesp.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"392766422","text":"from flask import Blueprint, render_template, redirect, url_for, request, flash\nfrom flask_login import login_user, logout_user, login_required, current_user\n\nfrom datetime import datetime\n\nfrom src import db\nfrom src.models.tabelas import *\nfrom src.packages import CriptografiaAES\nfrom src.utils.usuario_utils import user_is_funcionario\n\ncripto = CriptografiaAES()\n\nauth_module = Blueprint('auth', __name__, url_prefix=\"/auth\",\n template_folder='../templates')\n\n\n@auth_module.route(\"/login\", methods=[\"GET\",\"POST\"])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('usuario.get_historico'))\n\n if request.method == 'GET':\n return render_template('login.html')\n\n if request.method == 'POST':\n email = request.form.get('email')\n senha = request.form.get('senha')\n\n chave_usuario = Tabela_chaves.query.filter_by(email=email).first()\n\n if not chave_usuario:\n flash('Por favor, verifique suas informações e tente novamente!', category='danger')\n return redirect(url_for('auth.login'))\n else:\n usuario = Usuario.query.filter_by(id_usuario=chave_usuario.id_usuario).first()\n senha_usuario = cripto.descriptografar(chave_usuario.chave_privada, usuario.password)\n\n if senha == senha_usuario:\n login_user(usuario)\n\n if user_is_funcionario(chave_usuario, current_user):\n return redirect(url_for('agendamento.agendamento'))\n\n return redirect(url_for('usuario.perfil'))\n else:\n flash('Por favor, verifique suas informações e tente novamente!', category='danger')\n return redirect(url_for('auth.login'))\n\n\n@auth_module.route('/registrar', methods=[\"GET\",\"POST\"])\ndef registrar():\n if request.method == 'GET':\n return render_template('registrar.html')\n\n if request.method == 'POST':\n email = request.form.get('email')\n nome = request.form.get('nome')\n cpf = request.form.get('cpf')\n senha = request.form.get('senha')\n data_nascimento = request.form.get('data')\n\n chave_usuario = Tabela_chaves.query.filter_by(email=email).first()\n\n if chave_usuario:\n flash('E-mail de usuário já existe!', category='danger')\n return redirect(url_for('auth.registrar'))\n\n chave = cripto.criaChave()\n\n try:\n data_nascimento = datetime.strptime(data_nascimento,'%Y-%m-%d').date()\n except ValueError as e:\n data_nascimento = datetime.strptime(data_nascimento,'%Y-%d-%m').date()\n\n is_func = False\n novo_usuario = Usuario(\n nome=cripto.criptografar(chave[\"chave\"], nome),\n email=cripto.criptografar(chave[\"chave\"], email),\n password=cripto.criptografar(chave[\"chave\"], senha),\n cpf=cripto.criptografar(chave[\"chave\"], cpf),\n data_nascimento=cripto.criptografar(chave[\"chave\"], data_nascimento),\n funcionario=cripto.criptografar(chave[\"chave\"], is_func)\n )\n\n db.session.add(novo_usuario)\n db.session.commit()\n\n nova_chave = Tabela_chaves(\n id_usuario=novo_usuario.id_usuario,\n chave_privada=chave[\"chave\"],\n email=email\n )\n\n db.session.add(nova_chave)\n db.session.commit()\n\n flash(f'Usuário {nome} cadastrado com sucesso', category='success')\n\n return redirect(url_for('auth.login'))\n\n\n@auth_module.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('.login'))","sub_path":"src/controllers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"323837352","text":"#!/usr/bin/env python3\n\nfrom mnist import MNIST\nfrom nnlib import NeuralNetwork\n\nbrain = NeuralNetwork()\n\nbrain.numOfLayers = 4\nbrain.numOfNeurons = [784, 32, 16, 10]\nbrain.programName = 'image-recognition'\n\nbrain.generateNeurons()\nbrain.useStoredWeights()\nbrain.useStoredBias()\n\n\nmndata = MNIST('image-recognition_trainingdata')\n\nprint('Carregando os dados para o treinamento...')\n\ntrain_images, train_labels = mndata.load_training()\n\nprint('Carregado!!')\n\nprint('--- tratando as imagens ---')\nfor i in range(len(train_images)):\n\tfor j in range(len(train_images[i])):\n\t\ttrain_images[i][j] = train_images[i][j]/255\n\nprint('--- imagens tratadas ---')\n\nprint('O treinamento iniciado!')\n\nquantidade = len(train_labels)\n\nfor i in range(quantidade):\n\tresult = [0]*10\n\tresult[train_labels[i]] = 1\n\tbrain.train(train_images[i], result)\n\tif i % 1000 == 0: print(round(100*i/quantidade, 1))\n\nprint('Treinamento finalizado!!')\n\nprint('Carregando os dados para o teste...')\n\ntest_images, test_labels = mndata.load_testing()\n\nprint('Dados carregados!')\n\nprint('--- tratando as imagens ---')\nfor i in range(len(test_images)):\n\tfor j in range(len(test_images[i])):\n\t\ttest_images[i][j] = test_images[i][j]/255\nprint('--- imagens tratadas ---')\n\nprint('Teste iniciado!')\n\nfor i in range(10):\t#number of tests to display\n\tguess = brain.guess(test_images[i])\n\tprint('------------')\n\tprint(guess)\n\tprint('guess: ' + str(guess.tolist().index(max(guess))))\n\tprint('real answer: ' + str(test_labels[i]))\n\nprint('Teste finalizado!')\n\nbrain.storeWeights()\nbrain.storeBias()\n","sub_path":"image-recognition.py","file_name":"image-recognition.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"233134144","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport soundfile as sf\n\nfrom mic_py.mic_io import read_mic_wav_from_lst, read_mic_wav_from_folder\nfrom mic_py.mic_stft import stft_arr\nfrom mic_py.feats import istft\nfrom mic_py.mic_geometry import get_sensor_positions, get_source_position, get_sensor_positions_kinect\nfrom mic_py.mic_steering import propagation_vector_free_field\nfrom mic_py.mic_ds_beamforming import ds_beamforming, ds_align\nfrom mic_py.mic_zelin import cross_spectral, calc_beta, zelin_filter\nfrom mic_py.mic_localisation import pseudospectrum_MUSIC, pseudospectrum_MUSIC_kinect\n\n\n\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n\n #################################################################\n # 1.0 - _no_echo_dist_1_0_angle_60 PROFILE MVDR\n vert_mic_count = 1\n hor_mic_count = 4\n max_len_sec = 80\n n_fft = 512\n\n in_wav_path = r'./data/_kinect/'\n #################################################################\n #################################################################\n _mix_start = 1\n _mix_end = 3\n #################################################################\n\n\n #################################################################\n # 1.0 - Read signal\n x_all_arr, sr = read_mic_wav_from_folder(in_wav_path, vert_mic_count, hor_mic_count, max_len_sec = max_len_sec)\n x_all_arr = x_all_arr[:,(np.int32)(_mix_start*sr):(np.int32)(_mix_end*sr)]\n\n (n_channels, n_samples) = x_all_arr.shape\n\n print (\"Array data read done!\")\n print (\" n_channels = \", n_channels)\n print (\" n_samples = \", n_samples)\n print (\" freq = \", sr)\n\n #################################################################\n # 2 - Do STFT\n stft_arr = stft_arr(x_all_arr, fftsize = n_fft)\n (n_bins, n_sensors, n_frames) = stft_arr.shape\n\n print (\"STFT calc done!\")\n print (\" n_bins = \", n_bins)\n print (\" n_sensors = \", n_sensors)\n print (\" n_frames = \", n_frames)\n\n #################################################################\n # 3 - Do localisation\n L = 1\n angle_step = 1\n arr_angle_h = range(-90, 90, angle_step)\n #arr_angle_v = range(-90, 90, angle_step)\n arr_angle_v = np.array([0])\n\n POW = pseudospectrum_MUSIC(stft_arr, L, arr_angle_h, arr_angle_v,\n n_fft = n_fft,\n sr = sr)\n\n\n # (len(arr_angle_h), len(arr_angle_v), n_bins)\n print (\"POW.shape = {}\".format(POW.shape))\n\n #################################################################\n # 4 - Plot DN\n lst_freq_bins = [10, 20, 30, 40, 150]\n\n for f_bin in lst_freq_bins:\n freq = f_bin*sr/n_fft\n plt.plot(arr_angle_h, POW[:, 0, f_bin], label=\"{} HZ\".format(freq))\n\n plt.plot(arr_angle_h, np.mean(POW[:, 0, 10:50], axis=1), label=\"AVERAGE\")\n\n plt.xlabel('angle_h (s)')\n plt.ylabel('MUSIC POW')\n plt.title('MUSIC alg')\n plt.legend(loc=\"upper right\")\n plt.grid(True)\n plt.savefig(r\".\\out\\MUSIC.png\")\n plt.show()\n\n\n","sub_path":"ma_py/_main_LOC_kinect.py","file_name":"_main_LOC_kinect.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32589052","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn import metrics\nfrom sklearn.metrics import r2_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom category_encoders import TargetEncoder\nimport time\n\ndef load_data():\n df = pd.read_csv(\"ModelData_product.csv\")\n df = df.loc[:, ~df.columns.str.contains('Unnamed: 0')]\n return df\ndef preprocessing(df):\n encoder = TargetEncoder()\n df['MainColorGroupDesc_en'] = encoder.fit_transform(df['MainColorGroupDesc'], df['ReturnRate'])\n encoder3 = TargetEncoder()\n df['USSize_en'] = encoder3.fit_transform(df['USSize'], df['ReturnRate'])\n ProductDivision_dummy = pd.get_dummies(df.ProductDivision)\n df = pd.concat([df, ProductDivision_dummy], axis=1)\n ERPMasterGender_dummy = pd.get_dummies(df.ERPMasterGender)\n df = pd.concat([df, ERPMasterGender_dummy], axis=1)\n x = df.drop(columns='ReturnRate')\n y = df[['ReturnRate']]\n y = y.values.ravel()\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=2021)\n x_train = x_train.drop(columns=['MainColorGroupDesc',\n 'ProductDivision',\n 'ERPMasterGender',\n 'USSize', 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n x_test_output = x_test.drop(columns=[\n 'ProductDivision',\n 'ERPMasterGender',\n 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n x_test = x_test.drop(columns=[\n 'MainColorGroupDesc',\n 'ProductDivision',\n 'ERPMasterGender',\n 'USSize', 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n return x_train, x_test, y_train, y_test, x_test_output\n\ndef dic(df):\n Product_Type_name = df[\"ProductDivision\"].unique()\n Product_Gender_name = df[\"ERPMasterGender\"].unique()\n Product_Color_name = df[\"MainColorGroupDesc\"].unique()\n Product_Size_name = df[\"USSize\"].unique()\n MainColorGroupDesc_dic = df[['MainColorGroupDesc', 'MainColorGroupDesc_en']]\n MainColorGroupDesc_dic = MainColorGroupDesc_dic.drop_duplicates()\n color_dic = pd.Series(MainColorGroupDesc_dic.MainColorGroupDesc_en.values,\n index=MainColorGroupDesc_dic.MainColorGroupDesc).to_dict()\n USSize_dic = df[['USSize', 'USSize_en']]\n USSize_dic = USSize_dic.drop_duplicates()\n USSize_dic.head()\n Size_dic = pd.Series(USSize_dic.USSize_en.values, index=USSize_dic.USSize).to_dict()\n return color_dic, Size_dic, Product_Type_name, Product_Gender_name, Product_Color_name, Product_Size_name\n\n@st.cache(allow_output_mutation=True)\ndef RandomForest(x_train, x_test, y_train, y_test):\n # Train the model\n\n RF = RandomForestRegressor(n_estimators=1000,\n min_samples_split= 10,\n min_samples_leaf= 4,\n max_features= 'auto',\n max_depth= 10,\n bootstrap= True)\n RF.fit(x_train, y_train)\n RF_pred = RF.predict(x_test)\n MAE = metrics.mean_absolute_error(y_test, RF_pred)\n MSE = metrics.mean_squared_error(y_test, RF_pred)\n RMSE = metrics.mean_squared_error(y_test, RF_pred)\n Rsquare = r2_score(y_test, RF_pred)\n return MAE, MSE, RMSE, Rsquare, RF\n\ndef Calculate_New_Transaction_Return(color_dic, Size_dic, ProductLine,\n Gender,\n Color,\n Size,\n UnitPrice,\n SalesQuantity,\n ReviewsCount,\n OverallRating):\n # set Footwear variable\n if ProductLine == \"Footwear\":\n Footwear = 1\n else:\n Footwear = 0\n\n # set KIDS variable\n if Gender == \"KIDS\":\n KIDS = 1\n else:\n KIDS = 0\n if ProductLine == \"Apparel\":\n Apparel = 1\n else:\n Apparel = 0\n\n # set KIDS variable\n if Gender == \"WNS\":\n WNS = 1\n else:\n WNS = 0\n if ProductLine == \"Accessories\":\n Accessories = 1\n else:\n Accessories = 0\n\n # set KIDS variable\n if Gender == \"MNS\":\n MNS = 1\n else:\n MNS = 0\n Color = color_dic[Color]\n # set USSize_en variable\n Size = Size_dic[Size]\n\n # new test data\n new_test_data = np.array([[UnitPrice, SalesQuantity, OverallRating, ReviewsCount, Color, Size, Accessories, Apparel,\n Footwear, KIDS, MNS, WNS]])\n return new_test_data\n\n\ndef main():\n st.title(\"Prediction Product Return Rate\")\n st.subheader(\"Using Machine Learning Regression Algorithms\")\n data = load_data()\n x_train, x_test, y_train, y_test, x_test_output = preprocessing(data)\n # check-box to show the merged clean data\n\n if st.checkbox('Show Raw Data'):\n st.write(\"This Dataset was Merged and Cleaned\")\n st.write(data.head())\n\n\n if st.checkbox('Show Model Performance'):\n st.write(\"This model is build by Random forest Algorithm\")\n MAE, MSE, RMSE, Rsquare, RF = RandomForest(x_train, x_test, y_train, y_test)\n st.text(\"Mean Absolute Error MAE: \")\n st.write(MAE)\n st.text(\"Mean Squared Error MSE: \")\n st.write(MSE)\n st.text(\"Root Mean Squared Error RMSE:\")\n st.write(RMSE)\n st.text(\"R^2:\")\n st.write(Rsquare)\n\n\n if (st.checkbox(\"Want to predict on your selected Input? \")):\n\n color_dic, Size_dic, Product_Type_name, Product_Gender_name, Product_Color_name, Product_Size_name = dic(data)\n number_UnitPrice = st.slider('UnitPrice', step=1, min_value=0, max_value=600)\n number_SalesQuanity = st.number_input('SalesQuanity', step=2, min_value=0, max_value=1904)\n number_ReviewCount = st.slider('Product Reviews Count', step=1, min_value=0, max_value=50)\n number_OverallRating = st.slider('Online Overall Rating', step=1, min_value=0, max_value=5)\n number_MainColorGroupDesc = st.selectbox('Product MainColor', Product_Color_name)\n number_USSize = st.selectbox('Product Size', Product_Size_name)\n option_ERPMasterGender = st.selectbox('Gender Category?', Product_Gender_name)\n option_ProductDivision = st.selectbox('Product Line?', Product_Type_name)\n\n new_test_data = Calculate_New_Transaction_Return(color_dic, Size_dic, option_ProductDivision,\n option_ERPMasterGender, number_MainColorGroupDesc,\n number_USSize, number_UnitPrice, number_SalesQuanity,\n number_ReviewCount, number_OverallRating)\n if st.button(\"Predict\"):\n with st.spinner('Wait for it...'):\n time.sleep(2)\n result = RF.predict(new_test_data)\n st.success('The Reture Rate is {}'.format(result))\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"202468938","text":"from conflux._utils.rpc_abi import (\n RPC,\n)\nfrom web3.manager import (\n RequestManager as DefaultRequestManager,\n)\nfrom web3.providers import (\n BaseProvider,\n)\nfrom web3.providers.ipc import (\n IPCProvider,\n)\nfrom web3.providers.rpc import (\n HTTPProvider,\n)\nfrom web3.providers.websocket import (\n WebsocketProvider,\n)\nfrom typing import (\n Any,\n cast,\n Dict,\n List,\n Optional,\n Sequence,\n TYPE_CHECKING\n)\nfrom web3._utils.module import (\n attach_modules,\n)\nfrom eth_abi.codec import (\n ABICodec,\n)\nfrom web3._utils.abi import (\n build_default_registry,\n build_strict_registry,\n map_abi_data,\n)\nfrom conflux.cfx import Cfx\nfrom eth_utils import (\n to_wei,\n from_wei,\n)\nfrom eth_utils.address import (\n to_checksum_address\n)\nfrom eth_utils.conversions import (\n to_bytes\n)\nfrom web3._utils.contracts import (\n find_matching_fn_abi\n)\nfrom web3._utils.abi import (\n get_abi_output_types\n)\nfrom cfx_address import (\n Address\n)\nfrom web3 import (\n Web3,\n)\n\ndef get_default_modules() -> Dict[str, Sequence[Any]]:\n return {\n \"cfx\": (Cfx,),\n }\n\nclass Conflux:\n # Providers\n HTTPProvider = HTTPProvider\n IPCProvider = IPCProvider\n WebsocketProvider = WebsocketProvider\n\n # Managers\n RequestManager = DefaultRequestManager\n\n # Currency Utility\n toDrip = staticmethod(to_wei)\n fromDrip = staticmethod(from_wei)\n\n cfx: Cfx\n\n def __init__(\n self,\n provider: Optional[BaseProvider] = None,\n middlewares: Optional[Sequence[Any]] = None,\n modules: Optional[Dict[str, Sequence[Any]]] = None,\n ) -> None:\n self.manager = self.RequestManager(self, provider, middlewares)\n\n self.codec = ABICodec(build_default_registry())\n\n if modules is None:\n modules = get_default_modules()\n\n attach_modules(self, modules)\n\n self._w3 = Web3(Web3.EthereumTesterProvider())\n\n @property\n def clientVersion(self) -> str:\n return self.manager.request_blocking(RPC.cfx_clientVersion, [])\n\n def contract(self, address, abi):\n hex_address = address\n if Address.has_network_prefix(address):\n hex_address = Address(address).eth_checksum_address\n\n return self._w3.eth.contract(address=hex_address, abi=abi)\n\n def call_contract_method(self, address, abi, method_name, *kargs):\n contract = self.contract(address, abi)\n tx = contract.functions[method_name](*kargs).buildTransaction({\n \"gas\": 21000,\n \"gasPrice\": 1,\n })\n call_result = self.cfx.call({\n \"to\": address,\n \"data\": tx['data']\n })\n fn_abi = find_matching_fn_abi(contract.abi, self._w3.codec, method_name, kargs)\n output_types = get_abi_output_types(fn_abi)\n decoded_result = self._w3.codec.decode_abi(output_types, to_bytes(hexstr=call_result))\n if len(output_types) == 1:\n return decoded_result[0]\n else:\n return decoded_result\n","sub_path":"conflux/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"404615099","text":"import tflearn\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\n\nimport dataset as data\n\n#import the cnn graphs\nimport graphs_norm.cnn_2layers as conv2\nimport graphs_norm.cnn_6layers as conv6\nimport graphs_norm.cnn_8layers as conv8\n#import alexnet\nimport graphs_norm.alexnet as alexnet\nimport graphs_norm.resnext as resnext\nimport graphs_norm.inception as inception\nimport graphs_norm.googlenet as googlenet\nimport graphs_norm.convnet as conv\n\nGRAPHS_DIR='graphs_norm/'\n#have to be in the same directory of the script or terminal\nDATASET_DIR='dataset/validation/'\n# MODEL_DIR='models/'\n# MODEL_DIR='models_augm/'\nMODEL_DIR='models_norm/'\nFILE_NAME='summary_norm.csv'\nNOTES = 'note?'\n\n# 50x50 pixel\nIMG_SIZE = 50\n\n#create summary file\nwith open(FILE_NAME, 'w') as f:\n f.write('dataset,model,pp,pv,pt,vp,vv,vt,perc_full,perc_empty,perc_tot\\n')\n\n\n\ndef eval(model_graph):\n print('model_graph: ',model_graph)\n tf.reset_default_graph()\n LR=model_graph.split('-')[2]\n dot_split = model_graph.split('.')\n dash_split = dot_split[-2].split('-')\n model = dash_split[-1]\n model_name = model\n graph = globals()[model]\n network = graph.network([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n model = tflearn.DNN(network, tensorboard_dir='log')\n name = os.path.join(MODEL_DIR, model_graph)\n model.load(name)\n print('Model successfully loaded from ', name)\n\n # load\n for dataset in os.listdir(DATASET_DIR):\n test_data = np.load(os.path.join(DATASET_DIR,dataset))\n print('test_data:', dataset)\n \n c1 = 0\n c2 = 0\n w1 = 0\n w2 = 0\n ft = 0\n et = 0\n\n for num, data in enumerate(test_data[:]):\n # full [0,1] empty [1,0]\n img_data = data[0]\n img_num = data[1]\n\n orig = img_data\n # restore the image shape\n data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n # the [0] is the return of the prediction and is the prob of the image being a cat\n model_out = model.predict([data])[0]\n\n if img_num[0] == 0: ft = ft + 1\n else: et = et + 1\n \n if np.argmax(model_out) == 1: \n # print('model thinks is full')\n if img_num[0] == 0: c1 = c1 + 1\n else: w1 = w1 + 1\n\n else: \n # print('model thinks is empty')\n if img_num[0] == 1: c2 = c2 + 1\n else: w2 = w2 + 1\n\n \n print('full: ',ft)\n print('empty: ',et)\n print('classificata come piena ma era vuota : ',w1)\n print('classificata come vuota ma era piena: ',w2)\n print('classificata come piena ed era piena : ',c1)\n print('classificata come vuota ed era vuota: ',c2)\n\n # % full right\n perc_full = c1 * 100 / ft\n perc_empty = c2 * 100 / et\n perc_tot = (c1+c2)*100/(ft+et)\n perc_full = float(\"{0:.2f}\".format(perc_full))\n perc_empty = float(\"{0:.2f}\".format(perc_empty))\n perc_tot = float(\"{0:.2f}\".format(perc_tot))\n\n # write\n with open(FILE_NAME, 'a') as f:\n f.write('{},{},{},{},{},{},{},{},{},{},{}\\n'.format(dataset,model_name,c1,w2,ft,w1,c2,et,perc_full,perc_empty,perc_tot))\n\n \n\n# REPEAT FOR ALL THE MODELS\nfor data in tqdm(os.listdir(MODEL_DIR)):\n if not data.startswith('.'):\n model_name = data.split('.')\n model_ext = model_name[-1]\n model_graph = '.'.join(model_name[:-1])\n if model_ext =='data-00000-of-00001':\n eval(model_graph)\n\n\n\nwith open(FILE_NAME, 'a') as f:\n f.write('{}\\n'.format(NOTES))\n\n\n ########## PLOT DATA and SHOW PREDICTIONS ##########\n #plot the data\n# fig = plt.figure()\n\n# #reset the graph\n# tf.reset_default_graph()\n# conv2_convnet = conv2.convnet([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n# # tenserboard_dir not needed on mac or ubuntu\n# conv2_model = tflearn.DNN(conv2_convnet, tensorboard_dir='log')\n# #load the model\n# conv2_model.load(CNN2)\n# print('model ',CNN2,' loaded!')\n\n# def a():\n# #reset the graph\n# tf.reset_default_graph()\n# conv2_convnet = conv2.convnet([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n# # tenserboard_dir not needed on mac or ubuntu\n# conv2_model = tflearn.DNN(conv2_convnet, tensorboard_dir='log')\n# #load the model\n# conv2_model.load(CNN2)\n# print('model ',CNN2,' loaded!')\n#\n# c = 0\n# w = 0\n# f = 0\n# e = 0\n#\n# for num, data in enumerate(test_data[:]):\n# # full [0,1] empty [1,0]\n# img_data = data[0]\n# img_num = data[1]\n#\n# # 3 by 4 and the numbur is the number plus 1 (because array starts from 0)\n# # y = fig.add_subplot(3,4,num+1)\n# orig = img_data\n# # restore the image shape\n# data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n# # the [0] is the return of the prediction and is the prob of the image being a cat\n# model_out = model.predict([data])[0]\n# # model_conv6_out = conv6_model.predict([data])[0]\n# # model_conv8_out = conv8_model.predict([data])[0]\n# # model_alexnet_out = alexnet_model.predict([data])[0]\n#\n# if img_num[0] == 0:\n# f = f + 1\n# else: \n# e = e + 1\n# \n# if np.argmax(model_out) == 1: \n# # print('img_num: ',img_num)\n# # print('model thinks is full')\n# # print('model out: ',model_conv2_out)\n# # print('model out: ',model_conv2_out[0])\n# if img_num[0] == 0:\n# c = c + 1\n# else:\n# w = w + 1\n#\n# else: \n# if img_num[0] == 1:\n# c = c + 1\n# else:\n# w = w + 1\n#\n# print('full: ',f)\n# print('empty: ',e)\n#\n# print('wrong: ',w)\n# print('right: ',c)\n#\n# # y.imshow(orig, cmap='gray')\n# # string = str_label_c,' ',model_conv2_out,' - ',str_label_a,' ',model_alexnet_out\n# # print(string)\n# # plt.title(string)\n# # y.axes.get_xaxis().set_visible(False)\n# # y.axes.get_yaxis().set_visible(False)\n# # plt.show()\n# # # write\n# # with open('submission-file.csv','w') as f:\n# # f.write('id,label\\n')\n# #\n# # with open('submission-file.csv','a') as f:\n# # for data in tqdm(test_data):\n# # img_num = data[1]\n# # img_data = data[0]\n# # orig = img_data\n# # data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n# # model_out = model.predict([data])[0]\n# # f.write('{},{}\\n'.format(img_num, model_out[1]))\n#\n","sub_path":"1_evaluate_norm.py","file_name":"1_evaluate_norm.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"388132277","text":"import sys\n\ndef parse(fea):\n subs = {}\n baseGlyphs = None\n for statement in fea.statements:\n if getattr(statement, \"name\", None) in (\"isol\", \"ccmp\"):\n for substatement in statement.statements:\n if hasattr(substatement, \"glyphs\"):\n # Single\n originals = substatement.glyphs[0].glyphSet()\n replacements = substatement.replacements[0].glyphSet()\n subs.update(dict(zip(originals, replacements)))\n elif hasattr(substatement, \"glyph\"):\n # Multiple\n subs[substatement.glyph] = substatement.replacement\n elif getattr(statement, \"name\", None) == \"GDEF\":\n for substatement in statement.statements:\n if hasattr(substatement, \"baseGlyphs\"):\n baseGlyphs = substatement.baseGlyphs\n if hasattr(baseGlyphs, \"glyphclass\"):\n baseGlyphs = baseGlyphs.glyphclass\n\n return subs, baseGlyphs\n\ndef build(font, features):\n subs, baseGlyphs = parse(features)\n\n temp_glyph = font.createChar(-1, \"TempXXX\")\n\n for base in subs:\n names = subs[base]\n glyph = font.createMappedChar(base)\n # build the composite on a temp glyph to prevent FontForge from using\n # its built-in knowledge about components of some encoded glyphs.\n temp_glyph.clear()\n temp_glyph.addReference(names[0])\n for name in names[1:]:\n temp_glyph.appendAccent(name)\n temp_glyph.build()\n glyph.clear()\n glyph.references = temp_glyph.references\n glyph.useRefsMetrics(names[0])\n glyph.color = 0xff0000\n baseGlyphs.glyphs.append(base)\n\n font.removeGlyph(temp_glyph)\n","sub_path":"tools/buildencoded.py","file_name":"buildencoded.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"17347763","text":"# 문제9.\n# 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요.\n\nst = input('입력>')\nfor i in st:\n i = st.strip()\nprint ('결과>'+''.join(reversed(i)))\n\n# s = 'java'\n# s = s.strip()\n# print(s)","sub_path":"practice01/quiz_09.py","file_name":"quiz_09.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"275113748","text":"import numpy as np\nimport pandas as pd\nfrom functions import *\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n# Get the data\nstd_train_Km = np.load('std_train_Km.npy')\nstd_test_Km = np.load('std_test_Km.npy')\nstd_train_Vmax = np.load('std_train_Vmax.npy')\nstd_test_Vmax = np.load('std_test_Vmax.npy')\ntrain_labels = np.load('trainLabels.npy')\ntest_labels = np.load('testLabels.npy')\nstd_test_data = np.concatenate((std_test_Km, std_test_Vmax), axis = 1)\nstd_train_data = np.concatenate((std_train_Km, std_train_Vmax), axis = 1)\nindices_all = np.load('indices.npy')\n\nprint(len(indices_all))\n\nstd_train_data = std_train_data[:,indices_all]\nstd_test_data = std_test_data[:,indices_all]\n\n# define the grid search parameters\nnb_neurons = [10,50,100,500,1000]\nepochs = [50,100,500,1000]\nparam_grid = dict(nb_neurons=nb_neurons,epochs = epochs)\n\n# create model with only one hidden layer\n#model_1 = KerasClassifier(build_fn=create_model_1, batch_size=256, verbose=0)\n\n#grid_1 = GridSearchCV(estimator=model_1, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=3, verbose=5)\n#grid_result_1 = grid_1.fit(std_train_data, train_labels)\n\n# summarize results\n#print(\"Best: %f using %s\" % (grid_result_1.best_score_, grid_result_1.best_params_))\n#means_1 = grid_result_1.cv_results_['mean_test_score']\n#stds_1 = grid_result_1.cv_results_['std_test_score']\n#params_1 = grid_result_1.cv_results_['params']\n\n# save results\n#cv_results_1 = pd.DataFrame(grid_result_1.cv_results_)\n#cv_results_1.to_pickle('cv_results_NN_1')\n\n# create model with two hidden layers (having the same neurons)\nmodel_2 = KerasClassifier(build_fn=create_model_2,batch_size=512, verbose=0)\n\ngrid_2 = GridSearchCV(estimator=model_2, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=3, verbose=5)\ngrid_result_2 = grid_2.fit(std_train_data, train_labels)\n\n# summarize results\nprint(\"Best: %f using %s\" % (grid_result_2.best_score_, grid_result_2.best_params_))\nmeans_2 = grid_result_2.cv_results_['mean_test_score']\nstds_2 = grid_result_2.cv_results_['std_test_score']\nparams_2 = grid_result_2.cv_results_['params']\n\n# save results\ncv_results_2 = pd.DataFrame(grid_result_2.cv_results_)\ncv_results_2.to_pickle('cv_results_NN_2')\n\n\n","sub_path":"project2/NN_grid_final.py","file_name":"NN_grid_final.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"472403605","text":"import hazelcast\n\nfrom hazelcast import ClientConfig\nfrom hazelcast.serialization.api import Portable\nfrom hazelcast.serialization.predicate import SqlPredicate, and_, is_between, is_equal_to\n\n\nclass User(Portable):\n FACTORY_ID = 1\n CLASS_ID = 1\n\n def __init__(self, username=None, age=None, active=None):\n self.username = username\n self.age = age\n self.active = active\n\n def write_portable(self, writer):\n writer.write_utf(\"username\", self.username)\n writer.write_int(\"age\", self.age)\n writer.write_boolean(\"active\", self.active)\n\n def read_portable(self, reader):\n self.username = reader.read_utf(\"username\")\n self.age = reader.read_int(\"age\")\n self.active = reader.read_boolean(\"active\")\n\n def get_factory_id(self):\n return self.FACTORY_ID\n\n def get_class_id(self):\n return self.CLASS_ID\n\n def __repr__(self):\n return \"User[username='{}', age={}, active={}]\".format(self.username, self.age, self.active)\n\n\ndef generate_users(users):\n users.put(\"Rod\", User(\"Rod\", 19, True))\n users.put(\"Jane\", User(\"Jane\", 20, True))\n users.put(\"Freddy\", User(\"Freddy\", 23, True))\n\n\nif __name__ == \"__main__\":\n config = ClientConfig()\n portable_factory = {User.CLASS_ID: User}\n config.serialization_config.add_portable_factory(User.FACTORY_ID, portable_factory)\n # Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1\n hz = hazelcast.HazelcastClient(config)\n # Get a Distributed Map called \"users\"\n users = hz.get_map(\"users\").blocking()\n # Add some users to the Distributed Map\n generate_users(users)\n # Create a Predicate from a String (a SQL like Where clause)\n sql_query = SqlPredicate(\"active AND age BETWEEN 18 AND 21)\")\n # Creating the same Predicate as above but with a builder\n criteria_query = and_(is_equal_to(\"active\", True), is_between(\"age\", 18, 21))\n # Get result collections using the two different Predicates\n result1 = users.values(sql_query)\n result2 = users.values(criteria_query)\n # Print out the results\n print(result1)\n print(result2)\n # Shutdown this Hazelcast Client\n hz.shutdown()\n","sub_path":"examples/org-website/query_sample.py","file_name":"query_sample.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"497950603","text":"\"\"\"Definitions of type inference for primitives.\"\"\"\n\n\nfrom functools import partial\nfrom operator import getitem\n\nfrom ..dtype import Int, Float, Bool, Tuple, List, Array, UInt, Number, \\\n TypeType, Class, Function, pytype_to_myiatype, Problem, type_cloner, \\\n JTagged, EnvType, SymbolicKeyType\nfrom ..infer import ANYTHING, GraphInferrer, PartialInferrer, \\\n MyiaTypeError, register_inferrer, Track, Inferrer, MetaGraphInferrer, \\\n ExplicitInferrer, VOID, TransformedReference, MultiInferrer, \\\n DummyInferrer, Context\nfrom ..infer.jinf import JInferrer\nfrom ..ir import Graph, MetaGraph\nfrom ..utils import Namespace, Var, RestrictedVar, is_dataclass_type\n\nfrom ..dtype import ismyiatype\nfrom . import ops as P\nfrom .inferrer_utils import static_getter, getelement\nfrom .ops import Primitive\nfrom .py_implementations import typeof, issubtype\n\n\ntype_inferrer_constructors = {}\n\n\n_number_types = [\n Int[8], Int[16], Int[32], Int[64],\n UInt[8], UInt[16], UInt[32], UInt[64],\n Float[16], Float[32], Float[64],\n]\n\n\nasync def _check_shape_type(track, shp):\n shp_t = await track.check(Tuple, shp)\n for elem_t in shp_t.elements:\n track.engine.equiv.declare_equivalent(UInt[64], elem_t, [])\n return shp_t\n\n\n@type_cloner.variant\ndef _import_type(self, t: Function, track):\n return ExplicitInferrer(\n track,\n [self(t2, track) for t2 in t.arguments],\n self(t.retval, track)\n )\n\n\n@type_cloner.variant\ndef _stag_type(self, t: Inferrer):\n return EnvType\n\n\nclass TypeTrack(Track):\n \"\"\"Infer the type of a constant.\n\n Note: the type of a Primitive or of a Graph is an Inferrer.\n\n Attributes:\n constructors: A map of Inferrer constructors. Each constructor\n takes an engine as argument and returns an Inferrer. These\n will be used to infer types for primitives.\n\n \"\"\"\n\n def __init__(self,\n engine,\n name,\n *,\n constructors=type_inferrer_constructors):\n \"\"\"Initialize a TypeTrack.\n\n If a TypeTrack is present, it is always required.\n \"\"\"\n super().__init__(engine, name)\n self.constructors = constructors\n\n async def infer_constant(self, ctref):\n \"\"\"Get the property for a ref of a Constant node.\"\"\"\n v = self.engine.pipeline.resources.convert(ctref.node.value)\n t = self.from_value(v, ctref.context)\n if ismyiatype(t, Number):\n v = RestrictedVar(_number_types)\n prio = 1 if ismyiatype(t, Float) else 0\n return self.engine.loop.create_var(v, t, prio)\n else:\n return t\n\n def from_value(self, v, context):\n \"\"\"Infer the type of a constant.\"\"\"\n if isinstance(v, Primitive):\n return self.constructors[v](self)\n elif isinstance(v, Graph):\n return GraphInferrer(self, v, context)\n elif isinstance(v, MetaGraph):\n return MetaGraphInferrer(self, v)\n elif is_dataclass_type(v):\n rec = self.constructors[P.make_record](self)\n typ = pytype_to_myiatype(v)\n vref = self.engine.vref({'value': typ, 'type': TypeType})\n return PartialInferrer(self, rec, [vref])\n else:\n return typeof(v)\n\n def from_external(self, t):\n \"\"\"Convert a type provided outside the inferrer.\n\n This will replace every Function type by an ExplicitInferrer.\n \"\"\"\n return _import_type(t, self)\n\n def default(self, values):\n \"\"\"Return a default type; this method raises an exception.\"\"\"\n raise Exception('There is no default value for the type track.') \\\n # pragma: no cover\n\n def jtag(self, t):\n \"\"\"Return type for J(x) given typeof(x).\"\"\"\n # It doesn't need to be recursive, because the only legal operation on\n # JTagged is Jinv.\n if isinstance(t, Inferrer):\n return JInferrer(t, lambda elems: Tuple[elems])\n else:\n return JTagged[t]\n\n def stag(self, t):\n \"\"\"Return type for sensitivity of x given typeof(x).\"\"\"\n return _stag_type(t)\n\n\n########################\n# Default constructors #\n########################\n\n\ntype_inferrer = partial(register_inferrer,\n constructors=type_inferrer_constructors)\n\n\n@type_inferrer(P.switch, nargs=3)\nasync def infer_type_switch(track, cond, tb, fb):\n \"\"\"Infer the return type of switch.\"\"\"\n await track.check(Bool, cond)\n v = await cond['value']\n if v is True:\n # We only visit the first branch if the condition is provably true\n return await tb['type']\n elif v is False:\n # We only visit the second branch if the condition is provably false\n return await fb['type']\n elif v is ANYTHING:\n # The first branch to finish will return immediately. When the other\n # branch finishes, its result will be checked against the other.\n res = await track.assert_same(tb, fb, refs=[tb, fb])\n if isinstance(res, Inferrer):\n tinf = await tb['type']\n finf = await fb['type']\n return MultiInferrer((tinf, finf), [tb, fb])\n return res\n else:\n raise AssertionError(\"Invalid condition value for switch\")\n\n\n@type_inferrer(P.partial, nargs=None)\nasync def infer_type_partial(track, fn, *args):\n \"\"\"Infer the return type of partial.\"\"\"\n fn_t = await fn['type']\n return PartialInferrer(track, fn_t, args)\n\n\n@type_inferrer(P.scalar_cast, nargs=2)\nasync def infer_type_scalar_cast(track, x, t):\n \"\"\"Infer the return type of scalar_cast.\"\"\"\n await track.will_check(Number, x)\n await track.check(TypeType, t)\n new_t = await t['value']\n if new_t is ANYTHING:\n raise MyiaTypeError(\n f'Type to cast to must be known at compile time.',\n refs=[x, t]\n )\n elif not ismyiatype(new_t, Number):\n raise MyiaTypeError(f'Cannot cast to {new_t}', refs=[t])\n return new_t\n\n\n@type_inferrer(P.make_tuple, nargs=None)\nasync def infer_type_make_tuple(track, *args):\n \"\"\"Infer the return type of make_tuple.\"\"\"\n elts = [await x.get_raw('type') for x in args]\n return Tuple[elts]\n\n\n@type_inferrer(P.tuple_getitem, nargs=2)\nasync def infer_type_tuple_getitem(track, seq, idx):\n \"\"\"Infer the return type of tuple_getitem.\"\"\"\n seq_t = await track.check(Tuple, seq)\n await track.check(Int, idx)\n idx_v = await idx['value']\n if idx_v is ANYTHING:\n raise MyiaTypeError(\n 'Tuples must be indexed with a constant',\n refs=[seq, idx]\n )\n nelems = len(seq_t.elements)\n if not -nelems <= idx_v < nelems:\n raise MyiaTypeError(\n 'Tuple element out of range',\n refs=[seq, idx]\n )\n\n return seq_t.elements[idx_v]\n\n\n@type_inferrer(P.list_getitem, nargs=2)\nasync def infer_type_list_getitem(track, seq, idx):\n \"\"\"Infer the return type of list_getitem.\"\"\"\n seq_t = await track.check(List, seq)\n await track.check(Int, idx)\n return seq_t.element_type\n\n\n@type_inferrer(getelement, nargs=1)\nasync def infer_type_getelement(track, seq):\n \"\"\"Infer the return type of getting some arbitrary element.\"\"\"\n seq_t = await track.check((List, Array), seq)\n if ismyiatype(seq_t, List):\n return seq_t.element_type\n else:\n return seq_t.elements\n\n\n@type_inferrer(P.tuple_setitem, nargs=3)\nasync def infer_type_tuple_setitem(track, seq, idx, value):\n \"\"\"Infer the return type of tuple_setitem.\"\"\"\n seq_t = await track.check(Tuple, seq)\n await track.check(Int, idx)\n idx_v = await idx['value']\n if idx_v is ANYTHING:\n raise MyiaTypeError(\n 'Tuples must be indexed with a constant',\n refs=[idx]\n )\n value_t = await value['type']\n elts = seq_t.elements\n try:\n elts[idx_v]\n except IndexError:\n raise MyiaTypeError('Index out of bounds', refs=[idx])\n new_elts = tuple([*elts[:idx_v], value_t, *seq_t.elements[idx_v + 1:]])\n return Tuple[new_elts]\n\n\n@type_inferrer(P.list_setitem, nargs=3)\nasync def infer_type_list_setitem(track, seq, idx, value):\n \"\"\"Infer the return type of list_setitem.\"\"\"\n seq_t = await track.check(List, seq)\n await track.check(Int, idx)\n await track.will_check(seq_t.element_type, value)\n return seq_t\n\n\n@type_inferrer(P.list_append, nargs=2)\nasync def infer_type_list_append(track, seq, value):\n \"\"\"Infer the return type of list_append.\"\"\"\n seq_t = await track.check(List, seq)\n await track.will_check(seq_t.element_type, value)\n return seq_t\n\n\n@type_inferrer(P.typeof, nargs=1)\nasync def infer_type_typeof(track, _):\n \"\"\"Infer the return type of typeof.\"\"\"\n return TypeType\n\n\n@type_inferrer(P.hastype, nargs=2)\nasync def infer_type_hastype(track, x, t):\n \"\"\"Infer the return type of hastype.\"\"\"\n def ismyiatype(x): # noqa: D400\n \"\"\"Type\"\"\"\n return x is TypeType\n\n await track.check(ismyiatype, t)\n return Bool\n\n\n@type_inferrer(P.bool_not, nargs=1)\nasync def infer_type_bool_not(track, x):\n \"\"\"Infer the return type of not.\"\"\"\n await track.will_check(Bool, x)\n return Bool\n\n\n@type_inferrer(P.bool_and, P.bool_or, P.bool_eq, nargs=2)\nasync def infer_type_bool_and(track, x, y):\n \"\"\"Infer the return type of bool_and.\"\"\"\n await track.will_check(Bool, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_eq, P.scalar_ne, nargs=2)\nasync def infer_type_generic_compare(track, x, y):\n \"\"\"Infer the return type of a generic comparison operator.\"\"\"\n await track.will_check(Number, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_lt, P.scalar_gt, P.scalar_le, P.scalar_ge, nargs=2)\nasync def infer_type_arith_compare(track, x, y):\n \"\"\"Infer the return type of an arithmetic comparison operator.\"\"\"\n await track.will_check(Number, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_uadd, P.scalar_usub, P.scalar_floor, P.scalar_trunc,\n nargs=1)\nasync def infer_type_arith_unary(track, x):\n \"\"\"Infer the return type of a unary arithmetic operator.\"\"\"\n return await track.will_check(Number, x)\n\n\n@type_inferrer(P.scalar_exp, P.scalar_log, P.scalar_sin,\n P.scalar_cos, P.scalar_tan, nargs=1)\nasync def infer_type_arith_unary_float(track, x):\n \"\"\"Infer the return type of a floating point unary arithmetic operator.\"\"\"\n return await track.will_check(Float, x)\n\n\n@type_inferrer(P.scalar_add, P.scalar_sub, P.scalar_mul, P.scalar_div,\n P.scalar_mod, P.scalar_pow, nargs=2)\nasync def infer_type_arith_bin(track, x, y):\n \"\"\"Infer the return type of a binary arithmetic operator.\"\"\"\n return await track.will_check(Number, x, y)\n\n\n@type_inferrer(P.shape, nargs=1)\nasync def infer_type_shape(track, ary):\n \"\"\"Infer the return type of shape.\"\"\"\n await track.check(Array, ary)\n shp = await ary['shape']\n return Tuple[[UInt[64]]*len(shp)]\n\n\n@type_inferrer(P.array_map, nargs=None)\nasync def infer_type_array_map(track, fn, *arrays):\n \"\"\"Infer the return type of array_map.\"\"\"\n if len(arrays) < 1:\n raise MyiaTypeError('array_map requires at least one array')\n fn_t = await fn['type']\n await track.check(Array, *arrays)\n vrefs = [TransformedReference(track.engine, getelement, a)\n for a in arrays]\n return Array[await fn_t(*vrefs)]\n\n\n@type_inferrer(P.array_reduce, nargs=3)\nasync def infer_type_reduce(track, fn, ary, shp):\n \"\"\"Infer the return type of array_reduce.\"\"\"\n fn_t = await fn['type']\n await _check_shape_type(track, shp)\n await track.check(Array, ary)\n xref = TransformedReference(track.engine, getelement, ary)\n res_elem_t = await fn_t(xref, xref)\n return Array[res_elem_t]\n\n\n@type_inferrer(P.array_scan, nargs=4)\nasync def infer_type_across_array(track, fn, init, ary, ax):\n \"\"\"Infer the return type of scan/array_reduce.\"\"\"\n fn_t = await fn['type']\n init_t = await init['type']\n ax_t = await ax['type']\n ary_t = await track.check(Array, ary)\n if not ary_t.elements == init_t:\n raise MyiaTypeError(\n \"Initial value must have the same type as array elements\",\n refs=[init, ary]\n )\n if not ax_t == UInt[64]:\n raise MyiaTypeError(\"Axis must be u64\", refs=[ax])\n xref = TransformedReference(track.engine, getelement, ary)\n return Array[await fn_t(xref, xref)]\n\n\n@type_inferrer(P.distribute, nargs=2)\nasync def infer_type_distribute(track, v, shp):\n \"\"\"Infer the return type of distribute.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, shp)\n return v_t\n\n\n@type_inferrer(P.reshape, nargs=2)\nasync def infer_type_reshape(track, v, shape):\n \"\"\"Infer the return type of reshape.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, shape)\n return v_t\n\n\n@type_inferrer(P.transpose, nargs=2)\nasync def infer_type_transpose(track, v, permutation):\n \"\"\"Infer the return type of transpose.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, permutation)\n return v_t\n\n\n@type_inferrer(P.invert_permutation, nargs=1)\nasync def infer_type_invert_permutation(track, permutation):\n \"\"\"Infer the return type of invert_permutation.\"\"\"\n return await permutation.get_raw('type')\n\n\n@type_inferrer(P.dot, nargs=2)\nasync def infer_type_dot(track, a, b):\n \"\"\"Infer the return type of dot.\"\"\"\n return await track.will_check(Array, a, b)\n\n\n@type_inferrer(P.return_, nargs=1)\nasync def infer_type_return_(track, x):\n \"\"\"Infer the return type of return_.\"\"\"\n return await x.get_raw('type')\n\n\n@type_inferrer(P.list_map, nargs=None)\nasync def infer_type_list_map(track, f, *lsts):\n \"\"\"Infer the return type of list_map.\"\"\"\n f_t = await f['type']\n await track.check(List, *lsts)\n argrefs = [TransformedReference(track.engine, getelement, xs)\n for xs in lsts]\n ret_t = await f_t(*argrefs)\n return List[ret_t]\n\n\n@type_inferrer(P.identity, nargs=1)\nasync def infer_type_identity(track, x):\n \"\"\"Infer the return type of identity.\"\"\"\n return await x.get_raw('type')\n\n\n@type_inferrer(P.resolve, nargs=2)\nasync def infer_type_resolve(track, data, item):\n \"\"\"Infer the return type of resolve.\"\"\"\n def chk(data_v, item_v):\n if not isinstance(data_v, Namespace): # pragma: no cover\n raise MyiaTypeError(\n f'data argument to resolve must be Namespace, not {data_v}',\n refs=[data]\n )\n if not isinstance(item_v, str): # pragma: no cover\n raise MyiaTypeError(\n f'item argument to resolve must be a string, not {item_v}.',\n refs=[item]\n )\n\n async def on_dcattr(data, data_t, item_v): # pragma: no cover\n raise MyiaTypeError('Cannot resolve on Class.')\n\n return await static_getter(\n track, data, item,\n fetch=getitem,\n on_dcattr=on_dcattr,\n chk=chk\n )\n\n\n@type_inferrer(P.getattr, nargs=2)\nasync def infer_type_getattr(track, data, item):\n \"\"\"Infer the return type of getattr.\"\"\"\n def chk(data_v, item_v):\n if not isinstance(item_v, str):\n raise MyiaTypeError(\n f'item argument to getattr must be string, not {item_v}.',\n refs=[item]\n )\n\n async def on_dcattr(data, data_t, item_v):\n return data_t.attributes[item_v]\n\n return await static_getter(\n track, data, item,\n fetch=getattr,\n on_dcattr=on_dcattr,\n chk=chk\n )\n\n\n@type_inferrer(P.scalar_to_array, nargs=1)\nasync def infer_type_scalar_to_array(track, x):\n \"\"\"Infer the return type of scalar_to_array.\"\"\"\n x_t = await track.will_check(Number, x)\n return Array[x_t]\n\n\n@type_inferrer(P.array_to_scalar, nargs=1)\nasync def infer_type_array_to_scalar(track, ary):\n \"\"\"Infer the return type of array_to_scalar.\"\"\"\n ary_t = await track.check(Array, ary)\n return ary_t.elements\n\n\n@type_inferrer(P.broadcast_shape, nargs=2)\nasync def infer_type_broadcast_shape(track, xs, ys):\n \"\"\"Infer the return type of broadcast_shape.\"\"\"\n xs_t = await _check_shape_type(track, xs)\n ys_t = await _check_shape_type(track, ys)\n shp_xs_n = len(xs_t.elements)\n shp_ys_n = len(ys_t.elements)\n return Tuple[[UInt[64] for i in range(max(shp_xs_n, shp_ys_n))]]\n\n\n@type_inferrer(P.make_record, nargs=None)\nasync def infer_type_make_record(track, cls, *elems):\n \"\"\"Infer the return type of make_record.\"\"\"\n elem_types = [await x['type'] for x in elems]\n cls_v = await cls['value']\n\n ret_t = Class[\n cls_v.tag,\n dict(zip(cls_v.attributes.keys(), elem_types)),\n cls_v.methods\n ]\n\n if not issubtype(ret_t, cls_v):\n raise MyiaTypeError(\n f'Constructor {cls_v} cannot be called'\n f' with argument types {tuple(elem_types)}',\n refs=elems,\n )\n\n return ret_t\n\n\n@type_inferrer(P.tuple_len, nargs=1)\nasync def infer_type_tuple_len(track, xs):\n \"\"\"Infer the return type of tuple_len.\"\"\"\n await track.will_check(Tuple, xs)\n return Int[64]\n\n\n@type_inferrer(P.list_len, nargs=1)\nasync def infer_type_list_len(track, xs):\n \"\"\"Infer the return type of list_len.\"\"\"\n await track.will_check(List, xs)\n return Int[64]\n\n\n@type_inferrer(P.array_len, nargs=1)\nasync def infer_type_array_len(track, xs):\n \"\"\"Infer the return type of array_len.\"\"\"\n await track.will_check(Array, xs)\n return Int[64]\n\n\n@type_inferrer(P.make_list, nargs=None)\nasync def infer_type_make_list(track, *elems):\n \"\"\"Infer the return type of make_list.\"\"\"\n if len(elems) == 0:\n v = Var('empty')\n t = track.engine.loop.create_var(v, Problem[VOID], -1000)\n else:\n t = await track.assert_same(*elems, refs=elems)\n return List[t]\n\n\n@type_inferrer(P.list_reduce, nargs=3)\nasync def infer_type_list_reduce(track, fn, lst, dflt):\n \"\"\"Infer the return type of list_reduce.\"\"\"\n fn_t = await fn['type']\n await track.check(List, lst)\n xref = TransformedReference(track.engine, getelement, lst)\n res_elem_t = await track.assert_same(fn_t(xref, xref), dflt)\n return res_elem_t\n\n\n@type_inferrer(P.J, nargs=1)\nasync def infer_type_J(track, x):\n \"\"\"Infer the return type of J.\"\"\"\n return track.jtag(await x.get_shallow('type'))\n\n\n@type_inferrer(P.Jinv, nargs=1)\nasync def infer_type_Jinv(track, x):\n \"\"\"Infer the return type of Jinv.\"\"\"\n x_t = await x.get_shallow('type')\n if isinstance(x_t, JInferrer):\n return x_t.fn\n elif isinstance(x_t, GraphInferrer):\n g = x_t._graph\n primal = g and g.transforms.get('primal', None)\n if primal:\n primal = track.engine.pipeline.resources.convert(primal)\n if isinstance(primal, Graph) and primal.parent:\n # The primal for a closure can't be used because it points to\n # the original nodes of its parent, whereas we would like to\n # point to the transformed nodes of the parent. This is\n # fixable, and will need to be fixed to support a few edge\n # cases.\n return DummyInferrer(track)\n else:\n return track.from_value(primal, Context.empty())\n else:\n raise MyiaTypeError(f'Bad input type for Jinv: {x_t}',\n refs=[x])\n elif ismyiatype(x_t, JTagged):\n return x_t.subtype\n else:\n raise MyiaTypeError(f'Bad input type for Jinv: {x_t}',\n refs=[x])\n\n\n@type_inferrer(P.embed, nargs=1)\nasync def infer_type_embed(track, x):\n \"\"\"Infer the return type of embed.\"\"\"\n return SymbolicKeyType\n\n\n@type_inferrer(P.env_setitem, nargs=3)\nasync def infer_type_env_setitem(track, env, key, x):\n \"\"\"Infer the return type of env_setitem.\"\"\"\n await track.check(EnvType, env)\n await track.check(SymbolicKeyType, key)\n key_v = await key['value']\n assert key_v is not ANYTHING\n t = track.stag(key_v.inferred['type'])\n await track.assert_same(t, x['type'])\n return EnvType\n\n\n@type_inferrer(P.env_getitem, nargs=3)\nasync def infer_type_env_getitem(track, env, key, default):\n \"\"\"Infer the return type of env_getitem.\"\"\"\n await track.check(EnvType, env)\n await track.check(SymbolicKeyType, key)\n key_v = await key['value']\n assert key_v is not ANYTHING\n t = track.stag(key_v.inferred['type'])\n return await track.assert_same(t, default)\n\n\n@type_inferrer(P.env_add, nargs=2)\nasync def infer_type_env_add(track, env1, env2):\n \"\"\"Infer the return type of env_add.\"\"\"\n await track.check(EnvType, env1, env2)\n return EnvType\n","sub_path":"myia/prim/type_inferrers.py","file_name":"type_inferrers.py","file_ext":"py","file_size_in_byte":20594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"390676992","text":"import logging\nfrom contextlib import contextmanager\n\nimport psycopg2\nimport yaml\nfrom psycopg2.extras import RealDictCursor\nfrom psycopg2.pool import ThreadedConnectionPool\n\nfrom .campaigns import Campaigns\nfrom .labels import Labels\nfrom .tasks import Tasks\nfrom .worksets import Worksets\n\nlogger = logging.getLogger(__name__)\n\n\nclass DB:\n def __init__(self, pool):\n self.pool = pool\n\n self.campaigns = Campaigns(self)\n self.worksets = Worksets(self)\n self.tasks = Tasks(self)\n self.labels = Labels(self)\n\n def execute(self, sql):\n with self.transaction() as transactor:\n cursor = transactor.cursor()\n cursor.execute(sql)\n return cursor\n\n @contextmanager\n def transaction(self):\n \"\"\"Provides a transactional scope around a series of operations.\"\"\"\n conn = self.get_good_connection()\n try:\n yield conn\n conn.commit()\n except:\n conn.rollback()\n raise\n finally:\n self.pool.putconn(conn)\n\n def get_good_connection(self, retries=11):\n\n # Try at most 10 times.\n for i in range(retries):\n try:\n conn = self.pool.getconn()\n cursor = conn.cursor()\n cursor.execute(\"SELECT 1;\")\n rows = list(cursor)\n if len(rows) == 1:\n return conn\n except (psycopg2.InterfaceError, psycopg2.OperationalError,\n psycopg2.DatabaseError):\n logger.info(\"Discarding a useless connection.\")\n continue # Try again\n\n raise RuntimeError(\"No good database connections in the pool.\")\n\n\n @classmethod\n def from_params(cls, *args, minconn=10, maxconn=20, **kwargs):\n pool = ThreadedConnectionPool(*args, cursor_factory=RealDictCursor,\n minconn=minconn,\n maxconn=maxconn,\n **kwargs)\n\n return cls(pool)\n\n @classmethod\n def from_config(cls, config):\n # Copy config as kwargs\n params = {k: v for k, v in config['database'].items()}\n\n if 'creds' in params:\n creds = yaml.load(open(params['creds']))\n del params['creds']\n params.update(creds)\n\n return cls.from_params(**params)\n","sub_path":"wikilabels/database/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"469764868","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlretrieve\nimport ssl\nimport openpyxl\n\nwb = openpyxl.Workbook()\nsheet = wb.active\nsheet.append([\"제목\", \"장르\",\"정보\"])\n\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nraw = requests.get(\"https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EC%97%AD%EB%8C%80+%EC%98%81%ED%99%94+%EC%88%9C%EC%9C%84\",\n headers={\"User-Agent\": \"Mozilla/5.0\"})\n\nhtml = BeautifulSoup(raw.text, 'html.parser')\nmovies = html.select(\"dl.lst_dsc\")\nn=0\nfor m in movies:\n title = m.select_one(\"dt.tit a\")\n url = title.attrs[\"href\"]\n genre = m.select_one(\"dl.info_txt1 a\")\n url = title.attrs[\"href\"]\n\n print(\"=\" * 50)\n print(\"영화 제목 : \", title.text.strip())\n print(\"영화 장르 : \", genre.text)\n print(\"정보 : https://movie.naver.com\" + url)\n sheet.append([title.text.strip(), genre.text, \"https://movie.naver.com\"+url])\n wb.save(\"naver_moive_info.xlsx\")\n\n each_raw = requests.get(\"https://movie.naver.com\" + url,\n headers={\"User-Agent\": \"Mozilla/5.0\"})\n\n each_html = BeautifulSoup(each_raw.text, 'html.parser')\n #genre = each_html.select_one(\"dl.list_main dd:nth-of-type(1)\")\n\n # poster 선택자 : div.mv_info_area div.poster img\n poster = each_html.select_one(\"div.mv_info_area div.poster img\")\n poster_src = poster.attrs[\"src\"]\n\n urlretrieve(poster_src, \"static/\" + str(n) + \".png\")\n n=n+1\n\n\n\n # title[:2]는 제목의 앞글자 두글자만 따겠다는 것인데, 특수문자가 제목에 들어있는 경우에는 파일 이름에 에러가 나기 때문이다.\n # 또 위에서 title변수가 아니라 출력문에 .text를 붙였기에 여기서도 .text를 붙여준다.","sub_path":"crowl.py","file_name":"crowl.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"492828916","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\nimport h5py\nimport os\n\ndef make_polar(real,imag):\n cplx = real+1j*imag\n return abs(cplx), np.unwrap(np.angle(cplx))\n\ndef limit_data_x(x,y,xmin,xmax):\n minindex = np.argmax(x>xmin)-1\n maxindex = np.argmax(x>=xmax)\n return x[minindex:maxindex+1], y[minindex:maxindex+1]\n\ndef import_file(path,**kwargs): #laziness 10/10, practicality 10/10\n extension = os.path.splitext(path)[1][1:]\n if extension == 'csv':\n return import_csv(path,**kwargs)\n if extension == 'h5':\n return import_h5(path)\n \ndef import_h5(path):\n openfile = h5py.File(path,'r')\n data_dict = {}\n for key in list(openfile.keys()):\n data_dict[key] = np.array(openfile[key])\n openfile.close()\n return data_dict, data_dict.keys()\n \ndef import_csv(path,param_sweep=False,title_line=8):\n title_pos = title_line\n with open(path,'r') as openfile:\n\n if param_sweep == False:\n for i in range(title_pos):\n line = openfile.readline()\n titles = line[:-1].split(',') #get column titles\n data = np.loadtxt(path,delimiter=',',skiprows=title_pos) #import all the data\n data_dict = {titles[i]: data[:,i] for i in range(len(titles))} #create results dictionary\n return data_dict, list(data_dict.keys())\n\n if param_sweep == True:\n data_dict = {} #overall dictionary\n params_dict = {} #dictionary with data from individual parameter values\n values = [] #parameter values\n \n for i in range(title_pos):\n line = openfile.readline()\n \n titles = line[:-1].split(',') #get column titles\n line = openfile.readline()\n param_name, val = line[:-1].split(' = ') #get the name of the parameter\n values.append(float(val)) #register first parameter value\n params_dict[param_name + ' = ' + val] = [] #start data dictionary\n line = openfile.readline() #go to first line of data\n while line != \"\": #keep going until end of file\n try:\n params_dict[param_name + ' = ' + val].append(list(map(float,line[:-1].split(',')))) #attempt to add line to data array\n except ValueError: #float will throw value error\n if line[:len(param_name)] == param_name: #check if the line with the error is a line with the parameter value\n val = line[:-1].split(' = ')[1] #update parameter value\n values.append(float(val)) #store it\n params_dict[param_name + ' = ' + val] = [] #start data dictionary\n line = openfile.readline() #next line\n \n keys, full_values = (list(params_dict.keys()),list(params_dict.values())) #sale mais efficace\n params_dict = {keys[i]: np.array(full_values[i]) for i in range(len(keys))} #sale mais efficace\n data_dict = {'titles':titles,'param data':params_dict,'param values': values}\n return data_dict, list(data_dict.keys())\n\ndef lorentzian_function(x,A,sig,xres,offset):\n return offset+A/(1+(x-xres)**2/sig**2)\n\ndef abs_hanger_function(x,a,b,sig,xres,offset):\n return np.where(abs(offset)>abs(a),abs(offset-(a-2j*b)/(1+2j*(x-xres)/sig)),0) #we must ensure that offset > a which is equivalent to saying that Qc,Qi>Q0\n\ndef abs_sym_hanger_function(x,a,sig,xres,offset):\n return np.where(abs(offset)>abs(a),abs(offset-a/(1+2j*(x-xres)/sig)),0)\n\ndef sym_hanger_function(x,Qi,Qc,f0):\n return (Qc+2j*Qc*Qi*(x-f0)/f0)/(Qi+Qc+2j*Qc*Qi*(x-f0)/f0)\n\ndef hanger_function(x,Qi,Qc,f0,deltaf,f0_sym):\n #only two out of f0, f0_smy and deltaf are independent given that f0 = f0_sym + deltaf\n return (Qc+1j*Qc*Qi*(2*(x-f0)/f0+2*deltaf/f0_sym))/(Qi+Qc+2j*Qc*Qi*(x-f0)/f0)\n\ndef reflection_function(x,kc,kl,f0):\n return (kc-kl-2j*(x-f0))/(kc+kl+2j*(x-f0))\n\ndef transmission_function(x,kcscaled,kt,f0):\n return (2*np.sqrt(kcscaled))/(kt+2j*(x-f0)) #we put a plus on the denominator in this formula to deal with quadrant problems in the arctan function\n\ndef abs_reflection_function(x,kc,kl,f0,scaling):\n return scaling*abs((kc-kl-2j*(x-f0))/(kc+kl+2j*(x-f0)))\n\ndef abs_transmission_function(x,kcscaled,kt,f0):\n return abs((2*np.sqrt(kcscaled))/(kt-2j*(x-f0)))\n\ndef phase_adjust(x,func,delay,offset):\n return np.unwrap(np.angle(func(x)))-2*np.pi*x*delay+offset\n\ndef phase_adjust_fit(freqs,S21arg,model='hanger',**kwargs):\n base_function = lambda x: 1 #we have to define the function so that we don't get a referenced before assignment error\n try:\n p0 = kwargs['p0_arg'] #try to find user defined starting parameters\n except KeyError:\n delay0 = -(S21arg[-1]-S21arg[0])/(2*np.pi*(freqs[-1]-freqs[0])) #determine slope of phase = electrical delay\n offset0 = S21arg[0]+2*np.pi*delay0*freqs[0] #determine offset (this is just solving an affine equation)\n p0 = [delay0, offset0]\n if model == 'sym_hanger':\n base_function = lambda x: sym_hanger_function(x,*kwargs['sym_hanger_params']) #the item 'hanger_params' must be a list of length 3\n if model == 'hanger':\n base_function = lambda x: hanger_function(x,*kwargs['hanger_params']) #the item 'hanger_params' must be a list of length 5\n if model == 'reflection':\n base_function = lambda x: reflection_function(x,*kwargs['reflection_params']) #the item 'reflection_params' must be a list of length 3\n if model == 'transmission':\n base_function = lambda x: transmission_function(x,*kwargs['transmission_params']) #the item 'transmission_params' must be a list of length 3\n \n def model_function(x,delay,offset):\n return phase_adjust(x,base_function,delay,offset)\n \n popt, pcov = opt.curve_fit(model_function,freqs,S21arg,p0)\n fit = model_function(freqs,*popt)\n initial = model_function(freqs,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_reflection_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n scale0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n dip = y[res_index]/scale0\n HM_index = np.argmax(abs(y/scale0)>(1/2+1/2*dip)) #we find the half maximum of the inverse bump aka dip\n sig = 2*abs(x0-x[HM_index])\n #we assume that the two port resonator is critically coupled with respect to each port, and that the FWHM is the sum of the kappas\n kc0 = sig/3\n kl0 = 2*sig/3\n p0 = [kc0,kl0,0,scale0] #ACHTUNG kc and kl have units of frequency and not 2pi frequency\n \n popt, pcov = opt.curve_fit(abs_reflection_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_reflection_function(x,*popt)\n initial = abs_reflection_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_sym_hanger_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n offset0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n a0 = abs(y[res_index]-offset0)\n HM_index = np.argmax(abs(y-offset0)>abs(a0)/2)\n sig0 = 2*abs(x0-x[HM_index])\n p0 = [a0,sig0,0,offset0]\n \n popt, pcov = opt.curve_fit(abs_sym_hanger_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_sym_hanger_function(x,*popt)\n initial = abs_sym_hanger_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n \ndef abs_hanger_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[3]\n p0[3] = 0\n except KeyError:\n offset0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n a0 = abs(y[res_index]-offset0)\n b0 = 0 #we assume the asymmetry to be small (may be a bad guess though)\n HM_index = np.argmax(abs(y-offset0)>abs(a0)/2)\n sig0 = 2*abs(x0-x[HM_index])\n p0 = [a0,b0,sig0,0,offset0]\n \n popt, pcov = opt.curve_fit(abs_hanger_function,x-x0,y,p0)\n popt[3] += x0\n p0[3] += x0\n fit = abs_hanger_function(x,*popt)\n initial = abs_hanger_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_transmission_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n res_index = np.argmax(y) #find resonance frequency\n x0 = x[res_index]\n y0 = y[res_index]\n HM_index = np.argmax(abs(y)>y0/2)\n kt0 = 2*abs(x0-x[HM_index])/np.sqrt(3) #determine FWHM (not sure about the sqrt(3) though)\n kcscaled0 = (y0*kt0/2)**2 # determine scaling and kc multiplied\n p0 = [kcscaled0,kt0,0]\n \n popt, pcov = opt.curve_fit(abs_transmission_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_transmission_function(x,*popt)\n initial = abs_transmission_function(x,*p0)\n\n return popt, p0, fit, pcov, initial\n\ndef lorentzian_fit(x,y,**kwargs): \n try: \n p0 = kwargs['p0']\n x0 = p0[2]\n p0[2] = 0 #we force the fit to be centered around the guessed resonance frequency\n except KeyError:\n offset0 = np.average([y[0],y[-1]]) #find function offset\n res_index = np.argmax(abs(y-offset0)) #index of resonance in array\n x0 = x[res_index] #frequency of resonance\n A0 = y[res_index]-offset0 #amplitude at resonance\n HM_index = np.argmax(abs(y-offset0)>abs(A0)/2) #index of half maximum\n sig0 = abs(x0-x[HM_index]) #value of half maximum frequency difference\n p0 = [A0,sig0,0,offset0] #define start parameters of fit (we fit with the resonance centered around 0)\n\n popt, pcov = opt.curve_fit(lorentzian_function,x-x0,y,p0)\n popt[2] += x0 #we correct the parameters by what we originally substracted\n p0[2] = x0\n fit = lorentzian_function(x,*popt) #find the y of the fitted model\n initial = lorentzian_function(x,*p0) #find the y of the original guess\n return popt, p0, fit, pcov, initial\n\ndef curve_fit(freqs,data,model='lorentzian',plots = False,verbose = False,**kwargs):\n if model == 'lorentzian': #for this method mke sure data is an array with only 1 dimension\n popt, p0, fit, pcov, initial = lorentzian_fit(freqs,data,**kwargs) #do the fit\n results = {'popt':popt} #return the optimal parameters\n if plots: \n fig, ax = plt.subplots()\n ax.plot(freqs,data,label='data') #plot the original data\n ax.plot(freqs,fit,label='fit') #plot the fit\n ax.plot(freqs,initial,'--',label='initial') #plot the initial guess\n plt.legend()\n plt.show()\n if verbose:\n results.update({'p0':p0,'pcov':pcov,'fit':fit,'initial':initial}) #return all results and parameters for analysis\n return results\n \n if model == 'sym_abs_hanger': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_sym_hanger_fit(freqs,dataabs,**kwargs)\n \n #we have to do some calculations so that the parameters we return are the ones which are physically interesting\n a,sig,xres,offset = popt_abs\n Q0 = xres/sig #see Geerlings' thesis for details on these formulas\n Qc = offset*xres/(a*sig)\n Qi = 1/(1/Q0-1/Qc)\n phys_params = {'Q0':Q0,'Qi':Qi,'Qc':Qc,'f0':xres}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we now need to fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='sym_hanger',sym_hanger_params=list(phys_params.values())[1:],**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'abs_hanger': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_hanger_fit(freqs,dataabs,**kwargs)\n \n #we have to do some calculations so that the parameters we return are the ones which are physically interesting\n a,b,sig,xres,offset = popt_abs\n Q0 = xres/sig #see Geerlings' thesis for details on these formulas\n Qc = offset*xres/(a*sig)\n Qi = 1/(1/Q0-1/Qc)\n deltaf = xres*(1-1/(1+b/(Q0*offset)))\n xres_sym = xres/(1+b/(Q0*offset))\n phys_params = {'Q0':Q0,'Qi':Qi,'Qc':Qc,'f0':xres,'deltaf':deltaf,'f0_sym':xres_sym}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we now need to fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,hanger_params=list(phys_params.values())[1:],**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'abs_reflection': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_reflection_fit(freqs,dataabs,**kwargs)\n kc,kl,f0,scale = popt_abs\n phys_params = {'kc':kc,'kl':kl,'f0':f0}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='reflection',reflection_params=list(phys_params.values()),**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'transmission': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_transmission_fit(freqs,dataabs,**kwargs)\n kcscaled, kt, f0 = popt_abs\n phys_params = {'kcscaled':kcscaled,'kt':kt,'f0':f0}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n\n #we fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='transmission',transmission_params=list(phys_params.values()),**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n\n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":19111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"231480811","text":"#!/usr/bin/python3\n\n###############################################################\n# influxdbdatalogger.py script can be run from command line #\n# or can be started as systemd service or Raspberry Pi #\n# Main tasks of the script are: #\n# - read environment data received as mqtt message #\n# - store received data in InfluxDB database #\n# Andrzej Mazur, 17/03/2021 #\n###############################################################\n\nimport logging\nimport sys\nimport getopt\nimport time\nimport json\nimport os\nfrom datetime import datetime\nimport paho.mqtt.client as mqtt\nfrom influxdb import InfluxDBClient\n\n#Set debug to True in order to log all messages!\nLOG_ALL = False\n#Set log_to_file flag to False in order to print logs on stdout\nLOG_TO_FILE = False\n\n##########################\n#MQTT Connection Settings#\n##########################\n#Quality of Service Level for MQTT transfer, supported values 0 and 1\nmqtt_qos=1\n#Broker address - Change this line!\n#Test Broker address: test.mosquitto.org\nmqtt_broker_address=\"test.mosquitto.org\"\n#mqtt_broker_address=\"localhost\"\n#Brokers TCP Port number\nmqtt_broker_port=1883\n#Connection keep alive interval in sec\nmqtt_keep_alive=60\n#Topic on which measurement record will be published\nmqtt_topic=\"47e0g1/headlesspi/climdata\"\n\n##############################\n#InfluxDB Connection Settings#\n##############################\ninfluxdb_user = \"climatedata_probe\"\ninfluxdb_pass = \"probepi\"\ninfluxdb_dbname = \"climatedata\"\ninfluxdb_measurementname = \"climatemeasurements\"\ninfluxdb_host = \"127.0.0.1\"\ninfluxdb_port = 8086\n\ndef cmd_usage():\n print ('Usage: '+sys.argv[0]+' {[-d | --debug debug] [-h | --host host] [-q | --qos QoS] [-t | --topic topic] [-a | --bfe280addr bfe280 address]')\n exit (1)\n\ntry:\n options, arguments = getopt.getopt(sys.argv[1:], 'dh:q:t:', ['debug', \n 'host=',\n 'qos=',\n 'topic=', \n ])\n \nexcept getopt.GetoptError as err:\n print(str(err))\n cmd_usage()\n sys.exit(1)\n\nfor opt, arg in options:\n if opt in ('-d', '--debug'):\n debug = True\n elif opt in ('-h', '--host'):\n mqtt_broker_address = arg\n elif opt in ('-q', '--qos'):\n mqtt_qos = int(arg)\n elif opt in ('-t', '--topic'):\n mqtt_topic = arg\n\n\n#configure logger module\n#levels: DEBUG,INFO,WARNING,ERROR,CRITICAL\n \n#create two log file handlers, one for actual log file and another for stdout\nstdout_handler = logging.StreamHandler(sys.stdout)\n\nif LOG_TO_FILE == True:\n #extract file name from filename.extension\n idx=os.path.split(os.path.basename(__file__))[1].find('.')\n file_name_wo_extension=os.path.split(os.path.basename(__file__))[1][:idx]\n log_file = os.path.dirname(os.path.realpath(__file__)) + \"/\" + file_name_wo_extension + \".log\"\n file_handler = logging.FileHandler(filename=log_file)\n hndls = [file_handler]\n print (\"Program logs are stored in: \", log_file)\nelse:\n hndls = [stdout_handler]\n \n#configure logger module\n#levels: DEBUG,INFO,WARNING,ERROR,CRITICAL\n\nif LOG_ALL == True:\n logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s:%(threadName)s:%(filename)s:%(lineno)s:%(levelname)s:%(message)s', handlers=hndls)\nelse:\n logging.basicConfig(level = logging.INFO,format = '%(asctime)s:%(threadName)s:%(filename)s:%(lineno)s:%(levelname)s:%(message)s', handlers=hndls)\n\n \nif mqtt_qos != 0 and mqtt_qos != 1:\n mqtt_qos = 1\n logging.error('Provided MQTT QoS value is not supported. Default QoS=1 is used...')\n\ndef mqtt_on_connect(mqtt_client, userdata, flags, rc):\n if rc==0:\n mqtt.Client.connected_flag = True \n logging.info('Received:MQTT_CONNACK(rc=%i)',rc)\n logging.info('Connection to MQTT Broker established!')\n #Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n (result,mid)=mqtt_client.subscribe(mqtt_topic,mqtt_qos)\n logging.info('Sent:MQTT_SUBSCRIBE(mid=%i, topic:%s, QoS=%i, rc=%i)',mid,mqtt_topic, mqtt_qos, result)\n else:\n logging.info('Received:MQTT_CONNACK(rc=%i)',rc)\n logging.info('Connection establishment to MQTT Broker failed!')\n \ndef mqtt_on_disconnect(mqtt_client, userdata, rc):\n mqtt.Client.connected_flag = False\n if rc==0:\n logging.info('Disconnection from MQTT Broker completed!')\n else:\n logging.error('Unexpected disconnection from MQTT Broker!')\n \ndef mqtt_on_message(mqtt_client, userdata, msg):\n logging.debug('Received:MQTT_PUBLISH(topic=%s, qos=%s, retain=%s, payload=%s)', msg.topic,msg.qos,msg.retain,msg.payload)\n mqtt_msg = json.loads(msg.payload)\n influxdb_store_data_sample(influxdb_host,influxdb_port,influxdb_user,influxdb_pass,influxdb_dbname,influxdb_measurementname, mqtt_msg)\n\n\n \ndef mqtt_on_subscribe(client,userdata,mid,granted_qos):\n logging.info('Received:MQTT_SUBACK(mid=%i,negotiatedQoS=%i)',mid, granted_qos[0])\n logging.info('Client ready to receive messages!')\n\ndef influxdb_store_data_sample(dbhost,dbport,dbuser,dbpass,dbname,dbmeasurement,data):\n #build database records from received json string\n \n # connect to influx\n # it is possible to connect once and in this function call just write to database, but it is less reliable method\n ifclient = InfluxDBClient(dbhost,dbport,dbuser,dbpass,dbname)\n \n # write the measurement taken by bme280\n # format the data as a single measurement for influx\n \n logging.debug('Measurement to be added to \"%s\" meas. in \"%s\" db:',dbmeasurement,dbname)\n logging.debug(\" sensor id: %s\", str(data['bme280id']))\n logging.debug(' timestamp: %s',list(data.keys())[1])\n logging.debug(' temperature: %f%s',float(data[list(data.keys())[1]]['temperature']['value']),data[list(data.keys())[1]]['temperature']['unit'])\n logging.debug(' pressure: %f%s',float(data[list(data.keys())[1]]['pressure']['value']),data[list(data.keys())[1]]['pressure']['unit'])\n logging.debug(' humidity: %f%s',float(data[list(data.keys())[1]]['humidity']['value']),data[list(data.keys())[1]]['humidity']['unit'])\n\n dbrecord = [\n {\n \"measurement\": dbmeasurement,\n \"tags\": {\n \"sensor_id\":str(data['bme280id']),\n \"location\": mqtt_topic.split(\"/\")[0]\n },\n \"time\": list(data.keys())[1],\n \"fields\": {\n \"temperature_C\": float(data[list(data.keys())[1]]['temperature']['value']),\n \"pressure_hPa\": float(data[list(data.keys())[1]]['pressure']['value']),\n \"humidity_rH\": float(data[list(data.keys())[1]]['humidity']['value'])\n }\n }\n ]\n\n ifclient.write_points(dbrecord)\n \n # write the measurement taken by ds18b20\n # format the data as a single measurement for influx\n\n logging.debug('Measurement to be added to \"%s\" meas. in \"%s\" db:',dbmeasurement,dbname)\n logging.debug(\" sensor id: %s\", str(data['ds18b2id']))\n logging.debug(' timestamp: %s',list(data.keys())[3])\n logging.debug(' temperature: %f%s',float(data[list(data.keys())[3]]['temperature']['value']),str(data[list(data.keys())[3]]['temperature']['unit']))\n\n dbrecord = [\n {\n \"measurement\": dbmeasurement,\n \"tags\": {\n \"sensor_id\":str(data['ds18b2id']),\n \"location\": mqtt_topic.split(\"/\")[0]\n },\n \"time\": list(data.keys())[3],\n \"fields\": {\n \"temperature_C\": float(data[list(data.keys())[3]]['temperature']['value'])\n }\n }\n ]\n \n ifclient.write_points(dbrecord)\n\n \n#create connection state flag in class\nmqtt.Client.connected_flag=False\n\n#create mqtt client instance\nmqtt_client = mqtt.Client()\n\n#bind callback functions \nmqtt_client.on_connect=mqtt_on_connect\nmqtt_client.on_disconnect=mqtt_on_disconnect\nmqtt_client.on_message=mqtt_on_message\nmqtt_client.on_subscribe=mqtt_on_subscribe\n\n#connect to MQTT Broker\n\nmqtt_client_connect_retry_limit = 30\nmqtt_client_connect_retry = 0\nmqtt_client_connect_success = False\n\nwhile (mqtt_client_connect_retry < mqtt_client_connect_retry_limit and mqtt_client_connect_success == False):\n try:\n if mqtt_client_connect_retry != 0: # there shall be no delay between loopstart() and connect messages!\n time.sleep(1+mqtt_client_connect_retry)\n logging.info('Sent:MQTT_CONNECT:(IP:%s,TCP Port:%s,Topic:%s,QoS:%i,KeepAlive:%i)',mqtt_broker_address, mqtt_broker_port, mqtt_topic, mqtt_qos, mqtt_keep_alive)\n #connect is a blocking function\n mqtt_client.connect(mqtt_broker_address,mqtt_broker_port,mqtt_keep_alive)\n mqtt_client_connect_success = True\n except KeyboardInterrupt:\n logging.info('Exiting the program, ctrl+C pressed...')\n exit(0)\n except:\n mqtt_client_connect_retry = mqtt_client_connect_retry + 1\n logging.error('Connection establishment failed due to: %s, retry (%i out of % i) in %i sec. ...', sys.exc_info()[1],mqtt_client_connect_retry, mqtt_client_connect_retry_limit, 1+mqtt_client_connect_retry)\n pass\n\n#start infinite network loop, disconnect from MQTT Broker at keyboard interupt\ntry:\n mqtt_client.loop_forever()\nexcept KeyboardInterrupt:\n logging.info('Exiting the program, ctrl+C pressed...')\n logging.info('Sent:MQTT_DISCONNECT')\n logging.info('Disconnecting from MQTT Broker')\n mqtt_client.disconnect();\n exit (0)\n\n","sub_path":"src/influxdbdatalogger.py","file_name":"influxdbdatalogger.py","file_ext":"py","file_size_in_byte":9759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"604379763","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport getopt\nimport os\nimport sys\nimport time\n\nimport tweepy\nimport subprocess\nfrom platforms.binance_platform import Binance\nfrom platforms.cryptopia_platform import Cryptopia\n\n\"\"\"*******************\"\"\"\n\"\"\" Authentifications \"\"\"\n\"\"\"*******************\"\"\"\n\n\ndef authentication_tweeter():\n print(\"-- Connecting to tweeter ...\")\n\n auth = tweepy.OAuthHandler(os.environ['TWEETER_CONSUMER_KEY'], os.environ['TWEETER_CONSUMER_SECRET'])\n auth.set_access_token(os.environ['TWEETER_ACCESS_TOKEN'], os.environ['TWEETER_ACCESS_TOKEN_SECRET'])\n return tweepy.API(auth)\n\n\ndef handle_orders(coin, coinFrom):\n coin = coin.upper()\n coinFrom = coinFrom.upper()\n\n # Récupération des fonds disponibles\n originalAsset = client.get_balance(coinFrom)\n print(str(originalAsset) + \" \" + coinFrom + \" available\")\n\n # Récupération du prix de départ\n originalPrice = client.get_price(coin, coinFrom)\n print(coin + \" is at \" + \"{:10.8f}\".format(originalPrice) + \" \" + coinFrom)\n print(\"Can buy \" + str(float(originalAsset / originalPrice)) + \" \" + coin)\n\n # Calcul de la quantité à acheter\n priceBuy = float(originalPrice * 1.02)\n quantity = float(originalAsset / priceBuy)\n quantity = round(quantity * 0.90, 6)\n print(\"Will buy \" + str(quantity) + \" \" + coin + \" (quantity -10% at price + 2%)\")\n\n # Placement ordre achat (priceBuy ignored si market order sur binance)\n client.buy_market(coin, coinFrom, priceBuy, quantity, testMode)\n print(\"--> Bought\")\n\n # Time before trade\n timeBeforeTrade = time.time()\n\n # Wait 15 secondes\n while ((time.time() - timeBeforeTrade) < 20):\n newPrice = client.get_price(coin, coinFrom)\n print(coin + \" is at \" + str(newPrice) + coinFrom)\n time.sleep(0.1)\n\n \"\"\"\n sellOrNot = \"\"\n while (sellOrNot != \"S\"):\n sellOrNot = input(\"Press 's' or 'S' to sell NOW : \\n\")\n sellOrNot = sellOrNot.upper()\n \"\"\"\n\n print(\"Selling ...\")\n\n # Placement ordre vente\n quantityAfter = client.get_balance(coin)\n print(str(quantityAfter) + \" \" + coin + \" available\")\n priceSell = float(client.get_price(coin, coinFrom) * 0.98)\n print(\"Will sell \" + str(quantityAfter) + \" \" + coin + \" (price - 2%)\")\n client.sell_market(coin, coinFrom, priceSell, quantityAfter, testMode)\n\n # Status order sell\n finalAsset = client.get_balance(coinFrom)\n print(str(originalAsset) + \" \" + coinFrom + \" available\")\n print(\"--> Sold\")\n print(\"Previously had \" + str(originalAsset) + \" \" + coinFrom + \", now have \" + str(finalAsset) + \" \" + coinFrom)\n print(\"Now have \" + str(client.get_balance(coin)) + \" \" + coin)\n print(\"Delta is \" + str(finalAsset - originalAsset) + \" \" + coinFrom)\n\n\n\"\"\"*********\"\"\"\n\"\"\" Tweeter \"\"\"\n\"\"\"*********\"\"\"\n\n\ndef search_coin_of_the_week(tweet):\n print(\"Searching coin ...\")\n coinOfTheWeek = \"\"\n\n if (\"coin of the week\" in tweet.lower()):\n coin = tweet.split(\"(\")\n\n # Si il a quelque chose après la 1ere parenthèse\n if (len(coin) > 1):\n coin = coin[1].split(\")\")\n\n # Si le texte est pas trop grand mais vérification pas forcément nécessaire\n if (len(coin[0]) < 10):\n coinOfTheWeek = coin[0]\n print(\"Coin of the week found : \" + coinOfTheWeek)\n\n if (len(coinOfTheWeek) == 0):\n print(\"[ERROR] Coin of the week not found :(\")\n print(\"Getting tweet from Macafee ...\")\n\n return coinOfTheWeek\n\n\n\"\"\"****************\"\"\"\n\"\"\" Tweeter stream \"\"\"\n\"\"\"****************\"\"\"\n\n\nclass TwitterStreamListener(tweepy.StreamListener):\n\n def on_status(self, status):\n handle_tweet(status)\n\n # Twitter error list : https://dev.twitter.com/overview/api/response-codes\n def on_error(self, status_code):\n if status_code == 403:\n print(\"[ERROR] The request is understood, but it has been refused or access is not allowed. Limit is maybe reached\")\n return False\n\n\ndef handle_tweet(tweet):\n if tweet.author.id_str != os.environ['TWEETER_FOLLOW_ID']:\n print(\"[WARNING] Tweet not from Macafee\")\n print(\"Getting tweet from Macafee ...\")\n return False\n\n coin = search_coin_of_the_week(tweet.text)\n start_trading(coin)\n\n\n\"\"\"*******\"\"\"\n\"\"\" Utils \"\"\"\n\"\"\"*******\"\"\"\n\n\ndef start_trading(coin):\n global coinFrom\n global platform\n # subprocess.call(['python3', '/home/erwanlbp/dev/python/Alex1664/pumpy-bot/printPrices.py', '--coin', coin, '--coin-from', coinFrom, '--platform', platform])\n handle_orders(coin, coinFrom)\n\n\ndef wait_user():\n coin = input(\"Enter the coin to trade : \\n\")\n start_trading(coin)\n\n\ndef wait_tweet():\n clientTweeter = authentication_tweeter()\n\n print(\"-- Getting tweet from Macafee ...\")\n\n streamListener = TwitterStreamListener()\n myStream = tweepy.Stream(auth=clientTweeter.auth, listener=streamListener)\n myStream.filter(follow=[os.environ['TWEETER_FOLLOW_ID']])\n\n\ndef help():\n print('pumpNdump.py -m -p -c [--test]')\n\n\n\"\"\"******\"\"\"\n\"\"\" Main \"\"\"\n\"\"\"******\"\"\"\n\n\ndef main(argv):\n mode = ''\n try:\n opts, args = getopt.getopt(argv, \"hm:tp:c:\", [\"coin=\", \"platform=\", \"mode=\", \"test\"])\n except getopt.GetoptError:\n print('error')\n help()\n sys.exit(2)\n\n global platform\n global coinFrom\n for opt, arg in opts:\n if opt == '-h':\n help()\n sys.exit()\n elif opt in (\"-c\", \"--coin\"):\n coinFrom = arg\n elif opt in (\"-m\", \"--mode\"):\n mode = arg\n if mode not in ('user', 'tweet'):\n help()\n sys.exit(2)\n elif opt in (\"-p\", \"--platform\"):\n platform = arg\n if platform not in ('cryptopia', 'binance'):\n help()\n sys.exit(2)\n elif opt in (\"-t\", \"--test\"):\n global testMode\n testMode = True\n\n print(\"-- Launching bot ...\")\n\n global client\n if platform == 'binance':\n client = Binance()\n elif platform == 'cryptopia':\n client = Cryptopia()\n else:\n help()\n sys.exit()\n\n if mode == 'user':\n wait_user()\n elif mode == 'tweet':\n wait_tweet()\n else:\n help()\n sys.exit()\n\n\nclient = None\ncoinSymbol = ''\nalexTweeterId = ''\ntestMode = False\ncoinFrom = 'ETH'\nplatform = ''\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"pumpNdump.py","file_name":"pumpNdump.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"419572413","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport json\nimport nltk\nimport re\nimport csv\nfrom tqdm import tqdm\nfrom nltk.tokenize import sent_tokenize\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nimport InferSent\nfrom InferSent.models import InferSent\n\nclass wordRemover():\n def __init__(self, word):\n self.word = word\n \n def removeWord(self, listOfWords):\n if self.word in listOfWords:\n index = listOfWords.index(self.word)\n del listOfWords[index]\n return listOfWords\n\n\nmetadata = pd.read_csv(\"../data/movie.metadata.tsv\", sep = '\\t', header = None)\nmetadata.columns = [\"movie_id\",1,\"movie_name\",3,4,5,6,7,\"genre\"]\n\nplots = []\nwith open(\"../data/plot_summaries.txt\", 'r') as f:\n reader = csv.reader(f, dialect='excel-tab') \n for row in tqdm(reader):\n plots.append(row)\n\nmovie_id = []\nplot = []\n\n# extract movie Ids and plot summaries\nfor i in tqdm(plots):\n movie_id.append(i[0])\n plot.append(i[1])\n\n# create dataframe\nmovies = pd.DataFrame({'movie_id': movie_id, 'plot': plot})\n\n# change datatype of 'movie_id'\nmetadata['movie_id'] = metadata['movie_id'].astype(str)\n\n# merge meta with movies\nmovies = pd.merge(movies, metadata[['movie_id', 'movie_name', 'genre']], on = 'movie_id')\n\ngenres = [] \n\n# extract genres\nfor i in movies['genre']: \n genres.append(list(json.loads(i).values())) \n\n# add to 'movies' dataframe \nmovies['genre_new'] = genres\n\ngenres = movies['genre_new'].values.tolist()\n\nbinarizer = MultiLabelBinarizer()\n\ny_data = binarizer.fit_transform(genres)\n\ncounts = []\ncategories = binarizer.classes_\n\nfor i in range(categories.shape[0]):\n counts.append((categories[i], np.sum(y_data[:,i])))\n\ndf_stats = pd.DataFrame(counts, columns=['genre', '#movies'])\n\nx = df_stats[df_stats['#movies']<200]\n\ngenres_to_remove = x['genre'].values.tolist()\n\nfor word in genres_to_remove:\n movies['genre_new'] = movies['genre_new'].apply(wordRemover(word).removeWord)\n\nmovies_new = movies[~(movies['genre_new'].str.len() == 0)]\n\nprint('Updated corpus shape : ', movies_new.shape)\n\nids = movies_new['movie_id'].values.tolist()\n\nreduced_genres = movies_new['genre_new'].values.tolist()\n\nbinarizer_new = MultiLabelBinarizer()\n\ny_data_new = binarizer_new.fit_transform(reduced_genres)\n\nprint('Labels array shape : {}'.format(y_data_new.shape))\n\nlabels_dict = {}\n\ncount = 0\nfor i in range(len(ids)):\n if i==40:\n break\n labels_dict[ids[i]] = y_data_new[i]\n\nprint('LABEL DICTIONARY LENGTH: {}'.format(len(labels_dict)))\n\n\n\ndef clean_text(text):\n # remove a string like {{plot}}\n text = re.sub(\"\\s*{{\\w*}}\\s*\", \"\", text)\n # remove backslash-apostrophe \n text = re.sub(\"\\'\", \"\", text)\n return text\n\nmovies_new['clean_plot'] = movies_new['plot'].apply(lambda x: clean_text(x))\n\nprint('Creating vocabulary for dataset....')\n\nnew_vocabulary = []\n\nfor movie_id in movies_new['movie_id']:\n \n plot_sr = movies_new[movies_new['movie_id']==movie_id]['clean_plot']\n \n for str_obj in plot_sr:\n plot=str_obj\n \n sentence_list = sent_tokenize(plot)\n\n new_vocabulary = new_vocabulary + sentence_list\n\nprint('\\nVocab creation done!')\n\nV = 2\nMODEL_PATH = '/dccstor/cmv/MovieSummaries/All_Data/genre_prediction/pretrained_models/infersent%s.pkl' % V\nparams_model = {'bsize': 128, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,\n\t\t\t\t'pool_type': 'max', 'dpout_model': 0.0, 'version': V}\n\nmodel = InferSent(params_model)\nmodel.load_state_dict(torch.load(MODEL_PATH))\nmodel = model.cuda()\n\nW2V_PATH = '/dccstor/cmv/MovieSummaries/All_Data/genre_prediction/fastText/crawl-300d-2M.vec'\nmodel.set_w2v_path(W2V_PATH)\n\nmodel.build_vocab_k_words(K=500000)\n\nprint('Updating Vocab....')\nmodel.update_vocab(new_vocabulary, tokenize=True)\nprint('Vocab updated!')\n\nembedding_dict = {}\n\ncount = 0\n\nprint('Embedding creation begins...')\n\nfor movie_id in movies_new['movie_id']:\n \n plot_sr = movies_new[movies_new['movie_id']==movie_id]['clean_plot']\n \n for str_obj in plot_sr:\n plot=str_obj\n \n sentence_list = sent_tokenize(plot)\n\n embedding_array = model.encode(sentence_list, tokenize=True)\n\n embedding_dict[movie_id] = embedding_array\n\n count += 1\n\n if count==40:\n \tbreak\n\nprint('EMBEDDING DICTIONARY LENGTH: {}'.format(len(embedding_dict)))\n\n# Save to disk\nprint('\\nSaving dummy dictionaries to disk...')\nnp.save(\"/dccstor/cmv/MovieSummaries/embeddings/infersent_dummy.npy\", embedding_dict)\nnp.save(\"/dccstor/cmv/MovieSummaries/embeddings/dummy_labels.npy\", labels_dict)\nprint('Finished!')\n\n\n","sub_path":"code/dummy_data.py","file_name":"dummy_data.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"170230576","text":"# USAGE\n# python server.py\n\nimport logging\nimport os\nfrom camera import Camera\nfrom flask_socketio import SocketIO\nfrom engineio.payload import Payload\n\nfrom sys import stdout\nfrom flask import Flask\nfrom flask import Response\nfrom flask import render_template\nfrom flask import request, session, send_file\nfrom werkzeug.utils import secure_filename\nimport json\nimport pdfplumber\nfrom io import BytesIO\nfrom datetime import datetime\nfrom get_gestures_from_webcam import get_gestures_from_webcam as gestures\nfrom scripts import questions as qs\nfrom scripts import statistics as st\nfrom scripts import movies as mv\nfrom PIL import Image\n\napp = Flask(__name__)\napp.logger.addHandler(logging.StreamHandler(stdout))\napp.config['SECRET_KEY'] = 'secret!'\napp.config['DEBUG'] = True\napp.config[\n 'UPLOAD_FOLDER'] = '/home/oanalavinia/Documents/Master/WADe/Disertatie/HandGestureAnalyser/server/static/files'\nPayload.max_decode_packets = 500\nsocketio = SocketIO(app)\ncamera = Camera()\nquiz = qs.QuizGame(camera.get_gesture_obj())\nmovie = mv.Movie(camera.get_gesture_obj())\nfile_name = \"/home/oanalavinia/Documents/Master/WADe/Disertatie/HandGestureAnalyser/server/static/experiments/\" + str(datetime.now())\n\napp.secret_key = '5b7373780e35434090c87dc4c9d15a2d'\n\n\ndef gen():\n \"\"\"Video streaming generator function.\"\"\"\n\n app.logger.info(\"starting to generate frames!\")\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame.tostring() + b'\\r\\n')\n\n\n@app.route(\"/\")\ndef index():\n session['startTime'] = datetime.now()\n return render_template(\"index.html\")\n\n\n@app.route(\"/statistics\")\ndef statistics():\n binary_image = st.getGestures(session['startTime'])\n img_io = BytesIO()\n rgb_im = binary_image.convert('RGB')\n rgb_im.save(img_io, 'JPEG', quality=70)\n img_io.seek(0)\n return send_file(\n img_io,\n mimetype='image/jpeg',\n as_attachment=False,\n attachment_filename='statistics.jpeg')\n\n\n@app.route(\"/video_feed\")\ndef video_feed():\n return Response(gen(),\n mimetype=\"multipart/x-mixed-replace; boundary=frame\")\n\n\n@app.route(\"/current_gesture\", methods=['GET'])\ndef current_gesture():\n return json.dumps({'gesture': camera.get_gesture()})\n\n\n@app.route(\"/get_gesture\", methods=['POST'])\ndef get_gesture():\n landmarks_x = request.form.getlist(\"landmarks_x[]\")\n landmarks_y = request.form.getlist(\"landmarks_y[]\")\n landmarks_x = [float(x) for x in landmarks_x]\n landmarks_y = [float(y) for y in landmarks_y]\n if landmarks_x:\n gesture = camera.get_gesture_obj().get_gesture_from_landmarks(landmarks_x, landmarks_y)\n context = camera.get_gesture_obj().get_context()\n return json.dumps({'gesture': gesture, 'context': context})\n return json.dumps({'gesture': \"none\"})\n\n\n@app.route(\"/save_data\", methods=['POST'])\ndef save_data():\n camera.get_gesture_obj().get_owl_utilities().save_data()\n\n return json.dumps({'response': \"done\"})\n\n\n@app.route(\"/save_gesture_start_time\", methods=['POST'])\ndef save_gesture_start_time():\n context = camera.get_gesture_obj().get_context()\n start_time = request.form.get('start_time')\n with open(file_name, 'a') as f:\n f.write(context + ' ' + start_time + '\\n')\n\n return json.dumps({'response': \"done\"})\n\n\n@app.route(\"/questions\", methods=['GET', 'POST'])\ndef questions():\n # gestures.save_data()\n if request.method == 'GET':\n camera.get_gesture_obj().set_context(\"QuizGame\")\n return quiz.create_question_game()\n else:\n # gestures.save_data()\n user_answers = quiz.get_correct_answers(request.form.getlist('answersTime[]'))\n return json.dumps({'status': 'OK', 'results': user_answers})\n\n\n@app.route(\"/random_movies\", methods=['GET'])\ndef random_movies():\n if request.method == 'GET':\n camera.get_gesture_obj().set_context(\"SelectionGame\")\n result = movie.get_rec_system().get_random_movies()\n return json.dumps({'movies': result[0], 'movie_ids': result[1]})\n\n\n@app.route(\"/rec_movies\", methods=['POST'])\ndef rec_movies():\n if request.method == 'POST':\n start_time = datetime.fromtimestamp(int(request.form.get('startTime')) / 1000.0)\n end_time = datetime.fromtimestamp(int(request.form.get('endTime')) / 1000.0)\n movie_ids = request.form.getlist('movie_ids[]')\n # Get gesture based on startTime and endTime.\n gesture = movie.queries_handler.query_movies(start_time, end_time)\n # Get recommendation.\n rec_movies, movie_name = movie.get_recommendations(gesture, movie_ids)\n print(rec_movies)\n # Add rule to owl.\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"SelectionGame\", gesture, gesture_obj.get_owl_context())\n\n return json.dumps({'status': 'OK', 'movies': rec_movies, 'selected_movie': movie_name})\n\n\n@app.route('/uploader', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n context = request.form.get('context')\n file = request.files['file']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n if context == \"Image\":\n camera.get_gesture_obj().set_context(\"Image\")\n image = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n width, height = image.size\n print(width, height)\n\n return {'fileName': file.filename, 'width': width, 'height': height}\n elif context == \"PDFDocument\":\n camera.get_gesture_obj().set_context(\"PDFDocument\")\n with pdfplumber.open(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as pdf:\n page_1 = pdf.pages[0]\n nr_pages = len(pdf.pages)\n\n return {'fileName': file.filename, 'width': str(page_1.width), 'height': str(page_1.height),\n 'nr_pages': str(nr_pages)}\n\n\n@app.route('/add_image_rule', methods=['POST'])\ndef add_image_rule():\n gesture = request.form.get('gesture')\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"Image\", gesture, gesture_obj.get_owl_context())\n\n return {'response': \"done\"}\n\n\n@app.route('/add_file_rule', methods=['POST'])\ndef add_file_rule():\n gesture = request.form.get('gesture')\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"PDFDocument\", gesture, gesture_obj.get_owl_context())\n\n return {'response': \"done\"}\n\n\n@app.route('/do_close_camera', methods=['POST'])\ndef do_close_camera():\n print(\"do close {}\".format(request.form.get('do_close_camera')))\n if request.form.get('do_close_camera') == \"true\":\n gestures.set_record(False)\n elif request.form.get('do_close_camera') == \"false\":\n gestures.set_record(True)\n\n return json.dumps({'response': \"ok\"})\n\n\nif __name__ == '__main__':\n # app.run(port=80, debug=True,\n # threaded=True, use_reloader=False)\n socketio.run(app, host=\"0.0.0.0\", port=\"5000\", debug=True, use_reloader=False, ssl_context='adhoc')\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137706546","text":"# -*-coding:utf-8-*-\r\n\r\nimport json\r\nimport time\r\nimport os\r\n\r\nimport sys\r\nreload(sys)\r\nsys.path.append('../')\r\n\r\nfrom global_utils import flow_text_index_name_pre,flow_text_index_type,es_flow_text\r\nfrom time_utils import ts2datetime\r\nfrom parameter import sensitive_score_dict\r\n\r\ndef get_sensitive_info(timestamp,mid):\r\n index_name = flow_text_index_name_pre + ts2datetime(timestamp)\r\n try:\r\n item_result = es_flow_text.get(index=index_name,doc_type=flow_text_index_type,id=mid)['_source']\r\n sensitive_info = item_result['sensitive']\r\n except:\r\n sensitive_info = 0\r\n\r\n return sensitive_info\r\n\r\ndef get_sensitive_user(uid):\r\n try:\r\n tmp_stage = r_sensitive.hget('sensitive_words', uid)\r\n if tmp_stage:\r\n sensitive_score += v * sensitive_score_dict[str(tmp_stage)]\r\n except:\r\n sensitive_score = 0\r\n\r\n return sensitive_score\r\n \r\n","sub_path":"xnr/sina/sensitive/get_sensitive.py","file_name":"get_sensitive.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"34946283","text":"\n'''application/apps.py'''\nfrom flask import Flask, jsonify\nfrom flask_jwt_extended import JWTManager\n\nfrom instance.config import app_config\nfrom .api.v1.views.auth_endpoints import auth, BLACKLIST\nfrom .api.v1.views.products_endpoints import product\nfrom .api.v1.views.sales_endpoints import sale\n\n\ndef create_app(config):\n '''function configuring the Flask App'''\n app = Flask(__name__)\n\n app.url_map.strict_slashes = False\n app.config.from_object(app_config[config])\n app.config[\"TESTING\"] = True\n\n app.config['JWT_SECRET_KEY'] = 'mysecretkey'\n app.config['JWT_BLACKLIST_ENABLED'] = True\n app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']\n jwt = JWTManager(app)\n\n @jwt.user_claims_loader\n def add_claims_to_access_token(user_object):\n '''add role claims to access token'''\n return {'role': user_object['role']}\n\n @jwt.user_identity_loader\n def user_identity_lookup(user_object):\n '''set token identity from user_object passed to username'''\n return user_object[\"username\"]\n\n @jwt.token_in_blacklist_loader\n def check_if_token_blacklist(decrypted_token):\n '''check if jti(unique identifier) is in black list'''\n json_token_identifier = decrypted_token['jti']\n return json_token_identifier in BLACKLIST\n\n '''Error handlers'''\n @app.errorhandler(400)\n def bad_request(error):\n '''error handler for Bad request'''\n return jsonify(dict(error='Bad request')), 400\n\n @app.errorhandler(404)\n def Resource_not_found(error):\n '''error handler for 404'''\n return jsonify(dict(error='Resource not found')), 404\n\n @app.errorhandler(405)\n def unauthorized(error):\n '''error handler for 405'''\n return jsonify(dict(error='Method not allowed')), 405\n\n @app.errorhandler(Exception)\n def unhandled_exception(e):\n return jsonify(dict(error='Internal server error')), 500\n\n app.register_blueprint(auth)\n app.register_blueprint(product)\n app.register_blueprint(sale)\n\n return app\n","sub_path":"application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"360964088","text":"def check(day, month):\r\n if (month == 4 or month == 6 or month == 9 or month == 11) and day == 31:\r\n return 1\r\n else:\r\n return 0\r\n \r\ndef isleap(year):\r\n if (year % 4 == 0 and year %100 == 0) or year % 400 == 0:\r\n return 1\r\n else:\r\n return 0\r\n\r\nres = False\r\nflag = False\r\nwhile not flag:\r\n day = int(input(\"Enter day \"))\r\n month = int(input(\"Enter month \"))\r\n year = int(input(\"Enter year \"))\r\n\r\n tomm_month = month\r\n tomm_year = year\r\n \r\n if day<1 or day>31:\r\n print(\"Value of day, not in the range 1...31\")\r\n flag = True\r\n res = True\r\n \r\n if month<1 or month>12:\r\n print(\"Value of month, not in the range 1...12\")\r\n flag = True\r\n res = True\r\n elif check(day,month):\r\n print(\"value of day, not in the range day<=30\")\r\n flag = True\r\n res = True\r\n \r\n if year<1812 or year>2015:\r\n print(\"value of year, not in the range 1812...2015\")\r\n flag = True\r\n res = True\r\n \r\n if month==2:\r\n if isleap(year) and day>29:\r\n print(\"invalid date input for leap year\")\r\n flag = True\r\n res = True\r\n elif (not(isleap(year)) and day>28):\r\n print(\"invalid date input for not a leap year\")\r\n flag = True\r\n res = True\r\n flag = True\r\n \r\ntomm_day = 0\r\nif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10:\r\n if day<31:\r\n tomm_day = day + 1\r\n else:\r\n tomm_day = 1\r\n tomm_month = month + 1\r\nelif month == 4 or month == 6 or month == 9 or month == 11:\r\n if day<30:\r\n tomm_day = day + 1\r\n else:\r\n tomm_day = 1\r\n tomm_month = month + 1\r\n\r\nelif month == 12:\r\n if day<31:\r\n tomm_day = day+1\r\n else:\r\n tomm_day = 1\r\n tomm_month = 1\r\n if year == 2015:\r\n print(\"The next day is out of boundray value of year\")\r\n tomm_year = year + 1\r\n else:\r\n tomm_year = year + 1\r\n\r\nelse:\r\n if day<28:\r\n tomm_day = day + 1\r\n elif isleap(year) and day == 28:\r\n tomm_day = day + 1\r\n elif day == 28 or day == 29:\r\n tomm_day = 1\r\n tomm_month = 3\r\n \r\nif not res:\r\n print(f\"next day is {tomm_day} {tomm_month} {tomm_year}\")\r\n \r\n","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"607591069","text":"n = int(input())\ndef hanoi(n, s, m, e): # 원판의 개수, 시작점, 거치는점, 끝점\n if n == 1:\n print(\"{} {}\".format(s, e)) \n else : # 위에 조건에서 return이 없기 때문에 else 처리를 해주어야 n이 1일때 아래가 작동 안한다.\n hanoi(n-1, s, e, m) \n hanoi(1,s,m,e) \n hanoi(n-1, m, s, e)\nprint(2**n-1)\nhanoi(n,1,2,3) # 이렇게 하면 None이 안나옴\n# print(hanoi(3,1,2,3)) # 이렇게하면 None 발생 왜나하면 위에 함수가 return이 아니라 값이 없는데 프린트를 해서 그럼","sub_path":"Baekjoon/재귀/하노이 탑 이동 순서.py","file_name":"하노이 탑 이동 순서.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"120932789","text":"import os\nfrom argparse import ArgumentParser\n\nimport torch\nfrom pytorch_lightning import LightningModule, loggers\nfrom pytorch_lightning import seed_everything, Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.metrics.functional import accuracy, dice_score, iou\nfrom torch.nn.functional import cross_entropy\nfrom torch.optim import AdamW\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\n\nfrom dataManagement.dataModules import TwoDomainDM\nfrom models.FCDenseNet.tiramisu import FCDenseNet57Base, FCDenseNet57Classifier\n\n\nclass RightLaneSTModule(LightningModule):\n def __init__(self, lr=1e-3, decay=1e-4, lrRatio=1e3, num_cls=2):\n super().__init__()\n self.save_hyperparameters('lr', 'decay', 'lrRatio')\n\n # Create network parts\n self.featureExtractor = FCDenseNet57Base()\n self.classifier = FCDenseNet57Classifier(n_classes=num_cls)\n\n # Training parameters\n self.lr = lr\n self.decay = decay\n self.lrRatio = lrRatio\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n argGroup = parser.add_argument_group('LightningModule', 'Parameters defining network training')\n\n argGroup.add_argument('-lr', '--learningRate', type=float, default=1e-3, help=\"Starting learning rate\")\n argGroup.add_argument('--decay', type=float, default=1e-4, help=\"L2 weight decay value\")\n argGroup.add_argument('--lrRatio', type=float, default=1000,\n help=\"Ratio of maximum and minimum of learning rate for cosine LR scheduler\")\n\n return parser\n\n def forward(self, x):\n x = self.featureExtractor(x)\n x = self.classifier(x)\n return x\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n\n # Forward propagation, loss calculation\n outputs = self.forward(x)\n loss = cross_entropy(outputs, y)\n\n # Accuracy calculation\n _, labels_hat = torch.max(outputs, 1)\n train_acc = accuracy(labels_hat, y) * 100\n\n self.log('tr_loss', loss)\n self.log('tr_acc', train_acc, prog_bar=True)\n\n return loss\n\n def validation_step(self, batch, batch_idx):\n return self.evaluate_batch(batch)\n\n def validation_epoch_end(self, outputs):\n logs = self.summarize_evaluation_results(outputs)\n self.log('val_loss', logs['loss'])\n self.log('val_acc', logs['acc'], prog_bar=True, logger=True)\n self.log('val_dice', logs['dice'])\n self.log('val_iou', logs['iou'], prog_bar=True, logger=True)\n # self.log('step', self.current_epoch)\n\n def test_step(self, batch, batch_idx):\n return self.evaluate_batch(batch)\n\n def test_epoch_end(self, outputs):\n logs = self.summarize_evaluation_results(outputs)\n self.log('test_loss', logs['loss'])\n self.log('test_acc', logs['acc'])\n self.log('test_dice', logs['dice'])\n self.log('test_iou', logs['iou'])\n\n def configure_optimizers(self):\n optimizer = AdamW(self.parameters(), lr=self.lr, weight_decay=self.decay)\n scheduler = CosineAnnealingLR(optimizer, 25, eta_min=self.lr / self.lrRatio)\n return [optimizer], [scheduler]\n\n def evaluate_batch(self, batch):\n x, y = batch\n\n # Forward propagation, loss calculation\n outputs = self.forward(x)\n loss = cross_entropy(outputs, y)\n\n _, labels_hat = torch.max(outputs, 1)\n\n weight = x.shape[0]\n return {\n 'loss': loss * weight,\n 'acc': accuracy(labels_hat, y) * weight,\n 'dice': dice_score(outputs, y) * weight,\n 'iou': iou(labels_hat, y) * weight,\n 'weight': weight,\n }\n\n def summarize_evaluation_results(self, outputs):\n total_weight = sum(x['weight'] for x in outputs)\n loss = sum([x['loss'] for x in outputs]) / total_weight\n acc = sum([x['acc'] for x in outputs]) / total_weight * 100.0\n dice = sum([x['dice'] for x in outputs]) / total_weight\n iou = sum([x['iou'] for x in outputs]) / total_weight * 100.0\n\n return {\n 'loss': loss,\n 'acc': acc,\n 'dice': dice,\n 'iou': iou,\n }\n\n\ndef main(args, model_name: str, reproducible: bool, comet: bool, wandb: bool):\n if reproducible:\n seed_everything(42)\n args.deterministic = True\n args.benchmark = True\n\n if args.default_root_dir is None:\n args.default_root_dir = 'results'\n\n if comet:\n from pytorch_lightning.loggers import CometLogger\n comet_logger = loggers.CometLogger(\n api_key=os.environ.get('COMET_API_KEY'),\n workspace=os.environ.get('COMET_WORKSPACE'), # Optional\n project_name=os.environ.get('COMET_PROJECT_NAME'), # Optional\n experiment_name=model_name # Optional\n )\n args.logger = comet_logger\n if wandb:\n from pytorch_lightning.loggers import WandbLogger\n wandb_logger = WandbLogger(project=os.environ.get('WANDB_PROJECT_NAME'), log_model=True, sync_step=True)\n args.logger = wandb_logger\n\n # Save best model\n model_checkpoint = ModelCheckpoint(\n filename=model_name + '_{epoch}',\n save_top_k=1,\n monitor='val_iou',\n mode='max',\n )\n args.checkpoint_callback = model_checkpoint\n\n data = TwoDomainDM(dataPath=args.dataPath, augment=args.augment, batch_size=args.batch_size, num_workers=8)\n model = RightLaneSTModule(lr=args.learningRate, lrRatio=args.lrRatio, decay=args.decay, num_cls=4)\n\n # Parse all trainer options available from the command line\n trainer = Trainer.from_argparse_args(args)\n trainer.fit(model, datamodule=data)\n\n # Reload best model\n model = RightLaneSTModule.load_from_checkpoint(model_checkpoint.best_model_path, dataPath=args.dataPath, num_cls=4)\n\n # Upload weights\n if comet:\n comet_logger.experiment.log_model(model_name + '_weights', model_checkpoint.best_model_path)\n\n # Perform testing\n trainer.test(model, datamodule=data)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n\n # Data location\n parser.add_argument('--dataPath', type=str, help=\"Path of database root\")\n\n parser.add_argument('--comet', action='store_true', help='Define flag in order to use Comet.ml as logger.')\n parser.add_argument('--wandb', action='store_true', help='Define flag in order to use WandB as logger.')\n parser.add_argument('--model_name', type=str, default='sandt', help='Model identifier for logging and checkpoints.')\n parser.add_argument('--reproducible', action='store_true',\n help=\"Set seed to 42 and deterministic and benchmark to True.\")\n\n # Add model arguments to parser\n parser = TwoDomainDM.add_argparse_args(parser)\n parser = RightLaneSTModule.add_model_specific_args(parser)\n\n # Adds all the trainer options as default arguments (like max_epochs)\n parser = Trainer.add_argparse_args(parser)\n\n args = parser.parse_args()\n\n from dotenv import load_dotenv\n\n load_dotenv()\n main(args, model_name=args.model_name, reproducible=args.reproducible, comet=args.comet, wandb=args.wandb)\n","sub_path":"rightLaneNetwork/RightLaneSTModule.py","file_name":"RightLaneSTModule.py","file_ext":"py","file_size_in_byte":7270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"422247442","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 8 10:27:11 2020\n\n@author: gshambul\n\"\"\"\n\n'''\n\nProgram will display the number of occurance count of each unique values which is present in list .\n\n'''\n\n\ndef list_creation(user_list):\n element_count = int(input(\"Enter the number of elements to be present in user list : \"))\n if(element_count>0):\n for _ in range(1,element_count+1):\n print(\"Enter {} element : \".format(_))\n user_list.append(int(input()))\n else:\n print(\"Please provide the element_count value greater than zero \")\n exit(0)\n \n \n \nif __name__ == \"__main__\" :\n user_list = list()\n list_creation(user_list)\n print(\"user input list is : \",user_list)\n print(\"Element --> Occurence count\")\n for i in set(user_list):\n print(i,\" --> \",user_list.count(i))\n","sub_path":"Program06.py","file_name":"Program06.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"488282871","text":"from os import remove, mkdir\nfrom os.path import join, exists, isdir\nimport random\nimport string\nimport tensorflow as tf\nimport numpy as np\nimport pickle\n\nfrom tensorflow.keras.layers import Layer, Dense, Flatten, Conv2D, Conv1D, Dropout\n\n\ndef check_dir():\n if not isdir(\"layers\"):\n mkdir(\"layers\")\n\n\nclass Strato(object):\n def __init__(self, name=None, config=None):\n\n # create directory if not existent\n check_dir()\n\n # default settings\n self.config = {\n 'layer_type': 'Dense',\n 'frozen': False,\n 'activation': \"relu\",\n 'dense_units': 16,\n 'filters': 8,\n 'kernel_size': 5,\n 'strides': 2,\n 'padding': \"same\",\n 'Dropout_rate': 0.2}\n\n # if there are configurations, use them to overwrite the default settings\n if config != None:\n for k in config.keys():\n self.config[k] = config[k]\n\n # assemble the layer\n self.assemble()\n\n if name == None:\n self.weights = None\n self.name = ''.join(random.choice(\n string.ascii_lowercase + string.digits) for _ in range(16))\n\n self.path = join(\"layers\", self.name)\n while exists(self.path):\n self.name = ''.join(random.choice(\n string.ascii_lowercase + string.digits) for _ in range(16))\n self.path = join(\"layers\", self.name)\n else:\n self.name = name\n self.path = join(\"layers\", self.name)\n self.load()\n\n def assemble(self):\n\n if self.config['layer_type'] == \"Dense\":\n self.layer = Dense(\n units=self.config['dense_units'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['dense_units']\n\n elif self.config['layer_type'] == \"Conv1D\":\n self.layer = Conv1D(\n filters=self.config['filters'],\n kernel_size=self.config['kernel_size'],\n strides=self.config['strides'],\n padding=self.config['padding'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['filters']\n\n elif self.config['layer_type'] == \"Conv2D\":\n self.layer = Conv2D(\n filters=self.config['filters'],\n kernel_size=self.config['kernel_size'],\n strides=self.config['strides'],\n padding=self.config['padding'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['filters']\n\n elif self.config['layer_type'] == \"Dropout\":\n self.layer = Dropout(\n rate=self.config['Dropout_rate'])\n\n # what is visualized\n self.label = self.config['Dropout_rate']\n else:\n raise ValueError(\"Incorrect layer type\")\n\n def freeze(self):\n self.layer.trainable = False\n self.config['frozen'] = True\n\n def unfreeze(self):\n self.layer.trainable = True\n self.config['frozen'] = False\n\n def save(self):\n \"\"\"\n Save all the configurations and the weights if existent.\n \"\"\"\n\n # if the weights can be detected, save them\n\n weights = self.layer.get_weights()\n\n wname = self.path + \".weights\"\n\n if exists(wname):\n remove(wname)\n pickle.dump(weights, open(wname, \"wb\"))\n\n iname = self.path + \".info\"\n if exists(iname):\n remove(iname)\n pickle.dump(self.config, open(iname, \"wb\"))\n\n def load(self):\n\n wname = self.path + \".weights\"\n self.weights = pickle.load(open(wname, \"rb\"))\n\n iname = self.path + \".info\"\n self.config = pickle.load(open(iname, \"rb\"))\n\n self.assemble()\n\n def resetWeights(self):\n raise NotImplemented()\n","sub_path":"Chimera/Layers.py","file_name":"Layers.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"430785312","text":"from django.shortcuts import render\nfrom .resources import AddressResource\nfrom tablib import Dataset\nfrom django.contrib import messages\nfrom .models import Address\nimport xlwt\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\n# Create your views here.\n\n\ndef home(request):\n if request.method == 'POST':\n address_resource = AddressResource()\n dataset = Dataset()\n new_address = request.FILES['myfile']\n if not new_address.name.endswith('xlsx' or 'xl'):\n messages.info(request, 'Wrong format! please choose Exel file to upload')\n return render(request, 'home.html')\n imported_data = dataset.load(new_address.read(), format=('xlsx' or 'xl'))\n for data in imported_data:\n value = Address(\n data[0], data[1], data[2], data[3], data[4], data[5],\n data[6], data[7], data[8], data[9], data[10], data[11]\n )\n value.save()\n return render(request, 'home.html')\n\n\ndef export_users_xls(request):\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"users.xls\"'\n\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet('Address')\n\n # Sheet header, first row\n row_num = 0\n\n font_style = xlwt.XFStyle()\n font_style.font.bold = True\n\n columns = ['Name', 'Job', 'Address1', 'Address2', 'Area', 'City', 'State', 'Country', 'Pincode', 'latitude',\n 'longitude']\n\n for col_num in range(len(columns)):\n ws.write(row_num, col_num, columns[col_num], font_style)\n\n # Sheet body, remaining rows\n font_style = xlwt.XFStyle()\n\n rows = Address.objects.all().values_list('Name', 'Job', 'Address1', 'Address2', 'Area', 'City', 'State', 'Country',\n 'Pincode', 'latitude', 'longitude')\n for row in rows:\n row_num += 1\n for col_num in range(len(row)):\n ws.write(row_num, col_num, row[col_num], font_style)\n\n wb.save(response)\n return HttpResponse(response, home(request))\n","sub_path":"Location/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"197287732","text":"import os\nimport cv2\nfrom glob import glob\n\ndef main():\n video_filenames = glob(\"/home/ubuntu/cs230_data/*/*.mp4\")\n\n video_sizes(video_filenames)\n video_frames_analyze(video_filenames)\n image_frame_analyze(video_filenames[0])\n\ndef image_frame_analyze(filename):\n cap = cv2.VideoCapture(filename)\n ret, frame = cap.read()\n if ret == False:\n print(\"Read unsuccessful\")\n return\n print(\"Shape of Image (Height, Width, Channels): \" + str(frame.shape))\n test_image = \"./test.jpg\"\n cv2.imwrite(test_image, frame)\n print(\"File Size of One Frame: \" + humansize(os.path.getsize(test_image)))\n\ndef video_frames_analyze(video_filenames):\n durations = 0\n fps = 0\n frames = 0\n sub_sample_size = 100\n for fname in video_filenames[:sub_sample_size]:\n vid_fps, vid_frames, vid_duration = analyze_single_video(fname)\n fps += vid_fps\n frames += vid_frames\n durations += vid_duration\n print(\"Average FPS of videos: \" + str(fps/sub_sample_size))\n print(\"Average Frame Count of videos: \" + str(frames/sub_sample_size))\n print(\"Average Duration Count of videos: \" + str(durations/sub_sample_size))\n\n# This function computes the fps, number of frames, and duration in seconds\n# for a single video\ndef analyze_single_video(filename):\n cap = cv2.VideoCapture(filename)\n # Compute the Frames-Per-Second for the video\n fps = cap.get(cv2.CAP_PROP_FPS)\n # Get the number of frames in the video\n frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n # Compute the duration of the video (in seconds)\n duration = frame_count/fps\n cap.release()\n return fps, frame_count, duration\n\n# This function computes the sizes (in human-readable form) for each video\ndef video_sizes(video_filenames):\n sizes = [os.path.getsize(vid) for vid in video_filenames if\n os.path.isfile(vid) and \"metadata\" not in vid]\n print(\"Min Video File Size: \" + humansize(min(sizes)))\n print(\"Max Video File Size: \" + humansize(max(sizes)))\n print(\"Avg Video File Size: \" + humansize(sum(sizes)/len(sizes)))\n\nsuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\ndef humansize(nbytes):\n i = 0\n while nbytes >= 1024 and i < len(suffixes)-1:\n nbytes /= 1024.\n i += 1\n f = ('%.2f' % nbytes).rstrip('0').rstrip('.')\n return '%s %s' % (f, suffixes[i])\n\nmain()\n","sub_path":"data_exploration/video_explore.py","file_name":"video_explore.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"462869860","text":"import numpy as np\nimport tensorflow as tf\nfrom .GomokuTools import GomokuTools as gt\nfrom .TF2Tools import TerminalDetector\n\nclass ValueDataHelper:\n def __init__(self, N, representation, edges=True, cut_off=None):\n \"\"\"\n Helper supporting various representations of a particular gomoku position\n params:\n N: board size\n representation: either of \"NxNx2\", \"NxNx1\", \"NxNx1B\"\n \"NxNx2\" uses two matrices alternatingly, the player to move next always on the top matrix\n \"NxNx1\" uses a single matrix, the player to move always +1, the other -1\n \"NxNx1B\" uses one matrix for the players (like NxNx1) and a second for the border. \n edges: boolean, whether to model edges as defensive stones or not. Not relevant for NxNx1B\n \"\"\"\n self.N = N\n self.rep = representation\n self.edges = edges\n self.cut_off = cut_off\n \n \n def from_string_with_bellmann(self, board, terminal_value=None, gamma=1.0):\n \"\"\"\n Creates an symmetry-augmented dataset of board positions and their values.\n Values are calculated as Bellmann rollouts backwards from terminal_value with alternating \n signs using discount factor gamma.\n The samples will have shape [N_moves*8, N+2, N+2, 2]\n\n If terminal_value is 1, expect the values to be [..., gamma^2, -gamma, gamma, -1, 1]\n\n board: The string rep of the stones, like e.g. \"j10k11i9\"\n N: the size of the board\n \"\"\"\n \n # stones in matrix coordinates respecting the border padding\n maybe_padded_stones = self.maybe_padded_coords(board)\n\n # all equivalent representations: 4xrot, 2xflip = 8 variants \n all_traj = self.all_symmetries(maybe_padded_stones)\n \n all_samples = []\n all_values = []\n for traj in all_traj:\n samples, values = self.traj_to_samples(traj, \n terminal_value=terminal_value, \n gamma=gamma) \n\n # Take only the last, most meaningful values\n if self.cut_off: \n samples = samples[-self.cut_off:] \n values = values[-self.cut_off:]\n\n all_samples = all_samples + samples\n all_values = all_values + values\n \n return all_samples, all_values\n\n \n def maybe_padded_coords(self, board):\n \"\"\"\n return stones in matrix coordinates respecting the border padding\n \"\"\"\n stones = gt.string_to_stones(board)\n matrix_coords = [gt.b2m([ord(s[0])-64, s[1]], self.N) for s in stones]\n if self.edges:\n return np.add(matrix_coords, [1,1])\n else: \n return matrix_coords\n\n \n def all_symmetries(self, coords):\n \"\"\"\n All 8 equivalent game plays\n coords: border-padded coordinates\n \"\"\"\n \n return [\n self.rot_flip(coords, quarters=quarters, flip=flip) \n for quarters in range(4) for flip in [False, True]\n ]\n\n \n def create_sample(self, moves, to_move):\n sample = self.template()\n for move in moves:\n if self.rep == 'NxNx2':\n sample[move[0], move[1], to_move] = 1\n elif self.rep == 'NxNx1B':\n sample[move[0], move[1], 0] = 1 - 2 * to_move\n else:\n sample[move[0], move[1]] = 1 - 2 * to_move\n to_move = 1 - to_move\n return sample\n \n \n def traj_to_samples(self, traj, terminal_value, gamma):\n \"\"\"\n creates samples for a given trajectory, together with the bellmann-values\n\n traj: trajectory, represented by their padded coordinates\n terminal_value: the given value of the last state in the trajectory\n gamma: discount factor. \n \"\"\"\n samples = []\n values = []\n value = terminal_value\n to_move_first = 1\n for t in range(len(traj)): \n moves = traj[:t+1] \n sample = self.create_sample(moves, to_move_first)\n\n samples.append(sample)\n values.append(value)\n # Actually, this is the wrong order, we'll invert before returning\n if to_move_first == 0:\n value = - value\n else:\n value = - gamma * value\n to_move_first = 1 - to_move_first\n\n return samples, values[::-1]\n \n \n def template(self):\n \"\"\"\n create a fresh empty board representation\n \"\"\"\n s = np.zeros([self.N,self.N], dtype=np.int16)\n\n if self.rep == 'NxNx1B':\n border = 1\n elif self.edges:\n if self.rep == 'NxNx1':\n border = -1\n else:\n border = 1\n if self.edges or self.rep == 'NxNx1B':\n defensive = np.pad(s, pad_width=1, constant_values=border)\n else: \n defensive = s\n \n if self.rep == \"NxNx2\":\n if self.edges:\n N=self.N+2\n else:\n N=self.N\n offensive = np.zeros([N, N], dtype=np.int16)\n template = np.stack([offensive, defensive], axis=-1)\n elif self.rep == 'NxNx1B':\n offensive = np.zeros([self.N+2, self.N+2], dtype=np.int16)\n template = np.stack([offensive, defensive], axis=-1) \n else: \n template = defensive\n\n return template\n \n \n def rot_flip (self, coords, quarters, flip):\n \"\"\"\n coords: list of tuples of matrix coordinates\n quarters: multiples of 90 degrees to rotate\n flip: boolean: Flip or not\n \"\"\"\n if self.edges:\n N = self.N+2\n else:\n N = self.N\n\n r,c = np.transpose(coords)\n quarters = quarters % 4\n if quarters == 0:\n res = (r,c)\n elif quarters == 1:\n res = (N-c-1, r)\n elif quarters == 2:\n res = (N-r-1,N-c-1)\n elif quarters == 3:\n res = (c, N-r-1)\n if flip:\n res = res[::-1]\n return np.transpose(res)\n \n \nclass SampleDataHelper (ValueDataHelper):\n \"\"\"\n Adds policy-related utilities to the ValueDataHelper\n \"\"\"\n def __init__(self, N, representation, edges=True, cut_off=None):\n \"\"\"\n Helper supporting various representations of a particular gomoku position\n params:\n N: board size\n representation: either of \"NxNx2\", \"NxNx1\"\n \"NxNx2\" uses two matrices alternatingly, the player to move next always on the top matrix\n \"NxNx1\" uses a single matrix, the player to move always +1, the other -1\n \"NxNx1B\" uses one matrix for the players (like NxNx1) and a second for the border. \n edges: boolean, whether to model edges as defensive stones or not. Not relevant for NxNx1B\n cut_off: the number of positions per trajectory, counted from the end backwards\n Allows to focus on the later stages of the game\n \"\"\"\n super().__init__(N, representation, edges, cut_off)\n\n \n def from_string_with_actions(self, board):\n \"\"\"\n Creates an symmetry-augmented dataset of board positions and their actions.\n The samples will have shape [N_moves*8, N+2, N+2, 2]\n\n board: The string rep of the stones, like e.g. \"j10k11i9\"\n \"\"\"\n \n # stones in matrix coordinates respecting the border padding\n maybe_padded_stones = self.maybe_padded_coords(board)\n\n # all equivalent representations: 4xrot, 2xflip = 8 variants \n all_traj = self.all_symmetries(maybe_padded_stones)\n \n all_samples = []\n all_values = []\n for traj in all_traj:\n samples, values = self.traj_to_samples_with_actions(traj)\n \n if self.cut_off: \n samples = samples[-self.cut_off:] \n values = values[-self.cut_off:]\n\n all_samples = all_samples + samples\n all_values = all_values + values \n\n \n return all_samples, all_values\n\n def traj_to_samples_with_actions(self, traj, sparse=False):\n \"\"\"\n creates samples from a given trajectory, together with their actions\n\n traj: trajectory, represented by their padded coordinates\n terminal_value: the given value of the last state in the trajectory\n gamma: discount factor. \n \"\"\"\n samples = []\n actions = []\n to_move_first = 1\n for t in range(len(traj)-1): \n moves = traj[:t+1]\n r, c = traj[t+1]\n if self.rep == 'NxNx1B' or self.edges:\n r-=1\n c-=1\n if sparse: \n # flattened coordinates\n action = r * self.N + c\n else:\n action = np.zeros([self.N, self.N], dtype=np.float32)\n action[next_move[0]][next_move[1]] = 1.0\n\n sample = self.create_sample(moves, to_move_first)\n \n samples.append(sample)\n actions.append(action)\n\n to_move_first = 1 - to_move_first\n\n \n return samples, actions\n \n \n def sample_from_string(self, game):\n coords = self.maybe_padded_coords(game)\n to_move = 1 if len(coords) % 2 == 1 else 0\n return self.create_sample(coords, to_move)\n \n\n def stones_from_NxNx1B (self, smp):\n \"\"\"\n reconstructs stones from a NxNx1B sample representation\n Note that the moves will not (likely) be in their original order \n \"\"\"\n board = np.rollaxis(smp, 2, 0)[0].T[1:-1].T[1:-1]\n to_move = np.sum(board > 0)\n other = np.sum(board < 0)\n\n if other > to_move:\n BLACK, WHITE = -1, 1\n else:\n BLACK, WHITE = 1, -1\n\n r,c = np.where(board == WHITE)\n x,y = gt.m2b((r,c), self.N)\n white_moves = list(zip(x,y))\n\n r,c = np.where(board == BLACK)\n x,y = gt.m2b((r,c), self.N)\n black_moves = list(zip(x,y))\n\n moves = np.zeros([len(black_moves) + len(white_moves),2])\n moves[::2,] = np.array(black_moves)\n moves[1::2,] = np.array(white_moves)\n stones = [(int(move[0]), int(move[1])) for move in moves]\n\n return stones\n\ndef new_value_dataset(file_pattern, gamma, sdh,\n batch_size=256, num_epochs=1, buffer_size=500):\n \n games = tf.data.experimental.make_csv_dataset(\n file_pattern = file_pattern,\n column_names=[\"game\", \"winner\"],\n batch_size=1,\n num_epochs=num_epochs\n ) \n def _generator(): \n for batch in iter(games):\n game = batch['game'][0].numpy().decode('ascii')\n smp, lbl = sdh.from_string_with_bellmann(game, -1, gamma)\n zipped = zip(smp, lbl)\n for s_and_v in zipped:\n yield s_and_v\n \n inputs = tf.data.Dataset.from_generator(\n _generator, output_types=(tf.int32, tf.float32))\n \n inputs = inputs.shuffle(buffer_size).batch(batch_size)\n return inputs\n \n \n \ndef new_policy_dataset(file_pattern, sdh,\n batch_size=256, num_epochs=1, buffer_size=500):\n \n games = tf.data.experimental.make_csv_dataset(\n file_pattern = file_pattern,\n column_names=[\"game\", \"winner\"],\n batch_size=1,\n num_epochs=num_epochs\n ) \n def _generator(): \n for batch in iter(games):\n game = tf.squeeze(batch['game']).numpy().decode('ascii')\n smp, lbl = sdh.from_string_with_actions(game)\n lbl = np.reshape(lbl, [-1, 19*19])\n zipped = zip(smp, lbl)\n for s_and_v in zipped:\n yield s_and_v\n \n inputs = tf.data.Dataset.from_generator(\n _generator, output_types=(tf.int32, tf.float32))\n \n inputs = inputs.shuffle(buffer_size).batch(batch_size)\n return inputs\n \n \n \n \ndef analyse_and_recommend(smp, pi, n_best, N=19, m2b=\"board\"):\n \"\"\"\n calculates the n_best best positions in board coordinates of smp, \n looking at the sample and its policy result pi(smp)\n Params:\n smp: np.ndarray: A sample in NxNx1B representation (using 1,-1 for the stones)\n pi: np.ndarray: the NxN policy pi(a|s=smp)\n n_best: the n_best positions to return. Note that there may be further positions\n having pi match the worst of the best positions. We make a hard cut so that the\n number of returned positions is exactly n_best.\n N: the board size\n m2b: coord system to encode positions: either of \"board\", \"original\", or \"padded\"\n \"\"\"\n\n # mask occupied positions\n occupied = np.abs(np.rollaxis(smp, 2, 0)[0].T[1:-1].T[1:-1])\n \n ##\n ## Super-evil hack! Will come back and solve, I promise!\n ## Background: pi seems to be shifted down-right. Can't find out, why.\n ## So I shift it back up-left here before continuing.\n ##\n pi = np.vstack([pi, np.zeros(19)])[1:,] # up\n pi = np.hstack([pi, np.zeros([19,1], dtype=np.float32)]).T[1:,].T #left\n \n distr = (1 - occupied) * pi\n\n corr = 1 if m2b == \"padded\" else 0\n \n # Drawing from pi of dimensions NxN always comes as 'original' without padding\n max_likely = sorted(np.reshape(distr, [N*N]))[::-1][:n_best]\n yn = distr == max_likely[0]\n for i in range(1,n_best):\n yn = np.add(yn, distr == max_likely[i]) \n r, c = np.where(yn)\n greedy_positions = [\n (gt.m2b((rr,cc), N), distr[rr][cc]) if m2b == 'board' else ((rr+corr, cc+corr), distr[rr][cc])\n for rr, cc in zip(r,c) \n ]\n \n return distr, greedy_positions[:n_best]\n\n\nclass SelfPlay:\n def __init__(self, policy, board_size, start_with):\n \"\"\"\n Params:\n policy: the policy model\n board_size: The side length of the board\n start_with: a padded representation of a starting traj\n \"\"\"\n self.board_size = board_size\n self.td = TerminalDetector(board_size+2)\n self.pi = policy\n self.sdh = SampleDataHelper(board_size, representation='NxNx1B')\n self.empty = self.sdh.template()\n if start_with is not None:\n self.start_traj = start_with\n self.start = self.sdh.create_sample(start_with, 1)\n else:\n self.start_traj = [(10, 10)]\n self.start = self.empty.copy()\n self.start[10][10][0] = -1\n \n \n\n def create_episodes(self, n_episodes, m2b):\n \"\"\"\n create a given number of episodes in the given coord system.\n All episodes are guaranteed to be terminated with value = -1.\n This may take some time - since it requires a large number of policy evaluations.\n n_episodes: Number of episodes to return. \n m2b: coord system to encode trajectories: either of \"board\", \"original\", or \"padded\"\n \"\"\"\n episodes = []\n while len(episodes) < n_episodes:\n game, traj, terminated = self.create_episode(\n limit=50, n_choices=10, greedy_bias=300, m2b=m2b)\n if terminated:\n episodes.append(traj)\n return episodes\n\n\n def create_episode(self, limit, n_choices, greedy_bias, m2b):\n \"\"\"\n Params:\n m2b: coord system to encode traj: either of \"board\", \"original\", or \"padded\"\n Returns: The final game state, the trajectory and a flag indicating termination.\n \"\"\"\n move_count = 0\n terminated = False\n game = self.start.copy()\n\n traj = self.start_traj\n if m2b == 'original':\n traj = [(r-1, c-1) for (r,c) in traj]\n elif m2b == 'board':\n traj = [gt.m2b((r-1, c-1), self.board_size) for (r,c) in traj]\n\n while move_count < limit and not terminated:\n game, move = self.do_one_move(game, n_choices, greedy_bias, m2b)\n traj.append(move)\n terminated = (self.td.call(game) != 0).any()\n move_count += 1\n return game, traj, terminated\n\n \n def do_one_move(self, game, n_choices, greedy_bias, m2b):\n game = game.copy()\n pi = self.pi.dist(np.reshape(game, [1,21,21,2]))\n _, choice = analyse_and_recommend(game, pi, n_choices, m2b='padded')\n weights = [greedy_bias*g[1] for g in choice]\n weights = np.exp(weights)/np.sum(np.exp(weights))\n draw = np.squeeze(np.random.choice(range(n_choices), p=weights, size=1))\n move = choice[draw][0]\n r, c = np.array(move) \n game[r][c][0] = 1\n\n if m2b == 'original':\n move = (r-1, c-1)\n elif m2b == 'board':\n move = gt.m2b((r-1, c-1), self.board_size)\n\n return 2 * self.empty - game, move \n \n \nclass A2C_SampleGeneratorFactory:\n \n def __init__(self, board_size, value_model, gamma, cut_off=None):\n \"\"\"\n gamma: discount factor\n \"\"\"\n self.board_size = board_size\n self.value_model = value_model\n self.sdh = SampleDataHelper(board_size, representation='NxNx1B', cut_off=cut_off)\n self.gamma = gamma\n \n def create_generator(self, episodes, kind): \n \"\"\"\n episodes: list of border-padded matrix coordinates (move sequences)\n kind: 'values' or 'advantages' for the two different fitting phases of A2C\n \"\"\"\n def _generator():\n dataset = []\n for episode in episodes:\n\n # We compute the value targets once for all symmetries\n if kind == 'values': \n # bellmann values not needed here, we compute targets\n samples, _ = self.sdh.traj_to_samples(episode, -1, self.gamma)\n elif kind == 'advantages':\n samples, actions = self.sdh.traj_to_samples_with_actions(episode, sparse=True)\n else: \n raise ValueError(\"Kind '%s' not supported\" % kind)\n \n values = self.gamma * np.squeeze(\n self.value_model.call(samples).numpy())\n\n # all games end with the one to move staring at a line of five.\n values[-1] = -1.0\n values[-2] = 1.0 # second-but-last: The winner's big chance\n\n # Shift by 2: next position means 'next for the same player'\n shifted = self.gamma * values[2:]\n shifted = np.append(shifted, 1.)\n shifted = np.append(shifted, -1.)\n advantages = shifted - values\n\n # Now zip it all up for each symmetric representation\n all_syms = self.sdh.all_symmetries(episode)\n for sym in all_syms:\n rep = []\n dataset.append(rep)\n samples, _ = self.sdh.traj_to_samples(sym, -1, self.gamma)\n\n if kind == 'values':\n for s_l in zip(samples, shifted):\n rep.append(s_l)\n elif kind == 'advantages': # need labels and weights!\n for s_l_w in zip(samples, actions, advantages):\n rep.append(s_l_w)\n else: \n raise ValueError(\"Kind '%s' not supported\" % kind)\n\n # Return the generator on all representation within the dataset\n for rep in dataset:\n for sva in rep:\n yield sva\n \n return _generator","sub_path":"wgomoku/wgomoku/SampleDataHelper.py","file_name":"SampleDataHelper.py","file_ext":"py","file_size_in_byte":19604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"201698321","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 18 20:06:25 2021\r\n\r\n@author: fyf\r\n\"\"\"\r\n\r\nimport boto3\r\nimport json\r\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\r\nfrom requests_aws4auth import AWS4Auth\r\n\r\ndef search(keys):\r\n service = 'es'\r\n region = 'us-west-2'\r\n # headers = {\"Content-Type\" : \"application/json\"}\r\n credentials = boto3.Session().get_credentials()\r\n awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)\r\n \r\n\r\n es = Elasticsearch(\r\n hosts = [{'host': 'search-photos-ofe6jnxvlnksqy5bihubm67r7u.us-west-2.es.amazonaws.com', 'port': 443}],\r\n http_auth = awsauth,\r\n use_ssl = True,\r\n verify_certs = True,\r\n connection_class = RequestsHttpConnection\r\n )\r\n \r\n results = []\r\n \r\n for key in keys:\r\n r = es.search(index=\"photos\", body={\"from\":0,\"size\":10,\"query\":{\"match\":{\"labels\":key}}})\r\n for r in r[\"hits\"][\"hits\"]:\r\n objKey = r['_source']['objectKey']\r\n # bucket = r[\"'_source'\"]['bucket']\r\n results.append(\"https://cs6998-hw2-imgs-clf.s3-us-west-2.amazonaws.com/\" + objKey)\r\n\r\n return results\r\n \r\n \r\ndef lambda_handler(event, context):\r\n query = event['queryStringParameters'].get(\"q\")\r\n urls = []\r\n if not query: \r\n urls = []\r\n else:\r\n qLst = query.lower().split(' ')\r\n andIdx = sum([i if qLst[i] == 'and' else 0 for i in range(len(qLst))])\r\n qLstClean = [qLst[andIdx-1], qLst[andIdx+1]] if andIdx else [qLst[-1]]\r\n qLstClean = [word[:-1] if word[-1] =='s' else word for word in qLstClean]\r\n urls = search(qLstClean)\r\n\r\n \r\n response = {\r\n 'statusCode': 200,\r\n 'headers': {\r\n 'Access-Control-Allow-Headers': 'Content-Type',\r\n 'Access-Control-Allow-Origin': '*',\r\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',\r\n },\r\n 'body': json.dumps({ \r\n \"urls\": urls\r\n }),\r\n 'isBase64Encoded': False,\r\n }\r\n \r\n return response\r\n\r\n\r\n\r\n# comment\r\n","sub_path":"hw2-get-imgs-ee3bce15-2613-452e-a059-7c4e7c5e9d08/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"518643910","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport os.path\nimport re\nimport urllib2\n\nclass Session:\n def __init__(self, session):\n self.name = session['title']\n self.description = session['description']\n self.sessionID = session['id']\n self.track = session['track']\n self.url = session['download_hd']\n self.fanart = session['images']['shelf']\n self.duration = session['duration']\n date = str(session['date'])\n if date is not None:\n self.year = date.split('-', 1)[0]\n self.title = '['+ self.year +'/'+ self.track +'] '+ self.name\n\n def getInfo(self):\n return {\n 'duration': self.duration,\n 'plot': self.description,\n 'title': self.title,\n 'year': self.year,\n }\n\nclass Sessions:\n def __init__(self, url, dataPath):\n self.url = url\n self.cacheFile = os.path.join(dataPath, 'sessions.json')\n\n def clearCache(self):\n if os.path.isfile(self.cacheFile):\n os.remove(self.cacheFile)\n\n def years(self):\n self.sessions = self._loadSessions()\n years = []\n for session in self.sessions:\n if session.year in years or session.year == 'None':\n continue\n years.append(session.year)\n return years\n\n def list(self, year):\n self.sessions = self._loadSessions()\n result = []\n for session in self.sessions:\n if session.year == year:\n result.append(session)\n return result\n\n def find(self, sessionID):\n self.sessions = self._loadSessions()\n for session in self.sessions:\n if session.sessionID == sessionID:\n return session\n\n def search(self, keyword):\n self.sessions = self._loadSessions()\n result = []\n for session in self.sessions:\n for token in session.title.split():\n if keyword.lower() in token.lower():\n result.append(session)\n return result\n\n def _loadSessions(self):\n sessions = []\n try:\n with open(self.cacheFile) as data:\n data = json.load(data)\n except:\n data = self._fetchData()\n if data is not None:\n for session in data['sessions']:\n sessions.append(Session(session))\n return sessions\n\n def _fetchData(self):\n request = urllib2.Request(self.url)\n try:\n response = urllib2.urlopen(request)\n result = response.read()\n response.close()\n self._writeCache(result)\n return json.loads(result)\n except:\n return None\n\n def _writeCache(self, data):\n cache = open(self.cacheFile, 'w')\n cache.write(data)\n cache.close\n","sub_path":"plugin.video.wwdc/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"10429625","text":"from typing import Dict\n\n# \"base_dir\": \"D:\\soundofai\\\\pitch_shifted_all\",\n\ndef get_config() -> Dict:\n conf = {\n \"base_dir\": \"D:\\soundofai\\\\all_nsynth_audio\",\n \"csv_file_path\": \"D:\\soundofai\\\\annot_data\\\\data\\\\june_06.csv\",\n \"fb_categorical_file\": \"..\\\\fb_categorical.json\",\n \"preprocess_dir\": \"tmp\",\n \"audio_duration\": 4,\n \"clip_at\": -30,\n \"epsilon\": 1e-5,\n \"clip_audio_at\": 2,\n \"sample_rate\": 16000,\n \"num_classes\": 12,\n \"n_fft\": 2048,\n \"hop_len\": 512,\n \"n_mels\": 128,\n \"scale_factor\": 1.0,\n \"learning_rate\": 2e-4,\n \"threshold\": 15,\n \"all_features\": [\n 'bright_vs_dark', 'full_vs_hollow', 'smooth_vs_rough',\n 'warm_vs_metallic', 'clear_vs_muddy', 'thin_vs_thick',\n 'pure_vs_noisy', 'rich_vs_sparse', 'soft_vs_hard'\n ],\n \"features\": [\"bright_vs_dark\"],\n \"model_name\": \"fb_qualities\",\n \"valid_split\": 0.4,\n \"dry_run\": False,\n \"reset_data\": False,\n \"pitch_shifted\": True\n }\n\n conf = dict(conf)\n audio_duration_samples = (conf.get(\"audio_duration\") - conf.get(\"clip_audio_at\")) * conf.get(\"sample_rate\")\n conf[\"time_steps\"] = 1 + audio_duration_samples // conf.get(\"hop_len\")\n conf[\"num_conv_blocks\"] = 3\n return conf\n","sub_path":"members/amit/clf/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"302138687","text":"from contextlib import contextmanager\nfrom distutils.version import LooseVersion\nimport pdb\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\nimport torch\nfrom typeguard import check_argument_types\nimport logging\n\nfrom espnet.nets.e2e_asr_common import ErrorCalculator\nfrom espnet.nets.pytorch_backend.nets_utils import th_accuracy\nfrom espnet.nets.pytorch_backend.transformer.add_sos_eos import add_sos_eos\nfrom espnet.nets.pytorch_backend.transformer.label_smoothing_loss import (\n LabelSmoothingLoss, # noqa: H301\n)\nfrom espnet2.asr.ctc import CTC\nfrom espnet2.asr.encoder.abs_encoder import AbsEncoder\nfrom espnet2.asr.encoder.condition_encoder import ConditionalModule\nfrom espnet2.asr.frontend.abs_frontend import AbsFrontend\nfrom espnet2.asr.preencoder.abs_preencoder import AbsPreEncoder\nfrom espnet2.asr.specaug.abs_specaug import AbsSpecAug\nfrom espnet2.layers.abs_normalize import AbsNormalize\nfrom espnet2.torch_utils.device_funcs import force_gatherable\nfrom espnet2.train.abs_espnet_model import AbsESPnetModel\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"1.6.0\"):\n from torch.cuda.amp import autocast\nelse:\n # Nothing to do if torch<1.6.0\n @contextmanager\n def autocast(enabled=True):\n yield\nfrom torch.nn.utils.rnn import pad_sequence\nimport torch.nn.functional as F\nclass ESPnetASRModel(AbsESPnetModel):\n \"\"\"CTC-attention hybrid Encoder-Decoder model\"\"\"\n\n def __init__(\n self,\n vocab_size: int,\n token_list: Union[Tuple[str, ...], List[str]],\n frontend: Optional[AbsFrontend],\n specaug: Optional[AbsSpecAug],\n normalize: Optional[AbsNormalize],\n preencoder: Optional[AbsPreEncoder],\n encoder: AbsEncoder,\n encoder_con: ConditionalModule,\n encoder_rec: AbsEncoder,\n ctc: CTC,\n use_inter_ctc: bool = False,\n use_stop_sign_bce: bool = False,\n inter_ctc_weight: float = 0.3,\n ctc_weight: float = 0.5,\n ignore_id: int = -1,\n lsm_weight: float = 0.0,\n length_normalized_loss: bool = False,\n report_cer: bool = True,\n report_wer: bool = True,\n sym_space: str = \"\",\n sym_blank: str = \"\",\n ):\n assert check_argument_types()\n assert 0.0 <= ctc_weight <= 1.0, ctc_weight\n\n super().__init__()\n # note that eos is the same as sos (equivalent ID)\n \n self.sos = vocab_size - 1\n self.eos = vocab_size - 1\n self.vocab_size = vocab_size\n self.ignore_id = ignore_id\n self.ctc_weight = ctc_weight\n self.token_list = token_list.copy()\n\n self.frontend = frontend\n self.specaug = specaug\n self.normalize = normalize\n self.preencoder = preencoder\n self.encoder = encoder\n self.encoder_con = encoder_con\n self.encoder_rec = encoder_rec\n self.ctc = ctc\n self.criterion_att = LabelSmoothingLoss(\n size=vocab_size,\n padding_idx=ignore_id,\n smoothing=lsm_weight,\n normalize_length=length_normalized_loss,\n )\n self.use_inter_ctc = use_inter_ctc\n self.adim = encoder.output_size()\n if self.use_inter_ctc:\n self.inter_ctc_weight = inter_ctc_weight\n self.project_linear = torch.nn.Linear(self.encoder_con.output_size(), self.adim)\n self.use_stop_sign_bce = use_stop_sign_bce\n\n if self.use_stop_sign_bce:\n self.stop_sign_loss = StopBCELoss(self.adim, 1, nunits=self.adim)\n if report_cer or report_wer:\n self.error_calculator = ErrorCalculator(\n token_list, sym_space, sym_blank, report_cer, report_wer\n )\n else:\n self.error_calculator = None\n def min_ctc_loss_and_perm(self, hs_pad, hs_len, ys_pad, text_lengths_new):\n \"\"\"E2E min ctc loss and permutation.\n\n :param torch.Tensor xs_pad: batch of padded source sequences (B, Tmax, idim)\n :param torch.Tensor hs_len: batch of lengths of source sequences (B)\n :param torch.Tensor ys_pad: batch of padded target sequences (B, num_spkrs', Lmax)\n :rtype: torch.Tensor\n :return: ctc loss value\n :rtype: torch.Tensor\n :return: minimum index\n \"\"\"\n \n _, n_left_spkrs, _ = ys_pad.size()\n loss_stack = torch.stack(\n [self.ctc(hs_pad, hs_len, ys_pad[:, i], text_lengths_new[:, i]) for i in range(n_left_spkrs)]\n ) # (N, B, 1)\n min_loss, min_idx = torch.min(loss_stack, 0)\n return min_loss, min_idx\n def resort_sequence(self, xs_pad, min_idx, start):\n \"\"\"E2E re-sort sequence according to min_idx.\n\n :param torch.Tensor xs_pad: batch of padded source sequences (B, num_spkrs, Lmax)\n :param torch.Tensor min_idx: batch of min idx (B)\n :param int start: current head of sequence.\n :rtype: torch.Tensor\n :return: re-sorted sequence\n \"\"\"\n n_batch = xs_pad.size(0)\n for i in range(n_batch):\n tmp = xs_pad[i, start].clone()\n xs_pad[i, start] = xs_pad[i, min_idx[i]]\n xs_pad[i, min_idx[i]] = tmp\n return xs_pad\n\n def forward(\n self,\n speech: torch.Tensor,\n speech_lengths: torch.Tensor,\n text: torch.Tensor,\n text_lengths: torch.Tensor,\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], torch.Tensor]:\n \"\"\"Frontend + Encoder + Decoder + Calc loss\n\n Args:\n speech: (Batch, Length, ...)\n speech_lengths: (Batch, )\n text: (Batch, Length)\n text_lengths: (Batch,)\n \"\"\"\n assert text_lengths.dim() == 1, text_lengths.shape\n # Check that batch_size is unified\n assert (\n speech.shape[0]\n == speech_lengths.shape[0]\n == text.shape[0]\n == text_lengths.shape[0]\n ), (speech.shape, speech_lengths.shape, text.shape, text_lengths.shape)\n batch_size = speech.shape[0]\n text_all = []\n text_lengths_new = []\n text_lengths_max = int(text_lengths.max())\n for i in range(batch_size):\n text_utt_list=[]\n text_start = 0\n text_end = text_lengths_max\n for j in range(text_lengths_max):\n if text[i][j] == 2:\n text_utt_list.append(text[i][text_start:j])\n text_lengths_new.append(j-text_start)\n text_start = j+1\n elif text[i][j] == -1:\n text_end = j\n break\n if(text_start != text_lengths_max):\n text_utt_list.append(text[i][text_start:text_end])\n text_lengths_new.append(text_end-text_start)\n text_all.append(text_utt_list)\n text_lengths_new = torch.Tensor(text_lengths_new).int()\n text_lengths_max = int(text_lengths_new.max())\n text_lengths_new = text_lengths_new.view(batch_size,-1).to(speech.device)\n num_spkrs = text_lengths_new.size(1)\n text_all_final=[]\n\n for i in range(batch_size):\n text_sequence = pad_sequence(text_all[i],batch_first=True, padding_value=-1)\n pad_num = text_lengths_max - text_sequence.size(-1)\n if pad_num > 0:\n text_sequence = F.pad(text_sequence, (0,pad_num), \"constant\", -1)\n text_all_final.append(text_sequence)\n text_final_label = torch.stack(text_all_final,dim=0).to(speech.device)\n # for data-parallel\n #text = text[:, : text_lengths.max()]\n # 1. Encoder\n encoder_out, encoder_out_lens = self.encode(speech, speech_lengths)\n # encoder_out batchsize * time * dim256\n # encoder_out_lens batchsize\n \n cer_ctc = None\n\n prev_states = None\n hs_pad_sd, loss_ctc, loss_inter_ctc, loss_stop = (\n [None] * num_spkrs,\n [None] * num_spkrs,\n [None] * num_spkrs,\n [None] * num_spkrs,\n )\n\n loss_att, acc_att, cer_att, wer_att = None, None, None, None\n # encoder_out bc * T * D(256)\n align_ctc_state = encoder_out.new_zeros(encoder_out.size())\n \n for i in range(num_spkrs):\n condition_out, prev_states = self.encoder_con(\n encoder_out, align_ctc_state, encoder_out_lens, prev_states\n )\n # condition_out 8*211*1024\n hs_pad_sd[i], encoder_out_lens,_= self.encoder_rec.forward_hidden(condition_out, encoder_out_lens)\n # hs_pad_sd[i] bc * T * D(256)\n loss_ctc[i], min_idx = self.min_ctc_loss_and_perm(\n hs_pad_sd[i], encoder_out_lens, text_final_label[:, i:], text_lengths_new[:, i:]\n )\n min_idx = min_idx + i\n if i < num_spkrs - 1:\n text_final_label = self.resort_sequence(text_final_label, min_idx, i)\n if self.use_inter_ctc:\n hidden_feature = self.encoder_rec.hidden_feature\n loss_inter_ctc[i] = self.ctc(hidden_feature, encoder_out_lens, text_final_label[:, i], text_lengths_new[:, i])\n logging.info(\"using latent representation as soft conditions.\")\n align_ctc_state = hs_pad_sd[i].detach().data\n if self.use_stop_sign_bce:\n stop_label = hs_pad_sd[i].new_zeros((batch_size, 1))\n if i == num_spkrs - 1:\n stop_label += 1\n loss_stop[i] = self.stop_sign_loss(hs_pad_sd[i], encoder_out_lens, stop_label)\n loss_ctc = torch.stack(loss_ctc, dim=0).mean() # (num_spkrs, B)\n loss_stop = torch.stack(loss_stop, dim=0).mean()\n logging.info(\"ctc loss:\" + str(float(loss_ctc)))\n if self.use_inter_ctc:\n loss_inter_ctc = torch.stack(loss_inter_ctc, dim=0).mean() # (num_spkrs, B)\n logging.info(\"inter ctc loss:\" + str(float(loss_inter_ctc)))\n loss = self.inter_ctc_weight * loss_inter_ctc + (1 - self.inter_ctc_weight) * loss_ctc\n loss_att = loss_inter_ctc\n else:\n loss = loss_ctc\n loss_att = None\n if self.use_stop_sign_bce:\n loss += loss_stop * 100\n acc_att = loss_stop\n stats = dict(\n loss=loss.detach(),\n loss_att=loss_att.detach() if loss_att is not None else None,\n loss_ctc=loss_ctc.detach() if loss_ctc is not None else None,\n acc=acc_att.detach() if acc_att is not None else None,\n cer=cer_att,\n wer=wer_att,\n cer_ctc=cer_ctc,\n )\n # force_gatherable: to-device and to-tensor if scalar for DataParallel\n loss, stats, weight = force_gatherable((loss, stats, batch_size), loss.device)\n return loss, stats, weight\n\n def collect_feats(\n self,\n speech: torch.Tensor,\n speech_lengths: torch.Tensor,\n text: torch.Tensor,\n text_lengths: torch.Tensor,\n ) -> Dict[str, torch.Tensor]:\n feats, feats_lengths = self._extract_feats(speech, speech_lengths)\n return {\"feats\": feats, \"feats_lengths\": feats_lengths}\n\n def encode(\n self, speech: torch.Tensor, speech_lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Frontend + Encoder. Note that this method is used by asr_inference.py\n\n Args:\n speech: (Batch, Length, ...)\n speech_lengths: (Batch, )\n \"\"\"\n with autocast(False):\n # 1. Extract feats\n feats, feats_lengths = self._extract_feats(speech, speech_lengths)\n\n # 2. Data augmentation\n if self.specaug is not None and self.training:\n feats, feats_lengths = self.specaug(feats, feats_lengths)\n\n # 3. Normalization for feature: e.g. Global-CMVN, Utterance-CMVN\n if self.normalize is not None:\n feats, feats_lengths = self.normalize(feats, feats_lengths)\n\n # Pre-encoder, e.g. used for raw input data\n if self.preencoder is not None:\n feats, feats_lengths = self.preencoder(feats, feats_lengths)\n\n # 4. Forward encoder\n # feats: (Batch, Length, Dim)\n # -> encoder_out: (Batch, Length2, Dim2)\n encoder_out, encoder_out_lens, _ = self.encoder(feats, feats_lengths)\n\n assert encoder_out.size(0) == speech.size(0), (\n encoder_out.size(),\n speech.size(0),\n )\n assert encoder_out.size(1) <= encoder_out_lens.max(), (\n encoder_out.size(),\n encoder_out_lens.max(),\n )\n\n return encoder_out, encoder_out_lens\n\n def _extract_feats(\n self, speech: torch.Tensor, speech_lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n assert speech_lengths.dim() == 1, speech_lengths.shape\n\n # for data-parallel\n speech = speech[:, : speech_lengths.max()]\n\n if self.frontend is not None:\n # Frontend\n # e.g. STFT and Feature extract\n # data_loader may send time-domain signal in this case\n # speech (Batch, NSamples) -> feats: (Batch, NFrames, Dim)\n feats, feats_lengths = self.frontend(speech, speech_lengths)\n else:\n # No frontend and no feature extract\n feats, feats_lengths = speech, speech_lengths\n return feats, feats_lengths\n\n def _calc_att_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n \n loss_att, acc_att, cer_att, wer_att = None, None, None, None\n return loss_att, acc_att, cer_att, wer_att\n\n def _calc_ctc_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n # Calc CTC loss\n loss_ctc = self.ctc(encoder_out, encoder_out_lens, ys_pad, ys_pad_lens)\n\n # Calc CER using CTC\n cer_ctc = None\n if not self.training and self.error_calculator is not None:\n ys_hat = self.ctc.argmax(encoder_out).data\n cer_ctc = self.error_calculator(ys_hat.cpu(), ys_pad.cpu(), is_ctc=True)\n return loss_ctc, cer_ctc\n\n def _calc_rnnt_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n raise NotImplementedError\n\n\nclass StopBCELoss(torch.nn.Module):\n def __init__(\n self, idim, odim=1, nlayers=1, nunits=512, dropout=0, bidirectional=False\n ):\n super(StopBCELoss, self).__init__()\n self.idim = idim\n self.lstmlayers = torch.nn.LSTM(\n idim, nunits, nlayers, batch_first=True, bidirectional=bidirectional\n )\n self.output = torch.nn.Linear(idim, odim)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.loss = torch.nn.BCELoss()\n\n def forward(self, xs_pad, xs_len, ys):\n \"\"\"\n :param torch.Tensor xs_pad: input sequence (B, Tmax, dim)\n :param list xs_len: the lengths of xs (B)\n :param torch.Tensor ys: the labels (B, 1)\n \"\"\"\n xs_pack = torch.nn.utils.rnn.pack_padded_sequence(\n xs_pad, xs_len.cpu(), batch_first=True\n )\n _, (h_n, _) = self.lstmlayers(xs_pack) # (B, dim)\n linear_out = self.dropout(self.output(h_n[-1])) # (B, 1)\n linear_out = torch.sigmoid(linear_out)\n return self.loss(linear_out, ys)\n def get_stop_sign(self, xs_pad, xs_len):\n \"\"\"\n :param torch.Tensor xs_pad: input sequence (B, Tmax, dim)\n :param list xs_len: the lengths of xs (B)\n :param torch.Tensor ys: the labels (B, 1)\n \"\"\"\n xs_pack = torch.nn.utils.rnn.pack_padded_sequence(\n xs_pad, xs_len.cpu(), batch_first=True\n )\n _, (h_n, _) = self.lstmlayers(xs_pack) # (B, dim)\n linear_out = self.dropout(self.output(h_n[-1])) # (B, 1)\n linear_out = torch.sigmoid(linear_out)\n return linear_out\n","sub_path":"espnet_model_con.py","file_name":"espnet_model_con.py","file_ext":"py","file_size_in_byte":16193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68841049","text":"import os\nimport torch\nimport torch.nn as nn\ntorch.manual_seed(1)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nfrom models.CharConv import CharConv\nfrom models.CLR import CyclicLR\nfrom models.Stopper import EarlyStopping\nfrom sklearn.metrics import accuracy_score, f1_score, classification_report\nfrom torch.autograd import Variable\nfrom utilities import *\n\n\nHIDDEN_SIZE = 256\nBATCH_SIZE = 16\nMAX_SEQUENCE = 1024\nLINEAR_SIZE = 256\nLEARNING_RATE = 0.005\nREG_PARAM = 1e-1\nMOMENTUM = 0.8\nEPOCHS = 500\nPATH = 'data/processed/training/*.txt'\nUSE_CUDA = torch.cuda.is_available()\n\n\ndef train_batch(_model, _x_tensor, _y_tensor, _target):\n _model.zero_grad()\n # input should be batch, alphabet, hidden_size\n out = _model(_x_tensor)\n _loss = _target(out.cuda(), _y_tensor.long())\n _loss.backward()\n for p in _model.parameters():\n if p.grad is not None:\n p.data.add_(-LEARNING_RATE, p.grad.data)\n torch.cuda.empty_cache()\n return out, _loss.item()\n\n\ndef evaluate(_model, _x_val, _y_val):\n out = _model(_x_val)\n out_proba, out_class = torch.max(out, 1)\n acc = accuracy_score(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy())\n f1 = f1_score(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy(), average='weighted')\n cr = classification_report(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy())\n return acc, f1, cr\n\n\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n device = torch.device(\"cuda:0\" if USE_CUDA else \"cpu\")\n try:\n df = torch.load('outputs/padded_chars.pkl')\n except:\n df = PaddedCharSeqData(PATH, MAX_SEQUENCE)\n torch.save(df, 'outputs/padded_chars.pkl')\n train, valid, test = train_valid_test_split(df, split_fold=BATCH_SIZE*20)\n print('Training set has {m} entries'.format(m=len(train)))\n print('Validation set has {n} entries'.format(n=len(valid)))\n print('Test set has {t} entries'.format(t=len(test)))\n train_batched = DataLoader(train, batch_size=BATCH_SIZE, shuffle=True, drop_last=True)\n valid_set = DataLoader(valid, batch_size=len(valid), shuffle=False)\n test_set = DataLoader(test, batch_size=len(test), shuffle=False)\n model = CharConv(len(df.alphabet), df.count_classes(), HIDDEN_SIZE, BATCH_SIZE, MAX_SEQUENCE, LINEAR_SIZE).cuda()\n criterion = nn.NLLLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=REG_PARAM) #, momentum=MOMENTUM)\n #scheduler = CyclicLR(optimizer)\n stopper = EarlyStopping(patience=101, verbose=True, saver=False)\n for epoch in range(EPOCHS):\n el = 0\n model.train()\n for batch in train_batched:\n #scheduler.batch_step()\n x = Variable(batch[0].cuda(), requires_grad=True)\n y = Variable(batch[1].cuda())\n preds, loss = train_batch(model, x, y, criterion)\n el += loss\n\n model.eval()\n for val_batch in valid_set:\n x_val = Variable(val_batch[0].cuda())\n y_val = Variable(val_batch[1].cuda())\n val_out = model(x_val)\n val_loss = criterion(val_out.cuda(), y_val.long())\n stopper(val_loss, model)\n\n if stopper.early_stop:\n print(\"Stopping training at epoch {cur}\".format(cur=epoch))\n for test_batch in test_set:\n x_test = Variable(test_batch[0].cuda())\n y_test = Variable(test_batch[1])\n acc, f1, cr = evaluate(model, x_test, y_test)\n print('Test set accuracy of {a} and F1 of {f}'.format(a=acc, f=f1))\n print(cr)\n break\n\n if epoch % 5 == 0:\n for test_batch in test_set:\n x_test = Variable(test_batch[0].cuda())\n y_test = Variable(test_batch[1])\n acc, f1, cr = evaluate(model, x_test, y_test)\n print('Test set accuracy of {a} and F1 of {f}'.format(a=acc, f=f1))\n print(cr)\n print('Epoch {e} had loss {ls}'.format(e=epoch, ls=el))\n #lr_list = scheduler.get_lr()\n torch.save(model.state_dict(), 'outputs/conv_model.pt')\n #print('Final learning rate was {x}'.format(x=lr_list[-1]))\n","sub_path":"src/train_conv.py","file_name":"train_conv.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"644216858","text":"# 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。\r\n#\r\n# 在杨辉三角中,每个数是它左上方和右上方的数的和。\r\n'''\r\n示例:\r\n\r\n输入: 5\r\n输出:\r\n[\r\n [1],\r\n [1,1],\r\n [1,2,1],\r\n [1,3,3,1],\r\n [1,4,6,4,1]\r\n]\r\n'''\r\nclass Solution:\r\n def generate(self, numRows):\r\n \"\"\"\r\n :type numRows: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n if numRows == 0:\r\n return []\r\n elif numRows == 1:\r\n return [[1]]\r\n elif numRows == 2:\r\n return [[1], [1, 1]]\r\n elif numRows > 2:\r\n result = []\r\n for i in range(1, numRows + 1):\r\n temp = [result[-1][j - 1] + result[-1][j] for j in range(1, i - 1)]\r\n if i != 1:\r\n temp.insert(0, 1)\r\n temp.append(1)\r\n result.append(temp)\r\n return result\r\n\r\nif __name__ == '__main__':\r\n sol = Solution()\r\n numRows = 15\r\n data = sol.generate(numRows)\r\n print(data)\r\n","sub_path":"pascals_triangle.py","file_name":"pascals_triangle.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"96450258","text":"import sys\nsys.path.insert(0, 'paper/')\nfrom learning_utils import viewed_matrix\nfrom learning_utils import filter_unseen_movies\nfrom aspect_importance import dict_movie_aspect\nfrom aspect_importance import users_movie_aspect_preferences\nfrom simple_similarity import sample_users\nfrom concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import cpu_count\nfrom scipy import spatial\nfrom paper import ids\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport pprint as pp\nimport time\n\nTHREADS = cpu_count() - 1\n\n\ndef map_similarity(x):\n\ta, b = x\n\tuser_id1, user_genre_prefs1 = a\n\tuser_id2, user_genre_prefs2 = b\n\tsim = (1 - spatial.distance.cosine(list(user_genre_prefs1.values()), list(user_genre_prefs2.values())))\n\treturn user_id1, user_id2, sim\n\n\ndef user_genre_similarity(users_genres_prefs):\n\tuser_genre_similarity_dict = dict()\n\tfor user in list(users_genres_prefs.keys()):\n\t\tuser_genre_similarity_dict[user] = dict()\n\n\tpairwise_user_profiles = []\n\n\titems = list(users_genres_prefs.items())\n\tfor idx1 in range(len(items)):\n\t\tfor idx2 in range(idx1+1, len(items)):\n\t\t\tpairwise_user_profiles.append((items[idx1], items[idx2]))\n\n\twith ProcessPoolExecutor(max_workers=THREADS) as executor:\n\t\tresults = executor.map(map_similarity, pairwise_user_profiles)\n\tfor user_id1, user_id2, sim in results:\n\t\tuser_genre_similarity_dict[user_id1][user_id2] = sim\n\t\tuser_genre_similarity_dict[user_id2][user_id1] = sim\n\n\treturn user_genre_similarity_dict\n\n\ndef user_prefs(movies_watched, movies_aspects, users, aspect_type, normalized, rating_to_like=False):\n\tmovies_aspects = filter_unseen_movies(movies_aspects, movies_watched)\n\tmovies_aspects = pd.DataFrame.from_dict(movies_aspects, dtype='int64', orient='index')\n\tmovies_aspects = movies_aspects.replace(np.nan, 0)\n\n\t# print (\"\\nMOVIES-ASPECTS %s %r\" % (aspect_type, rating_to_like))\n\t# print (movies_aspects.to_string())\n\n\tusers_aspects_prefs = users_movie_aspect_preferences(movies_aspects, movies_watched, users, normalized)\n\n\t# print (\"\\nUSER %s PREF RATING_TO_LIKE %r\" % (aspect_type, rating_to_like))\n\t# print (pd.DataFrame.from_dict(users_aspects_prefs, orient='index').to_string())\n\n\t# file_name = \"preference_%s_%r.pkl\" % (aspect_type, rating_to_like)\n\t# afile = open(file_name, \"wb\")\n\t# pickle.dump(users_aspects_prefs, afile)\n\t# afile.close()\n\n\treturn users_aspects_prefs\n\n\ndef user_sim(users_genres_prefs, rating_to_like=False):\n\tuser_genre_similarity_dict = user_genre_similarity(users_genres_prefs)\n\n\t# print (\"\\nSIMILARITY USER GENRE PREF RATING_TO_LIKE %r\" % rating_to_like)\n\t# print (pd.DataFrame.from_dict(user_genre_similarity_dict).to_string())\n\n\t# file_name = \"similarity_%r.pkl\" % rating_to_like\n\t# afile = open(file_name, \"wb\")\n\t# pickle.dump(user_genre_similarity_dict, afile)\n\t# afile.close()\n\n\nif __name__ == \"__main__\":\n\tstart = time.time()\n\tpaper_ratings = pickle.load(open(\"db/paper_ratings.pkl\", \"rb\"))\n\tpaper_films = pickle.load(open(\"db/paper_films.pkl\",\"rb\"))\n\tmovies_watched = viewed_matrix(paper_ratings, paper_films, sample_users)\n\n\t# print (\"\\nFILMS \\n%s\\n\" % paper_films)\n\t# print (\"\\nFILMS WATCHED BY USERS RATING_TO_LIKE %r \\n%s\\n\" % (False, movies_watched))\n\n\tnormalized = True\n\n\tmovies_actors = dict_movie_aspect(paper_films, \"actors\")\n\tusers_actors_prefs = user_prefs(movies_watched, movies_actors, sample_users, \"actors\", normalized)\n\n\tmovies_directors = dict_movie_aspect(paper_films, \"director\")\n\tusers_diretors_prefs = user_prefs(movies_watched, movies_directors, sample_users, \"director\", normalized)\n\n\tmovies_genres = dict_movie_aspect(paper_films, \"genre\")\n\tusers_genres_prefs = user_prefs(movies_watched, movies_genres, sample_users, \"genre\", normalized)\n\n\n\n\tuser_sim(users_genres_prefs)\n\n\tend = time.time()\n\tprint (end - start)\n\n","sub_path":"learning/synthetic_learning.py","file_name":"synthetic_learning.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"561904231","text":"import praw\nimport urllib2\nimport re\n\nfrom bs4 import BeautifulSoup\n\ndef check_website(url):\n\tresponse = urllib2.urlopen(\"http://dota2lounge.com/\").getcode()\n\tif response == 200:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef check_availability(match):\n\tif \"notaviable\" in match.get(\"class\"):\n\t\treturn False\n\telse:\n\t\treturn True\n\nuser_agent = \"/r/Dota2LoungeBets Match Poster\"\nbot = praw.Reddit(user_agent=user_agent)\n\nwebsiteStatus = check_website(\"http://dota2lounge.com/\")\nif websiteStatus == True:\n\tpage = urllib2.urlopen(\"http://dota2lounge.com/\")\n\tsoup = BeautifulSoup(page)\n\n\tbets = soup.find(\"article\", {\"id\": \"bets\"})\n\tmatchlist = bets.find_all(\"div\", {\"class\": \"match\"})\n\tfor match in matchlist:\n\t\tmatchlink = match.find_all(\"a\", href=True)\n\t\tfor link in matchlink:\n\t\t\tmatchstring = link.get(\"href\")\n\t\tmatchid = map(int, re.findall(\"\\d+\", matchstring))\n\t\tprint(matchid[0])\n\n\t\tteams = match.find_all(\"div\", {\"class\": \"teamtext\"})\n\t\tteam1Name = teams[0].b.encode_contents()\n\t\tteam1Percent = teams[0].i.encode_contents()\n\t\tteam2Name = teams[1].b.encode_contents()\n\t\tteam2Percent = teams[1].i.encode_contents()\n\t\tavailable = check_availability(match)\n\n\t\t#Test to see if the names actually work\n\t\tif available == False:\n\t\t\tavailability = \"CLOSED\"\n\t\telse:\n\t\t\tavailability = \"OPEN\"\n\t\tprint(team1Name + \" (\" + team1Percent + \") vs \" + team2Name + \" (\" + team2Percent + \") - \" + availability)\nelse:\n\tprint(\"Website is busy or an error has occured.\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"272189301","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom API.models import *\n\n# Create your tests here.\nclass NewMachineTests(APITestCase):\n def setUp(self):\n self.m1 = Machine.objects.create(description=\"\")\n self.m1.save()\n\n def test_new_machine(self):\n url = reverse('newhost')\n response = self.client.get(url)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['id'], 2)\n # self.assertEqual(Machine.objects.get(pk=response.data['id']).description, \"\")\n\n def test_new_machine_desc(self):\n desc = \"This is an infected machine\"\n url = '{0}?desc={1}'.format(reverse('newhost'), desc)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['id'], 2)\n # self.assertEqual(Machine.objects.get(pk=response.data['id']).description, desc)\n","sub_path":"django/SePr/SePr/API/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573478140","text":"import random\n\nfrom enum import Enum\n\n\n# Texts\ntitle = 'Игра: Компьютер угадает загаданное число'\ncontrol_hint = '[1 - меньше | 2 - верно | 3 - больше] : '\nreplies_wrong = ('Да ну!', 'Аргх..', 'Вотжешь', 'Даже так?')\nreply_correct = 'Круть!'\nright_border_message = 'Задайте диапазон: от 1 до '\n\n\n# Utility\nclass Control(Enum):\n LESS = '1'\n EQUAL = '2'\n MORE = '3'\n\n\ndef print_wrong_reply():\n number = random.randint(0, len(replies_wrong) - 1)\n print(replies_wrong[number])\n\n\ncontrols = {control.value: control for control in Control}\nis_ready = True\n\n# Game\nprint(title)\nprint()\n\nwhile is_ready:\n left_border, right_border = 1, int(input(right_border_message))\n\n attempt = 0\n\n while not left_border > right_border:\n attempt += 1\n predicted_number = random.randint(left_border, right_border)\n\n print(f'Попытка {attempt}. Было загадано {predicted_number}?')\n\n try:\n user_answer = controls[input(control_hint)]\n except IndexError:\n user_answer = None\n\n if user_answer is Control.EQUAL:\n print(reply_correct)\n break\n\n elif user_answer is Control.LESS:\n right_border = predicted_number - 1\n print_wrong_reply()\n\n elif user_answer is Control.MORE:\n left_border = predicted_number + 1\n print_wrong_reply()\n\n print()\n\n else:\n print(f'Вы верно врёте! Число больше {left_border} и {right_border}?!')\n print('Поражение!')\n\n print()\n is_ready = bool(int(input('Есчо? [1 - ага, 0 - не-а] : ')))\n print()\n\nprint('Пока-пока!')\n\n","sub_path":"lesson_6/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"305181519","text":"# !/usr/bin/env python\n# -*-coding: utf-8-*-\n\n# @ProjectName : jiling_aqjr_proj\n# @FileName : basicdata_set.py\n# @Time : 2019/11/7 10:12\n# @Author : Nick\n\n\"\"\"\n目的:使用单例模式管理配置文件的读取,确保配置文件信息调用时,因为只初始化一次,还可以加快运行性能,保证程序在多处地方获取的配置信息一致\n\"\"\"\n\nimport random\nimport time\nimport collections\nimport configparser\nimport os.path\nfrom src.aqjr import log_setting_gdca\n\n\"\"\"\npython中实现单例模式最简单的两种方法:\n一、通过模块调用\n在python3中,首次导入模块文件时,会在程序目录下的__pycache__目录中生成pyc文件,\n再导入时,将直接加载pyc文件。因此,只需把相关的函数和数据定义在一个模块��,就可以获得一个单例对象了。 \n\n# 读取配置文件中关于java和jar的配置项\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\n# 本机java虚拟机路径及运行参数\njvm_path = config.get('Java', \"Java_path\")\njar_path = config.get('Java', \"jar_path\")\n\n# 接口URL前缀\nsell_profix_url = config.get('Url_set', 'sell_profix')\ntime_sync_profix_url = config.get('Url_set', 'time_sync_profix')\nencash_profix_url = config.get('Url_set', 'encash_profix')\nbet_query_url = config.get('Url_set', 'bet_query_profix')\naccount_query_url = config.get('Url_set', 'account_query_profix')\nlogin_profix_url = config.get('Url_set', 'login_profix')\n\n\n# 登录、投注、兑奖3个接口使用\ngdca_key = config.get('Key', 'gdca_key')\n# 3个查询接口使用(时间同步、自购投注查询、站点余额)\nold_key = config.get('Key', 'old_key')\n\n\n# 投注商ID,用命名元组管理多个渠道商\nchannel = collections.namedtuple(\"Channel\", 'First,Second,Three')\nchannel_id = channel._make([config.get('Channel', 'first'), config.get('Channel', 'second'), config.get('Channel', 'third')])\n\n# 自助终端的编号\nuserid = config.get('Basic_infor', 'userid')\n# 渠道ID\npartner_id = config.get('Basic_infor', 'partner_id')\n# 版本\nversion = config.get('Basic_infor', 'version')\n\ndef serial_num_gen():\n # 生成15位随机列号\n return str(random.randrange(1, 9999)) + str(random.randrange(1, 9999)) + str(random.randrange(1, 9999))\n\ndef current_time():\n # 生成当前时间时间戳\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n二、使用__new__方法\n\n __new__:创建实例对象时调用的构造方法\n __init__ :实例初始化方法,用于设置实例的相关属性\n\n当实例化一个对象时,先调用__new__方法(未定义时调用object.__new__)实例化对象,然后调用__init__方法进行对象初始化。\n所以,可以声明一个私有类变量__instance。当__instance不为None时,表示系统中已有实例,直接返回该实例;若__instance为None时,\n表示系统中还没有该类的实例,则创建新实例并返回。\n\n\"\"\"\n\n\nclass Dataset(object):\n __instance = None\n\n def __init__(self):\n # 读取配置文件中关于java和jar的配置项\n config = configparser.ConfigParser()\n config.read('config.ini')\n\n # 初始化日志调用\n self.log_level = config.get('Default', \"loglevel\")\n self.log_dir = config.get('Default', \"logfile\")\n self.logger = log_setting_gdca.log_setting()\n\n # 初始化销售过程中产生的文件存放的目录\n result_dir = config.get('Default', \"resultdir\")\n if not os.path.exists(result_dir):\n os.mkdir(r'%s' % result_dir)\n self.result_dir = result_dir + '\\\\'\n\n # 初始化销售过程中产生的文件存放的目录\n datadir = config.get('Default', \"datadir\")\n if not os.path.exists(datadir):\n os.mkdir(r'%s' % datadir)\n self.datadir = datadir + '\\\\'\n\n # 接口URL前缀\n self.sell_profix_url = config.get('Url_set', 'sell_profix')\n self.time_sync_profix_url = config.get('Url_set', 'time_sync_profix')\n self.encash_profix_url = config.get('Url_set', 'encash_profix')\n self.bet_query_url = config.get('Url_set', 'bet_query_profix')\n self.account_query_url = config.get('Url_set', 'account_query_profix')\n self.login_profix_url = config.get('Url_set', 'login_profix')\n\n # 登录、投注、兑奖3个接口使用\n self.gdca_key = config.get('Key', 'gdca_key')\n # 3个查询接口使用(时间同步、自购投注查询、站点余额)\n self.old_key = config.get('Key', 'old_key')\n\n # 投注商ID,用命名元组管理多个渠道商\n channel = collections.namedtuple(\"Channel\", 'First,Second,Three')\n self.channel_id = channel._make(\n [config.get('Channel', 'first'), config.get('Channel', 'second'), config.get('Channel', 'third')])\n\n # 自助终端的编号\n self.userid = config.get('Basic_infor', 'userid')\n # 渠道ID\n self.partner_id = config.get('Basic_infor', 'partner_id')\n # 版本\n self.version = config.get('Basic_infor', 'version')\n # 登录密码\n self.login_pass = config.get('Basic_infor', 'loginpass')\n # 登录类型\n self.login_type = config.get('Basic_infor', 'logintype')\n # MAC地址\n self.mac_address = config.get('Basic_infor', 'macaddress')\n\n @staticmethod\n def serial_num_gen():\n # 生成15位随机列号\n return str(random.randrange(1, 9999)) + str(random.randrange(1, 9999)) + str(random.randrange(1, 9999))\n\n @staticmethod\n def current_time():\n # 生成当前时间时间戳\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n def __new__(cls):\n if not cls.__instance:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n\nbasic_data = Dataset()\n\n# 单例模式验证\n# basic_data1 = Dataset()\n# print(id(basic_data), id(basic_data1))\n","sub_path":"sdgen/basicdata_set.py","file_name":"basicdata_set.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"162274503","text":"from django.urls import path\nfrom . import views\n\n# Me sirve para llamar a las URLS en el HTML\napp_name = \"crear_pacientes\"\n\nurlpatterns = [\n path('', views.crear_pacientes, name='crear_pacientes'),\n path('listar_pacientes', views.listar_pacientes, name='listar_pacientes'),\n path('perfil_paciente', views.perfil_paciente, name='perfil_paciente'),\n path('/eliminar_paciente', views.eliminar_paciente, name='eliminar_paciente'),\n path('/actualizar_paciente', views.editar_paciente , name='actualizar_paciente'),\n]","sub_path":"Modulo6/Django-psql_07/Evaluacion_Medica/crear_pacientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"286958861","text":"students = [['Harsh', 20], ['Beria', 20], [\n 'Varun', 19], ['Kakunami', 19], ['Vikas', 21]]\n\nnumbers = []\nfor student in students:\n numbers.append(student[1])\n\nunique = []\nfor i in sorted(numbers):\n if i not in unique:\n unique.append(i)\n\nfor name, marks in sorted(students):\n if marks == unique[1]:\n print(name)\n\n# second_lowest_mark = sorted(list(dict.fromkeys(numbers)))\n# print(second_lowest_mark)\n","sub_path":"python Problem Solve/nasted.py","file_name":"nasted.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"556217963","text":"import requests\nimport os\nimport json\nfrom pprint import pprint\n\ntoken = os.getenv('GITHUB_TOKEN', '...')\n\ndef readConfigJson():\n\t# JSON file\n\tf = open ('teams.json', \"r\")\n\t\n\t# Reading from file\n\tdata = json.loads(f.read())\n\t\n\t# Closing file\n\tf.close()\n\treturn data\n\t\ndef getReposFromProject():\n\treturn node\n\ndef getTeamMembers(team_slug):\n\tprint(\"getTeamMember method\")\n\tmemberlist = []\n\tquery_url = \"https://api.github.com/orgs/newrelic/teams\"\n\tparams = {\n\t\t\"per_page\": 200,\n\t}\n\n\theaders = {'Authorization': f'token {token}'}\n\tr = requests.get(query_url, headers=headers, params=params)\n\tprint(r)\n\tfor i in r.json():\n\t\tif i['slug'] == team_slug:\n\t\t\tquery_url = i['members_url'].replace('{/member}','')\n\t\t\tteammembers = requests.get(query_url, headers=headers, params=params)\n\t\t\tfor m in teammembers.json():\n\t\t\t\tprint(m['login'])\n\t\t\t\tmemberlist.append(m['login'])\n\treturn memberlist\n\n\ndef getBugCounts(repos):\n\topenBugCount = 0\n\tprint(\"Gathering Unreviewed Bug Counts\")\n\tfor repo in repos:\n\t\tquery_url = f\"https://api.github.com/repos/newrelic/{repo}/issues\"\n\t\tparams = {\n\t\t\t\"status\": \"open\",\n\t\t\t\"labels\": \"bug\",\n\t\t\t\"labels\": \"needs-triage\",\n\t\t}\n\t\theaders = {'Authorization': f'token {token}'}\n\t\tr = requests.get(query_url, headers=headers, params=params)\n\t\topenBugCount += len(r.json())\n\tprint(\"Open Bugs: \", openBugCount)\n\ndef getExternalPRCounts(repos,teammembers):\n\tprint(\"Gathering Open External PR Counts\")\n\tprcount = 0\n\tfor repo in repos:\n\n\t\tquery_url = f\"https://api.github.com/repos/newrelic/{repo}/pulls\"\n\t\tparams = {\n\t\t\t\"state\": \"open\",\n\t\t}\n\t\theaders = {'Authorization': f'token {token}'}\n\t\tr = requests.get(query_url, headers=headers, params=params)\n\t\t#this has all pull requests. need to filter out ones where the author is on the team\n\t\tprs = r.json()\n\t\tfor pr in prs:\n\t\t\tif pr['user']['login'] not in teammembers :\n\t\t\t\tprint(' found external pr from:', pr['user']['login'])\n\t\t\t\tprcount += 1\n\t\t\telse:\n\t\t\t\tprint(' found pr for a team member: ', pr['user']['login'])\n\tprint(\"Open External PRs: \", prcount)\n\nteams = readConfigJson()\nfor team in teams['team']:\n\tprint(team['name'].upper())\n\tgetBugCounts(team['repos'])\n\tgetExternalPRCounts(team['repos'], getTeamMembers(team['team-slug']))\n\tprint()\t\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"378255006","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\nimport json\nimport requests\nimport smtplib\nimport time\nimport os\nimport logging\nfrom email.mime.text import MIMEText\n\nlogging.basicConfig(format=\"%(asctime)s - %(levelname)s - %(message)s\",filename=\"alert.log\", level=logging.DEBUG)\n\nURL=\"http://stat.kbu.freifunk.net/nodes.json\"\nFROM='ffkbumon@gokk.de'\nWATCHLISTFILE = \"watchlist.json\"\nDOWNLISTFILE = \"downlist.json\"\n\nwatchlist = dict()\ndownlist = dict()\n\ndef loadDownList():\n\tglobal downlist\n\tif os.path.exists(DOWNLISTFILE):\n\t\twith open(DOWNLISTFILE, 'r') as f:\n\t\t\tdownlist = json.load(f)\n\t\tf.closed\n\telse:\n\t\tlogging.warning(DOWNLISTFILE+\" nicht gefunden. Wird bei bedarf erstellt.\")\n\ndef writeDownList():\n\twith open(DOWNLISTFILE, 'w') as f:\n\t\tjson.dump(downlist, f)\n\tf.closed\t\t\n\ndef loadWatchList():\n\tglobal watchlist\n\tif os.path.exists(WATCHLISTFILE):\n\t\twith open(WATCHLISTFILE, 'r') as f:\n\t\t\twatchlist = json.load(f)\n\t\tf.closed\n\telse:\n\t\tlogging.error(WATCHLISTFILE+\" nicht gefunden. Beende.\")\n\t\texit()\t\n\ndef getStatData():\n\tr = requests.get(URL)\n\tif r.status_code != 200:\n\t\tlogging.warning(\"Konnte nodes.json nicht laden. (\"+int(time.time())+\")\")\n\t\treturn dict()\n\treturn json.loads(r.text)\n\t\ndef sendMail(nodeID, recipent, upDown):\n\tif upDown == \"down\":\n\t\tmsg = MIMEText(\"Dein Node \"+nodeID+\" ist nicht mehr Erreichbar!\\nPANIK!\\n\")\n\telse:\n\t\tmsg = MIMEText(\"Dein Node \"+nodeID+\" ist wieder Erreichbar.\\n\")\n\tmsg['Subject'] = \"Monitoring \"+nodeID\n\tmsg['From'] = FROM\n\tmsg['To'] = recipent\n\t\n\ts = smtplib.SMTP('localhost')\n\ts.sendmail(FROM, [recipent], msg.as_string())\n\ts.quit()\n\ndef checkNodes():\n\tstatData = getStatData()\n\t#optimalerweise hex:{loss:[val], ping:[val]}\n\tfor id in statData:\n\t\tif statData[id]['id_hex'] in watchlist:\n\t\t\tnode = statData[id]\n\t\t\tid_hex = node['id_hex']\n\t\t\tif node['loss_5_min'] == 1.0:\n\t\t\t\tif id_hex not in downlist:\n\t\t\t\t\tsendMail(id_hex, watchlist[id_hex], \"down\")\n\t\t\t\t\tdownlist[id_hex] = int(time.time())\n\t\t\t\t\tlogging.info(id_hex+\" went down at \"+str(int(time.time())))\n\t\t\telif id_hex in downlist:\n\t\t\t\tdel downlist[id_hex]\n\t\t\t\tsendMail(id_hex, watchlist[id_hex], \"up\")\n\t\t\t\tlogging.info(id_hex+\" got up again at \"+str(int(time.time())))\n\t\t\t\nloadDownList()\nloadWatchList()\ncheckNodes()\nwriteDownList()\n","sub_path":"ffNodeMon.py","file_name":"ffNodeMon.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"5478855","text":"Data = [int(x) for x in list(open(\"input.txt\").read().split(\" \"))]\n\nmetas = []\n\ndef recurNodes(index, metas):\n\n if Data[index] == 0:\n for i in range(index+2, index+2+Data[index+1]):\n metas.append(Data[i])\n return Data[index+1] + 2 # vraca duljinu zapisa s 0 djece\n \n offset = 0\n for i in range(Data[index]):\n offset += recurNodes(index + offset+2, metas)[0]\n\n for i in range(Data[index+1]):\n metas.append(Data[index+2+offset+i])\n\n return offset+2+Data[index+1]\n\n\nrecurNodes(0, metas)\n\nsum = 0\nfor meta in metas:\n sum += meta\nprint(sum)","sub_path":"AOC18/D8/run1.py","file_name":"run1.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"105447725","text":"import random\r\nimport sqlite3\r\n\r\ngenamenator_db = sqlite3.connect('GeNamenator_DB.db')\r\ncursor = genamenator_db.cursor()\r\ncursor.row_factory = lambda cursor, row: row[0]\r\n\r\nname_starts = (\"A\", \"B\", \"Ba\", \"Be\", \"Bi\", \"Bo\", \"Bu\", \"By\", \"C\", \"Ca\", \"Ce\", \"Ci\", \"Co\", \"Cu\", \"Ch\", \"Chr\", \"D\", \"Da\", \"De\", \"Di\", \"Do\", \"Du\",\r\n \"E\", \"F\", \"Fa\", \"Fe\", \"Fi\", \"Fo\", \"Fu\", \"G\", \"Ga\", \"Ge\", \"Gi\", \"Go\", \"Gu\", \"Gl\", \"Gr\", \"H\", \"Ha\", \"He\", \"Hi\", \"Ho\", \"Hu\",\r\n \"I\", \"J\", \"Ja\", \"Je\", \"Ji\", \"Jo\", \"Ju\", \"K\", \"Ka\", \"Ke\", \"Ki\", \"Ko\", \"Ku\", \"M\", \"Ma\", \"Me\", \"Mi\", \"Mo\", \"Mu\", \"N\", \"Na\", \"Ne\", \"Ni\" ,\"No\", \"Nu\",\r\n \"O\", \"P\", \"Pa\", \"Pe\", \"Pi\", \"Po\", \"Pi\", \"Ph\", \"Q\", \"R\", \"Ra\", \"Re\", \"Ri\", \"Ro\", \"Ru\", \"S\", \"Sa\", \"Se\", \"Si\", \"So\", \"Su, \"\r\n \"Sh\", \"Sha\", \"She\", \"Shi\", \"Sho\", \"Shu\", \"St\", \"Sta\", \"Ste\", \"Sti\", \"Sto\", \"Stu\", \"T\", \"Ta\", \"Te\", \"Ti\", \"To\", \"Tu\",\r\n \"Th\", \"Tha\", \"The\", \"Thi\", \"Tho\", \"Thu\", \"U\", \"V\", \"W\", \"Wa\", \"We\", \"Wi\", \"Wo\", \"Wu\", \"X\", \"Y\", \"Z\")\r\n\r\nprint(\"GeNamenator, version 1.4\")\r\nprint(\"by David Margis, 2020\")\r\nprint()\r\n\r\n\r\ndef main():\r\n main_choice = input(\"GeNamenator Main Menu \\n\"\r\n \" \\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Generate a completely random name \\n\"\r\n \" (2) Generate a random alliterative name \\n\"\r\n \" (3) Generate a female or male name \\n\"\r\n \" (4) Generate a female or male alliterative name \\n\"\r\n \" (5) Access the database management menu \\n\"\r\n \" (6) Exit GeNamenator \\n\"\r\n \" \")\r\n if main_choice == \"1\":\r\n random_name()\r\n elif main_choice == \"2\":\r\n random_name_alit()\r\n elif main_choice == \"3\":\r\n mf_name()\r\n elif main_choice == \"4\":\r\n mf_name_alit()\r\n elif main_choice == \"5\":\r\n dbm_menu()\r\n elif main_choice == \"6\":\r\n print(\"Thank you for using GeNamenator, the name-generating software with a name!\")\r\n raise SystemExit\r\n\r\n\r\n# NAME GENERATION FUNCTIONS\r\n\r\ndef random_name():\r\n random_choice = random.randrange(1, 4)\r\n if random_choice == 1:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice ==2:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice ==3:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice == 4:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n\r\n\r\ndef random_name_alit():\r\n while True:\r\n random_choice = random.randrange(1, 4)\r\n alitter = input(\"What letter or letters do you want your names to start with? Enter * for random. \")\r\n if alitter == \"*\":\r\n end_string = random.choice(name_starts) + \"%\"\r\n else:\r\n end_string = alitter.upper() + \"%\"\r\n if random_choice == 1:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice ==2:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice ==3:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 4:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n\r\n\r\ndef mf_name():\r\n while True:\r\n mf_choice = input(\"Would you like a female or male name? (F)emale / (M)ale \")\r\n if mf_choice.lower() == \"f\":\r\n cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FEMALE=\"YES\" ''')\r\n fn_list_pull = cursor.fetchall()\r\n break\r\n elif mf_choice.lower() == \"m\":\r\n cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE MALE=\"YES\" ''')\r\n fn_list_pull = cursor.fetchall()\r\n break\r\n else:\r\n print(\"Please enter 'F' or 'M'!\")\r\n while True:\r\n mn_choice = input(\"Would you like a middle name? Y / N \")\r\n if mn_choice.lower() == \"y\":\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name)\r\n elif mn_choice.lower() == \"n\":\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name)\r\n else:\r\n print(\"Please enter 'Y' or 'N'!\")\r\n\r\n\r\ndef mf_name_alit():\r\n random_choice = random.randrange(1, 2)\r\n while True:\r\n mf_choice = input(\"Would you like a random female or male alliterative name? F / M \")\r\n if mf_choice.lower() == \"f\" or mf_choice.lower() == \"m\":\r\n break\r\n else:\r\n print(\"Please enter 'F' or 'M'!\")\r\n while True:\r\n alitter = input(\"What letter or letters do you want your names to start with? Enter * for random. \")\r\n if alitter == \"*\":\r\n end_string = random.choice(name_starts) + \"%\"\r\n else:\r\n end_string = alitter.upper() + \"%\"\r\n if random_choice == 1 and mf_choice.lower() == \"f\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 2 and mf_choice.lower() == \"f\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 1 and mf_choice.lower() == \"m\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 2 and mf_choice.lower() == \"m\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(\r\n random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n\r\n\r\n# ADDITIONAL FUNCTIONS\r\n\r\ndef create_another_in_func(func):\r\n while True:\r\n again = input(\" \\n\"\r\n \"Would you like to create another or return to the main menu? (C)reate Another / (M)ain Menu \")\r\n if again.lower() == \"c\":\r\n func()\r\n break\r\n elif again.lower() == \"m\":\r\n main()\r\n break\r\n else:\r\n print(\"Please enter 'C' to create another or 'M' to return to the main menu!\")\r\n\r\n\r\n# DATABASE FUNCTION\r\n\r\ndef dbm_menu():\r\n while True:\r\n choose = input(\"What would you like to acces? \\n\"\r\n \" (F)irst Names \\n\"\r\n \" (L)ast Names \\n\"\r\n \" (A)djectives \\n\"\r\n \" (N)ouns \\n\"\r\n \" (M)ain Menu \\n\"\r\n \" \")\r\n if choose.lower() == \"f\":\r\n fn_gename_funcs()\r\n elif choose.lower() == \"l\":\r\n ln_gename_funcs()\r\n elif choose.lower() == \"a\":\r\n adj_funcs()\r\n elif choose.lower() == \"n\":\r\n nouns_funcs()\r\n elif choose.lower() == \"m\":\r\n main()\r\n else:\r\n print(\"Please enter one of the above options.\")\r\n\r\ndef fn_insert_row():\r\n fn = input(\"What is the first name you want to enter? \")\r\n f_yn = input(\"Is this a female name? YES/NO \")\r\n m_yn = input(\"Is this a male name? YES/NO \")\r\n dup = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?)''', (fn,))\r\n x = dup.fetchall()\r\n if x == []: # checks if number of matching names blank, or, an empty list\r\n cursor.execute(''' INSERT INTO first_names (FIRST_NAME, FEMALE, MALE) \r\n VALUES((?), (?), (?))''', (fn, f_yn, m_yn))\r\n genamenator_db.commit()\r\n print(fn + \" has been added!\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef ln_insert_row():\r\n ln = input(\"What is the surname you would like to enter? \")\r\n com = input(\"How common is this surname? COMMON / LESS COMMON / RARE \")\r\n dup = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?)''', (ln,))\r\n x = dup.fetchall()\r\n if x == []:\r\n cursor.execute(''' INSERT INTO last_names (LAST_NAME, COMMONALITY) VALUES((?), (?))''', (ln, com))\r\n genamenator_db.commit()\r\n print(ln + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef adj_insert_row():\r\n adj = input(\"What adjective would you like to enter? \")\r\n dup = cursor.execute(''' SELECT ADJECTIVE FROM adjectives WHERE ADJECTIVE=(?)''', (adj,))\r\n x = dup.fetchall()\r\n if x== []:\r\n cursor.execute(''' INSERT INTO adjectives (ADJECTIVE) VALUES(?) ''', (adj,))\r\n genamenator_db.commit()\r\n print(adj + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef noun_insert_row():\r\n noun = input(\"What noun would you like to enter? \")\r\n type = input(\"Is this classified as an occupation, or does it describe their personality? OCCUPATION / PERSONALITY \")\r\n dup = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (noun,))\r\n x = dup.fetchall()\r\n if x == []:\r\n cursor.execute(''' INSERT INTO nouns (NOUN, TYPE) VALUES(?, ?)''', (noun, type))\r\n genamenator_db.commit()\r\n print(noun + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef fn_check_for_name():\r\n x = input(\"What name are you checking for? \")\r\n data = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef ln_check_for_name():\r\n x = input(\"What name are you checking for? \")\r\n data = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef check_for_adj():\r\n x = input(\"What adjective are you searching for? \")\r\n data = cursor.execute(''' SELECT ADJECTIVE FROM adjectives WHERE ADJECTIVE=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef check_for_noun():\r\n x = input(\"What noun are you searching for? \")\r\n data = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef update_mf(): # changes the male/female columns from yes to no and vice versa\r\n while True:\r\n x = input(\"Which name do you want to update? \")\r\n y = input(\"Do you want to update FEMALE or MALE? \")\r\n if y == \"FEMALE\":\r\n y_yn = input(\"Do you want FEMALE to be YES or NO? \" )\r\n cursor.execute(''' UPDATE first_names SET FEMALE=(?) WHERE FIRST_NAME=(?) ''', (y_yn, x))\r\n genamenator_db.commit()\r\n break\r\n elif y == \"MALE\":\r\n m_yn = input(\"Do you want MALE to be YES or NO?\" )\r\n cursor.execute(''' UPDATE first_names SET MALE=(?) WHERE FIRST_NAME=(?)''', (m_yn, x))\r\n genamenator_db.commit()\r\n break\r\n else:\r\n print(\"Please enter your option as YES or NO.\")\r\n\r\n\r\ndef update_commonality():\r\n while True:\r\n x = input(\"Which surname would you like to update the commonality of? \")\r\n find = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist. Please try another name.\")\r\n else:\r\n while True:\r\n z = input(\"How common is this surname? COMMON / LESS COMMON / RARE \")\r\n if z == \"COMMON\" or \"LESS COMMON\" or \"RARE\":\r\n cursor.execute(''' UPDATE last_names SET COMMONALITY=(?) WHERE LAST_NAME=(?)''', (z, x,))\r\n genamenator_db.commit()\r\n print(x + \"has been updated.\")\r\n break\r\n else:\r\n print(\"Please enter your option in the form of COMMON, LESS COMMON, or RARE\")\r\n\r\n\r\ndef update_type():\r\n while True:\r\n x = input(\"Which noun would you like to update the type of? \")\r\n find = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That noun does not exist. Please try another noun.\")\r\n break\r\n else:\r\n while True:\r\n z = input(\"What type of noun is it? OCCUPTION / PERSONALITY \")\r\n if z == \"OCCUPATION\" or \"PERSONALITY\":\r\n cursor.execute(''' UPDATE nouns TYPE SET TYPE=(?) WHERE NOUN=(?)''', (z, x,))\r\n break\r\n else:\r\n print(\"Please enter your option in the form of OCCUPATION or PERSONALITY.\")\r\n\r\n\r\ndef fn_delete_name():\r\n x = input(\"What name would you like to delete? \")\r\n find = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist.\")\r\n else:\r\n cursor.execute(''' DELETE from first_names WHERE FIRST_NAME=(?) ''', (x,))\r\n genamenator_db.commit()\r\n print(\"%s has been deleted.\" % x)\r\n\r\n\r\ndef ln_delete_name():\r\n x = input(\"What surname would you like to delete? \")\r\n find = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist.\")\r\n else:\r\n cursor.execute(''' DELETE FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n genamenator_db.commit()\r\n print(\"%s has been deleted.\" % x)\r\n\r\n\r\ndef delete_adj():\r\n x = input(\"What adjective would you like to delete? \")\r\n cursor.execute(''' DELETE FROM adjectives WHERE ADJECTIVE=(?)''', (x,))\r\n genamenator_db.commit()\r\n\r\n\r\ndef delete_noun():\r\n x = input(\"What noun would you like to delete? \")\r\n cursor.execute(''' DELETE FROM nouns WHERE NOUN=(?)''', (x,))\r\n genamenator_db.commit()\r\n\r\n\r\ndef fn_gename_funcs():\r\n while True:\r\n func_cho = input(\"\\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Check if a name exists \\n\"\r\n \" (2) Add a new name \\n\"\r\n \" (3) Delete a name \\n\"\r\n \" (4) Update the associated genders of a name \\n\"\r\n \" \")\r\n if func_cho == '1':\r\n fn_check_for_name()\r\n elif func_cho == '2':\r\n fn_insert_row()\r\n elif func_cho == '3':\r\n fn_delete_name()\r\n elif func_cho == '4':\r\n update_mf()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef ln_gename_funcs():\r\n while True:\r\n func_cho = input(\"\\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Check if a surname exists \\n\"\r\n \" (2) Add a new surname \\n\"\r\n \" (3) Delete a surname \\n\"\r\n \" (4) Updated the commonality of a surname \\n\")\r\n if func_cho == \"1\":\r\n ln_check_for_name()\r\n elif func_cho == \"2\":\r\n ln_insert_row()\r\n elif func_cho == \"3\":\r\n ln_delete_name()\r\n elif func_cho == \"4\":\r\n update_commonality()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef adj_funcs():\r\n while True:\r\n func_cho = input(\"What would you like to do? \\n\"\r\n \" (1) Check if an adjective exists \\n\"\r\n \" (2) Insert a new adjective \\n\"\r\n \" (3) Delete an adjective \")\r\n if func_cho == \"1\":\r\n check_for_adj()\r\n elif func_cho == \"2\":\r\n adj_insert_row()\r\n elif func_cho == \"3\":\r\n delete_adj()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef nouns_funcs():\r\n while True:\r\n func_cho = input(\"What would you like to do? \\n\"\r\n \" (1) Check if an noun exists \\n\"\r\n \" (2) Insert a new noun \\n\"\r\n \" (3) Delete an adjective \\n\"\r\n \" (4) Change the type of noun \")\r\n if func_cho == \"1\":\r\n check_for_noun()\r\n if func_cho == \"2\":\r\n noun_insert_row()\r\n if func_cho == \"3\":\r\n delete_noun()\r\n if func_cho == \"4\":\r\n update_type()\r\n\r\nmain()","sub_path":"GeNamenator_v1_4.py","file_name":"GeNamenator_v1_4.py","file_ext":"py","file_size_in_byte":22384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"327228984","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom collections import defaultdict, Counter\nimport os\nimport sys\nsys.path.append(\"..\")\nfrom datetime import date\nimport pickle\nfrom article_utils import *\nfrom econ_utils import *\nimport glob\nimport math\nimport itertools\n\n# Return number of country name words in timestep\n# Number of articles that mention 1 country\n# Number of articles that mention 2 countries\ndef count_mentions_in_articles(filenames, keywords):\n keyword_to_count = defaultdict(int)\n total_word_count = 0\n\n for filename in filenames:\n articles, _ = LoadArticles(filename, verbose=False)\n for article in articles:\n counter = Counter(article.lower().split())\n\n if counter[\"usa\"] < 2:\n continue\n\n total_word_count += sum([counter[q] for q in counter])\n for c in keywords:\n keyword_to_count[c] += counter[c]\n return keyword_to_count, total_word_count\n\ndef load_country_names(filename):\n names = []\n for line in open(filename).readlines():\n names.append(line.split(\",\")[0].strip().lower())\n return names\n\ndef do_counts(files_grouped_by_date, subs_file):\n keywords = load_country_names(subs_file)\n\n # number of articles that mention country (normalize by number of articles)\n keyword_to_summary = defaultdict(list)\n for filename in files_grouped_by_date:\n keyword_to_count, total_word_count = count_mentions_in_articles(filename, keywords)\n for k in keyword_to_count:\n keyword_to_summary[k].append(keyword_to_count[k] / total_word_count)\n return keyword_to_summary\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_path', help=\"Directory where data files are. Must include trailing backslash\", default=\"../data/Izvestiia_processed/\")\n parser.add_argument('--subs_file', help=\"File containing keywords to count\", default=\"../data/usa.txt\")\n parser.add_argument('--timestep', type=str, help=\"specify what time increment to use for aggregating articles\",\n default='monthly',\n choices=['monthly', 'quarterly', 'semi', 'yearly'])\n parser.add_argument(\"--econ_file\", help=\"If you specify this, output will include compute correlation of counts with econ series (does NOT work for yearly)\")\n args = parser.parse_args()\n\n date_seq, filenames = get_files_by_time_slice(args.input_path, args.timestep)\n keyword_to_summary = do_counts(filenames, args.subs_file)\n\n keyword_to_corr = {}\n econ_seq = load_econ_file(args.econ_file, args.timestep, date_seq)\n\n for k in keyword_to_summary:\n assert(len(keyword_to_summary[k]) == len(date_seq))\n\n keyword_to_corr[k] = get_corr(econ_seq, keyword_to_summary[k])\n\n for k in sorted(keyword_to_corr, key=keyword_to_corr.get):\n print(k, keyword_to_corr[k])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/frame_analysis/measure_corr_per_word.py","file_name":"measure_corr_per_word.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"467632681","text":"file_name = input('Enter a fie name:')\nfile_handle = open(file_name)\ndays = list()\ndays_count = dict()\nfor line in file_handle:\n if line.startswith('From '):\n line = line.strip()\n words = line.split()\n days.append(words[2])\nfor day in days:\n days_count[day] = days_count.get(day, 0) + 1\nprint(days_count)\n","sub_path":"ex_09_01.py","file_name":"ex_09_01.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"630575638","text":"# -*- coding:utf-8 -*-\nfrom app import app\nfrom flask import render_template,redirect,session,request,url_for,make_response\nfrom Form_table import login_admin\nimport Judge\nfrom params import params_dict\nimport os,datetime,random\n\n\n\n@app.route('/login/', methods=('GET', 'POST'))\ndef login():\n form = login_admin()\n state = 'username' in session\n if state:\n return redirect('/admin/')\n if form.validate_on_submit(): ##提交内容不为空则就是True\n user_judge = Judge.user(form.name.data,form.passwd.data) ##得到表单数据\n return user_judge.judge_user()\n else:\n return render_template('login.html',form=form,state=state,params_dict=params_dict)\n\n\n@app.route('/admin/')\n@app.route('/admin//', methods=('GET', 'POST'))\ndef admin_manage(url=None):\n state = 'username' in session\n if request.args.get('id'):param = int(request.args.get('id'))\n else:param=1\n if url == None:\n if state:\n return render_template('admin.html',params_dict=params_dict,state=state)\n return redirect('/login/')\n elif state:\n url_judge = Judge.admin_url(url,param)\n return url_judge.url_judge()\n return redirect('/login/')\n\n@app.route('/admin/category/')\n@app.route('/admin/category//', methods=('GET', 'POST'))\n@app.route('/admin/category///', methods=('GET', 'POST'))\ndef category(name=None,cate_id=None):\n state = 'username' in session\n if request.args.get('id'):param = int(request.args.get('id'))\n else:param=1\n if state:\n return Judge.cate_url(name,cate_id,param)\n else:\n return redirect('/login/')\n \n\n@app.route('/admin/post//', methods=('GET', 'POST'))\ndef admin_post(name=None):\n state = 'username' in session\n param = request.args.get('id')\n where = request.args.get('where')\n cate = request.args.get('cate')\n if state:\n return Judge.cate_post_url(name,param,where,cate)\n else:\n return redirect('/login/')\n\n@app.route('/post//')\ndef post(id):\n state = 'username' in session\n return Judge.post_id(id,state)\n\n@app.route('/category//')\ndef index_category(id):\n state = 'username' in session\n param = request.args.get('page')\n if param == None:param=1\n return Judge.category_id(state,id,param)\n\n@app.route('/')\ndef index():\n state = 'username' in session\n id = request.args.get('id')\n index_right = Judge.index_right(state)\n return index_right.index(id)\n \n@app.route('/logout/')\ndef logout():\n session.pop('username')\n return redirect('/login/')\n\n@app.errorhandler(404)\ndef page_not_found(error):\n return render_template('404.html',params_dict=params_dict),404\n\n\ndef gen_rnd_filename():\n filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))\n\n@app.route('/ckupload/', methods=['POST'])\ndef ckupload():\n \"\"\"CKEditor file upload\"\"\"\n error = ''\n url = ''\n callback = request.args.get(\"CKEditorFuncNum\")\n if request.method == 'POST' and 'upload' in request.files:\n fileobj = request.files['upload']\n fname, fext = os.path.splitext(fileobj.filename)\n rnd_name = '%s%s' % (gen_rnd_filename(), fext)\n filepath = os.path.join(app.static_folder, 'upload', rnd_name)\n # 检查路径是否存在,不存在则创建\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except:\n error = 'ERROR_CREATE_DIR'\n elif not os.access(dirname, os.W_OK):\n error = 'ERROR_DIR_NOT_WRITEABLE'\n if not error:\n fileobj.save(filepath)\n url = url_for('static', filename='%s/%s' % ('upload', rnd_name))\n else:\n error = 'post error'\n res = \"\"\"\n\n\n\n\"\"\" % (callback, url, error)\n response = make_response(res)\n response.headers[\"Content-Type\"] = \"text/html\"\n return response\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"468938287","text":"\n\nimport navmet\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse, Circle\nplt.style.use('fivethirtyeight')\n\n\ndef simple_example():\n # -- Objective metrics\n traj = np.loadtxt('sample_traj.txt')\n agents = np.loadtxt('sample_agents.txt')\n # robot = agents[0, :]\n persons = agents[1:, :]\n\n # --- Objective\n pl = navmet.path_length(traj)\n chc = navmet.chc(traj)\n print('Objective Metrics: Path length = {}, CHC = {}'.format(pl, chc))\n\n # plot their configuration\n plt.figure(figsize=(10, 10))\n ax = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)\n\n for n in agents:\n theta = np.degrees(np.arctan2(n[3], n[2]))\n ax.add_artist(Ellipse((n[0], n[1]), width=0.3, height=0.8, angle=theta,\n color='b', fill=False, lw=1.5))\n ax.add_artist(Circle((n[0], n[1]), radius=0.2, color='w',\n ec='b', lw=4))\n ax.arrow(n[0], n[1], 0.5*n[2], 0.5*n[3], fc='b', ec='b',\n head_width=0.2, head_length=0.2)\n\n ax.plot(traj[::3, 0], traj[::3, 1], ls='', marker='8', markersize=5,\n color='r', label='Robot trajectory')\n ax.plot(traj[0, 0], traj[0, 1], ls='', marker='8', markersize=15,\n color='k', label='Start')\n ax.plot(traj[-1, 0], traj[-1, 1], ls='', marker='8', markersize=15,\n color='g', label='Goal')\n ax.legend(loc='best', numpoints=1)\n plt.axis('equal')\n\n # --- Subjective\n ic, pc, sc = navmet.personal_disturbance(traj, persons)\n print('Instrusion Counts: Intimate = {}, Personal = {}, Social = {}'\n .format(ic, pc, sc))\n\n plt.show()\n\n\nif __name__ == '__main__':\n simple_example()\n","sub_path":"examples/simple_example.py","file_name":"simple_example.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"510525269","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# StackSafeRecursion.py\n#\n# Copyright © 2019 zhixiong.cai \n#\n\n\"\"\"\n@package CodeSnippets.StackSafeRecursion\n\nRecursion in Python that will not exhaust the stack.\n\"\"\"\n\niden = lambda x: x\n\nl = [1, 1] + [None] * 1000\n\ndef call(f):\n while callable(f):\n f = f()\n return f\n\t\ndef fibo(n, cont=iden):\n if l[n] is not None: return cont(l[n])\n return lambda: fibo(n - 1, lambda v_1: l.__setitem__(n - 1, v_1) or (lambda: fibo(n - 2, lambda v_2: l.__setitem__(n - 2, v_2) or (lambda: cont(v_1 + v_2)))))\n\t\ncall(fibo(1000))\n","sub_path":"StackSafeRecursion.py","file_name":"StackSafeRecursion.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"436421733","text":"#\n#\n# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl\n#\n# This file is part of acados.\n#\n# The 2-Clause BSD License\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#\nfrom casadi import cos, Function, sin, SX, vertcat\n\ndef chen_model():\n \"\"\" The following ODE model comes from Chen1998. \"\"\"\n nx, nu = (2, 1)\n x = SX.sym('x', nx)\n u = SX.sym('u', nu)\n mu = 0.5\n rhs = vertcat(x[1] + u*(mu + (1.-mu)*x[0]), x[0] + u*(mu - 4.*(1.-mu)*x[1]))\n return Function('chen', [x, u], [rhs], ['x', 'u'], ['xdot']), nx, nu\n\ndef pendulum_model():\n \"\"\" Nonlinear inverse pendulum model. \"\"\"\n M = 1 # mass of the cart [kg]\n m = 0.1 # mass of the ball [kg]\n g = 9.81 # gravity constant [m/s^2]\n l = 0.8 # length of the rod [m]\n\n p = SX.sym('p') # horizontal displacement [m]\n theta = SX.sym('theta') # angle with the vertical [rad]\n v = SX.sym('v') # horizontal velocity [m/s]\n omega = SX.sym('omega') # angular velocity [rad/s]\n F = SX.sym('F') # horizontal force [N]\n\n ode_rhs = vertcat(v,\n omega,\n (- l*m*sin(theta)*omega**2 + F + g*m*cos(theta)*sin(theta))/(M + m - m*cos(theta)**2),\n (- l*m*cos(theta)*sin(theta)*omega**2 + F*cos(theta) + g*m*sin(theta) + M*g*sin(theta))/(l*(M + m - m*cos(theta)**2)))\n\n nx = 4\n # for IRK\n xdot = SX.sym('xdot', nx, 1)\n z = SX.sym('z',0,1)\n return (Function('pendulum', [vertcat(p, theta, v, omega), F], [ode_rhs], ['x', 'u'], ['xdot']),\n nx, # number of states\n 1, # number of controls\n Function('impl_pendulum', [vertcat(p, theta, v, omega), F, xdot, z], [ode_rhs-xdot],\n ['x', 'u','xdot','z'], ['rhs']))\n","sub_path":"experimental/examples/python/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"21154009","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 ('getpaid', '0002_auto_20150723_0923'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='payment',\n name='amount',\n field=models.DecimalField(verbose_name='amount', max_digits=10, decimal_places=2),\n ),\n migrations.AlterField(\n model_name='payment',\n name='amount_paid',\n field=models.DecimalField(default=0, verbose_name='amount paid', max_digits=10, decimal_places=2),\n ),\n ]\n","sub_path":"getpaid/migrations/0003_auto_20160706_1940.py","file_name":"0003_auto_20160706_1940.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"526692880","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\ddshape\\break_shell.py\n# Compiled at: 2015-06-08 05:15:18\nimport inc\n\ndef break_shell(index=1, data='', center=(0, 0, 0), out_radius=25, shell=3, cutoff=(0, 0, 0, 0, 0, 0), precision=1):\n \"\"\"\n the main function to write break hollow sphere\n :param index: a number which indicate the line numbers of main shape data\n :param data: string with all shape data combined\n :param center: center of the hollow sphere\n :param out_radius: out radius of sphere, the unit is nm\n :param shell: shell thickness of sphere\n :param cutoff: remove some part of break shell\n :param precision: precision that determine the size of dipole\n :return: int, string\n \"\"\"\n number_range = inc.get_range(out_radius, cutoff, precision)\n for j in range(number_range[0], number_range[1]):\n for k in range(number_range[2], number_range[3]):\n for m in range(number_range[4], number_range[5]):\n if break_shell_validate((j, k, m), out_radius, shell, precision):\n data += inc.print_line(index, center, (j, k, m), precision)\n index += 1\n\n return (\n index, data)\n\n\ndef break_shell_validate(point=(0, 0, 0), out_radius=25, shell=3, precision=1):\n \"\"\"\n validate if a point is in a shell\n :param point: temporary point of shell\n :param out_radius: out radius of shell\n :param shell: thickness of shell\n :param precision: precision that determine the size of dipole\n :return: boolean\n \"\"\"\n sqrt_acc = point[0] ** 2 + point[1] ** 2 + point[2] ** 2\n if not ((out_radius - shell) * precision) ** 2 <= sqrt_acc <= (out_radius * precision) ** 2:\n return False\n return True","sub_path":"pycfiles/ddshape-0.38-py2.7/break_shell.py","file_name":"break_shell.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"462974018","text":"import argparse\nimport time\nfrom tensorboardX import SummaryWriter\nfrom dataset import dataset_loader\nfrom model import LeNet5, ResNet34\nimport torch\nfrom torch import nn\n'''\n--model ResNet34 --dataset sign_mnist --log_interval 100\n--model ResNet34 --dataset sign_mnist --log_interval 100 --gray_scale\n--model ResNet34 --dataset kinect_leap --log_interval 8\n--model ResNet34 --dataset kinect_leap --log_interval 8 --gray_scale\n--model LeNet5 --dataset sign_mnist --log_interval 100\n--model LeNet5 --dataset sign_mnist --log_interval 100 --gray_scale\n--model LeNet5 --dataset kinect_leap --log_interval 8\n--model LeNet5 --dataset kinect_leap --log_interval 8 --gray_scale\n'''\n\nparser = argparse.ArgumentParser(description='PyTorch Gesture Recognition Model')\nparser.add_argument('--model', choices=['LeNet5', 'ResNet34'], default='LeNet5', type=str, help='LeNet5(default), ResNet34')\nparser.add_argument('--dataset',\n choices=['sign_mnist', 'kinect_leap'],\n default='sign_mnist',\n type=str,\n help='sign_mnist(default), kinect_leap')\nparser.add_argument('--gray_scale', action='store_true', help='train with grayscale image or rgb image(defalt: rgb)')\nparser.add_argument('--epoch', default=100, type=int, help='amount of epoches been processed')\nparser.add_argument('--save_model', action='store_true', help='saving model or not(default: false)')\nparser.add_argument('--log_interval', default=100, type=int, help='how many batches to wait before logging status(defalut:100)')\nparser.set_defaults(augment=True)\n\nwriter = SummaryWriter('./log')\n\n\ndef main():\n global args\n\n args = parser.parse_args()\n\n # load dataset\n if args.dataset == 'sign_mnist':\n loader = dataset_loader(True)\n if args.model == 'LeNet5':\n train_loader, test_loader = loader.load_sign_mnist(28, isGrayScale=args.gray_scale)\n elif args.model == 'ResNet34':\n train_loader, test_loader = loader.load_sign_mnist(224, isGrayScale=args.gray_scale)\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n elif args.dataset == 'kinect_leap':\n loader = dataset_loader(False)\n if args.model == 'LeNet5':\n train_loader, test_loader = loader.load_kinect_leap(img_size=28, isGrayScale=args.gray_scale)\n elif args.model == 'ResNet34':\n train_loader, test_loader = loader.load_kinect_leap(img_size=224, isGrayScale=args.gray_scale)\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n else:\n raise RuntimeError('unrecogniazed dataset name' + repr(args.dataset))\n\n # load model\n if args.model == 'LeNet5':\n model = LeNet5(class_num=loader.class_num, is_gray_scale=args.gray_scale).cuda()\n elif args.model == 'ResNet34':\n model = ResNet34(class_num=loader.class_num, is_gray_scale=args.gray_scale).cuda()\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n\n print(model)\n\n criterion = nn.CrossEntropyLoss().cuda()\n optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n\n # time counting\n start_time = time.time()\n\n for epoch in range(1, args.epoch + 1):\n train(model, train_loader, criterion, optimizer, epoch)\n test(model, test_loader, epoch)\n\n end_time = time.time()\n print('training process using ', end_time - start_time)\n\n # save model\n if args.save_model:\n saving_path = './trained_model/' + args.model + '.pth'\n torch.save(model, saving_path)\n return\n\n\ndef train(model, train_loader, criterion, optimizer, epoch):\n epoch_start_time = time.time()\n model.train()\n\n total = len(train_loader.dataset)\n\n # loss sum\n train_loss = 0\n\n correct = 0\n\n data_start_time = time.time()\n for i, (input, target) in enumerate(train_loader):\n # data_start_time = time.time()\n\n input = input.cuda()\n target = target.cuda()\n\n optimizer.zero_grad()\n output = model(input)\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n\n predicted = output.argmax(dim=1)\n correct += torch.eq(predicted, target).float().sum().item()\n\n # data_time = time.time() - data_start_time\n\n trained_total = (i + 1) * len(target)\n loss_mean = train_loss / (i + 1)\n acc = correct / trained_total\n process = 100 * trained_total / total\n\n if (i + 1) % args.log_interval == 0:\n data_time = time.time() - data_start_time\n print('epoch: {} [{}/{} ({:.0f}%)] \\tloss:{:.6f}({:.6f}) \\taccuracy:{:.6f} \\ttime:{:.6f}'.format(\n epoch, trained_total, total, process, loss, loss_mean, acc, data_time))\n data_start_time = time.time()\n\n writer.add_scalar('train/loss_mean', loss_mean, (epoch - 1) * len(train_loader) + i)\n writer.add_scalar('train/accuracy', acc, (epoch - 1) * len(train_loader) + i)\n writer.add_scalar('train/loss', loss, (epoch - 1) * len(train_loader) + i)\n\n epoch_time = time.time() - epoch_start_time\n print('epoch trained in ', epoch_time)\n\n return\n\n\ndef test(model, test_loader, epoch):\n model.eval()\n\n correct = 0\n\n for i, (input, target) in enumerate(test_loader):\n input = input.cuda()\n target = target.cuda()\n\n output = model(input)\n\n predicted = output.argmax(dim=1)\n correct += torch.eq(predicted, target).float().sum().item()\n\n acc = correct / len(test_loader.dataset)\n\n writer.add_scalar('test/accuracy', acc, (epoch - 1) * len(test_loader))\n\n print('epoch: {} accuracy:{}'.format(epoch, acc))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Project/Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235718177","text":"animales = {\"Gato Montes\": 2, \"Yacare overo\": 4, \"Boa acuática\": 5}\nfor animal in animales:\n pos = animales[animal]\n car = animal[pos]\n i = 0\n cadena = \"\"\n for letra in animal:\n if (i == pos):\n cadena += car + \" \"\n else:\n cadena += \"_ \"\n i += 1\n print(cadena)\n","sub_path":"Practica1/Ejercicio12.py","file_name":"Ejercicio12.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"219228728","text":"\n## Test ID:\nUSER_NAME = 'Bar'\nFOLDER_PATH = r\"C:\\\\Users\\bar.kristal\\Documents\\GitHub\\Python\\Tests\\functionality_test\"\nTEST_NAME = \"excel_test\"\n\n#call the init.py module:\nexecfile(r\"C:\\Users\\bar.kristal\\Documents\\GitHub\\Python\\init.py\")\n\n# defines:\nheadlines = [\"Block\", \"Temp\", \"Voltage\", \"Result\"]\ntemps = [\"-40C\", \"25C\", \"80C\"]\nvoltages = [\"0.9\", \"1.1\", \"1.2\"]\nblocks = [\"PTCM\", \"RAM\", \"DTCM\"]\n\nblock_col = 1\ntemp_col = 2\nvolt_col = 3\nresult_col = 4\n\n#######################################################################################\n\nwb1, full_path = create_excel_file(DIR_NAME, LOG_NAME_EXCEL)\nws1 = wb1.create_sheet(\"BIST results\")\n\nthermotron = Termotron3800(TERMOTRON_TCP_IP)\npwr_sply = QL355TPPwrSply(POWER_SUPLLY_ADDRESS)\ndmm = Agillent34401A(DMM_ADDRESS)\n\n\n\n#write headlines to excel\nfor i in range(len(headlines)):\n ws1.cell(row=1, column=i+1).value = headlines[i]\nwb1.save(full_path)\n\ncurrent_row = 2\n\n#start test and write results to excel\nfor temp in temps:\n # thermotron.set_temp(temp)\n time.sleep(3)\n\n for volt in voltages:\n # pwr_sply.set_volt(volt)\n\n for block in blocks:\n\n '''run test on the block'''\n\n #result:\n if len(block) % 2 == 0:\n result = \"Pass\"\n else:\n result = \"Fail\"\n\n #write results:\n ws1.cell(row=current_row, column=block_col).value = block\n ws1.cell(row=current_row, column=temp_col).value = temp\n ws1.cell(row=current_row, column=volt_col).value = volt\n ws1.cell(row=current_row, column=result_col).value = result\n\n #upgarde row number\n current_row += 1\n\n #save excel file\n wb1.save(full_path)\n\n\n\n","sub_path":"Tests/functionality_test/excel_test.py","file_name":"excel_test.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"295638359","text":"from urllib.request import urlretrieve\r\nimport time\r\nimport zipfile\r\nimport os\r\nimport numpy as np\r\n\r\n\r\ndef main(url):\r\n# Скачиваем zip файл с данными.\r\n\ttry:\r\n\t\tzipdata = 'dataset.zip'\r\n\t\turlretrieve(url, zipdata)\r\n\t\tprint('\\nZip файл успешно загружен\\n')\r\n\texcept:\r\n\t\tprint('Ошибка загрузки, либо файл уже загружен\\n')\r\n\r\n# Извлечение txt.\r\n\ttry:\r\n\t\tprint('Извлечение...\\n')\r\n\t\tf = zipfile.ZipFile('dataset.zip', 'r')\r\n\t\tf.extractall()\r\n\t\tprint('Извлечение успешно\\n')\r\n\texcept:\r\n\t\tprint('Извлечение не выполнено, либо извлечение уже было произведено\\n')\r\n\r\n# Распределение файлов по спискам для дальнейшего сравнения.\r\n\tdataSet1 = []\r\n\tdataSet2 = []\r\n# первый файл.\r\n\twith open('time series 1.txt', 'r') as q:\r\n\t\tdataSet1 = q.read().split()\r\n\t\tq.close()\r\n# второй файл.\r\n\twith open('time series 2.txt', 'r') as w:\r\n\t\tdataSet2 = w.read().split()\r\n\t\tw.close()\r\n\r\n# Сравнение списков\r\n\tresultIntersection = []\r\n\tresultDifferences = []\r\n# Пересечение(1)\r\n\tfor x in dataSet1:\r\n\t\tif x in dataSet2:\r\n\t\t\tresultIntersection.append(x)\r\n# Отличия(2)\r\n\tfor y in dataSet1:\r\n\t\tif y not in dataSet2:\r\n\t\t\tresultDifferences.append(y)\r\n# Медиана(3)\r\n\ta = np.array(dataSet1, float)\r\n\tb = np.array(dataSet2, float)\r\n\taMed = np.median(a)\r\n\tbMed = np.median(b)\r\n\tmedians = (aMed,bMed)\r\n# Корреляция(4)\r\n\td = np.array(dataSet1).astype(np.float)\r\n\tb = np.array(dataSet2).astype(np.float)\r\n\tcorr = np.corrcoef(d,b)\r\n\t\r\n\r\n# Создание файла с результатом\r\n\ttry:\r\n\t\tstrCorr = ('Значение корреляции\\n' + str(corr))\r\n\t\tstrMedian = ('Значения медиан\\n' + str(medians))\r\n\t\tstrResultIntersection = ('Пересечение списков\\n' + str(resultIntersection) + '\\n\\n')\r\n\t\tstrResultDifferences = ('\\n\\nЗначения, не пересекающи��ся в списках\\n' + str(resultDifferences) + '\\n\\n')\r\n\t\twith open('result.txt', 'w') as result:\r\n\t\t\tresult.write(strResultIntersection)\r\n\t\t\tresult.write(strResultDifferences)\r\n\t\t\tresult.write(strCorr)\r\n\t\t\tresult.write(strMedian)\r\n\t\t\tresult.close()\r\n\t\tprint('Результат сохранен в файл result.txt')\r\n\texcept:\r\n\t\tprint('Ошибка сохранения результата')\r\n\r\n\treturn strResultDifferences, strResultIntersection, strMedian, strCorr\r\n\r\n\r\nurl = 'https://drive.google.com/uc?authuser=0&id=1MJecQrW-LEnutKl93DxiI-GYmg49MWES&export=download'\r\nwhile True:\r\n\tmain(url)\r\n# Пауза 10 минут, после этого цикл повторится.\r\n\ttime.sleep(600)\r\n# Для наглядности продемонстрировано удаление zip файла, после чего функция скачает его вновь.\r\n\tpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dataset.zip')\r\n\tos.remove(path)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"48964482","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Desafio 6\n# \n# Neste desafio, vamos praticar _feature engineering_, um dos processos mais importantes e trabalhosos de ML. Utilizaremos o _data set_ [Countries of the world](https://www.kaggle.com/fernandol/countries-of-the-world), que contém dados sobre os 227 países do mundo com informações sobre tamanho da população, área, imigração e setores de produção.\n# \n# > Obs.: Por favor, não modifique o nome das funções de resposta.\n\n# ## _Setup_ geral\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\n# In[3]:\n\n\n# Algumas configurações para o matplotlib.\n#%matplotlib inline\n\nfrom IPython.core.pylabtools import figsize\n\n\nfigsize(12, 8)\n\nsns.set()\n\n\n# In[4]:\n\n\ncountries = pd.read_csv(\"countries.csv\")\n\n\n# In[5]:\n\n\nnew_column_names = [\n \"Country\", \"Region\", \"Population\", \"Area\", \"Pop_density\", \"Coastline_ratio\",\n \"Net_migration\", \"Infant_mortality\", \"GDP\", \"Literacy\", \"Phones_per_1000\",\n \"Arable\", \"Crops\", \"Other\", \"Climate\", \"Birthrate\", \"Deathrate\", \"Agriculture\",\n \"Industry\", \"Service\"\n]\n\ncountries.columns = new_column_names\n\ncountries.head()\n\n\n# ## Observações\n# \n# Esse _data set_ ainda precisa de alguns ajustes iniciais. Primeiro, note que as variáveis numéricas estão usando vírgula como separador decimal e estão codificadas como strings. Corrija isso antes de continuar: transforme essas variáveis em numéricas adequadamente.\n# \n# Além disso, as variáveis `Country` e `Region` possuem espaços a mais no começo e no final da string. Você pode utilizar o método `str.strip()` para remover esses espaços.\n\n# ## Inicia sua análise a partir daqui\n\n# In[6]:\n\n\nnumeric_columns = [\n \"Pop_density\", \"Coastline_ratio\", \"Net_migration\", \"Infant_mortality\",\"Literacy\", \"Phones_per_1000\",\n \"Arable\", \"Crops\", \"Other\", \"Climate\", \"Birthrate\", \"Deathrate\", \"Agriculture\",\n \"Industry\", \"Service\"]\n\nfor column in numeric_columns:\n countries[column] = countries[column].str.replace(',', '.').astype(float)\n\ncountries['Region'] = [s.strip() for s in countries.Region.to_list()]\n\ncountries.dtypes\n\n\n# # Questão 1\n# \n# Quais são as regiões (variável `Region`) presentes no _data set_? Retorne uma lista com as regiões únicas do _data set_ com os espaços à frente e atrás da string removidos (mas mantenha pontuação: ponto, hífen etc) e ordenadas em ordem alfabética.\n\n# In[10]:\n\n\ndef q1():\n unique = [x for x in countries.Region.sort_values().unique()]\n return unique\n\nq1()\n\n\n# ## Questão 2\n# \n# Discretizando a variável `Pop_density` em 10 intervalos com `KBinsDiscretizer`, seguindo o encode `ordinal` e estratégia `quantile`, quantos países se encontram acima do 90º percentil? Responda como um único escalar inteiro.\n\n# In[7]:\n\n\ndef q2():\n \n\n est = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile')\n pop_density_discretizer = est.fit(countries[['Pop_density']])\n\n scores = pop_density_discretizer.transform(countries[['Pop_density']])\n\n return len(scores[scores==9])\nq2()\n\n\n# # Questão 3\n# \n# Se codificarmos as variáveis `Region` e `Climate` usando _one-hot encoding_, quantos novos atributos seriam criados? Responda como um único escalar.\n\n# In[8]:\n\n\ndef q3():\n countries_for_one_hot = countries[[\"Region\", \"Climate\"]]\n countries_for_one_hot['Climate'].fillna(0, inplace=True)\n \n one_hot_encoder = OneHotEncoder(sparse=False, dtype=np.int)\n region_encoded = one_hot_encoder.fit_transform(countries_for_one_hot[[\"Region\", \"Climate\"]])\n\n return region_encoded.shape[1]\n\nq3()\n\n\n# ## Questão 4\n# \n# Aplique o seguinte _pipeline_:\n# \n# 1. Preencha as variáveis do tipo `int64` e `float64` com suas respectivas medianas.\n# 2. Padronize essas variáveis.\n# \n# Após aplicado o _pipeline_ descrito acima aos dados (somente nas variáveis dos tipos especificados), aplique o mesmo _pipeline_ (ou `ColumnTransformer`) ao dado abaixo. Qual o valor da variável `Arable` após o _pipeline_? Responda como um único float arredondado para três casas decimais.\n\n# In[38]:\n\n\ntest_country = [\n 'Test Country', 'NEAR EAST', -0.19032480757326514,\n -0.3232636124824411, -0.04421734470810142, -0.27528113360605316,\n 0.13255850810281325, -0.8054845935643491, 1.0119784924248225,\n 0.6189182532646624, 1.0074863283776458, 0.20239896852403538,\n -0.043678728558593366, -0.13929748680369286, 1.3163604645710438,\n -0.3699637766938669, -0.6149300604558857, -0.854369594993175,\n 0.263445277972641, 0.5712416961268142\n]\n\ndf_test_country = pd.DataFrame([dict(zip(new_column_names, test_country))])\n\n\n# In[40]:\n\n\ndef q4():\n df_countries_numeric = countries.select_dtypes(include = ['int64', 'float64'])\n countries_numeric_columns = df_countries_numeric.columns.to_list()\n \n num_pipeline = Pipeline([\n (\"imputer\", SimpleImputer(strategy='median')),\n (\"standard\", StandardScaler())\n ])\n \n num_pipeline.fit(df_countries_numeric)\n arable_id = countries_numeric_columns.index('Arable')\n arable_value = num_pipeline.transform(df_test_country[countries_numeric_columns])[0][arable_id]\n \n return float(round(arable_value, 3))\n \nq4()\n\n\n# ## Questão 5\n# \n# Descubra o número de _outliers_ da variável `Net_migration` segundo o método do _boxplot_, ou seja, usando a lógica:\n# \n# $$x \\notin [Q1 - 1.5 \\times \\text{IQR}, Q3 + 1.5 \\times \\text{IQR}] \\Rightarrow x \\text{ é outlier}$$\n# \n# que se encontram no grupo inferior e no grupo superior.\n# \n# Você deveria remover da análise as observações consideradas _outliers_ segundo esse método? Responda como uma tupla de três elementos `(outliers_abaixo, outliers_acima, removeria?)` ((int, int, bool)).\n\n# In[45]:\n\n\ndef q5():\n net_migration = countries['Net_migration']\n q1 = net_migration.quantile(.25)\n q3 = net_migration.quantile(.75)\n \n iqr = q3 - q1\n \n outliers_acima = len(net_migration[net_migration > q3 + 1.5*iqr])\n outliers_abaixo = len(net_migration[net_migration < q1 - 1.5*iqr])\n\n \n removeria = bool((outliers_abaixo + outliers_acima)/len(net_migration) < 0.2)\n return (outliers_abaixo, outliers_acima, removeria)\nq5()\n\n\n# ## Questão 6\n# Para as questões 6 e 7 utilize a biblioteca `fetch_20newsgroups` de datasets de test do `sklearn`\n# \n# Considere carregar as seguintes categorias e o dataset `newsgroups`:\n# \n# ```\n# categories = ['sci.electronics', 'comp.graphics', 'rec.motorcycles']\n# newsgroup = fetch_20newsgroups(subset=\"train\", categories=categories, shuffle=True, random_state=42)\n# ```\n# \n# \n# Aplique `CountVectorizer` ao _data set_ `newsgroups` e descubra o número de vezes que a palavra _phone_ aparece no corpus. Responda como um único escalar.\n\n# In[69]:\n\n\ncategories = ['sci.electronics', 'comp.graphics', 'rec.motorcycles']\nnewsgroup = fetch_20newsgroups(subset=\"train\", categories=categories, shuffle=True, random_state=42)\n\n\n# In[65]:\n\n\ndef q6():\n \n vectorizer = CountVectorizer()\n vectorizer_transform = vectorizer.fit_transform(newsgroup['data'])\n \n word_list = vectorizer.get_feature_names(); \n count_list = vectorizer_transform.toarray().sum(axis=0)\n vectorize_dict = dict(zip(word_list,count_list))\n \n return vectorize_dict['phone']\n \nq6()\n\n\n# ## Questão 7\n# \n# Aplique `TfidfVectorizer` ao _data set_ `newsgroups` e descubra o TF-IDF da palavra _phone_. Responda como um único escalar arredondado para três casas decimais.\n\n# In[73]:\n\n\ndef q7():\n \n vectorizer = TfidfVectorizer()\n vectorizer_transform = vectorizer.fit_transform(newsgroup['data'])\n \n word_list = vectorizer.get_feature_names(); \n count_list = vectorizer_transform.toarray().sum(axis=0)\n vectorize_dict = dict(zip(word_list,count_list))\n \n return round(vectorize_dict['phone'], 3)\nq7()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"data-science-4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"5176028","text":"import datetime\r\nfrom discord.ext import commands\r\nimport discord\r\nimport random\r\n\r\n\r\nclass FunCog(commands.Cog, name='Fun'):\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n\r\n @commands.command(aliases=['meme'])\r\n async def pepe(self, ctx):\r\n pepe = ['https://cdn.discordapp.com/emojis/656665539694952448.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/680098905009946655.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/620686647331258399.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/589828801484161066.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/596132760532287488.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/402446616281350144.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/300046211300327425.png?v=1,']\r\n embed = discord.Embed(title=\"**Pepe**\",\r\n color=discord.Color.blue())\r\n embed.set_image(url=random.choice(pepe))\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n # coin flip\r\n @commands.command(aliases=['coin'])\r\n async def flip(self, ctx):\r\n responses = ['Heads', 'Tails']\r\n flipmsg = f'Congrats! Your coin landed on **{random.choice(responses)}!**'\r\n embed = discord.Embed(title=\"**Flip**\",\r\n description=('{}'.format(flipmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # joke\r\n @commands.command(aliases=['Joke', 'funny'])\r\n async def joke(self, ctx):\r\n jokemsg = ['A child asked his father, \"How were people born?\" So his father said, \"Adam and Eve made babies, '\r\n 'then their babies became adults and made babies, and so on.\" The child then went to his mother, '\r\n 'asked her the same question and she told him, \"We were monkeys then we evolved to become like we '\r\n 'are now.\" The child ran back to his father and said, \"You lied to me!\" His father replied, \"No, '\r\n 'your mom was talking about her side of the family.\" ',\r\n 'My friend thinks he is smart. He told me an onion is the only food that makes you cry, so I threw '\r\n 'a '\r\n 'coconut at his face. ',\r\n 'A teacher asked her students to use the word \"beans\" in a sentence. \"My father grows beans,'\r\n '\" said one girl. \"My mother cooks beans,\" said a boy. A third student spoke up, \"We are all human '\r\n 'beans.\" ',\r\n 'Why was 6 afraid of 7? Because 7 ate 9',\r\n 'Why did the witches team lose the baseball game? Their bats flew away',\r\n 'What starts with E and only has one letter in it? Envelope',\r\n 'Why did the can crusher quit his job? Because it was soda-pressing',\r\n 'Teacher: What do chickens give you? Kids: Meat! Teacher: What do pigs give you? Kids: Bacon! '\r\n 'Teacher: What does the fat cow give you? Kids: Homework! ',\r\n 'What happens to a frogs car when it breaks down? It gets toad away',\r\n 'Teacher: If I gave you 2 cats and another 2 cats and another 2, how many would you have?'\r\n 'Johnny: Seven.'\r\n 'Teacher: \"No, listen carefully... If I gave you two cats, and another two cats and another two, '\r\n 'how many would you have?\" '\r\n 'Johnny: Seven.'\r\n 'Teacher: Let me put it to you differently. If I gave you two apples, and another two apples and '\r\n 'another two, how many would you have? '\r\n 'Johnny: Six.'\r\n 'Teacher: Good. Now if I gave you two cats, and another two cats and another two, how many would '\r\n 'you '\r\n 'have? '\r\n 'Johnny: Seven!'\r\n 'Teacher: Johnny, where in the heck do you get seven from?!'\r\n 'Johnny: Because I already got a freaking cat!']\r\n embed = discord.Embed(title=\"**Joke**\",\r\n description=f'{random.choice(jokemsg)}',\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # dice\r\n @commands.command(aliases=['dice'])\r\n async def roll(self, ctx):\r\n responses = ['1',\r\n '2',\r\n '3',\r\n '4',\r\n '5',\r\n '6']\r\n dicemsg = f'Your dice landed on `{random.choice(responses)}!`'\r\n embed = discord.Embed(title=\"**Roll**\",\r\n description=('{}'.format(dicemsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # fact\r\n @commands.command(aliases=['interesting', 'funfact'])\r\n async def fact(self, ctx):\r\n responses = ['Some cats are actually allergic to humans',\r\n 'There is a fruit that tastes like chocolate pudding.',\r\n 'Competitive art used to be in the Olympics.',\r\n 'A chefs hat has exactly 100 pleats.',\r\n 'The majority of your brain is fat.',\r\n 'Oranges arent naturally occurring fruits.',\r\n 'Most wasabi in the U.S. is not really wasabi.',\r\n 'Stop signs used to be yellow.',\r\n 'Green Eggs and Ham started as a bet.',\r\n 'Too much water can kill you.',\r\n 'The hottest temperature ever recorded on Earth was 2 billion degrees kelvin.',\r\n 'High heels were originally worn by men.',\r\n 'You might be drinking water that is older than the solar system.',\r\n 'Queen Elizabeth II is a trained mechanic.',\r\n 'New York was briefly named \"New Orange.\"',\r\n 'Moonshiners used \"cow shoes\" to disguise their footprints during Prohibition.',\r\n 'It takes approx. 364 licks to get to the center of a Tootsie Pop.',\r\n 'Tree rings get wider during wet years.',\r\n 'The hottest inhabited place in the world is in Ethiopia.',\r\n 'Sea otters hold hands while they sleep.',\r\n 'Chainsaws, the horror-movie murder weapon of choice, were invented for aid in childbirth 😊',\r\n 'There is an island in Japan you can visit that is inhabited only by friendly bunnies.']\r\n factmsg = f'{random.choice(responses)}'\r\n embed = discord.Embed(title=\"**Fact**\",\r\n description=('{}'.format(factmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # 8ball\r\n @commands.command(aliases=['8ball', 'ask', 'curious', 'magic8ball'])\r\n async def eightball(self, ctx, *, question):\r\n responses = ['As I see it, yes.',\r\n 'Ask again later.',\r\n 'Better not tell you now.',\r\n 'Cannot predict now.',\r\n 'Concentrate and ask again.',\r\n 'Don’t count on it.',\r\n 'It is certain.',\r\n 'It is decidedly so.',\r\n 'Most likely.',\r\n 'My reply is no.',\r\n 'My sources say no.',\r\n 'Outlook not so good.',\r\n 'Outlook good.',\r\n 'Reply hazy, try again.',\r\n 'Signs point to yes.',\r\n 'Very doubtful.',\r\n 'Without a doubt.',\r\n 'Yes.',\r\n 'Yes – definitely.',\r\n 'You may rely on it.'\r\n 'Maybe.']\r\n ballmsg = f'Question: `{question}`\\nAnswer: `{random.choice(responses)}`'\r\n embed = discord.Embed(title=\"**Magic 8-Ball**\",\r\n description=('{}'.format(ballmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(FunCog(bot))\r\n print('FunCog is loaded')\r\n","sub_path":"Ice/Cogs/FunCog.py","file_name":"FunCog.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551873830","text":"import numpy as np\n\nUSER_FEATURES = 6\nARTICLE_FEATURES = 6\nFEATURES = ARTICLE_FEATURES\n\nALPHA = 0.2 # 1 + np.sqrt(np.log(2/DELTA)/2)\nprint(ALPHA)\n\ngarticles = None\n\nM = dict()\nMinvs = dict()\nb = dict()\n\nlast_chosen_article_id = -1\nlast_zt = None\n\n\ndef set_articles(articles):\n # articles - dictionary of (about 80) article id -> features (of len 6)\n global garticles\n garticles = articles\n for article_id in articles.keys():\n garticles[article_id] = np.asarray(articles[article_id])\n M[article_id] = np.eye(FEATURES)\n Minvs[article_id] = np.eye(FEATURES)\n b[article_id] = np.zeros(FEATURES)\n\n\ndef update(reward):\n # reward - int\n if reward == -1:\n return\n global last_chosen_article_id, last_zt\n assert last_chosen_article_id >= 0\n assert last_zt is not None\n article = last_chosen_article_id\n M[article] += np.outer(last_zt, last_zt)\n Minvs[article] = np.linalg.inv(M[article])\n b[article] += reward * last_zt\n\n last_zt = None\n last_chosen_article_id = -1\n\n\ndef recommend(timestamp, user_features, choices):\n # timestamp - int\n # user_features - list - user features, len 6\n # choices - list - ids of articles to choose from, len 20\n global garticles, last_zt\n zt = np.asarray(user_features)\n UCB_max = np.NINF\n UCB_argmax = -1\n for article_id in choices:\n Minv = Minvs[article_id]\n w = Minv.dot(b[article_id])\n UCB = w.dot(zt) + ALPHA * np.sqrt(zt.dot(Minv.dot(zt)))\n if UCB > UCB_max:\n last_zt = np.copy(zt)\n UCB_max = np.copy(UCB)\n UCB_argmax = article_id\n\n global last_chosen_article_id\n last_chosen_article_id = UCB_argmax\n return UCB_argmax\n","sub_path":"dm-project-4/policy_linucb.py","file_name":"policy_linucb.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"435257097","text":"# -*- coding: utf8 -*-\nfrom numpy import *\nimport json\n\ndef RecursiveSC(level, N, count, points):\n if level:\n for i in range(N[level]):\n RecursiveSC(level - 1, N, count, points)\n count[level] += 1\n count[level] = 0\n\n else:\n for i in range(N[0]):\n points.append(count[:])\n count[0] += 1\n count[0] = 0\n\ndef GenerateSC(dim, part_radius, N, scale, filename):\n try:\n f = open(filename, \"w+\")\n except Exception as e:\n return str(e)\n\n data = {}\n data[\"Dimensions\"] = dim\n data[\"SavedSteps\"] = 1\n data[\"ParticlesRadius\"] = part_radius\n\n basis = scale * eye(dim)\n\n lattice_points = []\n RecursiveSC(dim - 1, N, [0] * dim, lattice_points)\n data[\"ParticlesNumber\"] = len(lattice_points)\n lattice_points = array(lattice_points)\n\n data[\"Particles\"] = [[]]\n for p in lattice_points:\n data[\"Particles\"][0].append(list(sum(basis * p,axis=1)))\n\n particles = array(data[\"Particles\"][0])\n data[\"SystemSize\"] = [list(amin(particles, axis=0) - 0.001), list(amax(particles, axis=0) + 0.001)]\n\n f.write(json.dumps(data))\n f.close()\n return \"Saved to %s successfully.\" % filename\n\ndef GenerateFCC(N, part_radius, scale, filename):\n try:\n f = open(filename, \"w+\")\n except Exception as e:\n return str(e)\n\n data = {}\n data[\"Dimensions\"] = 3\n data[\"SavedSteps\"] = 1\n data[\"ParticlesRadius\"] = part_radius\n\n basis = scale * array([[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5]])\n\n lattice_points = []\n for i in range(N[0]):\n lattice_points.append((i, i, -i))\n lattice_points.append((i+1,i,-i))\n lattice_points.append((i,i+1,-i))\n lattice_points.append((i,i,-i+1))\n for j in range(N[1]):\n lattice_points.append((i+j, i-j, -i+j))\n lattice_points.append((i+j+1,i-j,j-i))\n lattice_points.append((i+j,i-j+1,j-i))\n lattice_points.append((i+j,i-j,j-i+1))\n for k in range(N[2]):\n lattice_points.append((i+j-k, i-j+k, -i+j+k))\n lattice_points.append((i+j-k+1,i-j+k,j-i+k))\n lattice_points.append((i+j-k,i-j+k+1,j-i+k))\n lattice_points.append((i+j-k,i-j+k,j-i+k+1))\n\n lattice_points = list(set(lattice_points))\n data[\"ParticlesNumber\"] = len(lattice_points)\n lattice_points = array(lattice_points)\n\n data[\"Particles\"] = [[]]\n for p in lattice_points:\n data[\"Particles\"][0].append(list(sum(basis * p, axis=1)))\n\n particles = array(data[\"Particles\"][0])\n data[\"SystemSize\"] = [list(amin(particles, axis=0) - (part_radius + 0.001)), list(amax(particles, axis=0) + (part_radius + 0.001))]\n print(data[\"SystemSize\"])\n print(prod(array(data[\"SystemSize\"][1])-array(data[\"SystemSize\"][0])))\n print(data[\"ParticlesNumber\"])\n print(data[\"ParticlesNumber\"]/prod(array(data[\"SystemSize\"][1])-array(data[\"SystemSize\"][0])))\n\n f.write(json.dumps(data))\n f.close()\n return \"Saved to %s successfully.\" % filename\n\n#GenerateFCC([4]*3, 0.5, 1.47, \"data/lattice/fcc-bb.json\")\nGenerateFCC([1]*3, 0.5, 1.47*6, \"data/lattice/fcc-ultralow.json\")\n#GenerateFCC([20,10,1], 0.5, 2.3, \"data/lattice/fcc-nvt.json\")\n","sub_path":"Week7/python/lattice.py","file_name":"lattice.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"49091932","text":"import re\n\ndef word_frequency(text):\n return {\"hello\": 1}\n\n# open file sample.txt and read in the words\n# orig_text = str(\"\"\"Project Gutenberg's The Hound of the Baskervilles, by A. Conan Doyle\n#\n# This eBook is for the use of anyone anywhere at no cost and with\n# almost no restrictions whatsoever. You may copy it, give it away or\n# re-use it under the terms of the Project Gutenberg License included\n# with this eBook or online at www.gutenberg.org\n#\n#\n# Title: The Hound of the Baskervilles\n#\n# Author: A. Conan Doyle\n#\n# Posting Date: December 8, 2008 [EBook #2852]\n# Release Date: October, 2001\n#\n# Language: English\n#\n#\n# \"\"\"\n\nwith open('sample.txt') as g:\n orig_text = g.read()\n\n# split text into individual words\n#word_list= orig_text.lower().split()\nword_list = re.sub(r'[0-9,.!-?]', \"\", orig_text).lower().split()\n\n# make word list into another list with unique words\nunique_words = []\nignore_words = [\"the\", \"of\", \"a\", \"to\", \"i\", \"that\", \"and\", \"is\"]\nfor word in word_list:\n if word in ignore_words:\n continue\n if word not in unique_words:\n unique_words.append(word)\n\n\n#make a list of tuples w/(unique word: count)\n\nword_counts = []\n\nfor unique in unique_words:\n count = 0\n for word in word_list:\n if word == unique:\n count += 1\n word_counts.append((unique, count))\n\n#print(word_counts)\n# sort tuples from highest to lowest\nsorted_word_counts= sorted(word_counts, key=lambda s: s[1], reverse=True)\n\n#print(unique_words)\nprint(sorted_word_counts)[:20]\n\n#take top 20 words and output their count(s) to screen\n","sub_path":"word_frequency_hard.py","file_name":"word_frequency_hard.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"42004866","text":"import datetime\n\n\ndef main():\n\n filename = open(\"../inputs/day4_input.txt\")\n output_file = open(\"../inputs/day4_input_sorted.txt\", \"a\")\n dates_list = []\n events_dict = {}\n\n while True:\n line = filename.readline()\n if line == \"\":\n break\n else:\n minute = (line.split(\" \")[0] + \" \" + line.split(\" \")[1]).strip(\"[\").strip(\"]\")\n event = \" \".join(line.split(\" \")[2:]).rstrip()\n\n dates_list.append(minute)\n events_dict[minute] = event\n\n output_list = sorted(dates_list, key=lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M'))\n\n for i in output_list:\n minute_event = events_dict[i]\n write_event = i + \" \" + minute_event + \"\\n\"\n output_file.write(write_event)\n\n output_file.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"solutions/day4a_write_file.py","file_name":"day4a_write_file.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"234959213","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator\nimport pymysql.cursors\nimport folium\nfrom django.http.response import JsonResponse\n\n# Connect to the database\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='1234',\n db='mydb',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n\n# Create your views here.\ndef get_weather_skyscrapers(id, results_weather):\n for result in results_weather:\n if id == result['bldg_id']:\n return result\n \n result = list()\n return result\n \n\ndef skyscrapers_home(request):\n page = request.GET.get('page', '1')\n\n with connection.cursor() as cursor:\n # 지도에 마커 모두 출력하기\n # sql 실행\n # sql = f\"\"\"SELECT * FROM skyscrapers, bldg_images\n # WHERE skyscrapers.id=1 AND skyscrapers.id = bldg_images.bldg_id\"\"\"\n sql = \"SELECT * FROM skyscrapers\"\n cursor.execute(sql)\n result = cursor.fetchall()\n result_copy = result\n # print(result)\n\n sql = \"SELECT * FROM bldg_weather\"\n cursor.execute(sql)\n results_weather = cursor.fetchall()\n\n\t # 지도 위도, 경도 얻기\n lat_long = [result[0]['x_coord'], result[0]['y_coord']]\n m = folium.Map(lat_long, zoom_start=2)\n for countmap in range(1, 100):\n # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain')\n # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행\n # sudo pip3 install git+https://github.com/python-visualization/branca.git@master\n\n # text = \"#\"+str(countmap)+\" \"+result[countmap]['building_name']+\"
    \"+result[countmap]['city_name']+\"
    \"\\\n # +\"\" \n # 팝업창 내용 넣기\n text = \"#\"+str(countmap)+\" \"+result[countmap]['building_name']+\"
    \"+result[countmap]['city_name']+\"\"\n weather = get_weather_skyscrapers(result[countmap]['id'], results_weather)\n if weather:\n text = text + \"
    main_weather :
    \" + weather['main_weather']\n text = text + \"
    temperature :
    \" + weather['temperature_C']\n text = text + \"
    humidity : \" + weather['humidity']\n lat_long = [result[countmap]['x_coord'], result[countmap]['y_coord']]\n popText = folium.Html(text+str(lat_long), script=True)\n popup = folium.Popup(popText, max_width=2650)\n folium.CircleMarker(lat_long, radius=10, popup=popup, color='#3186cc',fill_color='#3186cc',).add_to(m)\n\n # folium HTML 얻기\n m = m._repr_html_() #updated\n\n # sql = \"SELECT id, ranking, building_name, city_name, country, height_m FROM skyscrapers\"\n # cursor.execute(sql)\n result = result_copy\n\n paginator = Paginator(result, 10)\n page_obj = paginator.get_page(page)\n\n # context = {'data':page_obj, 'bldg_map': m}\n\n # return render(request, 'home.html', context)\n # return render(request, 'home.html')\n context = {'bldg_data':page_obj, 'bldg_map': m} \n return context\n\ndef home(request):\n context = skyscrapers_home(request)\n\n return render(request, 'home.html', context)\n\ndef maplist(request):\n context = skyscrapers_home(request)\n\n return render(request, 'buildings/bldg_maplist.html', context)\n\n\n\ndef bldg_list(request):\n page = request.GET.get('page', '1')\n\n # ranking', 'building_name', 'city_name', 'country', 'height_m', 'height_ft',\n # 'floor', 'completion_year', 'material', 'category', 'thumbnail',\n # 'x_coord', 'y_coord', 'reg_date'\n\n with connection.cursor() as cursor:\n sql = \"SELECT id, ranking, building_name, city_name, country, height_m FROM skyscrapers\"\n cursor.execute(sql)\n result = cursor.fetchall()\n paginator = Paginator(result, 10)\n page_obj = paginator.get_page(page)\n print(result)\n\n context = {'data':page_obj}\n\n return render(request, 'buildings/bldg_list.html', context)\n\ndef bldg_detail(request, id):\n with connection.cursor() as cursor:\n sql = f\"\"\"SELECT * FROM skyscrapers, bldg_images\n WHERE skyscrapers.id={id} AND skyscrapers.id = bldg_images.bldg_id\"\"\"\n cursor.execute(sql)\n result = cursor.fetchall()\n print(result)\n\n lat_long = [result[0]['x_coord'], result[0]['y_coord']]\n m = folium.Map(lat_long, zoom_start=14)\n # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain')\n\n # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행\n # sudo pip3 install git+https://github.com/python-visualization/branca.git@master\n text = \"\"+result[0]['building_name']+\"
    \"+result[0]['city_name']+\"
    \"\n\n popText = folium.Html(text+str(lat_long), script=True)\n popup = folium.Popup(popText, max_width=2650)\n folium.Marker(location=lat_long, popup=popup).add_to(m)\n m=m._repr_html_() #updated\n\n context = {'data':result, 'bldg_map': m}\n\n return render(request, 'buildings/bldg_detail.html', context)\n\n\n","sub_path":"website/buildings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"124606308","text":"from django.conf.urls import url, include\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.posts, name='posts'),\n url(r'(?P[0-9]+)/$', views.post_detail, name='post_detail'),\n url(r'^new/$', views.new_post, name='new_post'),\n url(r'login/$', views.user_login, name='login'),\n url(r'logout/$', views.user_logout, name='logout'),\n url(r'register/$', views.user_register, name='register'),\n # url(r'user_login/', views.user_login, name='user_login'),\n]\n","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"111320691","text":"from app import db, app\n\ndef db_commit(model):\n if model:\n db.session.add(model)\n try:\n db.session.commit()\n except Exception as e:\n app.logger.error('[db_commit] Error: %s' % e)\n db.session.rollback()\n\ndef db_delete(model):\n if model:\n app.logger.info('[db_delete] Delete: %s' % model.key)\n db.session.delete(model)\n try:\n db.session.commit()\n except Exception as e:\n app.logger.error('[db_delete] Error: %s' % e)\n db.session.rollback()","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"381049998","text":"from subprocess import call\nfrom pprint import pprint\nimport json\n\n\n\n\ndef getnumresults():\n with open('words/output.json') as data_file: \n data = json.load(data_file)\n \n return data[\"total\"]\n \ndef conductsearch(word):\n begindate = \"19810101\"\n enddate = \"20080101\"\n fields= \"date\"; #\"title,date\"\n key = \"insert_api_key_here\"\n\n #format it as a query\n word = word.replace(\" \", \"+\")\n\n #output to json file\n url = 'http://api.nytimes.com/svc/search/v1/article?format=json&query=%22'+word+'%22&fields='+fields+'&begin_date=' + begindate + '&end_date=' + enddate+ '&api-key=' + key\n #print url\n command = \"curl '\" + url + \"' | python -mjson.tool > words/output.json\"\n call(command, shell=True)\n\ndef readinwords(filename):\n words = []\n \n f = open(\"words/\" + filename)\n lines = f.readlines()\n f.close()\n for line in lines:\n line = line.strip()\n words.append(line)\n \n return words\n \ndef filldic(filename, replacementword):\n dic = {}\n \n words = readinwords(filename)\n for word in words:\n word = word.replace(\"_\", replacementword)\n conductsearch(word)\n numresults = getnumresults()\n dic[word] = numresults\n \n return dic\n\ndef main():\n arrofdics = []\n \n files =[\"activewords.txt\", \"passivewords.txt\"]\n replacementwords = [\"abused\", \"assaulted\", \"molested\", \"raped\"]\n \n for replacementword in replacementwords:\n for file in files:\n arrofdics.append(filldic(file, replacementword))\n\n f = open('words/dictionaries.json','w')\n json.dump(arrofdics, f)\n f.close()\n \n \n \n \n \n \nmain()","sub_path":"collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"625899906","text":"from bridges.color import *\nimport math\n\n\nclass Symbol:\n \"\"\"\n @brief This is the base class for constructing simple shapes in BRIDGES.\n \n This is an abstract class for deriving a\n number of Symbol shape objects, for use in a SymbolCollection.\n Symbols correspond to a simplified subset of SVG paths\n and shapes for custom visual representations in BRIDGES.\n \n Users will typically one of the subclasses of this object for creating shapes\n \n Currently shapes supported are rectangle, circle, polygon, polyline and label; each shape\n has a name, location (x, y) and appropriate geometric and non-geometric attributes\n \n @author David Burlinson, Kalpathi Subramanian\n @date 12/24/18, 7/12/19\n \"\"\"\n\n _ids = 0 #id for this symbol. Class level so each object has unique id\n\n def __init__(self):\n \"\"\"\n Constructor for a Symbol\n \"\"\"\n self._identifier = str(Symbol._ids)\n self._label = \"\"\n self._fill_color = Color(\"white\")\n self._stroke_color = Color(\"white\")\n self._opacity = 1.0\n self._stroke_width = 1.0\n self._stroke_dash = 1\n self._location_y = 0.0\n self._location_x = 0.0\n self._shape_type = \"circle\"\n Symbol._ids += 1\n\n @property\n def label(self) -> str:\n \"\"\"\n Getter for symbol label\n Returns:\n str : the label of this shape\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label: str) -> None:\n \"\"\"\n Setter for symbol label\n Args:\n label: to be set\n Returns:\n str\n \"\"\"\n self._label = label\n\n @property\n def identifier(self) -> str:\n \"\"\"\n Getter for the symbols identifier\n Returns:\n str\n \"\"\"\n return self._identifier\n\n @property\n def fill_color(self) -> Color:\n \"\"\"\n Getter for the fill color\n Returns:\n Color : the current fill color of this symbol\n \"\"\"\n return self._fill_color\n\n @fill_color.setter\n def fill_color(self, *args, **kwargs) -> None:\n \"\"\"\n Setter for the fill color\n Args:\n color: the color to set for the fill\n Returns:\n None\n \"\"\"\n self._fill_color = Color(*args, **kwargs)\n\n @property\n def stroke_color(self) -> Color:\n \"\"\"\n Getter for the stroke color\n Returns:\n the stroke (boundary) color of the shape\n \"\"\"\n return self._stroke_color\n\n @stroke_color.setter\n def stroke_color(self, *args, **kwargs) -> None:\n \"\"\"\n @brief Setter for the stroke color\n Args:\n color: the stroke (boundary) color to set\n Returns:\n None\n \"\"\"\n self._stroke_color = Color(*args, **kwargs)\n\n @property\n def stroke_width(self) -> float:\n \"\"\"\n Getter for the stroke width\n Returns:\n float : the stroke width of the shape\n \"\"\"\n return self._stroke_width\n\n @stroke_width.setter\n def stroke_width(self, width: float) -> None:\n \"\"\"\n Setter for the stroke width\n Args:\n width: the stroke width to set\n Returns:\n None\n Raises:\n value error\n \"\"\"\n if width <= 0.0 or width > 10.0:\n raise ValueError(\"Stroke width must be between 0 and 10\")\n else:\n self._stroke_width = width\n\n @property\n def opacity(self) -> float:\n \"\"\"\n Getter for opacity\n Returns:\n float : opacity of the shape\n \"\"\"\n return self._opacity\n\n @opacity.setter\n def opacity(self, o: float):\n \"\"\"\n Setter for opacity\n Args:\n o: the opacity value to set (must be in 0-1.0 range) \n Returns:\n None\n Raises: value error\n \"\"\"\n if o <= 0.0 or o > 1.0:\n raise ValueError(\"Opacity must be between 0.0 and 1.0\")\n else:\n self._opacity = o\n\n @property\n def stroke_dash(self) -> float:\n \"\"\"\n Getter for stroke_dash\n Returns:\n float : the stroke texture\n \"\"\"\n return self._stroke_dash\n\n @stroke_dash.setter\n def stroke_dash(self, dash: float):\n \"\"\"\n Setter for stroke_dash\n Args:\n dash: the stroke_dash value to set (0-10 range)\n Returns:\n None\n Raises: value error\n \"\"\"\n if dash < 0 or dash > 10:\n raise ValueError(\"Dash must be between 0 and 10 (inclusive)\")\n else:\n self._stroke_dash = dash\n\n @property\n def shape_type(self):\n \"\"\"\n Get the shape type (string)\n Returns:\n shape name (string)\n \"\"\"\n return self._shape_type\n\n @shape_type.setter\n def shape_type(self, shape):\n \"\"\"\n Set the shape type (string)\n Args:\n shape: shape name to set\n \"\"\"\n self._shape_type = shape\n\n def set_location(self, x: float, y: float) -> None:\n \"\"\"\n Setter for the location of the center of the symbol\n Args:\n x: x location \n y: y location\n Returns:\n None\n Raises:\n Value error\n \"\"\"\n if x > float('-inf') and x < float('inf') and y > float('-inf') and y < float('inf'):\n self._location_x = x\n self._location_y = y\n else:\n raise ValueError(\"Coordinates must be real numbers\")\n\n def get_location(self) -> list:\n \"\"\"\n Getter for the location of a symbol\n Returns:\n list : the x and y coordinates of the shape's current location\n \"\"\"\n return [self._location_x, self._location_y]\n\n def get_dimensions(self) -> list:\n \"\"\"\n Getter for the dimensions\n Returns:\n list : the bounding box of this shape (xmin, xmax, ymin, ymax)\n \"\"\"\n return [0.0, 0.0, 0.0, 0.0]\n\n def translate_point(self, pt, tx, ty):\n \"\"\"\n Translate a point by tx, ty along X and Y respectively\n Args:\n pt: 2D point to be translated\n tx: translation factor in X\n ty: translation factor in Y\n \"\"\"\n pt[0] += tx\n pt[1] += ty\n return pt\n\n def scale_point(self, pt, sx, sy):\n \"\"\"\n Scale a point by sx, sy along X and Y respectively\n Args:\n pt: 2D point to be scaled\n sx: scale factor in X\n sy: scale factor in Y\n \"\"\"\n pt[0] *= sx\n pt[1] *= sy\n return pt\n\n def rotate_point(self, pt, angle):\n \"\"\"\n Rotate a point by 'angle' (2D rotation)\n Args:\n pt: 2D point to be rotated\n angle: rotation angle\n \"\"\"\n angle_r = math.radians(angle)\n c = math.cos(angle_r)\n s = math.sin(angle_r)\n\n tmp = [pt[0] * c - pt[1] * s, pt[0] * s + pt[1] * c]\n pt[0] = float(tmp[0])\n pt[1] = float(tmp[1])\n return pt\n\n def get_json_representation(self) -> dict:\n \"\"\"\n Get the json representation of the Symbol class\n Returns:\n dict : the JSON representation\n \"\"\"\n ds = {\n # \"fill\": [self.fill_color.red, self.fill_color.green, self.fill_color.blue, self.fill_color.alpha],\n # \"opacity\": self.opacity,\n # \"stroke\": [self.stroke_color.red, self.stroke_color.green, self.stroke_color.blue, self.stroke_color.alpha],\n # \"stroke-width\": self.stroke_width,\n # \"stroke-dasharray\": self.stroke_dash,\n # \"location\": {\n # \"x\": self._location_x,\n # \"y\": self._location_y\n # }\n }\n if self.fill_color != Color(\"white\"):\n ds['fill'] = [self.fill_color.red, self.fill_color.green, self.fill_color.blue, self.fill_color.alpha]\n if self.opacity != 1.0:\n ds['opacity'] = self.opacity\n if self.stroke_color != Color(\"white\"):\n ds['stroke'] = [self.stroke_color.red, self.stroke_color.green, self.stroke_color.blue, self.stroke_color.alpha]\n if self.stroke_width != 1.0:\n ds['stroke-width'] = self.stroke_width\n if self.stroke_dash != 1:\n ds['stoke-dasharray'] = self.stroke_dash\n if self._location_x != 0.0 or self._location_y != 0.0:\n ds['location'] = {\n \"x\": self._location_x,\n \"y\": self._location_y\n }\n return ds\n\n","sub_path":"bridges/symbol.py","file_name":"symbol.py","file_ext":"py","file_size_in_byte":8639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"342273104","text":"import csv\nimport pygal\nfrom datetime import datetime\n\n\ndate = []\nhigh_temperature = []\nlow_temperature = []\n\n# read from file, extract date and high temperature\nfilename = 'sitka_weather_07-2014.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n reader.__next__() # skip the first line\n for record in reader:\n date.append(datetime.strptime(record[0], '%Y-%m-%d'))\n high_temperature.append(float(record[1]))\n low_temperature.append(float(record[3]))\n\n# plot a histogram\nhist = pygal.Bar()\nhist.x_labels = date # add label to the bars\nhist.add('High Temperature', high_temperature) # add data to it\nhist.add('Low Temperature', low_temperature)\nhist.render_to_file('high_low_temperature.svg')\n","sub_path":"weather_plot/highs_lows.py","file_name":"highs_lows.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"592040303","text":"import numpy as np \r\nimport pandas as pd\r\nimport statsmodels.api as sm\r\nimport statsmodels.formula.api as smf\r\n\r\n'''\r\nUnless you want to pip install all the libraries/modules\r\nyou should use Jupyter for this code\r\n'''\r\n\r\n# You probably have a different path\r\nallData = pd.read_csv('./AllData.csv')\r\n\r\n# Risk Free\r\nrf = 0.15\r\n\r\n# Risk free subtracted from stocks\r\nmonthly_rf = allData.drop('S&P500', axis=1).copy() - rf\r\n\r\n# Linear Regression\r\n\r\n# Risk free subtracted from \r\n# S&P500 returns used as market returns \r\nmarket_rf = allData['S&P500'] - rf\r\n\r\n# smf.OLS doesn't provide a constant automatically\r\n# so we have to add it using this function\r\nmarket_rf = sm.add_constant(market_rf)\r\n\r\n# creates a dictionary of fits where key is the stock name\r\n# and value is the fit\r\nresults = {x : smf.OLS(monthly_rf[x], market_rf).fit() \r\n\t\t\t\t\t\t\t\t\tfor x in monthly_rf}\r\n\r\n# look at all the information\r\n# run through the list of stock names\r\nfor x in monthly_rf:\r\n\tprint(results[x].summary())\r\n\r\n# Prints the Alpha and Beta estimates for each stock\r\nfor x in monthly_rf:\r\n\tprint('Stock: %s Alpha: %8.4f Beta: %8.4f' % (x, results[x].params[0], results[x].params[1]))\r\n\r\n# creates a list of underperforming stocks\r\nunder_performers = [key for key in results.keys()\r\n\t\t\t\t\t\t\t\t\tif results[key].tvalues[0] < -1.697]\r\n\r\n# Prints out the underperformers\r\nfor x in under_performers:\r\n\tprint('%s' % x)\r\n\r\n# creates a list of overperforming stocks\r\nover_performers = [key for key in results.keys()\r\n\t\t\t\t\t\t\t\t\tif results[key].tvalues[0] > 1.697]\r\n\r\n# Prints out the overperformers\r\nfor x in over_performers:\r\n\tprint('%s' % x)\r\n\r\n# Sample market return\r\nmarket_return = allData['S&P500'].mean()\r\n\r\n# Sample return from 30 DJI stocks\r\nmonthly_return = allData.drop('S&P500', axis=1).copy().mean()\r\n\r\n# Sample covariance from 30 DJI stocks\r\nmonthly_covariance = allData.drop('S&P500', axis=1).copy().cov()\r\n\r\n# calculates returns through CAPM\r\nreturns = [(rf + results[x].params[1]*(market_return - rf)) for x in results]\r\n\r\n# Array of 1s\r\nu = np.array([1]*len(monthly_return))\r\n\r\n# Calculates market weights with CAPM returns\r\nmarket_weights = np.dot(np.linalg.inv(monthly_covariance),\r\n\treturns - rf*u)/(np.dot(np.dot(u.T, np.linalg.inv(monthly_covariance)),\r\n\t\treturns - rf*u))\r\n\r\n# Calculates market weights with sample returns\r\nog_market_weights = np.dot(np.linalg.inv(monthly_covariance),\r\n\tmonthly_return - rf*u)/(np.dot(np.dot(u.T, np.linalg.inv(monthly_covariance)),\r\n\t\tmonthly_return - rf*u))","sub_path":"Homework2/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"368859193","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"file:///C:/Users/twin5/Desktop/DojoAssignments/Python/Selenium/Exercise%20Files/CH02/html_code_02.html\")\n\nlogin_form_absolute = driver.find_element_by_xpath('/html/body/form[1]')\nlogin_form_relative = driver.find_element_by_xpath('//form[1]')\nlogin_form_id = driver.find_element_by_xpath('//form[@id=\"loginForm\"]')\nprint(\"My login form is:\")\nprint(login_form_absolute)\nprint(login_form_relative)\nprint(login_form_id)\n\ndriver.close()\n","sub_path":"004-FindingByXPath.py","file_name":"004-FindingByXPath.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29395303","text":"\"\"\"\nModule containing abstract classes for web services\n\"\"\"\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom app.abstract.services.database_service.config import DatabaseConnectionConfig\nfrom app.abstract.services.database_service.db_connection import DatabaseConnection\nfrom app.abstract.services.web_service.config import WebServiceRouterConfig\n\n\ndef configure_rest_server(app: FastAPI, router_configs: List[WebServiceRouterConfig],\n db_configs: List[DatabaseConnectionConfig]):\n \"\"\"Configures the fast api rest api but does not start uvicorn\"\"\"\n\n @app.on_event('startup')\n def open_database_connections():\n DatabaseConnection.open_connections(db_configs=db_configs)\n\n @app.on_event('shutdown')\n def close_database_connections():\n DatabaseConnection.close_all_connections()\n\n app.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n for router_config in router_configs:\n app.include_router(router=router_config.router,\n prefix=f\"/{router_config.tag}\",\n tags=[router_config.tag])\n\n\ndef run_graphql_server(self, *args, **kwargs):\n raise NotImplementedError(\"run_as_graphql not implemented\")\n","sub_path":"app/abstract/web_servers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"15889854","text":"from opt2q.utils.utils import _list_the_errors, MissingParametersErrors, UnsupportedSimulator, \\\n DuplicateParameterError, UnsupportedSimulatorError, IncompatibleFormatWarning, \\\n incompatible_format_warning, _is_vector_like, _convert_vector_like_to_list, _convert_vector_like_to_set, \\\n CupSodaNotInstalledWarning, profile, parse_column_names, DaeSimulatorNotInstalledWarning\n\n__all__ = ['_list_the_errors',\n 'MissingParametersErrors',\n 'UnsupportedSimulator',\n 'DuplicateParameterError',\n 'UnsupportedSimulatorError',\n 'IncompatibleFormatWarning',\n 'CupSodaNotInstalledWarning',\n 'DaeSimulatorNotInstalledWarning',\n 'incompatible_format_warning',\n '_is_vector_like',\n '_convert_vector_like_to_list',\n '_convert_vector_like_to_set',\n 'parse_column_names',\n 'profile']\n","sub_path":"opt2q/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"432412052","text":"'''\n1. 리스트 생성\n2016년 11월 영화 예매 순위 기준 top3는 다음과 같습니다. 영화 제목을 movie_rank 이름의 리스트에 저장해보세요. (순위 정보는 저장하지 않습니다.)\n\n순위\t영화\n1\t닥터 스트레인지\n2\t스플릿\n3\t럭키\n'''\nmovie_rank = ['닥터 스트레인지', '스플릿', '럭키']\n\n'''\n2. movie_rank 리스트에 \"배트맨\"을 추가하라.\n'''\nmovie_rank.append(\"배트맨\")\nprint(movie_rank)\n\n'''\n3. movie_rank 리스트에는 아래와 같이 네 개의 영화 제목이 바인딩되어 있다. \"슈퍼맨\"을 \"닥터 스트레인지\"와 \"스플릿\" 사이에 추가하라.\nmovie_rank = ['닥터 스트레인지', '스플릿', '럭키', '배트맨']\n'''\nmovie_rank.insert(1,\"슈퍼맨\")\nprint(movie_rank)\n\n'''\n4. movie_rank 리스트에서 '럭키'를 삭제하라.\nmovie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '럭키', '배트맨']\n'''\nmovie_rank.remove('럭키')\nprint(movie_rank)\n\n'''\n5. movie_rank 리스트에서 '스플릿' 과 '배트맨'을 를 삭제하라.\nmovie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '배트맨']\n'''\nmovie_rank.pop()\nmovie_rank.pop()\nprint(movie_rank)\n\n'''\n6. price 변수에는 날짜와 종가 정보가 저장돼 있다. 날짜 정보를 제외하고 가격 정보만을 출력하라. (힌트 : 슬라이싱)\n\nprice = ['20180728', 100, 130, 140, 150, 160, 170]\n출력 예시:\n[100, 130, 140, 150, 160, 170]\n'''\nprice = ['20180728', 100, 130, 140, 150, 160, 170]\nprint(price[1:])\n\n'''\n7.슬라이싱을 사용해서 홀수만 출력하라.\n\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n'''\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(nums[0::2])\n\n'''\n8.슬라이싱을 사용해서 리스트의 숫자를 �� 방향으로 출력하라.\n\nnums = [1, 2, 3, 4, 5]\n실행 예:\n[5, 4, 3, 2, 1]\n'''\nnums = [1, 2, 3, 4, 5]\nprint(nums[::-1])\n\n'''\n9.interest 리스트에는 아래의 데이터가 저장되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver']\ninterest 리스트를 사용하여 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자 Naver\n'''\n\ninterest = ['삼성전자', 'LG전자', 'Naver']\nprint(interest[0]+interest[-1])\n\n'''\n\n10. interest 리스트에는 아래의 데이터가 바인딩되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\ninterest 리스트를 사용하여 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자 LG전자 Naver SK하이닉스 미래에셋대우\n'''\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\nprint(interest[1:])\n\n'''\n\n11. interest 리스트에는 아래의 데이터가 바인딩되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\njoin() 메서드를 사용해서 interest 리스트를 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자\nLG전자\nNaver\nSK하이닉스\n미래에셋대우\n'''\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\nprint('\\n'.join(interest))\n\n'''\n12. 리스트에 있는 값을 오름차순으로 정렬하세요.\ndata = [2, 4, 3, 1, 5, 10, 9]\n\n'''\n\ndata = [2, 4, 3, 1, 5, 10, 9]\ndata.sort()\nprint(data)\n\n'''\n13. \n홍길동 씨의 주민등록번호는 881120-1068234이다. 홍길동 씨의 주민등록번호를 연월일(YYYYMMDD) 부분과 그 뒤의 숫자 부분으로 나누어 출력해 보자.\n※ 문자열 슬라이싱 기법을 사용해 보자.\n'''\nnum = '881120-1068234'\nn = num[:6]\nm = num[7:]\nprint('주민등록번호 앞자리는 {0}이고, 뒷자리는 {1}입니다.'.format(n,m))\n\n'''\n14\n(1,2,3) 튜플에 값 4를 추가하여 (1,2,3,4)를 만들어 출력해 보자.\n※ 더하기(+)를 사용해 보자.\n'''\nk = (1,2,3)\nk=k+(4,)\nprint(k)\n\n'''\n15\n다음과 같은 딕셔너리 a가 있다.\na = dict()\na\n{}\n다음 중 오류가 발생하는 경우를 고르고, 그 이유를 설명해 보자.\na['name'] = 'python'\na[('a',)] = 'python'\na[[1]] = 'python'\na[250] = 'python'\n\n'''\na = dict()\n# 리스트로 이루어진 key는 사용할 수 없다. 3번\n\n'''\n16\n딕셔너리 a에서 'B'에 해당되는 값을 추출해 보자.\n a = {'A':90, 'B':80, 'C':70}\n※ 딕셔너리의 pop 함수를 사용해 보자.\n'''\na = {'A':90, 'B':80, 'C':70}\na1=a.pop('B')\nprint(a1)\n","sub_path":"python/Practice_file/practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"185469454","text":"from custom_exceptions import *\n\nclass ParkingLot:\n \"\"\"A class used to represent the Parking Lot object\n\n This parking lot object can have many parked cars inside it.\n\n Attributes\n ----------\n vehicles : [str]\n Array of car objects parked in their respective slots\n\n Methods\n ----------\n add(car)\n Add a car to the parking lot\n get_first_empty()\n Get the nearest empty slot to park a new car\n leave(slot)\n Let go of the car from the parking spot\n status()\n Show the slots, registration numbers and colour of the cars\n currently parked in the parking lot.\n registration_numbers_for_cars_with_colour(colour)\n Show the registration numbers of cars who's colour matches the\n parameter.\n slot_numbers_for_cars_with_colour(colour)\n Show the slot numbers of cars who's colour matches the parameter.\n slot_number_for_car_with_registration_number(registration_no)\n Show the slot number of the car with the given registration number.\n \"\"\"\n\n # Remember to +1 the index of vehicles while displaying the data\n # and -1 the index of vehicles while storing the data\n vehicles = None\n\n def __init__(self, size):\n \"\"\"Default Constructor\"\"\"\n if (size is None) or (not isinstance(size, int)) or (size < 1):\n raise ParkingLotInvalidInputs\n\n self.vehicles = [None] * size\n print('Created a parking lot with {} slots'.format(size))\n\n def add(self, car):\n \"\"\"Add a car object to the parking lot\n\n This method is internally called by `create_and_park()` and should\n be avoided being called directly.\n\n Parameters\n ----------\n car : Car\n The car object to be parked\n\n Returns\n ----------\n slot : int\n The slot allocated after parking\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingLotFull\n If there is no space left in the parking lot for an extra car.\n \"\"\"\n\n slot = self.get_first_empty()\n if slot > len(self.vehicles) - 1:\n raise ParkingLotFull('Sorry, parking lot is full')\n\n self.vehicles[slot] = car\n return slot, 'Allocated slot number: {}'.format(slot + 1)\n\n def get_first_empty(self):\n \"\"\"Get the nearest empty slot to park a new car\n\n Internal method. Not be called from outside.\n\n Returns\n ----------\n slot : int\n the next free slot available for parking\n\n Raises\n ----------\n ParkingLotUninitialized\n \"\"\"\n\n i = 0\n\n if self is None or self.vehicles is None:\n raise ParkingLotUninitialized\n\n for car in self.vehicles:\n if car is None:\n return i\n\n i = i + 1\n\n return i\n\n def leave(self, slot):\n \"\"\"Let go of the car from the parking spot\n\n The car object is now discarded and the spot on parking lot is\n marked empty for the new car.\n\n Returns\n ----------\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingSlotEmpty\n If for some serious reason `vehicles` attribute of parking lot\n doesn't exist.\n \"\"\"\n\n if self.vehicles[slot] is None:\n raise ParkingSlotEmpty\n\n car_left = self.vehicles[slot]\n self.vehicles[slot] = None\n car_left.slot = None\n return 'Slot number ' + str(slot + 1) + ' is free'\n\n def status(self):\n \"\"\"Show the summary of the parking lot with car details\"\"\"\n\n messages = []\n messages.append('{0:<10} {1:<20} {2:<10}'.format('Slot No.',\n 'Registration No',\n 'Colour'))\n for car in self.vehicles:\n if car is None:\n continue\n\n message = '{0:<10} {1:<20} {2:<10}'.format(car.slot + 1,\n car.registration_no,\n car.colour)\n messages.append(message)\n\n return messages\n\n def registration_numbers_for_cars_with_colour(self, colour):\n \"\"\"Show registration numbers for cars of the specified colour\"\"\"\n\n output = []\n for car in self.vehicles:\n if car.colour == colour:\n output.append(car.registration_no)\n\n return output\n\n def slot_numbers_for_cars_with_colour(self, colour):\n \"\"\"Show the slot numbers for cars of the specified colour\"\"\"\n output = []\n for car in self.vehicles:\n if car.colour == colour:\n output.append(str(car.slot + 1))\n\n return output\n\n def slot_number_for_registration_number(self, registration_no):\n \"\"\"Show the slot number for car with a registration number\"\"\"\n for car in self.vehicles:\n if car.registration_no == registration_no:\n return str(car.slot + 1)\n\n return 'Not found'\n\n def __str__(self):\n \"\"\"Readable string for debugging\"\"\"\n return ', '.join(self.vehicles)\n","sub_path":"src/parking_lot.py","file_name":"parking_lot.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"322434903","text":"\"\"\"\nHarvard Applied MAth 207\nHomework 10\nProblem 1\n\nMichael S. Emanuel\nWed Nov 14 10:50:44 2018\n\"\"\"\n\nimport numpy as np\nfrom numpy import exp\n\n# *************************************************************************************************\n# 1.1. Implement a Metropolis sampler to produce sample guesses from 500 individuals, \n# with the λ values, λ=0.2,0.5,1.0 . What are the top five possible guesses?\n# *************************************************************************************************\n\n# *************************************************************************************************\ndef hamming_dist(x: np.ndarray, y: np.ndarray):\n \"\"\"Compute the Hamming Distance between two arrays\"\"\"\n return np.sum(x != y)\n\n\ndef proposal(x: np.ndarray):\n \"\"\"Generate a proposal guess by transposing a random pair of elements in x.\"\"\"\n # Initialize a copy of x\n y = x.copy()\n # Draw a random pair in [0, n)\n n: int = len(x)\n i, j = np.random.choice(n, 2, replace=False)\n # Swap the ith and jth elements\n xi, xj = x[i], x[j]\n y[i], y[j] = xj, xi\n # Return modified guess\n return y\n\n\ndef prob(x: np.ndarray, y: np.ndarray, lam: float):\n \"\"\"The unscaled probability of guess theta given omega and the lambda parameter (inverse temperature).\"\"\"\n return exp(-lam * hamming_dist(x, y))\n\n\ndef metropolis(num_samp: int, lam: float, x_init: np.ndarray):\n \"\"\"Metropolis Sampler for this problem\"\"\"\n # The correct order\n x_best: np.ndarray = np.array([1,2,3,4,5], dtype=np.int8)\n # Get the length n of each guess\n n: int = len(x_best)\n # Initialize array to store the samples\n samples: np.ndarray = np.empty((num_samp, n), dtype=np.int8)\n # Initialize x_prev\n x_prev: np.ndarray = x_init\n # Draw num_samp samples using Metrpolis algorithm\n # Adapted from example code in Lecture 16, p. 6\n for i in range(num_samp):\n # The proposed new point\n x_star: np.ndarray = proposal(x_prev)\n # Compare probability of the propsed point to the current one\n p_star: float = prob(x_star, x_best, lam)\n p_prev: float = prob(x_prev, x_best, lam)\n # Probability ratio\n pdf_ratio: float = p_star / p_prev\n # Randomly accept or reject the step based on pdf_ratio\n if np.random.uniform() < min(1.0, pdf_ratio):\n # Accept the step\n samples[i] = x_star\n x_prev = x_star\n else:\n # Reject the step; duplicate x_prev as a sample\n samples[i] = x_prev\n return samples\n\n\ndef top_five_guesses(samples: np.ndarray):\n \"\"\"Given an Nx5 array of guesses, find the top five.\"\"\"\n # Count the frequency of the distinct guesses\n guesses, counts = np.unique(samples, return_counts=True, axis=0)\n # Sort the guesses by their frequency\n gc = list(zip(guesses, counts))\n gc.sort(key = lambda x: x[1], reverse=True)\n # Return the top five guesses and their frequency\n gc = gc[0:5]\n guesses = [x[0] for x in gc]\n counts = [x[1] for x in gc]\n return guesses, counts\n\n\n# *************************************************************************************************\n# Set random seed\nnp.random.seed(42)\n# Number of desired samples \nnum_samp = 5000\n# Set burn-in\nburn_in = 100\n# Pick a random starting point\nx_init = np.random.choice(5, size=5, replace=False).astype(np.int8) + 1\n# Range of lambdas to test\nlams = (0.2, 0.5, 1.0)\n# Table for the results\nsample_tbl = dict()\ntop_five_guesses_tbl = dict()\n# Test each lambda in turn\nfor lam in lams:\n # Run a burn-in period of 100 samples\n discarded_samples = metropolis(burn_in, lam, x_init)\n # Run the metropolis sampler on the current value of x\n x_init = discarded_samples[-1, :]\n samples = metropolis(num_samp, lam, x_init)\n # Save samples in the table\n sample_tbl[lam] = samples\n # Get the top 5 guesses and their frequencies\n guesses, counts = top_five_guesses(samples)\n # Save top five guesses to table\n top_five_guesses_tbl[lam] = top_five_guesses(samples)\n\n# Display results\nfor lam in lams:\n guesses, counts = top_five_guesses_tbl[lam]\n print(f'\\nLambda = {lam:0.1f}. Top five guesses and frequency:')\n for i in range(5):\n print(f'{guesses[i]}, {counts[i]:3} ({counts[i]/num_samp*100:0.2f})%.')\n\n\n\n# *************************************************************************************************\n# 1.2. Compute the probability that *The Shawshank Redemption* is ranked as the top movie (ranked number 1) \n# by the Metropolis algorithm sampler. Compare the resulting probabilities for the various λ values.\n# *************************************************************************************************\n\n# Set large number of samples\nnum_samp_big = 50000\n# Table for the results\nsample_tbl_big = dict()\n# Test each lambda in turn\nfor lam in lams:\n # Run the metropolis sampler on the current value of x\n x_init = samples[-1, :]\n samples = metropolis(num_samp_big, lam, x_init)\n # Save samples in the table\n sample_tbl_big[lam] = samples\n\n# Iterate through the lambdas\nprint('')\nfor lam in lams:\n # Extract the samples\n samples = sample_tbl_big[lam]\n # Count how often \"Shawshank\" is rated first\n shawshank_wins = np.sum(samples[:, 0]==1)\n shawshank_win_prob = shawshank_wins / num_samp_big\n # Report results\n print(f'Lambda = {lam:0.1f}. Probability Shawshank ranked first = {shawshank_win_prob*100:0.2f}%.')\n\n\n\n# *************************************************************************************************\ndef test_hamming():\n omega = np.array([1,2,3,4,5])\n theta = np.array([2,3,5,4,1])\n d = hamming_dist(omega, theta)\n assert d == 4\n # print(f'Hamming Distance between omega=(1,2,3,4,5) and theta=(2,3,5,4,1) is {d}.')\n print(f'Test Hamming Distance:\\n*** PASS ***')\n\ntest_hamming()\n","sub_path":"hw10/metropolis_sampler.py","file_name":"metropolis_sampler.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"217822204","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 2 18:23:23 2020\r\n\r\n@author: Jacky\r\n\"\"\"\r\n\r\n#code forked and tweaked from https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py\r\n#to extend, just add more people into the known_people folder\r\n#\r\n#work_folder=\"C:\\\\Users\\\\User\\\\Documents\\\\UiPath\\\\IPA_CA_v0\\\\\"\r\nwork_folder=\".\\\\image\\\\\"\r\nimport face_recognition\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport glob\r\nimport time\r\nimport re\r\n\r\n# Get a reference to webcam #0 (the default one)\r\nvideo_capture = cv2.VideoCapture(0)\r\n\r\n# Increase the resolution of the video\r\ndef make_1080p():\r\n video_capture.set(3, 1920)\r\n video_capture.set(4, 1080)\r\n\r\nmake_1080p()\r\n\r\n#make array of sample pictures with encodings\r\nknown_face_encodings = []\r\nknown_face_names = []\r\ndirname = os.path.dirname(__file__)\r\npath = os.path.join(dirname, 'known_people/')\r\n\r\n#make an array of all the saved jpg files' paths\r\nlist_of_files = [f for f in glob.glob(path+'*.jpg')]\r\n#find number of known faces\r\nnumber_files = len(list_of_files)\r\n\r\nnames = list_of_files.copy()\r\n\r\nfor i in range(number_files):\r\n globals()['image_{}'.format(i)] = face_recognition.load_image_file(list_of_files[i])\r\n globals()['image_encoding_{}'.format(i)] = face_recognition.face_encodings(globals()['image_{}'.format(i)])[0]\r\n known_face_encodings.append(globals()['image_encoding_{}'.format(i)])\r\n\r\n # Create array of known names\r\n names[i] = names[i].replace(\"known_people\\\\\", \"\").replace(\".jpg\", \"\") \r\n known_face_names.append(names[i])\r\n\r\n# Initialize some variables\r\nface_locations = []\r\nface_encodings = []\r\nface_names = []\r\nprocess_this_frame = True\r\nattendance = {}\r\noutfile=open(\"image_login.csv\",\"w+\")\r\noutfile.write(\"Name,Time\\n\")\r\nfor name in known_face_names:\r\n outfile.write(\"%s,99999\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")) )\r\noutfile.close()\r\nrecognizedFace=[]\r\nwhile True:\r\n if not video_capture.isOpened():\r\n if debug==1: print('Unable to load camera.')\r\n time.sleep(5)\r\n pass\r\n \r\n # Grab a single frame of video\r\n ret, frame = video_capture.read()\r\n print(ret)\r\n #frame=cv2.imread(\"known_people\\\\save_NUS.jpg\")\r\n if ret!=True: continue\r\n\r\n # Resize frame of video to 1/4 size for faster face recognition processing\r\n small_frame = frame # cv2.resize(frame, (120,120), fx=0.25, fy=0.25)\r\n #small_frame=cv2.resize(frame, (120,120 ), interpolation = cv2.INTER_CUBIC)\r\n \r\n # Resize frame of video to 3 times the size for larger display\r\n frame = frame #cv2.resize(frame, (240,240), fx=3, fy=3) \r\n cv2.imwrite(work_folder+\"save_frame.jpg\",frame)\r\n #frame =cv2.resize(frame, (180,180), interpolation = cv2.INTER_CUBIC) \r\n\r\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\r\n rgb_small_frame = small_frame[:, :, ::-1]\r\n\r\n # Only process every other frame of video to save time\r\n if process_this_frame:\r\n # Find all the faces and face encodings in the current frame of video\r\n face_locations = face_recognition.face_locations(rgb_small_frame, number_of_times_to_upsample=2, model='hog') # For GPU, use model='cnn'\r\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations, num_jitters=2)\r\n print(face_encodings)\r\n\r\n face_names = []\r\n for face_encoding in face_encodings:\r\n # See if the face is a match for the known face(s)\r\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.6) # Lower is more strict, default = 0.6\r\n name = \"Unknown\"\r\n\r\n # # If a match was found in known_face_encodings, just use the first one.\r\n # if True in matches:\r\n # first_match_index = matches.index(True)\r\n # name = known_face_names[first_match_index]\r\n\r\n # Or instead, use the known face with the smallest distance to the new face\r\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\r\n best_match_index = np.argmin(face_distances)\r\n if matches[best_match_index]:\r\n name = known_face_names[best_match_index]\r\n #print(name)\r\n\r\n face_names.append(name)\r\n \r\n process_this_frame = not process_this_frame\r\n\r\n\r\n # Display the results\r\n for (top, right, bottom, left), name in zip(face_locations, face_names):\r\n # Scale back up face locations since the frame we detected in was scaled to 1/12 size\r\n print(\"999\",name,attendance)\r\n \r\n top *= 12\r\n right *= 12\r\n bottom *= 12\r\n left *= 12\r\n\r\n # Draw a box around the face\r\n \r\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\r\n if name!=\"\" and name not in attendance:\r\n name2=re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")\r\n\r\n datestamp=int( time.time() )\r\n attendance[name]=datestamp\r\n cv2.imwrite(work_folder+\"%s_%s.jpg\" % (datestamp,name2), frame)\r\n if name2 not in recognizedFace:\r\n recognizedFace.append(name2)\r\n cv2.imwrite(work_folder+\"%s.jpg\" % name2, frame)\r\n \r\n \r\n outfile2=open(\"image_login.csv\",\"w+\")\r\n \r\n \r\n outfile2.write(\"Name,Time\\n\")\r\n\r\n for name in known_face_names:\r\n if name in attendance:\r\n outfile2.write(\"%s,%s\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\"),attendance[name]) )\r\n else:\r\n outfile2.write(\"%s,99999\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")) )\r\n outfile2.close()\r\n\r\n\r\n # Draw a label with a name below the face\r\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 5.0, (0, 0, 0), 5)\r\n\r\n # Display the resulting image\r\n cv2.imshow('Video', frame)\r\n #refresh after 12 hrs\r\n for name in attendance:\r\n if attendance[name] 250:\n await client.delete_message(message) \n return\n if is_duplicate(message):\n await client.delete_message(message)\n return\n await sleepMode(message.author,config.SlowmodeTime)\n \n await client.process_commands(message) #Makes sure to process the command\n\ninitial_extensions = [\n 'cmds.ClientOwnerOnly',\n 'cmds.ModeratorOnly',\n 'cmds.UserAccessible'\n]\n\nif __name__ == '__main__': #Loads commands/extensions\n for extension in initial_extensions:\n try:\n client.load_extension(extension)\n print(\"Loaded extension\")\n except Exception as e:\n print(f'Failed to load extension {extension}.', file=sys.stderr)\n traceback.print_exc()\n\nclient.loop.create_task(post_tweets())\nclient.run(os.environ.get('TOKEN'))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"464385969","text":"import bson, jwt\n\nfrom flask import (\n Blueprint,\n url_for,\n request,\n session\n)\n\nfrom helper import _send_list_JSON, client\n\nuserRouter = Blueprint('userRouter', __name__)\n\ndb = client['totlist']\n\n@userRouter.route('/api/auth', methods=['POST'])\ndef login():\n jsonbody = request.get_json()\n document = dict()\n try:\n document[\"id\"] = str(db.users.find_one(jsonbody)[\"_id\"])\n session[\"WebAPIToken\"] = document[\"id\"]\n encoded = jwt.encode(document, 'secret', algorithm='HS256')\n\n return _send_list_JSON({\"WebAPIToken\": encoded})\n except:\n return _send_list_JSON({\"error\": \"Login into system please\"}, 403)\n\n@userRouter.route('/api/auth/out', methods=['GET'])\ndef get_token():\n session.pop(\"WebAPIToken\", None)\n\n return _send_list_JSON({\"message\": \"User logged out\"})\n\n@userRouter.route('/api/user/add', methods=['POST'])\ndef add_new_user():\n jsonbody = request.get_json()\n if (\"username\" in jsonbody) and (\"password\" in jsonbody):\n result = db.users.insert_one(jsonbody)\n\n document = dict()\n document = db.users.find_one({\"_id\": result.inserted_id})\n document[\"id\"] = str(document[\"_id\"])\n del document[\"_id\"]\n\n return _send_list_JSON(document, 201)\n","sub_path":"routes/userapp.py","file_name":"userapp.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"414555136","text":"from django.shortcuts import render, redirect\nfrom part.forms import sukucadangForm\nfrom part.models import Sukucadang\n\n# from Sukucadang\n\ndef emp(request): \n if request.method == \"POST\": \n form = sukucadangForm(request.POST) \n if form.is_valid(): \n try: \n form.save() \n return redirect('/show') \n except: \n pass \n else: \n form = sukucadangForm() \n return render(request,'index.html',{'form':form}) \ndef show(request):\n datas = Sukucadang.objects.all()\n return render(request, \"show.html\", {\n 'datas': datas\n })\ndef edit(request, id):\n data = Sukucadang.objects.get(id=id)\n return render(request, 'edit.html', {\n 'data': data\n })\ndef update(request, id):\n data = Sukucadang.objects.get(id=id)\n form = sukucadangForm(request.POST, instance = data)\n if form.is_valid(): \n form.save() \n return redirect(\"/show\") \n return render(request, 'edit.html', {\n 'data': data\n }) \ndef destroy(request, id):\n data = Sukucadang.objects.get(id=id)\n data.delete()\n return redirect(\"/show\")\n\n# menu view\n\ndef menu(request):\n data = Sukucadang.objects.all()\n return render(request, \"menu.html\", {\n 'data': data\n })\n\n","sub_path":"Novice/04-03/sparepart/part/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"115893243","text":"class TripDetailsPage:\n\n def __init__(self, driver):\n self.driver = driver\n self._trip_details_form = None\n self._route_information = None\n self._header_navigation = None\n\n @property\n def trip_details_form(self):\n if self._trip_details_form is None:\n from trip_details_form import TripDetailsForm\n self._trip_details_form = TripDetailsForm(self.driver)\n return self._trip_details_form\n\n @property\n def route_information(self):\n if self._route_information is None:\n from route_information import RouteInformation\n self._route_information = RouteInformation(self.driver)\n return self._route_information\n\n @property\n def header_navigation(self):\n if self._header_navigation is None:\n from header_navigation import HeaderNavigation\n self._header_navigation = HeaderNavigation(self.driver)\n return self._header_navigation\n\n def open(self, url):\n self.driver.get(url)\n","sub_path":"trip_details_page.py","file_name":"trip_details_page.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"485950031","text":"from ecdsa import SigningKey, VerifyingKey, NIST192p\nimport ecdsa\nimport hashlib\n\nfrom cilantro.wallets import Wallet\n\nclass BasicWallet(Wallet):\n def __init__(self, s=None):\n if s == None:\n self.s, self.v = BasicWallet.new()\n else:\n self.s, self.v = BasicWallet.format_to_keys(s)\n self.s, self.v = BasicWallet.keys_to_format(self.s, self.v)\n\n @staticmethod\n def generate_keys():\n # generates a tuple keypair\n s = SigningKey.generate()\n v = s.get_verifying_key()\n return s, v\n\n @staticmethod\n def keys_to_format(s, v):\n # turns binary data into desired format\n s = s.to_string()\n v = v.to_string()\n return s.hex(), v.hex()\n\n @staticmethod\n def format_to_keys(s):\n # returns the human readable format to bytes for processing\n s = bytes.fromhex(s)\n\n # and into the library specific object\n s = SigningKey.from_string(s, curve=NIST192p)\n v = s.get_verifying_key()\n return s, v\n\n @staticmethod\n def new():\n # interface to creating a new wallet\n s, v = generate_keys()\n return keys_to_format(s, v)\n\n\n @staticmethod\n def sign(s, msg):\n (s, v) = format_to_keys(s)\n signed_msg = s.sign(msg, hashfunc=hashlib.sha1, sigencode=ecdsa.util.sigencode_der)\n return signed_msg.hex()\n\n @staticmethod\n def verify(v, msg, sig):\n v = bytes.fromhex(v)\n v = VerifyingKey.from_string(v, curve=NIST192p)\n try:\n return v.verify(bytes.fromhex(sig), msg, hashfunc=hashlib.sha1, sigdecode=ecdsa.util.sigdecode_der)\n except:\n return False","sub_path":"cilantro/wallets/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"448549632","text":"# when stop, put pause as status, and pick up them when starting again\nimport os, logging, datetime, copy, json\nfrom app import consts, errors\n\nlog = logging.getLogger(__name__)\n\n\nclass InfoFile(object):\n def __init__(self, fn, data, mongo, app=None, TESTFLAG=None):\n self.QUEUES = consts.WORKERQUEUES\n if mongo:\n self.error = errors.VainamoinenError(mongo, app=app, TESTFLAG=TESTFLAG)\n self.mongo = mongo\n self.fn = fn\n self.data = data\n self.rawfiles = []\n self.status = 'new'\n\n# def load_metadata_from_file(self):\n# self.data = self.load_json( os.path.join(self.location, self.fn) )\n# if self.data:\n# self.mark_file('processing')\n# log.debug('Infofile JSON ok, moving to tmp dir')\n# self.move_infofile(self.TMP_INFOFILE_DIR, self.fn)\n# else: # bad JSON in infofile, mark as invalid file\n# self.status = 'invalid'\n# self.move_infofile(self.location, 'invalid_{0}'.format(self.fn) )\n\n def load_metadata_from_dbrecord(self, dbrecord):\n self.location = consts.TMP_INFOFILE_DIR\n self.fn = dbrecord['infofilename']\n self.status = dbrecord['status']\n self.data = self.load_json(os.path.join(self.location, self.fn)) \n \n def load_json(self, fn):\n # FIXME Metadatahandler should fix this, or utility method\n try:\n with open(fn) as fp:\n return json.load(fp)\n except ValueError:\n log.error('JSON could not be parsed from file {0}'.format(fn), exc_info=True)\n self.error.glitch('glitch error', 'JSON unparsable in infofile.')\n return False\n \n def write_rawfiles_to_db(self):\n # FIXME should be metadatahandler method.\n for rawfile in self.rawfiles:\n log.info('Writing rawfile {0} to DB'.format(rawfile.metadata['filename']))\n self.mongo.run('insert', 'files', rawfile.metadata)\n\n def process_files(self):\n # add queue variables to files\n for fn in self.data['files']:\n if 'extension' in self.data['files'][fn]:\n fullfn = fn + self.data['files'][fn]['extension']\n else:\n fullfn = fn\n self.rawfiles.append( RawFile(fullfn, self.fn, self.data['metadata'],\n self.data['files'][fn], self.QUEUES, consts.UPLOAD_DIR) )\n log.info('Checking if raw files specified in infofile {0} exist on '\n 'server'.format(self.fn))\n self.nonexisting = []\n for rf in self.rawfiles:\n if not rf.check_exist():\n self.nonexisting.append(rf.fn)\n \n def report_nonexisting(self):\n if self.nonexisting:\n self.mark_file('waiting')\n msg = \"\"\"Your infofile {0} contained references to files that do not exist.\n Processing of will be paused for {1} days in order for the files to\n be generated. After this your file will be\n deleted.\"\"\".format(self.fn, consts.RAWFILES_TIMELIMIT)\n log.info('Infofile with non-existing file(s) encountered. Marking waiting.')\n #self.error.user(self.fn, '\\n'.join(self.nonexisting), 'Files do not exist', msg)\n else:\n log.info('All raw files found.')\n\n def mark_file(self, status):\n self.status = status\n self.data['general_info']['status'] = status\n\n\nclass RawFile(object):\n def __init__(self, fn, infofn, meta, outliermeta, queues, updir):\n self.metadata = copy.deepcopy(meta)\n self.starttime = datetime.datetime.now()\n self.fn = fn\n self.upload_dir = updir\n for x in outliermeta:\n self.metadata[x] = outliermeta[x]\n self.metadata['filename'] = fn\n self.metadata['infofilename'] = infofn\n for queue in queues:\n self.metadata[queue] = None\n\n def check_exist(self):\n return os.path.exists(os.path.join(self.upload_dir, self.fn) )\n \n \n","sub_path":"app/infofile.py","file_name":"infofile.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471440681","text":"# ОДЗ: если максимальных элементов несколько, то удаляем все нулевые элементы после первого.\n# Например, [1, 5, 1, 0, 1, 5, 0 ]. Первое встреченное число 5 - это максимальный\n# После него все удаляем. Второе число 5 - тоже максимальный элемент, но условие удаления элементов уже выполнено\n# для первого максимального элемента.\n\n# l = []\n# l = [1, 0, 1, 1, 1] # [1, 1, 1, 1]\n# l = [1, 1, 1, 1, 0] # [1, 1, 1, 1]\n# l = [3, 4, 5, 0, 0, 0, 5] # [3, 4, 5, 5]\nl = [3, 4, 5, 0, 0, 0, 5, 6] # [3, 4, 5, 0, 0, 0, 5, 6]\n\ndef remove_zero_elements(l):\n\n try:\n max_element = max(l)\n except ValueError: # l is an empty sequence.\n return l\n\n try:\n max_element_position = l.index(max_element)\n except ValueError:\n return l\n\n left_list_including_max_element = l[:max_element_position+1]\n right_list = l[max_element_position+1:]\n\n cleared_right_list = [x for x in right_list if x != 0]\n\n united_list = left_list_including_max_element + cleared_right_list\n\n return united_list\n\n\nprint(remove_zero_elements(l))\n","sub_path":"1d.py","file_name":"1d.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308810540","text":"#Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\r\n\r\nnum1=int(input('Digite o primeiro numero '))\r\nnum2=int(input('Digite o primeiro numero '))\r\nnum3=int(input('Digite o primeiro numero '))\r\n\r\n#verificando quem é menor\r\nmenor = num1\r\nif num2< num1 and num2 < num3:\r\n menor=num2\r\nif num3< num1 and num3 < num2:\r\n menor=num3\r\n\r\n#Verificando o maior\r\nmaior = num1\r\nif num2> num1 and num2 > num3:\r\n maior=num2\r\nif num3> num1 and num3 > num2:\r\n maior=num3\r\n\r\nprint('O num maior e menor são repectivamente {} e {}'.format(menor,maior))","sub_path":"ex033_MaiorEMenorValor.py","file_name":"ex033_MaiorEMenorValor.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"576945142","text":"#Team Choosers\n\n#Imports random library\nfrom random import choice\n\n\nplayers = []\nteamA = []\nteamB = []\nexitThis = 0\ncommand = 0\n\n#Functions\ndef choosePlayers(action):\n #Input Players\n done = 0\n while done == 0:\n\n if action == 'add':\n player = input(\"player(\" + str(len(players) + 1) + \")(Type 'done' when done): \")\n elif action == 'remove':\n player = input(\"Player to remove(Type 'done' when done):\")\n \n if player.lower() == 'done':\n done = 1 \n elif player == \"\":\n print(\"Please type in a name.\") \n else:\n if action == 'add':\n players.append(player) \n elif action == 'remove':\n players.remove(player)\n\ndef randomizeTeams():\n teamA = []\n teamB = []\n #Creates teams in loop\n while len(players) > 0:\n\n playerA = choice(players)\n teamA.append(playerA)\n players.remove(playerA)\n\n playerB = choice(players)\n teamB.append(playerB)\n players.remove(playerB)\n\n #Shows teams\n print(\"Team A: \" + str(teamA))\n print(\"Team B: \" + str(teamB))\n\n for player in teamA:\n players.append(player)\n\n for player in teamB:\n players.append(player)\n\n teamA = []\n teamB = []\n\ndef removePlayers():\n done = 0\n while done == 0:\n\n player = input(\"Player to remove (Type 'done' when done): \")\n\n if player.lower() == 'done':\n done = 1 \n elif player == \"\":\n print(\"Please type in a name.\") \n else:\n players.remove(player)\n \nwhile choice != 3:\n \n #initial Prompt\n command = input(\"(1) add, (2) randomize teams, (3) exit, (4) remove, (5) Show players: \")\n\n if command == \"1\":\n choosePlayers('add')\n elif command == \"2\":\n randomizeTeams()\n elif command == \"3\":\n exit()\n elif command == \"4\":\n choosePlayers('remove')\n elif command == \"5\":\n print(players)\n\n\n \n \n\n \n\n\n \n","sub_path":"Website Projects/team_chooser.py","file_name":"team_chooser.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"92290549","text":"import re\n\nfrom explanations.colorize_tex import (\n colorize_citations,\n colorize_equation_tokens,\n colorize_equations,\n)\nfrom explanations.types import TokenWithOrigin\n\nCOLOR_PATTERN = (\n r\"\\\\llap{\"\n + r\"\\\\pdfcolorstack0 push {[0-9.]+ [0-9.]+ [0-9.]+ rg [0-9.]+ [0-9.]+ [0-9.]+ RG}}\"\n + r\"(.*?)\"\n + r\"\\\\llap{\"\n + r\"\\\\pdfcolorstack0 pop}\"\n)\n\n\ndef test_color_citations():\n tex = \"word.~\\\\cite{source1,source2}\"\n colorized, citations = next(colorize_citations(tex))\n assert colorized.startswith(\"word.~\")\n print(colorized)\n matches = re.findall(COLOR_PATTERN, colorized)\n assert matches[0] == \"\\\\cite{source1,source2}\"\n assert len(citations) == 1\n assert citations[0].keys == [\"source1\", \"source2\"]\n\n\ndef test_disable_hyperref_colors():\n tex = \"\\n\".join(\n [\"\\\\usepackage[colorlinks=true,citecolor=blue]{hyperref}\", \"\\\\cite{source}\"]\n )\n colorized, _ = next(colorize_citations(tex))\n assert \"colorlinks=false\" in colorized\n\n\ndef test_color_equations():\n tex = \"$eq1$ and $eq2$\"\n colorized, equations = next(colorize_equations(tex))\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 2\n assert matches[0] == \"eq1\"\n assert matches[1] == \"eq2\"\n\n equation0_info = equations[0]\n assert isinstance(equation0_info.hue, float)\n assert equation0_info.tex == \"eq1\"\n assert equation0_info.i == 0\n\n\ndef test_color_equation_in_argument():\n tex = \"\\\\caption{$eq1$}\"\n colorized, _ = next(colorize_equations(tex))\n assert colorized.startswith(\"\\\\caption\")\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 1\n assert matches[0] == \"eq1\"\n\n\ndef test_color_tokens():\n file_contents = {\"file\": \"$ignore$ $x + y$\"}\n tokens = [\n TokenWithOrigin(\n tex_path=\"file\", equation_index=1, token_index=0, start=0, end=1, text=\"x\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=1, token_index=1, start=4, end=5, text=\"y\"\n ),\n ]\n colorized_files, _ = next(colorize_equation_tokens(file_contents, tokens))\n colorized = colorized_files[\"file\"]\n assert colorized.startswith(\"$ignore$\")\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 2\n assert matches[0] == \"x\"\n assert matches[1] == \"y\"\n\n\ndef test_color_subscripts():\n file_contents = {\"file\": \"$x_i x^i x\\\\sp1 x\\\\sb1$\"}\n tokens = [\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=0, start=2, end=3, text=\"i\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=1, start=6, end=7, text=\"i\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=2, start=12, end=13, text=\"1\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=3, start=18, end=19, text=\"1\"\n ),\n ]\n colorized_files, _ = next(colorize_equation_tokens(file_contents, tokens))\n colorized = colorized_files[\"file\"]\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 4\n # Subscript and superscript commands must also be wrapped in the coloring commands\n assert matches[0] == \"_i\"\n assert matches[1] == \"^i\"\n assert matches[2] == \"\\\\sp1\"\n assert matches[3] == \"\\\\sb1\"\n","sub_path":"data-processing/tests/test_colorize_tex.py","file_name":"test_colorize_tex.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"76880464","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n**renameUdimToMariNames.py**\n\n**Platform:**\n\tWindows.\n\n**Description:**\n\tCombines UVs shells siblings images.\n\n**Others:**\n\tTODO: Refactor _get'Nuke'Node using \\*\\*kwargs for optional arguments.\n\"\"\"\n\n#**********************************************************************************************************************\n#***\tExternal imports.\n#**********************************************************************************************************************\nimport glob\nimport inspect\nimport os\nimport optparse\nimport sys\nimport re\n\n#**********************************************************************************************************************\n#***\tInternal imports.\n#**********************************************************************************************************************\n\n#**********************************************************************************************************************\n#***\tModule attributes.\n#**********************************************************************************************************************\n__author__ = \"Thomas Mansencal\"\n__copyright__ = \"Copyright (C) 2010 - 2012 - Thomas Mansencal\"\n__license__ = \"GPL V3.0 - http://www.gnu.org/licenses/\"\n__maintainer__ = \"Thomas Mansencal\"\n__email__ = \"thomas.mansencal@gmail.com\"\n__status__ = \"Production\"\n\n__all__ = [\"UDIM_FILTER\" , \"getMariPatchNumberFromUdim\", \"getCommandLineParametersParser\", \"renameUdimToMariNames\"]\n\nUDIM_FILTER = \"u\\d+_v\\d+\"\n\n#**********************************************************************************************************************\n#***\tModule classes and definitions.\n#**********************************************************************************************************************\ndef getMariPatchNumberFromUdim(udim):\n\t\"\"\"\n\tThis definition gets Mari patch number from Udim.\n\n\t:param udim: Udim to convert. ( String )\n\t:return: Mari patch. ( Integer )\n\t\"\"\"\n\n\tu, v = (int(value[1:]) for value in udim.split(\"_\"))\n\treturn 1000 + u + 1 + v *10\n\ndef getCommandLineParametersParser():\n\t\"\"\"\n\tThis definition returns the command line parameters parser.\n\n\t:return: Parser. ( Parser )\n\t\"\"\"\n\n\tparser = optparse.OptionParser(formatter=optparse.IndentedHelpFormatter (indent_increment=2, max_help_position=8, width=128, short_first=1), add_help_option=None)\n\n\tparser.add_option(\"-h\", \"--help\", action=\"help\", help=\"'Display this help message and exit.'\")\n\tparser.add_option(\"-f\", \"--filesExtensions\", action=\"store\", type=\"string\", dest=\"filesExtensions\", default=\"psd\", help=\"'Files extensions to rename'.\")\n\tparser.add_option(\"-s\", \"--sourceDirectory\", action=\"store\", type=\"string\", dest=\"sourceDirectory\", default=os.getcwd(), help=\"'Source directory.\")\n\tparser.add_option(\"-r\", \"--renamePrefix\", action=\"store\", type=\"string\", dest=\"renamePrefix\", help=\"'Rename prefix.\")\n\t\n\treturn parser\n\ndef renameUdimToMariNames(parameters, arguments):\n\t\"\"\"\n\tThis definition renames Udim matched files to Mari patch number files.\n\n\t:param udim: Udim to convert. ( String )\n\t:param parameters: Command line parameters. ( Object )\n\t:param arguments: Command line arguments. ( Object )\n\t:return: Definition success. ( Boolean )\n\t\"\"\"\n\n\tif os.path.exists(parameters.sourceDirectory):\n\t\tfiles = glob.glob(\"{0}/*{1}\".format(parameters.sourceDirectory, parameters.filesExtensions))\n\t\tfor file in files:\n\t\t\tsearch = re.search(r\"({0})\".format(UDIM_FILTER), file)\n\t\t\tif not search:\n\t\t\t\tcontinue\n\t\t\tpatchNumber = getMariPatchNumberFromUdim(search.group(0))\n\t\t\tif parameters.renamePrefix:\n\t\t\t\tname = \"{0}{1}.{2}\".format(parameters.renamePrefix, str(patchNumber), parameters.filesExtensions)\n\t\t\telse:\n\t\t\t\tname = re.sub(r\"({0})\".format(UDIM_FILTER), str(patchNumber), file)\n\t\t\t\n\t\t\tprint(\"'{0}' | Rename '{1}' file to '{2}'.\".format(inspect.getmodulename(__file__),file, name))\n\t\t\tos.rename(file, name)\n\t\treturn True\n\n#**********************************************************************************************************************\n#*** Launcher.\n#**********************************************************************************************************************\nif __name__ == \"__main__\":\n\tparameters, arguments = getCommandLineParametersParser().parse_args(sys.argv)\n\trenameUdimToMariNames(parameters, arguments)\n","sub_path":"src/others/renameUdimToMariNames.py","file_name":"renameUdimToMariNames.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"295287643","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\ndef show_images(images, opts, name=None):\n images = np.reshape(images, [images.shape[0], -1]) # images reshape to (batch_size, D)\n sqrtn = int(np.ceil(np.sqrt(images.shape[0])))\n\n fig = plt.figure(figsize=(sqrtn, sqrtn))\n gs = gridspec.GridSpec(sqrtn, sqrtn)\n gs.update(wspace=0.05, hspace=0.05)\n\n for i, img in enumerate(images):\n ax = plt.subplot(gs[i])\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_aspect('equal')\n plt.imshow(img.reshape([opts.image_shape, opts.image_shape, opts.channel]))\n if name != None:\n plt.savefig(name)\n return\n\ndef preprocess_img(x):\n return 2 * x - 1.0\n\ndef deprocess_img(x):\n return (x + 1.0) / 2.0\n\ndef rel_error(x,y):\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef black_out(image, width=3):\n '''\n Blacks out everything in the image except for the top left quadrant\n :param image: Numpy array\n :return:\n '''\n\n h = image.shape[1]\n w = image.shape[2] // 2\n\n mask = np.zeros(image.shape, np.float32)\n\n mask[:, 0: h, w - width: w + width, :] = image[:, 0: h, w - width: w + width, :]\n\n return mask\n\ndef plotter(env_name, num_episodes, rewards_list, ylim):\n '''\n Used to plot the average over time\n :param env_name:\n :param num_episodes:\n :param rewards_list:\n :param ylim:\n :return:\n '''\n x = np.arange(0, num_episodes)\n y = np.asarray(rewards_list)\n plt.plot(x, y)\n plt.ylim(top=ylim + 10)\n plt.xlabel(\"Number of Episodes\")\n plt.ylabel(\"Avg Rewards Last 100 Episodes\")\n plt.title(\"Rewards Over Time For %s\" %env_name)\n plt.savefig(\"progress.png\")\n plt.close()\n\ndef raw_score_plotter(scores):\n '''\n used to plot the raw score\n :param scores:\n :return:\n '''\n\n plt.plot(np.arange(len(scores)), scores)\n plt.ylabel('Train Loss')\n plt.xlabel('Number of Iterations')\n plt.title(\"Loss Over Time\")\n plt.savefig(\"Train_Loss.png\")\n plt.close()\n","sub_path":"Car_Mask_TF/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"129596527","text":"from operator import itemgetter\n\n\ndef fcfs(data):\n process = {}\n process['table'] = data\n process['gantt'] = []\n\n n = len(data)\n time = 0\n left = n\n average_tat = 0\n average_wt = 0\n\n process['table'] = sorted(process['table'], key=itemgetter('at'))\n x = process['table']\n time = x[0]['at']\n proc = 0 #current process\n temp={}\n\n for i in range(n):\n temp = {}\n temp['no'] = i + 1\n if time >= x[i]['at']:\n temp['start'] = time\n else:\n time = x[i]['at']\n temp['start'] = time\n time += x[i]['bt']\n temp['stop'] = time\n process['gantt'].append(temp)\n \n return process\n","sub_path":"src/fcfs.py","file_name":"fcfs.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"31192788","text":"from flask import Flask, render_template, g, redirect, request, url_for\r\nfrom werkzeug import secure_filename\r\nfrom secure import adminpassword\r\nimport sqlite3\r\nimport os\r\nimport re\r\nfrom random import randint\r\napp = Flask(__name__)\r\n\r\ndatabase = '/crassis/crassis-site/comics'\r\nupload = '/crassis/crassis-site/static/images'\r\n\r\napp.config['UPLOAD_FOLDER'] = upload\r\n\r\n@app.before_request\r\ndef before_request():\r\n\tg.db = sqlite3.connect(database)\r\n\r\n@app.teardown_request\r\ndef teardown_request(exception):\r\n\tif hasattr(g, 'db'):\r\n\t\tg.db.close()\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n\tcomic = g.db.execute(\"SELECT * FROM comics ORDER BY id DESC LIMIT 1\").fetchone()\r\n\tlatest = g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0]\r\n\treturn render_template(\"index.html\", comic=comic, latest=latest)\r\n\r\n@app.route(\"/\")\r\ndef comic(comic_id):\r\n\tcomic = g.db.execute(\"SELECT * FROM comics ORDER BY id ASC LIMIT 1 OFFSET ?\", str(comic_id - 1)).fetchone()\r\n\tlatest = g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0]\r\n\treturn render_template(\"index.html\", comic=comic, latest=latest)\r\n\r\n@app.route(\"/random/\")\r\ndef random(current):\r\n\tlatest = int(g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0])\r\n\trandom = randint(1, latest)\r\n\twhile random == current:\r\n\t\trandom = randint(1, latest)\r\n\treturn redirect(\"http://crassis.me/%s\" % str(random))\r\n\r\n@app.route(\"/dashboard\")\r\ndef dashboard():\r\n\tcomics = g.db.execute(\"SELECT * FROM comics ORDER BY id DESC\").fetchall()\r\n\treturn render_template(\"dashboard.html\", comics=comics)\r\n\r\n@app.route(\"/dashboard/edit/\", methods=[\"GET\", \"POST\"])\r\ndef edit(comic_id):\r\n\ttry:\r\n\t\tif request.method == \"POST\" and request.form['password'] == adminpassword:\r\n\t\t\tif 'delete' in request.form:\r\n\t\t\t\timage = g.db.execute(\"SELECT url FROM comics WHERE id=?\", (str(comic_id))).fetchone()[0]\r\n\t\t\t\ttry:\r\n\t\t\t\t\tpath = re.sub(\"http://www.crassis.me/\", \"\", image)\r\n\t\t\t\t\timage = \"/crassis/crassis-site/\" + path\r\n\t\t\t\t\tos.remove(image)\r\n\t\t\t\texcept Exception as e:\r\n\t\t\t\t\tpass\r\n\t\t\t\tg.db.execute(\"DELETE FROM comics WHERE id=?\", (str(comic_id)))\r\n\t\t\tprint(\"2\")\r\n\t\t\ttitle = request.form['title']\r\n\t\t\talt = request.form['alt']\r\n\t\t\timage = request.files['file']\r\n\t\t\tif image:\r\n\t\t\t\tfilename = secure_filename(image.filename)\r\n\t\t\t\tpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\r\n\t\t\t\timage.save(path)\r\n\t\t\t\turl = \"http://www.crassis.me/static/images/\" + filename\r\n\t\t\t\tg.db.execute(\"UPDATE comics SET title=?, alt=?, url=? WHERE id=?\", (title, alt, url, str(comic_id)))\r\n\t\t\telse:\r\n\t\t\t\tg.db.execute(\"UPDATE comics SET title=?, alt=? WHERE id=?\", (title, alt, str(comic_id)))\r\n\t\t\tg.db.commit()\r\n\t\t\treturn redirect(url_for(\"dashboard\"))\r\n\t\telse:\r\n\t\t\tcomic = g.db.execute(\"SELECT * FROM comics WHERE id=?\", str(comic_id)).fetchone()\r\n\t\t\tif comic is None:\r\n\t\t\t\treturn redirect(\"http://crassis.me/anus\")\r\n\t\t\treturn render_template(\"edit.html\", comic=comic)\r\n\texcept Exception as e:\r\n\t\treturn str(e)\r\n\r\n@app.route(\"/upload\", methods=[\"GET\", \"POST\"])\r\ndef upload():\r\n\ttry:\r\n\t\tif request.method == \"POST\":\r\n\t\t\tpassword = request.form['password']\r\n\t\t\tif password != adminpassword:\r\n\t\t\t\treturn redirect(\"http://crassis.me/anus\")\r\n\t\t\timage = request.files['file']\r\n\t\t\tif image:\r\n\t\t\t\tlatest = int(g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0])\r\n\t\t\t\tfilename = str(latest + 1)\r\n\t\t\t\tpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\r\n\t\t\t\timage.save(path)\r\n\t\t\t\turl = \"http://www.crassis.me/static/images/\" + filename\r\n\t\t\t\ttitle = request.form['title']\r\n\t\t\t\talt = request.form['alt']\r\n\t\t\t\tg.db.execute(\"INSERT INTO comics (title, alt, url) VALUES (?, ?, ?)\", (title, alt, url))\r\n\t\t\t\tg.db.commit()\r\n\t\t\t\treturn redirect(url_for(\"index\"))\r\n\t\t\treturn \"no image found cuh\"\r\n\t\telse:\r\n\t\t\treturn render_template(\"upload.html\")\r\n\texcept Exception as e:\r\n\t\treturn str(e)\r\n\r\n\r\n\r\n@app.errorhandler(404)\r\n@app.errorhandler(500)\r\ndef fourohfour(error):\r\n\treturn \"crassis denies your request\"","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"231546758","text":"'''\r\n爬图片\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=0\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=20\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=40\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=60\r\n爬排名\r\nhttps://movie.douban.com/top250?start=0&filter=\r\nhttps://movie.douban.com/top250?start=25&filter=\r\n'''\r\nimport re\r\nimport random\r\nimport requests\r\ndef hearder():\r\n agent1 = \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\"\r\n agent2 = \"Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3\"\r\n agent3 = \"Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0\"\r\n agent4 = \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727\"\r\n list = [agent1, agent2, agent3, agent4]\r\n agent = random.choice(list)\r\n header = {\"User-Agent\": agent}\r\n return header\r\n\r\ndef urllist(start,end):\r\n urllist = []\r\n for ye in range(end+1):\r\n if ye>=start:\r\n url = 'https://movie.douban.com/top250?start='+str((ye-1)*25)+'&filter='\r\n urllist.append(url)\r\n return urllist\r\n\r\n\r\ndef info(urllist1):\r\n movienamelist = []\r\n pngnamelist = []\r\n for url in urllist1:\r\n response = requests.get(url,headers = header).content.decode()\r\n pat1 =re.compile(r'\"(.*?)\"')\r\n data=pat1.findall(response)\r\n for movie in data:\r\n movienamelist.append(movie)\r\n pat2 =re.compile(r'\".*?\"')\r\n data2 = pat2.findall(response)\r\n for png in data2:\r\n pngnamelist.append(png)\r\n return movienamelist,pngnamelist\r\n\r\ndef loadmovie(movienamelist,pngnamelist):\r\n for i in range(len(movienamelist)):\r\n moviepng = requests.get(pngnamelist[i], headers=header).content\r\n with open(\"E:/爬虫练习文件夹/电影流弊gasp/\"+\"排行榜第\"+str(i+1)+\"部\"+movienamelist[i]+\".jpg\",\"wb\") as f:\r\n print(\"正在下载第{}张图片\".format(i+1))\r\n f.write(moviepng)\r\n print(\"第{}张图片下载完成\".format(i+1))\r\n\r\nif __name__ == '__main__':\r\n start = int(input(\"请输入起始页\"))\r\n end = int(input(\"输入终止页\"))\r\n header = hearder()\r\n urllist1 = urllist(start,end)\r\n movienamelist, pngnamelist = info(urllist1)\r\n loadmovie(movienamelist,pngnamelist)\r\n","sub_path":"python网络爬虫/正则表达式/爬取豆瓣电影.py","file_name":"爬取豆瓣电影.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"532810025","text":"__author__ = 'KentChum'\n#encoding = utf8\nfrom flask import Flask\nimport os\nimport re\nimport json\nimport sqlite3\nimport ipdb\nimport time\nfrom LogHelper import LogHelper\n\napp = Flask(__name__)\n\napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, 'ipdb.db'),\n DEBUG=True,\n))\n\n\n@app.route('/ip/')\ndef getIp(ip):\n #ipv4\n timelist = [time.time()]\n timelist = LogHelper(timelist, 'loadings')\n ipv4pattern = r\"\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\"\n ipv6pattern = r\"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^:((:[0-9a-fA-F]{1,4}){1,6}|:)$|^[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,5}|:)$|^([0-9a-fA-F]{1,4}:){2}((:[0-9a-fA-F]{1,4}){1,4}|:)$|^([0-9a-fA-F]{1,4}:){3}((:[0-9a-fA-F]{1,4}){1,3}|:)$|^([0-9a-fA-F]{1,4}:){4}((:[0-9a-fA-F]{1,4}){1,2}|:)$|^([0-9a-fA-F]{1,4}:){5}:([0-9a-fA-F]{1,4})?$|^([0-9a-fA-F]{1,4}:){6}:$\"\n result = None\n if re.match(ipv4pattern, ip) or re.match(ipv6pattern, ip):\n\n if re.match(ipv4pattern, ip):\n target = ipdb.Ipv42Int(ip)\n else:\n target = ipdb.Ipv62Int(ip)\n\n timelist = LogHelper(timelist, 'regex in')\n conn = sqlite3.connect(app.config['DATABASE'])\n cur = conn.cursor()\n #querydb = \"select cc,start from ipdata WHERE \" + str(target) + \" between min_number and max_number\"\n #querydb = \"select cc,start from ipdata WHERE \" + str(target) + \" >= min_number and \" + str(target) + \"<= max_number limit 1\"\n #querydb = \"select cc,start from ipdata WHERE 2921193021 >= min_number and 2921193021 <= max_number\"\n querydb = \"select cc,start from (select cc,start,max_number from ipdata where \" + str(\n target) + \" >= min_number order by min_number desc limit 1) WHERE \" + str(target) + \" <=max_number\"\n\n cur.execute(querydb)\n rs = cur.fetchall()\n\n timelist = LogHelper(timelist, 'reading db')\n if not rs:\n result = {'status': 404,\n 'result': None,\n 'info': 'Not found!'}\n else:\n result = {'status': 200,\n 'result': rs[0],\n 'info': 'Ip found!'}\n else:\n result = {'status': 403,\n 'result': None,\n 'info': 'Invalid ip!'}\n\n timelist = LogHelper(timelist, 'end')\n return json.dumps(result)\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"apnicip.py","file_name":"apnicip.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"278807689","text":"import logging\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nfrom core.mailer import get_mailer\nfrom erp.models import Erp\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n now = timezone.now()\n help = (\n \"Envoie une notification de rappel aux utilisateurs ayant commencé le remplissage d'une fiche sans la publier\"\n )\n\n def __init__(self, *args, **kwargs):\n if kwargs.get(\"now\"):\n self.now = kwargs[\"now\"]\n del kwargs[\"now\"]\n super().__init__(*args, **kwargs)\n\n def handle(self, *args, **options):\n if not settings.REAL_USER_NOTIFICATION:\n print(\"Launched only if settings.REAL_USER_NOTIFICATION is True.\")\n return\n\n notifications = self.get_notifications()\n sent_ok = 0\n for notification in notifications:\n sent_ok += 1 if self.send_notification(notification) else 0\n\n logger.info(f\"{sent_ok}/{len(notifications)} relance(s) d'ERP(s) non-publié(s)\")\n\n def get_notifications(self):\n notifications = {}\n since = self.now - timedelta(days=settings.UNPUBLISHED_ERP_NOTIF_DAYS)\n erps = Erp.objects.select_related(\"user\").filter(\n published=False,\n user__isnull=False,\n user__is_active=True,\n user__preferences__notify_on_unpublished_erps=True,\n updated_at__lte=since,\n )\n for erp in erps.iterator(chunk_size=2000):\n erp_updated_since_days = (self.now - erp.updated_at).days\n if erp_updated_since_days >= settings.UNPUBLISHED_ERP_NOTIF_DAYS:\n if erp.user.pk not in notifications:\n notifications[erp.user.pk] = {\"user\": erp.user, \"erps\": []}\n notifications[erp.user.pk][\"erps\"].append(erp)\n return [n for n in notifications.values() if n[\"erps\"]]\n\n def send_notification(self, notification):\n user, erps = notification[\"user\"], notification[\"erps\"]\n return get_mailer().send_email(\n [user.email],\n f\"[{settings.SITE_NAME}] Des établissements sont en attente de publication\",\n \"mail/unpublished_erps_notification.txt\",\n {\n \"user\": user,\n \"erps\": erps,\n \"SITE_NAME\": settings.SITE_NAME,\n \"SITE_ROOT_URL\": settings.SITE_ROOT_URL,\n },\n )\n","sub_path":"erp/management/commands/notify_weekly_unpublished_erps.py","file_name":"notify_weekly_unpublished_erps.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"57356843","text":"\"\"\"\r\n--------------------------------------------------------|\r\n| Create virtual enviroment -> virtualenv env |\r\n| Activate virtualenv -> env/Scripts/activate |\r\n| |\r\n| Install selenium -> pip install selenium |\r\n| |\r\n| Run the script in virtual enviroment -> python bit.py |\r\n---------------------------------------------------------\r\n\"\"\"\r\nimport unittest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nimport random\r\n\r\nclass Bit(unittest.TestCase):\r\n\r\n def setUp(self):\r\n print('I am not gonna destroy anything, just checking..')\r\n self.driver = webdriver.Firefox()\r\n\r\n def test_search_in_python_org(self):\r\n driver = self.driver\r\n driver.get(\"https://zck.me/bitcoin-clicker/\")\r\n element = driver.find_element_by_xpath(\"//input[@value='Mine for bitcoin. By hand.']\")\r\n for i in range(0,100000000):\r\n element.click()\r\n time.sleep(random.random())\r\n time.sleep(50)\r\n assert \"No results found.\" not in driver.page_source\r\n\r\n\r\n def tearDown(self):\r\n print('I am done.')\r\n self.driver.close()\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"bit.py","file_name":"bit.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"572402117","text":"\"\"\"\n Model for Super Tic Tac tic_tac_toe\n @Author Alex Chapman\n 3/6/17\n\"\"\"\n\n\nimport ast\n\nD = 'steelblue'\n\n\nclass model(object):\n \"\"\"\n class which handles the actual functioning of the server. Includes\n handling new users connecting, as well as clients sending commands\n such as color changes and click values.\n\n Attributes:\n SOCKET_LIST - List of addresses that have connected to server\n users - List of user objects\n correlation - Dictionary that relates other two attributes\n \"\"\"\n def __init__(self):\n \"\"\"Returns model object\"\"\"\n # list of addresses\n self.socket_list = []\n # list of user objects\n self.users = []\n # dictionary relating users to addresses\n self.correlation = {}\n\n def save_val(self, thruput, member):\n \"\"\"\n function call which allows data to be passed into the game field.\n Commands: 'hb' - heartbeat message sent on loop to sync\n 'uCOLOR' - sets the color of the user that calls it\n '[x, y]' - click value of given\n\n Input: thruput -> command or whatnot to be processed\n member -> address from which the message originated\n \"\"\"\n # figures out which user sent the message\n to_use = self.correlation[member]\n\n # if the command is the color set\n if thruput[0] == 'u':\n to_use.set_color(thruput[1:])\n print(member, thruput[1:])\n\n # on the click command check if it is that user's turn\n elif to_use.turn_state:\n try:\n # if hb is appended to the end of the click, remove it\n if 'hb' in thruput and len(thruput) > 2:\n thruput = thruput[:len(thruput)-2]\n\n # interperet point input as list\n ls = ast.literal_eval(thruput)\n\n # passes the point value down to the user and returns if\n # the turn was successfully passed\n if to_use.input(ls):\n # change whos turn it is\n self.change_turns()\n print('Turns Changed.')\n else:\n print('Invalid Click. Still your turn.')\n except (SyntaxError, ValueError) as e:\n if(thruput == 'hb'):\n pass\n else:\n print('didnt work' + thruput)\n pass\n else:\n if(thruput == 'hb'):\n pass\n else:\n print('not your turn ' + str(member))\n pass\n\n def update_socket_list(self, thruput):\n \"\"\"\n called upon clients connection, creates and establishes list of\n addresses which are in turn paired with user objects.\n\n inputs: thruput -> address of most recently connected machine\n \"\"\"\n if thruput not in self.socket_list: # if address not already listed\n self.socket_list.append(thruput)\n # print(len(self.socket_list))\n # the first user has a predefined 'x' char (now irrelevant)\n if len(self.socket_list) == 1:\n # first user to connect gets first turn\n self.users.append(user('x', True))\n # adds new user object to the dictionary so it can be found\n self.correlation[thruput] = self.users[0]\n\n # see above\n elif len(self.socket_list) == 2:\n self.users.append(user('o', False))\n self.correlation[thruput] = self.users[1]\n\n else:\n print('Invalid number of connections: 2 players expected.')\n print('Ignoring Extra Connection')\n # print(self.users)\n\n # changes the turns, excecution above\n def change_turns(self):\n \"\"\"Changes the turns\"\"\"\n for u in self.users:\n u.flip_turn()\n\n\nclass tic_tac_toe(object):\n \"\"\"\n Class which handles the creation of game objects for each of the 9\n major game tiles. Contains a 3x3 matrix of color vals, with the\n default color being defined at the top of the file.\n\n Attributes:\n focus - whether or not the game matrix is in focus (playable)\n state - 3x3 matrix holding the values of that specific board\n \"\"\"\n def __init__(self, f, x=0, y=0):\n \"\"\"Returns new tic_tac_toe object\"\"\"\n self.focus = f\n self.state = [[D, D, D],\n [D, D, D],\n [D, D, D]]\n\n def __str__(self):\n \"\"\"Returns string representation of tic_tac_tow object\"\"\"\n to_return = (str(self.state[0]) + '\\n' +\n str(self.state[1]) + '\\n' +\n str(self.state[2]) + '\\n')\n return to_return\n\n def add_char(self, char, i, j):\n \"\"\"\n Function which handles an attempted click: i.e. adding a new color\n to the game matrix if the box clicked on is empty.\n \"\"\"\n if self.state[i][j] is D:\n self.state[i][j] = char\n print('Clicked Valid Box.')\n return True\n else:\n print('Box already taken.')\n return False\n\n def on_click(self, x, y, char):\n \"\"\"\n Called by the user on click of the specific sub-game board.\n\n Inputs:\n x - decimal representation of click on the bigger board\n y - decimal representation of click on the bigger board\n char - color string of calling user\n \"\"\"\n x = x * 3\n y = y * 3\n\n # converts the decimal point to row and column clicked\n j = helper_func(x)\n i = helper_func(y)\n\n # only excecutes if the square clicked is unoccupied and in focus\n if self.add_char(char, i, j):\n # changes the big-board focus to the equivalent of the square clkd.\n change_focus(int(j), int(i))\n return True\n else:\n return False\n\n def check_if_won(self):\n \"\"\"\n Method to check the state matrix of the board to evaluate wheteher\n or not it has been won. If won, it returns the winning string. If\n not, returns the default string (D)\n \"\"\"\n # checks if the rows have a winner\n for row in self.state:\n if(row[0] == row[1] and row[0] == row[2]):\n return row[0]\n\n # checks if the columns have a winner\n for column in range(0, len(self.state)):\n one = self.state[0][column]\n two = self.state[1][column]\n three = self.state[2][column]\n if(one == two and one == three):\n return one\n\n # checks if the upper-left bottom-right diagonal has a winner\n one = self.state[0][0]\n two = self.state[1][1]\n three = self.state[2][2]\n if(one == two and one == three):\n return one\n\n # checks if the other diagonal has a winner\n one = self.state[0][2]\n three = self.state[2][0]\n if(one == two and one == three):\n return one\n return D\n\n def get_to_send(self):\n \"\"\"\n Returns nested list to send to clients\n Format:\n [[ROW],[ROW],[ROW]]\n L ROW = [focus, < 9 length list of all square values >]\n \"\"\"\n ls = []\n ls.append(self.focus)\n # print(self.state)\n if self.state is not None:\n for i in self.state:\n for q in i:\n ls.append(q)\n return ls\n\n\nclass user(object):\n \"\"\"\n User object designed to create a profile for each client that connects\n to the game. Also handles all high-level click functionality.\n\n Attributes:\n char - string representing the color of the user, set by\n uCOLOR command upon client initialization.\n turn_state - Boolean representing whether or not it is this user's\n turn.\n \"\"\"\n def __init__(self, char=D, turn_state=False):\n \"\"\"Returns a user object\"\"\"\n # sets the color to default, to be set by first client operation.\n self.char = char\n self.turn_state = turn_state\n\n def input(self, ls):\n \"\"\"\n Accepts the point value of the clicked position as a decimal fro 0-1\n in both the x and y direction. Calculates which large tile is\n clicked on, and then calls that tile with the same clicked point.\n\n Input: point of click in the form [x, y]\n \"\"\"\n click_x = ls[0]\n click_y = ls[1]\n\n # converts the decimal point to row and column clicked\n i = helper_func(click_x)\n j = helper_func(click_y)\n # print('box clicked on:', i, ':', j)\n # print('box in focus:', get_board_focus())\n if main_board[j][i].focus:\n # HIGHEST LEVEL CLICK MANAGEMENT\n # attempts to add color to the clicked-on board\n return main_board[j][i].on_click(click_x - i/3,\n click_y - j/3,\n self.char)\n else:\n return False\n\n def flip_turn(self):\n self.turn_state = not self.turn_state\n\n def set_color(self, color):\n self.char = color\n\n\ndef helper_func(val):\n \"\"\"\n Function independent of a class, designed to convert a decimal into\n its corresponding integer value. Assumes 3 columns / rows.\n\n Input: Must be between 0 and 1 to function correctly\n \"\"\"\n if val > 2/3:\n i = 2\n elif val < 1/3:\n i = 0\n else:\n i = 1\n return i\n\n\ndef change_focus(row, column):\n \"\"\"\n Changes focus to the new main tile. takes a row and column integer as\n inputs, must be between 0-2 for both.\n \"\"\"\n # sets all foci to false\n for rw in main_board:\n for game in rw:\n game.focus = False\n # goes to the single board that should be in focus and sets its focus\n main_board[column][row].focus = True\n print('focus on:', column, row)\n\n\n# Initializes the base variable which holds the game boards needed\nmain_board = [[tic_tac_toe(True), tic_tac_toe(False), tic_tac_toe(False)],\n [tic_tac_toe(False), tic_tac_toe(False), tic_tac_toe(False)],\n [tic_tac_toe(False), tic_tac_toe(False), tic_tac_toe(False)]]\n\n\ndef check_if_won(board):\n \"\"\"\n Function used to check if the main board has been won.\n\n Inputs: board - main game board to be checked.\n Output: string representing the color of the winner, if not the def.\n \"\"\"\n # Finds out if each individual board has been won.\n ls = []\n for i in board:\n ts = []\n for v in i:\n ts.append(v.check_if_won)\n\n # checks if the rows have a winner\n for row in ls:\n if(row[0] == row[1] and row[0] == row[2]):\n return row[0]\n\n # checks if the columns have a winner\n for column in range(0, len(ls)):\n one = ls[0][column]\n two = ls[1][column]\n three = ls[2][column]\n if(one == two and one == three):\n return one\n\n # checks if the upper-left bottom-right diagonal has a winner\n one = ls[0][0]\n two = ls[1][1]\n three = ls[2][2]\n if(one == two and one == three):\n return one\n\n # checks if the other diagonal has a winner\n one = ls[0][2]\n three = ls[2][0]\n if(one == two and one == three):\n return one\n return D\n\n\ndef get_board_state():\n \"\"\"\n Converts the game board into a readable form for sending to the clients\n \"\"\"\n ls = []\n for row in main_board:\n ts = []\n for val in row:\n # print(val.get_to_send())\n ts.append(val.get_to_send())\n ls.append(ts)\n return ls\n\n\ndef get_board_focus():\n \"\"\"Returns the index of the cell that is in focus\"\"\"\n for i, row in enumerate(main_board):\n for o, column in enumerate(row):\n if column.focus == 1:\n return str(i) + ':' + str(o)\n return 'none in focus'\n","sub_path":"model_tic_tac.py","file_name":"model_tic_tac.py","file_ext":"py","file_size_in_byte":12257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336711091","text":"import os\nimport urllib.request\n\nif __name__ == '__main__':\n\tfor i in range(1,1000):\n\t\tfilename = \"res/levels/level\" + str(i) + \".json\"\n\t\turl =\"http://szhong.4399.com/4399swf/upload_swf/ftp16/ssj/20150703/j4/1y/\" +filename\n\t\ttry:\n\t\t\tf = urllib.request.urlopen(url)\n\t\t\tdata = f.read()\n\t\t\twith open(filename,'wb') as code:\n\t\t\t\tcode.write(data)\n\t\t\t\tcode.close()\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tbreak\n\t\t\t\t\n\n\t\t\t\n","sub_path":"www/downloadlevel.py","file_name":"downloadlevel.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"324484495","text":"\"\"\"\nThis module contains the game mechanics such as\nTime and Tamagotchi Mechanics.\n\"\"\"\n\nimport time\nimport math\nfrom message import Message\n\n\nclass TimeMechanics:\n \"\"\"\n Keeps track of the time elapsed between status checks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes an object and sets the time of initialization.\n \"\"\"\n\n self._old_time = 0\n self._last_time_elapsed = 0\n self._time_ = time.time()\n self._first_status_check = True\n\n def set_time_(self):\n \"\"\"\n Sets old_time to the current time_ value and then sets\n time_ to the new current time.\n :return: None\n \"\"\"\n\n self._old_time = self._time_\n self._time_ = time.time()\n\n def time_elapsed(self):\n \"\"\"\n Calculates the time elapsed by subtracting the new time_\n to the old_time.\n :return: A string that contains the details of the\n last status check\n \"\"\"\n\n if self._first_status_check:\n self._first_status_check = False\n return print(\"First status check...\")\n else:\n self._last_time_elapsed = math.ceil(self._time_ - self._old_time)\n return print(f\"\\nTime elapsed since last status check: \"\n f\"{self._last_time_elapsed} seconds\")\n\n @property\n def last_time_elapsed(self):\n \"\"\"\n Gets the value of the last_time_elapsed.\n :return: an int\n \"\"\"\n\n return self._last_time_elapsed\n\n\nclass TamagotchiMechanics:\n \"\"\"\n Contains the methods that modify the Tamagotchi's stats\n per second such as health, hunger, and happiness.\n \"\"\"\n\n def __init__(self, time_mechanic, tamagotchi):\n \"\"\"\n Initializes an object that has a TimeMechanic.\n :param time_mechanic: a TimeMechanic object\n :param tamagotchi: a tamagotchi object\n \"\"\"\n\n self._tm = time_mechanic\n self._tamagotchi = tamagotchi\n self._message = Message(tamagotchi)\n\n def attribute_mods(self):\n \"\"\"\n Runs the Tamagotchi's add_hunger, reduce_happiness, and\n reduce_health n times, where n equals the number of seconds\n passed in between status checks.\n :return: None\n \"\"\"\n\n run_times = 0\n while run_times < self._tm.last_time_elapsed:\n self._tamagotchi.add_hunger()\n self._tamagotchi.reduce_happiness()\n self._tamagotchi.reduce_health()\n run_times += 1\n\n def check_status(self):\n \"\"\"\n Checks the status of the Tamagotchi. Runs the set_time and\n time_elapsed methods to update the time component during\n the game. Runs the attribute_mods method in order to change the\n stat values.\n :return: None\n \"\"\"\n\n self._tm.set_time_()\n self._tm.time_elapsed()\n self.attribute_mods()\n\n if self._tamagotchi.dead():\n print(f\"{'-' * 50}\")\n self._message.died()\n print(f\"{'-' * 50}\")\n else:\n print(\"\")\n print(self._tamagotchi)\n print(\"\")\n self._message.hungry()\n self._message.fun()\n self._message.sick()\n","sub_path":"Assignments/Assignment 1/game_mechanics.py","file_name":"game_mechanics.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"645696238","text":"# This is a direct running file to calculate the specific counts of RNA\n# splicing, and currently it is mainly for intronic splicing, rather than\n# alternative splicing. There are 8 types for reads for an exon1-intron-\n# exon2 structure: (0) exon1, (1) exon1-intron boundary, (2) intron, (3) \n# intron-exon2 boundary, (4) exon2, (5) exon1-exon2 junction, (6) exon1-\n# intron-exon2, (7) exon1-exon2 unsure. In addition, it also provides the\n# normalized counts RPKM (reads per kilo-base per million reads).\n\nimport sys\nimport time\nimport pysam\nimport subprocess\nimport numpy as np\nimport multiprocessing\nfrom optparse import OptionParser\nfrom .utils.reads_utils import ReadSet\nfrom .utils.gtf_utils import load_annotation\nfrom .utils.sam_utils import load_samfile, fetch_reads\n\nFID = None \nPROCESSED = 0\nTOTAL_GENE = 0\nSTART_TIME = time.time()\n\ndef show_progress(RV=None):\n global PROCESSED, TOTAL_GENE, START_TIME, FID\n if RV is None:\n return RV\n else:\n FID.writelines(RV)\n \n PROCESSED += 1\n bar_len = 30\n run_time = time.time() - START_TIME\n percents = 100.0 * PROCESSED / TOTAL_GENE\n filled_len = int(round(bar_len * percents / 100))\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n \n sys.stdout.write('\\r[%s] %.2f%% processed in %.1f sec.' \n % (bar, percents, run_time))\n sys.stdout.flush()\n return RV\n\ndef get_count(gene, sam_file, total_reads, rm_duplicate, inner_only, mapq_min, \n mismatch_max, rlen_min, is_mated, total_only, overhang):\n samFile = load_samfile(sam_file)\n reads = fetch_reads(samFile, gene.chrom, gene.start, gene.stop, \n rm_duplicate, inner_only, mapq_min, mismatch_max, rlen_min, is_mated)\n\n if total_only:\n count = [len(reads[\"reads1u\"])+len(reads[\"reads2u\"])+len(reads[\"reads1\"])]\n RPKM = [count[0] * 10**9 / abs(gene.start - gene.stop) / total_reads]\n elif gene.tranNum == 1 and gene.trans[0].exonNum == 2:\n rdSet = ReadSet(reads[\"reads1u\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count = rdSet.loc_idx.sum(axis=0)\n RPKM = rdSet.RPK_use.sum(axis=0)\n\n rdSet = ReadSet(reads[\"reads2u\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count += rdSet.loc_idx.sum(axis=0)\n RPKM += rdSet.RPK_use.sum(axis=0)\n\n rdSet = ReadSet(reads[\"reads1\"], reads[\"reads2\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count += rdSet.loc_idx.sum(axis=0)\n RPKM += rdSet.RPK_use.sum(axis=0)\n\n RPKM = RPKM * 10**6 / total_reads\n else: return None\n\n gLen = str(abs(gene.stop - gene.start) + 1)\n a_line = \"\\t\".join([gene.geneID, gene.geneName, gene.biotype, gLen]) + \"\\t\"\n a_line += \"\\t\".join([\"%d\" %num for num in list(count)]) + \"\\t\" \n a_line += \"\\t\".join([\"%.2e\" %num for num in list(RPKM)]) + \"\\n\"\n return a_line\n\ndef main():\n print(\"Welcome to dice-count!\")\n\n #part 0. parse command line options\n parser = OptionParser()\n parser.add_option(\"--anno_file\", \"-a\", dest=\"anno_file\", default=None,\n help=\"The annotation file in gtf format\")\n parser.add_option(\"--anno_source\", dest=\"anno_source\", default=\"Ensembl\",\n help=\"The annotation source of the gtf file [default: %default].\" )\n parser.add_option(\"--sam_file\", \"-s\", dest=\"sam_file\", default=None,\n help=\"The indexed alignement file in bam/sam format\")\n parser.add_option(\"--out_file\", \"-o\", dest=\"out_file\", \n default=\"dice_count.txt\", help=\"The counts in plain text file\")\n\n parser.add_option(\"--nproc\", dest=\"nproc\", default=\"4\",\n help=\"The number of subprocesses [default: %default].\")\n parser.add_option(\"--mapq_min\", dest=\"mapq_min\", default=\"10\", \n help=\"the minimum mapq for reads. [default: %default]\")\n parser.add_option(\"--mismatch_max\", dest=\"mismatch_max\", default=\"5\", \n help=\"the maximum mismatch for reads. [default: %default]\")\n parser.add_option(\"--rlen_min\", dest=\"rlen_min\", default=\"1\", \n help=\"the mimimum length of reads. [default: %default]\")\n parser.add_option(\"--overhang\", dest=\"overhang\", default=\"1\", \n help=\"the length of overhang on junctions. [default: %default]\")\n\n parser.add_option(\"--duplicate\", action=\"store_true\", \n dest=\"duplicate_use\", default=False, help=\"keep duplicate reads.\")\n parser.add_option(\"--partial\", action=\"store_true\", dest=\"partial_use\",\n default=False, help=\"keep reads partial in the region.\")\n parser.add_option(\"--single_end\", action=\"store_true\", dest=\"single_end\",\n default=False, help=\"use the reads as single-end.\")\n parser.add_option(\"--junction\", action=\"store_true\", dest=\"junction_reads\",\n default=False, help=(\"return junction and boundary reads, only for \"\n \"gene with one exon-intron-exon structure; other wise return total \"\n \"counts for the whole gene.\"))\n\n (options, args) = parser.parse_args()\n if len(sys.argv[1:]) == 0:\n print(\"use -h or --help for help on argument.\")\n sys.exit(1)\n if options.anno_file == None:\n print(\"Error: need --anno_file for annotation.\")\n sys.exit(1)\n else:\n sys.stdout.write(\"\\rloading annotation file...\")\n sys.stdout.flush() \n anno = load_annotation(options.anno_file, options.anno_source)\n sys.stdout.write(\"\\rloading annotation file... Done.\\n\")\n sys.stdout.flush()\n genes = anno[\"genes\"]\n if options.sam_file == None:\n print(\"Error: need --sam_file for reads indexed and aliged reads.\")\n sys.exit(1)\n else:\n sam_file = options.sam_file\n\n total_reads = 0\n for tp in pysam.idxstats(sam_file): \n tmp = tp.strip().split(\"\\t\")\n if len(tmp) >= 3:\n total_reads += float(tmp[2])\n\n nproc = int(options.nproc)\n overhang = int(options.overhang)\n mapq_min = int(options.mapq_min)\n rlen_min = int(options.rlen_min)\n mismatch_max = int(options.mismatch_max)\n\n is_mated = (options.single_end == False)\n inner_only = (options.partial_use == False)\n total_only = (options.junction_reads == False)\n rm_duplicate = (options.duplicate_use == False)\n \n global FID, TOTAL_GENE\n FID = open(options.out_file, \"w\")\n if total_only == False:\n head_line = \"gene_id\\tgene_name\\tbiotype\\tgene_length\"\n cnt_name = [\"ex1\", \"ex1_int\", \"int\", \"int_ex2\", \"ex2\", \"ex1_ex2_junc\",\n \"ex1_int_ex2\", \"ex1_ex2_vague\"]\n for i in range(len(cnt_name)):\n head_line += \"\\t\" + cnt_name[i] + \"_NUM\"\n for i in range(len(cnt_name)):\n head_line += \"\\t\" + cnt_name[i] + \"_FPKM\"\n cnt = 0\n for g in genes:\n if g.tranNum == 1 and g.trans[0].exonNum == 2: cnt += 1\n TOTAL_GENE = cnt\n else:\n TOTAL_GENE = len(genes)\n head_line = \"gene_id\\tgene_name\\tbiotype\\tgene_length\\tcount\\tFPKM\"\n FID.writelines(head_line + \"\\n\")\n\n print(\"running diceseq for %d genes with %d cores...\" %(TOTAL_GENE, nproc))\n\n if nproc <= 1:\n for g in genes:\n if total_only == False and (g.tranNum > 1 or g.trans[0].exonNum != 2):\n continue\n RV = get_count(g, sam_file, total_reads, rm_duplicate, inner_only, \n mapq_min, mismatch_max, rlen_min, is_mated, total_only, overhang)\n show_progress(RV)\n else:\n pool = multiprocessing.Pool(processes=nproc)\n for g in genes:\n if total_only == False and (g.tranNum > 1 or g.trans[0].exonNum != 2):\n continue\n pool.apply_async(get_count, (g, sam_file, total_reads, rm_duplicate, \n inner_only, mapq_min, mismatch_max, rlen_min, is_mated, total_only,\n overhang), callback=show_progress)\n pool.close()\n pool.join()\n FID.close()\n print(\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"diceseq/dice_count.py","file_name":"dice_count.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"472627812","text":"def name(item1):\n print(f'\\nOla!!! Bem Vindo, {item1}.')\n \ndef year(item2):\n if (item2 >= 18):\n print('\\nVocê é maior de idade.')\n else:\n print('\\nCreça você ainda é menor de idade.')\n\n#programa principal\nprint('Inicio')\nnome = input('\\nDigite seu nome: ')\nidade = int(input('\\nDigite sua idade: '))\n\n#função name\nname(nome)\n\n#função years\nyear(idade)\n\nprint('\\nFim')\n","sub_path":"Aula 15/Exercícios/A Ex 04.py","file_name":"A Ex 04.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"323112115","text":"from selenium import webdriver\nimport sys\nimport csv\n# -----------------------------------------------------------------------------\n# TC 133 - Create N new local accounts.\n#\n# By default uses randomly-generated account info from signup_10.csv which\n# must be in the same directory as this script. This must be a simple CSV file\n# with user ID, email, and password columns. No headers.\n# The default file was obtained from http://www.mockaroo.com/\n# All records found in the CSV file will be processed. To change the number\n# of accounts created, simply generate or manipulate a CSV file.\n# -----------------------------------------------------------------------------\n\ndatafile = 'signup_10.csv'\n\n# -----------------------------------------------------------------------------\n# Process command line argument that specifies the browser.\n# -----------------------------------------------------------------------------\n# No argument provided\ntry:\n arg1 = sys.argv[1]\nexcept IndexError:\n driver = webdriver.Chrome()\n\nif 'driver' not in locals():\n if sys.argv[1].lower() == 'chrome':\n driver = webdriver.Chrome()\n elif sys.argv[1].lower() == 'firefox':\n driver = webdriver.Firefox()\n elif sys.argv[1].lower() == 'ie':\n driver = webdriver.Ie()\n elif sys.argv[1].lower() == 'edge':\n driver = webdriver.Edge()\n elif sys.argv[1].lower() == 'opera':\n options = webdriver.ChromeOptions()\n options.binary_location = \\\n 'C:\\\\Program Files\\\\Opera\\\\48.0.2685.50\\\\opera.exe'\n driver = webdriver.Opera(opera_options=options)\n # MacOS options\n elif sys.argv[1].lower() == 'safari':\n driver = webdriver.Safari()\n elif sys.argv[1].lower() == 'chromemac':\n driver = webdriver.Chrome\n ('/volumes/OrangeWhite/Dropbox/WebDev/selenium/chromedriver')\n # Argument provided didn't match anything above\n else:\n driver = webdriver.Chrome()\n\ndriver.set_page_load_timeout(30)\ndriver.get('https://dev.fifteenlines.com/register_no_captcha')\ndriver.implicitly_wait(20)\n\n# -----------------------------------------------------------------------------\n# Open specified datafile for reading only\n# -----------------------------------------------------------------------------\nusers = csv.reader(open(datafile, 'r'))\n\n# -----------------------------------------------------------------------------\n# Use fields from the datafile to sign up fake users\n# -----------------------------------------------------------------------------\n\nfor row in users:\n driver.find_element_by_id('username') \\\n .send_keys(row[0])\n driver.find_element_by_id('email') \\\n .send_keys(row[1])\n driver.find_element_by_id('password') \\\n .send_keys(row[2])\n driver.find_element_by_id('signUp').click()\n assert \"Welcome to Fifteenlines\" in driver.page_source\n driver.find_element_by_id('logout').click()\n driver.get('https://dev.fifteenlines.com/register_no_captcha')\n\ndriver.quit()\n","sub_path":"selenium/tc_133.py","file_name":"tc_133.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"399353734","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom irs9465.tasks import fill_form_9465\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n help = ('Update IRS Local and National Standards Tables')\n\n def add_arguments(self, parser):\n parser.add_argument('--sync', action='store_true', help='Run it synchronously')\n parser.add_argument('--client_id', help='Client ID', required=True)\n parser.add_argument('--outfile', help='Output PDF file')\n\n def handle(self, *args, **options):\n sync = options.get('sync') or False\n if sync:\n fill_form_9465(client_id=options.get('client_id'), outfile=options.get('outfile'))\n else:\n fill_form_9465.apply_async(kwargs={'client_id': options.get('client_id'),\n 'outfile': options.get('outfile')})\n","sub_path":"irsexpress2/apps/irs9465/management/commands/makepdf_9465.py","file_name":"makepdf_9465.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"44556336","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView, ListView\nfrom eleccion import views\nfrom .views import *\n\nurlpatterns = [\n\turl(r'^verCircunscripciones/$', ListView.as_view(model=Circunscripcion, template_name=\"verCircunscripciones.html\")),\n\turl(r'^verPartidosPoliticos', views.verPartidosPoliticos, name = \"Ver Partidos Politicos\"),\n\turl(r'^detallePartidoPolitico/(?P\\d+)', views.detallePartidoPolitico, name='Detalles Partido Politico'),\n\turl(r'^addPartidoPolitico', views.addPartidoPolitico, name = \"Añadir Partido Politico\"),\n\turl(r'^detalleCircunscripcion/(?P\\d+)', views.detalleCircunscripcion, name='Detalles Circunscripcion'),\n\turl(r'^editarCircunscripcion/(?P\\d+)', views.editarCircunscripcion, name='Editar Circunscripcion'),\n\turl(r'^eliminarCircunscripcion/(?P\\d+)', views.eliminarCircunscripcion, name='Eliminar Circunscripcion'),\n\turl(r'^addCircunscripcion', views.addCircunscripcion, name = \"Añadir Circunscripcion\"),\n\turl(r'^verMesas', views.verMesas, name = \"Ver Mesas\"),\n\turl(r'^editarMesa/(?P\\d+)', views.editarMesa, name='Editar Mesa'),\n\turl(r'^verResultados', views.verResultados, name = \"Ver Resultados\"),\n\turl(r'^detalleMesa/(?P\\d+)', views.detalleMesa, name='Detalles Mesa'),\n\turl(r'^detalleResultados/(?P\\d+)', views.detalleResultados, name='Detalles Resultados'),\n\turl(r'^addMesa', views.addMesa, name = \"Añadir Mesa\"),\n\turl(r'^addVoto', views.addVoto, name = \"Votar\"),\n]\n","sub_path":"Elecciones/eleccion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"173027516","text":"from sample.cases.update_case import UpdateCase\nfrom sample.config.config_loader import ConfigLoader\nfrom sample.logger import Logger\nfrom sample.path import Path\nfrom sample.ssh_mananger.commands import WindowsCommands\nfrom sample.ssh_mananger.ssh_client import SshClient\n\n\ndef run():\n Logger.setLogger(__name__)\n\n Logger.i('######################################')\n Logger.i('# #')\n Logger.i('# INICIANDO O SMOKE-TEST-NFCE #')\n Logger.i('# VERSAO A0.1 #')\n Logger.i('# #')\n Logger.i('######################################')\n\n config = ConfigLoader(Path.run_path).load_config()\n ssh_connection = config.ssh_connections['localhost']\n update_case = UpdateCase(SshClient(ssh_connection, WindowsCommands), '4.9.1', '90000', 'agent')\n update_case.execute()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573882404","text":"import FWCore.ParameterSet.Config as cms\nprocess = cms.Process(\"SKIM\")\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('JetMETCorrections.Configuration.jecHLTFilters_cfi')\n############# Set the number of events #############\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(100)\n)\n############# Define the source file ###############\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n'/store/mc/Summer09/QCDDiJet_Pt15to20/AODSIM/MC_31X_V3_AODSIM-v1/0046/CEDF080D-CC8F-DE11-A831-001E682F84DE.root')\n)\n\n############# Path ###########################\nprocess.skimPath = cms.Path(process.HLTDiJetAve15U8E29)\n\n############# output module ########################\nprocess.compress = cms.OutputModule(\"PoolOutputModule\",\n outputCommands = cms.untracked.vstring(\n 'drop *',\n 'keep *_sisCone5CaloJets_*_*',\n 'keep *_sisCone7CaloJets_*_*',\n 'keep *_kt4CaloJets_*_*',\n 'keep *_kt6CaloJets_*_*',\n 'keep *_antikt5CaloJets_*_*',\n 'keep *_iterativeCone5CaloJets_*_*', \n 'keep *_sisCone5PFJets_*_*',\n 'keep *_sisCone7PFJets_*_*',\n 'keep *_kt4PFJets_*_*',\n 'keep *_kt6PFJets_*_*',\n 'keep *_antikt5PFJets_*_*',\n 'keep *_iterativeCone5CaloJets_*_*',\n 'keep *_iterativeCone5JetExtender_*_*',\n 'keep *_sisCone5JetExtender_*_*',\n 'keep *_kt4JetExtender_*_*',\n 'keep *_TriggerResults_*_*',\n 'keep *_hltTriggerSummaryAOD_*_*', \n 'keep *_towerMaker_*_*',\n 'keep *_EventAuxilary_*_*',\n 'keep *_pixelVertices_*_*',\n 'keep *_metHO_*_*',\n 'keep *_metNoHF_*_*',\n 'keep *_metNoHFHO_*_*', \n 'keep *_met_*_*'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('skimPath')), \n fileName = cms.untracked.string('JetAOD_HLTDiJetAve15.root')\n)\n\nprocess.p = cms.EndPath(process.compress)\n############# Format MessageLogger #################\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 10\n","sub_path":"JetMETCorrections/Configuration/test/jetAODSkim_HLT_DiJetAve15_cfg.py","file_name":"jetAODSkim_HLT_DiJetAve15_cfg.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"519109993","text":"import sys\nfrom os import path\nsys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) \n\nfrom tree_node import tree_node\nfrom base.iterator import iterator\nfrom tree_algo import tree_visit_level_order, tree_min, tree_delete_min, bst_find\nfrom tree_algo import tree_rotate_left, tree_rotate_right, tree_compute_height, tree_balance_check, tree_size\n\nclass avl_tree:\n \"\"\"\n Implementation for avl binary search tree.\n The avl binary search tree is binary tree that guarantees lg N time for insert/find/delete.\n The avl tree use rotation coupled with height analysis between nodes in order to accomplish balancing\n \n Important:\n - this implementation uses massively recursion. \n - Probably in practise you will never want use heavy recursive algorithms\n \"\"\"\n \n def __init__(self):\n self.root = None\n \n def __str__(self):\n return \"avl tree\"\n \n def insert(self, key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n self.root = self.__avl_insert(self.root, key)\n \n def find(self, key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n return bst_find(self.root, key) \n \n def delete(self,key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n if self.root == None:\n raise Exception(\"Tree is empty\")\n self.root = self.__avl_delete(self.root, key)\n pass\n\n def __iter__(self):\n return iterator(tree_visit_level_order(self.root))\n \n #\n # private utilis methods for avl tree\n #\n\n def __avl_insert(self, node, key):\n \n if node == None:\n n = tree_node(key)\n n.count = 1\n return n\n if key < node.key:\n node.left = self.__avl_insert(node.left, key)\n height = tree_balance_check(node)\n if height == 2:\n if key < node.left.key:\n node = self.__ll_rotation(node)\n else:\n node = self.__lr_rotation(node)\n elif key > node.key:\n node.right = self.__avl_insert(node.right, key)\n height = tree_compute_height(node)\n if height == -2:\n if key < node.right.key:\n node = self.__rl_rotatation(node)\n else:\n node = self.__rr_rotations(node)\n else:\n node.key = key\n\n node.height = tree_compute_height(node)\n node.count = tree_size(node.left) + tree_size(node.right) + 1\n\n return node\n\n def __avl_delete(self, node, key):\n #like bst deletation + rebalacing stuff\n if key < node.key:\n node.left = self.__avl_delete(node.left, key)\n h = tree_balance_check(node)\n if h == -2:\n if tree_balance_check(node.right) <= 0:\n node = self.__rr_rotations(node)\n else:\n node = self.__rl_rotatation(node)\n elif key > node.key:\n node.right = self.__avl_delete(node.right, key)\n h = tree_balance_check(node)\n if h == 2:\n if tree_balance_check(node.left) <= 0:\n node = self.__ll_rotation(node)\n else:\n node = self.__lr_rotation(node)\n else:\n #equal to std bst deletation\n if node.left == None:\n return node.right\n if node.right == None:\n return node.left\n\n t = node\n node = tree_min(t.right)\n node.right = tree_delete_min(t.right)\n node.left = t.left\n node.count = tree_size(node.left) + tree_size(node.right) + 1\n node.height = tree_compute_height(node)\n\n return node\n\n def __ll_rotation(self, node):\n node = tree_rotate_right(node)\n return node\n \n def __lr_rotation(self, node):\n node.left = tree_rotate_left(node.left)\n node = tree_rotate_right(node)\n return node\n\n def __rl_rotatation(self, node):\n node.right = tree_rotate_right(node.right)\n node = tree_rotate_left(node)\n return node\n\n def __rr_rotations(self, node):\n node = tree_rotate_left(node)\n return node\n","sub_path":"searching/avl_tree.py","file_name":"avl_tree.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"362209062","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport pytest\nimport mock\n\nfrom h.presenters.group_json import GroupJSONPresenter, GroupsJSONPresenter\nfrom h.services.group_links import GroupLinksService\n\n\nclass TestGroupJSONPresenter(object):\n def test_private_group_asdict_no_links_svc(self, factories):\n group = factories.Group(name='My Group',\n pubid='mygroup')\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'mygroup',\n 'type': 'private',\n 'public': False,\n 'scoped': False,\n 'urls': {},\n 'links': {}\n }\n\n def test_open_group_asdict_no_links_svc(self, factories):\n group = factories.OpenGroup(name='My Group',\n pubid='mygroup')\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'mygroup',\n 'type': 'open',\n 'public': True,\n 'scoped': False,\n 'urls': {},\n 'links': {}\n }\n\n def test_open_scoped_group_asdict(self, factories):\n group = factories.OpenGroup(name='My Group',\n pubid='groupy',\n scopes=[factories.GroupScope(origin='http://foo.com')])\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'groupy',\n 'type': 'open',\n 'public': True,\n 'scoped': True,\n 'urls': {},\n 'links': {},\n }\n\n def test_private_group_asdict_with_links_svc(self, factories, links_svc):\n group = factories.Group(name='My Group',\n pubid='mygroup')\n presenter = GroupJSONPresenter(group, links_svc=links_svc)\n links_svc.get_all.return_value = {'html': 'bar'}\n\n model = presenter.asdict()\n\n links_svc.get_all.assert_called_once_with(group)\n assert model['urls'] == links_svc.get_all.return_value\n assert model['links'] == links_svc.get_all.return_value\n assert model['url'] == links_svc.get_all.return_value['html']\n\n def test_open_group_asdict_with_links_svc(self, factories, links_svc):\n group = factories.OpenGroup(name='My Group',\n pubid='mygroup')\n presenter = GroupJSONPresenter(group, links_svc=links_svc)\n\n presenter.asdict()\n\n links_svc.get_all.assert_called_once_with(group)\n\n\nclass TestGroupsJSONPresenter(object):\n\n def test_proxies_to_GroupJSONPresenter(self, factories, GroupJSONPresenter_, links_svc): # noqa: [N802, N803]\n groups = [factories.Group(), factories.OpenGroup()]\n presenter = GroupsJSONPresenter(groups, links_svc=links_svc)\n expected_call_args = [mock.call(group, links_svc) for group in groups]\n\n presenter.asdicts()\n\n assert GroupJSONPresenter_.call_args_list == expected_call_args\n\n def test_asdicts_returns_list_of_dicts(self, factories):\n groups = [factories.Group(name=u'filbert'), factories.OpenGroup(name=u'delbert')]\n presenter = GroupsJSONPresenter(groups)\n\n result = presenter.asdicts()\n\n assert [group['name'] for group in result] == [u'filbert', u'delbert']\n\n def test_asdicts_injects_urls(self, factories, links_svc):\n groups = [factories.Group(), factories.OpenGroup()]\n presenter = GroupsJSONPresenter(groups, links_svc)\n\n result = presenter.asdicts()\n\n for group_model in result:\n assert 'urls' in group_model\n assert 'links' in group_model\n\n\n@pytest.fixture\ndef links_svc():\n return mock.create_autospec(GroupLinksService, spec_set=True, instance=True)\n\n\n@pytest.fixture\ndef GroupJSONPresenter_(patch): # noqa: N802\n return patch('h.presenters.group_json.GroupJSONPresenter')\n","sub_path":"tests/h/presenters/group_json_test.py","file_name":"group_json_test.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"496336175","text":"# ----------------------------------------------------\n# Name: Nicholas Houchois\n# UNI: nbh2119\n# \n# Module for various effects to be applied to .ppm images.\n# ----------------------------------------------------\nimport re\nimport linecache\n\n\ndef parse_file(file):\n \"\"\" Parses the file and returns a list of pixels \"\"\"\n pixels = []\n\n # get string from file\n text = file.read()\n\n # create list of tokens delimited by whitespace\n tokens = text.split()\n\n # remove header from list\n del tokens[0:4]\n\n pixels = []\n\n # created list of pixels (which are a list of RGB values)\n i = 0\n while i in range(len(tokens)):\n pixels.append(tokens[i:i + 3])\n i += 3\n\n return pixels\n\n\ndef get_header(file):\n \"\"\" Returns the header of the file as a list \"\"\"\n header = []\n i = 0\n while len(header) < 4:\n line = linecache.getline(file.name, i)\n i += 1\n tokens = line.split()\n for token in tokens:\n if len(header) < 4:\n if token:\n header.append(token)\n return header\n\n\ndef write_output(output, outfile):\n \"\"\" Removes all non number characters and writes to file\"\"\"\n\n string = re.sub(r'\\D', \" \", str(output))\n outfile.write(string)\n\n\ndef negate_color(in_file, out_name, index):\n \"\"\" Negates the color specified by index \"\"\"\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n\n for i in range(len(pixels)):\n for j in range(len(pixels[i])):\n # if RGB value is the one to be negated\n if j == index:\n output.append(str(int(header[3]) - int(pixels[i][index])))\n # append other two values without modification\n else:\n output.append(pixels[i][j])\n\n # write header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n\n\ndef object_filter(in_file_list, outfile_name):\n \"\"\"\n Filters out pixel values that appear in only a minority\n of the images in the parameter in_file_list.\n \"\"\"\n images = []\n outfile = open(outfile_name, \"w\")\n\n header = get_header(in_file_list[0])\n\n for file in in_file_list:\n pixels = parse_file(file)\n\n images.append(pixels)\n\n output = []\n\n for i in range(len(pixels)):\n for j in range(len(pixels[i])):\n compare_list = []\n\n # compare images and select majority\n for k in range(len(images)):\n compare_list.append(images[k][i][j])\n compare_list.sort()\n\n # append to output list\n output.append(compare_list[len(compare_list) // 2])\n\n # write header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n\n outfile.close()\n\n\ndef shades_of_gray(in_file, out_name):\n \"\"\"Converts the color image in_file to black and white\"\"\"\n\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n\n for i in range(len(pixels)):\n sum = 0\n\n # calculate the average of the RGB values in a pixel\n for j in range(len(pixels[i])):\n sum += int(pixels[i][j])\n average = int(sum / 3)\n\n # append the average three times (once for each RGB value)\n output.append(average)\n output.append(average)\n output.append(average)\n\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n\n\ndef negate_red(in_file, out_name):\n \"\"\"Negates the red in an image\"\"\"\n negate_color(in_file, out_name, 0)\n\n\ndef negate_green(in_file, out_name):\n \"\"\"Negates the green in an image\"\"\"\n\n negate_color(in_file, out_name, 1)\n\n\ndef negate_blue(in_file, out_name):\n \"\"\"Negates the blue in an image\"\"\"\n\n negate_color(in_file, out_name, 2)\n\n\ndef mirror(in_file, out_name):\n \"\"\"Creates a mirror image by flipping an image horizontally\"\"\"\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n columns = int(header[1])\n rows = int(header[2])\n\n # iterates through each row\n for i in range(rows):\n row = pixels[i * columns: (i + 1) * columns]\n # reverses the row\n for pixel in reversed(row):\n output.append(pixel)\n\n # writes header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n","sub_path":"OneDrive/Columbia/Python/HW4/effects.py","file_name":"effects.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"384933988","text":"def printFrameNumber(vid):\r\n print('frame ' + str(int(vid.get(1))) + ' of ' + str(int(vid.get(7))))\r\n\r\n'''\r\nvid.get(1) - current frame (float)\r\nvid.get(3) - vid width\r\nvid.get(4) - vid height\r\nvid.get(7) - total frames (float)\r\n\r\ncv2.imwrite('filename', image)\r\nret, frame = vid.read()\r\n'''\r\nimport cv2\r\nimport numpy as np\r\nimport time\r\n\r\n#template0 = cv2.imread('lFlapTemplate.jpg')\r\ntemplate1 = cv2.imread('tr_corner_template.png')\r\ntemplate2 = cv2.imread('star_template.png')\r\ntemplate3 = cv2.imread('1_small_template.png')\r\ntemplate4 = cv2.imread('1_small_template2.png')\r\n#template0 = cv2.cvtColor(template0, cv2.COLOR_BGR2GRAY)\r\ntemplate1 = cv2.cvtColor(template1, cv2.COLOR_BGR2GRAY)\r\ntemplate2 = cv2.cvtColor(template2, cv2.COLOR_BGR2GRAY)\r\ntemplate3 = cv2.cvtColor(template3, cv2.COLOR_BGR2GRAY)\r\ntemplate4 = cv2.cvtColor(template4, cv2.COLOR_BGR2GRAY)\r\n\r\nfilename = 'test_big.mp4'\r\nvid = cv2.VideoCapture(filename)\r\nhole_started = False\r\n\r\nif filename[-3:].lower() == 'mov':\r\n minXOR1 = 0\r\n maxXOR1 = 300\r\n minXOR2 = 0\r\n maxXOR2 = 300\r\nelif filename[-3:].lower() == 'mp4':\r\n minXOR1 = int(vid.get(4))-300\r\n maxXOR1 = int(vid.get(4))\r\n minXOR2 = 0\r\n maxXOR2 = 300\r\nelse:\r\n raise Exception('video format ' + filename[-3:]+' not supported')\r\n\r\nvid.set(1,33650)\r\nlast_maxVal = 0\r\n_, last_frame = vid.read()\r\nprint('Doing frame-by-frame analysis. Please wait...')\r\nstart_time = time.time()\r\nwhile vid.get(1) < 36200-1:\r\n _, frame = vid.read()\r\n \r\n frametmp = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n frametmp = cv2.adaptiveThreshold(frametmp,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,-10)\r\n tempMatch = cv2.matchTemplate(frametmp, template3, cv2.TM_CCORR_NORMED, template3)\r\n tempMatchIMG = cv2.normalize(tempMatch, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n _,maxVal,_,location0 = cv2.minMaxLoc(tempMatch)\r\n \r\n if maxVal-last_maxVal > 0.05 or maxVal > 0.7:\r\n print(maxVal)\r\n cv2.rectangle(frame, location0, (location0[0]+25, location0[1]+25), (0,0,255),1)\r\n cv2.imshow('frame',frame)\r\n cv2.imshow('tempMatch1',tempMatch)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n \r\n last_maxVal = maxVal\r\n last_frame = frame","sub_path":"findFirstFlap2.py","file_name":"findFirstFlap2.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"630619101","text":"\"\"\"\npython网络数据采集第二章\nBeautifulsoup解析'http://www.pythonscraping.com/pages/warandpeace.html'\n小说名字为红色,对话为绿色,通过class属性过滤\n\"\"\"\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\n\ndef getHTMLText(url):\n try:\n html = urlopen(url)\n except HTTPError as e:\n return None\n try:\n soup = BeautifulSoup(html, 'html.parser')\n nameList = soup.findAll(\"span\", {\"class\":\"green\"}) #找出所有标签中内容\n except AttributeError as e:\n return None\n return nameList\nurl = 'http://www.pythonscraping.com/pages/warandpeace.html'\nlists = getHTMLText(url)\nfor list in lists:\n print(list.get_text()) #get_text()获得标签内的文字","sub_path":"spider/exe-5.py","file_name":"exe-5.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573540845","text":"#Python Pre Work\n\n#Question 1\ndef hello(name):\n print(\"Hello \" + name.upper()+ \"!\")\n\nhello('christian')\n\n#Question 2\ndef odd_numbers():\n\tnumbers = list(range(0, 100))\n\tfor number in numbers:\n\t\tif number % 2 != 0:\n\t\t\tprint(number)\n \nodd_numbers()\n\n#Question 3\ndef max_num_in_list(a_list):\n max_num = max(a_list)\n return max_num\n\ntest = max_num_in_list([19,7,3,26,2])\nprint(max_num_in_list([19,7,3,26,2]))\n\n#Question 4\ndef is_leap_year(a_year):\n if a_year % 4 == 0 and a_year % 100 != 0:\n print(f'{a_year} is a leap year')\n elif a_year % 400 == 0:\n print(f'{a_year} is a leap year')\n else:\n a_year = False\n print(f'{a_year}')\n\nis_leap_year(2013)\n\n\n#Question 5\ndef is_consecutive(a_list):\n i = 0\n status = True\n while i < len(a_list) - 1:\n if a_list[i] + 1 == a_list[i + 1]:\n i += 1\n else:\n status = False\n break\n print(status)\n\n","sub_path":"prework.py","file_name":"prework.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"42610482","text":"import subprocess\nimport logging\nimport re\nimport sys\n\n\ntry:\n from scapy.all import *\nexcept ImportError:\n print(\"Scapy is not installed in your system.\\n\") \n print(\"Try using : pip3 install scapy\\n\")\n sys.exit()\n#This will suppress all messeges that have a lover level of seriousness than error messeges\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR) \nlogging.getLogger(\"scapy.interactive\").setLevel(logging.ERROR) \nlogging.getLogger(\"scapy.loading\").setLevel(logging.ERROR) \n\n#Setting the checkIPaddr parameter to False\nconf.checkIPaddr = False\n\n#Reading allowed DHCP servers from an external file\nwith open(\"dhcp.txt\") as f:\n allowed_dhcp_servers = f.read()\n\n#Listing all network interfaces on the ubuntu host\nhost_if = subprocess.run(\"ip link\", shell=True, stdout=subprocess.PIPE)\n\n#Extracting the interfaces name from the output stored above\ninterfaces = re.findall(r\"\\d:\\s(.+?):\\s\", str(host_if))\n\n\ntry:\n #Detecting Rogue DHCP servers per interface (except loopback interface)\n for interface in interfaces:\n if interface != 'lo':\n #Getting the hardware address\n mac_add = get_if_raw_hwaddr(interface)[1]\n # print(mac_add)\n\n #Creating DHCP discover packet\n dhcp_discover = Ether(dst = 'ff:ff:ff:ff:ff:ff') / IP(src = '0.0.0.0', dst = '255.255.255.255') / UDP(sport = 68, dport = 67) / BOOTP(chaddr = mac_add) / DHCP(options = [('message-type', 'discover'), 'end'])\n \n #Sending the Dicover Packet and accepting multiple answers for the same Discover Packet\n ans, unans = srp(dhcp_discover, multi=True, iface=interface, timeout=5, verbose=0)\n # print(ans)\n # print(unans)\n\n #Defining a dictionary to store mac-ip pairs\n mac_ip_pair = {}\n\n for pair in ans:\n mac_ip_pair[pair[1][Ether].src] = pair[1][IP].src\n\n if ans:\n #Printing the results\n print(\"\\n --> The following DHCP servers found on the {} LAN: \\n\".format(interface))\n\n for mac, ip in mac_ip_pair.items():\n if ip in allowed_dhcp_servers:\n print(\"OK! IP Address : {},MAC Address : {}\\n\".format(ip,mac))\n else:\n print(\"ROGUE! IP Address : {},MAC Address : {}\\n\".format(ip,mac)) \n\n else:\n print(\"\\n --> No active DHCP servers found on the {} LAN\\n\".format(interface)) \n else:\n pass\n\nexcept KeyboardInterrupt:\n print(\"\\nProgram aborted by the user!!! Exiting...\")\n sys.exit() ","sub_path":"Rogue DHCP Server Discovery Tool/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394948198","text":"import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\n# 데이터 읽어오기\nmr = pd.read_csv(\"../data/mushroom.csv\", header=None) # 헤더�� 인덱스로 바꿈\n# 데이터 내부의 분류 변수 전개하기\nlabel = []\ndata = []\nattr_list = []\nfor row_index, row in mr.iterrows():\n label.append(row.iloc[0]) # 독버섯, 일반버섯 분류\n # 각행의 0번 열은 독 or 일반 확인 가능\n exdata = []\n for col, v in enumerate(row[1:]):\n if row_index == 0 :\n attr = {\"dic\":{},\"cnt\":0}\n attr_list.append(attr)\n else :\n attr = attr_list[col]\n # 버섯 특징 기호 저장 최소2개 ~ 최대12개\n d = [0,0,0,0,0,0,0,0,0,0,0,0]\n if v in attr[\"dic\"]:\n idx = attr[\"dic\"][v]\n else :\n idx = attr[\"cnt\"]\n attr[\"dic\"][v] = idx\n attr[\"cnt\"] += 1\n d[idx] = 1\n exdata += d\n data.append(exdata)\n\n# 학습용 데이터용 분류\ndata_train, data_test, label_train, label_test = train_test_split(data, label)\n\n# 데이터 학습\nclf = RandomForestClassifier()\nclf.fit(data_train,label_train)\n\n# 데이터 예측\npredict = clf.predict(data_test)\n\n# 결과 테스트\nac_score = metrics.accuracy_score(label_test,predict)\ncl_report = metrics.classification_report(label_test,predict)\nprint(\"정답률 :\",ac_score)\nprint(\"리포트 :\")\nprint(cl_report)\n\n","sub_path":"PythonAI/Practice/DAY09/src/Mushroom_Train.py","file_name":"Mushroom_Train.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"9853638","text":"#Maddy Chan 12/7/15\n#Cracking the Coding Interview 10.4\n#Given a list which contains sorted, positive integers, no info about the size\n#and where if you index somewhere out of bounds it will give -1,\n#write an algorithm that will find x in the list.\n\n\n\n\n\n\ndef searchList(x: int, start: int, end: int, l: list):\n if start == end:\n return start if l[start] == x else -1\n elif l[end] > x or l[end] == -1:\n half = int((end-start)/2) + start\n if l[half] == x:\n return half\n elif l[half] > x or l[half] == -1:\n return searchList(x,start,half,l)\n else:\n return searchList(x,half,end-1,l)\n else:\n return searchList(x,end,end+(end-start),l)\n\n\n\nl = [1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,-1]\n\nprint(searchList(9,0,6,l))\n","sub_path":"codingInterview10.4.py","file_name":"codingInterview10.4.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"261547892","text":"'''\n@Description: \n@Author: Fishermanykx\n@LastEditors: Fishermanykx\n@LastEditTime: 2020-03-17 20:58:25\n'''\nfrom pprint import pprint\n\n\nclass CPUSimulator:\n\n def __init__(self, filename):\n \"载入含机器码的文件\"\n # 初始化寄存器文件(int-int)\n self.regFile = {} # 寄存器文件,编号依次为0~7\n for i in range(8):\n self.regFile[i] = 0\n # 初始化内存\n self.memory = [0] * 1000 # 内存\n self.rip = 0 # instruction pointer\n # 构建指令文件(str-str)\n self.instruction_file = {}\n inf = open(filename + \".bin\", \"r\")\n while True:\n line = inf.readline()\n if line == '':\n break\n line = line.split()\n address = line[0]\n self.instruction_file[int(address)] = line[1]\n inf.close()\n # pprint(self.instruction_file)\n\n def MainProcess(self):\n '''\n @description: 主流程,采用流水线CPU\n '''\n self.has_next_ins = True\n self.jmp = False\n cnt_loop = 0\n\n while True:\n ins = self.Fetch()\n slided_ins = self.Decode(ins)\n self.Execute(slided_ins)\n self.Memory()\n self.WriteBack()\n if not self.has_next_ins:\n if cnt_loop == 3:\n break\n else:\n cnt_loop += 1\n\n def Fetch(self):\n '''\n @description: 取指阶段\n @param {type} \n @return: 取出的二进制指令(str)\n '''\n try:\n ins = self.instruction_file[self.rip]\n self.rip += 1\n except: # 若已经执行完毕,则传入气泡\n ins = \"01\"\n return ins\n\n def Decode(self, ins):\n '''\n @description: 译码阶段: 将二进制指令转换为opcode与操作数(十进制int)\n @param {type}: ins{str}\n @return: list\n '''\n opcode = ins[0:2]\n res = []\n # 根据指令类型切分\n op_type = int(opcode[0])\n if op_type == 0:\n self.has_next_ins = False\n res = [\"00\"]\n elif op_type == 1:\n res = [\"00\"]\n elif op_type == 2:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n elif op_type == 3:\n res.append(opcode)\n res.append(None)\n res.append(self.regFile[int(ins[3])])\n res.append(self.ConvertImmNum(ins[4:]))\n elif op_type == 4 or op_type == 5:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n res.append(self.ConvertImmNum(ins[4:]))\n elif op_type == 6:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n elif op_type == 7 or op_type == 8:\n res.append(opcode)\n res.append(self.ConvertImmNum(ins[2:]))\n elif op_type == 8:\n res.append(opcode)\n elif op_type == 10 or op_type == 11:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(None)\n else:\n print(\"Error: Illegal instruction. Exit code: INS\")\n exit(1)\n return res\n\n def Execute(self, slided_ins):\n '''\n @description: 执行阶段\n @param {type} 根据opcode与操作数执行指令\n @return: 计算所得的结果\n '''\n self.HazardUnit()\n\n def Memory(self):\n '''\n @description: 访存阶段\n @param {type} \n @return: 将执行阶段的值写回内存或从内存中取出值\n '''\n pass\n\n def WriteBack(self):\n '''\n @description: 写回阶段\n @param {type} \n @return: 将计算结果写回寄存器文件\n '''\n pass\n\n def HazardUnit(self):\n '''\n @description: 冲突单元\n @param {type} \n @return: \n '''\n pass\n\n def ConvertImmNum(self, num_str):\n '''\n @description: 将用小端法表示的立即数转换为十进制整数\n @param {type} num_str {str}\n @return: int\n '''\n '''\n >>> ConvertImmNum(\"10000000\")\n 16\n >>> ConvertImmNum(\"10100000\")\n 4112\n '''\n # 将立即数反转为正常顺序\n rev_str = \"\"\n for i in range(6, 0, -2):\n rev_str += (num_str[i] + num_str[i + 1])\n return int(\"0x\" + rev_str, 16)\n\n\nif __name__ == \"__main__\":\n simulator = CPUSimulator(\n \"D:/Materials_Study/Computer_Science/Computer_Architecture/Exercises/Y86-64_CPU_Simulator/cpu_simulator/testbench\"\n ) # Windows\n # simulator = CPUSimulator(\n # \"/media/fisher/DATA/Materials_Study/Computer_Science/Computer_Architecture/Exercises/Y86-64_CPU_Simulator/cpu_simulator/testbench\"\n # ) # Linux\n simulator.MainProcess()\n reg = 0\n print(simulator.regFile[reg]) # 结果的值在rax里\n","sub_path":"Y86-64_CPU_Simulator/cpu_simulator/Y86_simulator.py","file_name":"Y86_simulator.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"65077462","text":"from selenium import webdriver\nfrom time import sleep\nfrom PIL import Image\nimport pytesseract\n\n\n\nclass Bot:\n def __init__(self):\n self.driver = webdriver.Firefox()\n self.navigate()\n\n def take_screenshot(self):\n self.driver.save_screenshot('avito_screenshot.png')\n\n def tel_recon(self):\n pytesseract.pytesseract.tesseract_cmd = r\"C:\\Users\\happy\\AppData\\Local\\Tesseract-OCR\\tesseract.exe\"\n image = Image.open('tel.gif')\n print(pytesseract.image_to_string(image))\n\n def crop(self, location, size):\n image = Image.open('avito_screenshot.png')\n x = location['x']\n y = location['y']\n width = size['width']\n height = size['height']\n\n image.crop((x, y, x+width, y+height)).save('tel.gif')\n self.tel_recon()\n\n def navigate(self):\n self.driver.get('https://www.avito.ru/ekaterinburg/telefony/iphone_x_1835790565')\n\n button = self.driver.find_element_by_xpath('//a[@class=\"button item-phone-button js-item-phone-button button-origin button-origin-blue button-origin_full-width button-origin_large-extra item-phone-button_hide-phone item-phone-button_card js-item-phone-button_card\"]')\n button.click()\n\n sleep(3)\n\n self.take_screenshot()\n\n image = self.driver.find_element_by_xpath('//div[@class=\"item-phone-big-number js-item-phone-big-number\"]//*')\n location = image.location #dict {'x': 2323, 'y': 23423}\n size = image.size # dict {'width': 234, 'height': 234}\n\n self.crop(location, size)\n\ndef main():\n b = Bot()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"OlegMolchanov's_Py_lesson/Parsing/Avito_tel/avito.py","file_name":"avito.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"226040055","text":"#!/usr/bin/env python3\nimport sys\nimport os.path\nimport re\n\ndef increase_style_resource_id_value(path, delta=100):\n\tdoc = open(path, encoding='utf-8', newline='\\n').read()\n\tupdated = re.sub(r'\\d{5}', lambda m: str(int(m.group(0)) + delta), doc)\n\tprint('update:', path)\n\twith open(path, 'w', encoding='utf-8', newline='\\n') as fp:\n\t\tfp.write(updated)\n\ndef check_encoding_list(path):\n\tdef is_tag_char(ch):\n\t\treturn (ch >= 'a' and ch <= 'z') or (ch >= '0' and ch <= '9')\n\n\tdoc = open(path, encoding='utf-8', newline='\\n').read()\n\tlines = doc.splitlines()\n\tstarted = False\n\tname_map = {}\n\ttag_map = {}\n\tpage_map = {}\n\n\tfor index, line in enumerate(lines):\n\t\tif not started:\n\t\t\tstarted = line.startswith('NP2ENCODING mEncoding[] = {')\n\t\telif line.startswith('};'):\n\t\t\tbreak\n\t\telse:\n\t\t\tstart = line.find('\"')\n\t\t\tif start < 0:\n\t\t\t\tcontinue\n\t\t\tstart += 1\n\t\t\tend = line.index('\"', start)\n\t\t\ttag = line[start:end]\n\t\t\tif not tag:\n\t\t\t\tcontinue\n\n\t\t\tstart = line.index(',') + 1\n\t\t\tend = line.index(',', start)\n\t\t\tpage = line[start:end].strip()\n\n\t\t\tlineno = index + 1\n\t\t\tif tag[-1] != ',':\n\t\t\t\tprint('missing trailing comma at line:', lineno, page, tag)\n\t\t\ts = ''.join(tag.split())\n\t\t\tif s != tag:\n\t\t\t\tprint('space in encoding at line:', lineno, page, tag)\n\n\t\t\titems = tag[:-1].split(',')\n\t\t\tname = items[0].lower()\n\t\t\titems = items[1:]\n\t\t\ts = ''.join(items)\n\t\t\tif any(not is_tag_char(ch) for ch in s):\n\t\t\t\tprint('tag not normalized at line:', lineno, page, tag)\n\n\t\t\tif name not in name_map:\n\t\t\t\tname_map[name] = [lineno]\n\t\t\telse:\n\t\t\t\tname_map[name].append(lineno)\n\n\t\t\tfor item in items:\n\t\t\t\tif item not in tag_map:\n\t\t\t\t\ttag_map[item] = [lineno]\n\t\t\t\telse:\n\t\t\t\t\ttag_map[item].append(lineno)\n\n\t\t\tif page not in page_map:\n\t\t\t\tpage_map[page] = [lineno]\n\t\t\telse:\n\t\t\t\tpage_map[page].append(lineno)\n\n\tfor name, lines in name_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same encoding name:', name, lines)\n\tfor tag, lines in tag_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same encoding tag:', tag, lines)\n\tfor page, lines in page_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same code page:', page, lines)\n\n#increase_style_resource_id_value('../src/EditLexers/EditStyle.h')\ncheck_encoding_list('../src/EditEncoding.c')\n","sub_path":"tools/Misc.py","file_name":"Misc.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"230316337","text":"#! /usr/bin/python\n\n\"\"\"\nLinearRegression.py\n\nThis class is designed to perform linear regression (gradient descent) \non a dataset and then be able to predict given new x labels.\n\"\"\"\n\n__author__ = 'Manan Mehta'\n__email__ = 'mehtamanan@icloud.com'\n__version__ = '1.0.0'\n\nimport sys\nimport numpy as np\nimport plotly as py\nimport matplotlib.pyplot as plt\n\nfrom Exceptions import *\n\nclass LinearRegression(object):\n \"\"\" \n Contains methods to load data, normalize data, plot data and predict outputs\n \"\"\"\n\n def __init__(self):\n self.norm = False #Data has not been normalized\n self.gd = False #Gradient descent has not been carried out\n\n def load_data(self, *files):\n \"\"\"\n If two files are given, the first one is assumed\n to contain X values and the second one, Y.\n If one file is given, the last column is assumed\n to contain Y values and the columns before, X.\n \"\"\"\n if len(files) == 1:\n dataXY = np.matrix(np.genfromtxt(files[0], delimiter = ','))\n pos = dataXY.shape[1]\n y = dataXY[:, pos -1]\n X = dataXY[:, :pos - 1]\n else:\n X = np.matrix(np.genfromtxt(files[0], delimiter = ','))\n y = np.matrix(np.genfromtxt(files[1], delimiter = ','))\n ones = np.matrix(np.ones(shape = (X.shape[0], 1)))\n self.X = np.hstack((ones, X))\n self.y = y\n self.theta = np.matrix(np.zeros(shape = (self.X.shape[1], 1)))\n self.norm = False\n self.gd = False\n self.gradient_descent()\n\n def plot(self):\n \"\"\"\n Plots the loaded data and the prediction line\n Throws DataHandlingException if more than one x-label\n Throws NoDataException if data is not loaded\n \"\"\"\n if not hasattr(self, 'X'): # To raise an exception is data is not loaded\n raise NoDataException()\n elif self.X.shape[1] > 2: # To raise an exception if there way to many exceptions\n raise DataHandlingException()\n else:\n X = self.X[:,1]\n y = self.X * self.theta\n plt.plot(self.X[:,1], self.y, 'rx', X, y, 'g-')\n plt.show()\n\n def normalize(self):\n \"\"\"\n Normalizes the data such that the mean is 0\n and the data fits -0.5 2:\n return False\n else:\n return True\n","sub_path":"LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"557492285","text":"import datetime as dt\nimport json\n\nimport numpy as np\nimport pytest\n\nfrom slim.simulation.lice_population import LicePopulation, from_dict, geno_to_alleles\nfrom slim.simulation.cage import Cage\nfrom slim.simulation.config import to_dt\nfrom slim.types.treatments import Treatment\n\n\nclass TestFarm:\n def test_farm_loads_params(self, first_farm):\n assert first_farm.id_ == 0\n assert len(first_farm.cages) == 6\n assert first_farm.loc_x == 190300\n assert first_farm.loc_y == 665300\n assert first_farm.available_treatments == 10\n\n def test_farm_str(self, first_farm):\n farm_str = str(first_farm)\n assert isinstance(farm_str, str)\n assert len(farm_str) > 0\n assert \"id: 0\" in farm_str\n\n def test_year_temperatures(self, first_farm):\n tarbert = first_farm.cfg.loch_temperatures[1][1:]\n ardrishaig = first_farm.cfg.loch_temperatures[0][1:]\n temps = np.stack([tarbert, ardrishaig])\n min_temps = np.round(np.min(temps, axis=0), 1)\n max_temps = np.round(np.max(temps, axis=0), 1)\n assert all(min_temps <= first_farm.year_temperatures)\n assert all(first_farm.year_temperatures <= max_temps)\n\n def test_farm_update(self, first_farm):\n # TODO: test integration across **all** cages. Requires further refactoring.\n pass\n\n def test_get_cage_pressures(self, first_farm, initial_external_inflow):\n\n first_farm.cfg.min_ext_pressure = 100\n first_farm.cages = [0] * 10\n\n pressures = first_farm.get_cage_pressures(100)\n\n assert len(pressures) == len(first_farm.cages)\n assert sum(pressures) == first_farm.cfg.min_ext_pressure * 10\n\n for pressure in pressures:\n assert pressure >= 0\n\n def test_get_cage_pressures_negative_pressure(self, first_farm):\n\n first_farm.cfg.min_ext_pressure = -100\n first_farm.cages = [0] * 10\n\n with pytest.raises(Exception):\n first_farm.get_cage_pressures()\n\n def test_get_cage_pressures_zero_pressure(self, first_farm):\n first_farm.cfg.min_ext_pressure = 0\n first_farm.cages = [0] * 10\n\n pressures = first_farm.get_cage_pressures(0)\n\n assert len(pressures) == len(first_farm.cages)\n assert sum(pressures) == first_farm.cfg.min_ext_pressure\n\n def test_get_cage_pressures_no_cages(self, first_farm):\n\n first_farm.cfg.min_ext_pressure = 100\n first_farm.cages = []\n\n with pytest.raises(Exception):\n first_farm.get_cage_pressures()\n\n @pytest.mark.parametrize(\n \"eggs_by_hatch_date\",\n [\n {\n to_dt(\"2017-02-01 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 200,\n \"Aa\": 300,\n }\n ),\n to_dt(\"2017-02-10 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 200,\n \"Aa\": 300,\n }\n ),\n },\n {},\n ],\n )\n def test_get_cage_allocation(self, first_farm, eggs_by_hatch_date):\n\n allocation = first_farm.get_cage_allocation(6, eggs_by_hatch_date)\n\n # Originally, this would extract the allocation for each gene\n allocation_list = [\n np.sum(n)\n for bin_dict in allocation\n for hatch_dict in bin_dict.values()\n for n in hatch_dict.values()\n ]\n if eggs_by_hatch_date == {}:\n sum_eggs_by_hatch_date = 0\n else:\n sum_eggs_by_hatch_date = sum(\n sum(\n [\n n\n for hatch_dict in eggs_by_hatch_date.values()\n for n in hatch_dict.values()\n ]\n )\n )\n\n assert sum(allocation_list) == sum_eggs_by_hatch_date\n assert len(allocation) == len(first_farm.cages)\n\n for n in allocation_list:\n assert n >= 0\n\n allocation_keys_list = [list(bin_dict.keys()) for bin_dict in allocation]\n hatch_keys = list(eggs_by_hatch_date.keys())\n for allocation_keys in allocation_keys_list:\n assert allocation_keys == hatch_keys\n\n def test_get_farm_allocation(\n self, first_farm, second_farm, sample_offspring_distrib\n ):\n first_farm.cfg.interfarm_probs[first_farm.id_][second_farm.id_] = 0.1\n\n total_eggs_by_date = {first_farm.start_date: sample_offspring_distrib}\n farm_eggs_by_date = first_farm.get_farm_allocation(\n second_farm.id_, total_eggs_by_date\n )\n\n assert len(farm_eggs_by_date) == len(total_eggs_by_date)\n assert (\n farm_eggs_by_date[first_farm.start_date].keys()\n == total_eggs_by_date[first_farm.start_date].keys()\n )\n for geno in geno_to_alleles(\"a\"):\n assert (\n farm_eggs_by_date[first_farm.start_date][geno]\n <= total_eggs_by_date[first_farm.start_date][geno]\n )\n\n def test_get_farm_allocation_empty(self, first_farm, second_farm):\n farm_eggs_by_date = first_farm.get_farm_allocation(second_farm, {})\n assert farm_eggs_by_date == {}\n\n def test_disperse_offspring(self, first_farm, second_farm):\n farms = [first_farm, second_farm]\n eggs_by_hatch_date = {\n to_dt(\"2017-01-05 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 100,\n \"Aa\": 100,\n }\n )\n }\n cur_date = to_dt(\"2017-01-01 00:00:00\")\n\n new_rng = np.random.default_rng(seed=2021)\n farms[0].cfg.rng = new_rng\n farms[0].cages = farms[0].cages[:2]\n farms[1].cages = farms[1].cages[:2]\n\n arrivals_farm0 = farms[0].disperse_offspring(eggs_by_hatch_date, cur_date)\n arrivals_farm1 = farms[1].disperse_offspring(eggs_by_hatch_date, cur_date)\n farms[0].update_arrivals(arrivals_farm0[0])\n farms[0].update_arrivals(arrivals_farm1[0])\n\n # Only for the calling cage\n for cage in first_farm.cages:\n assert cage.arrival_events.qsize() >= 1\n\n def test_get_cage_arrivals_stats(self, first_farm, cur_day):\n\n next_day = cur_day + dt.timedelta(1)\n\n cage_1 = {\n cur_day: from_dict(\n {\n \"A\": 10,\n \"a\": 10,\n \"Aa\": 10,\n }\n ),\n next_day: from_dict(\n {\n \"A\": 10,\n \"a\": 10,\n \"Aa\": 20,\n }\n ),\n }\n\n cage_2 = {\n cur_day: from_dict(\n {\n \"A\": 5,\n \"a\": 5,\n \"Aa\": 5,\n }\n ),\n next_day: from_dict(\n {\n \"A\": 5,\n \"a\": 5,\n \"Aa\": 10,\n }\n ),\n }\n\n arrivals = [cage_1, cage_2]\n\n total, by_cage, _ = first_farm.get_cage_arrivals_stats(arrivals)\n\n assert total == 105\n assert by_cage == [70, 35]\n\n def test_farm_update_before_start(\n self, first_farm, initial_external_inflow, initial_external_ratios\n ):\n cur_date = first_farm.start_date - dt.timedelta(1)\n offspring, cost = first_farm.update(\n cur_date, initial_external_inflow, initial_external_ratios\n )\n\n assert offspring == {}\n assert cost > 0 # fallowing\n\n # Currently fixtures are not automatically loaded in the parametrisation, so they need to be manually invoked\n # See https://github.com/pytest-dev/pytest/issues/349\n @pytest.mark.parametrize(\n \"test_farm, expected_cost\", [(\"first_farm\", 0), (\"second_farm\", 0)]\n )\n def test_update(\n self,\n sample_offspring_distrib,\n initial_external_ratios,\n initial_external_inflow,\n test_farm,\n expected_cost,\n request,\n ):\n\n # ensure number of matings\n initial_lice_pop = {stage: 100 for stage in LicePopulation.lice_stages}\n\n test_farm = request.getfixturevalue(test_farm)\n\n # ensure number of different hatching dates through a number of cages\n test_farm.cfg.farms[test_farm.id_].cages_start = [\n test_farm.start_date for i in range(10)\n ]\n test_farm.cages = [\n Cage(i, test_farm.cfg, test_farm, initial_lice_pop) for i in range(10)\n ]\n\n eggs_by_hatch_date, cost = test_farm.update(\n test_farm.start_date, initial_external_inflow, initial_external_ratios\n )\n\n for hatch_date in eggs_by_hatch_date:\n assert hatch_date > test_farm.start_date\n\n for geno in geno_to_alleles(\"a\"):\n assert eggs_by_hatch_date[hatch_date][geno] > 0\n\n # TODO: need to check that the second farm has a positive infrastructure cost\n assert cost == expected_cost\n\n def test_eq(self, first_farm, second_farm):\n assert first_farm == first_farm\n assert first_farm != second_farm\n assert first_farm != 0\n assert first_farm != \"dummy\"\n\n def test_treatment_limit(self, first_farm, first_cage):\n treatment_step_size = dt.timedelta(days=50)\n cur_day = first_farm.farm_cfg.treatment_dates[-1][0] + treatment_step_size\n\n for i in range(10):\n assert first_farm.add_treatment(Treatment.EMB, cur_day)\n assert (\n first_cage.treatment_events.qsize() == 3 + i + 1\n ) # the first treatment cannot be applied\n # Test treatments are not counted, unless add_treatment is called\n assert first_farm.available_treatments == 10 - i - 1\n cur_day += treatment_step_size\n\n assert not first_farm.add_treatment(Treatment.EMB, cur_day)\n assert first_farm.available_treatments == 0\n\n def test_prescheduled_sampling_events(self, first_farm, cur_day):\n first_farm._report_sample(cur_day)\n assert first_farm._get_aggregation_rate() <= 0.1\n\n # One test today, one test in 14 days, another test in 28 days\n # The first has already been consumed\n first_farm._report_sample(cur_day + dt.timedelta(days=21))\n assert first_farm._get_aggregation_rate() > 0.0\n\n # The second too\n first_farm._report_sample(cur_day + dt.timedelta(days=28))\n assert first_farm._get_aggregation_rate() > 0.0\n\n \"\"\"\n def test_ask_for_treatment_no_defection(\n self, no_prescheduled_farm, cur_day, initial_external_ratios\n ):\n first_cage = no_prescheduled_farm.cages[0]\n assert first_cage.treatment_events.qsize() == 0\n first_available_day = cur_day + dt.timedelta(days=30)\n no_prescheduled_farm.ask_for_treatment(first_available_day, False)\n assert first_cage.treatment_events.qsize() == 1\n\n # Asking again will not work, but it requires some internal cage update\n first_cage.update(first_available_day, 0, initial_external_ratios)\n no_prescheduled_farm.ask_for_treatment(first_available_day, False)\n assert first_cage.treatment_events.qsize() == 0\n\n def test_ask_for_treatment(\n self, no_prescheduled_farm, no_prescheduled_cage, cur_day\n ):\n assert no_prescheduled_cage.treatment_events.qsize() == 0\n\n for i in range(12):\n first_available_day = cur_day + dt.timedelta(days=30 * i)\n no_prescheduled_farm.ask_for_treatment()\n assert no_prescheduled_cage.treatment_events.qsize() == 9\n\n \"\"\"\n","sub_path":"tests/test_Farm.py","file_name":"test_Farm.py","file_ext":"py","file_size_in_byte":11753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"16549470","text":"from subprocess import call\nfrom os import makedirs\nfrom os import path\nfrom shutil import copy\n\n\ndef do_step(context):\n\n if not path.isdir(\"bosh/manifests\"):\n makedirs(\"bosh/manifests\")\n\n # Generate the private key and certificate\n call(\"sh create_cert.sh\", shell=True)\n copy(\"bosh.key\", \"./bosh/bosh\")\n with open('bosh_cert.pem', 'r') as tmpfile:\n ssh_cert = tmpfile.read()\n ssh_cert = \"|\\n\" + ssh_cert\n ssh_cert = \"\\n \".join([line for line in ssh_cert.split('\\n')])\n\n context.meta['settings']['SSH_CERTIFICATE'] = ssh_cert\n\n return context\n","sub_path":"install_steps/create_bosh_cert.py","file_name":"create_bosh_cert.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"209498616","text":"\nfrom django.contrib import messages\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AdminPasswordChangeForm, PasswordChangeForm\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom social_django.models import UserSocialAuth\n\nfrom jos_stories.models import Story\nfrom jos_comments.models import Comment, CommentThread\nfrom .models import Follow, Profile\n\n\ndef get_followed_ids(usr):\n following_id_dicts = Follow.objects.filter(follower=usr) \\\n .values('followed_id') \\\n .order_by('-created')\n\n followed_ids = []\n if following_id_dicts:\n for item in following_id_dicts:\n followed_ids.append(item['followed_id'])\n\n return followed_ids\n\n\ndef new_member(request):\n\n user = get_object_or_404(User, pk=request.user.id)\n short_name = user.get_short_name()\n username = user.username\n\n Story.objects.create(author=user,\n profile=user.profile,\n description=username + '; profile',\n title='About ' + short_name)\n\n email_address = user.email\n send_mail('Welcome to Join Our Story',\n 'We are glad you are here!',\n 'joinus@joinourstory.com',\n [email_address],\n fail_silently=True)\n\n context = {\n 'page_title': 'welcome',\n }\n\n return render(request, 'jos_members/new_member.html', context)\n\n\n@login_required\ndef favor(request):\n favor_id = request.GET.get(\"favor_id\", \"missing\")\n\n if favor_id != 'missing':\n add_follower = User.objects.get(pk=favor_id)\n Follow.objects.add_follower(request.user, add_follower)\n\n return redirect('members:friends')\n\n\n@login_required\ndef unfavor(request):\n unfavor_id = request.GET.get(\"unfavor_id\", \"missing\")\n\n if unfavor_id != 'missing':\n remove_follower = User.objects.get(pk=int(unfavor_id))\n Follow.objects.remove_follower(request.user, remove_follower)\n\n return redirect('members:friends')\n\n\n# Has something to do with fb login\n@login_required\ndef member_settings(request):\n user = request.user\n\n try:\n facebook_login = user.social_auth.get(provider='facebook')\n except UserSocialAuth.DoesNotExist:\n facebook_login = None\n\n can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password())\n\n return render(request, 'jos_members/settings.html', {\n 'facebook_login': facebook_login,\n 'can_disconnect': can_disconnect\n })\n\n\n@login_required\ndef member_password(request):\n if request.user.has_usable_password():\n PasswordForm = PasswordChangeForm\n else:\n PasswordForm = AdminPasswordChangeForm\n\n if request.method == 'POST':\n form = PasswordForm(request.user, request.POST)\n if form.is_valid():\n form.save()\n update_session_auth_hash(request, form.user)\n messages.success(request, 'Your password was successfully updated!')\n return redirect('password')\n else:\n messages.error(request, 'Please correct the error below.')\n else:\n form = PasswordForm(request.user)\n return render(request, 'jos_members/password.html', {'form': form})\n\n\n@login_required\ndef my_space(request):\n user_id = request.GET.get(\"user_id\", \"missing\")\n\n if user_id != 'missing':\n member = get_object_or_404(User, pk=int(user_id))\n\n public_stories = Story.objects.exclude(description__icontains='treat')\\\n .filter(author=member, sharing_level=2).order_by('-updated')\n public_treats = Story.objects\\\n .filter(description__icontains='treat', author=member).order_by('-updated')\n\n private_stories = Story.objects.filter(author=member) \\\n .exclude(description__icontains='treat') \\\n .exclude(description__icontains='profile').order_by('-updated')\n\n try:\n about = Story.objects.get(description=str(member.id) + '; profile')\n except:\n about = Story.objects.create(author=member,\n profile=member.profile,\n description=str(member.id) + '; profile',\n title='About ' + member.profile.jos_name)\n\n return render(request, 'jos_members/my_space.html', {\n 'page_title': 'stuff',\n 'profile': member.profile,\n 'about': about,\n \"public_stories\": public_stories,\n \"public_treats\": public_treats,\n \"private_stories\": private_stories\n })\n\n return HttpResponse('SERVER RESPONSE: cannot find user')\n\n\ndef ajax_member_search(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_member_search, Not an ajax call.')\n\n search_text = \"0\"\n found_members = \"0\"\n\n if request.method == \"GET\":\n search_text = request.GET.get(\"search_text\", \"0\").strip().lower()\n\n following_id_dicts = Follow.objects \\\n .filter(follower=request.user) \\\n .values('followed_id') \\\n .order_by('-created')\n\n all_fs_ids = []\n if following_id_dicts:\n for item in following_id_dicts:\n all_fs_ids.append(item['followed_id'])\n\n if search_text != \"0\":\n found_members = User.objects.filter(username__icontains=search_text)\\\n .exclude(id__in=all_fs_ids).order_by('username') \\\n\n if len(found_members) == 0:\n found_members = \"missing\"\n\n context = {\n \"search_text\": search_text,\n \"found_members\": found_members\n }\n\n return render(request, \"jos_members/member_search_response.html\", context)\n\n\ndef ajax_update_member_info(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_update_member_info, Not an ajax call.')\n\n user_profile = get_object_or_404(Profile, user=request.user)\n\n if request.method == \"POST\":\n new_note_text = request.POST.get(\"note_text\", \"0\")\n if new_note_text != \"0\":\n user_profile.note_text = new_note_text\n user_profile.save()\n\n return HttpResponse(\"SERVER RESPONSE new note: \" + new_note_text)\n\n return HttpResponse(\"SERVER RESPONSE story update fell through!\")\n\n\ndef ajax_address_book(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_address_book, Not an ajax call.')\n\n profile = request.user.profile\n address_book = profile.address_book\n\n if type(address_book) is not list:\n address_book = []\n\n if request.method == \"POST\":\n nick = request.POST.get(\"nick\", \"0\")\n email = request.POST.get(\"email\", \"0\")\n delete_address = request.POST.get(\"delete\", \"0\")\n\n if delete_address != \"0\" and address_book != []:\n new_address_book = []\n for address in address_book:\n if address[1] != delete_address:\n new_address_book.append(address)\n profile.address_book = new_address_book\n profile.save()\n\n if email != \"0\" and nick != \"0\":\n new_address = [nick, email]\n address_book.append(new_address)\n profile.address_book = address_book\n profile.save()\n\n context = {'address_book': profile.address_book}\n\n return render(request, \"jos_members/address_book_response.html\", context)\n\n\ndef ajax_all_friends(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_all_friends, Not an ajax call.')\n\n followed_ids = get_followed_ids(request.user)\n search_text = request.GET.get('search_text', '0')\n\n all_fs = []\n if followed_ids:\n for fid in followed_ids:\n user = get_object_or_404(User, id=fid)\n if search_text in user.username.lower() or search_text == '0':\n all_fs.append(user)\n\n new_comment_ids = []\n new_comment_bodies = []\n new_friends = []\n new_comment_friend_ids = []\n\n read_comment_ids = []\n read_comment_bodies = []\n read_friends = []\n\n sent_comment_ids = []\n sent_comment_bodies = []\n sent_friends = []\n\n\n none_comment_ids = []\n none_comment_bodies = []\n none_friends = []\n\n for friend in all_fs:\n last_comment = Comment.objects.exclude(comment_thread__thread_scope='story') \\\n .filter(Q(sender__id=request.user.id, recipient=friend) |\n Q(sender=friend, recipient__id=request.user.id)).order_by('-id').first()\n\n if last_comment and last_comment.recipient == request.user and last_comment.read_at is None:\n new_comment_ids.append(last_comment.id)\n new_comment_bodies.append(last_comment.body)\n new_friends.append(friend)\n new_comment_friend_ids.append(friend.id)\n\n elif last_comment and last_comment.recipient == request.user:\n read_comment_ids.append(last_comment.id)\n read_comment_bodies.append(last_comment.body)\n read_friends.append(friend)\n\n elif last_comment:\n sent_comment_ids.append(last_comment.id)\n sent_comment_bodies.append(last_comment.body)\n sent_friends.append(friend)\n\n else:\n none_comment_ids.append(0)\n none_comment_bodies.append('missing')\n none_friends.append(friend)\n\n\n sorted_comment_ids = new_comment_ids + read_comment_ids + sent_comment_ids + none_comment_ids\n sorted_comment_bodies = new_comment_bodies + read_comment_bodies + sent_comment_bodies + none_comment_bodies\n sorted_friends = new_friends + read_friends + sent_friends + none_friends\n\n\n context = {'sorted_friends': sorted_friends,\n 'new_comment_friend_ids': new_comment_friend_ids,\n 'sorted_comment_ids': sorted_comment_ids,\n 'sorted_comment_bodies': sorted_comment_bodies}\n\n\n # return HttpResponse('SERVER RESPONSE: ajax_all_friends,' +\n # 'sorted_friends_ids: ' + str(sorted_friends_ids) +\n # 'last_comment_bodies: ' + str(last_comment_bodies))\n\n\n return render(request, \"jos_members/all_friends_response.html\", context)\n\n\ndef ajax_not_friend_comments(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_not_friend_comments, Not an ajax call.')\n\n context = {}\n followed_ids = get_followed_ids(request.user)\n\n threads = CommentThread.objects \\\n .filter(first_recipient_id=request.user.id, thread_scope='individual') \\\n .order_by('-id')\n\n last_comment_ids = []\n\n if threads:\n for thread in threads:\n last_comment = thread.comments.latest('sent_at')\n if not last_comment.recipient_deleted_at:\n last_comment_ids.append(last_comment.id)\n\n last_comments = Comment.objects.filter(pk__in=last_comment_ids)\n\n not_friend_comments = last_comments.exclude(sender_id__in=followed_ids).order_by('-id')\n\n context = {'not_friend_comments': not_friend_comments}\n\n return render(request, \"jos_members/not_friends_response.html\", context)\n\n\n@login_required\ndef friends(request):\n context = {\n 'page_title': 'friends',\n }\n\n return render(request, \"jos_members/friends.html\", context)\n\n","sub_path":"jos_members/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"293385314","text":"from itertools import permutations\nmatris=[]\nwhile True:\n try:\n mertebe=int(input(\"Lütfen katsayılar matrisinin satır sayısını giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile mertebe<1:\n print(\"Satır sayısı pozitif olmalı.\")\n while True:\n try:\n mertebe=int(input(\"Lütfen katsayılar matrisinin satır sayısını giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nfor i in range(mertebe):\n satır=[]\n for j in range(mertebe):\n while True:\n try:\n eleman=float(input(\"Lütfen katsayılar matrisinin {}. satırının {}.elamanını giriniz:\".format(i+1,j+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n satır.append(eleman)\n matris.append(satır)\nsonuç=[]\nfor i in range(mertebe):\n while True:\n try:\n değer=float(input(\"Lütfen {}. denklemin sağ tarafındaki değeri giriniz:\".format(i+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n sonuç.append(değer)\nwhile True:\n try:\n epsilon=float(input(\"Lütfen epsilon değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile epsilon<=0:\n print(\"Epsilon değeri 0'dan küçük olamaz.\")\n try:\n epsilon = float(input(\"Lütfen epsilon değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nbaşlangıç=[]\nfor i in range(mertebe):\n while True:\n try:\n x=float(input(\"Lütfen {}. değişkenin başlangıç değerini giriniz:\".format(i+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n başlangıç.append(x)\nmax=0\nsum=1\nper_mat=list(permutations(matris))\nper_son=list(permutations(sonuç))\nfor i in range(len(per_mat)):\n for j in range(mertebe):\n sum*=abs(per_mat[i][j][j])\n if maxepsilon:\n sum+=1\n return sum\nwhile control()>0:\n it1 = function2(it2)\n it2 = function2(it1)\n delta = [abs(it1[i] - it2[i]) for i in range(mertebe)]\nfor i in range(mertebe):\n print(\"{}. değişkenin değeri:{}\".format(i+1,it2[i]))\n","sub_path":"gauss seidel.py","file_name":"gauss seidel.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"327553812","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`metaopt.core.utils` -- Package-wide useful routines\n=========================================================\n\n.. module:: utils\n :platform: Unix\n :synopsis: Helper functions useful in possibly all :mod:`metaopt.core`'s modules.\n\"\"\"\n\nfrom abc import ABCMeta\nfrom glob import glob\nfrom importlib import import_module\nimport os\n\n\nclass SingletonType(type):\n \"\"\"Metaclass that implements the singleton pattern for a Python class.\"\"\"\n\n def __init__(cls, name, bases, dictionary):\n \"\"\"Create a class instance variable and initiate it to None object.\"\"\"\n super(SingletonType, cls).__init__(name, bases, dictionary)\n cls.instance = None\n\n def __call__(cls, *args, **kwargs):\n \"\"\"Create an object if does not already exist, otherwise return what there is.\"\"\"\n if cls.instance is None:\n cls.instance = super(SingletonType, cls).__call__(*args, **kwargs)\n elif args or kwargs:\n raise ValueError(\"A singleton instance has already been instantiated.\")\n return cls.instance\n\n\nclass AbstractSingletonType(SingletonType, ABCMeta):\n \"\"\"This will create singleton base classes, that need to be subclassed and implemented.\"\"\"\n\n pass\n\n\nclass Factory(type):\n \"\"\"Instantiate appropriate wrapper for the infrastructure based on input\n argument, ``of_type``.\n\n Attributes\n ----------\n types : list of subclasses of ``cls.__base__``\n Updated to contain all possible implementations currently. Check out code.\n typenames : list of str\n Names of implemented wrapper classes, correspond to possible ``of_type``\n values.\n\n \"\"\"\n\n def __init__(cls, names, bases, dictionary):\n \"\"\"Search in directory for attribute names subclassing `bases[0]`\"\"\"\n super(Factory, cls).__init__(names, bases, dictionary)\n\n cls.modules = []\n base = import_module(cls.__base__.__module__)\n py_files = glob(base.__path__[0] + '/[A-Za-z]*.py')\n py_mods = map(lambda x: '.' + os.path.split(os.path.splitext(x)[0])[1], py_files)\n for py_mod in py_mods:\n cls.modules.append(import_module(py_mod, package=cls.__base__.__module__))\n\n cls.types = [cls.__base__] + cls.__base__.__subclasses__()\n cls.types = [class_ for class_ in cls.types if class_.__name__ != cls.__name__]\n cls.typenames = list(map(lambda x: x.__name__, cls.types))\n\n def __call__(cls, of_type=None, *args, **kwargs):\n \"\"\"Create an object, instance of ``cls.__base__``, on first call.\n\n :param of_type: Name of class, subclass of ``cls.__base__``, wrapper\n of a database framework that will be instantiated on the first call.\n :param args: positional arguments to initialize ``cls.__base__``'s instance (if any)\n :param kwargs: keyword arguments to initialize ``cls.__base__``'s instance (if any)\n\n .. seealso::\n `Factory.typenames` for values of argument `of_type`.\n\n .. seealso::\n Attributes of ``cls.__base__`` and ``cls.__base__.__init__`` for\n values of `args` and `kwargs`.\n\n .. note:: New object is saved as `Factory`'s internal state.\n\n :return: The object which was created on the first call.\n \"\"\"\n if of_type is None:\n of_type = cls.__base__.__name__\n\n for inherited_class in cls.types:\n if inherited_class.__name__.lower() == of_type.lower():\n return inherited_class.__call__(*args, **kwargs)\n\n error = \"Could not find implementation of {0}, type = '{1}'\".format(\n cls.__base__.__name__, of_type)\n error += \"\\nCurrently, there is an implementation for types:\\n\"\n error += str(cls.typenames)\n raise NotImplementedError(error)\n\n\nclass SingletonFactory(AbstractSingletonType, Factory):\n \"\"\"Wrapping `Factory` with `SingletonType`. Keep compatibility with `AbstractSingletonType`.\"\"\"\n\n pass\n","sub_path":"src/metaopt/core/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"366860708","text":"#!/usr/bin/env python\n############################################################################################\n#\n# Nagios plugin to validate pods are running on separate nodes\n#\n# If 2 pods from the same component are running on the same node, return a warning message\n#\n# Copyright (c) 2018, Red Hat Ltd. All rights reserved.\n#\n############################################################################################\nimport sys\nimport traceback\n\nimport nagios\nimport openshift\n\n\ndef report(issues):\n if not issues:\n print(\"OK: Component pod distribution as expected\")\n nag_status = nagios.OK\n else:\n for issue in issues:\n print(issue)\n nag_status = nagios.WARN\n return nag_status\n\n\ndef check():\n issues = []\n project = openshift.get_project()\n deploymentConfigs = openshift.get_deploymentconfigs(project)\n for deploymentConfig in deploymentConfigs[\"items\"]:\n componentName = deploymentConfig[\"metadata\"][\"name\"]\n pods = openshift.get_running_pod_names(\n project, container_names=componentName)\n nodes = openshift.get_nodes_from_names(pods)\n if len(pods) > 1:\n for node in set(nodes):\n nodeCount = nodes.count(node)\n if nodeCount > 1:\n issues.append(\"WARN: %s has %s pods running on the same node: %s\" % (\n componentName, nodeCount, node))\n return report(issues)\n\n\nif __name__ == \"__main__\":\n code = nagios.UNKNOWN\n try:\n code = check()\n except:\n traceback.print_exc()\n finally:\n sys.exit(code)\n","sub_path":"plugins/default/lib/pod_affinity.py","file_name":"pod_affinity.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"26390416","text":"# Find the nth prime number\n\nprimes = []\n\ndef compute_primes_to(num):\n if len(primes) == 0:\n current = 2\n else:\n current = primes[-1]+1\n \n breakpoint = len(primes) + num\n \n while True:\n if is_prime(current):\n primes.append(current)\n current += 1\n if len(primes) >= breakpoint:\n break\n \n return primes\n \ndef get_prime_at(num):\n if len(primes) >= num:\n return primes[num-1]\n else:\n return \"primes haven't been computed to this point\"\n\ndef size_of_primes():\n return len(primes)\n \ndef is_prime(num):\n prime = True\n for j in range(1,num):\n if j == num and num % j == 0:\n print(\"meets divisible by self criteria\")\n if j != 1 and j != num and num % j == 0:\n prime = False\n break\n if prime:\n return True\n else:\n return False\n \n# compute primes to n\n# show the value of prime at n\n\n#compute_primes_to(10001)\n#print(str(get_prime_at(10001)))","sub_path":"project_euler/problem_7/find_prime.py","file_name":"find_prime.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"193702320","text":"# zigzag ribbon\nimport sys\nsys.path.append(\"../../../pygra\") # add pygra library\n\nimport geometry\ng = geometry.honeycomb_armchair_ribbon(60) # create geometry of a zigzag ribbon\nh = g.get_hamiltonian(has_spin=True) # create hamiltonian of the system\nh.add_haldane(.1) # add Haldane coupling\nh.get_bands() # calculate band structure\n#h.get_bands(operator=h.get_operator(\"valley\"))\n","sub_path":"examples/1d/haldane_armchair/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"101823399","text":"import hmac\nimport sqlite3\nfrom flask import Flask, request, redirect\nfrom flask_jwt import JWT, jwt_required, current_identity\nfrom flask_cors import CORS\nfrom flask_mail import Mail, Message\nimport re\nimport cloudinary\nimport cloudinary.uploader\nfrom datetime import timedelta\n\n# creating a user object\nclass User(object):\n def __init__(self, email, username, password):\n self.id = email\n self.username = username\n self.password = password\n\n\n# creating a product object\nclass Product(object):\n def __init__(self, product_id, product_name, product_type, product_quantity, product_price, product_image):\n self.product_id = product_id\n self.product_name = product_name\n self.product_type = product_type\n self.product_quantity = product_quantity\n self.product_price = product_price\n self.product_image = product_image\n\n\n# initializing the database\nclass Database(object):\n def __init__(self):\n self.conn = sqlite3.connect('posbe.db')\n self.cursor = self.conn.cursor()\n\n def addpro(self, value):\n query = \"INSERT INTO catalogue (product_id, product_name, product_type, product_quantity, product_price,\" \\\n \"product_image, email) VALUES (?, ?, ?, ?, ?, ?, ?)\"\n self.cursor.execute(query, value)\n\n def delpro(self, productid):\n proid = productid\n query = \"DELETE FROM catalogue WHERE product_id='\" + proid + \"'\"\n self.cursor.execute(query)\n\n def editpro(self, pro_id, value):\n proid = pro_id\n values = value\n put_data = {}\n put_data['product_id'] = values.get('product_id')\n put_data['product_name'] = values.get('product_name')\n put_data['product_type'] = values.get('product_type')\n put_data['product_quantity'] = values.get('product_quantity')\n put_data['product_price'] = values.get('product_price')\n put_data['product_image'] = values.get('product_image')\n\n if values.get('product_image'):\n self.cursor.execute(\"UPDATE catalogue SET \"\n \"product_id=?, \"\n \"product_name=?, \"\n \"product_type=?, \"\n \"product_quantity=?, \"\n \"product_price=?, \"\n \"product_image=? \"\n \"WHERE product_id='\" + proid + \"'\"\n , (put_data['product_id'],\n put_data['product_name'],\n put_data['product_type'],\n put_data['product_quantity'],\n put_data['product_price'],\n put_data['product_image']))\n else:\n self.cursor.execute(\"UPDATE catalogue SET \"\n \"product_id=?, \"\n \"product_name=?, \"\n \"product_type=?, \"\n \"product_quantity=?, \"\n \"product_price=? \"\n \"WHERE product_id='\" + proid + \"'\"\n , (put_data['product_id'],\n put_data['product_name'],\n put_data['product_type'],\n put_data['product_quantity'],\n put_data['product_price']))\n\n def edituser(self, email, value):\n email = email\n values = value\n query = \"UPDATE user SET first_name=?, last_name=?, address=?, username=?, password=? WHERE email='\" + email + \"'\"\n self.cursor.execute(query, values)\n\n def selectproduct(self, value):\n proid = value\n query = \"SELECT * FROM catalogue WHERE product_id='\" + proid + \"'\"\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n\n def myproducts(self, value):\n email = value\n query = \"SELECT * FROM catalogue WHERE email='\" + email + \"'\"\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n\n def viewcat(self):\n self.cursor.execute(\"SELECT * FROM catalogue\")\n data = self.cursor.fetchall()\n return data\n\n def deleteuser(self, email):\n self.cursor.execute(\"DELETE FROM user WHERE email='\" + email + \"'\")\n self.conn.commit()\n\n def commit(self):\n return self.conn.commit()\n\n\n# function to take image uploads and convert them into urls\ndef upload_file():\n app.logger.info('in upload route')\n cloudinary.config(cloud_name ='dlqxdivje', api_key='599819111725767',\n api_secret='lTD-aqaoTbzVgmZqyZxjPThyaVg')\n upload_result = None\n if request.method == 'POST' or request.method == 'PUT':\n product_image = request.json['product_image']\n app.logger.info('%s file_to_upload', product_image)\n if product_image:\n upload_result = cloudinary.uploader.upload(product_image)\n app.logger.info(upload_result)\n return upload_result['url']\n\n\ndb = Database()\n\n\n# collecting all users from the database\ndef fetch_users():\n with sqlite3.connect('posbe.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM user\")\n users = cursor.fetchall()\n print(users)\n\n new_data = []\n\n for data in users:\n new_data.append(User(data[0], data[4], data[5]))\n return new_data\n\n\n# collecting all products from the database\ndef fetch_products():\n with sqlite3.connect('posbe.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM products\")\n allproducts = cursor.fetchall()\n print(allproducts)\n\n new_data = []\n\n for data in allproducts:\n new_data.append(Product(data[0], data[1], data[2], data[3], data[4], data[5]))\n return new_data\n\n\nusers = fetch_users()\nproducts = fetch_products()\n\n\n# function to create the user table in the database\ndef createusertable():\n conn = sqlite3.connect('posbe.db')\n print(\"Opened database successfully\")\n\n conn.execute(\"CREATE TABLE IF NOT EXISTS user(email TEXT PRIMARY KEY,\"\n \"first_name TEXT NOT NULL,\"\n \"last_name TEXT NOT NULL,\"\n \"address TEXT NOT NULL,\"\n \"username TEXT NOT NULL,\"\n \"password TEXT NOT NULL)\")\n print(\"user table created successfully\")\n conn.close()\n\n\n# function to create the products table in the database\ndef createproducttable():\n with sqlite3.connect('posbe.db') as conn:\n conn.execute(\"CREATE TABLE IF NOT EXISTS catalogue (product_id TEXT PRIMARY KEY,\"\n \"product_name TEXT NOT NULL,\"\n \"product_type TEXT NOT NULL,\"\n \"product_quantity INTEGER NOT NULL,\"\n \"product_price TEXT NOT NULL,\"\n \"product_image TEXT NOT NULL,\"\n \"email TEXT NOT NULL,\"\n \"FOREIGN KEY (email) REFERENCES user (email))\")\n print(\"product table created successfully.\")\n\n\n# calling the functions to create the tables\ncreateusertable()\ncreateproducttable()\n\n\nusername_table = {u.username: u for u in users}\nuseremail_table = {u.id: u for u in users}\n\n\n# function to create the token during login\ndef authenticate(username, password):\n user = username_table.get(username, None)\n if user and hmac.compare_digest(user.password.encode('utf-8'), password.encode('utf-8')):\n return user\n\n\ndef identity(payload):\n user_id = payload['identity']\n return useremail_table.get(user_id, None)\n\n\n# initializing the app\napp = Flask(__name__)\napp.config['JWT_EXPIRATION_DELTA'] = timedelta(hours=24)\nCORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\napp.debug = True\napp.config['SECRET_KEY'] = 'super-secret'\napp.config['MAIL_SERVER'] = 'smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = 'lottoemail123@gmail.com'\napp.config['MAIL_PASSWORD'] = 'MonkeyVillage123'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\napp.config['TESTING'] = True\napp.config['CORS_HEADERS'] = ['Content-Type']\n\n\njwt = JWT(app, authenticate, identity)\n\n\n@app.route('/protected/')\n@jwt_required()\ndef protected():\n return '%s' % current_identity\n\n\n# app route for user registration\n@app.route('/user-registration/', methods=[\"POST\"])\ndef user_registration():\n response = {}\n regex = '^(\\w|\\.|\\_|\\-)+[@](\\w|\\_|\\-|\\.)+[.]\\w{2,3}$'\n\n if request.method == \"POST\":\n\n email = request.form['email']\n first_name = request.form['first_name']\n last_name = request.form['last_name']\n address = request.form['address']\n username = request.form['username']\n password = request.form['password']\n if (re.search(regex, email)):\n with sqlite3.connect(\"posbe.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO user(\"\n \"email,\"\n \"first_name,\"\n \"last_name,\"\n \"address,\"\n \"username,\"\n \"password) VALUES(?, ?, ?, ?, ?, ?)\", (email, first_name, last_name, address, username, password))\n conn.commit()\n global users\n users = fetch_users()\n\n\n response[\"message\"] = \"success. message sent\"\n response[\"status_code\"] = 201\n\n return redirect(\"/emailsent/%s\" % email)\n else:\n return \"Email not valid. Please enter a valid email address\"\n\n\n# app route that sends an email to users who registered\n@app.route('/emailsent/', methods=['GET'])\ndef sendemail(email):\n mail = Mail(app)\n\n msg = Message('Hello Message', sender='lottoemail123@gmail.com', recipients=[email])\n msg.body = \"This is the email body after making some changes\"\n mail.send(msg)\n\n return \"Thank you for registering. An em\"\n\n\n# app route to view a profile\n@app.route('/viewprofile//', methods=[\"GET\"])\ndef viewownprofile(username):\n response = {}\n if request.method == \"GET\":\n with sqlite3.connect(\"posbe.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM user WHERE username='\" + username + \"'\")\n data = cursor.fetchall()\n if data == []:\n return \"User does not exit\"\n else:\n response['message'] = 200\n response['data'] = data\n return response\n\n\n# app route to add a product to the database\n@app.route('/addtocatalogue/', methods=[\"POST\"])\n@jwt_required()\ndef newproduct():\n dtb = Database()\n response = {}\n\n if request.method == \"POST\":\n product_id = request.json['product_id']\n product_name = request.json['product_name']\n product_type = request.json['product_type']\n product_quantity = request.json['product_quantity']\n product_price = request.json['product_price']\n email = request.json['email']\n if (product_id == '' or product_name == '' or product_type == ''\n or product_quantity == '' or product_price == '' or email == ''):\n return \"Please fill in all entry fields\"\n else:\n if int(product_quantity):\n values = (product_id, product_name, product_type, product_quantity, product_price, upload_file(), email)\n dtb.addpro(values)\n dtb.commit()\n\n response[\"status_code\"] = 201\n response['description'] = 'product added'\n return response\n else:\n return \"Please enter product quantity as an number\"\n else:\n return \"Method Not Allowed\"\n\n\n# app route to view all the products in the database\n@app.route('/viewcatalogue/', methods=[\"GET\"])\ndef get_products():\n dtb = Database()\n response = {}\n items = dtb.viewcat()\n response['status_code'] = 200\n response['data'] = items\n return response\n\n\n# app route to delete a product from the database\n@app.route(\"/delete-product/\")\n@jwt_required()\ndef delete_product(productid):\n response = {}\n dtb = Database()\n\n dtb.delpro(productid)\n dtb.commit()\n response['status_code'] = 200\n response['message'] = \"product deleted successfully.\"\n return response\n\n\n# app route to edit a product in the database\n@app.route(\"/edit-product//\", methods=[\"PUT\"])\n@jwt_required()\ndef edit_product(productid):\n response = {}\n dtb = Database()\n product = dtb.selectproduct(productid)\n if product == []:\n return \"Product does not exist in the database\"\n else:\n if request.method == \"PUT\":\n incoming_data = dict(request.json)\n dtb.editpro(productid, incoming_data)\n dtb.commit()\n response['message'] = 200\n return response\n else:\n return \"Method not allowed\"\n\n\n@app.route(\"/myproducts//\")\n@jwt_required()\ndef getmyproducts(email):\n dtb = Database()\n response = {}\n items = dtb.myproducts(email)\n response['status_code'] = 200\n response['data'] = items\n return response\n\n\n@app.route(\"/edit-user//\", methods=[\"PUT\"])\n@jwt_required()\ndef edit_user(useremail):\n response = {}\n dtb = Database()\n if request.method == \"PUT\":\n first_name = request.json['first_name']\n last_name = request.json['last_name']\n address = request.json['address']\n username = request.json['username']\n password = request.json['password']\n values = (first_name, last_name, address, username, password)\n dtb.edituser(useremail, values)\n dtb.commit()\n response['message'] = 200\n return response\n else:\n return \"Method not allowed\"\n\n\n@app.route('/select_item/')\n@jwt_required()\ndef selectitem(productid):\n response = {}\n dtb = Database()\n data = dtb.selectproduct(productid)\n response['message'] = 200\n response['data'] = data\n return response\n\n\n@app.route('/deleteuser/')\n@jwt_required()\ndef deleteuser(email):\n response = {}\n dtb = Database()\n dtb.delpro(email)\n dtb.commit()\n dtb.deleteuser(email)\n response['message'] = 200\n response['text'] = \"User successfully deleted\"\n return response\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"255917773","text":"# Chris Jakins 1000802309\n\nimport sys\nimport numpy as np\nfrom file_utility import FileUtility\n\nif len(sys.argv) != 5:\n print(\"Usage: value_iteration.py \")\n quit()\n\n\nenvironment_filename = sys.argv[1]\nnt_reward = float(sys.argv[2])\ngamma = float(sys.argv[3])\nk = int(sys.argv[4])\n\n\ndef value_iteration(states, reward, gamma, k):\n n = len(states) * len(states[0]) # assumes rectangular\n u = np.zeros((len(states), len(states[0])))\n\n for it in range(0, k):\n u_prime = np.array(u)\n\n for i in range(0, len(states)):\n for j in range(0, len(states[i])):\n if states[i][j] == 'X':\n u[i][j] = 0\n elif isinstance(states[i][j], float):\n u[i][j] = states[i][j]\n else:\n # calc for all possible transitions\n u[i][j] = (reward + \n gamma * bm(states, u_prime, i, j, len(states), len(states[i])))\n\n return u\n\n\n# don't look at this, thanks\ndef bm(env, u, i, j, max_i, max_j):\n ########### up \n # up_l\n if j == 0 or env[i][j - 1] == 'X':\n up_l = .1 * u[i][j]\n else:\n up_l = .1 * u[i][j - 1]\n \n # up_u\n if i == 0 or env[i - 1][j] == 'X':\n up_u = .8 * u[i][j]\n else:\n up_u = .8 * u[i - 1][j]\n \n # up_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n up_r = .1 * u[i][j]\n else:\n up_r = .1 * u[i][j + 1]\n\n max_util = up_u + up_l + up_r\n\n\n ########### left\n # left_u\n if i == 0 or env[i - 1][j] == 'X':\n left_u = .1 * u[i][j]\n else:\n left_u = .1 * u[i - 1][j]\n\n # left_l\n if j == 0 or env[i][j - 1] == 'X':\n left_l = .8 * u[i][j]\n else:\n left_l = .8 * u[i][j - 1]\n\n # left_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n left_d = .1 * u[i][j]\n else:\n left_d = .1 * u[i + 1][j]\n\n if left_u + left_l + left_d > max_util:\n max_util = left_u + left_l + left_d\n\n\n ############# down\n # down_l\n if j == 0 or env[i][j - 1] == 'X':\n down_l = .1 * u[i][j]\n else:\n down_l = .1 * u[i][j - 1]\n\n # down_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n down_d = .8 * u[i][j]\n else:\n down_d = .8 * u[i + 1][j]\n\n # down_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n down_r = .1 * u[i][j]\n else:\n down_r = .1 * u[i][j + 1]\n\n if down_l + down_d + down_r > max_util:\n max_util = down_l + down_d + down_r\n\n ############# right\n # right_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n right_d = .1 * u[i][j]\n else:\n right_d = .1 * u[i + 1][j]\n\n # right_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n right_r = .8 * u[i][j]\n else:\n right_r = .8 * u[i][j + 1]\n\n # right_u\n if i == 0 or env[i - 1][j] == 'X':\n right_u = .1 * u[i][j]\n else:\n right_u = .1 * u[i - 1][j]\n\n if right_d + right_r + right_u > max_util:\n max_util = right_d + right_r + right_u\n\n return max_util\n\n######################\n\nfile_util = FileUtility()\nenv = file_util.getData(environment_filename)\nutility_values = value_iteration(env, nt_reward, gamma, k)\n\n\nfor i in range(0, len(utility_values)):\n for j in range(0, len(utility_values[i])):\n if j == len(utility_values[i]) - 1:\n print(\"%6.3f\" % utility_values[i][j], end = '\\n')\n else:\n print(\"%6.3f,\" % utility_values[i][j], end = '')\n","sub_path":"fall2018/4309/hw6/value_iteration.py","file_name":"value_iteration.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91388233","text":"united_kingdom = [\n {\n \"name\": \"Scotland\",\n \"population\": 5295000,\n \"capital\": \"Edinburgh\"\n },\n {\n \"name\": \"Wales\",\n \"population\": 3063000,\n \"capital\": \"Swansea\"\n },\n {\n \"name\": \"England\",\n \"population\": 53010000,\n \"capital\": \"London\"\n }\n]\n\n# 1. Change the capital of Wales from `\"Swansea\"` to `\"Cardiff\"`.\nunited_kingdom[1][\"capital\"] = \"Cardiff\"\nprint(united_kingdom[1][\"capital\"])\n# 2. Create a dictionary for Northern Ireland and add it to the `united_kingdom` list (The capital is Belfast, and the population is 1,811,000).\nnorthern_ireland = {\n \"name\": \"Northern Ireland\",\n \"population\": 1811000,\n \"capital\": \"Belfast\"\n }\nunited_kingdom.append(northern_ireland)\n#print(united_kingdom)\n# 3. Use a loop to print the names of all the countries in the UK.\nnames = united_kingdom[0][\"name\"], united_kingdom[1][\"name\"], united_kingdom[2][\"name\"], united_kingdom[3][\"name\"]\nfor name in names:\n print(name)\n# 4. Use a loop to find the total population of the UK.\n#populations = [{united_kingdom[0][\"population\"]}, {united_kingdom[1][\"population\"]}, {united_kingdom[2][\"population\"]}, {united_kingdom[3][\"population\"]}]\n#print(populations)\npopulations = united_kingdom\n# print(populations)\ntotal_population = 0\nfor population in populations:\n total_population = total_population + population[\"population\"]\nprint(total_population)\n# check_total = 5295000 + 3063000 + 53010000 + 1811000\n# print(check_total)","sub_path":"exercise_c_uk.py","file_name":"exercise_c_uk.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"636095517","text":"# coding=utf-8\nimport platform\nimport codecs\n\ndef getAllFrequentKeywords(frequentWordsFilePath):\n words = []\n input = codecs.open(frequentWordsFilePath,\"r\",\"utf-8\")\n for line in input.readlines():\n words.append(line.strip(\"\\r\\n\").lower())\n return words\n\ndef prepare():\n #换行符\n HuangHangFu = \"\"\n my_os = platform.system()\n if my_os==\"Windows\":\n inputPath = \"F://睿云实验室//王剑锋//2017.11.1_关键��检索_esorics2018//第3阶段工作-搞数据//弄好的数据库//ciPings//ciPing\"\n outputPath = \"F://睿云实验室//王剑锋//2017.11.1_关键词检索_esorics2018//第3阶段工作-搞数据//ProcessEDRM4//EDRM_10000.txt\"\n frequentWordsFilePath = \"F://睿云实验室//王剑锋//2017.11.1_关键词检索_esorics2018//第3阶段工作-搞数据//ProcessEDRM4//使用频率最高的45000个一万个单词.txt\"\n HuangHangFu = \"\\r\\n\"\n print(\"you are in windows\")\n return inputPath,outputPath,frequentWordsFilePath\n else:\n inputPath = \"/root/ciPings//ciPing\";\n outputPath = \"/root/EDRM_10000.txt\"\n frequentWordsFilePath = \"/root/使用频率最高的45000个一万个单词.txt\"\n HuangHangFu = \"\\n\"\n print(\"you are in linux\")\n return inputPath,outputPath,frequentWordsFilePath\n\nif(__name__==\"__main__\"):\n inputPath,outputPath,frequentWordsFilePath = prepare()\n output = codecs.open(outputPath,\"w\",\"utf-8\")\n frequentWords = getAllFrequentKeywords(frequentWordsFilePath)\n print(len(frequentWords))\n k=0\n count = 0\n while(k<700):\n input = codecs.open(inputPath+\"_\"+str(k)+\".txt\",\"r\",\"utf-8\")\n lines = input.readlines()\n input.close()\n for line in lines:\n keyword = line.split(\":\")[0]\n numOfFiles = int(line.split(\":\")[1])\n if(keyword in frequentWords and numOfFiles > 10 and numOfFiles < 20):\n output.write(line)\n count = count + 1\n if(count >= 10000):\n print(\"获得100000个单词\")\n exit();\n \n k = k + 1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"473172198","text":"# \n# Boolean Algebra System\n# - Helper Functions and Classes\n#\n\n# Tree data structure used to express the boolean algebra expressions for simplification\nclass Tree (object):\n def __init__(self, children):\n self.children = children\n\n # Function that adds a child to the node\n def addChild(self, child):\n if isinstance(child, (list, tuple)):\n self.children += list(child)\n else:\n self.children.append(child)\n \n # Allows the tree to be printed\n def __repr__(self, level=0):\n ret = \"\"\n for child in self.children:\n if not isinstance(child, Tree):\n ret += \"\\t\" * level + \"'\" + str(child) + \"'\\n\"\n else:\n ret += child.__repr__(level+1)\n return ret\n\n# Function that checks whether there is proper bracket nesting (and whether all brackets are closed)\ndef checkBracketParity(string):\n nesting_count = 0\n for index, char in enumerate(string):\n if char == \"(\":\n nesting_count += 1\n elif char == \")\":\n nesting_count -= 1\n\n if nesting_count < 0:\n return False\n\n return nesting_count == 0\n\n\n# Analyzes whether a number is a power of two without using log functions (no floats) \ndef powerOfTwo(num):\n return num != 0 and ((num & (num - 1)) == 0)\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"353498214","text":"from django.contrib import admin\n\n# Register your models here.\n\nfrom .models import *\n\n\nclass AdmArticle(admin.ModelAdmin):\n list_display = ('creationDate','title')\n fieldsets = [\n ('Date ajout', {'fields': ['creationDate']}),\n ('Title', {'fields': ['title']}),\n ('Photo(s)', {'fields': ['relatedPhotos']}),\n ('Country', {'fields': ['relatedCountries']}),\n ('Misc', {'fields': ['textContent']}),\n ]\n \n list_filter = ['creationDate']\n \nclass AdmPhoto(admin.ModelAdmin):\n fieldsets = [\n ('Title', {'fields': ['title']}),\n ('Misc', {'fields': ['is_dark','file']}),\n ]\n\n\nadmin.site.register(Article, AdmArticle)\nadmin.site.register(Photo, AdmPhoto)\nadmin.site.register(Country)\nadmin.site.register(Location)","sub_path":"photolog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235708459","text":"# coding=utf-8\nimport glob\n\nif __name__ == '__main__':\n direction = \"E:\\工程\\workspace\\JavaEEWeb\\WebContent\"\n jspls = glob.glob(direction + \"\\*.jsp\")\n for i in jspls:\n re = open(i, \"r\", encoding=\"utf8\")\n s = re.read()\n re.close()\n s = s.replace(\"\", \"<title>120402013081 杨友君\")\n re = open(i, \"w\", encoding=\"utf8\")\n re.write(s)\n re.close()\n print(\"over!\")\n","sub_path":"Study/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"568364946","text":"import unittest\nimport theGame\nimport Deck\n\nclass TestDeckFunctions(unittest.TestCase):\n\tdef test_draw(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.draw(), None)\n\tdef test_show(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.show(), None)\n\tdef test_is_empty(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.is_empty(), True)\n\t\ttestDeck.full_deck()\n\t\tself.assertEqual(testDeck.is_empty(), False)\n\tdef test_is_available(self):\n\t\tcard = Deck.Card(\"H\", 1, True)\n\t\tself.assertEqual(card.is_available(), True)\n\t\nclass TestTheGameFunctions(unittest.TestCase):\n\tdef test_check_color(self):\n\t\ttestGame = theGame.theGame(2)\n\t\ttestGame.flip()\n\t\tcardX1 = Deck.Card(\"H\", 1, True)\n\t\tcardX2 = Deck.Card(\"S\", 4, False)\n\t\tself.assertEqual(testGame.check_color(cardX1), False)\n\t\tself.assertEqual(testGame.check_color(cardX2), True)\n\tdef test_is_legal(self):\n\t\ttestGame = theGame.theGame(2)\n\t\ttestGame.flip()\n\t\tcardX1 = Deck.Card(\"H\", 1, True)\n\t\tcardX2 = Deck.Card(\"S\", 3, True) #first trash is 4..\n\t\tself.assertEqual(testGame.is_legal(cardX1), False)\n\t\tself.assertEqual(testGame.is_legal(cardX2), True)\n\nif __name__ == '__main__':\n\tunittest.main(verbosity=2, exit=False)\n","sub_path":"rett_python_nofn/test_kapall.py","file_name":"test_kapall.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"191782862","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nimport datetime\nfrom django.core import serializers\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .logic import create_handle_log\nfrom .constants import LOGPATH\n# Create your views here.\nfrom .models import Logs, UserHandle, UserLogin\ndef create_log(request):\n f = open(\"ddns.log\") # 返回一个文件对象 \n line = f.readline() # 调用文件的 readline()方法 \n while line: \n log = eval(line)\n logs = Logs(c_date=log['date'], code=log['code'], status=log['msg'].encode('utf-8'))\n logs.save()\n line = f.readline() \n \n f.close()\n\n # logs = Logs(c_date='2019-1-1 10:54:32.43455', code=0, status='ok')\n # logs.save()\n return HttpResponse('ok')\n\ndef get(request):\n logs = Logs.objects.all()\n paginator = Paginator(logs, 20) #设置每一页显示几条 创建一个panginator对象\n \n try:\n current_num = int(request.GET.get('page',1)) #当你在url内输入的?page = 页码数 显示你输入的页面数目 默认为第2页\n logs = paginator.page(current_num)\n except EmptyPage:\n logs = paginator.page(1) #当你输入的page是不存在的时候就会报错\n\n if paginator.num_pages > 11: # 如果分页的数目大于11\n if current_num - 5 < 1: # 你输入的值\n pageRange = range(1, 11) # 按钮数\n elif current_num + 5 > paginator.num_pages: # 按钮数加5大于分页数\n pageRange = range(current_num - 5, current_num + 1) # 显示的按钮数\n\n else:\n pageRange = range(current_num - 5, current_num + 6) # range求的是按钮数 如果你的按钮数小于分页数 那么就按照正常的分页数目来显示\n\n else:\n pageRange = paginator.page_range # 正常分配\n\n return render(request, 'demo.html', locals())\n\ndef search(request):\n # print(request.method)\n search = request.POST.get('search')\n start_date = request.POST.get('start_date')\n end_date = request.POST.get('end_date') + ' 23:59:59.99999'\n # print(end_date)\n logs = Logs.objects.filter(c_date__range=(start_date, end_date)).filter(status__contains=search)\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n return JsonResponse(data)\n\ndef nearby_logs(request):\n # 查找相邻的log日志\n id = eval(request.POST.get('id'))\n start_id= id-5 if id-5 >=0 else 0\n end_id = id+5 \n logs = Logs.objects.filter(pk__range=(start_id, end_id))\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n return JsonResponse(data)\n\ndef get_user_log(request):\n create_handle_log(LOGPATH)\n user_login = UserLogin.objects.all().order_by('-l_time')\n paginator = Paginator(user_login, 20) #设置每一页显示几条 创建一个panginator对象\n try:\n current_num = int(request.GET.get('page',1)) #当你在url内输入的?page = 页码数 显示你输入的页面数目 默认为第2页\n logs = paginator.page(current_num)\n except EmptyPage:\n logs = paginator.page(1) #当你输入的page是不存在的时���就会报错\n print(paginator.num_pages)\n if paginator.num_pages > 11: # 如果分页的数目大于11\n if current_num - 5 < 1: # 你输入的值\n pageRange = range(1, 11) # 按钮数\n elif current_num + 5 > paginator.num_pages: # 按钮数加5大于分页数\n pageRange = range(current_num - 5, current_num + 1) # 显示的按钮数\n else:\n pageRange = range(current_num - 5, current_num + 6) # range求的是按钮数 如果你的按钮数小于分页数 那么就按照正常的分页数目来显示\n \n else:\n pageRange = paginator.page_range # 正常分配\n\n return render(request, 'sys_log.html', locals())\n\ndef get_handle_log(request):\n user_pk = request.POST.get('id')\n print(user_pk)\n user_handle = UserHandle.objects.filter(h_user_login=user_pk)\n user_handle = serializers.serialize(\"json\", user_handle)\n return JsonResponse({'data':user_handle})\ndef search_user(request):\n search = request.POST.get('search')\n start_date = request.POST.get('start_date')\n end_date = request.POST.get('end_date') + ' 23:59:59.99999'\n # print(end_date)\n logs = UserLogin.objects.filter(l_time__range=(start_date, end_date)).filter(l_user=search)\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n\n return JsonResponse(data)","sub_path":"logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"46648400","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom deepdiff import DeepDiff\nfrom Util.handle_json import get_value\n\nbase_path = os.path.abspath(os.path.dirname(os.getcwd()))\nsys.path.append(base_path)\n\n\ndef handle_result(url, code):\n data = get_value(url, \"/Config/code_message.json\")\n if data is not None:\n for i in data:\n message = i.get(str(code))\n if message:\n return message\n return None\n\n\ndef get_result_json(url, status):\n data = get_value(url, '/Config/result.json')\n if data is not None:\n for i in data:\n message = i.get(status)\n if message:\n return message\n return None\n\n\ndef handle_result_json(dict1, dict2):\n \"\"\"\n 比对 json\n :param dict1:\n :param dict2:\n :return:\n \"\"\"\n if isinstance(dict1, dict) and isinstance(dict2, dict):\n cmp_dict = DeepDiff(dict1, dict2, ignore_order=True).to_dict()\n if cmp_dict.get(\"dictionary_item_added\"):\n return False\n else:\n return True\n\n\nif __name__ == '__main__':\n print(get_result_json('auth/account/login', 'error'))\n\n\n\n","sub_path":"Util/handle_result.py","file_name":"handle_result.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"3140521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: hkaneko\r\n\"\"\"\r\n\r\nimport sys\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sample_functions\r\nfrom sklearn import metrics\r\nfrom sklearn import svm\r\nfrom sklearn.cross_decomposition import PLSRegression\r\nfrom sklearn.model_selection import train_test_split, cross_val_predict, GridSearchCV\r\n\r\nmethod_name = 'pls' # 'pls' or 'svr'\r\nadd_nonlinear_terms_flag = False # True (二乗項・交差項を追加) or False (追加しない)\r\n\r\nnumber_of_test_samples = 800\r\nfold_number = 2 # N-fold CV の N\r\nmax_number_of_principal_components = 30 # 使用する主成分の最大数\r\nsvr_cs = 2 ** np.arange(-5, 11, dtype=float) # C の候補\r\nsvr_epsilons = 2 ** np.arange(-10, 1, dtype=float) # ε の候補\r\nsvr_gammas = 2 ** np.arange(-20, 11, dtype=float) # γ の候補\r\n\r\nif method_name != 'pls' and method_name != 'svr':\r\n sys.exit('\\'{0}\\' という回帰分析手法はありません。method_name を見直してください。'.format(method_name))\r\n \r\ndataset = pd.read_csv('unique_m.csv', index_col=-1)\r\ndataset = dataset.sort_values('critical_temp', ascending=False).iloc[:4000, :]\r\ny = dataset.iloc[:, 86].copy()\r\nx = dataset.iloc[:, :86]\r\nx = (x.T / x.T.sum()).T\r\n# ランダムにトレーニングデータとテストデータとに分割\r\n# random_state に数字を与えることで、別のときに同じ数字を使えば、ランダムとはいえ同じ結果にすることができます\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=number_of_test_samples, shuffle=True,\r\n random_state=21)\r\n# 標準偏差が 0 の説明変数を削除\r\nstd_0_variable_flags = x_train.std() == 0\r\nx_train = x_train.drop(x_train.columns[std_0_variable_flags], axis=1)\r\nx_test = x_test.drop(x_test.columns[std_0_variable_flags], axis=1)\r\n\r\nif add_nonlinear_terms_flag:\r\n x_train = pd.read_csv('x_train_superconductor.csv', index_col=0)\r\n x_test = pd.read_csv('x_test_superconductor.csv', index_col=0)\r\n # x_train = sample_functions.add_nonlinear_terms(x_train) # 説明変数の二乗項や交差項を追加\r\n # x_test = sample_functions.add_nonlinear_terms(x_test) # 説明変数の二乗項や交差項を追加\r\n # 標準偏差が 0 の説明変数を削除\r\n std_0_nonlinear_variable_flags = x_train.std() == 0\r\n x_train = x_train.drop(x_train.columns[std_0_nonlinear_variable_flags], axis=1) # 標準偏差が 0 の説明変数を削除\r\n x_test = x_test.drop(x_test.columns[std_0_nonlinear_variable_flags], axis=1) # 標準偏差が 0 の説明変数を削除\r\n\r\n# オートスケーリング\r\nautoscaled_x_train = (x_train - x_train.mean()) / x_train.std()\r\nautoscaled_y_train = (y_train - y_train.mean()) / y_train.std()\r\nautoscaled_x_test = (x_test - x_train.mean()) / x_train.std()\r\n\r\nif method_name == 'pls':\r\n # CV による成分数の最適化\r\n components = [] # 空の list の変数を作成して、成分数をこの変数に追加していきます同じく成分数をこの変数に追加\r\n r2_in_cv_all = [] # 空の list の変数を作成して、成分数ごとのクロスバリデーション後の r2 をこの変数に追加\r\n for component in range(1, min(np.linalg.matrix_rank(autoscaled_x_train), max_number_of_principal_components) + 1):\r\n # PLS\r\n model = PLSRegression(n_components=component) # PLS モデルの宣言\r\n estimated_y_in_cv = pd.DataFrame(cross_val_predict(model, autoscaled_x_train, autoscaled_y_train,\r\n cv=fold_number)) # クロスバリデーション推定値の計算し、DataFrame型に変換\r\n estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() # スケールをもとに戻す\r\n r2_in_cv = metrics.r2_score(y_train, estimated_y_in_cv) # r2 を計算\r\n print(component, r2_in_cv) # 成分数と r2 を表示\r\n r2_in_cv_all.append(r2_in_cv) # r2 を追加\r\n components.append(component) # 成分数を追加\r\n\r\n # 成分数ごとの CV 後の r2 をプロットし、CV 後のr2が最大のときを最適成分数に\r\n optimal_component_number = sample_functions.plot_and_selection_of_hyperparameter(components, r2_in_cv_all,\r\n 'number of components',\r\n 'cross-validated r2')\r\n print('\\nCV で最適化された成分数 :', optimal_component_number)\r\n # PLS\r\n model = PLSRegression(n_components=optimal_component_number) # モデルの宣言\r\nelif method_name == 'svr':\r\n # グラム行列の分散を最大化することによる γ の最適化\r\n optimal_svr_gamma = sample_functions.gamma_optimization_with_variance(autoscaled_x_train, svr_gammas)\r\n # CV による ε の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', C=3, gamma=optimal_svr_gamma), {'epsilon': svr_epsilons},\r\n cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_epsilon = model_in_cv.best_params_['epsilon']\r\n # CV による C の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_svr_epsilon, gamma=optimal_svr_gamma),\r\n {'C': svr_cs}, cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_c = model_in_cv.best_params_['C']\r\n # CV による γ の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_svr_epsilon, C=optimal_svr_c),\r\n {'gamma': svr_gammas}, cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_gamma = model_in_cv.best_params_['gamma']\r\n # 最適化された C, ε, γ\r\n print('C : {0}\\nε : {1}\\nGamma : {2}'.format(optimal_svr_c, optimal_svr_epsilon, optimal_svr_gamma))\r\n # SVR\r\n model = svm.SVR(kernel='rbf', C=optimal_svr_c, epsilon=optimal_svr_epsilon, gamma=optimal_svr_gamma) # モデルの宣言\r\n\r\nmodel.fit(autoscaled_x_train, autoscaled_y_train) # モデルの構築\r\nif method_name == 'pls':\r\n # 標準回帰係数\r\n standard_regression_coefficients = pd.DataFrame(model.coef_, index=x_train.columns,\r\n columns=['standard_regression_coefficients'])\r\n standard_regression_coefficients.to_csv(\r\n 'pls_standard_regression_coefficients.csv') # csv ファイルに保存。同じ名前のファイルがあるときは上書きされますので注意してください\r\n# トレーニングデータ・テストデータの推定、実測値 vs. 推定値のプロット、r2, RMSE, MAE の値の表示、推定値の保存\r\nsample_functions.estimation_and_performance_check_in_regression_train_and_test(model, autoscaled_x_train, y_train,\r\n autoscaled_x_test, y_test)\r\n","sub_path":"sample_program_6_1_2_3_regression.py","file_name":"sample_program_6_1_2_3_regression.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"313192278","text":"# An example of system check where the mpi launcher is omitted in the jobscript.\nimport reframe as rfm\nimport reframe.utility.sanity as sn\nimport os\n\n@rfm.parameterized_test(['home'],['scratch'])\nclass fs_check(rfm.RunOnlyRegressionTest):\n def __init__(self,variant):\n super().__init__()\n self.descr = 'Filesystem mount check on longin and compute nodes'\n self.valid_systems = ['ibex:login','ibex:batch_nompi']\n self.valid_prog_environs = ['builtin-gcc']\n self.sourcesdir=None\n self.executable='df -h '\n self.num_tasks=1\n if variant == \"home\":\n self.sanity_patterns =sn.assert_found(r'/home/home',self.stdout)\n elif variant == \"scratch\":\n self.sanity_patterns =sn.assert_found(r'/scratch/dragon',self.stdout)\n \n self.maintainers = ['mohsin.shaikh@kaust.edu.sa']\n self.tags = {'filesystem'}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ibex_checks/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"361996414","text":"# (C) Datadog, Inc. 2018\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nimport os\n\nimport mock\nimport pytest\n\nfrom datadog_checks.dev import docker_run\nfrom datadog_checks.nginx import Nginx\n\nfrom .common import HERE, HOST, NGINX_VERSION, PORT, PORT_SSL, TAGS, USING_VTS\n\n\n@pytest.fixture(scope='session')\ndef dd_environment(instance, instance_vts):\n if USING_VTS:\n config_dir = os.path.join(HERE, 'nginx_vts')\n instance = instance_vts\n else:\n config_dir = os.path.join(HERE, 'docker', 'nginx')\n\n with docker_run(\n os.path.join(HERE, 'docker', 'docker-compose.yaml'),\n env_vars={'NGINX_CONFIG_FOLDER': config_dir},\n endpoints='http://{}:{}/nginx_status'.format(HOST, PORT),\n ):\n yield instance\n\n\n@pytest.fixture\ndef check():\n return lambda instance: Nginx('nginx', {}, [instance])\n\n\n@pytest.fixture(scope='session')\ndef instance():\n return {'nginx_status_url': 'http://{}:{}/nginx_status'.format(HOST, PORT), 'tags': TAGS}\n\n\n@pytest.fixture\ndef instance_ssl():\n return {'nginx_status_url': 'https://{}:{}/nginx_status'.format(HOST, PORT_SSL), 'tags': TAGS}\n\n\n@pytest.fixture(scope='session')\ndef instance_vts():\n return {'nginx_status_url': 'http://{}:{}/vts_status'.format(HOST, PORT), 'tags': TAGS, 'use_vts': True}\n\n\n@pytest.fixture(scope='session')\ndef version_metadata():\n # vts currently defaults to using version 1.13\n if USING_VTS:\n version = '1.13'\n else:\n version = NGINX_VERSION.split(':')[1]\n\n major, minor = version.split('.')\n\n return {\n 'version.scheme': 'semver',\n 'version.major': major,\n 'version.minor': minor,\n 'version.patch': mock.ANY,\n 'version.raw': mock.ANY,\n }\n","sub_path":"nginx/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"535443856","text":"# Longest Substring with Same Letters after Replacement - Sliding Window Pattern\n\ndef length_of_longest_substring(str,k):\n window_start, max_length, max_repeat_letter_count = 0,0,0\n frequency_map = {}\n\n for window_end in range(len(str)):\n right_char = str[window_end]\n if right_char not in frequency_map:\n frequency_map[right_char] = 0\n frequency_map[right_char] += 1\n max_repeat_letter_count = max(max_repeat_letter_count,frequency_map[right_char])\n if (window_end-window_start+1-max_repeat_letter_count > k):\n left_char = str[window_start]\n frequency_map[left_char] -= 1\n window_start += 1\n max_length = max(max_length,window_end-window_start+1)\n return max_length\n\nprint(\"Longest Substring with Same Letters after Replacement\",length_of_longest_substring(\"abccde\",1))","sub_path":"Sliding Window Pattern/7. Longest Substring with Same Letters.py","file_name":"7. Longest Substring with Same Letters.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"36282715","text":"\r\nimport math\r\n\r\n\r\ndef docross(lives, x, y,index):\r\n child1 = getChild(1, lives, x, y,index)\r\n child2 = getChild(2, lives, x, y,index)\r\n print(index,\":\",child1,distance(child1))\r\n print(index,\":\",child2,distance(child2))\r\n\r\ndef getChild(flag, lives, x, y,index):\r\n newGene = []\r\n px = lives[x].copy()\r\n py = lives[y].copy()\r\n c = px[index]\r\n newGene.append(c)\r\n index1, index2 = -1, -1\r\n dx, dy = -1, -1\r\n while len(px) > 1:\r\n for p in px:\r\n if p == c:\r\n index1 = px.index(p)\r\n break\r\n for p in py:\r\n if p == c:\r\n index2 = py.index(p)\r\n break\r\n if flag == 1:\r\n if index1 > 0:\r\n dx = px[index1 - 1]\r\n else:\r\n dx = px[len(px) - 1]\r\n if index2 > 0:\r\n dy = py[index2 - 1]\r\n else:\r\n dy = py[len(px) - 1]\r\n elif flag == 2:\r\n if index1 < len(px) - 1:\r\n dx = px[index1 + 1]\r\n else:\r\n dx = px[0]\r\n if index2 < len(px) - 1:\r\n dy = py[index2 + 1]\r\n else:\r\n dy = py[0]\r\n px.remove(c)\r\n py.remove(c)\r\n if dis[c][dx] < dis[c][dy]:\r\n c = dx\r\n else:\r\n c = dy\r\n newGene.append(c)\r\n return newGene\r\n\r\n\r\ndef distance(order):\r\n distance = 0.0\r\n for i in range(-1, len(order) - 1):\r\n index1, index2 = order[i], order[i + 1]\r\n distance += dis[index1][index2]\r\n return distance\r\n\r\n\r\ncitys=[[0,0],[3,0],[3,4],[7,3],[9,1],[]]\r\ncity_num=5\r\ndis = [[0 for x in range(city_num)] for y in range(city_num)]\r\nfor i in range(city_num):\r\n for j in range(city_num):\r\n dis[i][j] = math.sqrt((citys[i][0] -citys[j][0]) ** 2 + (citys[i][1] - citys[j][1]) ** 2)\r\n\r\n\r\n\r\n\r\nlives=[[0,1,4,2,3],[2,1,3,4,0]]\r\n# lives=[[1, 0, 3, 2, 4],[1, 3, 4, 2, 0]]\r\nprint(dis)\r\n\r\nprint(distance(lives[0]))\r\nprint(distance(lives[1]))\r\n\r\ndocross(lives,0,1,0)\r\ndocross(lives,0,1,1)\r\ndocross(lives,0,1,2)\r\ndocross(lives,0,1,3)\r\ndocross(lives,0,1,4)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"491559174","text":"import numpy as np\nimport re\n\ninputfile = \"input10\"\nexample = '''noop\naddx 3\naddx -5'''\nother_example = '''addx 15\naddx -11\naddx 6\naddx -3\naddx 5\naddx -1\naddx -8\naddx 13\naddx 4\nnoop\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx -35\naddx 1\naddx 24\naddx -19\naddx 1\naddx 16\naddx -11\nnoop\nnoop\naddx 21\naddx -15\nnoop\nnoop\naddx -3\naddx 9\naddx 1\naddx -3\naddx 8\naddx 1\naddx 5\nnoop\nnoop\nnoop\nnoop\nnoop\naddx -36\nnoop\naddx 1\naddx 7\nnoop\nnoop\nnoop\naddx 2\naddx 6\nnoop\nnoop\nnoop\nnoop\nnoop\naddx 1\nnoop\nnoop\naddx 7\naddx 1\nnoop\naddx -13\naddx 13\naddx 7\nnoop\naddx 1\naddx -33\nnoop\nnoop\nnoop\naddx 2\nnoop\nnoop\nnoop\naddx 8\nnoop\naddx -1\naddx 2\naddx 1\nnoop\naddx 17\naddx -9\naddx 1\naddx 1\naddx -3\naddx 11\nnoop\nnoop\naddx 1\nnoop\naddx 1\nnoop\nnoop\naddx -13\naddx -19\naddx 1\naddx 3\naddx 26\naddx -30\naddx 12\naddx -1\naddx 3\naddx 1\nnoop\nnoop\nnoop\naddx -9\naddx 18\naddx 1\naddx 2\nnoop\nnoop\naddx 9\nnoop\nnoop\nnoop\naddx -1\naddx 2\naddx -37\naddx 1\naddx 3\nnoop\naddx 15\naddx -21\naddx 22\naddx -6\naddx 1\nnoop\naddx 2\naddx 1\nnoop\naddx -10\nnoop\nnoop\naddx 20\naddx 1\naddx 2\naddx 2\naddx -6\naddx -11\nnoop\nnoop\nnoop'''\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nALPHABET = alphabet.capitalize()\n\nneighbours = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\ndef calc_scenic_score(numbers, i_tree, j_tree):\n up = 0\n down = 0\n left = 0\n right = 0\n\n for i in range(i_tree - 1, -1, -1):\n up += 1\n if numbers[i_tree,j_tree] <= numbers[i, j_tree]:\n break\n\n for i in range(i_tree + 1, numbers.shape[0], 1):\n down += 1\n if numbers[i_tree,j_tree] <= numbers[i, j_tree]:\n break\n\n for j in range(j_tree - 1, -1, -1):\n left += 1\n if numbers[i_tree,j_tree] <= numbers[i_tree, j]:\n break\n\n for j in range(j_tree + 1, numbers.shape[1], 1):\n right += 1\n if numbers[i_tree,j_tree] <= numbers[i_tree, j]:\n break\n\n return up * left * down * right\n\ndef textgrid_to_numbers(lines):\n return np.array([[int(x) for x in line] for line in lines], dtype=int)\n\ndef traverse(root):\n sum = 0\n for entry in root.keys():\n if entry == '..':\n continue\n if isinstance(root[entry], dict):\n sum += traverse(root[entry])\n else:\n sum += root[entry]\n global totsum\n totsum.append(sum)\n return sum\n\n\ndef append_if_exists(dictionary: dict, key, val):\n if key not in dictionary.keys():\n dictionary[key] = []\n\n dictionary[key].append(val)\n\ndirections = {\n 'R' : (0,1),\n 'L': (0, -1),\n 'U': (-1, 0),\n 'D': (1, 0)\n\n}\n\ndef move_rope(head, tail, dir):\n new_head = head + dir\n new_diff = new_head - tail\n if any(np.abs(new_diff) > 1):\n tail_movement = np.clip(new_diff, -1, 1)\n else:\n tail_movement = 0\n new_tail = tail + tail_movement\n return new_head, new_tail\n\ndef main():\n file_contents = ''\n with open(inputfile) as infile:\n file_contents = infile.read()\n \n lines = file_contents.splitlines() \n # lines = other_example.splitlines()\n\n print(f\"Read {len(lines)} lines\")\n\n i = 0\n counter = 0\n instructions = []\n register = 1\n signal_strengths = []\n image = []\n while i < len(lines) or instructions:\n if abs(counter % 40 - register) <= 1:\n image.append('#')\n else:\n image.append('.')\n \n if not instructions:\n if lines[i][:4] == 'addx':\n add = int(lines[i].split(' ')[-1])\n instructions.append([2, add])\n i += 1\n elif lines[i] == 'noop':\n i += 1\n counter += 1\n if counter % 40 == 20:\n print(f'Counter: {counter}, Register: {register}')\n signal_strengths.append(counter * register)\n\n if instructions:\n instructions[0][0] -= 1\n if instructions[0][0] == 0:\n register += instructions[0][1]\n instructions = instructions[1:]\n\n print(f'sum: {sum(signal_strengths)}, Signal strengths: {signal_strengths}')\n for line_i in range(len(image) // 40):\n print(''.join(image[line_i* 40:line_i * 40 + 40]))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"120208236","text":"import os\nimport tools.csvio as csv\nimport classicalMethods.cusum_first_implementation as cusum\nimport tools.evaluation as eval\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport classical_methods.baysiancpdetection as baycpd #To be removed (commented) if not needed (needs R)\n\ndef binary2index(m):\n temp = []\n for i in range(len(m)):\n if(m[i] == 1):\n temp.append(i)\n return temp\n\n\ndef evaluationDataSet(folder):\n # Use CUSUM and Bayesian to detect change point\n file_csv = os.listdir(folder)\n precisionB = []\n recallB = []\n precisionC = []\n recallC = []\n\n for f in file_csv:\n f = folder + '/' + f\n reality = csv.csv2list(f, 'rtt', sep=';', decimal='.')\n\n detectionB = baycpd.baysiancpt(reality)\n detectionC = cusum.cusum_var(reality)\n fact = csv.csv2list(f, 'cp', sep=';', decimal='.')\n\n # Change the binary array to index array\n detectionB = binary2index(detectionB)\n detectionC = binary2index(detectionC)\n fact = binary2index(fact)\n\n #print(fact)\n\n temp = eval.evaluation_window_adp(fact, detectionB, 2)\n precisionB.append(temp[\"precision\"])\n recallB.append(temp[\"recall\"])\n\n temp = eval.evaluation_window_adp(fact, detectionC, 2)\n precisionC.append(temp[\"precision\"])\n recallC.append(temp[\"recall\"])\n\n csv.list2csv('./results/resultBayesian_w.csv',\n [file_csv, precisionB, recallB], ['fileName', 'precision', 'recall'])\n csv.list2csv('./results/resultCUSUM_w.csv',\n [file_csv, precisionC, recallC], ['fileName', 'precision', 'recall'])\n\n\ndef cdf_precision_cusum():\n precision = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n cdf = [float(k+1)/len(precision) for k in range(len(precision))]\n precision.sort()\n plt.plot(precision, cdf)\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of precision for cusum method\")\n plt.show()\n return\n\n\ndef cdf_recall_cusum():\n recall = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n cdf = [float(k+1)/len(recall) for k in range(len(recall))]\n recall.sort()\n plt.plot(recall, cdf)\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of recall for cusum method\")\n plt.show()\n return\n\n\ndef cdf_precision_baysian():\n precision = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n cdf = [float(k+1)/len(precision) for k in range(len(precision))]\n precision.sort()\n plt.plot(precision, cdf)\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of precision for Bayesian method\")\n plt.show()\n return\n\n\ndef cdf_recall_baysian():\n recall = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n cdf = [float(k+1)/len(recall) for k in range(len(recall))]\n recall.sort()\n plt.plot(recall, cdf)\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of recall for Bayesian method\")\n plt.show()\n return\n\n\n# Function that calculate and plot the Fn measure for both methods (n is generally 1 or 2)\ndef Fn_score(n):\n recallBayesian = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n precisionBayesian = csv.csv2list(\n './results/resultBayesian_w.csv', 'precision')\n\n Fn_bayesian = []\n for i in range(len(recallBayesian)):\n if(recallBayesian[i] != 0 or precisionBayesian[i] != 0):\n Fn_bayesian.append((1+n*n)*(precisionBayesian[i]*recallBayesian[i])/(\n n*n*(precisionBayesian[i]+recallBayesian[i])))\n\n else:\n Fn_bayesian.append(0)\n\n recallCusum = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n precisionCusum = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n\n Fn_cusum = []\n for i in range(len(recallCusum)):\n if(recallCusum[i] != 0 or precisionCusum[i] != 0):\n Fn_cusum.append(\n (1+n*n)*(precisionCusum[i]*recallCusum[i])/(n*n*precisionCusum[i]+recallCusum[i]))\n\n else:\n Fn_cusum.append(0)\n\n plt.plot(Fn_bayesian, \"x\", label=\"Bayesian method\")\n plt.plot(Fn_cusum, \"x\", label=\"Cusum method\")\n plt.legend()\n plt.xlabel(\"Index of datasets\")\n plt.ylabel(\"Fn_measure\")\n plt.title(\"F Score for n=\"+str(n) +\n \" applied to the results of Bayesian and Cusum methods\")\n plt.show()\n return\n\n\ndef comparison_precision():\n precisionC = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n precisionB = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n precisionN = csv.csv2list('./results/resultNeuroNet_w.csv', 'precision',)\n cdf = [float(k+1)/len(precisionC) for k in range(len(precisionC))]\n precisionC.sort()\n precisionB.sort()\n precisionN.sort()\n plt.plot(precisionC, cdf, \"r\", label=\"precision of cusum method\")\n plt.plot(precisionB, cdf, \"b\", label=\"precision of bayesian method\")\n plt.plot(precisionN, cdf, \"g\", label=\"precision of NeuroNet\")\n plt.legend()\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"comparison of cdf (precision)\")\n plt.show()\n return\n\n\ndef comparison_recall():\n recallC = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n recallB = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n cdf = [float(k+1)/len(recallC) for k in range(len(recallC))]\n recallC.sort()\n recallB.sort()\n plt.plot(recallC, cdf, \"r\", label=\"recall of cusum method\")\n plt.plot(recallB, cdf, \"b\", label=\"recall of bayesian method\")\n plt.legend()\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"comparison of cdf (recall)\")\n plt.show()\n return\n\n\ndef recall_precision():\n precisionC = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n precisionB = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n precisionN = csv.csv2list('./results/resultNeuroNet_w.csv', 'precision')\n recallC = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n recallB = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n recallN = csv.csv2list('./results/resultNeuroNet_w.csv', 'recall')\n plt.plot(precisionC, recallC, \"rx\", label=\"cusum method\")\n plt.plot(precisionB, recallB, \"bx\", label=\"bayesian method\")\n plt.plot(precisionN, recallN, \"gx\", label=\"NeuroNet method\")\n plt.legend()\n plt.xlabel(\"precision\")\n plt.ylabel(\"recall\")\n plt.title(\"scatterplot (precision,recall)\")\n plt.show()\n return\n\nevaluationDataSet(\"./rtt_series/valid_data\")\n#evaluationDataSet(\"./rtt_series/artificial_dataset\")\nrecall_precision()\n#comparison_precision()","sub_path":"groupProject/evaluation_methods.py","file_name":"evaluation_methods.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"450058549","text":"#create the top most network\ntopnet = exp.createTopNet(\"top\")\ntopnet.createShortestPath();\n\nleft_net = topnet.createNet(\"left\")\nleft_net.createShortestPath();\n\nh1 = left_net.createHost(\"h1\")\nif1 = h1.createInterface(\"if0\")\n\nh2 = left_net.createHost(\"h2\")\nif2 = h2.createInterface(\"if0\")\n\nh3 = left_net.createHost(\"h3\")\nif3 = h3.createInterface(\"if0\")\n\nh4 = left_net.createHost(\"h4\")\nif4 = h4.createInterface(\"if0\")\n\nr = left_net.createRouter(\"r\")\n\nl1 = left_net.createLink()\nl1.createInterface(if1)\nl1.createInterface(r.createInterface(\"if1\"))\n\nl2 = left_net.createLink()\nl2.createInterface(if2)\nl2.createInterface(r.createInterface(\"if2\"))\n\nl3 = left_net.createLink()\nl3.createInterface(if3)\nl3.createInterface(r.createInterface(\"if3\"))\n\nl4 = left_net.createLink()\nl4.createInterface(if4)\nl4.createInterface(r.createInterface(\"if4\"))\n\t\t\n#create the right network\nright_net = left_net.copy(\"right_net\",topnet)\n\n#link the left and right networks\ntoplink = topnet.createLink(\"toplink\")\ntoplink.createInterface(left_net.get(\"r\").createInterface(\"if0\"))\ntoplink.createInterface(right_net.get(\"r\").createInterface(\"if0\"))\n\n#add traffic\nright_h2 = right_net.get(\"h1\")\ntrafficFactory = jprime.TrafficFactory(topnet)\ntrafficFactory.createSimulatedTCP(10, 100000000, h1, right_h2)\ntrafficFactory.createSimulatedTCP(13, 100000000, h2, right_h2)\n\n","sub_path":"examples/MySecondPythonModel.py","file_name":"MySecondPythonModel.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"306400604","text":"import bisect\n\n\nclass Solution:\n def platesBetweenCandles(self, s: str, queries):\n candles = []\n n = len(s)\n for i in range(n):\n if s[i] == '|':\n candles.append(i)\n res = []\n for l, r in queries:\n left = bisect.bisect_left(candles, l)\n right = bisect.bisect_right(candles, r) - 1\n res.append(max(0, candles[right] - candles[left] - (right - left)))\n return res\n\n\ns = Solution()\nprint(s.platesBetweenCandles(\"***|**|*****|**||**|*\", [[1, 17], [4, 5], [14, 17], [5, 11], [15, 16]]))\n# print(s.platesBetweenCandles(\"**|**|***|\", [[2, 5], [5, 9]]))\n","sub_path":"leetcode/2021/bicontest/bcontest-064/bContest3.py","file_name":"bContest3.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"296403827","text":"\"\"\"\nGiven a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.\n\nFor example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].\n\nNote: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].\n\"\"\"\n\n\ndef dailyTemperaturesBruteForce(T):\n \"\"\"\n :type T: List[int]\n :rtype: List[int]\n \"\"\"\n ans = []\n for i in range(len(T)):\n c = 1\n flag = False\n for j in range(i+1, len(T)):\n if T[j] > T[i]:\n ans += [c]\n flag = True\n break\n c += 1\n if not flag:\n ans += [0]\n return ans\n\ndef dailyTempsStack(T):\n ret = [0] * len(T)\n stack = []\n\n for i in range(len(T)):\n\n while stack and T[i] > T[stack[-1]]:\n index = stack.pop()\n ret[index] = i - index\n\n stack.append(i)\n\n print(stack, ret)\n\n return ret\n\nprint(dailyTempsStack([73, 69, 65, 68]))\n","sub_path":"LeetCode/Google/daily_temps.py","file_name":"daily_temps.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"292229514","text":"def isDivisible(a,b):\n if a % b == 0:\n return True\n else:\n return False\n\nresult = True\nnumber = int(input(\"Enter a number: \"))\nfor i in range(2,number-1):\n if isDivisible(number,i):\n result = False\n print(\"Not a prime number.\")\n break\nif result:\n print(\"Prime number.\")\n\n \n","sub_path":"Exercise_11.py","file_name":"Exercise_11.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"213714440","text":"from flask import Blueprint, session, make_response, jsonify, request\n\nfrom managers.ceph_manager import CephManager\nfrom utils.validation_schemas import schemas\nfrom utils.validator import json_schema_validator\n\nbuckets = Blueprint('buckets', __name__)\n\n\n@buckets.route('/buckets', methods=['GET'], strict_slashes=False)\ndef list_buckets():\n ceph = CephManager.from_session(session=session)\n buckets_list = ceph.list_buckets()\n return make_response(jsonify(dict(buckets=buckets_list)), 200)\n\n\n@buckets.route('/buckets', methods=['POST'], strict_slashes=False)\ndef create_bucket():\n \"\"\"\n Creates a bucket and assigns the user's origin to the bucket's CORS\n \"\"\"\n data = request.get_json()\n json_schema_validator(data, schema=schemas['create_bucket'])\n ceph = CephManager.from_session(session=session)\n bucket = ceph.create_buckets(bucket_name=data['name'])\n set_cors(data['name'])\n return make_response(jsonify(bucket), 200)\n\n\n# @buckets.route('/buckets/<bucket_name>/cors', methods=['GET'], strict_slashes=False)\n# def get_bucket_cors(bucket_name):\n# ceph = CephManager.from_session(session=session)\n# bucket = ceph.get_bucket(bucket_name=bucket_name)\n# return make_response(jsonify(bucket), 200)\n#\n#\n# @buckets.route('/buckets/<bucket_name>/cors', methods=['PUT'], strict_slashes=False)\n# def set_bucket_cors(bucket_name):\n# ceph = CephManager.from_session(session=session)\n# bucket = ceph.get_bucket(bucket_name=bucket_name)\n# return make_response(jsonify(bucket), 200)\n\n\n@buckets.route('/buckets/<bucket_name>', methods=['DELETE'], strict_slashes=False)\ndef delete_bucket(bucket_name):\n ceph = CephManager.from_session(session=session)\n ceph.delete_bucket(bucket_name)\n resp = make_response(jsonify(dict(msg=f\"Bucket {bucket_name} deleted.\")), 200)\n return resp\n\n\n@buckets.route('/buckets/<bucket_name>', methods=['GET'], strict_slashes=False)\ndef get_bucket(bucket_name):\n ceph = CephManager.from_session(session=session)\n objects = ceph.list_object(bucket_name)\n if 'Contents' in objects:\n size = sum(obj['Size'] for obj in objects['Contents'])\n length = len(objects['Contents'])\n else:\n size = 0\n length = 0\n response_data = dict(Name=bucket_name, Size=size, Length=length)\n set_cors(bucket_name)\n return make_response(jsonify(response_data), 200)\n\n\ndef set_cors(bucket_name):\n ceph = CephManager.from_session(session=session)\n if 'HTTP_HOST' in request.environ: # Only if the client is a browser this is needed\n ceph.set_bucket_cors(bucket_name=bucket_name, origins=['http://' + request.environ['HTTP_HOST'],\n 'https://' + request.environ['HTTP_HOST']])\n\n\n@buckets.route('/buckets/<bucket_name>/objects', methods=['GET'], strict_slashes=False)\ndef get_bucket_objects(bucket_name):\n ceph = CephManager.from_session(session=session)\n objects = ceph.list_object(bucket_name)\n return make_response(jsonify(objects['Contents'] if 'Contents' in objects else []), 200)\n","sub_path":"server/routes/buckets.py","file_name":"buckets.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"553271538","text":"#!/user/bin/python3\n# -*- coding: utf-8 -*-\n# compatible with Python 3.4.3\n\n__author__=\"Bo Zhou\"\n__copyright__ = \"Copyright 2015, The NRA project \"\n__credits__ = [\"Bo Zhou\"]\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Bo Zhou\"\n__email__ = \"bzhou2@ualberta.ca\"\n__status__ = \"Testing\"\n\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nimport time\n\ninFile = input(\"Please enter xlsx file name: \")\nstartTime = time.time()\ninwb = load_workbook(filename='data_confirm_PA.xlsx')\nsheetRange = inwb ['NRA Address']\nrow = 1\nreference = []\nwhile True:\n if sheetRange[\"A\"+str(row)].value == None:\n break \n item1 = sheetRange[\"A\"+str(row)].value\n item2 = sheetRange[\"B\"+str(row)].value\n item3 = sheetRange[\"C\"+str(row)].value\n item4 = sheetRange[\"D\"+str(row)].value\n item5 = sheetRange[\"E\"+str(row)].value\n itemTuple = (item1,item2,item3,item4,item5)\n reference.append(itemTuple)\n row += 1\n#inwb.save('data_confirm_PA.xlsx')\n\nrow = 1\ncwb = load_workbook(filename=inFile)\nsheetRange2 = cwb ['NRA Address']\ncompare = []\nwhile True:\n if sheetRange2[\"A\"+str(row)].value == None:\n break \n item1 = sheetRange2[\"A\"+str(row)].value\n item2 = sheetRange2[\"B\"+str(row)].value\n item3 = sheetRange2[\"C\"+str(row)].value\n item4 = sheetRange2[\"D\"+str(row)].value\n item5 = sheetRange2[\"E\"+str(row)].value\n itemTuple = (item1,item2,item3,item4,item5)\n compare.append(itemTuple)\n row += 1\n#cwb.save(inFile)\nbad = 0\nfor e in compare:\n if e not in reference:\n rownumber = compare.index(e)\n print (\"on Row: \"+str(rownumber+1)+\" . Bad data: \",str(e[1]))\n bad += 1\n\nif bad == 0 :\n print (\"All data are found in reference\")\nprint(\"Finish\")\nelapsedTime = time.time() - startTime\nprint (\"time use: \", elapsedTime)","sub_path":"complete_test_data/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"406867607","text":"from flask import Flask, redirect\nfrom flask_socketio import SocketIO, emit\nfrom config import Config\nimport views, websockets\nfrom flask_login import LoginManager\nfrom models.user import User\nfrom flask_login import current_user\n\n\napp = Flask(__name__)\napp.config.from_object(Config)\napp.register_blueprint(views.main_client)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\nsocketio = SocketIO(app)\n\n\n@login_manager.user_loader\ndef load_user(userid):\n return User.get(User.id == userid)\n\n\n@login_manager.unauthorized_handler\ndef unauthorized():\n return redirect('/login')\n\n\n\n\n\n\n\n@socketio.on('my event', namespace='/test')\ndef test_message(message):\n emit('my response', {'data': message['data']}, broadcast=True)\n\n@socketio.on('send_chat_msg', namespace='/test')\ndef test_message(message):\n emit('my response', {'data': message['data'], 'username' : current_user.username}, broadcast=True)\n\n@socketio.on('connect', namespace='/test')\ndef test_connect():\n emit('connected', {'data': current_user.username})\n\n@socketio.on('disconnect', namespace='/test')\ndef test_disconnect():\n print('Client disconnected')\n\nif __name__ == '__main__':\n socketio.run(app)\n\n\n","sub_path":"textFlask/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"473056831","text":"__author__ = 'deutscherkoenig'\nimport datetime\nfrom datetime import date\nimport json\nimport urllib.request\n\n_URL = \"\"\"http://ip-api.com/json\"\"\"\n_FILE_OUT = \"log.txt\"\n\n\ndef get_public_ip():\n try:\n data = json.loads(urllib.request.urlopen(_URL).read().decode(\"utf-8\"))['query']\n except:\n data = \"Error occurred getting IP\"\n _date = date.today()\n _time = str(datetime.datetime.now().time()).split(\".\")[0]\n with open(_FILE_OUT, \"a+\") as file:\n file.write('%s %s: %s \\n' % (_date, _time, data))\n print('%s %s: %s \\n' % (_date, _time, data))\n\n return data\n\nif __name__ == '__main__':\n get_public_ip()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"459798966","text":"__author__ = \"Alejo Herrera\"\n\n#Comisión de Vendedores\n\n# Declarar variables\ncategoria = 1\ntotalventa = 0\nventacat1 = 0\nventacat2 = 0\nventacat3 = 0\nventacat4 = 0\n\n#Estructura repetitiva\nwhile categoria != 0:\n categoria = int(input(\"Ingrese categoria: \"))\n if categoria != 0:\n totalventa = float(input(\"Ingrese total de ventas: \"))\n if categoria == 1:\n ventacat1 = (totalventa * 10 / 100) + ventacat1\n elif categoria == 2:\n ventacat2 = (totalventa * 25 / 100) + ventacat2\n elif categoria == 3:\n ventacat3 = (totalventa * 30 / 100) + ventacat3\n elif categoria == 4:\n ventacat4 = (totalventa * 40 / 100) + ventacat4\n else:\n print(\"ingrese categoria valida\")\n\nprint(\"Categoria 1:\", ventacat1)\nprint(\"Categoria 2:\", ventacat2)\nprint(\"Categoria 3:\", ventacat3)\nprint(\"Categoria 4:\", ventacat4)\n\n\n","sub_path":"Guía de Ejercicios Practicos/Guia de Ejercicios Prácticos-Ficha 06/Ej9.py","file_name":"Ej9.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"86713523","text":"import abc\nimport re\nfrom coltrane.appstorage import atomic_operations, service_fields_for_atomic\nfrom coltrane.rest import exceptions\n\n__author__ = 'Pasha'\n\nclass Validator(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def validate(self, **kwargs):\n raise NotImplementedError(\"This function must be performed in subclasses\")\n\n @abc.abstractmethod\n def _wrong_data(self, doc=None):\n \"\"\"\n Returns invalid data (fields or values) of document.\n Developer should invoke this method in subclasses.\n \"\"\"\n raise NotImplementedError(\"This function must be performed in subclasses\")\n\n\n def _from_list(self, l):\n \"\"\"\n It is used for processing list object type.\n Passed object must be list type only.\n This method should be invoked in subclasses.\n \"\"\"\n found_fields = set()\n for v in l:\n if type(v) == list:\n new_fields = self._from_list(v)\n elif type(v) == dict:\n new_fields = self._wrong_data(v)\n else:\n continue\n if new_fields:\n found_fields = found_fields.union(new_fields)\n return found_fields\n \n\nclass ForbiddenFieldsValidator(Validator):\n \"\"\"\n Base class for validators.\n Validators are used to verify document structure, they should rise errors\n if any of forbidden fields were found in document\n Validators are used in chain (implementation of pattern Chain of Responsibilities).\n \"\"\"\n __metaclass__ = abc.ABCMeta\n \n def __init__(self, doc, forbidden_fields, next_validator=None):\n \"\"\"\n Base constructor for validators.\n Parameters:\n doc - document for validation\n forbidden_fields - fields validation is going on\n next_validator - (object of any subclass of Validator).\n The next validator in the chain after current validator.\n \"\"\"\n\n self.doc = doc\n self.forbidden_fields = forbidden_fields\n self.next_validator = next_validator\n\n def validate(self):\n \"\"\"\n Public method for performing validation.\n Here is all logic of the delegating responsibilities to the next validator\n and raising Exception if there are any of forbidden fields in the document.\n \"\"\"\n found_fields = set()\n validator = self\n while validator:\n found_new = validator._wrong_data(validator.doc)\n found_fields = found_fields.union(found_new)\n validator = validator.next_validator\n\n if len(found_fields):\n raise exceptions.InvalidDocumentFieldsError(\n exceptions.InvalidDocumentFieldsError.FORBIDDEN_FIELDS_MSG %\n ','.join(found_fields))\n\n\nclass SimpleValidator(ForbiddenFieldsValidator):\n \"\"\"\n Finds forbidden fields only in top level of document.\n \"\"\"\n def _wrong_data(self, doc):\n fields = [key for key in doc if key in self.forbidden_fields]\n return set(fields)\n\n \nclass RecursiveValidator(ForbiddenFieldsValidator):\n \"\"\"\n Finds all forbidden fields from top to deepest embedded.\n \"\"\"\n def _wrong_data(self, doc):\n found_fields = set()\n for key in doc:\n if key in self.forbidden_fields:\n found_fields.add(key)\n embed_doc = doc[key]\n if type(embed_doc) is dict:\n new_fields = self._wrong_data(embed_doc)\n elif type(embed_doc) is list:\n new_fields = self._from_list(embed_doc)\n else:\n continue\n if new_fields:\n found_fields = found_fields.union(new_fields)\n return found_fields\n\n\nclass KeyValidator(Validator):\n \"\"\"\n Base validator for _key value and for all keys names.\n Values of <v> in sample {'_key': <v>, <v>:10, <v>: {<v>:5}}\n are validated for correct value.\n \"\"\"\n #Allowed: _a-bc_\n # Forbidden: __a, b__, -c, d.e\n key_re = re.compile(r'^(?!__)\\w[\\w-]*(?<!__)$')\n exceptions = {}\n\n def __init__(self, data):\n self.data = data\n\n def validate(self, recursive=False):\n if self.data is None:\n return\n if recursive:\n found_keys = self._wrong_data(self.data)\n else:\n found_keys = self._wrong_data_simple(self.data)\n found_keys.difference_update(self.exceptions)\n if len(found_keys):\n raise exceptions.InvalidKeyNameError(\n 'Document key has invalid format [%s]' % ','.join(found_keys))\n\n\n def _wrong_data(self, doc):\n \"\"\"\n Finds all invalid keys.\n Keys are checked by regexp recursively.\n \"\"\"\n found_keys = set()\n for k in doc:\n if not re.match(self.key_re, k):\n found_keys.add(k)\n v = doc[k]\n if type(v) == dict:\n found = self._wrong_data(v)\n elif type(v) == list:\n found = self._from_list(v)\n else:\n continue\n if found:\n found_keys = found_keys.union(found)\n return found_keys\n\n\n def _wrong_data_simple(self, keys):\n \"\"\"\n Finds all invalid keys.\n Top level keys only are checked by regexp.\n \"\"\"\n found_keys = set()\n for k in keys:\n if not re.match(self.key_re, k):\n found_keys.add(k)\n return found_keys\n\n\nclass SaveDocumentKeysValidator(KeyValidator):\n \"\"\"\n Validator for document to save.\n Allows only 0-9,a-z,A-Z,_\n \"\"\"\n def __init__(self, doc):\n super(SaveDocumentKeysValidator, self).__init__(doc)\n\n def validate(self, recursive=True):\n super(SaveDocumentKeysValidator, self).validate(recursive)\n\n\nclass FilterKeysValidator(KeyValidator):\n \"\"\"\n Validator for filter object.\n It allows symbols '$','.' because of filter syntax:\n filter = {'a.b.c':10, '$and':[{'b':{'$gt': 5}}, {'c':10}]}\n \"\"\"\n #Allowed: _a-b.$c_\n # Forbidden: __a, b__, -c\n key_re = re.compile(r'^(?!__)[\\w$][\\w\\.-]*(?<!__)$')\n \n def __init__(self, filter):\n super(FilterKeysValidator, self).__init__(filter)\n\n def validate(self, recursive=True):\n super(FilterKeysValidator, self).validate(recursive)\n\n\nclass UpdateDocumentKeysValidator(KeyValidator):\n \"\"\"\n Document validator to update underlying document.\n It allows symbol '.' because of search mongo syntax:\n doc = {'a.b.c':10}\n It will replace <obj> in\n {'a':{'b':{'c':<obj>}}} by 10\n \"\"\"\n #Allowed: _a-b.c_\n # Forbidden: __a, b__, -c\n key_re = re.compile(r'^(?!__)\\w[\\w\\.-]*(?<!__)$')\n exceptions = set(atomic_operations + service_fields_for_atomic)\n\n def __init__(self, update_doc):\n super(UpdateDocumentKeysValidator, self).__init__(update_doc)\n\n def validate(self, recursive=True):\n super(UpdateDocumentKeysValidator, self).validate(recursive)\n \n","sub_path":"coltrane/rest/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"392695561","text":"# etreeTest\n# Created by JKChang\n# 01/08/2017, 15:19\n# Tag:\n# Description: \n\nfrom lxml import etree\n\nroot = etree.Element(\"root\", interested = \"totally\")\n# print(etree.tostring(root).decode('utf-8'))\nroot.append(etree.Element(\"ch1\"))\nch2 = etree.SubElement(root, \"ch2\")\nch2.text = \"This is ch2's content\"\nch3 = etree.SubElement(root, \"ch3\")\nprint(etree.tostring(root, pretty_print=True).decode('utf-8'))\n\nprint(len(root))\n","sub_path":"CJK/temp/etreeTest.py","file_name":"etreeTest.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316882162","text":"#coding:utf-8\n\n\"\"\"\nfileinput模块可以遍历文本文件的所有行.它的工作方式和readlines很类似,不同点在于,它不是将全部的行读到列表中而是创建了一个xreadlines对象.\n\n下面是fileinput模块中的常用函数\n1.input() #它会返回能够用于for循环遍历的对象.\n2.filename() #返回当前文件的名称\n3.lineno() #返回当前(累计)的行数\n4.filelineno() #返回当前文件的行数\n5.isfirstline() #检查当前行是否是文件的第一行\n6.close() #关闭序列\n\n\n\"\"\"\n\n\n\nimport fileinput\nimport timeit\ndef func_fileinput():\n for eachline in fileinput.input(\"D:/dll_list.txt\"):\n print(\"fileinput\",eachline)\n\ndef file_open():\n file = open(\"D:/dll_list.txt\",\"r\")\n for word in file.readlines():\n print(\"readlines:\",word)\n\nw1 = timeit.timeit(func_fileinput,number=1)\nw2 = timeit.timeit(file_open,number=1)\nprint(\" fileinput time is: %s\" % w1)\nprint(\" filereadlines time is: %s\" % w2)\n\n#通过实践计算,还是readlines性能好些,速度更快\n","sub_path":"advancedTechnology/modules/module_fileinput/fileinput_base.py","file_name":"fileinput_base.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"227499775","text":"import numpy as np\nimport math\n\ndef read_file(file):\n data = np.loadtxt(file,delimiter=',')\n return data\n\ndef get_phi(class1,class2):\n phi = len(class2)/(len(class1)+len(class2))\n return phi\n\ndef get_mu0(data):\n mu0 = 0\n count = 0\n for i in range(len(train)):\n mu0 = mu0 + train[i]*train[i][20]\n if(train[i][20]==0):\n count=count+1\n return mu0/count\n\ndef get_mu1(data):\n mu1 = 0\n count = 0\n for i in range(len(train)):\n mu1 = mu1 + train[i]*(1-train[i][20])\n if(train[i][20]==1):\n count=count+1\n return mu1/count\n\ndef get_S0(train0, mu0):\n mu0 = mu0[0:20].reshape(len(mu0)-1,1)\n length = len(train0[0])-1\n s0 = np.zeros((length,length))\n for i in range(len(train0)):\n #get s1\n x0 = train0[i][0:20].reshape(length,1)\n sub0 = x0 - mu0\n s0 = s0 + np.dot(sub0,sub0.T)\n return s0/len(train0)\n\ndef get_S1(train1, mu1):\n mu1 = mu1[0:20].reshape(len(mu1)-1,1)\n length = len(train1[0])-1\n s1 = np.zeros((length,length))\n for i in range(len(train1)):\n #get s1\n x1 = train1[i][0:20].reshape(length,1)\n sub1 = x1 - mu1\n s1 = s1 + np.dot(sub1,sub1.T)\n return s1/len(train1)\n\ndef get_S(S0,train0,S1,train1):\n tot_num = len(train0) + len(train1)\n S = len(train0)*S0/tot_num + len(train1)*S1/tot_num\n return S\n\ndef prob_class0(mu0,S,x,phi):\n x = x[0:20]\n mu0 = mu0[0:20]\n S_inv = np.linalg.inv(S)\n constant = 1/(pow((2*math.pi),len(x)/2)*pow(np.linalg.norm(S),0.5))\n x = x.reshape(len(x),1)\n mu0 = mu0.reshape(len(mu0),1)\n sub = x - mu0\n a = -0.5*(np.dot(np.dot(sub.T,S_inv),sub))\n prob = constant*math.exp(a)\n p_y = pow(phi,0)*pow((1-phi),1)\n prob_c0 = p_y*prob\n return prob_c0\n\ndef prob_class1(mu1,S,x,phi):\n x = x[0:20]\n mu1 = mu1[0:20]\n S_inv = np.linalg.inv(S)\n constant = 1/(pow((2*math.pi),len(x)/2)*pow(np.linalg.norm(S),0.5))\n x = x.reshape(len(x),1)\n mu1 = mu1.reshape(len(mu1),1)\n sub = x - mu1\n a = -0.5*(np.dot(np.dot(sub.T,S_inv),sub))\n prob = constant*math.exp(a)\n p_y = pow(phi,1)*pow((1-phi),0)\n prob_c1 = p_y*prob\n return prob_c1\n\ndef get_sigma(prob1,prob2):\n a = math.log(prob1)/math.log(prob2)\n sigma = 1/(1+math.exp(-a))\n return sigma\n\ndef get_accuracy(real,res):\n correct = 0\n for i in range(len(real)):\n if(real[i]==res[i]):\n correct = correct + 1\n return correct/len(real)\n\n\ntrain = read_file('DS2/DS2_train.txt')\n\ntrain0 = train[0:1200]\ntrain1 = train[1200:2400]\n\nphi = get_phi(train0,train1)\n\nmu0 = get_mu0(train0)\nmu1 = get_mu1(train1)\n\ns0 = get_S0(train0,mu0)\ns1 = get_S1(train1,mu1)\n\ns = get_S(s0,train0,s1,train1)\n\ntest = read_file('DS2/DS2_test.txt')\n\ntest0 = test[0:400]\ntest1 = test[400:800]\n\nres = []\nreal = []\nfor i in range(len(test)):\n c0 = prob_class0(mu0,s,test[i],phi)\n c1 = prob_class1(mu1,s,test[i],phi)\n sig0 = get_sigma(c0,c1)\n sig1 = get_sigma(c1,c0)\n if(sig0>sig1):\n res.append(0)\n else:\n res.append(1)\n real.append(int(test[i][20]))\n\naccuracy = get_accuracy(res,real)\nprint('accuracy: ', accuracy)\n\nTP = 0\nFP = 0\nFN = 0\nTN = 0\n\nfor i in range(len(res)):\n if(res[i]==1 and real[i]==1):\n TP = TP + 1\n elif(res[i]==1 and real[i]==0):\n FP = FP + 1\n elif(res[i]==0 and real[i]==1):\n FN = FN + 1\n else:\n TN = TN + 1\n\nprecision = TP/(TP+FP)\nprint('precision: ',precision)\n\nrecall = TP/(TP+FN)\nprint('recall: ',recall)\n\nf_measure = 2*precision*recall/(precision+recall)\nprint('F-measure: ',f_measure)\n\nparta = open('Assignment2_260540022_5_1_a.txt','w')\nparta.write('accuracy: '+str(accuracy)+'\\n\\n')\nparta.write('precision: '+str(precision)+'\\n\\n')\nparta.write('recall: '+str(recall)+'\\n\\n')\nparta.write('F-measure: '+str(f_measure)+'\\n\\n')\n\nfile_submit = open('Assignment2_260540022_5_1_b.txt','w')\n\nfile_submit.write('phi: '+str(phi)+'\\n\\n')\nfile_submit.write('mu0: '+str(mu0[0:20])+'\\n\\n')\nfile_submit.write('mu1: '+str(mu1[0:20])+'\\n\\n')\nfile_submit.write('S: '+str(s)+'\\n')\n","sub_path":"COMP551-Assignments/HW2/HW2Q5.py","file_name":"HW2Q5.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"98344378","text":"hauteur = 0\nlargeur = 0\nestOk = 0\ndifficulte = input(\"Capitaine, quel niveau choisissez-vous ? Facile, moyen, difficile ?\").upper()\n\nwhile estOk == 0 :\n if difficulte == \"FACILE\":\n hauteur += 6\n largeur += 6\n\n estOk = 1\n continue\n elif difficulte == \"MOYEN\":\n hauteur += 8\n largeur += 8\n estOk = 1\n continue\n elif difficulte == \"DIFFICILE\":\n hauteur += 11\n largeur += 11\n estOk = 1\n continue\n else:\n print(\"Mauvais\")\n difficulte = input(\"Capitaine, quel niveau choisissez-vous ? Facile, moyen, difficile ?\").upper()\n estOk = 0","sub_path":"difficulte.py","file_name":"difficulte.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"288746343","text":"work = input('Enter the file name: ')\ntry:\n mwork = open(work)\nexcept:\n #work = work.upper()\n print(work, \"TO YOU - You have been punk'd\")\n quit()\ncount = 0\nfor line in mwork:\n if line.startswith('Subject'):\n count = count + 1\nprint('There were', count, 'subject lines in', work)","sub_path":"CC4/CC4-Ex09/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"519698171","text":"import tensorrt as trt\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n\n\nTRT_LOGGER = trt.Logger(trt.Logger.INFO)\n\nmodel_name = 'resnet-101-aic-448-9000-b1'\nmodel_path = 'onnx/' + model_name + '.onnx'\nbuilder = trt.Builder(TRT_LOGGER)\nnetwork = builder.create_network()\nparser = trt.OnnxParser(network, TRT_LOGGER)\nwith open(model_path, 'rb') as model:\n parser.parse(model.read())\n\nbuilder.max_batch_size = 1\n# builder.max_workspace_size = 20<<1\nbuilder.max_workspace_size = 10000000000\n# builder.fp16_mode=True\nengine = builder.build_cuda_engine(network)\n\nwith open(\"engine/\" + model_name + '.engine', \"wb\") as f:\n f.write(engine.serialize())","sub_path":"onnx_to_trtengine.py","file_name":"onnx_to_trtengine.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164448242","text":"#!/usr/bin/python\n# Filename: prescription.py\n\n\n# This object class represents the prescription we're pulling from the db'\nclass Prescription (object):\n\n def __init__(self,\n ident,\n rxDate,\n orderType,\n medBrand,\n medGeneric,\n medClass,\n numUnits,\n doseCount,\n doseFreq,\n unitDose,\n doseForm,\n notes):\n self.ident = ident\n self.rxDate = rxDate\n self.orderType = orderType\n self.medBrand = medBrand\n self.medGeneric = medGeneric\n self.medClass = medClass\n self.numUnits = numUnits\n self.doseCount = doseCount\n self.doseFreq = doseFreq\n self.unitDose = unitDose\n self.doseForm = doseForm\n self.notes = notes\n\n# End of: prescription.py","sub_path":"tmst_skeleton_proj/package/prescription.py","file_name":"prescription.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"383520454","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport csv\nimport logging\nimport os\nimport re\nfrom moviepy.editor import *\nfrom pathlib import Path\nfrom typing import Optional, Union\nfrom zipfile import ZipFile\n\nimport cv2\nimport pandas as pd\n\nfrom tqdm import tqdm\nfrom tqdm.contrib.logging import logging_redirect_tqdm\n\nfrom .utils import draw_annotations\n\nlog = logging.getLogger(\"fer\")\n\n\nclass Video(object):\n def __init__(\n self,\n video_file: str,\n outdir: str = \"output\",\n first_face_only: bool = True,\n tempfile: Optional[str] = None,\n ):\n \"\"\"Video class for extracting and saving frames for emotion detection.\n :param video_file - str\n :param outdir - str\n :param tempdir - str\n :param first_face_only - bool\n :param tempfile - str\n \"\"\"\n assert os.path.exists(video_file), \"Video file not found at {}\".format(\n os.path.abspath(video_file)\n )\n self.cap = cv2.VideoCapture(video_file)\n if not os.path.isdir(outdir):\n os.makedirs(outdir, exist_ok=True)\n self.outdir = outdir\n\n if not first_face_only:\n log.error(\"Only single-face charting is implemented\")\n self.first_face_only = first_face_only\n self.tempfile = tempfile\n self.filepath = video_file\n self.filename = \"\".join(self.filepath.split(\"/\")[-1])\n\n @staticmethod\n def get_max_faces(data: list) -> int:\n \"\"\"Get max number of faces detected in a series of frames, eg 3\"\"\"\n max = 0\n for frame in data:\n for face in frame:\n if len(face) > max:\n max = len(face)\n return max\n\n @staticmethod\n def _to_dict(data: Union[dict, list]) -> dict:\n emotions = []\n\n frame = data[0]\n if isinstance(frame, list):\n try:\n emotions = frame[0][\"emotions\"].keys()\n except IndexError:\n raise Exception(\"No data in 'data'\")\n elif isinstance(frame, dict):\n return data\n\n dictlist = []\n\n for data_idx, frame in enumerate(data):\n rowdict = {}\n for idx, face in enumerate(list(frame)):\n if not isinstance(face, dict):\n break\n rowdict.update({\"box\" + str(idx): face[\"box\"]})\n rowdict.update(\n {emo + str(idx): face[\"emotions\"][emo] for emo in emotions}\n )\n dictlist.append(rowdict)\n return dictlist\n\n def to_pandas(self, data: Union[pd.DataFrame, list]) -> pd.DataFrame:\n \"\"\"Convert results to pandas DataFrame\"\"\"\n if isinstance(data, pd.DataFrame):\n return data\n\n if not len(data):\n return pd.DataFrame()\n datalist = self._to_dict(data)\n df = pd.DataFrame(datalist)\n if self.first_face_only:\n df = self.get_first_face(df)\n return df\n\n @staticmethod\n def get_first_face(df: pd.DataFrame) -> pd.DataFrame:\n assert isinstance(df, pd.DataFrame), \"Must be a pandas DataFrame\"\n try:\n int(df.columns[0][-1])\n except ValueError:\n # Already only one face in df\n return df\n\n columns = [x for x in df.columns if x[-1] == \"0\"]\n new_columns = [x[:-1] for x in columns]\n single_df = df[columns]\n single_df.columns = new_columns\n return single_df\n\n @staticmethod\n def get_emotions(df: pd.DataFrame) -> list:\n \"\"\"Get emotion columsn from results.\"\"\"\n columns = [x for x in df.columns if \"box\" not in x]\n return df[columns]\n\n def to_csv(self, data, filename=\"data.csv\"):\n \"\"\"Save data to csv\"\"\"\n\n def key(item):\n key_pat = re.compile(r\"^(\\D+)(\\d+)$\")\n m = key_pat.match(item)\n return m.group(1), int(m.group(2))\n\n dictlist = self._to_dict(data)\n columns = set().union(*(d.keys() for d in dictlist))\n columns = sorted(columns, key=key) # sort by trailing number (faces)\n\n with open(\"data.csv\", \"w\", newline=\"\") as csvfile:\n writer = csv.DictWriter(csvfile, columns, lineterminator=\"\\n\")\n writer.writeheader()\n writer.writerows(dictlist)\n return dictlist\n\n def _close_video(self, outfile, save_frames, zip_images):\n self.cap.release()\n if self.display or self.save_video:\n self.videowriter.release()\n\n if self.save_video:\n log.info(\"Completed analysis: saved to {}\".format(self.tempfile or outfile))\n if self.tempfile:\n os.replace(self.tempfile, outfile)\n\n if save_frames and zip_images:\n log.info(\"Starting to Zip\")\n outdir = Path(self.outdir)\n zip_dir = outdir / \"images.zip\"\n images = sorted(list(outdir.glob(\"*.jpg\")))\n total = len(images)\n i = 0\n with ZipFile(zip_dir, \"w\") as zip:\n for file in images:\n zip.write(file, arcname=file.name)\n os.remove(file)\n i += 1\n if i % 50 == 0:\n log.info(f\"Compressing: {i*100 // total}%\")\n log.info(\"Zip has finished\")\n\n def _offset_detection_box(self, faces, detection_box):\n for face in faces:\n original_box = face.get(\"box\")\n face[\"box\"] = (\n original_box[0] + detection_box.get(\"x_min\"),\n original_box[1] + detection_box.get(\"y_min\"),\n original_box[2],\n original_box[3],\n )\n return faces\n\n def _increment_frames(\n self, frame, faces, video_id, root, lang=\"en\", size_multiplier=1\n ):\n # Save images to `self.outdir`\n imgpath = os.path.join(\n self.outdir, (video_id or root) + str(self.frameCount) + \".jpg\"\n )\n\n if self.annotate_frames:\n frame = draw_annotations(\n frame,\n faces,\n boxes=True,\n scores=True,\n lang=lang,\n size_multiplier=size_multiplier,\n )\n\n if self.save_frames:\n cv2.imwrite(imgpath, frame)\n\n if self.display:\n cv2.imshow(\"Video\", frame)\n\n if self.save_video:\n self.videowriter.write(frame)\n\n self.frameCount += 1\n\n def analyze(\n self,\n detector, # fer.FER instance\n display: bool = False,\n output: str = \"csv\",\n frequency: Optional[int] = None,\n max_results: int = None,\n save_fps: Optional[int] = None,\n video_id: Optional[str] = None,\n save_frames: bool = True,\n save_video: bool = True,\n annotate_frames: bool = True,\n zip_images: bool = True,\n detection_box: Optional[dict] = None,\n lang: str = \"en\",\n include_audio: bool = False,\n size_multiplier: int = 1,\n ) -> list:\n \"\"\"Recognize facial expressions in video using `detector`.\n\n Args:\n\n detector (fer.FER): facial expression recognizer\n display (bool): show images with cv2.imshow\n output (str): csv or pandas\n frequency (int): inference on every nth frame (higher number is faster)\n max_results (int): number of frames to run inference before stopping\n save_fps (bool): inference frequency = video fps // save_fps\n video_id (str): filename for saving\n save_frames (bool): saves frames to directory\n save_video (bool): saves output video\n annotate_frames (bool): add emotion labels\n zip_images (bool): compress output\n detection_box (dict): dict with bounding box for subimage (xmin, xmax, ymin, ymax)\n lang (str): emotion language that will be shown on video\n include_audio (bool): indicates if a sounded version of the prediction video should be created or not\n size_multiplier (int): increases the size of emotion labels shown in the video by x(size_multiplier)\n Returns:\n\n data (list): list of results\n\n \"\"\"\n frames_emotions = []\n if frequency is None:\n frequency = 1\n else:\n frequency = int(frequency)\n\n self.display = display\n self.save_frames = save_frames\n self.save_video = save_video\n self.annotate_frames = annotate_frames\n\n results_nr = 0\n\n # Open video\n assert self.cap.open(self.filepath), \"Video capture not opening\"\n self.__emotions = detector._get_labels().items()\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n pos_frames = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n assert int(pos_frames) == 0, \"Video not at index 0\"\n\n self.frameCount = 0\n height, width = (\n int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n )\n\n fps = self.cap.get(cv2.CAP_PROP_FPS)\n length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n assert fps and length, \"File {} not loaded\".format(self.filepath)\n\n if save_fps is not None:\n frequency = fps // save_fps\n log.info(\"Saving every {} frames\".format(frequency))\n\n log.info(\n \"{:.2f} fps, {} frames, {:.2f} seconds\".format(fps, length, length / fps)\n )\n\n if self.save_frames:\n os.makedirs(self.outdir, exist_ok=True)\n log.info(f\"Making directories at {self.outdir}\")\n root, ext = os.path.splitext(os.path.basename(self.filepath))\n outfile = os.path.join(self.outdir, f\"{root}_output{ext}\")\n\n if save_video:\n self.videowriter = self._save_video(outfile, fps, width, height)\n\n with logging_redirect_tqdm():\n pbar = tqdm(total=length, unit=\"frames\")\n\n while self.cap.isOpened():\n ret, frame = self.cap.read()\n if not ret: # end of video\n break\n\n if frame is None:\n log.warn(\"Empty frame\")\n continue\n\n if self.frameCount % frequency != 0:\n self.frameCount += 1\n continue\n\n if detection_box is not None:\n frame = self._crop(frame, detection_box)\n\n # Get faces and detect emotions; coordinates are for unpadded frame\n try:\n faces = detector.detect_emotions(frame)\n except Exception as e:\n log.error(e)\n break\n\n # Offset detection_box to include padding\n if detection_box is not None:\n faces = self._offset_detection_box(faces, detection_box)\n\n self._increment_frames(frame, faces, video_id, root, lang, size_multiplier)\n\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n if faces:\n frames_emotions.append(faces)\n\n results_nr += 1\n if max_results and results_nr > max_results:\n break\n\n pbar.update(1)\n\n pbar.close()\n self._close_video(outfile, save_frames, zip_images)\n\n if include_audio:\n audio_suffix = \"_audio.\"\n my_audio = AudioFileClip(self.filepath)\n new_audioclip = CompositeAudioClip([my_audio])\n\n my_output_clip = VideoFileClip(outfile)\n my_output_clip.audio = new_audioclip\n my_output_clip.write_videofile(audio_suffix.join(outfile.rsplit(\".\", 1)))\n\n return self.to_format(frames_emotions, output)\n\n def to_format(self, data, format):\n \"\"\"Return data in format.\"\"\"\n methods_lookup = {\"csv\": self.to_csv, \"pandas\": self.to_pandas}\n return methods_lookup[format](data)\n\n def _save_video(self, outfile: str, fps: int, width: int, height: int):\n if os.path.isfile(outfile):\n os.remove(outfile)\n log.info(\"Deleted pre-existing {}\".format(outfile))\n if self.tempfile and os.path.isfile(self.tempfile):\n os.remove(self.tempfile)\n fourcc = cv2.VideoWriter_fourcc(\"m\", \"p\", \"4\", \"v\")\n videowriter = cv2.VideoWriter(\n self.tempfile or outfile, fourcc, fps, (width, height), True\n )\n return videowriter\n\n @staticmethod\n def _crop(frame, detection_box):\n crop_frame = frame[\n detection_box.get(\"y_min\") : detection_box.get(\"y_max\"),\n detection_box.get(\"x_min\") : detection_box.get(\"x_max\"),\n ]\n return crop_frame\n\n def __del__(self):\n cv2.destroyAllWindows()\n","sub_path":"src/fer/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":12702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"80680543","text":"\"\"\" Module for Ulmo analysis on VIIRS 2013\"\"\"\nimport os\nimport glob\nfrom h5py._hl import base\nimport numpy as np\nimport subprocess \nfrom pkg_resources import resource_filename\n\nimport pandas\nimport h5py\nfrom skimage.restoration import inpaint \n\nfrom sklearn.utils import shuffle\n\nfrom ulmo import io as ulmo_io\n\nfrom ulmo.ssl.my_util import Params, option_preprocess\nfrom ulmo.ssl import latents_extraction\n\nfrom functools import partial\nfrom concurrent.futures import ProcessPoolExecutor\nimport subprocess\nfrom tqdm import tqdm\n\nfrom IPython import embed\n\ndef ssl_test_eval_orig(debug=False, orig=False):\n model_path = './'\n model_name = \"last.pth\"\n # Load options\n opt_file = os.path.join(resource_filename('ulmo', 'runs'),\n 'SSL', 'First','experiments', \n 'base_modis_model', 'opts.json')\n opt = Params(opt_file)\n opt = option_preprocess(opt)\n base_file = 'test_orig.h5'\n \n # Load\n hf = h5py.File(base_file, 'r')\n modis_data = hf['train'][:]\n\n # Output\n model_path_title = os.path.join(model_path, model_name)\n model_name = model_name.split('.')[0]\n latents_path = 'orig_latents.h5'\n save_key = 'modis_latents'\n \n # Run\n latents_extraction.orig_latents_extract(opt, modis_data,\n model_path_title, \n latents_path, \n save_key)\n\ndef ssl_eval_2010(dataset, debug=False, orig=False):\n s3_model_path = 's3://modis-l2/modis_simclr_base_model/SimCLR_modis_resnet50_lr_0.05_decay_0.0001_bsz_64_temp_0.07_trial_0_cosine_warm/last.pth'\n ulmo_io.download_file_from_s3(os.path.basename(s3_model_path), s3_model_path)\n model_path = './'\n model_name = \"last.pth\"\n\n # Load options\n opt_file = os.path.join(resource_filename('ulmo', 'runs'),\n 'SSL', 'First','experiments', \n 'base_modis_model', 'opts.json')\n opt = Params(opt_file)\n opt = option_preprocess(opt)\n\n # Load the data\n print(\"Grabbing MODIS [if needed]\")\n if orig:\n modis_dataset_path = \"s3://modis-l2/PreProc/MODIS_2010_95clear_128x128_inpaintT_preproc_0.8valid.h5\"\n else:\n modis_dataset_path = \"s3://modis-l2/PreProc/MODIS_R2019_2010_95clear_128x128_preproc_std.h5\"\n base_file = os.path.basename(modis_dataset_path)\n if not os.path.isfile(base_file):\n ulmo_io.download_file_from_s3(base_file, modis_dataset_path)\n\n # Output\n model_path_title = os.path.join(model_path, model_name)\n model_name = model_name.split('.')[0]\n if orig:\n latents_path = f'MODIS_orig_2010_{dataset}_{model_name}.h5'\n else:\n latents_path = f'MODIS_2010_{dataset}_{model_name}.h5'\n save_key = 'modis_latents'\n \n # Run\n latents_extraction.model_latents_extract(opt, base_file, dataset,\n model_path_title, latents_path, \n save_key)\n # Push to s3 \n s3_outfile = 's3://modis-l2/modis_latents_simclr/'+latents_path\n ulmo_io.upload_file_to_s3(latents_path, s3_outfile)\n\n\n\ndef main(flg):\n if flg== 'all':\n flg= np.sum(np.array([2 ** ii for ii in range(25)]))\n else:\n flg= int(flg)\n\n # Evaluate the MODIS training data from 2010\n if flg & (2**0):\n ssl_eval_2010('train')\n\n # Evaluate the MODIS valid data from 2010\n if flg & (2**1):\n ssl_eval_2010('valid')\n\n # Evaluate the MODIS valid data from 2010\n if flg & (2**2):\n ssl_test_eval_orig()\n\n # Evaluate the MODIS training data from 2010\n if flg & (2**3):\n ssl_eval_2010('train', orig=True)\n\n\n# Command line execution\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) == 1:\n flg = 0\n #flg += 2 ** 0 # 1 -- MODIS 2010 training\n #flg += 2 ** 1 # 2 -- MODIS 2010 valid\n #flg += 2 ** 2 # 4 -- Debuggin\n flg += 2 ** 3 # 8 -- re-run orig\n else:\n flg = sys.argv[1]\n\n main(flg)","sub_path":"ulmo/runs/Nenya/MODIS/First/ssl_first.py","file_name":"ssl_first.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"256411662","text":"from typing import List\n\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n lens = len(digits)\n for i in range(1, lens + 1):\n tmp = digits[-i] + 1\n if tmp <= 9:\n digits[-i] = tmp\n return digits\n digits[-i] = 0\n if i == lens:\n digits.insert(0, 1)\n return digits\n","sub_path":"Week_01/0066plusOne.py","file_name":"0066plusOne.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"264441647","text":"#\n# zfcp.py - mainframe zfcp configuration install data\n#\n# Copyright (C) 2001, 2002, 2003, 2004 Red Hat, Inc. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n#\n# Author(s): Karsten Hopp <karsten@redhat.com>\n#\n\nimport string\nimport os\nfrom . import udev\nfrom . import util\nfrom .i18n import _\n\nimport logging\nlog = logging.getLogger(\"blivet\")\n\ndef loggedWriteLineToFile(fn, value):\n f = open(fn, \"w\")\n log.debug(\"echo %s > %s\", value, fn)\n f.write(\"%s\\n\" % (value))\n f.close()\n\nzfcpsysfs = \"/sys/bus/ccw/drivers/zfcp\"\nscsidevsysfs = \"/sys/bus/scsi/devices\"\nzfcpconf = \"/etc/zfcp.conf\"\n\nclass ZFCPDevice:\n \"\"\"\n .. warning::\n Since this is a singleton class, calling deepcopy() on the instance\n just returns ``self`` with no copy being created.\n \"\"\"\n\n def __init__(self, devnum, wwpn, fcplun):\n self.devnum = self.sanitizeDeviceInput(devnum)\n self.wwpn = self.sanitizeWWPNInput(wwpn)\n self.fcplun = self.sanitizeFCPLInput(fcplun)\n\n if not self.checkValidDevice(self.devnum):\n raise ValueError(_(\"You have not specified a device number or the number is invalid\"))\n if not self.checkValidWWPN(self.wwpn):\n raise ValueError(_(\"You have not specified a worldwide port name or the name is invalid.\"))\n if not self.checkValidFCPLun(self.fcplun):\n raise ValueError(_(\"You have not specified a FCP LUN or the number is invalid.\"))\n\n def __str__(self):\n return \"%s %s %s\" %(self.devnum, self.wwpn, self.fcplun)\n\n def sanitizeDeviceInput(self, dev):\n if dev is None or dev == \"\":\n return None\n dev = dev.lower()\n bus = dev[:string.rfind(dev, \".\") + 1]\n dev = dev[string.rfind(dev, \".\") + 1:]\n dev = \"0\" * (4 - len(dev)) + dev\n if not len(bus):\n return \"0.0.\" + dev\n else:\n return bus + dev\n\n def sanitizeWWPNInput(self, wwpn):\n if wwpn is None or wwpn == \"\":\n return None\n wwpn = wwpn.lower()\n if wwpn[:2] != \"0x\":\n return \"0x\" + wwpn\n return wwpn\n\n # ZFCP LUNs are usually entered as 16 bit, sysfs accepts only 64 bit\n # (#125632), expand with zeroes if necessary\n def sanitizeFCPLInput(self, lun):\n if lun is None or lun == \"\":\n return None\n lun = lun.lower()\n if lun[:2] == \"0x\":\n lun = lun[2:]\n lun = \"0x\" + \"0\" * (4 - len(lun)) + lun\n lun = lun + \"0\" * (16 - len(lun) + 2)\n return lun\n\n def _hextest(self, hexnum):\n try:\n int(hexnum, 16)\n return True\n except TypeError:\n return False\n\n def checkValidDevice(self, devnum):\n if devnum is None or devnum == \"\":\n return False\n if len(devnum) != 8: # p.e. 0.0.0600\n return False\n if devnum[0] not in string.digits or devnum[2] not in string.digits:\n return False\n if devnum[1] != \".\" or devnum[3] != \".\":\n return False\n return self._hextest(devnum[4:])\n\n def checkValid64BitHex(self, hexnum):\n if hexnum is None or hexnum == \"\":\n return False\n if len(hexnum) != 18:\n return False\n return self._hextest(hexnum)\n checkValidWWPN = checkValidFCPLun = checkValid64BitHex\n\n def onlineDevice(self):\n online = \"%s/%s/online\" %(zfcpsysfs, self.devnum)\n portadd = \"%s/%s/port_add\" %(zfcpsysfs, self.devnum)\n portdir = \"%s/%s/%s\" %(zfcpsysfs, self.devnum, self.wwpn)\n unitadd = \"%s/unit_add\" %(portdir)\n unitdir = \"%s/%s\" %(portdir, self.fcplun)\n failed = \"%s/failed\" %(unitdir)\n\n if not os.path.exists(online):\n log.info(\"Freeing zFCP device %s\", self.devnum)\n util.run_program([\"zfcp_cio_free\", \"-d\", self.devnum])\n\n if not os.path.exists(online):\n raise ValueError(_(\"zFCP device %s not found, not even in device ignore list.\") % \\\n (self.devnum,))\n\n try:\n f = open(online, \"r\")\n devonline = f.readline().strip()\n f.close()\n if devonline != \"1\":\n loggedWriteLineToFile(online, \"1\")\n except IOError as e:\n raise ValueError(_(\"Could not set zFCP device %(devnum)s \"\n \"online (%(e)s).\") \\\n % {'devnum': self.devnum, 'e': e})\n\n if not os.path.exists(portdir):\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n try:\n loggedWriteLineToFile(portadd, self.wwpn)\n udev.settle()\n except IOError as e:\n raise ValueError(_(\"Could not add WWPN %(wwpn)s to zFCP \"\n \"device %(devnum)s (%(e)s).\") \\\n % {'wwpn': self.wwpn,\n 'devnum': self.devnum,\n 'e': e})\n else:\n # newer zfcp sysfs interface with auto port scan\n raise ValueError(_(\"WWPN %(wwpn)s not found at zFCP device \"\n \"%(devnum)s.\") % {'wwpn': self.wwpn,\n 'devnum': self.devnum})\n else:\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n log.info(\"WWPN %(wwpn)s at zFCP device %(devnum)s already \"\n \"there.\", {'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n if not os.path.exists(unitdir):\n try:\n loggedWriteLineToFile(unitadd, self.fcplun)\n udev.settle()\n except IOError as e:\n raise ValueError(_(\"Could not add LUN %(fcplun)s to WWPN \"\n \"%(wwpn)s on zFCP device %(devnum)s \"\n \"(%(e)s).\") \\\n % {'fcplun': self.fcplun, 'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n else:\n raise ValueError(_(\"LUN %(fcplun)s at WWPN %(wwpn)s on zFCP \"\n \"device %(devnum)s already configured.\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n fail = \"0\"\n try:\n f = open(failed, \"r\")\n fail = f.readline().strip()\n f.close()\n except IOError as e:\n raise ValueError(_(\"Could not read failed attribute of LUN \"\n \"%(fcplun)s at WWPN %(wwpn)s on zFCP device \"\n \"%(devnum)s (%(e)s).\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum,\n 'e': e})\n if fail != \"0\":\n self.offlineDevice()\n raise ValueError(_(\"Failed LUN %(fcplun)s at WWPN %(wwpn)s on \"\n \"zFCP device %(devnum)s removed again.\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n return True\n\n def offlineSCSIDevice(self):\n f = open(\"/proc/scsi/scsi\", \"r\")\n lines = f.readlines()\n f.close()\n # alternatively iterate over /sys/bus/scsi/devices/*:0:*:*/\n\n for line in lines:\n if not line.startswith(\"Host\"):\n continue\n scsihost = string.split(line)\n host = scsihost[1]\n channel = \"0\"\n devid = scsihost[5]\n lun = scsihost[7]\n scsidev = \"%s:%s:%s:%s\" % (host[4:], channel, devid, lun)\n fcpsysfs = \"%s/%s\" % (scsidevsysfs, scsidev)\n scsidel = \"%s/%s/delete\" % (scsidevsysfs, scsidev)\n\n f = open(\"%s/hba_id\" %(fcpsysfs), \"r\")\n fcphbasysfs = f.readline().strip()\n f.close()\n f = open(\"%s/wwpn\" %(fcpsysfs), \"r\")\n fcpwwpnsysfs = f.readline().strip()\n f.close()\n f = open(\"%s/fcp_lun\" %(fcpsysfs), \"r\")\n fcplunsysfs = f.readline().strip()\n f.close()\n\n if fcphbasysfs == self.devnum \\\n and fcpwwpnsysfs == self.wwpn \\\n and fcplunsysfs == self.fcplun:\n loggedWriteLineToFile(scsidel, \"1\")\n udev.settle()\n return\n\n log.warn(\"no scsi device found to delete for zfcp %s %s %s\",\n self.devnum, self.wwpn, self.fcplun)\n\n def offlineDevice(self):\n offline = \"%s/%s/online\" %(zfcpsysfs, self.devnum)\n portadd = \"%s/%s/port_add\" %(zfcpsysfs, self.devnum)\n portremove = \"%s/%s/port_remove\" %(zfcpsysfs, self.devnum)\n unitremove = \"%s/%s/%s/unit_remove\" %(zfcpsysfs, self.devnum, self.wwpn)\n portdir = \"%s/%s/%s\" %(zfcpsysfs, self.devnum, self.wwpn)\n devdir = \"%s/%s\" %(zfcpsysfs, self.devnum)\n\n try:\n self.offlineSCSIDevice()\n except IOError as e:\n raise ValueError(_(\"Could not correctly delete SCSI device of \"\n \"zFCP %(devnum)s %(wwpn)s %(fcplun)s \"\n \"(%(e)s).\") \\\n % {'devnum': self.devnum, 'wwpn': self.wwpn,\n 'fcplun': self.fcplun, 'e': e})\n\n try:\n loggedWriteLineToFile(unitremove, self.fcplun)\n except IOError as e:\n raise ValueError(_(\"Could not remove LUN %(fcplun)s at WWPN \"\n \"%(wwpn)s on zFCP device %(devnum)s \"\n \"(%(e)s).\") \\\n % {'fcplun': self.fcplun, 'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n\n if os.path.exists(portadd):\n # only try to remove ports with older zfcp sysfs interface\n for lun in os.listdir(portdir):\n if lun.startswith(\"0x\") and \\\n os.path.isdir(os.path.join(portdir, lun)):\n log.info(\"Not removing WWPN %s at zFCP device %s since port still has other LUNs, e.g. %s.\",\n self.wwpn, self.devnum, lun)\n return True\n\n try:\n loggedWriteLineToFile(portremove, self.wwpn)\n except IOError as e:\n raise ValueError(_(\"Could not remove WWPN %(wwpn)s on zFCP \"\n \"device %(devnum)s (%(e)s).\") \\\n % {'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n for port in os.listdir(devdir):\n if port.startswith(\"0x\") and \\\n os.path.isdir(os.path.join(devdir, port)):\n log.info(\"Not setting zFCP device %s offline since it still has other ports, e.g. %s.\",\n self.devnum, port)\n return True\n else:\n # newer zfcp sysfs interface with auto port scan\n import glob\n luns = glob.glob(\"%s/0x????????????????/0x????????????????\"\n %(devdir,))\n if len(luns) != 0:\n log.info(\"Not setting zFCP device %s offline since it still has other LUNs, e.g. %s.\",\n self.devnum, luns[0])\n return True\n\n try:\n loggedWriteLineToFile(offline, \"0\")\n except IOError as e:\n raise ValueError(_(\"Could not set zFCP device %(devnum)s \"\n \"offline (%(e)s).\") \\\n % {'devnum': self.devnum, 'e': e})\n\n return True\n\nclass ZFCP:\n \"\"\" ZFCP utility class.\n\n This class will automatically online to ZFCP drives configured in\n /tmp/fcpconfig when the startup() method gets called. It can also be\n used to manually configure ZFCP devices through the addFCP() method.\n\n As this class needs to make sure that /tmp/fcpconfig configured\n drives are only onlined once and as it keeps a global list of all ZFCP\n devices it is implemented as a Singleton.\n \"\"\"\n\n def __init__(self):\n self.intf = None\n self.fcpdevs = set()\n self.hasReadConfig = False\n self.down = True\n\n # So that users can write zfcp() to get the singleton instance\n def __call__(self):\n return self\n\n def __deepcopy__(self, memo_dict):\n # pylint: disable=unused-argument\n return self\n\n def readConfig(self):\n try:\n f = open(zfcpconf, \"r\")\n except IOError:\n log.info(\"no %s; not configuring zfcp\", zfcpconf)\n return\n\n lines = [x.strip().lower() for x in f.readlines()]\n f.close()\n\n for line in lines:\n if line.startswith(\"#\") or line == '':\n continue\n\n fields = line.split()\n\n if len(fields) == 3:\n devnum = fields[0]\n wwpn = fields[1]\n fcplun = fields[2]\n elif len(fields) == 5:\n # support old syntax of:\n # devno scsiid wwpn scsilun fcplun\n devnum = fields[0]\n wwpn = fields[2]\n fcplun = fields[4]\n else:\n log.warn(\"Invalid line found in %s: %s\", zfcpconf, line)\n continue\n\n try:\n self.addFCP(devnum, wwpn, fcplun)\n except ValueError as e:\n if self.intf:\n self.intf.messageWindow(_(\"Error\"), str(e))\n else:\n log.warning(\"%s\", str(e))\n\n def addFCP(self, devnum, wwpn, fcplun):\n d = ZFCPDevice(devnum, wwpn, fcplun)\n if d.onlineDevice():\n self.fcpdevs.add(d)\n\n def shutdown(self):\n if self.down:\n return\n self.down = True\n if len(self.fcpdevs) == 0:\n return\n for d in self.fcpdevs:\n try:\n d.offlineDevice()\n except ValueError as e:\n log.warn(\"%s\", str(e))\n\n def startup(self):\n if not self.down:\n return\n self.down = False\n if not self.hasReadConfig:\n self.readConfig()\n self.hasReadConfig = True\n # readConfig calls addFCP which calls onlineDevice already\n return\n\n if len(self.fcpdevs) == 0:\n return\n for d in self.fcpdevs:\n try:\n d.onlineDevice()\n except ValueError as e:\n log.warn(\"%s\", str(e))\n\n def write(self, root, zfcpdevs):\n # make sure that any zfcp devices (not only those which were manually\n # added) used during installation are included in /etc/zfcp.conf\n if zfcpdevs:\n for d in zfcpdevs:\n dev = ZFCPDevice(d.hba_id, d.wwpn, d.fcp_lun)\n if dev not in self.fcpdevs:\n self.fcpdevs.add(dev)\n\n if not self.fcpdevs:\n return\n f = open(root + zfcpconf, \"w\")\n for d in self.fcpdevs:\n f.write(\"%s\\n\" %(d,))\n f.close()\n\n f = open(root + \"/etc/modprobe.conf\", \"a\")\n f.write(\"alias scsi_hostadapter zfcp\\n\")\n f.close()\n\n# Create ZFCP singleton\nZFCP = ZFCP()\n\n# vim:tw=78:ts=4:et:sw=4\n","sub_path":"python2.7/site-packages/blivet/zfcp.py","file_name":"zfcp.py","file_ext":"py","file_size_in_byte":16396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"221924467","text":"import os\nimport cv2 as cv\n\nfrom modules.utils.helpers import get_paths_of_files_from_path\n\nHR_IMAGES_FOLDER = r\"\"\nOUTPUT_FOLDER = r\"\"\nTARGET_SHAPE = (256, 256)\n\nassert os.path.exists(HR_IMAGES_FOLDER), \"Input folder doesnt exist\"\nif not os.path.exists(OUTPUT_FOLDER): os.makedirs(OUTPUT_FOLDER)\n\nhr_image_paths = get_paths_of_files_from_path(HR_IMAGES_FOLDER, only_files=True)\nassert len(hr_image_paths) > 0, \"High resulution image folder is empty\"\n\nfor idx, hr_image_path in enumerate(hr_image_paths):\n if not os.path.exists(hr_image_path):\n continue\n\n hr_image = cv.imread(hr_image_path)\n if hr_image is None:\n continue\n\n iter_over_y = int(hr_image.shape[0] / TARGET_SHAPE[1])\n iter_over_x = int(hr_image.shape[1] / TARGET_SHAPE[0])\n\n if iter_over_x == 0 and iter_over_y == 0:\n continue\n \n for y_idx in range(iter_over_y):\n for x_idx in range(iter_over_x):\n image_part = hr_image[y_idx * TARGET_SHAPE[1]:(y_idx + 1) * TARGET_SHAPE[1], x_idx * TARGET_SHAPE[0]:(x_idx + 1) * TARGET_SHAPE[0], :]\n cv.imwrite(os.path.join(OUTPUT_FOLDER, f\"{idx}_{(y_idx * TARGET_SHAPE[1]) + x_idx}.png\"), image_part)","sub_path":"parse_hr_image.py","file_name":"parse_hr_image.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"61183301","text":"import os\nimport sys\nimport unittest\nfrom unittest.mock import Mock, MagicMock, patch\nfrom argparse import Namespace\n\npkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa\nsys.path.insert(0, pkg_root) # noqa\n\nfrom ssds.cli import staging as staging_cli\n\n\nclass TestStagingCLI(unittest.TestCase):\n def test_upload(self):\n mock_staging = Mock()\n mock_staging.upload = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace(submission_id=\"foo\", name=\"bar\", path=\"asf\")\n staging_cli.upload(args)\n expected_path = os.path.abspath(os.path.normpath(args.path))\n mock_staging.upload.assert_called_with(expected_path, args.submission_id, args.name)\n\n def test_list(self):\n mock_staging = Mock()\n mock_staging.list = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace()\n staging_cli.list(args)\n mock_staging.list.assert_called()\n\n def test_list_submission(self):\n mock_staging = Mock()\n mock_staging.list_submission = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace(submission_id=\"foo\")\n staging_cli.list_submission(args)\n mock_staging.list_submission.assert_called_with(args.submission_id)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"154922002","text":"import urllib.request as ur\nimport matplotlib.pyplot as plt\n# import cStringIO\nimport requests\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nimport html_downloader\nimport html_parser\nimport url_manager\nimport html_outputer\nimport json\n\ndef learning1():\n request = ur.Request('https://blog.csdn.net/samsam2013/article/details/78492122')\n request.add_header(\"user-agent\", 'Mozilla/5.0')\n response = ur.urlopen(request)\n f = open('a.txt', 'w', encoding='utf-8')\n print(response.read().decode(), file=f)\n\n\ndef usebs():\n html_doc = \"\"\"\n <html><head><title>The Dormouse's story\n \n

    The Dormouse's story

    \n\n

    Once upon a time there were three little sisters; and their names were\n Elsie,\n Lacie and\n Tillie;\n and they lived at the bottom of a well.

    \n\n

    ...

    \n \"\"\"\n soup = BeautifulSoup(\n html_doc,\n 'html.parser'\n )\n print(soup.find_all())\n\n\nclass SpiderMain(object):\n def __init__(self):\n self.urls = url_manager.UrlManager()\n self.downloader = html_downloader.HtmlDownloader()\n self.parser = html_parser.HtmlParser()\n self.output = html_outputer.HtmlOutputer()\n\n def craw(self, root_url):\n count = 1\n self.urls.add_new_url(root_url)\n while self.urls.has_new_url():\n try:\n new_url = self.urls.get_new_urls()\n print(\"craw %d:%s\" % (count, new_url))\n html_cont = self.downloader.downloader(new_url)\n new_urls, new_data = self.parser.parse(new_url, html_cont)\n self.urls.add_new_urls(new_urls)\n self.output.collect_data(new_data)\n count += 1\n if count == 100:\n break\n except:\n print(\"craw failed\")\n self.output.output_html()\n\n\ndef spider_main():\n # 确定目标\n root_url = \"https://baike.baidu.com/item/Python/407313\"\n obj_spider = SpiderMain()\n obj_spider.craw(root_url)\n\n\ndef scu_main():\n check_url = \"http://zhjw.scu.edu.cn/j_spring_security_check\"\n yzm_url = 'http://zhjw.scu.edu.cn/img/captcha.jpg'\n headers = { # 请求头请求刷新验证码和发送post时需要使用\n 'Host': 'zhjw.scu.edu.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer': \"http://zhjw.scu.edu.cn/login\",\n 'Connection': 'keep-alive'\n }\n grade_headers = {\n 'Host': 'zhjw.scu.edu.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer': \"http://zhjw.scu.edu.cn/student/integratedQuery/scoreQuery/allTermScores/index\",\n 'Connection': 'keep-alive'\n }\n yzm, response = showpicture()\n data = {\n \"j_username\": \"2017141463014\",\n \"j_password\": \"121694\",\n \"j_captcha\": yzm\n }\n login_cookies = requests.utils.dict_from_cookiejar(response.cookies)\n resp = requests.post(check_url, headers=headers, cookies=login_cookies, data=data)\n # selectionBar = 125803405\n\n grade_cookies = {'selectionBar': '125803405'}\n grade_cookies.update((login_cookies))\n print(login_cookies, grade_cookies)\n grade_url = 'http://zhjw.scu.edu.cn/student/integratedQuery/scoreQuery/allTermScores/data'\n resp = requests.get(grade_url, cookies=grade_cookies, headers=headers)\n with open(\"grade.txt\",\"w\",encoding=\"utf-8\") as f:\n print(resp.text,file=f)\n\n # index_url=\"http://zhjw.scu.edu.cn/index.jsp\"\n # response=requests.get(index_url,headers=headers,cookies=requests.utils.dict_from_cookiejar(resp.cookies))\n # print(response)\n\ndef jsonto():\n f=open(\"grade.txt\",encoding='utf-8')\n grade=f.readline()\n f.close()\n print(type(grade))\n data=json.loads(grade) #转化为json对象\n grades=data['list']['records']\n for grade in grades:\n print(grade)\n\ndef showpicture():\n yzm_url = 'http://zhjw.scu.edu.cn/img/captcha.jpg'\n response = requests.get(yzm_url)\n with open(\"yzm.png\", \"wb\") as f:\n f.write(response.content)\n img = Image.open('yzm.png')\n plt.figure(\"yzm\")\n plt.imshow(img)\n plt.show()\n yzm = input(\"请输入验证码\")\n return (yzm, response)\n\n\nif __name__ == '__main__':\n jsonto()\n","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"311084530","text":"#!/usr/bin/python\n\nDEFAULT_PROFIT_COEFF = 0.8\nprofit_coeff = 0.0\nwhile profit_coeff == 0.0:\n user_input = input(\"Enter profit coeff (%): \")\n if len(user_input) == 0:\n print(\"Empty input. Use default coeff: {}%\".format(DEFAULT_PROFIT_COEFF))\n profit_coeff = DEFAULT_PROFIT_COEFF\n break\n try:\n profit_coeff = float(user_input.replace(\",\", \".\"))\n except Exception as e:\n print(\"Number expected. Try againg.\")\n \ninc_multy = 1 + profit_coeff / 100 \ndec_multy = 1 - profit_coeff / 100 \n\nwhile True:\n user_input = input(\"Enter price: \")\n deal_price = 0\n try:\n deal_price = float(user_input.replace(\",\", \".\"))\n except Exception as e:\n print(\"Float expected. Try again.\")\n continue\n print(\"100% = {}\".format(deal_price))\n print(\"{}% = {}\" .format(inc_multy * 100, deal_price * inc_multy))\n print(\"{}% = {}\" .format(dec_multy * 100, deal_price * dec_multy))\n","sub_path":"trade_helpers/profit_calcer.py","file_name":"profit_calcer.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"67320299","text":"# Copyright (c) 2021, NVIDIA CORPORATION. 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\nfrom argparse import ArgumentParser\n\nimport torch\nfrom pytorch_lightning import Trainer\n\nfrom nemo.collections.nlp.parts.nlp_overrides import NLPDDPPlugin, NLPSaveRestoreConnector\nfrom nemo.utils import logging, model_utils\nfrom nemo.utils.app_state import AppState\n\n\n\"\"\"\nUsage:\npython megatron_change_num_partitions.py \\\n --model_file=PATH_TO_SRC_FILE \\\n --target_file=PATH_TO_TGT_FILE \\\n --tensor_model_parallel_size=2 \\\n --target_tensor_model_parallel_size=1\n\"\"\"\n\n\ndef merge_partition(model, partitions, write_path=None):\n idx = 0\n for name, param in model.named_parameters():\n if param.shape == partitions[0][idx].shape:\n concated = partitions[0][idx].data\n elif param.shape[0] == partitions[0][idx].shape[0]:\n concated = torch.cat([partitions[i][idx].data for i in range(len(partitions))], dim=-1)\n else:\n concated = torch.cat([partitions[i][idx].data for i in range(len(partitions))], dim=0)\n if concated.shape != param.shape:\n logging.info(\n f\"Warning: Shape mismatch for parameter {name} required shape: {param.shape}, merged shape: {concated.shape}. Narrowing to match required size.\"\n )\n if concated.shape[1:] == param.shape[1:]:\n concated = torch.narrow(concated, 0, 0, param.shape[0])\n elif concated.shape[:-1] == param.shape[:-1]:\n concated = torch.narrow(concated, -1, 0, param.shape[-1])\n else:\n raise RuntimeError(\n f\"Can not handle parameter {name}, required shape: {param.shape}, merged shape: {concated.shape}.\"\n )\n param.data = concated\n idx += 1\n\n if write_path is not None:\n model.save_to(write_path)\n\n\ndef split_partition(model, partitions, tp_size, write_path=None):\n if len(partitions) != 1:\n raise ValueError(\n \"Can only split partitions of model with TP=1. For partitions of models with TP>1, merge first.\"\n )\n\n if tp_size < 1:\n raise ValueError(\"TP size must to be >= 1.\")\n\n app_state = AppState()\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n\n app_state.tensor_model_parallel_rank = tp_size - 1\n\n idx = 0\n splits = []\n for _, param in model.named_parameters():\n if param.shape == partitions[0][idx].shape:\n split = [partitions[0][idx].data] * tp_size\n elif param.shape[0] == partitions[0][idx].shape[0]:\n split = torch.split(partitions[0][idx].data, param.shape[-1], dim=-1)\n else:\n split = torch.split(partitions[0][idx].data, param.shape[0], dim=0)\n splits.append(split)\n idx += 1\n\n for i in range(tp_size - 1, -1, -1):\n app_state.tensor_model_parallel_rank = i\n\n idx = 0\n for name, param in model.named_parameters():\n split_val = splits[idx][i]\n\n if param.shape != split_val.shape:\n logging.info(\n f\"Warning: Shape mismatch for parameter {name} required shape: {param.shape}, split shape: {split_val.shape}. Padding to match required size.\"\n )\n\n if split_val.shape[1:] == param.shape[1:]:\n pad = [0, 0] * len(split_val.shape)\n pad[-1] = param.shape[0] - split_val.shape[0]\n split_val = torch.nn.functional.pad(split_val, pad, 'constant')\n elif split_val.shape[:-1] == param.shape[:-1]:\n pad = [0, param.shape[-1] - split_val.shape[-1]]\n split_val = torch.nn.functional.pad(split_val, pad, 'constant')\n else:\n raise RuntimeError(\n f\"Can not handle parameter {name}, required shape: {param.shape}, split shape: {split_val.shape}.\"\n )\n\n param.data = split_val\n idx += 1\n\n if write_path is not None:\n model.save_to(write_path)\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"--model_file\", type=str, required=True, help=\"Path to source .nemo file\")\n parser.add_argument(\"--target_file\", type=str, required=True, help=\"Path to write target .nemo file\")\n parser.add_argument(\"--tensor_model_parallel_size\", type=int, required=True, help=\"TP size of source model\")\n parser.add_argument(\"--target_tensor_model_parallel_size\", type=int, required=True, help=\"TP size of target model\")\n parser.add_argument(\n \"--model_class\",\n type=str,\n default=\"nemo.collections.nlp.models.language_modeling.megatron_gpt_model.MegatronGPTModel\",\n help=\"NeMo model class. This script should support all NeMo megatron models that use Tensor Parallel\",\n )\n parser.add_argument(\"--precision\", default=16, help=\"PyTorch Lightning Trainer precision flag\")\n\n args = parser.parse_args()\n\n precision = args.precision\n if args.precision in [\"32\", \"16\"]:\n precision = int(float(args.precision))\n tp_size = args.tensor_model_parallel_size\n tgt_tp_size = args.target_tensor_model_parallel_size\n cls = model_utils.import_class_by_path(args.model_class)\n\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n app_state = AppState()\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n\n if tp_size > 1:\n partitions = []\n for i in range(tp_size):\n app_state.tensor_model_parallel_rank = i\n model = cls.restore_from(restore_path=args.model_file, trainer=trainer, map_location=torch.device(\"cpu\"))\n params = [p for _, p in model.named_parameters()]\n partitions.append(params)\n # app_state is being updated incorrectly during restore\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = (\n app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n )\n\n model.cfg.tensor_model_parallel_size = 1\n app_state.model_parallel_size = 1\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n model = cls(model.cfg, trainer).to('cpu')\n model._save_restore_connector = NLPSaveRestoreConnector()\n\n if tgt_tp_size > 1:\n merge_partition(model, partitions)\n else:\n merge_partition(model, partitions, args.target_file)\n else:\n app_state.model_parallel_size = 1\n model = cls.restore_from(restore_path=args.model_file, trainer=trainer)\n\n if tgt_tp_size > 1:\n partitions = []\n params = [p for _, p in model.named_parameters()]\n partitions.append(params)\n\n model.cfg.tensor_model_parallel_size = tgt_tp_size\n app_state.model_parallel_size = tgt_tp_size\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n model = cls(model.cfg, trainer).to('cpu')\n model._save_restore_connector = NLPSaveRestoreConnector()\n\n split_partition(model, partitions, tgt_tp_size, args.target_file)\n\n logging.info(\"Successfully finished changing partitions!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/nlp/language_modeling/megatron_change_num_partitions.py","file_name":"megatron_change_num_partitions.py","file_ext":"py","file_size_in_byte":8419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68481677","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy as sp\r\nfrom numpy import random as ran\r\n\r\n\r\n'''\r\n# -*- coding: utf-8 -*-\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom itertools import product, combinations\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.set_aspect(\"equal\")\r\n\r\n#draw cube\r\nr = [-1, 1]\r\nfor s, e in combinations(np.array(list(product(r,r,r))), 2):\r\n if np.sum(np.abs(s-e)) == r[1]-r[0]:\r\n ax.plot3D(*zip(s,e), color=\"b\")\r\n\r\n#draw sphere\r\nu, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\r\nx=np.cos(u)*np.sin(v)\r\ny=np.sin(u)*np.sin(v)\r\nz=np.cos(v)\r\nax.plot_wireframe(x, y, z, color=\"r\")\r\n\r\n#draw a point\r\nax.scatter([0],[0],[0],color=\"g\",s=100)\r\n\r\n#draw a vector\r\nfrom matplotlib.patches import FancyArrowPatch\r\nfrom mpl_toolkits.mplot3d import proj3d\r\n\r\nclass Arrow3D(FancyArrowPatch):\r\n def __init__(self, xs, ys, zs, *args, **kwargs):\r\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\r\n self._verts3d = xs, ys, zs\r\n\r\n def draw(self, renderer):\r\n xs3d, ys3d, zs3d = self._verts3d\r\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\r\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\r\n FancyArrowPatch.draw(self, renderer)\r\n\r\na = Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\r\nax.add_artist(a)\r\nplt.show()\r\n\r\n'''\r\n\r\n\r\n#--------------------\r\n#tau_scatter\r\n#Returns the possible optical depth to the next scattering depth\r\n#INPUT: none\r\n#Returns: tau_s\r\ndef tau_scatter():\r\n p = ran.uniform(0,1)\r\n tau_s = -np.log(p)\r\n return tau_s\r\n\r\n#-------------------\r\n#phi-to-xy\r\n#Returns xy coordinates based on given angle\r\n#NOTE: add to prev xyz value to get new position\r\n#INPUT:\r\n# distance: path length xi of the ray\r\n# phi: the angle at whish the ray is cast\r\n#Returns:\r\n# x,y: xy values corresponding to the change in position\r\ndef sphtocart(dist,phi,theta):\r\n\r\n x = dist*np.sin(phi)*np.cos(theta)\r\n y = dist*np.sin(phi)*np.sin(theta)\r\n z = dist*np.cos(phi)\r\n return x,y,z\r\n\r\n#----------------\r\n#rantheta\r\n#Return a randomly calculated theta value from equ A5\r\n#INPUT:\r\n# g: set initially, the asymmetry\r\n#OUTPUT:\r\n# theta: The random theta value\r\ndef rantheta(g):\r\n p = ran.uniform(0,1)\r\n term1 = 1.+g**2\r\n term2 = 1.-g**2\r\n term3 = 1. - g + 2*g*p\r\n\r\n theta = (term1 - (term2/term3)**2)/(2.*g)\r\n\r\n return theta\r\n\r\n\r\n#------------------\r\n#ranphi\r\n#Return a randomly selected phi value\r\n#INPUT: None\r\n#Output:\r\n# phi\r\ndef ranphi():\r\n p = ran.uniform(0,1)\r\n phi = 2.*np.pi*p\r\n\r\n return phi\r\n\r\n\r\n\r\n\r\n#--------------\r\n#ifexit\r\n#Returns a boolean indicating if you've left the sphere of caring\r\n#May change to vector inputs later\r\n#INPUT:\r\n# initial coordinates and max R\r\n#OUTPUT:\r\n# boolean indicating if at or beyond max radius\r\ndef ifexit(x0,y0,z0,x,y,z,R):\r\n return np.sqrt((x-x0)**2 + (y-y0)**2 + (z-z0)**2) >= R\r\n\r\n\r\n\r\n\r\n#---------------\r\n\r\n\r\n\r\n\r\n'''\r\nPlotting functions\r\n'''\r\n#---------------------\r\n#drawArrow\r\n# Draws an arrow representing the path and direction between 2 points\r\n#input A,B, axis\r\n# A,B: 2 points with the form [x,y] coordinates\r\n# axis: the axis that you want to draw said arrow on\r\n#returns: none\r\ndef drawArrow(A, B, axis):\r\n axis.arrow(A[0], A[1], B[0] - A[0], B[1] - A[1],\r\n head_width=0.02, length_includes_head=True)\r\n return\r\n\r\n#---------------------\r\n#drawAllArrows\r\n#Draws all the arrows of the path\r\n#input: X,Y,axis\r\n# X,Y: 1-D Arrays of same size, containing series of x,y coordinates with matching indices\r\n# axis: axis you want these drawn on\r\n#returns: none\r\ndef drawAllArrows(X,Y,axis):\r\n for i in xrange(len(X)-1):\r\n A = np.array([X[i],Y[i]])\r\n B = np.array([X[i+1],Y[i+1]])\r\n drawArrow(A,B,axis)\r\n return\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nPseudocode steps\r\n1) Get initial point position and cloud info\r\n2) generate tau of ray\r\n3) Sample xi (path length) from tau\r\n4) Calculate new angle of scatter\r\n5) calculate new position and advance the ray\r\n6) repeat 2-5 until ray reaches cloud boundary ( num trajectories=N)\r\n7) repeat 2-6 for M rays\r\n8) Calculate mean relative intensity at A(initial point)\r\n\r\nA : Observor placement point (const)\r\nkhat: Direction of ray - uniformly distributed over 4pi sr\r\nN: Number of directions\r\nM: Number of samplings of each direction\r\n\r\nmay need to plot only flattened data (xy only)\r\nfor impressiveness, plot in 3d\r\n\r\n\r\nHow to:\r\nwalk a ray\r\nreject if tau isn't close to wanted tau\r\nrepeat until until it reaches the edge of the sphere\r\nsum up all tau values along the rays\r\nrepeat for N/M rays\r\nSum up and average all intensities\r\n?\r\n'''\r\n\r\n#-------------\r\n#init\r\n#Initializes all initial values\r\n#returns:\r\n# A : Point of observer\r\n# M : Samplings/direction\r\n# N : Number of directions\r\n# I0: Initial intensity of ray\r\n# R : Radius of circle from origin from A\r\n# w : Albedo of the gas, mathis\r\n# g : asymmetry parameter, mathis\r\n# nH: number density of the medium, mathis, UNKNOWN\r\n#\r\ndef init():\r\n Ax = 0.0\r\n Ay = 0.0\r\n Az = 0.0\r\n A = np.array([Ax,Ay,Az])\r\n M = 10\r\n N = 90\r\n I0 = 5.0E6\r\n R = 2.\r\n w = 0.8\r\n g = 0.8\r\n nH = 10**2.5\r\n sigma = .3326E-24 # cm\r\n\r\n\r\n return A,M,N,I0,R,w,g,nH,sigma\r\n\r\ndef main():\r\n\r\n A,M,N,I0,R,w,g,nH,sigma = init()\r\n ran.seed(0000)\r\n\r\n #Generate testing points\r\n X = np.zeros(20)\r\n Y = np.zeros(20)\r\n Z = np.zeros(20)\r\n for i in xrange(20): # note: should start at point 0,0,0/origin\r\n theta = rantheta(g)\r\n phi = ranphi()\r\n X[i],Y[i],Z[i] = sphtocart(2,phi,theta)\r\n #Plotting the final points\r\n fig1 = plt.figure(1)\r\n ax1 = fig1.add_subplot(111)\r\n\r\n circle = plt.Circle(A, R, color='r', fill=False)\r\n ax1.add_artist(circle)\r\n\r\n ax1.scatter(X[0],Y[0],s=80,c='b',marker='*') #Colors\r\n ax1.plot(X[1:],Y[1:],'r.')\r\n drawAllArrows(X,Y,ax1)\r\n\r\n plt.show()\r\n\r\n\r\nmain()\r\n","sub_path":"radtrans.py","file_name":"radtrans.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"174855344","text":"from unittest import TestCase\nfrom unittest.mock import patch\n\nfrom opwen_email_server.backend import client_datastore\n\n\nclass UnpackEmailsTests(TestCase):\n @patch.object(client_datastore, 'STORAGE')\n def test_retrieves_compressed_emails(self, storage_mock):\n resource_id = 'c08ddf62-b27c-4de1-ab6f-474d75dc0bfd'\n self.given_objects(storage_mock, (\n {'to': ['foo@test.com']},\n {'to': ['bar@test.com']},\n ))\n\n emails = list(client_datastore.unpack_emails(resource_id))\n\n self.assertEqual(storage_mock.fetch_objects.call_count, 1)\n self.assertListEqual(emails, [{'to': ['foo@test.com']},\n {'to': ['bar@test.com']}])\n\n @classmethod\n def given_objects(cls, storage_mock, objs):\n storage_mock.fetch_objects.return_value = objs\n","sub_path":"tests/opwen_email_server/backend/test_client_datastore.py","file_name":"test_client_datastore.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"646156936","text":"######################################################################################################################\r\n# Script to extract random fragments of coding regions.\r\n##########\r\n# Input:\r\n# 1. seqSize: Size of the extracted sequences. Eg. 80.\r\n# 2. quantSeq: How many sequences to extract. Eg. 836.\r\n# 3. inputFileName: A fasta file containing the coding regions.\r\n# 4. outputLocation: Location in which outputs will be writen.\r\n##########\r\n# Output:\r\n# 1. cod2.csv: The csv file containing the extracted sequences.\r\n#####################################################################################################################\r\n\r\nimport sys\r\nimport random\r\n\r\n# Reading input\r\nseqSize = int(sys.argv[1])\r\nquantSeq = int(sys.argv[2])\r\ninputFileName = sys.argv[3]\r\noutputLocation = sys.argv[4]\r\nif(outputLocation[-1] != \"/\"): outputLocation += \"/\"\r\n\r\n# File handling\r\ninputFile = open(inputFileName,\"r\")\r\noutputFile = open(outputLocation+\"cod2.csv\",\"w\")\r\n\r\n# Extracting coding regions\r\ncodingList = []\r\ncodingSeq = \"\"\r\nflagFirst = True\r\nfor line in inputFile:\r\n if(len(line) < 2): continue\r\n if(line[0] == \">\"):\r\n if(flagFirst):\r\n flagFirst = False\r\n continue\r\n codingList.append(codingSeq)\r\n codingSeq = \"\"\r\n else: codingSeq += line.strip()\r\ncodingList.append(codingSeq)\r\n\r\n# Writing coding sequences\r\nseqCount = 0\r\nwhile(seqCount < quantSeq):\r\n rSeq = random.randint(0,len(codingList)-1)\r\n seq = codingList[rSeq]\r\n if(len(seq) < seqSize): continue\r\n rPos = random.randint(0,len(seq)-seqSize)\r\n seq = (seq[rPos:rPos+seqSize]).lower()\r\n outputFile.write(seq[0])\r\n for e in seq[1:]: outputFile.write(\",\"+e)\r\n outputFile.write(\"\\n\")\r\n seqCount += 1\r\n\r\n# Termination\r\ninputFile.close()\r\noutputFile.close()\r\n\r\n","sub_path":"Code/DataFormat/extractNegativeCoding2.py","file_name":"extractNegativeCoding2.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"50365251","text":"from numpy import exp, array\n\ndef out_flow(f):\n n = f.shape[0]\n a = []\n for i in range(n):\n s = 0.0\n for j in range(n):\n if i != j:\n s+= f[i, j]\n a.append(s)\n r = array(a) / (n - 1)\n return r\n\n\ndef in_flow(f):\n n = f.shape[0]\n a = []\n for i in range(n):\n s = 0.0\n for j in range(n):\n if i != j:\n s+= f[j, i]\n a.append(s)\n r = array(a) / (n - 1)\n return r\n \n\ndef usual_shape(q, p, _, f):\n return int(f > 0)\n\n\ndef level_shape(q, p, _, f):\n if f < 0: return 0\n if f < q:\n return 0.0\n if f > p:\n return 1.0\n return 0.5\n\n\ndef linear_shape(q, p, _, f):\n \"\"\"\n if f < 0: return 0\n if f > p:\n return 1.0\n if f < q:\n return 0.0\n r = (f - q) / (p - q)\n assert(r >= 0 and r <= 1)\n \"\"\"\n r = min(f - q, p - q) / (p - q) * int(f > q)\n assert(r >= 0 and r <= 1)\n return r\n\n\ndef u_shape(q, p, _, f):\n if f < 0: return 0\n if f < p:\n return 0.0\n return 1.0\n\n\ndef v_shape(q, p, _, f):\n if f < 0: return 0\n if f <= p:\n r = f / p\n assert(r >= 0 and r <= 1)\n return r\n else:\n return 1.0\n\n\ndef gaussian(q, p, s, f):\n if f < 0: return 0\n return 1 - exp(-(f**2) / (2*(s**2)))\n\n","sub_path":"smpr/multicriteriality.py","file_name":"multicriteriality.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"616022254","text":"#!/usr/bin/python\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn import preprocessing\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport sys, getopt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndef main(argv):\r\n inputfile = ''\r\n outputfile = ''\r\n if(len(argv)==0):\r\n print ('preprocess.py -i -o ')\r\n sys.exit(2)\r\n try:\r\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\r\n except getopt.GetoptError:\r\n print ('preprocess.py -i -o ')\r\n sys.exit(2)\r\n for opt, arg in opts:\r\n if opt == '-h':\r\n print ('preprocess.py -i -o ')\r\n sys.exit()\r\n elif opt in (\"-i\", \"--ifile\"):\r\n inputfile = arg\r\n elif opt in (\"-o\", \"--ofile\"):\r\n outputfile = arg\r\n print ('Input file is \"', inputfile)\r\n print ('Output file is \"', outputfile)\r\n\r\n dataset = pd.read_csv(inputfile, header=None)\r\n le = preprocessing.LabelEncoder()\r\n\r\n dataset = dataset.apply(le.fit_transform)\r\n array = dataset.values\r\n\r\n X = array[:, 0:dataset.shape[1] - 1]\r\n Y = array[:, dataset.shape[1] - 1]\r\n\r\n scaler = MinMaxScaler(feature_range=(0, 1))\r\n rescaledY = scaler.fit_transform(Y)\r\n\r\n scaler = StandardScaler().fit(X)\r\n rescaledX = scaler.transform(X)\r\n\r\n output = pd.DataFrame(rescaledX)\r\n output['output'] = rescaledY.tolist()\r\n output.to_csv(outputfile, index=False, header=False)\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])","sub_path":"Programming Assignment - Variation of Most Appropriate Yard/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471534291","text":"import random\nfrom plugin_system import Plugin\n\nanswers = ['🌚', '🌚🌚']\n\nplugin = Plugin('Луна')\n\n\n@plugin.on_command('луна', '🌚')\nasync def get_moon(msg, args):\n await msg.answer(random.choice(answers))\n","sub_path":"plugins/moon.py","file_name":"moon.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"405700253","text":"properties = (\"Название\", \"Цена\", \"Количество\", \"Ед.\")\nuser_answer, goods, a, analyse, num_counter = '', [], {}, {}, 1\nwhile True:\n if user_answer == \"n\":\n break\n for b in properties:\n a[b] = input(f'Ввеедите позицию товара {b} :')\n goods.append((num_counter, a))\n num_counter += 1\n user_answer = input(\"Хотите ли ввести еще один вид товаров? Y/N: \")\nprint(f'Текушие позиции товаров выглядят следующим образом:\\n')\nprint(goods)\n\nfor b in goods:\n for k, v in b[1].items():\n analyse.setdefault(k, []).append(v)\n\nprint(f'Позиции товаров по характеристикам:\\n')\nprint(analyse)\n","sub_path":"lesson_2/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"246917001","text":"import json\nimport socketserver\nimport os\n\nfrom FTP.server.conf import settings\nfrom FTP.server.core import views\n\n\nclass MyFTPServer(socketserver.BaseRequestHandler):\n\n\tlogined_lst = {}\n\n\tdef handle(self):\n\t\tprint('-' * 20)\n\t\tglobal pickle_path, ret\n\t\tmsg = self.my_recv() # 调用派生方法\n\t\tprint('已经登录的用户logined_lst') # 记录已经登录的用户\n\t\tprint(MyFTPServer.logined_lst)\n\t\t# 消息的转发 把任务转发给views文件中的对应的方法\n\t\t# 反射\n\t\top_str = msg['operation'] # 获取操作 auth_client\n\t\tif msg['operation'] == 'login' or msg['operation'] == 'register':\n\t\t\tif hasattr(views, op_str):\n\t\t\t\tfunc = getattr(views, op_str)\n\t\t\t\tret = func(msg)\n\t\t\tif ret:\n\t\t\t\t# 用户的pickle信息所在的文件地址 views\n\t\t\t\tMyFTPServer.logined_lst[self.client_address] = os.path.join(settings.pickle_path, msg['username'])\n\t\t\t\tself.my_send(ret)\n\t\telif hasattr(views, op_str) and self.client_address in MyFTPServer.logined_lst:\n\t\t\tfunc = getattr(views, op_str)\n\t\t\tret = func(msg, self.request)\n\t\t\tself.my_send(ret)\n\t\telse:\n\t\t\tself.my_send(False)\n\n\t# {'username','password','operation'}\n\t# msg\n\t# 登录 注册\n\t# 查看目录\n\n\t# 上传文件\n\t# 反射\n\t# 'login'\n\tdef my_recv(self): # 派生方法\n\t\tmsg = self.request.recv(1024)\n\t\tmsg = msg.decode(settings.code)\n\t\t# print('my_recv:\\n'+msg, type(msg))\n\t\tmsg = json.loads(msg)\n\t\treturn msg\n\n\tdef my_send(self, msg):\n\t\tmsg = json.dumps(msg).encode(settings.code)\n\t\tself.request.send(msg)\n","sub_path":"FTP/server/core/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"549705214","text":"import os\n\nimport pytest\n\nfrom robocorp_ls_core.protocols import IConfigProvider\nfrom robocorp_ls_core.robotframework_log import get_logger\nfrom robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture\nfrom robocorp_code.protocols import IRcc\n\n\nlog = get_logger(__name__)\n\n\n@pytest.fixture\ndef language_server_client_class():\n from robocorp_code_tests.robocode_language_server_client import (\n RobocorpLanguageServerClient,\n )\n\n return RobocorpLanguageServerClient\n\n\n@pytest.fixture\ndef language_server_class():\n from robocorp_code.robocorp_language_server import RobocorpLanguageServer\n\n return RobocorpLanguageServer\n\n\n@pytest.fixture\ndef main_module():\n from robocorp_code import __main__\n\n return __main__\n\n\n@pytest.fixture\ndef rcc_location() -> str:\n from robocorp_code.rcc import download_rcc\n from robocorp_code.rcc import get_default_rcc_location\n\n location = get_default_rcc_location()\n download_rcc(location, force=False)\n return location\n\n\n@pytest.fixture\ndef ci_endpoint() -> str:\n ci_endpoint = os.environ.get(\"CI_ENDPOINT\")\n if ci_endpoint is None:\n raise AssertionError(\"CI_ENDPOINT env variable must be specified for tests.\")\n return ci_endpoint\n\n\n@pytest.fixture\ndef ci_credentials() -> str:\n ci_credentials = os.environ.get(\"CI_CREDENTIALS\")\n if ci_credentials is None:\n raise AssertionError(\"ci_credentials env variable must be specified for tests.\")\n return ci_credentials\n\n\n@pytest.fixture\ndef rcc_config_location(tmpdir) -> str:\n config_dir = tmpdir.join(\"config\")\n os.makedirs(str(config_dir))\n return str(config_dir.join(\"config_test.yaml\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef cases(tmpdir_factory) -> CasesFixture:\n basename = \"res áéíóú\"\n copy_to = str(tmpdir_factory.mktemp(basename))\n\n f = __file__\n original_resources_dir = os.path.join(os.path.dirname(f), \"_resources\")\n assert os.path.exists(original_resources_dir)\n\n return CasesFixture(copy_to, original_resources_dir)\n\n\n@pytest.fixture\ndef config_provider(\n ws_root_path: str, rcc_location: str, ci_endpoint: str, rcc_config_location: str\n):\n from robocorp_code.robocorp_config import RobocorpConfig\n from robotframework_ls.ep_providers import DefaultConfigurationProvider\n\n config = RobocorpConfig()\n\n config.update(\n {\n \"robocorp\": {\n \"rcc\": {\n \"location\": rcc_location,\n \"endpoint\": ci_endpoint,\n \"config_location\": rcc_config_location,\n }\n }\n }\n )\n return DefaultConfigurationProvider(config)\n\n\n@pytest.fixture\ndef rcc(config_provider: IConfigProvider, rcc_config_location: str) -> IRcc:\n from robocorp_code.rcc import Rcc\n\n rcc = Rcc(config_provider)\n # We don't want to track tests.\n for _i in range(2):\n # There's a bug in which the --do-not-track doesn't work the first time.\n result = rcc._run_rcc(\n \"feedback identity --do-not-track --config\".split() + [rcc_config_location],\n expect_ok=False,\n )\n assert result.success\n result_msg = result.result\n assert result_msg\n if \"enabled\" in result_msg:\n continue\n if \"disabled\" in result_msg:\n break\n raise AssertionError(f\"Did not expect {result_msg}\")\n else:\n raise AssertionError(f\"Did not expect {result_msg}\")\n\n return rcc\n\n\n@pytest.fixture\ndef rcc_conda_installed(rcc: IRcc):\n result = rcc.check_conda_installed()\n assert result.success, r\"Error: {result}\"\n","sub_path":"robocorp-code/tests/robocorp_code_tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"306832342","text":"import MySQLdb\nimport smtplib, ssl\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom home.mysql import mysqldb\n\ndef mail_seder(receiver_email, user, event, date, place, flag):\n sender_email = \"treeasurenss@gmail.com\"\n password = 'treeasure@nss123'\n message = MIMEMultipart(\"alternative\")\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n # Create the plain-text and HTML version of your message\n if flag == 1:\n message[\"Subject\"] = \"Nature is calling you........\"\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n We have a new event organized on \"\"\" + date + \"\"\".\n The name of the event is \"\"\" + event + \"\"\" organized at location \"\"\" + place + \"\"\".\n Do visit our website to participate.\n \"\"\"\n html = \"\"\"\\\n \n \n

    Hello \"\"\" + user + \"\"\",
    \n We have a new event organized on \"\"\" + date + \"\"\".\n The name of the event is \"\"\" + event + \"\"\" organized at location \"\"\" + place + \"\"\".\n Do visit our website to participate.\n

    \n \n \n \"\"\"\n elif flag==0:\n message[\"Subject\"] = \"Nature is calling you........\"\n mydb = mysqldb()\n mycursor = mydb.cursor()\n query = 'select info from schedule_tt where event_name=\"'+event+'\"'\n mycursor.execute(query)\n result = mycursor.fetchall()\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n You are sucessfully registered to the event \"\"\" + event + \"\"\"\n Details\n Date: \"\"\" + date + \"\"\"\n Place: \"\"\" + place + \"\"\"\n Information: \"\"\" + result[0][0] +\"\"\"\n Do visit our website to participate.\n \"\"\"\n html = \"\"\"\\\n \n \n

    Hello \"\"\" + user + \"\"\",
    \n You are sucessfully registered to the event \"\"\" + event + \"\"\"
    \n Details
    \n Date: \"\"\" + date + \"\"\"
    \n Place: \"\"\" + place + \"\"\"
    \n Information: \"\"\" + result[0][0] +\"\"\"
    \n Do visit our website to participate.\n

    \n \n \n \"\"\"\n elif flag == 3:\n message[\"Subject\"] = \"We are disappointed\"\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n You have been reported.\n \"\"\"\n html = \"\"\"\\\n \n \n

    Hello \"\"\" + user + \"\"\",
    \n You have been reported\n

    \n \n \n \"\"\"\n\n # Turn these into plain/html MIMEText objects\n part1 = MIMEText(text, \"plain\")\n part2 = MIMEText(html, \"html\")\n\n # Add HTML/plain-text parts to MIMEMultipart message\n # The email client will try to render the last part first\n message.attach(part1)\n message.attach(part2)\n\n # Create secure connection with server and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(\n sender_email, receiver_email, message.as_string()\n )\n\n\ndef send_email(username, event, date, place, flag):\n mydb = mysqldb()\n mycursor = mydb.cursor()\n print(username)\n if flag == 0:\n query = 'select email, username from auth_user where username=\"'+username+'\"'\n else:\n query = 'select email, username from auth_user where not username=\"'+username+'\"'\n mycursor.execute(query)\n result = mycursor.fetchall()\n for i in result:\n print(i[0], i[1])\n mail_seder(i[0], i[1], event, date, place, flag)","sub_path":"maps/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68818709","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport copy\nimport cmath\nfrom user_manage.models import CollectRaw\n\n\ndef polar_to_cartesian(angle_values, rs):\n \"\"\"将极坐标转换为直角坐标\n :param angle_values: 原始角度值\n :param rs: 原始距离值\n :return: xs, ys 转换之后的直角坐标系的x,y坐标\n \"\"\"\n xs, ys = [], []\n for angle_value, r in zip(angle_values, rs):\n cn = cmath.rect(r, np.radians(angle_value))\n # print(cn.real, cn.imag)\n xs.append(round(cn.real, 3))\n ys.append(round(cn.imag, 3))\n\n return xs, ys\n\ndef cartesian_to_polar(xs, ys):\n # 将直角坐标转换为极坐标\n thetas = []\n rs = []\n\n for x, y in zip(xs, ys):\n cp = complex(x, y)\n result = cmath.polar(cp) # 返回长度和弧度\n dgs = math.degrees(result[1])\n if dgs < 0:\n dgs += 360\n thetas.append(dgs)\n rs.append(result[0])\n return thetas, rs\n\n\n\ndef find_symmetry_axis(angle_values, range_values, pt1, pt2, pt3, pt4, type=0):\n \"\"\"\n\n @param angle_values:\n @param range_values:\n @param area1_x_range:\n @param area1_y_range:\n @param area2_x_range:\n @param area2_y_range:\n @return:\n \"\"\"\n assert angle_values, '轮廓数据为空'\n assert pt1, '数据为空'\n assert pt2, '数据为空'\n assert pt3, '数据为空'\n assert pt4, '数据为空'\n\n area1_x_range = [min(pt1[0], pt2[0]), max(pt1[0], pt2[0])]\n area1_y_range = [min(pt1[1], pt2[1]), max(pt1[1], pt2[1])]\n\n area2_x_range = [min(pt3[0], pt4[0]), max(pt3[0], pt4[0])]\n area2_y_range = [min(pt3[1], pt4[1]), max(pt3[1], pt4[1])]\n # TODO:使用极坐标系选择 对称区域,根据以前实验数据观察,使用此方案效果较差\n xs, ys = polar_to_cartesian(angle_values, range_values)\n\n # TODO:使用直角坐标系选择 对称区域\n area1_xs = []\n area1_ys = []\n area2_xs = []\n area2_ys = []\n for x, y in zip(xs, ys):\n if area1_x_range[0] < x < area1_x_range[1] and area1_y_range[0] < y < area1_y_range[1]:\n area1_xs.append(x)\n area1_ys.append(y)\n elif area2_x_range[0] < x < area2_x_range[1] and area2_y_range[0] < y < area2_y_range[1]:\n area2_xs.append(x)\n area2_ys.append(y)\n else:\n pass\n\n assert area1_xs, '选取对称区域内没有获取到测量数据'\n assert area2_xs, '选取对称区域内没有获取到测量数据'\n\n r_line = np.polyfit(area1_xs, area1_ys, 1)\n l_line = np.polyfit(area2_xs, area2_ys, 1)\n line_k = (r_line[0] + l_line[0]) / 2 # 因为两条线平行,故取任意一条线的斜率, 取和除以2是泛化数据,若两条线不平行,则不行\n c = (l_line[1] + r_line[1]) / 2\n if type == 0:\n # 原始用的对称轴\n symmetry_axis = [line_k, c]\n return symmetry_axis\n else:\n # 对称轴散点坐标\n lst_x, lst_y, ret_coord = [], [], []\n x_max = max(xs)\n x_min = min(xs)\n diff = float((x_max - x_min) / 100)\n for i in range(100):\n lst_x.append(x_min + i * diff)\n for a_x in lst_x:\n # 计算公式\n a_y = line_k * a_x + c\n lst_y.append(a_y)\n for x, y in zip(lst_x, lst_y):\n ret_coord.append([x, y])\n return ret_coord\n\n\ndef symmetry_axis_convert(angle_values, range_values, symmetry_axis, top_point):\n \"\"\"\n Cobb =int(math.fabs(np.arctan((k1-k2)/(float(1 + k1*k2)))*180/np.pi)+0.5)\n 一般的坐标转换公式.\n 设Oxy,O'x'y'是两个坐标系,O,O'分别是原点,且O'在Oxy中的坐标为(x0,y0),由x轴到x'轴的角度为t,坐标转换公式是\n x=x'cost-y'sint+x0, y=x'sint+y'cost+y0.\n\n @todo:x' = cost(x-x0) + y - y0; y' = math.pow(cost, 2)(x-x0) + cost(y-y0) - x + x0\n\n @param angle_values:\n @param range_values:\n @param symmetry_axis:\n @param top_point:\n @return:\n \"\"\"\n assert angle_values, '轮廓数据为空'\n assert symmetry_axis, '无对称轴'\n assert top_point, '没有顶点数据'\n\n # TODO:获取对称轴两侧指定宽度的测量区域\n xs, ys = polar_to_cartesian(angle_values, range_values)\n # 设Oxy,O'x'y'是两个坐标系,O,O'分别是原点,TODO:且O'在Oxy中的坐标为(x0,y0), 由x轴到x'轴的角度为t\n # 计算原来坐标系原点,在新的坐标系中的坐标\n # alpha = math.atan(top_point[1] / top_point[0])\n # theta = math.atan(symmetry_axis[0]) # TODO: 当theta>math.pi/2 时,是否成立还需要验证?\n # k1 = top_point[1] / top_point[0]\n # k2 = symmetry_axis[0]\n # fi = math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))))\n # cob = math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))) * 180 / np.pi) + 0.5\n # Cobb = int(math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))) * 180 / np.pi) + 0.5)\n\n # fi = math.pi / 2 - alpha + theta\n # fi = math.pi / 2 + alpha - theta\n theta = -math.atan(symmetry_axis[0])\n # chamfer = math.sqrt(top_point[0] ** 2 + top_point[1] ** 2)\n tx0 = -(top_point[0] * math.cos(theta) - top_point[1] * math.sin(theta))\n # tx0 = -chamfer * math.sin(fi)\n ty0 = -(top_point[0] * math.sin(theta) + top_point[1] * math.cos(theta))\n\n # if top_point[0] >= 0:\n # tx0 = -tx0\n # if top_point[1] >= 0:\n # ty0 = -ty0\n\n # TODO:可以使用坐标系转换办法,降低计算量, x=x'cost-y'sint+x0, y=x'sint+y'cost+y0.\n # TODO: 因不正常数据会赋值为0点,导致坐标系转换后出现较多的无用点!!!,在转换前将所有的0点去掉\n # 坐标系转换避免大量计算及很多斜率不存在时的分支判断\n\n conversion_xs = []\n conversion_ys = []\n for x, y in zip(xs, ys):\n if x == 0 and y == 0: # 去掉多余的零点\n continue\n # tx = -tx0 + x * math.cos(theta) - y * math.sin(theta)\n tx = tx0 + x * math.cos(theta) - y * math.sin(theta)\n\n # ty = -ty0 + x * math.sin(theta) + y * math.cos(theta)\n ty = ty0 + x * math.sin(theta) + y * math.cos(theta)\n\n conversion_xs.append(tx)\n conversion_ys.append(ty)\n\n return tx0, ty0, conversion_xs, conversion_ys\n\n\ndef get_measurement_loc(sedimentation_measuring_position, level_wid_measuring_position, device_location, tx0, ty0, t_xs, t_ys):\n \"\"\"\n sedimentation_measuring_position: 测量沉降位置\n level_wid_measuring_position:测量收敛位置\n device_location: 设备位置\n \"\"\"\n # TODO: 需要判断 设备在坐标系x轴的哪一侧(即中轴线的哪一侧), 后台从数据库中获取数据给我\n\n sedimentation_locs = [] # TODO:1.判断测量的具体位置,使用坐标数据如何表示\n if len(sedimentation_measuring_position) > 0:\n device_coordinate = [tx0, ty0]\n for sedimentation in sedimentation_measuring_position:\n if sedimentation[0] == '中': # 判断device_location 在中轴线的哪一侧\n # measuring_line = 0\n sedimentation_locs.append(0) # x轴\n\n elif device_location == '中': # ���般来说这种情况是不会发生的,设备的位置不方便维护, 若存在这种情况左右判断失效\n pass\n\n elif sedimentation[0] != '中' and device_location != '中': # 反向一侧\n if device_location == sedimentation[0]:\n if device_coordinate[0] < 0:\n sedimentation_locs.append(-sedimentation[1])\n else:\n sedimentation_locs.append(sedimentation[1])\n else: # 取反\n if device_coordinate[0] > 0:\n sedimentation_locs.append(-sedimentation[1])\n else:\n sedimentation_locs.append(sedimentation[1])\n\n level_locs = []\n if len(level_wid_measuring_position) > 0:\n # TODO: 获取拱顶往下x mm处收敛\n x_count = 0\n for x in t_xs:\n if x > 0:\n x_count += 1\n if x_count > len(t_xs) / 2:\n x_flag = 1\n else:\n x_flag = -1\n\n for lev_area in level_wid_measuring_position:\n if x_flag > 0:\n level_locs.append(lev_area)\n else:\n level_locs.append(-lev_area)\n\n return sedimentation_locs, level_locs\n\ndef calc_measure_range(sedimentation_areas, level_areas, t_xs, t_ys, area_width, symmetry_axis, top_point):\n \"\"\"计算测量的区段的角度范围\"\"\"\n sed_measure_areas = []\n\n # TODO:求出区段,坐标系变换为原来的坐标系,然后求出角度范围\n wd = area_width / 2 # TODO:若扫描间隔过大,可能导致选择的需要内没有数据点,所以不能用初始的粗扫数据来做计算,粗扫数据知道对称轴完\n for sed_area in sedimentation_areas:\n line_xs, line_ys = [], []\n for tx, ty in zip(t_xs, t_ys):\n if sed_area - wd <= ty <= sed_area + wd:\n line_xs.append(tx)\n line_ys.append(ty)\n\n assert len(line_xs) > 2, '设置的沉降区域内没有测量数据'\n # 区域两端的两条线段, 直接使用x的值应该是能判断的\n line1_xs, line1_ys = [], []\n line2_xs, line2_ys = [], []\n\n last_lx = line_xs[0]\n for lx, ly in zip(line_xs, line_ys): # 其中的一种方法\n if abs(lx - last_lx) < 1000: # 1000 为阈值,同一侧的点差值应该不会比这个阈值大,差值过大的说明不是同一侧的点\n line1_xs.append(lx)\n line1_ys.append(ly)\n else: # 另一侧的点\n line2_xs.append(lx)\n line2_ys.append(ly)\n if abs(line1_xs[0]) > abs(line2_xs[0]):\n line1_xs = line2_xs\n line1_ys = line2_ys\n # logger.debug('区段内点的坐标值 x值:{}, y值:{}', line1_xs, line1_ys)\n # logger.debug('区段内点的坐标值 x值:{}, y值:{}', line2_xs, line2_ys)\n line1 = np.polyfit(line1_xs, line1_ys, 1)\n # line2 = np.polyfit(line2_xs, line2_ys, 1)\n # logger.debug('区段内点拟合的曲线 斜率:{}, 截距:{}', line1[0], line1[1])\n # logger.debug('区段内点拟合的曲线 斜率:{}, 截距:{}', line2[0], line2[1])\n # TODO: 求交点,根据交点反算出范围\n y1 = sed_area - wd\n y2 = sed_area + wd\n cross_11_p_x = (y1 - line1[1]) / line1[0]\n cross_12_p_x = (y2 - line1[1]) / line1[0]\n\n # cross_21_p_x = (y2 - line2[1]) / line2[0]\n # cross_22_p_x = (y1 - line2[1]) / line2[0]\n\n # pt1 = [cross_11_p_x, y1]\n # pt2 = [cross_12_p_x, y2]\n #\n # pt3 = [cross_21_p_x, y1]\n # pt4 = [cross_22_p_x, y2]\n\n # cross_xs = [cross_11_p_x, cross_12_p_x, cross_21_p_x, cross_22_p_x]\n cross_xs = [cross_11_p_x, cross_12_p_x]\n cross_ys = [y1, y2]\n\n theta = math.atan(symmetry_axis[0])\n org_xs = []\n org_ys = []\n for x, y in zip(cross_xs, cross_ys):\n org_x = top_point[0] + x * math.cos(theta) - y * math.sin(theta)\n org_y = top_point[1] + x * math.sin(theta) + y * math.cos(theta)\n org_xs.append(org_x)\n org_ys.append(org_y)\n\n bcc_org_ags, bcc_org_rgs = cartesian_to_polar(org_xs, org_ys) # thetas 是角度值, 只完成了一个区间的,\n # TODO: 需要做区间排序\n if bcc_org_ags[0] > bcc_org_ags[1]:\n bcc_org_ags[0], bcc_org_ags[1] = bcc_org_ags[1], bcc_org_ags[0]\n\n # if bcc_org_ags[2] > bcc_org_ags[3]:\n # bcc_org_ags[2], bcc_org_ags[3] = bcc_org_ags[3], bcc_org_ags[2]\n\n measure_area = [[bcc_org_ags[0], bcc_org_ags[1]]]\n sed_measure_areas.append(measure_area)\n\n lev_measure_areas = []\n for lv_area in level_areas:\n line_xs, line_ys = [], []\n for tx, ty in zip(t_xs, t_ys):\n if lv_area - wd <= tx <= lv_area + wd:\n line_xs.append(tx)\n line_ys.append(ty)\n\n assert len(line_xs) > 2, '设置的收敛区域内没有测量数据'\n # TODO:区域两端的两条线段, 直接使用x的值应该是能判断的\n line1_xs, line1_ys = [], []\n line2_xs, line2_ys = [], []\n\n last_ly = line_ys[0]\n for lx, ly in zip(line_xs, line_ys): # 其中的一种方法\n if abs(ly - last_ly) < 1000: # 1000 为阈值,同一侧的点差值应该不会比这个阈值大,差值过大的说明不是同一侧的点\n line1_xs.append(lx)\n line1_ys.append(ly)\n else: # 另一侧的点\n line2_xs.append(lx)\n line2_ys.append(ly)\n\n print('区段内点的坐标值 x值:{}, y值:{}', line1_xs, line1_ys)\n print('区段内点的坐标值 x值:{}, y值:{}', line2_xs, line2_ys)\n line1 = np.polyfit(line1_xs, line1_ys, 1)\n line2 = np.polyfit(line2_xs, line2_ys, 1)\n print('区段内点拟合的曲线 斜率:{}, 截距:{}', line1[0], line1[1])\n print('区段内点拟合的曲线 斜率:{}, 截距:{}', line2[0], line2[1])\n # TODO: 求交点,根据交点反算出范围\n\n x1 = lv_area - wd\n x2 = lv_area + wd\n\n cross_11_p_y = line1[0] * x1 + line1[1]\n cross_12_p_y = line1[0] * x2 + line1[1]\n\n cross_21_p_y = line2[0] * x2 + line2[1]\n cross_22_p_y = line2[0] * x1 + line2[1]\n\n cross_xs = [x1, x2, x2, x1]\n cross_ys = [cross_11_p_y, cross_12_p_y, cross_21_p_y, cross_22_p_y]\n\n theta = math.atan(symmetry_axis[0])\n org_xs = []\n org_ys = []\n for x, y in zip(cross_xs, cross_ys):\n org_x = top_point[0] + x * math.cos(theta) - y * math.sin(theta)\n org_y = top_point[1] + x * math.sin(theta) + y * math.cos(theta)\n org_xs.append(org_x)\n org_ys.append(org_y)\n\n bcc_org_ags, bcc_org_rgs = cartesian_to_polar(org_xs, org_ys)\n\n if bcc_org_ags[0] > bcc_org_ags[1]:\n bcc_org_ags[0], bcc_org_ags[1] = bcc_org_ags[1], bcc_org_ags[0]\n\n if bcc_org_ags[2] > bcc_org_ags[3]:\n bcc_org_ags[2], bcc_org_ags[3] = bcc_org_ags[3], bcc_org_ags[2]\n\n measure_area = [[bcc_org_ags[0], bcc_org_ags[1]], [bcc_org_ags[2], bcc_org_ags[3]]]\n # TODO:排序得出区间,append 到区间列表中存起来\n lev_measure_areas.append(measure_area)\n\n return sed_measure_areas, lev_measure_areas\n\n\n# @logger.catch\n# def re_part_area(meas_areas, tp, ags, rgs):\n# \"\"\"计算返回各区段与顶点围成的面积\"\"\"\n# area_part_area = []\n# for ara in meas_areas:\n# tmp_ara = copy.deepcopy(ara)\n# ara[0][0] = math.floor(ara[0][0])\n# ara[0][1] = math.ceil(ara[0][1])\n# ara[1][0] = math.floor(ara[1][0])\n# ara[1][1] = math.ceil(ara[1][1])\n#\n# tmp_ara[0][0] = round(tmp_ara[0][0], 1)\n# tmp_ara[0][1] = round(tmp_ara[0][1], 1)\n# tmp_ara[1][0] = round(tmp_ara[1][0], 1)\n# tmp_ara[1][1] = round(tmp_ara[1][1], 1)\n#\n# area_part_1_ag = []\n# area_part_1_rg = []\n# area_part_2_ag = []\n# area_part_2_rg = []\n#\n# for ag, rg in zip(ags, rgs):\n# if tmp_ara[0][0] <= ag < tmp_ara[0][1]:\n# area_part_1_ag.append(ag)\n# area_part_1_rg.append(rg)\n# elif tmp_ara[1][0] <= ag < tmp_ara[1][1]:\n# area_part_2_ag.append(ag)\n# area_part_2_rg.append(rg)\n# area_part_1_xs, area_part_1_ys = tools.polar_to_cartesian(area_part_1_ag, area_part_1_rg)\n# area_part_1_points = []\n# for x, y in zip(area_part_1_xs, area_part_1_ys):\n# p = [x, y]\n# area_part_1_points.append(p)\n# area_part_1_points.append(tp)\n# area_points = calc_area.coords_sort(area_part_1_points)\n# area_part_1_area = calc_area.getPolygonArea(area_points)\n# area_part_area.append(area_part_1_area)\n#\n# area_part_2_xs, area_part_2_ys = tools.polar_to_cartesian(area_part_2_ag, area_part_2_rg)\n# area_part_2_points = []\n# for x, y in zip(area_part_2_xs, area_part_2_ys):\n# p = [x, y]\n# area_part_2_points.append(p)\n# area_part_2_points.append(tp)\n# area_points = calc_area.coords_sort(area_part_2_points)\n# area_part_2_area = calc_area.getPolygonArea(area_points)\n#\n# area_part_area.append(area_part_2_area)\n#\n# return meas_areas\n\n\ndef re_mea_areas(ags, rgs, tp, sy_as, sed_areas, lev_areas, area_width):\n \"\"\"计算返回各区域的面积\"\"\"\n xs, ys = polar_to_cartesian(ags, rgs)\n out_line_all_points = []\n for x, y in zip(xs, ys):\n p = [x, y]\n out_line_all_points.append(p)\n # area_points = calc_area.coords_sort(out_line_all_points)\n # init_full_profile_area = calc_area.getPolygonArea(area_points)\n\n tx0, ty0, t_xs, t_ys = symmetry_axis_convert(ags, rgs, sy_as, tp) # 坐��系转换得目的是获取区域,将实际的数据与测量数据结合\n sed_meas_locs, lev_meas_locs = calc_measure_range(sed_areas, lev_areas, t_xs, t_ys, area_width, sy_as, tp)\n\n # sed_meas_locs = re_part_area(sed_meas_locs, tp, ags, rgs)\n # lev_meas_locs = re_part_area(lev_meas_locs, tp, ags, rgs)\n\n return sed_meas_locs, lev_meas_locs\n\n\n\n# 数据分圈\ndef gen_a_circle_data(device_sn):\n lst_angle = []\n lst_range = []\n # 获取device_sn\n try:\n res = CollectRaw.objects.filter(device_sn=device_sn).order_by('id').values('create_time', 'angle', 'range')[:3600]\n for i in range(len(res)):\n fflag = 1\n if i > 1 and res[i]['angle'] - res[i - 1]['angle'] < 0: # 到此,一圈数据结束\n lst_data = [] # 重新装下一圈数据\n return lst_angle, lst_range\n\n elif i == len(res) - 1 and fflag: # 防止最新的一圈数据获取不到,\n lst_angle.append(res[len(res) - 1]['angle'])\n lst_range.append(res[len(res) - 1]['range'])\n\n lst_angle.append(res[i]['angle'])\n\n if res[i]['range'] > 20000:\n lst_range.append(0)\n else:\n lst_range.append(res[i]['range'])\n # print(\"=========\", lst_data)\n except:\n pass\n finally:\n return lst_angle, lst_range\n\n","sub_path":"utils/init_configuration.py","file_name":"init_configuration.py","file_ext":"py","file_size_in_byte":18500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"307310793","text":"from django.conf import settings\nfrom django.shortcuts import render, redirect,get_object_or_404\nfrom django.contrib.auth.models import User,auth\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nimport random\nfrom django.db.models import Q\nfrom django.core.files.storage import FileSystemStorage\nimport requests\nfrom django.db import models\nfrom .models import Post\nfrom .models import blog\nfrom .models import Video\nfrom .models import Userprofile,Comment,SubComment,Categories,FeedBack\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render\nfrom .form import PostForm\nfrom .form import UserprofileForm\nfrom datetime import datetime\nfrom django_ckeditor_5.fields import CKEditor5Field\nimport os\nimport json\nfrom django.http import HttpResponse,JsonResponse\nfrom taggit.models import Tag\ndef homepage(request):\n \"\"\"\n post=Post.objects.all()\n post_list = Post.objects.all()\n print(post)\n query = request.GET.get(\"q\")\n print(query)\n if query:\n post_list = post_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query)\n ).distinct()\n\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n \"\"\"\n feed = FeedBack.objects.all()\n if request.user.is_authenticated:\n try:\n profile = get_object_or_404(Userprofile,user=request.user)\n except:\n user_profile = Userprofile(user=request.user,username=request.user)\n user_profile.save()\n if request.user.is_staff ==False :\n instanace = get_object_or_404(User,username=request.user)\n instanace.is_staff = True\n instanace.save()\n return render(request,'index2.html',{'feed':feed})\ndef blogs(request):\n post=Post.objects.filter(draft=False)\n post_list = Post.objects.filter(draft=False)\n query = request.GET.get(\"q\")\n query1 = request.GET.get(\"query\")\n if query1:\n categories = get_object_or_404(Categories,categories=query1)\n post=Post.objects.filter(draft=False,categories=categories)\n post_list = Post.objects.filter(draft=False,categories=categories)\n print(post)\n elif query:\n post_list = post_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query) \n ).distinct()\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef signup(request):\n if request.method == 'POST':\n first_name = request.POST['first']\n last_name = request.POST['last']\n email = request.POST['email']\n UserName = request.POST['username']\n globals()['first_name']=first_name\n globals()['last_name']=last_name\n globals()['email'] = email\n globals()['username'] = UserName\n if User.objects.filter(email=email).exists():\n messages.info(request,'Email Already exist')\n return redirect('signup')\n elif Userprofile.objects.filter(username=username).exists():\n messages.info(request,'UserName Already exist')\n return redirect('signup')\n else:\n otp = random.randint(100000,999999)\n #user = User.objects.create_user(username=phonenumber,password=password,email=email,first_name=first_name,last_name=last_name)\n #user.save()\n globals()['otp']=otp\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello ' + first_name+ ' thanks for registering to the website otp for login is'+ str(otp),\n 'noreply@gmail.com',\n [email,'dheerukreddy@gmail.com'],\n \n )\n\n return redirect('verification')\n return render(request,'signup.html')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n return render(request,'signup.html')\ndef verification(request):\n if request.method == 'POST':\n email_otp = int(request.POST['otp'])\n try:\n user=User.objects.filter(email=email).exists()\n print(otp)\n otp is not None\n except:\n return redirect('signup')\n print(user)\n if email_otp == otp or '12345' and user == False:\n password = request.POST['password']\n messages.info(request,'otp verified')\n user = User.objects.create_user(username=email,password=password,email=email,first_name=first_name,last_name=last_name)\n user.save()\n profile = get_object_or_404(User,email=email)\n print(profile)\n user_profile = Userprofile(user=profile,username=username)\n user_profile.save()\n return redirect('login')\n elif user == True:\n messages.info(request,'user already verified')\n return redirect('login')\n else:\n messages.info(request,'otp invalid')\n return redirect('verification')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n else:\n return render(request,'verification.html')\ndef login(request):\n if request.method == 'POST':\n password = request.POST['password']\n email = request.POST['email']\n user = auth.authenticate(username=email,password=password)\n if user is not None:\n auth.login(request,user)\n return redirect(\"/\")\n else:\n messages.info(request,'invalid phone or password')\n return redirect('/login')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n else:\n return render(request,'login.html')\ndef logout(request):\n auth.logout(request)\n return redirect('homepage')\ndef createpost(request):\n if request.method == 'POST':\n form = PostForm(request.POST,request.FILES or None)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = request.user\n instance.save()\n form.save_m2m()\n \n return redirect('/myposts')\n else:\n print(request.user)\n form = PostForm()\n context = {\n \"form\":form,\n }\n return render(request,'test.html',context)\ndef style1(request):\n return redirect('/error')\ndef style2(request):\n return render(request,'style2.html')\ndef style3(request):\n return render(request,'style3.html')\ndef style4(request):\n return render(request,'style4.html')\ndef template1(request):\n return render(request,'template1.html')\ndef template2(request):\n return render(request,'template2.html')\ndef template3(request):\n return render(request,'template3.html')\ndef template4(request):\n return render(request,'template4.html')\n\ndef postdetail(request,slug=None):\n if slug == None:\n \n return redirect('signup')\n else:\n instance = get_object_or_404(Post,slug=slug)\n tag = Tag.objects.filter()\n is_liked =False\n print(instance.user)\n profile = get_object_or_404(Userprofile,user=instance.user)\n print(profile)\n post = get_object_or_404(Post,slug=slug)\n com = Comment.objects.filter(post=post).count\n if request.method=='POST':\n comm = request.POST.get('comm')\n comm_id = request.POST.get('comm_id')\n if comm_id:\n SubComment(\n post=instance,\n user=request.user,\n comm = comm,\n comment = Comment.objects.get(id=int(comm_id))\n ).save()\n return redirect('/'+str(slug)+'/post-detail')\n else:\n Comment(post=instance,user=request.user,comm=comm).save()\n return redirect('/'+str(slug)+'/post-detail')\n comments = []\n for c in Comment.objects.filter(post=instance):\n comments.append([c,SubComment.objects.filter(comment=c)])\n\n if instance.likes.filter(username=request.user).exists():\n is_liked = True\n common_tags = Post.tags.most_common()[:8]\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"comments\":comments,\n \"is_liked\" :is_liked,\n \"total_likes\":instance.total_likes(),\n \"profile\":profile,\n \"com\":com,\n 'common_tags':common_tags,\n }\n return render(request,\"detail1.html\",context)\n\"\"\"\ndef likes(request):\n slug=request.POST.get('like')\n post = get_object_or_404(Post,slug=request.POST.get('like'))\n is_liked =False\n \n if post.likes.filter(username=request.user).exists():\n \n post.likes.remove(request.user)\n \n is_liked = False\n else:\n post.likes.add(request.user)\n is_liked = True\n return HttpResponse('/' + str(slug)+'/post-detail' )\n\"\"\"\ndef likes(request):\n user = request.user\n if request.method == 'POST':\n pk = request.POST.get('post_pk')\n post_obj = Post.objects.get(pk=pk)\n post = get_object_or_404(Post,pk=pk)\n if user in post_obj.likes.all():\n post_obj.likes.remove(user)\n post.countlikes = post_obj.total_likes()\n post.save()\n else:\n post_obj.likes.add(user)\n post.countlikes = post_obj.total_likes()\n post.save()\n return HttpResponse()\ndef post_serialized_view(request,slug):\n data = list(Post.objects.filter(slug=slug).values())\n post =get_object_or_404(Post,slug=slug)\n return JsonResponse(data,safe=False)\ndef myposts(request):\n if request.user.is_authenticated:\n post=Post.objects.filter(user=request.user)\n user1 = get_object_or_404(Userprofile,user=request.user)\n context = {\n \"post\":post,\n \"user1\":user1,\n }\n print(post)\n return render(request,\"yourpost1.html\",context)\n else:\n return redirect('/error')\ndef othersposts(request,user=None):\n user1 = get_object_or_404(Userprofile,username=user)\n print(user1.user)\n post = Post.objects.filter(email=user1,draft=False)\n name = get_object_or_404(User,username=user1)\n print(post)\n use=User.objects.filter(email=user1)\n \n context = {\n \"name\":name,\n \"post\":post,\n \"use\":use,\n \"user1\":user1,\n }\n \n return render(request,\"others1.html\",context)\ndef editpost(request,slug=None):\n if request.method == 'POST':\n instance = get_object_or_404(Post,slug=slug)\n form = PostForm(request.POST or None,instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.slug = slug\n instance.save()\n form.save_m2m()\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"form\":form\n } \n return redirect('/myposts')\n else:\n return redirect('/error')\n\n \ndef edit(request,slug=None):\n if request.method == \"POST\":\n instance = get_object_or_404(Post,slug=slug)\n form = PostForm(instance=instance)\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"form\":form\n } \n return render(request,'test1.html',context)\n else:\n return redirect('/error')\ndef deletepost(request,slug=None):\n if request.method == \"POST\":\n instance = get_object_or_404(Post,slug=slug)\n instance.delete()\n return redirect('/myposts')\n else:\n return redirect('/error')\ndef error(request):\n return render(request,'detail1.html')\n\ndef test(request):\n form = PostForm(request.POST or None)\n if form.is_valid():\n form.save()\n return render(request,'test.html',{'form':form})\n#def profile(request):\n# if request.user.is_authenticated:\n# profile = get_object_or_404(Profile,user=str(request.user))\n# print(profile)\n# instance = get_object_or_404(Profile,user=str(request.user))\n# form = ProfileForm(request.POST or None,instance=instance)\n# if form.is_valid():\n # instance = form.save(commit=False)\n # instance.save()\n # return redirect('/profile')\n # context={\n # 'profile':profile,\n # 'form':form\n # }\n # return render(request,'profile.html',context)\n #else:\n # return redirect('login')\ndef profileedit(request):\n if request.user.is_authenticated:\n instance = get_object_or_404(Userprofile,user=request.user)\n form = UserprofileForm(request.POST or None,request.FILES or None,instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n return redirect('/myposts')\n context={\n 'form':form\n }\n return render(request,'profile-edit.html',context)\n else:\n return redirect('/error')\ndef profile(request):\n if request.user.is_authenticated:\n user1 = get_object_or_404(Userprofile,user=request.user)\n context = {\n \"user1\":user1,\n }\n return render(request,\"profile.html\",context)\n else:\n return redirect('/error')\ndef contact(request):\n if request.method == 'POST':\n name = request.POST['name']\n email = request.POST['email']\n message = request.POST['message']\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello '+' ' + name+' ' +'Your Query Has Been Recorded Our Team Will Contact You As Soon As Possible',\n 'noreply@gmail.com',\n [email,'dheerukreddy@gmail.com'],\n )\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello Dheeraj '+' ' + 'There Is a Query REcorded By' + name+' '\n 'email:'+' '+ str(email)+' '\n 'message:'+' '+ str(message),\n 'noreply@gmail.com',\n ['dheerukreddy@gmail.com'],\n )\n messages.info(request,'Your Query Has been Sucessfully Recoded We will contact You soon')\n return redirect('/contact-us') \n return render(request,'contact.html')\ndef addemail(request):\n if request.method == 'POST':\n email = request.POST['email']\n if User.objects.filter(email=email).exists():\n messages.info(request,'EMAIL ALREADY EXISTS')\n return redirect('/add-email')\n else:\n instance = get_object_or_404(User,username=request.user)\n instance.email = email\n instance.save()\n return redirect('/profile')\n else:\n if request.user.is_authenticated:\n return render(request,'add-email.html')\n else:\n return redirect('/')\ndef tags(request):\n tags = request.GET['q']\n tags = tags.replace('#','')\n tag = get_object_or_404(Tag,slug=tags)\n print(tag)\n post=Post.objects.filter(draft=False,tags=tag)\n print(post)\n post_list = Post.objects.filter(draft=False,tags=tag)\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef tagsslug(request,slug):\n tag = get_object_or_404(Tag,slug=slug)\n print(tag)\n post=Post.objects.filter(draft=False,tags=tag)\n print(post)\n post_list = Post.objects.filter(draft=False,tags=tag)\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef feedback(request):\n if request.method == 'POST':\n name = request.POST['name']\n rating = request.POST['rate']\n feedback = request.POST['feedback']\n feed = FeedBack(name=name,rating=rating,feedback=feedback)\n feed.save()\n return redirect('/')\n else:\n return redirect('/')","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"206504863","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: DIYer22@github\n@mail: ylxx@live.com\nCreated on Wed Jan 9 23:24:20 2019\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nclass Markdown(pd.DataFrame):\n '''\n Markdown class base on DataFrame\n '''\n def __round__(self, *l, **kv):\n redf = pd.DataFrame.__round__(self, *l, **kv)\n return Markdown(redf)\n \n def round(self, *l, **kv):\n redf = pd.DataFrame.round(self, *l, **kv)\n return Markdown(redf)\n \n def to_md(df, nblankBetweenCell=1, tableMidSymbol = \"---:\"):\n '''\n Transfer DataFrame to markdown\n \n Parameters\n ----------\n df : DataFrame\n pandas.DataFrame\n \n nblankBetweenCell : int, default 1\n How many blanks between 2 cells\n tableMidSymbol : str, default \"---:\"\n \"-:\", \":-\", \":-:\" for markdown \n \n '''\n blanks = nblankBetweenCell *\" \"\n betweenCell = blanks + \"|\" + blanks\n rowFormat = \"|%s%s%s|\" % (blanks, \"%s\", blanks)\n ncols = len(df.columns)\n strcols = df.columns.map(str)\n lencols = np.array(strcols.map(len))\n \n strdf = df.applymap(str)\n lendf = np.array(strdf.applymap(len))\n \n \n maxLens = np.array(list(zip(lendf.max(0), lencols, [len(tableMidSymbol)]*ncols))).max(1)\n \n vMulBlank = np.vectorize(lambda x:x * \" \")\n\n mdcols = vMulBlank(maxLens - lencols) + strcols\n mddf = vMulBlank(maxLens - lendf) + strdf\n \n headstr = rowFormat % betweenCell.join(mdcols)\n \n tableMidStr = rowFormat% betweenCell.join(map(lambda x: x + tableMidSymbol, vMulBlank(maxLens-len(tableMidSymbol))))\n \n bodystr = \"\\n\".join(map(lambda kv: rowFormat% betweenCell.join(kv[-1]), mddf.iterrows()))\n \n tablestr = '\\n'.join([headstr, tableMidStr, bodystr])\n return tablestr\n def __str__(self):\n return self.to_md()\n \n @staticmethod\n def test():\n df = pd.DataFrame([{\"a\":1, \"b\":1,}, {\"a\":1, \"bbbbbb\":1,}, {\"a\":1, \"bbbbbb\":1/2, \"c\":1/3}])\n md = Markdown(df)\n print(md)\n print(\"-\"*20)\n print(md.round(2))\n return df\nif __name__ == \"__main__\":\n pass\n \n \n \n","sub_path":"boxx/tool/toolMarkdown.py","file_name":"toolMarkdown.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"525313736","text":"from flask import Flask, render_template, request\nimport json\nimport pandas\nimport math\nimport random\n\napp = Flask(__name__)\napp.debug = True\n\nfilepathPoints = \"./results/points.csv\"\nfilepathClusters = \"./results/centers.csv\"\n\n\ndef max_cluster(list_points, key):\n max_c = 0\n for p in list_points : \n distance =math.sqrt(math.pow( p[0]-key[0],2) + (math.pow(p[1]- key[1],2) ))\n if distance > max_c :\n max_c = distance\n return p\n return 0\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/mapPoint\", methods = ['POST','GET'])\ndef generatePoints():\n if request.method == 'GET':\n points = pandas.read_csv(filepath_or_buffer=filepathPoints) # Read the file\n\n table_points = points[['longitude', 'latitude','hashtags','url' ,'cluster' ]]\n table_points = table_points.fillna('').values.tolist()\n\n points = pandas.read_csv(filepath_or_buffer=filepathClusters) # Read the file\n table_clusters = points[['longitude','latitude','cluster', 'tags']].fillna('').values.tolist()\n\n\n # now creating a list of objects in this form : [cluster_number, center point] , [list of the points contained in this cluster]\n result =[ [ [cluster,[clust for clust in table_clusters if clust[2] == cluster][0],10 ], [l for l in table_points if l[4] == cluster] ] for cluster in set([ p[4] for p in table_points])]\n \n for cluster in result :\n for point in cluster[1] :\n point[1] = point[1]+0.0005-(random.randint(0,10)/10000.0)#max_cluster(cluster[1],cluster[0][1])\n point[0] = point[0]+0.0005-(random.randint(0,10)/10000.0)#max_cluster(cluster[1],cluster[0][1])\n\n return json.dumps(result)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=8080, debug=True)\n","sub_path":"python/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100857760","text":"#\n# SPDX-License-Identifier: MIT\n#\n\nfrom oeqa.selftest.case import OESelftestTestCase\nfrom oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars\n\nclass TestSyzkallerWR(OESelftestTestCase):\n def setUpSyzkallerConfig(self):\n syz_target_sysroot = get_bb_var('PKGD', 'syzkaller')\n syzkaller_native = get_bb_var('RECIPE_SYSROOT_NATIVE', 'syzkaller-native')\n self.logger.info(\"syz_target_sysroot %s\" % syz_target_sysroot)\n\n self.syz_manager_bin = os.path.join(syzkaller_native, 'usr/bin/syz-manager')\n self.syzkaller_target = os.path.join(syz_target_sysroot, 'usr')\n self.logger.info(\"self.syzkaller_target %s\" % self.syzkaller_target)\n self.syzkaller_workdir = os.path.join(self.topdir, 'syzkaller_workdir')\n self.syzkaller_cfg = os.path.join(self.syzkaller_workdir, 'wrl.cfg')\n\n bb_vars = get_bb_vars(['SYZ_FUZZTIME', 'SYZ_QEMU_MEM', 'SYZ_QEMU_CPUS'])\n self.syzkaller_fuzztime = int(bb_vars['SYZ_FUZZTIME'] or 30) * 60\n self.logger.info(\"self.syzkaller_fuzztime %s\" % self.syzkaller_fuzztime)\n self.syzkaller_qemu_mem = int(bb_vars['SYZ_QEMU_MEM'] or 1024)\n self.logger.info(\"self.syzkaller_qemu_mem %s\" % self.syzkaller_qemu_mem)\n self.syzkaller_qemu_cpus = int(bb_vars['SYZ_QEMU_CPUS'] or 2)\n self.logger.info(\"self.syzkaller_qemu_cpus %s\" % self.syzkaller_qemu_cpus)\n self.syzkaller_vms = self.nprocs // self.syzkaller_qemu_cpus or 1\n\n self.kernel_cmdline = \"dummy_hcd.num=%s\" % (self.syzkaller_qemu_cpus)\n\n if not os.path.exists(self.syzkaller_workdir):\n os.mkdir(self.syzkaller_workdir)\n\n with open(self.syzkaller_cfg, 'w') as f:\n f.write(\n\"\"\"\n{\n\t\"target\": \"linux/amd64\",\n\t\"http\": \"127.0.0.1:56741\",\n\t\"workdir\": \"%s\",\n\t\"kernel_obj\": \"%s\",\n\t\"kernel_src\": \"%s\",\n\t\"image\": \"%s\",\n\t\"syzkaller\": \"%s\",\n\t\"type\": \"qemu\",\n\t\"reproduce\" : false,\n\t\"sandbox\": \"none\",\n\t\"vm\": {\n\t\t\"count\": %s,\n\t\t\"kernel\": \"%s\",\n\t\t\"cmdline\": \"%s\",\n\t\t\"cpu\": %s,\n\t\t\"mem\": %s\n\t}\n}\n\"\"\"\n% (self.syzkaller_workdir, self.kernel_objdir, self.kernel_src, self.rootfs, \\\n self.syzkaller_target, self.syzkaller_vms, self.kernel, self.kernel_cmdline, \\\n self.syzkaller_qemu_cpus, self.syzkaller_qemu_mem)\n )\n\n def setUpLocal(self):\n super(TestSyzkallerWR, self).setUpLocal()\n\n self.image = 'wrlinux-image-glibc-core'\n self.machine = 'intel-x86-64'\n self.fstypes = \"ext4\"\n\n bb_vars = get_bb_vars(['TOPDIR', 'DEPLOY_DIR_IMAGE', 'STAGING_KERNEL_DIR'])\n\n self.topdir = bb_vars['TOPDIR']\n self.deploy_dir_image = bb_vars['DEPLOY_DIR_IMAGE']\n self.kernel_src = bb_vars['STAGING_KERNEL_DIR']\n\n self.nprocs = os.cpu_count() or 1\n self.kernel = os.path.join(self.deploy_dir_image, 'bzImage')\n self.rootfs = os.path.join(self.deploy_dir_image, '%s-%s.ext4' % (self.image, self.machine))\n self.kernel_objdir = self.deploy_dir_image\n\n self.setUpSyzkallerConfig()\n\n self.write_config(\n\"\"\"\nMACHINE = \"%s\"\nIMAGE_FSTYPES = \"%s\"\n\"\"\"\n% (self.machine, self.fstypes)\n )\n\n bitbake(self.image, output_log=self.logger)\n bitbake('syzkaller-native -c addto_recipe_sysroot', output_log=self.logger)\n bitbake('syzkaller', output_log=self.logger)\n\n def test_syzkaller_wr(self):\n runCmd([self.syz_manager_bin, '-config', self.syzkaller_cfg], timeout=self.syzkaller_fuzztime, output_log=self.logger, ignore_status=True, shell=False)\n","sub_path":"lib/oeqa/selftest/cases/syzkaller_wr.py","file_name":"syzkaller_wr.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574982384","text":"# Write your solution for 1.2 here!b=0\nb=0\nfor i in range (101):\n if i%2==0:\n b=b+i\nprint (b)\ni=0\nwhile i<1000:\n if i%6==2 and i**3%5==3:\n print(i)\n i=i+1","sub_path":"exercises/conditionals.py","file_name":"conditionals.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573744974","text":"from django.test import TestCase\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nfrom tickets.tests.factories import TicketFactory\nfrom tickets.constants.status import VERIFIED, COMPLETED, STARTED, ASSIGNED, UNASSIGNED\n\n\nclass TicketTestCase(TestCase):\n def test_status(self):\n t0 = timezone.now() - timedelta(days=2)\n t1 = timezone.now() - timedelta(days=1)\n t2 = timezone.now()\n ticket_unassigned = TicketFactory(assignee=None)\n ticket_assigned = TicketFactory()\n ticket_started = TicketFactory(started=t0)\n ticket_completed = TicketFactory(completed=t1)\n ticket_verified = TicketFactory(verified=t2)\n assert ticket_unassigned.status() == UNASSIGNED\n assert ticket_assigned.status() == ASSIGNED\n assert ticket_started.status() == STARTED\n assert ticket_completed.status() == COMPLETED\n assert ticket_verified.status() == VERIFIED\n","sub_path":"tickets/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"531961890","text":"\"\"\"\nAuthor: Mr.Jiang\nGithub: https://github.com/1642195610\nCSDN : https://blog.csdn.net/qq_43722162\n\"\"\"\n\n\nclass Student():\n def __init__(self, name, sex, age):\n \"\"\"\n\n :param name:姓名\n :type name: str\n :param sex: 性别\n :type sex: str\n :param age: 年龄\n :type age: int\n \"\"\"\n self.name = name\n self.sex = sex\n self.age = age\n\n def learn(self):\n print(\"%s能自主学习\" % self.name)\n\n def sleep(self):\n print(\"{}能自主休息\".format(self.name))\n\n\nl = Student(\"姜泽毓\", \"男\", 24)\nprint(l.name)\nprint(l.sex)\nprint(l.age)\nl.learn()\nl.sleep()\n","sub_path":"data_zgd/python进阶/10.6-链表/10.6.py","file_name":"10.6.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"244673100","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 ('controller', '0012_auto_20150119_1605'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='traffic',\n name='for_sta',\n field=models.ForeignKey(related_name='for_station', default=None, to='controller.Station', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"apps/controller/migrations/0013_auto_20150119_1810.py","file_name":"0013_auto_20150119_1810.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"609540775","text":"#coding=utf-8\nimport numpy as np\nimport cv2\nimport time\n\n\n\ndef cost(func):\n def __wrap__(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(\"-------------\", func.__name__, end - start)\n return result\n\n return __wrap__\n \n\nclass GMM:\n\n def __init__(self, height, width, model_per_pixl, channel=3):\n self.k = model_per_pixl\n self.channel = channel\n self.height, self.width = height, width\n self.means = np.zeros([height, width, model_per_pixl, channel], np.float64)\n self.variance = np.ones([height, width, model_per_pixl, channel])\n self.omega = np.ones([height, width, model_per_pixl]) / model_per_pixl # model_wight \n self.rol = np.zeros([height, width, model_per_pixl]) \n\n self.lr = self.alpha = 0.05\n self.init_weight = 0.1\n self.max_var = 255\n self.count = 0\n\n def norm_weight(self):\n self.omega = self.omega /np.sum(self.omega, axis=-1)[..., np.newaxis]\n\n @cost\n def pdf(self, img):\n # 多维高斯分布\n exp = -0.5 * np.sum(np.power(img - self.means, 2) / self.variance, axis=-1)\n c = np.power(2 * np.pi * np.sum(self.variance, axis=-1), self.channel / 2)\n return 1 / c * np.exp(exp)\n\n @cost\n def resorted(self):\n sort_idx = np.argsort(-self.omega, axis=-1)\n for r in range(self.height):\n for c in range(self.width):\n perm = sort_idx[r, c] # 降序\n self.omega[r, c] = self.omega[r, c, perm]\n self.means[r, c] = self.means[r, c, perm]\n self.variance[r, c] = self.variance[r, c, perm]\n\n @cost\n def background_mask(self, T=0.3):\n cum_weight = np.cumsum(self.omega, axis=-1)\n return cum_weight < T\n\n\n @cost\n def fit(self, img):\n new_img = np.tile(img[:,:, np.newaxis,:], [1, 1, self.k, 1])\n self.rol = self.alpha * self.pdf(new_img)\n\n update_var = (new_img - self.means) ** 2\n bgd_delta = np.sqrt(np.sum(update_var / self.variance, axis=-1))\n bgd_mask = bgd_delta < 2.5\n result = np.any(bgd_mask & self.background_mask(), axis=-1)\n self.count += 1\n \n self.alpha = 0.1 if self.count < 10 else 0.0001\n print(self.alpha)\n\n # update omega\n # min_dis_index = np.argmin(bgd_delta, axis=-1)\n for r in range(self.height):\n for c in range(self.width):\n min_dis_idx = None\n for idx, bgd in enumerate(bgd_delta[r][c]):\n if bgd:\n min_dis_idx = idx\n min_weight_idx = -1\n self.omega[r, c] = (1 - self.alpha) * self.omega[r, c]\n if min_dis_idx is not None and bgd_mask[r, c, min_dis_idx]: # 最小的高斯 小于2.5\n self.omega[r, c, min_dis_idx] += self.alpha # update weight\n self.means[r, c, min_dis_idx] += self.rol[r, c, min_dis_idx] * (img[r, c] - self.means[r, c, min_dis_idx])\n self.variance[r, c, min_dis_idx] += self.rol[r, c, min_dis_idx] * (update_var[r, c, min_dis_idx] - self.variance[r, c, min_dis_idx])\n\n else: # 都不是backgound\n self.omega[r, c, min_weight_idx] = self.init_weight\n self.means[r, c, min_weight_idx] = img[r, c]\n self.variance[r, c, min_weight_idx] = self.max_var\n\n self.norm_weight()\n self.resorted()\n return result\n\ndef main():\n cap = cv2.VideoCapture(0)\n cap.set(3, 300)\n cap.set(4, 300)\n _, img = cap.read()\n height, width, channel = img.shape\n start = time.time()\n gm = GMM(height, width, 5, channel)\n while(True):\n _, img = cap.read()\n mask = gm.fit(img)\n print(mask.shape, img.shape)\n mask = cv2.medianBlur(mask.astype(np.uint8), 5)\n img[mask.astype(np.bool)] = (255, 255, 255)\n cv2.imshow(\"test\", img)\n cv2.waitKey(100)\nmain()\n","sub_path":"gmm.py","file_name":"gmm.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"486254760","text":"def modify_eni(connection, vpc_id, module, eni):\n instance_id = module.params.get('instance_id')\n attached = module.params.get('attached')\n do_detach = (module.params.get('state') == 'detached')\n device_index = module.params.get('device_index')\n description = module.params.get('description')\n security_groups = module.params.get('security_groups')\n force_detach = module.params.get('force_detach')\n source_dest_check = module.params.get('source_dest_check')\n delete_on_termination = module.params.get('delete_on_termination')\n secondary_private_ip_addresses = module.params.get('secondary_private_ip_addresses')\n purge_secondary_private_ip_addresses = module.params.get('purge_secondary_private_ip_addresses')\n secondary_private_ip_address_count = module.params.get('secondary_private_ip_address_count')\n changed = False\n try:\n if (description is not None):\n if (eni.description != description):\n connection.modify_network_interface_attribute(eni.id, 'description', description)\n changed = True\n if (len(security_groups) > 0):\n groups = get_ec2_security_group_ids_from_names(security_groups, connection, vpc_id=vpc_id, boto3=False)\n if (sorted(get_sec_group_list(eni.groups)) != sorted(groups)):\n connection.modify_network_interface_attribute(eni.id, 'groupSet', groups)\n changed = True\n if (source_dest_check is not None):\n if (eni.source_dest_check != source_dest_check):\n connection.modify_network_interface_attribute(eni.id, 'sourceDestCheck', source_dest_check)\n changed = True\n if ((delete_on_termination is not None) and (eni.attachment is not None)):\n if (eni.attachment.delete_on_termination is not delete_on_termination):\n connection.modify_network_interface_attribute(eni.id, 'deleteOnTermination', delete_on_termination, eni.attachment.id)\n changed = True\n current_secondary_addresses = [i.private_ip_address for i in eni.private_ip_addresses if (not i.primary)]\n if (secondary_private_ip_addresses is not None):\n secondary_addresses_to_remove = list((set(current_secondary_addresses) - set(secondary_private_ip_addresses)))\n if (secondary_addresses_to_remove and purge_secondary_private_ip_addresses):\n connection.unassign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=list((set(current_secondary_addresses) - set(secondary_private_ip_addresses))), dry_run=False)\n changed = True\n secondary_addresses_to_add = list((set(secondary_private_ip_addresses) - set(current_secondary_addresses)))\n if secondary_addresses_to_add:\n connection.assign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=secondary_addresses_to_add, secondary_private_ip_address_count=None, allow_reassignment=False, dry_run=False)\n changed = True\n if (secondary_private_ip_address_count is not None):\n current_secondary_address_count = len(current_secondary_addresses)\n if (secondary_private_ip_address_count > current_secondary_address_count):\n connection.assign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=None, secondary_private_ip_address_count=(secondary_private_ip_address_count - current_secondary_address_count), allow_reassignment=False, dry_run=False)\n changed = True\n elif (secondary_private_ip_address_count < current_secondary_address_count):\n secondary_addresses_to_remove_count = (current_secondary_address_count - secondary_private_ip_address_count)\n connection.unassign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=current_secondary_addresses[:secondary_addresses_to_remove_count], dry_run=False)\n if (attached is True):\n if (eni.attachment and (eni.attachment.instance_id != instance_id)):\n detach_eni(eni, module)\n eni.attach(instance_id, device_index)\n wait_for_eni(eni, 'attached')\n changed = True\n if (eni.attachment is None):\n eni.attach(instance_id, device_index)\n wait_for_eni(eni, 'attached')\n changed = True\n elif (attached is False):\n detach_eni(eni, module)\n except BotoServerError as e:\n module.fail_json(msg=e.message)\n eni.update()\n module.exit_json(changed=changed, interface=get_eni_info(eni))","sub_path":"Data Set/bug-fixing-5/fed4217fd75f5dd734ce48973c0eaadbb6060774--fix.py","file_name":"fed4217fd75f5dd734ce48973c0eaadbb6060774--fix.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"296603661","text":"import numpy as np\nfrom collections import Iterable\n\nfrom .form.utils import docval, getargs, popargs, call_docval_func\n\nfrom . import register_class, CORE_NAMESPACE\nfrom .base import TimeSeries, _default_conversion, _default_resolution\nfrom .core import NWBContainer, ElementIdentifiers, DynamicTable, DynamicTableRegion\n\n\n@register_class('AnnotationSeries', CORE_NAMESPACE)\nclass AnnotationSeries(TimeSeries):\n \"\"\"\n Stores text-based records about the experiment. To use the\n AnnotationSeries, add records individually through\n add_annotation() and then call finalize(). Alternatively, if\n all annotations are already stored in a list, use set_data()\n and set_timestamps()\n \"\"\"\n\n __nwbfields__ = ()\n\n _ancestry = \"TimeSeries,AnnotationSeries\"\n _help = \"Time-stamped annotations about an experiment.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames',\n 'default': list()},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': None},\n {'name': 'comments', 'type': str,\n 'doc': 'Human-readable comments about this TimeSeries dataset', 'default': 'no comments'},\n {'name': 'description', 'type': str, 'doc':\n 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)\n super(AnnotationSeries, self).__init__(name, data, 'n/a',\n resolution=-1.0, conversion=1.0,\n timestamps=timestamps, **kwargs)\n\n @docval({'name': 'time', 'type': float, 'doc': 'The time for the anotation'},\n {'name': 'annotation', 'type': str, 'doc': 'the annotation'})\n def add_annotation(self, **kwargs):\n '''\n Add an annotation\n '''\n time, annotation = getargs('time', 'annotation', kwargs)\n self.fields['timestamps'].append(time)\n self.fields['data'].append(annotation)\n\n\n@register_class('AbstractFeatureSeries', CORE_NAMESPACE)\nclass AbstractFeatureSeries(TimeSeries):\n \"\"\"\n Represents the salient features of a data stream. Typically this\n will be used for things like a visual grating stimulus, where\n the bulk of data (each frame sent to the graphics card) is bulky\n and not of high value, while the salient characteristics (eg,\n orientation, spatial frequency, contrast, etc) are what important\n and are what are used for analysis\n \"\"\"\n\n __nwbfields__ = ('feature_units',\n 'features')\n\n _ancestry = \"TimeSeries,AbstractFeatureSeries\"\n _help = \"Features of an applied stimulus. This is useful when storing the raw stimulus is impractical.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'feature_units', 'type': (str, Iterable), 'doc': 'The unit of each feature'},\n {'name': 'features', 'type': (str, Iterable), 'doc': 'Description of each feature'},\n\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames',\n 'default': list()},\n {'name': 'resolution', 'type': float,\n 'doc': 'The smallest meaningful difference (in specified unit) between values in data',\n 'default': _default_resolution},\n {'name': 'conversion', 'type': float,\n 'doc': 'Scalar to multiply each element in data to convert it to the specified unit',\n 'default': _default_conversion},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': None},\n {'name': 'starting_time', 'type': float, 'doc': 'The timestamp of the first sample', 'default': None},\n {'name': 'rate', 'type': float, 'doc': 'Sampling rate in Hz', 'default': None},\n {'name': 'comments', 'type': str, 'doc': 'Human-readable comments about this TimeSeries dataset',\n 'default': 'no comments'},\n {'name': 'description', 'type': str,\n 'doc': 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'control', 'type': Iterable,\n 'doc': 'Numerical labels that apply to each element in data', 'default': None},\n {'name': 'control_description', 'type': Iterable,\n 'doc': 'Description of each control value', 'default': None},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, features, feature_units = popargs('name', 'data',\n 'features', 'feature_units', kwargs)\n super(AbstractFeatureSeries, self).__init__(name, data, \"see 'feature_units'\", **kwargs)\n self.features = features\n self.feature_units = feature_units\n\n @docval({'name': 'time', 'type': float, 'doc': 'the time point of this feature'},\n {'name': 'features', 'type': (list, np.ndarray), 'doc': 'the feature values for this time point'})\n def add_features(self, **kwargs):\n time, features = getargs('time', 'features', kwargs)\n self.timestamps.append(time)\n self.data.append(features)\n\n\n@register_class('IntervalSeries', CORE_NAMESPACE)\nclass IntervalSeries(TimeSeries):\n \"\"\"\n Stores intervals of data. The timestamps field stores the beginning and end of intervals. The\n data field stores whether the interval just started (>0 value) or ended (<0 value). Different interval\n types can be represented in the same series by using multiple key values (eg, 1 for feature A, 2\n for feature B, 3 for feature C, etc). The field data stores an 8-bit integer. This is largely an alias\n of a standard TimeSeries but that is identifiable as representing time intervals in a machinereadable\n way.\n \"\"\"\n\n __nwbfields__ = ()\n\n _ancestry = \"TimeSeries,IntervalSeries\"\n _help = \"Stores the start and stop times for events.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': '>0 if interval started, <0 if interval ended.', 'default': list()},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': list()},\n {'name': 'comments', 'type': str,\n 'doc': 'Human-readable comments about this TimeSeries dataset', 'default': 'no comments'},\n {'name': 'description', 'type': str,\n 'doc': 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'control', 'type': Iterable,\n 'doc': 'Numerical labels that apply to each element in data', 'default': None},\n {'name': 'control_description', 'type': Iterable,\n 'doc': 'Description of each control value', 'default': None},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)\n unit = 'n/a'\n self.__interval_timestamps = timestamps\n self.__interval_data = data\n super(IntervalSeries, self).__init__(name, data, unit,\n timestamps=timestamps,\n resolution=-1.0,\n conversion=1.0,\n **kwargs)\n\n @docval({'name': 'start', 'type': float, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'stop', 'type': float, 'doc': 'The name of this TimeSeries dataset'})\n def add_interval(self, **kwargs):\n start, stop = getargs('start', 'stop', kwargs)\n self.__interval_timestamps.append(start)\n self.__interval_timestamps.append(stop)\n self.__interval_data.append(1)\n self.__interval_data.append(-1)\n\n @property\n def data(self):\n return self.__interval_data\n\n @property\n def timestamps(self):\n return self.__interval_timestamps\n\n\n@register_class('Units', CORE_NAMESPACE)\nclass Units(DynamicTable):\n \"\"\"\n Event times of observed units (e.g. cell, synapse, etc.).\n \"\"\"\n\n __columns__ = (\n {'name': 'spike_times', 'description': 'the spike times for each unit', 'vector_data': True},\n {'name': 'electrode', 'description': 'the electrode that each spike unit came from'},\n {'name': 'electrode_group', 'description': 'the electrode group that each spike unit came from'},\n {'name': 'waveform_mean', 'description': 'the spike waveform mean for each spike unit'},\n {'name': 'waveform_sd', 'description': 'the spike waveform standard deviation for each spike unit'}\n )\n\n @docval({'name': 'name', 'type': str, 'doc': 'Name of this Units interface', 'default': 'Units'},\n {'name': 'id', 'type': ('array_data', ElementIdentifiers),\n 'doc': 'the identifiers for the units stored in this interface', 'default': None},\n {'name': 'columns', 'type': (tuple, list), 'doc': 'the columns in this table', 'default': None},\n {'name': 'colnames', 'type': 'array_data', 'doc': 'the names of the columns in this table',\n 'default': None},\n {'name': 'description', 'type': str, 'doc': 'a description of what is in this table', 'default': None})\n def __init__(self, **kwargs):\n if kwargs.get('description', None) is None:\n kwargs['description'] = \"\"\n call_docval_func(super(Units, self).__init__, kwargs)\n if 'spike_times' not in self.colnames:\n self.__has_spike_times = False\n\n @docval({'name': 'spike_times', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'electrode', 'type': DynamicTableRegion, 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'electrode_group', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'waveform_mean', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'waveform_sd', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'id', 'type': int, 'help': 'the ID for the ROI', 'default': None},\n allow_extra=True)\n def add_unit(self, **kwargs):\n \"\"\"\n Add a unit to this table\n \"\"\"\n super(Units, self).add_row(**kwargs)\n\n @docval({'name': 'index', 'type': int,\n 'doc': 'the index of the unit in unit_ids to retrieve spike times for'})\n def get_unit_spike_times(self, **kwargs):\n index = getargs('index', kwargs)\n return np.asarray(self['spike_times'][index])\n","sub_path":"src/pynwb/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":11629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"304189952","text":"from Dataset import Dataset\nfrom Processing.Lungs import Lungs\nfrom Processing.LunglessCT import LunglessCT\nfrom Processing.Bones import Bones\nfrom Processing.Tissues import Tissues\nfrom Processing.Fats import Fats\n\nimport numpy as np\nfrom scipy.ndimage import median_filter\n\n\nclass PreProcess:\n \"\"\"PreProcessing by creating the label map from the binary maps.\"\"\"\n def __init__(self, emphysema_va1=50, ventilated_val=300, poorly_vent_val=700, atelectatic_val=1000, bones_val=1200,\n tissue_val=1050, fats_val=650):\n \"\"\"Initialize the parameters for the preprocessing of the label map.\n\n :param emphysema_va1: Weighted value for the lung binary map\n :param ventilated_val: Weighted value for the lung binary map\n :param poorly_vent_val: Weighted value for the lung binary map\n :param atelectatic_val: Weighted value for the lung binary map\n :param bones_val: Weighted value for the bones binary map\n :param tissue_val: Weighted value for the tissues binary map\n :param fats_val: Weighted value for the fats binary map\n \"\"\"\n self.bones_val = bones_val\n self.tissue_val = tissue_val\n self.fats_val = fats_val\n\n # Initialize default parameters for lungs label map\n self._emphysema_val = 50\n self._ventilated_val = 300\n self._poorly_vent_val = 700\n self._atelectatic_val = 1000\n\n # Initialize the parameters\n if emphysema_va1 is None:\n self.emphysema_va1 = self._emphysema_val\n else:\n self.emphysema_va1 = emphysema_va1\n if ventilated_val is None:\n self.ventilated_val = self._ventilated_val\n else:\n self.ventilated_val = ventilated_val\n if poorly_vent_val is None:\n self.poorly_vent_val = self._poorly_vent_val\n else:\n self.poorly_vent_val = poorly_vent_val\n if atelectatic_val is None:\n self.atelectatic_val = self._atelectatic_val\n else:\n self.atelectatic_val = atelectatic_val\n\n if emphysema_va1 != self._emphysema_val or ventilated_val != self._ventilated_val or \\\n poorly_vent_val != self._poorly_vent_val or atelectatic_val != self._atelectatic_val:\n self.recreate_lungs = True\n else:\n self.recreate_lungs = False\n\n def __repr__(self):\n return '{self.__class__.__name__}(emphysema_va1={self.emphysema_va1}, ventilated_val=' \\\n '{self.ventilated_val}, poorly_vent_val={self.poorly_vent_val}, atelectatic_val={self.atelectatic_val},'\\\n ' bones_val={self.bones_val}, tissue_val={self.tissue_val}, fats_val={self.fats_val})'.format(self=self)\n\n def LTRC_label_map(self, pat_obj):\n \"\"\"Creates the label map for LTRC dataset.\n\n :param pat_obj: The object of LTRC class\n :return: source_data (LTRC)\n \"\"\"\n # Initialize the parameters and empty dictionary\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n source_data, target_data = {}, {}\n\n # Read single series\n for series_num, series_lungs_map in lungs_map.items():\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape[series_num])\n\n # Combine the bones to the base map\n series_bones_data = bones_data[series_num]\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data[series_num]\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data[series_num]\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Read the lungless CT data and lungs data\n series_ct_data = lungless_ct[series_num]\n series_lungs = lungs_data[series_num]\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n series_map = np.rollaxis(series_lungs_map[np.newaxis], axis=0, start=3)\n series_map = np.rollaxis(series_map, axis=3, start=0)\n\n series_ct = np.rollaxis(series_ct_data[np.newaxis], axis=0, start=3)\n series_ct = np.rollaxis(series_ct, axis=3, start=0)\n\n series_lungs = np.rollaxis(series_lungs[np.newaxis], axis=0, start=3)\n series_lungs = np.rollaxis(series_lungs, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, series_map), axis=3)\n target_map = np.concatenate((series_ct, series_lungs), axis=3)\n\n source_data[series_num] = source_map\n target_data[series_num] = target_map\n\n # Cache the data\n pat_obj.source_data = source_data\n pat_obj.target_data = target_data\n return source_data\n\n def UMM_label_map(self, pat_obj):\n \"\"\"Creates the label map for UMM dataset.\n\n :param pat_obj: The object of UMM class\n :return: source_data (UMM)\n \"\"\"\n # Initialize the parameters\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n\n if not isinstance(lungs_map, dict):\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape)\n\n # Combine the bones to the base map\n series_bones_data = bones_data\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n lungs = np.rollaxis(lungs_map[np.newaxis], axis=0, start=3)\n lungs = np.rollaxis(lungs, axis=3, start=0)\n\n ct = np.rollaxis(lungless_ct[np.newaxis], axis=0, start=3)\n ct = np.rollaxis(ct, axis=3, start=0)\n\n lungs_ct = np.rollaxis(lungs_data[np.newaxis], axis=0, start=3)\n lungs_ct = np.rollaxis(lungs_ct, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, lungs), axis=3)\n target_map = np.concatenate((ct, lungs_ct), axis=3)\n\n # Cache the data\n pat_obj.source_data = source_map\n pat_obj.target_data = target_map\n source_data = source_map\n else:\n source_data, target_data = {}, {}\n\n for series_date, series_lungs_map in lungs_map.items():\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape[series_date])\n\n # Combine the bones to the base map\n series_bones_data = bones_data[series_date]\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data[series_date]\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data[series_date]\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Read the lungless CT data and lungs data\n series_ct_data = lungless_ct[series_date]\n series_lungs = lungs_data[series_date]\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n series_map = np.rollaxis(series_lungs_map[np.newaxis], axis=0, start=3)\n series_map = np.rollaxis(series_map, axis=3, start=0)\n\n series_ct = np.rollaxis(series_ct_data[np.newaxis], axis=0, start=3)\n series_ct = np.rollaxis(series_ct, axis=3, start=0)\n\n series_lungs = np.rollaxis(series_lungs[np.newaxis], axis=0, start=3)\n series_lungs = np.rollaxis(series_lungs, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, series_map), axis=3)\n target_map = np.concatenate((series_ct, series_lungs), axis=3)\n\n source_data[series_date] = source_map\n target_data[series_date] = target_map\n\n # Cache the data\n pat_obj.source_data = source_data\n pat_obj.target_data = target_data\n return source_data\n\n def UKSH_label_map(self, pat_obj):\n \"\"\"Creates the label map for UKSH dataset.\n\n :param pat_obj: Object of UKSH class\n :return: source_data (UKSH)\n \"\"\"\n # Initialize the parameters\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape)\n\n # Combine the bones to the base map\n series_bones_data = bones_data\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n lungs = np.rollaxis(lungs_map[np.newaxis], axis=0, start=3)\n lungs = np.rollaxis(lungs, axis=3, start=0)\n\n ct = np.rollaxis(lungless_ct[np.newaxis], axis=0, start=3)\n ct = np.rollaxis(ct, axis=3, start=0)\n\n lungs_ct = np.rollaxis(lungs_data[np.newaxis], axis=0, start=3)\n lungs_ct = np.rollaxis(lungs_ct, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, lungs), axis=3)\n target_map = np.concatenate((ct, lungs_ct), axis=3)\n\n # Cache the data\n pat_obj.source_data = source_map\n pat_obj.target_data = target_map\n return source_map\n\n def full_label_map(self, pat_obj, bones_threshold=150, tissues_threshold=0, fats_threshold=-400):\n \"\"\"Creates the label map using all the binary maps.\n\n :param pat_obj: Object of either LTRC, UMM or UKSH class\n :param bones_threshold: The threshold value to separate the bone from CT image (Default is 150)\n :param tissues_threshold: The threshold value to separate the soft tissue from CT image (Default is 0)\n :param fats_threshold: The threshold value to separate the fats and muscles from CT image (Default is -400)\n :return: full label map and instance to the binary map (i.e. 'self')\n \"\"\"\n assert (isinstance(pat_obj, Dataset)), 'Object is not instance of Dataset'\n\n # Check if all binary maps are available\n if hasattr(pat_obj, 'lungs_bin_map') is False or self.recreate_lungs is True:\n pat_obj.lungs_bin_map = Lungs(pat_obj, emphysema_va1=self.emphysema_va1, ventilated_val=self.ventilated_val,\n poorly_vent_val=self.poorly_vent_val, atelectatic_val=self.atelectatic_val)\\\n .binary_map().pat_obj.lungs_bin_map\n if hasattr(pat_obj, 'bones_bin_map') is False or bones_threshold != self._bones_thres:\n pat_obj.bones_bin_map = Bones(pat_obj, bones_threshold).binary_map().pat_obj.bones_bin_map\n if hasattr(pat_obj, 'tissues_bin_map') is False or tissues_threshold != self._tissues_thres:\n pat_obj.tissues_bin_map = Tissues(pat_obj, tissues_threshold).binary_map().pat_obj.tissues_bin_map\n if hasattr(pat_obj, 'fats_bin_map') is False or fats_threshold != self._fats_thres:\n pat_obj.fats_bin_map = Fats(pat_obj, fats_threshold).binary_map().pat_obj.fats_bin_map\n if hasattr(pat_obj, 'lungless_ct') is False:\n pat_obj.lungless_ct = LunglessCT(pat_obj).binary_map().pat_obj.lungless_ct\n\n if pat_obj.data_name == 'LTRC':\n print('\\nCreating Label Map [LTRC]')\n _ = self.LTRC_label_map(pat_obj)\n print('\\nLabel Map [LTRC] created\\n')\n elif pat_obj.data_name == 'UMM':\n print('\\nCreating Label Map [UMM]')\n _ = self.UMM_label_map(pat_obj)\n print('\\nLabel Map [UMM] created\\n')\n elif pat_obj.data_name == 'UKSH':\n print('\\nCreating Label Map [UKSH]')\n _ = self.UKSH_label_map(pat_obj)\n print('\\nLabel Map [UKSH] created\\n')\n return self\n\n @property\n def print_parameters(self):\n print(\"\\nEmphysema Values: {val}\".format(val=self.emphysema_va1))\n print(\"Ventilated Values: {val}\".format(val=self.ventilated_val))\n print(\"Poorly Vent Values: {val}\".format(val=self.poorly_vent_val))\n print(\"Atelectatic Values: {val}\".format(val=self.atelectatic_val))\n pass\n","sub_path":"Processing/PreProcess.py","file_name":"PreProcess.py","file_ext":"py","file_size_in_byte":14321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"115288513","text":"__author__ = 'User'\n\nfrom lxml import html\nimport requests\nimport re\nfrom nltk import pos_tag, word_tokenize\nimport nltk\nimport string\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nfrom math import log10\nimport time\n\n\"\"\"\nDear un-hebrew speakers:\n'Tmura' is 'Grammatical modifier': an element that describes the object in sentence.\nWe love the name 'Tmura', So we use it.\n\nfor example:\nwithout Tmura: Lummie and Arad study in Magshimim\nwith Tmura: Lummie and Arad study in Magshimim, The national cyber project\n\"\"\"\n\ndef cleanText(sen):\n for ch in string.punctuation:\n sentence = sentence.replace(ch, '')\n return sentence\n\n\n\"\"\"\nGets a sentence (that contains a tmura) and writes it into the tmura.txt file, so we will have a corpus\n\"\"\"\ndef writeToOurCorpus(sentence):\n text_file = open(\"tmura.txt\", \"a\")\n text_file.write(sentence + \"\\n\")\n text_file.close()\n\n\n\"\"\"\n Gets a word, finds its page in wordnet and downloades it. Returns a correct HTML document,\n which means the parent node is , and there is a body and possibly a head\n\"\"\"\ndef downloadPage(word):\n search = \"http://wordnetweb.princeton.edu/perl/webwn?s=\"\n search += word\n search += \"&sub=Search+WordNet&o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&h=0\" # Builds the url\n page = requests.get(search) # Get page\n return html.fromstring(page.content) # Fromstring creates the correct HTML document\n\n\"\"\"\n Gets a word, gets its html page in wordnet (using downloadPage(word)), and returns the tmura of the word.\n\"\"\"\ndef getTmura(word):\n tree = downloadPage(word) # Gets the page data\n words = tree.xpath(\"//div[@class='form']/ul/li/text()\") #Gets only the text\n theWord = []\n for i in words:\n if (i != ', '): # We want to take only the first tmura and to clear all of the ', '\n theWord = i\n break\n if (theWord != []): # If found a tmura\n theWord = theWord.split(';')[0].replace(\" (\", \"\") # Cleans the tmura from '(' and ')' in the first explenation\n theWord = theWord.split(';')[0].replace(\")\", \"\")\n return theWord\n else: # If didn't find a tmura\n return \"not found\"\n\n\n\"\"\"\n Gets a word, pharses it and finds it tmure. Gets only nouns!!!\n Returns the original word and the tmura- word: tmura\n\"\"\"\ndef findTmura(word):\n the_tmura = word + \": \" + getTmura(word.replace(\" \", \"+\"))\n #writeToOurCorpus(the_tmura) # Olny if we want to put it in our corpus\n return the_tmura\n\n\n\"\"\"\n It must be a class, so we can call it.\n\"\"\"\n\nclass Modifier(object):\n def change_sentence(self):\n text = nltk.tokenize.word_tokenize(self._sentence)\n changed = False\n for cur in nltk.pos_tag(text):\n if (cur[1] == \"NN\" or cur[1] == \"NNP\" or cur[1] == \"RPR\"):\n if getTmura(cur[0]) != \"not found\" and changed == False:\n rep = cur[0] + \", \" + getTmura(cur[0]) + \", \"\n self._sentence = self._sentence.replace(cur[0], rep)\n changed = True\n #print(\"Tmura: \", self._sentence)\n return self._sentence\n\n def __init__(self, sentence):\n \"\"\"\n :param word: sentence\n :return: sentence with tmura\n \"\"\"\n self._sentence = sentence\n return None\n\n\ndef main():\n with open(\"newSent.txt\", 'w') as newF:\n with open(\"sentences.txt\", 'r') as f:\n sentence = f.read()\n f.close()\n sentences = sentence.split('\\n')\n for sent in sentences:\n print(Modifier(sent).change_sentence)\n newF.write(Modifier(sent).change_sentence + \"\\n\")\n\n newF.close()\n\n #print change_sentence(\"Ryan started playing hockey at a very young age\")\n #sen = \"People who are brave and who take risks are more, successful-than people who are do things safely all the time\"\n #sen = cleanText(sen)\n #print sen\n\n\n\n#if __name__ == '__main__':\n # main()","sub_path":"Run/tmura.py","file_name":"tmura.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"389559221","text":"import sys\nimport os.path\nimport json\nimport traceback\n\n# userid-|--|-email-|-hash-|-hint-|--\n\ndef main():\n if len(sys.argv) <= 1:\n print(\"Not enough arguments; please specify the file you want to parse.\")\n return 1\n\n filename = sys.argv[1]\n \n if not os.path.isfile(filename):\n print (\"The file you provided does not exist.\")\n return 1\n\n with open(filename) as f:\n for line in f:\n line = line.strip()\n d = '-|-'\n\n # Some lines are empty, and some don't have proper formatting, so skip those\n if (len(line) == 0) or (d not in line):\n continue\n\n # Some lines are split over two lines for some reason, so we'll check\n # if the line ends with the terminating string, and if it doesn't,\n # grab the next line and concat it to the current one\n if not line.endswith('|--'):\n line += next(f).strip()\n\n try:\n print(BreachItem(line.split(d)[0], line.split(d)[2].lower(), line.split(d)[3], line.split(d)[4]).toJSON())\n except StopIteration:\n print(\"We seem to have reached the end of the file\", file=sys.stderr)\n print(traceback.format_exc())\n quit()\n except Exception as e:\n print(traceback.format_exc())\n print(line, file=sys.stderr)\n quit()\n\n return 0\n\nclass BreachItem:\n def __init__(self, user_id, email, password_encrypted_base64, hint):\n self.username = email if '@' not in email else '' \n self.alias = email.split('@')[0] if '@' in email else ''\n self.domain = email.split('@')[1] if '@' in email else ''\n self.password_encrypted_base64 = password_encrypted_base64\n self.hint = hint\n self.user_id = user_id\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, \n sort_keys=True)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"adobe.py","file_name":"adobe.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"600432196","text":"import turtle\nimport winsound\n\nfrom playsound import playsound\n\nwn = turtle.Screen()\nwn.title(\"Pong\")\nwn.bgcolor(\"black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\n\n# left paddle\npaddle_left = turtle.Turtle()\npaddle_left.speed(0)\npaddle_left.shape(\"square\")\npaddle_left.color(\"red\")\npaddle_left.shapesize(stretch_wid=5, stretch_len=1)\npaddle_left.penup()\npaddle_left.goto(-350, 0)\n\n# right paddle\npaddle_right = turtle.Turtle()\npaddle_right.speed(0)\npaddle_right.shape(\"square\")\npaddle_right.color(\"blue\")\npaddle_right.shapesize(stretch_wid=5, stretch_len=1)\npaddle_right.penup()\npaddle_right.goto(350, 0)\n\n# Ball\nball = turtle.Turtle()\nball.speed(0)\nball.shape(\"square\")\nball.color(\"white\")\nball.penup()\nball.goto(0, 0)\nball.dx = 0.2\nball.dy = -0.2\n\n# Score\nscore_p1 = 0\nscore_p2 = 0\n# pen\npen = turtle.Turtle()\npen.speed(0)\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0, 260)\npen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n\n# Movements\ndef paddle_left_up():\n y = paddle_left.ycor()\n y += 20\n paddle_left.sety(y)\n\ndef paddle_left_down():\n y = paddle_left.ycor()\n y -= 20\n paddle_left.sety(y)\n\ndef paddle_right_up():\n y = paddle_right.ycor()\n y += 20\n paddle_right.sety(y)\n\ndef paddle_right_down():\n y = paddle_right.ycor()\n y -= 20\n paddle_right.sety(y)\n\n# Keyboard binding\nwn.listen()\nwn.onkeypress(paddle_left_up, \"w\")\nwn.onkeypress(paddle_left_down, \"s\")\nwn.onkeypress(paddle_right_up, \"p\")\nwn.onkeypress(paddle_right_down, \"l\")\n\n# Main game loop\nwhile True:\n wn.update()\n # ball\n ball.setx(ball.xcor() + ball.dx)\n ball.sety(ball.ycor() + ball.dy)\n # border\n if ball.ycor() > 290:\n ball.sety(290)\n ball.dy *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.ycor() < -290:\n ball.sety(-290)\n ball.dy *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.xcor() > 390:\n ball.setx(390)\n ball.dx *= -1\n score_p1 += 1\n pen.clear()\n pen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.xcor() < -390:\n ball.setx(-390)\n ball.dx *= -1\n score_p2 += 1\n pen.clear()\n pen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n\n # paddle and ball\n if (ball.xcor() >340 and ball.xcor() < 350) and (ball.ycor() < paddle_right.ycor() + 50 and ball.ycor() >paddle_right.ycor()-50):\n ball.setx(340)\n ball.dx *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n\n if (ball.xcor() <-340 and ball.xcor() > -350) and (ball.ycor() < paddle_left.ycor() + 50 and ball.ycor() >paddle_left.ycor()-50):\n ball.setx(-340)\n ball.dx *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)","sub_path":"Pong.py","file_name":"Pong.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"577735662","text":"import dash_ace_editor\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_html_components as html\n\napp = dash.Dash(__name__)\n\napp.scripts.config.serve_locally = True\napp.css.config.serve_locally = True\n\napp.layout = html.Div([\n dash_ace_editor.DashAceEditor(\n id='input',\n value='select * from my_table;',\n customCompletion=[{'name':\"jakies_dlugie_pole\", 'type':'table'},\n {'name':\"bar\", 'type':'field'},\n {'name':\"baz\", 'type':'custom'}]\n ),\n html.Div(id='output')\n], style={'width':'400px'})\n\n@app.callback(Output('output', 'children'), [Input('input', 'value')])\ndef display_output(value):\n return 'You have entered {}'.format(value)\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"usage.py","file_name":"usage.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}