diff --git "a/1557.jsonl" "b/1557.jsonl" new file mode 100644--- /dev/null +++ "b/1557.jsonl" @@ -0,0 +1,754 @@ +{"seq_id":"474968809","text":"import unittest\n\nimport mock\nimport numpy as np\nimport os.path as osp\nimport tempfile\n\nfrom chainer import testing\n\nfrom chainercv.extensions import DetectionVisReport\nfrom chainercv.utils import ConstantReturnModel\nfrom chainercv.utils import DummyDataset\n\ntry:\n import matplotlib # NOQA\n optional_modules = True\nexcept ImportError:\n optional_modules = False\n\n\n@testing.parameterize(\n {'bbox_shape': (3, 4), 'label_shape': (3,)},\n {'bbox_shape': (0, 4), 'label_shape': (0,)},\n)\nclass TestDetectionVisReport(unittest.TestCase):\n\n indices = [0, 1]\n\n def setUp(self):\n self.trainer = mock.MagicMock()\n self.out_dir = tempfile.mkdtemp()\n self.trainer.out = self.out_dir\n self.trainer.updater.iteration = 0\n\n model = ConstantReturnModel(\n (np.random.uniform(size=(1,) + self.bbox_shape),\n np.random.uniform(size=(1,) + self.label_shape)))\n dataset = DummyDataset(\n shapes=[(3, 10, 10), self.bbox_shape, self.label_shape],\n dtypes=[np.float32, np.float32, np.int32])\n\n self.extension = DetectionVisReport(\n self.indices, dataset, model,\n filename_base='detection')\n\n def test_call(self):\n self.extension(self.trainer)\n if optional_modules:\n for idx in self.indices:\n file_name = osp.join(\n self.out_dir, 'detection_idx={}_iter=0.jpg'.format(idx))\n self.assertTrue(osp.exists(file_name))\n\n\ntesting.run_module(__name__, __file__)\n","sub_path":"tests/extensions_tests/detection_tests/test_detection_vis_report.py","file_name":"test_detection_vis_report.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"113492439","text":"__author__ = 'yk3274'\n\nfrom collections.abc import Iterable\n\n\nclass Extractor(Iterable):\n \"\"\"\n Extraction Algorithm.\n This class uses iterators and predicated to yield a set of matching values.\n It has a dual role:\n -> When only one predicate is given, the extractor has the same role as the\n built-in filter() function.\n -> When instantiated with two predicates, the extractors matches the whole\n data against the values filtered by the first predicate, in a way that is\n defined by the second.\n \"\"\"\n\n def __init__(self, data, pred_match, pred_join=None):\n \"\"\"Extractor instantiation.\n Params:\n -> data : Must be an iterable\n if pred_join is defined at instantiation,\n data MUST be a multiple-pass ITERATOR (list, range, ...)\n Raises AttributeError otherwise.\n\n -> pred_match : a one argument predicate\n pred_match is used to build a list of matching values,\n in the same way as the built-in filter() function\n\n -> pred_join : a two-argument predicate\n pred_join is used to match the filtered data (given by pred_match)\n with the data in the following manner:\n EVERY DATA ELEMENT MATCHING AN ELEMENT IN THE FILTERED SET ACCORDING\n TO PRED_JOIN WILL NOT BE EXTRACTED\n \"\"\"\n\n self.data = data\n self.ref_data = filter(pred_match, data) # A gen is sufficient if no pred_join defined\n self.pred = pred_join\n\n if self.pred and list(self.data) != list(self.data): # Ensure multi-path iteration\n msg = \"Multi-pass iterators only. Here: {!r}\".format(self.data)\n raise TypeError(msg)\n\n def __iter__(self):\n # Extractor implements the Iterable abc.\n # Overloading __iter__ is enough, as the underlying\n # functions make generators.\n\n if self.pred:\n return self.__iter_join()\n else:\n return self.__iter_simple()\n\n def __iter_join(self):\n\n self.ref_data = list(self.ref_data) # Un-lazify ref_data as multiple iterations will be necessary\n\n for dt in self.data:\n matching = False\n for rd in self.ref_data:\n if self.pred(dt, rd): # We extract from data so we can compare from it, hence order\n matching = True\n break\n if not matching: # If there is at least one matching element\n yield dt\n\n def __iter_simple(self):\n # the filtering has already been made and is stored in memory\n\n for rd in self.ref_data:\n yield rd\n","sub_path":"pyextract/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571981039","text":"import numpy as np\nimport json\n\n\ndef parse(filename: str) -> tuple[np.ndarray, np.ndarray]:\n with open(filename) as f:\n data = json.load(f)\n n = len(data)\n dimensions = len(data[0]['position'])\n\n m = np.zeros(n)\n y = np.zeros((2 * n, dimensions))\n x = y[:n]\n p = y[n:]\n\n for i in range(n):\n m[i] += data[i]['mass']\n x[i] += data[i]['position']\n\n if 'velocity' in data[i]:\n p[i] += data[i]['velocity']\n p[i] *= m[i]\n else:\n p[i] += data[i]['momentum']\n\n return y, m\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365288208","text":"import numpy as np\nfrom scipy import stats\nimport math\n\ndef compute_conf_interval(data, \n interval = 0.95, \n method = 't'):\n series = data \n mean_val = series.mean()\n n = series.count()\n stdev = series.std()\n if method == 't':\n test_stat = stats.t.ppf((interval + 1)/2, n)\n elif method == 'z':\n test_stat = stats.norm.ppf((interval + 1)/2)\n \n lower_bound = mean_val - test_stat * stdev / math.sqrt(n)\n upper_bound = mean_val + test_stat * stdev / math.sqrt(n)\n \n print(f'Lower limit: {lower_bound}\\n Upper limit: {upper_bound}')\n\n#import pandas as pd\n#\n#df = pd.read_csv('sample_dataframe.csv')\n#compute_conf_interval(df['x1'])","sub_path":"compute_conf_interval.py","file_name":"compute_conf_interval.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"337986292","text":"import sys \ndef rotate(argv):\n filename1=sys.argv[1]\n filename2=sys.argv[2]\n matrix1=read(filename1)\n matrix2=read(filename2)\n x=(len(matrix1))\n count=0\n matrixnew=[[]for i in range(x)]\n for num1 in range(x):\n for num2 in range(x):\n matrixnew[num1].append(0)\n return(rotate_append(matrix1,matrix2,x,count))\n\n\n\n \n \ndef rotate_append(matrix1,matrix2,x,count):\n matrixnew=[[]for i in range(x)]\n for num1 in range(x):\n for num2 in range(x):\n matrixnew[num1].append(0)\n for num in range(3):\n for i in range(x):\n for j in range(x):\n matrixnew[j][x-i-1]=matrix1[i][j]\n if matrixnew==matrix2:\n return True\n else:\n count+=1\n if count==4:\n return False\n else:\n return(rotate_append(matrixnew,matrix2,x,count))\n\ndef read(filename):\n inputfile = open(filename,\"r\")\n data1=inputfile.read()\n data_list=[]\n data_list =data1.split()\n a=[]\n matrix=[]\n for i in data_list:\n a=i.split(\",\")\n c=[int(x) for x in a]\n matrix.append(c)\n return matrix\n\n\nprint(rotate(sys.argv))\n","sub_path":"Other/lab6/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229622770","text":"\r\n# stats_text module\r\nimport re\r\ndef stats_text_en(text, count): #在第八天基础上那个增加count控制输出\r\n from collections import Counter #调用Counter计算器\r\n if not isinstance(text, str):\r\n raise ValueError('input data is not string type!,again!')\r\n text = text.replace(',','').replace('.','').replace('--','').replace('*','').replace('!','')#讲非英文字符转化为空\r\n text = text.lower()#将所有英文字符改为小写\r\n text = text.split()#以空格拆分独立的单词\r\n #count = int(count) #增加一个int类型变量count\r\n dir1 = {}\r\n for i in text: #将字符转换为字典\r\n count = text.count(i)\r\n r1 = {i:count}\r\n dir1.update(r1)\r\n\r\n # dir2 = sorted(dir1.items(),key = lambda x:x[1],reverse = True)\r\n #dir2 = Counter(dir1).most_common(count) #按词频排序并用count控制输出\r\n #print(dir2)\r\n\r\n\r\nimport jieba\r\ndef stats_text_cn(text, count): #在第八天基础上那个增加count控制输出\r\n from collections import Counter #调用Counter计算器\r\n if not isinstance(text, str):\r\n raise ValueError('input data is not string type!')\r\n text = text.replace('\\n','').replace(',','').replace('、','').replace(' ','').replace('\"\"','')#删掉换行符,逗号,顿号,空格\r\n text = re.sub('[^\\u4e00-\\u9fa5]','',text)\r\n text = jieba.lcut(text)\r\n text1 =[]\r\n for i in text:\r\n if len(i) >= 2:\r\n text1.append(i)\r\n count = int(count) #增加一个int类型变量count\r\n #b1 = {} \r\n #for i in text: #由字符生成字典\r\n # b1.update({i: text.count(i)})\r\n\r\n #b2 = sorted(b1.items(),key = lambda x:x[1],reverse = True)\r\n b2 = Counter(text1).most_common(count) #按词频排序并用count控制输出\r\n print(b2)\r\n\r\n\r\ndef stats_text(text, count):\r\n from collections import Counter #调用Counter计算器\r\n if not isinstance(text, str):\r\n raise ValueError('input data is not string type!')\r\n stats_text_en(text, count) #统计英文单词\r\n stats_text_cn(text, count) #统计中文单词","sub_path":"exercises/1901040027/d10/mymodule/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"650572159","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom article import views as article_views\n\nurlpatterns = [\n url(r'^1/', article_views.basic_one, name='basic_one'),\n url(r'^2/', article_views.template_two, name='template_two'),\n url(r'^3/', article_views.template_three_simple, name='template_three'),\n url(r'^articles/all/$', article_views.articles, name='articles'),\n url(r'^articles/get/(?P\\d+)/$', article_views.article, name='article'),\n url(r'^articles/addlike/(?P\\d+)/$', article_views.addlike, name='addlike'),\n url(r'^articles/addcomment/(?P\\d+)/$', article_views.addcomment, name='addcomment'),\n url(r'^page/(\\d+)/$', article_views.articles, name='articles'),\n url(r'^category/get/(?P\\d+)/$', article_views.article_cat, name='article_cat'),\n url(r'^keyword/(?P\\d+)/$', article_views.keywords, name='keywords'),\n url(r'^$', article_views.articles, name='articles'),\n\n]\n\nif settings.DEBUG:\n if settings.MEDIA_ROOT:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n urlpatterns += staticfiles_urlpatterns()","sub_path":"article/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"159972401","text":"# Source: https: // www.youtube.com/watch?v = W8KRzm-HUcc & list = PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7 & index = 4\n\n# lits and tuples : aloows to work with sequencial data\n# Sets: unorder collection of data with no duplicate\n\ncources = ['History', 'math', 'physics', 'comSci']\nnum = [1, 4, 2, 5, 6]\n# print(cources)\n# print(len(cources))\n# print(cources[1])\n# print(cources[-1])\n# print(cources[4])\n# print(cources[1:3])\n\n# cources.append('Art')\n# print(cources)\n\n# cources.insert(1, 'I am second')\n# print(cources)\n\n# print(cources)\n# print(cources.append([\"AA\", \"BB\"])) #append obejct to end\n# print(cources)\n# print(cources.extend([\"C\", \"D\"]))\n# print(cources)\n\n# print(cources)\n# cources.remove('math')\n# print(cources)\n# cources.pop(1)\n# print(cources)\n# popped_item = cources.pop() #remove and return the item\n# print(popped_item)\n\n\n# print(cources)\n# cources.reverse()\n# print(cources)\n# cources.sort()\n# print(cources)\n\n# print(cources, num)\n# cources.sort(reverse=True)\n# num.sort(reverse=True)\n# print(cources, num)\n# sorted_list = sorted(cources)\n# print(sorted_list)\n\n# print(min(num), max(num), sum(num))\n\n# print(cources.index('physics'))\n# print(cources.index('Not in list'))\n\n# print('math' in cources)\n# print('I am not in cosurces' in cources)\n\n# for i in cources:\n# print(i)\n\n# for index, course in enumerate(cources, start=2):\n# print(index, course)\n\n# cources_strn = '-'.join(cources)\n# print(cources_strn)\n# new_list = cources_strn.split('-')\n# print(new_list)\n\n\n# TUPLES\n# tuples are very similar to list but one major diff is we can't modify tuples. tuples are immutable\n\n# list1 = ['history', 'physics', 'chemisty', 'english']\n# list2 = list1\n\n# list1[0] = 'I am changed'\n# print(list1)\n# print(list2)\n\n# tup1 = ('history', 'physics', 'chemisty', 'english')\n# tup2 = tup1\n# tup1[0] = 'I will not change anymore'\n# print(tup1)\n# print(tup2)\n\n\n# # Sets\n# cs_cources = {'data science', 'data structers',\n# 'machine learining', 'cloud computing'}\n\n# cs_cources_new = {'data science', 'data structers',\n# 'machine learining', 'cloud computing', 'data science', 'machine learining'} # remove duplicate\n# print(cs_cources)\n\n# # sets used to test if the value is as part of a set. lists and tuples will also do that but sets are more effecient in doing that\n# print('machine learining' in cs_cources_new)\n\n\ncs_cources = {'data science', 'data structers',\n 'machine learining', 'cloud computing'}\ncs_cources_others = {'data science', 'Artificial intellegence',\n 'machine learining', 'netowrk automation'}\n\nprint(cs_cources.intersection(cs_cources_others))\n# In cs course not in cs_course_others\nprint(cs_cources.difference(cs_cources_others))\nprint(cs_cources.union(cs_cources_others))\n\n\n# creating empty list, tuples and sets\n\n# Empty lists\nl1 = []\nl2 = list()\n\n# Empty tuples\nt1 = ()\nt2 = tuple()\n\n# Empty sets\nst1 = {} # this is not correct. It is actually an dictionary\nst2 = set()\n","sub_path":"PythonMacProgramme/2020_Python/CoreyAgain/List_tuples_sets.py","file_name":"List_tuples_sets.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"377819056","text":"import logging\n\nfrom django.db import transaction\nfrom rest_framework import serializers\n\nfrom api.v1.serializers import ReadOnlyModelSerializer\nfrom address.models import Region, Address\n\nREGION_KEY = 'region'\n\nlogger = logging.getLogger('api.v1.address.serializers')\n\n\nclass RegionSerializer(serializers.ModelSerializer):\n \"\"\"\n For GET/POST only\n \"\"\"\n class Meta:\n model = Region\n fields = (\n 'name',\n 'code',\n 'country',\n )\n # disable the default validators, as they include the unique_together validator, which kills us as we\n # simply reuse if existing.\n validators = []\n\n def create(self, validated_data):\n region = Region.objects.filter(code=validated_data['code'], country=validated_data['country']).first()\n if region is None:\n region = super(RegionSerializer, self).create(validated_data)\n return region\n\n def update(self, instance, validated_data):\n raise Exception(\"Not a valid operation.\")\n\n\nclass AddressSerializer(ReadOnlyModelSerializer):\n \"\"\"\n For Read (GET) requests only\n \"\"\"\n region = RegionSerializer()\n\n class Meta:\n model = Address\n exclude = ('id',)\n\n\nclass AddressUpdateSerializer(serializers.ModelSerializer):\n \"\"\"\n For Update (PUT/POST) requests only\n \"\"\"\n region = RegionSerializer()\n\n class Meta:\n model = Address\n fields = (\n 'address',\n 'post_code',\n REGION_KEY,\n 'global_id',\n )\n\n @transaction.atomic\n def create(self, validated_data):\n region_ser = RegionSerializer(data=validated_data.pop(REGION_KEY))\n region_ser.is_valid(raise_exception=True)\n validated_data[REGION_KEY] = region_ser.save()\n return super(AddressUpdateSerializer, self).create(validated_data)\n","sub_path":"api/v1/address/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"470984440","text":"#! /usr/bin/\n\nif __name__ == \"__main__\" :\n import sys, os, subprocess, time\n sys.path.append(\"/Users/nil/.talkeron/Actions/Common\")\n import utils \n \n print(\"Execution of latexcard.py started.\")\n \n success, workPos, parasDic = utils.handle_sys_argv(sys.argv)\n \n if success is not True : \n exit(1)\n \n takeronHome = parasDic.get(\"talkeron\", None)\n cardDir = parasDic.get(\"directory\", None)\n cardName = parasDic.get(\"cardname\", None)\n \n if cardDir is not None and os.path.isdir(cardDir) :\n print(\"Card directory: \", cardDir)\n else :\n print(\"Exit. [Input parameter \\\"directory\\\" is missing or inavailable.]\")\n exit(1)\n\n cardPath = cardDir + \"/\" + time.strftime(\"%y%m%d%H%M%S\") + \"-\" + cardName\n if cardPath is not None and not os.path.isdir(cardPath) :\n print(\"Card path: \", cardPath)\n else :\n print(\"Exit. [Card path : \" + cardPath + \" already exist.]\")\n exit(1)\n \n os.mkdir(cardPath)\n os.chdir(cardPath)\n \n with open(\"./\" + cardName + \".tex\", 'w') as f :\n f.write(\"\\\\documentclass{article}\\n\") \n f.write(\"\\\\usepackage[paperwidth=10.5cm,paperheight=7.4cm,top=0.2cm,bottom=0.2cm,left=0.5cm,right=0.5cm]{geometry}\\n\")\n \n # add configurations to the file \n \n f.write(\"%\\n\")\n f.write(\"%\\n\")\n f.write(\"\\\\usepackage{amsmath}%\\\\allowdisplaybreaks[4]\\n\")\n f.write(\"\\\\usepackage{amsthm}\\n\")\n f.write(\"\\\\usepackage{amsfonts}\\n\")\n f.write(\"\\\\usepackage{amssymb}\\n\")\n\n # add graphic configurations to the file \n\n f.write(\"\\\\usepackage{graphicx}\\n\")\n f.write(\"\\\\usepackage[sl]{caption}\\n\")\n f.write(\"\\\\usepackage{color}\\n\")\n\n # add algorithm configurations to the file \n \n f.write(\"\\\\usepackage{listings}\\n\")\n f.write(\"\\\\usepackage[ruled,vlined]{algorithm2e}\\n\")\n f.write(\"\\\\usepackage{hyperref}\\n\")\n f.write(\"\\\\hypersetup{colorlinks=true,linkcolor=blue,urlcolor=red,linktoc=all}\\n\")\n \n # sample definitions for newtheorem\n\n f.write(\"%\\n\")\n f.write(\"%\\n\")\n f.write(\"%\\\\newtheorem{theorem}{\\\\hskip\\\\parindent Theorem}\\n\")\n f.write(\"%\\\\newtheorem{lemma}{\\\\hskip\\\\parindent Theorem}\\n\")\n\n # sample definitions for newcommand\n\n f.write(\"%\\\\newcommand{\\\\abstractname}{abstract}\\n\")\n\n # sample definitions for symbols\n\n f.write(\"%\\\\newcommand{\\\\ftwo}{\\\\frac{1}{2}}\\n\")\n\n # personalized note form\n \n f.write(\"%\\n\")\n f.write(\"%\\n\")\n\n f.write(\"\\\\newcommand{\\\\ignore}[1]{}\\n\")\n f.write(\"\\\\newcounter{note}[section]\\n\")\n f.write(\"\\\\renewcommand{\\\\thenote}{\\\\thesection.\\\\arabic{note}}\\n\")\n f.write(\"\\\\newcommand{\\\\li}[1]{\\\\refstepcounter{note}$\\\\ll ${\\\\sf Li's Comment~\\\\thenote:}\\n\")\n f.write(\"{\\\\sf \\\\textcolor{blue}{#1}}$\\\\gg$\\\\marginpar{\\\\tiny\\\\bf LC~\\\\thenote}}\\n\")\n\n # begin the document\n\n f.write(\"\\\\begin{document}\\n\")\n f.write(\"\\n\")\n f.write(\"\\n\")\n f.write(\"\\\\rightline{\\\\small\\\\bf NiL,~~\\\\tt{csningli@gmail.com}}\\n\")\n f.write(\"\\\\vspace{0.1cm}\\n\")\n f.write(\"\\\\noindent {\\\\bf \" + cardName + \"}\\n\")\n f.write(\"\\\\vspace{0.1cm}\\n\")\n f.write(\"\\\\hrule height 2pt\\n\")\n f.write(\"\\\\vspace{0.1cm}\\n\")\n f.write(\"\\\\noindent Content here.\\n\")\n \n # end the document\n\n f.write(\"\\\\end{document}\\n\")\n\n # samples that does not appear\n\n # sample figure\n\n f.write(\"%\\n\") \n f.write(\"%\\n\")\n f.write(\"%\\\\begin{figure}[!htb]\\n\")\n f.write(\"%\\\\begin{minipage}[t]{0.8\\\\textwidth}\\n\")\n f.write(\"%\\\\centering\\n\")\n f.write(\"%\\\\includegraphics[width=0.3\\\\textwidth]{fig.pdf}\\n\")\n f.write(\"%\\\\caption{caption}\\n\") \n f.write(\"%\\\\label{fig}\\n\")\n f.write(\"%\\\\end{minipage}\\n\")\n f.write(\"%\\\\end{figure}\\n\")\n\n # sample algorithm\n\n f.write(\"%\\n\")\n f.write(\"%\\n\")\n f.write(\"%\\\\begin{algorithm}\\n\")\n f.write(\"%\\\\textbf{Initialization:} \\\\\\\\ \\n\")\n f.write(\"%\\\\nl $p(v) := q(v) := \\\\zeta$; \\\\\\\\ \\n\")\n f.write(\"%\\\\nl\t\\\\If{condition}{\\n\")\n f.write(\"%\\\\nl\t\tstatement; \\\\\\\\ \\n\") \n f.write(\"%}\\n\")\n f.write(\"%\\\\nl\t\\\\Else{\\n\") \n f.write(\"%\\\\nl\t\tstatement; \\\\\\\\ \\n\")\n f.write(\"%}\\n\")\n f.write(\"%\\\\vspace{0.2cm}\\n\")\n f.write(\"%\\\\nl\t\\\\lIf{condition}{statement;}\\n\")\n f.write(\"%\\n\")\n f.write(\"%\\\\caption{caption}\\n\")\n f.write(\"%\\\\label{algo}\\n\")\n f.write(\"%\\\\end{algorithm}\\n\")\n\n # sample listing\n\n f.write(\"%\\n\")\n f.write(\"%\\n\")\n f.write(\"%\\\\begin{lstlisting}[language=C++,frame=single,caption={caption}]\\n\")\n f.write(\"% statement\\n\")\n f.write(\"%\\\\end{lstlisting}\\n\")\n f.write(\"%\\\\lstinputlisting[language=C, firstline=1, lastline=10, numbers=left]{source.c}\\n\")\n\n # sample table\n\n f.write(\"%\\n\")\n f.write(\"%\\n\")\n f.write(\"%\\\\begin{table}[!htp]\\n\")\n f.write(\"%\\\\centering\\n\")\n f.write(\"%\\\\begin{tabular}{|c|c|}\\n\")\n f.write(\"%\\\\hline\\n\")\n f.write(\"% 1.0 & 1.0 \\\\\\\\ \\n\")\n f.write(\"% 1.0 & 1.0 \\n\")\n f.write(\"%\\\\hline\\n\")\n f.write(\"%\\\\end{tabular}\\n\")\n f.write(\"%\\\\caption{caption}\\n\")\n f.write(\"%\\\\label{tab}\\n\")\n f.write(\"%\\\\end{table}\\n\")\n \n print(\"Now you can edit the note.\")\n\n cmd = \"open \" + cardPath\n subprocess.call(cmd, shell = True)\n \n print(\"Done.\")\n","sub_path":"ext/Actions/Note/latexcard.py","file_name":"latexcard.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"26924561","text":"import pygame\nfrom pygame.locals import *\nclass balloon():\n \"\"\"docstring for balloon.\"\"\"\n def __init__(self, transform, img):\n self.transform = transform\n self.obj = img\n self.collider = pygame.Rect\\\n ( transform[0]\n , transform[1]\n , 154\n , 200)\n #\n def draw(self, SURF):\n #pygame.draw.ellipse(SURF,\n # (255, 255, 255),\n # self.obj, 5)\n SURF.blit(self.obj, self.transform)\n #\n def setTransform(self, arg):\n self.transform = arg\n self.collider.topleft = arg\n","sub_path":"guibox/aguibox.py","file_name":"aguibox.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"24046745","text":"from . import *\n\nimport pickle\n\nclass PickleModel(O.Model):\n a = Pickle()\n b = Pickle(list, strict=True)\n c = Pickle(int)\n d = Pickle(dict, ({'t': 1},))\n\nclass TestJSONFields(unittest.TestCase):\n def setUp(self):\n db.create_table('PickleModels', default_cols(a='blob', b='blob', c='blob', d='blob'))\n\n def tearDown(self):\n db.drop_table('PickleModels')\n\n def test_model_initialization(self):\n t1 = PickleModel()\n\n self.assertIs(t1.a, None)\n self.assertIsInstance(t1.b, list)\n self.assertIsInstance(t1.c, int)\n self.assertIsInstance(t1.d, dict)\n\n self.assertEqual(t1.b, [])\n self.assertEqual(t1.c, 0)\n self.assertEqual(t1.d, {'t': 1})\n\n def test_model_strict_changing_raises_TypeError(self):\n t1 = PickleModel()\n\n with self.assertRaises(TypeError):\n t1.b = 42\n\n def test_model_setting(self):\n t1 = PickleModel()\n\n t1.a = None\n t1.c = 2.3\n t1.d = False\n\n self.assertEqual(t1.a, None)\n self.assertEqual(t1.c, 2.3)\n self.assertEqual(t1.d, False)\n\n def test_saving_pickle_defaults(self):\n t1 = PickleModel()\n t1.save()\n\n result = QueryBuilder.table('PickleModels').first()\n\n self.assertEqual(result['a'], pickle.dumps(t1.a))\n self.assertEqual(result['b'], pickle.dumps(t1.b))\n self.assertEqual(result['c'], pickle.dumps(t1.c))\n self.assertEqual(result['d'], pickle.dumps(t1.d))\n\n def test_getting_loaded_picle(self):\n t1 = PickleModel()\n t1.save()\n\n first = PickleModel.first()\n\n self.assertEqual(first.a, None)\n self.assertEqual(first.b, [])\n self.assertEqual(first.d, {'t': 1})\n\n def test_setting_pure_bytes(self):\n t1 = PickleModel()\n t1.a = pickle.dumps([1,2,3])\n t1.save()\n\n result = QueryBuilder.table('PickleModels').first()\n\n self.assertEqual(result['a'], pickle.dumps([1,2,3]))","sub_path":"test/model_tests/test_pickle_column.py","file_name":"test_pickle_column.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"232312719","text":"\"\"\"\nInsert a node at a specific position in a linked list\n\nYou’re given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node.\n\nA position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.\n\nAs an example, if your list starts as and you want to insert a node at position with , your new list should be \n\nFunction Description Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list.\n\ninsertNodeAtPosition has the following parameters:\n\nhead: a SinglyLinkedListNode pointer to the head of the list\ndata: an integer value to insert as data in your new node\nposition: an integer position to insert the new node, zero based indexing\nInput Format\n\nThe first line contains an integer , the number of elements in the linked list.\nEach of the next lines contains an integer SinglyLinkedListNode[i].data.\nThe next line contains an integer denoting the data of the node that is to be inserted.\nThe last line contains an integer .\n\nConstraints\n\n, where is the element of the linked list.\n.\nOutput Format\n\nReturn a reference to the list head. Locked code prints the list for you.\n\nSample Input\n\n3\n16\n13\n7\n1\n2\nSample Output\n\n16 13 1 7\nExplanation\n\nThe initial linked list is 16 13 7. We have to insert at the position which currently has in it. The updated linked list will be 16 13 1 7\n\n\"\"\"\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\nclass SinglyLinkedListNode:\n def __init__(self, node_data):\n self.data = node_data\n self.next = None\n\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert_node(self, node_data):\n node = SinglyLinkedListNode(node_data)\n\n if not self.head:\n self.head = node\n else:\n self.tail.next = node\n\n self.tail = node\n\n\ndef print_singly_linked_list(node, sep, fptr):\n while node:\n fptr.write(str(node.data))\n\n node = node.next\n\n if node:\n fptr.write(sep)\n\n# Complete the insertNodeAtPosition function below.\n\n\n#\n# For your reference:\n#\n# SinglyLinkedListNode:\n# int data\n# SinglyLinkedListNode next\n#\n#\n\"\"\"\nUMPIRE:\n\nUnderstand: \n--> can we get an empty list? yes add it to the head.\n--> where do we add? we add at that specific position\n--> is this a singlely linked list ?\n--> what do we return?\n--> can we use extra space?\n--> do we return the list in place?\n\nmatch: -->POINTERS, rearrange\n -->iterate through\n\n\nplan: \n\n1. first we have to do a check for an empty list\n\nif head == None and position == 0:\n head = SinglyLinkedListNode(value)\n\n2. then we need to create a traversal loop that goes through the list looking for the correct index to stop at to make the change.\n\n3. then return the head \n\n\n\n\"\"\"\n\n\ndef insertNodeAtPosition(head, data, position):\n\n if head == None and position == 0:\n head = SinglyLinkedListNode(data)\n else:\n\n curr = head\n counter = 1\n\n while counter < position: # 16. 13 7. . insert 1\n curr = curr.next\n counter += 1\n print(curr.data)\n\n if curr.next != None:\n node = SinglyLinkedListNode(data)\n\n temp = curr.next\n curr.next = node\n node.next = temp\n else:\n curr.next = SinglyLinkedListNode(data)\n\n return head\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n llist_count = int(input())\n\n llist = SinglyLinkedList()\n\n for _ in range(llist_count):\n llist_item = int(input())\n llist.insert_node(llist_item)\n\n data = int(input())\n\n position = int(input())\n\n llist_head = insertNodeAtPosition(llist.head, data, position)\n\n print_singly_linked_list(llist_head, ' ', fptr)\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"LinkedLists/HackerrankInsertNodeAtASpecificPositionInALinkedlist.py","file_name":"HackerrankInsertNodeAtASpecificPositionInALinkedlist.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"367957589","text":"import matplotlib.pyplot as plt # 파이썬의 라이브러리 matplotlib 함수 사용\r\nfrom matplotlib.widgets import Button #matplotlib 함수의 widget 에서 Button import\r\n\r\nx=list(range(0,11)) # 임의로 차트값을 주었습니다\r\ny= list(range(0,110,10))\r\n\r\nfig,ax=plt.subplots()\r\nplt.subplots_adjust(left=0.1,bottom=0.3)\r\np,=plt.plot(x,y,lw=2)\r\n\r\n\r\nclass index (object): #class 로 선굵기 증가 감소 함수 이벤트 묶기\r\n a=0\r\n def plus(self,event):\r\n self.a+=1\r\n p.set_linewidth(1+self.a) \r\n \r\n def minus(self,event):\r\n self.a-=1\r\n p.set_linewidth(1+self.a)\r\n\r\n \r\ncallback=index() #버튼 이벤트를 계속 쓰기 위해 index 함수 callback 과 버튼 디자인\r\naxButton1 =plt.axes([0.1,0.1,0.1,0.1])\r\nbtn1=Button(axButton1,label='+')\r\nbtn1.on_clicked(callback.plus)\r\naxButton2=plt.axes([0.3,0.1,0.1,0.1])\r\nbtn2=Button(axButton2,label='-')\r\nbtn2.on_clicked(callback.minus)\r\n \r\nplt.show()\r\n","sub_path":"form4-matplotlib.py","file_name":"form4-matplotlib.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"298155624","text":"'''\n问题描述:给出一棵二叉树,返回其节点值的前序遍历。\n\n示例:\n输入:{1,#,2,3}\n输出:[1,2,3]\n解释:\n1\n \\\n 2\n /\n3\n它将被序列化为{1,#,2,3}\n前序遍历\n\n思路:递归遍历即可\n\n'''\n\n\nclass Solution:\n \"\"\"\n @param root: A Tree\n @return: Preorder in ArrayList which contains node values.\n \"\"\"\n\n def preorderTraversal(self, root):\n # write your code here\n # 用于存储结点œ\n self.output = []\n # 对根节点递归调用遍历 ‘\n self.traverse(root)\n return self.output\n\n def traverse(self, node):\n if node != None:\n self.output.append(node.val)\n self.traverse(node.left)\n self.traverse(node.right)\n return","sub_path":"66_done.py","file_name":"66_done.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"488904814","text":"#46 permutations/\nclass Solution(object):\n def perImp(self, res, cur_res, nums, select, idx):\n if idx == len(cur_res):\n res.append([x for x in cur_res])\n return\n if idx > len(cur_res):\n return\n for i in range(len(nums)):\n if select[i] == False:\n select[i] = True\n cur_res[idx] = nums[i]\n self.perImp(res, cur_res, nums, select, idx+1)\n select[i] = False\n\n\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n select =[False for x in nums]\n res = []\n cur_res = [0 for x in nums ]\n self.perImp(res, cur_res, nums, select, 0)\n return res\n","sub_path":"46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456511559","text":"from cpc.cpc import *\r\nimport time\r\nimport board\r\nfrom digitalio import DigitalInOut, Direction, Pull\r\n\r\nspi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)\r\ncs = DigitalInOut(board.radioCS)\r\ngdo0 = DigitalInOut(board.WAKE)\r\nbytelength = 4\r\nbitlength = bytelength*8\r\nrx = CC1101(spi, cs, gdo0, 50000, 434423000, \"30B6\")\r\ntx = CC1101(spi, cs, gdo0, 50000, 434423000, \"30B6\")\r\nstarthz = 434300000\r\nrange = 100000\r\nstep = 1000\r\n# sweep = CC1101(spi, cs, gdo0, 50000, starthz, \"0000\")\r\n# SPI object, Chip Select Pin, baudrate, frequency in Hz, Syncword\r\n\r\ndef byte(numstr):\r\n\tif len(numstr) > bitlength:\r\n\t\treturn numstr[len(numstr)-bitlength,len(numstr)-1]\r\n\tif len(numstr) == bitlength:\r\n\t\treturn numstr\r\n\tif numstr[0] == \"0\":\r\n\t\treturn (bitlength-len(numstr))*\"0\" + numstr\r\n\treturn (bitlength-len(numstr))*\"1\" + numstr\r\n\r\n#text = open(\"test.txt\",\"w\")\r\ndef invert(string,index):\r\n\tif string[index] == \"1\":\r\n\t\treturn \"0\"\r\n\telse:\r\n\t\treturn \"1\"\r\n\r\ndef replace(str,index,char):\r\n\treturn str[0:index] + char + str[index+1:-1]\r\ndef bitpp(bit):\r\n\ttemp = bit2int(bit)\r\n\treturn int2bits(temp + 1)\r\ndef twocomp(bit):\r\n\tonecomp = \"\"\r\n\tfor i in range(0,len(bit)):\r\n\t\tonecomp += invert(bit,i)\r\n\treturn bitpp(onecomp)\r\ndef bit2int(bit):\r\n\tneg = 1\r\n\tif bit[0] == \"1\":\r\n\t\tbit = twocomp(bit)\r\n\t\tneg = -1\r\n\tout = 0\r\n\texp = 0\r\n\tfor i in range(len(bit) - 1, 0, -1):\r\n\t\tif bit[i] == \"1\":\r\n\t\t\tout += int(2 ** exp)\r\n\t\texp += 1\r\n\treturn out*neg\r\ndef int2bits(num):\r\n\tout = \"\"\r\n\tfor i in range(bitlength):\r\n\t\tif int(2**i) & num == 0:\r\n\t\t\tout = \"0\" + out\r\n\t\telse:\r\n\t\t\tout = \"1\" + out\r\n\treturn out\r\n\r\n# Built in LEDs\r\nled = DigitalInOut(board.LED)\r\nled.direction = Direction.OUTPUT\r\nled.value = 0\r\ntimeout = 5000\r\ndef send(data):\r\n\ttx.setupTX()\r\n\ttx.setupCheck()\r\n\ttx.sendData(data, \"30B6\")\r\ndef get(obj):\r\n\tobj.setupRX()\r\n\tobj.setupCheck()\r\n\tdata = obj.receiveData(bytelength,timeout)\r\n\treturn data\r\ndata = byte(\"01\")\r\nwhile True:\r\n\ttry:\r\n\t\tdata = get(rx)\r\n\t\tdata = bitpp(data)\r\n\t\tprint(\"count = \" + str(bit2int(data)))\r\n\texcept ZeroDivisionError:\r\n\t\tprint(\"Timeout, try again\")\r\n\tsend(data)\r\n# Sweep frequency\r\n\r\n# while True:\r\n# \tfor freq in range(starthz+step,starthz+range,step):\r\n# \t\ttry:\r\n# \t\t\tdata = get(sweep)\r\n# \t\t\tprint(\"count = \" + str(bit2int(data)))\r\n# \t\texcept ZeroDivisionError:\r\n# \t\t\tprint(\"Timeout, try again\")\r\n#\r\n# \t\tsweep.setFrequency(freq,0)","sub_path":"software/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"542395447","text":"# 6th December 2016\n\nfrom DataSet import DataSet\nfrom sklearn import linear_model, datasets\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n\n''' Preamble '''\nL1 = False\nPCA_F = True\n\n''' Prepare Data '''\n\n# Variables\ndata = DataSet.load_data_set('Split Data_Standard-&-Specto_12-09-2016')\ndata_type = 'auto'\ny_label = ['Normal/Abnormal','Noise'] # 'Noise'\n\n# Data Preparation\ntest = data.testing[data_type]\ntrain = data.training[data_type]\nval = data.validation[data_type]\n\ntest_y = test[y_label].values.astype(float)#.ravel()\n# print('Test\\n')\n# DataSet.print_balance(test_y)\ntrain_y = train[y_label].values.astype(float)#.ravel()\n# print('Train\\n')\n# DataSet.print_balance(train_y)\nval_y = val[y_label].values.astype(float)#.ravel()\n# print('Val\\n')\n# DataSet.print_balance(val_y)\n\ntest_x = test[data.feature_names[data_type]].values.astype(float)\ntrain_x = train[data.feature_names[data_type]].values.astype(float)\nval_x = val[data.feature_names[data_type]].values.astype(float)\n\n# Balance DataSets\ntest_y,test_x = DataSet.balance_dataset_by_reproduction(test_y,test_x)\ntest_y_sound = test_y[:, 0].ravel()\ntest_y_noise = test_y[:, 1].ravel()\ntrain_y,train_x = DataSet.balance_dataset_by_reproduction(train_y,train_x)\ntrain_y_sound = train_y[:, 0].ravel()\ntrain_y_noise = train_y[:, 1].ravel()\nval_y,val_x = DataSet.balance_dataset_by_reproduction(val_y,val_x)\nval_y_sound = val_y[:, 0].ravel()\nval_y_noise = val_y[:, 1].ravel()\n\n''' L1 Feature Selection '''\nif L1:\n logreg = linear_model.LogisticRegression(penalty='l1',C=1)\n logreg.fit(train_x, train_y_sound)\n model = SelectFromModel(logreg, prefit=True)\n\n X_new = model.transform(train_x)\n\n print('Old Features: ')\n print(train_x.shape)\n print('New Features: ')\n print(X_new.shape)\n print('Coefficients: ')\n print(model.estimator.coef_)\n\n\n''' PCA Feature Selection '''\nif PCA_F:\n pca = PCA(n_components=20)\n pca.fit(train_x)\n print(pca.explained_variance_ratio_)\n\n plt.plot(pca.explained_variance_ratio_)\n plt.ylabel('PCA')\n plt.show()\n\n x_new = pca.transform(train_x)\n\n print(x_new.shape)\n\n","sub_path":"Python/Feature Selection.py","file_name":"Feature Selection.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"311898369","text":"import re\n\ndef getAmount(inFile):\n\n f = open(inFile,\"r\")\n Amount = \"((([0-9]+)\\.([0-9]+))|([0-9]+))\"\n ans = None\n for line in f:\n x = re.search(Amount, line)\n if x and findPattern(line) :\n ans = x.group()\n f.close()\n print(ans)\n return ans \n\ndef findPattern( line ):\n \n if re.search(r'Total',line,re.IGNORECASE) : return True \n # Add other such statements and don't forget to add ignoreCase \n return False; \n\nif __name__ == \"__main__\":\n getAmount(\"out_text.txt\")","sub_path":"python_files/attachment_processor/getAmount.py","file_name":"getAmount.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"508313724","text":"from uuid import uuid4\nfrom datetime import datetime, timedelta\nfrom sqlalchemy import Column, Text, Boolean, DateTime\n\nfrom .skygear_mixin import SkygearMixin\nfrom .base import Base\n\n\nCODE_VALIDITY_PERIOD = timedelta(minutes=5)\n\n\nclass EmailVerification(Base, SkygearMixin):\n __tablename__ = 'email_verification'\n revoked = Column(Boolean, nullable=False, default=False)\n email = Column(Text, nullable=False)\n code = Column(Text, nullable=False)\n expired_at = Column(DateTime, nullable=False)\n\n def __init__(self, email, code):\n current_time = datetime.utcnow()\n self.id = str(uuid4())\n self._created_at = current_time\n self._updated_at = current_time\n self.email = email\n self.code = code\n self.expired_at = current_time + CODE_VALIDITY_PERIOD\n","sub_path":"plugin/models/email_verification.py","file_name":"email_verification.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"479648230","text":"#!/usr/bin/env python3\n\n\n\"\"\"\nexpLoLer - explore LoL data\naaronjst93@gmail.com\n\"\"\"\n\n\nfrom multiprocessing import Lock\nfrom multiprocessing.pool import Pool\nfrom os import listdir\nfrom time import sleep\n\nimport json\nimport pickle\nimport requests\n\n\ndef api_get(endpoint: str, params: str = {}):\n \"\"\"Base GET request for the Riot Games API.\"\"\"\n\n params['api_key'] = ''\n\n url = 'https://na1.api.riotgames.com{}'.format(endpoint)\n\n response = requests.get(url, params=params)\n\n stdo_lock.acquire()\n print(response.url)\n stdo_lock.release()\n\n if response.status_code == requests.codes.ok:\n return response.json()\n else:\n stdo_lock.acquire()\n print(response.content)\n stdo_lock.release()\n\n if response.status_code >= 500:\n sleep(2)\n\n return api_get(endpoint, params)\n else:\n response.raise_for_status()\n\n\ndef get_seed_data():\n \"\"\"Get bulk seed data.\"\"\"\n\n for i in range(1, 11):\n url = ('https://s3-us-west-1.amazonaws.com/riot-developer-portal/seed-'\n 'data/matches{}.json').format(i)\n\n response = requests.get(url)\n\n if response.status_code == requests.codes.ok:\n json.dump(response.json(),\n open('seed/matches{}.json'.format(i), 'w'))\n else:\n response.raise_for_status()\n\n\ndef seed_accounts():\n \"\"\"Extract account_ids from seed match data.\"\"\"\n\n account_ids = []\n\n for i in range(1, 11):\n matches = json.load(\n open('seed/matches{}.json'.format(i), 'r'))['matches']\n\n for match in matches:\n for participant in match['participantIdentities']:\n account_ids.append(participant['player']['accountId'])\n\n account_ids = list(set(account_ids))\n\n print('Extracted {} unique accounts from seed match data.'.format(\n len(account_ids)))\n\n pickle.dump(account_ids, open('seed/account_ids.pickle', 'wb'))\n\n\ndef get_account_ids_from_match(*matches: dict):\n \"\"\"From an initial list of matches, find all account ids.\"\"\"\n\n account_ids = []\n\n for match in matches:\n for participant in match['participantIdentities']:\n account_ids.append(participant['player']['accountId'])\n\n return list(set(account_ids))\n\n\ndef get_matchlist(account_id: str, start_index: int = 0):\n \"\"\"Get a match list using provided ``account_id`` and ``start_index``.\n Recurse if total matches > ending index.\n \"\"\"\n\n params = {\n 'queue': 420, # Ranked 5v5 Solo-Queue\n 'beginIndex': start_index,\n 'season': 9 # 2017 Season\n }\n\n endpoint = '/lol/match/v3/matchlists/by-account/{}'.format(account_id)\n\n data = api_get(endpoint, params=params)\n\n match_ids = list(map(lambda x: x['gameId'], data['matches']))\n\n if data['endIndex'] < data['totalGames'] - 1:\n return match_ids + get_matchlist(account_id, data['endIndex'])\n else:\n stdo_lock.acquire()\n print('\\nAccount {} played {} matches in the 2017 season.\\n'.format(\n account_id, data['totalGames']))\n stdo_lock.release()\n\n return match_ids\n\n\ndef get_matches(*match_ids: int):\n \"\"\"Get full match data for matches corresponding to ``match_ids``.\"\"\"\n\n current_matches = map(int, listdir('spider/matches'))\n\n for mid in set(match_ids) - set(current_matches):\n if mid not in current_matches:\n match = None\n\n try:\n match = api_get('/lol/match/v3/matches/{}'.format(mid))\n except requests.exceptions.HTTPError:\n continue\n\n rw_lock.acquire()\n pickle.dump(match, open('spider/matches/{}'.format(mid), 'wb'))\n rw_lock.release()\n\n\ndef get_matches_for_account(account_id: int):\n \"\"\"Get matches for given ``account_id``.\"\"\"\n\n match_ids = None\n\n if account_id in map(int, listdir('spider/accounts')):\n rw_lock.acquire()\n match_ids = pickle.load(\n open('spider/accounts/{}'.format(account_id), 'rb'))\n rw_lock.release()\n else:\n try:\n match_ids = get_matchlist(account_id)\n except requests.exceptions.HTTPError:\n return\n\n rw_lock.acquire()\n pickle.dump(match_ids,\n open('spider/accounts/{}'.format(account_id), 'wb'))\n rw_lock.release()\n\n get_matches(*match_ids)\n\n\ndef initialize_locks(lock1: Lock, lock2: Lock):\n \"\"\"Initialize global locks for use by process pool.\"\"\"\n\n global rw_lock, stdo_lock\n\n rw_lock = lock1\n stdo_lock = lock2\n\n\ndef spider_matches(account_ids: list, degrees: int = 1):\n \"\"\"From an initial list of ``account_ids``, find relevant matches.\n Use new accounts found to additionally search for further matches\n when degrees > 1.\n \"\"\"\n\n if degrees < 1:\n raise ValueError('``degrees`` must be >= 1')\n\n # new_account_ids = set()\n\n lock1 = Lock()\n lock2 = Lock()\n\n pool = Pool(initializer=initialize_locks, initargs=(lock1, lock2))\n\n pool.imap_unordered(get_matches_for_account, account_ids)\n pool.close()\n pool.join()\n\n ''' # Rework to not use local ``new_account_ids``\n if degrees > 1:\n print('\\nFound {} new accounts, spidering to matches.\\n'.format(\n len(new_account_ids)))\n\n spider_matches(list(new_account_ids), degrees - 1)\n else:\n n_accounts = len(listdir('spider/accounts'))\n n_matches = len(listdir('spider/matches'))\n\n print('\\n\\nSpidered to {} accounts and {} matches.'.format(\n n_accounts, n_matches))\n '''\n\n\nif __name__ == '__main__':\n # get_seed_data()\n # seed_accounts()\n\n SUMMONERS = [\n 39016347, # HushRaze\n 39137330, # PowerK00K\n 39010660, # VanityDemon\n 35765317, # ILovePhoKingLOL\n 33662222, # 19970809\n 202637677 # Miss Nini\n ]\n\n ACCOUNTS = pickle.load(open('seed/account_ids.pickle', 'rb'))\n ACCOUNTS = list(set(ACCOUNTS + SUMMONERS))\n\n print('{} seed accounts'.format(len(ACCOUNTS)))\n\n spider_matches(ACCOUNTS)\n\n print('done')\n","sub_path":"expLoLer.py","file_name":"expLoLer.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"304700914","text":"from traitlets.config import Configurable\nfrom traitlets import (\n Int,\n List,\n Unicode,\n)\nimport numpy as np\nimport logging\nfrom event.arguments.prepare.event_vocab import load_vocab\n\n\nclass Resources(Configurable):\n \"\"\"\n Resource class.\n \"\"\"\n event_embedding_path = Unicode(help='Event Embedding path').tag(config=True)\n word_embedding_path = Unicode(help='Word Embedding path').tag(config=True)\n\n event_vocab_path = Unicode(help='Event Vocab').tag(config=True)\n word_vocab_path = Unicode(help='Word Vocab').tag(config=True)\n\n raw_lookup_path = Unicode(help='Raw Lookup Vocab.').tag(config=True)\n\n def __init__(self, **kwargs):\n super(Resources, self).__init__(**kwargs)\n self.event_embedding = np.load(self.event_embedding_path)\n self.word_embedding = np.load(self.word_embedding_path)\n\n self.event_vocab = self.__read_vocab(self.event_vocab_path)\n logging.info(\"%d events in vocabulary.\" % len(self.event_vocab))\n\n self.word_vocab = self.__read_vocab(self.word_vocab_path)\n logging.info(\"%d words in vocabulary.\" % len(self.word_vocab))\n\n self.lookups, self.oovs = load_vocab(self.raw_lookup_path)\n logging.info(\"Loaded lookup maps and oov words.\")\n\n def __read_vocab(self, vocab_file):\n vocab = {}\n with open(vocab_file) as din:\n index = 0\n for line in din:\n word, count = line.split()\n vocab[word] = index\n index += 1\n return vocab\n","sub_path":"event/arguments/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"81891971","text":"import tkinter as tk\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter.scrolledtext import *\r\nimport tkinter.filedialog\r\n\r\nimport time\r\ntimestr = time.strftime(\"%Y%m%d- %H%M%S\")\r\n\r\nfrom spacy_summarization import text_summarizer\r\nfrom nltk_summarization import nltk_summarizer\r\nfrom glove_summarization import summarize\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.request import urlopen\r\n\r\nwindow = Tk()\r\nwindow.title(\"Summaryzer GUI\")\r\nwindow.geometry('700x500')\r\n\r\n# Style\r\nstyle = ttk.Style(window)\r\n\r\nstyle.configure('lefttab.TNotebook', tabposition='wn')\r\n\r\n# Tabs\r\ntab_control = ttk.Notebook(window, style='lefttab.TNotebook')\r\n\r\ntab1 = ttk.Frame(tab_control)\r\ntab2 = ttk.Frame(tab_control)\r\ntab3 = ttk.Frame(tab_control)\r\ntab4 = ttk.Frame(tab_control)\r\ntab5 = ttk.Frame(tab_control)\r\n\r\n\r\n# Add tabs to notebook\r\ntab_control.add(tab1, text=f'{\"Home\":^20s}')\r\ntab_control.add(tab2, text=f'{\"File\":^20s}')\r\ntab_control.add(tab3, text=f'{\"URL\":^20s}')\r\ntab_control.add(tab4, text=f'{\"Comparer\":^20s}')\r\ntab_control.add(tab5, text=f'{\"About\":^20s}')\r\n\r\n# Labels\r\nlabel1 = Label(tab1, text=\"Summaryzer\", padx=5, pady=5)\r\nlabel1.grid(row=0, column=0)\r\nlabel1 = Label(tab2, text=\"File Processing\", padx=5, pady=5)\r\nlabel1.grid(row=0, column=0)\r\nlabel1 = Label(tab3, text=\"URL\", padx=5, pady=5)\r\nlabel1.grid(row=0, column=0)\r\nlabel1 = Label(tab4, text=\"Comparer\", padx=5, pady=5)\r\nlabel1.grid(row=0, column=0)\r\nlabel1 = Label(tab5, text = \"About\", padx=5, pady=5)\r\nlabel1.grid(row=0, column=0)\r\n\r\ntab_control.pack(expand=1, fill=\"both\")\r\n\r\n# Functions\r\ndef get_summary():\r\n raw_text = entry.get('1.0', tk.END)\r\n final_text = summarize(raw_text)\r\n print(final_text)\r\n result = '\\nSummary: {}'.format(final_text)\r\n tab1_display.insert(tk.END,result)\r\n\r\ndef save_summary():\r\n raw_text = entry.get('1.0', tk.END)\r\n final_text = summarize(raw_text)\r\n file_name = 'Yoursummary' + timestr + '.txt'\r\n with open(file_name, \"w\") as f:\r\n f.write(final_text)\r\n result = '\\nName Of File: {}, \\nSummary: {}'.format(file_name, final_text)\r\n tab1_display.insert(tk.END, result)\r\n\r\ndef clear_text():\r\n entry.delete('1.0', tk.END)\r\n\r\ndef clear_display_result():\r\n tab1_display.delete('1.0', tk.END)\r\n\r\n# Open files Functions\r\ndef open_files():\r\n file1 = tkinter.filedialog.askopenfilename(filetype=(('Text Files', \".txt\"), ('All Files', \"*\")))\r\n read_text = open(file1).read()\r\n displayed_file.insert(tk.END, read_text)\r\n\r\ndef get_file_summary():\r\n raw_text = displayed_file.get('1.0', tk.END)\r\n final_text = summarize(raw_text)\r\n result = '\\nSummary: {}'.format(final_text)\r\n tab2_display.insert(tk.END, result)\r\n\r\ndef clear_text_file():\r\n displayed_file.delete('1.0',tk.END)\r\n\r\ndef clear_text_results():\r\n tab2_display.delete('1.0', tk.END)\r\n\r\n\r\n# URL Functions\r\ndef get_text():\r\n\traw_text = str(url_entry.get())\r\n\tpage = urlopen(raw_text)\r\n\tsoup = BeautifulSoup(page)\r\n\tfetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\r\n\turl_display.insert(tk.END, fetched_text)\r\n\r\ndef get_url_summary():\r\n\traw_text = url_display.get('1.0', tk.END)\r\n\tfinal_text = summarize(raw_text)\r\n\tresult = '\\nSummary:{}'.format(final_text)\r\n\ttab3_display.insert(tk.END, result)\r\n\r\ndef clear_url_entry():\r\n url_entry.delete( 0, tk.END)\r\ndef clear_url_entry_box():\r\n url_display.delete( '1.0', tk.END)\r\n\r\ndef clear_url_display():\r\n tab3_display.delete('1.0', tk.END)\r\n\r\n\r\n# COMPARER FUNCTIONS\r\n\r\ndef use_spacy():\r\n\traw_text = str(entry1.get('1.0', tk.END))\r\n\tfinal_text = text_summarizer(raw_text)\r\n\t# print(final_text)\r\n\tresult = '\\nSpacy Summary:{}\\n'.format(final_text)\r\n\ttab4_display.insert(tk.END, result)\r\n\r\n\r\ndef use_nltk():\r\n\traw_text = str(entry1.get('1.0', tk.END))\r\n\tfinal_text = nltk_summarizer(raw_text)\r\n\t# print(final_text)\r\n\tresult = '\\nNLTK Summary:{}\\n'.format(final_text)\r\n\ttab4_display.insert(tk.END, result)\r\n\r\n\r\ndef use_glove():\r\n\traw_text = str(entry1.get('1.0', tk.END))\r\n\tfinal_text = summarize(raw_text)\r\n\t# print(final_text)\r\n\tresult = '\\nGlove Summary:{}\\n'.format(final_text)\r\n\ttab4_display.insert(tk.END, result)\r\n\r\ndef clear_compare_text():\r\n\tentry1.delete('1.0', END)\r\n\r\ndef clear_compare_display_result():\r\n\ttab1_display.delete('1.0', END)\r\n\r\n\r\n# Main home Tab\r\nl1 = Label(tab1, text=\"Enter Text To Summarize\", padx=5, pady=5)\r\nl1.grid(row=1,column=0)\r\nentry = ScrolledText(tab1, height=10)\r\nentry.grid(row=2, column=0, columnspan=2, padx=5, pady=5)\r\n\r\n# Buttons\r\nbutton1 = Button(tab1, text=\"Reset\", command=clear_text, width=12, bg=\"green\", fg=\"white\")\r\nbutton1.grid(row=4, column=0, padx=10, pady=10)\r\nbutton2 = Button(tab1, text=\"Summarize\", command=get_summary, width=12, bg=\"green\", fg=\"white\")\r\nbutton2.grid(row=4, column=1, padx=10, pady=10)\r\nbutton3 = Button(tab1, text=\"Clear Result\", command=clear_display_result, width=12, bg=\"green\", fg=\"white\")\r\nbutton3.grid(row=5, column=0, padx=10, pady=10)\r\nbutton4 = Button(tab1, text=\"Save\", command=save_summary,width=12, bg=\"green\", fg=\"white\")\r\nbutton4.grid(row=5, column=1, padx=10, pady=10)\r\n\r\n# Display screen for results\r\ntab1_display = ScrolledText(tab1, height=10)\r\ntab1_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\r\n\r\n\r\n\r\n# File Processing Tab\r\nl1 = Label(tab2, text=\"Open File To Summarize\", padx=5, pady=5)\r\nl1.grid(row=1, column=1)\r\ndisplayed_file = ScrolledText(tab2, height=10)\r\ndisplayed_file.grid(row=2, column=0, columnspan=2, padx=5, pady=5)\r\n\r\n# Buttons\r\nb1 = Button(tab2, text=\"Open File\", command=open_files,width=12, bg=\"green\", fg=\"white\")\r\nb1.grid(row=3, column=0, padx=10, pady=10)\r\nb2 = Button(tab2, text=\"Reset\", command=clear_text_file,width=12, bg=\"green\", fg=\"white\")\r\nb2.grid(row=3, column=1, padx=10, pady=10)\r\nb3 = Button(tab2, text=\"Summarize\", command=get_file_summary,width=12, bg=\"green\", fg=\"white\")\r\nb3.grid(row=3, column=2, padx=10, pady=10)\r\nb4 = Button(tab2, text=\"Clear results\", command=clear_text_results,width=12, bg=\"green\", fg=\"white\")\r\nb4.grid(row=5, column=1, padx=10, pady=10)\r\nb5 = Button(tab2, text=\"Close\", command=window.destroy)\r\nb5.grid(row=5, column=2, padx=10, pady=10)\r\n\r\n# Display screen for results\r\ntab2_display = ScrolledText(tab2, height=10)\r\ntab2_display.grid(row=7, column=0, columnspan=2, padx=5, pady=5)\r\n\r\n# Allows you to edit\r\ntab2_display.config(state=NORMAL) \r\n\r\n\r\n\r\n# URL Tab\r\nl1 = Label(tab3, text=\"Enter URL To Summarize\", padx=5, pady=5)\r\nl1.grid(row=1, column=0)\r\n\r\nraw_entry = StringVar()\r\nurl_entry = Entry(tab3, textvariable=raw_entry, width=50)\r\nurl_entry.grid(row=1, column=1)\r\n\r\n# Buttons\r\nb1 = Button(tab3, text=\"Reset\", command=clear_url_entry,width=12, bg=\"green\", fg=\"white\")\r\nb1.grid(row=4, column=0, padx=10, pady=10)\r\nb2 = Button(tab3, text=\"Get Text\", command=get_text,width=12, bg=\"green\", fg=\"white\")\r\nb2.grid(row=4, column=1, padx=10, pady=10)\r\nb3 = Button(tab3, text=\"Clear Result\", command=clear_url_display,width=12, bg=\"green\", fg=\"white\")\r\nb3.grid(row=5, column=0, padx=10, pady=10)\r\nb5 = Button(tab3, text=\"Clear\", command=clear_url_entry_box,width=12, bg=\"green\", fg=\"white\")\r\nb5.grid(row=6, column=0, padx=10, pady=10)\r\nb4 = Button(tab3, text=\"Summarize\", command=get_url_summary,width=12, bg=\"green\", fg=\"white\")\r\nb4.grid(row=5, column=1, padx=10, pady=10)\r\n\r\n# Display screen for results\r\nurl_display = ScrolledText(tab3, height=10)\r\nurl_display.grid(row=7, column=0, columnspan=2, padx=5, pady=5)\r\n\r\ntab3_display = ScrolledText(tab3, height=10)\r\ntab3_display.grid(row=10, column=0, columnspan=2, padx=5, pady=5)\r\n\r\n# COMPARER TAB\r\nl1 = Label(tab4, text=\"Enter Text To Summarize\")\r\nl1.grid(row=1, column=0)\r\n\r\nentry1 = ScrolledText(tab4, height=10)\r\nentry1.grid(row=2, column=0, columnspan=3, padx=5, pady=3)\r\n\r\n# BUTTONS\r\nbutton1 = Button(tab4, text=\"Reset\", command=clear_compare_text,width=12, bg='#03A9F4', fg='#fff')\r\nbutton1.grid(row=4, column=0, padx=10, pady=10)\r\n\r\nbutton2 = Button(tab4, text=\"SpaCy\", command=use_spacy, width=12, bg='#03A9F4', fg='#fff')\r\nbutton2.grid(row=4, column=1, padx=10, pady=10)\r\n\r\nbutton3 = Button(tab4, text=\"Clear Result\",command=clear_compare_display_result, width=12, bg='#03A9F4', fg='#fff')\r\nbutton3.grid(row=5, column=0, padx=10, pady=10)\r\n\r\nbutton4 = Button(tab4, text=\"NLTK\", command=use_nltk, width=12, bg='#03A9F4', fg='#fff')\r\nbutton4.grid(row=4, column=2, padx=10, pady=10)\r\n\r\nbutton4 = Button(tab4, text=\"Glove\", command=use_glove, width=12, bg='#03A9F4', fg='#fff')\r\nbutton4.grid(row=5, column=1, padx=10, pady=10)\r\n\r\n\r\n\r\n# variable = StringVar()\r\n# variable.set(\"SpaCy\")\r\n# choice_button = OptionMenu(tab4, variable, \"SpaCy\", \"Gensim\", \"Sumy\", \"NLTK\")\r\n# choice_button.grid(row=6, column=1)\r\n\r\n\r\n# Display Screen For Result\r\ntab4_display = ScrolledText(tab4, height=15)\r\ntab4_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\r\n\r\n# About TAB\r\nabout_label = Label(\r\n tab5, text=\" ML Project \\n Aditya Singh A-09 \\n Prathamesh Chaskar A-10\\n Shruti Rathod A-32\", pady=5, padx=5)\r\nabout_label.grid(column=0, row=1)\r\n\r\n\r\nwindow.mainloop()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"380735669","text":"\n\n#calss header\nclass _REHABILITATE():\n\tdef __init__(self,): \n\t\tself.name = \"REHABILITATE\"\n\t\tself.definitions = [u'to return someone to a good, healthy, or normal life or condition afterthey have been in prison, been very ill, etc.: ', u'to return something to a good condition: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_rehabilitate.py","file_name":"_rehabilitate.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"180713308","text":"from itertools import combinations\nimport itertools\nfrom random import *\nimport random\nimport pdb\nfrom lifelines.utils import concordance_index\nfrom sklearn import preprocessing\nimport functools\nimport random\nimport time\nimport pandas as pd\n\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data.distributed import DistributedSampler\n\nimport torch\nimport torch.nn as nn\nfrom models.gat import GATNet\nfrom models.gat_gcn import GAT_GCN\nfrom models.gcn import GCNNet\nfrom models.ginconv import GINConvNet\nfrom utils import *\nfrom processing import process_data\nimport argparse\n\n\nprint = functools.partial(print, flush=True)\n\n\n\ndef group_by(data):\n \"\"\"\n group documents by query-id\n :param data: input_data which contains multiple query and corresponding documents\n :param qid_index: the column num where qid locates in input data\n :return: a dict group by qid\n \"\"\"\n qid_doc_map = {}\n idx = 0\n for record in data:\n qid_doc_map.setdefault(record, [])\n qid_doc_map[record].append(idx)\n idx += 1\n return qid_doc_map\n\n\n\ndef sample_index(pairs,sampling_method = None):\n '''\n pairs: the score pairs for train or test\n \n return:\n index of x1 and x2\n '''\n x1_index = []\n x2_index = []\n\n for i_data in pairs:\n if sampling_method == '500 times':\n sampled_data = pd.DataFrame(i_data).sample(n=500,replace=True) \n if sampling_method == None:\n sampled_data = pd.DataFrame(i_data)\n \n x1_index.append(sampled_data.iloc[:,0].values)\n x2_index.append(sampled_data.iloc[:,1].values)\n \n return x1_index, x2_index\n\ndef get_pairs(scores,K,eps=0.2,seed=0):\n \"\"\"\n compute the ordered pairs whose firth doc has a higher value than second one.\n :param scores: given score list of documents for a particular query\n :param K: times of sampling\n :return: ordered pairs. List of tuple, like [(1,2), (2,3), (1,3)]\n \"\"\"\n pairs = [] \n random.seed(seed)\n for i in range(len(scores)):\n #for j in range(len(scores)):\n # sampling K times\n for _ in range(K):\n idx = random.randint(0, len(scores) - 1)\n score_diff = float(scores[i]) - float(scores[idx])\n if abs(score_diff) > eps:\n pairs.append((i, idx, score_diff, len(scores))) \n\n return pairs\n\n\ndef split_pairs(order_pairs, true_scores):\n \"\"\"\n split the pairs into two list, named relevant_doc and irrelevant_doc.\n relevant_doc[i] is prior to irrelevant_doc[i]\n\n :param order_pairs: ordered pairs of all queries\n :param ture_scores: scores of docs for each query\n :return: relevant_doc and irrelevant_doc\n \"\"\"\n relevant_doc = []\n irrelevant_doc = []\n score_diff = []\n N_smiles = []\n doc_idx_base = 0\n query_num = len(order_pairs)\n for i in range(query_num):\n pair_num = len(order_pairs[i])\n docs_num = len(true_scores[i])\n for j in range(pair_num):\n d1, d2, score, N = order_pairs[i][j]\n d1 += doc_idx_base\n d2 += doc_idx_base\n relevant_doc.append(d1)\n irrelevant_doc.append(d2)\n score_diff.append(score)\n N_smiles.append(N)\n doc_idx_base += docs_num\n return relevant_doc, irrelevant_doc, score_diff, N_smiles\n\n\n\ndef filter_pairs(data,order_paris,threshold):\n # filterred the pairs which have score diff less than 0.2 \n order_paris_filtered = []\n for i_pairs in order_paris:\n pairs1_score = data[pd.DataFrame(i_pairs).iloc[:,0].values][:,1].astype('float32') \n pairs2_score = data[pd.DataFrame(i_pairs).iloc[:,1].values][:,1].astype('float32')\n\n # filtered |score| threshold # 0.2 threshold \n i_pairs_filtered = np.array(i_pairs)[temp_mask].tolist()\n if len(i_pairs_filtered)>0:\n order_paris_filtered.append(i_pairs_filtered)\n return order_paris_filtered\n\nclass hinge_loss(nn.Module):\n def __init__(self,threshold=1,weight=None):\n super().__init__()\n self.threshold = 1\n self.weight = weight\n \n def forward(self,predicted_score,true_score,n = None):\n # score_diff = predicted_score - true_score\n score_diff = predicted_score*true_score\n loss = self.threshold - score_diff\n \n loss = torch.clip(loss,min=0) \n loss = torch.square(loss) \n\n if not self.weight is None:\n loss = loss * self.weight\n\n return 0.5*loss.mean()\n\ndef sample_pairs(true_scores,K,eps,seed):\n # get all the pairs after filtering based on scores\n order_paris = []\n for scores in true_scores:\n order_paris.append(get_pairs(scores,K=K,eps=eps,seed=seed))\n x1_index, x2_index, train_scores, N_smiles = split_pairs(order_paris ,true_scores)\n print('Number of training dataset is {}'.format(len(x1_index)))\n # change labels to binary\n Y = np.array(train_scores).astype('float32')\n\n Y[Y<0] = 0\n Y[Y>0] = 1\n\n return x1_index, x2_index, train_scores, Y\n\ndef distributed_concat(tensor, num_total_examples): \n\toutput_tensors = [tensor.clone() for _ in range(torch.distributed.get_world_size())] \n\ttorch.distributed.all_gather(output_tensors, tensor) \n\tconcat = torch.cat(output_tensors, dim=0) # truncate the dummy elements added by SequentialDistributedSampler \n\treturn concat[:num_total_examples]\n\n\ndef model_eval(model,val_dataloader,device):\n model.eval()\n ## validation\n CI_list = []\n weighted_CI_list = []\n weights_len = []\n\n with torch.no_grad():\n \n for batch_id, data in enumerate(val_dataloader):\n i_target_len = len(data)\n i_target_pred_scores = []\n i_target_y_label = []\n\n # loop over all the D-T pairs in one group(T group)\n for i_data in data: \n i_data = i_data.to(device) \n pred_scores = model.forward_single(i_data)\n # get the predicted labels\n i_target_pred_scores.append(float(pred_scores)) \n # get the true labels\n i_target_y_label.append(float(i_data.y.cpu()))\n\n i_target_pred_scores = np.array(i_target_pred_scores)\n i_target_y_label = np.array(i_target_y_label)\n\n\n # compute CI\n CI = concordance_index(i_target_y_label,i_target_pred_scores)\n CI_list.append(CI)\n weighted_CI_list.append(i_target_len*CI)\n weights_len.append(i_target_len)\n\n\n average_CI = np.mean(CI_list)\n weighted_CI = np.sum(weighted_CI_list)/np.sum(weights_len)\n\n return average_CI, weighted_CI\n\n\ndef dist_run(rank, args, world_size, train_set,mixed_set,val_set,test_set,model,CV):\n dist.init_process_group('nccl', rank=rank, world_size=world_size)\n print(rank)\n\n # prepare the processed data\n #train\n train_t = train_set[2]\n train_d = train_set[1]\n train_groups = train_set[0]\n train_y = train_set[3]\n train_smiles_graph = train_set[4]\n if args.is_mixed:\n #mixed\n mixed_t = mixed_set[2]\n mixed_d = mixed_set[1]\n mixed_groups = mixed_set[0]\n mixed_y = mixed_set[3]\n mixed_smiles_graph = mixed_set[4]\n\n del train_set\n del mixed_set\n # val\n val_t = val_set[2]\n val_d = val_set[1]\n val_groups = val_set[0]\n val_y = val_set[3]\n val_smiles_graph = val_set[4]\n # test\n test_t = test_set[2]\n test_d = test_set[1]\n test_groups = test_set[0]\n test_y = test_set[3]\n test_smiles_graph = test_set[4]\n ##################### load the data ############################\n\n if args.is_mixed:\n # concatenate the data\n train_t_data = np.concatenate((train_t,mixed_t))\n train_d_data = np.concatenate((train_d,mixed_d))\n train_smiles_graph_data = {**train_smiles_graph, **mixed_smiles_graph}\n else:\n train_t_data = train_t\n train_d_data = train_d\n train_smiles_graph_data = train_smiles_graph\n\n # get the group\n qid_doc_map_train = group_by(train_groups)\n query_idx_train = qid_doc_map_train.keys()\n train_keys = np.array(list(query_idx_train))\n\n if args.is_mixed:\n id_doc_map_mixed = group_by(mixed_groups)\n query_idx_mixed = id_doc_map_mixed.keys()\n mixed_keys = np.array(list(query_idx_mixed))\n \n qid_doc_map_val = group_by(val_groups)\n query_idx_val = qid_doc_map_val.keys()\n val_keys = np.array(list(query_idx_val))\n\n qid_doc_map_test = group_by(test_groups)\n query_idx_test = qid_doc_map_test.keys()\n test_keys = np.array(list(query_idx_test))\n ###### get the protein group and index for train/val/test\n\n # get the true scores of train\n true_scores = [train_y[qid_doc_map_train[qid]] for qid in query_idx_train]\n if args.is_mixed:\n true_scores_mixed = [mixed_y[id_doc_map_mixed[qid]] for qid in query_idx_mixed]\n\n # ###### get val/test dataloader\n val_index = []\n for qid in val_keys: \n val_index.append(qid_doc_map_val[qid]) \n val_dataset = TestDataset(test_index=val_index,xd=val_d,xt=val_t,y=val_y,smile_graph=val_smiles_graph)\n val_dataloader = DataLoader(val_dataset, batch_size=args.test_batch_size,shuffle=False)\n \n test_index = []\n for qid in test_keys: \n test_index.append(qid_doc_map_test[qid]) \n test_dataset = TestDataset(test_index=test_index,xd=test_d,xt=test_t,y=test_y,smile_graph=test_smiles_graph)\n test_dataloader = DataLoader(test_dataset, batch_size=args.test_batch_size,shuffle=False)\n\n\n ###### load model\n model = model.to(rank)\n model_dist = DistributedDataParallel(model, device_ids=[rank], find_unused_parameters=True)\n\n\n # define the optimizer\n optimizer = torch.optim.Adam(model_dist.parameters(), lr=args.learning_rate)\n \n print('start to train the model...')\n for epoch in range(args.N_epoch):\n\n ##################### resampling the pairs for each epoch #####################\n start_time = time.time()\n\n train_x1_index, train_x2_index, train_scores, Y_train = sample_pairs(true_scores,K=args.sampling_N_train,eps=args.filter_threshold,seed=epoch)\n if args.is_mixed:\n mixed_x1_index, mixed_x2_index, mixed_scores, Y_mixed = sample_pairs(true_scores_mixed,K=args.sampling_N_mixed,eps=args.filter_threshold,seed=epoch)\n\n # mixed all pairs from train and mixed dataset\n len_train = len(train_x1_index)\n onehot_train = np.zeros(len_train)\n\n if args.is_mixed:\n len_mixed1 = len(mixed_x1_index)\n onehot_mixed = np.ones(len_mixed1)\n onehot_train_mixed = np.concatenate((onehot_train,onehot_mixed))\n else:\n onehot_train_mixed = onehot_train\n\n if args.is_mixed:\n temp = len(train_d)\n mixed_x1_index = [i + temp for i in mixed_x1_index] \n mixed_x2_index = [i + temp for i in mixed_x2_index] \n\n train_x1_index = train_x1_index + mixed_x1_index\n train_x2_index = train_x2_index + mixed_x2_index\n\n Y_train_data = np.concatenate((Y_train,Y_mixed))\n else:\n Y_train_data = Y_train\n\n # get dataloader\n train_dataset = TrainDataset(train_x1_index=train_x1_index,train_x2_index=train_x2_index,train_d=train_d_data, train_t=train_t_data, y=Y_train_data,onehot_train_mixed=onehot_train_mixed,smile_graph=train_smiles_graph_data)\n train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank, shuffle=True)\n train_dataloader = DataLoader(train_dataset, batch_size=args.train_batch_size,sampler=train_sampler)\n \n end_time = time.time()\n print('make pairs + sampling, take time {}'.format(end_time-start_time))\n ##################### resampling the pairs for each epoch #####################\n\n print('***************train')\n LOSS = []\n model.train()\n start_time = time.time()\n for batch_id, data in enumerate(train_dataloader):\n data1 = data[0].to(rank)\n data2 = data[1].to(rank)\n\n batch_train_mixed = data1.train_mixed \n\n optimizer.zero_grad()\n\n output = model_dist(data1,data2)\n\n ture_labels = data1.y.view(-1, 1).float()\n\n output_train = output[batch_train_mixed==0]\n output_mixed = output[batch_train_mixed==1]\n\n ture_labels_train = ture_labels[batch_train_mixed==0]\n ture_labels_test = ture_labels[batch_train_mixed==1]\n\n ###### define loss and optimization function\n loss_fn = nn.BCEWithLogitsLoss()\n loss = loss_fn(output, ture_labels)\n \n loss.backward()\n optimizer.step()\n \n if batch_id % 20 == 0:\n print('batch {} loss {}'.format(batch_id,loss.item()))\n LOSS.append(loss.cpu().detach().numpy())\n \n end_time = time.time()\n print('take time {}'.format(end_time-start_time))\n print('epoch {}: loss: {} '.format(epoch,np.mean(LOSS)))\n\n if rank == 0:\n # validation\n print('***************validation')\n val_average_CI, val_weighted_CI = model_eval(model,val_dataloader,device='cuda:0')\n print(\"val_Average CI is {}\".format(val_average_CI))\n print(\"val_weighted CI is {}\".format(val_weighted_CI))\n\n # test\n print('***************test')\n test_average_CI, test_weighted_CI = model_eval(model,test_dataloader,device='cuda:0')\n print(\"test_Average CI is {}\".format(test_average_CI))\n print(\"test_weighted CI is {}\".format(test_weighted_CI))\n\n if epoch == 0:\n best_average_CI = val_average_CI\n # save the best epoch\n torch.save(model.state_dict(), args.save_direct + CV + '_' + 'train_model_best' )\n with open(args.save_direct + CV + '_' + \"best_results.txt\", \"w\") as text_file:\n text_file.write('epoch {}: loss: {} '.format(epoch,np.mean(LOSS)) + '\\n')\n text_file.write(\"val Average CI is {}\".format(val_average_CI) + '\\n')\n text_file.write(\"val weighted CI is {}\".format(val_weighted_CI) + '\\n')\n\n text_file.write(\"test Average CI is {}\".format(test_average_CI) + '\\n')\n text_file.write(\"test weighted CI is {}\".format(test_weighted_CI) + '\\n')\n text_file.write('##############################################' + '\\n')\n \n if (epoch != 0) & (val_average_CI >= best_average_CI):\n best_average_CI = val_average_CI\n # save the best epoch\n torch.save(model.state_dict(), args.save_direct + CV + '_' + 'train_model_best' )\n with open(args.save_direct + CV + '_' + \"best_results.txt\", \"w\") as text_file:\n text_file.write('epoch {}: loss: {} '.format(epoch,np.mean(LOSS)) + '\\n')\n text_file.write(\"val Average CI is {}\".format(val_average_CI) + '\\n')\n text_file.write(\"val weighted CI is {}\".format(val_weighted_CI) + '\\n')\n\n text_file.write(\"test Average CI is {}\".format(test_average_CI) + '\\n')\n text_file.write(\"test weighted CI is {}\".format(test_weighted_CI) + '\\n')\n text_file.write('##############################################' + '\\n') \n \n\n\ndef run(args):\n print('Load data...')\n\n ###### load model\n model = eval(args.model_name)()\n \n CVs = ['CV1','CV2','CV3','CV4','CV5']\n\n data_path = args.data_path + args.dataset + '/'\n\n for CV in CVs:\n print('><<><><><><><><><><><><><><><><><><><><><><><><><<><><><><><>')\n print('start {}'.format(CV))\n\n ##################### load the data ############################\n train_file = CV + '_' + args.dataset + '_' + args.split +'_' + 'train' + '.csv'\n val_file = CV + '_' + args.dataset + '_' + args.split + '_' + 'val' + '.csv'\n test = 'test_' + args.dataset + '_' + args.split + '.csv'\n\n # load the data\n train_data = pd.read_csv(data_path + CV + '/' + train_file)\n val_data = pd.read_csv(data_path + CV + '/' + val_file)\n test_data = pd.read_csv(data_path + test)\n\n if args.is_mixed:\n # load the mixed data\n if args.dataset == 'DAVIS':\n mixed_dataset = 'KIBA'\n if args.dataset == 'KIBA':\n mixed_dataset = 'DAVIS'\n\n # laod the mixed data\n mixed_data_file = mixed_dataset + '_mixed_train_unseenP_seenD.csv'\n mixed_data = pd.read_csv(data_path + mixed_data_file)\n # remove the repeated protein sequence\n val_t = val_data['Target Sequence'].unique()\n mixed_t = mixed_data['Target Sequence'].unique()\n filter1 = list((set(val_t).intersection(set(mixed_t))))\n mixed_data = mixed_data[~mixed_data['Target Sequence'].isin(filter1)]\n mixed_set = process_data(mixed_data) \n else:\n mixed_set = None\n \n # pre-processing the data\n train_set = process_data(train_data) \n val_set = process_data(val_data)\n test_set = process_data(test_data)\n \n world_size = torch.cuda.device_count()\n print('Let\\'s use', world_size, 'GPUs!')\n mp.spawn(dist_run, args=(args, world_size, train_set,mixed_set,val_set,test_set,model,CV), nprocs=world_size, join=True)\n\n\nif __name__ == '__main__':\n ##################### set parameters #####################\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--save_direct\", default='./output/')\n parser.add_argument(\"--data_path\", default='../Data_for_ALL/')\n parser.add_argument(\"--dataset\", default='DAVIS',help=' DAVIS | KIBA')\n parser.add_argument(\"--model_name\", default='GAT_GCN',help='[GATNet, GAT_GCN , GCNNet, GINConvNet]')\n parser.add_argument(\"--split\", default='unseenP_seenD')\n parser.add_argument(\"--local_rank\", default=0)\n\n\n parser.add_argument(\"--is_mixed\", default=False)\n\n\n parser.add_argument(\"--sampling_N_train\", type=int,default=10)\n parser.add_argument(\"--sampling_N_mixed\", type=int,default=5)\n parser.add_argument(\"--filter_threshold\", type=int,default=0.2)\n\n parser.add_argument(\"--train_batch_size\", type=int, default=256)\n parser.add_argument(\"--test_batch_size\", type=int, default=1)\n parser.add_argument(\"--learning_rate\", type=float, default=1e-3)\n parser.add_argument(\"--N_epoch\", type=int,default=200)\n args = parser.parse_args()\n ##################### set parameters #####################\n run(args)\n\n\n","sub_path":"apps/drug_target_interaction/batchdta/pairwise/GraphDTA/run_pairwise_GraphDTA_CV.py","file_name":"run_pairwise_GraphDTA_CV.py","file_ext":"py","file_size_in_byte":18993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152736426","text":"import time\r\nimport numpy as np\r\nfrom keras import optimizers\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom sklearn.model_selection import KFold\r\n\r\nstartTime = time.time()\r\n\r\nseed = np.random.seed(1)\r\n\r\ndef CrossValidation(model, trainingImages, trainingLabels):\r\n batchSize = 32\r\n kfold = KFold(n_splits=3, shuffle=True, random_state=seed)\r\n cvscores = []\r\n i = 1\r\n for train, test in kfold.split(trainingImages, trainingLabels):\r\n model.fit(trainingImages[train], trainingLabels[train], validation_split=0.16, batch_size=batchSize, epochs=500, verbose=0)\r\n evaluation = model.evaluate(trainingImages[test], trainingLabels[test], verbose=2)\r\n print(\"Fold %i out of 3\" % i)\r\n print(\"Accuracy: %.2f%%\" % (evaluation[1] * 100))\r\n cvscores.append(evaluation[1] * 100)\r\n i += 1\r\n print(\"Mean(+/-Standard Deviation): %.2f%% (+/- %.2f%%)\" % (np.mean(cvscores), np.std(cvscores)))\r\n\r\nimages = np.load('images.npy')\r\nimages = images.reshape(6500, 784)\r\n\r\nlabels = np.load('labels.npy')\r\nencodedLabels = np.zeros((6500,10))\r\nencodedLabels[np.arange(6500), labels]=1\r\n\r\npixels = 784\r\nnumbers = 10\r\ntrainingImages = np.zeros([5200, pixels])\r\ntestImages = np.zeros([1300, pixels])\r\ntrainingLabels = np.zeros([5200, numbers])\r\ntestLabels = np.zeros([1300, numbers])\r\nfor i in range(6500):\r\n if i < 5200:\r\n trainingImages[i] = images[i]\r\n trainingLabels[i] = encodedLabels[i]\r\n else:\r\n testImages[i-5200] = images[i]\r\n testLabels[i-5200] = encodedLabels[i]\r\n\r\nmodel = Sequential()\r\nmodel.add(Dense(50, input_dim=pixels, activation='relu'))\r\nfor i in range(9):\r\n model.add(Dense(50, activation='relu'))\r\nmodel.add(Dense(10, activation='softmax'))\r\n\r\nsgd = optimizers.SGD(lr=0.001)\r\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\r\nCrossValidation(model, trainingImages, trainingLabels)\r\n\r\nevaluation = model.evaluate(testImages, testLabels, verbose=2)\r\nprint(\"Final Baseline Error for Test: %.2f%%\" % (100-evaluation[1]*100))\r\n\r\nprint(\"Time to run: %s seconds\" % (time.time() - startTime))","sub_path":"Task4Part2.py","file_name":"Task4Part2.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"458419910","text":"import requests\nimport json\n\nencoded_body = json.dumps({\n\"aaaUser\": {\n\"attributes\": {\n\"name\": \"admin\",\n\"pwd\": \"ciscopsdt\"\n}\n}\n})\n\nresp = requests.post(\"https://sandboxapicdc.cisco.com/api/aaaLogin.json\", data=encoded_body, verify=False)\n\nheader = {\"Cookie\": \"APIC-cookie=\" + resp.cookies[\"APIC-cookie\"]}\n\ntenants = requests.get(\"https://sandboxapicdc.cisco.com/api/node/class/fvTenant.json?rsp-subtree-include=health,faults\", headers=header, verify=False)\n\n#print(tenants.text)\n\njson_response = json.loads(tenants.text)\n#print(json.dumps(json_response, sort_keys=True, indent=4))\njson_tenants = json_response['imdata']\nfor tenant in json_tenants:\n tenant_name = tenant['fvTenant']['attributes']['name']\n tenant_dn = tenant['fvTenant']['attributes']['dn']\n tenant_health = tenant['fvTenant']['children'][0]['healthInst']['attributes']['cur']\n output = \"Tenant: \" + tenant_name + \"\\t Health Score: \" + tenant_health + \"\\n DN: \" + tenant_dn\n print(output.expandtabs(40))","sub_path":"get-tenant-json.py","file_name":"get-tenant-json.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477771490","text":"# Usage: \n# voms-proxy-init -rfc -voms cms -valid 192:00\n# python3 extractRunNumber.py -l HSCP_file2.list\n\nimport argparse\nimport ROOT\n\ndef extractRunNumber(inlist):\n\twith open(inlist) as file:\n\t\tfor f_name in file:\n\t\t\t#print(f_name.rstrip())\n\t\t\t#filename = \"root://cms-xrd-global.cern.ch/\"+f_name.rstrip()\n\t\t\t#f=ROOT.TFile.Open(\"root://cms-xrd-global.cern.ch//store/user/tvami/PixelTrees/SingleMuon/crab_ALCARECO_2018A_PixelTrees_v1/200604_040318/0000/PixelTree_99.root\")\n\t\t\tf=ROOT.TFile.Open(f_name.rstrip())\n\t\t\tif f.IsZombie():\n\t\t\t\tcontinue\n\t\t\ttree=f.Get(\"pixelTree\")\n\t\t\trunHisto=ROOT.TH1F(\"runHisto\",\"\", 3300000,0,3300000 )\n\t\t\ttree.Draw(\"run>>runHisto\")\n\t\t\tFirstNonZeroBin = runHisto.FindFirstBinAbove()\n\t\t\trunNumber = int(round(FirstNonZeroBin-1))\n\t\t\tprint(\"inputFileName=\"+(f_name.rstrip())+\" runNumber=\" +str(runNumber))\n\t\t\t\n\t\t\nif __name__ == '__main__':\n \n ROOT.gROOT.SetBatch(True)\n\n parser = argparse.ArgumentParser(description='Run number extractor')\n parser.add_argument('-l', action=\"store\", dest = 'inlist', default = 'HSCP_file.list')\n \n p = parser.parse_args()\n extractRunNumber(p.inlist)\n\n","sub_path":"DataAna/condor/Prep/extractRunNumberV2.py","file_name":"extractRunNumberV2.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"115291943","text":"#!python\n\nimport string\n# Hint: Use these string constants to encode/decode hexadecimal digits and more\n# string.digits is '0123456789'\n# string.hexdigits is '0123456789abcdefABCDEF'\n# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'\n# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n# string.ascii_letters is ascii_lowercase + ascii_uppercase\n# string.printable is digits + ascii_letters + punctuation + whitespace\n\n\ndef decode(digits, base):\n \"\"\"Decode given digits in given base to number in base 10.\n digits: str -- string representation of number (in given base)\n base: int -- base of given number\n return: int -- integer representation of number (in base 10)\"\"\"\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base <= 36, 'base is out of range: {}'.format(base)\n # # \"Cheating\" way\n # #1 get each digit\n # decimal_num = 0\n # digits = digits[::-1]\n # for i in range(len(digits)):\n # digit = int(digits[i], base=base)\n # decimal_num += digits * base ** i\n # return decimal_num\n\n # TODO: Decode digits from any base (2 up to 36)\n print(\"::DECODE() start::\")\n decoded = 0\n strings = string.digits + string.ascii_lowercase\n print(strings)\n digits = digits[::-1]\n # digits = digits[::-1] which is reverse ordering of \n\n for i, number in enumerate(digits):\n print(\"i: \", i)\n print(\"number: \", number)\n print(\"strings.index(number)\", strings.index(number))\n print(\"strings: \", strings)\n decoded += base**i * strings.index(number)\n #enumerate adds a counter and an iterable, so the i will increase as we loop each number\n print(\"decoded: \", decoded)\n return decoded\n\n\ndef encode(number, base):\n \"\"\"Encode given number in base 10 to digits in given base.\n number: int -- integer representation of number (in base 10)\n base: int -- base to convert to\n return: str -- string representation of number (in given base)\"\"\"\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base <= 36, 'base is out of range: {}'.format(base)\n # Handle unsigned numbers only for now\n assert number >= 0, 'number is negative: {}'.format(number)\n\n print(\"::ENCODE start::\")\n encoded = ''\n strings = string.digits + string.ascii_lowercase\n p = 0\n if number == 0:\n return 0\n # If user wants to convert to base 10, immediately return decoded number (which is already in base 10)\n elif base == 10:\n return number\n \n while (base**p) <= number:\n p += 1\n\n while p > 0:\n print('p:', p)\n div = number//(base**(p-1))\n #1st 12 / 8 = 1.5 ==> 1\n #2nd 4 / 4\n print('div:', div)\n convert = min(div, (base-1))\n # 1 = 1 ==> 1\n print('convert:', convert)\n encoded += strings[convert]\n # 0[1]234... ==> 1\n print('encoded:', encoded)\n number = number - ( convert * base**(p-1))\n # 12 - ( 1 * 2**3 ) = 12 - 8 = 4\n print('#: ', number)\n p -= 1\n\n return encoded\n\n\ndef convert(digits, base1, base2):\n \"\"\"Convert given digits in base1 to digits in base2.\n digits: str -- string representation of number (in base1)\n base1: int -- base of given number\n base2: int -- base to convert to\n return: str -- string representation of number (in base2)\"\"\"\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base1 <= 36, 'base1 is out of range: {}'.format(base1)\n assert 2 <= base2 <= 36, 'base2 is out of range: {}'.format(base2)\n\n print(\"::CONVERT start::\")\n # Convert digits string to all LOWERCASE words to avoid error if user inputs capital letters for base 16 numbers\n return encode(decode(str(digits).lower(), base1), base2)\n\n\ndef main():\n \"\"\"Read command-line arguments and convert given digits between bases.\"\"\"\n import sys\n args = sys.argv[1:] # Ignore script file name\n if len(args) == 3:\n digits = args[0]\n base1 = int(args[1])\n base2 = int(args[2])\n # Convert given digits between bases\n result = convert(digits, base1, base2)\n print('{} in base {} is {} in base {}'.format(digits, base1, result, base2))\n else:\n print('Usage: {} digits base1 base2'.format(sys.argv[0]))\n print('Converts digits from base1 to base2')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Code/number-bases/bases.py","file_name":"bases.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"137656053","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.ttk import Combobox\n\nroot = Tk()\nroot.title('Maveric Transformation Validator')\n# root.geometry('850x650')\nroot.resizable(0, 0)\n\n\n\n# SOURCE FILE DIRECTORY\nsourceFileFrame = LabelFrame(root, text='Source File Directory', padx=20, pady=20)\nsourceFileFrame.grid(row=0, column=0, padx=50, pady=20)\n\n# DATE FORMAT FRAME\ndateFormatFrame = LabelFrame(root, text='Date Format Standardization', padx=20, pady=20)\ndateFormatFrame.grid(row=1, column=0, padx=50, pady=20)\n\n# SPLIT COLUMN FRAME\nsplitColumnFrame = LabelFrame(root, text='Split Columns', padx=20, pady=20)\nsplitColumnFrame.grid(row=2, column=0, padx=50, pady=20)\n\n# MERGE COLUMN FRAME\nmergeColumnFrame = LabelFrame(root, text='Merge Columns', padx=20, pady=20)\nmergeColumnFrame.grid(row=3, column=0, padx=50, pady=20)\n\n# HARD CODE VALUE FRAME\nhcodeColumnFrame = LabelFrame(root, text='Hard Code Values', padx=20, pady=20)\nhcodeColumnFrame.grid(row=4, column=0, padx=50, pady=20)\n\n# SOURCE FILE DIRECTORY\nLabel(sourceFileFrame, text='Source File').grid(row=0, column=0)\nsrcFile = Entry(sourceFileFrame, width=50)\nsrcFile.grid(row=0, column=1, padx=5, pady=5)\n\n\ndef browseFiles():\n filename = filedialog.askopenfilename(initialdir=\"/\", title=\"Select a File\",\n filetypes=((\"Excel files\", \"*.xlsx*\"), (\"all files\", \"*.*\")))\n srcFile.insert(0, filename)\n\n\nButton(sourceFileFrame, text='Browse', command=browseFiles).grid(row=0, column=2, padx=20, pady=20, sticky='')\n\n# DATE FORMAT STANDARDIZATION\nLabel(dateFormatFrame, text=\"Select Date Format\").grid(row=0, column=0, padx=10, pady=25)\nn = StringVar()\nformatChoosen = Combobox(dateFormatFrame, width=27, textvariable=n)\nformatChoosen['values'] = (\n 'dd-mmm-yy', 'dd-mmm-yyyy', 'mm/dd/yy', 'mm/dd/yyyy', 'dd.mm.yy', 'dd.mm.yyyy', 'yyddd', 'yyyyddd', 'yy/mm/dd',\n 'yyyy/mm/dd', 'mmm yy', 'mmm yyyy', 'dd-mmm-yyyy hh:mm:ss.s')\nformatChoosen.grid(row=0, column=1)\nformatChoosen.current()\n\n# Source and Target columns\nLabel(dateFormatFrame, text='Source Column').grid(row=1, column=0)\nLabel(dateFormatFrame, text='Target Column').grid(row=1, column=2)\n# Source column input\nEntry(dateFormatFrame).grid(row=1, column=1, padx=5, pady=5)\n# Target column input\nEntry(dateFormatFrame).grid(row=1, column=3, padx=5, pady=5)\n\n# SPLIT COLUMNS\nLabel(splitColumnFrame, text='Source Column').grid(row=0, column=0)\nLabel(splitColumnFrame, text='Target Column 1').grid(row=1, column=0)\nLabel(splitColumnFrame, text='Target Column 2').grid(row=1, column=2)\nLabel(splitColumnFrame, text='Target Column 3').grid(row=1, column=4)\n# Source column input\nEntry(splitColumnFrame).grid(row=0, column=1, padx=5, pady=5)\n# Target column 1 input\nEntry(splitColumnFrame).grid(row=1, column=1, padx=5, pady=5)\n# Target column 2 input\nEntry(splitColumnFrame).grid(row=1, column=3, padx=5, pady=5)\n# Target column 3 input\nEntry(splitColumnFrame).grid(row=1, column=5, padx=5, pady=5)\n\n# MERGE COLUMNS\nLabel(mergeColumnFrame, text='Source Column 1').grid(row=0, column=0)\nLabel(mergeColumnFrame, text='Source Column 2').grid(row=0, column=2)\nLabel(mergeColumnFrame, text='Target Column').grid(row=1, column=0)\n# Target column 1 input\nEntry(mergeColumnFrame).grid(row=0, column=1, padx=5, pady=5)\n# Target column 2 input\nEntry(mergeColumnFrame).grid(row=0, column=3, padx=5, pady=5)\n# Source column input\nEntry(mergeColumnFrame).grid(row=1, column=1, padx=5, pady=5)\n\n# HARD CODE VALUES\nLabel(hcodeColumnFrame, text=\"Select Category\").grid(row=0, column=0, padx=10, pady=25)\nn = StringVar()\nformatChoosen = Combobox(hcodeColumnFrame, width=27, textvariable=n)\nformatChoosen['values'] = (\n 'Countries', 'Others')\nformatChoosen.grid(row=0, column=1)\nformatChoosen.current()\n\n# Source and Target columns\nLabel(hcodeColumnFrame, text='Source Column').grid(row=1, column=0)\nLabel(hcodeColumnFrame, text='Target Column').grid(row=1, column=2)\n# Source column input\nEntry(hcodeColumnFrame).grid(row=1, column=1, padx=5, pady=5)\n# Target column input\nEntry(hcodeColumnFrame).grid(row=1, column=3, padx=5, pady=5)\n\n# Button to run transformation\nButton(root, text='Run Transform').grid(padx=20, pady=20, sticky='')\n\nroot.mainloop()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599107234","text":"import os # , sys, subprocess, shlex, re\nimport sys\nimport shutil\n# from subprocess import call\n\nfrom tinytag import TinyTag\n\nimport django\n# export DJANGO_SETTINGS_MODULE=collection.settings\n\n# sys.path.append(\"/home/mclovin/code/collection/\")\nsys.path.append(\"/home/pickledog/code/collection/\")\n# sys.path.append(\"/Users/wilkersonje/Code/collection/\")\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"collection.settings\"\ndjango.setup()\n# import ipdb; ipdb.set_trace()\nfrom music.models import Genre, Artist, Album, Song\n\nbase_location_dir = \"/media/pickledog/music750gb/music/locations\"\nbase_music_dir = \"/media/pickledog/music750gb/music\"\n\nLOCATIONS = {2: '128gb1', 3: '128gb2', 4: '128gb3', 5: '64gb1'}\n\ndef clean_string(string):\n string = string.replace(\" \", \".\")\n string = string.strip()\n return string\n\n\ndef create_directory(new_location):\n # create directory if doesn't exist\n if not os.path.exists(new_location):\n os.makedirs(new_location)\n\n\ndef create_locations(base_dir):\n locations = LOCATIONS.values()\n for location in locations:\n new_location = base_dir + \"/\" + location\n print(new_location)\n if not os.path.exists(new_location):\n os.makedirs(new_location)\n\n\ndef get_songs(album):\n songs = Song.objects.filter(album=album)\n return songs\n\n\ndef rename_file(dest_dir, src_file, new_file_name):\n \"\"\"rename the copied file\"\"\"\n dst_file = os.path.join(dest_dir, src_file)\n new_dst_file_name = os.path.join(dest_dir, new_file_name)\n os.rename(dst_file, new_dst_file_name)\n\n\ndef copy_file(src_dir, dest_dir, src_file, new_file_name):\n src_full = src_dir + \"/\" + src_file\n dest_full = dest_dir + \"/\" + src_file\n print(src_full)\n\n print(dest_full)\n print(\"..................\")\n if not os.path.exists(dest_full):\n shutil.copy(src_full, dest_full)\n rename_file(dest_dir, src_file, new_file_name)\n else:\n pass\ncreate_locations(base_location_dir)\n\nalbums = Album.objects.all()\n\nfor album in albums:\n if album.album_location in LOCATIONS:\n old_location = base_music_dir + \"/\" + \"/\" + album.artist.artist_name + \"/\" + album.album_name\n # import ipdb; ipdb.set_trace()\n # sys.exit()\n new_location = base_location_dir + \"/\" + LOCATIONS[album.album_location] + \"/\" + clean_string(album.artist.artist_name) + \"/\" + clean_string(album.album_name)\n create_directory(new_location)\n songs = get_songs(album)\n for song in songs:\n copy_file(old_location, new_location, song.song_name, clean_string(song.song_name))\n pass\n","sub_path":"music/scripts/copy_to_locations.py","file_name":"copy_to_locations.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"213026256","text":"import matplotlib as mpl\nmpl.rcdefaults()\nmpl.rcParams.update(mpl.rc_params_from_file('meine-matplotlibrc'))\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport uncertainties.unumpy as unp\nfrom uncertainties.unumpy import (\n nominal_values as noms,\n std_devs as stds,\n)\n\nfrom curve_fit import ucurve_fit\nfrom table import (\n make_table,\n make_SI,\n write,\n)\n\n\nT_weiss, U_weiss = np.genfromtxt('Messergebnisse/Ergebnisse_Weiß.txt', unpack=True)\nT_schwarz, U_schwarz = np.genfromtxt('Messergebnisse/Ergebnisse_Schwarz.txt', unpack=True)\nT_matt, U_matt = np.genfromtxt('Messergebnisse/Ergebnisse_Matt.txt', unpack=True)\nT_glanz, U_glanz = np.genfromtxt('Messergebnisse/Ergebnisse_Glänzend.txt', unpack=True)\nT_weiss+=273.1 # T in K\nT_schwarz+=273.1\nT_matt+=273.1\nT_glanz+=273.1\nU_weiss*=10**(-7) # U in V\nU_schwarz*=10**(-7) # U in V\nU_matt*=10**(-7) # U in V\nU_glanz*=10**(-7) # U in V\n\nT0 = 273.1+23.6 # Umgebungstemperatur in K\nU0 = 60e-7 # Offsetspannung in V\n\ndef f(t, a, b):\n return a * t + b\n\nparams_w = ucurve_fit(f, (T_weiss**4-T0**4), (U_weiss - U0), p0=[0.8e-9, 0])\nparams_s = ucurve_fit(f, (T_schwarz**4-T0**4), (U_schwarz - U0), p0=[0.8e-9, 0])\nparams_m = ucurve_fit(f, (T_matt**4-T0**4), (U_matt - U0), p0=[0.8e-9, 0])\nparams_g = ucurve_fit(f, (T_glanz**4-T0**4), (U_glanz - U0), p0=[0.8e-9, 0])\n\na_w, b_w = params_w\na_s, b_s = params_s\na_m, b_m = params_m\na_g, b_g = params_g\nwrite('build/Steigung_w.tex', make_SI(a_w * 1e13, r'\\volt\\per\\kelvin\\tothe{4}' , 'e-13'))\nwrite('build/Offset_w.tex', make_SI(b_w * 1e6, r'\\volt' , 'e-6'))\nwrite('build/Steigung_s.tex', make_SI(a_s * 1e13, r'\\volt\\per\\kelvin\\tothe{4}' , 'e-13'))\nwrite('build/Offset_s.tex', make_SI(b_s * 1e6, r'\\volt' , 'e-6'))\nwrite('build/Steigung_m.tex', make_SI(a_m * 1e13, r'\\volt\\per\\kelvin\\tothe{4}' , 'e-13'))\nwrite('build/Offset_m.tex', make_SI(b_m * 1e6, r'\\volt' , 'e-6'))\nwrite('build/Steigung_g.tex', make_SI(a_g * 1e13, r'\\volt\\per\\kelvin\\tothe{4}' , 'e-13'))\nwrite('build/Offset_g.tex', make_SI(b_g * 1e6, r'\\volt' , 'e-6'))\n\ne = [a_w/a_s , a_s/a_s , a_m/a_s , a_g/a_s]\n\ni=1\nfor x in e:\n name = 'build/Epsilon' + str(i) + '.tex'\n i+=1\n write(name, str(np.round(noms(x),3))+r'\\pm'+str(np.round(stds(x),3)))\n\n\nT_diff_weiss = (T_weiss**4-T0**4)*10**(-9) # Differenz in e-9 K\nT_diff_schwarz = (T_schwarz**4-T0**4)*10**(-9)\nT_diff_matt = (T_matt**4-T0**4)*10**(-9)\nT_diff_glanz = (T_glanz**4-T0**4)*10**(-9)\n\n\nplt.plot(T_diff_weiss, f(T_diff_weiss*1e9, *noms(params_w)) * 1e6, 'r-', label='Fit weiße Fläche')\nplt.plot(T_diff_schwarz, f(T_diff_schwarz*1e9, *noms(params_s)) * 1e6, 'b-', label='Fit schwarze Fläche')\nplt.plot(T_diff_matt, f(T_diff_matt*1e9, *noms(params_m)) * 1e6, 'k-', label='Fit matte Fläche')\nplt.plot(T_diff_glanz, f(T_diff_glanz*1e9, *noms(params_g)) * 1e6, 'm-', label='Fit glänzende Fläche')\n\nplt.plot(T_diff_weiss, (U_weiss-U0)*1e6, '.r', label='Messdaten weiße Fläche')\nplt.plot(T_diff_schwarz, (U_schwarz-U0)*1e6, '.b', label='Messdaten schwarze Fläche')\nplt.plot(T_diff_matt, (U_matt-U0)*1e6, '.k', label='Messdaten matte Fläche')\nplt.plot(T_diff_glanz, (U_glanz-U0)*1e6, '.m', label='Messdaten glänzende Fläche')\nT_diff = np.array([T_diff_weiss, T_diff_schwarz, T_diff_matt , T_diff_glanz])\n#plt.xlim(np.min(T_diff), np.max(T_diff))\nplt.xlabel(r'$T^4-T_0^4 \\:/\\: 10^9\\si{\\kelvin}^4$')\nplt.ylabel(r'$U \\:/\\: \\si{\\micro\\volt}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/plot.pdf')\n\n\n# für die Tabellen: U in µV, T in K, T^4-T0^4 in K^4*10^9\nU_weiss*=10**6 # U in µV\nU_schwarz*=10**6 # U in µV\nU_matt*=10**6 # U in µV\nU_glanz*=10**6 # U in µV\nU0 *=10**6 # U0 in µV\n\nprint(T_weiss)\nprint(U_weiss)\n\nwrite('build/weiss.tex', make_table([T_weiss, U_weiss, U_weiss-U0, T_diff_weiss],[1, 1, 1, 2]))\nwrite('build/schwarz.tex', make_table([T_schwarz, U_schwarz, U_schwarz-U0, T_diff_schwarz],[1, 1, 1, 2]))\nwrite('build/matt.tex', make_table([T_matt, U_matt, U_matt-U0, T_diff_matt],[1, 1, 1, 2]))\nwrite('build/glanz.tex', make_table([T_glanz, U_glanz, U_glanz-U0, T_diff_glanz],[1, 1, 1, 2]))\n\n\n# Abstandsmessungen\n\nT_dist, d , U_dist = np.genfromtxt('Messergebnisse/Ergebnisse_Abstand_Weiß.txt', unpack=True)\nT_dist += 273.1\nT_diff_dist = (T_dist**4-T0**4)\ndist = np.linspace(0.16, 0.26, num=np.size(U_dist))\nKorrektur = []\nfor Temperatur in T_diff_dist:\n Korrektur.append(-f(Temperatur, *noms(params_w)) + f(T_diff_dist[0], *noms(params_w)))\n\nU_dist *= 1e-7 # in Volt\nU_dist_korrigiert = U_dist + Korrektur\n\n\ndef g (x, k, l):\n return k/(x**2)+l\n\nparams_dist = ucurve_fit(g, dist, U_dist_korrigiert - U0*1e-6)\nprint(params_dist)\n\n\nplt.clf()\nplt.plot(dist*100, U_dist*1e6, 'x', label='Messdaten')\nplt.plot(dist*100, U_dist_korrigiert*1e6, 'x', label='Messdaten korrigiert')\nd = np.linspace(10e-2,30e-2, num=1000)\nplt.plot(d*1e2, g(d, *noms(params_dist)*1e6), 'r-', label=r'Fit $1/r^2$')\n#plt.xlim(min(dist)*1e2, max(dist)*1e2)\nplt.xlabel(r'$d \\:/\\: \\si{\\centi\\meter}$')\nplt.ylabel(r'$U \\:/\\: \\si{\\micro\\volt}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/plot2.pdf')\n\nwrite('build/dist.tex', make_table([T_dist, dist*100, U_dist*1e6, (U_dist-U0*1e-6)*1e6, (U_dist_korrigiert-U0*1e-6)*1e6],[1, 0, 1, 1, 1]))\nc_dist, d_dist = params_dist\nwrite('build/c_dist.tex', make_SI(c_dist * 1e6, r'\\volt\\meter\\tothe{2}' , 'e-6'))\nwrite('build/d_dist.tex', make_SI(d_dist * 1e6, r'\\volt' , 'e-6'))\n\n\n\n#\n# t1, t2 = np.array_split(t * 1e3, 2)\n# U1, U2 = np.array_split(U * 1e-3, 2)\n# write('build/loesung-table.tex', make_table([t1, U1, t2, U2], [3, None, 3, None]))\n#\n# a, b, c, d = params\n# write('build/loesung-a.tex', make_SI(a * 1e-3, r'\\kilo\\volt'))\n# write('build/loesung-b.tex', make_SI(b * 1e-3, r'\\kilo\\hertz'))\n# write('build/loesung-c.tex', make_SI(c, r''))\n# write('build/loesung-d.tex', make_SI(d * 1e-3, r'\\kilo\\volt'))\n","sub_path":"WS15_16/207/PythonSkript.py","file_name":"PythonSkript.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204815566","text":"\"\"\"\nCalc Bonuses\n\"\"\"\ndef calcBonuses(bonuses, n):\n it = iter(bonuses)\n #(b for b in bonuses)\n #[(yield x) for x in bonuses]\n res = 0\n\n try:\n for _ in range(n):\n res += next(it)\n except StopIteration:\n res = 0\n\n return res\n\n\"\"\"\nCalc Final Score\n\"\"\"\ndef calcFinalScore(scores, n):\n gen = iter([x * x for x in sorted(scores)[::-1]])\n #iter([x*x for x in sorted(scores)[::-1]])\n #(i*i for i in sorted(scores)[-n:])\n #reversed(sorted(j*j for j in scores))\n #(s**2 for s in sorted(scores, key=lambda x: -x))\n\n res = 0\n try:\n for _ in range(n):\n res += next(gen)\n except StopIteration:\n res /= 5\n\n return res\n\n\"\"\"\nFibonacci Generator\n\"\"\"\ndef fibonacciGenerator(n):\n def fib():\n last = (0, 1)\n while True:\n yield last[0]\n last = last[0] + last[1], last[0]\n\n gen = fib()\n return [next(gen) for _ in range(n)]\n\n\"\"\"\nCalkin Wilf Sequence\n\"\"\"\ndef calkinWilfSequence(number):\n def fractions():\n n = 1\n d = 1\n yield [n, d]\n while True:\n n, d = d, 2 * (n // d) * d + d - n\n yield [n, d]\n\n #n, d = 1, 1\n #while True:\n # yield [n, d]\n # n, d = d, 2 * (n - n % d) + d - n\n\n #n = 1\n #d = 1\n #yield [n, d]\n #while True:\n # n, d = d, 2 * (n // d) * d + d - n\n # yield [n, d]\n\n gen = fractions()\n res = 0\n while next(gen) != number:\n res += 1\n return res\n\n\"\"\"\nCheck Password\n\"\"\"\ndef checkPassword(attempts, password):\n def check():\n while True:\n val = yield\n yield password == val\n #yield (yield) == password\n #att = yield password == att if 'att' in locals() else False\n #yield password == (yield attempt)\n\n #x = yield\n #if password==x:\n # yield x\n\n #try:\n # res = yield password == res\n #except:\n # res = None\n\n checker = check()\n for i, attempt in enumerate(attempts):\n next(checker)\n if checker.send(attempt):\n return i + 1\n\n return -1\n\n\"\"\"\nGreetings Generator\n\"\"\"\nclass Greeter(object):\n def __init__(self, names):\n self.cnt = 0\n self.names = names\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.cnt < len(self.names):\n self.cnt += 1\n return 'Hello, {}!'.format(self.names[self.cnt - 1])\n else:\n raise StopIteration\n\n\ndef greetingsGenerator(team):\n return list(Greeter(team))\n\n\"\"\"\nRange Float\n\"\"\"\nclass FRange(object):\n def __init__(self, start, stop=None, step=None):\n if stop is None:\n self.i = 0\n self.stop = start\n self.step = 1\n elif step is None:\n self.i = start\n self.stop = stop\n self.step = 1\n else:\n self.i = start\n self.stop = stop\n self.step = step\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if((self.i < self.stop and self.step > 0) or (self.i > self.stop and self.step < 0)):\n temp = self.i\n self.i += self.step\n return temp\n else:\n raise StopIteration\n #if self.i*self.step >= self.stop*self.step:\n # raise StopIteration\n #self.i += self.step\n #return self.i-self.step\n\n #if ((self.stop - self.i) / self.step) <= 0:\n # raise StopIteration\n #else:\n # result = self.i\n # self.i += self.step\n # return result\ndef rangeFloat(args):\n return list(FRange(*args))\n\n\"\"\"\nSuper Prize\n\"\"\"\nclass Prizes(object):\n #def __init__(self,purchases,n,d):\n # self.winners = [(i+1)*n for i,x in enumerate(purchases[n-1::n]) if x%d == 0]\n \n #def __iter__(self):\n # return iter(self.winners)\n\n #start of solution\n #def __new__(_, p, n, d):\n # return [(i+1)*n for i, v in enumerate(p[n-1::n]) if v%d == 0]\n #end of solution => that guy is genius!\n\n def __init__(self, purchases, n, d):\n self.purchases = purchases\n self.n = n\n self.d = d\n self.index = n - 1\n #def __init__(self, p, n, d):\n #self.p, self.n, self.d, self.i = p, n, d, 0\n\n def __iter__(self):\n 'Returns itself as an iterator object'\n return self\n\n def __next__(self):\n while self.index < len(self.purchases):\n temp = self.index\n self.index += self.n\n if self.purchases[self.index - self.n] % self.d == 0: return temp+1\n else:\n raise StopIteration\n #self.cnt += self.n\n # if self.cnt <= len(self.purchases):\n # if self.purchases[self.cnt-1] % self.d == 0:\n # return self.cnt\n # else:\n # return self.__next__()\n # else:\n # raise StopIteration\n\n #for i,x in enumerate(self.p, 1):\n # if x % self.d == 0 and i % self.n == 0:\n # yield i\n\n\ndef superPrize(purchases, n, d):\n return list(Prizes(purchases, n, d))","sub_path":"PythonCodeFightsSolutions/Ying_and_Yang_of_Yields/Ying_and_Yang_of_Yields.py","file_name":"Ying_and_Yang_of_Yields.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646549488","text":"import base64\nimport datetime\nimport json\nimport re\n\nfrom lxml import etree\nfrom pymongo import MongoClient\nfrom requests_oauthlib import OAuth2Session\n\nfrom scripture.xpath import booking_hotels\n\n# logging.basicConfig(\n# format='%(name)s %(message)s',\n# level=logging.DEBUG\n# )\n\n\nCLIENT_ID = '543145811859-jq7priq34edkea7ifm09bk6dkinueh9u.apps.googleusercontent.com'\nCLIENT_SECRET = 'J5yZsSO3FpdfsOCDD1Hk2ule'\nMONGO_ADDRESS = 'mongodb://172.17.1.201:27017'\nallow_domain = re.compile(r'(booking.com|opentable.com|agoda.com|hotels.cn|hotels.com)')\nuser_id = 'sww4718168@gmail.com'\n\nxpath_list = [booking_hotels.CONFIRM_NUMBER, booking_hotels.CHECK_IN, booking_hotels.CHECK_OUT,\n booking_hotels.STAY, booking_hotels.CANCELLATION_POLICY, booking_hotels.NAME,\n booking_hotels.ADDRESS, booking_hotels.TELEPHONE, booking_hotels.IMPORTANT_NOTICE,\n booking_hotels.REQUIRED, booking_hotels.ROOM_DETAILS, booking_hotels.PRICE, booking_hotels.COST]\n\ndata_keys = ['confirm_number', 'check_in', 'check_out', 'stay', 'cancellation_policy', 'name', 'address',\n 'telephone', 'notice', 'required', 'room_details', 'price', 'cost']\n\n# page.xpath return a list, some attribute contains more than one items\nspecial = [booking_hotels.IMPORTANT_NOTICE, booking_hotels.ROOM_DETAILS]\n\n\nclass Booking:\n def __init__(self, user_id):\n self.user_id = user_id\n self.token = self.get_token()\n self.session = OAuth2Session(client_id=CLIENT_ID, token=self.token)\n self.session.access_token = self.token\n self.session.proxies = {'http': 'http://172.17.1.198:1118',\n 'https': 'https://172.17.1.198:1118'}\n self.url_user = 'https://www.googleapis.com/gmail/v1/users/{}/messages'.format(self.user_id)\n self.url_id = self.url_user + '/{}'\n print(self.token)\n self.ids = []\n self.data = []\n # self.get_time_line(self.url_user)\n\n def get_token(self):\n mongo_client = MongoClient(MONGO_ADDRESS)\n user = mongo_client.scripture.oauth.find_one({'email': self.user_id})\n return user.get('access_token')\n\n def get_html(self, url):\n return self.session.request('get', url, client_id=CLIENT_ID, client_secret=CLIENT_SECRET).json()\n # return self.session.request('get', url, client_id=CLIENT_ID, client_secret=CLIENT_SECRET).text\n\n def get_time_line(self, url):\n print(url)\n html = json.dumps(self.get_html(url))\n msgs = re.compile('\"id\": \"(.*?)\"')\n next_page = re.compile('\"nextPageToken\": \"(.*?)\"')\n ids = msgs.findall(html)\n next_page_token = next_page.findall(html) and next_page.findall(html)[0] or ''\n self.ids.extend(ids)\n\n msg = self.get_html(self.url_id.format(ids[len(ids)//2]))\n for header in msg['payload']['headers']:\n if header['name'] == 'X-Received':\n received_time = header['value'].split(',')[-1].split('(')[0].strip()\n received_time = '-'.join(received_time.split(' ')[:3])\n received_time = datetime.datetime.strptime(received_time, '%d-%b-%Y')\n print(received_time)\n time_in = int(re.match('(\\d+)', str(datetime.date.today()-received_time.date())).group(1)) < 31\n if time_in and next_page_token:\n self.get_time_line(self.url_user+'?pageToken='+next_page_token)\n break\n\n def get_booking_data(self, msg_id):\n data = ''\n url = self.url_id.format(msg_id)\n msg = self.get_html(url)\n print('_________________________________________________________')\n website = subject = None\n for header in msg['payload']['headers']:\n if header['name'] == 'From':\n print(header['value'])\n website = allow_domain.search(header['value'].lower())\n elif header['name'] == 'Subject':\n subject = header['value'].lower()\n print(subject)\n else:\n continue\n\n if website and 'booking' in subject:\n if 'cancel' in subject:\n pass\n else:\n if msg['payload']['mimeType'].startswith('multipart'):\n for part in msg['payload']['parts']:\n if part['body']['size'] == 0:\n for i in part['parts']:\n data = base64.urlsafe_b64decode(i['body']['data']).decode('utf-8', 'ignore').strip()\n else:\n data = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8', 'ignore').strip()\n\n elif 'data' in msg['payload']['body']:\n data = base64.urlsafe_b64decode(msg['payload']['body']['data']).decode('utf-8', 'ignore').strip()\n else:\n pass\n return data\n\n @staticmethod\n def find_data(page, path):\n if path in special:\n return page.xpath(path)\n return (page.xpath(path))[0]\n\n def parse(self, data):\n if data:\n page = etree.HTML(data)\n return {k: self.find_data(page, v) for k, v in zip(data_keys, xpath_list)}\n\nx = Booking(user_id)\n\n\n\n","sub_path":"booking.py","file_name":"booking.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"548823125","text":"from pyspark import SparkContext,SparkConf\r\nimport sys\r\nimport configparser as cp\r\n\r\nprops=cp.ConfigParser()\r\nprint(props.read('C:\\\\Users\\\\nara_\\\\PycharmProjects\\\\BootCampPyspark\\\\src\\\\resources\\\\application.properties'))\r\nprint ('sections:',props.sections())\r\n\r\nenv=sys.argv[1]\r\nmonth=sys.argv[2]\r\nconf=SparkConf().setMaster(props.get(env,'executionMode')).setAppName('PrcticeApp')\r\nsc=SparkContext(conf=conf)\r\nproducts=sc.textFile(props.get(env,'input.base.dir')+'/products')\r\nprint (products.take(10))","sub_path":"BootCampPyspark/src/main/python/retail_db/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402025912","text":"# Definition for singly-linked list.\n# Time Complexity - O(nlogn)\n# Space Complexity - O(n)\n# Solution 1 - Using n size - Min heap \nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nimport heapq\nclass Solution(object):\n def mergeKLists1(self, lists):\n heap = []\n dummy = head = ListNode(None)\n for l in lists:\n while l:\n heapq.heappush(heap, l.val)\n l = l.next\n while heap:\n value = heapq.heappop(heap)\n head.next = ListNode(value)\n head = head.next\n return dummy.next\n","sub_path":"MergeKSortedList.py","file_name":"MergeKSortedList.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"34059175","text":"#!/usr/bin/env python3\n\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.support.ui import Select\n\n\ntry:\n browser = webdriver.Chrome()\n link = \"https://SunInJuly.github.io/execute_script.html\"\n browser.get(link)\n button = browser.find_element_by_tag_name(\"button\")\n button.click()\n\nfinally:\n time.sleep(3)\n browser.quit()\n\n\n","sub_path":"les2.2.5.py","file_name":"les2.2.5.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"387371546","text":"import spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\ndef add_songs_to_playlist(country, artists):\n cid= '16b80191a35b48778bb2df4b6f9cee65'\n secret = '19fa57fbd8c3431983c1af5ccc8359e4'\n redirect = \"http://localhost/\"\n playlist_id = '4IHRZLGxuLYWk5IrHqorJg'\n scope = 'playlist-modify-public, playlist-modify-private'\n username = 'brielle.dolphin'\n client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager, auth_manager=SpotifyOAuth(client_id = cid, client_secret = secret, scope=scope, redirect_uri = redirect))\n\n #create playlist\n sp.user_playlist_create(user = username, name = country)\n results = sp.current_user_playlists(limit=50)\n for i, item in enumerate(results['items']):\n print(\"%d %s\" % (i, item['name']))\n if (item['name'] == country):\n playlist_id = item ['id']\n break\n\n track_id = []\n track_names = []\n for artist in artists:\n for i in range(0,5):\n query = f\"artist:{artist}\"\n track_results = sp.search(q=query, type='track', limit=10,offset=i)\n #print (\"len\" + str(len(track_results[\"tracks\"][\"items\"])))\n if (len(track_results[\"tracks\"][\"items\"]) > i):\n track_uri = track_results[\"tracks\"][\"items\"][0]['uri']\n track_name = track_results[\"tracks\"][\"items\"][0]['name']\n track_names.append(track_name)\n track_id.append(track_uri)\n sp.playlist_add_items( playlist_id = playlist_id, items = track_id) \n for track in track_names:\n print (track)\n return (\"https://open.spotify.com/playlist/\" + str (playlist_id))\n\nprint (add_songs_to_playlist(\"US\", [\"Taylor Swift\", \"AJR\"]))","sub_path":"spotipy_app.py","file_name":"spotipy_app.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"31237416","text":"import pygame\nfrom image import *\nfrom const import *\n\nclass Ingredient(pygame.sprite.Sprite):\n def __init__(self, playfield, name, col, row):\n pygame.sprite.Sprite.__init__(self)\n self.playfield = playfield\n self.name = name\n self.col = col\n self.row = row\n self.x = self.col * GRID_WIDTH + OFFSET_X + 1\n self.y = self.row * GRID_HEIGHT + OFFSET_Y + 1\n # init swap\n self.swap_speed = 6.5\n self.moving_right = False\n self.moving_left = False\n self.ingredient_to_left = None\n self.ingredient_to_right = None\n self.dest_left = self.x - GRID_WIDTH\n self.dest_right = self.x + GRID_WIDTH\n # init move down\n self.move_down_speed = 50\n self.dest_row = self.row\n self.dest_y = self.y\n self.move_down_list = []\n # init clear\n self.clearing = False\n # Track the time we started, and the time between updates.\n # Then we can figure out when we have to switch the image.\n self._delay = playfield.tick.delay\n self._last_time = playfield.tick.last_time\n self._frame = playfield.tick.frame\n self._images = self.load_animate_image()\n self.image = self._images[self._frame]\n self.rect = self.image.get_rect()\n self.rect.topleft = (self.x, self.y)\n \n ##self.poweringup = False\n \n def move_right(self, right_ingredient):\n self.moving_right = True\n self.ingredient_to_right = right_ingredient\n \n def move_left(self, left_ingredient):\n self.moving_left = True\n self.ingredient_to_left = left_ingredient\n \n def move_down(self, dest_row, move_down_list):\n self.dest_row = dest_row\n self.dest_y = dest_row * GRID_HEIGHT + OFFSET_Y + 1\n self.move_down_list = move_down_list\n \n def clear(self):\n self.clearing = True\n # Track the time we started, and the time between updates.\n # Then we can figure out when we have to switch the image.\n self._delay = 50\n self._last_time = self.playfield.tick.last_time\n self._frame = -1\n self._images = self.load_clear_image()\n self.image = self._images[0]\n self.rect = self.image.get_rect()\n self.rect.topleft = (self.x, self.y)\n \n ##def powerup(self):\n ##self.poweringup = True\n ### Track the time we started, and the time between updates.\n ### Then we can figure out when we have to switch the image.\n ##self._delay = 50\n ##self._last_time = self.playfield.tick.last_time\n ##self._frame = -1\n ##self._images = self.load_powerup_image()\n ##self.image = self._images[0]\n ##self.rect = self.image.get_rect()\n ##self.rect.topleft = (self.x, self.y)\n \n def inanimate(self):\n self._images = self.load_inanimate_image()\n \n def update(self, t):\n # Note that this doesn't work if it's been more that self._delay\n # time between calls to update(); we only update the image once\n # then, but it really should be updated twice.\n if t - self._last_time > self._delay:\n self._frame += 1\n if self._frame >= len(self._images): self._frame = 0\n self.image = self._images[self._frame]\n self._last_time = t\n self.rect = self.image.get_rect()\n self.rect.topleft = (self.x, self.y)\n # clearing logic\n if self.clearing and self._frame == len(self._images) - 1:\n self.playfield.remove_ingredient(self.row, self.col)\n self.playfield.clear_set.discard((self.row, self.col))\n if not self.playfield.clear_set:\n self.playfield.move_down()\n \n # move down logic\n if (self.y < self.dest_y):\n self.y += self.move_down_speed\n if self.y > self.dest_y:\n self.y = self.dest_y\n if self.y == self.dest_y:\n self.playfield.move_down_set.discard((self.row, self.dest_row, self.col, self.name))\n if not self.playfield.move_down_set:\n self.playfield.update_move_down(self.move_down_list)\n # swapping logic (move right)\n if (self.moving_right):\n if (self.x < self.dest_right):\n self.x += self.swap_speed\n else:\n self.moving_right = False\n if (not isinstance(self.ingredient_to_right, Ingredient) or (isinstance(self.ingredient_to_right, Ingredient) and not self.ingredient_to_right.moving_left)):\n self.playfield.update_swap(self.row, self.col)\n # swapping logic (move left)\n if (self.moving_left):\n if (self.x > self.dest_left):\n self.x -= self.swap_speed\n else:\n self.moving_left = False\n if (not isinstance(self.ingredient_to_left, Ingredient) or (isinstance(self.ingredient_to_left, Ingredient) and not self.ingredient_to_left.moving_right)):\n self.playfield.update_swap(self.row, self.col-1)\n \n def load_animate_image(self):\n if self.playfield.level == 1:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'baconsprite.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'berrysprite.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'breadsprite.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'cheesesprite.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'eggsprite.png')\n elif self.playfield.level == 2:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'greenpeppersprite.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'carrotsprite.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'chickensprite.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'eggplantsprite.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'tomatosprite.png')\n elif self.playfield.level == 3:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'asparagussprite.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'beetsprite.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'yellowpeppersprite.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'mushroomsprite.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'steaksprite.png')\n \n def load_clear_image(self):\n if self.playfield.level == 1:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'bacon-exp.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'berry-exp.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'bread-exp.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'cheese-exp.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'egg-exp.png')\n elif self.playfield.level == 2:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'greenpepper-exp.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'carrot-exp.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'chicken-exp.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'eggplant-exp.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'tomato-exp.png')\n elif self.playfield.level == 3:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'asparagus-exp.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'beet-exp.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'yellowpepper-exp.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'mushroom-exp.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'steak-exp.png')\n \n def load_inanimate_image(self):\n if self.playfield.level == 1:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'bacon-dead.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'berry-dead.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'bread-dead.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'cheese-dead.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'egg-dead.png')\n elif self.playfield.level == 2:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'greenpepper-dead.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'carrot-dead.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'chicken-dead.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'eggplant-dead.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'tomato-dead.png')\n elif self.playfield.level == 3:\n if self.name == INGRED_1:\n return Image.load_sliced_sprites(50, 50, 'asparagus-dead.png')\n elif self.name == INGRED_2:\n return Image.load_sliced_sprites(50, 50, 'beet-dead.png')\n elif self.name == INGRED_3:\n return Image.load_sliced_sprites(50, 50, 'yellowpepper-dead.png')\n elif self.name == INGRED_4:\n return Image.load_sliced_sprites(50, 50, 'mushroom-dead.png')\n elif self.name == INGRED_5:\n return Image.load_sliced_sprites(50, 50, 'steak-dead.png')\n \n ##def load_powerup_image(self):\n ##return Image.load_sliced_sprites(50, 50, 'egg-exp.png')","sub_path":"ingredient.py","file_name":"ingredient.py","file_ext":"py","file_size_in_byte":10973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"211490518","text":"from konlpy.tag import Mecab\nfrom collections import Counter\nimport konlpy\nimport kss\nimport pandas as pd\nmecab = Mecab()\n\n# 문장 단위로 토큰화\ndef sentences_tokenize(orig_text, stop_text):\n sent_text = kss.split_sentences(orig_text)\n stop_words = stop_text.split()\n \n sentences = []\n \n for i in sent_text:\n sentence = mecab.morphs(i) # 단어 토큰화\n result = []\n \n for word in sentence:\n if word not in stop_words: # 단어 토큰화 된 결과에 대해서 불용어를 제거\n if len(word) > 1: # 단어 길이가 1 이하인 경우에 대해서 추가로 단어를 제거\n result.append(word)\n sentences.append(result)\n #print(sentences)\n return sentences\n\n\n# 상위 10개 단어\ndef top_10_words(orig_text, stop_text):\n words = sum(sentences_tokenize(orig_text, stop_text), []) # 단어들을 하나의 리스트로 만들기\n frequency = Counter(words)\n # Counter 모듈을 이용하면 단어의 모든 빈도를 쉽게 계산 가능\n vocab_size = 10 \n vocab = frequency.most_common(vocab_size) # 등장 빈도수 상위 10개 단어만 저장\n \n word = [] # 단어 리스트\n freq = [] # 빈도수 리스트\n \n print(f'< 상위 {vocab_size}개 단어와 빈도수 >\\n')\n i = 0\n for (w, f) in vocab:\n i = i+1\n print(f'{i}. {w} \\t({f} 회)')\n word.append(w)\n freq.append(f)\n \n return vocab\n\n\ndef run():\n #USER_PATH = f'/mnt/c/Users/ehdal/Hanium_Project/Hanium_AI_Introduction/Final/07_Saramin_dataset/testset/test.txt' # 경로\n #STOPWORDS_PATH = f'/mnt/c/Users/ehdal/Hanium_Project/Hanium_AI_Introduction/Final/07_Saramin_dataset/testset/stop_words.txt' # 경로\n USER_PATH = '../07_Saramin_dataset/testset/test.txt' # 경로\n STOPWORDS_PATH = '../07_Saramin_dataset/testset/stop_words.txt' # 경로\n # 원본 텍스트 데이터\n origin_text = konlpy.utils.read_txt(USER_PATH , encoding='UTF-8') # txt 파일 읽음\n stopwords_text = konlpy.utils.read_txt(STOPWORDS_PATH , encoding='UTF-8') # 불용어 파일\n\n print(f'<원본 텍스트>')\n print(origin_text, '\\n')\n\n # 불용어 제거\n sentences_tokenize(origin_text, stopwords_text)\n # 상위 10개 단어 추출\n top_10_words(origin_text, stopwords_text)\n \nrun()","sub_path":"DeepSquare/deepsquareapp/Result_Code/Top_10_words.py","file_name":"Top_10_words.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152577368","text":"import tensorflow as tf\n\n\nclass Model(object):\n\n def __init__(self, user_count, item_count, cate_count, cate_list):\n \"\"\"模型初始化\n\n Args:\n user_count ([int]): user 数量\n item_count ([int]): item 数量\n cate_count ([int]): category 数量\n cate_list ([list]): category 列表\n \"\"\"\n self.u = tf.placeholder(tf.int32, [None, ]) # [B]\n # 要预测的next click\n self.i = tf.placeholder(tf.int32, [None, ]) # [B]\n # j 正确的next click\n self.j = tf.placeholder(tf.int32, [None, ]) # [B]\n self.y = tf.placeholder(tf.float32, [None, ]) # [B]\n self.hist_i = tf.placeholder(tf.int32, [None, None]) # [B, T]\n self.sl = tf.placeholder(tf.int32, [None, ]) # [B]\n self.lr = tf.placeholder(tf.float64, [])\n\n hidden_units = 128\n\n user_emb_w = tf.get_variable(\"user_emb_w\", [user_count, hidden_units])\n # TODO 为什么hidden_units要除2\n item_emb_w = tf.get_variable(\"item_emb_w\", [item_count, hidden_units // 2])\n item_b = tf.get_variable(\n \"item_b\",\n [item_count],\n initializer=tf.constant_initializer(0.0)\n )\n cate_emb_w = tf.get_variable(\"cate_emb_w\", [cate_count, hidden_units // 2])\n cate_list = tf.convert_to_tensor(cate_list, dtype=tf.int64)\n # 将每个user_id初始化,做第一层embedding映射\n u_emb = tf.nn.embedding_lookup(user_emb_w, self.u)\n # 将每个item找到对应的category存储起来\n ic = tf.gather(cate_list, self.i)\n # 将item_id的embedding和对应category的embedding拼接起来\n concat_list = [\n tf.nn.embedding_lookup(item_emb_w, self.i),\n tf.nn.embedding_lookup(cate_emb_w, ic),\n ]\n i_emb = tf.concat(values=concat_list, axis=1)\n # 找到每个item_id对应的映射\n i_b = tf.gather(item_b, self.i)\n # TODO j 是什么含义\n # 找到j对应的category\n jc = tf.gather(cate_list, self.j)\n concat_list_j = [\n tf.nn.embedding_lookup(item_emb_w, self.j),\n tf.nn.embedding_lookup(cate_emb_w, jc),\n ]\n # 找到j对应的embedding, 拼接id和category\n j_emb = tf.concat(\n concat_list_j,\n axis=1\n )\n # 找到j对应的初始化的向量\n j_b = tf.gather(item_b, self.j)\n # 对历史行为, 找到对应的category\n hc = tf.gather(cate_list, self.hist_i)\n hc_concat = [\n tf.nn.embedding_lookup(item_emb_w, self.hist_i),\n tf.nn.embedding_lookup(cate_emb_w, hc),\n ]\n h_emb = tf.concat(hc_concat, axis=2)\n\n # -- sum begin -------\n # 做mask\n mask = tf.sequence_mask(self.sl, tf.shape(h_emb)[1], dtype=tf.float32) # [B, T]\n mask = tf.expand_dims(mask, -1) # [B, T, 1]\n mask = tf.tile(mask, [1, 1, tf.shape(h_emb)[2]]) # [B, T, H]\n h_emb *= mask # [B, T, H]\n hist = h_emb\n # 加权求和\n hist = tf.reduce_sum(hist, 1)\n hist = tf.div(hist, tf.cast(tf.tile(tf.expand_dims(self.sl, 1), [1, 128]), tf.float32))\n print(h_emb.get_shape().as_list())\n # -- sum end ---------\n\n # 做batch normalization\n hist = tf.layers.batch_normalization(inputs=hist)\n hist = tf.reshape(hist, [-1, hidden_units])\n hist = tf.layers.dense(hist, hidden_units)\n\n u_emb = hist\n # -- fcn begin -------\n # Fully Convolutional Networks\n din_i = tf.concat([u_emb, i_emb], axis=-1)\n din_i = tf.layers.batch_normalization(inputs=din_i, name='b1')\n # 全连接网络\n # 第1层 80\n d_layer_1_i = tf.layers.dense(din_i, 80, activation=tf.nn.sigmoid, name='f1')\n # 第2层 40\n d_layer_2_i = tf.layers.dense(d_layer_1_i, 40, activation=tf.nn.sigmoid, name='f2')\n # 输出预测结果\n d_layer_3_i = tf.layers.dense(d_layer_2_i, 1, activation=None, name='f3')\n # 将user embedding和真实结果拼接起来\n din_j = tf.concat([u_emb, j_emb], axis=-1)\n # batch normalization\n din_j = tf.layers.batch_normalization(inputs=din_j, name='b1', reuse=True)\n # 这个再预测一遍\n d_layer_1_j = tf.layers.dense(din_j, 80, activation=tf.nn.sigmoid, name='f1', reuse=True)\n d_layer_2_j = tf.layers.dense(d_layer_1_j, 40, activation=tf.nn.sigmoid, name='f2', reuse=True)\n d_layer_3_j = tf.layers.dense(d_layer_2_j, 1, activation=None, name='f3', reuse=True)\n d_layer_3_i = tf.reshape(d_layer_3_i, [-1])\n d_layer_3_j = tf.reshape(d_layer_3_j, [-1])\n # TODO 这个是什么含义\n x = i_b - j_b + d_layer_3_i - d_layer_3_j # [B]\n self.logits = i_b + d_layer_3_i\n u_emb_all = tf.expand_dims(u_emb, 1)\n u_emb_all = tf.tile(u_emb_all, [1, item_count, 1])\n # logits for all item:\n all_emb = tf.concat([\n item_emb_w,\n tf.nn.embedding_lookup(cate_emb_w, cate_list)\n ], axis=1)\n all_emb = tf.expand_dims(all_emb, 0)\n all_emb = tf.tile(all_emb, [512, 1, 1])\n din_all = tf.concat([u_emb_all, all_emb], axis=-1)\n din_all = tf.layers.batch_normalization(inputs=din_all, name='b1', reuse=True)\n d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1', reuse=True)\n d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2', reuse=True)\n d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3', reuse=True)\n d_layer_3_all = tf.reshape(d_layer_3_all, [-1, item_count])\n self.logits_all = tf.sigmoid(item_b + d_layer_3_all)\n # -- fcn end -------\n\n self.mf_auc = tf.reduce_mean(tf.to_float(x > 0))\n self.score_i = tf.sigmoid(i_b + d_layer_3_i)\n self.score_j = tf.sigmoid(j_b + d_layer_3_j)\n self.score_i = tf.reshape(self.score_i, [-1, 1])\n self.score_j = tf.reshape(self.score_j, [-1, 1])\n self.p_and_n = tf.concat([self.score_i, self.score_j], axis=-1)\n print(self.p_and_n.get_shape().as_list())\n\n # Step variable\n self.global_step = tf.Variable(0, trainable=False, name='global_step')\n self.global_epoch_step = \\\n tf.Variable(0, trainable=False, name='global_epoch_step')\n self.global_epoch_step_op = \\\n tf.assign(self.global_epoch_step, self.global_epoch_step+1)\n\n self.loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=self.logits,\n labels=self.y)\n )\n\n trainable_params = tf.trainable_variables()\n self.opt = tf.train.GradientDescentOptimizer(learning_rate=self.lr)\n gradients = tf.gradients(self.loss, trainable_params)\n clip_gradients, _ = tf.clip_by_global_norm(gradients, 5)\n self.train_op = self.opt.apply_gradients(\n zip(clip_gradients, trainable_params), global_step=self.global_step)\n\n def train(self, sess, uij, l):\n loss, _ = sess.run([self.loss, self.train_op], feed_dict={\n self.u: uij[0],\n self.i: uij[1],\n self.y: uij[2],\n self.hist_i: uij[3],\n self.sl: uij[4],\n self.lr: l,\n })\n return loss\n\n def eval(self, sess, uij):\n \"\"\"计算AUC\n\n Args:\n sess ([tf]): sesstion\n uij ([iterator]): 输入行为序列\n\n Returns:\n u_auc [int]: auc指标\n socre_p_and_n [list]: 正负样本的得分\n \"\"\"\n u_auc, socre_p_and_n = sess.run([self.mf_auc, self.p_and_n], feed_dict={\n self.u: uij[0],\n self.i: uij[1],\n self.j: uij[2],\n self.hist_i: uij[3],\n self.sl: uij[4],\n })\n return u_auc, socre_p_and_n\n\n def test(self, sess, uid, hist_i, sl):\n \"\"\"[summary]\n\n Args:\n sess ([type]): [description]\n uid ([type]): [description]\n hist_i ([type]): [description]\n sl ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n feed_dict = {\n self.u: uid,\n self.hist_i: hist_i,\n self.sl: sl,\n }\n result = sess.run(self.logits_all, feed_dict=feed_dict)\n return result\n\n def save(self, sess, path):\n \"\"\"模型存储\n\n Args:\n sess ([tf]): [session]\n path ([string]): [存储路径]\n \"\"\"\n saver = tf.train.Saver()\n saver.save(sess, save_path=path)\n\n def restore(self, sess, path):\n \"\"\"恢复路径\n\n Args:\n sess ([tf]): [session]\n path ([string]): [恢复的路径]\n \"\"\"\n saver = tf.train.Saver()\n saver.restore(sess, save_path=path)\n","sub_path":"base_model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"609562816","text":"# Play with inheritance\n\nclass NamedList(list):\n def __init__(self, a_name):\n super().__init__([]) # Call List constructor\n self.name = a_name\n\ndef test():\n john = NamedList(\"John\")\n # Show Object type\n print(type(john))\n # Show list of all functions\n print(dir(john)) \n \n # Add elements\n john.append(\"Bass Player\")\n john.extend([\"Composer\", \"Arranger\", \"Musician\"])\n print(john)\n\n for attr in john:\n print(john.name + \" is a \" + attr)\n\nif __name__ == \"__main__\":\n test()","sub_path":"HFP/Chapter6/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147242159","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: /mnt/c/Users/rafae/repo/epic/EPIC/cosmology/cosmic_objects.py\n# Compiled at: 2018-09-11 00:05:42\n# Size of source mod 2**32: 40683 bytes\nimport numpy as np, scipy.integrate as integrate\nfrom scipy.interpolate import interp1d\nfrom EPIC import Unsupported, NotAnalytic\nfrom EPIC.cosmology import a_of_z, z_of_a, rho_critical, rho_critical_SI\nfrom EPIC.utils.numbers import speedoflight, a_B_over_c2, GmumH, Mpc_to_km, G_SI, G\nfrom EPIC.utils.io_tools import pasta\nfrom EPIC import root, user_folder\nimport uncertainties\nfrom uncertainties import umath\nfrom collections import OrderedDict\nimport os, configparser\n\nclass CosmologicalSetup(object):\n\n def __init__(self, model, optional_species=[], combined_species=[], interaction_setup={}, physical=True, derived=None, a0=1):\n \"\"\" keys for interaction_setup:\n species (-> list), propto_other (-> dict), parameter (-> dict), \n tex (-> str), sign (-> dict)\n \"\"\"\n self.model = model\n self.a0 = a0\n self.physical_density_parameters = physical\n available_species = configparser.ConfigParser()\n available_species.read([\n os.path.join(root, 'cosmology', 'available_species.ini'),\n os.path.join(user_folder, 'modifications', 'cosmology', 'available_species.ini')])\n species_labels = self.get_species(available_species, optional_species=optional_species, combined_species=combined_species)\n for fluid in species_labels:\n eos_type = available_species['EoS type'][fluid]\n eos_value = eval(available_species['EoS value'].get(fluid, 'None'))\n eos_woa = fluid if eos_type == 'woa' and available_species['EoS woa parametrization'].getboolean(fluid) else None\n eos_parameters = eval(available_species['EoS parameters'].get(fluid, '[]'))\n eos_par_tex = eval(available_species['tex EoS parameters'].get(fluid, '[]'))\n eos_parameters_obj = [FreeParameter(par, tex=tex, model_name=self.model) for par, tex in zip(eos_parameters, eos_par_tex)]\n eos = EquationOfState(eos_type, value=eos_value, parameters=eos_parameters_obj, woa=eos_woa)\n physical_densities = 'physical ' if self.physical_density_parameters else ''\n if derived == fluid:\n density_parameter = DerivedParameter(available_species[('%sdensity parameter' % physical_densities)][fluid], list(set(species_labels) - set([fluid])), tex=available_species[('tex %sdensity parameter' % physical_densities)][fluid], physical=bool(self.physical_density_parameters))\n else:\n if fluid == 'radiation':\n temperature_parameter = FreeParameter(available_species[('%sdensity parameter' % physical_densities)][fluid], available_species[('tex %sdensity parameter' % physical_densities)][fluid], model_name=self.model)\n density_parameter = DensityFromTemperature(temperature_parameter, physical=bool(self.physical_density_parameters), model_name=self.model)\n else:\n density_parameter = DensityParameter(available_species[('%sdensity parameter' % physical_densities)][fluid], available_species[('tex %sdensity parameter' % physical_densities)][fluid], physical=bool(self.physical_density_parameters), model_name=self.model)\n if fluid in interaction_setup.get('species', []):\n int_parameter = interaction_setup.get('parameter', {}).get(fluid)\n int_other = interaction_setup.get('propto_other', {}).get(fluid)\n this_fluid = InteractingFluid(fluid, eos, density_parameter, interaction_setup={'parameter': int_parameter, \n 'tex_parameter': interaction_setup.get('tex') if int_parameter else None, \n \n 'sign': interaction_setup.get('sign', {})[fluid], \n 'propto_other': int_other}, model_name=self.model)\n else:\n this_fluid = NonInteractingFluid(fluid, eos, density_parameter)\n self.add_species(fluid, this_fluid)\n\n for key in self.species.keys():\n if getattr(self.species[key], 'interaction_propto_other', None) is not None:\n self.species[key].interacts_with = self.species[self.species[key].interaction_propto_other]\n\n self.directly_solvable = self.is_directly_solvable()\n for par in self.parameters:\n if isinstance(par, DerivedParameter):\n par.dependencies = [free for free in self.parameters if isinstance(free, DensityParameter)]\n\n if self.physical_density_parameters:\n if derived is None:\n Hubble_parameter = HubbleDerivedParameter('h', 'Hubble', [par for par in self.parameters if isinstance(par, DensityParameter)], physical=self.physical_density_parameters)\n else:\n Hubble_parameter = HubbleFreeParameter('h', model_name=self.model)\n else:\n Hubble_parameter = HubbleFreeParameter('H0', tex='H_0', model_name=self.model)\n self.parameters.append(Hubble_parameter)\n self.HubbleParameter = Hubble_parameter\n for fluid in self.species.values():\n if isinstance(fluid.density_parameter, DerivedParameter) and not isinstance(fluid.density_parameter, (\n HubbleDerivedParameter, DerivedDensityDistribution,\n DerivedParameterDensityDistribution,\n DerivedDensityFromTemperature)) or not self.physical_density_parameters and isinstance(fluid.density_parameter, DensityFromTemperature):\n fluid.density_parameter.hubble = self.HubbleParameter\n\n def is_directly_solvable(self):\n return np.all([self.species[key].is_directly_solvable() for key in self.species.keys()])\n\n def show_defaults(self):\n return [par.default for par in self.parameters if not isinstance(par, DerivedParameter)]\n\n def add_species(self, name, fluid):\n if not hasattr(self, 'species'):\n self.species = OrderedDict()\n if not hasattr(self, 'parameters'):\n self.parameters = []\n self.species[name] = fluid\n self.parameters.append(fluid.density_parameter)\n self.parameters.extend(fluid.EoS.parameters)\n int_parameter = getattr(fluid, 'interaction_parameter', None)\n if int_parameter:\n self.parameters.append(int_parameter)\n\n def get_species(self, available_species, optional_species=[], combined_species=[]):\n model_recipes = configparser.ConfigParser()\n model_recipes.read([\n os.path.join(root, 'cosmology', 'model_recipes.ini'),\n os.path.join(user_folder, 'modifications', 'cosmology', 'model_recipes.ini')])\n self.tex = model_recipes[self.model].get('tex', self.model)\n species = eval(model_recipes[self.model]['mandatory species'])\n species.extend([fluid for fluid in optional_species if fluid in eval(model_recipes[self.model].get('supported optional species', '[]'))])\n supported_composed_species = eval(model_recipes[self.model].get('supported composed species', '[]'))\n for fluid in combined_species:\n if fluid in supported_composed_species:\n for component in eval(available_species['composed of'][fluid]):\n try:\n species.remove(component)\n except ValueError:\n pass\n\n species.append(fluid)\n\n return species\n\n def get_age_of_the_universe(self, z, a_zinf=0, **kwargs):\n zinf = np.inf if a_zinf == 0 else z_of_a(a_zinf, a0=self.a0)\n t_of_z = integrate.quad(lambda Z: 1 / self.get_Hubble_Friedmann_of_z(Z, **kwargs) / (1 + Z), z, zinf)[0]\n t_of_z *= 976.480247152\n return t_of_z\n\n def get_age_of_various_z(self, Z, **kwargs):\n return np.array([self.get_age_of_the_universe(z, **kwargs) for z in Z])\n\n def get_lookback_time(self, z, **kwargs):\n try:\n return self.get_age_of_the_universe(0, a_zinf=a_of_z(z), **kwargs)\n except ValueError:\n return np.array([self.get_age_of_the_universe(0, a_zinf=A, **kwargs) for A in a_of_z(z)])\n\n def get_Hubble_Friedmann_of_z(self, z, **kwargs):\n a = a_of_z(z, a0=self.a0)\n return self.get_Hubble_Friedmann(a, **kwargs)\n\n def get_Hubble_Friedmann(self, a, given_densities=None, **kwargs):\n try:\n adim_Hubble = 0\n if given_densities is not None:\n adim_Hubble += sum(given_densities)\n else:\n for fluid in self.species.values():\n rho0 = fluid.density_parameter.get_value(**kwargs)\n adim_Hubble += fluid.rho_over_rho0(a, a0=self.a0, **kwargs) * rho0\n\n adim_Hubble = np.sqrt(adim_Hubble)\n if self.physical_density_parameters:\n return 100 * adim_Hubble\n else:\n return adim_Hubble * self.HubbleParameter.get_value(**kwargs)\n except NotAnalytic:\n if not hasattr(self, 'background_solution_rhos') or not kwargs.get('in_MCMC', False):\n self.solve_background(**kwargs)\n hubble = self.HubbleParameter.get_value(**kwargs)\n H = np.sqrt(self.background_solution_rhos['total']) * (100 if self.physical_density_parameters else hubble)\n H_of_a = interp1d(self.a_range, H)\n if isinstance(a, float):\n return float(H_of_a(a))\n else:\n return H_of_a(a)\n\n def get_luminosity_distance(self, zhel, zcmb, **kwargs):\n luminosity_distance = (1 + zhel) / self.a0 * integrate.quad(lambda Z: 1 / self.get_Hubble_Friedmann_of_z(Z, **kwargs), 0, zcmb)[0]\n luminosity_distance *= 1000000.0\n luminosity_distance *= speedoflight / 1000.0\n return luminosity_distance\n\n def get_distance_moduli(self, z, nuisance_magnitude, **kwargs):\n mu = 5 * np.log10(np.array([self.get_luminosity_distance(Z, Z, **kwargs) for Z in z], ndmin=2) / 10)\n M = nuisance_magnitude['M'].get_value(**kwargs)\n return M + mu\n\n def get_distance_moduli_full(self, z, **kwargs):\n return 5 * np.log10(np.array([self.get_luminosity_distance(zhel, zcmb, **kwargs) for zhel, zcmb in z], ndmin=2) / 10)\n\n def d_a(self, z, **kwargs):\n c = speedoflight / 1000.0\n try:\n da_c = c / self.a0 * integrate.quad(lambda Z: 1 / self.get_Hubble_Friedmann_of_z(Z, **kwargs), 0, z)[0]\n except ValueError:\n da_c = c / self.a0 * np.array([integrate.quad(lambda Z: 1 / self.get_Hubble_Friedmann_of_z(Z, **kwargs), 0, redshift)[0] for redshift in z])\n\n return da_c\n\n def D_A(self, z, **kwargs):\n return self.d_a(z, **kwargs) * self.a0 / (1 + z)\n\n def D_V(self, z, **kwargs):\n DV = self.d_a(z, **kwargs) ** 2 * z * self.D_H(z, **kwargs)\n DV = DV ** 0.3333333333333333\n return DV\n\n def D_H(self, z, **kwargs):\n return speedoflight / 1000.0 / self.get_Hubble_Friedmann_of_z(z, **kwargs)\n\n def r_s(self, z, a_zinf=0, **kwargs):\n baryons = self.species['baryons'].density_parameter.get_value(**kwargs)\n photons = self.species['radiation'].density_parameter.get_value(sub_species='photons', **kwargs)\n zinf = np.inf if a_zinf == 0 else z_of_a(a_zinf, a0=self.a0)\n c = speedoflight / 1000.0\n R_S = c * integrate.quad(lambda Z: 1 / self.get_Hubble_Friedmann_of_z(Z, **kwargs) / np.sqrt(3 * (1 + 3 * baryons * self.a0 / (4 * photons * (1 + Z)))), z, zinf)[0]\n return R_S\n\n def get_BAO_ratio(self, z, isotropic=True, **kwargs):\n dm_fluid = 'idm' if 'cde' in self.model else 'cdm'\n if self.physical_density_parameters:\n Obh2 = self.species['baryons'].density_parameter.get_value(**kwargs)\n Och2 = self.species[dm_fluid].density_parameter.get_value(**kwargs)\n else:\n h = self.HubbleParameter.get_value(**kwargs) / 100\n h2 = h * h\n Obh2 = self.species['baryons'].density_parameter.get_value(**kwargs) * h2\n Och2 = self.species[dm_fluid].density_parameter.get_value(**kwargs) * h2\n Omh2 = Obh2 + Och2\n b1 = 0.313 * Omh2 ** (-0.419) * (1 + 0.607 * Omh2 ** 0.674)\n b2 = 0.238 * Omh2 ** 0.223\n zd = 1291 * Omh2 ** 0.251 * (1 + b1 * Obh2 ** b2) / (1 + 0.659 * Omh2 ** 0.828)\n rs_zd = self.r_s(zd, **kwargs)\n if isotropic:\n return rs_zd / self.D_V(z, **kwargs)\n return (\n self.D_A(z, **kwargs) / rs_zd,\n rs_zd * self.get_Hubble_Friedmann_of_z(z, **kwargs))\n\n def get_equilibrium_virial_ratio(self, **kwargs):\n assert self.model in ('cde LI', 'wcde LI')\n xi = self.species['idm'].interaction_parameter.get_value(**kwargs)\n xi *= self.species['idm'].interaction_sign\n return -(1 - 6 * xi) / (2 + 3 * xi)\n\n def get_a_range(self, **kwargs):\n log_a0 = np.log10(self.a0)\n log_a_initial = kwargs.get('log_a_initial', -5)\n numpoints = kwargs.get('numpoints', 10000)\n assert log_a_initial < log_a0\n self.a_range = np.logspace(log_a_initial, log_a0, numpoints)\n\n def solve_background(self, **kwargs):\n if not hasattr(self, 'a_range'):\n self.get_a_range(**kwargs)\n self.background_solution_Omegas = OrderedDict()\n self.background_solution_rhos = OrderedDict()\n if self.directly_solvable:\n for key in self.species.keys():\n fluid = self.species[key]\n rho0 = fluid.density_parameter.get_value(**kwargs)\n self.background_solution_rhos[fluid.name] = fluid.rho_over_rho0(self.a_range, a0=self.a0, **kwargs) * rho0\n\n else:\n from EPIC.utils import integrators\n numpoints = kwargs.get('numpoints', 10000)\n for key in self.species.keys():\n self.background_solution_rhos[key] = np.zeros(numpoints)\n self.background_solution_rhos[key][-1] = self.species[key].density_parameter.get_value(**kwargs)\n\n i = -2\n while i >= -numpoints:\n da = -(self.a_range[(i + 1)] - self.a_range[i])\n densities = np.array([self.background_solution_rhos[key][(i + 1)] for key in self.species.keys()])\n next_RK = integrators.generic_runge_kutta(da, self.a_range[(i + 1)], densities, [fluid.drho_da for fluid in self.species.values()], intermediate=[\n self.get_Hubble_Friedmann], a0=self.a0, **kwargs)\n for e, key in enumerate(self.background_solution_rhos.keys()):\n self.background_solution_rhos[key][i] = next_RK[e]\n\n i -= 1\n\n self.background_solution_rhos['total'] = sum(self.background_solution_rhos.values())\n for key in self.background_solution_rhos.keys():\n if key != 'total':\n self.background_solution_Omegas[key] = self.background_solution_rhos[key] / self.background_solution_rhos['total']\n\n def clusters_dlnrho_over_H(self, cluster, nuisance, **kwargs):\n Hz = self.get_Hubble_Friedmann_of_z(cluster.z, **kwargs)\n dlnpot_dlnr200 = 2 - cluster.dFdc / cluster.fc * cluster.c\n res = 3 * cluster.ovr + dlnpot_dlnr200\n logt0 = nuisance['logt0'].get_value(**kwargs)\n t0 = 10 ** logt0\n g = nuisance['gamma'].get_value(**kwargs)\n res *= (g * g * 3 ** (g + 1)) ** (1 / (1 - g)) / t0\n return res / Hz\n\n def get_Planck_Distance_Priors(self, *args, **kwargs):\n dm_fluid = 'idm' if 'cde' in self.model else 'cdm'\n if self.physical_density_parameters:\n Obh2 = self.species['baryons'].density_parameter.get_value(**kwargs)\n Och2 = self.species[dm_fluid].density_parameter.get_value(**kwargs)\n else:\n h = self.HubbleParameter.get_value(**kwargs) / 100\n h2 = h * h\n Obh2 = self.species['baryons'].density_parameter.get_value(**kwargs) * h2\n Och2 = self.species[dm_fluid].density_parameter.get_value(**kwargs) * h2\n g1 = 0.0783 * Obh2 ** (-0.238) / (1 + 39.5 * Obh2 ** 0.763)\n g2 = 0.56 / (1 + 21.1 * Obh2 ** 1.81)\n Omh2 = Obh2 + Och2\n zdec = 1048 * (1 + 0.00124 * Obh2 ** (-0.738)) * (1 + g1 * Omh2 ** g2)\n da_comoving = self.d_a(zdec, **kwargs)\n R = np.sqrt(Omh2) * da_comoving * 100000.0 / speedoflight\n rs = self.r_s(zdec, **kwargs)\n try:\n l_A = np.pi * da_comoving / rs\n except ZeroDivisionError:\n l_A = np.nan\n\n return np.array([R, l_A, Obh2])\n\n\nclass EquationOfState(object):\n\n def __init__(self, EoStype, value=None, parameters=[], woa=None):\n self.type = EoStype\n self.parameters = parameters\n if value is not None:\n self.value = value\n elif woa:\n from EPIC.cosmology import EoS_parametrizations\n self.w_of_a = eval('EoS_parametrizations.%s' % woa)\n self.cosmological_constant = self.type == 'cosmological_constant'\n self.pressureless = self.type == 'pressureless'\n self.constant_EoS = self.type == 'constant'\n\n\nclass Fluid(object):\n\n def __init__(self, name, w, density_parameter):\n self.name = name\n self.EoS = w\n self.density_parameter = density_parameter\n\n def is_directly_solvable(self):\n conditions = []\n conditions.append(isinstance(self, NonInteractingFluid))\n conditions.append(isinstance(self, InteractingFluid) and (self.EoS.cosmological_constant or not hasattr(self, 'interacts_with')))\n return np.any(conditions)\n\n def rho_over_rho0(self, a, a0=1, **kwargs):\n if isinstance(self, NonInteractingFluid):\n if self.EoS.type == 'cosmological_constant':\n if isinstance(a, float):\n return 1\n return np.ones_like(a)\n else:\n if self.EoS.type == 'pressureless':\n return self.rho_parametric_EoS(a, w0=0, exp_integral=1, xi=0, a0=a0)\n if self.EoS.type == 'constant':\n w0 = getattr(self.EoS, 'value', None)\n if w0 is None:\n assert len(self.EoS.parameters) == 1\n w0 = self.EoS.parameters[0].get_value(**kwargs)\n return self.rho_parametric_EoS(a, w0=w0, exp_integral=1, xi=0, a0=a0)\n return self.rho_parametric_EoS(a, w0=0, exp_integral=True, xi=0, a0=a0, **kwargs)\n else:\n if isinstance(self, InteractingFluid):\n try:\n xi = self.interaction_parameter.get_value(**kwargs)\n except AttributeError:\n xi = self.interacts_with.interaction_parameter.get_value(**kwargs)\n\n xi *= self.interaction_sign\n if not hasattr(self, 'interacts_with'):\n if self.EoS.type in ('constant', 'cosmological_constant', 'pressureless'):\n w0 = getattr(self.EoS, 'value', None)\n if w0 is None:\n assert len(self.EoS.parameters) == 1\n w0 = self.EoS.parameters[0].get_value(**kwargs)\n exp_integral = 1\n else:\n w0 = 0\n exp_integral = True\n return self.rho_parametric_EoS(a, w0=w0, exp_integral=exp_integral, xi=xi, a0=a0, **kwargs)\n if self.EoS.cosmological_constant:\n assert self.EoS.value == -1\n if self.interacts_with.EoS.type in ('cosmological_constant', 'constant',\n 'pressureless'):\n wb = getattr(self.interacts_with.EoS, 'value', None)\n if wb is None:\n assert len(self.interacts_with.Eos.parameters) == 1\n wb = self.interacts_with.EoS.parameters[0].get_value(**kwargs)\n return self.interacting_rho_parametric_EoS(a, wb=wb, expintb=1, xi=xi, a0=a0, **kwargs)\n else:\n return self.interacting_rho_parametric_EoS(a, wb=0, expintb=self.interacts_with, xi=xi, a0=a0, **kwargs)\n else:\n raise NotAnalytic('Should not have come here. Check direct solving conditions.')\n else:\n raise Unsupported('What kind of fluid is this?')\n\n def interacting_rho_parametric_EoS(self, a, wb=0, expintb=1, xi=0, a0=1, **kwargs):\n if isinstance(expintb, InteractingFluid):\n expintb = expintb.get_exponential_int_w_over_a(a, a0=a0, **kwargs)\n xib = xi * self.interacts_with.interaction_sign\n xia = xi * self.interaction_sign\n assert self.interacts_with.interaction_sign == -self.interaction_sign\n rhoa0 = self.density_parameter.get_value(**kwargs)\n rhob0 = self.interacts_with.density_parameter.get_value(**kwargs)\n return 1 + rhob0 / rhoa0 * xia / (xib - 1 - wb) * expintb ** (-3) * ((a / a0) ** (3 * (xib - 1 - wb)) - 1)\n\n def rho_parametric_EoS(self, a, w0=0, exp_integral=1, xi=0, a0=1, **kwargs):\n if exp_integral is True:\n exp_integral = self.get_exponential_int_w_over_a(a, a0=a0, **kwargs)\n return (a / a0) ** (3 * (xi - 1 - w0)) * exp_integral ** (-3)\n\n def get_exponential_int_w_over_a(self, a, a0=1, **kwargs):\n try:\n return self.EoS.w_of_a(a, a0=a0, expIwoa=True, **kwargs)\n except NotAnalytic:\n return np.exp(integrate.quad(lambda A: self.EoS.w_of_a(A, a0=a0, **kwargs) / A, a0, a))\n\n def drho_da(self, rho, a, intermediate=[], a0=1, **kwargs):\n assert len(intermediate) == 1\n Q = self.Q(a, **kwargs) if hasattr(self, 'Q') else 0\n w = getattr(self.EoS, 'value', None)\n if w is None:\n if self.EoS.type == 'constant':\n w = self.EoS.parameters[0].get_value(**kwargs)\n else:\n w = self.EoS.w_of_a(a, a0=a0, **kwargs)\n return Q - 3 * rho * (1 + w) / a\n\n\nclass NonInteractingFluid(Fluid):\n\n def __init__(self, name, w, density_parameter):\n super().__init__(name, w, density_parameter)\n self.directly_solvable = self.is_directly_solvable()\n\n\nclass InteractingFluid(Fluid):\n __doc__ = '\\n because of interacting_other, must always define first the simpler\\n interacting fluid, which depends on its own density.\\n '\n\n def __init__(self, name, w, density_parameter, interaction_setup={}, model_name=None):\n \"\"\" uses the following keys for interaction_setup:\n parameter, tex_paramter, sign, propto_other.\n Omitting any of them will default to None.\n \"\"\"\n super().__init__(name, w, density_parameter)\n self.interaction_parameter = interaction_setup.get('parameter')\n if self.interaction_parameter is not None:\n tex_parameter = interaction_setup.get('tex_parameter')\n self.interaction_parameter = FreeParameter(self.interaction_parameter, tex=tex_parameter, model_name=model_name)\n self.interaction_sign = interaction_setup.get('sign')\n self.interaction_propto_other = interaction_setup.get('propto_other')\n if self.interaction_propto_other is None:\n assert self.interaction_sign is not None\n else:\n self.Q = self.two_fluid_propto_other\n self.directly_solvable = self.is_directly_solvable()\n\n def two_fluid_propto_other(self, a, **kwargs):\n xi = self.interacts_with.interaction_parameter.get_value(**kwargs)\n other = self.interacts_with.density_parameter.get_value(**kwargs)\n return self.interaction_sign * 3 * other * xi / a\n\n\nclass Parameter(object):\n\n def __repr__(self):\n return ' '.join([str(self.__class__).split('.')[(-1)].rstrip(\"'>\"),\n self.label])\n\n\nclass FreeParameter(Parameter):\n\n def __init__(self, label, tex=None, model_name='DEFAULT'):\n self.label = label\n self.tex = tex or label\n for attribute, source, alt in (\n [\n 'default', 'default_parameter_values.ini',\n '\"(missing default value for %s)\"' % self.label],\n [\n 'default_gaussiansigmas',\n 'default_parameter_gaussiansigmapriors.ini', ''],\n [\n 'default_flatpriors', 'default_parameter_flatpriors.ini', '']):\n default_values = configparser.ConfigParser()\n default_values.read([\n os.path.join(root, 'cosmology', source),\n os.path.join(user_folder, 'modifications', 'cosmology', source)])\n model_name_or_default = model_name if model_name in default_values else 'DEFAULT'\n value = default_values[model_name_or_default].get(label)\n value = alt if value is None else eval(value)\n setattr(self, attribute, value)\n\n def set_prior(self, *pars, distribution='Flat'):\n from EPIC.utils.statistics import FlatPrior, GaussianPrior\n self.prior = eval('%sPrior' % distribution)(*pars)\n\n def get_value(self, **kwargs):\n try:\n return self.sim_value\n except AttributeError:\n if hasattr(self, 'fixed_value'):\n return self.fixed_value\n else:\n parameter_space = kwargs.get('parameter_space', {})\n accepts_default = kwargs.get('accepts_default', False)\n return parameter_space.get(self.label, self.default if accepts_default else None)\n\n def set_default_priors(self, event=None):\n p = self.prior_setup\n dist = p.prior_dist.get()\n if 'Flat' in dist:\n a, b = self.default_flatpriors\n p.parameters_var[0].set(a)\n p.parameters_var[1].set(b)\n p.sig_var.set(self.default_gaussiansigmas / 10)\n else:\n if 'Gaussian' in dist:\n p.parameters_var[0].set(self.default)\n p.parameters_var[1].set(self.default_gaussiansigmas)\n p.sig_var.set(self.default_gaussiansigmas / 10)\n elif 'Fixed' in dist:\n p.parameters_var[0].set(self.default)\n p.sig_var.set(0.0)\n\n\nclass NuisanceParameter(FreeParameter):\n pass\n\n\nclass HubbleFreeParameter(FreeParameter):\n pass\n\n\nclass DensityParameter(FreeParameter):\n\n def __init__(self, label, tex, physical=True, model_name='DEFAULT'):\n super().__init__(label, tex=tex, model_name=model_name)\n self.physical = physical\n\n\nclass DensityFromTemperature(DensityParameter):\n\n def __init__(self, temp_parameter, physical=True, model_name='DEFAULT'):\n self.temperature = temp_parameter\n super().__init__(self.temperature.label, self.temperature.tex, physical=physical, model_name=model_name)\n\n def get_value(self, **kwargs):\n try:\n return self.sim_value\n except AttributeError:\n try:\n return self.fixed_value\n except AttributeError:\n T = self.temperature.get_value(**kwargs)\n Omega = get_Omega_from_Temperature(T)\n sub_species = kwargs.get('sub_species', None)\n if sub_species == 'photons':\n pass\n else:\n if sub_species == 'neutrinos':\n Omega *= 0.68132195298\n else:\n assert sub_species is None\n Omega *= 1.68132195298\n if self.physical:\n return Omega\n else:\n h = self.hubble.get_value(**kwargs) / 100\n if hasattr(self.temperature, 'fixed_value'):\n self.fixed_value = Omega / h ** 2\n return self.fixed_value\n return Omega / h ** 2\n\n\nclass DerivedParameter(Parameter):\n\n def __init__(self, label, dependencies, tex=None, physical=None):\n self.label = label\n self.tex = tex or label\n self.physical = physical\n self.dependencies = dependencies\n\n def flatness(self, densities, **kwargs):\n Omegas_sum = sum([Omega.get_value(**kwargs) for Omega in densities])\n if self.physical:\n return self.hubble.get_value(**kwargs) ** 2 - Omegas_sum\n return 1 - Omegas_sum\n\n def Hubble(self, densities, **kwargs):\n assert self.physical\n Omegas_sum = sum([Omega.get_value(**kwargs) for Omega in densities])\n return np.sqrt(Omegas_sum)\n\n def get_value(self, **kwargs):\n try:\n return self.sim_value\n except AttributeError:\n if isinstance(self, HubbleDerivedParameter):\n return self.Hubble(self.dependencies, **kwargs)\n else:\n return self.flatness(self.dependencies, **kwargs)\n\n def get_available_species(self):\n available_species = configparser.ConfigParser()\n available_species.read([\n os.path.join(root, 'cosmology', 'available_species.ini'),\n os.path.join(user_folder, 'modifications', 'cosmology', 'available_species.ini')])\n return available_species\n\n\nclass HubbleDerivedParameter(DerivedParameter):\n pass\n\n\nclass DerivedDensityDistribution(DerivedParameter):\n\n def __init__(self, name, h, dens_parameter, h_bf, bestfit, physical=True):\n self.name = name\n if physical:\n self.Omega = [\n dens_parameter / h ** 2]\n self.bestfit = [bestfit / h_bf ** 2]\n else:\n self.Omega = [\n dens_parameter * h ** 2]\n self.bestfit = [bestfit * h_bf ** 2]\n available_species = self.get_available_species()\n physical_ = '' if physical else 'physical '\n self.label = [available_species[('%sdensity parameter' % physical_)].get(self.name)]\n self.tex = [\n available_species[('tex %sdensity parameter' % physical_)].get(self.name, self.label[0])]\n\n\nclass DerivedParameterDensityDistribution(DerivedParameter):\n\n def __init__(self, name, h, dependencies, h_bf, dependencies_bf, physical=True):\n self.name = name\n self.physical = physical\n self.Omega = self.flatness(dependencies, h=h)\n self.bestfit = self.flatness(dependencies_bf, h=h_bf)\n available_species = self.get_available_species()\n self.label = [available_species['physical density parameter'].get(self.name),\n available_species['density parameter'].get(self.name)]\n self.tex = [available_species['tex physical density parameter'].get(self.name),\n available_species['tex density parameter'].get(self.name)]\n\n def flatness(self, densities, h=None):\n Omegas_sum = sum(densities)\n h2 = h ** 2\n if self.physical:\n return [h2 - Omegas_sum, 1 - Omegas_sum / h2]\n return [\n h2 - Omegas_sum * h2, 1 - Omegas_sum]\n\n\nclass DerivedParameterMatterDensityDistribution(DerivedParameterDensityDistribution):\n\n def flatness(self, constituents, h=None):\n Omega = sum(constituents)\n h2 = h ** 2\n if self.physical:\n return [Omega, Omega / h2]\n return [\n Omega * h2, Omega]\n\n\nclass DerivedDensityFromTemperature(DerivedParameter):\n\n def __init__(self, name, h, Tg, h_bf, bestfit):\n self.name = name\n Omega = get_Omega_from_Temperature(Tg)\n self.Omega = [Omega, Omega / h ** 2]\n Omega_bf = get_Omega_from_Temperature(bestfit)\n self.bestfit = [Omega_bf, Omega_bf / h_bf ** 2]\n self.label = ['Orh2', 'Or0']\n self.tex = ['\\\\Omega_{r0}h^2', '\\\\Omega_{r0}']\n\n\nclass Cluster(object):\n\n def __init__(self, name, redshift, Mmu, Msig, cmu, csig, Tmu, Tsig, Tsym, dT):\n self.name = name\n self.z = float(redshift)\n logM200 = uncertainties.ufloat_fromstr(Mmu + '+/-' + Msig)\n logc = uncertainties.ufloat_fromstr(cmu + '+/-' + csig)\n Om = 0.3\n Ode = 1 - Om\n self.Hz = 100 * np.sqrt(Om * (1 + self.z) ** 3 + Ode)\n self.rhoc = rho_critical(self.Hz)\n roM = (3 / (4 * np.pi) / 200 / self.rhoc) ** 0.3333333333333333 * 46415.88833612776\n temperature = {}\n try:\n temperature['logT'] = uncertainties.ufloat_fromstr(Tmu + '+/-' + Tsig)\n except ValueError:\n temperature['Tsym'] = uncertainties.ufloat_fromstr(Tsym + '+/-' + dT)\n\n self.fc, self.dFdc = self.fc_gc_dFdc_from_c(logc)\n self.ovr = get_OVR(roM, temperature, logM200, self.fc)\n\n def fc_gc_dFdc_from_c(self, logc):\n self.c = umath.exp(logc)\n c = self.c\n one_plus_c = 1 + c\n two_plus_c = 2 + c\n c_squared = c * c\n log_one_plus_c = umath.log(one_plus_c)\n one_plus_c__times__log_opc = one_plus_c * log_one_plus_c\n one_plus_c__times__logsquare = one_plus_c__times__log_opc * log_one_plus_c\n fc = one_plus_c__times__logsquare - 2 * c * log_one_plus_c\n fc = fc + one_plus_c * c_squared / one_plus_c ** 2\n fc = fc / c / (0.5 * (one_plus_c - 1 / one_plus_c) - log_one_plus_c)\n dFdc = 2 * (one_plus_c__times__log_opc - c)\n dFdc = dFdc * (c * (4 + 5 * c + c_squared) * log_one_plus_c - c_squared * (2 + 3 * c) - 2 * one_plus_c__times__logsquare)\n dFdc = -1 * dFdc / (c_squared * (c * two_plus_c - 2 * one_plus_c__times__log_opc) ** 2)\n return (fc, dFdc)\n\n def __repr__(self):\n return self.name\n\n\ndef get_OVR(roM, temperature, logM200, fc):\n try:\n ovr = umath.exp(-0.6666666666666666 * logM200 + temperature['logT'])\n except KeyError:\n ovr = umath.exp(-0.6666666666666666 * logM200) * temperature['Tsym']\n\n ovr *= roM * fc\n ovr *= -1.5e-14 / GmumH\n return ovr\n\n\ndef get_Omega_from_Temperature(T):\n rho = a_B_over_c2 * T ** 4\n rho_cr = rho_critical_SI(100)\n return rho / rho_cr","sub_path":"pycfiles/epic-code-1.4.tar/cosmic_objects.cpython-35.py","file_name":"cosmic_objects.cpython-35.py","file_ext":"py","file_size_in_byte":34103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510760354","text":"import os\nfrom .queries import GET_TABLE_SCHEMA\nfrom . import TYPE_MAP, db_conn\n\n\nclass Scanner(object):\n\n def __init__(self, db_url):\n self.conn = db_conn(db_url)\n\n def get_table_schema(self, table_name):\n r = None\n try:\n with self.conn.cursor() as c:\n c.execute(GET_TABLE_SCHEMA, (table_name, ))\n r = c.fetchall()\n except Exception:\n pass\n return r\n\n def build_props(self, table_name):\n cols = self.get_table_schema(table_name)\n props = {}\n for col in cols:\n props[col[0]] = dict(type=TYPE_MAP[col[1]])\n return props\n","sub_path":"es_map_writer/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"131521","text":"import pandas as pd\r\nimport numpy as np\r\n\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\nfrom xgboost import XGBClassifier\r\nfrom lightgbm import LGBMClassifier\r\nfrom catboost import CatBoostClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier\r\n\r\n# Regularized Greedy Forest\r\nfrom rgf.sklearn import RGFClassifier # https://github.com/fukatani/rgf_python\r\n\r\ntrain = pd.read_csv('../input/train.csv')\r\ntest = pd.read_csv('../input/test.csv')\r\n\r\n# Preprocessing (Baseline)\r\nid_test = test['id'].values\r\nprint(\"data loaded\")\r\n\r\nprint(train.shape)\r\n#print(train.info())\r\nprint(train.columns)\r\nprint(test.shape)\r\n\r\n#Use only required columns, from xgb feature importance\r\ntrain_features = [\r\n \"ps_car_13\", # : 1571.65 / shadow 609.23\r\n \"ps_reg_03\", # : 1408.42 / shadow 511.15\r\n \"ps_ind_05_cat\", # : 1387.87 / shadow 84.72\r\n \"ps_ind_03\", # : 1219.47 / shadow 230.55\r\n \"ps_ind_15\", # : 922.18 / shadow 242.00\r\n \"ps_reg_02\", # : 920.65 / shadow 267.50\r\n \"ps_car_14\", # : 798.48 / shadow 549.58\r\n \"ps_car_12\", # : 731.93 / shadow 293.62\r\n \"ps_car_01_cat\", # : 698.07 / shadow 178.72\r\n \"ps_car_07_cat\", # : 694.53 / shadow 36.35\r\n \"ps_ind_17_bin\", # : 620.77 / shadow 23.15\r\n \"ps_car_03_cat\", # : 611.73 / shadow 50.67\r\n \"ps_reg_01\", # : 598.60 / shadow 178.57\r\n \"ps_car_15\", # : 593.35 / shadow 226.43\r\n \"ps_ind_01\", # : 547.32 / shadow 154.58\r\n \"ps_ind_16_bin\", # : 475.37 / shadow 34.17\r\n \"ps_ind_07_bin\", # : 435.28 / shadow 28.92\r\n \"ps_car_06_cat\", # : 398.02 / shadow 212.43\r\n \"ps_car_04_cat\", # : 376.87 / shadow 76.98\r\n \"ps_ind_06_bin\", # : 370.97 / shadow 36.13\r\n \"ps_car_09_cat\", # : 214.12 / shadow 81.38\r\n \"ps_car_02_cat\", # : 203.03 / shadow 26.67\r\n \"ps_ind_02_cat\", # : 189.47 / shadow 65.68\r\n \"ps_car_11\", # : 173.28 / shadow 76.45\r\n \"ps_car_05_cat\", # : 172.75 / shadow 62.92\r\n \"ps_calc_09\", # : 169.13 / shadow 129.72\r\n \"ps_calc_05\", # : 148.83 / shadow 120.68\r\n \"ps_ind_08_bin\", # : 140.73 / shadow 27.63\r\n \"ps_car_08_cat\", # : 120.87 / shadow 28.82\r\n \"ps_ind_09_bin\", # : 113.92 / shadow 27.05\r\n \"ps_ind_04_cat\", # : 107.27 / shadow 37.43\r\n \"ps_ind_18_bin\", # : 77.42 / shadow 25.97\r\n \"ps_ind_12_bin\", # : 39.67 / shadow 15.52\r\n \"ps_ind_14\", # : 37.37 / shadow 16.65\r\n]\r\n\r\n#create X,y,T\r\nX = train[train_features].values\r\ny = train.loc[:,'target'].values\r\nT = test[train_features].values\r\n\r\n#create the models\r\n# LightGBM params\r\nlgb_params_1 = {\r\n 'learning_rate': 0.01,\r\n 'n_estimators': 1250,\r\n 'max_bin': 10,\r\n 'subsample': 0.8,\r\n 'subsample_freq': 10,\r\n 'colsample_bytree': 0.8, \r\n 'min_child_samples': 500\r\n}\r\n\r\nlgb_params_2 = {\r\n 'learning_rate': 0.005,\r\n 'n_estimators': 3700,\r\n 'subsample': 0.7,\r\n 'subsample_freq': 2,\r\n 'colsample_bytree': 0.3, \r\n 'num_leaves': 16\r\n}\r\n\r\nlgb_params_3 = {\r\n 'objective':'binary:logistic',\r\n 'learning_rate':0.02,\r\n 'n_estimators':1000,\r\n 'max_depth':4,\r\n 'subsample':0.9,\r\n 'colsample_bytree':0.9, \r\n 'min_child_weight':10\r\n}\r\n\r\nlgb_params_4 = {\r\n 'objective':'binary:logistic',\r\n 'learning_rate':0.02,\r\n 'n_estimators':1000,\r\n 'max_depth':4,\r\n 'subsample':0.9,\r\n 'colsample_bytree':0.9, \r\n 'min_child_weight':10\r\n}\r\n\r\nlgb_model_1 = LGBMClassifier(**lgb_params_1)\r\nlgb_model_2 = LGBMClassifier(**lgb_params_2)\r\nlgb_model_3 = XGBClassifier(**lgb_params_3)\r\n#base_models = (lgb_model_1, lgb_model_2, lgb_model_3)\r\nbase_models = (lgb_model_1, lgb_model_2)\r\n\r\nlog_model = LogisticRegression()\r\nstacker = log_model\r\nprint(\"models created\")\r\n\r\n#now we have the data with equal set of positives and negatives\r\n#lets check cross validation scores\r\nn_splits=3\r\nfolds = list(StratifiedKFold(n_splits, shuffle=True, random_state=15).split(X, y))\r\n\r\nS_train = np.zeros((X.shape[0], len(base_models)))\r\nS_test = np.zeros((T.shape[0], len(base_models)))\r\nfor i, clf in enumerate(base_models):\r\n S_test_i = np.zeros((T.shape[0], n_splits))\r\n for j, (train_idx, test_idx) in enumerate(folds):\r\n X_train = X[train_idx]\r\n y_train = y[train_idx]\r\n X_holdout = X[test_idx]\r\n print(X_train.shape)\r\n # Get positive examples\r\n pos = pd.Series(y_train == 1)\r\n # Add positive examples\r\n X_train = pd.concat([pd.DataFrame(X_train), pd.DataFrame(X_train[pos])])\r\n y_train = pd.concat([pd.DataFrame(y_train), pd.DataFrame(y_train[pos])])\r\n # Shuffle data\r\n idx = np.arange(len(X_train))\r\n np.random.shuffle(idx)\r\n X_train = X_train.iloc[idx]\r\n y_train = y_train.iloc[idx]\r\n\r\n print (\"Fit %s fold %d\" % (str(clf).split('(')[0], j+1))\r\n clf.fit(X_train, y_train)\r\n y_pred = clf.predict_proba(X_holdout)[:,1] \r\n\r\n S_train[test_idx, i] = y_pred\r\n S_test_i[:, j] = clf.predict_proba(T)[:,1]\r\n \r\n S_test[:, i] = S_test_i.mean(axis=1)\r\n\r\nresults = cross_val_score(stacker, S_train, y, cv=5, scoring='roc_auc')\r\nprint(\"Stacker score: %.5f\" % (results.mean()))\r\nprint(results)\r\nprint(\"S train size is : \", S_train.shape)\r\nstacker.fit(S_train, y)\r\nres = stacker.predict_proba(S_test)[:,1]\r\n\r\nprint(res)\r\n\r\nprint(results)\r\nprint(res)\r\n\r\nsub = pd.DataFrame()\r\nsub['id'] = id_test\r\nsub['target'] = res\r\nsub.to_csv('stacked_result_strat_upsample.csv', index=False)\r\n\r\nprint('completed')","sub_path":"SafeDriver/Safe_Driver_21.py","file_name":"Safe_Driver_21.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"455716289","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*- \n\nimport urllib.request\nimport lxml.html\nimport lxml.etree\nimport urllib\nimport pymysql\nimport time\nimport urllib.request\nimport zipfile\n\ndef unzip(zip_file, outdir):\n \"\"\"\n Unzip a given 'zip_file' into the output directory 'outdir'.\n \"\"\"\n \n zf.extractall(outdir)\n \ndef ProcessSPO():\n import os\n directory = \"/tmp/spo/\"\n files = os.listdir(directory)\n #print(files)\n for file_name in files:\n if \".zip\" in file_name:\n print(\"unzip: \"+file_name)\n zf = zipfile.ZipFile(directory+file_name)\n zf.extractall(\"/tmp/spo\") \n os.remove(directory+file_name)\n return 1\n\ndef ImportSPO():\n print(\"ImportSPO\")\n tree = lxml.etree.parse(\"/tmp/spo/spo.xml\")\n offers = tree.xpath('/OFFERS/OFFER')\n print(len(offers))\n n = 1\n for offer in offers:\n #if offer.get('ADL')==\"2\":\n # if \"\"\n print(offer.keys())\n n = n + 1\n #print(offer.get('COUNTRYC'),offer.get('TOURTYPE'),offer.get('CURRENCYC'))\n return 1 \n \ndef GetCurrStamp():\n currstamp = ''\n query = urllib.request.urlopen(\"http://agency.pegast.ru/samo5/export/default.php?samo_action=reference&oauth_token=f3f0bee75befb8e616a864e05206a1e9&type=currentstamp\");\n tree = lxml.etree.fromstring(query.read())\n stamp = tree.xpath('/Response/Data/currentstamp')\n for curr in stamp:\n currstamp = curr.values()[0]\n return currstamp\n\ndef GetDict(stamp,type):\n last_stamp=hex(0)\n search_cont = True\n list=[] \n print(\"get \"+str(type)+\" dict;\")\n len_item = 0\n while search_cont:\n url = \"http://agency.pegast.ru/samo5/export/default.php?samo_action=reference&oauth_token=f3f0bee75befb8e616a864e05206a1e9&type=\"+type+\"&laststamp=\"+last_stamp+\"&delstamp=\"+stamp\n #print(url)\n query = urllib.request.urlopen(url);\n tree = lxml.etree.fromstring(query.read())\n xpath_url=\"/Response/Data/\"+str(type)\n xpath_tree = tree.xpath(xpath_url)\n xpath_len=len(xpath_tree)\n if xpath_len>0:\n print(\"get \"+str(len(xpath_tree))+\" items. Stamp: \"+str(last_stamp))\n n = 0\n m = 0\n for item in xpath_tree:\n m = m+1\n try: \n if type==\"htplace\":\n #print(item.values())\n l = [item.values()[0],item.values()[2],item.values()[3]]\n # print(m)\n ls = item.values()[-1]\n list.append(l) \n else: \n if len(item)>=len_item:\n list.append(item.values())\n len_item=len(item)\n except:\n print(\"except: \",item.values())\n n = n + 1\n if type==\"htplace\":\n last_stamp = ls\n else:\n last_stamp = list[-1][-1]\n # print(\"Last stamp: \"+str(last_stamp))\n if xpath_len<500:\n search_cont = False\n else:\n search_cont = False\n #print(\"last request\")\n print(len(list))\n # print(list) \n return list\t\n\ndef mysql_dict(list,type,count):\n print(\"connect to database\")\n conn = pymysql.connect(host='localhost',user='pegast',passwd='pegast',db='pegast',charset='utf8')\n conn.autocommit(1)\n cur = conn.cursor()\n print(\"clear table \"+str(type))\n \n cur.execute(\"truncate \"+str(type))\n cur.close()\n n = 0\n print(len(list))\n c = 0\n for item in list:\n # print(item)\n n=0\n \n skeep_item = 0\n if len(item)0:\n for item in xpath_tree:\n if len(item.values())==9:\n #print(item.values())\n list.append(item.values())\n print(len(list))\n spo_cont = False\n return list\n\ndef SaveSpoZip():\n import os.path\n print(\"connect to database\")\n conn = pymysql.connect(host='localhost',user='pegast',passwd='pegast',db='pegast',charset='utf8')\n sql = \"SELECT url_file FROM spo\"\n cur = conn.cursor()\n cur.execute(sql)\n \n n = 0\n for row in cur:\n print(\"save[\"+str(n)+\"]:\"+row[0])\n #print(n)\n n = n+1\n savepath = \"/tmp/spo/\"+str(os.path.basename(row[0]))\n #print(savepath)\n SaveUrl(row[0],savepath)\n cur.close()\n conn.close()\n return 1 \n\n#refresh_dict()\n#ClearSPODB\n#UpdateSPO(get_spo(97,8))\nprint(\"start\")\n#SaveSpoZip()\n#ProcessSPO()\n#ImportSPO()\ntest_dict()\nprint(\"stop\")\n","sub_path":"pegast.py","file_name":"pegast.py","file_ext":"py","file_size_in_byte":12608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"452022008","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n#\n#\n# MIT License\n#\n# Copyright (c) 2017 Mattia Verga \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\"\"\"Creates sqlite3 database from csv OpenNGC file.\nThe first line of the csv file, which contains the headers, must be removed.\n\n Usage: createdb.py\n\"\"\"\n\nimport os\nimport csv\nimport sqlite3\n#\noutputFile = os.path.join(os.path.dirname(__file__), os.pardir, 'pyongc', 'ongc.db')\n\n# Dictionaries\nobjectTypes = {'*':'Star',\n '**':'Double star',\n '*Ass':'Association of stars',\n 'OCl':'Open Cluster',\n 'GCl':'Globular Cluster',\n 'Cl+N':'Star cluster + Nebula',\n 'G':'Galaxy',\n 'GPair':'Galaxy Pair',\n 'GTrpl':'Galaxy Triplet',\n 'GGroup':'Group of galaxies',\n 'PN':'Planetary Nebula',\n 'HII':'HII Ionized region',\n 'DrkN':'Dark Nebula',\n 'EmN':'Emission Nebula',\n 'Neb':'Nebula',\n 'RfN':'Reflection Nebula',\n 'SNR':'Supernova remnant',\n 'Nova':'Nova star',\n 'NonEx':'Nonexistent object',\n 'Other':'Object of other/unknown type',\n 'Dup':'Duplicated record'}\n\n# Create db\ntry:\n db = sqlite3.connect(outputFile)\n cursor = db.cursor()\n\n # Create objects types table\n cursor.execute(\"DROP TABLE IF EXISTS objTypes\")\n cursor.execute('''CREATE TABLE IF NOT EXISTS objTypes(\n type TEXT PRIMARY KEY NOT NULL,\n typedesc TEXT NOT NULL\n )''')\n listTypes = objectTypes.items()\n cursor.executemany(\"INSERT INTO objTypes VALUES(?,?)\", listTypes)\n\n # Create main objects table\n cursor.execute(\"DROP TABLE IF EXISTS objects\")\n cursor.execute('''CREATE TABLE IF NOT EXISTS objects(\n id INTEGER PRIMARY KEY NOT NULL,\n name TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n ra TEXT,\n dec TEXT,\n const TEXT,\n majax REAL,\n minax REAL,\n pa INTEGER,\n bmag REAL,\n vmag REAL,\n jmag REAL,\n hmag REAL,\n kmag REAL,\n sbrightn REAL,\n hubble TEXT,\n cstarumag REAL,\n cstarbmag REAL,\n cstarvmag REAL,\n messier INTEGER,\n ngc TEXT,\n ic TEXT,\n cstarnames TEXT,\n identifiers TEXT,\n commonnames TEXT,\n nednotes TEXT,\n ongcnotes TEXT\n )''')\n\n with open(\"NGC.csv\", 'r') as csvFile:\n reader = csv.reader(csvFile, delimiter=\";\")\n for line in reader:\n cursor.execute('''INSERT INTO objects(name,type,ra,dec,const,majax,minax,pa,bmag,vmag,\n jmag,hmag,kmag,sbrightn,hubble,cstarumag,cstarbmag,cstarvmag,messier,ngc,ic,\n cstarnames,identifiers,commonnames,nednotes,ongcnotes)\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\n ''', (line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8],\n line[9],line[10],line[11],line[12],line[13],line[14],line[15],line[16],line[17],\n line[18],line[19],line[20],line[21],line[22],line[23],line[24],line[25]))\n\n db.commit()\n\nexcept Exception as e:\n db.rollback()\n raise e\n\nfinally:\n db.close()\n","sub_path":"helper/createdb.py","file_name":"createdb.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"54981485","text":"# -*- coding: utf-8 -*-\n# Author: 无名的弗兰克 @ ChemDog\n# https://github.com/Frank-the-Obscure/\n# misc function for i/o of basic data\n\nimport re\nimport math\nfrom sys import argv\n\n#file1 = 'first100user.txt'\n#file1 = 'weibo_train_data.txt'\n\nscript, filein_name = argv\n#filein = open(filein_name, encoding='utf-8')\n\n#fileout = open('predict_1000_average.txt', 'w')\n\n#predict = open('predict/predict_1000_average.txt') \n#real = open('predict/predict_1000_real.txt') \n\n#predict_file = open('first1000user.txt')\n#predict_data = open('uid_average.txt')\n\ndef sep(filein):\n f = filein.readlines()\n print(len(f[:100000]), len(f[100000:200000]), len(f[200000:]))\n\n fileout = open(filein_name + '-0.txt', 'w', encoding='utf-8')\n fileout.writelines(f[:100000])\n fileout = open(filein_name + '-1.txt', 'w', encoding='utf-8')\n fileout.writelines(f[100000:200000])\n fileout = open(filein_name + '-2.txt', 'w', encoding='utf-8')\n fileout.writelines(f[200000:])\n\ndef predict_000(filein, fileout):\n \"\"\"保留前两列内容, 写下000\n\n 前两列内容必须为 uid, mid\n \"\"\"\n t = re.compile('\\t')\n\n for line in filein:\n data = t.split(line)\n del data[2:]\n data.append('0,0,0')\n fileout.write('\\t'.join(data))\n fileout.write('\\n')\n\ndef predict_average(predict_file, predict_data, fileout):\n \"\"\"用 predict_data 的数据预测 predict_file\n\n i: predict_file, 暂时用 000 data\n p: 把 000 换成 average\n \"\"\"\n\n t = re.compile('\\t')\n predict_data = predict_data.readlines()\n\n dataset = {}\n\n for line in predict_data:\n uid, num_post, f,c,l = t.split(line)\n f = round(float(f))\n c = round(float(c))\n l = round(float(l))\n dataset[uid] = '{},{},{}'.format(f, c, l)\n \n i = 0\n for line in predict_file:\n uid, mid = t.split(line)[0], t.split(line)[1]\n\n if uid in dataset:\n fileout.write(uid + '\\t' + mid + '\\t' + dataset[uid] + '\\n')\n else:\n fileout.write(uid + '\\t' + mid + '\\t' + '0,0,0' + '\\n')\n\ndef get_data_and_write(filein, fileout):\n \"\"\"用 readline 逐行读入数据并 unpack\n\n 可用适当参数输出\n \"\"\"\n t = re.compile('\\t')\n time_sep = re.compile('-')\n\n temp = []\n for line in filein: # write number of users as demand in num_user \n (uid, mid, time, forward_count,\n comment_count, like_count, content) = t.split(line)\n yyyy, mm, dd = time_sep.split(time)\n #print(yyyy, mm, dd)\n forward_count = int(forward_count)\n comment_count = int(comment_count)\n like_count = int(like_count)\n if forward_count == 0 and comment_count == 0 and like_count == 0:\n fileout000.write(line)\n else: \n fileout111.write(line)\n if forward_count != 0:\n fileout100.write(line)\n if comment_count != 0:\n fileout010.write(line)\n if like_count != 0:\n fileout001.write(line)\n if forward_count and comment_count and like_count:\n fileout222.write(line)\n '''\n fileout.write(uid + '\\t' + mid + '\\t' + str(len(content)) + '\\t')\n fileout.write(forward_count + ',' + \n comment_count + ',' + \n like_count + '\\n')'''\n '''fileout.write('\\t'.join([uid, mid, time, \n forward_count, comment_count, like_count, \n str(len(content)), content]))'''\n\ndef precision(predict, real):\n \"\"\"实现计算精度的算法\n\n http://tianchi.aliyun.com/competition/information.htm?spm=0.0.0.0.31CeDM&raceId=5\n \"\"\"\n\n find = re.compile('\\d+,\\d+,\\d+')\n split = re.compile(',')\n\n precision_up = 0\n precision_down = 0\n\n for pred_i in predict:\n real_i = real.readline()\n fp, cp, lp = split.split(re.search(find, pred_i).group())\n fp, cp, lp = int(fp), int(cp), int(lp)\n # forward_predict, comment_predict, like_predict\n fr, cr, lr = split.split(re.search(find, real_i).group())\n fr, cr, lr = int(fr), int(cr), int(lr)\n\n # forward_real, comment_real, like_real\n dev_f = math.fabs(fp - fr) / (fr + 5)\n dev_c = math.fabs(cp - cr) / (cr + 3)\n dev_l = math.fabs(lp - lr) / (lr + 3)\n precision_i = 1 - 0.5 * dev_f - 0.25 * dev_c - 0.25 * dev_l\n #print(dev_f, dev_c, dev_l)\n count_i = fr + cr + lr\n if count_i > 100: # counti为第i篇博文的总的转发、评论、赞之和,当counti>100时,取值为100\n count_i = 100\n\n if precision_i - 0.8 > 0:\n precision_up += count_i + 1\n precision_down += count_i + 1\n print(precision_up, precision_down, precision_up / precision_down)\n\ndef get_data_user(filein, num_user):\n \"\"\"读取 n 个用户的全部微博数据\n\n 需要 uid 排序\n 可用适当参数输出\n \"\"\"\n t = re.compile('\\t')\n\n uid0 = ''\n num_post = 0\n sum_f = 0\n sum_c = 0\n sum_l = 0\n i = 0\n j = 0\n fileout = open(filein_name[:-4] + '-' + str(num_user)+ '.txt', 'w', encoding='utf-8')\n while i < num_user: # write number of users as demand in num_user \n line = filein.readline()\n j += 1\n if line:\n uid, mid, time, forward_count, comment_count, like_count, content = t.split(line)\n fileout.write(line)\n else:\n #fileout.write(line)\n #fileout.write('\\n')\n print(j)\n return\n\n if uid != uid0: # new uid\n if uid0:\n pass\n #fileout.write(line)\n #fileout.write('\\n')\n i += 1\n if i % 1000 == 0:\n print(i)\n uid0 = uid\n \n\n if i >= num_user:\n print(j)\n break\n else:\n num_post += 1\n \n #fileout.write('\\t'.join([uid, mid, time, forward_count, comment_count, like_count, str(len(content)), content]))\n\nif __name__ == '__main__':\n #predict_average(predict_file, predict_data, fileout)\n #print(len(filein.readlines()))\n #get_data_and_write(filein, fileout)\n #sep(filein)\n #get_data_user(filein, 1000)\n #predict_000(filein, fileout)\n #get_data(filein, fileout)\n #precision(predict, real)\n f1 = open('7-10-log_reg.txt', encoding='utf-8')\n for i in range(0,10):\n print(f1.readline())\n ","sub_path":"misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":6443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"64836290","text":"import json\nimport os\n\nimport requests\nimport pymongo\nimport simplejson as sjson\nfrom pymongo import MongoClient\nfrom klein import Klein\n\nMONGODB_HOSTNAME = os.getenv('MONGODB_HOSTNAME')\nMONGODB_PORT = int(os.getenv('MONGODB_PORT'))\nMONGODB_USERNAME = os.getenv('MONGODB_USERNAME')\nMONGODB_PASSWORD = os.getenv('MONGODB_PASSWORD')\nclient = MongoClient(host=MONGODB_HOSTNAME,\n port=MONGODB_PORT, \n username=MONGODB_USERNAME, \n password=MONGODB_PASSWORD,\n authSource=\"admin\")\nMONGODB_DATABASE = os.getenv('MONGODB_DATABASE')\napp = Klein()\n\n\ndef get_ghibli_films():\n r = requests.get('https://ghibliapi.herokuapp.com/films')\n if r.status_code == 200:\n return r.json()\n else:\n return {\"messgae\": \"something went wrong\"} \n\n\ndef get_ghibli_film(film_id):\n r = requests.get(f'https://ghibliapi.herokuapp.com/films/{film_id}')\n if r.status_code == 200:\n return r.json()\n else:\n return {\"messgae\": \"something went wrong\"} \n \n\n@app.route('/')\ndef pg_root(request):\n return 'Welcome to Ghibli'\n\n\n@app.route('/api/v1/films/')\ndef pg_films(request):\n content = get_ghibli_films()\n response = json.dumps(content)\n return response\n\n# @app.route('/api/v1/films//')\n# def pg_film(request, film_id):\n# db = client[MONGODB_DATABASE]\n# collection = db.films\n# data = collection.find_one({'film_id': film_id})\n# film = get_ghibli_film(film_id)\n# film['r_name'] = data['r_name'] #.encode(encoding = 'UTF-8',errors = 'strict')\n# response = sjson.dumps(film) #, ensure_ascii=False).encode('utf8')\n# return response\n \n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 8080))\n app.run(\"0.0.0.0\", port)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"384020992","text":"import codecs\nimport os\nimport sys\n\nfrom distutils.core import setup\nfrom pip.req import parse_requirements\n\nif sys.argv[-1] == 'publish':\n os.system('python setup.py sdist upload -r pypi')\n sys.exit()\n\nPACKAGE_VERSION = '0.1.0'\nPACKAGE_DOWNLOAD_URL = (\n 'https://github.com/dbader/jack/tarball/' + PACKAGE_VERSION\n)\n\ninstall_reqs = parse_requirements('requirements.txt')\nreqs = [str(ir.req) for ir in install_reqs]\n\ndef read_file(filename):\n \"\"\"\n Read a utf8 encoded text file and return its contents.\n \"\"\"\n with codecs.open(filename, 'r', 'utf8') as f:\n return f.read()\n\nsetup(\n name='jack',\n packages=['jack'],\n version=PACKAGE_VERSION,\n description='A command line tool for time-based queries on log files.',\n long_description=read_file('README.md'),\n license=read_file('LICENSE'),\n author='Daniel Bader',\n author_email='mail@dbader.org',\n url='https://github.com/dbader/jack',\n download_url=PACKAGE_DOWNLOAD_URL,\n install_requires=reqs,\n entry_points={\n 'console_scripts': [\n 'jack = jack:_main',\n ],\n },\n keywords=[\n 'jack', 'log', 'logs', 'logging', 'query',\n 'search'\n ],\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2.7',\n 'Natural Language :: English',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"169098994","text":"import argparse, time, re, asyncio, functools, base64, random, urllib.parse, socket\nfrom . import proto\nfrom .__doc__ import *\n\nSOCKET_TIMEOUT = 300\nPACKET_SIZE = 65536\nUDP_LIMIT = 30\nDUMMY = lambda s: s\n\nasyncio.StreamReader.read_ = lambda self: self.read(PACKET_SIZE)\nasyncio.StreamReader.read_n = lambda self, n: asyncio.wait_for(self.readexactly(n), timeout=SOCKET_TIMEOUT)\nasyncio.StreamReader.read_until = lambda self, s: asyncio.wait_for(self.readuntil(s), timeout=SOCKET_TIMEOUT)\n\nclass AuthTable(object):\n _auth = {}\n def __init__(self, remote_ip, authtime):\n self.remote_ip = remote_ip\n self.authtime = authtime\n def authed(self):\n return time.time() - self._auth.get(self.remote_ip, 0) <= self.authtime\n def set_authed(self):\n self._auth[self.remote_ip] = time.time()\n\nasync def prepare_ciphers(cipher, reader, writer, bind=None, server_side=True):\n if cipher:\n cipher.pdecrypt = cipher.pdecrypt2 = cipher.pencrypt = cipher.pencrypt2 = DUMMY\n for plugin in cipher.plugins:\n if server_side:\n await plugin.init_server_data(reader, writer, cipher, bind)\n else:\n await plugin.init_client_data(reader, writer, cipher)\n plugin.add_cipher(cipher)\n return cipher(reader, writer, cipher.pdecrypt, cipher.pdecrypt2, cipher.pencrypt, cipher.pencrypt2)\n else:\n return None, None\n\ndef schedule(rserver, salgorithm, host_name, port):\n filter_cond = lambda o: o.alive and (not o.match or o.match(host_name) or o.match(str(port)))\n if salgorithm == 'fa':\n return next(filter(filter_cond, rserver), None)\n elif salgorithm == 'rr':\n for i, roption in enumerate(rserver):\n if filter_cond(roption):\n rserver.append(rserver.pop(i))\n return roption\n elif salgorithm == 'rc':\n filters = [i for i in rserver if filter_cond(i)]\n return random.choice(filters) if filters else None\n elif salgorithm == 'lc':\n return min(filter(filter_cond, rserver), default=None, key=lambda i: i.total)\n else:\n raise Exception('Unknown scheduling algorithm') #Unreachable\n\nasync def stream_handler(reader, writer, unix, lbind, protos, rserver, cipher, sslserver, authtime=86400*30, block=None, salgorithm='fa', verbose=DUMMY, modstat=lambda r,h:lambda i:DUMMY, **kwargs):\n try:\n reader, writer = proto.sslwrap(reader, writer, sslserver, True, None, verbose)\n if unix:\n remote_ip, server_ip, remote_text = 'local', None, 'unix_local'\n else:\n remote_ip, remote_port, *_ = writer.get_extra_info('peername')\n server_ip = writer.get_extra_info('sockname')[0]\n remote_text = f'{remote_ip}:{remote_port}'\n local_addr = None if server_ip in ('127.0.0.1', '::1', None) else (server_ip, 0)\n reader_cipher, _ = await prepare_ciphers(cipher, reader, writer, server_side=False)\n lproto, host_name, port, lbuf, rbuf = await proto.parse(protos, reader=reader, writer=writer, authtable=AuthTable(remote_ip, authtime), reader_cipher=reader_cipher, sock=writer.get_extra_info('socket'), **kwargs)\n if host_name == 'echo':\n asyncio.ensure_future(lproto.channel(reader, writer, DUMMY, DUMMY))\n elif host_name == 'empty':\n asyncio.ensure_future(lproto.channel(reader, writer, None, DUMMY))\n elif block and block(host_name):\n raise Exception('BLOCK ' + host_name)\n else:\n roption = schedule(rserver, salgorithm, host_name, port) or ProxyURI.DIRECT\n verbose(f'{lproto.name} {remote_text}{roption.logtext(host_name, port)}')\n try:\n reader_remote, writer_remote = await roption.open_connection(host_name, port, local_addr, lbind)\n except asyncio.TimeoutError:\n raise Exception(f'Connection timeout {roption.bind}')\n try:\n reader_remote, writer_remote = await roption.prepare_connection(reader_remote, writer_remote, host_name, port)\n writer.write(lbuf)\n writer_remote.write(rbuf)\n except Exception:\n writer_remote.close()\n raise Exception('Unknown remote protocol')\n m = modstat(remote_ip, host_name)\n lchannel = lproto.http_channel if rbuf else lproto.channel\n asyncio.ensure_future(lproto.channel(reader_remote, writer, m(2+roption.direct), m(4+roption.direct)))\n asyncio.ensure_future(lchannel(reader, writer_remote, m(roption.direct), roption.connection_change))\n except Exception as ex:\n if not isinstance(ex, asyncio.TimeoutError) and not str(ex).startswith('Connection closed'):\n verbose(f'{str(ex) or \"Unsupported protocol\"} from {remote_ip}')\n try: writer.close()\n except Exception: pass\n\nasync def reuse_stream_handler(reader, writer, unix, lbind, protos, rserver, urserver, block, cipher, salgorithm, verbose=DUMMY, modstat=lambda r,h:lambda i:DUMMY, **kwargs):\n try:\n if unix:\n remote_ip, server_ip, remote_text = 'local', None, 'unix_local'\n else:\n remote_ip, remote_port, *_ = writer.get_extra_info('peername')\n server_ip = writer.get_extra_info('sockname')[0]\n remote_text = f'{remote_ip}:{remote_port}'\n local_addr = None if server_ip in ('127.0.0.1', '::1', None) else (server_ip, 0)\n reader_cipher, _ = await prepare_ciphers(cipher, reader, writer, server_side=False)\n lproto = protos[0]\n except Exception as ex:\n verbose(f'{str(ex) or \"Unsupported protocol\"} from {remote_ip}')\n async def tcp_handler(reader, writer, host_name, port):\n try:\n if block and block(host_name):\n raise Exception('BLOCK ' + host_name)\n roption = schedule(rserver, salgorithm, host_name, port) or ProxyURI.DIRECT\n verbose(f'{lproto.name} {remote_text}{roption.logtext(host_name, port)}')\n try:\n reader_remote, writer_remote = await roption.open_connection(host_name, port, local_addr, lbind)\n except asyncio.TimeoutError:\n raise Exception(f'Connection timeout {roption.bind}')\n try:\n reader_remote, writer_remote = await roption.prepare_connection(reader_remote, writer_remote, host_name, port)\n except Exception:\n writer_remote.close()\n raise Exception('Unknown remote protocol')\n m = modstat(remote_ip, host_name)\n asyncio.ensure_future(lproto.channel(reader_remote, writer, m(2+roption.direct), m(4+roption.direct)))\n asyncio.ensure_future(lproto.channel(reader, writer_remote, m(roption.direct), roption.connection_change))\n except Exception as ex:\n if not isinstance(ex, asyncio.TimeoutError) and not str(ex).startswith('Connection closed'):\n verbose(f'{str(ex) or \"Unsupported protocol\"} from {remote_ip}')\n try: writer.close()\n except Exception: pass\n async def udp_handler(sendto, data, host_name, port, sid):\n try:\n if block and block(host_name):\n raise Exception('BLOCK ' + host_name)\n roption = schedule(urserver, salgorithm, host_name, port) or ProxyURI.DIRECT\n verbose(f'UDP {lproto.name} {remote_text}{roption.logtext(host_name, port)}')\n data = roption.prepare_udp_connection(host_name, port, data)\n await roption.open_udp_connection(host_name, port, data, sid, sendto)\n except Exception as ex:\n if not str(ex).startswith('Connection closed'):\n verbose(f'{str(ex) or \"Unsupported protocol\"} from {remote_ip}')\n lproto.get_handler(reader, writer, verbose, tcp_handler, udp_handler)\n\nasync def datagram_handler(writer, data, addr, protos, urserver, block, cipher, salgorithm, verbose=DUMMY, **kwargs):\n try:\n remote_ip, remote_port, *_ = addr\n remote_text = f'{remote_ip}:{remote_port}'\n data = cipher.datagram.decrypt(data) if cipher else data\n lproto, host_name, port, data = proto.udp_parse(protos, data, sock=writer.get_extra_info('socket'), **kwargs)\n if host_name == 'echo':\n writer.sendto(data, addr)\n elif host_name == 'empty':\n pass\n elif block and block(host_name):\n raise Exception('BLOCK ' + host_name)\n else:\n roption = schedule(urserver, salgorithm, host_name, port) or ProxyURI.DIRECT\n verbose(f'UDP {lproto.name} {remote_text}{roption.logtext(host_name, port)}')\n data = roption.prepare_udp_connection(host_name, port, data)\n def reply(rdata):\n rdata = lproto.udp_client2(host_name, port, rdata)\n writer.sendto(cipher.datagram.encrypt(rdata) if cipher else rdata, addr)\n await roption.open_udp_connection(host_name, port, data, addr, reply)\n except Exception as ex:\n if not str(ex).startswith('Connection closed'):\n verbose(f'{str(ex) or \"Unsupported protocol\"} from {remote_ip}')\n\nasync def check_server_alive(interval, rserver, verbose):\n while True:\n await asyncio.sleep(interval)\n for remote in rserver:\n if remote.direct:\n continue\n try:\n _, writer = await remote.open_connection(None, None, None, None, timeout=3)\n except asyncio.CancelledError as ex:\n return\n except Exception as ex:\n if remote.alive:\n verbose(f'{remote.rproto.name} {remote.bind} -> OFFLINE')\n remote.alive = False\n continue\n if not remote.alive:\n verbose(f'{remote.rproto.name} {remote.bind} -> ONLINE')\n remote.alive = True\n try:\n if remote.backward:\n writer.write(b'\\x00')\n writer.close()\n except Exception:\n pass\n\nclass BackwardConnection(object):\n def __init__(self, uri, count):\n self.uri = uri\n self.count = count\n self.closed = False\n self.conn = asyncio.Queue()\n async def open_connection(self):\n while True:\n reader, writer = await self.conn.get()\n if not writer.transport.is_closing():\n return reader, writer\n def close(self):\n self.closed = True\n try:\n self.writer.close()\n except Exception:\n pass\n async def start_server(self, handler):\n for _ in range(self.count):\n asyncio.ensure_future(self.server_run(handler))\n return self\n async def server_run(self, handler):\n errwait = 0\n while not self.closed:\n if self.uri.unix:\n wait = asyncio.open_unix_connection(path=self.uri.bind)\n else:\n wait = asyncio.open_connection(host=self.uri.host_name, port=self.uri.port, local_addr=(self.uri.lbind, 0) if self.uri.lbind else None)\n try:\n reader, writer = await asyncio.wait_for(wait, timeout=SOCKET_TIMEOUT)\n writer.write(self.uri.auth)\n self.writer = writer\n try:\n data = await reader.read_n(1)\n except asyncio.TimeoutError:\n data = None\n if data and data[0] != 0:\n reader._buffer[0:0] = data\n asyncio.ensure_future(handler(reader, writer))\n else:\n writer.close()\n errwait = 0\n except Exception as ex:\n try:\n writer.close()\n except Exception:\n pass\n if not self.closed:\n await asyncio.sleep(errwait)\n errwait = min(errwait*1.3 + 0.1, 30)\n def client_run(self, args):\n async def handler(reader, writer):\n if self.uri.auth:\n try:\n assert self.uri.auth == (await reader.read_n(len(self.uri.auth)))\n except Exception:\n return\n await self.conn.put((reader, writer))\n if self.uri.unix:\n return asyncio.start_unix_server(handler, path=self.uri.bind)\n else:\n return asyncio.start_server(handler, host=self.uri.host_name, port=self.uri.port, reuse_port=args.get('ruport'))\n\nclass ProxyURI(object):\n def __init__(self, **kw):\n self.__dict__.update(kw)\n self.total = 0\n self.udpmap = {}\n self.handler = None\n self.streams = None\n if self.backward:\n self.backward = BackwardConnection(self, self.backward)\n def logtext(self, host, port):\n if self.direct:\n return f' -> {host}:{port}'\n elif self.tunnel:\n return f' ->{(\" ssl\" if self.sslclient else \"\")} {self.bind}'\n else:\n return f' -> {self.rproto.name+(\"+ssl\" if self.sslclient else \"\")} {self.bind}' + self.relay.logtext(host, port)\n def connection_change(self, delta):\n self.total += delta\n async def open_udp_connection(self, host, port, data, addr, reply):\n class Protocol(asyncio.DatagramProtocol):\n def __init__(prot, data):\n self.udpmap[addr] = prot\n prot.databuf = [data]\n prot.transport = None\n prot.update = 0\n def connection_made(prot, transport):\n prot.transport = transport\n for data in prot.databuf:\n transport.sendto(data)\n prot.databuf.clear()\n prot.update = time.perf_counter()\n def new_data_arrived(prot, data):\n if prot.transport:\n prot.transport.sendto(data)\n else:\n prot.databuf.append(data)\n prot.update = time.perf_counter()\n def datagram_received(prot, data, addr):\n data = self.cipher.datagram.decrypt(data) if self.cipher else data\n data = self.rproto.udp_client(data) if not self.direct else data\n reply(data)\n prot.update = time.perf_counter()\n def connection_lost(prot, exc):\n self.udpmap.pop(addr, None)\n if addr in self.udpmap:\n self.udpmap[addr].new_data_arrived(data)\n else:\n if self.direct and host == 'tunnel':\n raise Exception('Unknown tunnel endpoint')\n self.connection_change(1)\n if len(self.udpmap) > UDP_LIMIT:\n min_addr = min(self.udpmap, key=lambda x: self.udpmap[x].update)\n prot = self.udpmap.pop(min_addr)\n if prot.transport:\n prot.transport.close()\n prot = Protocol(data)\n remote_addr = (host, port) if self.direct else (self.host_name, self.port)\n await asyncio.get_event_loop().create_datagram_endpoint(lambda: prot, remote_addr=remote_addr)\n def prepare_udp_connection(self, host, port, data):\n if not self.direct:\n data = self.relay.prepare_udp_connection(host, port, data)\n whost, wport = (host, port) if self.relay.direct else (self.relay.host_name, self.relay.port)\n data = self.rproto.udp_connect(rauth=self.auth, host_name=whost, port=wport, data=data)\n if self.cipher:\n data = self.cipher.datagram.encrypt(data)\n return data\n def start_udp_server(self, args):\n class Protocol(asyncio.DatagramProtocol):\n def connection_made(prot, transport):\n prot.transport = transport\n def datagram_received(prot, data, addr):\n asyncio.ensure_future(datagram_handler(prot.transport, data, addr, **vars(self), **args))\n return asyncio.get_event_loop().create_datagram_endpoint(Protocol, local_addr=(self.host_name, self.port))\n async def open_connection(self, host, port, local_addr, lbind, timeout=SOCKET_TIMEOUT):\n if self.reuse or self.ssh:\n if self.streams is None or self.streams.done() and (self.reuse and not self.handler):\n self.streams = asyncio.get_event_loop().create_future()\n else:\n if not self.streams.done():\n await self.streams\n return self.streams.result()\n try:\n local_addr = local_addr if self.lbind == 'in' else (self.lbind, 0) if self.lbind else \\\n local_addr if lbind == 'in' else (lbind, 0) if lbind else None\n family = 0 if local_addr is None else socket.AF_INET6 if ':' in local_addr[0] else socket.AF_INET\n if self.direct:\n if host == 'tunnel':\n raise Exception('Unknown tunnel endpoint')\n wait = asyncio.open_connection(host=host, port=port, local_addr=local_addr, family=family)\n elif self.ssh:\n try:\n import asyncssh\n for s in ('read_', 'read_n', 'read_until'):\n setattr(asyncssh.SSHReader, s, getattr(asyncio.StreamReader, s))\n except Exception:\n raise Exception('Missing library: \"pip3 install asyncssh\"')\n username, password = self.auth.decode().split(':', 1)\n if password.startswith(':'):\n client_keys = [password[1:]]\n password = None\n else:\n client_keys = None\n conn = await asyncssh.connect(host=self.host_name, port=self.port, local_addr=local_addr, family=family, x509_trusted_certs=None, known_hosts=None, username=username, password=password, client_keys=client_keys, keepalive_interval=60)\n if not self.streams.done():\n self.streams.set_result((conn, None))\n return conn, None\n elif self.backward:\n wait = self.backward.open_connection()\n elif self.unix:\n wait = asyncio.open_unix_connection(path=self.bind)\n else:\n wait = asyncio.open_connection(host=self.host_name, port=self.port, local_addr=local_addr, family=family)\n reader, writer = await asyncio.wait_for(wait, timeout=timeout)\n except Exception as ex:\n if self.reuse:\n self.streams.set_exception(ex)\n self.streams = None\n raise\n return reader, writer\n def prepare_connection(self, reader_remote, writer_remote, host, port):\n if self.reuse and not self.handler:\n self.handler = self.rproto.get_handler(reader_remote, writer_remote, DUMMY)\n return self.prepare_ciphers_and_headers(reader_remote, writer_remote, host, port, self.handler)\n async def prepare_ciphers_and_headers(self, reader_remote, writer_remote, host, port, handler):\n if not self.direct:\n reader_remote, writer_remote = proto.sslwrap(reader_remote, writer_remote, self.sslclient, False, self.host_name)\n if not handler or not handler.ready:\n _, writer_cipher_r = await prepare_ciphers(self.cipher, reader_remote, writer_remote, self.bind)\n else:\n writer_cipher_r = None\n whost, wport = (host, port) if self.relay.direct else (self.relay.host_name, self.relay.port)\n if self.rproto.reuse():\n if not self.streams.done():\n self.streams.set_result((reader_remote, writer_remote))\n reader_remote, writer_remote = handler.connect(whost, wport)\n elif self.ssh:\n reader_remote, writer_remote = await reader_remote.open_connection(whost, wport)\n else:\n await self.rproto.connect(reader_remote=reader_remote, writer_remote=writer_remote, rauth=self.auth, host_name=whost, port=wport, writer_cipher_r=writer_cipher_r, myhost=self.host_name, sock=writer_remote.get_extra_info('socket'))\n return await self.relay.prepare_ciphers_and_headers(reader_remote, writer_remote, host, port, handler)\n return reader_remote, writer_remote\n def start_server(self, args):\n handler = functools.partial(reuse_stream_handler if self.reuse else stream_handler, **vars(self), **args)\n if self.backward:\n return self.backward.start_server(handler)\n elif self.unix:\n return asyncio.start_unix_server(handler, path=self.bind)\n else:\n return asyncio.start_server(handler, host=self.host_name, port=self.port, reuse_port=args.get('ruport'))\n async def tcp_connect(self, host, port, local_addr=None, lbind=None):\n reader, writer = await self.open_connection(host, port, local_addr, lbind)\n try:\n reader, writer = await self.prepare_connection(reader, writer, host, port)\n except Exception:\n writer.close()\n raise\n return reader, writer\n async def udp_sendto(self, host, port, data, answer_cb, local_addr=None):\n if local_addr is None:\n local_addr = random.randrange(2**32)\n data = self.prepare_udp_connection(host, port, data)\n await self.open_udp_connection(host, port, data, local_addr, answer_cb)\n @classmethod\n def compile_rule(cls, filename):\n if filename.startswith(\"{\") and filename.endswith(\"}\"):\n return re.compile(filename[1:-1]).match\n with open(filename) as f:\n return re.compile('(:?'+''.join('|'.join(i.strip() for i in f if i.strip() and not i.startswith('#')))+')$').match\n @classmethod\n def compile_relay(cls, uri):\n tail = cls.DIRECT\n for urip in reversed(uri.split('__')):\n tail = cls.compile(urip, tail)\n return tail\n @classmethod\n def compile(cls, uri, relay=None):\n scheme, _, uri = uri.partition('://')\n url = urllib.parse.urlparse('s://'+uri)\n rawprotos = scheme.split('+')\n err_str, protos = proto.get_protos(rawprotos)\n if err_str:\n raise argparse.ArgumentTypeError(err_str)\n if 'ssl' in rawprotos or 'secure' in rawprotos:\n import ssl\n sslserver = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n sslclient = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n if 'ssl' in rawprotos:\n sslclient.check_hostname = False\n sslclient.verify_mode = ssl.CERT_NONE\n else:\n sslserver = sslclient = None\n protonames = [i.name for i in protos]\n if 'pack' in protonames and relay and relay != cls.DIRECT:\n raise argparse.ArgumentTypeError('pack protocol cannot relay to other proxy')\n urlpath, _, plugins = url.path.partition(',')\n urlpath, _, lbind = urlpath.partition('@')\n plugins = plugins.split(',') if plugins else None\n cipher, _, loc = url.netloc.rpartition('@')\n if cipher:\n from .cipher import get_cipher\n if ':' not in cipher:\n try:\n cipher = base64.b64decode(cipher).decode()\n except Exception:\n pass\n if ':' not in cipher:\n raise argparse.ArgumentTypeError('userinfo must be \"cipher:key\"')\n err_str, cipher = get_cipher(cipher)\n if err_str:\n raise argparse.ArgumentTypeError(err_str)\n if plugins:\n from .plugin import get_plugin\n for name in plugins:\n if not name: continue\n err_str, plugin = get_plugin(name)\n if err_str:\n raise argparse.ArgumentTypeError(err_str)\n cipher.plugins.append(plugin)\n match = cls.compile_rule(url.query) if url.query else None\n if loc:\n host_name, _, port = loc.partition(':')\n port = int(port) if port else (22 if 'ssh' in rawprotos else 8080)\n else:\n host_name = port = None\n return ProxyURI(protos=protos, rproto=protos[0], cipher=cipher, auth=url.fragment.encode(), \\\n match=match, bind=loc or urlpath, host_name=host_name, port=port, \\\n unix=not loc, lbind=lbind, sslclient=sslclient, sslserver=sslserver, \\\n alive=True, direct='direct' in protonames, tunnel='tunnel' in protonames, \\\n reuse='pack' in protonames or relay and relay.reuse, backward=rawprotos.count('in'), \\\n ssh='ssh' in rawprotos, relay=relay)\nProxyURI.DIRECT = ProxyURI(direct=True, tunnel=False, reuse=False, relay=None, alive=True, match=None, cipher=None, backward=None, ssh=None, lbind=None)\n\nasync def test_url(url, rserver):\n url = urllib.parse.urlparse(url)\n assert url.scheme in ('http', 'https'), f'Unknown scheme {url.scheme}'\n host_name, _, port = url.netloc.partition(':')\n port = int(port) if port else 80 if url.scheme == 'http' else 443\n initbuf = f'GET {url.path or \"/\"} HTTP/1.1\\r\\nHost: {host_name}\\r\\nUser-Agent: pproxy-{__version__}\\r\\nAccept: */*\\r\\nConnection: close\\r\\n\\r\\n'.encode()\n for roption in rserver:\n print(f'============ {roption.bind} ============')\n try:\n reader, writer = await roption.open_connection(host_name, port, None, None)\n except asyncio.TimeoutError:\n raise Exception(f'Connection timeout {rserver}')\n try:\n reader, writer = await roption.prepare_connection(reader, writer, host_name, port)\n except Exception:\n writer.close()\n raise Exception('Unknown remote protocol')\n if url.scheme == 'https':\n import ssl\n sslclient = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n sslclient.check_hostname = False\n sslclient.verify_mode = ssl.CERT_NONE\n reader, writer = proto.sslwrap(reader, writer, sslclient, False, host_name)\n writer.write(initbuf)\n headers = await reader.read_until(b'\\r\\n\\r\\n')\n print(headers.decode()[:-4])\n print(f'--------------------------------')\n body = bytearray()\n while 1:\n s = await reader.read_()\n if not s:\n break\n body.extend(s)\n print(body.decode('utf8', 'ignore'))\n print(f'============ success ============')\n\ndef main():\n parser = argparse.ArgumentParser(description=__description__+'\\nSupported protocols: http,socks4,socks5,shadowsocks,shadowsocksr,redirect,pf,tunnel', epilog=f'Online help: <{__url__}>')\n parser.add_argument('-l', dest='listen', default=[], action='append', type=ProxyURI.compile, help='tcp server uri (default: http+socks4+socks5://:8080/)')\n parser.add_argument('-r', dest='rserver', default=[], action='append', type=ProxyURI.compile_relay, help='tcp remote server uri (default: direct)')\n parser.add_argument('-ul', dest='ulisten', default=[], action='append', type=ProxyURI.compile, help='udp server setting uri (default: none)')\n parser.add_argument('-ur', dest='urserver', default=[], action='append', type=ProxyURI.compile_relay, help='udp remote server uri (default: direct)')\n parser.add_argument('-b', dest='block', type=ProxyURI.compile_rule, help='block regex rules')\n parser.add_argument('-a', dest='alived', default=0, type=int, help='interval to check remote alive (default: no check)')\n parser.add_argument('-s', dest='salgorithm', default='fa', choices=('fa', 'rr', 'rc', 'lc'), help='scheduling algorithm (default: first_available)')\n parser.add_argument('-v', dest='v', action='count', help='print verbose output')\n parser.add_argument('--ssl', dest='sslfile', help='certfile[,keyfile] if server listen in ssl mode')\n parser.add_argument('--pac', help='http PAC path')\n parser.add_argument('--get', dest='gets', default=[], action='append', help='http custom {path,file}')\n parser.add_argument('--auth', dest='authtime', type=int, default=86400*30, help='re-auth time interval for same ip (default: 86400*30)')\n parser.add_argument('--sys', action='store_true', help='change system proxy setting (mac, windows)')\n parser.add_argument('--reuse', dest='ruport', action='store_true', help='set SO_REUSEPORT (Linux only)')\n parser.add_argument('--daemon', dest='daemon', action='store_true', help='run as a daemon (Linux only)')\n parser.add_argument('--test', help='test this url for all remote proxies and exit')\n parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')\n args = parser.parse_args()\n if args.test:\n asyncio.get_event_loop().run_until_complete(test_url(args.test, args.rserver))\n return\n if not args.listen and not args.ulisten:\n args.listen.append(ProxyURI.compile_relay('http+socks4+socks5://:8080/'))\n args.httpget = {}\n if args.pac:\n pactext = 'function FindProxyForURL(u,h){' + (f'var b=/^(:?{args.block.__self__.pattern})$/i;if(b.test(h))return \"\";' if args.block else '')\n for i, option in enumerate(args.rserver):\n pactext += (f'var m{i}=/^(:?{option.match.__self__.pattern})$/i;if(m{i}.test(h))' if option.match else '') + 'return \"PROXY %(host)s\";'\n args.httpget[args.pac] = pactext+'return \"DIRECT\";}'\n args.httpget[args.pac+'/all'] = 'function FindProxyForURL(u,h){return \"PROXY %(host)s\";}'\n args.httpget[args.pac+'/none'] = 'function FindProxyForURL(u,h){return \"DIRECT\";}'\n for gets in args.gets:\n path, filename = gets.split(',', 1)\n with open(filename, 'rb') as f:\n args.httpget[path] = f.read()\n if args.sslfile:\n sslfile = args.sslfile.split(',')\n for option in args.listen:\n if option.sslclient:\n option.sslclient.load_cert_chain(*sslfile)\n option.sslserver.load_cert_chain(*sslfile)\n elif any(map(lambda o: o.sslclient, args.listen)):\n print('You must specify --ssl to listen in ssl mode')\n return\n if args.daemon:\n try:\n __import__('daemon').DaemonContext().open()\n except ModuleNotFoundError:\n print(\"Missing library: pip3 install python-daemon\")\n return\n # Try to use uvloop instead of the default event loop\n try:\n __import__('uvloop').install()\n print('Using uvloop')\n except ModuleNotFoundError:\n pass\n loop = asyncio.get_event_loop()\n if args.v:\n from . import verbose\n verbose.setup(loop, args)\n servers = []\n for option in args.listen:\n print('Serving on', option.bind, 'by', \",\".join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' '+','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')\n try:\n server = loop.run_until_complete(option.start_server(vars(args)))\n servers.append(server)\n except Exception as ex:\n print('Start server failed.\\n\\t==>', ex)\n for option in args.ulisten:\n print('Serving on UDP', option.bind, 'by', \",\".join(i.name for i in option.protos), f'({option.cipher.name})' if option.cipher else '')\n try:\n server, protocol = loop.run_until_complete(option.start_udp_server(vars(args)))\n servers.append(server)\n except Exception as ex:\n print('Start server failed.\\n\\t==>', ex)\n for option in args.rserver:\n if option.backward:\n print('Serving on', option.bind, 'backward by', \",\".join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' '+','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')\n try:\n server = loop.run_until_complete(option.backward.client_run(vars(args)))\n servers.append(server)\n except Exception as ex:\n print('Start server failed.\\n\\t==>', ex)\n if servers:\n if args.sys:\n from . import sysproxy\n args.sys = sysproxy.setup(args)\n if args.alived > 0 and args.rserver:\n asyncio.ensure_future(check_server_alive(args.alived, args.rserver, args.verbose if args.v else DUMMY))\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n print('exit')\n if args.sys:\n args.sys.clear()\n for task in asyncio.Task.all_tasks():\n task.cancel()\n for server in servers:\n server.close()\n for server in servers:\n if hasattr(server, 'wait_closed'):\n loop.run_until_complete(server.wait_closed())\n loop.run_until_complete(loop.shutdown_asyncgens())\n loop.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"pproxy/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":33085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"311310981","text":"import numpy as np\n\ndef promedio(x):\n\tx = np.array(x)\n\ta = np.sum(x)\n\tb = x.shape\n\tN = b[0]\n\tpromedio0 = a/N\n\treturn promedio0\n\ndef mediacua(x): \n\tx = np.abs(np.array(x))\t\n\tmediacua0 = promedio(x**2)\n\treturn mediacua0\n\ndef varianza(x):\n\tx = np.array(x)\n\ta2 = (x - promedio(x))**2 \n\tvarianza0 = promedio(a2)\n\treturn varianza0\t\n\ndef rms(x):\n\tx = np.abs(np.array(x))**2\n\trms0 = np.sqrt(promedio(x))\t\n\treturn rms0\n\ndef potenpro(x):\n\tx = np.abs(x)**2\n\tpotenpro0 = promedio(x)\n\treturn potenpro0\n\ndef autocor(x,tao):\n\tx = np.array(x)\n\txnext = np.concatenate((x[tao:],np.zeros(tao)))\n\ta = x*xnext\n\tif(x.dtype=='complex128'):\n\t\ta = np.abs(a)\t\t\n\tautocor0 = promedio(a)\n\treturn autocor0\n\nx = [0, 0.5, 1.2, 0.5, 0, -0.5]\ntao = 2\n\nprint(\"Promedio de x[n] = \", promedio(x))\nprint(\"Media cuadrática de x[n] = \", mediacua(x))\nprint(\"Varianza = \", varianza(x))\nprint(\"Valor RMS = \", rms(x))\nprint(\"Potencia promedio = \", potenpro(x))\nprint(\"Función de autocorrelación = \", autocor(x,tao))\n","sub_path":"Laboratorio/02/codigos/codigo_2.py","file_name":"codigo_2.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"490361814","text":"import argparse\n\n\ndef get_cmd_params():\n parser = argparse.ArgumentParser()\n parser.add_argument('price', help='Price for formatting')\n return parser.parse_args()\n\n\ndef format_price(price):\n\n try:\n float_price = float(str(price))\n except ValueError:\n return None\n\n round_float_price = round(float_price, 2)\n\n if round_float_price.is_integer():\n format_string = '{:,.0f}'\n else:\n format_string = '{:,.2f}'\n\n result_price = format_string.format(round_float_price).replace(',', ' ')\n return result_price\n\n\ndef main():\n params = get_cmd_params()\n price = params.price\n print(format_price(price))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"format_price.py","file_name":"format_price.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"600825631","text":"__author__ = 'Quan'\n\nfrom bs4 import BeautifulSoup as bs\nimport requests as r\nimport openpyxl as x\n\nfn='sample.xlsx'\nwb= x.Workbook()\nwb= x.load_workbook(fn)\n\n\ndef getcafef():\n cafef= r.get('http://cafef.vn/')\n cafef=bs(cafef.content)\n\n cafefnews=cafef.find_all(\"div\",{\"class\": \"right\"})\n cafefnews=cafefnews[1] # chon div class right thu 2 trong tat cac cach div class right\n lis=cafefnews.find_all(\"li\")\n linklis=cafefnews.find_all('a', href=True)\n li_content=[ele.text.strip() for ele in lis]\n\n cafefheadnews=cafef.find_all(\"div\",{\"class\":\"left\"})\n cafefheadnews=cafefheadnews[1]\n linkcafefhead=cafefheadnews.find('a', href=True)\n cafefheadnews=cafefheadnews.find(\"h2\").text\n\n ws=wb.worksheets[0]\n for i in range(len(li_content)):\n ws.cell(row = i + 3, column = 1).value = li_content[i]\n ws.cell(row = i + 3, column = 2).value = 'http://cafef.vn'+linklis[i]['href']\n ws.cell(row=2, column=1).value =cafefheadnews\n ws.cell(row=2, column=2).value ='http://cafef.vn'+linkcafefhead['href']\n wb.save(fn)\n\n\n\ndef getvietstock():\n vietstock= r.get('http://vietstock.vn/')\n vietstock=bs(vietstock.content)\n\n vietstocknews=vietstock.find_all(\"div\",{\"id\": \"hotnews_news\"})\n vietstocknews=vietstocknews[0] # chon div class right thu 1 trong tat cac cach div class right\n lis=vietstocknews.find_all(\"li\")\n li_content=[ele.text.strip() for ele in lis]\n linkvietnews=vietstocknews.find_all('a', href=True)\n\n vietstockhead=vietstock.find(\"div\",{\"class\":\"hotnews_head\"})\n linkvietstockhead=vietstockhead.find('a', href=True)\n vietstockhead=vietstockhead.find(\"h1\").text\n\n ws=wb.worksheets[0]\n for i in range(len(li_content)):\n ws.cell(row = i + 16, column = 1).value = li_content[i]\n ws.cell(row = i +16, column = 2).value = 'http://vietstock.vn'+linkvietnews[i]['href']\n ws.cell(row= 15, column=1).value = vietstockhead\n ws.cell(row=15, column=2).value = 'http://vietstock.vn'+linkvietstockhead['href']\n wb.save(fn)\n\ndef getgafin():\n nhipcaudautu=r.get('http://nhipcaudautu.vn/')\n nhipcaudautu=bs(nhipcaudautu.content)\n\n nhipcaunews=nhipcaudautu.find(\"ul\",{\"class\":\"homeUp\"})\n listnews=nhipcaunews.find_all(\"ul\")\n listnews=listnews[1]\n linklistnews=listnews.find_all('a',href=True)\n listnews=listnews.find_all(\"li\")\n li_content2=[ele.text.strip() for ele in listnews]\n\n nhipcaunewshead=nhipcaunews.find(\"h1\")\n textcuatitle=nhipcaunewshead.text\n linkdautien=nhipcaunewshead.find(\"a\",href=True)\n\n ws=wb.worksheets[0]\n for i in range(len(li_content2)):\n ws.cell(row = i + 27, column =1).value = li_content2[i]\n ws.cell(row = i + 27, column = 2).value= 'http://nhipcaudautu.vn'+linklistnews[i]['href']\n ws.cell(row=26, column=1).value =textcuatitle\n ws.cell(row=26,column=2).value='http://nhipcaudautu.vn'+linkdautien['href']\n wb.save(fn)\n\ndef getADB():#41\n ADB= r.get('http://asianbondsonline.adb.org/vietnam/news.php')\n ADB=bs(ADB.content)\n\n ADBnews=ADB.find('table')\n ADBlink=ADBnews.find_all('a',href=True)\n ADBnews=ADBnews.find_all(\"tr\")\n\n ws = wb.worksheets[0]\n for i in range(len(ADBnews)):\n cols = ADBnews[i].find_all('td',{\"class\":'title'})\n cols = [ele.text.strip() for ele in cols]\n\n ws.cell(row=41+i, column=2).value = ADBlink[i]['href']\n for j in range(len(cols)):\n\n ws.cell(row=41+i, column=1).value = cols[j]\n\n wb.save(fn)\n\n\n\n\n\n\ngetcafef()\ngetvietstock()\ngetgafin()\ngetADB()\n","sub_path":"new1.py","file_name":"new1.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"593058682","text":"from __future__ import unicode_literals\n\nimport random\nfrom os.path import abspath, join, dirname\n\n__title__ = 'names'\n__version__ = '0.3.0'\n__author__ = 'Trey Hunner'\n__license__ = 'MIT'\n\nfull_path = lambda filename: abspath(join(dirname(__file__), filename))\n\nFILES = {\n 'first:male': full_path('names.male.first'),\n 'first:female': full_path('names.female.first'),\n 'last': full_path('names.all.last'),\n}\n\n\ndef get_name(filename):\n selected = random.random() * 90\n with open(filename) as name_file:\n for line in name_file:\n name, _, cummulative, _ = line.split()\n if float(cummulative) > selected:\n return name\n return \"\" # Return empty string if file is empty\n\n\ndef get_first_name(gender=None):\n if gender not in ('male', 'female'):\n gender = random.choice(('male', 'female'))\n return get_name(FILES['first:%s' % gender]).capitalize()\n\n\ndef get_last_name():\n return get_name(FILES['last']).capitalize()\n\n\ndef get_full_name(gender=None):\n return \"{0} {1}\".format(get_first_name(gender), get_last_name())\n","sub_path":"tests/utils/names/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"487586177","text":"from torch.autograd import Variable\nimport torch.optim as optim\nimport torch\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nn_predictions = 100\n\ndef main():\n toy_problem = ToyProblem()\n toy_prediction_model = ToyPredictionModel2()\n\n train(toy_problem, toy_prediction_model)\n\n test(toy_problem, toy_prediction_model)\n\n\nclass ToyProblem:\n def __init__(self):\n self.weight = 10\n self.bias = 2\n # self.loss_function = torch.nn.MSELoss()\n\n def loss_function(self, prediction, target):\n return -torch.log(torch.exp(-torch.pow(prediction - target, 2)).sum(dim=1) + 1e-5).sum()\n #return -torch.log(torch.exp(-torch.pow(prediction - target, 2)).sum(dim=1)).sum()\n #return torch.pow(torch.abs(prediction - target.expand(prediction.size())), 0.5).sum()\n\n\n def mean(self, data):\n return data*self.weight + self.bias\n\n def loss(self, target, prediction):\n return self.loss_function(prediction, target)\n\n @staticmethod\n def generate_data(n_samples):\n return torch.FloatTensor(n_samples, 1).normal_(0, 1)\n\n def generate_target(self, data):\n target = self.mean(data)\n displacement = torch.round(torch.FloatTensor(data.size()).normal_(0, 1))*10\n target += torch.FloatTensor(data.size()).normal_(0, 1) + displacement\n return target\n\n\nclass ToyPredictionModel(nn.Module):\n def __init__(self):\n super(ToyPredictionModel, self).__init__()\n self.layer1 = nn.Linear(1, 1)\n\n def forward(self, x):\n return self.layer1(x)\n\n\nclass ToyPredictionModel2(nn.Module):\n def __init__(self):\n super(ToyPredictionModel2, self).__init__()\n self.layer1 = nn.Linear(1, 5)\n self.layer2 = nn.Linear(5, 5)\n self.layer3_mu = nn.Linear(5, 5)\n self.layer3_sigma = nn.Linear(5, 5)\n self.layer4 = nn.Linear(5, 5)\n self.layer5 = nn.Linear(5, 5)\n self.layer6 = nn.Linear(5, 5)\n self.layer7 = nn.Linear(5, 1)\n\n def forward(self, x):\n x = self.layer1(x)\n x = F.relu(x)\n x = self.layer2(x)\n x = F.relu(x)\n mu = self.layer3_mu(x)\n mu = (mu - mu.mean(dim=1, keepdim=True)) / (mu.std(dim=1, keepdim=True) + 1e-5)\n logvar = self.layer3_sigma(x)\n std = logvar.mul(0.5).exp_()\n x = mu + std*Variable(torch.FloatTensor(std.size()).normal_(0, 1))\n x = F.relu(x)\n x = self.layer4(x)\n x = F.relu(x)\n x = self.layer5(x)\n x = F.relu(x)\n x = self.layer6(x)\n x = F.relu(x)\n x = self.layer7(x)\n return x, logvar.sum()\n\n\ndef train(toy_problem, toy_prediction_model, batch_size=500, n_iterations=10000):\n\n optimizer = optim.SGD(toy_prediction_model.parameters(), lr=1e-4, momentum=1e-5)\n toy_prediction_model.train()\n for iteration in range(n_iterations):\n data = toy_problem.generate_data(batch_size)\n target = toy_problem.generate_target(data)\n repeated_data = data.expand((-1, 5)).contiguous().view(-1, 1)\n\n repeated_data, target = Variable(repeated_data), Variable(target)\n\n predictions, logvars = toy_prediction_model(repeated_data)\n\n predictions = predictions.view((-1, 5))\n\n loss = toy_problem.loss(target, predictions) #- 1e-6*logvars.sum()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if iteration % 2 == 0:\n print('Iteration: {}\\tLoss: {:.6f}'.format(\n iteration, torch.mean(loss.data)))\n # print([x for x in toy_prediction_model.named_parameters()])\n\n\ndef test(toy_problem, toy_prediction_model):\n\n n_samples = 100\n data = toy_problem.generate_data(n_samples)\n data, indices = data.sort(dim=0)\n\n target = toy_problem.generate_target(data)\n data, target = Variable(data), Variable(target)\n predictions = []\n for _ in range(n_predictions):\n prediction, logvar = toy_prediction_model(data)\n predictions.append(prediction)\n predictions = torch.cat(predictions, dim=1)\n\n plt.scatter(data.data.numpy(), target.data.numpy())\n for i in range(n_predictions):\n plt.scatter(data.data.numpy(), predictions.data.numpy()[:, i], c='r', alpha=1/n_predictions)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155127964","text":"import os\nimport sys\nimport pytest\nfrom datetime import datetime\n#from core.base_test import BaseTest #it should be added?\n\n\nif __name__ == \"__main__\":\n arguments = dict()\n for arg in sys.argv[1:]:\n key, value = arg.split('=')\n arguments[key] = value\n\n # Create directory for the report\n directory = 'allure-report/' + datetime.today().strftime(\"%Y-%m-%d_%H-%M-%S\")\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n pytest.main('tests/{0} --alluredir {1}/xml'.format(arguments['suite'], directory))\n os.system('allure generate {0}/xml -o {0}/html'.format(directory))","sub_path":"run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400086840","text":"'''--------------------------------------------------------------------------------------\nMODULE\n sbl_iress_rec_report\n\nDESCRIPTION\n Date : 2020-04-20\n Purpose : Script generates IRESS Recon downstream report\n Department and Desk : SBL and Collateral\n Requester : Gasant Thulsie, James Stevens\n Developer : Sihle Gaxa\n JIRA : PCGDEV-60\n\nHISTORY\n=========================================================================================\nDate JIRA no Developer Description\n-----------------------------------------------------------------------------------------\n2020-04-20 PCGDEV-60 Sihle Gaxa Initial implementation.\n\nENDDESCRIPTION\n--------------------------------------------------------------------------------------'''\nimport acm\nimport csv\nimport datetime\n\nfrom at_logging import getLogger\nimport FUploaderFunctions as gen_uploader\nimport sbl_reporting_utils as reporting_utils\n\nLOGGER = getLogger(__name__)\nFILE_HEADERS = [\"BGNREF\", \"LINKREF\", \"CPTY\",\n \"PTYPE\", \"QTY\", \"STOCK\", \"TRADE\",\n \"SSET_DT\", \"SMODE\", \"LNRATE\", \"MIN_FEE\",\n \"LNPRC\", \"COLL_FLG\", \"OP\", \"STATUS\", \"LNVAL\", \"CLASS\"]\n\n\nclass RowData(reporting_utils.ReportingData):\n\n def __init__(self, trade, instrument, counterparty, run_date):\n super(RowData, self).__init__(trade, instrument, counterparty, run_date)\n self.data = {}\n\n def get_row_data(self):\n try:\n default_value = 0\n trade_date = self.get_trade_date()\n trade_quantity = self.get_trade_quantity()\n instrument_name = self.instrument.Name()[4:]\n instrument_class = self.get_instrument_class()\n counterparty_code = self.get_counterparty_code()\n trade_settlement_date = self.get_settlement_date()\n trade_settlement_type = self.trade.add_info(\"SL_SWIFT\")\n trade_market_value = self.get_market_value(trade_quantity)\n if int(trade_market_value) == 0:\n return\n if not trade_settlement_type:\n trade_settlement_type = \"SWIFT\"\n if self.get_counterparty_major() in self.EXCLUDED_MAJORS:\n return\n\n LOGGER.info(\"Writing common row details for {trade}\".format(trade=self.trade.Oid()))\n\n self.data[\"QTY\"] = trade_quantity\n self.data[\"LNPRC\"] = default_value\n self.data[\"MIN_FEE\"] = default_value\n self.data[\"STOCK\"] = instrument_name\n self.data[\"CPTY\"] = counterparty_code\n self.data[\"CLASS\"] = instrument_class\n self.data[\"OP\"] = self.OPEN_TRADE_FLAG\n self.data[\"STATUS\"] = self.LOANED_FLAG\n self.data[\"LNVAL\"] = trade_market_value\n self.data[\"TRADE\"] = self.get_trade_date()\n self.data[\"SMODE\"] = trade_settlement_type\n self.data[\"SSET_DT\"] = trade_settlement_date\n self.data[\"BGNREF\"] = self.get_settlement_id()\n self.data[\"COLL_FLG\"] = self.TRADE_FLAG[\"Loan\"]\n self.data[\"LINKREF\"] = self.trade.Oid()\n\n if self.trade.Instrument().InsType() == \"SecurityLoan\":\n return self.add_loan_details()\n elif (reporting_utils.COLL_INSTYPE_BOND_QUERY.IsSatisfiedBy(self.trade.Instrument()) \n or reporting_utils.COLL_INSTYPE_EQUITY_QUERY.IsSatisfiedBy(self.trade.Instrument())):\n return self.add_non_cash_collateral_details()\n elif reporting_utils.COLL_INSTYPE_CASH_QUERY.IsSatisfiedBy(self.trade.Instrument()):\n return self.add_cash_collateral_details()\n except Exception as e:\n LOGGER.info(\"Could not add row because {err}\".format(err=str(e)))\n raise Exception(\"Could not add row because {error}\".format(error=str(e)))\n\n def add_loan_details(self):\n trade_rate = self.get_trade_rate()\n trade_price = self.get_trade_price()\n LOGGER.info(\"Writing loan details for {loan}\".format(loan=self.trade.Instrument().Name()))\n self.data[\"LNPRC\"] = trade_price\n self.data[\"LNRATE\"] = trade_rate\n self.data[\"BGNREF\"] = self.get_settlement_id()\n self.data[\"LNVAL\"] = abs(round((trade_price * self.data[\"QTY\"]), 2))\n if self.get_counterparty_type() == \"Borrower\":\n self.data[\"PTYPE\"] = self.LOANED_FLAG\n else:\n self.data[\"PTYPE\"] = self.BORROWED_FLAG\n return self.data\n\n def add_non_cash_collateral_details(self):\n self.data[\"LNVAL\"] = 0\n self.data[\"LNRATE\"] = 0\n counterparty_type = self.get_counterparty_type()\n if self.instrument.InsType() == \"CD\":\n self.data[\"STOCK\"] = \"NCD\"\n collateral_flag = self.get_collateral_flag(self.get_trade_quantity(), counterparty_type)\n LOGGER.info(\"Writing non-cash collateral details for {ins}\".format(ins=self.instrument.Name()))\n self.data[\"PTYPE\"] = collateral_flag\n self.data[\"COLL_FLG\"] = self.TRADE_FLAG[\"Collateral\"]\n return self.data\n\n def add_cash_collateral_details(self):\n counterparty_type = self.get_counterparty_type()\n counterparty_code = self.get_counterparty_code()\n deposit_rate = self.instrument.Legs()[0].FixedRate()\n if counterparty_type == \"Borrower\":\n self.data[\"PTYPE\"] = self.LOANED_FLAG\n else:\n self.data[\"PTYPE\"] = self.BORROWED_FLAG\n deposit_name = \"{code}:{flag}:{currency}\".format(\n code=counterparty_code, flag=self.data[\"PTYPE\"],\n currency=self.instrument.Currency().Name())\n LOGGER.info(\"Writing cash collateral details for {cash}\".format(cash=self.instrument.Name()))\n self.data[\"QTY\"] = 0\n self.data[\"CLASS\"] = \"\"\n self.data[\"STOCK\"] = \"\"\n self.data[\"TRADE\"] = \"\"\n self.data[\"SMODE\"] = \"\"\n self.data[\"STATUS\"] = \"\"\n self.data[\"LINKREF\"] = \"\"\n self.data[\"SSET_DT\"] = \"\"\n self.data[\"BGNREF\"] = deposit_name\n self.data[\"LNRATE\"] = deposit_rate\n return self.data\n\n\ndef add_file_data(trades, run_date, directory):\n try:\n with open(directory, \"wb\") as csv_file:\n writer = csv.DictWriter(csv_file, FILE_HEADERS)\n writer.writeheader()\n for trade in trades[0].Trades():\n LOGGER.info(\"Processing trade {trade}\".format(trade=trade.Oid()))\n instrument = trade.Instrument()\n instrument_type = instrument.InsType()\n trade_counterparty = trade.Counterparty()\n if instrument_type == \"SecurityLoan\":\n lender = trade.add_info(\"SL_G1Counterparty2\")\n borrower = trade.add_info(\"SL_G1Counterparty1\")\n lender_counterparty = acm.FParty[lender]\n borrower_counterparty = acm.FParty[borrower]\n if lender_counterparty and lender_counterparty.add_info(\"PERFIX_CLIENT\") == \"Yes\":\n trade_row = RowData(trade, instrument.Underlying(),\n lender_counterparty, run_date)\n row_data = trade_row.get_row_data()\n if row_data:\n writer.writerow(row_data)\n if borrower_counterparty and borrower_counterparty.add_info(\"PERFIX_CLIENT\") == \"Yes\":\n trade_row = RowData(trade, instrument.Underlying(),\n borrower_counterparty, run_date)\n row_data = trade_row.get_row_data()\n if row_data:\n writer.writerow(row_data)\n elif ((reporting_utils.COLL_INSTYPE_BOND_QUERY.IsSatisfiedBy(instrument) \n or reporting_utils.COLL_INSTYPE_EQUITY_QUERY.IsSatisfiedBy(instrument))\n and trade_counterparty.add_info(\"PERFIX_CLIENT\") == \"Yes\"):\n trade_row = RowData(trade, instrument, trade.Counterparty(), run_date)\n row_data = trade_row.get_row_data()\n if row_data:\n writer.writerow(row_data)\n elif instrument_type == \"Deposit\" and trade_counterparty.add_info(\"PERFIX_CLIENT\") == \"Yes\":\n trade_row = RowData(trade, instrument, trade.Counterparty(), run_date)\n row_data = trade_row.get_row_data()\n if row_data:\n writer.writerow(row_data)\n except Exception as e:\n LOGGER.info(\"Could not get file data because {err}\".format(err=str(e)))\n raise Exception(\"Could not get file data because {err}\".format(err=str(e)))\n\nael_variables = reporting_utils.get_ael_variables()\n\n\ndef ael_main(dictionary):\n try:\n file_name = dictionary[\"file_name\"]\n run_date = gen_uploader.get_input_date(dictionary)\n date_string = datetime.datetime.strptime(str(run_date), '%Y-%m-%d').strftime('%m%d')\n filename = \"{file_name}_{file_date}01.txt\".format(file_name=file_name,\n file_date=date_string)\n output_file, run_date = reporting_utils.get_directory(dictionary, filename, True)\n add_file_data(dictionary[\"sbl_trades\"], run_date, output_file)\n LOGGER.info(\"Completed successfully\")\n LOGGER.info(\"Wrote secondary output to: {path}\".format(path=output_file))\n except Exception as e:\n LOGGER.info(\"Failed to write file because {err}\".format(err=str(e)))\n raise Exception(\"Failed to write file because {error}\".format(error=str(e)))\n","sub_path":"Python modules/sbl_iress_rec_report.py","file_name":"sbl_iress_rec_report.py","file_ext":"py","file_size_in_byte":9752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"85374355","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Views for create/rename/update/delete columns.\"\"\"\n\nimport random\nfrom builtins import range\nfrom typing import Optional\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.db import IntegrityError\nfrom django.http import HttpRequest, JsonResponse\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ontask.core.decorators import ajax_required, get_column, get_workflow\nfrom ontask.core.permissions import is_instructor\nfrom ontask.dataops.formula import evaluation\nfrom ontask.dataops.pandas import (\n load_table, pandas_datatype_names, rename_df_column, store_dataframe,\n)\nfrom ontask.dataops.sql import add_column_to_db, db_rename_column\nfrom ontask.models import (\n ActionColumnConditionTuple, Column, Condition, Log, Workflow,\n)\nfrom ontask.workflow.forms import (\n ColumnAddForm, ColumnRenameForm, FormulaColumnAddForm, QuestionAddForm,\n QuestionRenameForm, RandomColumnAddForm,\n)\nfrom ontask.workflow.ops import clone_wf_column, workflow_delete_column\n\n# These are the column operands offered through the GUI. They have immediate\n# translations onto Pandas operators over dataframes.\n# Each tuple has:\n# - Pandas operation name\n# - Textual description\n# - List of data types that are allowed (for data type checking)\n_formula_column_operands = [\n ('sum', _('sum: Sum selected columns'), ['integer', 'double']),\n (\n 'prod',\n _('prod: Product of the selected columns'),\n ['integer', 'double']),\n ('max', _('max: Maximum of the selected columns'), ['integer', 'double']),\n ('min', _('min: Minimum of the selected columns'), ['integer', 'double']),\n ('mean', _('mean: Mean of the selected columns'), ['integer', 'double']),\n (\n 'median',\n _('median: Median of the selected columns'),\n ['integer', 'double']),\n (\n 'std',\n _('std: Standard deviation over the selected columns'),\n ['integer', 'double']),\n (\n 'all',\n _('all: True when all elements in selected columns are true'),\n ['boolean']),\n (\n 'any',\n _('any: True when any element in selected columns is true'),\n ['boolean']),\n]\n\n_op_distrib = {\n 'sum': lambda operand: operand.sum(axis=1, skipna=False),\n 'prod': lambda operand: operand.prod(axis=1, skipna=False),\n 'max': lambda operand: operand.max(axis=1, skipna=False),\n 'min': lambda operand: operand.min(axis=1, skipna=False),\n 'mean': lambda operand: operand.mean(axis=1, skipna=False),\n 'median': lambda operand: operand.median(axis=1, skipna=False),\n 'std': lambda operand: operand.std(axis=1, skipna=False),\n 'all': lambda operand: operand.all(axis=1, skipna=False),\n 'any': lambda operand: operand.any(axis=1, skipna=False),\n}\n\n\ndef _partition(list_in, num):\n \"\"\"Partitions the list in num lists.\n\n Given a list and n, returns a list with n lists, and inside each of them a\n set of elements from the shuffled list. All lists are of the same size\n\n :param list_in: List of elements to partition\n\n :param num: Number of partitions\n\n :return: List of lists with shuffled elements partitioned\n \"\"\"\n random.shuffle(list_in)\n return [list_in[idx::num] for idx in range(num)]\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_workflow(pf_related=['actions', 'columns'])\ndef column_add(\n request: HttpRequest,\n pk: Optional[int] = None,\n workflow: Optional[Workflow] = None,\n) -> JsonResponse:\n \"\"\"Add column.\n\n :param request: Http Request\n\n :param pk: Action ID where to add the question\n\n :return: JSON response\n \"\"\"\n # Detect if this operation is to add a new column or a new question (in\n # the edit in page)\n is_question = pk is not None\n\n if workflow.nrows == 0:\n if is_question:\n messages.error(\n request,\n _('Cannot add question to a workflow without data'),\n )\n else:\n messages.error(\n request,\n _('Cannot add column to a workflow without data'),\n )\n return JsonResponse({'html_redirect': ''})\n\n action = None\n action_id = None\n if is_question:\n # Get the action and the columns\n action = workflow.actions.filter(pk=pk).first()\n action_id = action.id\n if not action:\n messages.error(\n request,\n _('Cannot find action to add question.'),\n )\n return JsonResponse({'html_redirect': reverse('action:index')})\n\n # Form to read/process data\n if is_question:\n form = QuestionAddForm(request.POST or None, workflow=workflow)\n else:\n form = ColumnAddForm(request.POST or None, workflow=workflow)\n\n if request.method == 'POST' and form.is_valid():\n\n # Processing now a valid POST request\n # Access the updated information\n column_initial_value = form.initial_valid_value\n\n # Save the column object attached to the form\n column = form.save(commit=False)\n\n # Catch the special case of integer type and no initial value. Pandas\n # encodes it as NaN but a cycle through the database transforms it into\n # a string. To avoid this case, integer + empty value => double\n if column.data_type == 'integer' and column_initial_value is None:\n column.data_type = 'double'\n\n # Fill in the remaining fields in the column\n column.workflow = workflow\n column.is_key = False\n\n # Update the positions of the appropriate columns\n workflow.reposition_columns(workflow.ncols + 1, column.position)\n\n # Save column, refresh workflow, and increase number of columns\n column.save()\n form.save_m2m()\n workflow.refresh_from_db()\n workflow.ncols += 1\n workflow.set_query_builder_ops()\n workflow.save()\n\n # Add the new column to the DB\n try:\n add_column_to_db(\n workflow.get_data_frame_table_name(),\n column.name,\n column.data_type,\n initial=column_initial_value)\n except Exception as exc:\n messages.error(\n request,\n _('Unable to add column: {0}').format(str(exc)))\n return JsonResponse({'html_redirect': ''})\n\n # If the column is a question, add it to the action\n if is_question:\n ActionColumnConditionTuple.objects.get_or_create(\n action=action,\n column=column,\n condition=None)\n\n # Log the event\n if is_question:\n event_type = Log.QUESTION_ADD\n else:\n event_type = Log.COLUMN_ADD\n Log.objects.register(\n request.user,\n event_type,\n workflow,\n {\n 'id': workflow.id,\n 'name': workflow.name,\n 'column_name': column.name,\n 'column_type': column.data_type})\n\n return JsonResponse({'html_redirect': ''})\n\n if is_question:\n template = 'workflow/includes/partial_question_addedit.html'\n else:\n template = 'workflow/includes/partial_column_addedit.html'\n\n return JsonResponse({\n 'html_form': render_to_string(\n template,\n {\n 'form': form,\n 'is_question': is_question,\n 'action_id': action_id,\n 'add': True},\n request=request),\n })\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_workflow(pf_related='columns')\ndef formula_column_add(\n request: HttpRequest,\n workflow: Optional[Workflow] = None,\n) -> JsonResponse:\n \"\"\"Add a formula column.\n\n :param request:\n\n :return:\n \"\"\"\n # Get the workflow element\n if workflow.nrows == 0:\n messages.error(\n request,\n _('Cannot add column to a workflow without data'),\n )\n return JsonResponse({'html_redirect': ''})\n\n # Form to read/process data\n form = FormulaColumnAddForm(\n form_data=request.POST or None,\n operands=_formula_column_operands,\n columns=workflow.columns.all(),\n )\n\n if request.method == 'POST' and form.is_valid():\n # Save the column object attached to the form and add additional fields\n column = form.save(commit=False)\n column.workflow = workflow\n column.is_key = False\n\n # Save the instance\n try:\n column.save()\n form.save_m2m()\n except IntegrityError:\n form.add_error('name', _('A column with that name already exists'))\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_formula_column_add.html',\n {'form': form},\n request=request),\n })\n\n # Update the data frame\n df = load_table(workflow.get_data_frame_table_name())\n\n try:\n # Add the column with the appropriate computation\n operation = form.cleaned_data['op_type']\n cnames = [col.name for col in form.selected_columns]\n df[column.name] = _op_distrib[operation](df[cnames])\n except Exception as exc:\n # Something went wrong in pandas, we need to remove the column\n column.delete()\n\n # Notify in the form\n form.add_error(\n None,\n _('Unable to add the column: {0}').format(\n exc,\n ),\n )\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_formula_column_add.html',\n {'form': form},\n request=request,\n ),\n })\n\n # Populate the column type\n column.data_type = pandas_datatype_names.get(\n df[column.name].dtype.name)\n\n # Update the positions of the appropriate columns\n workflow.reposition_columns(workflow.ncols + 1, column.position)\n\n # Save column and refresh the prefetched related in the workflow\n column.save()\n workflow.refresh_from_db()\n\n # Store the df to DB\n try:\n store_dataframe(df, workflow)\n except Exception as exc:\n messages.error(\n request,\n _('Unable to clone column: {0}').format(str(exc)))\n return JsonResponse({'html_redirect': ''})\n\n # Log the event\n Log.objects.register(\n request.user,\n Log.COLUMN_ADD_FORMULA,\n workflow,\n {'id': workflow.id,\n 'name': workflow.name,\n 'column_name': column.name,\n 'column_type': column.data_type})\n\n # The form has been successfully processed\n return JsonResponse({'html_redirect': ''})\n\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_formula_column_add.html',\n {'form': form},\n request=request,\n ),\n })\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_workflow(pf_related='columns')\ndef random_column_add(\n request: HttpRequest,\n workflow: Optional[Workflow] = None,\n) -> JsonResponse:\n \"\"\"Create a column with random values (Modal).\n\n :param request:\n\n :return:\n \"\"\"\n # Get the workflow element\n if workflow.nrows == 0:\n messages.error(\n request,\n _('Cannot add column to a workflow without data'))\n return JsonResponse({'html_redirect': ''})\n\n # Form to read/process data\n form = RandomColumnAddForm(data=request.POST or None)\n\n if request.method == 'POST' and form.is_valid():\n\n # Save the column object attached to the form and add additional fields\n column = form.save(commit=False)\n column.workflow = workflow\n column.is_key = False\n\n # Save the instance\n try:\n column = form.save()\n form.save_m2m()\n except IntegrityError:\n form.add_error('name', _('A column with that name already exists'))\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_random_column_add.html',\n {'form': form},\n request=request),\n })\n\n # Update the data frame\n df = load_table(workflow.get_data_frame_table_name())\n\n # Get the values and interpret its meaning\n column_values = form.cleaned_data['column_values']\n # First, try to see if the field is a valid integer\n try:\n int_value = int(column_values)\n except ValueError:\n int_value = None\n\n if int_value:\n # At this point the field is an integer\n if int_value <= 1:\n form.add_error(\n 'values',\n _('The integer value has to be larger than 1'))\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_random_column_add.html',\n {'form': form},\n request=request),\n })\n\n intvals = [idx + 1 for idx in range(int_value)]\n else:\n # At this point the field is a string and the values are the comma\n # separated strings.\n intvals = [\n valstr.strip() for valstr in column_values.strip().split(',')\n if valstr\n ]\n if not intvals:\n form.add_error(\n 'values',\n _('The value has to be a comma-separated list'),\n )\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_random_column_add.html',\n {'form': form},\n request=request),\n })\n\n # Empty new column\n new_column = [None] * workflow.nrows\n # Create the random partitions\n partitions = _partition(\n [idx for idx in range(workflow.nrows)],\n len(intvals))\n\n # Assign values to partitions\n for idx, indexes in enumerate(partitions):\n for col_idx in indexes:\n new_column[col_idx] = intvals[idx]\n\n # Assign the new column to the data frame\n df[column.name] = new_column\n\n # Populate the column type\n column.data_type = pandas_datatype_names.get(\n df[column.name].dtype.name,\n )\n\n # Update the positions of the appropriate columns\n workflow.reposition_columns(workflow.ncols + 1, column.position)\n\n column.save()\n workflow.refresh_from_db()\n\n # Store the df to DB\n try:\n store_dataframe(df, workflow)\n except Exception as exc:\n messages.error(\n request,\n _('Unable to add the column: {0}').format(str(exc)))\n return JsonResponse({'html_redirect': ''})\n\n # Log the event\n Log.objects.register(\n request.user,\n Log.COLUMN_ADD_RANDOM,\n workflow,\n {'id': workflow.id,\n 'name': workflow.name,\n 'column_name': column.name,\n 'column_type': column.data_type,\n 'value': column_values})\n\n # The form has been successfully processed\n return JsonResponse({'html_redirect': ''})\n\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_random_column_add.html',\n {'form': form},\n request=request),\n })\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_column(pf_related=['columns', 'views', 'actions'])\ndef column_edit(\n request: HttpRequest,\n pk: int,\n workflow: Optional[Workflow] = None,\n column: Optional[Column] = None,\n) -> JsonResponse:\n \"\"\"Edit a column.\n\n :param request:\n\n :param pk:\n\n :return:\n \"\"\"\n # Detect if this operation is to edit a new column or a new question (in\n # the edit in page)\n is_question = 'question_edit' in request.path_info\n # Form to read/process data\n if is_question:\n form = QuestionRenameForm(\n request.POST or None,\n workflow=workflow,\n instance=column)\n else:\n form = ColumnRenameForm(\n request.POST or None,\n workflow=workflow,\n instance=column)\n\n if request.method == 'POST' and form.is_valid():\n if not form.has_changed():\n return JsonResponse({'html_redirect': None})\n\n # Some field changed value, so save the result, but\n # no commit as we need to propagate the info to the df\n column = form.save(commit=False)\n\n # If there is a new name, rename the data frame columns\n if form.old_name != form.cleaned_data['name']:\n db_rename_column(\n workflow.get_data_frame_table_name(),\n form.old_name,\n column.name)\n rename_df_column(workflow, form.old_name, column.name)\n\n if form.old_position != form.cleaned_data['position']:\n # Update the positions of the appropriate columns\n workflow.reposition_columns(form.old_position, column.position)\n\n # Save the column information\n column.save()\n\n # Go back to the DB because the prefetch columns are not valid\n # any more\n workflow = Workflow.objects.prefetch_related('columns').get(\n id=workflow.id,\n )\n\n # Changes in column require rebuilding the query_builder_ops\n workflow.set_query_builder_ops()\n\n # Save the workflow\n workflow.save()\n\n # Log the event\n if is_question:\n event_type = Log.QUESTION_ADD\n else:\n event_type = Log.COLUMN_ADD\n Log.objects.register(\n request.user,\n event_type,\n workflow,\n {\n 'id': workflow.id,\n 'name': workflow.name,\n 'column_name': column.name})\n\n # Done processing the correct POST request\n return JsonResponse({'html_redirect': ''})\n\n if is_question:\n template = 'workflow/includes/partial_question_addedit.html'\n else:\n template = 'workflow/includes/partial_column_addedit.html'\n return JsonResponse({\n 'html_form': render_to_string(\n template,\n {'form': form,\n 'cname': column.name,\n 'pk': pk},\n request=request),\n })\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_column(pf_related=['columns', 'actions'])\ndef column_delete(\n request: HttpRequest,\n pk: int,\n workflow: Optional[Workflow] = None,\n column: Optional[Column] = None,\n) -> JsonResponse:\n \"\"\"Delete a column in the table attached to a workflow.\n\n :param request: HTTP request\n\n :param pk: ID of the column to delete. The workflow element is taken\n from the session.\n\n :return: Render the delete column form\n \"\"\"\n # Get the workflow element\n # If the columns is unique and it is the only one, we cannot allow\n # the operation\n unique_column = workflow.get_column_unique()\n if column.is_key and len([col for col in unique_column if col]) == 1:\n # This is the only key column\n messages.error(request, _('You cannot delete the only key column'))\n return JsonResponse({'html_redirect': reverse('workflow:detail')})\n\n # Get the name of the column to delete\n context = {'pk': pk, 'cname': column.name}\n\n # Get the conditions/actions attached to this workflow\n cond_to_delete = [\n col for col in Condition.objects.filter(action__workflow=workflow)\n if evaluation.has_variable(col.formula, column.name)]\n # Put it in the context because it is shown to the user before confirming\n # the deletion\n context['cond_to_delete'] = cond_to_delete\n\n if request.method == 'POST':\n # Proceed deleting the column\n workflow_delete_column(workflow, column, cond_to_delete)\n\n # Log the event\n Log.objects.register(\n request.user,\n Log.COLUMN_DELETE,\n workflow,\n {\n 'id': workflow.id,\n 'name': workflow.name,\n 'column_name': column.name})\n\n # There are various points of return\n from_url = request.META['HTTP_REFERER']\n if from_url.endswith(reverse('table:display')):\n return JsonResponse({'html_redirect': reverse('table:display')})\n\n return JsonResponse({'html_redirect': reverse('workflow:detail')})\n\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_column_delete.html',\n context,\n request=request),\n })\n\n\n@user_passes_test(is_instructor)\n@ajax_required\n@get_column(pf_related='columns')\ndef column_clone(\n request: HttpRequest,\n pk: int,\n workflow: Optional[Workflow] = None,\n column: Optional[Column] = None,\n) -> JsonResponse:\n \"\"\"Clone a column in the table attached to a workflow.\n\n :param request: HTTP request\n\n :param pk: ID of the column to clone. The workflow element is taken\n from the session.\n\n :return: Render the clone column form\n \"\"\"\n # Get the name of the column to clone\n context = {'pk': pk, 'cname': column.name}\n\n if request.method == 'GET':\n return JsonResponse({\n 'html_form': render_to_string(\n 'workflow/includes/partial_column_clone.html',\n context,\n request=request),\n })\n\n # POST REQUEST\n\n # Proceed to clone the column\n try:\n new_column = clone_wf_column(column)\n except Exception as exc:\n messages.error(\n request,\n _('Unable to clone column: {0}').format(str(exc)))\n return JsonResponse({'html_redirect': ''})\n\n # Log the event\n Log.objects.register(\n request.user,\n Log.COLUMN_CLONE,\n workflow,\n {\n 'id': workflow.id,\n 'name': workflow.name,\n 'old_column_name': column.name,\n 'new_column_name': new_column.name})\n\n return JsonResponse({'html_redirect': ''})\n","sub_path":"ontask/workflow/views/column_crud.py","file_name":"column_crud.py","file_ext":"py","file_size_in_byte":22595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76533230","text":"import urllib3\nfrom bs4 import BeautifulSoup\n\n\nhttp = urllib3.PoolManager()\npagina = http.request('GET','https://pt.wikipedia.org/wiki/Linguagem_de_programa%C3%A7%C3%A3o''')\nsopa = BeautifulSoup(pagina.data,'html5lib')\n\nfor tags in sopa(['scrip', 'style']):\n tags.decompose\nconteudo = ' '.join(sopa.stripped_strings)","sub_path":"exemplo_extracao_conteudo.py","file_name":"exemplo_extracao_conteudo.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"285210991","text":"from django.shortcuts import render,redirect,HttpResponse\nfrom cmdb import models\n\n\n# Create your views here.\n\n\n\nUSER_DICT = {\n '1':{'name':'root1','email':'root@qq.com'},\n '2':{'name':'root2','email':'root@qq.com'},\n '3':{'name':'root3','email':'root@qq.com'},\n '4':{'name':'root4','email':'root@qq.com'},\n '5':{'name':'root5','email':'root@qq.com'},\n '6':{'name':'root6','email':'root@qq.com'},\n}\n\n# USER_LIST = {\n# {'name':'root'},\n# {'name':'root'},\n# {'name':'root'},\n# }\n\ndef login(request):\n # 包含用户提交的所有信息\n # 获取用户提交方法\n # print(request.method)\n error_msg = \"\"\n if request.method == \"POST\":\n # 获取用户通过POST提交过来的数据\n user = request.POST.get('user',None)\n pwd = request.POST.get('pwd',None)\n if user == 'root' and pwd == \"123\":\n # 去跳转到\n return redirect('/home')\n else:\n # 用户密码不配\n error_msg = \"用户名或密码错误\"\n return render(request,'login.html', {'error_msg': error_msg})\n\ndef detail(request,nid):\n # return HttpResponse(uid)\n # nid=request.GET.get('nid')\n detail_info = USER_DICT[nid]\n return render(request,'detail.html',{'detail_info':detail_info})\n\ndef index(request):\n\n return render(request,'index.html',{'user_dict':USER_DICT})\n# def home(request):\n# USER_LIST = models.getUser()\n# if request.method == \"POST\":\n# # 获取用户提交的数据 POST请求中\n# u = request.POST.get('username')\n# e = request.POST.get('email')\n# g = request.POST.get('gender')\n# id = 5\n# temp = {'id':id,'username': u, 'email': e, \"gender\": g}\n# USER_LIST.append(temp)\n# return render(request, 'test/home.html', {'user_list': USER_LIST})\n\ndef del_host(request):\n USER_LIST = models.getUser()\n\n print(\"响应del_host\")\n if request.method == \"POST\":\n # 获取用户提交的数据 POST请求中\n nid = request.POST.get('nid')\n print(\"提交过来的nid\"+nid)\n models.deleteUserById(int(nid))\n\n # e = request.POST.get('email')\n # g = request.POST.get('gender')\n # id = 5\n # temp = {'id':id,'username': u, 'email': e, \"gender\": g}\n return render(request, 'test/home.html', {'user_list': USER_LIST})\n else:\n USER_LIST = models.getUser()\n return render(request, 'test/home.html', {'user_list': USER_LIST})\n # USER_LIST.append(temp)\n\nfrom django.views import View\nclass Home(View):\n def dispatch(self, request, *args, **kwargs):\n print('before')\n result = super(Home,self).dispatch(request, *args, **kwargs)\n print('after')\n print(result)\n return result\n\n def get(self,request):\n print(\"get\")\n USER_LIST = models.getUser()\n return render(request, 'test/home.html', {'user_list': USER_LIST})\n def post(self,request):\n print(\"post\")\n USER_LIST = models.getUser()\n if request.method == \"POST\":\n # 获取用户提交的数据 POST请求中\n u = request.POST.get('username')\n e = request.POST.get('email')\n g = request.POST.get('gender')\n id = 5\n temp = {'id': id, 'username': u, 'email': e, \"gender\": g}\n USER_LIST.append(temp)\n return render(request, 'test/home.html', {'user_list': USER_LIST})\n\n\n\n# def login(request):\n# # string = \"\"\"\n# #
\n# # \n# #
\n# #\n# # \"\"\"\n# # f = open('templates/login.html', 'r', encoding='utf-8')\n# # data = f.read()\n# # f.close()\n# # return HttpResponse(data)\n# return render(request,'login.html')\n\n# def home(request):\n# return HttpResponse('

CMDB

')\n\n# 主机管理\n# 防火墙\n# 。。。\n","sub_path":"cmdb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576853012","text":"import RPi.GPIO as GPIO\nimport time\n\nPWMFrequency = 50\nInitialDutyCycle = 7.5\n\nclass OutputClock:\n\tpin = None\n\tfrequency = None\n\tpwm = None\n\tname = None\n\n\tdef stop(self):\n\t\tself.pwm.stop()\n\n\tdef __init__(self, pin, name, frequency):\n\t\tprint(\"Initializing clock on pin \" + str(pin) + \" with output frequency of \" + str(frequency) + \"Hz\")\n\t\tself.pin = pin\n\t\tGPIO.setup(self.pin, GPIO.OUT)\n\t\tself.frequency = frequency\n\t\tself.name = name\n\t\tself.pwm = GPIO.PWM(self.pin, frequency)\n\t\tself.pwm.start(50)\n\n\nclass Input:\n\tfunction = None\n\tpin = None\n\tname = None\n\n\tdef __init__(self, pin, name, function):\n\t\tprint(\"Initializing Input Listener on pin \" + str(pin) + \" named: \" + name)\n\t\tself.pin = pin\n\t\tself.name = name\n\t\tGPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\t\tself.function = function\n\t\tGPIO.add_event_detect(pin, GPIO.RISING, callback=self.function, bouncetime=300)\n\n\nclass Servo:\n\tpwm = None\n\tpin = None\n\n\tdef rotate(self, dutyCycle):\n\t\tprint(\"Rotating servo to duty cycle \" + str(dutyCycle))\n\t\tself.pwm = GPIO.PWM(self.pin, PWMFrequency)\n\t\tself.pwm.start(dutyCycle)\n\t\ttime.sleep(0.5)\n\t\tself.pwm.stop()\n\n\tdef __init__(self, pin):\n\t\tprint(\"Initializing Servo on pin \" + str(pin) + \" with frequency \" + str(PWMFrequency) + \"Hz\")\n\t\tself.pin = pin\n\t\tGPIO.setup(self.pin, GPIO.OUT)\n\t\tself.rotate(InitialDutyCycle)\n\n\nclass IO:\n\t__instance = None\n\tpanServo = None\n\ttiltServo = None\n\n\t@staticmethod\n\tdef getInstance():\n\t\t\"\"\" Static access method. \"\"\"\n\t\tif IO.__instance == None:\n\t\t\tIO()\n\t\treturn IO.__instance\n\n\tdef __init__(self):\n\t\tprint(\"Initializing IO\")\n\t\tif IO.__instance != None:\n\t\t\tprint(\"IO was already initialized, throwing exception\")\n\t\t\traise Exception(\"This class is a singleton!\")\n\t\telse:\n\t\t\tprint(\"Setting board mode\")\n\t\t\tGPIO.setmode(GPIO.BCM)\n\t\t\tIO.__instance = self\n","sub_path":"IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"128305109","text":"from flask import Flask, render_template, json, jsonify, request\nfrom neo4j.v1 import GraphDatabase, basic_auth\nimport re\nfrom django.utils.encoding import smart_str, smart_unicode\nimport csv\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n return \"Hello World!\"\n\n@app.route(\"/hello/\")\ndef hello(name):\n return \"Hello \" + name + \" !\"\n\n@app.route(\"/visu\")\ndef visu():\n return app.send_static_file(\"panama-visu.html\")\n\n@app.route(\"/data.json\")\ndef data():\n return app.send_static_file(\"data.json\")\n\n@app.route(\"/visu_temp\")\ndef temp():\n return render_template(\"panama-visu.html\", data = { \"truc\" : 4, \"muche\" : 2 })\n\n@app.route(\"/visu_temp_json\")\ndef tempJson():\n return render_template(\"panama-visu.html\", data = json.load(open(\"static/data.json\")))\n\n@app.route(\"/data/count/\")\ndef count(type):\n data = json.load(open(\"static/data.json\"))\n if type in data:\n return str(data[type]) + \" \" + type\n else:\n return \"Type not found\"\n\n@app.route(\"/data/neo/\")\ndef neo(type):\n driver = GraphDatabase.driver(\"bolt://localhost\", auth=basic_auth(\"neo4j\", \"91401364\"))\n session = driver.session()\n\n request = \"MATCH (a:%s) RETURN count(*) AS count;\" % type\n\n result = session.run(request)\n\n for record in result:\n if record[\"count\"] != 0 :\n return \"%s\" % (record[\"count\"])\n else :\n return \"Entite non trouvee!\"\n\n@app.route(\"/histo/neo\")\ndef histoNeo():\n driver = GraphDatabase.driver(\"bolt://localhost\", auth=basic_auth(\"neo4j\", \"91401364\"))\n session = driver.session()\n\n request = \"match (n) return distinct labels(n) as label, count(n) as count;\"\n result = session.run(request)\n\n ch = {}\n\n for record in result :\n if record[\"count\"] > 1 :\n label = re.search(\"(?<=')[a-zA-Z]*\", str(record[\"label\"]))\n labelRe = label.group(0)\n ch[\"%s\"%labelRe] = record[\"count\"]\n\n return render_template(\"panama-visu.html\", data = ch)\n session.close()\n\n@app.route(\"/world/map\")\ndef worldMap():\n #myfile = open(\"static/data.csv\", 'wb')\n driver = GraphDatabase.driver(\"bolt://localhost\", auth=basic_auth(\"neo4j\", \"91401364\"))\n session = driver.session()\n\n request = \"MATCH (n) WHERE EXISTS(n.countries) RETURN DISTINCT n.countries AS countries, n.country_codes as country_codes, COUNT(n.countries) as count;\"\n result = session.run(request)\n\n country_code_tab = {}\n country_tab = {}\n\n for record in result :\n countries = smart_str(record[\"countries\"])\n tabCountries = countries.split(\";\")\n countries_codes = re.search(\"[A-Z;]*[A-Z]\", str(record[\"country_codes\"]))\n label = countries_codes.group(0)\n tabCountriesCodes = label.split(\";\")\n for country in tabCountriesCodes :\n if country in country_code_tab :\n country_code_tab[\"%s\"%country] += record[\"count\"]\n else :\n country_code_tab[\"%s\"%country] = record[\"count\"]\n c = csv.writer(open(\"static/data.csv\", \"wb\"))\n c.writerow([\"Series Code\",\"Country Code\",\"Link\"])\n for country_code in country_code_tab :\n c.writerow([\"SP.POP.TOTL\",country_code,country_code_tab[\"%s\"%country_code]])\n for country in tabCountries :\n country_tab[\"%s\"%country] = 0\n return render_template(\"world_map.html\", data = country_tab)\n session.close()\n\n@app.route(\"/countries/link\")\ndef countriesLink():\n driver = GraphDatabase.driver(\"bolt://localhost\", auth=basic_auth(\"neo4j\", \"91401364\"))\n session = driver.session()\n\n req = \"match (n)-[r]->(o) where n.countries = '%s' and o.countries = '%s' return n as first, r as relation, o as second;\"%(request.args.get(\"country_one\"), request.args.get(\"country_Two\"))\n result = session.run(req)\n\n relation_tab = list()\n i = 0\n\n for record in result :\n relation_tab.append([record[\"first\"][\"name\"], record[\"first\"][\"country_codes\"], record[\"relation\"][\"rel_type\"], record[\"relation\"][\"name\"], record[\"second\"][\"name\"], record[\"second\"][\"country_codes\"]])\n return render_template(\"link_map.html\", data = relation_tab)\n #return str(relation_tab)\n\n session.close()\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"Flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"258453706","text":"\"\"\"Test CartesianProduct Class\n\"\"\"\n\nfrom unittest.mock import patch, call, mock_open\nfrom contextlib import nullcontext as does_not_raise\n\nimport pytest\nimport numpy\n\nfrom waves.parameter_generators import CartesianProduct\nfrom waves._settings import _set_coordinate_key\nfrom common import consistent_hash_parameter_check, self_consistency_checks, merge_samplers\n\n\nclass TestCartesianProduct:\n \"\"\"Class for testing CartesianProduct parameter study generator class\"\"\"\n\n validate_input = {\n \"good schema\": (\n {'parameter_1': [1], 'parameter_2': (2,) , 'parameter_3': set([3, 4])},\n does_not_raise()\n ),\n \"not a dict\": (\n 'not a dict',\n pytest.raises(TypeError)\n ),\n \"bad schema int\": (\n {'parameter_1': 1},\n pytest.raises(TypeError)\n ),\n \"bad schema dict\": (\n {'parameter_1': {'thing1': 1}},\n pytest.raises(TypeError)\n ),\n \"bad schema str\": (\n {'parameter_1': 'one'},\n pytest.raises(TypeError)\n ),\n }\n\n @pytest.mark.unittest\n @pytest.mark.parametrize('parameter_schema, outcome',\n validate_input.values(),\n ids=validate_input.keys())\n def test_validate(self, parameter_schema, outcome):\n with outcome:\n try:\n # Validate is called in __init__. Do not need to call explicitly.\n TestValidate = CartesianProduct(parameter_schema)\n finally:\n pass\n\n generate_io = {\n 'one_parameter': ({'parameter_1': [1, 2]},\n numpy.array([[1], [2]])),\n 'two_parameter': ({'parameter_1': [1, 2], 'parameter_2': ['a', 'b']},\n numpy.array(\n [[1, \"a\"],\n [1, \"b\"],\n [2, \"a\"],\n [2, \"b\"]], dtype=object)),\n 'ints and floats': ({'parameter_1': [1, 2], 'parameter_2': [3.0, 4.0]},\n numpy.array(\n [[1, 3.0],\n [1, 4.0],\n [2, 3.0],\n [2, 4.0]], dtype=object))\n }\n\n @pytest.mark.unittest\n @pytest.mark.parametrize('parameter_schema, expected_array',\n generate_io.values(),\n ids=generate_io.keys())\n def test_generate(self, parameter_schema, expected_array):\n TestGenerate = CartesianProduct(parameter_schema)\n generate_array = TestGenerate._samples\n assert numpy.all(generate_array == expected_array)\n # Verify that the parameter set name creation method was called\n assert list(TestGenerate._parameter_set_names.values()) == [f\"parameter_set{num}\" for num in range(len(expected_array))]\n # Check that the parameter set names are correctly populated in the parameter study Xarray Dataset\n expected_set_names = [f\"parameter_set{num}\" for num in range(len(expected_array))]\n parameter_set_names = list(TestGenerate.parameter_study[_set_coordinate_key])\n assert numpy.all(parameter_set_names == expected_set_names)\n\n merge_test = {\n 'new set':\n ({'parameter_1': [1, 2], 'parameter_2': [3.0], 'parameter_3': ['a']},\n {'parameter_1': [1, 2], 'parameter_2': [3.0, 4.0], 'parameter_3': ['a']},\n # Ordered by md5 hash during Xarray merge operation. New tests must verify hash ordering.\n numpy.array(\n [[2, 3.0, \"a\"],\n [1, 4.0, \"a\"],\n [2, 4.0, \"a\"],\n [1, 3.0, \"a\"]], dtype=object)),\n 'unchanged sets':\n ({'parameter_1': [1, 2], 'parameter_2': [3.0], 'parameter_3': ['a']},\n {'parameter_1': [1, 2], 'parameter_2': [3.0], 'parameter_3': ['a']},\n # Ordered by md5 hash during Xarray merge operation. New tests must verify hash ordering.\n numpy.array(\n [[2, 3.0, \"a\"],\n [1, 3.0, \"a\"]], dtype=object)),\n }\n\n @pytest.mark.unittest\n @pytest.mark.parametrize('first_schema, second_schema, expected_array', merge_test.values(), ids=merge_test.keys())\n def test_merge(self, first_schema, second_schema, expected_array):\n original_study, merged_study = merge_samplers(CartesianProduct, first_schema, second_schema, {})\n generate_array = merged_study._samples\n assert numpy.all(generate_array == expected_array)\n consistent_hash_parameter_check(original_study, merged_study)\n self_consistency_checks(merged_study)\n\n generate_io = {\n 'one parameter yaml':\n ({\"parameter_1\": [1, 2]},\n 'out',\n None,\n 'yaml',\n 2,\n [call(\"parameter_1: 1\\n\"),\n call(\"parameter_1: 2\\n\")]),\n 'two parameter yaml':\n ({\"parameter_1\": [1, 2], \"parameter_2\": [\"a\", \"b\"]},\n 'out',\n None,\n 'yaml',\n 4,\n [call(\"parameter_1: 1\\nparameter_2: a\\n\"),\n call(\"parameter_1: 1\\nparameter_2: b\\n\"),\n call(\"parameter_1: 2\\nparameter_2: a\\n\"),\n call(\"parameter_1: 2\\nparameter_2: b\\n\")]),\n 'two parameter yaml: floats and ints':\n ({\"parameter_1\": [1, 2], \"parameter_2\": [3.0, 4.0]},\n 'out',\n None,\n 'yaml',\n 4,\n [call(\"parameter_1: 1\\nparameter_2: 3.0\\n\"),\n call(\"parameter_1: 1\\nparameter_2: 4.0\\n\"),\n call(\"parameter_1: 2\\nparameter_2: 3.0\\n\"),\n call(\"parameter_1: 2\\nparameter_2: 4.0\\n\")]),\n 'one parameter one file yaml':\n ({\"parameter_1\": [1, 2]},\n None,\n 'parameter_study.yaml',\n 'yaml',\n 1,\n [call(\"parameter_set0:\\n parameter_1: 1\\n\" \\\n \"parameter_set1:\\n parameter_1: 2\\n\")]),\n 'two parameter one file yaml':\n ({\"parameter_1\": [1, 2], \"parameter_2\": [\"a\", \"b\"]},\n None,\n 'parameter_study.yaml',\n 'yaml',\n 1,\n [call(\"parameter_set0:\\n parameter_1: 1\\n parameter_2: a\\n\" \\\n \"parameter_set1:\\n parameter_1: 1\\n parameter_2: b\\n\" \\\n \"parameter_set2:\\n parameter_1: 2\\n parameter_2: a\\n\" \\\n \"parameter_set3:\\n parameter_1: 2\\n parameter_2: b\\n\")])\n }\n\n @pytest.mark.unittest\n @pytest.mark.parametrize('parameter_schema, output_file_template, output_file, output_type, file_count, ' \\\n 'expected_calls',\n generate_io.values(),\n ids=generate_io.keys())\n def test_write_yaml(self, parameter_schema, output_file_template, output_file, output_type, file_count,\n expected_calls):\n with patch('waves.parameter_generators._ParameterGenerator._write_meta'), \\\n patch('builtins.open', mock_open()) as mock_file, \\\n patch('xarray.Dataset.to_netcdf') as xarray_to_netcdf, \\\n patch('sys.stdout.write') as stdout_write, \\\n patch('pathlib.Path.is_file', return_value=False):\n TestWriteYAML = CartesianProduct(parameter_schema,\n output_file_template=output_file_template,\n output_file=output_file,\n output_file_type=output_type)\n TestWriteYAML.write()\n stdout_write.assert_not_called()\n xarray_to_netcdf.assert_not_called()\n assert mock_file.call_count == file_count\n mock_file().write.assert_has_calls(expected_calls, any_order=False)\n","sub_path":"waves/tests/test_cartesian_product.py","file_name":"test_cartesian_product.py","file_ext":"py","file_size_in_byte":7934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"325228557","text":"\"\"\"VIN training.\n\nGrid 28x28\n\nAuthor: Yuhuang Hu\nEmail : duguyue100@gmail.com\n\"\"\"\nimport os\n\nimport keras.backend as K\n\nimport rlvision\nfrom rlvision import utils\nfrom rlvision.vin import vin_model\n\n# load data\nfile_name = os.path.join(rlvision.RLVISION_DATA,\n \"chain_data\", \"grid28_with_idx.pkl\")\n\n# parameters\nbatch_size = 256\nnb_epochs = 50\n\nprint('# Minibatch-size: {}'.format(batch_size))\nprint('# epoch: {}'.format(nb_epochs))\nprint('')\n\ntrain, test, _ = utils.process_map_data(file_name)\nmodel = vin_model(l_s=train[0].shape[2], k=20)\nmodel.compile(optimizer=\"adam\",\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit([train[0].transpose((0, 2, 3, 1))\n if K.image_dim_ordering() == 'tf' else train[0],\n train[1]],\n train[2],\n batch_size=batch_size,\n epochs=nb_epochs)\n\nmodel_json = os.path.join(rlvision.RLVISION_MODEL, \"vin_model_28.json\")\nmodel_h5 = os.path.join(rlvision.RLVISION_MODEL, \"vin_model_28.h5\")\nwith open(model_json, 'w') as f:\n f.write(model.to_json())\nmodel.save_weights(model_h5, overwrite=True)\n","sub_path":"rlvision/exps/vin_exp_28.py","file_name":"vin_exp_28.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"84168344","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\n\n# Read in power spectra\nps_data = np.loadtxt('DragCumulant_Second_Contribution_all_parts_t_500.d')\n\nk = ps_data[:,0]\nps_drag2= ps_data[:,1]\nps_drag2_linear = ps_data[:,2]\nps_drag2_nonlinear = ps_data[:,3]\nps_free =ps_data[:,4]\n\n# Create a new figure \nfig = plt.figure(figsize=(8,8), dpi=80)\n\n# Create subplots\nplot_ps = fig.add_subplot(111)\n\n\n# Plot power spectrum\nplot_ps.set_xscale('log')\nplot_ps.set_yscale('log')\nplot_ps.grid(True)\n\n#plot_ps.set_xlim(1.0e-5, 1.0e5)\nplot_ps.set_ylim(1.0e-7, 1.0e6)\n\nplot_ps.set_xlabel(r'wave number $k \\; [h / \\textrm{Mpc}]$')\nplot_ps.set_ylabel(r'powerspectrum $ [\\textrm{Mpc}^3] $')\n\nplot_ps.plot(k, ps_drag2, color=\"black\", linewidth=1.8, linestyle=\"-\", label=r'$\\left[i \\int \\textrm{d}3 \\; G^{(0,2)}_{\\rho_1 \\rho_2 D_3} \\mid_{\\vec{s}_3=0,\\tau_1=\\tau_2, \\vec{k}_1=-\\vec{k}_2} \\right]_2$')\nplot_ps.plot(k, ps_drag2_linear, color=\"orange\", linewidth=1.2, linestyle=\"-\", label=r'$\\left[i \\int \\textrm{d}3 \\; G^{(0,2)}_{\\rho_1 \\rho_2 D_3} \\mid_{\\vec{s}_3=0,\\tau_1=\\tau_2, \\vec{k}_1=-\\vec{k}_2} \\right]^{\\textrm{Linear}}_2$')\nplot_ps.plot(k, ps_drag2_nonlinear, color=\"red\", linewidth=1.2, linestyle=\"-\", label=r'$\\left[i \\int \\textrm{d}3 \\; G^{(0,2)}_{\\rho_1 \\rho_2 D_3} \\mid_{\\vec{s}_3=0,\\tau_1=\\tau_2, \\vec{k}_1=-\\vec{k}_2} \\right]^{\\textrm{Nonlinear}}_2$')\nplot_ps.plot(k, ps_free, color=\"navy\", linewidth=1.2, linestyle=\":\", label=r'$G^{(0,2)}_{\\rho \\rho}$')\n\n\n#plot_ps.plot(k, np.fabs(ps-ps_mm)/ps, 'orange')\n\nplot_ps.legend(prop={'size':12})\n\n\n# Set y ticks\n#plt.yticks(np.linspace(-1,1,5,endpoint=True))\n\n# Save figure using 72 dots per inch\nplt.savefig(\"DragCumulant_Second_Contribution_all_parts_t_500.pdf\",dpi=80)\n\n# Show result on screen\nplt.show()\n","sub_path":"DragCumulant/Second Contribution/Linear and Non linear Second Contribution Comparison to ff2p.py","file_name":"Linear and Non linear Second Contribution Comparison to ff2p.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112586210","text":"import os\nimport sys\n\nclass Atopy(object):\n\tdef __init__(self, sfile = None, wdebug = False, run = True, fsep = '\\\\'):\n\t\tself.debug = wdebug\n\t\tself.sfile = sfile\n\t\tself.dirs = []\n\t\tself.mpath = ''\n\t\tself.fsep = fsep\n\t\tself.ddir = os.path.dirname(os.path.realpath(__file__)).replace(self.fsep, '/')\n\t\tself.lists = self.getCwDirectory()\n\t\tself.mobjects = {}\n\n\t\tif run:\n\t\t\tself.autoload(self.lists)\n\n\tdef getCwDirectory(self, apath = None):\n\t\tif apath is not None:\n\t\t\tos.chdir(apath)\n\t\t\treturn os.listdir(apath)\n\n\t\tos.chdir(self.ddir)\n\t\treturn os.listdir(self.ddir)\n\n\tdef setCwDirectory(self, apath = None, supdir = 0):\n\t\tif apath is not None:\n\t\t\tndir = os.path.dirname(os.path.realpath(apath))\n\n\t\t\tfor i in range(0, supdir):\n\t\t\t\tndir = os.path.dirname(ndir).replace(self.fsep, '/')\n\n\t\t\tsys.path.append(ndir)\n\t\t\tself.ddir = ndir\n\n\t\tos.chdir(self.ddir)\n\t\tself.lists = os.listdir(self.ddir)\n\n\tdef autoload(self, lists = None, lev = 0):\n\t\tlists = self.lists if lists is None else lists\n\t\t\t\n\t\tfor fod in lists:\n\t\t\tif self.isValidDir(fod):\n\t\t\t\tself.dirs.append(fod)\n\t\t\telif self.isValidFile(fod):\n\t\t\t\ttry:\n\t\t\t\t\timp = __import__(self.getImportPath(fod), locals = True, globals = True, fromlist = [None], level = 0)\n\t\t\t\t\tself.mobjects[self.getClassname(fod)] = imp.__export__() if hasattr(imp, '__export__') else imp\n\n\t\t\t\t\tif self.debug:\n\t\t\t\t\t\tprint('[IMPORT] ' + self.getImportPath(fod) + ' [SUCCESS]')\n\t\t\t\texcept:\n\t\t\t\t\tprint('[IMPORT] ' + self.getImportPath(fod) + ' [FAILED]')\n\t\t\t\t\tpass\n\n\t\tdirs = self.dirs\n\t\tmpath = self.mpath\n\n\t\tfor idir in dirs:\n\t\t\tos.chdir(self.ddir + '/' + mpath.replace('.', '/'))\n\n\t\t\tif self.isValidDir(idir):\n\t\t\t\tself.dirs = []\n\t\t\t\tself.mpath = mpath\n\t\t\t\tself.mpath += idir if lev == 0 else '.' + idir\n\t\t\t\tself.autoload(self.getCwDirectory(self.ddir + '/' + self.mpath.replace('.', '/')), lev = lev + 1)\n\t\treturn\n\n\tdef get(self, mname):\n\t\tif mname in self.mobjects:\n\t\t\treturn self.mobjects.get(mname)\n\n\t\tprint('[MODULE] ' + mname + ' [NOT FOUND]')\n\t\treturn None\n\n\tdef listModules(self):\n\t\tprint('\\n***********************\\n', ' ' * int((len('***********************') / 2) - len('MODULE LIST') / 2 - 1), end=\"\")\n\t\tprint('MODULE LIST')\n\t\tprint('***********************')\n\t\tfor mod in self.mobjects:\n\t\t\tprint('[*]', mod, '==>', self.mobjects[mod])\n\t\tprint('***********************\\n')\n\n\tdef getImportPath(self, file):\n\t\treturn self.mpath + '.' + file.replace('.py', '') if len(self.mpath) > 0 else self.mpath + file.replace('.py', '')\n\n\tdef getClassname(self, file):\n\t\treturn file.replace('.py', '')\n\n\tdef isValidFile(self, file):\n\t\treturn os.path.isfile(file) and not file.startswith(__file__.split(self.fsep)[-1]) and not file.startswith(self.sfile.split(self.fsep)[-1]) and file.endswith('.py') and not file.startswith('__') and not file.endswith('__.py')\n\n\tdef isValidDir(self, cdir):\n\t\treturn os.path.isdir(cdir) and not cdir.startswith('__') and not cdir.endswith('__') and not '.' in cdir\n","sub_path":"Atopy.py","file_name":"Atopy.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556509303","text":"import pandas as pd\nfrom sklearn import preprocessing, linear_model, metrics\n\nfrom e1.constants import (\n MONETARY,\n ATTRIBUTE_COLUMN_NAMES,\n LABEL,\n RANDOM_OVERSAMPLER,\n IQR,\n)\nfrom e1.data_resampler import DataResampler\nfrom e1.data_scaler import DataScaler\nfrom e1.outlier_detector import OutlierDetector\n\nif __name__ == \"__main__\":\n test_data = pd.read_csv(\"test_data.csv\")\n train_data = pd.read_csv(\"train_data.csv\")\n\n train_data = train_data.drop(columns=MONETARY)\n\n train_data = OutlierDetector.remove_outliers(\n train_data, IQR, ATTRIBUTE_COLUMN_NAMES\n )\n\n train_data = DataScaler.scale(\n train_data, preprocessing.StandardScaler(), ATTRIBUTE_COLUMN_NAMES\n )\n\n attributes_data_resampled, label_data_resampled = DataResampler(\n RANDOM_OVERSAMPLER\n ).resample_data(train_data, ATTRIBUTE_COLUMN_NAMES, LABEL)\n\n linear_regression_model = linear_model.LinearRegression()\n logistic_regression_model = linear_model.LogisticRegression()\n\n linear_regression_model.fit(attributes_data_resampled, label_data_resampled)\n logistic_regression_model.fit(attributes_data_resampled, label_data_resampled)\n\n test_data = DataScaler.scale(\n test_data, preprocessing.StandardScaler(), ATTRIBUTE_COLUMN_NAMES\n )\n test_label_data = test_data[[LABEL]].values[:, 0]\n test_attributes_data = test_data[ATTRIBUTE_COLUMN_NAMES].values\n\n output_label_data = linear_regression_model.predict(test_attributes_data)\n # output_label_data = logistic_regression_model.predict(test_attributes_data)\n\n fpr, tpr, thresholds = metrics.roc_curve(\n test_label_data, output_label_data, pos_label=1\n )\n auc = metrics.auc(fpr, tpr)\n print(auc)\n","sub_path":"e1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395873093","text":"import time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import datetime\nfrom netmiko import ConnectHandler\nfrom my_devices import device_list\n\n\ndef ssh_conn(device):\n net_connect = ConnectHandler(**device)\n return net_connect.find_prompt()\n\n\nif __name__ == \"__main__\":\n\n start_time = datetime.now()\n max_threads = 4\n\n pool = ThreadPoolExecutor(max_threads)\n future = pool.submit(ssh_conn, device_list[0])\n\n print(future.done())\n time.sleep(5)\n print(future.done())\n\n # Waits until the future is complete\n print(\"Result: \" + future.result())\n\n end_time = datetime.now()\n print(end_time - start_time)\n\n","sub_path":"lesson10/ssh_threads_simple.py","file_name":"ssh_threads_simple.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"200526139","text":"#coding:utf-8\nimport re\nimport urllib.parse\nimport os\nimport sys\nimport requests\n\ndef create_folder(path):\n if os.path.isdir(path) ==False:\n os.system('md %s'%path)\n print(\"%s 创建成功\"%path)\n else:\n pass\n\nf = open('C:\\\\Users\\\\chenye\\\\Desktop\\\\logo.txt','r',encoding='utf-8')\nfor url in f.readlines():\n basepath = 'C:\\\\imgpath\\\\'\n print(url.replace('\\n',''))\n urlsplit = urllib.parse.urlsplit(url.replace('\\n',''))\n print(urlsplit)\n if urlsplit.netloc.startswith('en'):\n basepath = basepath+'en\\\\'\n else:\n basepath = basepath + 'cn\\\\'\n pathsplit = urlsplit.path.split('/')[1:-1]\n path = basepath + '\\\\'.join(pathsplit)\n # print(os.path.isdir(path))\n create_folder(path)\n # print(urlsplit.path)\n # print( urlsplit.path.replace(' ','%20'))\n with open(path+'\\\\'+urlsplit.path.split('/')[-1],'wb') as f:\n response = requests.get(urlsplit.scheme+'://'+urlsplit.netloc + urlsplit.path.replace(' ','%20'))\n # print(response.text)\n f.write(response.content)\n\n\n\n","sub_path":"tools/other/下载拍企logo图片并建立目录.py","file_name":"下载拍企logo图片并建立目录.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"153109636","text":"import socket, threading\nfrom common.constants import TRANSPORT\nimport logging\nlogger = logging.getLogger(\"sys.\" + __name__.split(\".\")[-1])\n\n\nclass BaseServer(object):\n\n def __init__(self, request_queue, response_queue, port, host=\"127.0.0.1\"):\n \"\"\"\n A base class for both client and meta server\n \"\"\"\n self.request_queue = request_queue\n self.response_queue = response_queue\n self.host = host\n self.port = port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind((self.host, self.port))\n\n self.connections = dict()\n\n def listen(self):\n \"\"\"\n Start listening for connections.\n Once accepted, on_connection will be called.\n \"\"\"\n threading.Thread(target=self._listen).start()\n\n def _listen(self):\n self.sock.listen()\n logger.info(\"Server @ port {} listening...\".format(self.port))\n while True:\n # wait for incoming connections\n connection, address = self.sock.accept()\n self.on_connection(connection, address)\n\n def on_connection(self, connection, address):\n pass\n\n def broadcast(self, data, without=None, type=None):\n \"\"\"\n Broadcast the data to all connections except \"without\".\n :param data: the data to be broadcasted\n :param without: broadcast to everyone except this client\n \"\"\"\n for client_id in list(self.connections):\n if client_id != without:\n try:\n self.connections[client_id].send(data, type)\n except:\n logger.error(\"Failed sending message to {} : data {}\".format(self.connections[client_id], data))\n\n def remove_connection(self, id):\n \"\"\"\n Removes the client from the list of currently connected clients.\n :param id: the client to be removed\n \"\"\"\n if id in self.connections:\n del self.connections[id]\n\n # Optional\n # Reduce udp delay\n if hasattr(self, 'udp_server'):\n self.udp_server.delay -= TRANSPORT.UDP_DELAY_PER_PLAYER\n logger.info(\"New UDP Delay value {}\".format(self.udp_server.delay))\n","sub_path":"server/network/base_server.py","file_name":"base_server.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550664686","text":"\"\"\"WALS model input data, training and predict functions.\"\"\"\n\nimport datetime\nimport numpy as np\nimport os\nimport pandas as pd\nfrom scipy.sparse import coo_matrix\nimport sh\nimport tensorflow as tf\n\nimport wals\nimport util\n\n# ratio of train set size to test set size\nTEST_SET_RATIO = 10\n\n# default hyperparameters\nDEFAULT_PARAMS = {\n 'weights': True,\n 'latent_factors': 5,\n 'num_iters': 20,\n 'regularization': 0.07,\n 'unobs_weight': 0.01,\n 'wt_type': 0,\n 'feature_wt_factor': 130.0,\n 'feature_wt_exp': 0.08,\n 'delimiter': ','\n}\n\n# parameters optimized with hypertuning for the MovieLens data set\nOPTIMIZED_PARAMS = {\n 'latent_factors': 5,\n 'regularization': 0.0010489312166459541,\n 'unobs_weight': 0.0012959067370488242,\n 'feature_wt_factor': 1.0067790209054464,\n}\n\n# parameters optimized with hypertuning for the included web views data set\nOPTIMIZED_PARAMS_WEB = {\n 'latent_factors': 30,\n 'regularization': 7.27,\n 'unobs_weight': 0.01,\n 'feature_wt_exp': 5.05,\n}\n\n\ndef create_test_and_train_sets(args, input_file, data_type='ratings'):\n \"\"\"Create test and train sets, for different input data types.\n\n Args:\n args: input args for job\n input_file: path to csv data file\n data_type: 'ratings': MovieLens style ratings matrix\n 'web_views': Google Analytics time-on-page data\n\n Returns:\n array of user IDs for each row of the ratings matrix\n array of item IDs for each column of the rating matrix\n sparse coo_matrix for training\n sparse coo_matrix for test\n\n Raises:\n ValueError: if invalid data_type is supplied\n \"\"\"\n if data_type == 'ratings':\n return _ratings_train_and_test(args['delimiter'],\n input_file,args['output_dir'],args['job_name'])\n else:\n raise ValueError('data_type arg value %s not supported.' % data_type)\n\n\ndef _ratings_train_and_test(delimiter, input_file,output_dir,job_name):\n \"\"\"Load data set. Assumes Movielens header, format etc.\n\n MovieLens data starts with user_id=1. The max user id is close to\n the number of users, but there may be missing user_id's or item ids\n (i.e. movies). For our sparse matrices we need to map the user/item ids\n down to a zero-based set of indices, without missing values.\n\n Args:\n use_headers: (boolean) true = headers, false = no headers\n delimiter: (string) delimiter to use for csv\n input_file: path to csv data file\n\n Returns:\n array of user IDs for each row of the ratings matrix\n array of item IDs for each column of the rating matrix\n sparse coo_matrix for training\n sparse coo_matrix for test\n \"\"\"\n df_shopping = pd.read_csv(input_file,sep=delimiter, low_memory=False)\n\n ## rename colnmaes\n df_shopping.columns = [\"Assignment_ID\", \"Logged_In\", \"User_ID\", \"Preformed\",\n \"Wound_duration\", \"Type_of_wound\", \"Wound_healing_phase\",\n \"Necrotic\", \"Infection\", \"Moisture\", \"Survival\", \"Painful_experience\",\n \"Edge_Callus\", \"Edge_Cyanotic\", \"Edge_Inverted\", \"Edge_Inert\", \"Edge_Maceration\",\n \"Edge_Normal\", \"Edge_Reepithelizing\", \"Skin_type\", \"Compression\", \"Filling\", \"Covering\",\n \"Absorbing\", \"Fixing\",\n \"Cleaning\", \"Reducing_pressure\", \"Debridement\", \"Combating_infection\", \"Restore_biobalance\",\n \"Article\"]\n\n df_shopping = df_shopping.drop(['Assignment_ID'], axis=1)\n\n # make_identifier already o-based\n\n df_shopping['Wound_ID'] = util.make_identifier(\n df_shopping[['Preformed', 'Wound_duration', 'Type_of_wound', 'Wound_healing_phase',\n 'Necrotic', 'Infection', 'Moisture', 'Survival', 'Painful_experience',\n 'Edge_Callus', 'Edge_Cyanotic', 'Edge_Inverted', 'Edge_Maceration',\n 'Edge_Inert', 'Edge_Normal', 'Edge_Reepithelizing', 'Skin_type', 'Compression',\n 'Filling', 'Covering', 'Absorbing', 'Fixing', 'Cleaning', 'Reducing_pressure',\n 'Debridement', 'Combating_infection', 'Restore_biobalance']])\n\n # save reindexed woundID back\n saved_df = df_shopping[['Preformed', 'Wound_duration', 'Type_of_wound', 'Wound_healing_phase',\n 'Necrotic', 'Infection', 'Moisture', 'Survival', 'Painful_experience',\n 'Edge_Callus', 'Edge_Cyanotic', 'Edge_Inverted', 'Edge_Maceration',\n 'Edge_Inert', 'Edge_Normal', 'Edge_Reepithelizing', 'Skin_type', 'Compression',\n 'Filling', 'Covering', 'Absorbing', 'Fixing', 'Cleaning', 'Reducing_pressure',\n 'Debridement', 'Combating_infection', 'Restore_biobalance','Wound_ID']]\n\n model_dir = os.path.join(output_dir, 'model')\n # if our output directory is a GCS bucket, write model files to /tmp,\n # then copy to GCS\n gs_model_dir = None\n if model_dir.startswith('gs://'):\n gs_model_dir = model_dir\n model_dir = '/tmp/{0}'.format(job_name+'woundID')\n\n os.makedirs(model_dir)\n saved_df.to_csv(os.path.join(model_dir, 'woundID'),index=None)\n\n if gs_model_dir:\n sh.gsutil('cp', '-r', os.path.join(model_dir, '*'), gs_model_dir)\n\n\n ratings_df = df_shopping[['Article', 'Wound_ID']]\n ratings_df = ratings_df.groupby([\"Article\", \"Wound_ID\"]).size().reset_index(name=\"Times\")\n ratings_df['article_id_rearranged'] = util.make_identifier(ratings_df[['Article']])\n ratings_df.columns = ['article_id', 'wound_id', 'rating', 'article_id_rearranged']\n ratings_df = ratings_df[['wound_id', 'article_id_rearranged', 'rating', 'article_id']]\n\n ratings_df[ratings_df.columns] = ratings_df[ratings_df.columns].apply(pd.to_numeric, errors='coerce')\n\n np_users = ratings_df.wound_id.as_matrix()\n np_items = ratings_df.article_id_rearranged.as_matrix()\n unique_users = np.unique(np_users)\n unique_items = np.unique(np_items)\n\n n_users = unique_users.shape[0]\n n_items = unique_items.shape[0]\n\n ratings_cp = ratings_df.as_matrix(['wound_id', 'article_id_rearranged', 'rating', 'article_id'])\n user_map = ratings_cp[:, 0]\n item_map = ratings_cp[:, 3]\n\n ratings_df = ratings_df.drop(['article_id'], axis=1)\n ratings = ratings_df.as_matrix(['wound_id', 'article_id_rearranged', 'rating'])\n\n tr_sparse, test_sparse = _create_sparse_train_and_test(ratings,\n n_users, n_items)\n # the true article id saved\n return user_map, item_map, tr_sparse, test_sparse\n\ndef _create_sparse_train_and_test(ratings, n_users, n_items):\n \"\"\"Given ratings, create sparse matrices for train and test sets.\n\n Args:\n ratings: list of ratings tuples (u, i, r)\n n_users: number of users\n n_items: number of items\n\n Returns:\n train, test sparse matrices in scipy coo_matrix format.\n \"\"\"\n # pick a random test set of entries, sorted ascending\n test_set_size = int(len(ratings) / TEST_SET_RATIO)\n test_set_idx = np.random.choice(range(len(ratings)), size=test_set_size, replace=False)\n test_set_idx = sorted(test_set_idx)\n\n # sift ratings into train and test sets\n ts_ratings = ratings[test_set_idx]\n tr_ratings = np.delete(ratings, test_set_idx, axis=0)\n\n u_tr, i_tr, r_tr = zip(*tr_ratings)\n tr_sparse = coo_matrix((r_tr, (u_tr, i_tr)), shape=(n_users, n_items))\n\n u_ts, i_ts, r_ts = zip(*ts_ratings)\n test_sparse = coo_matrix((r_ts, (u_ts, i_ts)), shape=(n_users, n_items))\n\n return tr_sparse, test_sparse\n\ndef train_model(args, tr_sparse):\n \"\"\"Instantiate WALS model and use \"simple_train\" to factorize the matrix.\n\n Args:\n args: training args containing hyperparams\n tr_sparse: sparse training matrix\n\n Returns:\n the row and column factors in numpy format.\n \"\"\"\n dim = args['latent_factors']\n num_iters = args['num_iters']\n reg = args['regularization']\n unobs = args['unobs_weight']\n wt_type = args['wt_type']\n feature_wt_exp = args['feature_wt_exp']\n obs_wt = args['feature_wt_factor']\n\n tf.logging.info('Train Start: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))\n\n # generate model\n input_tensor, row_factor, col_factor, model = wals.wals_model(tr_sparse,\n dim,\n reg,\n unobs,\n args['weights'],\n wt_type,\n feature_wt_exp,\n obs_wt)\n\n # factorize matrix\n session = wals.simple_train(model, input_tensor, num_iters)\n\n tf.logging.info('Train Finish: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))\n\n # evaluate output factor matrices\n output_row = row_factor.eval(session=session)\n output_col = col_factor.eval(session=session)\n\n # close the training session now that we've evaluated the output\n session.close()\n\n return output_row, output_col\n\n\ndef save_model(args, user_map, item_map, row_factor, col_factor):\n \"\"\"Save the user map, item map, row factor and column factor matrices in numpy format.\n\n These matrices together constitute the \"recommendation model.\"\n\n Args:\n args: input args to training job\n user_map: user map numpy array\n item_map: item map numpy array\n row_factor: row_factor numpy array\n col_factor: col_factor numpy array\n \"\"\"\n model_dir = os.path.join(args['output_dir'], 'model')\n\n # if our output directory is a GCS bucket, write model files to /tmp,\n # then copy to GCS\n gs_model_dir = None\n if model_dir.startswith('gs://'):\n gs_model_dir = model_dir\n model_dir = '/tmp/{0}'.format(args['job_name'])\n\n os.makedirs(model_dir)\n np.save(os.path.join(model_dir, 'user'), user_map)\n np.save(os.path.join(model_dir, 'item'), item_map)\n np.save(os.path.join(model_dir, 'row'), row_factor)\n np.save(os.path.join(model_dir, 'col'), col_factor)\n\n if gs_model_dir:\n sh.gsutil('cp', '-r', os.path.join(model_dir, '*'), gs_model_dir)\n\n\n\ndef generate_recommendations(user_idx, row_factor, col_factor, k):\n \"\"\"Generate recommendations for a user.\n\n Args:\n user_idx: the row index of the user in the ratings matrix,\n\n row_factor: the row factors of the recommendation model\n col_factor: the column factors of the recommendation model\n\n k: number of recommendations requested\n\n Returns:\n list of k item indexes with the predicted highest rating, excluding\n those that the user has already rated\n \"\"\"\n\n # bounds checking for args\n # assert (row_factor.shape[0] - len(user_rated)) >= k\n\n # retrieve user factor\n user_f = row_factor[user_idx]\n\n # dot product of item factors with user factor gives predicted ratings\n pred_ratings = col_factor.dot(user_f)\n\n # find candidate recommended item indexes sorted by predicted rating\n k_r = k\n candidate_items = np.argsort(pred_ratings)[-k_r:]\n\n # remove previously rated items and take top k\n recommended_items = [i for i in candidate_items]\n recommended_items = recommended_items[-k:]\n\n # flip to sort highest rated first\n recommended_items.reverse()\n\n return recommended_items\n\n","sub_path":"wal_ml_engine/trainer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402336124","text":"#!/usr/bin/python\n#coding=utf-8\n\nimport getter\nfrom bs4 import BeautifulSoup\n\n\nclass JandanHome(getter.Getter):\n\tdef get_target(self):\n\t\tbs=BeautifulSoup(self.content.content)\n\t\tself.target=bs.findAll(name='div',attrs={'class':'post f'})\n\t\tif self.target is None:\n\t\t\texit()\n\t\tfor item in self.target:\n\t\t\ttmp=item.findChild('h2')\n\t\t\tif tmp is not None:\n\t\t\t\tself.fmted+=tmp\n\nclass JandanMorePage(getter.Getter):\n\tdef get_target(self):\n\t\tbs=BeautifulSoup(self.content.content)\n\t\tself.target=bs.findAll(name='div',attrs={'class':'post'})\n\t\tif self.target is None:\n\t\t\texit()\n\t\tfor item in self.target:\n\t\t\ttmp=item.findChild('h2')\n\t\t\tif tmp is not None:\n\t\t\t\tself.fmted+=tmp\n\n\nclass JandanNode(getter.Getter):\n\tdef get_target(self):\n\t\tbs=BeautifulSoup(self.content.content)\n\t\tself.target=bs.findChild(name='div',attrs={'id':'body'})\n\t\ttmp=[]\n\t\ttmp+=self.target.findChild(name='div',attrs={'class':'post f'}).findAll('p')\n\t\tself.fmted.append(tmp)\n\t\tself.fmted+=bs.findAll(name='div',attrs={'class':'acv_comment'})\n\ndef jandan_show_home(home):\n\tif(len(home)==0):\n\t\tprint(\"nothing to show.\\n\")\n\t\treturn\n\tcnt=0\n\ttn=''\n\tfor i in home:\n\t\tcnt+=1\n\t\tif(cnt<10):\n\t\t\ttn='0'+str(cnt)\n\t\telse:\n\t\t\ttn=str(cnt)\n\t\tprint('['+tn+'] - '+i.text)\n\ndef jandan_show_node(node):\n\tif(len(node)==0):\n\t\tprint(\"nothing to show.\\n\")\n\t\treturn\n\tprint('\\n[Content:]\\n')\n\tfor item in node[0]:\n\t\ttry:\n\t\t\tprint(item.text)\n\t\texcept UnicodeEncodeError:\n\t\t\tprint('meet some error.')\n\t\t\tcontinue\n\n\tprint('\\n[%s Nice Replys:]'%(str(len(node)-1)))\t\t\t\n\tfor i in node[1:]:\n\t\tbuf='[#] - '+i.text.lstrip('\\r\\n').strip(' ')\n\t\ttry:\n\t\t\tprint(buf)\n\t\texcept UnicodeEncodeError:\t\t\t\n\t\t\tcontinue\n\t\n\t\ndef jandan_show(url):\n\tisnode=False\n\ttarget_url=url\n\thome=JandanHome(target_url)\n\thome_page=home.start()\n\tindex=1\n\twhile True:\n\t\tinstr=''\n\t\tif isnode is True:\n\t\t\tinstr=input('\\nPress b to return, q to quit\\n')\n\t\t\tif instr=='b':\n\t\t\t\tisnode=False\n\t\t\t\tcontinue\n\t\telse:\n\t\t\tjandan_show_home(home_page)\n\t\t\tinstr=input('\\nPlease select the page you want to read.\\nKeys:\\nj-->previous page\\nk-->next page\\nq to quit\\n')\n\n\t\tif len(instr)>3 or instr =='':\n\t\t\tcontinue\n\t\tif instr=='q' or instr=='b':\n\t\t\tbreak\n\t\tif instr=='j':\n\t\t\tindex-=1\n\t\t\tif index < 2:\n\t\t\t\thome=JandanHome(target_url)\n\t\t\t\tindex=1\n\t\t\telse:\n\t\t\t\thome=JandanMorePage(target_url+'/page/'+str(index))\n\t\t\thome_page=home.start()\n\t\t\tcontinue\n\t\tif instr=='k':\n\t\t\tindex+=1\n\t\t\thome=JandanMorePage(target_url+'/page/'+str(index))\n\t\t\thome_page=home.start()\n\t\t\tcontinue\n\t\ttry:\n\t\t\tif int(instr)>0 and int(instr)<=len(home_page):\n\t\t\t\tnode=JandanNode(home_page[int(instr)-1]['href'])\n\t\t\t\tnode_page=node.start()\n\t\t\t\tjandan_show_node(node_page)\n\t\t\t\tisnode=True\n\t\texcept ValueError:\n\t\t\tcontinue\n","sub_path":"viewsimple/jandanGetter.py","file_name":"jandanGetter.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"588553896","text":"from .exceptions import StateError\n\n\nclass Parser(object):\n \"\"\"\n An implementation of an LL(1) parser\n \"\"\"\n def __init__(self, lexer):\n self.lexer = lexer\n self._state = None\n\n def run(self, input):\n self._state = _ParserState(self.lexer, input)\n try:\n return self.begin()\n finally:\n self._state = None\n\n def begin(self):\n \"\"\"\n Parse the top level statement/expression. Called automatically by\n `run`. It is an error if not implemented\n \"\"\"\n raise NotImplementedError('Parser.begin')\n\n def move_next(self, lookahead=False):\n if self._state is None:\n raise StateError('No current parser state')\n return self._state.move_next(lookahead=lookahead)\n\n @property\n def position(self):\n if self._state is None:\n raise StateError('No current parser state')\n return self._state.position\n\n\nclass _ParserState(object):\n def __init__(self, lexer, input):\n self.iter_tokens = lexer.run(input)\n self.lookahead_token = None\n self.position = 0\n\n def _peek_next(self):\n if self.lookahead_token is None:\n try:\n self.lookahead_token = next(self.iter_tokens)\n except StopIteration:\n pass\n return self.lookahead_token\n\n def move_next(self, lookahead=False):\n if lookahead:\n return self._peek_next()\n if self.lookahead_token is not None:\n token = self.lookahead_token\n self.lookahead_token = None\n else:\n try:\n token = next(self.iter_tokens)\n except StopIteration:\n return None\n self.position = token.position\n return token\n","sub_path":"sam_server/parsers/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"253941804","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 7 02:58:30 2020\n\n@author: jidekickpush\n\"\"\"\n\"\"\" What is the relation between shark attacks, seasons and human activity? \n - Seasonality of the attacks\n - Human activity vs shark attack\n - Activity vs fatal shark attack\"\"\"\n \nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\n\n\n\n#year=2005\nyear=int(input('Enter the year: '))\n\ndef acquisition():\n df=pd.read_csv('/Users/jidekickpush/Documents/GitHub/0323_2020DATAPAR/Labs/module_1/Pipelines-Project/Data/GSAF5.csv', encoding ='cp1252')\n return df\n\ndef data_cleaning(df):\n null_cols = df.isnull().sum()\n null_cols\n null_cols[null_cols > 0]\n \n df=df.drop(['Unnamed: 22','Unnamed: 23','Case Number.1','Case Number.2','Date','Type','Name', 'Sex ','Age','Injury','Time','Species ','Investigator or Source','pdf','href formula', 'href'], axis=1)\n \n df.rename(columns={'original order':'Id','Country':'Place'}, inplace = True)\n \n df=df[df['Year']>1900]\n \n df.replace(regex={\n r'\\?':'', \n r'\\s\\/\\s[A-Z\\s]+': '', \n r'\\s$':'', r'^\\s':''\n }, inplace=True)\n \n df['Activity'] = df['Activity'].fillna('Not_Identified')\n \n df.rename(columns={'Activity':'unActivity'}, inplace=True)\n df_activity = df['unActivity']\n activity = []\n for a in df_activity:\n if re.search(r'Not_y[\\w\\s\\,]+|Not_[\\w\\s\\,]+|[\\w\\s\\,]+Not_[\\w\\s\\,]+', str(a)):\n a = 'Not_Identified'\n elif re.search(r'Surf[\\w\\s\\,]+|surf[\\w\\s\\,]+|[\\w\\s\\,]+surf[\\w\\s\\,]+', str(a)):\n a = 'Surfing'\n elif re.search(r'Board[\\w\\s\\,]+|board[\\w\\s\\,]+|[\\w\\s\\,]+board[\\w\\s\\,]+', str(a)):\n a = 'Surfing'\n elif re.search(r'Fish[\\w\\s\\,]+|fish[\\w\\s\\,]+|[\\w\\s\\,]+fish[\\w\\s\\,]+', str(a)):\n a = 'Fishing'\n elif re.search(r'Spear[\\w\\s\\,]+|spear[\\w\\s\\,]+|[\\w\\s\\,]+spear[\\w\\s\\,]+', str(a)):\n a = 'Fishing'\n elif re.search(r'Swim[\\w\\s\\,]+|swim[\\w\\s\\,]+|[\\w\\s\\,]+swim[\\w\\s\\,]+', str(a)):\n a = 'Swimming'\n elif re.search(r'Bath[\\w\\s\\,]+|bath[\\w\\s\\,]+|[\\w\\s\\,]+bath[\\w\\s\\,]+', str(a)):\n a = 'Bathing'\n elif re.search(r'Wadi[\\w\\s\\,]+|wadi[\\w\\s\\,]+|[\\w\\s\\,]+wadi[\\w\\s\\,]+', str(a)):\n a = 'Bathing'\n elif re.search(r'Snor[\\w\\s\\,]+|snor[\\w\\s\\,]+|[\\w\\s\\,]+snor[\\w\\s\\,]+', str(a)):\n a = 'Snorkeling'\n elif re.search(r'Div[\\w\\s\\,]+|div[\\w\\s\\,]+|[\\w\\s\\,]+div[\\w\\s\\,]+', str(a)):\n a = 'Diving'\n elif re.search(r'Boat[\\w\\s\\,]+|boat[\\w\\s\\,]+|[\\w\\s\\,]+boat[\\w\\s\\,]+', str(a)):\n a = 'Boating'\n elif re.search(r'Sail[\\w\\s\\,]+|sail[\\w\\s\\,]+|[\\w\\s\\,]+sail[\\w\\s\\,]+', str(a)):\n a = 'Boating'\n elif re.search(r'Crui[\\w\\s\\,]+|crui[\\w\\s\\,]+|[\\w\\s\\,]+crui[\\w\\s\\,]+', str(a)):\n a = 'Boating'\n else: a = 'Others'\n activity.append(a)\n df['Activity'] = activity\n df = df.drop(['unActivity'], axis=1)\n \n df['Date']=df['Case Number']\n df['Date'].replace(regex = {r'.[A-Za-z]$':''}, inplace = True)\n \n df['Month']=[m[5:7] for m in df['Case Number']]\n df['Month'].astype(int)\n # Get 'Months' of indexes for which column month has value 00\n indexMonth = df[ df['Month'] == '00' ].index\n \n # Delete these row indexes from dataFrame\n df.drop(indexMonth , inplace=True)\n \n df.rename(columns={ 'Fatal (Y/N)' : 'Fatal'}, inplace=True)\n df = df.replace({'Fatal': { 'N' : '0', 'Y' : '1', 'n' : '0', 'y' : '1', 'UNKNOWN' : '0', 'F' : '0', '#VALUE!' : '0'}})\n df['Fatal'].astype(bool)\n \n df = df[['Id','Date', 'Year', 'Month', 'Place', 'Area','Location', 'Activity', 'Fatal']]\n return df\n\ndef binning(df):\n season_labels=['Winter','Spring','Summer','Fall']\n cutoffs= ['00','04','07','10','12']\n bins = pd.cut(df['Month'], cutoffs, labels=season_labels)\n df['Season']=bins\n return df\n\ndef filter_by_year(df):\n global year\n filtered=df[df.Year==year]\n return filtered\n\n\"\"\"Seasonality of the attacks\"\"\"\n\ndef seasonality_attacks(df):\n seasonality = df.pivot_table(index=['Season'], values=['Date'], aggfunc= len,fill_value=0)\n seasonality = seasonality.rename(columns= {'Date':'Count'})\n seasonality['Ratio'] = seasonality['Count'] * 100 / seasonality['Count'].sum()\n seasonality = seasonality.round({'Ratio':2})\n df_view1 = seasonality.T\n display(df_view1)\n return df\n\ndef viz_seasonality_attacks(df):\n global year\n barchart=df.groupby('Season')['Season']\\\n .value_counts()\\\n .unstack(level=0)\\\n .plot.bar(stacked=False)\n plt.title(f\"Season vs shark attack during the {year}\")\n plt.show() \n return barchart\n\n\"\"\"Human activity vs shark attack\"\"\"\n \ndef activity_season(df):\n activity_season = df.pivot_table(index=['Activity', 'Season'], values=['Date'], aggfunc= len, fill_value=0) \n activity_season = activity_season.rename(columns= {'Date' : 'Count'})\n activity_season['Ratio'] = activity_season['Count'] * 100 / activity_season['Count'].sum() \n activity_season = activity_season.round({'Ratio' : 2})\n activity_season.sort_values(by=['Activity','Ratio'], ascending=False, inplace=True)\n df_view2 = activity_season.T\n display(df_view2)\n return df\n\ndef viz_activity_season(df):\n global year\n barchart=df.groupby('Season')['Activity']\\\n .value_counts()\\\n .unstack(level=0)\\\n .plot.bar(stacked=False)\n plt.title(f\"Human activity vs shark attack during the {year}\")\n plt.show()\n return barchart\n\"\"\"Activity vs fatal shark attack\"\"\"\n\ndef activity_fatal(df):\n fatal_activity = df.pivot_table(index=['Activity', 'Fatal'], values=['Date'], aggfunc= len, fill_value=0) \n fatal_activity = fatal_activity.rename(columns= {'Date' : 'Count'})\n fatal_activity['Ratio'] = fatal_activity['Count'] * 100 / fatal_activity['Count'].sum() \n fatal_activity = fatal_activity.round({'Ratio' : 2})\n df_view3 = fatal_activity.T\n display (df_view3)\n return df\n\ndef viz_activity_fatal(df):\n global year\n barchart=df.groupby('Activity')['Fatal']\\\n .value_counts()\\\n .unstack(level=1)\\\n .plot.bar(stacked=False)\n plt.title(f\"Activity vs fatal shark attack during the {year}\")\n plt.show()\n return barchart\n\n\n\nif __name__=='__main__':\n data_raw=acquisition()\n data_cleaned=data_cleaning(data_raw)\n data_binning=binning(data_cleaned)\n data_filtered=filter_by_year(data_binning)\n data_seasonality = seasonality_attacks(data_filtered)\n data_viz_seasonality_attacks = viz_seasonality_attacks(data_filtered)\n data_activity_season = activity_season(data_filtered)\n data_viz_activity_season = viz_activity_season(data_filtered)\n data_sactivity_fatal = activity_fatal(data_filtered)\n data_viz_activity_fatal = viz_activity_fatal(data_filtered)\n \n #save_fig = viz_activity_season(barchart)\n \n \n \n \n \n \n \n \n ","sub_path":"Labs/module_1/Pipelines-Project/Project_Sharks_Analytics_final.py","file_name":"Project_Sharks_Analytics_final.py","file_ext":"py","file_size_in_byte":6929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"638414120","text":"from datetime import datetime\n\n#converts a string containing the date for the first entry of netcdf4 ebos data (and anything else under certain constraints)\n# want to reduce the messy ebos datestr to one able to be handled by datetime functions, should work for most common date formats as long as : is not used to seperate yyyy:mm:dd also no other numbers unrealed to date in string\n# function outputs the reduced string\n# also fails at american (aka retarded) dates mm/dd/yyyy\ndef format_datestr(datestr):\n \n numbers=\"0123456789\"\n strlen=len(datestr)\n i=0\n count=0\n prevno=0\n prevdelim=0\n pdelimstr=''\n yeardef=0 \n p=-1 \n struse=''\n pdelim=''\n while p < strlen: #first go through datstr to identify if a number or not\n print(p) \n p+=1\n if datestr[p]==numbers[0] or datestr[p]==numbers[1] or datestr[p]==numbers[2]\\\n or datestr[p]==numbers[3] or datestr[p]==numbers[4] or datestr[p]==numbers[5]\\\n or datestr[p]==numbers[6] or datestr[p]==numbers[7] or datestr[p]==numbers[8] or datestr[p]==numbers[9]:\n \n struse+=datestr[p] #if number add to reduced string \n prevno=1 \n count+=1 # count to see if groups of numbers are years or not\n print('count='+str(count))\n print('struse=' + struse)\n else:\n if prevno==1:\n delim=datestr[p] # in non-number branch but since last entry was number this must be a delimiter\n print('pdelim='+pdelim)\n print('delim='+delim)\n if delim==\":\": # a : delimiter is almost exclusive to times of day hh:mm therfore want to skip ahead and overwrite struse\n struse=''\n p+=2\n \n else: \n struse+=delim\n i+=1\n \n if count==4:\n yst=p-count\n yeardef=1 # identify if its a year\n \n \n if pdelim==delim:\n if yeardef==1:\n print('op1='+struse)\n struse=struse + datestr[p+1:p+3] \n fmt='%Y'+delim+'%m'+ delim + '%d' #if a year has been identified aswell as a repeated delim tehn format must be as shown\n break\n else:\n print('op2='+struse)\n struse=struse + datestr[p+1:p+5]\n fmt='%d'+delim+'%m'+delim+'%Y' #if a year hasnt been then\n break #Reset count\n pdelim=delim\n count=0\n \n prevno=0 \n print('in else p=' + str(p)) \n\n \n return (struse, fmt)\n","sub_path":"backend/datehandle.py","file_name":"datehandle.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"18383191","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"Event/Issue Connector\"\"\"\nfrom lib.utility import Utility\nfrom lib.event import Event\nfrom lib.issue import Issue\n\ndef main_events():\n \"\"\"Main function for retrieve_events\"\"\"\n utility = Utility()\n args = utility.updated_hash()\n if args[\"starting\"] is not None:\n for i in args[\"api_keys\"]:\n event = Event(i['key_id'], i['secret_key'])\n event.retrieve_events()\n\n\ndef main_issues():\n \"\"\"Main function for retrieve_issues\"\"\"\n utility = Utility()\n args = utility.issues_updated_hash()\n if args[\"issues_starting\"] is not None:\n for i in args[\"api_keys\"]:\n issue = Issue(i['key_id'], i['secret_key'])\n issue.retrieve_issues()\n\n\nif __name__ == \"__main__\":\n main_events()\n main_issues()\n","sub_path":"halo_events.py","file_name":"halo_events.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"35072303","text":"import re\n\nfrom elasticsearch import Elasticsearch\n\nfrom constant.stree import STree\n\nes = Elasticsearch()\n\n\nclass State:\n def __init__(self, search_text):\n self.search_text = search_text\n self.constant_list = []\n self.similarity_score = 0\n\n def update_search_text(self, constant):\n return re.sub(constant, r\" \\0 \", self.search_text)\n\n def generate_children(self, stree, transformed_type, visited_list):\n new_cs_list = stree.most_cs(self.constant_list, [], 100)\n new_state_list = []\n for cs in new_cs_list:\n if cs in visited_list:\n continue\n print(cs, self.update_search_text(cs))\n state = State(self.update_search_text(cs))\n # print(cs)\n state.constant_list = self.constant_list[:] + [cs]\n state.similarity_score = state.similarity(transformed_type)\n new_state_list.append(state)\n return new_state_list\n\n def similarity(self, transformed_type):\n try:\n result = es.search(index=\"transformed\", doc_type=transformed_type,\n body={\n \"query\": {\n \"match\": {\n \"textual\": self.search_text,\n }\n }\n },\n size=1)\n return result['hits']['hits'][0][\"_score\"]\n except:\n return 0\n\n\nclass Searcher:\n def __init__(self, raw_list, transformed_list, transformed_type):\n self.current_state_list = []\n self.value_list = raw_list\n self.transformed_list = transformed_list\n self.transformed_type = transformed_type\n\n self.stree = STree([val.text for val in self.value_list])\n self.visited_state_list = []\n self.used_constant_list = []\n\n def index_data(self):\n if not es.indices.exists(index=\"transformed\"):\n es.indices.create(index=\"transformed\", body={\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"textual\": {\n \"tokenizer\": \"my_tokenizer\"\n }\n },\n \"tokenizer\": {\n \"my_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 1,\n \"max_gram\": 3,\n \"token_chars\": [\n \"letter\",\n \"digit\",\n \"punctuation\"\n ]\n }\n }\n }\n }\n })\n es.index(index=\"transformed\", doc_type=self.transformed_type, body={\"textual\": \" \".join(self.transformed_list)})\n\n def search(self):\n self.index_data()\n state = State(\" \".join([x.text for x in self.value_list]))\n self.current_state_list = [state]\n while self.current_state_list:\n state = self.current_state_list[0]\n print(state.constant_list, state.similarity_score)\n if state.constant_list:\n self.used_constant_list.append(state.constant_list[-1])\n new_states = state.generate_children(self.stree, self.transformed_type, self.used_constant_list)\n\n self.current_state_list.remove(state)\n self.visited_state_list.append(state)\n for new_state in new_states:\n if new_state.similarity_score < state.similarity_score:\n self.visited_state_list.append(new_state)\n self.used_constant_list.append(new_state.constant_list[-1])\n continue\n if new_state not in self.visited_state_list:\n self.current_state_list.append(new_state)\n best_states = sorted(self.visited_state_list, key=lambda state: state.similarity_score, reverse=True)\n return best_states[0].constant_list\n","sub_path":"src/constant/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"114422306","text":"# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0\n# For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt\n\ntry:\n import readline # noqa: F401\nexcept ImportError:\n pass\nimport argparse\nimport os\nimport sys\n\nfrom .prog_snapshot import ProgSnapshot\n\n\nclass Simulator:\n def __init__(self, json_string, no_clear=False, extra_newline=False):\n try:\n from rich.console import Console # type: ignore\n from rich.syntax import Syntax # type: ignore\n self.console = Console()\n\n def p(s):\n syntax = Syntax(s, \"python\", theme=\"monokai\")\n self.console.print(syntax, soft_wrap=True)\n\n self.print = p\n except ImportError:\n self.print = print\n self.snapshot = ProgSnapshot(json_string, self.print)\n if not self.snapshot.valid:\n sys.exit(1)\n self.no_clear = no_clear\n self.extra_newline = extra_newline\n\n def start(self):\n self.clear()\n self.snapshot.show()\n while True:\n try:\n cmd = input(\">>> \")\n if self.extra_newline:\n print(\"\")\n self.parse_cmd(cmd)\n except EOFError:\n sys.exit(0)\n\n def clear(self):\n if not self.no_clear:\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\n def parse_cmd(self, cmd):\n args = cmd.split()\n if not args:\n return\n success = False\n if args[0] == \"s\":\n success, err_msg = self.snapshot.step()\n elif args[0] == \"sb\":\n success, err_msg = self.snapshot.step_back()\n elif args[0] == \"n\":\n success, err_msg = self.snapshot.next()\n elif args[0] == \"nb\":\n success, err_msg = self.snapshot.next_back()\n elif args[0] == \"r\":\n success, err_msg = self.snapshot.func_return()\n elif args[0] == \"rb\":\n success, err_msg = self.snapshot.func_return_back()\n elif args[0] == \"t\":\n if len(args) == 1:\n success, err_msg = self.snapshot.print_timestamp()\n return\n elif len(args) == 2:\n success, err_msg = self.snapshot.goto_timestamp(float(args[1]))\n else:\n success, err_msg = False, \"t takes 1 or no argument\"\n elif args[0] == \"u\":\n success, err_msg = self.snapshot.up()\n elif args[0] == \"d\":\n success, err_msg = self.snapshot.down()\n elif args[0] == \"w\":\n success, err_msg = self.snapshot.where()\n return\n elif args[0] == \"tid\":\n if len(args) == 1:\n success, err_msg = self.snapshot.list_tid()\n return\n elif len(args) == 2:\n try:\n tid = int(args[1])\n success, err_msg = self.snapshot.goto_tid(tid)\n except ValueError:\n print(\"tid needs to be an integer\")\n return\n else:\n success, err_msg = False, \"tid takes 1 or no argument\"\n elif args[0] == \"pid\":\n if len(args) == 1:\n success, err_msg = self.snapshot.list_pid()\n return\n elif len(args) == 2:\n try:\n pid = int(args[1])\n success, err_msg = self.snapshot.goto_pid(pid)\n except ValueError:\n print(\"tid needs to be an integer\")\n return\n else:\n success, err_msg = False, \"pid takes 1 or no argument\"\n elif args[0] in [\"arg\", \"args\"]:\n success, err_msg = self.snapshot.print_args()\n return\n elif args[0] == \"counter\":\n success, err_msg = self.snapshot.print_counter()\n return\n elif args[0] == \"object\":\n success, err_msg = self.snapshot.print_object()\n return\n elif args[0] in [\"quit\", \"exit\", \"q\"]:\n sys.exit(0)\n else:\n print(\"Invalid command: {}\".format(cmd))\n return\n\n if success:\n self.clear()\n self.snapshot.show()\n else:\n print(err_msg)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", nargs=1)\n parser.add_argument(\"--no_clear\", action=\"store_true\", default=False)\n parser.add_argument(\"--extra_newline\", action=\"store_true\", default=False)\n\n options = parser.parse_args(sys.argv[1:])\n\n filename = options.file[0]\n with open(filename, encoding=\"utf-8\") as f:\n s = f.read()\n\n sim = Simulator(s, no_clear=options.no_clear, extra_newline=options.extra_newline)\n sim.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/viztracer/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400292647","text":"import sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n#from PyQt5.QtChart import *\n\nfrom enum import IntEnum\nimport random\nfrom functools import partial\nimport math\nimport os\nimport numpy as np\nimport time\n\ndef samplediscrete(probabilityvec):\n r = random.random()*sum(probabilityvec)\n cumsum = 0.0\n for (i,v) in enumerate(probabilityvec):\n cumsum += v\n if r <= cumsum:\n return i\n return 0\n \n\nRELEASE_VERSION = False\n\nclass Answer(IntEnum):\n NONE = -1\n YES = 0 \n NO = 1\n PROBABLYYES = 2\n DONTKNOW = 3\n PROBABLYNO = 4 \n\nscript_path = os.path.dirname(os.path.abspath( __file__ ))\n\nclass PausableQTimer(QTimer):\n \n def __init__(self):\n self.remainingtime = 0\n \n def pause(self):\n self.remainingtime = self.remainingTime()\n self.stop()\n self.setInterval(self.remainingtime)\n \n def resume(self):\n self.start()\n \n \n\nclass InputMethod(IntEnum):\n MOUSE = 0\n P300SPELLING = 1\n SSVEP = 2\n\nborderpen = QPen(QColor(100,100,100,255), 2)\npressedborderpen = QPen(QColor(25,25,25,255), 3)\n\nunselectedcolor = Qt.white\nmouseovercolor = QColor(225,225,225,255)\npressedcolor = QColor(175,175,175,255) \nselectedcolor = QColor(255,128,128,255)\nflashcolor = QColor(50,50,200,255)\nselectedcolor = pressedcolor\n\nfontpenblack = QPen(QColor(0,0,0,225))\nfontpentransparent = QPen(QColor(0,0,0,30))\nnormalfont = QFont('Roboto', 36, weight=QFont.Normal)\nboldfont = QFont('Roboto', 36, weight=QFont.Bold)\n \nclass AnswerPanelWidget(QWidget):\n \n answerclicked = pyqtSignal(int)\n \n def setInputMethod(self, inputmethod): \n self.inputmethod = inputmethod\n if self.inputmethod == InputMethod.MOUSE:\n self.setMouseTracking(True)\n else:\n self.setMouseTracking(False)\n \n def __init__(self, inputmethod):\n super().__init__() \n self.setInputMethod(inputmethod)\n \n self.pressedanswer = Answer.NONE\n self.mouseoveranswer = Answer.NONE\n self.softoptionsenabled = True\n self.answerclicked.connect(self.answerClickedEvent) \n \n self.answers = [\"Yes\", \"No\"]\n self.answerstates = [0 for i in range(len(self.answers))]\n self.frequencies = [5.0,9.0] \n self.divisions = 2\n self.fractionofdivision = 1 # show face for 1/4 of time\n self.periodsinmilli = [1000.0/freq/self.divisions for freq in self.frequencies]\n self.counts = [0 for i in range(len(self.answers))]\n \n self.timers = [QTimer() for i in range(len(self.answers))]\n for (index, timer) in enumerate(self.timers):\n \"\"\"timer.timeout.connect(partial(self.flash,index))\"\"\"\n \n \n self.singletimer = QTimer()\n self.singletimer.timeout.connect(self.singleflash)\n self.singletimerperiod = 0.005\n \n \n self.blockrects = []\n self.panelpadding = 2\n self.blockwidth = 150\n self.blockheight = self.blockwidth\n self.blockrounding = 7\n self.buttonspacing = 880\n self.yoffset = 0\n for (index,ans) in enumerate(self.answers):\n self.blockrects.append(QRectF(self.panelpadding + index*(self.blockwidth+self.buttonspacing), self.panelpadding + self.yoffset, self.blockwidth, self.blockheight)) \n self.blockpaths = []\n for blockrect in self.blockrects:\n blockpath = QPainterPath()\n blockpath.addRoundedRect(blockrect, self.blockrounding, self.blockrounding)\n self.blockpaths.append(blockpath)\n \n self.facepixmaps = []\n \n self.facepixmaps.append(QPixmap(os.path.abspath(os.path.join(script_path, '../images/faces/jennifer-lawrence.jpg'))).scaledToWidth(self.blockwidth, mode=Qt.SmoothTransformation))\n self.facepixmaps.append(QPixmap(os.path.abspath(os.path.join(script_path, '../images/faces/nicolas-cage.jpg'))).scaledToWidth(self.blockwidth, mode=Qt.SmoothTransformation))\n self.panelwidth = 2*self.panelpadding + self.buttonspacing*(len(self.answers)-1) + self.blockwidth*len(self.answers) \n self.panelheight = 2*self.panelpadding + self.blockheight + self.yoffset\n self.setFixedWidth(self.panelwidth)\n self.setFixedHeight(self.panelheight)\n self.mouseinteractionenabled = True\n \n def setFrequencies(self, frequencies):\n self.frequencies = frequencies \n self.periodsinmilli = [1000.0/freq/self.divisions for freq in self.frequencies]\n \n def singleflash(self): \n currenttime = time.time()\n dorepaint = False\n for (index,answer) in enumerate(self.answers):\n v = int(currenttime*2.0*self.frequencies[index])\n m = v % 2\n if self.answerstates[index] != m:\n self.answerstates[index] = m\n dorepaint = True\n if dorepaint:\n self.repaint()\n \n \n def flash(self, index):\n if self.counts[index] % self.divisions < self.fractionofdivision:\n self.answerstates[index] = 1 # show face\n else:\n self.answerstates[index] = 0 # don't show face\n self.counts[index] += 1\n self.repaint()\n \n def startBCIanimation(self):\n self.singletimer.start(self.singletimerperiod)\n \n for (index,period) in enumerate(self.periodsinmilli):\n self.counts[index] = 0\n self.timers[index].start(period)\n \n def stopBCIanimation(self):\n self.singletimer.stop()\n \n for (index,period) in enumerate(self.periodsinmilli):\n self.timers[index].stop()\n self.answerstates[index] = 0\n self.repaint()\n\n def paintEvent(self, event):\n qp = QPainter()\n qp.begin(self)\n self.redraw(event, qp)\n qp.end()\n \n def mouseMoveEvent(self, event): \n if self.mouseinteractionenabled:\n previous = self.mouseoveranswer\n self.pressedanswer = Answer.NONE\n self.mouseoveranswer = Answer.NONE\n for (index,blockrect) in enumerate(self.blockrects):\n if blockrect.contains(event.x(), event.y()):\n self.mouseoveranswer = index\n if previous != self.mouseoveranswer: \n self.repaint()\n \n def mousePressEvent(self, event):\n if self.mouseinteractionenabled:\n self.pressedanswer = self.mouseoveranswer\n self.repaint()\n \n def mouseReleaseEvent(self, event):\n if self.mouseinteractionenabled:\n if self.mouseoveranswer != Answer.NONE:\n self.pressedanswer = Answer.NONE\n self.answerclicked.emit(self.mouseoveranswer)\n self.pressedanswer = Answer.NONE\n self.repaint()\n else: \n #self.mouseinteractionenabled = not self.mouseinteractionenabled\n if not self.mouseinteractionenabled:\n self.startanimation()\n self.mouseoveranswer = Answer.NONE \n else:\n for (index,timer) in enumerate(self.timers):\n timer.stop() \n self.answerstates[index] = 0\n self.mouseoveranswer = Answer.NONE\n self.repaint()\n \n def answerClickedEvent(self, event):\n print(event)\n \n def resetSelected(self):\n for (index,blockrect) in enumerate(self.blockrects):\n self.answerstates[index] = 0\n self.repaint()\n \n def setSelected(self, selectedindex):\n for (index,blockrect) in enumerate(self.blockrects):\n self.answerstates[index] = 0\n self.answerstates[selectedindex] = 2\n self.repaint()\n \n \n \n def redraw(self, event, qp):\n #qp.setRenderHint(QPainter.TextAntialiasing)\n #qp.setRenderHint(QPainter.HighQualityAntialiasing)\n \n \n \n for (index,(answer,blockrect)) in enumerate(zip(self.answers, self.blockrects)):\n \n fillcolor = unselectedcolor\n qp.setFont(normalfont)\n if self.answerstates[index] == 1 or self.mouseoveranswer == index:\n fillcolor = mouseovercolor\n qp.setFont(boldfont)\n if self.pressedanswer == index:\n qp.setFont(boldfont)\n fillcolor = pressedcolor \n \n \n \n if self.answerstates[index] == 1 or self.mouseoveranswer == index:\n \n facerect = QRectF(0.0,0.0, self.blockwidth, self.blockheight)\n tempbrush = qp.brush()\n brush = QBrush(self.facepixmaps[index]);\n t = QTransform()\n t.translate(blockrect.x(), blockrect.y())\n brush.setTransform(t)\n qp.setBrush(brush);\n qp.drawRoundedRect(blockrect, self.blockrounding, self.blockrounding)\n qp.setBrush(tempbrush)\n #qp.fillPath(self.blockpaths[index], flashcolor)\n elif self.answerstates[index] == 2:\n qp.fillPath(self.blockpaths[index], selectedcolor)\n else: \n qp.fillPath(self.blockpaths[index], fillcolor)\n \n if self.pressedanswer == index:\n qp.setPen(pressedborderpen) \n else:\n qp.setPen(borderpen)\n qp.drawPath(self.blockpaths[index]) \n \n \n qp.setPen(fontpenblack)\n if self.answerstates[index] == 1:\n qp.setPen(fontpentransparent)\n else:\n qp.drawText(blockrect, Qt.AlignCenter, answer)\n\nclass QuestionAnswerWidget(QWidget):\n \n def __init__(self, parent):\n super().__init__()\n self.parent = parent\n\n self.inputmethod = InputMethod.SSVEP # InputMethod.MOUSE, InputMethod.SSVEP\n \n self.setWindowTitle('Unibrowser')\n self.setMouseTracking(True)\n \n self.vboxlayout = QVBoxLayout() \n self.vboxlayout.setAlignment(Qt.AlignCenter)\n \n \n self.warningtimesecs = 3.0 if RELEASE_VERSION else 1.0\n self.questiontimeoutmillis = 12000.0 if RELEASE_VERSION else 3000.0\n self.questiontimeoutmillis += self.warningtimesecs*1000.0\n self.timerintervalmillis = 1000.0\n self.questionno = 0\n self.questionframe = 0\n self.questiontimer = QTimer() \n self.questiontimer.timeout.connect(self.updatequestion)\n \n self.bcianimationtimeoutmillis = 6000.0 if RELEASE_VERSION else 2000.0\n self.choicetimeoutmillis = 4000.0 if RELEASE_VERSION else 2000.0\n \n labelfont = QFont()\n labelfont.setPointSize(16)\n #questionfont.setBold(True)\n #questionfont.setWeight(75)\n self.label = QLabel(\"\")\n self.label.setFont(labelfont)\n self.label.setAlignment(Qt.AlignCenter)\n self.vboxlayout.addWidget(self.label)\n \n self.answerpanel = AnswerPanelWidget(self.inputmethod)\n self.vboxlayout.addWidget(self.answerpanel) \n \n self.shownextquestion()\n \n self.setLayout(self.vboxlayout)\n \n \n def refreshquestiontext(self):\n if self.inputmethod == InputMethod.MOUSE:\n self.label.setText(self.parent.questiontext)\n elif self.inputmethod == InputMethod.SSVEP:\n elapsedtimequestionmillis = self.questionframe*self.timerintervalmillis\n elapsedtimequestionsecs = math.ceil((self.questiontimeoutmillis-elapsedtimequestionmillis)/1000.0)\n if elapsedtimequestionsecs > self.warningtimesecs:\n self.label.setText(\"%s\\n(%d seconds)\" % (self.parent.questiontext, elapsedtimequestionsecs-self.warningtimesecs))\n else:\n self.label.setText(\"%s\\nNow focus on your best guess.\" % self.parent.questiontext)\n return elapsedtimequestionmillis\n \n \n def shownextquestion(self):\n self.parent.nextquestion()\n self.answerpanel.resetSelected()\n self.refreshquestiontext()\n if self.inputmethod == InputMethod.SSVEP:\n self.questiontimer.start(self.timerintervalmillis)\n \n def updatequestion(self):\n self.questionframe += 1 \n elapsedtimequestionmillis = self.refreshquestiontext()\n if elapsedtimequestionmillis >= self.questiontimeoutmillis: \n self.questiontimer.stop()\n self.questionframe = 0\n self.startBCI()\n QTimer.singleShot(self.bcianimationtimeoutmillis, self.stopBCI)\n \n def startBCI(self):\n self.answerpanel.startBCIanimation()\n \n def stopBCI(self):\n answervec = self.parent.model.answerdict[('Italy',self.parent.qkey)]\n #simulatedanswer = samplediscrete(answervec)\n simulatedanswer = np.argmax(answervec)\n print(self.parent.model.questions[self.parent.qkey])\n print(\"%s, choice %d\" % (answervec,simulatedanswer))\n self.answerpanel.stopBCIanimation()\n self.answerpanel.setSelected(simulatedanswer)\n QTimer.singleShot(self.choicetimeoutmillis, partial(self.answerpanel.answerclicked.emit, simulatedanswer))\n \n\nif __name__ == '__main__':\n \n app = QApplication(sys.argv)\n ex = QuestionAnswerWidget()\n sys.exit(app.exec_())","sub_path":"src/questionanswerwidget_backup.py","file_name":"questionanswerwidget_backup.py","file_ext":"py","file_size_in_byte":13592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"50729692","text":"# coding=utf-8\n# Created by 智捷关东升\n# 本书网站:www.zhijieketang.com/group/8\n# 智捷课堂在线课堂:www.zhijieketang.com\n# 智捷课堂微信公共号:zhijieketang\n# 邮箱:eorient@sina.com\n# 读者服务QQ群:628808216\n# 【配套电子书】网址:\n# 百度阅读:\n# https://yuedu.baidu.com/ebook/5823871e59fafab069dc5022aaea998fcc2240fc\n# 代码文件:chapter26/LostRoutes/com/zhijieketang/scene/help_scene.py\n\n\"\"\"帮助场景\"\"\"\nimport logging\n\nimport cocos.layer\nimport cocos.scene\nimport cocos.scenes\nimport cocos.sprite\n\nfrom com.zhijieketang.utility import tools\n\n# 资源图片路径\nfrom com.zhijieketang.utility.tools import add_to_scene\n\nRES_PATH = 'resources/image/help/'\nlogger = logging.getLogger(__name__)\n\n\nclass HelpLayer(cocos.layer.Layer):\n\n def __init__(self):\n super(HelpLayer, self).__init__()\n\n logger.info('初始化帮助层')\n\n # # 获得窗口的宽度和高度\n # s_width, s_height = cocos.director.director.get_window_size()\n # # 创建背景精灵\n # background = cocos.sprite.Sprite(RES_PATH + 'bg.png')\n # background.position = s_width // 2, s_height // 2\n # # 添加背景精灵到HelloWorld层\n # self.add(background, 0)\n add_to_scene(self, RES_PATH + 'bg.png')\n\n\nclass MainMenu(cocos.menu.Menu):\n\n def __init__(self):\n super(MainMenu, self).__init__()\n\n logger.info('初始化MainMenu')\n\n # 菜单项初始化设置\n self.font_item['font_size'] = 60\n self.font_item['color'] = (180, 200, 255, 255)\n self.font_item_selected['color'] = (255, 255, 255, 255)\n self.font_item_selected['font_size'] = 60\n\n start_item = cocos.menu.ImageMenuItem(RES_PATH + 'button-ok.png',\n self.on_item_callback)\n\n self.create_menu([start_item],\n layout_strategy=cocos.menu.fixedPositionMenuLayout(\n [(210, 50)]))\n\n def on_item_callback(self):\n cocos.director.director.pop()\n # 播放音效\n tools.playeffect('Blip.wav')\n\n\n# 创建场景函数\ndef create_scene():\n # 创建场景\n scene = cocos.scene.Scene(HelpLayer())\n # 添加主菜单\n scene.add(MainMenu())\n return scene\n","sub_path":"LostRoutes/com/zhijieketang/scene/help_scene.py","file_name":"help_scene.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"150112338","text":"# Hash Map\n# https://github.com/joeyajames/Python/blob/master/\nclass HashMap:\n\tdef __init__(self):\n\t\tself.size = 6\n\t\tself.map = [None] * self.size\n\t\t\n\tdef _get_hash(self, key):\n\t\thash = 0\n\t\tfor char in str(key):\n\t\t\thash += ord(char)\n\t\treturn hash % self.size\n\t\t\n\tdef add(self, key, value):\n\t\tkey_hash = self._get_hash(key)\n\t\tkey_value = [key, value]\n\t\t\n\t\tif self.map[key_hash] is None:\n\t\t\tself.map[key_hash] = list([key_value])\n\t\t\treturn True\n\t\telse:\n\t\t\tfor pair in self.map[key_hash]:\n\t\t\t\tif pair[0] == key:\n\t\t\t\t\tpair[1] = value\n\t\t\t\t\treturn True\n\t\t\tself.map[key_hash].append(key_value)\n\t\t\treturn True\n\t\t\t\n\tdef get(self, key):\n\t\tkey_hash = self._get_hash(key)\n\t\tif self.map[key_hash] is not None:\n\t\t\tfor pair in self.map[key_hash]:\n\t\t\t\tif pair[0] == key:\n\t\t\t\t\treturn pair[1]\n\t\treturn None\n\t\t\t\n\tdef delete(self, key):\n\t\tkey_hash = self._get_hash(key)\n\t\t\n\t\tif self.map[key_hash] is None:\n\t\t\treturn False\n\t\tfor i in range (0, len(self.map[key_hash])):\n\t\t\tif self.map[key_hash][i][0] == key:\n\t\t\t\tself.map[key_hash].pop(i)\n\t\t\t\treturn True\n\t\treturn False\n\t\t\t\n\tdef print(self):\n\t\tprint('---PHONEBOOK----')\n\t\tfor item in self.map:\n\t\t\tif item is not None:\n\t\t\t\tprint(str(item))\n\t\t\t\nh = HashMap()\nh.add('Bob', '567-8888')\nh.add('Ming', '293-6753')\nh.add('Ming', '333-8233')\nh.add('Ankit', '293-8625')\nh.add('Aditya', '852-6551')\nh.add('Alicia', '632-4123')\nh.add('Mike', '567-2188')\nh.add('Aditya', '777-8888')\nh.print()\t\t\nh.delete('Bob')\nh.print()\nprint('Ming: ' + h.get('Ming'))\n\n##https://codereview.stackexchange.com/questions/183112/hashmap-implementation-in-python\n## Here's my implementation of a bare-bones HashMap in Python. Expected behavior, it returns None if a key is missing, When a key is inserted the second time it just overwrites the first value.\nclass HashMap:\n def __init__(self):\n self.store = [None for _ in range(16)]\n self.size = 0\n\n def get(self, key):\n key_hash = self._hash(key)\n index = self._position(key_hash)\n if not self.store[index]:\n return None\n else:\n list_at_index = self.store[index]\n for i in list_at_index:\n if i.key == key:\n return i.value\n return None\n\n def put(self, key, value):\n p = Node(key, value)\n key_hash = self._hash(key)\n index = self._position(key_hash)\n if not self.store[index]:\n self.store[index] = [p]\n self.size += 1\n else:\n list_at_index = self.store[index]\n if p not in list_at_index:\n list_at_index.append(p)\n self.size += 1\n else:\n for i in list_at_index:\n if i == p:\n i.value = value\n break\n\n def __len__(self):\n return self.size\n\n def _hash(self, key):\n if isinstance(key, int):\n return key\n result = 5381\n for char in key:\n result = 33 * result + ord(char)\n return result\n\n def _position(self, key_hash):\n return key_hash % 15\n\n\nclass Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n def __eq__(self, other):\n return self.key == other.key\n\n\nif __name__ == '__main__':\n hashmap = HashMap()\n hashmap.put(2, 12)\n hashmap.put('asd', 13)\n hashmap.put(2, 11)\n print(hashmap.get(2))\n print(hashmap.get('asd'))\n print(hashmap.get('ade'))\n","sub_path":"dataStructures-Algorithms/hashmap.py","file_name":"hashmap.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"143020428","text":"import numpy as np\nfrom libs.stocks.queues.queue.queue import Queue\nimport apps.ai.config as config\n\ndef pre_process(queue_obj, split):\n # split train and test data\n\n instance = isinstance(queue_obj, Queue)\n\n if instance: # is Queue\n train = np.array(list(queue_obj._norm_queue)[:split])\n test = np.array(list(queue_obj._norm_queue)[split:])\n\n else: # is Candle\n dataset = queue_obj.get_vstacked_queues() #returned ndarray\n train = dataset[:, :split]\n test = dataset[:, split:]\n\n trainX, trainY = load_dataset(train, split, instance)\n testX, testY = load_dataset(test, split, instance)\n\n return (trainX, trainY, testX, testY)\n\n\ndef load_dataset(dataset, dataset_window, instance):\n first_values = int(dataset_window * 0.7)\n last_values = -int(dataset_window * 0.3)\n if instance:\n dataX = dataset[:first_values]\n dataY = dataset[last_values:]\n else:\n dataX = dataset[:, :first_values]\n dataY = dataset[:, last_values:]\n\n return dataX, dataY\n\ndef stack_dataset(trainX_s,testX_s,trainY_s,testY_s,trainX,testX,trainY,testY,time_scale):\n if trainX_s is None:\n trainX_s, testX_s, = trainX, testX\n\n #MANY2ONE\n trainY_s, testY_s = trainY.T.reshape(-1), testY.T.reshape(-1)\n\n else: # stacking stocks\n if time_scale == '1s':\n trainX_s = np.vstack((trainX_s, trainX))\n testX_s = np.vstack((testX_s, testX))\n\n else: # 1m,2m,5m...\n trainX_s = np.stack((trainX_s, trainX), axis=1).T\n testX_s = np.stack((testX_s, testX), axis=1).T\n\n # only output layer changes if prediction_type=MANY2MANY\n if config.prediction_type == config.MANY2MANY:\n if time_scale == '1s':\n trainY_s = np.hstack((trainY_s, trainY))\n testY_s = np.hstack((testY_s, testY))\n else:\n trainY_s, testY_s = np.hstack((trainY_s, trainY.T.reshape(-1))), np.hstack(\n (testY_s, testY.T.reshape(-1)))\n\n\n return trainX_s,testX_s,trainY_s,testY_s","sub_path":"libs/dataset/perceptron/load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"130831972","text":"from turtle import Turtle, Screen\nimport random\n\n\ndef run_game():\n score = 0\n is_race_on = True\n screen.clear()\n user_bet = screen.textinput(title=\"Make your bet!\",\n prompt=\"Which turtle will win the race? Enter a colour: \").lower()\n colours = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\n if user_bet not in colours:\n screen.textinput(title=\"Make your bet!\", prompt=\"Please choose a colour!!\").lower()\n\n all_turtles = []\n\n for i in range(6):\n new_turtle = Turtle(shape=\"turtle\")\n new_turtle.penup()\n new_turtle.color(colours[i])\n new_turtle.goto(x = -240, y =- 100 + (i * 50))\n all_turtles.append(new_turtle)\n\n if user_bet:\n is_race_on = True\n\n while is_race_on:\n for turtle in all_turtles:\n random_distance = random.randint(0, 10)\n turtle.forward(random_distance)\n if turtle.xcor() > 230:\n is_race_on = False\n winning_colour = turtle.pencolor()\n if winning_colour == user_bet:\n score += 1\n print(f\"You win! The {winning_colour} turtle won. \\n Your score is {score}\")\n else:\n print(f\"You lose! The {winning_colour} turtle won! \\n Your score is {score}\")\n is_race_on = False\n\n\n\n\n\nscreen = Screen()\nscreen.setup(width = 500, height = 400)\n\ngame_running = True\nwhile game_running:\n start_game = screen.textinput(title= \"Start game?\", prompt=\"Yes or no:\").lower()\n if start_game == \"yes\":\n run_game()\n else:\n game_running = False\n screen.bye()\n\n\n\n\n\n","sub_path":"Day19/turtle_race.py","file_name":"turtle_race.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441641608","text":"from PyTrinamicMicro.platforms.motionpy.modules.hc_sr04_multi import hc_sr04_multi\nfrom PyTrinamicMicro.platforms.motionpy.modules.MCP23S08 import MCP23S08\nfrom PyTrinamic.modules.TMCM0960.TMCM0960 import TMCM0960\nimport logging\n\nclass linear_distance(object):\n\n def __init__(self, sensor, sensor_index, module, length=1000):\n self.__sensor = sensor\n self.__sensor_index = sensor_index\n self.module = module\n self.__length = 1000\n self.bounds = []\n\n def homing_direct(self, velocity=10000, margin=0.2, margin_hyst=0.5):\n self.bounds = []\n self.module.rotate(0, velocity)\n distance = self.__sensor.distance(self.__sensor_index)\n while((margin * self.__length) < distance < ((1.0 - margin) * self.__length)):\n distance = self.__sensor.distance(self.__sensor_index)\n print(distance)\n self.module.stop(0)\n position = self.module.getActualPosition(0)\n self.bounds.append((distance, position))\n self.module.rotate(0, -velocity)\n if(((margin - (margin * margin_hyst)) * self.__length) < distance < ((margin + (margin * margin_hyst)) * self.__length)): # lower\n while(distance < ((1.0 - margin) * self.__length)):\n distance = self.__sensor.distance(self.__sensor_index)\n print(distance)\n else: # higher\n while((margin * self.__length) < distance):\n distance = self.__sensor.distance(self.__sensor_index)\n print(distance)\n self.module.stop(0)\n position = self.module.getActualPosition(0)\n self.bounds.append((distance, position))\n self.bounds.sort(key=lambda x: x[0])\n\n def homing(self, homing_status, length=1000, velocity=10000, acceleration=1000, margin=0.2, margin_hyst=0.5):\n if(homing_status == TMCM0960.ENUMs.HOMING_STATUS_INIT):\n self.bounds = []\n #print(velocity)\n self.module.setMaxAcceleration(0, acceleration)\n self.module.rotate(0, velocity)\n homing_status = TMCM0960.ENUMs.HOMING_STATUS_FIRST\n elif(homing_status == TMCM0960.ENUMs.HOMING_STATUS_FIRST):\n distance = self.__sensor.distance(self.__sensor_index)\n if(((margin * length) > distance) or (distance > ((1.0 - margin) * length))):\n self.bounds.append((distance, self.module.getActualPosition(0)))\n self.module.rotate(0, -velocity)\n homing_status = TMCM0960.ENUMs.HOMING_STATUS_SECOND\n elif(homing_status == TMCM0960.ENUMs.HOMING_STATUS_SECOND):\n distance = self.__sensor.distance(self.__sensor_index)\n #print(\"distance: {}, bounds[0][0]: {}, margin: {}, hyst: {}\".format(distance, self.bounds[0][0], margin, margin_hyst))\n done = False\n if(self.bounds[0][0] < ((margin + (margin * margin_hyst)) * length)): # lower\n done = (distance > ((1.0 - margin) * length))\n else: # higher\n done = ((margin * length) > distance)\n if(done):\n self.bounds.append((distance, self.module.getActualPosition(0)))\n self.module.stop(0)\n self.bounds.sort(key=lambda x: x[0])\n homing_status = TMCM0960.ENUMs.HOMING_STATUS_DONE\n return homing_status\n\n def position_step(self, position=None, velocity=10000, acceleration=1000):\n if(position is None):\n return self.module.getActualPosition(0)\n else:\n self.module.setMaxAcceleration(0, acceleration)\n self.module.setMaxVelocity(0, velocity)\n self.module.moveTo(0, position)\n\n def position_absolute(self, position=None, velocity=10000, acceleration=1000):\n if(position is None):\n return self.__sensor.distance(self.__sensor_index)\n else:\n self.position_step(int((((position - self.bounds[0][0]) * (self.bounds[1][1] - self.bounds[0][1])) / (self.bounds[1][0] - self.bounds[0][0])) + self.bounds[0][1]),\n velocity, acceleration)\n\n def position_relative(self, position=None, velocity=None, acceleration=None):\n if(position is None):\n return ((self.position_absolute() - self.bounds[0][0]) / (self.bounds[1][0] - self.bounds[0][0]))\n else:\n self.position_step(int(self.bounds[0][1] + ((self.bounds[1][1] - self.bounds[0][1]) * position)),\n velocity, acceleration)\n","sub_path":"PyTrinamicMicro/platforms/motionpy/modules/linear_distance.py","file_name":"linear_distance.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282854821","text":"import pandas as pd\nimport math\nimport random\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport os\nfrom backend.settings import BASE_DIR\n\ndepthLimit = 0\nexampleLimit = 0\nnumFeature = 0\n\n\ndef getX(data):\n \n X = []\n \n for i in range(0, len(data[\"gender\"])):\n temp = []\n for key in data:\n temp.append(data[key][i])\n X.append(temp)\n \n return X\n\n\ndef getFrac(data):\n \n temp = []\n X = []\n for key in data:\n temp.append(list(data[key]))\n\n \n for i in range(0, len(temp[0])):\n tmp = []\n for j in range(0, len(temp)):\n tmp.append(temp[j][i])\n X.append(tmp)\n\n return X\n\n\ndef calcGini(leftB, rightB):\n\n# time.sleep(1)\n lenL = float(len(leftB))\n lenR = float(len(rightB))\n \n totalN = lenL + lenR\n giniVal = 0\n if(lenL > 0):\n temp = 0\n dicOut = {0:0, 1:0}\n \n for r in leftB:\n dicOut[r[-1]] += 1\n \n temp += pow((dicOut[0]/lenL), 2)\n temp += pow((dicOut[1]/lenL), 2)\n\n giniVal += (1.0 - temp) * (lenL / totalN)\n \n if(lenR > 0):\n\n temp = 0\n dicOut = {0:0, 1:0}\n \n for r in rightB:\n dicOut[r[-1]] += 1\n \n temp += pow((dicOut[0]/lenR),2)\n temp += pow((dicOut[1]/lenR),2)\n\n giniVal += (1.0 - temp) * (lenR / totalN)\n \n return giniVal\n\n\ndef subSplit(data):\n \n# giniDic = {}\n iterN = len(data[0]) - 1\n optimalB = {'L':0, 'R':0, \"idx\":0, \"val\":0}\n optimalGini = math.inf\n \n \n for i in range(0, iterN):\n\n# giniDic.update({i:[-1,-1]})\n giniDic = {i:[-1,-1]}\n for d in data:\n if(giniDic[i][d[i]] == -1):\n \n leftB = []\n rightB = []\n \n for s in data:\n if s[i] < d[i]:\n leftB.append(s)\n else:\n rightB.append(s)\n \n gini = calcGini(leftB, rightB)\n giniDic[i][d[i]] = gini\n \n if(giniDic[i][d[i]] < optimalGini):\n optimalGini = giniDic[i][d[i]]\n optimalB['L'] = leftB\n optimalB['R'] = rightB\n optimalB[\"idx\"] = i\n optimalB[\"val\"] = d[i]\n \n if((giniDic[i][0] != -1) and (giniDic[i][1] != -1)):\n break\n \n return optimalB\n\n\ndef stopGrow(branch):\n \n dicOut = {0:0, 1:0}\n \n for r in branch:\n dicOut[r[-1]] += 1\n \n if(dicOut[0] >= dicOut[1]):\n return 0\n\n return 1\n\ndef subSplitRF(data):\n# print(\"split!\")\n optimalB = {'L':0, 'R':0, \"idx\":0, \"val\":0}\n optimalGini = math.inf\n \n selected = []\n \n while(1):\n \n if(len(selected) > numFeature):\n break\n \n i = random.randint(0, (len(data[0]) - 2))\n if i not in selected:\n selected.append(i)\n else:\n continue\n \n giniDic = {i:[-1,-1]}\n for d in data:\n if(giniDic[i][d[i]] == -1):\n \n leftB = []\n rightB = []\n \n for s in data:\n if s[i] < d[i]:\n leftB.append(s)\n else:\n rightB.append(s)\n \n gini = calcGini(leftB, rightB)\n giniDic[i][d[i]] = gini\n \n if(giniDic[i][d[i]] < optimalGini):\n optimalGini = giniDic[i][d[i]]\n optimalB['L'] = leftB\n optimalB['R'] = rightB\n optimalB[\"idx\"] = i\n optimalB[\"val\"] = d[i]\n \n if((giniDic[i][0] != -1) and (giniDic[i][1] != -1)):\n break\n \n return optimalB\n\n\ndef getSplitRF(node, depth = 0):\n \n left = node['L']\n right = node['R']\n\n stopFlag = 0\n\n if(depth >= depthLimit):\n node[\"LBranch\"] = stopGrow(left)\n node[\"RBranch\"] = stopGrow(right)\n stopFlag += 1\n elif((len(left) == 0) or(len(right) == 0)):\n stopResult = stopGrow(left + right)\n node[\"LBranch\"] = stopResult\n node[\"RBranch\"] = stopResult\n stopFlag += 1\n \n if(stopFlag == 0):\n\n if len(left) <= exampleLimit:\n node[\"LBranch\"] = stopGrow(left)\n else:\n node[\"LBranch\"] = subSplitRF(left)\n getSplitRF(node[\"LBranch\"], depth+1)\n\n if len(right) <= exampleLimit:\n node[\"RBranch\"] = stopGrow(right)\n else:\n node[\"RBranch\"] = subSplitRF(right)\n getSplitRF(node[\"RBranch\"], depth+1)\n\n\ndef getSplit(node, depth = 0):\n \n left = node['L']\n right = node['R']\n\n stopFlag = 0\n\n if(depth >= depthLimit):\n node[\"LBranch\"] = stopGrow(left)\n node[\"RBranch\"] = stopGrow(right)\n stopFlag += 1\n elif((len(left) == 0) or(len(right) == 0)):\n stopResult = stopGrow(left + right)\n node[\"LBranch\"] = stopResult\n node[\"RBranch\"] = stopResult\n stopFlag += 1\n \n if(stopFlag == 0):\n\n if len(left) <= exampleLimit:\n node[\"LBranch\"] = stopGrow(left)\n else:\n node[\"LBranch\"] = subSplit(left)\n getSplit(node[\"LBranch\"], depth+1)\n\n if len(right) <= exampleLimit:\n node[\"RBranch\"] = stopGrow(right)\n else:\n node[\"RBranch\"] = subSplit(right)\n getSplit(node[\"RBranch\"], depth+1)\n\n\n\n\ndef predict(node, data):\n \n while(1):\n if(data[node[\"idx\"]] < node[\"val\"]):\n if isinstance(node[\"LBranch\"], int):\n return node[\"LBranch\"]\n else:\n node = node[\"LBranch\"]\n else:\n if isinstance(node[\"RBranch\"], int):\n return node[\"RBranch\"]\n else:\n node = node[\"RBranch\"]\n\n\ndef getAccDT(dataSet, tree):\n \n data = dataSet[0]\n ans = dataSet[1]\n \n for x in data:\n x[-1] = None\n \n correct = 0\n for i in range(0,len(data)):\n# print(data[i])\n pred = predict(tree, data[i])\n# print(pred)\n if(pred == ans[i]):\n correct += 1\n\n# print(\"@@@@@@\")\n return float(correct)/float(len(ans))\n\n\ndef getAcc(dataSet, trees):\n \n data = dataSet[0]\n ans = dataSet[1]\n \n for x in data:\n x[-1] = None\n \n correct = 0\n for i in range(0, len(data)):\n \n dicOut = {0:0, 1:0}\n \n for t in trees:\n dicOut[predict(t, data[i])] += 1\n \n pred = -1\n# print(dicOut[0], \" --- \", dicOut[1])\n if(dicOut[0] > dicOut[1]):\n pred = 0\n else:\n pred = 1\n \n if(pred == ans[i]):\n correct += 1\n\n# print(\"@@@@@@\")\n return float(correct)/float(len(ans))\n\n\ndef runDT(trainData, testPath):\n \n depthL = 8\n exampleL = 50\n \n \n global depthLimit\n global exampleLimit\n \n depthLimit = depthL\n exampleLimit = exampleL\n \n # Beginning of Training \n train = pd.read_csv(trainData)\n del train[\"Unnamed: 0\"]\n Ytrain = train[\"decision\"]\n# del train[\"decision\"]\n Xtrain = getX(train)\n test = pd.read_csv(testPath)\n del test[\"Unnamed: 0\"]\n Ytest = test[\"decision\"]\n# del test[\"decision\"]\n Xtest = getX(test)\n \n train = None\n test = None\n \n trainSet = [Xtrain, Ytrain]\n testSet = [Xtest, Ytest]\n \n# print(len(Xtest[1]))\n \n print(\"DT training!\")\n d_Tree = subSplit(Xtrain)\n getSplit(d_Tree)\n \n trainAcc = getAccDT(trainSet, d_Tree)\n testAcc = getAccDT(testSet, d_Tree)\n \n \n print(\"---------------------------\")\n print(\"Training Accuracy DT:\", round(trainAcc, 2))\n print(\"Testing Accuracy DT:\", round(testAcc, 2))\n \n# End of Testing \n\n\n\ndef runBT(trainData, testPath):\n \n depthL = 8\n exampleL = 50\n numTree = 30\n\n global depthLimit\n global exampleLimit\n \n depthLimit = depthL\n exampleLimit = exampleL\n \n \n # Beginning of Training \n train = pd.read_csv(trainData)\n del train[\"Unnamed: 0\"]\n Ytrain = train[\"decision\"]\n# del train[\"decision\"]\n Xtrain = getX(train)\n \n test = pd.read_csv(testPath)\n del test[\"Unnamed: 0\"]\n Ytest = test[\"decision\"]\n# del test[\"decision\"]\n Xtest = getX(test)\n \n \n trainSet = [Xtrain, Ytrain]\n testSet = [Xtest, Ytest]\n \n dfList = []\n for i in range(0, numTree):\n dfList.append(train.sample(frac = 1, replace = True))\n \n dataSets = []\n for i in range(0, numTree):\n dataSets.append(getFrac(dfList[i]))\n \n dfList = None\n b_trees = []\n \n \n print(\"BT training!\")\n for i in range(0, numTree):\n# print(\"@@@@@@@ \", i)\n tree = subSplit(dataSets[i])\n getSplit(tree)\n b_trees.append(tree)\n \n\n trainAcc = getAcc(trainSet, b_trees)\n testAcc = getAcc(testSet, b_trees)\n \n print(\"---------------------------\")\n print(\"Training Accuracy DT:\", round(trainAcc, 2))\n print(\"Testing Accuracy DT:\", round(testAcc, 2))\n\n\ndef runRF(trainData, testPath, depthLim, exampleLim, nTree):\n \n depthL = depthLim\n exampleL = exampleLim\n numTree = nTree\n \n \n global depthLimit\n global exampleLimit\n global numFeature\n \n depthLimit = depthL\n exampleLimit = exampleL\n \n \n# Beginning of Training \n train = pd.read_csv(trainData)\n del train[\"Unnamed: 0\"]\n Ytrain = train[\"decision\"]\n# del train[\"decision\"]\n Xtrain = getX(train)\n \n test = pd.read_csv(testPath)\n del test[\"Unnamed: 0\"]\n Ytest = test[\"decision\"]\n# del test[\"decision\"]\n Xtest = getX(test)\n \n \n numFeature = int(math.sqrt(len(Xtrain[0]) - 1))\n \n trainSet = [Xtrain, Ytrain]\n testSet = [Xtest, Ytest]\n \n dfList = []\n for i in range(0, numTree):\n dfList.append(train.sample(frac = 1, replace = True))\n \n dataSets = []\n for i in range(0, numTree):\n dataSets.append(getFrac(dfList[i]))\n\n dfList = None\n rf_trees = []\n \n print(\"RF training!\")\n for i in range(numTree):\n# print(\"@@@@@@@@@@@ \", i)\n tree = subSplitRF(dataSets[i])\n getSplitRF(tree)\n rf_trees.append(tree)\n \n \n trainAcc = getAcc(trainSet, rf_trees)\n testAcc = getAcc(testSet, rf_trees)\n \n \n print(\"---------------------------\")\n print(\"Training Accuracy RF:\", round(trainAcc, 2))\n print(\"Testing Accuracy DT:\", round(testAcc, 2))\n\n plt.subplot(211)\n plt.plot([25, 50, 75, 100], [float(25*round(trainAcc, 2)), float(50*round(trainAcc, 2)), float(75*round(trainAcc, 2)), float(100*round(trainAcc, 2))])\n plt.ylabel('Testing Accuracy')\n plt.subplot(212)\n plt.plot([25, 50, 75, 100], [float(25*round(testAcc, 2)), float(50*round(testAcc, 2)), float(75*round(testAcc, 2)), float(100*round(testAcc, 2))])\n plt.ylabel('Testing Accuracy')\n plt.xlabel('Number Of Inputs')\n # plt.show()\n save_path = os.path.join(BASE_DIR, 'backend/randomForest_result.png') \n plt.savefig(save_path)\n\n\nif __name__ == '__main__':\n \n \n trainingDataFilename = \"trainingSetT.csv\"\n testDataFilename = \"testSetT.csv\"\n modelIdx = 3\n\n# trainingDataFilename = sys.argv[1]\n# testDataFilename = sys.argv[2]\n# modelIdx = int(sys.argv[3])\n\n runRF(trainingDataFilename, testDataFilename)\n","sub_path":"backend/backend/randomForest.py","file_name":"randomForest.py","file_ext":"py","file_size_in_byte":11562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147542973","text":"import curses\nimport time\n\nscreen = curses.initscr()\nscreen.border()\nscreen.nodelay(1)\nscreen.keypad(1)\n\ndirection =0 \ngame_over =False \nhead=[1,1]\n\ndef processInput(direction):\n \"\"\"This function processes any user input\"\"\"\n userinput = screen.getch()\n if userinput == curses.KEY_UP:\n direction = 3\n elif userinput == curses.KEY_DOWN:\n direction = 2\n elif userinput == curses.KEY_LEFT:\n direction = 1\n elif userinput == curses.KEY_RIGHT:\n direction = 0\n return direction\n \ndef update(direction):\n \"\"\"This function updates the state of the game. It advances the game one step. Performs AI and Physics\"\"\" \n if direction == 3:\n head[0] -=1\n elif direction == 2:\n head[0] += 1\n elif direction == 1:\n head[1] -= 1\n elif direction == 0:\n head[1] += 1\n \n screen.refresh()\n time.sleep(0.1)\n \ndef collison(direction):\n \"\"\"This function is used to detect a collision\"\"\"\n if direction == 3 and screen.inch(head[0]-1,head[1]) !=ord(' '):\n return True\n elif direction == 2 and screen.inch(head[0]+1,head[1]) !=ord(' '):\n return True\n elif direction == 1 and screen.inch(head[0],head[1]-1) !=ord(' '):\n return True\n elif direction == 0 and screen.inch(head[0],head[1]+1) !=ord(' '):\n return True \n else:\n return False\n \ndef display():\n \"\"\"This function draws all of the stuff in the game\"\"\"\n screen.addch(head[0],head[1],'x')\n\nwhile game_over == False:\n direction = processInput(direction)\n update(direction)\n display()\n game_over = collison(direction)\n \ncurses.endwin()\n \n\n \n\n","sub_path":"Projects/project_2/snake_4b.py","file_name":"snake_4b.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"122341792","text":"import requests\n\nbaseUrl = None\ncache = {}\n\ndef init(ip, port):\n global baseUrl\n\n url = 'http://' + ip + ':' + port\n result = requests.get(url, timeout=2)\n if result.status_code != requests.codes.ok:\n raise Exception('Invalid configuration for sevice registry server!')\n\ndef register(name, port):\n if baseUrl is None:\n raise Exception('Service registry client not initialized!')\n\n url = baseUrl + '/register/' + name\n try:\n result = requests.post(url, params={'port': port}, timeout=2)\n except Exception:\n raise Exception('Failed to register due to web request issue!')\n\n if result.status_code != requests.codes.ok:\n msg = result.json()['msg']\n raise Exception(msg)\n\ndef unregister(name, port):\n if baseUrl is None:\n raise Exception('Service registry client not initialized')\n\n url = baseUrl + '/unregister/' + name\n try:\n result = requests.post(url, params={'port': port}, timeout=2)\n except Exception:\n raise Exception('Failed to unregister due to web request issue!')\n\n if result.status_code != requests.codes.ok:\n msg = result.json()['msg']\n raise Exception(msg)\n\ndef lookup(name):\n if baseUrl is None:\n raise Exception('Service registry client not initialized!')\n\n if name in cache:\n services = cache[name]\n return services\n\n url = baseUrl + '/lookup/' + name\n try:\n result = requests.get(url, timeout=2)\n except Exception:\n raise Exception('Failed to lookup due to web request issue!')\n\n jsonBody = result.json()\n if result.status_code != requests.codes.ok:\n msg = jsonBody['msg']\n raise Exception(msg)\n\n services = jsonBody['services']\n cache[name] = services\n return services\n","sub_path":"client-libs/python/serviceregistryclient.py","file_name":"serviceregistryclient.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"287362798","text":"import os\nfrom pathlib import Path\n\nimport pytest\n\nimport copier\n\nfrom .helpers import DATA, PROJECT_TEMPLATE, assert_file, filecmp, render\n\n\ndef test_project_not_found(dst):\n with pytest.raises(ValueError):\n copier.copy(\"foobar\", dst)\n\n with pytest.raises(ValueError):\n copier.copy(__file__, dst)\n\n\ndef test_copy(dst):\n render(dst)\n\n generated = (dst / \"pyproject.toml\").read_text()\n control = (Path(__file__).parent / \"reference_files/pyproject.toml\").read_text()\n assert generated == control\n\n assert_file(dst, \"doc\", \"mañana.txt\")\n assert_file(dst, \"doc\", \"images\", \"nslogo.gif\")\n\n p1 = str(dst / \"awesome\" / \"hello.txt\")\n p2 = str(PROJECT_TEMPLATE / \"[[ myvar ]]\" / \"hello.txt\")\n assert filecmp.cmp(p1, p2)\n\n with open(dst / \"README.txt\") as readme:\n assert readme.read() == \"This is the README for Copier.\\n\"\n\n p1 = str(dst / \"awesome.txt\")\n p2 = str(PROJECT_TEMPLATE / \"[[ myvar ]].txt\")\n assert filecmp.cmp(p1, p2)\n\n assert not os.path.exists(dst / \"[% if not py3 %]py2_only.py[% endif %]\")\n assert not os.path.exists(dst / \"[% if py3 %]py3_only.py[% endif %]\")\n assert not os.path.exists(dst / \"py2_only.py\")\n assert os.path.exists(dst / \"py3_only.py\")\n assert not os.path.exists(\n dst / \"[% if not py3 %]py2_folder[% endif %]\" / \"thing.py\"\n )\n assert not os.path.exists(dst / \"[% if py3 %]py3_folder[% endif %]\" / \"thing.py\")\n assert not os.path.exists(dst / \"py2_folder\" / \"thing.py\")\n assert os.path.exists(dst / \"py3_folder\" / \"thing.py\")\n\n\ndef test_copy_repo(dst):\n copier.copy(\"gh:jpscaletti/siht.git\", dst, vcs_ref=\"HEAD\", quiet=True)\n assert (dst / \"setup.py\").exists()\n\n\ndef test_default_exclude(dst):\n render(dst)\n assert not (dst / \".svn\").exists()\n\n\ndef test_include_file(dst):\n render(dst, exclude=[\"!.svn\"])\n assert_file(dst, \".svn\")\n\n\ndef test_include_pattern(dst):\n render(dst, exclude=[\"!.*\"])\n assert (dst / \".svn\").exists()\n\n\ndef test_exclude_file(dst):\n render(dst, exclude=[\"mañana.txt\"])\n assert not (dst / \"doc\" / \"mañana.txt\").exists()\n assert (dst / \"doc\" / \"mañana.txt\").exists()\n assert (dst / \"doc\" / \"manana.txt\").exists()\n\n\ndef test_skip_if_exists(dst):\n copier.copy(\"tests/demo_skip_dst\", dst)\n copier.copy(\n \"tests/demo_skip_src\",\n dst,\n skip_if_exists=[\"b.noeof.txt\", \"meh/c.noeof.txt\"],\n force=True,\n )\n\n assert (dst / \"a.noeof.txt\").read_text() == \"OVERWRITTEN\"\n assert (dst / \"b.noeof.txt\").read_text() == \"SKIPPED\"\n assert (dst / \"meh\" / \"c.noeof.txt\").read_text() == \"SKIPPED\"\n\n\ndef test_skip_if_exists_rendered_patterns(dst):\n copier.copy(\"tests/demo_skip_dst\", dst)\n copier.copy(\n \"tests/demo_skip_src\",\n dst,\n data={\"name\": \"meh\"},\n skip_if_exists=[\"[[ name ]]/c.noeof.txt\"],\n force=True,\n )\n assert (dst / \"a.noeof.txt\").read_text() == \"OVERWRITTEN\"\n assert (dst / \"b.noeof.txt\").read_text() == \"OVERWRITTEN\"\n assert (dst / \"meh\" / \"c.noeof.txt\").read_text() == \"SKIPPED\"\n\n\ndef test_config_exclude(dst, monkeypatch):\n def fake_data(*_args, **_kwargs):\n return {\"_exclude\": [\"*.txt\"]}\n\n monkeypatch.setattr(copier.config.factory, \"load_config_data\", fake_data)\n copier.copy(str(PROJECT_TEMPLATE), dst, data=DATA, quiet=True)\n assert not (dst / \"aaaa.txt\").exists()\n\n\ndef test_config_exclude_overridden(dst):\n def fake_data(*_args, **_kwargs):\n return {\"_exclude\": [\"*.txt\"]}\n\n copier.copy(str(PROJECT_TEMPLATE), dst, data=DATA, quiet=True, exclude=[])\n assert (dst / \"aaaa.txt\").exists()\n\n\ndef test_config_include(dst, monkeypatch):\n def fake_data(*_args, **_kwargs):\n return {\"_exclude\": [\"!.svn\"]}\n\n monkeypatch.setattr(copier.config.factory, \"load_config_data\", fake_data)\n copier.copy(str(PROJECT_TEMPLATE), dst, data=DATA, quiet=True)\n assert (dst / \".svn\").exists()\n\n\ndef test_skip_option(dst):\n render(dst)\n path = dst / \"pyproject.toml\"\n content = \"lorem ipsum\"\n path.write_text(content)\n render(dst, skip=True)\n assert path.read_text() == content\n\n\ndef test_force_option(dst):\n render(dst)\n path = dst / \"pyproject.toml\"\n content = \"lorem ipsum\"\n path.write_text(content)\n render(dst, force=True)\n assert path.read_text() != content\n\n\ndef test_pretend_option(dst):\n render(dst, pretend=True)\n assert not (dst / \"doc\").exists()\n assert not (dst / \"config.py\").exists()\n assert not (dst / \"pyproject.toml\").exists()\n","sub_path":"tests/test_copy.py","file_name":"test_copy.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"277335485","text":"import samna.dynapse1 as dyn1\nimport Dynapse1Utils as ut\nimport NetworkGenerator as n\nfrom NetworkGenerator import Neuron\nfrom Dynapse1Constants import *\nimport time\nimport samna\nimport json\n\n# read the samna info from json file written by py_server.py\nwith open('./samna_info.json') as f:\n data = json.load(f)\nprint(data)\nsender_port = data[\"sender_port\"]\nreceiver_port = data[\"receiver_port\"]\nsamna_node_id = data[\"samna_node_id\"]\ndevice_name = data[\"device_name\"]\npython_node_id = data[\"python_node_id\"]\n\npython_node_id += 3\n\n# setup the python interpreter node\nsamna.setup_local_node(receiver_port, sender_port, python_node_id)\n# open a connection to device_node, i.e. the store. Must open the device_node here\nsamna.open_remote_node(samna_node_id, \"device_node\")\nstore = samna.device_node\nmodel = getattr(store, device_name)\n\n# get Dynapse1 api from the model\napi = model.get_dynapse1_api()\n\n# ------------------- build network -------------------\nnet_gen = n.NetworkGenerator()\n\nchip = 0\ncore = 3\nspikegen_ids = [(0,core,66,True)]\nspikegens = []\nfor spikegen_id in spikegen_ids:\n spikegens.append(Neuron(spikegen_id[0],spikegen_id[1],spikegen_id[2],spikegen_id[3]))\nneuron_ids = [(chip,core,10), (chip,core,25), (chip,core,31), (chip,core,65), (chip,core,107), (chip,core,152)]\nneurons = []\nfor nid in neuron_ids:\n neurons.append(Neuron(nid[0],nid[1],nid[2]))\n\nnet_gen.add_connection(spikegens[0], neurons[0], dyn1.Dynapse1SynType.AMPA)\nnet_gen.add_connection(neurons[0], neurons[1], dyn1.Dynapse1SynType.AMPA)\nnet_gen.add_connection(neurons[0], neurons[2], dyn1.Dynapse1SynType.NMDA)\nnet_gen.add_connection(neurons[0], neurons[3], dyn1.Dynapse1SynType.GABA_A)\nnet_gen.add_connection(neurons[1], neurons[4], dyn1.Dynapse1SynType.GABA_B)\nnet_gen.add_connection(neurons[2], neurons[5], dyn1.Dynapse1SynType.GABA_B)\n\n# print the network so you can double check (optional)\nnet_gen.print_network()\n\n# make a dynapse1config using the network\nnew_config = net_gen.make_dynapse1_configuration_in_core(chip, core)\n\n# apply the configuration\nmodel.apply_configuration_by_core(new_config, chip, core)\n# ------------------- build network -------------------\n\n# check the configuration...\nglobal_ids = ut.get_global_id_list(neuron_ids)\nconfig = model.get_configuration()\nfor i in range(len(global_ids)):\n nid = global_ids[i]\n neuron = ut.get_neuron_from_config(config, nid)\n print(\"------------Neuron\", neuron_ids[i],\"------------\")\n print(\"Cams:\")\n ut.print_neuron_synapses(neuron, range(2))\n print(\"Srams:\")\n ut.print_neuron_destinations(neuron)\n\n# set spike generators (0,1,66)\npoisson_gen_id = ut.get_global_id(0,1,66)\nrate = 200\npoisson_gen = model.get_poisson_gen()\npoisson_gen.set_chip_id(0)\npoisson_gen.write_poisson_rate_hz(poisson_gen_id, rate) # neuron20 on chip 0 core 0\n\n# set parameters\nut.set_parameters_in_txt_file(model, './parameters.txt')\n\n# save parameters\nut.save_parameters2txt_file(model.get_configuration(), './current_parameters_sharing.txt')\n\n# start the poisson gen\npoisson_gen.start()\n\n\npoisson_gen.stop()\n\nwhile True:\n pass","sub_path":"code/ctxctl_contrib/sharing_1board_examples/4_sharing_dynapse1_C0c3.py","file_name":"4_sharing_dynapse1_C0c3.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"127295845","text":"#!/usr/bin/env python\n\n\"Function to sort files for main_pipeline.\"\n\"Authors: Owen Eskandari, Kerry Paterson\"\n\n__version__ = \"2.1\" #last updated 24/02/2021 by DV\n\nfrom astropy.io import fits\nfrom astropy.table import Table\nimport shutil\nimport importlib\nimport tel_params\nimport numpy as np\nimport os\n\n# Sort the calibration files:\ndef sort_files(files, telescope, path): #manual_filter=None, log2=None, date=None,\n\n '''\n\n Function used to sort a list of files into a dictionary of files sorted by filter.\n\n Parameters\n ----------\n\n :param files: list (string)\n List of strings of files (path should be included).\n\n :param manual_filter: string, optional\n Filter name if filter is not given in header of files.\n Default is ``None``.\n\n :param log2: log, optional\n Overview log used to write the object and date observed (if ``date`` parameter is not ``None``).\n If no log is inputted, information is printed out instead of being written to ``log2``.\n Default is ``None``.\n\n :param date: string, optional\n String of the date the observations were taken (to be recorded in ``log2`` if it is not ``None``).\n Default is ``None``.\n\n Returns\n -------\n\n :return: python dictionary\n Dictionary of files. Key is the filter of the file, values are the file names themselves.\n\n '''\n\n tel = importlib.import_module('tel_params.'+telescope)\n\n ext = tel.raw_header_ext()\n science_keyword = tel.science_keyword()\n flat_keyword = tel.flat_keyword()\n bias_keyword = tel.bias_keyword()\n dark_keyword = tel.dark_keyword()\n\n science_files = tel.science_files()\n flat_files = tel.flat_files()\n bias_files = tel.bias_files()\n dark_files = tel.dark_files()\n\n target_keyword = tel.target_keyword()\n fil_keyword = tel.filter_keyword()\n\n cal_list = {'BIAS':[],'DARK':[]}\n sci_list = {}\n sky_list = {}\n time_list = {}\n\n file_list = path+'/file_list.txt'\n file_table = Table(names=('File','Filter','Type','Time'),dtype=('S', 'S', 'S', 'f'))\n \n dir_path = path +'BIAS/'\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n for i, f in enumerate(files):\n with fits.open(f) as file_open:\n hdr = file_open[ext].header\n target = hdr[target_keyword].replace(' ','')\n fil = hdr[fil_keyword].replace(' ','')\n file_time = None\n if np.all([hdr[science_keyword[j]] == science_files[j] for j in range(len(science_keyword))]):\n file_type = 'SCIENCE'\n try:\n sci_list[target+'_'+fil]\n except KeyError:\n sci_list.update({target+'_'+fil:[]})\n sci_list[target+'_'+fil].append(f)\n try:\n time_list[target+'_'+fil]\n except KeyError:\n time_list.update({target+'_'+fil:[]})\n file_time = tel.time_format(hdr)\n time_list[target+'_'+fil].append(file_time)\n if tel.sky():\n try:\n sky_list[fil]\n except KeyError:\n sky_list.update({fil:[]})\n sky_list[fil].append(f)\n elif np.all([hdr[flat_keyword[j]] == flat_files[j] for j in range(len(flat_keyword))]):\n file_type = 'FLAT'\n try:\n cal_list['FLAT_'+fil]\n except KeyError:\n cal_list.update({'FLAT_'+fil:[]})\n cal_list['FLAT_'+fil].append(f) \n elif np.all([hdr[bias_keyword[j]] == bias_files[j] for j in range(len(bias_keyword))]):\n file_type = 'BIAS'\n cal_list['BIAS'].append(f)\n elif np.all([hdr[dark_keyword[j]] == dark_files[j] for j in range(len(dark_keyword))]):\n file_type = 'DARK'\n cal_list['DARK'].append(f)\n #David changes here\n #elif np.all([hdr[spec_keyword[j]] == spec_files[j] for j in range(len(spec_keyword))]):\n # file_type = 'SPEC'\n # shutil.move(f,path+'spec/')\n else:\n file_type = 'BAD'\n #David changes here\n # check if directory exists or not yet\n dir_path = path +'BAD/'\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n shutil.move(f,dir_path)\n \n file_table.add_row((target,fil,file_type,file_time))\n file_table.write(file_list,format='ascii',delimiter='\\t')\n lists_to_move = [cal_list, sci_list]\n dir_path = path +'raw/'\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n for l in lists_to_move:\n for key in l:\n [shutil.move(f,path+'raw/') for f in l]\n l[i] = [l[i].replace(path,path+'raw/') for i in l]\n\n return cal_list, sci_list, sky_list, time_list\n\ndef load_files(file_list):\n cal_list = {'BIAS':[],'DARK':[]}\n sci_list = {}\n sky_list = {}\n time_list = {}\n file_table = Table.read(file_list,format='ascii',delimiter='\\t')\n for i in range(len(file_table)):\n if file_table['Type'] == 'SCIENCE':\n target = file_table['File'][i]\n fil = file_table['Filter'][i]\n try:\n sci_list[target+'_'+fil]\n except KeyError:\n sci_list.update({target+'_'+fil:[]})\n sci_list[target+'_'+fil].append(f)\n try:\n time_list[target+'_'+fil]\n except KeyError:\n time_list.update({target+'_'+fil:[]})\n time_list[target+'_'+fil].append(file_time)\n if tel.sky():\n try:\n sky_list[fil]\n except KeyError:\n sky_list.update({fil:[]})\n sky_list[fil].append(f)\n elif file_table['Type'] == 'FLAT':\n try:\n cal_list['FLAT_'+fil]\n except KeyError:\n cal_list.update({'FLAT_'+fil:[]})\n cal_list['FLAT_'+fil].append(f)\n elif file_table['Type'] == 'BIAS':\n cal_list['BIAS'].append(f)\n elif file_table['Type'] == 'DARK':\n cal_list['DARK'].append(f)\n return cal_list, sci_list, sky_list, time_list\n","sub_path":"dvSort_files.py","file_name":"dvSort_files.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"1163407","text":"import numpy as np\nimport csv\n\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.datasets import cifar10, cifar100\nfrom keras.utils import to_categorical\n\nfrom encoder import Encoder, StateSpace\nfrom manager import NetworkManager\nfrom model import model_fn\nimport random\nimport time\nfrom utils import Logger\nimport sys\nimport os\nfrom datetime import datetime\nimport shutil\n\n# create a shared session between Keras and Tensorflow\npolicy_sess = tf.Session()\nK.set_session(policy_sess)\n\nB = 5 # number of blocks in each cell\nK_ = 25 # number of children networks to train\n\nMAX_EPOCHS = 3 # maximum number of epochs to train\nBATCHSIZE = 128 # batchsize\nREGULARIZATION = 0 # regularization strength\nCONTROLLER_CELLS = 100 # number of hidden units in RNN controller\nRNN_TRAINING_EPOCHS = 10\nRESTORE_CONTROLLER = True # restore controller to continue training\nNORMAL_CELL_NUMBER = 3\nFIRST_LAYER_FILTERS = 48\nLOG_FILE='log.txt'\nCLEAR_SHARE_WEIGHTS= True\n\n\nsys.stdout=Logger(LOG_FILE)\n\n\noperators = ['3x3 dconv', '5x5 dconv', '7x7 dconv',\n '1x7-7x1 conv', '3x3 maxpool', '3x3 avgpool','identity','3x3 conv'] # use the default set of operators, minus identity and conv 3x3\n\n\n# construct a state space\nstate_space = StateSpace(B, input_lookback_depth=-1, input_lookforward_depth=4,\n operators=operators)\n\n\n\n\n# print the state space being searched\nstate_space.print_state_space()\nNUM_TRAILS = state_space.print_total_models(K_)\n\n# prepare the training data for the NetworkManager\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\ndataset = [x_train, y_train, x_test, y_test] # pack the dataset for the NetworkManager\n\n\n#start recording time\nstart_time=time.time()\n\n# create the directory for model saving\nmodel_dir = 'models_{:%Y-%m-%dT%H:%M}'.format(datetime.now())\nos.makedirs(model_dir)\n\nwith policy_sess.as_default():\n # create the Encoder and build the internal policy network\n controller = Encoder(policy_sess, state_space, B=B, K=K_,\n train_iterations=RNN_TRAINING_EPOCHS,\n reg_param=REGULARIZATION,\n controller_cells=CONTROLLER_CELLS,\n restore_controller=RESTORE_CONTROLLER)\n\n# create the Network Manager\nmanager = NetworkManager(dataset, epochs=MAX_EPOCHS, batchsize=BATCHSIZE,cell_number=NORMAL_CELL_NUMBER,filters=FIRST_LAYER_FILTERS)\nprint()\n\n#reset all shared weights\nif os.path.isdir('shared_weights') and CLEAR_SHARE_WEIGHTS:\n shutil.rmtree('shared_weights')\n\n\n# train for number of trails\nfor trial in range(B):\n with policy_sess.as_default():\n K.set_session(policy_sess)\n\n if trial == 0:\n k = None\n else:\n k = K_\n\n actions = controller.get_actions(top_k=k) # get all actions for the previous state\n\n rewards = []\n for t, action in enumerate(actions):\n # print the action probabilities\n state_space.print_actions(action)\n print(\"Model #%d / #%d\" % (t + 1, len(actions)))\n print(\"Predicted actions : \", state_space.parse_state_space_list(action))\n\n save_path = '{}/model_{}.h5'.format(model_dir, t) if trial == B - 1 else None\n\n reward = manager.get_rewards(model_fn, state_space.parse_state_space_list(action), save_path=save_path)\n print(\"Final Accuracy : \", reward)\n\n rewards.append(reward)\n print(\"\\nFinished %d out of %d models ! \\n\" % (t + 1, len(actions)))\n\n # write the results of this trial into a file\n with open(os.path.join(model_dir, 'test.csv'), mode='a+', newline='') as f:\n data = [reward]\n data.extend(state_space.parse_state_space_list(action))\n writer = csv.writer(f)\n writer.writerow(data)\n\n #save result_model\n if trial==B-1:\n with open(os.path.join(model_dir, 'result.csv'), mode='a+', newline='') as f:\n data = [reward]\n data.extend(state_space.parse_state_space_list(action))\n data.append('model_'+str(t)+'.h5')\n writer = csv.writer(f)\n writer.writerow(data)\n\n with policy_sess.as_default():\n K.set_session(policy_sess)\n # train the controller on the saved state and the discounted rewards\n loss = controller.train_step(rewards)\n print(\"Trial %d: Encoder loss : %0.6f\" % (trial + 1, loss))\n\n controller.update_step()\n print()\n\n#record endding time \nend_time=time.time()\nprint('Total Time : ',end_time-start_time ,' sec')\nprint(\"Finished !\")\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"280389845","text":"import pandas as pd\nimport numpy as np\nfrom sqlalchemy.engine import create_engine\nimport ast\nimport os\nimport pdb\nfrom panoptes_client import *\n\n# Load my sql tables of confusion matrices and pp_matrices\nSQL_USER = os.environ['SQL_USER']\nSQL_PASS = os.environ['SQL_PASS']\nengine = create_engine('mysql://{0}:{1}@localhost/GravitySpy'.format(SQL_USER,SQL_PASS))\n\n# Open classification table and extract most recent classificationID\nimages = pd.read_sql('SELECT * FROM images_for_pp',engine)\nconfusion_matrices = pd.read_sql('SELECT * FROM confusion_matrices',engine)\ncurrentStatus = pd.read_sql('SELECT * FROM user_status_Oct_14',engine)\n\nconfusion_matrices1 = confusion_matrices.merge(currentStatus,how='left', left_on='userID', right_on='userID')\n\nconfusion_matrices1 = confusion_matrices1[confusion_matrices1.promoted_x != confusion_matrices1.promoted_y]\n\n# Connect to panoptes and query all classifications done on project 1104 (i.e. GravitySpy)\nPanoptes.connect()\nproject = Project.find(slug='zooniverse/gravity-spy')\n\nworkflow_dict = {\"B1\":1610, \"B2\":1934, \"B3\":1935,\"A\":2360,\"M\":2117}\n\n# Determine who is promoted and change their workflow preference\ndef promote_users(x):\n user = User.find(\"{0}\".format(x.userID))\n new_settings = {\"workflow_id\": \"{0}\".format(workflow_dict[x.promoted_x])}\n print(user)\n print(new_settings)\n ProjectPreferences.save_settings(project=project, user=user, settings=new_settings)\n\nconfusion_matrices1[confusion_matrices1.promoted_x != 'S'][['userID','promoted_x']].apply(promote_users,axis =1)\n\ndef move_image(x):\n # If has received enough labels or enough NOA form the beginner workflows that it has not been retired then we move it into the NOA Apprentice workflow for further analysis. We also remove it from whatever subject set it was in before.\n tmp = SubjectSet.find(5676)\n subject = Subject.find(x.zooID)\n # Add to new subject set\n print(subject)\n #tmp.add(subject)\n # Remove it form subject set it is currently in.\n tmp = SubjectSet.find(x.subject_set)\n print(tmp)\n #tmp.remove(subject)\n return\n\n#images[images.decision == 2][['subject_set','zooID']].apply(move_image,axis=1)\nretire_sets = [6354,6355,6356,6357,6358,6359,6360,6361,6364, 6365, 6367, 6366, 6375, 6374, 6373, 6372, 6371, 6370, 6369, 6368]\n\ndef retire_image(x):\n # If has received enough labels or enough NOA form the beginner workflows that it has not been retired then we move it into the NOA Apprentice workflow for further analysis. We also remove it from whatever subject set it was in before.\n tmp = SubjectSet.find(retire_sets[x.true_label])\n subject = Subject.find(x.zooID)\n # Add to new subject set\n print(subject)\n #tmp.add(subject)\n # Remove it form subject set it is currently in.\n tmp = SubjectSet.find(x.subject_set)\n print(tmp)\n #tmp.remove(subject)\n return\n\ndef checklen(x):\n len(x)\n#images[images.decision == 1][['subject_set','zooID','true_label']].apply(retire_image,axis=1)\n\n#iI = 0\n#iII = range(0,len(confusion_matrices),25)\n#for iIT in range(0,len(confusion_matrices),25):\n# if iIT == 0:\n# confusion_matrices[['userID','promoted']][0:iII[iI+1]].to_sql(con=engine, name='user_status', if_exists='replace', flavor='mysql',index=False)\n# elif iIT != iII[-1]:\n# confusion_matrices[['userID','promoted']][iII[iI]+1:iII[iI+1]].to_sql(con=engine, name='user_status', if_exists='append', flavor='mysql',index=False)\n# else:\n# confusion_matrices[['userID','promoted']][iII[iI]+1:len(confusion_matrices)].to_sql(con=engine, name='user_status', if_exists='append', flavor='mysql',index=False)\n# iI = iI + 1\n\nconfusion_matrices[['userID','promoted']].to_sql(con=engine, name='user_status', if_exists='replace', flavor='mysql')\n","sub_path":"API/CCPostProc.py","file_name":"CCPostProc.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"238113891","text":"import json\nfrom django.contrib.auth.decorators import login_required\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom api.models import Aorb\nfrom api.serializers import AorbSerializer\n\n\nclass AorbsView(APIView):\n\n def get(self, request, format=None):\n \"\"\"\n Return a list of all aorb cards.\n \"\"\"\n aorbs = Aorb.objects.all()\n serializer = AorbSerializer(aorbs, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n \"\"\"\n Create a aorb card\n \"\"\"\n serializer = AorbSerializer(\n data=json.loads(request.body.decode(\"utf-8\")))\n\n if serializer.is_valid():\n serializer.save(user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass AorbView(APIView):\n def get_object(self, id):\n try:\n return Aorb.objects.get(id=id)\n except Aorb.DoesNotExist:\n raise Http404\n\n def get(self, request, id):\n \"\"\"\n Return a list of all aorb cards.\n \"\"\"\n aorb = self.get_object(id)\n serializer = AorbSerializer(aorb)\n return Response(serializer.data)\n","sub_path":"server/api/views/aorb.py","file_name":"aorb.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"202282006","text":"import os\nimport shutil\nimport glob\nimport re\nfrom urllib.parse import urlparse\n\ndef rewrite_any_relative_links(line, file_path):\n match = re.search(r'\\[.+\\]\\((.+)\\)', line)\n if match and match[1] and not match[1].endswith('.png'):\n domain = urlparse(match[1]).netloc\n if not domain:\n # this is pretty fragile but it works for the POC\n new_link = match[1].replace('.md', '')\n #if file_path.endswith('index.mdx'):\n # new_link = 'pgbackrest/' + new_link\n return re.sub(r'\\]\\(.+\\)', ']({})'.format(new_link), line)\n return line \n\ndef process_md(file_path):\n if os.path.islink(file_path):\n os.remove(file_path)\n return\n\n split_path = file_path.split('/')\n split_path.insert(len(split_path)-1, 'pgbackrest')\n new_file_path = '/'.join(split_path).replace('.md', '.mdx')\n if split_path[-1] == 'README.md':\n new_file_path = new_file_path.replace('README.mdx', 'index.mdx')\n\n with open(new_file_path, 'w') as new_file:\n with open(file_path, 'r') as md_file:\n copying = False\n previous_line_was_blank = False\n gh_relative_path = file_path.replace('external_sources/pgbackrest', '')\n\n for line in md_file:\n if copying:\n line_blank = line.strip() == ''\n if line_blank and not previous_line_was_blank:\n previous_line_was_blank = True\n new_file.write(line)\n elif not line_blank:\n previous_line_was_blank = False\n new_file.write(\n rewrite_any_relative_links(\n line.replace('
', '
'),\n new_file_path\n )\n )\n if line.startswith('#') and not copying:\n copying = True\n new_file.write(\"---\\ntitle: '{0}'\\noriginalFilePath: '{1}'\\n---\\n\\n\".format(\n re.sub(r'#+ ', '', line).strip().replace('
', '-'),\n gh_relative_path\n ))\n os.remove(file_path)\n\ndef source_pgbackrest():\n print('Pulling pgbackrest...')\n\n # Commented out as the repo is private, use included files for now\n # os.system('git clone -b docs_development git@github.com:EnterpriseDB/pgbackrest-docs.git external_sources/pgbackrest')\n os.system('cp -r temp_pgbackrest/. external_sources/pgbackrest')\n\n os.system('mkdir external_sources/pgbackrest/docs/pgbackrest')\n\n print('Processing pgbackrest...')\n files = glob.glob('external_sources/pgbackrest/docs/**/*.md', recursive=True)\n for file_path in files:\n process_md(file_path)\n os.system('mv external_sources/pgbackrest/docs/images external_sources/pgbackrest/docs/pgbackrest/images')\n\nif __name__ == '__main__':\n source_pgbackrest()\n","sub_path":"scripts/source/source_pgbackrest.py","file_name":"source_pgbackrest.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"318525141","text":"# Given a sorted linked list, delete all nodes that have duplicate numbers,\n# leaving only distinct numbers from the original list.\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n dummy.next = head\n curr = dummy\n while curr.next and curr.next.next:\n if curr.next.val == curr.next.next.val:\n val = curr.next.val\n while curr.next and curr.next.val == val:\n curr.next = curr.next.next\n else:\n curr = curr.next\n return dummy.next\n\n \n","sub_path":"leetcode/82_remove_duplicates_from_sorted_list_II.py","file_name":"82_remove_duplicates_from_sorted_list_II.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500501396","text":"import subprocess\nimport os\nimport time\n#import signal\n\n\n# print '\\nCpp simulation\\n'\n\n# os.environ['GOMP_CPU_AFFINITY'] = '0 28 1 29 2 30 3 31 4 32 5 33 6 34 7 35 8 36 9 37 10 ' + \\\n# '38 11 39 12 40 13 41 14 42 15 43 16 44 17 45 18 46 19 47 20 48 21 49 22 50 23 51 24 52 25 53 26 54 27 55'\n\nproject_dir = '/afs/cern.ch/work/k/kiliakis/git/thesis/bench-queues/'\nexe_dir = project_dir + 'build_gcc/bench-queues/'\noutfiles = '/afs/cern.ch/work/k/kiliakis/git/thesis/bench-queues/results/raw/pair3/'\n\n# exe_list = ['boost-static', 'boost-static-push', 'boost-static-pop',\n# 'boost-dynamic', 'boost-dynamic-push', 'boost-dynamic-pop',\n# 'folly', 'folly-push', 'folly-pop',\n# 'circularfifo', 'circularfifo-push', 'circularfifo-pop'\n# ]\n\nexe_list = ['boost-static', 'boost-dynamic', 'cameron', 'folly', 'circularfifo']\n\n# exe_list = ['circularfifo-push', 'circularfifo-pop' ]\n# exe_list = ['histogram4']\nn_turns_list = ['1000']\n# n_elements_list = ['10000']\nn_threads_list = ['1', '2', '4', '8', '14', '28']\nrepeats = 5\n\n# os.chdir(exe_dir)\ntotal_sims = len(n_turns_list) * len(n_threads_list) * len(exe_list) * repeats\nprint(\"Total runs: \", total_sims)\n\ncurrent_sim = 0\nfor exe in exe_list:\n if('push' in exe) or ('pop' in exe):\n n_elems = '100000'\n else:\n n_elems = '1000000'\n for n_turns in n_turns_list:\n for n_threads in n_threads_list:\n outdir = outfiles\n name = exe + '-' + 'n_e' + n_elems + 'n_t' + n_turns +\\\n 'n_thr' + n_threads\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n # res = open(outdir + name + '.txt', 'w')\n stdout = open(outdir + name+'.stdout', 'w')\n # stderr = open(outdir + name+'.stderr', 'w')\n for i in range(0, repeats):\n exe_args = [exe_dir + exe,\n '-e' + n_elems,\n '-b' + '1000',\n '-t' + n_turns,\n '-m' + n_threads\n ]\n print(exe, n_turns, n_elems, n_threads, i)\n output = subprocess.check_output(exe_args)\n current_sim += 1\n stdout.write(output.decode('utf-8'))\n # time = output.split(\n # 'Elapsed time: ')[1].split('sec')[0]\n # res.write(time+'\\n')\n print(\"%.2f %% is completed\" % (100.0 * current_sim /\n total_sims))\n","sub_path":"scripts/scan_haswell.py","file_name":"scan_haswell.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"359561252","text":"import os\nimport cv2\nimport torch\nimport numpy as np\nimport glob\nimport torch.nn.functional as F\nfrom dataset import Data\n\nroot = '/data/DUTS/DUTS-TR'\nECSSD = '/data/ECSSD'\npascal = '/data/PASCAL'\nomron = '/data/DUTS/DUT-OMRON'\nhku = '/data/HKU-IS'\nduts = '/data/DUTS/DUTS-TE'\n\ndata_dict = {'train':root, 'ECSSD':ECSSD, 'PASCAL': pascal, 'HKU':hku, 'DUTS':duts,'DUT-O':omron}\n\nclass Config(object):\n def __init__(self, **kwargs):\n self.kwargs = kwargs\n\n\n print('\\nParameters...')\n for k, v in self.kwargs.items():\n print('%-10s: %s'%(k, v))\n\n def __getattr__(self, name):\n if name in self.kwargs:\n return self.kwargs[name]\n else:\n return None\n\ndef get_data(mode,data):\n\n\tcfg_test = Config(datapath=data_dict[data],mode=data)\n\tdata_test = Data(cfg_test,mode)\n\n\tcfg = Config(datapath=data_dict['train'], mode='train')\n\tdata_train = Data(cfg,mode)\n\t# print(cfg.datapath)\n\t# print(data)\n\t# print(data_dict[data])\n\t# cfg_test = Config(datapath=data_dict[data],mode=data)\n\t# data_test = Data(cfg_test,mode)\n\n\t# if mode == 'orginal':\n\n\n\treturn data_train, data_test\n\n","sub_path":"paper_result/PoolNet/bicon/test/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"280423790","text":"#-------------------------------------------------------------------------------\r\n#\r\n# project: fxApp - gui toolkit for pyqt\r\n# version: 0.x\r\n#\r\n#-------------------------------------------------------------------------------\r\n\r\nfrom PyQt4 import QtCore, QtGui\r\n\r\n#-------------------------------------------------------------------------------\r\n\r\ndef isX11():\r\n '''\r\n Returns True if this is an X11-based system (such as Linux, BSD, Solaris, etc)\r\n and False if it is not. The 'qt_x11_wait_for_window_manager' function only\r\n exists if PyQt4 is being executed on a system with X11.\r\n \r\n @note This has not been tested on an X11 system yet.\r\n '''\r\n return hasattr(PyQt4.QtGui, \"qt_x11_wait_for_window_manager\")\r\n \r\ndef isMAC():\r\n '''\r\n Returns True if this is a MAC and False if it is not. The function used,\r\n \"qt_mac_set_native_menubar\", only exists in PyQt4 if the program is being\r\n run on a MAC.\r\n \r\n @note This has not been tested on a MAC system yet.\r\n '''\r\n return hasattr(PyQt4.QtGui, \"qt_mac_set_native_menubar\")\r\n \r\n\r\n\r\n#-------------------------------------------------------------------------------\r\n\r\nclass ErrorHandling:\r\n @staticmethod\r\n def getFileErrorMessage(errorCode):\r\n if(errorCode == QtCore.QFile.NoError): #errorCode = 0\r\n retTuple = (\"QtCore.QFile.NoError\", \"No error occurred.\")\r\n \r\n elif(errorCode == QtCore.QFile.ReadError): #errorCode = 1\r\n retTuple = (\"QtCore.QFile.ReadError\", \"An error occurred when reading from the file.\")\r\n \r\n elif(errorCode == QtCore.QFile.WriteError): #errorCode = 2\r\n retTuple = (\"QtCore.QFile.WriteError\", \"An error occurred when writing to the file.\")\r\n \r\n elif(errorCode == QtCore.QFile.FatalError): #errorCode = 3\r\n retTuple = (\"QtCore.QFile.FatalError\", \"A fatal error occurred.\")\r\n \r\n elif(errorCode == QtCore.QFile.ResourceError): #errorCode = 4\r\n retTuple = (\"QtCore.QFile.ResourceError\", \"A resource error occurred.\")\r\n \r\n elif(errorCode == QtCore.QFile.OpenError): #errorCode = 5\r\n retTuple = (\"QtCore.QFile.OpenError\", \"The file could not be opened.\")\r\n \r\n elif(errorCode == QtCore.QFile.AbortError): #errorCode = 6\r\n retTuple = (\"QtCore.QFile.AbortError\", \"The operation was aborted.\")\r\n\r\n elif(errorCode == QtCore.QFile.TimeOutError): #errorCode = 7\r\n retTuple = (\"QtCore.QFile.TimeOutError\", \"A timeout occurred.\")\r\n \r\n elif(errorCode == QtCore.QFile.UnspecifiedError): #errorCode = 8\r\n retTuple = (\"QtCore.QFile.UnspecifiedError\", \"An unspecified error occurred.\")\r\n \r\n elif(errorCode == QtCore.QFile.RemoveError): #errorCode = 9\r\n retTuple = (\"QtCore.QFile.RemoveError\", \"The file could not be removed.\")\r\n \r\n elif(errorCode == QtCore.QFile.RenameError): #errorCode = 10\r\n retTuple = (\"QtCore.QFile.RenameError\", \"The file could not be renamed.\")\r\n \r\n elif(errorCode == QtCore.QFile.PositionError): #errorCode = 11\r\n retTuple = (\"QtCore.QFile.PositionError\", \"The position in the file could not be changed.\")\r\n \r\n elif(errorCode == QtCore.QFile.ResizeError): #errorCode = 12\r\n retTuple = (\"QtCore.QFile.ResizeError\", \"The file could not be resized.\")\r\n \r\n elif(errorCode == QtCore.QFile.PermissionsError): #errorCode = 13\r\n retTuple = (\"QtCore.QFile.PermissionsError\", \"The file could not be accessed.\")\r\n \r\n elif(errorCode == QtCore.QFile.CopyError): #errorCode = 14\r\n retTuple = (\"QtCore.QFile.CopyError\", \"The file could not be copied.\")\r\n \r\n else:\r\n msg = \"An unknown error occured! The error code you provided does not coincide with the possible values in QtCore.QFile.error().\\n\"\r\n msg += \"Please reference: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qfile.html#FileError-enum\"\r\n retTuple = (\"UnknownErrorCode\", msg)\r\n\r\n\r\n","sub_path":"src/fxApp/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382831139","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 17 18:32:47 2016\n\n@author: twovillage\n\"\"\"\nimport lxml.html\nfrom selenium import webdriver\nfrom datetime import datetime as dt\nimport re\nimport urllib.parse as urlparse\nimport pymysql as msc\nimport time\n\nfrom models import mysql_modelmanager\n\nROOT_URL = 'http://www.football-lab.jp'\n\nclass MatchPageController(object):\n def __init__(self,url):\n super(MatchPageController).__init__()\n self.url = url\n self.mysql_model = mysql_modelmanager.MySqlConnectiorModelManager()\n \n print(\"ページ取得開始\")\n start_time = time.time()\n for i in range(10):\n try:\n driver = webdriver.PhantomJS()\n driver.get(self.url)\n elapse_time = time.time() - start_time\n print(\"取得時間:{0}\".format(elapse_time) + \" [sec]\")\n \n if elapse_time < 30:\n self.is_access_webpage = True\n \n self.root = lxml.html.fromstring(driver.page_source)\n self._current_page_team_info()\n driver.close()\n driver.quit()\n \n break\n else:\n self.is_access_webpage = False\n driver.close()\n driver.quit()\n \n print(\"取得完了\")\n except:\n import traceback\n traceback.print_exc()\n print(\"webdriver error\")\n self.is_access_webpage = False\n break\n \n \n \n \n \n \n def _current_page_team_info(self):\n page_team_and_year_string = self.root.cssselect('#teamInfo > .unit#teamName > em')[0].text_content()\n split_string_list = page_team_and_year_string.split('[') \n self.page_team_name = split_string_list[0]\n self.league_name = split_string_list[1].split(' ')[0]\n \n self._past_year_match()\n \n def _past_year_match(self):\n year_box = self.root.cssselect('#navYear > ul > li > a[href]')\n \n self.past_year_urls = []\n for link in year_box:\n if not link.cssselect('.sel'):\n full_url = urlparse.urljoin(ROOT_URL,link.get('href'))\n self.past_year_urls.append(full_url)\n \n \n def collect_match_links(self):\n match_links = self.root.cssselect('.cFix.linkPast > a[href]')\n \n self.link_past_urls =[]\n for link in match_links:\n if not link.cssselect('.sel'):\n full_url = urlparse.urljoin(ROOT_URL,link.get('href'))\n self.link_past_urls.append(full_url)\n \n def collect_match_informations(self):\n self._scrape_date_and_location()\n self._scrape_pitch_info()\n if self.league_name == 'J1' or self.league_name == 'J2':\n self._scrape_scores()\n self._scrape_team_info()\n else:\n self._scrape_scores_and_team_info_at_J3()\n if self.is_exist_match_stats():\n self.is_exist_stats = True\n self._scrape_stats()\n else:\n self.is_exist_stats = False\n \n print(self.league_name)\n print(\"日時: \"+ str(self.tdatetime)+\" 場所: \"+self.location)\n print(\"HOME: \" + self.home_team + \" AWAY: \"+self.away_team)\n print(\" \" + str(self.home_total_score) +\" \"+ str(self.away_total_score))\n \n def _scrape_date_and_location(self):\n #date & location\n previewcard_tag = self.root.cssselect('#previewcard')\n date_string = previewcard_tag[0].cssselect('.uiDate')[0].text_content()\n date_string = re.sub(' Kick off','',date_string)\n self.tdatetime = dt.strptime(str(date_string),'%Y %m/%d[%a] %H:%M')\n\n self.location = str(previewcard_tag[0].cssselect('.s')[0].text_content())\n \n def _scrape_team_info(self):\n #team\n preview_team = self.root.cssselect('.preview_name')\n \n \n for team in preview_team:\n pos = team.cssselect('h3 > span')[0].text_content()\n \n \n if pos == 'HOME':\n self.home_team = str(team.cssselect('a > span')[0].text_content())\n elif pos == 'AWAY':\n self.away_team = str(team.cssselect('a > span')[0].text_content())\n \n def _scrape_pitch_info(self):\n #会場情報\n all_box = self.root.cssselect('.allbox')\n #一個に決まらないので天気という名称で該当箇所を探す\n for boxs in all_box:\n candidates = boxs.cssselect('.player_profile')\n for candidate in candidates:\n if candidate.text_content() == '天気':\n for i,table in enumerate(boxs.cssselect('td')):\n if table.text_content() == '天気':\n self.weather = str(boxs.cssselect('td')[i + 1].text_content())\n \n elif table.text_content() == '気温':\n self.temp = boxs.cssselect('td')[i + 1].\\\n cssselect('.uiNum')[0].text_content()\n self.temp = float(self.temp)\n elif table.text_content() == '芝':\n self.pitch = str(boxs.cssselect('td')[i + 1].text_content())\n elif table.text_content() == '観客数':\n self.audience = boxs.cssselect('td')[i + 1].\\\n cssselect('.uiNum')[0].text_content()\n self.audience = int(self.audience.replace(',',''))\n \n\n def _scrape_scores(self):\n #スコア\n score_1st = self.root.cssselect('.score1st')[0]\n self.home_1st_score = int(score_1st.cssselect('.tH > .uiNum')[0].text_content())\n self.away_1st_score = int(score_1st.cssselect('.tA > .uiNum')[0].text_content())\n score_2nd = self.root.cssselect('.score2nd')[0]\n self.home_2nd_score = int(score_2nd.cssselect('.tH > .uiNum')[0].text_content())\n self.away_2nd_score = int(score_2nd.cssselect('.tA > .uiNum')[0].text_content())\n self.home_total_score = self.home_1st_score + self.home_2nd_score\n self.away_total_score = self.away_1st_score + self.away_2nd_score\n\n def _scrape_scores_and_team_info_at_J3(self):\n score_and_team_box = self.root.cssselect('.sp_score > tbody > tr')\n for tag in score_and_team_box:\n if len(tag.cssselect('.eng')) == 0:\n #チーム名の抽出\n self.home_team = str(tag.cssselect('.pretd4#boxright')[0].text_content())\n self.away_team = str(tag.cssselect('.pretd4#boxleft')[0].text_content())\n #トータルスコアの抽出\n extract_tags = tag.cssselect('td:not(#boxright)')\n for ex_tag in extract_tags:\n ex2_tag = ex_tag.cssselect('td:not(#boxleft)')\n if len(ex2_tag) == 1:\n score_board = ex2_tag[0].text_content() \n total_score_string_list = score_board.split('-')\n self.home_total_score = int(total_score_string_list[0])\n self.away_total_score = int(total_score_string_list[1])\n \n if self.home_total_score > 0 or self.away_total_score > 0:\n #前半戦・後半戦スコアの計算とトータルスコアの検算\n boxs = self.root.cssselect('div.allbox >table')\n \n for box in boxs:\n \n box_text = box.text_content()\n \n if '前半' in box_text or '後半' in box_text:\n \n score_rows = box.cssselect('tbody')\n home_1st_score = 0\n home_2nd_score = 0\n away_1st_score = 0\n away_2nd_score = 0\n for row in score_rows:\n raw_home_player_name = str(row.cssselect('.pretd4#boxright')[0].text_content())\n point_section = str(row.cssselect('.pretd10#boxright')[0].text_content())\n raw_away_player_name = str(row.cssselect('.pretd4#boxleft')[0].text_content())\n \n home_player_name = raw_home_player_name.strip()\n away_player_name = raw_away_player_name.strip()\n \n if home_player_name =='':\n home_point = 0\n away_point = 1\n elif away_player_name =='':\n home_point = 1\n away_point = 0\n else:\n print('スコア計算でデータ異常があり')\n \n if point_section == '前半':\n home_1st_score += home_point\n away_1st_score += away_point\n elif point_section == '後半':\n home_2nd_score += home_point\n away_2nd_score += away_point\n \n self.home_1st_score = home_1st_score\n self.home_2nd_score = home_2nd_score\n self.away_1st_score = away_1st_score\n self.away_2nd_score = away_2nd_score\n \n if self.home_total_score == self.home_1st_score + self.home_2nd_score:\n print(\"ホームチーム点数計算異常なし\")\n else:\n print(\"ホームチーム点数計算異常なし\")\n \n if self.away_total_score == self.away_1st_score + self.away_2nd_score:\n print(\"アウェイチーム点数計算異常なし\")\n else:\n print(\"アウェイチーム点数計算異常なし\") \n \n \n \n break\n else:\n self.home_1st_score = 0\n self.home_2nd_score = 0\n self.away_1st_score = 0\n self.away_2nd_score = 0\n \n \n def _scrape_stats(self):\n #スタッツ\n self.stats_dic = {}\n stats_tag = self.root.cssselect('tbody')\n for tags in stats_tag:\n boxcenter = tags.cssselect('#boxcenter')\n for word in boxcenter:\n if word.text_content() == '総数':\n for row in tags:\n if len(row) < 4:\n continue\n content = row[2].text_content()\n home_rate = row[0].text_content()\n home_count = row[1].text_content()\n away_count = row[3].text_content()\n away_rate = row[4].text_content()\n \n #データの整形(適当な方にする)\n if home_rate != '-' :\n if home_rate != '成功率':\n home_rate = float(re.sub('%','',home_rate))\n else:\n home_rate = -1.0\n else:\n home_rate = -1.0\n \n if away_rate != '-' :\n if away_rate != '成功率':\n away_rate = float(re.sub('%','',away_rate))\n else:\n away_rate = -1.0\n else:\n away_rate = -1.0\n \n if 'km' in home_count:\n home_count = float(re.sub('km','',home_count))\n elif home_count != '総数':\n home_count = int(home_count.replace(',',''))\n else:\n home_count = -1\n \n if 'km' in away_count:\n away_count = float(re.sub('km','',away_count))\n elif away_count != '総数':\n away_count = int(away_count.replace(',',''))\n else:\n away_count = -1\n \n array = [home_count,home_rate,away_count,away_rate]\n \n if content == 'シュート':\n self.stats_dic['shoot'] = array\n elif content == '枠内シュート':\n self.stats_dic['inside_shoot'] = array\n elif content == 'PKによるシュート':\n self.stats_dic['pk_shoot'] = array\n elif content == 'パス':\n self.stats_dic['pass'] = array\n elif content == 'クロス':\n self.stats_dic['cross'] = array\n elif content == '直接FK':\n self.stats_dic['direct_fk'] = array\n elif content == '間接FK':\n self.stats_dic['indirect_fk'] = array\n elif content == 'CK':\n self.stats_dic['ck'] = array\n elif content == 'スローイン':\n self.stats_dic['throwin'] = array\n elif content == 'ドリブル':\n self.stats_dic['dribble'] = array\n elif content == 'タックル':\n self.stats_dic['tackle'] = array\n elif content == 'クリア':\n self.stats_dic['clear'] = array\n elif content == 'インターセプト':\n self.stats_dic['intercept'] = array\n elif content == 'オフサイド':\n self.stats_dic['offside'] = array\n elif content == '警告':\n self.stats_dic['warning'] = array\n elif content == '退場':\n self.stats_dic['leaving'] = array\n elif content == '30mライン進入':\n self.stats_dic['30m_line'] = array\n elif content == '総走行距離':\n self.stats_dic['total_range'] = array\n elif content == 'スプリント数':\n self.stats_dic['sprint'] = array\n \n break\n if 'total_range' not in self.stats_dic:\n self.stats_dic['total_range'] = [-1.0,-1.0,-1.0,-1.0]\n if 'sprint' not in self.stats_dic:\n self.stats_dic['sprint'] = [-1,-1.0,-1,-1.0]\n \n def is_exist_match_stats(self):\n yahoo_link_tags = self.root.cssselect('.allbox.c > p')\n\n for tag in yahoo_link_tags:\n message = tag.text_content()\n if message == '※外部サイトへ移動します':\n return False\n return True\n \n def insert_database(self):\n \n \n connector = self.mysql_model.connector\n cur = self.mysql_model.cur\n \n #試合会場の検索\n location_id = self.mysql_model.search_and_insert_db(\"location\",self.location)\n #ホームチームの検索\n home_team_id = self.mysql_model.search_and_insert_db(\"team\",self.home_team)\n #アウェイチームの検索\n away_team_id = self.mysql_model.search_and_insert_db(\"team\",self.away_team)\n #ピッチコンディションの検索 \n pitch_id = self.mysql_model.search_and_insert_db(\"pitch\",self.pitch)\n #天気の検索\n weather_id = self.mysql_model.search_and_insert_db(\"weather\",self.weather)\n\n cur.execute(\"\"\"SELECT * FROM game WHERE date_time = %s AND location = %s \"\"\",(self.tdatetime,location_id) )\n rows = cur.fetchall()\n if len(rows) == 0:\n print(\"マッチデータを記録\")\n\n try:\n cur.execute(\n \"\"\"INSERT INTO game (date_time,location,league,\n home_team,away_team,weather,pitch,temp,audience,\n home_1st_score,home_2nd_score,\n away_1st_score,away_2nd_score,\n home_shoot_count,home_shoot_rate,\n away_shoot_count,away_shoot_rate,\n home_inside_shoot,\n away_inside_shoot,\n home_pk_shoot,\n away_pk_shoot,\n home_pass_count,home_pass_rate,\n away_pass_count,away_pass_rate,\n home_cross_count,home_cross_rate,\n away_cross_count,away_cross_rate,\n home_direct_fk,\n away_direct_fk,\n home_indirect_fk,\n away_indirect_fk,\n home_ck,\n away_ck,\n home_throwin_count,home_throwin_rate,\n away_throwin_count,away_throwin_rate,\n home_drible_count,home_drible_rate,\n away_drible_count,away_drible_rate,\n home_tackle_count,home_tackle_rate,\n away_tackle_count,away_tackle_rate,\n home_clear,\n away_clear,\n home_intercept,\n away_intercept,\n home_offside,\n away_offside,\n home_warning,\n away_warning,\n home_leaving,\n away_leaving,\n home_30m_line,\n away_30m_line,\n home_total_range,\n away_total_range,\n home_sprint,\n away_sprint) \n VALUES (%s,%s,%s,\n %s,%s,%s,%s,%s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,\n %s,\n %s,\n %s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,%s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s)\"\"\" ,\n (self.tdatetime,location_id,self.league_name,\n home_team_id,away_team_id,weather_id,pitch_id,self.temp,self.audience,\n self.home_1st_score,self.home_2nd_score,\n self.away_1st_score,self.away_2nd_score,\n self.stats_dic['shoot'][0],self.stats_dic['shoot'][1],\n self.stats_dic['shoot'][2],self.stats_dic['shoot'][3],\n self.stats_dic['inside_shoot'][0],\n self.stats_dic['inside_shoot'][2],\n self.stats_dic['pk_shoot'][0],\n self.stats_dic['pk_shoot'][2],\n self.stats_dic['pass'][0],self.stats_dic['pass'][1],\n self.stats_dic['pass'][2],self.stats_dic['pass'][3],\n self.stats_dic['cross'][0],self.stats_dic['cross'][1],\n self.stats_dic['cross'][2],self.stats_dic['cross'][3],\n self.stats_dic['direct_fk'][0],\n self.stats_dic['direct_fk'][2],\n self.stats_dic['indirect_fk'][0],\n self.stats_dic['indirect_fk'][2],\n self.stats_dic['ck'][0],\n self.stats_dic['ck'][2],\n self.stats_dic['throwin'][0],self.stats_dic['throwin'][1],\n self.stats_dic['throwin'][2],self.stats_dic['throwin'][3],\n self.stats_dic['dribble'][0],self.stats_dic['dribble'][1],\n self.stats_dic['dribble'][2],self.stats_dic['dribble'][3],\n self.stats_dic['tackle'][0],self.stats_dic['tackle'][1],\n self.stats_dic['tackle'][2],self.stats_dic['tackle'][3],\n self.stats_dic['clear'][0],\n self.stats_dic['clear'][2],\n self.stats_dic['intercept'][0],\n self.stats_dic['intercept'][2],\n self.stats_dic['offside'][0],\n self.stats_dic['offside'][2],\n self.stats_dic['warning'][0],\n self.stats_dic['warning'][2],\n self.stats_dic['leaving'][0],\n self.stats_dic['leaving'][2],\n self.stats_dic['30m_line'][0],\n self.stats_dic['30m_line'][2],\n self.stats_dic['total_range'][0],\n self.stats_dic['total_range'][2],\n self.stats_dic['sprint'][0],\n self.stats_dic['sprint'][2],))\n connector.commit()\n except msc.IntegrityError as error:\n import traceback\n print('挿入エラー')\n traceback.print_exc()\n \n else:\n print(\"このマッチデータはデータベースに存在しているのでスキップ\")\n \n if __name__ == '__main__':\n #メインならばクローズ処理\n cur.close()\n connector.close()\n print(\"クローズ処理完了\")\n \n def close(self):\n self.mysql_model.close()\n \n \nif __name__ == '__main__': \n url = 'http://www.football-lab.jp/kiky/report/?year=2012&month=04&date=08' \n controller = MatchPageController(url)\n print(controller.page_team_name)\n controller.collect_match_informations()\n \n #print(\"データベース接続\")\n #controller.insert_database()\n \n","sub_path":"controllers/matchpagecontroller.py","file_name":"matchpagecontroller.py","file_ext":"py","file_size_in_byte":23201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"286585968","text":"from copy import deepcopy\nimport math\nfrom pathlib import Path\nimport re\n\nfrom lxml import etree\nimport pandas as pd\n\nimport utils as ut\nimport taxonomy_front_utils as txnm\n\n\nFILES_PATH = ut.REPO_PATH\nWORKS_SHEET_PATH = Path('reference/works.xlsx')\nCOMMENTS_SHEET_PATH = Path('reference/letters.xlsx')\nANNOTATIONS_SHEETS_PATH = Path('reference/annotations.xlsx')\nCATALOGUE_PATH = Path('headers/templates/header_catalogue_v3.xml')\nRESULT_PATH = Path('reference', 'catalogue.xml')\nTAXONOMY_PATH = Path(ut.REPO_PATH, 'reference', 'taxonomy.xml')\nNEW_TAXONOMY_PATH = Path(ut.REPO_PATH, 'reference', 'taxonomy_front.xml')\n\nCATEGORIES_ORDER = {\n 'finished': 0,\n 'not_finished': 1,\n 'editions': 2\n}\n\nMULTIVOLUME_WORKS = ['Vojna_i_mir', 'Anna_Karenina', 'Voskresenie', 'Na_kazhdyj_den']\n\n\ndef get_list_item(root: etree._Element, work_id: str) -> etree._Element | None:\n for item in root.xpath('//item'):\n ref_tag = item[0]\n if ref_tag.text == work_id:\n return item\n\n\ndef create_new_list_item(work_id: str, data: dict, taxonomies: list[dict]) -> etree._Element:\n item = etree.Element('item')\n ref_tag = etree.Element('ref')\n ref_tag.text = work_id\n item.append(ref_tag)\n title_tag = etree.Element('title')\n title_tag.text = data['title'].rstrip(' ')\n item.append(title_tag)\n item.append(data['date_tag'])\n\n old_ana = [i.strip('#') for i in data['catrefs'].values()]\n old_ana.append('main')\n new_ana = txnm.old_catrefs_to_new_catrefs(old_ana, taxonomies)\n new_ana = txnm.remove_vse_prosto_ana_for_bibllist(new_ana)\n new_ana.remove('main')\n taxonomy, new_taxonomy = taxonomies\n new_catrefs = {}\n for ana in new_ana:\n try:\n new_catrefs[taxonomy[ana]['target']] = ana\n except KeyError:\n new_catrefs[new_taxonomy[ana]['target']] = ana\n for target, ana in new_catrefs.items():\n item.append(etree.Element('catRef', ana=ana, target=target))\n\n note_annotation = etree.Element('note')\n note_annotation.text = data.get('annotation')\n note1 = etree.Element('note', {'type': 'entities_number_in_texts'})\n note2 = etree.Element('note', {'type': 'entities_number_in_comments'})\n item.append(note_annotation)\n item.append(note1)\n item.append(note2)\n\n for related_item, _, _, _ in data['related_items']:\n item.append(related_item)\n\n if 'comments' in data:\n for comment_data in data['comments']:\n comment_tag = etree.Element('relatedItem')\n ref_tag = etree.Element('ref', ana=f'#comments #{comment_data[\"category\"]}')\n ref_tag.text = comment_data['file_id']\n comment_tag.append(ref_tag)\n title_tag = etree.Element('title', resp=\"volume_editor\")\n title_tag.text = comment_data['title'].strip(' ')\n comment_tag.append(title_tag)\n\n # add bibliography\n bibl_tag = etree.Element('title', type='bibl')\n bibl_tag.text = comment_data['bibliography']\n comment_tag.append(bibl_tag)\n\n author = comment_data['author']\n if author is not None:\n author_tag = etree.Element('author')\n author_tag.text = author\n comment_tag.append(author_tag)\n item.append(comment_tag)\n\n if 'related_works' in data:\n for related_work in data['related_works']:\n item.append(related_work)\n return item\n\n\ndef get_file_data(data: dict, folder='works') -> dict:\n file_data = {}\n filename = data.get('названия файла')\n file_root = etree.fromstring(ut.read_xml(Path(ut.REPO_TEXTS_PATH, folder, filename), 'rb'))\n try:\n creation_tag = file_root.xpath('//ns:creation', namespaces={'ns': ut.xmlns_namespace})[0]\n date_tag = deepcopy(creation_tag[0])\n date_tag.set('type', 'action')\n file_data['date_tag'] = date_tag\n except IndexError:\n pass\n labels = [t.get('ana') for t in file_root.xpath('//ns:catRef', namespaces={'ns': ut.xmlns_namespace})\n if t.get('ana') != '#main']\n catrefs = {\n 'sphere': file_root.xpath('//ns:catRef[@target=\"sphere\"]', namespaces={'ns': ut.xmlns_namespace})[0].attrib.get('ana'),\n 'genre': file_root.xpath('//ns:catRef[@target=\"genre\"]', namespaces={'ns': ut.xmlns_namespace})[0].attrib.get('ana'),\n 'published': file_root.xpath('//ns:catRef[@target=\"published\"]', namespaces={'ns': ut.xmlns_namespace})[0].attrib.get('ana'),\n }\n try:\n catrefs['topic'] = file_root.xpath('//ns:catRef[@target=\"topic\"]', namespaces={'ns': ut.xmlns_namespace})[0].attrib.get('ana')\n except IndexError:\n pass\n\n file_data['labels'] = labels\n file_data['catrefs'] = catrefs\n return file_data\n\n\ndef is_nan(value) -> bool:\n if any(\n [\n isinstance(value, str) and value == 'nan',\n isinstance(value, float) and math.isnan(value),\n ]\n ):\n return True\n return False\n\n\ndef create_related_item(row_data: dict, file_data: dict, taxonomy: list[dict]) -> etree._Element:\n related_item_tag = etree.Element('relatedItem')\n ref_tag = etree.Element('ref')\n ref_tag.text = row_data.get('id файлов')\n related_item_tag.append(ref_tag)\n\n title_tag = etree.Element('title')\n title = row_data.get(' название').rstrip(' ')\n if not is_nan(row_data.get('main')):\n title = row_data.get('НАЗВАНИЕ СЕМЬИ').rstrip(' ')\n title_tag.text = title\n if not is_nan(row_data['название дано редакторами (сверять по списку 91 тома)']):\n title_tag.set('resp', 'volume_editor')\n related_item_tag.append(title_tag)\n\n title_appendix = row_data.get('дополнение к названию')\n if not is_nan(title_appendix):\n title_tag.set('type', 'main')\n subtitle_tag = etree.Element('title', type='sub')\n if not is_nan((row_data['подзагловок дан редактором'])):\n subtitle_tag.set('resp', 'volume_editor')\n subtitle_tag.text = title_appendix.rstrip(' ')\n related_item_tag.append(subtitle_tag)\n\n # add bibliography tag\n bibliography = row_data.get('БИБЛ = итог + страницы = cured')\n bibl_tag = etree.Element('title', type='bibl')\n if bibliography:\n related_item_tag.append(bibl_tag)\n bibl_tag.text = bibliography\n\n if file_data['is_main']:\n date_tag = deepcopy(file_data['date_tag'])\n if 'when' in date_tag.attrib:\n date_tag.text = date_tag.attrib['when']\n elif 'from' in date_tag.attrib:\n date_tag.text = f'{date_tag.attrib[\"from\"]}-{date_tag.attrib[\"to\"]}'\n else:\n pass\n related_item_tag.append(date_tag)\n\n if file_data['is_main'] or row_data.get('ID связанного произвдения)') in MULTIVOLUME_WORKS:\n volume_tag = etree.Element('volume')\n volume = str(int(row_data.get('volume')))\n volume_tag.text = volume\n related_item_tag.append(volume_tag)\n\n ana_value = ' '.join(f'{v}' for v in file_data['labels'])\n if file_data['is_main']:\n ana_value = f'#main {ana_value}'\n ana_value = set_ana_value_from_new_taxonomy([i.strip('#') for i in ana_value.split()], taxonomy)\n ref_tag.set('ana', ana_value)\n return related_item_tag\n\n\ndef set_ana_value_from_new_taxonomy(catrefs: list, taxonomies: list[dict]) -> str:\n new_catrefs = txnm.old_catrefs_to_new_catrefs(catrefs, taxonomies)\n return ' '.join([f'#{i}' for i in new_catrefs])\n\n\ndef get_volume_and_pages_range_from_text_id(text_id: str) -> tuple[int, int, int]:\n parts = text_id.split('_')\n volume, left, right = int(parts[0].strip('v')), int(parts[1]), int(parts[2])\n return volume, left, right\n\n\ndef is_date_intersection(comment_date: str, date_tag: etree._Element) -> bool:\n if isinstance(comment_date, float) or isinstance(comment_date, int):\n comment_date = str(int(comment_date))\n comment_dates = [int(date.strip(' ')) for date in comment_date.split(',')]\n work_dates = []\n if 'when' in date_tag.attrib:\n when = date_tag.get('when')\n work_dates.append(int(when))\n if 'from' in date_tag.attrib and 'to' in date_tag.attrib:\n _from = date_tag.get('from')\n to = date_tag.get('to')\n work_dates.extend(range(int(_from), int(to) + 1))\n if not date_tag.attrib:\n dates = date_tag.text\n dates = dates.strip('.?г')\n dates = dates.replace('и', ',')\n dates = dates.replace('-', '—')\n dates = dates.replace('–', '—')\n dates = [d.strip() for d in dates.split(',')]\n for date in dates:\n if date.isnumeric():\n work_dates.append(date)\n elif '—' in date:\n _from, to = date.split('—')\n work_dates.extend(range(int(_from), int(to)))\n for date in comment_dates:\n if date in work_dates:\n return True\n return False\n\n\ndef add_comments_to_bibllist(sheet_path: Path, bibllist_items: dict) -> None:\n df = pd.read_excel(sheet_path, sheet_name='Comments')\n df = df.dropna(subset=['ID файла'])\n for row in df.iterrows():\n row_data = row[1]\n category = row_data.get('категория комментария')\n if is_nan(category) or 'comments_works' not in category:\n continue\n work_ids = row_data.get('ID связанного произведения (семьи)')\n if is_nan(work_ids):\n continue\n work_ids = [w_id.strip(' ') for w_id in work_ids.split(', ')]\n for work_id in work_ids:\n file_id = row_data.get('ID файла')\n title = row_data.get('Имя файла для карточки и справочника')\n author = row_data.get('автор комментария')\n bibliography = row_data.get('БИБЛ = ИТОГ')\n if is_nan(author):\n author = None\n data = {\n 'file_id': file_id,\n 'title': title,\n 'author': author,\n 'category': category,\n 'bibliography': bibliography\n }\n try:\n bibllist_items[work_id]['comments'].append(data)\n except KeyError:\n try:\n bibllist_items[work_id]['comments'] = [data]\n except KeyError: # Novaja_Azbuka\n print(work_id)\n pass\n\n for row in df.iterrows():\n row_data = row[1]\n category = row_data.get('категория комментария')\n if is_nan(category) and 'comments_works' in category:\n continue\n comment_date = row_data.get('год для произведения')\n if is_nan(comment_date):\n continue\n\n file_id = row_data.get('ID файла')\n title = row_data.get('Имя файла для карточки и справочника')\n author = row_data.get('автор комментария')\n bibliography = row_data.get('БИБЛ = ИТОГ')\n if is_nan(author):\n author = None\n data = {\n 'file_id': file_id,\n 'title': title,\n 'author': author,\n 'category': category,\n 'bibliography': bibliography\n }\n\n for work_id, family in bibllist_items.items():\n try: # Ошибки там, где нет крестиков\n date_tag = family['date_tag']\n except KeyError:\n print(work_id)\n continue\n if is_date_intersection(comment_date, date_tag):\n try:\n bibllist_items[work_id]['comments'].append(data)\n except KeyError:\n try:\n bibllist_items[work_id]['comments'] = [data]\n except KeyError:\n print(work_id)\n pass\n\n\ndef create_related_works(row_data: dict, work_id: str) -> list[etree.Element]:\n work_id_raw = row_data.get('связанные произведения')\n work_ids = [w_id.strip(' ') for w_id in work_id_raw.split(',')]\n related_works = []\n for w_id in work_ids:\n related_item = etree.Element('relatedItem')\n ref = etree.Element('ref', ana='related_works')\n ref.text = w_id\n related_item.append(ref)\n related_works.append(related_item)\n return related_works\n\n\ndef fix_unconventional_dates(root: etree._Element) -> None:\n date_tags = root.xpath('//ns:date', namespaces={'ns': ut.xmlns_namespace})\n for tag in date_tags:\n text = tag.text\n if text is not None:\n if re.search(r'^\\s*\\d{4}\\s*$', text):\n continue\n if re.search(r'^\\s*\\d{4}-\\d{4}\\s*$', text):\n continue\n years = [i.group() for i in re.finditer(r'\\d{4}', tag.text)]\n years.sort(key=int)\n if len(years) == 1:\n tag.text = years[0]\n tag.set('when', years[0])\n else:\n first_date, last_date = years[0], years[-1]\n tag.text = f'{first_date}-{last_date}'\n tag.set('from', first_date)\n tag.set('to', last_date)\n\n\ndef main():\n root = etree.fromstring(ut.read_xml(CATALOGUE_PATH, 'rb'))\n list_tag = root.xpath('//ns:list', namespaces={'ns': ut.xmlns_namespace})[0]\n df = pd.read_excel(WORKS_SHEET_PATH, sheet_name='Works', header=1)\n df = df.dropna(subset=['volume'])\n annotations_df = pd.read_excel(ANNOTATIONS_SHEETS_PATH, sheet_name='Произведения')\n bibllist_items = {}\n taxonomy = txnm.get_taxonomy_as_dict(TAXONOMY_PATH)\n new_taxonomy = txnm.get_taxonomy_as_dict(NEW_TAXONOMY_PATH)\n for row in df.iterrows():\n row_data = row[1]\n filename = row_data.get(\"названия файла\")\n if is_nan(filename) or filename == 'названия файла':\n continue\n\n work_id_raw = row_data.get('ID связанного произвдения)')\n\n work_ids = [w_id.strip(' ') for w_id in work_id_raw.split(',')]\n for work_id_index, work_id in enumerate(work_ids):\n # Фекла сказала выкинуть этот текст\n if work_id == 'Chastnoe_pismo_roditeljam_doktoram_i_nachalnikam_shkol_Eliza_B_Bernz':\n continue\n\n text_id = row_data.get('id файлов')\n file_data = get_file_data(row_data, 'works')\n is_main_text = not is_nan(row_data.get(' карточка (изначально - 91-том - указатель)')) # Если поле не пустое\n file_data['is_main'] = is_main_text\n related_item = create_related_item(row_data, file_data, [taxonomy, new_taxonomy])\n order = CATEGORIES_ORDER[row_data.get('finished / not finished new')]\n sorting_value = row_data.get(' название').strip(' ') # Для сортировки семей по алфавиту\n\n related_work_id = row_data.get('связанные произведения')\n try:\n if not is_nan(related_work_id):\n bibllist_items[work_id]['related_works'] = create_related_works(row_data, work_id)\n print(work_id, related_work_id)\n except KeyError:\n bibllist_items[work_id] = {}\n if not is_nan(related_work_id):\n bibllist_items[work_id]['related_works'] = create_related_works(row_data, work_id)\n print(work_id, related_work_id)\n\n try:\n bibllist_items[work_id]['related_items'].append((related_item, is_main_text, text_id, order))\n except KeyError:\n if work_id not in bibllist_items:\n bibllist_items[work_id] = {}\n bibllist_items[work_id]['related_items'] = [(related_item, is_main_text, text_id, order)]\n\n title = row_data.get('BI = OLD = точки и main')\n if (is_main_text\n ):\n bibllist_items[work_id]['title'] = title\n bibllist_items[work_id]['date_tag'] = file_data['date_tag']\n bibllist_items[work_id]['sorting_value'] = sorting_value\n bibllist_items[work_id]['catrefs'] = file_data['catrefs']\n annotation = annotations_df.loc[annotations_df['ID - технич информация'] == work_id].to_dict('records')[0]['ОПИСАНИЯ-ЗАГЛУШКИ']\n if not is_nan(annotation):\n bibllist_items[work_id]['annotation'] = annotation\n\n # Добавляем к семьям комментарии\n add_comments_to_bibllist(COMMENTS_SHEET_PATH, bibllist_items)\n\n # Сортируем внутри семьи: сначала главный текст, потом по порядку следования в томе\n for _, family in bibllist_items.items():\n family['related_items'].sort(\n key=lambda x: (-x[1], x[3], get_volume_and_pages_range_from_text_id(x[2]))\n )\n\n # Сортируем семьи по алфавиту\n families = []\n for w_id, family in bibllist_items.items():\n try:\n families.append((w_id, family['sorting_value']))\n except KeyError: # Если нет крестика в таблице, Фекла поправит\n continue\n families.sort(key=lambda x: x[1])\n\n # Cоздаем айтемы-семьи (теги)\n for work_id, _ in families:\n item = create_new_list_item(work_id, bibllist_items[work_id], [taxonomy, new_taxonomy])\n list_tag.append(item)\n\n fix_unconventional_dates(root)\n etree.indent(list_tag, space=' ', level=2)\n text = etree.tostring(root, encoding='unicode')\n RESULT_PATH.write_text(text)\n\n\nif __name__ == '__main__':\n ut.change_to_project_directory()\n main()\n","sub_path":"utils/create_bibllist.py","file_name":"create_bibllist.py","file_ext":"py","file_size_in_byte":18096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"131841499","text":"from Board import Board\nfrom CursesBoardView import CursesBoard, bgBoard\nfrom pprint import pprint\nfrom time import sleep\nfrom BGEngine import BGEngine\n\nimport curses, curses.panel\nimport logging\nimport re\nimport random\nimport copy\n\nlogging.basicConfig(filename='/tmp/curses.log',level=logging.DEBUG)\n\nclass GameController():\n def __init__(self):\n self.board = Board()\n self.board.setDefaultBoardState()\n self.initCurses()\n self.boardView = CursesBoard(self.stdscr)\n\n def setCustomBoardState(self, state, turn):\n self.board.setCustomBoardState(state, turn)\n\n def initCurses(self):\n self.stdscr = curses.initscr()\n curses.noecho()\n curses.cbreak()\n self.stdscr.keypad(True)\n\n def cleanUpCurses(self):\n curses.nocbreak()\n self.stdscr.keypad(False)\n curses.echo()\n curses.endwin()\n\n def setupBoardView(self, dice = False):\n activeDice = self.board.getActiveDice()\n self.boardView.setActiveDice(copy.deepcopy(activeDice))\n self.boardView.addBoardObj(self.board)\n if not dice:\n self.boardView.addDice(copy.deepcopy(activeDice))\n else :\n self.boardView.addDice(copy.deepcopy(dice))\n self.boardView.createBoard(self.board.getTurn())\n\n def doDiceRoll(self):\n d1 = random.randint(1,6)\n d2 = random.randint(1,6)\n if d1 == d2:\n return [d1, d2, d1, d2]\n else :\n return [d1, d2]\n\n def doMove(self, player, sourceDest) :\n source, dest = re.split('\\s', sourceDest)\n r = self.board.movePiece(player, source, dest)\n if not r :\n errors = self.board.getErrorsList()\n return False\n else :\n return True\n return True\n\n def doHumanMove(self):\n inputStr = self.boardView.getUserInput().decode('ascii').strip()\n error = False\n self.boardView.addErrorMessage('')\n if inputStr == 'q' :\n self.cleanUpCurses()\n quit()\n if re.search('^(jail|\\d{1,2})\\s(\\d{1,2}|home)$',inputStr) :\n if not self.doMove(self.board.getTurn(), inputStr):\n self.boardView.addErrorMessage(self.board.getRecentError())\n error = True\n else:\n self.boardView.addErrorMessage('Bad command. . Enter move> ')\n error = True\n return error\n\n def doComputerMove(self, move, dice, testing = False):\n error = False\n for oneMove in move:\n moveStr = \" \".join(str(i) for i in oneMove)\n logging.debug('applying move {0} to board {1} for player {2} with dice {3}'.format(oneMove, \",\".join(str(x) for x in self.board.board), str(self.board.getTurn()), dice))\n if not self.doMove(self.board.getTurn(), moveStr):\n error = True\n return error\n self.boardView.addPromptText('Computer move> {0}'.format(moveStr))\n self.setupBoardView(dice)\n if not testing:\n sleep(2.5)\n self.boardView.addPromptText(False)\n return error\n\n def gameLoop(self):\n random.seed();\n dice = self.doDiceRoll()\n self.board.setDiceRoll(copy.deepcopy(dice))\n self.setupBoardView()\n self.boardView.addPromptText('(h)uman; (c)omputer; (t)est; (q)uit?> ')\n testing = False\n computer = False\n human = False\n\n while True:\n self.setupBoardView()\n inputStr = self.boardView.getUserInput().decode('ascii').strip()\n if inputStr in ['c', 'C']:\n computer = True\n break\n elif inputStr in ['h', 'H']:\n human = True\n break\n elif inputStr in ['t', 'T']:\n testing = True\n break\n elif inputStr in ['q', 'Q']:\n self.cleanUpCurses()\n return True\n else:\n self.boardView.addPromptText('(h)uman; (c)omputer; (t)est; (q)uit?> ')\n self.boardView.addPromptText(False)\n self.setupBoardView()\n\n while True:\n if not self.board.playerHasMoveAvailable():\n self.boardView.addErrorMessage('Player {0} has no moves available with dice {1},{2}!'\\\n .format(self.boardView.returnViewPlayerFromBoardPlayer(self.board.getTurn()), dice[0], dice[1] ))\n logging.debug('No move for {0}'.format(self.board.getTurn()))\n self.board.toggleTurn()\n dice = self.doDiceRoll()\n self.board.setDiceRoll(copy.deepcopy(dice))\n self.board.clearErrors()\n self.setupBoardView()\n continue\n\n if self.board.getTurn() == 1:\n if testing:\n bgEngine = BGEngine(copy.deepcopy(self.board))\n bgEngine.addDice(copy.deepcopy(self.board.getActiveDice()))\n move = bgEngine.getMoveForPlayer(self.board.getTurn())\n if not move:\n logging.debug('FAIL getting move for board {0} for player {1} with dice {2}'.format(\",\".join(str(x) for x in self.board.board), str(self.board.getTurn()), dice))\n import pdb; pdb.set_trace()\n error = self.doComputerMove(move, dice, testing)\n else:\n error = self.doHumanMove()\n else:\n if human :\n error = self.doHumanMove()\n elif computer or testing:\n if not testing:\n sleep(1)\n bgEngine = BGEngine(copy.deepcopy(self.board))\n bgEngine.addDice(copy.deepcopy(self.board.getActiveDice()))\n move = bgEngine.getMoveForPlayer(self.board.getTurn())\n if not move:\n logging.debug('FAIL getting move for board {0} for player {1} with dice {2}'.format(\",\".join(str(x) for x in self.board.board), str(self.board.getTurn()), dice))\n import pdb; pdb.set_trace()\n error = self.doComputerMove(move, dice,testing)\n\n if not error and self.board.gameIsOver():\n self.boardView.addErrorMessage(self.board.getRecentError())\n self.board.clearErrors()\n self.boardView.addState(self.board.getBoardState())\n self.boardView.createBoard(self.board.getTurn())\n return True\n\n if not error and self.board.turnIsOver():\n self.board.toggleTurn()\n dice = self.doDiceRoll()\n self.board.setDiceRoll(copy.deepcopy(dice))\n self.boardView.addDice(copy.deepcopy(dice))\n\n self.board.clearErrors()\n self.setupBoardView(dice)\n\n\n","sub_path":"GameController.py","file_name":"GameController.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152925247","text":"#\n# Copyright 2019 The FATE 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#\nfrom flask import Flask, request\nfrom google.protobuf import json_format\n\nfrom arch.api.utils.core import json_loads\nfrom fate_flow.db.db_models import Job, DB\nfrom fate_flow.manager.tracking import Tracking\nfrom fate_flow.settings import stat_logger\nfrom fate_flow.storage.fate_storage import FateStorage\nfrom fate_flow.utils import job_utils, data_utils\nfrom fate_flow.utils.api_utils import get_json_result\nfrom federatedml.feature.instance import Instance\n\nmanager = Flask(__name__)\n\n\n@manager.errorhandler(500)\ndef internal_server_error(e):\n stat_logger.exception(e)\n return get_json_result(retcode=100, retmsg=str(e))\n\n\n@manager.route('/job/data_view', methods=['post'])\ndef job_view():\n request_data = request.json\n check_request_parameters(request_data)\n job_tracker = Tracking(job_id=request_data['job_id'], role=request_data['role'], party_id=request_data['party_id'])\n job_view_data = job_tracker.get_job_view()\n if job_view_data:\n job_metric_list = job_tracker.get_metric_list(job_level=True)\n job_view_data['model_summary'] = {}\n for metric_namespace, namespace_metrics in job_metric_list.items():\n job_view_data['model_summary'][metric_namespace] = job_view_data['model_summary'].get(metric_namespace, {})\n for metric_name in namespace_metrics:\n job_view_data['model_summary'][metric_namespace][metric_name] = job_view_data['model_summary'][\n metric_namespace].get(metric_name, {})\n for metric_data in job_tracker.get_job_metric_data(metric_namespace=metric_namespace,\n metric_name=metric_name):\n job_view_data['model_summary'][metric_namespace][metric_name][metric_data.key] = metric_data.value\n return get_json_result(retcode=0, retmsg='success', data=job_view_data)\n else:\n return get_json_result(retcode=101, retmsg='error')\n\n\n@manager.route('/component/metric/all', methods=['post'])\ndef component_metric_all():\n request_data = request.json\n check_request_parameters(request_data)\n tracker = Tracking(job_id=request_data['job_id'], component_name=request_data['component_name'],\n task_id=job_utils.generate_task_id(request_data['job_id'], request_data['component_name']),\n role=request_data['role'], party_id=request_data['party_id'])\n metrics = tracker.get_metric_list()\n all_metric_data = {}\n if metrics:\n for metric_namespace, metric_names in metrics.items():\n all_metric_data[metric_namespace] = all_metric_data.get(metric_namespace, {})\n for metric_name in metric_names:\n all_metric_data[metric_namespace][metric_name] = all_metric_data[metric_namespace].get(metric_name, {})\n metric_data, metric_meta = get_metric_all_data(tracker=tracker, metric_namespace=metric_namespace,\n metric_name=metric_name)\n all_metric_data[metric_namespace][metric_name]['data'] = metric_data\n all_metric_data[metric_namespace][metric_name]['meta'] = metric_meta\n return get_json_result(retcode=0, retmsg='success', data=all_metric_data)\n else:\n return get_json_result(retcode=0, retmsg='no data', data={})\n\n\n@manager.route('/component/metrics', methods=['post'])\ndef component_metrics():\n request_data = request.json\n check_request_parameters(request_data)\n tracker = Tracking(job_id=request_data['job_id'], component_name=request_data['component_name'],\n task_id=job_utils.generate_task_id(request_data['job_id'], request_data['component_name']),\n role=request_data['role'], party_id=request_data['party_id'])\n metrics = tracker.get_metric_list()\n if metrics:\n return get_json_result(retcode=0, retmsg='success', data=metrics)\n else:\n return get_json_result(retcode=0, retmsg='no data', data={})\n\n\n@manager.route('/component/metric_data', methods=['post'])\ndef component_metric_data():\n request_data = request.json\n check_request_parameters(request_data)\n tracker = Tracking(job_id=request_data['job_id'], component_name=request_data['component_name'],\n task_id=job_utils.generate_task_id(request_data['job_id'], request_data['component_name']),\n role=request_data['role'], party_id=request_data['party_id'])\n metric_data, metric_meta = get_metric_all_data(tracker=tracker, metric_namespace=request_data['metric_namespace'],\n metric_name=request_data['metric_name'])\n if metric_data or metric_meta:\n return get_json_result(retcode=0, retmsg='success', data=metric_data,\n meta=metric_meta)\n else:\n return get_json_result(retcode=0, retmsg='no data', data=[], meta={})\n\n\ndef get_metric_all_data(tracker, metric_namespace, metric_name):\n metric_data = tracker.get_metric_data(metric_namespace=metric_namespace,\n metric_name=metric_name)\n metric_meta = tracker.get_metric_meta(metric_namespace=metric_namespace,\n metric_name=metric_name)\n if metric_data or metric_meta:\n metric_data_list = [(metric.key, metric.value) for metric in metric_data]\n metric_data_list.sort(key=lambda x: x[0])\n return metric_data_list, metric_meta.to_dict() if metric_meta else {}\n else:\n return [], {}\n\n\n@manager.route('/component/parameters', methods=['post'])\ndef component_parameters():\n request_data = request.json\n check_request_parameters(request_data)\n job_id = request_data.get('job_id', '')\n job_dsl_parser = job_utils.get_job_dsl_parser_by_job_id(job_id=job_id)\n if job_dsl_parser:\n component = job_dsl_parser.get_component_info(request_data['component_name'])\n parameters = component.get_role_parameters()\n for role, partys_parameters in parameters.items():\n for party_parameters in partys_parameters:\n if party_parameters.get('local', {}).get('role', '') == request_data['role'] and party_parameters.get(\n 'local', {}).get('party_id', '') == request_data['party_id']:\n output_parameters = {}\n output_parameters['module'] = party_parameters.get('module', '')\n for p_k, p_v in party_parameters.items():\n if p_k.endswith('Param'):\n output_parameters[p_k] = p_v\n return get_json_result(retcode=0, retmsg='success', data=output_parameters)\n else:\n return get_json_result(retcode=102, retmsg='can not found this component parameters')\n else:\n return get_json_result(retcode=101, retmsg='can not found this job')\n\n\n@manager.route('/component/output/model', methods=['post'])\ndef component_output_model():\n request_data = request.json\n check_request_parameters(request_data)\n job_runtime_conf = job_utils.get_job_runtime_conf(job_id=request_data['job_id'], role=request_data['role'],\n party_id=request_data['party_id'])\n model_key = job_runtime_conf['job_parameters']['model_key']\n tracker = Tracking(job_id=request_data['job_id'], component_name=request_data['component_name'],\n role=request_data['role'], party_id=request_data['party_id'], model_key=model_key)\n output_model = tracker.get_output_model()\n output_model_json = {}\n for buffer_name, buffer_object in output_model.items():\n if buffer_name.endswith('Param'):\n output_model_json = json_format.MessageToDict(buffer_object, including_default_value_fields=True)\n if output_model_json:\n pipeline_output_model = tracker.get_output_model_meta()\n this_component_model_meta = {}\n for k, v in pipeline_output_model.items():\n if k.endswith('_module_name'):\n if k == '{}_module_name'.format(request_data['component_name']):\n this_component_model_meta['module_name'] = v\n else:\n k_i = k.split('.')\n if '.'.join(k_i[:-1]) == request_data['component_name']:\n this_component_model_meta[k] = v\n return get_json_result(retcode=0, retmsg='success', data=output_model_json, meta=this_component_model_meta)\n else:\n return get_json_result(retcode=0, retmsg='no data', data={})\n\n\n@manager.route('/component/output/data', methods=['post'])\ndef component_output_data():\n request_data = request.json\n check_request_parameters(request_data)\n tracker = Tracking(job_id=request_data['job_id'], component_name=request_data['component_name'],\n role=request_data['role'], party_id=request_data['party_id'])\n job_dsl_parser = job_utils.get_job_dsl_parser_by_job_id(job_id=request_data['job_id'])\n if not job_dsl_parser:\n return get_json_result(retcode=101, retmsg='can not new parser', data=[])\n component = job_dsl_parser.get_component_info(request_data['component_name'])\n if not component:\n return get_json_result(retcode=102, retmsg='can found component', data=[])\n output_dsl = component.get_output()\n output_data_table = tracker.get_output_data_table(output_dsl.get('data')[0])\n output_data = []\n num = 100\n data_label = False\n if output_data_table:\n for k, v in output_data_table.collect():\n if num == 0:\n break\n l = [k]\n if isinstance(v, Instance):\n if v.label is not None:\n l.append(v.label)\n data_label = True\n l.extend(data_utils.dataset_to_list(v.features))\n else:\n l.extend(data_utils.dataset_to_list(v))\n output_data.append(l)\n num -= 1\n if output_data:\n output_data_meta = FateStorage.get_data_table_meta_by_instance(output_data_table)\n schema = output_data_meta.get('schema', {})\n header = [schema.get('sid_name', 'sid')]\n if data_label:\n header.append(schema.get('label_name'))\n header.extend(schema.get('header', []))\n return get_json_result(retcode=0, retmsg='success', data=output_data, meta={'header': header})\n else:\n return get_json_result(retcode=0, retmsg='no data', data=[])\n\n\ndef check_request_parameters(request_data):\n with DB.connection_context():\n if 'role' not in request_data and 'party_id' not in request_data:\n jobs = Job.select(Job.f_runtime_conf).where(Job.f_job_id == request_data.get('job_id', ''),\n Job.f_is_initiator == 1)\n if jobs:\n job = jobs[0]\n job_runtime_conf = json_loads(job.f_runtime_conf)\n job_initiator = job_runtime_conf.get('initiator', {})\n role = job_initiator.get('role', '')\n party_id = job_initiator.get('party_id', 0)\n request_data['role'] = role\n request_data['party_id'] = party_id\n","sub_path":"fate_flow/apps/tracking_app.py","file_name":"tracking_app.py","file_ext":"py","file_size_in_byte":11879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17457416","text":"#!/usr/bin/python3\n\nimport importlib.util, glob\nfrom datetime import datetime\n\ndef loadDay(directory):\n spec = importlib.util.spec_from_file_location(\"aoc.fun\", directory + \"solution.py\")\n day = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(day)\n\n return (day.part1, day.part2)\n\ndef timeFunction(f):\n start = datetime.now()\n r = f()\n t = (datetime.now() - start).total_seconds()\n return (r,t)\n\ndef runDay(directory):\n f = loadDay(directory)\n p1 = timeFunction(f[0])\n p2 = timeFunction(f[1])\n\n return p1, p2\n\ndef main():\n print(\"\\u001b[32;1mAdvent \\u001b[34;1mof \\u001b[31;1mCode \\u001b[0m2018\")\n\n dirs = sorted(list(glob.glob(\"./day*/\")), key=lambda k: int(k.split(\"day\")[1][:-1]))\n\n for directory in dirs:\n p1,p2 = runDay(directory)\n day = directory.split(\"day\")[1][:-1]\n print(\"\\u001b[33;1mDay\", day)\n print(\"\\u001b[36;1m Part 1\")\n print(\"\\u001b[32m \", p1[0])\n print(\"\\u001b[0m \", p1[1])\n print(\"\\u001b[36;1m Part 2\")\n print(\"\\u001b[32m \", p2[0])\n print(\"\\u001b[0m \", p2[1])\n print(\"\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run-all.py","file_name":"run-all.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205796942","text":"import pymysql\nfrom tools.read_config import ReadConfig\nfrom tools.project_path import mysql_config_path\n\n\nclass HandleMysql:\n def __init__(self):\n db_config = eval(ReadConfig.get_config(mysql_config_path, 'Config', 'db_config'))\n db = pymysql.connect(db_config[\"host\"], db_config[\"user\"], db_config[\"password\"],\n db_config[\"database\"], port=db_config[\"port\"])\n self.cursor = db.cursor()\n\n def select_sql(self, sql):\n self.cursor.execute(sql)\n results = self.cursor.fetchall()\n return results\n\n def execute_sql(self, sql):\n try:\n # 执行SQL语句\n self.cursor.execute(sql)\n print('执行成功')\n # 提交修改\n self.conn.commit()\n print('修改成功')\n except Exception as e:\n # 发生错误时回滚\n self.conn.rollback()\n\n\nif __name__ == '__main__':\n sql = 'select * from jobs'\n data = HandleMysql().select_sql(sql)\n print(data)\n print(type(data))\n for i in data:\n print(i)\n","sub_path":"API_AUTO/tools/handle_mysql.py","file_name":"handle_mysql.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"279087203","text":"from __future__ import absolute_import\nfrom aiida.plugins import DataFactory\nfrom aiida.common.extendeddicts import AttributeDict\n\n\nclass ParameterParser():\n \"\"\"\n Parse the input parameters for premod.\n \"\"\"\n def __init__(self, data):\n \"\"\"Initialize with a given AiiDA Dict instance.\"\"\"\n if isinstance(data, type(DataFactory('dict')(dict={}))):\n self.data = data\n else:\n self._logger.warning(\n 'Please supply an AiiDA Dict datatype for `data`.')\n self.data = None\n\n def write(self, dst):\n \"\"\"Write the parameter file for premod at dst.\"\"\"\n with open(dst, 'w') as handler:\n data = AttributeDict(self.data.get_dict())\n handler.write('MODE_SIM=' + data.MODE_SIM + '\\n')\n handler.write('MODE_ENTITY=' + data.MODE_ENTITY + '\\n')\n handler.write('MODE_SD=' + data.MODE_SD + '\\n')\n handler.write('FILE_OUT_PPT=' + data.FILE_OUT_PPT + '\\n')\n handler.write('OUTPUT_TIMES=' + str(len(data.OUTPUT_TIMES)) + '\\n')\n # Loop over the output times\n for time in data.OUTPUT_TIMES:\n handler.write(str(time) + ' ')\n handler.write('\\n')\n #handler.write('!' + '\\n')\n handler.write('MODE_IO=' + data.MODE_IO + '\\n')\n handler.write('FILE_SOLVER=' + data.FILE_SOLVER + '\\n')\n handler.write('FILE_ALLOY=' + data.FILE_ALLOY + '\\n')\n handler.write('FILE_PROCESS=' + data.FILE_PROCESS + '\\n')\n handler.write('FILE_PHASES=' + data.FILE_PHASES + '\\n')\n handler.write('FILE_PPTLIB=' + data.FILE_PPTLIB + '\\n')\n handler.write('FILE_PPTSIM=' + data.FILE_PPTSIM + '\\n')\n","sub_path":"aiida_premod/parsers/file_parsers/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489876467","text":"from django.shortcuts import render , redirect\nfrom django.contrib import messages\nfrom .models import Post\nfrom .forms import PostForm\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n@login_required\ndef home(request):\n \n posts = Post.objects.filter(user=request.user).order_by('-published_at') \n form = PostForm()\n\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n new_post = form.save()\n new_post.user = request.user\n new_post.save()\n\n context = {\n 'posts':posts,\n 'form':form,\n 'title':'Home Page'\n }\n\n return render(request,'posts/home.html',context)\n\n@login_required\ndef UpdatePost(request,pk):\n post = Post.objects.get(id=pk)\n form = PostForm(instance=post)\n\n if request.method == 'POST':\n form = PostForm(request.POST,instance=post)\n if form.is_valid():\n form.save()\n messages.success(request,'Your task has been updated successfully')\n return redirect('/')\n\n context = {\n 'form':form\n }\n\n return render(request,'posts/update.html',context)\n\n@login_required\ndef DeletePost(request,pk):\n post = Post.objects.get(id=pk)\n\n if request.method == 'POST':\n post.delete()\n messages.warning(request,'Your task has been deleted successfully')\n return redirect('/')\n\n context = {\n 'post':post\n }\n\n return render(request,'posts/delete.html',context)\n\n","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"221956680","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom helper import one_hot_encode, get_batches\nfrom model import Network\n\n\ndef train(net, data, epochs=10, batch_size=10, seq_length=50, lr=0.001):\n clip = 5\n val_frac = 0.1\n print_every = 10\n opt = torch.optim.Adam(net.parameters(), lr=lr)\n criterion = nn.CrossEntropyLoss()\n val_idx = int(len(data) * (1-val_frac))\n data, val_data = data[:val_idx], data[val_idx:]\n if torch.cuda.is_available():\n net = net.cuda()\n counter = 0\n n_chars = len(net.chars)\n print(data)\n for e in range(epochs):\n h = net.init_hidden(batch_size)\n for x, y in get_batches(data, batch_size, seq_length):\n counter += 1\n x = one_hot_encode(x, n_chars)\n inputs = torch.from_numpy(x)\n targets = torch.from_numpy(y)\n if torch.cuda.is_available():\n inputs = inputs.cuda()\n targets = targets.long().cuda()\n h = tuple([each.data for each in h])\n net.zero_grad()\n output, h = net(inputs, h)\n loss = criterion(output, targets.view(batch_size*seq_length))\n loss.backward()\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n opt.step()\n if counter % print_every == 0:\n val_h = net.init_hidden(batch_size)\n val_losses = []\n for x, y in get_batches(val_data, batch_size, seq_length):\n x = one_hot_encode(x, n_chars)\n x = torch.from_numpy(x)\n y = torch.from_numpy(y)\n val_h = tuple([each.data for each in val_h])\n inputs, targets = x, y\n if torch.cuda.is_available():\n inputs = inputs.cuda()\n targets = targets.long().cuda()\n output, val_h = net(inputs, val_h)\n val_loss = criterion(output,\n targets.view(batch_size*seq_length))\n val_losses.append(val_loss.item())\n print('epoch: {}/{}'.format(e+1, epochs),\n 'steps: {}'.format(counter),\n 'Loss {:.4f}'.format(loss.item()),\n 'val_loss {:.4f}'.format(np.mean(val_losses)))\n\n\nwith open('data/x_files_dataset.txt', 'r') as f:\n text = f.read()\n\n\n# We need turn our data into numerical tokens\n# Neural networks can only learn from numerical data\nchars = tuple(set(text))\n# obtaining all of the unique characters being used in the text\nchars = tuple(set(text))\n\n# coverting the chars into a dictionary with the index\n# being the key, and the unique chars being the value\nint2char = dict(enumerate(chars))\n# Creating a dictionary where the we map the unique characters as key\n# the values being the digits\nchar2int = {ch: i for i, ch in int2char.items()}\n\n# Looping through the text, and pulling the interger values\n# char2int dictionary then coverting to array\n\nencoded = np.array([char2int[ch] for ch in text])\nnet = Network(chars,\n n_hidden=1024,\n n_layers=2,\n drop_prob=0.5,\n lr=0.001)\n\nbatch_size = 128\nseq_length = 250\nn_epochs = 70\ntrain(net, encoded,\n epochs=n_epochs,\n batch_size=batch_size,\n seq_length=seq_length)\n\n\nmodel_name = \"rnn_70_epochs.net\"\ncheckpoint = {\"n_hidden\": net.n_hidden,\n \"n_layers\": net.n_layers,\n \"state_dict\": net.state_dict(),\n \"tokens\": net.chars}\n\nwith open(\"weights/\"+model_name, mode=\"wb\") as f:\n torch.save(checkpoint, f)\n\n\ndef predict(net, char, h=None, top_k=None):\n x = np.array([[net.char2int[char]]])\n x = one_hot_encode(x, len(net.chars))\n inputs = torch.from_numpy(x)\n if torch.cuda.is_available():\n inputs = inputs.cuda()\n h = tuple([each.data for each in h])\n out, h = net(inputs, h)\n p = F.softmax(out, dim=1).data\n if torch.cuda.is_available():\n p = p.cpu()\n if top_k is None:\n top_ch = np.arange(len(net.chars))\n else:\n p, top_ch = p.topk(top_k)\n top_ch = top_ch.numpy().squeeze()\n p = p.numpy().squeeze()\n char = np.random.choice(top_ch, p=p/p.sum())\n return net.int2char[char], h\n\n\ndef sample(net=net, size=2000, prime='Mulder', top_k=3):\n if torch.cuda.is_available():\n net.cuda()\n else:\n net.cpu()\n chars = [ch for ch in prime]\n h = net.init_hidden(1)\n for ch in prime:\n char, h = predict(net, ch, h, top_k=top_k)\n chars.append(char)\n for i in range(size):\n char, h = predict(net, char[-1], h, top_k=top_k)\n chars.append(char)\n return ''.join(chars)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"593021896","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 24 16:27:00 2020\r\n\r\n@author: Priyanka\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd \r\ndata=pd.read_csv(\"C://Users//Priyanka//Desktop//iris.csv\")\r\nprint(data)\r\nX=data.drop(columns=[\"Species_name\", \"Species_No\",\"Unnamed: 0\"])\r\ny=data[\"Species_name\"]\r\nfrom sklearn.ensemble import ExtraTreesClassifier\r\nbest_feat=ExtraTreesClassifier()\r\nmodel=best_feat.fit(X,y)\r\n\r\nfeature_imp=model.feature_importances_\r\nprint(feature_imp)\r\nmodel_feat=pd.Series(feature_imp,index=X.columns)\r\nimport matplotlib.pyplot as plt\r\nmodel_feat.plot(kind=\"barh\")\r\nplt.show()","sub_path":"feature importance.py","file_name":"feature importance.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"265913529","text":"\"\"\"Dell Telnet Driver.\"\"\"\nfrom __future__ import unicode_literals\nfrom netmiko.cisco_base_connection import CiscoSSHConnection\nfrom netmiko.ssh_exception import NetMikoAuthenticationException\n\nimport time\nimport re\n\n\nclass DellPowerConnectTelnet(CiscoSSHConnection):\n def disable_paging(self, command=\"terminal length 0\", delay_factor=1):\n print(\"MADE IT HERE:\")\n \"\"\"Must be in enable mode to disable paging.\"\"\"\n self.enable()\n debug = True\n delay_factor = self.select_delay_factor(delay_factor)\n time.sleep(delay_factor * .1)\n self.clear_buffer()\n command = self.normalize_cmd(command)\n if debug:\n print(\"In disable_paging\")\n print(\"Command: {}\".format(command))\n self.write_channel(command)\n output = self.read_until_prompt()\n if self.ansi_escape_codes:\n output = self.strip_ansi_escape_codes(output)\n if debug:\n print(output)\n print(\"Exiting disable_paging\")\n return output\n\n def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>',\n username_pattern=r\"User:\", pwd_pattern=r\"assword\",\n delay_factor=1, max_loops=60):\n \"\"\"Telnet login. Can be username/password or just password.\"\"\"\n TELNET_RETURN = '\\r\\n'\n\n delay_factor = self.select_delay_factor(delay_factor)\n time.sleep(1 * delay_factor)\n\n output = ''\n return_msg = ''\n i = 1\n while i <= max_loops:\n try:\n output = self.read_channel()\n return_msg += output\n\n # Search for username pattern / send username\n if re.search(username_pattern, output):\n self.write_channel(self.username + TELNET_RETURN)\n time.sleep(1 * delay_factor)\n output = self.read_channel()\n return_msg += output\n\n # Search for password pattern / send password\n if re.search(pwd_pattern, output):\n self.write_channel(self.password + TELNET_RETURN)\n time.sleep(.5 * delay_factor)\n output = self.read_channel()\n return_msg += output\n if pri_prompt_terminator in output or alt_prompt_terminator in output:\n return return_msg\n\n # Check if proper data received\n if pri_prompt_terminator in output or alt_prompt_terminator in output:\n return return_msg\n\n self.write_channel(TELNET_RETURN)\n time.sleep(.5 * delay_factor)\n i += 1\n except EOFError:\n msg = \"Telnet login failed: {0}\".format(self.host)\n raise NetMikoAuthenticationException(msg)\n","sub_path":"netmiko/dell/dell_powerconnect_telnet.py","file_name":"dell_powerconnect_telnet.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"270955377","text":"# Create your views here.\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse, HttpRequest, Http404, HttpResponseRedirect\nfrom django.template import RequestContext\nimport forms, models\n\n@login_required(login_url = \"/account/login\")\ndef deadline_top(request):\n\t\"\"\"toppage of Dline\"\"\"\n\tform = forms.DeadlineForm()\n\tif request.method == \"POST\":\n\t\tform = forms.DeadlineForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tvalues = form.cleaned_data\n\t\t\tvalues['user'] = request.user\n\t\t\tif values['d_id'] == \"\":\n\t\t\t\tmodels.add_deadline(values)\n\t\t\telse:\n\t\t\t\tmodels.modify_deadline(values['d_id'], values)\n\tdeadlines = sorted(models.get_D_from_user(request.user), key=lambda x: x.urgent_rate)[::-1]\n\tcontext = {\n\t\t'form' : form,\n\t\t'deadlines' : deadlines,\n\t\t'user': request.user,\n\t}\n\treturn render_to_response(\"deadline_top.html\", context, context_instance = RequestContext(request) )\n\n@login_required(login_url = \"/account/login\")\ndef delete_deadline(request, d_id):\n\t\"\"\"Delete a schedule from http request\"\"\"\n\tmodels.delete_deadline(d_id)\n\treturn HttpResponseRedirect('/deadline/')\n\t\n@login_required(login_url = \"/account/login\")\ndef achieve_deadline(request, d_id):\n\t\"\"\"Achieve a schedule from http request\"\"\"\n\tmodels.achieve_deadline(d_id)\n\treturn HttpResponseRedirect('/deadline/')\n","sub_path":"deadlines/apps/dline/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262399948","text":"#-*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom .Station import STN\nfrom scipy.spatial import cKDTree\nimport SparseConeQP as sp\nfrom matutils import dmultl, dmultr\nfrom timeutils import generateRegularTimeArray\nimport tsinsar as ts\nimport sys, os\n\nfrom .TimeSeries import TimeSeries\n\n\nclass GPS(TimeSeries):\n \"\"\"\n Class to hold GPS station data and perform inversions\n \"\"\"\n \n statDict = None\n\n def __init__(self, name='gps', stnfile=None, datformat=None, **kwargs):\n \"\"\"\n Initiate GPS structure with station list\n \"\"\"\n # Initialize the parent class\n super().__init__(name=name, stnfile=stnfile, dtype='gps', **kwargs)\n\n self.datformat = datformat\n return\n\n \n def read_data(self, gpsdir, fileKernel='CleanFlt', dataFactor=1000.0):\n \"\"\"\n Reads GPS data and convert to mm\n \"\"\"\n self.stns = []\n lon = []; lat = []; elev = []; name = []\n # If the list of stations/coordinates have already been set, loop over them\n if self.nstat > 0:\n for ii in range(self.nstat):\n stn = STN(self.name[ii], gpsdir, format=self.datformat,\n fileKernel=fileKernel, dataFactor=dataFactor)\n if stn.success:\n self.stns.append(stn)\n lon.append(self.lon[ii])\n lat.append(self.lat[ii])\n elev.append(self.elev[ii])\n name.append(self.name[ii])\n\n # If not, we loop over the files listed in gpsdir, and pull the coordinates\n # from the header\n else:\n for root, dirs, files in os.walk(gpsdir):\n for fname in files:\n if fileKernel not in fname:\n continue\n statname = fname[:4].lower()\n stn = STN(statname, gpsdir, format=self.datformat,\n fileKernel=fileKernel, dataFactor=dataFactor, getcoords=True)\n self.stns.append(stn)\n lon.append(stn.lon)\n lat.append(stn.lat)\n elev.append(stn.elev)\n name.append(statname)\n \n # Save coordinates and names to self \n for key, value in (('lon', lon), ('lat', lat), ('elev', elev), ('name', name)):\n setattr(self, key, value)\n self.nstat = len(name)\n return\n\n\n def preprocess(self, hdrformat='filt', dataFactor=1000.0):\n \"\"\"\n Preprocess the data to remove any known offsets as listed in the \n Sopac header file. Only for Sopac data formats\n \"\"\"\n\n # Don't do anything if we're not using Sopac\n if self.datformat != 'sopac':\n return\n\n if hdrformat == 'filt':\n csopac = ts.sopac.sopac\n elif hdrformat == 'trend':\n csopac = sopac\n\n # Loop through stations\n print('Preprocessing for realz')\n for stn in self.stns:\n smodel = csopac(stn.fname)\n components = [smodel.north, smodel.east, smodel.up]\n data = [stn.north, stn.east, stn.up]\n # Loop through components\n for ii in range(len(data)):\n comp = components[ii]\n # Get representation for offset\n frep = comp.offset\n if len(frep) < 1:\n continue\n rep = []; amp = []\n for crep in frep:\n print(stn.fname, crep.rep, crep.amp)\n rep.append(crep.rep)\n amp.append(crep.amp)\n # Construct design matrix\n plt.plot(stn.tdec, data[ii], 'o')\n G = np.asarray(ts.Timefn(rep, stn.tdec)[0], order='C')\n amp = dataFactor * np.array(amp)\n # Compute modeled displacement and remove from data\n fit = np.dot(G, amp)\n data[ii] -= fit\n #plt.plot(stn.tdec, data[ii], 'or')\n #plt.show()\n\n\n def resample(self, interp=False, t0=None, tf=None):\n \"\"\"\n Resample GPS data to a common time array\n \"\"\"\n\n # Loop through stations to find bounding times\n tmin = 1000.0\n tmax = 3000.0\n for stn in self.stns:\n tmin_cur = stn.tdec.min()\n tmax_cur = stn.tdec.max()\n if tmin_cur > tmin:\n tmin = tmin_cur\n if tmax_cur < tmax:\n tmax = tmax_cur\n\n refflag = False\n if t0 is not None and tf is not None:\n refflag = True\n tref = generateRegularTimeArray(t0, tf)\n days = tref.size\n tree = cKDTree(tref.reshape((days,1)), leafsize=2*days)\n else:\n tref = generateRegularTimeArray(tmin, tmax)\n days = tref.size\n\n # Retrieve data that lies within the common window\n for stn in self.stns:\n if interp:\n stn.north = np.interp(tref, stn.tdec, stn.north)\n stn.east = np.interp(tref, stn.tdec, stn.east)\n stn.up = np.interp(tref, stn.tdec, stn.up)\n stn.tdec = tref.copy()\n elif t0 is not None and tf is not None:\n north = np.nan * np.ones_like(tref)\n east = np.nan * np.ones_like(tref)\n up = np.nan * np.ones_like(tref)\n dn = np.nan * np.ones_like(tref)\n de = np.nan * np.ones_like(tref)\n du = np.nan * np.ones_like(tref)\n for i in range(stn.tdec.size):\n if stn.tdec[i] < t0 or stn.tdec[i] > tf:\n continue\n nndist, ind = tree.query(np.array([stn.tdec[i]]), k=1, eps=1.0)\n north[ind] = stn.north[i]\n east[ind] = stn.east[i]\n up[ind] = stn.up[i]\n dn[ind] = stn.sn[i]\n de[ind] = stn.se[i]\n du[ind] = stn.su[i]\n stn.tdec, stn.north, stn.east, stn.up = tref, north, east, up\n stn.sn, stn.se, stn.su = dn, de, du\n else:\n bool = (stn.tdec >= tmin) & (stn.tdec <= tmax)\n stn.north = stn.north[bool]\n stn.east = stn.east[bool]\n stn.up = stn.up[bool]\n stn.tdec = stn.tdec[bool]\n\n\n def extended_spinvert(self, tdec, repDict, penalty, cutoffDict, maxiter=4,\n outlierThresh=1.0e6):\n \"\"\"\n Performs sparse inversion of model coefficients on each component. Each\n station will have its own time representation and its own cutoff.\n \"\"\"\n # Loop over the stations\n mDicts = {}\n for statname, stat in self.statGen:\n\n # Construct a G matrix\n Gref = np.asarray(ts.Timefn(repDict[statname], tdec-tdec[0])[0], order='C')\n ndat,Npar = Gref.shape\n refCutoff = cutoffDict[statname]\n\n # Loop over the components\n mDict = {}\n for comp, w_comp in [('east','w_e'), ('north','w_n'), ('up','w_u')]:\n\n #if comp in ['east', 'north']:\n # G = Gref[:,4:]\n # cutoff = refCutoff - 4\n #else:\n # G = Gref\n # cutoff = refCutoff\n cutoff = refCutoff\n G = Gref\n\n # Get finite data\n dat = (getattr(stat, comp)).copy()\n ind = np.isfinite(dat)\n dat = dat[ind]\n wgt = getattr(stat, w_comp)[ind]\n\n # Instantiate a solver\n solver = sp.BaseOpt(cutoff=cutoff, maxiter=maxiter, weightingMethod='log')\n\n # Perform estimation\n m = solver.invert(dmultl(wgt, G[ind,:]), wgt*dat, penalty)[0]\n\n # Do one pass to remove outliers\n fit = np.dot(G, m)\n raw_dat = getattr(stat, comp)\n misfit = np.abs(raw_dat - fit)\n ind = misfit > outlierThresh\n if ind.nonzero()[0].size > 1:\n print('Doing another pass to remove outliers')\n raw_dat[ind] = np.nan\n finiteInd = np.isfinite(raw_dat)\n dat = raw_dat[finiteInd]\n wgt = getattr(stat, w_comp)[finiteInd]\n m = solver.invert(dmultl(wgt, G[finiteInd,:]), wgt*dat, penalty)[0]\n\n #if comp in ['east', 'north']:\n # m = np.hstack((np.zeros((4,)), m))\n mDict[comp] = m\n mDicts[statname] = (mDict, G)\n\n return mDicts\n\n# end of file\n","sub_path":"GPS.py","file_name":"GPS.py","file_ext":"py","file_size_in_byte":8758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"231619006","text":"import sqlite3\nimport exploretrial\n\ndef checking():\n conn = sqlite3.connect('base.db')\n c = conn.cursor()\n\n c.execute(\"SELECT st1_regno FROM base_attendance\")\n\n l = []\n for i in c.fetchall():\n l.append(list(i)[0])\n\n return l\n","sub_path":"checkstud.py","file_name":"checkstud.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"285111193","text":"import pygame\n# from pygame.rect import Rect\nfrom gameengine.util.Vector2 import Vector2\n\nfrom gameengine.core.Sprite import Sprite\nfrom gameengine.util.Rect import Rect\nfrom gameengine.util.util import scaleRect\n\nzoom = 2\n\nbigMarioSize = Vector2(16, 32)\nsmallMarioSize = Vector2(16, 16)\nblockSize1 = Vector2(16, 16)\nblockSize2 = Vector2(16, 32)\nitemSize = Vector2(16, 16)\nenemySize1 = Vector2(16, 16)\nenemySize2 = Vector2(16, 24)\n\nbgOverworldSurface = pygame.image.load(\"sprites/bgOverworld.png\").convert_alpha()\nbgOverworldSurface = pygame.transform.scale(bgOverworldSurface, (bgOverworldSurface.get_width() * zoom, bgOverworldSurface.get_height() * zoom))\n\nplayerSheet = pygame.image.load(\"sprites/player.png\").convert_alpha()\nplayerSheet = pygame.transform.scale(playerSheet, (playerSheet.get_width() * zoom, playerSheet.get_height() * zoom))\n\nplayerSprites = {\n \"small\": {\n \"stand\": Sprite(playerSheet, [scaleRect(Rect(80, 34, *smallMarioSize), zoom)], -1),\n\n \"walk\": Sprite(playerSheet, [scaleRect(Rect(97, 34, *smallMarioSize), zoom),\n scaleRect(Rect(114, 34, *smallMarioSize), zoom),\n scaleRect(Rect(131, 34, *smallMarioSize), zoom)], 100),\n\n \"break\": Sprite(playerSheet, [scaleRect(Rect(148, 34, *smallMarioSize), zoom)], -1),\n\n \"jump\": Sprite(playerSheet, [scaleRect(Rect(165, 34, *smallMarioSize), zoom)], -1),\n\n \"crouch\": Sprite(playerSheet, [scaleRect(Rect(80, 34, *smallMarioSize), zoom)], -1),\n\n \"dying\": Sprite(playerSheet, [scaleRect(Rect(182, 34, *smallMarioSize), zoom)], -1)\n },\n\n \"big\": {\n \"stand\": Sprite(playerSheet, [scaleRect(Rect(80, 1, *bigMarioSize), zoom)], -1),\n\n \"walk\": Sprite(playerSheet, [scaleRect(Rect(97, 1, *bigMarioSize), zoom),\n scaleRect(Rect(114, 1, *bigMarioSize), zoom),\n scaleRect(Rect(131, 1, *bigMarioSize), zoom)], 100),\n\n \"break\": Sprite(playerSheet, [scaleRect(Rect(148, 1, *bigMarioSize), zoom)], -1),\n\n \"jump\": Sprite(playerSheet, [scaleRect(Rect(165, 1, *bigMarioSize), zoom)], -1),\n\n \"crouch\": Sprite(playerSheet, [scaleRect(Rect(182, 1, *bigMarioSize), zoom)], -1)\n }\n}\n\n\n\ntilesetSheet = pygame.image.load(\"sprites/tileset.png\").convert_alpha()\ntilesetSheet = pygame.transform.scale(tilesetSheet, (tilesetSheet.get_width() * zoom, tilesetSheet.get_height() * zoom))\n\ntilesetSprites = {\n \"ground\": Sprite(tilesetSheet, [scaleRect(Rect(0, 0, *blockSize1), zoom)], -1),\n\n \"bill_blaster\": Sprite(tilesetSheet, [scaleRect(Rect(144, 0, *blockSize2), zoom)], -1),\n\n \"pipeHead\": Sprite(tilesetSheet, [scaleRect(Rect(0, 128, 32, 16), zoom)], -1),\n\n \"pipeBody\": Sprite(tilesetSheet, [scaleRect(Rect(2, 144, 28, 16), zoom)], -1),\n\n \"hard\": Sprite(tilesetSheet, [scaleRect(Rect(0, 16, *blockSize1), zoom)], -1)\n}\n\nblocksSheet = pygame.image.load(\"sprites/blocks.png\").convert_alpha()\nblocksSheet = pygame.transform.scale(blocksSheet, (blocksSheet.get_width() * zoom, blocksSheet.get_height() * zoom))\n\nblocksSprites = {\n \"brick\": {\n \"normal\": Sprite(blocksSheet, [scaleRect(Rect(272, 112, *blockSize1), zoom)], -1),\n\n \"hit_empty\": Sprite(blocksSheet, [scaleRect(Rect(288, 112, *blockSize1), zoom)], -1),\n\n \"pieces\": {\n \"1\": Sprite(blocksSheet, [scaleRect(Rect(304, 112, 8, 8), zoom)], -1),\n\n \"2\": Sprite(blocksSheet, [scaleRect(Rect(312, 112, 8, 8), zoom)], -1),\n\n \"3\": Sprite(blocksSheet, [scaleRect(Rect(304, 120, 8, 8), zoom)], -1),\n\n \"4\": Sprite(blocksSheet, [scaleRect(Rect(312, 120, 8, 8), zoom)], -1)\n },\n \"hit\": Sprite(blocksSheet, [scaleRect(Rect(320, 112, *blockSize1), zoom)], -1),\n\n \"hit_after\": Sprite(blocksSheet, [scaleRect(Rect(336, 112, *blockSize1), zoom)], -1)\n },\n\n \"question\": {\n \"normal\": Sprite(blocksSheet, [scaleRect(Rect(80, 112, *blockSize1), zoom),\n scaleRect(Rect(96, 112, *blockSize1), zoom),\n scaleRect(Rect(112, 112, *blockSize1), zoom),\n scaleRect(Rect(96, 112, *blockSize1), zoom),\n scaleRect(Rect(80, 112, *blockSize1), zoom),\n scaleRect(Rect(80, 112, *blockSize1), zoom)], 100),\n\n \"hit\": Sprite(blocksSheet, [scaleRect(Rect(128, 112, *blockSize1), zoom)], -1),\n\n \"hit_after\": Sprite(blocksSheet, [scaleRect(Rect(144, 112, *blockSize1), zoom)], -1)\n }\n}\n\nitemsSheet = pygame.image.load(\"sprites/items.png\").convert_alpha()\nitemsSheet = pygame.transform.scale(itemsSheet, (itemsSheet.get_width() * zoom, itemsSheet.get_height() * zoom))\n\nitemsSprites = {\n \"coin\": Sprite(itemsSheet, [scaleRect(Rect(384, 16, *itemSize), zoom),\n scaleRect(Rect(400, 16, *itemSize), zoom),\n scaleRect(Rect(416, 16, *itemSize), zoom),\n scaleRect(Rect(400, 16, *itemSize), zoom),\n scaleRect(Rect(384, 16, *itemSize), zoom),\n scaleRect(Rect(384, 16, *itemSize), zoom)], 100),\n\n \"rotatingCoin\": Sprite(itemsSheet, [scaleRect(Rect(0, 112, *itemSize), zoom),\n scaleRect(Rect(16, 112, *itemSize), zoom),\n scaleRect(Rect(32, 112, *itemSize), zoom)], 50),\n\n \"mushroom\": Sprite(itemsSheet, [scaleRect(Rect(0, 0, *itemSize), zoom)], -1),\n\n \"superStar\": Sprite(itemsSheet, [scaleRect(Rect(0, 48, *itemSize), zoom),\n scaleRect(Rect(16, 48, *itemSize), zoom),\n scaleRect(Rect(32, 48, *itemSize), zoom),\n scaleRect(Rect(48, 48, *itemSize), zoom)], 100)\n}\n\nenemiesSheet = pygame.image.load(\"sprites/enemies.png\").convert_alpha()\nenemiesSheet = pygame.transform.scale(enemiesSheet, (enemiesSheet.get_width() * zoom, enemiesSheet.get_height() * zoom))\n\nenemiesSprites = {\n \"goomba\": {\n \"walking\": Sprite(enemiesSheet, [scaleRect(Rect(0, 16, *enemySize1), zoom),\n scaleRect(Rect(16, 16, *enemySize1), zoom)], 200),\n\n \"stomped\": Sprite(enemiesSheet, [scaleRect(Rect(32, 16, *enemySize1), zoom)], -1)\n },\n\n \"koopa_troopa\": {\n \"walking\": Sprite(enemiesSheet, [scaleRect(Rect(96, 8, *enemySize2), zoom),\n scaleRect(Rect(112, 8, *enemySize2), zoom)], 200),\n\n \"stomped\": Sprite(enemiesSheet, [scaleRect(Rect(160, 16, *enemySize1), zoom)], -1),\n\n \"recovering\": Sprite(enemiesSheet, [scaleRect(Rect(160, 16, *enemySize1), zoom),\n scaleRect(Rect(176, 16, *enemySize1), zoom)], 200),\n\n \"flying\": Sprite(enemiesSheet, [scaleRect(Rect(128, 8, *enemySize2), zoom),\n scaleRect(Rect(144, 8, *enemySize2), zoom)], 200)\n },\n\n \"bullet_bill\": Sprite(enemiesSheet, [scaleRect(Rect(560, 16, *enemySize1), zoom)], -1)\n}","sub_path":"gameengine/tests/SuperMarioBros/sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":6920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571605254","text":"from nltk import TreebankWordTokenizer\n\ndoc_0 = \"The faster Harry got to the store, the faster Harry, the faster, would get home.\"\ndoc_1 = \"Harry is hairy and faster than Jill.\"\ndoc_2 = \"Jill is not as hairy as Harry.\"\n\ndocs = []\ndocs.append(doc_0)\ndocs.append(doc_1)\ndocs.append(doc_2)\n\ntokenizer = TreebankWordTokenizer()\ndoc_tokens = []\nfor doc in docs:\n doc_tokens += [sorted(tokenizer.tokenize(doc.lower()))]\n\nprint(doc_tokens)\nprint(\"length doc 0 :{}\".format(len(doc_tokens[0])))\nprint(\"length doc 0 :{}\".format(len(doc_tokens[1])))\nprint(\"length doc 0 :{}\".format(len(doc_tokens[2])))\n\nall_doc_tokens = sum(doc_tokens, [])\nprint(\"all docs tokens length:{}\".format(len(all_doc_tokens)))\nlexicon = sorted(set(all_doc_tokens))\nprint(\"lexicon tokens length:{}\".format(len(lexicon)))\n\n\nfrom collections import OrderedDict\nzero_vector = OrderedDict((token, 0) for token in lexicon)\nprint(\"zero vector:{}\".format(zero_vector))\n\nimport copy\nfrom collections import Counter\ndoc_vectors = []\nfor doc in docs:\n vec = copy.copy(zero_vector)\n tokens = tokenizer.tokenize(doc.lower())\n token_counters = Counter(tokens)\n for key, value in token_counters.items():\n # 词在文中出现的总数 / 词总数量\n vec[key] = value / len(lexicon)\n doc_vectors.append(vec)\nprint(doc_vectors)\n","sub_path":"python/nlp/chapter3/_4_docs_vector.py","file_name":"_4_docs_vector.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"202362794","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport filecmp\nimport tempfile\nfrom uuid import uuid4\n\nimport pytest\nfrom flaky import flaky\nfrom click.testing import CliRunner\n\nfrom ivona_speak.command_line import cli\n\n\n# Module fixtures\n@pytest.fixture(scope='module')\ndef auth_keys():\n \"\"\"Get working auth keys from environment variables\"\"\"\n access_key = os.environ[\"IVONA_ACCESS_KEY\"]\n secret_key = os.environ[\"IVONA_SECRET_KEY\"]\n assert access_key and secret_key\n\n return access_key, secret_key\n\n\n# Tests\n@pytest.mark.parametrize('subcommand,extra_args', [\n ('synthesize', ['-o', tempfile.NamedTemporaryFile().name, 'Hello world']),\n ('list-voices', []),\n])\ndef test_auth_keys(subcommand, extra_args):\n \"\"\"Test passing auth keys\"\"\"\n runner = CliRunner()\n\n # No keys provided\n args = [subcommand] + extra_args\n\n result = runner.invoke(cli, args)\n assert isinstance(result.exception, SystemExit)\n assert result.exit_code == 1\n\n # Wrong keys provided\n args = ([subcommand] +\n ['--access-key', str(uuid4()), '--secret-key', str(uuid4())] +\n extra_args)\n\n result = runner.invoke(cli, args)\n assert isinstance(result.exception, SystemExit)\n assert result.exit_code == 1\n\n # Incorrect auth file provided\n with tempfile.NamedTemporaryFile() as temp_file:\n args = ([subcommand] +\n ['--auth-file', temp_file.name] +\n extra_args)\n\n result = runner.invoke(cli, args)\n assert isinstance(result.exception, SystemExit)\n assert result.exit_code == 1\n\n\n@flaky\n@pytest.mark.parametrize('voice_name,voice_language,content,org_file', [\n ('Salli', 'en-US', 'Hello world', 'files/salli_hello_world.mp3'),\n ('Maja', 'pl-PL', 'Dzień dobry', 'files/maja_dzien_dobry.mp3'),\n])\ndef test_synthesize(auth_keys, voice_name, voice_language, content, org_file):\n \"\"\"Test 'synthesize' subcommand\"\"\"\n runner = CliRunner()\n\n with tempfile.NamedTemporaryFile() as temp_file:\n args = [\n 'synthesize',\n '--access-key', auth_keys[0],\n '--secret-key', auth_keys[1],\n '--output-file', temp_file.name,\n '--voice-name', voice_name,\n '--voice-language', voice_language,\n content,\n ]\n result = runner.invoke(cli, args)\n assert result.exit_code == 0\n assert result.output\n\n assert filecmp.cmp(org_file, temp_file.name)\n\n\n@flaky\ndef test_list_voices(auth_keys):\n \"\"\"Test 'list-voice' subcommand\"\"\"\n runner = CliRunner()\n\n args = ['list-voices', '--access-key', auth_keys[0], '--secret-key',\n auth_keys[1]]\n\n result = runner.invoke(cli, args)\n assert result.exit_code == 0\n assert result.output\n\n\n@flaky\ndef test_list_voices_with_filter(auth_keys):\n \"\"\"Test 'list-voice' subcommand with filter\"\"\"\n runner = CliRunner()\n\n # Correct filter\n args = [\n 'list-voices',\n '--access-key', auth_keys[0],\n '--secret-key', auth_keys[1],\n '--voice-language', 'en-US',\n ]\n\n result = runner.invoke(cli, args)\n assert result.exit_code == 0\n assert result.output\n\n # Incorrect filter\n args = [\n 'list-voices',\n '--access-key', auth_keys[0],\n '--secret-key', auth_keys[1],\n '--voice-language', str(uuid4()),\n ]\n\n result = runner.invoke(cli, args)\n assert isinstance(result.exception, SystemExit)\n assert result.exit_code == 1\n","sub_path":"ivona_speak/test/test_command_line.py","file_name":"test_command_line.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"56828889","text":"from PyQt5 import QtWidgets\nfrom autoUpdateLocalization import Ui_MainWindow\n\nimport update_services\nimport queries\nimport utils\n\n\nclass updateLocalization(QtWidgets.QMainWindow):\n def __init__(self):\n super(updateLocalization, self).__init__()\n self.ui = Ui_MainWindow() # Load ui file for main window\n self.ui.setupUi(self)\n self.anotherwindow = None\n self.bypass = False\n\n # Connect buttons\n self.ui.button_update_event.clicked.connect(self.handle_update_event)\n self.ui.button_menu.clicked.connect(self.handle_menu)\n\n # Connect type box to make price visible or not\n self.ui.choose_type.activated.connect(self.change_price_option)\n self.change_price_option()\n\n\n # Makes the price visible/invisible\n def change_price_option(self):\n option = self.ui.choose_type.currentText()\n\n # Make invisible\n if 'Adicionar' in option or 'Remover' in option:\n stylesheet = 'font: 14pt \"Cantarell\"; color: rgb(46, 52, 54);'\n else:\n stylesheet = 'font: 14pt \"Cantarell\"; color: white;'\n\n self.ui.text_price.setStyleSheet(stylesheet)\n self.ui.line_edit_price.setStyleSheet(stylesheet)\n self.ui.label_event_info.setStyleSheet(stylesheet)\n self.ui.label_cpf.setStyleSheet(stylesheet)\n self.ui.label_data.setStyleSheet(stylesheet)\n self.ui.line_edit_cpf.setStyleSheet(stylesheet)\n self.ui.date_edit.setStyleSheet(stylesheet)\n\n # Handles\n def handle_menu(self):\n self.anotherwindow = update_services.updateServices()\n self.anotherwindow.show()\n self.bypass = True\n self.close()\n return\n\n\n def handle_update_event(self):\n option = self.ui.choose_type.currentText()\n cep = self.ui.line_edit_cep.text()\n\n # Deals with empty cpf or invalid amount of digits\n if cep == \"-\" or len(cep) != 9:\n print(cep, len(cep))\n utils.warning(\"cep inválido!\")\n return\n\n if 'Adicionar' in option:\n print(\"here\")\n message = queries.localization_service(cep, create=True)\n elif 'Remover' in option:\n message = queries.localization_service(cep, create=False)\n\n else: # Update price\n date = self.ui.date_edit.date().toPyDate()\n organizer_cpf = self.ui.line_edit_cpf.text()\n price = self.ui.line_edit_price.text()\n if not price:\n utils.warning(\"Preço inválido\")\n return\n price = int(price)\n\n # Deals with empty cpf or invalid amount of digits\n if organizer_cpf == \"...\" or len(organizer_cpf) != 14:\n utils.warning(\"CPF inválido!\")\n return\n\n message = queries.update_localization_service(cep, price)\n utils.warning(message)\n\n # Overloading classes\n def closeEvent(self, event):\n utils.closeEvent(self.bypass, event)\n return\n\nif __name__ == \"__main__\":\n import sys\n APP = QtWidgets.QApplication(sys.argv)\n GUI = updateLocalization()\n GUI.show()\n sys.exit(APP.exec_())\n","sub_path":"src/update_localization.py","file_name":"update_localization.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"77055457","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n#Declaracion de las variables.\n\n#tiempo en segundos\nt=[3673,3628,3659,3652,3639,3737]\nprint(t)\n\n#posiciones cartesianas en x (km)\npx=[4,10,12,80,50,40]\nprint(px)\n\n#posiciones cartesianas en x (km)\npy=[100,5,80,50,50,200]\nprint(py)\n\ndef metropolis(t,px):\n actual=px\n MH=[]\n MH.append(actual)\n #array de pasos de MH\n for i in range(N):\n propuesta=actual+np.random.normal()*500\n #propuesta\n p=min((t(i),propuesta)/(t(i),actual),1) #verosimilitud\n alpha=np.random.random()\n if(alpha < p):\n actual = propuesta #se acepta el cambio\n MH.append(actual)\n else:\n MH.append(actual) #se rechaza el cambio\n return MH\n print (MH)\n","sub_path":".ipynb_checkpoints/BlandonValentina_final_16-checkpoint.py","file_name":"BlandonValentina_final_16-checkpoint.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"621796810","text":"n, m = list(map(int, input().split(' ')))\nrez = [0]*m*n\nindex = 0\n\nfor i in range(1, n+1):\n for j in range(1, m+1):\n a = i*j\n if a % 2 == 0:\n rez[index] = 1\n if a % 3 == 0:\n rez[index] = 2\n if a % 5 == 0:\n rez[index] = 3\n index += 1\n\nprint('RED : ', rez.count(1))\nprint('GREEN : ', rez.count(2))\nprint('BLUE : ', rez.count(3))\nprint('BLACK : ', rez.count(0))","sub_path":"Python/[0051] - [0100]/[0053] Раскраска таблицы умножения.py","file_name":"[0053] Раскраска таблицы умножения.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446749817","text":"import time\r\ncurrentTimeMillis = lambda: int(round(time.time() * 1000))\r\nbeginTime = currentTimeMillis()\r\n\r\nimport sys\r\ndef totalSize():\r\n size = 0\r\n for k in globals().keys():\r\n size += sys.getsizeof(globals()[k])\r\n return size\r\nbeginSize = totalSize()\r\nbeginSize += sys.getsizeof(beginSize)\r\n\r\na = \"\"\r\n# print(a)\r\n\r\nprint(\"Ended in: \" + str(currentTimeMillis() - beginTime) + \" ms\")\r\nprint(\"Total size: \" + str(totalSize() - beginSize) + \" bytes\")\r\n","sub_path":"do.py","file_name":"do.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365694395","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder\nfrom Instanssi.arkisto.models import OtherVideo, OtherVideoCategory\nimport urlparse\n\nclass VideoForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n # Initialize\n self.event = kwargs.pop('event', None)\n super(VideoForm, self).__init__(*args, **kwargs)\n \n # Set choices\n if self.event:\n cats = []\n for cat in OtherVideoCategory.objects.filter(event=self.event):\n cats.append((cat.id, cat.name))\n self.fields['category'].choices = cats\n \n # Set form\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Fieldset(\n u'Muu Video',\n 'name',\n 'category',\n 'description',\n 'youtube_url',\n ButtonHolder (\n Submit('submit', u'Tallenna')\n )\n )\n )\n \n def clean_youtube_url(self):\n # Make sure field has content\n if not self.cleaned_data['youtube_url']:\n return self.cleaned_data['youtube_url']\n \n # Check if we already have a valid embed url\n url = self.cleaned_data['youtube_url']\n if url.find('http://www.youtube.com/v/') == 0:\n return url\n\n # Parse querystring to find video ID\n parsed = urlparse.urlparse(url)\n qs = urlparse.parse_qs(parsed.query)\n \n # Check if the video id exists in query string\n if 'v' not in qs:\n raise ValidationError(u'Osoitteesta ei löytynyt videotunnusta.')\n \n # All done. Return valid url\n return 'http://www.youtube.com/v/'+qs['v'][0]+'/'\n \n class Meta:\n model = OtherVideo\n fields = ('category','name','description','youtube_url')\n\nclass VideoCategoryForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(VideoCategoryForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Fieldset(\n u'Kategoria',\n 'name',\n ButtonHolder (\n Submit('submit', u'Tallenna')\n )\n )\n )\n \n class Meta:\n model = OtherVideoCategory\n fields = ('name',)\n","sub_path":"Instanssi/admin_arkisto/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"226423881","text":"#!/usr/bin/env python\n#coding:utf-8\nimport subprocess\nimport re\nimport urllib2\nfrom lib import myLog\n\nclass Vnc_viewer(object):\n def __init__(self):\n self.password = \"bdzss\"\n self.urlstart = \"http://wechat-client.100mj.com/r_2/machine/message/\"\n self.urlendopen = \"/107?content=2\"\n self.urlendclose = \"/107?content=5\"\n self.log = myLog.MyLog()\n\n def start_GetPort(self,machineID):\n kai = self.urlstart+machineID+self.urlendopen #拼接生成触发URL\n request = urllib2.Request(kai) #### 以下为发送GET请求到找到的ID\n request.add_header(\"marker\",\"manager\")\n response = urllib2.urlopen(request)\n self.log.info(\"Get Responses %s\"%response)\n mod = r\"apolloserver.100mj.com:[\\d]{5}\"\n portlist = re.findall(mod, response.read())\n self.log.info(\"Match Port %s\"%str(portlist))\n return str(portlist[:1])\n\n\n def stop_Port(self,machineID):\n close = self.urlstart + machineID + self.urlendclose ####关闭远程连接接口\n request = urllib2.Request(close)\n request.add_header(\"marker\", \"manager\")\n response = urllib2.urlopen(request)\n self.log.info(\"Get Response %s\"%response)\n\n def start_Novnc(self,port):\n cmd = \"cd /root/ && sh novnc_start.sh \"+str(port)\n self.log.info(cmd)\n child = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n child.wait()\n self.log.info(\"Get start scripts response %s\"%str(child.stdout.read()))\n\n def stop_Novnc(self):\n cmd = \"cd /root/ && sh novnc_stop.sh\"\n self.log.info(cmd)\n child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n child.wait()\n self.log.info(\"Get stop script response %s\"%str(child.stdout.read()))\n\n def main_Open(self,machineid):\n port = self.start_GetPort(machineid)\n port = port.split(':')[1].split(\"'\")[0]\n self.start_Novnc(port)\n\n def main_Stop(self,machineid):\n self.stop_Novnc()\n self.stop_Port(machineid)\n\n\nif __name__ == \"__main__\":\n system = Vnc_viewer()\n port = system.start_GetPort(\"ME68EDA40F4D95\")\n port = port.split(':')[1].split(\"'\")[0]\n system.start_Novnc(port)\n\n","sub_path":"projects/noVNC/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"463603172","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.ion()\n\n#read in some data\ndfile = 'food.npz'\ndata = np.load(dfile)['arr_0']\ngrams = data[:,0]\ncost = data[:,1]\n\nplt.plot(grams,cost,'o')\nplt.xlabel('Mass (g)')\nplt.ylabel('Cost ($)')\n\n\nn = 100\ntrue_weights = np.array([[2,.5]])\n\nX = np.array([np.random.random(n), np.ones(n)]).T\nerrs = (np.random.random(n)-.5)/5\nY_meas = true_weights.dot(X.T)[0,:] + errs\n\nweights = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y_meas)\n\nprint(true_weights,weights)\n\ntest_pts = np.array([[0,1],[1,1]])\ntest_pred = weights.dot(test_pts.T)\nplt.plot(X[:,0],Y_meas, 'bo',\n test_pts[:,0],test_pred,'g-')\n\n\n\n","sub_path":"unit01/foundation.py","file_name":"foundation.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"347161210","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2016 matsumotoyasuyuki\n#\n# Distributed under terms of the MIT license.\n\n\nfrom __future__ import print_function\nimport argparse\n# import math\n# import sys\nimport os\n\nimport numpy as np\n# import matplotlib.pyplot as plt\nimport six\n\nimport chainer\nfrom chainer import cuda, optimizers, serializers\n# import chainer.functions as F\nimport chainer.links as L\n\nfrom tqdm import tqdm\n# import pickle\nimport imagenet_net as net\nimport trec_lstm as lstm\n\nparser = argparse.ArgumentParser(\n description='Predict a label for a image based on CaffeNet')\n# parser.add_argument('--initmodel', '-m', default='inet.model',\n# help='Initialize the model from given file')\n# parser.add_argument('--resume', '-r', default='inet.state',\n# help='Resume the optimization from snapshot')\nparser.add_argument('--gpu', '-g', type=int, default=-1,\n help='Zero-origin GPU ID (nevative value indicates CPU)')\nparser.add_argument('--epoch', '-e', default=1, type=int,\n help='number of epochs to learn')\n# parser.add_argument('--batchsize', '-b', type=int, default=100,\n# help='learning minibatch size')\n# parser.add_argument('--bproplen', '-l', type=int, default=35,\n# help='length of truncated BPTT')\nparser.add_argument('--gradclip', '-c', type=int, default=5,\n help='gradient norm threshold to clip')\nargs = parser.parse_args()\n\n\nHOME = os.environ['HOME']\nSTILL_MODEL_DIR = HOME + \"/mnt/concept_model/net_still_trec_vgg/\"\nFEATURE_DIR = HOME + '/mnt/iacc1/feature_vgg/'\nMODEL_DIR = HOME + \"/mnt/concept_model/net_lstm_vgg/\"\n\n# for concept_id in ['3', '5', '9', '17', '38']:\nfor concept_id in ['3']:\n\n print('concept id:' + str(concept_id))\n INFO_DIR = HOME + '/annInf/' + concept_id + '/'\n\n n_epoch = args.epoch # number of epochs\n # n_units = args.unit # number of units per layer\n # batchsize = args.batchsize # minibatch size\n # bprop_len = args.bproplen # length of truncated BPTT\n grad_clip = args.gradclip # gradient norm threshold to clip\n\n # Prepare trained net still model\n still_model = L.Classifier(net.Inet(4096, 32, 2))\n if args.gpu >= 0:\n cuda.get_device(args.gpu).use()\n still_model.to_gpu()\n xp = np if args.gpu < 0 else cuda.cupy\n inet_model = STILL_MODEL_DIR + concept_id + '_inet_trec.model'\n print('Load model from', inet_model)\n serializers.load_npz(inet_model, still_model)\n W1, W2, b1, b2 = still_model.predictor.getWeight(args.gpu)\n b1 = b1[np.newaxis, :, np.newaxis]\n b2 = b2[np.newaxis, :]\n\n # Prepare LSTM model, defined in trec_lstm.py\n vf = lstm.RNNVF(4096, 32, 2, W1, W2, b1, b2)\n model = L.Classifier(vf)\n if args.gpu >= 0:\n cuda.get_device(args.gpu).use()\n model.to_gpu()\n xp = np if args.gpu < 0 else cuda.cupy\n\n # Setup optimizer\n optimizer = optimizers.SGD(lr=1.)\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.GradientClipping(grad_clip))\n\n # Prepare dataset\n pred = []\n p_shot_features = []\n n_shot_features = []\n neg_num = 1000\n sum_accuracy = 0\n sum_loss = 0\n N_test = 0\n with open(INFO_DIR + 'pos.info') as f:\n print('Loading pos features...')\n for line in tqdm(f):\n video_id = line.split(' ')[0]\n shot_id = line.split(' ')[1]\n try:\n with open(FEATURE_DIR + video_id + '/' + shot_id + '_fc7.npy') as ff:\n features = np.load(ff)\n p_shot_features.append(np.array(features, dtype=np.float32))\n except IOError:\n pass\n\n with open(INFO_DIR + 'ranNeg.info') as f:\n print('Loading neg features...')\n negs = []\n for line in f:\n negs.append(line)\n for line in tqdm(negs[:neg_num]):\n # for line in tqdm(negs):\n video_id = line.split(' ')[0]\n shot_id = line.split(' ')[1]\n try:\n with open(FEATURE_DIR + video_id + '/' + shot_id + '_fc7.npy') as ff:\n features = np.load(ff)\n n_shot_features.append(np.array(features, dtype=np.float32))\n except IOError:\n pass\n\n pos_shot_features = np.array(p_shot_features)\n neg_shot_features = np.array(n_shot_features)\n N_pos_test = 100\n N_neg_test = 100\n N_test = N_pos_test + N_neg_test\n N_pos = int(pos_shot_features.shape[0]) - N_pos_test\n N_neg = int(neg_shot_features.shape[0]) - N_neg_test\n N = N_pos + N_neg\n train_data = {}\n test_data = {}\n test_data['pos'], train_data['pos'] = np.split(pos_shot_features, [N_pos_test])\n test_data['neg'], train_data['neg'] = np.split(neg_shot_features, [N_neg_test])\n x_train = np.r_[train_data['pos'], train_data['neg']]\n x_test = np.r_[test_data['pos'], test_data['neg']]\n y_train = np.array([0] * N_pos + [1] * N_neg, dtype=np.int32)\n y_test = np.array([0] * N_pos_test + [1] * N_neg_test, dtype=np.int32)\n\n # x = []\n # for i in x_train:\n # x.append(i.shape[0])\n # bin_lst = np.arange(0, 30)\n # plt.hist(x, bins=bin_lst)\n # plt.savefig('test.png')\n\n # Learning loop\n for epoch in six.moves.range(1, n_epoch + 1):\n print('epoch', epoch)\n\n # training\n sum_accuracy = 0\n sum_loss = 0\n sum_size = 0\n for i in tqdm(six.moves.range(N)):\n vf.reset_state()\n t = chainer.Variable(xp.asarray(np.array([y_train[i]], dtype=np.int32)))\n for j in x_train[i]:\n x = chainer.Variable(xp.asarray(np.array([xp.asarray(j)], dtype=np.float32)))\n loss = model(x, t)\n model.zerograds()\n loss.backward()\n optimizer.update()\n # optimizer.update(model, x, t)\n\n # x = chainer.Variable(xp.asarray(x_train[i]))\n size = x_train[i].shape[0]\n # sum_size += size\n sum_size += 1\n # target = np.array([y_train[i]] * size, dtype=np.int32)\n # t = chainer.Variable(xp.asarray(target))\n\n # Pass the loss function (Classifier defines it) and its arguments\n # optimizer.update(model, x, t)\n # sum_loss += float(model.loss.data) * len(t.data)\n # sum_accuracy += float(model.accuracy.data) * len(t.data)\n sum_loss += float(model.loss.data)\n sum_accuracy += float(model.accuracy.data)\n print('train mean loss={:.4f}, accuracy={:.4f}'.format(\n sum_loss / sum_size, sum_accuracy / sum_size))\n\n # evaluation\n sum_accuracy = 0\n sum_loss = 0\n model.predictor.reset_state() # initialize state\n model.predictor.train = False # dropout does nothing\n sum_size = 0\n for i in six.moves.range(N_test):\n vf.reset_state()\n t = chainer.Variable(xp.asarray(np.array([y_test[i]], dtype=np.int32)), volatile='on')\n for j in x_test[i]:\n x = chainer.Variable(xp.asarray(np.array([xp.asarray(j)], dtype=np.float32)), volatile='on')\n loss = model(x, t)\n # sum_loss += loss\n\n size = x_test[i].shape[0]\n sum_size += 1\n sum_loss += float(model.loss.data)\n sum_accuracy += float(model.accuracy.data)\n\n # x = chainer.Variable(xp.asarray(x_test[i]), volatile='on')\n # size = x_test[i].shape[0]\n # sum_size += size\n # target = np.array([y_test[i]] * size, dtype=np.int32)\n # t = chainer.Variable(xp.asarray(target), volatile='on')\n #\n # loss = model(x, t)\n # sum_loss += float(loss.data) * len(t.data)\n # sum_accuracy += float(model.accuracy.data) * len(t.data)\n print('test mean loss={:.4f}, accuracy={:.4f}'.format(\n sum_loss / sum_size, sum_accuracy / sum_size))\n\n # Save the model and the optimizer\n print('save the model')\n serializers.save_npz(MODEL_DIR + concept_id + '_lstm_trec_vgg.model', model)\n print('save the optimizer')\n serializers.save_npz(MODEL_DIR + concept_id + '_lstm_trec_vgg.state', optimizer)\n","sub_path":"net_lstm/train_lstm_trec_vgg.py","file_name":"train_lstm_trec_vgg.py","file_ext":"py","file_size_in_byte":8158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"625199929","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nhttps://leetcode.com/problems/missing-number/description/\n\nGiven an array containing n distinct numbers taken from 0, 1, 2, ..., n,\nfind the one that is missing from the array.\n\nExample 1\n\nInput: [3,0,1]\nOutput: 2\nExample 2\n\nInput: [9,6,4,2,3,5,7,0,1]\nOutput: 8\n\nNote:\nYour algorithm should run in linear runtime complexity.\nCould you implement it using only constant extra space complexity?\n\"\"\"\n\n\nclass Solution(object):\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n from __builtin__ import xrange\n\n n = len(nums) + 1\n\n total_xor = 0\n\n for num in xrange(1, n):\n total_xor ^= num\n\n local_xor = nums[0]\n\n for i in xrange(1, len(nums)):\n local_xor ^= nums[i]\n\n result = total_xor ^ local_xor\n return result\n\n def youshouldbesmart(self, nums):\n n = len(nums)\n return n * (n + 1) / 2 - sum(nums)\n\n\ndef build():\n return [9, 6, 4, 2, 3, 5, 7, 0, 1]\n\n\nif __name__ == \"__main__\":\n\n s = Solution()\n result = s.missingNumber(build())\n\n print(result)\n","sub_path":"co_ms/268_Missing_Number.py","file_name":"268_Missing_Number.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"164484758","text":"import re\n\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.shortcuts import HttpResponse\nfrom django.conf import settings\n\n\nclass RbacMiddleware(MiddlewareMixin):\n def process_request(self, request):\n '''\n 1. 拿到当前用户请求的url\n 2. 获取当前用户在session中保存的权限列表\n 3. 权限信息匹配\n '''\n current_url = request.path_info\n # 有一些权限是所有人默认都有的,不需要做权限判断,先进行一个白名单判断,如果是白名单url,就不用再走权限判断了\n valid_url_list = settings.VALID_URL_LIST\n for valid_url in valid_url_list:\n if re.match(valid_url, current_url):\n # 白名单中的url,无需权限验证\n # 返回None,继续走后续步骤\n return None\n\n url_record = [\n {'title': '首页', 'url': '#'}\n ]\n\n for url in settings.NO_PERMISSION_LIST:\n if re.match(url, request.path_info):\n # 需要登录,但无需权限校验\n request.current_selected_permission = 0\n request.breadcrumb = url_record\n\n return None\n\n permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY)\n if not permission_dict:\n # 返回 HttpResponse 不走 后续步骤,直接返回到页面\n return HttpResponse('为获取到用户权限信息')\n\n print(current_url)\n print(permission_dict)\n\n flag = False\n\n for item in permission_dict.values():\n regx = '^{}$'.format(item.get('url'))\n if re.match(regx, current_url):\n flag = True\n request.current_selected_permission = item.get('pid') or item.get('id')\n if item.get('pid'):\n # 三级路径导航\n url_record.extend([\n {'title': item.get('p_title'), 'url': item.get('p_url')},\n {'title': item.get('title'), 'url': item.get('url'), 'class': 'active'}\n ])\n else:\n url_record.extend([{'title': item.get('title'), 'url': item.get('url'), 'class': 'active'}])\n print(url_record)\n break\n request.url_record = url_record\n\n if not flag:\n return HttpResponse('无权访问')","sub_path":"rbac/rbac/middlewares/rbac.py","file_name":"rbac.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257441527","text":"\"\"\"\n给定两个仅由大写字母或小写字母组成的字符串(长度介于1到10之间),它们之间的关系是以下4中情况之一:\n1:两个字符串长度不等。比如 你好 和 你好啊\n2:两个字符串不仅长度相等,而且相应位置上的字符完全一致(区分大小写),比如 Beijing 和 Beijing\n3:两个字符串长度相等,相应位置上的字符仅在不区分大小写的前提下才能达到完全一致(也就是说,它并不满足情况2),比如 beijing 和 BEIjing\n4:两个字符串长度相等,但是即使是不区分大小写也不能使这两个字符串一致。比如 Beijing 和 Nanjing\n编程判断输入的两个字符串之间的关系属于这四类中的哪一类,给出所属的类的编号\n\"\"\"\n\ns1=str(input())\ns2=str(input())\n\nif len(s1)!=len(s2):\n print(1)\nelif s1==s2:\n print(2)\nelif s1.lower()==s2.lower():\n print(3)\nelse:\n print(4)","sub_path":"Code/CodeRecords/2984/60836/271863.py","file_name":"271863.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"301302798","text":"#!/home/usr/new/pyneng/bin/python3.6\n# -*- coding: utf-8 -*-\n'''\nЗадание 22.6\n\nЭто задание похоже на задание 22.5, но в этом задании подключения надо выполнять параллельно с помощью потоков.\nДля параллельного подключения использовать модуль concurrent.futures.\n\nВ этом упражнении нужно создать функцию send_and_parse_command_parallel:\n* она должна использовать внутри себя функцию send_and_parse_command\n* какие аргументы должны быть у функции send_and_parse_command_parallel, нужно решить самостоятельно\n* функция send_and_parse_command_parallel должна возвращать словарь, в котором:\n * ключ - IP устройства\n * значение - список словарей\n\nПроверить работу функции send_and_parse_command_parallel на команде sh ip int br.\n\n'''\n\n\nfrom task_22_5 import send_and_parse_command\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport yaml\n\nfrom pprint import pprint\n\n\n\ndef send_and_parse_command_parallel(devices_list, command, function=send_and_parse_command, limit=4,\n\t\t\t\t\t\t\tattributes='Default', index_filename='index', templates_folder='templates'):\n\t\n\tall_results = {}\n\twith ThreadPoolExecutor(max_workers=limit) as executor:\n\t\tfuture_send_func = [ executor.submit (function, device,\n\t\t\t\t\t\t\t command, attributes, index_filename, templates_folder) \n\t\t\t\t\t\t\t for device in devices_list ]\n\t\t\t\t\t\t\t \n\t\tfor f in as_completed(future_send_func):\n\t\t\tall_results.update(f.result())\n\n\treturn all_results\n\t\n\t\n\n\nif __name__ == '__main__':\n\tcommand = 'sh ip int bri | excl down'\n\tdevices = yaml.load(open('devices.yaml'))\n\t\n\tres = send_and_parse_command_parallel(devices['routers'], command)\n\tpprint(res)\n\n","sub_path":"normlabs/22_textfsm/task_22_6.py","file_name":"task_22_6.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"461460941","text":"\"\"\"freshmarket 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\"\"\"\nimport xadmin\n\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url, include\n\nfrom rest_framework.routers import DefaultRouter\n\nfrom goods.views import (GoodsListView, CategoryViewSet, IndexGoodsBannerViewSet,\n IndexPromotionBannerViewSet, IndexTypeViewSet,\n NewGoodsViewSet, HotGoodsViewSet, RecommendGoodsViewSet)\n\nrouter = DefaultRouter()\n#base_name:用于指定url的初始部分\nrouter.register(r'goods', GoodsListView, base_name='goods')\n#商品种类路由\nrouter.register(r'categories', CategoryViewSet, base_name='categories')\n#首页轮播视图url\nrouter.register(r'banner', IndexGoodsBannerViewSet, base_name='banner')\n#首页促销活动url\nrouter.register(r'promotion', IndexPromotionBannerViewSet, base_name='promotion')\n#首页商品种类url\nrouter.register(r'indexgoods', IndexTypeViewSet, base_name='indexgoods')\n#首页新品url\nrouter.register(r'newgoods', NewGoodsViewSet, base_name='newgoods')\n#首页热销商品url\nrouter.register(r'hotgoods', HotGoodsViewSet, base_name='hotgoods')\n#首页推荐商品url\nrouter.register(r'recommendgoods', RecommendGoodsViewSet, base_name='recommendgoods')\n\n\nurlpatterns = [\n #path('admin/', admin.site.urls),\n #使用xadmin后台\n url(r'^xadmin/', xadmin.site.urls),\n #第三方认证登入url\n url(r'^', include('social_django.urls', namespace='social')),\n]\n","sub_path":"freshmarket/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"274289183","text":"\nfrom glob import iglob\n\nimport cv2\nimport numpy as np\n\nimport CLLibrary as cl\nimport tools\n\ndef drawMinAreaRect(img, points):\n\tretImg = tools.convertBGR(img)\n\n\tif points is None:\n\t\treturn retImg\n\n\tfor p in points:\n\t\tcv2.circle(retImg, tuple(p), 2, cl.green, -1)\n\n\tif points.shape[0] < 4:\n\t\treturn retImg\n\n\tminRect = cv2.minAreaRect(points)\n\tcorners = np.int0(cv2.boxPoints(minRect))\n\tcv2.drawContours(retImg, corners.reshape(1, -1, 1, 2), 0, cl.red, 1)\n\treturn retImg\n\ndef saveWarpMat(cd, points):\n\tif points is None or points.shape[0] < 4:\n\t\tprint(\"We need at least four points\")\n\t\treturn\n\n\tminRect = cv2.minAreaRect(points)\n\tcorners = np.int0(cv2.boxPoints(minRect))\n\n\tsrc = np.zeros((3, 2), dtype = np.float32)\n\tdst = np.zeros((3, 2), dtype = np.float32)\n\tsz = sorted(minRect[1])\n\n\tif cl.dist(corners[0], corners[1]) < cl.dist(corners[1], corners[2]):\n\t\tsrc[0] = tuple(corners[0])\n\t\tsrc[1] = tuple(corners[1])\n\t\tsrc[2] = tuple(corners[2])\n\telse:\n\t\tsrc[0] = tuple(corners[1])\n\t\tsrc[1] = tuple(corners[2])\n\t\tsrc[2] = tuple(corners[3])\n\n\tdst[0] = [0, 0]\n\tdst[1] = [sz[0], 0]\n\tdst[2] = sz\n\n\tcd['warpMat'] = cv2.getAffineTransform(src, dst)\n\tcd['warpMatSz'] = (int(sz[0]), int(sz[1]))\n\tcd.save()\n\nclass FeatureGen(object):\n\n\tdef __init__(self, cd, winName, imgGen, drawFunc, saveFunc, maxPtsCnt = 20):\n\t\tself._cd = cd\n\t\tself._winName = winName\n\t\tself._imgGen = imgGen\n\t\tself._drawFunc = drawFunc\n\t\tself._saveFunc = saveFunc\n\t\tself._maxPtsCnt = maxPtsCnt\n\n\t\tcv2.namedWindow(self._winName)\n\t\tdef onClick(evt, x, y, idk, userData):\n\t\t\tif evt == 4:\n\t\t\t\tuserData['clickedL'] = True\n\t\t\t\tuserData['mouseX'] = x\n\t\t\t\tuserData['mouseY'] = y\n\t\t\telif evt == 5:\n\t\t\t\tuserData['clickedR'] = True\n\n\t\tuserData = {'clickedL'\t: False,\n\t\t\t\t\t'clickedR'\t: False,\n\t\t\t\t\t'mouseX'\t: 0,\n\t\t\t\t\t'mouseY'\t: 0}\n\t\tcv2.setMouseCallback(self._winName, onClick, userData)\n\n\t\tself._points = np.zeros(shape = (self._maxPtsCnt, 2), dtype = np.int64)\n\t\tself._ptIdx = 0\n\t\tself._userData = userData\n\n\tdef update(self):\n\t\tself._imgGen.update()\n\t\timg = self._imgGen.img\n\t\tself.mouseEvent()\n\n\t\tdrawImg = self._drawFunc(img, self._points[:self._ptIdx])\n\t\tcv2.imshow(self._winName, drawImg)\n\n\tdef mouseEvent(self):\n\t\tif self._userData['clickedL']:\n\t\t\tself._userData['clickedL'] = False\n\t\t\tif self._ptIdx < self._maxPtsCnt:\n\t\t\t\tself._points[self._ptIdx] = [self._userData['mouseX'], self._userData['mouseY']]\n\t\t\t\tself._ptIdx += 1\n\t\t\telse:\n\t\t\t\tprint('Max points count reached')\n\t\telif self._userData['clickedR']:\n\t\t\tself._userData['clickedR'] = False\n\t\t\tself._ptIdx = 0\n\n\tdef keyEvent(self, key):\n\t\tif key == ord('y'):\n\t\t\tself._saveFunc(self._cd, self._points[:self._ptIdx])\n\t\telif key == ord('n'):\n\t\t\tself._ptIdx = 0\n\nclass ImgGenSlider(object):\n\n\tdef __init__(self, cd, winName, imgGen, func):\n\t\tself._cd = cd\n\t\tself._winName = winName\n\t\tself._imgGen = imgGen\n\t\tself._func = func\n\t\tself._img = None\n\n\t\tkeys = self._func.__code__.co_varnames[1:self._func.__code__.co_argcount]\n\t\tuserData = {k: cd.getDefault(k, 0) for k in keys}\n\n\t\tif self._winName is not None:\n\t\t\tcv2.namedWindow(self._winName)\n\n\t\t\tclass OnSliderChangeObject(object):\n\t\t\t\tdef __init__(self, k):\n\t\t\t\t\tself._k = k\n\t\t\t\t\tdef onSliderChange(newVal):\n\t\t\t\t\t\tuserData[self._k] = newVal\n\t\t\t\t\tself.func = onSliderChange\n\n\t\t\tfor k in keys:\n\t\t\t\tcv2.createTrackbar('_%s' % k, self._winName, userData[k], 300, OnSliderChangeObject(k).func)\n\n\t\tself._keys = keys\n\t\tself._userData = userData\n\n\t@property\n\tdef img(self):\n\t\treturn self._img\n\n\tdef update(self):\n\t\tself._imgGen.update()\n\t\timg = self._imgGen.img\n\t\tkwargs = {k: self._userData[k] for k in self._keys}\n\t\tself._img = self._func(img, **kwargs)\n\n\t\tif self._winName is not None:\n\t\t\tcv2.imshow(self._winName, self._img)\n\n\tdef keyEvent(self, key):\n\t\tif self._winName is None:\n\t\t\treturn\n\n\t\tif key == ord('y'):\n\t\t\tfor k in self._keys:\n\t\t\t\tself._cd[k] = self._userData[k]\n\t\t\tself._cd.save()\n\t\telif key == ord('n'):\n\t\t\tfor k in self._keys:\n\t\t\t\tself._userData[k] = self._cd[k]\n\t\t\t\tcv2.setTrackbarPos('_%s' % k, self._winName, self._userData[k])\n\nclass ImgGenFilter(object):\n\n\tdef __init__(self, cd, winName, imgGen, func):\n\t\tself._cd = cd\n\t\tself._winName = winName\n\t\tself._imgGen = imgGen\n\t\tself._func = func\n\t\tself._img = None\n\n\t\tif self._winName is not None:\n\t\t\tcv2.namedWindow(self._winName)\n\n\t@property\n\tdef img(self):\n\t\treturn self._img\n\n\tdef update(self):\n\t\tself._imgGen.update()\n\t\timg = self._imgGen.img\n\t\tkeys = self._func.__code__.co_varnames[1:self._func.__code__.co_argcount]\n\t\tkwargs = {k: self._cd[k] for k in keys}\n\t\tself._img = self._func(img, **kwargs)\n\n\t\tif self._winName is not None:\n\t\t\tcv2.imshow(self._winName, self._img)\n\nclass ImgGenCap(object):\n\n\tdef __init__(self, cd, winName, input):\n\t\tself._cd = cd\n\t\tself._winName = winName\n\t\tself._cap = cv2.VideoCapture(input)\n\t\tself._img = None\n\n\t\tif self._winName is not None:\n\t\t\tcv2.namedWindow(self._winName)\n\n\t@property\n\tdef img(self):\n\t\treturn self._img\n\n\tdef update(self):\n\t\t_, self._img = self._cap.read()\n\n\t\tif self._winName is not None:\n\t\t\tcv2.imshow(self._winName, self._img)\n\nclass ImgGenStream(object):\n\n\tdef __init__(self, cd, winName, imgMask):\n\t\tself._cd = cd\n\t\tself._winName = winName\n\t\tself._imgPaths = list(iglob(imgMask))\n\t\tself._img = None\n\n\t\tkeys = ['imgNum']\n\t\tuserData = {k: cd.getDefault(k, 0) for k in keys}\n\n\t\tif self._winName is not None:\n\t\t\tcv2.namedWindow(self._winName)\n\n\t\t\tclass OnSliderChangeObject(object):\n\t\t\t\tdef __init__(self, k):\n\t\t\t\t\tself._k = k\n\t\t\t\t\tdef onSliderChange(newVal):\n\t\t\t\t\t\tuserData[self._k] = newVal\n\t\t\t\t\tself.func = onSliderChange\n\n\t\t\tfor k in keys:\n\t\t\t\tcv2.createTrackbar('_%s' % k, self._winName, userData[k], len(self._imgPaths), OnSliderChangeObject(k).func)\n\n\t\tself._keys = keys\n\t\tself._userData = userData\n\n\t@property\n\tdef img(self):\n\t\treturn self._img\n\n\tdef update(self):\n\t\tself._img = cv2.imread(self._imgPaths[self._userData[self._keys[0]]])\n\n\t\tif self._winName is not None:\n\t\t\tcv2.imshow(self._winName, self._img)\n\n\tdef keyEvent(self, key):\n\t\tif self._winName is None:\n\t\t\treturn\n\n\t\tif key == ord('y'):\n\t\t\tfor k in self._keys:\n\t\t\t\tself._cd[k] = self._userData[k]\n\t\t\tself._cd.save()\n\t\telif key == ord('n'):\n\t\t\tfor k in self._keys:\n\t\t\t\tself._userData[k] = self._cd[k]\n\t\t\t\tcv2.setTrackbarPos('_%s' % k, self._winName, self._userData[k])\n","sub_path":"MoveChips/ImgGen.py","file_name":"ImgGen.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"114747199","text":"# In Python, you can work with different types of data (strings, numbers, Booleans)\r\n# You can also sort these data with lists, dictionaries, tuples, etc.\r\n# However not all things can be represented as strings, numbers, Booleans. ex. objects\r\n# Classes allow us to create our own data types ex. create phone class, student class, computer class, etc,\r\n# and attribute all types of values (strings, numbers, Booleans) related to the phone. \\\r\n# Each entry element that has such attributes is considered an 'object' of the class\r\n\r\n# Lets say we want to make a 'student' class of data\r\n# To do so, we create an initialized function =\r\n# def __init__(self, string/int/Boolean, string/int/Boolean, string/int/Boolean, ... ):\r\n\r\nclass Student:\r\n\r\n def __init__(self, name, major, gpa, is_on_probation):\r\n self.name = name\r\n self.major = major\r\n self.gpa = gpa\r\n self.is_on_probation = is_on_probation","sub_path":"Student_Class.py","file_name":"Student_Class.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477195174","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand\nfrom basket_scraper.scraper.scraper import Scraper\nfrom basket_scraper.models import Category, Competition, Group, Phase, Team, TeamPhase\n\nfrom pprint import pprint\n\n\nclass Command(BaseCommand):\n help = 'Populates the teams with the scrapped datas'\n\n def handle(self, *args, **options):\n sp = Scraper()\n for comp in sp.get_competitions():\n competition = Competition.get_or_create(comp.get('id'), comp.get('name'))\n sp.set_competition(competition.feb_id)\n for cat in sp.get_categories():\n category = Category.get_or_create(cat.get('id'), cat.get('name'))\n sp.set_category(category.feb_id)\n for pha in sp.get_phases():\n phase = Phase.get_or_create(pha.get('id'), pha.get('name'))\n sp.set_phase(phase.feb_id)\n for gro in sp.get_groups():\n group = Group.get_or_create(gro.get('id'), gro.get('name'))\n sp.set_group(group.feb_id)\n teams = sp.get_teams()\n for team_key in teams:\n Team.create_or_update_team(\n teams[team_key], competition, category, group,\n phase)\n","sub_path":"basket_scraper/management/commands/populate_teams.py","file_name":"populate_teams.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"380486772","text":"#Данные\nm=[[1,4,6,-4,-9,-12,1,9,5,-31,0,-3,-1],[4,-10,9,2,-5,-1,9,3,-18]]\n#7 Задание\nrm=[]\n#8 Задание\nmax,min = 0,0\n#9 Задание\nc=0\n\n#Обработка списка\nfor i in range(len(m)):\n for j in range(len(m[i])):\n #7 Задание\n if (m[i][j]%2!=0):\n rm.append(m[i][j])\n #8 Задание\n if (maxm[i][j]):\n min=m[i][j]\n #9 Задание\n if (m[i][j]==9):\n c+=1\n#8 Задание\nfor i in range(len(m)):\n for j in range(len(m[i])):\n if (m[i][j]==max):\n m[i][j]=min\n\n#Вывод\n#7 Задание\nprint('Нечётные числа в порядке возрастания:')\nrm.sort()\nprint(rm)\n#8 Задание\nprint('Список в котором максимальое значение заменено на минимальное:')\nprint(m)\n#9 Задание\nprint('Кол-во девяток:',c)","sub_path":"Python/Универ/Типовой Расчёт 5/TR5 - 7-9.py","file_name":"TR5 - 7-9.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"364537898","text":"\"\"\"\n\nTODO: add functionality to parse items, habits and dailies in a later sprint.\n\n.\n\nThis class handles parsing the XML character data file. To initially parse\nthe file into a useable form, call\n\ndata = parser(filepath)\n\ntasks = parse_hacks() will return a list of dicts to represent all the data\nin the tasks.\n\n>>> data = parser('character.xml')\n>>> tasks = data.parse_hacks()\n>>> sorted(tasks[0].keys())\n['description', 'due', 'index', 'title']\n>>> name = data.parse_name()\n>>> name\n'Krugg'\n>>> level = data.parse_level()\n>>> level\n2\n>>> token = data.parse_token()\n>>> token\n'xoH35mr0iRwAAAAAAAAAI0OZOexRWxqEKabFZRlf6m2WY3j8xkLEcwAEpV297oXv'\n>>> exp = data.parse_exp()\n>>> exp\n120\n>>> cash = data.parse_cash()\n>>> cash\n42\n\n\"\"\"\n\nimport xml.dom.minidom\n\n\nclass file_parser:\n\n\n #This list is used to check parsed values for conversion\n #purposes (everything is parsed in as a string initially)\n integer_types = ['ID', 'cash', 'level', 'exp']\n float_types = ['version']\n\n def parse_simple(self, tag):\n \"\"\"\n This function is used to parse the enclosed text in simple\n tags with no children.\n \"\"\"\n self.nodes = self.doc.getElementsByTagName(tag)\n\n if len(self.nodes) == 0:\n return 0\n \n if self.nodes[0].nodeName in self.integer_types:\n return int(self.nodes[0].firstChild.data)\n\n elif self.nodes[0].nodeName in self.float_types:\n return float(self.nodes[0].firstChild.data)\n\n else:\n return self.nodes[0].firstChild.data\n\n\n def parse_firstname(self):\n return self.parse_simple('firstname')\n\n def parse_lastname(self):\n return self.parse_simple('lastname')\n\n def parse_birthday(self):\n return self.parse_simple('birthday')\n \n def parse_name(self):\n return self.parse_simple('username')\n \n def parse_token(self):\n return self.parse_simple('token')\n\n def parse_version(self):\n return self.parse_simple('version')\n\n def parse_lastran(self):\n return self.parse_simple('lastran')\n \n def parse_exp(self):\n return self.parse_simple('exp')\n\n def parse_level(self):\n return self.parse_simple('level')\n\n def parse_cash(self):\n return self.parse_simple('cash')\n\n def parse_boss(self):\n return self.parse_simple('boss')\n\n def parse_hacks(self):\n \"\"\"\n Returns a list of dictionaries, each dict is a separate hack.\n The dictionary attribute names are determined by the tag name used\n in the XML.\n\n Ex: to get the title of the first hack, you could just\n do hacks[0]['title']\n \"\"\"\n\n self.hack_list = self.doc.getElementsByTagName('hack')\n\n hacks = list()\n \n for hack in self.hack_list:\n hack_dict = {}\n \n for node in hack.childNodes:\n if node.nodeType != node.TEXT_NODE:\n tag_type = node.nodeName\n if len(node.childNodes) == 0:\n inner = ''\n else:\n inner = node.childNodes[0].data\n\n if tag_type in self.integer_types:\n inner = int(inner)\n \n hack_dict[tag_type] = inner\n\n hacks.append(hack_dict)\n \n return hacks\n\n def parse_items(self):\n \"\"\"\n Returns list of dictionaries for items\n \"\"\"\n\n self.item_list = self.doc.getElementsByTagName('item')\n \n items = list()\n \n for item in self.item_list:\n item_dict = {}\n \n for node in item.childNodes:\n if node.nodeType != node.TEXT_NODE:\n tag_type = node.nodeName\n inner = node.childNodes[0].data\n\n if tag_type in self.integer_types:\n inner = int(inner)\n \n item_dict[tag_type] = inner\n\n items.append(item_dict)\n \n return items\n\n\n def replace_text(self, node, newText):\n if node.firstChild.nodeType != node.TEXT_NODE:\n raise Exception(\"node doesn't contain text\")\n\n node.firstChild.replaceWholeText(newText)\n\n def create_list_node(self, doc, hack_data):\n '''\n Returns a hack XMLNode element\n '''\n\n h_type = hack_data['h_type']\n title = hack_data['title']\n desc = hack_data['desc']\n _id = hack_data['ID']\n value = hack_data['value']\n exp = hack_data['exp']\n \n node = doc.createElement('hack')\n h_type_node = doc.createElement('h_type')\n title_node = doc.createElement('title')\n desc_node = doc.createElement('desc')\n id_node = doc.createElement('ID')\n value_node = doc.createElement('value')\n exp_node = doc.createElement('exp')\n\n h_type_node_text = doc.createTextNode(h_type)\n title_node_text = doc.createTextNode(title)\n desc_node_text = doc.createTextNode(desc)\n id_node_text = doc.createTextNode(str(_id))\n value_node_text = doc.createTextNode(str(value))\n exp_node_text = doc.createTextNode(str(exp))\n\n h_type_node.appendChild(h_type_node_text)\n title_node.appendChild(title_node_text)\n desc_node.appendChild(desc_node_text)\n id_node.appendChild(id_node_text)\n value_node.appendChild(value_node_text)\n exp_node.appendChild(exp_node_text)\n\n node.appendChild(h_type_node)\n node.appendChild(title_node)\n node.appendChild(desc_node)\n node.appendChild(id_node)\n node.appendChild(value_node)\n node.appendChild(exp_node)\n\n return node\n \n def update_file(self, char, savefile):\n\n #placeholder, this will handle saving character data to\n #the file I'm thinking we'll want to pass everything in\n #as a single list and structure the XML data depending\n #on whether it's a single item or a list\n\n #Recreate the dom\n newdoc = xml.dom.minidom.Document()\n \n #print(self.doc.toprettyxml(indent=\"\", encoding='utf-8'))\n\n #Local variables from character\n \n char_fname = char['firstname']\n char_lname = char['lastname']\n char_birthday = char['birthday']\n char_token = char['token']\n char_lastran = char['lastran']\n char_version = str(char['version'])\n char_name = char['name']\n char_cash = str(char['cash'])\n char_level = str(char['level'])\n char_exp = str(char['exp'])\n char_boss = char['boss']\n char_hacks = char['hacks']\n char_items = char['items']\n\n #Create XML Node Elements\n root_element = newdoc.createElement('data')\n token_element = newdoc.createElement('token')\n version_element = newdoc.createElement('version')\n lastran_element = newdoc.createElement('lastran')\n firstname_element = newdoc.createElement('firstname')\n lastname_element = newdoc.createElement('lastname')\n username_element = newdoc.createElement('username')\n birthday_element = newdoc.createElement('birthday')\n cash_element = newdoc.createElement('cash')\n exp_element = newdoc.createElement('exp')\n boss_element = newdoc.createElement('boss')\n level_element = newdoc.createElement('level')\n hacks_element = newdoc.createElement('hacks')\n items_element = newdoc.createElement('items')\n \n #Create text nodes for elements\n token_text = newdoc.createTextNode(char_token)\n version_text = newdoc.createTextNode(char_version)\n lastran_text = newdoc.createTextNode(char_lastran)\n firstname_text = newdoc.createTextNode(char_fname)\n lastname_text = newdoc.createTextNode(char_lname)\n username_text = newdoc.createTextNode(char_name)\n birthday_text = newdoc.createTextNode(char_birthday)\n cash_text = newdoc.createTextNode(char_cash)\n exp_text = newdoc.createTextNode(char_exp)\n boss_text = newdoc.createTextNode(char_boss)\n level_text = newdoc.createTextNode(char_level)\n \n #Append text nodes to elements\n token_element.appendChild(token_text)\n version_element.appendChild(version_text)\n lastran_element.appendChild(lastran_text)\n firstname_element.appendChild(firstname_text)\n lastname_element.appendChild(lastname_text)\n username_element.appendChild(username_text)\n birthday_element.appendChild(birthday_text)\n cash_element.appendChild(cash_text)\n boss_element.appendChild(boss_text)\n exp_element.appendChild(exp_text)\n level_element.appendChild(level_text)\n \n #Fill hacks and items\n for hack in char_hacks:\n node = self.create_list_node(newdoc, hack)\n hacks_element.appendChild(node)\n \n for item in char_items:\n node = newdoc.createElement('item')\n title_element = newdoc.createElement('title')\n description_element = newdoc.createElement('desc')\n ID_element = newdoc.createElement('ID')\n image_element = newdoc.createElement('image')\n value_element = newdoc.createElement('value')\n uses_element = newdoc.createElement('uses')\n item_type_element = newdoc.createElement('item_type')\n effect_element = newdoc.createElement('effect')\n active_element = newdoc.createElement('active')\n duration_element = newdoc.createElement('duration')\n component_element = newdoc.createElement('component')\n \n title_text_node = newdoc.createTextNode(item['title'])\n description_text_node = newdoc.createTextNode(item['desc'])\n ID_text_node = newdoc.createTextNode(str(item['ID']))\n image_text_node = newdoc.createTextNode(item['image'])\n value_text_node = newdoc.createTextNode(str(item['value']))\n uses_text_node = newdoc.createTextNode(str(item['uses']))\n item_type_text_node = newdoc.createTextNode(str(item['item_type']))\n effect_text_node = newdoc.createTextNode(str(item['effect']))\n active_text_node = newdoc.createTextNode(str(item['active']))\n duration_text_node = newdoc.createTextNode(str(item['duration']))\n component_text_node = newdoc.createTextNode(str(item['component']))\n \n title_element.appendChild(title_text_node)\n description_element.appendChild(description_text_node)\n ID_element.appendChild(ID_text_node)\n image_element.appendChild(image_text_node)\n value_element.appendChild(value_text_node)\n uses_element.appendChild(uses_text_node)\n item_type_element.appendChild(item_type_text_node)\n effect_element.appendChild(effect_text_node)\n active_element.appendChild(active_text_node)\n duration_element.appendChild(duration_text_node)\n component_element.appendChild(component_text_node)\n \n node.appendChild(title_element)\n node.appendChild(description_element)\n node.appendChild(ID_element)\n node.appendChild(image_element)\n node.appendChild(value_element)\n node.appendChild(uses_element)\n node.appendChild(item_type_element)\n node.appendChild(effect_element)\n node.appendChild(active_element)\n node.appendChild(duration_element)\n node.appendChild(component_element)\n \n items_element.appendChild(node)\n \n #Append elements to root element\n root_element.appendChild(token_element)\n root_element.appendChild(version_element)\n root_element.appendChild(lastran_element)\n root_element.appendChild(firstname_element)\n root_element.appendChild(lastname_element)\n root_element.appendChild(username_element)\n root_element.appendChild(birthday_element)\n root_element.appendChild(cash_element)\n root_element.appendChild(exp_element)\n root_element.appendChild(level_element)\n root_element.appendChild(boss_element)\n root_element.appendChild(hacks_element)\n root_element.appendChild(items_element)\n newdoc.appendChild(root_element)\n \n #print(name_node.toprettyxml())\n #print(cash_node.toprettyxml())\n #print(level_node.toprettyxml())\n #print(exp_node.toprettyxml())\n #print(hacks_node.toprettyxml())\n #print(items_node.toprettyxml())\n\n #Write XMLDocument to file\n try:\n file = open(savefile, 'wb')\n file.write(newdoc.toprettyxml(indent=\" \", encoding=\"utf-8\"))\n file.close()\n \n except:\n print(\"Couldn't save data to file\")\n \n return\n \n\n def __init__(self, filename):\n try:\n self.doc = xml.dom.minidom.parse(filename)\n\n except FileNotFoundError:\n self.doc = xml.dom.minidom.Document()\n\n#unit tests, aww yiss\nif __name__ == \"__main__\":\n \n import doctest\n doctest.testmod()\n \n data = parser('character.xml')\n tasks = data.parse_hacks()\n","sub_path":"file_parser.py","file_name":"file_parser.py","file_ext":"py","file_size_in_byte":13424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"536312281","text":"#-*- coding=utf-8 -*-\nimport pygame\nimport time\n\nclass HeroPlane(object):\n \"\"\"英雄的创建和展示类\"\"\"\n def __init__(self, arg):\n super(HeroPlane, self).__init__()\n self.screen = arg\n self.x = 150\n self.y = 500\n #3.英雄\n self.image = pygame.image.load('./images/hero1.png')\n # 4. 定义英雄的初始位置\n self.hero_rect = pygame.Rect(self.x, self.y, 102, 126)\n def display(self):\n self.screen.blit(self.image,self.hero_rect)\ndef key_control(hero):\n '''键盘的监听控制方法'''\n move_x, move_y = 0, 0\n # =====事件监听\n for event in pygame.event.get():\n # 判断用户是否点击了关闭按钮\n if event.type == pygame.QUIT:\n print(\"退出游戏...\")\n pygame.quit()\n # 直接退出系统\n exit()\n elif event.type == pygame.KEYDOWN:\n #键盘有按下?\n if event.key == pygame.K_LEFT:\n #按下的是左方向键的话,把x坐标减一\n move_x = -2\n elif event.key == pygame.K_RIGHT:\n #右方向键则加一\n move_x = 2\n elif event.key == pygame.K_UP:\n #类似了\n move_y = -2\n elif event.key == pygame.K_DOWN:\n move_y = 2\n elif event.type == pygame.KEYUP:\n #如果用户放开了键盘,图就不要动了\n move_x = 0\n move_y = 0\n\n #计算出新的坐标\n hero.hero_rect.x += move_x\n hero.hero_rect.y += move_y\ndef main():# 主方法 调用 类和方法\n #1.窗口\n screen = pygame.display.set_mode((480,600),0,32)\n #2.背景\n background = pygame.image.load('./images/background.png')\n #3.英雄\n hero = HeroPlane(screen)\n # 4.1. 创建游戏时钟对象\n clock = pygame.time.Clock()\n\n while True:\n screen.blit(background,(0,0))\n hero.display()\n \n #time.sleep(0.01)\n # 设置屏幕刷新帧率\n clock.tick(60)\n # hero_rect.y -= 1 #move hero y\n if hero.hero_rect.y <= 0:\n hero.hero_rect.y = 500\n\n key_control(hero)\n \n pygame.display.update()\n \nif __name__ == '__main__':\n main()\n","sub_path":"feiji/06_def移动.py","file_name":"06_def移动.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7609716","text":"import torch\nfrom transformers import BertModel\n\nfrom pathlib import PurePath\n\nCURR_PATH = PurePath(__file__).parent\nPRE_TRAINED_MODEL_PATH = str(CURR_PATH.parent.parent / \"res/bert_base_wwm/\")\n\n\nclass BertClassificationModel(torch.nn.Module):\n def __init__(self,\n num_labels,\n finetune=True,\n label_weights=None,\n hidden_dim=50,\n dropout=0.3,\n pre_trained_model_path=PRE_TRAINED_MODEL_PATH):\n super(BertClassificationModel, self).__init__()\n self.num_labels = num_labels\n\n self.bert = BertModel.from_pretrained(pre_trained_model_path)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.hidden = torch.nn.Linear(self.bert.config.hidden_size, hidden_dim)\n self.classifier = torch.nn.Linear(hidden_dim, self.num_labels)\n self.softmax = torch.nn.Softmax(dim=1)\n self.loss = torch.nn.MSELoss()\n\n self.finetune = finetune\n torch.nn.init.xavier_uniform_(self.classifier.weight)\n\n def forward(self, word_seq_tensor, word_mask_tensor, labels=None):\n if not self.finetune:\n self.bert.eval()\n with torch.no_grad():\n outputs = self.bert(input_ids=word_seq_tensor, attention_mask=word_mask_tensor)\n else:\n outputs = self.bert(input_ids=word_seq_tensor, attention_mask=word_mask_tensor)\n\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n pooled_output = torch.nn.functional.relu(self.hidden(pooled_output))\n pooled_output = self.dropout(pooled_output)\n logits = self.softmax(self.classifier(pooled_output))\n\n outputs = (logits,)\n\n if labels is not None:\n loss = self.loss(logits, labels)\n outputs = outputs + (loss,)\n else:\n outputs = outputs + (None,)\n return outputs # logits, loss\n","sub_path":"xatc/models/bert_classifier/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"351830254","text":"from productTools.toolsScripts.zonalStatistics import getProductLocation\nfrom productTools.toolsScripts import timeSeriesChartPoints\nimport os\nfrom productTools.toolsScripts.miscModule import getDatesBetweenTwoDates\nfrom rasterstats import point_query\nfrom shapely.geometry import Point\nfrom osgeo import gdal, ogr\nfrom osgeo.gdalconst import GA_ReadOnly\nimport json\nimport ast\nimport numpy as np\n\n\ndef getZonalTimeSeriesData(startingDate, endingDate, product, polygons):\n ## Prepair the results container.\n polygonPoints = []\n\n ## Get the requested product dataset sample.\n productLocation = getProductLocation(product)\n filesList = os.listdir(productLocation)\n ## Check if datesList element is a valid directory\n datesList = []\n for anything in filesList:\n if os.path.isdir(f'{productLocation}/{anything}'):\n datesList.append(anything)\n else:\n pass\n\n ## Get sample raster path. Sample reaster is needed get its properties and create a new in-memory raster that will hold rasterized polygons.\n sampleDatasetPath = f'{productLocation}/{datesList[0]}/{product}'\n sampleDataset = os.listdir(sampleDatasetPath)[0]\n sampleDataset = f'{sampleDatasetPath}/{sampleDataset}'\n\n ## Open sample raster and get poperties needed.\n inRaster = gdal.Open(sampleDataset, GA_ReadOnly)\n inCols = inRaster.RasterXSize\n inRows = inRaster.RasterYSize\n inGeotransform = inRaster.GetGeoTransform()\n\n ## Create in-memory raster.\n mem_drv = gdal.GetDriverByName('MEM')\n targetRaster = mem_drv.Create('', inCols, inRows, 1, gdal.GDT_Byte)\n targetRaster.SetGeoTransform(inGeotransform)\n\n ## Open geojson from submitted json..\n source_ds = ogr.Open(polygons[0])\n source_layer = source_ds.GetLayer()\n\n ## Rasterize\n gdal.RasterizeLayer(targetRaster, [1], source_layer, burn_values=[1])\n\n ## Read raster as numpy array to get the resterized polygon pixel indices.\n rasterBand = targetRaster.GetRasterBand(1)\n rasArray = rasterBand.ReadAsArray()\n\n ## Convert array to point coordinates\n count = 0\n polygonIndices = np.where(rasArray != 0)\n for indexY in polygonIndices[0]:\n indexX = polygonIndices[1][count]\n originX = inGeotransform[0]\n originY = inGeotransform[3]\n pixelWidth = inGeotransform[1]\n pixelHeight = inGeotransform[5]\n Xcoord = originX+pixelWidth*indexX\n Ycoord = originY+pixelHeight*indexY\n ## Construct each feature so it can be used by the point time series tool.\n pointFeature = {'id': count, 'product': product, 'x': Xcoord, 'y': Ycoord}\n ## Append it to results list.\n polygonPoints.append(f\"{pointFeature}\")\n count += 1\n\n ## Pass the list of points to the point time series tool.\n timeSeriesChartPolygonResult = timeSeriesChartPoints.getTimeSeriesData(startingDate, endingDate, product, polygonPoints)\n return timeSeriesChartPolygonResult\n\nif __name__ == '__main__':\n pass\n","sub_path":"productTools/toolsScripts/timeSeriesChartPolygons.py","file_name":"timeSeriesChartPolygons.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"171677943","text":"import requests\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom bs4 import BeautifulSoup\nimport json\n\nscholarships = []\ntotal = 0\n\n\ndef scrape(start_url):\n\n website_url = start_url.replace('st=0', 'st={}'.format(0))\n parse(website_url)\n browser.quit()\n print('All data successfully scraped!')\n\n data = {\n 'total': total,\n 'scholarships': scholarships\n }\n return json.dumps(data)\n\n\ndef parse(scholarships_page):\n\n global total\n browser.get(scholarships_page)\n WebDriverWait(browser, 20).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'h-c-grid__col'))\n )\n\n body = browser.page_source\n soup = BeautifulSoup(body, 'html.parser')\n scholarships_content = soup.select('#scholarships div.h-c-grid__col')\n\n total += len(scholarships_content)\n\n scholarships_urls = []\n for sch in scholarships_content:\n sch_header = sch.select_one('a.pas-tile--scholarship[href]')\n sch_link = 'https://buildyourfuture.withgoogle.com' + sch_header['href']\n print(sch_link)\n scholarships_urls.append(sch_link)\n\n parse_scholarships(scholarships_urls)\n\n\ndef parse_scholarships(scholarships_urls):\n \n global scholarships\n scholarships_html = []\n for url in scholarships_urls:\n browser.execute_script(\"window.open('{}', 'new_window')\".format(url))\n browser.switch_to.window(browser.window_handles[1])\n\n try:\n WebDriverWait(browser, 20).until(\n EC.element_to_be_clickable((By.CLASS_NAME, 'h-c-grid__col--7'))\n )\n except TimeoutException:\n browser.close()\n browser.switch_to.window(browser.window_handles[0])\n continue\n\n scholarships_html.append(browser.page_source)\n browser.close()\n browser.switch_to.window(browser.window_handles[0])\n\n scholarships_list = []\n for scho in scholarships_html:\n soup = BeautifulSoup(scho, 'html.parser')\n scho_title = soup.select_one('div.h-c-grid__col--7 > h1').get_text()\n location = soup.select_one('ul.pas-metadata > li:nth-last-of-type(1) div.h-c-copy').get_text()\n amnt = soup.select_one('.h-no-bullet').get_text()\n\n location = location.strip('\\n')\n amnt = amnt.strip('\\n')\n location = location.strip()\n amnt = amnt.strip()\n scho_dict = {\n 'title': scho_title,\n 'location': location,\n 'amount': amnt\n }\n\n scholarships_list.append(scho_dict)\n\n scholarships += scholarships_list\n\n\nif __name__ == '__main__':\n print('Start scraping all google scholarships ...')\n\n base_url = 'https://buildyourfuture.withgoogle.com/scholarships/'\n result = requests.get(url=base_url)\n url = result.url.replace('?', '#')\n\n chrome_options = webdriver.ChromeOptions()\n browser = webdriver.Chrome('C:/Users/Dell/Desktop/chromedriver.exe')\n\n data_json = scrape(url)\n data_json=json.loads(data_json)\n with open('data.json', 'w') as file:\n json.dump(data_json, file)","sub_path":"Scrape_test_01/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645736627","text":"# -*- coding: utf-8 -*-\r\n\r\n# Define your item pipelines here\r\n#\r\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\r\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\r\nfrom sqlalchemy import Table, Column, Integer, String, MetaData\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy_utils import create_database\r\nfrom scrapy.exceptions import DropItem\r\nfrom urllib.parse import unquote\r\n\r\nclass DuplicatesPipeline(object):\r\n\r\n def __init__(self):\r\n self.urls_seen = set()\r\n self.partnerAdIDs = set()\r\n\r\n def process_item(self, item, spider):\r\n if item['url'] in self.urls_seen:\r\n raise DropItem(\"Duplicate item found: %s\" % item)\r\n else:\r\n self.urls_seen.add(item['url'])\r\n url = unquote(item['url'])\r\n options = url.split('&')\r\n adID = \"\"\r\n for opt in options:\r\n if \"attr1\" in opt:\r\n adID = opt.split('=')[1]\r\n if adID is not \"\" and adID in self.partnerAdIDs:\r\n raise DropItem(\"Duplicate partner ad found: %s\" % item)\r\n else:\r\n self.partnerAdIDs.add(adID)\r\n return item\r\n\r\n\r\nclass QKPipeline(object):\r\n \r\n def open_spider(self, spider):\r\n self.metadata = MetaData()\r\n self.QKData = Table('QKData', self.metadata,\r\n Column('id', Integer, primary_key=True),\r\n Column('Boersen_ID', String()),\r\n Column('OBID', String()),\r\n Column('erzeugt_am', String()),\r\n Column('Anbieter_ID', String(8)),\r\n Column('Anbieter_ObjektID', String(100)),\r\n Column('Immobilientyp', String(50)),\r\n Column('Immobilientyp_detail', String(200)),\r\n Column('Vermarktungstyp', String(50)),\r\n Column('Land', String(30)),\r\n Column('Bundesland', String(50)),\r\n Column('Bezirk', String(150)),\r\n Column('Stadt', String(150)),\r\n Column('PLZ', String(10)),\r\n Column('Strasse', String(100)),\r\n Column('Hausnummer', String(40)),\r\n Column('Ueberschrift', String(500)),\r\n Column('Beschreibung', String(15000)),\r\n Column('Etage', String(30)),\r\n Column('Kaufpreis', String()),\r\n Column('Kaltmiete', String(8)),\r\n Column('Warmmiete', String(8)),\r\n Column('Nebenkosten', String(8)),\r\n Column('Zimmeranzahl', String(8)),\r\n Column('Wohnflaeche ', String(8)),\r\n Column('Monat', String(8)),\r\n Column('url', String(1000)),\r\n Column('Telefon', String(100)),\r\n Column('Erstellungsdatum', String()),\r\n Column('Gewerblich', String(8))\r\n )\r\n\r\n db_path = 'sqlite:///QKData.db'\r\n create_database(db_path)\r\n self.engine = create_engine(db_path)\r\n self.metadata.create_all(self.engine) \r\n self.connection = self.engine.connect()\r\n\r\n def close_spider(self, spider):\r\n pass\r\n \r\n def process_item(self, item, spider):\r\n self.connection.execute(self.QKData.insert(), dict(item))\r\n return item\r\n\r\n","sub_path":"QKCrawl/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"9307683","text":"import csv\n\n\nclass Series(list):\n def sum(self):\n return sum(self)\n\n def average(self):\n return sum(self) / len(self)\n\n avg = average\n\n def apply(self, func):\n self = Series([func(x) for x in self])\n return self\n\n\nclass GroupBy(dict):\n def sum(self, on=None):\n return self.aggregate(on=on, using_func=sum)\n\n def average(self, on=None):\n def func(listo):\n return sum(listo) / len(listo)\n\n return self.aggregate(on=on, using_func=func)\n\n avg = average\n\n def count(self, on=None):\n return self.aggregate(on=on, using_func=len)\n\n def min(self, on=None):\n return self.aggregate(on=on, using_func=min)\n\n def max(self, on=None):\n return self.aggregate(on=on, using_func=max)\n\n def spread(self, on=None):\n def func(listo):\n return max(listo) - min(listo)\n\n return self.aggregate(on=on, using_func=func)\n\n def aggregate(self, on=None, using_func=None):\n aggregator = {}\n if on == None:\n raise Exception(\"What column do you want aggregated?\")\n if using_func == None:\n raise Exception(f\"How do you want '{on}' aggregated?\")\n else:\n for key in self.keys():\n addends = [item[on] for item in self[key]]\n aggregator[key] = using_func(addends)\n return aggregator\n\n def describe_with(self, *args):\n descriptions = {}\n for aggregation in args:\n if aggregation['agg'] == 'aggregate':\n result = self.aggregate(on=aggregation['column'], using_func=aggregation['using_func'])\n function_name = aggregation['using_func'].__name__\n else:\n aggregation_function = getattr(self, aggregation['agg'])\n result = aggregation_function(on=aggregation['column'])\n function_name = aggregation['agg']\n\n for result_key in result.keys():\n if not descriptions.get(result_key):\n descriptions[result_key] = {}\n aggregation_label = f\"{aggregation['column']} {function_name}\"\n descriptions[result_key][aggregation_label] = result[result_key]\n return GroupBy(descriptions)\n\n def print_cute(self):\n '''\n Prints out a GroupBy or a GroupBy Description in a nice format.\n\n Input:\n None - this method operates on the existing GroupBy object.\n\n Output:\n None - no return value\n\n Modifies:\n Prints to standard out with a list of the groups. For each group,\n prints an indented list of the items in it (for a GroupBy),\n or an indented list of summary statistics (for a Groupby Description).\n '''\n for key, value in self.items():\n print(key)\n\n if isinstance(value, dict):\n for key, component in value.items():\n print(f\" {key} : {component}\")\n else:\n for component in value:\n print(f\" {component}\")\n\n\nclass DataFrame():\n def __init__(self):\n self._dictionary = {}\n self._list = []\n\n # Ways to crate an instance\n @classmethod\n def from_csv(cls, file_path):\n df = cls()\n header_unread = True\n\n with open(file_path) as f:\n reader = csv.DictReader(f)\n\n for row in reader:\n if header_unread:\n for key in row.keys():\n df._dictionary[key] = Series()\n header_unread = False\n \n df._list.append(row)\n\n for key in row.keys():\n df._dictionary[key].append(row[key])\n\n for key in list(df._dictionary.keys()):\n setattr(df, key.lower().replace(\" \", \"_\"), df._dictionary[key])\n return df\n\n @classmethod\n def from_rows(cls, rows):\n df = cls()\n for key in rows[0].keys():\n df._dictionary[key] = Series()\n for row in rows:\n for key in rows[0].keys():\n df._dictionary[key].append(row[key])\n \n df._list.append(row)\n\n for key in list(df._dictionary.keys()):\n setattr(df, key.lower().replace(\" \", \"_\"), df._dictionary[key])\n\n return df\n\n @classmethod\n def from_dictionary(cls, dictionary):\n df = cls()\n df._dictionary = dictionary\n for i in range(len(dictionary[list(dictionary.keys())[0]])):\n item = {}\n for key in dictionary.keys():\n item[key] = dictionary[key][i]\n df._list.append(item)\n\n for key in list(df._dictionary.keys()):\n setattr(df, key.lower().replace(\" \", \"_\"), df._dictionary[key])\n\n return df\n\n # Properties\n @property\n def shape(self):\n return \\\n len(self._dictionary.keys()), \\\n len(self._dictionary[list(self._dictionary.keys())[0]])\n\n @property\n def columns(self):\n return list(self._dictionary.keys())\n\n # Methods for getting a column in the dictionary\n def __getitem__(self, item):\n '''\n Get a reference to a column in the dataframe.\n\n Input:\n item - the column header\n\n Output:\n the column, which is a series\n\n Modifies:\n Nothing\n '''\n return self._dictionary[item]\n\n # Method for setting a column in the dictionary\n def __setitem__(self, key, value):\n '''\n Set a new column in the dataframe.\n\n Inputs:\n key - the column header\n value - the column (as a Series for consistency, please)\n\n Outputs:\n None\n\n Modifies:\n Modifies the dataframe object in place.\n '''\n self._dictionary[key] = value\n for index, item in enumerate(self._list):\n item[key] = value[index]\n\n setattr(self, key.lower().replace(\" \", \"_\"), self._dictionary[key])\n\n def where(self, condition):\n rows = [row for row in self._list if condition(row)]\n return DataFrame.from_rows(rows)\n\n def assign(self, **kwargs):\n for key, value in kwargs.items():\n new_column = Series()\n for row in self._list:\n new_column.append(value(row))\n self.__setitem__(key, new_column)\n return self\n\n def group_by(self, column):\n '''\n Returns an object that aggregates the items in the dataframe\n based on one value that they have in common,\n similar to a pivot table in the software to which\n phoenixcell's name pays tribute (Please don't sue me, Microsoft)\n\n Inputs:\n column - the column on whose value the items should be grouped\n\n Outputs:\n A new GroupBy() object\n\n Modifies:\n Nothing\n '''\n groups = GroupBy()\n for item in self._list:\n maybe_unique_column_value = item[column]\n if maybe_unique_column_value in groups.keys():\n groups[maybe_unique_column_value].append(item)\n else:\n groups[maybe_unique_column_value] = Series()\n groups[maybe_unique_column_value].append(item)\n return groups","sub_path":"data_frame_exercise/phoenixcel/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":7286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290125515","text":"#import sys\n#sys.path.append('C:/Users/Richard/Desktop/Informatik/Semester_5/MLMI/git/mlmi-federated-learning')\n\nfrom mlmi.datasets.ham10k import load_ham10k_federated\nfrom mlmi.models.ham10k import MobileNetV2Lightning\n\nfrom typing import Callable, Dict, List, Optional\n\nfrom sacred import Experiment\nfrom functools import partial\n\nfrom torch import Tensor, optim\n\nfrom mlmi.experiments.log import log_goal_test_acc, log_loss_and_acc\nfrom mlmi.reptile.omniglot import load_omniglot_datasets\nfrom mlmi.fedavg.femnist import load_femnist_dataset\nfrom mlmi.fedavg.model import CNNLightning\nfrom mlmi.reptile.model import OmniglotLightning\nfrom mlmi.reptile.structs import ReptileExperimentContext\nfrom mlmi.reptile.run_reptile_experiment import run_reptile\n\nfrom mlmi.plot import generate_data_label_heatmap\nfrom mlmi.settings import REPO_ROOT\nfrom mlmi.structs import FederatedDatasetData\nfrom mlmi.utils import create_tensorboard_logger, fix_random_seeds\n\nex = Experiment('reptile')\n\n\n@ex.config\ndef femnist():\n name = 'reptile'\n dataset = 'femnist' # Options: 'omniglot', 'femnist'\n swap_labels = False # Only used with dataset='femnist'\n classes = 0 # Only used with dataset='omniglot'\n shots = 0 # Only used with dataset='omniglot'\n seed = 123123123\n\n model_class = CNNLightning\n sgd = True # True -> Use SGD as inner optimizer; False -> Use Adam\n adam_betas = (0.9, 0.999) # Used only if sgd = False\n\n num_clients_train = 367\n num_clients_test = 0 # Used only with dataset='omniglot'\n meta_batch_size = 5\n num_meta_steps = 1000\n meta_learning_rate_initial = 3\n meta_learning_rate_final = 0\n\n eval_interval = 25\n num_eval_clients_training = -1\n do_final_evaluation = True\n num_eval_clients_final = -1\n\n inner_batch_size = 100\n inner_learning_rate = [0.05]\n num_inner_steps = [7]\n num_inner_steps_eval = 7\n\n\n@ex.named_config\ndef ham10k():\n name = 'ham10kreptile'\n dataset = 'ham10k' # Options: 'omniglot', 'femnist'\n swap_labels = False # Only used with dataset='femnist'\n classes = 0 # Only used with dataset='omniglot'\n shots = 0 # Only used with dataset='omniglot'\n seed = 123123123\n\n model_class = MobileNetV2Lightning\n sgd = True # True -> Use SGD as inner optimizer; False -> Use Adam\n adam_betas = (0.9, 0.999) # Used only if sgd = False\n\n num_clients_train = 27\n num_clients_test = 0 # Used only with dataset='omniglot'\n meta_batch_size = 5\n num_meta_steps = 1000\n meta_learning_rate_initial = 1\n meta_learning_rate_final = 0\n\n eval_interval = 20\n num_eval_clients_training = -1\n do_final_evaluation = True\n num_eval_clients_final = -1\n\n inner_batch_size = 8\n inner_learning_rate = [0.007]\n num_inner_steps = [5]\n num_inner_steps_eval = 32\n mean = (0.485, 0.456, 0.406)\n std = (0.229, 0.224, 0.225)\n\n\n@ex.named_config\ndef omniglot():\n name = 'reptile'\n dataset = 'omniglot' # Options: 'omniglot', 'femnist'\n swap_labels = False\n classes = 5 # Only used with dataset='omniglot'\n shots = 5 # Only used with dataset='omniglot'\n seed = 0\n\n model_class = OmniglotLightning\n sgd = True # True -> Use SGD as inner optimizer; False -> Use Adam\n adam_betas = None # Used only if sgd = False\n\n num_clients_train = 10000\n num_clients_test = 1000 # Used only with dataset='omniglot'\n meta_batch_size = 5\n num_meta_steps = 100000\n meta_learning_rate_initial = 1\n meta_learning_rate_final = 0\n\n eval_interval = 10\n num_eval_clients_training = 1\n do_final_evaluation = True\n num_eval_clients_final = 1000 # Applies only when do_final_evaluation=True\n\n inner_batch_size = 16\n inner_learning_rate = [0.001]\n num_inner_steps = 5\n num_inner_steps_eval = 50\n\ndef log_after_round_evaluation(\n experiment_logger,\n tag: str,\n loss_train_test: Tensor,\n acc_train_test: Tensor,\n loss_test_test: Tensor,\n acc_test_test: Tensor,\n step: int\n ):\n log_loss_and_acc(\n f'{tag}train-test',\n loss_train_test,\n acc_train_test,\n experiment_logger,\n step\n )\n log_goal_test_acc(f'{tag}train-test', acc_train_test, experiment_logger, step)\n if loss_test_test is not None and acc_test_test is not None:\n log_loss_and_acc(\n f'{tag}test-test',\n loss_test_test,\n acc_test_test,\n experiment_logger,\n step\n )\n log_goal_test_acc(f'{tag}test-test', acc_test_test, experiment_logger, step)\n\n\ndef log_dataset_distribution(experiment_logger, tag: str, dataset: FederatedDatasetData):\n dataloaders = list(dataset.train_data_local_dict.values())\n image = generate_data_label_heatmap(tag, dataloaders, dataset.class_num)\n experiment_logger.experiment.add_image('label distribution', image.numpy())\n\n\n@ex.automain\ndef run_reptile_experiment(\n name,\n dataset,\n swap_labels,\n classes,\n shots,\n seed,\n model_class,\n sgd,\n adam_betas,\n num_clients_train,\n num_clients_test,\n meta_batch_size,\n num_meta_steps,\n meta_learning_rate_initial,\n meta_learning_rate_final,\n eval_interval,\n num_eval_clients_training,\n do_final_evaluation,\n num_eval_clients_final,\n inner_batch_size,\n inner_learning_rate,\n num_inner_steps,\n num_inner_steps_eval,\n mean=None,\n std=None\n):\n fix_random_seeds(seed)\n fed_dataset_test = None\n if dataset == 'femnist':\n fed_dataset_train = load_femnist_dataset(\n data_dir=str((REPO_ROOT / 'data').absolute()),\n num_clients=num_clients_train,\n batch_size=inner_batch_size,\n random_seed=seed\n )\n elif dataset == 'omniglot':\n fed_dataset_train, fed_dataset_test = load_omniglot_datasets(\n data_dir=str((REPO_ROOT / 'data' / 'omniglot').absolute()),\n num_clients_train=num_clients_train,\n num_clients_test=num_clients_test,\n num_classes_per_client=classes,\n num_shots_per_class=shots,\n inner_batch_size=inner_batch_size,\n random_seed=seed\n )\n elif dataset == 'ham10k':\n fed_dataset_train = load_ham10k_federated(partitions=num_clients_train, batch_size=inner_batch_size, mean=mean, std=std)\n else:\n raise ValueError(f'dataset \"{dataset}\" unknown')\n\n if not hasattr(inner_learning_rate, '__iter__'):\n inner_learning_rate = [inner_learning_rate]\n if not hasattr(num_inner_steps, '__iter__'):\n num_inner_steps = [num_inner_steps]\n #data_distribution_logged = False\n for lr in inner_learning_rate:\n for _is in num_inner_steps:\n reptile_context = ReptileExperimentContext(\n name=name,\n dataset_name=dataset,\n swap_labels=swap_labels,\n num_classes_per_client=classes,\n num_shots_per_class=shots,\n seed=seed,\n model_class=model_class,\n sgd=sgd,\n adam_betas=adam_betas,\n num_clients_train=num_clients_train,\n num_clients_test=num_clients_test,\n meta_batch_size=meta_batch_size,\n num_meta_steps=num_meta_steps,\n meta_learning_rate_initial=meta_learning_rate_initial,\n meta_learning_rate_final=meta_learning_rate_final,\n eval_interval=eval_interval,\n num_eval_clients_training=num_eval_clients_training,\n do_final_evaluation=do_final_evaluation,\n num_eval_clients_final=num_eval_clients_final,\n inner_batch_size=inner_batch_size,\n inner_learning_rate=lr,\n num_inner_steps=_is,\n num_inner_steps_eval=_is\n )\n\n experiment_specification = f'{reptile_context}'\n experiment_logger = create_tensorboard_logger(\n reptile_context.name, experiment_specification\n )\n reptile_context.experiment_logger = experiment_logger\n\n log_after_round_evaluation_fns = [\n partial(log_after_round_evaluation, experiment_logger)\n ]\n run_reptile(\n context=reptile_context,\n dataset_train=fed_dataset_train,\n dataset_test=fed_dataset_test,\n initial_model_state=None,\n after_round_evaluation=log_after_round_evaluation_fns\n )\n","sub_path":"mlmi/experiments/reptile_federated.py","file_name":"reptile_federated.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"98093149","text":"# Написать функцию которая будет простое число возводить в квардрат.\n# Необходимо возвести в квадрат все простые числа в списке используя функцию map\n\nL = [2, 5, 7, 6, 14, 11, 22, 113]\n\ndef f1(i):\n\tn = 2\n\twhile i % n:\n\t\tn += 1\n\tn == i\n\tif (n == i):\n\t\treturn i * i\n\nprint(list(map(f1, L)))","sub_path":"HW-05/L-05-2.py","file_name":"L-05-2.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"368812398","text":"from flask import Flask, render_template, request, redirect, session, url_for\nimport random\napp = Flask(__name__)\napp.secret_key = 'ThisIsSecret' # you need to set a secret key for security purposes\n\n\n@app.route('/')\ndef index():\n if not 'random' in session:\n session['random'] = random.randrange(0,101)\n if not 'counter' in session:\n session['counter'] = 0\n session['counter'] += 1\n return render_template(\"index.html\")\n\n@app.route('/submit', methods=['POST'])\ndef guess():\n guess = int(request.form['guess'])\n if session['random'] > guess:\n session['content'] = \"Guess is too low You have guessed \"+str(session['counter'])+\" times\"\n elif session['random'] < guess:\n session['content'] = \"Guess is too high You have guessed \"+str(session['counter'])+\" times\"\n else:\n session['content'] = \"YOU ARE A WINNER IN \"+str(session['counter'])+\" GUESSES\"\n return redirect(\"/\")\n\n@app.route('/clear', methods=['POST'])\ndef clear():\n session.clear()\n return redirect(\"/\")\n\napp.run(debug=True)\n\n\n","sub_path":"Python/flask_fundamentals/great_number_game/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"284644350","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 ('main', '0016_tariffgroup_public'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Service',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=30)),\n ('description', models.IntegerField(blank=True, max_length=200)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='tariffgroup',\n name='services',\n field=models.ManyToManyField(to='main.Service'),\n preserve_default=True,\n ),\n ]\n","sub_path":"main/migrations/0017_auto_20141129_2043.py","file_name":"0017_auto_20141129_2043.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"538875009","text":"import re\nimport urllib.request\nimport urllib.error\nimport subprocess\n\n#The name of the script that prints the note about the latest handled news to stdout.\nscript = '/etc/archupgrade.d/latest-handled-news'\n\n#The web page listing the Arch linux news.\nURL = 'https://www.archlinux.org/news/'\n\ndef isHandled():\n print(_('Checking for news about manual upgrades')+'...')\n #Get latest news from Arch Linux news page.\n try:\n news = urllib.request.urlopen(URL).read()\n except urllib.error.URLError:\n #Translators: {URL} will be substituted with an address to a webpage.\n print(_('The internet page with the news ({URL}) was not accessible.').format(URL=URL))\n print(_('The system will not be upgraded at this time.'))\n print(_('You will have to upgrade some other time.'))\n return False\n\n news = news.decode() #read() returns a binary blob. It must be decoded into a textual string before the script can work on the data.\n #Find the first news item on the page.\n news = news.split('',1)[1]\n news = news.split('',1)[0]\n #Extract the date, title and author.\n newsDate = re.findall('[0-9]{4}-[0-9]{2}-[0-9]{2}', news)[0]\n newsTitle = re.findall('title=[^>]+>([^<]+)', news)[0]\n newsAuthor = re.findall('(?:[^>]+>){2}([^<]+)', news)[0]\n #Compose a news string.\n news = newsDate+':'+newsAuthor+':'+newsTitle\n\n #Get the note about the latest handled news.\n try:\n note = subprocess.run([script], universal_newlines=True, check=True, stdout=subprocess.PIPE).stdout.strip()\n except FileNotFoundError:\n #Translators: {file} will be substituted with a file name.\n note = _('{file} not found.').format(file=script)\n except PermissionError:\n #Translators: {file} will be substituted with a file name.\n note = _('{file} is not executable.').format(file=script)\n note += '\\n'\n #Translators: {file} will be substituted with a file name.\n #Translators: {application} will be substituted with the name of the application that you are translating.\n note += _('{file} must be executable for {application} to be able to execute.').format(file=script, application=os.path.basename(sys.argv[0]))\n except subprocess.CalledProcessError as e:\n #Translators: {command} will be substituted with the name of a script file.\n note = _('{command} exited with an error:').format(command=script)\n note += '\\n'\n #Translators: {command} will be substituted with the name of a script file.\n #Translators: {errorcode} will be substituted with the command's exit status. Likely '1', but could be an other integer.\n note += _(\"{command} returned error code {errorcode}\").format(command=script, errorcode=e.args[0])\n\n if news == note:\n #All news have been handled.\n print(_('No news since last check.'))\n return True\n else:\n if re.match('[0-9]{4}-[0-9]{2}-[0-9]{2}:', note):\n #The latest handled news is not the latest news on the Arch news page. Some news need to be handled.\n print(_('The latest news about manual upgrades, has not been handled on this computer.'))\n print(_('The latest news is:'))\n print(' '+news)\n print(_('The latest handled news on this computer is:'))\n print(' '+note)\n #Translators: {URL} will be substituted with an address to a webpage.\n print(_('Follow the news item instructions on {URL} that are later than the latest handled news item, and then register the latest handled news item.').format(URL=URL))\n print(_('If you do not know how to do that, please contact someone to help you.'))\n else:\n #String is a reason for not being able to return a news string.\n print(_('It could not be determined if the latest news about manual upgrades, has been handled on this computer.'))\n print(_('Reason:'))\n print(note)\n print(_('The system will not be upgraded at this time.'))\n print(_('You will have to upgrade some other time.'))\n return False\n","sub_path":"usr/lib/archupgrade/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"496831622","text":"import PyPDF2\nfrom PyPDF2 import PdfFileReader\n\nimport pandas as pd\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport spacy\nfrom spacy.lang.es import Spanish\nfrom spacy.lang.es.stop_words import STOP_WORDS\n\nimport sklearn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nimport pickle\nimport string\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef extract_pdf(paths):\n all_parties = []\n for path in paths:\n party_pdf = open(path, mode='rb')\n party = PyPDF2.PdfFileReader(party_pdf)\n pages = party.getNumPages()\n all_text = []\n for page in range(pages):\n info = party.getPage(page)\n text = info.extractText()\n text_clean = re.sub('\\n', '', text)\n text_clean = re.sub(\"˜\", \"fi\", text_clean)\n text_clean = re.sub(\"-\", \"\", text_clean)\n all_text.append(text_clean)\n all_parties.append(str(all_text))\n\n return all_parties\n\ndef spacy_tokenizer(sentence):\n nlp=spacy.load('es')\n parser = Spanish()\n spacy_stopwords = spacy.lang.es.stop_words.STOP_WORDS\n STOPWORDS=list(spacy_stopwords)\n STOPWORDS.extend(('y','a','u','o','e','quiero','España'))\n tokens = parser(sentence)\n filtered_tokens = []\n for word in tokens:\n lemma = word.lemma_.lower().strip()\n lemma=re.sub(\"á\", \"a\", lemma)\n lemma=re.sub(\"é\", \"e\", lemma)\n lemma=re.sub(\"í\", \"i\", lemma)\n lemma=re.sub(\"ó\", \"o\", lemma)\n lemma=re.sub(\"ú\", \"u\", lemma)\n lemma=re.sub(\"ñ\", \"n\", lemma)\n if lemma not in STOPWORDS and re.search('^[a-zA-Z]+$', lemma):\n filtered_tokens.append(lemma)\n return filtered_tokens\n\nparty_names=['Podemos','PSOE','Ciudadanos', 'PP','Vox']\npath_list=['data/podemos.pdf','data/psoe.pdf','data/ciudadanosV2.pdf','data/pp.pdf','data/vox.pdf']\nparties=extract_pdf(path_list)\ntfidf_vectorizer = TfidfVectorizer(tokenizer=spacy_tokenizer, ngram_range=(1,2) )\ntfidf_matrix = tfidf_vectorizer.fit_transform(parties)\n\n#tfidf_vectorizer_pkl_filename = 'tfidf_vectorizer.Wed.pkl'\ntfidf_vectorizer_pkl = open('tfidf_vectorizer.Wed.pkl', 'wb')\npickle.dump(tfidf_vectorizer, tfidf_vectorizer_pkl)\n\n#tfidf_matrix_pkl_filename = 'tfidf_matrix.Wed.pkl'\ntfidf_matrix_pkl = open('tfidf_matrix.Wed.pkl', 'wb')\npickle.dump(tfidf_matrix, tfidf_matrix_pkl)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"651956689","text":"import json\nimport os\nimport uuid\nfrom datetime import datetime as dt\n\nfrom query_builder.domain_model.dtos import Query as QueryDTO, Step as StepDTO, \\\n Threshold as Threshold, ReadTime\nfrom query_builder.domain_model.models import Query as QueryModel, \\\n Step as StepModel\n\nSTEPS_MODEL = []\nREF_TIME = ReadTime(\n _type='TIMESTAMP',\n value=\"1w\",\n zone=None\n)\n\n\nTHRESHOLD_STEP_1 = Threshold(operator='ge', value='15')\nTHRESHOLD_STEP_2 = Threshold(operator='le', value='15')\n\nSTEPS_MODEL_1 = StepModel(uuid.uuid4(), order=1, scc_resource_type=\"ASSET\",\n out_value=\"attribute.parent_id\",\n threshold_operator=THRESHOLD_STEP_1.operator, threshold_value=THRESHOLD_STEP_1.value,\n read_time_type=REF_TIME._type,\n read_time_value=REF_TIME.value,\n read_time_zone=REF_TIME.zone, in_value=None,\n filter=\"attribute.asset_type = \\\"Firewall\\\" AND property.allowed : \\\"0-65535\\\"\",\n last_execution_status=\"fail\",last_execution_result=5) \nSTEPS_MODEL.append(STEPS_MODEL_1)\nSTEPS_MODEL_2 = StepModel(uuid.uuid4(), order=2, scc_resource_type=\"ASSET\",\n in_value=\"attribute.parent_id\",\n compare_duration=\"1w\",\n threshold_operator=THRESHOLD_STEP_2.operator, threshold_value=THRESHOLD_STEP_2.value,\n read_time=None, out_value=None,\n filter=\"attribute.asset_type = \\\"Instance\\\"\",\n last_execution_status=None,last_execution_result=None)\nSTEPS_MODEL.append(STEPS_MODEL_2)\nQUERY_MODEL = QueryModel(uuid=\"087d49d1-5296-4270-997c-9074d9079a5a\", name='number_1',\n description='some description for first query',\n owner='dandrade@ciandt.com', topic='topic', steps=STEPS_MODEL,\n sendNotification=True,\n last_execution_result=None, last_execution_status=None, last_execution_date=None)\n\nSTEPS_DTO = []\n\nSTEPS_DTO_1 = StepDTO(order=STEPS_MODEL_1.order, kind=STEPS_MODEL_1.scc_resource_type,\n out_join=STEPS_MODEL_1.out_value,\n threshold=THRESHOLD_STEP_1,\n last_execution_status=STEPS_MODEL_1.last_execution_status,\n last_execution_result=STEPS_MODEL_1.last_execution_result,\n read_time=REF_TIME, in_join=STEPS_MODEL_1.in_value,\n filter_=STEPS_MODEL_1.filter, uuid=QUERY_MODEL.uuid)\nSTEPS_DTO.append(STEPS_DTO_1)\nSTEPS_DTO_2 = StepDTO(order=STEPS_MODEL_2.order, kind=STEPS_MODEL_2.scc_resource_type,\n out_join=STEPS_MODEL_2.out_value,\n threshold=THRESHOLD_STEP_2,\n last_execution_status=STEPS_MODEL_2.last_execution_status,\n last_execution_result=STEPS_MODEL_2.last_execution_result,\n read_time=REF_TIME, in_join=STEPS_MODEL_2.in_value,\n filter_=STEPS_MODEL_2.filter, uuid=QUERY_MODEL.uuid)\nSTEPS_DTO.append(STEPS_DTO_2)\nQUERY_DTO = QueryDTO(uuid=QUERY_MODEL.uuid, name=QUERY_MODEL.name,\n description=QUERY_MODEL.description,\n owner=QUERY_MODEL.owner, topic=QUERY_MODEL.topic,\n send_notification=QUERY_MODEL.sendNotification, \n last_execution_date=QUERY_MODEL.last_execution_date,\n last_execution_result=QUERY_MODEL.last_execution_result,\n last_execution_status=QUERY_MODEL.last_execution_status)\n\nQUERY_DTO_WITH_LAST_EXECUTION = QueryDTO(uuid=QUERY_MODEL.uuid,\n name=QUERY_MODEL.name,\n description=QUERY_MODEL.description,\n owner=QUERY_MODEL.owner,\n topic=QUERY_MODEL.topic,\n send_notification=QUERY_MODEL.sendNotification,\n last_execution_date=dt(2019, 1, 14, 10,\n 34, 55),\n last_execution_result=8,\n last_execution_status='SUCCESS')\n\n\ndef load_json_file(path):\n json_file = open(path, 'r')\n json_object = json.loads(json_file.read())\n json_file.close()\n return json_object\n\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nQUERY_JSON_WITH_STEPS = load_json_file(PATH + \"/query_json_with_steps.json\")\nQUERY_JSON_STEP = load_json_file(PATH + \"/step.json\")\nQUERY_JSON_WITHOUT_STEPS = load_json_file(PATH + \"/query_without_steps.json\")\nQUERY_JSON_WITH_STEPS_WITH_LAST_EXECUTION = load_json_file(\n PATH + \"/query_json_with_steps_with_last_execution.json\")\nQUERY_JSON_WITH_STEPS_WITHOUT_LAST_EXECUTION = load_json_file(\n PATH + \"/query_json_with_steps_without_last_execution.json\")\n","sub_path":"securitycenter/query-builder/back/tests/helpers/query_objects.py","file_name":"query_objects.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"461499578","text":"class MockHeaders(object):\n\n def __init__(self, requested_page):\n Link = 'Links ; rel=\"next\", ; rel=\"last\"'.format( # noqa E501\n min(requested_page + 1, 4)\n )\n self.headers = {'Link': Link}\n\n\nclass MockObject(object):\n\n def __init__(self, page, kwargs):\n self._response = MockHeaders(page)\n self.json = {'page': page, 'kwargs': kwargs}\n # self.is_last_page = True if page == 4 else False\n # self.next_page = min(page + 1, 4) if page else 2\n\n\ndef MockResponse(page=None, **kwargs):\n print('mr', page, kwargs)\n return MockObject(page, kwargs)\n\n\nclass TestOctokit(object):\n\n def test_can_instantiate_class(self):\n import octokit\n assert isinstance(octokit.Octokit, object)\n octo = octokit.Octokit()\n assert isinstance(octo, object)\n\n def test_can_import_class(self):\n from octokit import Octokit\n assert isinstance(Octokit, object)\n octokit = Octokit()\n assert isinstance(octokit, object)\n\n def test_clients_are_lower_case(self):\n from octokit import Octokit\n assert all(client.islower() for client in Octokit.__dict__)\n\n def test_pagination(self):\n from octokit import Octokit\n sut_obj = MockResponse\n p = Octokit().paginate(sut_obj, param='value')\n assert next(p) == {'page': 1, 'kwargs': {'param': 'value'}}\n assert next(p) == {'page': 2, 'kwargs': {'param': 'value'}}\n assert next(p) == {'page': 3, 'kwargs': {'param': 'value'}}\n assert next(p) == {'page': 4, 'kwargs': {'param': 'value'}}\n","sub_path":"tests/test_octokit.py","file_name":"test_octokit.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"570112120","text":"\nclass GameModel():\n FIELD_WIDTH = 10\n FIELD_HEIGHT = 20\n\n\n def __init__(self):\n self.board = []\n self.fallingPiece = None\n self.nextPiece = None\n self.score = 0\n self.gameOver = False\n self.action_queue = []\n\n for i in range(0, self.FIELD_HEIGHT):\n self.board.append([0]*self.FIELD_WIDTH)\n self.nextPiece = ModelPiece()\n\n def maxHeights(self):\n res = [0]*10\n for i in range(0, len(self.board)):\n for j in range(0, len(self.board[i])):\n if self.board[i][j] != 0:\n res[j] = i+1\n return res\n\n def isValid(self, adjX, adjY):\n heights = self.maxHeights()\n for box in self.fallingPiece.boxes:\n if self.fallingPiece.x + box[0] + adjX < 0:\n return False\n if self.fallingPiece.x + box[0] + adjX >= self.FIELD_WIDTH:\n return False\n if self.fallingPiece.y + box[1] + adjY < 0:\n return False\n if self.fallingPiece.y + box[1] + adjY >= self.FIELD_HEIGHT:\n continue\n if self.board[self.fallingPiece.y + box[1] + adjY][self.fallingPiece.x + box[0] + adjX] != 0:\n return False\n return True\n\n def turn(self):\n if not self.fallingPiece:\n self.fallingPiece = self.nextPiece\n self.nextPiece = ModelPiece()\n self.fallingPiece.x = int(self.FIELD_WIDTH/2)\n self.fallingPiece.y = self.FIELD_HEIGHT\n\n if len(self.action_queue) > 0:\n action = self.action_queue.pop(0)\n if action == 'R' and self.isValid(1, 0):\n self.fallingPiece.x += 1\n if action == 'L' and self.isValid(-1, 0):\n self.fallingPiece.x -= 1\n if action == 'D':\n while self.isValid(0, -1):\n self.fallingPiece.y -= 1\n if action == 'U':\n self.fallingPiece.rotate()\n if self.isValid(0, -1):\n self.fallingPiece.y -= 1\n else:\n self.fallingPiece.fixBoxes(self)\n self.fallingPiece = None\n self.action_queue = []\n self.checkRows()\n def checkRows(self):\n self.board[:] = [x for x in self.board if len(list(filter(lambda a: a !=0, x))) < self.FIELD_WIDTH]\n self.score += self.FIELD_HEIGHT - len(self.board)\n for i in range(len(self.board), self.FIELD_HEIGHT):\n self.board.append([0]*self.FIELD_WIDTH)\n\nclass ModelPiece():\n def __init__(self):\n x = y = 0\n self.boxes = []\n self.boxes.append((0,0))\n # self.boxes.append((1,0))\n\n def fixBoxes(self, gameModel):\n for box in self.boxes:\n if self.y + box[1] >= len(gameModel.board):\n gameModel.gameOver = True\n return\n gameModel.board[self.y + box[1]][self.x + box[0]] = 1\n\n def rotate(self):\n new_boxes = []\n for a,b in self.boxes:\n new_boxes.append((b, -a))\n self.boxes = new_boxes\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"30528924","text":"import pyglet\nimport math\nfrom pyglet.gl import *\nfrom pyglet.window import key\nfrom pyglet.window import mouse\n\nfrom Updateable import Updateable\nfrom Drawable \timport Drawable\nfrom Robot \t\timport Robot\nfrom Box \t\timport Box\nfrom Conveyor \timport Conveyor\nfrom Programmer import Programmer\nfrom Delivery_Block import Delivery_Block\nfrom Config\t\timport Config\nfrom Program_Visualiser import Program_Visualiser\nfrom Program_Builder import Program_Builder\n\nwindow_height \t= Config.get_val(\"window_height\")\nwindow_width \t= Config.get_val(\"window_width\")\nscore\t\t\t= Config.get_val(\"score\")\ntime_count\t\t= Config.get_val(\"time_count\")\nsize\t\t\t= Config.get_val(\"size\")\n\nclass Main_Window(pyglet.window.Window):\n\tdef __init__(self):\n\t\tsuper(Main_Window, self).__init__(width=window_width, height=window_height)\n\t\tself.set_caption(\"BlockBots!\")\n\n\t\tself.selected = 0\n\t\tself.instruction = \"program builder\"\n\t\tself.console = pyglet.text.Label(text=self.instruction, y=5, x=5)\n\t\tself.score = pyglet.text.Label(text=str(score), x=int(window_width/2), y=int(window_height-15), bold=1)\n\t\tself.push_handlers(Updateable()) # Pushing an extra pointless handler onto the stack to be popped later\n\n\t\tpyglet.clock.schedule(self.update)\n\n\t\tself.map_init()\n\n\tdef map_init(self):\n\t\tRobot(pos=[20,0])\n\t\tBox(pos=[20,20])\n\t\tDelivery_Block(pos=[20,60], delivering=1, time=2)\n\t\tProgrammer([20,40], program=\"(0,w,->1)(1,s,)\")\n\t\tConveyor(pos=[20,80], dir=\"d\")\n\t\tBox(pos=[20,80])\n\t\tConveyor(pos=[40,80], dir=\"d\")\n\t\tDelivery_Block(pos=[60,80], delivering=0, time=2)\n\n\t\tRobot(pos=[100,100])\n\t\tBox(pos=[120,100])\n\n\tdef update(self, dt):\n\t\tglobal time_count, score\n\t\ttime_count += dt\n\t\tif(dt != 0):\n\t\t\tscore += Updateable.update(dt, time_count)\n\t\t\tself.score = pyglet.text.Label(text=str(score), x=int(window_width/2), y=int(window_height-15), bold=1)\n\n\tdef select(self, s): # Gives the selected object access to input events\n\t\tself.pop_handlers()\n\t\tself.selected = s\n\t\tself.push_handlers(s)\n\n\tdef on_draw(self):\n\t\tself.clear()\n\t\tDrawable.draw()\n\t\tself.console.draw()\n\t\tself.score.draw()\n\n\tdef on_key_press(self, symbol, modifiers):\n\t\tif symbol == key.ENTER:\n\t\t\tself.selected.set_instruction(self.instruction)\n\n\t\tif symbol == key.BACKSPACE:\n\t\t\tif modifiers & key.MOD_SHIFT:\n\t\t\t\tself.instruction = \"\" # Deletes whole line\n\t\t\telse:\n\t\t\t\tself.instruction = self.instruction[0:len(self.instruction)-1] # Removes last characterobot\n\n\t\t\tself.console = pyglet.text.Label(text=self.instruction, y=5, x=5)\n\n\tdef on_text(self, text):\n\t\tself.instruction += text\n\t\tself.console = pyglet.text.Label(self.instruction, y=5, x=5)\n\n\tdef on_mouse_release(self, x, y, button, modifiers):\n\t\tposition = [int(x - x%size), int(y - y%size)]\n\n\t\tif button == pyglet.window.mouse.LEFT:\n\n\t\t\tif self.instruction.startswith(\"box\"):\n\t\t\t\tself.select(Box(position))\n\t\t\telif self.instruction.startswith(\"programmer\"):\n\t\t\t\tself.select(Programmer(position, program=self.instruction.split(\"programmer\")[1]))\n\t\t\telif self.instruction.startswith(\"conveyor\"):\n\t\t\t\tself.select(Conveyor(pos=position, dir=self.instruction.split(\" \")[1]))\n\t\t\telif self.instruction.startswith(\"robot\"):\n\t\t\t\tself.select(Robot(pos=position))\n\t\t\telif self.instruction.startswith(\"delivery\"):\n\t\t\t\tself.select(Delivery_Block(pos=position, delivering=int(self.instruction.split(\" \")[1]), time=int(self.instruction.split(\" \")[2])))\n\t\t\telif self.instruction.startswith(\"program visualiser\"):\n\t\t\t\tself.select(edProgram_Visualiser(pos=position, instruction=self.instruction.split(\"program visualiser\")[1]))\n\t\t\telif self.instruction.startswith(\"program builder\"):\n\t\t\t\tself.select(Program_Builder(pos=position))\n\t\t\telif self.instruction.startswith(\"select\"):\n\t\t\t\tfor d in Drawable.drawables:\n\t\t\t\t\tif d.position == position:\n\t\t\t\t\t\tself.select(d)\n\t\t\telif self.instruction == \"delete\":\n\t\t\t\tfor d in Drawable.drawables:\n\t\t\t\t\tif d.position == position:\n\t\t\t\t\t\tif d is self.selected:\n\t\t\t\t\t\t\tself.selected = 0\n\t\t\t\t\t\td.delete()\n\nwindow = Main_Window()\npyglet.app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161158730","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Function\n\nimport torch_dwconv_C\n\ndef make_tuple(value, n_value):\n if not isinstance(value, (list, tuple)):\n return (value,) * n_value\n\n else:\n n_item = len(value)\n\n if n_item > n_value:\n raise ValueError(\n f'Number items does not match with requirements: {n_item}, expected: {n_value}'\n )\n\n if len(value) == n_value:\n return value\n\n return value * n_value\n\ndef check_options(in_channels, out_channels, bias):\n if in_channels != out_channels:\n raise ValueError('DepthwiseConv2d does not support in_channels != out_channels')\n\n if bias:\n raise ValueError('DepthwiseConv2d does not support bias')\n\n\nclass DepthwiseConv2dFunction(Function):\n @staticmethod\n def forward(ctx, input, weight, stride, pad):\n ctx.stride = stride\n ctx.pad = pad\n\n ctx.save_for_backward(input, weight)\n\n _, _, in_h, in_w = input.size()\n out = torch_dwconv_C.dwconv2d(\n input, weight, 1, 1, *stride, pad[0], pad[0], pad[1], pad[1], True\n )\n\n _, _, out_h, out_w = out.size()\n\n ctx.g_pad = (\n weight.size(2) - pad[0] - 1,\n in_h - out_h * stride[0] + pad[0],\n weight.size(3) - pad[1] - 1,\n in_w - out_w * stride[1] + pad[1],\n )\n \n return out\n \n @staticmethod\n def backward(ctx, grad_output):\n input, weight = ctx.saved_tensors\n\n stride = ctx.stride\n pad = ctx.pad\n g_pad = ctx.g_pad\n\n grad_input = torch_dwconv_C.dwconv2d(\n grad_output, weight, *stride, 1, 1, *g_pad, False\n )\n\n grad_weight = torch_dwconv_C.dwconv2d_backward_kernel(\n input, grad_output, weight, 1, 1, *stride, *pad\n )\n #print(\"grad_input size \",grad_input.size(), \"grad_weights size\", grad_weight.size())\n return grad_input, grad_weight, None, None, None, None\n\n\nclass DepthwiseConv2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, \n padding=0, bias=False):\n super().__init__()\n\n check_options(in_channels, out_channels, bias)\n\n self.stride = make_tuple(stride, 2)\n self.padding = make_tuple(padding, 2)\n self.in_channel = in_channels\n self.kernel_size = kernel_size\n\n self.weight = nn.Parameter(\n torch.randn(out_channels, 1, kernel_size, kernel_size)\n )\n\n self._initialize_weights()\n\n def _initialize_weights(self):\n nn.init.kaiming_normal_(self.weight, mode='fan_out', nonlinearity='relu')\n\n def forward(self, input):\n return DepthwiseConv2dFunction.apply(input, self.weight, self.stride, self.padding)\n","sub_path":"models/torch_dwconv/dwconv.py","file_name":"dwconv.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"179716454","text":"def read_file():\n \"\"\"\n Converts file in list of lines and checks size of field\n >read_file()\n >> %lines%, True\n \"\"\"\n temp = False\n i = 0\n with open(\"file.txt\", \"r\") as f:\n lines = f.readlines()\n if len(lines) > 10:\n return temp\n else:\n while i < 10:\n if len(lines[i]) > 10:\n return temp\n else:\n i += 1\n return lines, temp\n\ndef has_ship(x, y):\n \"\"\"\n Checks content of that coordinate. If there is normal or damaged ship - returns True.\n >has_ship(0, 0)\n >> False\n \"\"\"\n temp = False\n lines = read_file()\n if lines[x][y] == \"*\" or lines[x][y] == \"X\":\n temp = True\n return temp\n\n\ndef ship_size(x, y):\n \"\"\"\n Checks content of coordinate. If there is any ship, than returns its size.\n >ship_size(0,0)\n >>3\n \"\"\"\n size = 0\n if has_ship(x, y):\n size += 1\n if has_ship(x-1, y):\n size += 1\n if has_ship(x - 2, y):\n size += 1\n if has_ship(x - 3, y):\n size += 1\n elif has_ship(x+1, y):\n size += 1\n if has_ship(x+2, y):\n size += 1\n if has_ship(x+3, y):\n size += 1\n elif has_ship(x, y-1):\n size += 1\n if has_ship(x, y-2):\n size += 1\n if has_ship(x, y-3):\n size += 1\n elif has_ship(x, y+1):\n size += 1\n if has_ship(x, y+2):\n size += 1\n if has_ship(x, y+3):\n size += 1\n return size\n\n\ndef is_valid():\n \"\"\"\n Checks number of ships on the field\n >is_valid()\n >>True\n \"\"\"\n temp = False\n i = 0\n j = 0\n cap_ship = 0 #size 4\n large_ship = 0 #size 3\n mid_ship = 0 #size 2\n small_ship = 0 #size 1\n while i < 11:\n while j < 11:\n if ship_size(i, j) == 4:\n cap_ship += 1\n j += 1\n elif ship_size(i, j) == 3:\n large_ship += 1\n j += 1\n elif ship_size(i, j) == 2:\n mid_ship += 1\n j += 1\n elif ship_size(i, j) == 1:\n small_ship += 1\n j += 1\n i += 1\n j = 0\n if (cap_ship == 4) and (large_ship == 6) and (mid_ship == 6) and (small_ship == 4):\n temp = True\n return temp\n\n","sub_path":"battle_of_ships.py.py","file_name":"battle_of_ships.py.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"51067404","text":"#! python3\r\n# mapIt.py - Launches a map in the browser using an address from the\r\n# command line or clipboard.\r\n# Ok lets look at another protocol http\r\n\r\n\r\nimport webbrowser, sys\r\n\r\nif len(sys.argv) > 1:\r\n # Get address from command line.\r\n address = ' '.join(sys.argv[1:])\r\n webbrowser.open('https://www.google.com/maps/place/' + address)\r\nelse:\r\n # Get address from clipboard.\r\n address = 'Bangalore'\r\n webbrowser.open('https://www.google.com/maps/place/' + address)\r\n\r\n# a few things here sys.argv[] is contains all command line parameters\r\n# http - stands for hypertext transfer protocol\r\n# there are 3 important things to remember\r\n# connectionless \r\n# media independent\r\n# stateless\r\n# http primary mechanisms are \r\n# 1 send a request() close()\r\n# 2.send a response() close()\r\n# watch this video for a quick understanding of request and response\r\n# https://youtu.be/eesqK59rhGA\r\n# Think of http as a messenger\r\n# you can send text, video, audio etc\r\n# http is an application level protocol and which means\r\n# the 2 systems that need to communicate must be physically connected\r\n# and able to connect with each other http uses TCP communication\r\n# http is defined by rules - so has rigor in it\r\n# http is all text (not actually)divided into 3 parts\r\n# Request \r\n# -------\r\n# start , header and body\r\n# body can contain binary data \r\n# start line contains some methods asking what to do\r\n# GET, POST etc and then what to get or post and the version of http\r\n# headers contains name, value pairs like what language, data content etc\r\n# Response\r\n# --------\r\n# start line contains\r\n# version of http\r\n# contains status code\r\n# 200 ok\r\n# 404 file not found\r\n# header contains name value pairs\r\n# and finally the body contains the actual file itself\r\n# This groslly simplified\r\n# but enough for our purpose for http\r\n#-------------------------------------\r\n# to get going we need to import\r\nimport requests\r\n#let us send a request\r\nres = requests.get('https://automatetheboringstuff.com/files/rj.txt')\r\n# let us examine this guy\r\ntype(res)\r\n# what are its properties\r\ndir(res)\r\n# what is the url,status_code\r\nprint(res.url+str(res.status_code))\r\n# what text came in the body\r\nprint(res.text)\r\nprint(len(res.text))\r\n# so what is the file is not found - how do we gracefully handle this\r\nres = requests.get('https://automatetheboringstuff.com/files/page_that_does_not_exist')\r\n#there is a method for handling this stuff\r\n# raise_for_status()\r\nimport requests\r\nres = requests.get('https://automatetheboringstuff.com/files/page_that_does_not_exist')\r\ntry:\r\n res.raise_for_status()\r\nexcept Exception as exc:\r\n print('%s' %(exc))\r\n# for a file found\r\nimport requests\r\nres = requests.get('https://automatetheboringstuff.com/files/rj.txt')\r\ntry:\r\n res.raise_for_status()\r\nexcept Exception as exc:\r\n print('%s' %(exc))\r\n#we have a nice method call iter_content which returns the text in chunks of \r\n#the parameter specified\r\nimport requests\r\nimport os\r\nres = requests.get('https://automatetheboringstuff.com/files/rj.txt')\r\ntry:\r\n res.raise_for_status()\r\n playFile=open('RomeoAndJuliet.txt','wb')\r\n for chunk in res.iter_content(100000):\r\n playFile.write(chunk)\r\n playFile.close()\r\nexcept Exception as exc:\r\n print('%s' %(exc))\r\n# now that you now how to download files and videos etc\r\n# Yesterday I wanted you to use regular expressions to parse HTML\r\n# but like every Prof today I dont want you to do it\r\n# There is this very nice module called beautiful soup which can help you \r\n# parse HTML\r\n# So let us import this guy\r\nimport requests, bs4\r\n# There is a nice function called beautufulsoup that returns\r\n# what else soup not ketchup object with which we can do a variety of things\r\n# so lets have some fun\r\nres=requests.get('https://www.pes.edu') \r\n# lets get the soup out of the way\r\nsoup=bs4.BeautifulSoup(res.text)\r\nprint(soup)\r\nprint(type(soup))\r\n#me no teach html but we all know html, div,#author which are all elements of HTML\r\nprint(soup.select('#author'))\r\n# :( no author\r\nprint(soup.select('div'))\r\n# Let us use a URL which has these elements filled in\r\nres=requests.get('https://nostarch.com') \r\n# lets get the soup out of the way\r\nsoup=bs4.BeautifulSoup(res.text)\r\nelement=(soup.select('div'))\r\nfor i in range(100):\r\n print(element[i])\r\n# There are other nice elements of beutuful soup\r\n# Let us explore some of them\r\n# soup.find_all('b') - Finds all the b tags\r\n# print soup.find_all([\"a\", \"b\"]) find all tags a and b\r\n# for tag in soup.find_all(True):\r\n# print(tag.name)\r\n# prints all tags\r\n# Read about this in https://www.pythonforbeginners.com/beautifulsoup/beautifulsoup-4-python\r\n# for doing the exercise - The topic here is http and so \r\n# I have not gone into details","sub_path":"day2/d2p6.py","file_name":"d2p6.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44434242","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 4 11:20:04 2020\r\n\r\n@author: USER\r\n\"\"\"\r\n\r\nimport random\r\nxyz = random.randint(1,20)\r\n\r\nwhile True:\r\n a=int (input(\"請輸入1~20的數字: \")) \r\n if a<0 and a>=20:\r\n print(\"錯誤\")\r\n else:\r\n if xyz a:\r\n print(\"大一點\")\r\n else:\r\n print(\"BINGO\")\r\n break\r\n","sub_path":"day2-2.py","file_name":"day2-2.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"408405850","text":"\"\"\"\n@ File: index_monitor.py\n@ Author: pleiadesian\n@ Datetime: 2020-04-21 09:01\n\"\"\"\nimport time\nimport tushare as ts\nfrom subprocess import call\n\nwhile True:\n df = ts.get_realtime_quotes('sh')\n time.sleep(3)\n if float(df.price) > 2837.0:\n cmd = 'display notification \\\"' + \\\n \"At expected price\" + '\\\" with title \\\"Price alert\\\"'\n call([\"osascript\", \"-e\", cmd])\n","sub_path":"util/index_monitor.py","file_name":"index_monitor.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510389706","text":"import pandas as pd\n\nmovies_df = pd.read_csv(\"IMDB-Movie-Data.csv\", index_col=\"Title\")\nmovies_df.columns = ['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 'rating', 'votes', 'revenue_millions', 'metascore']\n\ndef rating_function(x):\n if x >= 8.0:\n return \"good\"\n else:\n return \"bad\"\n\nmovies_df[\"rating_category\"] = movies_df[\"rating\"].apply(rating_function) #apply defined function on rating and create new column called \"rating category\"\n\n#or with lamda\nmovies_df[\"rating_category\"] = movies_df[\"rating\"].apply(lambda x: 'good' if x >= 8.0 else 'bad')\n\n\n\n","sub_path":"learning-and-practising/pandas/pd-applying_functions.py","file_name":"pd-applying_functions.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"506312454","text":"#!/usr/bin/env python\n\nimport sys\nimport time\nfrom datetime import datetime ,timedelta\n\nfrom opcua import Client\nfrom opcua import ua\n\n\nfrom Setup_MYSQL_V1_0_0 import MYSQL_Database\n\n\nBarn_Number = 1\nDevice_Name = \"HMI_Barn_1\"\nHMI_IP = \"192.168.0.12\"\nOPC_Port = \"48010\"\n\nInsert = \"_\"+str(Barn_Number)\nPLC_Time = None\n\n\nclass History_Submit(object):\n SW_Tag_Data = None\n SW_Tag_Label = None\n SW_Tag_Update = False\n \n History_Tag_Data = []\n History_Tag_Label = []\n History_Tag_Update = False\n Array_Type = False\n\n\n\n def mysql_history_update(self):\n val = self.History_Tag_Data\n tag_name = self.History_Tag_Label\n \n tag_values = []\n tag_names = []\n if type(val) is list:\n for i in range(0, len(val), 1):\n tag_names.append(tag_name[i]+\"[\"+str(i)+\"]\")\n tag_values.append(val[i])\n else:\n tag_values = val\n tag_names = tag_name\n \n # Get Table Names\n Q = \"SELECT Tag_Name FROM Full_History\"\n data = Database.DB_Fetch(Q)\n data_list = []\n if data != []:\n for i in data:\n data_list.append(list(i)[0])\n \n if data_list == []:\n if type(tag_names) is list:\n for i in range(0, len(tag_names), 1):\n ii = i\n Q = \"INSERT INTO Full_History (Tag_Name, History_Label, Tag_Value, Device_ID) VALUES (%s, %s, %s, %s)\"\n var = (tag_names[i]+Insert, tag_names[i], tag_values[i], Barn_Number)\n Database.DB_Insert(Q, var)\n else:\n \n if tag_names[0]+Insert not in data_list:\n if type(tag_names) is list:\n for i in range(0, len(tag_names), 1):\n ii = i\n Q = \"INSERT INTO Full_History (Tag_Name, History_Label, Tag_Value, Device_ID) VALUES (%s, %s, %s, %s)\"\n var = (tag_names[i]+Insert, tag_names[i], tag_values[i], Barn_Number)\n Database.DB_Insert(Q, var)\n else: \n if type(tag_names) is list:\n for i in range(0, len(tag_names), 1):\n Q = \"UPDATE Full_History SET Tag_Value = %s WHERE Tag_Name = %s\"\n var = (tag_values[i], tag_names[i]+Insert)\n Database.DB_Insert(Q, var)\n \n self.History_Tag_Update = False\n\nif __name__ == \"__main__\":\n Database = MYSQL_Database()\n Database.DB_Setup(Barn_Number,Device_Name)\n\n client = Client(\"opc.tcp://\"+HMI_IP+\":\"+OPC_Port)\n\n client.connect()\n client.load_type_definitions()\n root = client.get_root_node()\n #obj = root.get_child([\"0:Objects\", \"2:Tags\"])\n\n #myvar = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//PLC_Time/DT_Now\"])\n #myvar_1 = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//Output_HOA_R/SW\"])\n #myvar_2 = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//Output_HOA_AO_R/SW\"])\n #myvar_3 = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//Output_5POS_R/SW\"])\n\n Mysql = History_Submit()\n\n myvar = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//Full_History/History_REAL\"])\n\n data = myvar.get_value()\n for i in range(0, len(data), 8):\n Mysql.History_Tag_Data.append(data[i])\n\n i_range = len(Mysql.History_Tag_Data)\n\n for i in range(0, i_range, 1):\n myvar = root.get_child([\"0:Objects\", \"2:Tags\", \"2:PLC//Full_History_Label/History_Label[\"+str(i)+\"]\"])\n Mysql.History_Tag_Label.append(myvar.get_value())\n\n \n client.disconnect()\n\n Mysql.mysql_history_update()\n","sub_path":"Programs/History_Management/West_Heritage/V1_0_0/Barn_1_OPC_Sub.py","file_name":"Barn_1_OPC_Sub.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"187123038","text":"from django.urls import path\nfrom . import views\nfrom .views import adminView,answer_delete,quest_delete, adminblogView,post_delete,comment_delete,adminusersView,user_delete\nfrom Blog.views import PostUpdateView\nurlpatterns=[\n path('qaadmin', adminView, name='qaadmin'),\n path('admin_blog', adminblogView, name='admin_blog'),\n path('admin_Users', adminusersView, name='admin_Users'),\n path('answer//delete', answer_delete, name='answer-delete'),\n path('quest//delete', quest_delete, name='quest-delete'),\n path('post//delete', post_delete, name='post-delete'),\n path('comment//delete', comment_delete, name='comment-delete'),\n path('post//update/', PostUpdateView.as_view(), name='post-update'),\n path('user//delete', user_delete, name='user-delete'),\n \n] ","sub_path":"qaadmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"544354539","text":"from selenium import webdriver\nfrom webdriver_manager.firefox import GeckoDriverManager\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nimport random\nimport time\nimport schedule\n\n\ndef tool():\n # ブラウザーを起動\n options = Options()\n # options.binary_location = '/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox'\n options.add_argument('-headless')\n driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(),firefox_options=options)\n\n # 画面を開く。\n driver.get(\"https://www.instagram.com/\")\n time.sleep(4)\n\n # ログインIDを入力する\n id_box = driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[1]/div/label/input')\n id_box.send_keys('ys_shiro19')\n\n #パスワードを入力する\n id_pass = driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[2]/div/label/input')\n id_pass.send_keys('toukoudai2')\n\n #ログインボタンを押す\n lg_box = driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[3]')\n lg_box.click()\n\n time.sleep(5)\n #後でのボタンを押す\n\n WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/section/main/div/div/div/div/button'))).click()\n\n later = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[5]/div/div/div/div[3]/button[2]')))\n later.click()\n\n\n\n time.sleep(3)\n word = ['いいねした人で気になった人フォロー','いいね返しは絶対','21歳','美男美女と繋がりたい','渋谷スカイ','インスタ映え','詐欺師','大学生弁当',\n '大学生ごはん','サークル','春から大学生',]\n x = random.choice(word)\n print(x)\n\n time.sleep(1)\n #ハッシュタグ検索を行う\n srech = driver.find_element_by_xpath('//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/div/div')\n srech.click()\n enter = driver.find_element_by_xpath('//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/input')\n enter.send_keys(x)\n time.sleep(5)\n push = driver.find_element_by_xpath('/html/body/div[1]/section/nav/div[2]/div/div/div[2]/div[3]/div/div[2]/div/div[1]/a/div')\n push.click()\n\n\n time.sleep(3)\n\n #最新の投稿をクリックする\n touko = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/section/main/article/div[2]/div/div[1]/div[1]/a/div/div[2]')))\n\n touko.click()\n\n time.sleep(3)\n\n iine = driver.find_element_by_xpath('/html/body/div[5]/div[2]/div/article/div[3]/section[1]/span[1]/button')\n\n iine.click()\n\n time.sleep(2)\n\n next = driver.find_element_by_xpath('/html/body/div[5]/div[1]/div/div/a[2]')\n\n next.click()\n\n\n for i in range(150):\n time.sleep(1)\n try:\n element = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[5]/div[2]/div/article/div[3]/section[1]/span[1]/button')))\n element.click()\n\n except:\n pass\n finally:\n next2 = driver.find_element_by_xpath('/html/body/div[5]/div[1]/div/div/a[2]')\n next2.click()\n\n\n\n print('終了しました')\n time.sleep(2)\n\n\n # ブラウザーを終了\n driver.quit()\n\n\nschedule.every().day.at(\"13:00\").do(tool)\nschedule.every().day.at(\"14:00\").do(tool)\nschedule.every().day.at(\"15:00\").do(tool)\nschedule.every().day.at(\"16:00\").do(tool)\nschedule.every().day.at(\"17:00\").do(tool)\nschedule.every().day.at(\"18:00\").do(tool)\nschedule.every().day.at(\"19:00\").do(tool)\n\n\nwhile True:\n schedule.run_pending()\n time.sleep(60)\n","sub_path":"p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"164825227","text":"# Time Complexity : O(n) n = length of word\n# Space Complexity : O(n)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n# Your code here along with comments explaining your approach\nclass Trie:\n def __init__(self):\n self.childrens = [False] * 26 \n self.word = '' \n\nclass TrieNode:\n def __init__(self):\n self.root = Trie()\n \n def insert(self,word):\n node = self.root\n for ch in word:\n indx = ord(ch) - ord('a')\n if node.childrens[indx] == False:\n node.childrens[indx] = Trie()\n node = node.childrens[indx]\n node.word = word \n \nclass Solution:\n def replaceWords(self, dict: List[str], sentence: str) -> str:\n t = TrieNode()\n for word in dict:\n t.insert(word)\n result = []\n words = sentence.split(' ')\n for word in words:\n node = t.root\n # print(node.childrens)\n for ch in word:\n indx = ord(ch) - ord('a')\n if not node.childrens[indx] or node.word != '':\n break \n node = node.childrens[indx]\n if node.word :\n result.append(node.word)\n else:\n result.append(word)\n return ' '.join(result)\n \n \n \n \n ","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"512230857","text":"from _ast import Lambda\nfrom tkinter import *\n\nroot = Tk()\nroot.title(\"Image Insertion\")\nroot.iconbitmap('C:/calc.ico')\n\n#defining title of the project\nroot.title(\"Calculator By Niraj\")\nroot.geometry(\"490x480+500+200\")\n\ne =Entry(root,justify=\"right\", width=35,bd=29, bg=\"light green\",font=(\"ariel\", 14), borderwidth=40,)\ne.grid(row=0, column=0,columnspan=4)\n\n\ndef button_click(number):\n current = e.get()\n e.delete(0, END)\n e.insert(0, str(current) + str(number))\n\ndef button_clear():\n e.delete(0,END)\n\ndef button_add():\n first_number = e.get()\n global f_num\n global math\n math = \"addition\"\n f_num = int(first_number)\n e.delete(0, END)\n\ndef button_subtract():\n first_number = e.get()\n global f_num\n global math\n math = \"subtraction\"\n f_num = int(first_number)\n e.delete(0,END)\n\ndef button_multiply():\n first_number = e.get()\n global f_num\n global math\n math = \"multiplication\"\n f_num = int(first_number)\n e.delete(0,END)\n\ndef button_divide():\n first_number = e.get()\n global f_num\n global math\n math = \"division\"\n f_num = int(first_number)\n e.delete(0,END)\n\ndef button_total():\n second_number = e.get()\n e.delete(0, END)\n if math == \"addition\":\n e.insert(0, f_num + int(second_number))\n if math == \"subtraction\":\n e.insert(0, f_num - int(second_number))\n if math == \"multiplication\":\n e.insert(0, f_num * int(second_number))\n if math == \"division\":\n e.insert(0, f_num / int(second_number))\n\n\n\n\n# Defining the buttons\nbutton_1 = Button(root, text=\"1\",padx=40, pady=20,font=(\"Ariel\",14, \"bold\"), bd=10, height=0,command=lambda : button_click(1))\nbutton_2 = Button(root, text=\"2\", padx=40, pady=20, font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(2))\nbutton_3 = Button(root, text=\"3\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(3))\nbutton_4 = Button(root, text=\"4\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(4))\nbutton_5 = Button(root, text=\"5\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(5))\nbutton_6 = Button(root, text=\"6\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(6))\nbutton_7 = Button(root, text=\"7\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(7))\nbutton_8 = Button(root, text=\"8\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(8))\nbutton_9 = Button(root, text=\"9\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(9))\nbutton_0 = Button(root, text=\"0\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=lambda : button_click(0))\nbutton_add = Button(root, text=\"+\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=button_add)\nbutton_total = Button(root, text=\"=\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, bg=(\"light green\"), command=button_total)\nbutton_clear = Button(root, text=\"C\",bg=\"brown\", padx=40,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, pady=20, command=button_clear)\n\n\nbutton_subtract = Button(root, text=\"-\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=button_subtract)\nbutton_multiply = Button(root, text=\"*\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=button_multiply)\nbutton_divide = Button(root, text=\"/\", padx=40, pady=20,font=(\"Ariel\",14, \"bold\"),bd=10, height=0, command=button_divide)\n\n\n\n\n#Putting buttons on the screen\nbutton_1.grid(row=1, column=0)\nbutton_2.grid(row=1, column=1)\nbutton_3.grid(row=1, column=2)\nbutton_clear.grid(row=1, column=3)\n\nbutton_4.grid(row=2, column=0)\nbutton_5.grid(row=2, column=1)\nbutton_6.grid(row=2, column=2)\nbutton_add.grid(row=2, column=3)\n\nbutton_7.grid(row=3, column=0)\nbutton_8.grid(row=3, column=1)\nbutton_9.grid(row=3, column=2)\nbutton_subtract.grid(row=3, column=3)\n\nbutton_divide.grid(row=4, column=0)\nbutton_0.grid(row=4, column=1)\nbutton_multiply.grid(row=4, column=2)\nbutton_total.grid(row=4, column=3)\n\n\n\n\nroot.mainloop()","sub_path":"cal/simpcal.py","file_name":"simpcal.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"209482521","text":"from typing import Iterable\n\nfrom OpenGL import GL as gl\nfrom OpenGL.GL import shaders\nfrom GameUtilities import *\n\n\nclass AABBShader:\n def __init__(self, cube_obj_data: ObjData):\n self.cube_obj_data = cube_obj_data\n\n # Compile shaders\n vertex_shader = shaders.compileShader(\"\"\"#version 330\n layout(location = 0) in vec3 vertex_position;\n uniform mat4 projection;\n uniform mat4 view;\n uniform mat4 transformation;\n\n void main()\n {\n // Because the transformation matrix is 4x4, we have to construct a vec4 from position, so we an multiply them\n vec4 pos = vec4(vertex_position, 1.0);\n gl_Position = projection * view * transformation * pos;\n }\n \"\"\", gl.GL_VERTEX_SHADER)\n\n fragment_shader = shaders.compileShader(\"\"\"#version 330\n out vec4 fragment_color;\n\n void main()\n {\n fragment_color = vec4(1.0, 0.41, 0.70, 1.0);\n }\n \"\"\", gl.GL_FRAGMENT_SHADER)\n\n # Compile the program\n self.id = shaders.compileProgram(vertex_shader, fragment_shader)\n\n # Get the locations\n gl.glUseProgram(self.id)\n self.transformation_location = gl.glGetUniformLocation(self.id, \"transformation\")\n self.view_location = gl.glGetUniformLocation(self.id, \"view\")\n self.projection_location = gl.glGetUniformLocation(self.id, \"projection\")\n gl.glUseProgram(0)\n\n def draw(self, projection, view, aabbs: Iterable[AABB]):\n # Set the polygon mode to lines so we can see the actual object inside the AABB\n gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)\n\n gl.glUseProgram(self.id)\n\n gl.glUniformMatrix4fv(self.projection_location, 1, False, glm.value_ptr(projection))\n gl.glUniformMatrix4fv(self.view_location, 1, False, glm.value_ptr(view))\n\n for aabb in aabbs:\n # Set the vao\n gl.glBindVertexArray(self.cube_obj_data.vao)\n\n AABB_transformation = glm.mat4x4()\n AABB_transformation = glm.translate(AABB_transformation, aabb.get_center())\n AABB_transformation = glm.scale(AABB_transformation, aabb.get_dimensions() / 2.0)\n\n # Set the transform uniform to self.transform\n gl.glUniformMatrix4fv(self.transformation_location, 1, False, glm.value_ptr(AABB_transformation))\n\n for mesh in self.cube_obj_data.meshes:\n # Draw the mesh with an element buffer.\n gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, mesh.element_array_buffer)\n # When the last parameter in 'None', the buffer bound to the GL_ELEMENT_ARRAY_BUFFER will be used.\n gl.glDrawElements(gl.GL_TRIANGLES, mesh.element_count, gl.GL_UNSIGNED_INT, None)\n\n # Set the state to its initial\n gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL)\n","sub_path":"AABBShader.py","file_name":"AABBShader.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"105513095","text":"from PIL import Image, ImageDraw, ImageFont\n\n\nDIMS = (500, 726)\nGREEN = (56, 161, 42)\nYELLOW = (189, 186, 36)\nRED = (166, 38, 38)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\n\ndef makeImage(num, value, color, text_color):\n img = Image.new('RGB', DIMS, color=color)\n d = ImageDraw.Draw(img)\n\n fnt = ImageFont.truetype('arial.ttf', size=75)\n d.text((10, 10), str(value), font=fnt, fill=text_color)\n\n img.save(f\"cardImages/{ num }.png\")\n\n\n# make multicolored 1\nmakeImage(13, 1, BLACK, WHITE)\n\n# make the other cards\nfor value in range(1, 12):\n for c in range(3):\n if c == 0:\n color = GREEN\n elif c == 1:\n color = YELLOW\n else:\n color = RED\n num = 10 * value + c\n makeImage(num, value, color, WHITE)\n ","sub_path":"setup/imageMaker.py","file_name":"imageMaker.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"384324931","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nimport re\nimport csv\nimport pandas as pd\nimport numpy as np\n\n# the goal of this code is to use web scrapingto get winning team season stats \n# I noticed that the table I want to get the data from has different style and different position in\n# each winning team's link. As a result, I had a hard time getting all the data I want through program\n# This program helps me to get every line of data I want except 12 lines out of 54.\n# I have to manually enter data for those 12 lines.\n# main features to scrape: season record, end of the season streak, points for and points against\nroot_url = 'https://en.wikipedia.org/wiki/List_of_Super_Bowl_champions'\nresp = requests.get(root_url)\nsoup = BeautifulSoup(resp.content, \"html.parser\")\ntable = soup.find_all(\"table\")\n# pprint(table[1])\nsuper_bowl_links = table[1].find_all('a')\n# print(super_bowl_links)\nlinks = [super_bowl.get(\"href\") for super_bowl in super_bowl_links]\n# print(links)\n\nhrefs = []\npattern = r'\\w+(?=_season)_season'\nfor href in links:\n\t# print(href)\n\tmatch = re.findall(pattern, href)\n\t# print(match)\n\tif len(match) != 0 and 'NFL' not in match[0] and 'Football' not in match[0]:\n\t \threfs.append(match[0])\n# print(len(hrefs))\n\n# winning_list and losing_list contain sublink to winning teams season and losing teasm season\nwinning_list = [hrefs[i] for i in range(len(hrefs)) if i % 2 == 0]\nlosing_list = [hrefs[i] for i in range(len(hrefs)) if i % 2 == 1]\n# print(winning_list)\n# print(len(winning_list))\n# print(losing_list)\n# print(len(losing_list))\n\nwinning_links = [\"https://en.wikipedia.org/wiki/\" + sublink for sublink in winning_list]\nlosing_links = [\"https://en.wikipedia.org/wiki/\" + sublink for sublink in losing_list]\n# save the losing_links for the next coding file to get the season stats for losing team\n# array = np.array(losing_links)\n# losing_links_tran = array.transpose()\ndf_losing = pd.DataFrame(losing_links)\ndf_losing.to_csv('losing_links.csv')\n\n# print(winning_links)\n# print(losing_links)\n\nwinning_pct = []\npoint_for = []\npoint_against = []\nend_streak = []\nfor link in winning_links:\n\t# print(link)\n\tif 'Louis_Rams_season' in link:\n\t\tlink = 'https://en.wikipedia.org/wiki/1999_St._Louis_Rams_season'\n\tresp = requests.get(link)\n\tsoup = BeautifulSoup(resp.content, \"html.parser\")\n\t# print(len(winning_pct))\n\t# table = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size: 95%;'})\n\tif len(winning_pct) >= 10 and len(winning_pct) < 14:\n\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size: 95%;'})\n\telif len(winning_pct) >= 14 and len(winning_pct) < 15:\n\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size:95%; text-align:center'})\n\telif len(winning_pct) == 21:\n\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size: 95%; text-align:center'})\n\telif len(winning_pct) > 35:\n\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size: 95%;'})\n\telse:\n\t\tif link[35:-7].replace(\"_\",' ') == 'Dallas Cowboys' or link[35:-7].replace(\"_\",' ') == 'Pittsburgh Steelers':\n\t\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size: 95%; text-align:center'})\n\t\telse:\n\t\t\ttable = soup.find_all(\"table\", attrs={'class':'wikitable', 'style':'font-size:95%; text-align:center'})\n\t# pprint(table)\n\ttry:\n\t\tif link[35:-7].replace(\"_\",' ') == 'New York Jets':\n\t\t\tfor item in table[1].find_all('tr'):\n\t\t\t# print(len(item.find_all('td')))\n\t\t\t\tfor i in range(len(item.find_all('td'))):\n\t\t\t\t\t# print(item.find_all('td')[i].text.strip('\\n\\n'))\n\t\t\t\t\t# print(link[35:-7].replace(\"_\",' '))\n\t\t\t\t\tif item.find_all('td')[i].text.strip('\\n\\n') == link[35:-7].replace(\"_\",' '):\n\t\t\t\t\t\twinning_pct.append(item.find_all('td')[4].text.strip())\n\t\t\t\t\t\tpoint_for.append(item.find_all('td')[-3].text.strip())\n\t\t\t\t\t\tpoint_against.append(item.find_all('td')[-2].text.strip())\n\t\t\t\t\t\tend_streak.append(item.find_all('td')[-1].text.strip())\n\t\t\t\t\telse:\n\t\t\t\t\t\ti += 9\n\t\tif \"2011\" in link:\n\t\t\twinning_pct.append(\" \")\n\t\t\tpoint_for.append(\" \")\n\t\t\tpoint_against.append(\" \")\n\t\t\tend_streak.append(\" \")\n\t\telse:\n\t\t\tfor item in table[0].find_all('tr'):\n\t\t\t# print(len(item.find_all('td')))\n\t\t\t\tfor i in range(len(item.find_all('td'))):\n\t\t\t\t\t# print(item.find_all('td')[i].text.strip('\\n\\n'))\n\t\t\t\t\t# print(link[35:-7].replace(\"_\",' '))\n\t\t\t\t\tif item.find_all('td')[i].text.strip('\\n\\n') == link[35:-7].replace(\"_\",' ') \\\n\t\t\t\t\t\tor item.find_all('td')[i].text.strip('\\n\\n')[:-3] == link[35:-7].replace(\"_\",' ') \\\n\t\t\t\t\t\tor item.find_all('td')[i].text.strip('\\n\\n')[3:] == link[35:-7].replace(\"_\",' ') \\\n\t\t\t\t\t\tor item.find_all('td')[i].text.strip('\\n\\n')[4:] == link[35:-7].replace(\"_\",' '):\n\t\t\t\t\t\twinning_pct.append(item.find_all('td')[4].text.strip())\n\t\t\t\t\t\tpoint_for.append(item.find_all('td')[-3].text.strip())\n\t\t\t\t\t\tpoint_against.append(item.find_all('td')[-2].text.strip())\n\t\t\t\t\t\tend_streak.append(item.find_all('td')[-1].text.strip())\n\t\t\t\t\telse:\n\t\t\t\t\t\ti += 9\n\texcept:\n\t\twinning_pct.append(\" \")\n\t\tpoint_for.append(\" \")\n\t\tpoint_against.append(\" \")\n\t\tend_streak.append(\" \")\n\t\t# print the ones that the code are not able to convert, can be manually entered \n\t\t# print(link)\n\t\tcontinue\n\n# remove unrelated item\ndel winning_pct[3]\ndel point_for[3]\ndel point_against[3]\ndel end_streak[3]\n# print(winning_pct)\n# print(len(winning_pct))\n# print(point_for)\n# print(len(point_for))\n# print(point_against)\n# print(len(point_against))\n# print(end_streak)\n# print(len(end_streak))\ninfo = []\ninfo.append(winning_pct)\ninfo.append(point_for)\ninfo.append(point_against)\ninfo.append(end_streak)\n\na = np.array(info)\na_trans = a.transpose()\n\ndf = pd.DataFrame(a_trans, columns = ['winnor_season_winning_pct','winnor_season_point_score', \\\n\t\t\t\t\t\t\t\t\t'winnor_season_point_allow','winnor_end_streak'])\n# print(df.head())\ndf.to_csv(\"Winnor_season_stats.csv\")\n\n\n\n\n\n\n","sub_path":"Data Collection and Cleaning/Data Collection/data_collection4_2.py","file_name":"data_collection4_2.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"360512724","text":"import collections\nimport numpy\nfrom google.colab import files\n\n# Specific to the google environment, upload files from local computer\ndef upload_data():\n uploaded = files.upload()\n\n# Read a data file in csv format, separate into features and class arrays\ndef read_data(type):\n if type == 'train':\n data = numpy.loadtxt(fname='traindata.csv', delimiter=',')\n else:\n data = numpy.loadtxt(fname='testdata.csv', delimiter=',')\n X = data[:,:-1] # features are all values but the last on the line\n y = data[:,-1] # class is the last value on the line\n return X, y\n\n# The simple majority classifier determines the most common class label\n# and labels all instances with that class value\ndef simple_majority_train(X, y):\n majority_class = collections.Counter(y).most_common(1)[0][0]\n return majority_class\n\n# Classify test instances based on majority label\ndef simple_majority_test(X, y, majority_class):\n total = len(y)\n true_positive = 0\n false_positive = 0\n true_negative = 0\n false_negative = 0\n\n for i in range(total): # evaluate each test instance\n label = majority_class # not really needed, just illustrates point\n if label == 0.0: # majority label is negative\n if y[i] == 0.0: # this is a negative instance\n true_negative += 1\n else: # this is a positive instance\n false_negative += 1\n else: # majority label is positive (label == 1.0)\n if y[i] == 0.0: # this is a negative instance\n false_positive += 1\n else: # this is a positive instance\n true_positive += 1\n report_statistics(total, true_positive, false_positive,\n true_negative, false_negative)\n\ndef report_statistics(total, tp, fp, tn, fn):\n print(\"total\", total, \"tp\", tp, \"fp\", fp, \"tn\", tn, \"fn\", fn)\n\n# Train and test simple majority classifier\nif __name__ == \"__main__\":\n upload_data()\n X, y = read_data('train')\n majority_class = simple_majority_train(X, y)\n X, y = read_data('test')\n simple_majority_test(X, y, majority_class)\n","sub_path":"Class_Code/Sample_Majority_Classifier/majority2.py","file_name":"majority2.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"192653297","text":"import pygame\nfrom shared.display import DISPLAY_WIDTH, DISPLAY_HEIGHT, gameDisplay\nfrom shared.text import text_objects\n\n# Button position, configuration, and action\nBUTTON_WIDTH = DISPLAY_WIDTH * 0.25 # Number is a scaling factor. On 1920 screen this is a 300mm button\nBUTTON_HEIGHT = DISPLAY_HEIGHT * 0.17 # Number is a scaling factor. On 1080 screen this is a 150mm button\nBUTTON_CENTER_HORIZONTAL = (DISPLAY_WIDTH*0.5)-(BUTTON_WIDTH/2)\nBUTTON_CENTER_ONE_THIRD = (DISPLAY_WIDTH*0.33)-(BUTTON_WIDTH/2)\nBUTTON_CENTER_TWO_THIRD = (DISPLAY_WIDTH*0.66)-(BUTTON_WIDTH/2)\nBUTTON_CENTER_VERTICAL = (DISPLAY_HEIGHT*0.5)-(BUTTON_HEIGHT/2)\n\ndef button(msg,x,y,w,h,ic,ac,action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if x+w > mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(gameDisplay, ac,(x,y,w,h))\n if click[0] == 1 and action != None:\n action() \n else:\n pygame.draw.rect(gameDisplay, ic,(x,y,w,h))\n smallText = pygame.font.SysFont(\"comicsansms\",20)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ( (x+(w/2)), (y+(h/2)) )\n gameDisplay.blit(textSurf, textRect)","sub_path":"shared/buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"359513617","text":"from Pokemon import Pokemon\r\n\r\n\r\nCAPACITY = 100\r\n\r\n\r\nclass Node:\r\n def __init__(self, key, value):\r\n self.key = key\r\n self.value = value\r\n self.next = None\r\n\r\n\r\nclass hashtable:\r\n def __init__(self):\r\n self.size = 0\r\n self.capacity = CAPACITY\r\n self.slots = [None] * self.capacity\r\n\r\n def hashfunction(self, key):\r\n hashsum = 0\r\n\r\n for index, char in enumerate(key):\r\n hashsum += (index + len(key)) ** ord(char)\r\n hashsum = hashsum % self.capacity\r\n\r\n return hashsum\r\n\r\n def store(self, key, data):\r\n self.size += 1\r\n\r\n index = self.hashfunction(key)\r\n\r\n node = self.slots[index]\r\n\r\n if node is None:\r\n self.slots[index] = Node(key, data)\r\n return\r\n\r\n prev = node\r\n while node is not None:\r\n prev = node\r\n node = node.next\r\n prev.next = Node(key, data)\r\n\r\n def search(self, key):\r\n index = self.hashfunction(key)\r\n node = self.slots[index]\r\n\r\n while node is not None and node.key != key:\r\n node = node.next\r\n\r\n if node is None:\r\n return None\r\n else:\r\n return node.value\r\n\r\n\r\nblabla = hashtable()\r\n\r\n\r\ndef read_create_pokemon_from_file():\r\n fr = open(\"pokemon.csv\")\r\n fr_list = []\r\n list_of_pokemon = []\r\n fr.readline()\r\n var = 0\r\n for i in fr.readlines():\r\n fr_list.append(i.strip().split(\",\"))\r\n list_of_pokemon.append(Pokemon(fr_list[var][0], fr_list[var][1], fr_list[var][2], fr_list[var][3],\r\n float(fr_list[var][4]), float(fr_list[var][5]), float(fr_list[var][6]),\r\n float(fr_list[var][7]), float(fr_list[var][8]), float(fr_list[var][9]),\r\n float(fr_list[var][10]), int(fr_list[var][11]), fr_list[var][12]))\r\n var += 1\r\n fr.close()\r\n for pokemon in list_of_pokemon:\r\n blabla.store(pokemon.name, pokemon)\r\n return list_of_pokemon\r\n\r\nread_create_pokemon_from_file()\r\n\r\n","sub_path":"Hash.py","file_name":"Hash.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"279576496","text":"import json\n\nimport pandas as pd\n\nIN_FOLDER = \"data/repertoires/csv/\"\nOUT_FILEPATH = \"data/stats.json\"\n\ndf = pd.read_csv(IN_FOLDER + \"all.csv\")\n\nnb_repos = len(df)\nnb_orgs = len(df.groupby(\"organisation_nom\"))\navg_nb_repos = df.groupby(\"organisation_nom\").count()[\"nom\"].agg(\"mean\").round(2)\nmedian_nb_repos = df.groupby(\"organisation_nom\").count()[\"nom\"].agg(\"median\").round(2)\nswh_exists_count = len(df.loc[df[\"software_heritage_exists\"].fillna(False)])\n\ntop_orgs_by_repos = (\n df[[\"plateforme\", \"organisation_nom\"]]\n .groupby([\"plateforme\", \"organisation_nom\"])\n .size()\n .to_frame(\"count\")\n .sort_values(by=\"count\", ascending=False)\n .head(10)\n .reset_index()\n .to_dict(orient=\"records\")\n)\n\ntop_orgs_by_stars = (\n df.groupby([\"organisation_nom\"])[\"nombre_stars\"]\n .sum()\n .sort_values(ascending=False)\n .head(10)\n .to_dict()\n)\n\ntop_repos_stars = (\n df.groupby(\"repertoire_url\")[\"nombre_stars\"]\n .sum()\n .sort_values(ascending=False)\n .head(10)\n .to_dict()\n)\ntop_repos_forks = (\n df.groupby(\"repertoire_url\")[\"nombre_forks\"]\n .sum()\n .sort_values(ascending=False)\n .head(10)\n .to_dict()\n)\ntop_repos_issues = (\n df.groupby(\"repertoire_url\")[\"nombre_issues_ouvertes\"]\n .sum()\n .sort_values(ascending=False)\n .head(10)\n .to_dict()\n)\n\ntop_licenses = (\n df.fillna(\"Inconnue\")\n .groupby(\"licence\")[\"nom\"]\n .count()\n .sort_values(ascending=False)\n .to_dict()\n)\n\ntop_languages = (\n df.fillna(\"Inconnu\")\n .groupby(\"langage\")[\"nom\"]\n .count()\n .sort_values(ascending=False)\n .head(11)\n .to_dict()\n)\n\nplatforms = (\n df.groupby(\"plateforme\")[\"nom\"].count().sort_values(ascending=False).to_dict()\n)\n\nres = {\n \"nb_repos\": nb_repos,\n \"nb_orgs\": nb_orgs,\n \"avg_nb_repos\": avg_nb_repos,\n \"median_nb_repos\": median_nb_repos,\n \"top_orgs_by_repos\": top_orgs_by_repos,\n \"top_orgs_by_stars\": top_orgs_by_stars,\n \"top_repos_stars\": top_repos_stars,\n \"top_repos_forks\": top_repos_forks,\n \"top_repos_issues\": top_repos_issues,\n \"top_licenses\": top_licenses,\n \"top_languages\": top_languages,\n \"platforms\": platforms,\n \"software_heritage\": {\n \"repos_in_archive\": swh_exists_count,\n \"ratio_in_archive\": round(swh_exists_count / nb_repos, 2),\n },\n}\n\nwith open(OUT_FILEPATH, \"w\") as f:\n json.dump(res, f)\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"278470821","text":"db = []\r\n\r\nwith open(\"input19.txt\", \"r\") as textfile:\r\n\tfor line in textfile:\r\n\t\tif len(line) > 20:\r\n\t\t\tcode = line[:-1]\r\n\t\telif len(line) > 4:\r\n\t\t\tcut = line.split(\" \")\r\n\t\t\tdb.append([cut[0], cut[2][:-1]])\r\n\r\nnext_permutation = []\r\n\r\nfor pair in db:\r\n\ti = 0\r\n\twhile pair[0] in code[i:]:\r\n\t\ti = code.find(pair[0],i)\r\n\t\tmuted = code[:i] + pair[1] + code[i + len(pair[0]):]\r\n\t\tif muted not in next_permutation:\r\n\t\t\tnext_permutation.append(muted)\r\n\t\ti += 1\r\n\r\n\r\nprint(\"Answer to 19A:\", len(next_permutation))\r\n\r\ngen = [code]\r\ng = 0\r\n\r\nwhile 'e' not in gen:\r\n\tnext_gen = []\r\n\tfor molecule in gen:\r\n\r\n\t\tfor pair in db:\r\n\r\n\t\t\ti = 0\r\n\t\t\twhile i < len(molecule) and pair[1] in molecule[i:]:\r\n\t\t\t\ti = molecule.find(pair[1],i)\r\n\t\t\t\tmutated = molecule[:i] + pair[0] + molecule[i + len(pair[1]):]\r\n\t\t\t\tif mutated not in next_gen and len(mutated) <= len(code):\r\n\t\t\t\t\tnext_gen.append(mutated)\r\n\t\t\t\ti += 1\r\n\tg += 1\r\n\tnext_gen.sort(key=(lambda x: len(x)))\r\n\tgen = next_gen[:10]\r\n\r\n\r\nprint(\"Answer to 19B:\", g)\r\n\r\n","sub_path":"19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"418400493","text":"import unittest\nfrom unittest import mock\n\nfrom transiter.database import syncutil\nfrom transiter import models\n\n\nclass TestSync(unittest.TestCase):\n\n ID_ONE = 4\n ID_TWO = 5\n ID_THREE = 6\n OLD_VALUE_ONE = \"1\"\n OLD_VALUE_TWO = \"2\"\n NEW_VALUE_TWO = \"3\"\n NEW_VALUE_THREE = \"4\"\n\n class MockDbModel:\n\n def __init__(self, id=None, value=None):\n self.id = id\n self.key = value\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n def __hash__(self):\n return hash(str(self))\n\n def __str__(self):\n return str(self.__dict__)\n\n def __repr__(self):\n return str(self)\n\n def test_copy_pks(self):\n\n new_model = self.MockDbModel('1')\n updated_model_new = self.MockDbModel('2')\n updated_model_old = self.MockDbModel('2')\n updated_model_old.pk = 2\n old_model = self.MockDbModel('3')\n old_model.pk = 3\n\n (old_models, updated_model_tuples, new_models) = syncutil.copy_pks(\n [updated_model_old, old_model], [new_model, updated_model_new],\n ('id', )\n )\n\n self.assertEqual([old_model], old_models)\n self.assertEqual([new_model], new_models)\n self.assertEqual([(updated_model_old, updated_model_new)], updated_model_tuples)\n\n @mock.patch('transiter.database.syncutil.connection')\n def test_sync(self, connection):\n \"\"\"[Database sync] Sync data\"\"\"\n\n def add_function(entity):\n self._new_entities.add(entity)\n\n def delete_function(session, entity):\n self._deleted_entities.add(entity)\n\n session = mock.MagicMock()\n connection.get_session.return_value = session\n session.add.side_effect = add_function\n\n self._new_entities = set()\n self._deleted_entities = set()\n\n old_one = self.MockDbModel(self.ID_ONE, self.OLD_VALUE_ONE)\n old_two = self.MockDbModel(self.ID_TWO, self.OLD_VALUE_TWO)\n new_two = self.MockDbModel(self.ID_TWO, self.NEW_VALUE_TWO)\n new_three = self.MockDbModel(self.ID_THREE, self.NEW_VALUE_THREE)\n db_entities = [old_one, old_two]\n expected_new_db_entities = [new_two, new_three]\n new_entities = [\n {\n 'id': self.ID_TWO,\n 'key': self.NEW_VALUE_TWO\n },\n None,\n {\n 'id': self.ID_THREE,\n 'key': self.NEW_VALUE_THREE\n }\n ]\n\n actual_new_db_entities = syncutil.sync(\n self.MockDbModel, db_entities, new_entities, ['id'], delete_function)\n\n self.assertListEqual(actual_new_db_entities, expected_new_db_entities)\n self.assertSetEqual(self._deleted_entities, {old_one})\n # NOTE: Unittest's assertSetEqual uses set.difference() which does\n # not use the obj.__eq__ method, so sets containing objects with the\n # the same data fail the assertion\n self.assertListEqual(list(self._new_entities), [new_three])\n\n def _session_add(self, entity):\n self._new_entities.add(entity)\n\n def test_delete_from_db(self):\n session = mock.MagicMock()\n entity = mock.MagicMock()\n\n syncutil.delete_from_db(session, entity)\n\n session.delete.assert_called_once_with(entity)\n\n","sub_path":"tests/unittests/database/test_syncutil.py","file_name":"test_syncutil.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"490689325","text":"\n__author__ = 'Carter'\nfrom django_mako_plus.controller import view_function\nfrom django.db.models import Q\nimport locale\nfrom django.http import HttpResponseRedirect, HttpResponse\nimport CHF.models as cMod\nimport datetime\nfrom django_mako_plus.controller.router import get_renderer\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib.auth.models import Group\n\n@view_function\n@permission_required('CHF.manager_rights')\ndef process_request(request):\n items = cMod.RentedItem.objects.all()\n overdueItems = []\n for item in items:\n if item.due_date < datetime.date.today() and item.item_return is None:\n name = item.item.name\n date = item.due_date\n overdueItems.append('''\n
\n
%s
\n
 
\n
\n Date Due: %s\n
\n
\n ''' % (name, str(date)))\n print(overdueItems)\n\n html = \"\\n\"\n html = html.join(overdueItems)\n return HttpResponse(html)\n","sub_path":"CHF/CHF/views/batchProcess.py","file_name":"batchProcess.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477267623","text":"__author__ = 'artemredkin'\n\nimport json\nimport urllib\nimport urlparse\nimport db\nimport telegram\nimport collections\nimport rsvp\nimport destiny\nimport logging\nimport random\nimport poll\n\nfrom google.appengine.api import urlfetch\n\n\ndef parse(message):\n values = message.split(None, 1)\n if len(values) == 1:\n return values[0], None\n return values\n\n\nclass Registry():\n\n def __init__(self):\n self.commands = collections.OrderedDict({})\n\n def register(self, command):\n self.commands[command.name()] = command\n\n\nclass Command:\n\n def call(self, chat, author, arguments):\n pass\n\n def help(self):\n pass\n\n def name(self):\n pass\n\n def description(self):\n pass\n\n\nclass EchoCommand(Command):\n\n def call(self, chat, author, arguments):\n telegram.send(chat, arguments.encode('utf-8'))\n\n def help(self):\n return \"Usage: /echo \"\n\n def name(self):\n return \"/echo\"\n\n def description(self):\n return \"Send back message\"\n\n\nclass ImageCommand(Command):\n\n def __init__(self):\n self.google_search_key = None\n self.cache_list = []\n self.cache = {}\n\n def find(self, q, start):\n if self.google_search_key is None:\n self.google_search_key = db.get_key('google_search')\n data = {\n 'key': self.google_search_key,\n 'cx': '009373417816394415455:i3e_omr58us',\n 'q': q.encode('utf-8'),\n 'searchType': 'image',\n 'safe': 'medium',\n 'num': 10\n }\n response = urlfetch.fetch(url='https://www.googleapis.com/customsearch/v1?' + urllib.urlencode(data), method=urlfetch.GET)\n return json.loads(response.content)['items']\n\n def call(self, chat, author, q):\n if q in self.cache:\n (items, offset) = self.cache[q]\n if offset == 10:\n items = self.find(q, 10)\n offset = 0\n self.cache[q] = (items, offset + 1)\n image = items[offset]\n else:\n items = self.find(q, 0)\n if len(items) == 0:\n telegram.send(chat, \"Nothing found\")\n return\n image = items[0]\n if self.cache_list == 10:\n last = self.cache_list[0]\n self.cache_list.pop(0)\n self.cache.pop(last, None)\n self.cache_list.append(q)\n self.cache[q] = (items, 1)\n\n image_url = image['link']\n image_response = urlfetch.fetch(image_url, method=urlfetch.GET)\n if image_response.status_code != 200:\n telegram.send(chat, \"Error retrieving image\")\n return\n image_name = urlparse.urlsplit(image_url).path.split('/')[-1]\n telegram.send_image(chat, image_response.content, image_name, image['mime'])\n\n def help(self):\n return \"Usage: /img \"\n\n def name(self):\n return \"/img\"\n\n def description(self):\n return \"Google Image Search\"\n\n\nclass QuoteCommand(Command):\n\n def __init__(self):\n self.quotes = ['We\\'ve woken the hiiiveee!', 'Well, at least it\\'s chained up.',\n 'And I thought YOU had the hard job.', 'I\\'m beginning to sense a pattern!',\n 'Don\\'t do that.', 'Can\\'t we just stay here with the murderous robots?',\n 'Well that had to ruin their day.', 'I think you got your point across.',\n 'IT\\'S IN THE WALLS!!!', 'That wizard came from The Moon.',\n 'Just so you know I have no idea what I\\'m doing','This should take us right to the grave.',\n 'I\\'m a Ghost, actually', 'We may want to move back.',\n 'Think they\\'d mind if we take their Pikes?','Fallen ships this close to the surface.... MOVE!',\n 'This will take just a little while longer.', 'So... think you can kill a God?',\n 'This could be bad!', 'This could be good!', 'This could be going better...',\n 'Those Fallen are just as crazy as we are.', 'I\\'ll work faster']\n\n def call(self, chat, author, arguments):\n telegram.send(chat, random.choice(self.quotes))\n\n def help(self):\n return \"Usage: /quote\"\n\n def name(self):\n return \"/quote\"\n\n def description(self):\n return \"Dinklebot Wisdom\"\n\n\nclass MapCommand(Command):\n\n def call(self, chat, author, count):\n cnt = 1\n if count is not None and len(count) > 0:\n cnt = int(count)\n telegram.send(chat, ', '.join(destiny.get_next_maps(cnt)))\n\n def help(self):\n return \"Usage: /map [how many]\"\n\n def name(self):\n return \"/map\"\n\n def description(self):\n return \"Map Choice Generator, current pool: [\" + \", \".join(destiny.maps) + \"]\"\n\n\nr = Registry()\nr.register(EchoCommand())\nr.register(ImageCommand())\nr.register(QuoteCommand())\nr.register(MapCommand())\nr.register(rsvp.RsvpRegisterCommand())\nr.register(rsvp.RsvpTypesCommand())\nr.register(rsvp.RsvpListCommand())\nr.register(rsvp.RsvpNewCommand())\nr.register(rsvp.RsvpJoinCommand())\nr.register(rsvp.RsvpLeaveCommand())\nr.register(rsvp.RsvpDeleteCommand())\nr.register(rsvp.RsvpPartitionCommand())\nr.register(poll.PollCommand())\nr.register(poll.NewPollCommand())\nr.register(poll.AsnwerCommand())\nr.register(poll.VotePollCommand())\nr.register(poll.ResultPollCommand())\nr.register(poll.EndPollCommand())\n\n\ndef recieve(request):\n commands = r.commands\n (chat, author, message) = telegram.recieve(request)\n if message.startswith('/'):\n (command, arguments) = parse(message)\n if command == '/help':\n if arguments is not None:\n cmd = '/' + arguments\n if cmd not in commands:\n telegram.send(chat, \"Uknown command: \" + str(arguments))\n return\n telegram.send(chat, commands[cmd].help())\n return\n\n response = 'Commands:'\n for name, command in commands.iteritems():\n response += '\\n' + name + ': ' + command.description()\n response += '\\n\\nType /help to know more'\n telegram.send(chat, response)\n return\n if command in commands:\n try:\n commands[command].call(chat, author, arguments)\n except Exception as e:\n logging.info(request)\n logging.error(e, exc_info=True)\n","sub_path":"dinklebot.py","file_name":"dinklebot.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319992467","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom fpdf import FPDF\nimport os\nfrom PIL import Image\n\nfrom ar_tracking_tools.geometry_utils import getEdges, foldPoints\n\nIN2CM = 2.54\nCM2PT = 72./IN2CM\n\ndef addMarker(pdf, index, position, size = 5.0, text_size = None, coords = None):\n x, y = position\n y *= -1\n os.system('rosrun ar_track_alvar createMarker {0:d} -s {1:}'.format(index, size))\n filename = 'MarkerData_{0:d}.png'.format(index)\n pdf.image(filename, x-size/2., y-size/2., size, size)\n os.remove(filename)\n \n if(text_size is not None):\n pdf.set_font('Courier', '', text_size*CM2PT)\n if(coords is not None):\n pdf.text(x-size/2., y+size/2. + text_size,\n 'Alvar {0:d} {1:}cm ({2:})'.format(index, size, ', '.join(np.round(coords, 2).astype(str))))\n else:\n pdf.cell(x-size/2., y+size/2. + text_size,\n 'Alvar {0:d} {1:}cm ({2:},{3:})'.format(index, size, x, y))\n \ndef addOrientedKey(pdf, position, size = 2.0, text_size = None, coords = None):\n x, y = position\n y *= -1\n pdf.line(x-size/2., y, x+size/2., y)\n pdf.line(x, y-size/2., x, y+size/2.)\n pdf.ellipse(x-size/4., y-size/4., size/2., size/2.)\n pdf.line(x, y-size/2.,\n x+size/16., y-.375*size)\n pdf.line(x, y-size/2.,\n x-size/16., y-.375*size)\n \n if(text_size is not None):\n pdf.set_font('Courier', '', text_size*CM2PT)\n pdf.set_xy(x, y + size/2. - text_size)\n if(coords is not None):\n pdf.text(x, y + size/2. - text_size, '({0:})'.format(', '.join(np.round(coords, 2).astype(str))))\n else:\n pdf.text(x, y + size/2. - text_size, '({0:},{1:})'.format(x, y))\n\ndef isOnSheet(pt, marker_size, page_idxs, printable_size, overlap):\n xm,ym = pt-marker_size/2.\n xp,yp = pt+marker_size/2.\n j,k = page_idxs\n w,h = printable_size - overlap\n left = xm >= j*w and xm <= (j+1)*w + overlap\n rigth = xp >= j*w and xp <= (j+1)*w + overlap\n upper = yp <= -k*h and yp >= -(k+1)*h - overlap\n lower = yp <= -k*h and yp >= -(k+1)*h - overlap\n ul = upper and left\n ur = upper and rigth\n ll = lower and left\n lr = lower and rigth\n \n return ul or ur or ll or lr\n\ndef makeBundlePdf(point_sets, marker_size, \n edges = None, \n start_index = 0,\n paper_size = None, \n paper_orientation = 'P',\n text_size = None, \n margin = 1., \n overlap = 2.,\n rosette_positions = None, \n rosette_size = 1.):\n \"\"\"\n Create a bundle pdf from set of points, seperated by face. \n First set should be the central face\n \"\"\"\n # Calculate edges, if not given\n if(edges is None):\n edges = getEdges(point_sets)\n \n # Flattens all marker centers\n flat_pts = []\n pts = []\n for p, e in zip(point_sets, edges):\n if(e is None):\n unfolded_pts = p\n else:\n unfolded_pts = foldPoints(p, e)\n assert np.all(np.abs(unfolded_pts[:,2]) < 1e-9), 'Unfolded z value nonzero for edge {}'.format(e)\n\n flat_pts.extend(unfolded_pts)\n pts.extend(p)\n flat_pts = np.stack(flat_pts)[:,:2]\n \n\n # Flattens all edge end points\n flat_edges = []\n for e in edges:\n if(e is not None):\n flat_e = foldPoints(np.stack([e[0], e[1]]), e)\n flat_edges.append(flat_e)\n\n \n if(rosette_positions is None):\n rosette_pts = []\n flat_rosette_pts = []\n elif(np.array(rosette_positions).size <= 3):\n rosette_pts = [np.array(rosette_positions)]\n flat_rosette_pts = np.expand_dims(np.array(rosette_positions)[:2], 0).astype(float)\n else:\n rosette_pts = []\n flat_rosette_pts = []\n for p, e in zip(rosette_positions, edges):\n if(e is None):\n unfolded_pts = p\n else:\n unfolded_pts = foldPoints(p, e)\n assert np.all(np.abs(unfolded_pts[:,2]) < 1e-9), 'Unfolded z value nonzero rosette on edge {}'.format(e)\n\n flat_rosette_pts.extend(unfolded_pts)\n rosette_pts.extend(p)\n\n flat_rosette_pts = np.stack(flat_rosette_pts)[:,:2]\n\n\n if(type(rosette_size) not in [np.ndarray, list]):\n rosette_size = np.repeat(rosette_size, len(flat_rosette_pts))\n\n if(type(marker_size) not in [np.ndarray, list]):\n marker_size = np.repeat(marker_size, len(flat_pts))\n\n\n # Find upper left corner of all markers\n min_x = np.min(flat_pts[:,0])\n max_y = np.max(flat_pts[:,1])\n max_marker_size = np.max(marker_size)\n tl_corner = np.array([min_x-max_marker_size/2., \n max_y+max_marker_size/2.])\n flat_pts = flat_pts.copy()\n flat_pts[:,0] -= tl_corner[0]\n flat_pts[:,1] -= tl_corner[1]\n \n if(len(flat_rosette_pts) > 0):\n flat_rosette_pts = flat_rosette_pts.copy()\n flat_rosette_pts[:,0] -= tl_corner[0]\n flat_rosette_pts[:,1] -= tl_corner[1]\n\n # If paper size is not defined, set to required size to fit all markers\n if(paper_size is None):\n overlap = 0\n paper_size = ( np.max(flat_pts[:,0]) + 2*margin + max_marker_size/2., \n -np.min(flat_pts[:,1]) + 2*margin + max_marker_size/2.)\n\n # Determine the number of sheets required\n printable_size = (np.array(paper_size) - 2*margin)\n sheet_coords = np.abs(flat_pts) / (printable_size - overlap)\n overlap_norm = overlap / (printable_size - overlap)\n num_sheets = np.ceil(np.max(sheet_coords, axis=0) - overlap_norm).astype(int)\n\n pdf = FPDF(orientation = paper_orientation, unit = 'cm', format=paper_size)\n if(text_size is not None):\n pdf.set_font('Courier', '', text_size*CM2PT)\n \n for j in range(num_sheets[0]):\n for k in range(num_sheets[1]):\n \n pdf.add_page()\n \n # Add alignment markings if necessary \n if(j > 0):\n mark_loc = margin\n pdf.line(mark_loc, 0, mark_loc, margin)\n pdf.line(mark_loc, paper_size[1], mark_loc, paper_size[1]-margin)\n if(k > 0):\n mark_loc = margin\n pdf.line(0, mark_loc, margin, mark_loc)\n pdf.line(paper_size[0], mark_loc, paper_size[0]-margin, mark_loc)\n \n if(j < num_sheets[0]-1):\n mark_loc = paper_size[0]-margin-overlap\n pdf.line(mark_loc, 0, mark_loc, margin)\n pdf.line(mark_loc, paper_size[1], mark_loc, paper_size[1]-margin)\n if(k < num_sheets[1]-1):\n mark_loc = paper_size[1]-margin-overlap\n pdf.line(0, mark_loc, margin, mark_loc)\n pdf.line(paper_size[0], mark_loc, paper_size[0]-margin, mark_loc)\n \n if(text_size is not None and np.any(num_sheets>1)):\n pdf.text(margin/2, margin/2, '{0:}'.format((j,k)))\n \n paper_corner = np.array((j,-k))*(printable_size - overlap) - np.array([margin,-margin])\n\n for e in flat_edges:\n e_srt = e[0][:2] - tl_corner - paper_corner\n e_end = e[1][:2] - tl_corner - paper_corner\n pdf.dashed_line(e_srt[0], -e_srt[1], e_end[0], -e_end[1])\n \n for idx, (pt2, pt3, sz) in enumerate(zip(flat_rosette_pts, rosette_pts, rosette_size)):\n if(isOnSheet(pt2, sz, (j,k), printable_size, overlap)):\n addOrientedKey(pdf, pt2 - paper_corner,\n sz, text_size = text_size, coords = pt3)\n \n for idx, (pt2, pt3, sz) in enumerate(zip(flat_pts, pts, marker_size)):\n if(isOnSheet(pt2, sz, (j,k), printable_size, overlap)):\n addMarker(pdf, start_index + idx, pt2 - paper_corner, \n sz, text_size = text_size, coords = pt3)\n return pdf\n","sub_path":"src/ar_tracking_tools/bundle_pdf_utils.py","file_name":"bundle_pdf_utils.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"113557805","text":"import streamlit as st\nimport pandas as pd\nfrom Functions.for_streamlit.bygroups_app import bygroups_show\nfrom Functions.for_streamlit.overall_app import overall_show\nfrom Dictionaries.colnames_dictionary import header_dictionary as hd\n\nDATA_URL = ('https://raw.githubusercontent.com/mbalcerzak/BJJ/master/Data')\n\n#@st.cache\n# ---------------------- LOADING DATA FROM GITHUB -------------------------- #\ndef load_data(file_name):\n data = pd.read_csv(DATA_URL + '/{}.csv'.format(file_name), sep = ';')\n\n if 'training' in file_name:\n for column in [\"how_old_when_started\", \"num_gis\", \"num_rashguards\", \n \"num_shorts\"]: \n \n def chop(x):\n return str(x[1:-1]) if x != 'no answer' else x\n \n data[column] = data[column].apply(lambda x: chop(x))\n \n return data\n\n#data_load_state = st.text('Loading data...')\n\ndata_view = load_data(\"data_bjj\") # the one that has a pre-view\n\ndata = load_data(\"info/training_info\")\ndata_back_ma = load_data(\"info/background_info\")\ndata_current_ma = load_data(\"info/current_ma_info\")\ndata_subs = load_data(\"info/subs_info\")\ndata_reasons = load_data(\"info/reasons_info\")\ndata_least_f = load_data(\"info/least_f_info\")\ndata_podcast = load_data(\"info/podcast_info\")\ndata_web = load_data(\"info/web_info\")\ndata_gi = load_data(\"info/gi_info\")\ndata_rash = load_data(\"info/rash_info\")\ndata_shorts = load_data(\"info/shorts_info\")\ndata_apparel = load_data(\"info/apparel_info\")\ndata_comp = load_data(\"info/comp_info\")\ndata_injury = load_data(\"info/injury_info\")\ndata_athlete = load_data(\"info/athlete_info\")\ndata_watch = load_data(\"info/watch_info\")\n\n\n#data_load_state.text('Loading data... done!')\n\n# ----------------- FINISHED LOADING DATA FROM GITHUB ---------------------- #\n\nst.sidebar.text(\"github.com/mbalcerzak\")\n\nst.sidebar.header(\"Overall results or for a selected group?\")\n\nall_or_not = st.sidebar.radio(\"\",[\"Introduction\",\n \"Overall\",\n 'Show by groups',\n 'Select one group',\n 'Interesting raw data'])\n\ncol_dictionary = {'white belt':'gray',\n 'blue belt':'steelblue', \n 'purple belt':'rebeccapurple',\n 'brown belt':'sienna', \n 'black belt':'black',\n 'no rank':'olivedrab',\n 'all belts':'olivedrab'}\n\nbelts = ['all belts', \n 'white belt','blue belt', 'purple belt', 'brown belt', 'black belt', \n 'no rank'] \n\ngenders = ['Every gender', 'Male', 'Female']\n\ndef only_answers(column, data):\n return data[data[column] != 'no answer']\n\nif all_or_not == 'Show by groups':\n \n by_group = 'Current rank'\n \n st.sidebar.header(\"Split the answers by ...\")\n by_group = st.sidebar.radio(\"\",['Current rank','Gender'])\n\n by_gr_dict = {'Current rank':['current_belt', belts[1:6]],\n 'Gender':['gender', None]} \n \n \n data1 = only_answers(by_gr_dict[by_group][0], data)\n data_back_ma1 = only_answers(by_gr_dict[by_group][0], data_back_ma)\n data_current_ma1 = only_answers(by_gr_dict[by_group][0], data_current_ma)\n\n bygroups_show(data1, data_back_ma1, data_current_ma1, by_gr_dict, by_group)\n\n\nelif all_or_not == 'Select one group':\n \n by_belt = False\n by_gender = False\n \n belt_chosen = belts[0]\n gender_chosen = genders[0]\n \n belt_chosen = st.sidebar.selectbox(\"Rank of the group:\", belts)\n gender_chosen = st.sidebar.selectbox(\"Gender of the group:\", genders)\n \n colour = col_dictionary[belt_chosen]\n \n def filter_data(data, belt_chosen = belt_chosen,\n gender_chosen = gender_chosen):\n\n if belt_chosen != belts[0]:\n data = data[data['current_belt'] == belt_chosen]\n \n data = data[data['current_belt'] != 'no answer']\n \n if gender_chosen != genders[0]: \n data = data[data['gender'] == gender_chosen]\n \n data = data[data['gender'] != 'no answer']\n \n return data\n \n if belt_chosen != belts[0] or gender_chosen != genders[0]:\n \n data_f = filter_data(data)\n data_current_ma_f = filter_data(data_current_ma)\n data_back_ma_f = filter_data(data_back_ma)\n data_reasons_f = filter_data(data_reasons)\n data_least_f_f = filter_data(data_least_f)\n data_subs_f = filter_data(data_subs)\n data_podcast_f = filter_data(data_podcast)\n data_web_f = filter_data(data_web)\n data_gi_f = filter_data(data_gi)\n data_rash_f = filter_data(data_rash)\n data_shorts_f = filter_data(data_shorts)\n data_apparel_f = filter_data(data_apparel)\n data_comp_f = filter_data(data_comp)\n data_injury_f = filter_data(data_injury)\n data_athlete_f = filter_data(data_athlete)\n data_watch_f = filter_data(data_watch) \n \n if belt_chosen != belts[0]:\n by_belt = True\n \n if gender_chosen != genders[0]:\n by_gender = True\n \n overall_show(data_f, data_current_ma_f, data_back_ma_f, data_reasons_f, \n data_least_f_f, data_subs_f, data_podcast_f, data_web_f, \n data_gi_f, data_rash_f, data_shorts_f, data_apparel_f, \n data_comp_f, data_injury_f, data_athlete_f, data_watch_f, \n colour, by_gender, by_belt, selected = True)\n\n\nelif all_or_not == 'Interesting raw data':\n data_raw = load_data(\"data_raw\")\n \n def only_answers_col(column, data = data_raw):\n return data[column][data[column] != 'no answer']\n \n st.subheader(hd['Q18'])\n if st.checkbox('Show reasons:'): \n st.write(\"My personal favourite: \\n I saw that I could get a good \\\n workout while lying on soft mats.\")\n st.table(only_answers_col('reasons_raw'))\n \n st.subheader(hd['Q19'])\n if st.checkbox('Show favourite:'):\n st.table(only_answers_col('favourite_raw'))\n \n st.subheader(hd['Q20'])\n if st.checkbox('Show least favourite:'):\n st.table(only_answers_col('least_fav_raw'))\n \n st.subheader(hd['Q44'])\n if st.checkbox('Show problems with manufacturers:'):\n st.table(only_answers_col('brand_problem'))\n\n\nelif all_or_not == \"Overall\": \n \n if st.checkbox('Show the data used for analysis'):\n st.subheader('Answers')\n st.write(data_view)\n \n colour = 'steelblue'\n \n #st.sidebar.radio(\"\",['royalblue','midnightblue','navy','steelblue'])\n\n overall_show(data, data_current_ma, data_back_ma, data_reasons, \n data_least_f, data_subs, data_podcast, data_web, data_gi, \n data_rash, data_shorts, data_apparel, data_comp, data_injury, \n data_athlete, data_watch, colour, by_gender = False, \n by_belt= False, selected = False)\n \nelse:\n st.title(\"Brazilian jiu-jitsu survey analysis\")\n \n st.markdown(\"Data comes from a survey about Brazilian jiu-jitsu (BJJ) created by \\\n [Grumpy Grappler Blog](https://philosophycommons.typepad.com/the_grumpy_grappler/bjj-survey/). \\\n The app is a summary of 807 answers. The free-text \\\n answers have been cleaned, you can check out the methodology \\\n and my code on my [GitHub](https://github.com/mbalcerzak/BJJ)\")\n \n #st.image(\"Data\\jonathan-borba-Yf1SegAI84o-unsplash.jpg\", width = 300,\n # caption = \"Photo by Jonathan Borba on Unsplash\") \n \n st.image(\"https://raw.githubusercontent.com/mbalcerzak/BJJ/master/Data/samuel-castro-g6lq1z1BS2g-unsplash.jpg\", \n use_column_width=True , caption=\"Photo by Samuel Castro on Unsplash\")","sub_path":"bjj-survey.py","file_name":"bjj-survey.py","file_ext":"py","file_size_in_byte":7826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"34649614","text":"from django.shortcuts import render\nfrom .models import Post\nfrom .forms import PostForm\nfrom django.utils import timezone\nfrom django.shortcuts import redirect, get_object_or_404\n\n\ndef post_list(request):\n posts = Post.objects.all()\n return render(request, 'blog/post_list.html', {\n 'posts': posts,\n 'primero': posts[0]\n })\n\n\ndef post_new(request):\n success = False\n # Cramos el formulario\n form = PostForm()\n # Rellenamos el formulario con el Post del Usuario\n if request.method == 'POST':\n form = PostForm(request.POST)\n # es valido\n if form.is_valid():\n # Guardamos la información del formulario en la base da datos\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n success = True\n return redirect('post_list',)\n return render(request, 'blog/post_edit.html', {\n 'form': form,\n 'success': success\n })\n\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_list',)\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form})\n\n\ndef post_delete(request, pk):\n Post.objects.filter(pk=pk).delete()\n return redirect('post_list',)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"201082941","text":"\"\"\"Описание и инициализация кнопок\"\"\"\nimport gpiozero\n\n# pin_sensor, pin_led, points : int, start\nbuttons_specs = [\n [20, 16, 20],\n [27, 8, 15],\n [25, 24, 10],\n [18, 15, 25],\n [26, 19, 10],\n [13, 6, 15],\n [22, 11, 20]\n]\nbutttons = []\n\nclass BUTTON(object):\n \"\"\"Класс кнопка\n \"\"\"\n def __init__(self, number, pin_sensor, pin_led, points: int):\n self.number = number\n self.sensor = gpiozero.Button(pin_sensor, pull_up=False, bounce_time=None)\n self.led = gpiozero.LED(pin_led)\n self.points_per_click = points\n\nstart_button = BUTTON(0, 21, 12, 10)\n","sub_path":"buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"331252253","text":"import numpy as np\nfrom NeuralNetworkTF import ProcessImage, NeuralNetwork\n\nEPSILON_UPPER = 1.0\nEPSILON_LOWER = 0.1\nEPSILON_DECAY = 0.000001\n\n\nclass DqnAgent:\n def __init__(self, pong_game):\n self.epsilon = EPSILON_UPPER\n self.game = pong_game\n self.state_size = pong_game.env.observation_space.shape\n self.action_size = pong_game.env.action_space.n\n\n # Neural networks\n self.nn_img_pre_process = ProcessImage()\n self.nn_q_learn = NeuralNetwork(\"q_learn\")\n self.nn_q_target = NeuralNetwork(\"q_target\")\n\n def epsilon_decay(self):\n if self.epsilon > EPSILON_LOWER:\n self.epsilon -= EPSILON_DECAY\n\n # select random action probability epsilon\n # select next action according policy with probability 1-epsilon\n def get_next_action(self, sess, env, state):\n if np.random.random() < self.epsilon:\n return env.action_space.sample()\n else:\n return self.get_max_action(sess, env, state)\n\n # select next action according policy\n # state [None, 84, 84, 4]\n def get_max_action(self, sess, env, state):\n # np.expand_dims((x1,x2,...)), 0) = (1,x1,x2,...)\n q_values = self.nn_q_learn.predict(sess, np.expand_dims(state, 0))[0]\n best_action = np.argmax(q_values) # get action with max q value\n return best_action\n","sub_path":"DQN/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"160710309","text":"\"\"\" This file contains unittests for trivia app \"\"\"\n# import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question, Category\n\n\nclass TriviaTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n # defining test database\n self.database_name = \"trivia_test\"\n # self.database_path = \"postgres://{}/{}\".format('localhost:5432', self.database_name)\n self.database_path = \"postgresql://{}:{}@{}/{}\".format('postgres',\n 'postgres',\n 'localhost:5432',\n self.database_name)\n setup_db(self.app, self.database_path)\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n self.new_question = {\n 'new_question':'Who is the current president of U.S.A',\n 'new_answer':'Donald Trump',\n 'new_category': 4,\n 'new_dificulty':'2'\n }\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n\n\n # @TODO\n # Write at least one test for each test for successful operation and for expected errors.\n\n def test_get_categories(self):\n \"\"\"\n Test case for /categories endpoint,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().get('/categories')\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['categories'])\n\n def test_get_questions(self):\n \"\"\"\n Test case for /questions endpoint,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().get('/questions')\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['total_questions'])\n self.assertTrue(data['questions'])\n\n def test_404_get_questions_error(self):\n \"\"\"\n Test case for /questions endpoint for unavailable page number,\n returns 404 NOT FOUND status code\n in case of not success\n \"\"\"\n response = self.client().get('/questions?page=150')\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Resource Not found')\n\n def test_post_new_question(self):\n \"\"\"\n Test case for /questions/new endpoint to create new question,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().post('/questions/new', json=self.new_question)\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['created_question'])\n self.assertTrue(data['questions'])\n\n def test_422_new_question_error(self):\n \"\"\"\n Test case for /questions/new endpoint error to create new question,\n returns 422 Unprocessable Request status code\n in case of error\n \"\"\"\n response = self.client().post('/questions/new', json={})\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 422)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Unprocessable Request')\n\n def test_questions_search(self):\n \"\"\"\n Test case for /questions/search endpoint to find questions based posted data,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().post('/questions/search', json={\"searchTerm\":\"What\"})\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['questions'])\n\n def test_questions_by_categories(self):\n \"\"\"\n Test case for /categories//questions endpoint\n to find questions based on provided category,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().get('/categories/2/questions')\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['current_category'])\n self.assertTrue(data['questions'])\n\n def test_play_quizzes(self):\n \"\"\"\n Test case for /quizzes endpoint to find questions based on provided category,\n returns 200 OK status code\n in case of success\n \"\"\"\n response = self.client().post('/quizzes', json={\"quiz_category\":{\"id\":\"2\"},\n \"previous_questions\":[]})\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['question'])\n\n def test_delete_question(self):\n \"\"\"\n Test case for /questions/id endpoint to delete a question,\n returns 200 OK status code\n in case of success\n In case the question ID is already deleted try another one\n \"\"\"\n response = self.client().delete('/questions/2')\n data = json.loads(response.data)\n\n question = Question.query.filter(Question.id == 2).one_or_none()\n\n if question is None:\n self.test_422_if_question_does_not_exist()\n # print(question)\n else:\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertEqual(data['deleted'], 2)\n self.assertTrue(data['questions'])\n self.assertEqual(question, None)\n\n def test_422_if_question_does_not_exist(self):\n \"\"\"\n Test case for /questions/id endpoint to delete a question,\n returns 422 Unprocessable Request status code\n in case of error\n \"\"\"\n response = self.client().delete('/questions/150')\n data = json.loads(response.data)\n\n self.assertEqual(response.status_code, 422)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Unprocessable Request')\n\n\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"projects/02_trivia_api/starter/backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"398037381","text":"from typing import Union, List, Tuple\nfrom random import shuffle as shuffler\nfrom .generator import Generator\n\n\nclass AllOf(Generator):\n def __init__(self, *args: any, shuffle=False, **kwargs):\n super().__init__(**kwargs)\n self.options: List[any] = [*args]\n self.working_copy: List[any] = [*self.options]\n self.shuffle = shuffle\n\n if self.shuffle:\n shuffler(self.working_copy)\n\n def _one(self) -> any:\n return self.options.pop()\n\n def add(self, option: any):\n self.options.append(option)\n\n def exhausted(self) -> bool:\n result = len(self.options) == 0\n\n # auto-reset\n if result:\n self.working_copy = [*self.options]\n if self.shuffle:\n shuffler(self.working_copy)\n\n return result\n","sub_path":"json_mockery/mocks/all_of.py","file_name":"all_of.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205876454","text":"#!/usr/bin/env python\n\n# Dependencies\nfrom lxml import html, etree\nimport requests\nimport pandas as pd\nimport datetime as dt\n\n# The webscraper works by implementing a class called upon the URL\n# returned by a search performed on the rightmove website. The class\n# contains various methods for extracting data from the search\n# results returned.\n\nclass rightmove_data(object):\n\n def __init__(self, url):\n \n self.url = url\n \n try:\n if \"searchType=SALE\" in self.url:\n self.rent_or_sale = \"SALE\"\n elif \"searchType=RENT\" in self.url:\n self.rent_or_sale = \"RENT\"\n except ValueError:\n print(\"Not a valid rightmove search URL.\")\n\n def results_count(self):\n \"\"\"Returns an integer of the total number of results returned by the search URL.\"\"\"\n page = requests.get(self.url)\n tree = html.fromstring(page.content)\n xp_result_count = '//span[@class=\"searchHeader-resultCount\"]/text()'\n return int(tree.xpath(xp_result_count)[0].replace(\",\", \"\"))\n\n def result_pages_count(self):\n \"\"\"Returns the number of result pages returned by the search URL.\n There are 24 results on each results page, but note that the\n rightmove website limits results pages to a maximum of 42 pages.\"\"\"\n\n page_count = self.results_count() / 24\n if self.results_count() % 24 > 0:\n page_count += 1\n\n # Rightmove will return a maximum of 42 results pages, hence:\n if page_count >42: page_count = 42\n\n return page_count\n\n def __get_page_results(self,page_url):\n # This is a hidden method to scrape the data from a single page\n # of search results. It is used iteratively by the .get_results\n # method to scrape data from every page returned by the search.\n\n # Set the correct xpath for the price.\n if self.rent_or_sale == \"RENT\":\n xp_prices = '//span[@class=\"propertyCard-priceValue\"]/text()'\n elif self.rent_or_sale == \"SALE\":\n xp_prices = '//div[@class=\"propertyCard-priceValue\"]/text()'\n\n # Set the xpaths for listing title, property address, and listing URL.\n xp_titles = '//div[@class=\"propertyCard-details\"]//a[@class=\"propertyCard-link\"]\\\n //h2[@class=\"propertyCard-title\"]/text()'\n xp_addresses = '//address[@class=\"propertyCard-address\"]//span/text()'\n xp_weblinks = '//div[@class=\"propertyCard-details\"]//a[@class=\"propertyCard-link\"]/@href'\n\n # Use the requests library to get the whole webpage\n page = requests.get(page_url)\n\n # Process the html\n tree = html.fromstring(page.content)\n\n # Create empty lists to store the data\n price_pcm, titles, addresses, weblinks = [], [], [], []\n\n # Create data lists from Xpaths\n for val in tree.xpath(xp_prices):\n price_pcm.append(val)\n for val in tree.xpath(xp_titles):\n titles.append(val)\n for val in tree.xpath(xp_addresses):\n addresses.append(val)\n for val in tree.xpath(xp_weblinks):\n weblinks.append('http://www.rightmove.co.uk'+val)\n\n # Store the data in a temporary pandas DataFrame\n data = [price_pcm, titles, addresses, weblinks]\n temp_df = pd.DataFrame(data)\n temp_df = temp_df.transpose()\n temp_df.columns = ['price','type','address','url']\n\n # Drop empty rows from DataFrame which come from placeholders in the html\n temp_df = temp_df[temp_df['address'].notnull()]\n\n return temp_df\n\n def get_results(self):\n \"\"\"Returns a dataframe with all results returned by the search.\"\"\"\n\n # Create dataframe to store results.\n full_results = pd.DataFrame(columns={'price','type','address','url'})\n\n # Iterate through pages of results, using the .__get_page_results method to scrape results.\n for page in range(0,self.result_pages_count()+1,1):\n\n # Create the URL of the specific results page.\n iteration_url = str(self.url) + '&index=' + str((page*24))\n\n # Create a temporary dataframe of the page results.\n temp_df = self.__get_page_results(iteration_url)\n\n # Concatenate the temporary dataframe with the full dataframe.\n frames = [full_results,temp_df]\n full_results = pd.concat(frames)\n\n # Tidy up results dataframe for analysis\n full_results = full_results.reset_index(drop=True)\n\n # Convert price column to numeric values for analysis\n full_results.price.replace(regex=True,inplace=True,to_replace=r'\\D',value=r'')\n full_results.price = pd.to_numeric(full_results.price)\n\n # Extract postcodes to a separate column\n full_results['postcode'] = full_results['address'].str.extract\\\n (r'\\b([A-Za-z][A-Za-z]?[0-9][0-9]?[A-Za-z]?)\\b',expand=True)\n\n # Extract number of bedrooms from 'type' to a separate column\n full_results['number_bedrooms'] = full_results.type.str.extract(r'\\b([\\d][\\d]?)\\b',expand=True)\n full_results.loc[full_results['type'].str.contains('studio',case=False),'number_bedrooms']=0\n \n # Clean up annoying white spaces and newlines in \"type\" column\n for row in range(len(full_results)):\n type_string = full_results.loc[row, \"type\"]\n cleaned_string = type_string.strip(\"\\n\")\n cleaned_string = cleaned_string.strip()\n full_results.loc[row, \"type\"] = cleaned_string\n\n # Add in search_date column to record the date the search was run (i.e. today's date)\n now = dt.datetime.today().strftime(\"%d/%m/%Y\")\n full_results['search_date'] = now\n\n return full_results","sub_path":"rightmove_webscraper.py","file_name":"rightmove_webscraper.py","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"40120484","text":"import os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\nplt.rc('xtick', labelsize='small')\nplt.rc('ytick', labelsize='small')\n\nfig = plt.figure(figsize=(4, 3))\n\nalgo = 'brs'\n#path = '/media/trevor/22c63957-b0cc-45b6-9d8f-173d9619fb73/outputs/rl_adaptive_sampling/vpg/5_6_18r3/'\n# path = '/home/dockeruser/DockerShare/tpbarron/data/rl_adaptive_sampling/vpg/5_7_18r3/'\n# path2 = '/home/dockeruser/DockerShare/tpbarron/data/rl_adaptive_sampling/vpg/5_7_18r3/'\npath = '/home/trevor/Documents/data/rl_adaptive_sampling/'+algo+'/5_13_18r1/'\npath2 = '/home/trevor/Documents/data/rl_adaptive_sampling/'+algo+'/5_13_18r1/'\n\nfunc = '2dquad'\n# func = 'ndquad'\nuse_diagonal_approx = 1\nnoisy_obj = 1\nseeds = list(range(5))\nlr = 0.01\nalpha = 0.2\nsos_init = 0.0\nnu = 0.5\nname = algo+'_'+func+'_sos'+str(sos_init)+'noisy'+str(noisy_obj)+'_smallbatch'\n\n# no kalman\n# bs = [50, 100] #, 50, 10]\nbs = [1, 2, 10] #, 100]\ncolors = ['xkcd:coral', 'xkcd:tangerine', 'xkcd:scarlet'] #, 'xkcd:red orange'] #, '#7fbf7b', '#1b7837']\nmarkers = [',', ',', ',']\nfor b, c, m in zip(bs, colors, markers):\n # batch 1000\n xs = []\n ys = []\n for s in seeds:\n if algo == 'brs':\n batch_sizes1 = np.load(path+'batch'+str(b)+'_lr'+str(lr)+'_error0.0_noisyobj'+str(noisy_obj)+'_f'+func+'_diag0_sos0.0_nu'+str(nu)+'/'+str(s)+'/log_batch_sizes.npy')\n mu_est1 = np.load(path+'batch'+str(b)+'_lr'+str(lr)+'_error0.0_noisyobj'+str(noisy_obj)+'_f'+func+'_diag0_sos0.0_nu'+str(nu)+'/'+str(s)+'/log_min_est.npy')\n else:\n batch_sizes1 = np.load(path+'batch'+str(b)+'_lr'+str(lr)+'_error0.0_noisyobj'+str(noisy_obj)+'_f'+func+'_diag0_sos0.0/'+str(s)+'/log_batch_sizes.npy')\n mu_est1 = np.load(path+'batch'+str(b)+'_lr'+str(lr)+'_error0.0_noisyobj'+str(noisy_obj)+'_f'+func+'_diag0_sos0.0/'+str(s)+'/log_min_mu_est.npy')\n batch_ends1 = np.cumsum(batch_sizes1)\n # print (batch_ends1)\n x = batch_ends1\n y = mu_est1[batch_ends1]**2.0\n # y = np.reshape(1, y.shape[0])\n y = np.squeeze(y)\n y = np.mean(y, axis=1)\n # print (y.shape)\n # input(\"\")\n xs.append(x)\n ys.append(y)\n xs = np.array(xs)\n ys = np.array(ys)\n x = np.mean(xs, axis=0)\n y = np.mean(ys, axis=0)\n std = np.std(ys, axis=0)\n plt.plot(x, y, label='PG '+str(b), color=c, marker=m, linestyle='dashed')\n plt.fill_between(x, y, y+std, alpha=alpha, color=c)\n plt.fill_between(x, y, y-std, alpha=alpha, color=c)\n # plt.errorbar(x, y, yerr=std, color=c)\n\n# kalman\nerrs = [0.4, 0.5, 0.75] #, 0.1]\n# errs = [0.1, 0.2, 0.3]\ncolors = ['xkcd:jade', 'xkcd:aqua', 'xkcd:sea blue'] #, 'xkcd:cobalt blue'] #, '#7fbf7b', '#1b7837']\nmarkers = [',', ',', ','] #, ',']\n\ndef sync_data(xs, ys):\n max_samples = 0\n for x in xs:\n max_samples = max(max_samples, np.max(x))\n print (\"Max samples\", max_samples)\n\n xsnew = []\n ysnew = []\n\n for i in range(len(xs)):\n xnew = np.linspace(0, max_samples, max_samples)\n ynew = np.interp(xnew, xs[i], ys[i])\n xsnew.append(xnew)\n ysnew.append(ynew)\n return xsnew[0], np.array(ysnew)\n\nfor e, c, m in zip(errs, colors, markers):\n xs = []\n ys = []\n for seed in seeds:\n if algo == 'brs':\n batch_sizes1 = np.load(path2+'batch1000_lr'+str(lr)+'_error'+str(e)+'_noisyobj'+str(noisy_obj)+'_f'+func+'_diag'+str(use_diagonal_approx)+'_sos'+str(sos_init)+'_nu'+str(nu)+'/'+str(seed)+'/log_batch_sizes.npy')\n mu_est1 = np.load(path2+'batch1000_lr'+str(lr)+'_error'+str(e)+'_noisyobj'+str(noisy_obj)+'_f'+func+'_diag'+str(use_diagonal_approx)+'_sos'+str(sos_init)+'_nu'+str(nu)+'/'+str(seed)+'/log_min_est.npy')\n batch_ends1 = np.cumsum(batch_sizes1)\n else:\n batch_sizes1 = np.load(path2+'batch1000_lr'+str(lr)+'_error'+str(e)+'_noisyobj'+str(noisy_obj)+'_f'+func+'_diag'+str(use_diagonal_approx)+'_sos'+str(sos_init)+'/'+str(seed)+'/log_batch_sizes.npy')\n mu_est1 = np.load(path2+'batch1000_lr'+str(lr)+'_error'+str(e)+'_noisyobj'+str(noisy_obj)+'_f'+func+'_diag'+str(use_diagonal_approx)+'_sos'+str(sos_init)+'/'+str(seed)+'/log_min_mu_est.npy')\n batch_ends1 = np.cumsum(batch_sizes1)\n # batch_ends1 = np.concatenate((np.array([0]), batch_ends1))\n x = batch_ends1-1\n print (batch_sizes1)\n print (batch_ends1)\n y = mu_est1[x]**2.0\n y = np.squeeze(y)\n y = np.mean(y, axis=1)\n # y = np.squeeze(y)\n xs.append(x)\n ys.append(y)\n # convert xs, ys to same length\n xsnew, ysnew = sync_data(xs, ys)\n print (ysnew.shape)\n y = np.mean(ysnew, axis=0)\n ystd = np.std(ysnew, axis=0)\n\n # from scipy.interpolate import spline\n # xnew = np.linspace(xsnew.min(), xsnew.max(), 10)\n # ysmooth = spline(xsnew, y, xnew)\n # plt.plot(xnew, ysmooth, label='PG-KF '+str(e), color=c, linestyle='dashed', marker=m)\n plt.plot(xsnew, y, label='PG-KF '+str(e), color=c, marker=m)\n plt.fill_between(xsnew, y, y+ystd, alpha=alpha, color=c)\n plt.fill_between(xsnew, y, y-ystd, alpha=alpha, color=c)\n\nplt.xlabel(\"Samples\")\nplt.ylabel(\"Squared Error\")\n\nif func == '2dquad':\n plt.xlim((0, 2000))\n # plt.xlim((0, 250))\nelif func == 'ndquad':\n plt.xlim((0, 10000))\nplt.ylim((0, 1.0))\n\nplt.legend(prop={'size': 8})\nplt.tight_layout()\n\nplt.show()\n# plt.savefig(fname=name+'.pdf', format='pdf')\n","sub_path":"paper/vis/simple_analysis_brs.py","file_name":"simple_analysis_brs.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"527007173","text":"import json\n\n# json中dumps表示将Python对象(字典,列表等)转化为json字符串,s表示string\n# dump表示将转化后的内容写进文件\n\nperson = {\"name\": \"wuchao\", \"age\": 30, \"tel\": [\"1123334\", \"1323435\"], \"isonly\": True}\n# person = [\"1123334\", \"1323435\"]\nprint(person)\nprint(type(person))\n\n#转换为json格式\ndict2json = json.dumps(person\n , indent=4 #分割符,表转化输出\n , sort_keys=True #是否排序\n )\nprint(dict2json)\nprint(type(dict2json))\n\n# 写入文件\ndict2jsonfile = json.dump(person\n , open('demo.json', \"w\")\n , indent=4\n , sort_keys=True)\n\n# json格式转化为python对象\n\n#转换为python对象格式\ndemo = '{\"age\": 30, \"isonly\": true, \"name\": \"wuchao\", \"tel\": [\"1123334\", \"1323435\"]}'\njson2dict = json.loads(demo)\nprint(json2dict)\nprint(type(json2dict))\n\n#读取json文件,输出为python对象\n\njsonfile2dict = json.load(open(\"demo.json\", \"r\"))\nprint(jsonfile2dict)\nprint(type(jsonfile2dict))","sub_path":"learn_json/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"486473665","text":"from werkzeug.utils import redirect\n\nfrom utils.common import gen_code as gen_register_confirmation_code\nfrom flask import Blueprint, render_template, abort, url_for\n\nfrom user.models import User\nfrom user.register.form import RegisterForm\nfrom utils.security.passwd import Password\nfrom utils.emailer.sender import EmailSender\nfrom user.decorators import is_user_already_logged_in\nfrom utils.security.secure import is_safe_url\n\nregistration_app = Blueprint(\"registration_app\", __name__)\n\n\n@registration_app.route(\"/register\", methods=[\"GET\", \"POST\"])\n@is_user_already_logged_in\ndef register():\n \"\"\"\"\"\"\n\n form = RegisterForm()\n\n if form.validate_on_submit():\n user = _save_form_data_to_database(form, registration_code=str(gen_register_confirmation_code()))\n _email_user_registration_confirmation_code(recipient_email=form.email.data, user=user)\n if is_safe_url(\"login_app.login\"):\n return redirect(url_for(\"login_app.login\"))\n return render_template(\"users/register/register.html\", form=form)\n\n\ndef _email_user_registration_confirmation_code(recipient_email, user):\n \"\"\"\"\"\"\n subject = \"Welcome to the social network\"\n body_html = render_template(\"users/mail/register/register.html\", user=user)\n\n email = EmailSender(recipient=recipient_email, subject=subject, content=body_html)\n email.send()\n\n\ndef _save_form_data_to_database(form, registration_code):\n \"\"\"\"\"\"\n\n user = User(\n username=form.username.data.lower(),\n password=Password.hash_password(form.password.data),\n email=form.email.data.lower(),\n first_name=form.username.data,\n last_name=form.last_name.data,\n change_configuration = {\n \"new_email\": form.email.data.lower(),\n \"confirmation_code\": registration_code,\n }\n )\n\n user.save()\n return user\n\n\n@registration_app.route(\"/confirm//\", methods=[\"GET\", \"POST\"])\ndef confirm_registration_code(username, code):\n \"\"\"\"\"\"\n\n user = User.objects.filter(username=username.lower()).first()\n\n if user and user.change_configuration and user.change_configuration.get(\"confirmation_code\") == code:\n \n user.email = user.change_configuration.get(\"new_email\")\n user.email_confirmed = True\n del user.change_configuration['confirmation_code']\n del user.change_configuration[\"new_email\"]\n user.save()\n return render_template(\"users/mail/email/email_confirmed.html\")\n \n abort(404)\n","sub_path":"user/register/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"385801891","text":"\nimport math\nimport cmath\nimport numpy as np\n\nx1=0.4\ny1=1.3\nz1=x1+y1\nprint(z1)\n\nh1=math.cos(x1)\nprint(h1)\n\ng1=cmath.exp(1j*2*math.pi*x1)\nprint(g1)\n\nx2=np.array([1,5,7,8,9])\ny2=np.array([3,8,2,6,8])\nz2=x2+y2\nprint(z2)\n\nh2=np.cos(x2)\nprint(h2)\n\ng2=np.exp(1j*2*math.pi*x2)\nprint(g2)","sub_path":"ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"572086619","text":"# -*- coding: utf-8 -*-\r\n#-------------------------------------------------------------------------------\r\n# Name: 模块2\r\n# Purpose:\r\n# Author: WIN7\r\n# Created: 24/07/2018\r\n# Copyright: Python 3.0及以上\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\nimport pandas as pd\r\nfrom pandas import DataFrame,Series\r\nimport numpy as np\r\nimport re\r\nimport datetime\r\n\r\ndelta = datetime.timedelta(days=1)\r\nnow= datetime.datetime.now()\r\ni=now.strftime('%m%d_%H.%M')\r\nj=now.strftime('%m%d')\r\nk=now.strftime('%Y%m%d')\r\nm=(now - delta).strftime('%Y%m%d')\r\npath = r'C:\\Users\\WIN7\\Desktop\\xiaji\\%s.xlsx'%j\r\nout_put = r'C:\\Users\\WIN7\\Desktop\\xiaji\\%s.csv'%i\r\n\r\n#外地批次汇总\r\nsheet_1=pd.read_excel(path,'Sheet1')\r\nsheet_1=DataFrame(sheet_1,columns=['医院','最新批次'])\r\nformat_1_1=lambda x : re.match(r'(\\S*)_(\\S*)_(\\d{4})_(\\w{10})',x).group(1)+'_'+re.match(r'(\\S*)_(\\S*)_(\\d{4})_(\\w{10})',x).group(2)\r\nformat_1_2=lambda x : re.match(r'(\\S*)_(\\S*)_(\\d{4})_(\\w{10})',x).group(1)\r\nformat_1_3=lambda x : re.match(r'(\\S*)_(\\S*)_(\\d{4})_(\\w{10})',x).group(2)\r\nformat_1_4=lambda x : re.match(r'(\\S*)_(\\S*)_(\\d{4})_(\\w{10})',x).group(4)\r\n\r\nsheet_1['医院']=sheet_1.apply(lambda x: x['医院'].strip(), axis=1)\r\nsheet_1['最新批次']=sheet_1.apply(lambda x: x['最新批次'].strip(), axis=1)#将元素的最前面的空格去除\r\n\r\nsheet_1[\"FC\"]=sheet_1['最新批次'].map(format_1_4)\r\nsheet_1.drop_duplicates(\"FC\",'first', inplace=True) #去掉重复的FC号,只保留第一次出现的\r\nsheet_1[\"系统编号\"]=sheet_1['最新批次'].map(format_1_1)\r\nsheet_1[\"重复编号\"]=(sheet_1[\"系统编号\"][sheet_1[\"系统编号\"].duplicated()]+'A')\r\nsheet_1[\"系统编号\"]=sheet_1[\"重复编号\"].fillna(sheet_1[\"系统编号\"])\r\ndel sheet_1[\"重复编号\"]\r\nlist_del=['NS500821','CUOWU180524','2000','NS500430','NS500826','NS500262','NS500824','CUOWU180719']\r\nsheet_1[\"最新批次\"]=sheet_1['最新批次'][~ sheet_1['最新批次'].map(format_1_2).isin(list_del)]\r\nsheet_1=sheet_1.dropna()\r\nsheet_1[\"最新批次\"]=sheet_1['最新批次'][~ sheet_1['最新批次'].map(format_1_3).isin(list_del)]\r\nsheet_1=sheet_1.dropna()\r\n\r\n\r\n#本地批次汇总\r\nsheet_2=pd.read_excel(path,'Sheet2')\r\nsheet_2=DataFrame(sheet_2,columns=['样品编号','FC号','机器编号','上机时间'])\r\n\r\nsheet_2['样品编号']=sheet_2.apply(lambda x: x['样品编号'].strip(), axis=1)\r\nsheet_2['FC号']=sheet_2.apply(lambda x: x['FC号'].strip(), axis=1)\r\nsheet_2['机器编号']=sheet_2.apply(lambda x: x['机器编号'].strip(), axis=1)\r\nsheet_2['上机时间']=sheet_2.apply(lambda x: x['上机时间'].strip(), axis=1)\r\n\r\n#根据某一列数据中重复元素删除其他行,只保留第一次出现的行,见下面\r\nsheet_2.drop_duplicates('FC号','first', inplace=True)\r\nformat_2_1=lambda x : re.match(r'\\d{2}(\\S*)-(\\S*)-(\\S*)',str(x)).group(1) + re.match(r'(\\S*)-(\\S*)-(\\S*)',str(x)).group(2) + re.match(r'(\\S*)-(\\S*)-(\\S*)',str(x)).group(3)\r\nformat_2_2=lambda x : re.match(r'(\\S*)_(\\S*)_(\\S*)',str(x)).group(1) +'_'+ re.match(r'(\\S*)_(\\S*)_(\\S*)',str(x)).group(2)\r\nformat_2_3=lambda x : re.match(r'(\\S*)_(\\S*)_(\\S*)',str(x)).group(1) +'_'+ re.match(r'(\\S*)_(\\S*)_(\\S*)',str(x)).group(3)\r\nformat_2_4=lambda x : re.match(r'(\\S*)_(\\S*)_(\\S*)',str(x)).group(3)\r\nformat_2_5=lambda x : re.match(r'(\\S*)_(\\S*)',str(x)).group(2)\r\nqingdao=['7001459','TPNB500155','NS500548','NS500822']\r\nshanghai=['TPNB500170','D00169','NS500251','NS500280']\r\nsheet_2[\"日期\"]=sheet_2['上机时间'].map(format_2_1)\r\n\r\n#将某一列中的元素含有特定字符串替换为目的字符串,见下面\r\nsheet_2['机器编号']=sheet_2.apply(lambda x: x['机器编号'].replace('TPNS500822','NS500822') if 'TPNS500822' in x['机器编号'] else x['机器编号'], axis=1)\r\nsheet_2['机器编号']=sheet_2.apply(lambda x: x['机器编号'].replace('D00169-B','D00169') if 'D00169-B' in x['机器编号'] else x['机器编号'], axis=1)\r\nsheet_2[\"青岛机器号\"]=sheet_2['机器编号'][sheet_2['机器编号'].isin(qingdao)]\r\nsheet_2[\"上海机器号\"]=sheet_2['机器编号'][sheet_2['机器编号'].isin(shanghai)]\r\nsheet_2[\"北京机器号\"]=sheet_2['机器编号'][~ sheet_2['机器编号'].isin(shanghai+qingdao)]\r\nsheet_2[\"青岛编号\"]=sheet_2[\"日期\"]+'_'+sheet_2[\"青岛机器号\"]\r\nsheet_2[\"上海编号\"]=sheet_2[\"日期\"]+'_'+sheet_2[\"上海机器号\"]\r\nsheet_2[\"北京编号\"]=sheet_2[\"日期\"]+'_'+sheet_2['FC号'][sheet_2['北京机器号'].notnull()]\r\nsheet_2[\"系统编号\"]=sheet_2[\"北京编号\"].fillna(sheet_2[\"上海编号\"]).fillna(sheet_2[\"青岛编号\"])\r\n#出现重复元素,第二次或者第三次...全部末尾添加B,见下面\r\nsheet_2[\"重复一次\"]=(sheet_2[\"系统编号\"][sheet_2[\"系统编号\"].duplicated()]+'B')\r\n#两个B,则第三次加C,见下面\r\nsheet_2[\"重复二次\"]=(sheet_2[\"重复一次\"][sheet_2[\"重复一次\"].duplicated()]+'C')\r\nif True in [x for x in sheet_2[\"重复二次\"].notnull()]:\r\n sheet_2[\"重复一次\"]=sheet_2[\"重复二次\"].fillna(sheet_2[\"重复一次\"])\r\n sheet_2[\"系统编号\"]=sheet_2[\"重复一次\"].fillna(sheet_2[\"系统编号\"])\r\nelse:\r\n sheet_2[\"系统编号\"]=sheet_2[\"重复一次\"].fillna(sheet_2[\"系统编号\"])\r\n\r\n#系统批次汇总\r\nsheet_3=pd.read_excel(path,'Sheet3',header=None)\r\nsheet_3=DataFrame(sheet_3,columns=[1])\r\nformat_3=lambda x : re.match(r'(\\S*)_(\\S*)_(\\S*)',x).group(1)+'_'+re.match(r'(\\S*)_(\\S*)_(\\S*)',x).group(2)\r\nsheet_3[\"系统编号\"]=sheet_3[1].map(format_3)\r\n\r\n#data_merge = Series().append(sheet_1[\"系统编号\"]).append(sheet_2[\"系统编号\"])\r\n\r\nwaidi_out = Series(np.setdiff1d(sheet_1[\"系统编号\"],sheet_3[\"系统编号\"]))\r\nbendi_out = Series(np.setdiff1d(sheet_2[\"系统编号\"],sheet_3[\"系统编号\"]))\r\n\r\nwaidi_pici=sheet_1[['医院','最新批次','系统编号']][sheet_1['系统编号'].isin(waidi_out)]\r\nbendi_pici=sheet_2[['样品编号','FC号','机器编号','上机时间','系统编号']][sheet_2['系统编号'].isin(bendi_out)]\r\n\r\nwaidi_pici[',']=','\r\nbendi_pici[',']=','\r\n#waidi_pici['医院']=waidi_pici.apply(lambda x: x['医院'].strip(), axis=1)\r\nwaidi_pici=waidi_pici[[',','医院',',','最新批次',',','系统编号']].reset_index(drop=True)\r\nbendi_pici=bendi_pici[[',','样品编号',',','FC号',',','机器编号',',','上机时间',',','系统编号']].reset_index(drop=True)\r\n\r\n#输出文件\r\nf = open(out_put,'wt',encoding='utf-8-sig')\r\nf.write(','+'外地批次未导入系统批次:'+','+'(外地系统编号末尾加A,两批次都要查询)\\n')\r\nf.write(str(waidi_pici)+'\\n')\r\nf.write('\\n')\r\nf.write(','+'本地批次未导入系统批次:'+','+'(本地系统编号末尾加B,两批次都要查询)\\n')\r\nf.write(str(bendi_pici)+'\\n')\r\nf.close()\r\n","sub_path":"2018_07_27.py","file_name":"2018_07_27.py","file_ext":"py","file_size_in_byte":6781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146117182","text":"from game_engine import Sprite\n\nBASE_1 = r'assets/base_1.png'\nBASE_2 = r'assets/base_2.png'\nBULLET_1 = r'assets/bullet_1.png'\nBULLET_2 = r'assets/bullet_2.png'\nKEY_A = 97\nKEY_P = 112\n\nclass Base(Sprite):\n\n def __init__(self, player_number, position):\n\n self.player_number = player_number\n\n if player_number == 1:\n base_player_path = BASE_1\n else:\n base_player_path = BASE_2\n\n super().__init__(base_player_path, position, anchor=(64, 0))\n\n def on_key_press(self, key, modifiers):\n\n if self.player_number == 1 and key == KEY_A:\n print(\"player 1 shoot.\")\n elif self.player_number == 2 and key == KEY_P:\n print(\"player 2 shoot.\")\n\n\nclass Bullet(Sprite):\n\n def __init__(self, player_number, position, speed):\n\n self.player_number = player_number\n self.speed = speed\n\n if player_number == 1:\n bullet_player_path = BULLET_1\n else:\n bullet_player_path = BULLET_2\n\n super().__init__(bullet_player_path, position, anchor=(8, 8))\n\n def update(self, dt):\n super().update(dt)\n\n dx = self.speed[0] * dt\n dy = self.speed[1] * dt\n\n self.position = self.position[0] + dx, self.position[1] + dy\n\n","sub_path":"Exercices/canons/corrections/step 4/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"515391671","text":"# -*- coding: utf-8 -*-\nfrom telegram import Bot, Update\n\nfrom moderator.core.service.welcome import TIP_TEMPLATE\nfrom moderator.db.model import AllChats\nfrom moderator.util.logger import logger\nfrom moderator.util.message import send_message\nfrom moderator.util.permision import admin\nfrom moderator.util.util import get_chat_id_and_users\n\n\n@admin\ndef ban(bot: Bot, update: Update):\n logger.info(\"ban user...\")\n chat_id, users = get_chat_id_and_users(bot, update)\n if not users:\n send_message(bot, chat_id, TIP_TEMPLATE + '进行踢出~')\n\n for user in users:\n AllChats.ban(bot, chat_id, user)\n\n logger.info(\"ban user done!!!\")\n\n\n@admin\ndef unban(bot: Bot, update: Update):\n logger.info(\"unban user...\")\n chat_id, users = get_chat_id_and_users(bot, update)\n if not users:\n send_message(bot, chat_id, TIP_TEMPLATE + '进行解冻')\n\n for user in users:\n AllChats.unban(bot, chat_id, user)\n\n logger.info(\"unban user done!!!\")\n","sub_path":"moderator/core/service/ban.py","file_name":"ban.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"479608343","text":"#Autores: Programa realizado por Equipo2_CodePain\n#Version 1.0\n#Programa que determina la cantidad de años bisiestos que hay entre dos años\n\n#Entrada: Lectura de baseYear y topYear\nbaseYear=-1\ntopYear=-1\nplace=0\nquantity=0\n\nwhile baseYear<0 or topYear<0: #Comprueba que esten ordenados y positivos\n baseYear=int(input())\n topYear=int(input())\n if baseYear>topYear:\n baseYear=-1\n topYear=-1\n\n#Proceso: Detecta cuantos años le falta para ser viciesto y encuentra la cantidad presente en el rango\nplace=baseYear%4\n\nif place==0:\n quantity=int((topYear-baseYear)/4+1)\nelse:\n if place==1:\n quantity=int((topYear+1-baseYear)/4)\n else:\n if place==2:\n quantity=int((topYear+2-baseYear)/4)\n else:\n quantity=int((topYear+3-baseYear)/4)\n\n\n#Salida: La cantidad de años bisiestos en el rango de años\nprint(quantity)","sub_path":"Unidad 2-Estructuras de Control/Ejercicio32.py","file_name":"Ejercicio32.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503942975","text":"import discord\nimport requests\nimport threading\nimport time\n\nTOKEN = \"\"\nclient = discord.Client()\n\ndef getpage(ids, page):\n\ttry:\n\t\tr = requests.get(\"https://discordapp.com/api/v9/guilds/\" + ids + \"/messages/search?has=link&offset=\" + str(page * 25), headers={'authorization': TOKEN})\n\t\tfor messages in r.json()[\"messages\"]:\n\t\t\tthemessage = messages[0]\n\t\t\t#print(themessage[\"content\"])\n\t\t\tif \"discord.gg/\" in themessage[\"content\"]:\n\t\t\t\tprint((f\"https://discord.gg/{themessage['content'].split('discord.gg/')[1].split(' ')[0]}\"))\n\texcept:\n\t\tasdsdfsdgsdg = 0\n\t\t\t\n@client.event\nasync def on_ready():\n\tprint(f'{client.user} has connected to Discord!')\n\n@client.event\nasync def on_message(message):\n\tif message.author.id != client.user.id:\n\t\treturn\n\tif \"zxc \" in message.content:\n\t\tids = message.content.split(\"zxc \")[1]\n\t\tfor i in range(2000):\n\t\t\tt = threading.Thread(target=getpage, args=(ids, i))\n\t\t\tt.start()\n\t\t\ttime.sleep(0.1)\n\t\t\t\nclient.run(TOKEN)\n","sub_path":"Project DSC/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"321770581","text":"import matplotlib.pyplot as plt\nimport seaborn as sb\n\nsb.set_style(style=\"whitegrid\")\nsb.set_color_codes()\nimport numpy as np\nimport scipy.stats as sts\nimport pandas\nimport pandas as pd\nimport eif_old as eif_old_class\nimport scipy.io as sio\nimport os\nimport sklearn.metrics as skm\n\n\ndef draw_ROC(filename, number_of_trees, subsample_size, extensionLevel, dataset_type, algo_type):\n if algo_type == \"SIF\":\n path = './EIF_SIF_Result/SIF_Result/' + filename + \"_SIF_Result_Data_\" + dataset_type + \"-\" + str(\n number_of_trees) + \"-\" + str(subsample_size) + \"-\" + str(0) + \".xlsx\"\n pd_data = pd.read_excel(path, index_col=0)\n\n else:\n prob_result_path = \"./EIF_SIF_Result/chordalysis_log_prob_result/\" + filename + \"-\" + dataset_type + \"-\" + algo_type + \"_result.xlsx\"\n pd_prob_result_data = pd.read_excel(prob_result_path)\n dataset_path = \"./datasets/\" + filename + \"_discretized_\" + dataset_type + \"_withLabel.csv\"\n pd_data = pd.read_csv(dataset_path)\n pd_data[\"score\"] = abs(pd_prob_result_data)\n\n y_test = np.array(pd_data.loc[:, \"label\"], dtype=\"int32\")\n y_score = np.array(pd_data.loc[:, \"score\"])\n\n # auc_roc_score = skm.roc_auc_score(y_test, y_score)\n # print(\"ROC_AUC_Score: \" + str(auc_roc_score))\n\n fpr_s, tpr_s, thresholds_s = skm.roc_curve(y_test, y_score, pos_label=1)\n return fpr_s, tpr_s\n # return fpr_s, tpr_s, auc_roc_score\n\n\n# dataset_names = [\"annthyroid\", \"cardio\", \"foresttype\", \"ionosphere\", \"mammography\", \"satellite\", \"shuttle\", \"thyroid\"]\n# dataset_names = [\"annthyroid\", \"cardio\", \"ionosphere\",\"mammography\" ,\"satellite\", \"shuttle\", \"thyroid\"]\n# dataset_names = [\"annthyroid\", \"cardio\", \"ionosphere\", \"mammography\", \"satellite\", \"shuttle\", \"thyroid\",\"smtp\",\"satimage-2\",\"pendigits\",\"speech\"]\ndataset_names = [\"foresttype\",\"http\"]\n# dataset_names = [\"smtp\",\"satimage-2\",\"pendigits\",\"speech\"]\ndataset_types = [\"10BIN\", \"15BIN\"]\nalgo_types = [\"SIF\", \"log_pseudolikelihood\", \"ordered_log_prob\"]\n# parameter for traing the forest\nnumber_of_trees = 500\nsubsample_size = 256\nextensionLevel = 0\n\nfor dataset_name in dataset_names:\n fig, ax = plt.subplots()\n for dataset_type in dataset_types:\n for algo_type in algo_types:\n fpr_s, tpr_s = draw_ROC(filename=dataset_name,\n number_of_trees=number_of_trees,\n subsample_size=subsample_size,\n extensionLevel=extensionLevel,\n dataset_type=dataset_type, algo_type=algo_type)\n if dataset_type == \"10BIN\":\n plot_color = \"brown\"\n elif dataset_type == \"15BIN\":\n plot_color = \"darkblue\"\n else:\n # origin\n plot_color = \"black\"\n\n if algo_type == \"log_pseudolikelihood\":\n plot_linestyle = \"--\"\n algo_type_on_plot = \"Chordalysis_Pseudolikelihood\"\n elif algo_type == \"ordered_log_prob\":\n plot_linestyle = \"dotted\"\n algo_type_on_plot = \"Chordalysis_Joint_Probability\"\n else:\n plot_linestyle = \"-\"\n algo_type_on_plot = \"SIF\"\n\n\n\n ax.plot(fpr_s, tpr_s, label=dataset_type + \"-\" + algo_type_on_plot, color=plot_color, linestyle=plot_linestyle)\n # result_summary_path = \"./plots/\" + dataset_name + \"_Chordalysis_Result_Summary.txt\"\n # with open(result_summary_path, 'a') as opened_file:\n # opened_file.write(\"Data_Type: \" + dataset_type)\n # opened_file.write(\"\\n\")\n # opened_file.write(\"Algo_type: \" + algo_type)\n # opened_file.write(\"\\n\")\n # opened_file.write(\"ROC_AUC_Score: \" + str(auc_roc_score))\n # opened_file.write(\"\\n\")\n # opened_file.write(\"\\n\")\n\n\n ax.set_xlabel('FPR')\n ax.set_ylabel('TPR')\n ax.set_title(\"ROC Curve\")\n ax.legend()\n if extensionLevel == \"full\":\n extensionLevel_str = extensionLevel\n else:\n extensionLevel_str = str(extensionLevel)\n plot_path = \"./plots/\" + dataset_name + \"-Chordalysis_ROC_Curve-\" + str(number_of_trees) + \"-\" + str(\n subsample_size) + \"-\" + extensionLevel_str + \".jpg\"\n fig.savefig(plot_path)\n plt.close(fig)\n","sub_path":"IsolaionForest/tool_draw_ROC_Chordalysis.py","file_name":"tool_draw_ROC_Chordalysis.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204817488","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nx = pd.read_csv('/Users/nate/Projects/EBV_interactome/Akata_Zta.summary.genes.csv', index_col=0)\nx = x[x.columns[:4]]\nebv = pd.read_table('/Users/nate/Projects/EBV_interactome/ebvgenes', header=None)\nebv = set(ebv[0]) & set(x.index)\nebv = {i for i in ebv if 'miR' not in i}\nncrna = {'RPMS1', 'EBER1', 'EBER2', 'A73'}\ncoding = {i for i in ebv if i not in ncrna}\n\ncoding_exp = np.sum(x.loc[coding])\nnoncod_exp = np.sum(x.loc[ncrna])\n\n\n\n\nf, (ax, ax2) = plt.subplots(2, 1, sharex=True)\nax.bar(range(4), noncod_exp)\nax2.bar(range(4), noncod_exp)\nax.bar(range(4), coding_exp, bottom=noncod_exp)\nax2.bar(range(4), coding_exp, bottom=noncod_exp)\n\nax2.set_ylim([0,2000])\nax.set_ylim([2000, 1000000])\n\nplt.savefig('/Users/nate/Projects/EBV_interactome/sinclair_lytic.svg')\n\nlatencygenes = {'LMP-2A',\n 'LMP-2B',\n 'LMP-1',\n 'Cp-EBNA2',\n 'Cp-EBNA3A',\n 'Cp-EBNA3B',\n 'Cp-EBNA3C',\n 'Cp-EBNA1',\n 'EBNA-LP',\n 'Qp-EBNA1',\n 'EBER1',\n 'EBER2',\n 'RPMS1',\n 'LF3',\n 'A73',\n 'BHLF1'}\n\n\n\ncoding_exp = np.sum(x.loc[coding & latencygenes])\nnoncod_exp = np.sum(x.loc[ncrna & latencygenes])\n\n\n\n\nf, (ax, ax2) = plt.subplots(2, 1, sharex=True)\nax.bar(range(4), noncod_exp)\nax2.bar(range(4), noncod_exp)\nax.bar(range(4), coding_exp, bottom=noncod_exp)\nax2.bar(range(4), coding_exp, bottom=noncod_exp)\n\nax2.set_ylim([0,2000])\nax.set_ylim([2000, 1000000])\n\nplt.savefig('/Users/nate/Projects/EBV_interactome/sinclair_lytic_latency_genes_only.svg')\n","sub_path":"sinclair_lytic.py","file_name":"sinclair_lytic.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"106478463","text":"import warnings\nimport os\nimport errno\nimport datetime\nimport time\nimport math\nimport json\nfrom functools import wraps, partial\nfrom collections import Sequence\ntry:\n from itertools import izip\nexcept ImportError: #python3.x\n izip = zip\n\nimport numpy as np\nfrom numpy.linalg import pinv\nfrom skimage.transform._geometric import GeometricTransform\n\nimport xml.etree.cElementTree as ET\nfrom xml.dom import minidom\nimport ephem\nfrom string import Template\n\nfrom shapely.geometry import shape, box\nfrom shapely.wkt import loads\nfrom shapely import ops\nfrom affine import Affine\nimport pyproj\n\nfrom gbdxtools.rda.graph import VIRTUAL_RDA_URL\nimport gbdxtools.rda.constants as constants\n\nfrom gbdxtools.deprecate import GBDXDeprecation, deprecation\n\nRDA_TO_DTYPE = {\n \"BINARY\": \"bool\",\n \"BYTE\": \"uint8\",\n \"SHORT\": \"short\",\n \"UNSIGNED_SHORT\": \"ushort\",\n \"INTEGER\": \"int32\",\n \"UNSIGNED_INTEGER\": \"uint32\",\n \"LONG\": \"int64\",\n \"UNSIGNED_LONG\": \"uint64\",\n \"FLOAT\": \"float32\",\n \"DOUBLE\": \"float64\"\n}\n\nCUSTOM_PRJ = {\n \"EPSG:54008\": \"+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\"\n}\n\ndef get_proj(prj_code):\n \"\"\"\n Helper method for handling projection codes that are unknown to pyproj\n\n Args:\n prj_code (str): an epsg proj code\n\n Returns:\n projection: a pyproj projection\n \"\"\"\n if prj_code in CUSTOM_PRJ:\n proj = pyproj.Proj(CUSTOM_PRJ[prj_code])\n else:\n proj = pyproj.Proj(init=prj_code)\n return proj\n\n# TODO need to handle diff projections: project WGS84 bounds into image proj\ndef preview(image, **kwargs):\n ''' Show a slippy map preview of the image. Requires iPython.\n\n Args:\n image (image): image object to display\n zoom (int): zoom level to intialize the map, default is 16\n center (list): center coordinates to initialize the map, defaults to center of image\n bands (list): bands of image to display, defaults to the image's default RGB bands\n '''\n \n try:\n from IPython.display import Javascript, HTML, display\n from gbdxtools.rda.interface import RDA\n from gbdxtools import Interface\n gbdx = Interface()\n except:\n print(\"IPython is required to produce maps.\")\n return\n\n zoom = kwargs.get(\"zoom\", 16)\n bands = kwargs.get(\"bands\")\n if bands is None:\n bands = image._rgb_bands\n wgs84_bounds = kwargs.get(\"bounds\", list(loads(image.metadata[\"image\"][\"imageBoundsWGS84\"]).bounds))\n center = kwargs.get(\"center\", list(shape(image).centroid.bounds[0:2]))\n \n if image.proj != 'EPSG:4326':\n code = image.proj.split(':')[1]\n conn = gbdx.gbdx_connection\n proj_info = conn.get('https://ughlicoordinates.geobigdata.io/ughli/v1/projinfo/{}'.format(code)).json()\n tfm = partial(pyproj.transform, pyproj.Proj(init='EPSG:4326'), pyproj.Proj(init=image.proj))\n bounds = list(ops.transform(tfm, box(*wgs84_bounds)).bounds)\n else:\n proj_info = {}\n bounds = wgs84_bounds\n # Applying DRA to a DRA'ed image looks bad, skip if already in graph\n if not image.options.get('dra'):\n rda = RDA()\n # Need some simple DRA to get the image in range for display.\n dra = rda.HistogramDRA(image)\n image = dra.aoi(bbox=image.bounds)\n graph_id = image.rda_id\n node_id = image.rda.graph()['nodes'][0]['id']\n map_id = \"map_{}\".format(str(int(time.time())))\n scales = ','.join(['1'] * len(bands))\n offsets = ','.join(['0'] * len(bands))\n\n display(HTML(Template('''\n
\n \n \n \n \n ''').substitute({\"map_id\": map_id})))\n\n js = Template(\"\"\"\n require.config({\n paths: {\n oljs: 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol',\n proj4: 'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4'\n }\n });\n\n require(['oljs', 'proj4'], function(oljs, proj4) {\n oljs.proj.setProj4(proj4)\n var md = $md;\n var georef = $georef;\n var graphId = '$graphId';\n var nodeId = '$nodeId';\n var extents = $bounds;\n\n var x1 = md.minTileX * md.tileXSize;\n var y1 = ((md.minTileY + md.numYTiles) * md.tileYSize + md.tileYSize);\n var x2 = ((md.minTileX + md.numXTiles) * md.tileXSize + md.tileXSize);\n var y2 = md.minTileY * md.tileYSize;\n var tileLayerResolutions = [georef.scaleX];\n\n var url = '$url' + '/tile/';\n url += graphId + '/' + nodeId;\n url += \"/{x}/{y}.png?token=$token&display_bands=$bands&display_scales=$scales&display_offsets=$offsets\";\n\n var proj = '$proj';\n var projInfo = $projInfo;\n\n if ( proj !== 'EPSG:4326' ) {\n var proj4def = projInfo[\"proj4\"];\n proj4.defs(proj, proj4def);\n var area = projInfo[\"area_of_use\"];\n var bbox = [area[\"area_west_bound_lon\"], area[\"area_south_bound_lat\"],\n area[\"area_east_bound_lon\"], area[\"area_north_bound_lat\"]]\n var projection = oljs.proj.get(proj);\n var fromLonLat = oljs.proj.getTransform('EPSG:4326', projection);\n var extent = oljs.extent.applyTransform(\n [bbox[0], bbox[1], bbox[2], bbox[3]], fromLonLat);\n projection.setExtent(extent);\n } else {\n var projection = oljs.proj.get(proj);\n }\n\n var rda = new oljs.layer.Tile({\n title: 'RDA',\n opacity: 1,\n extent: extents,\n source: new oljs.source.TileImage({\n crossOrigin: null,\n projection: projection,\n extent: extents,\n\n tileGrid: new oljs.tilegrid.TileGrid({\n extent: extents,\n origin: [extents[0], extents[3]],\n resolutions: tileLayerResolutions,\n tileSize: [md.tileXSize, md.tileYSize],\n }),\n tileUrlFunction: function (coordinate) {\n if (coordinate === null) return undefined;\n const x = coordinate[1] + md.minTileX;\n const y = -(coordinate[2] + 1 - md.minTileY);\n if (x < md.minTileX || x > md.maxTileX) return undefined;\n if (y < md.minTileY || y > md.maxTileY) return undefined;\n return url.replace('{x}', x).replace('{y}', y);\n }\n })\n });\n\n var map = new oljs.Map({\n layers: [ rda ],\n target: '$map_id',\n view: new oljs.View({\n projection: projection,\n center: $center,\n zoom: $zoom\n })\n });\n });\n \"\"\").substitute({\n \"map_id\": map_id,\n \"proj\": image.proj,\n \"projInfo\": json.dumps(proj_info),\n \"graphId\": graph_id,\n \"bounds\": bounds,\n \"bands\": \",\".join(map(str, bands)),\n \"nodeId\": node_id,\n \"md\": json.dumps(image.metadata[\"image\"]),\n \"georef\": json.dumps(image.metadata[\"georef\"]),\n \"center\": center,\n \"zoom\": zoom,\n \"token\": gbdx.gbdx_connection.access_token,\n \"scales\": scales,\n \"offsets\": offsets,\n \"url\": VIRTUAL_RDA_URL\n })\n display(Javascript(js))\n\ndef reproject_params(proj):\n _params = {}\n if proj is not None:\n _params[\"Source SRS Code\"] = \"EPSG:4326\"\n _params[\"Source pixel-to-world transform\"] = None\n _params[\"Dest SRS Code\"] = proj\n _params[\"Dest pixel-to-world transform\"] = None\n return _params\n\ndef ortho_params(proj, gsd=None):\n params = {}\n if gsd is not None:\n params[\"Requested GSD\"] = str(gsd)\n params[\"Resampling Kernel\"] = \"INTERP_BILINEAR\"\n params[\"Grid Size\"] = 10\n if proj is not None:\n params[\"Output Coordinate Reference System\"] = proj\n params[\"Sensor Model\"] = None\n params[\"Elevation Source\"] = \"\"\n params[\"Output Pixel to World Transform\"] = \"\"\n return params\n\n\ndef calc_toa_gain_offset(meta):\n \"\"\"\n Compute (gain, offset) tuples for each band of the specified image metadata\n \"\"\"\n # Set satellite index to look up cal factors\n sat_index = meta['satid'].upper() + \"_\" + meta['bandid'].upper()\n\n # Set scale for at sensor radiance\n # Eq is:\n # L = GAIN * DN * (ACF/EBW) + Offset\n # ACF abscal factor from meta data\n # EBW effectiveBandwidth from meta data\n # Gain provided by abscal from const\n # Offset provided by abscal from const\n acf = np.asarray(meta['abscalfactor']) # Should be nbands length\n ebw = np.asarray(meta['effbandwidth']) # Should be nbands length\n gain = np.asarray(constants.DG_ABSCAL_GAIN[sat_index])\n scale = (acf / ebw) * gain\n offset = np.asarray(constants.DG_ABSCAL_OFFSET[sat_index])\n\n e_sun_index = meta['satid'].upper() + \"_\" + meta['bandid'].upper()\n e_sun = np.asarray(constants.DG_ESUN[e_sun_index])\n sun = ephem.Sun()\n img_obs = ephem.Observer()\n img_obs.lon = meta['latlonhae'][1]\n img_obs.lat = meta['latlonhae'][0]\n img_obs.elevation = meta['latlonhae'][2]\n img_obs.date = datetime.datetime.fromtimestamp(meta['img_datetime_obj_utc']['$date'] / 1000.0).strftime(\n '%Y-%m-%d %H:%M:%S.%f')\n sun.compute(img_obs)\n d_es = sun.earth_distance\n\n # Pull sun elevation from the image metadata\n # theta_s can be zenith or elevation - the calc below will us either\n # a cos or s in respectively\n # theta_s = float(self.meta_dg.IMD.IMAGE.MEANSUNEL)\n theta_s = 90 - float(meta['mean_sun_el'])\n scale2 = (d_es ** 2 * np.pi) / (e_sun * np.cos(np.deg2rad(theta_s)))\n\n # Return scaled data\n # Radiance = Scale * Image + offset, Reflectance = Radiance * Scale2\n return zip(scale, scale2, offset)\n\n\nclass RatPolyTransform(GeometricTransform):\n def __init__(self, A, B, offset, scale, px_offset, px_scale, gsd=None, proj=None, default_z=0):\n self.proj = proj\n self._A = A\n self._B = B\n self._offset = offset\n self._scale = scale\n self._px_offset = px_offset\n self._px_scale = px_scale\n self._gsd = gsd\n self._offscl = np.vstack([offset, scale])\n self._offscl_rev = np.vstack([-offset/scale, 1.0/scale])\n self._px_offscl_rev = np.vstack([px_offset, px_scale])\n self._px_offscl = np.vstack([-px_offset/px_scale, 1.0/px_scale])\n\n self._default_z = default_z\n\n self._A_rev = np.dot(pinv(np.dot(np.transpose(A), A)), np.transpose(A))\n # only using the numerator (more dynamic range for the fit?)\n # self._B_rev = np.dot(pinv(np.dot(np.transpose(B), B)), np.transpose(B))\n\n @property\n def gsd(self):\n return self._gsd\n\n def rev(self, lng, lat, z=None, _type=np.int32):\n if z is None:\n z = self._default_z\n\n if all(isinstance(var, (int, float, tuple)) for var in [lng, lat]):\n lng, lat = (np.array([lng]), np.array([lat]))\n if not all(isinstance(var, np.ndarray) for var in [lng, lat]):\n raise ValueError(\"lng, lat inputs must be of type int, float, tuple or numpy.ndarray\")\n if not isinstance(z, np.ndarray):\n z = np.zeros_like(lng) + z\n coord = np.dstack([lng, lat, z])\n offset, scale = np.vsplit(self._offscl, 2)\n normed = coord * scale + offset\n X = self._rpc(normed)\n result = np.rollaxis(np.inner(self._A, X) / np.inner(self._B, X), 0, 3)\n rev_offset, rev_scale = np.vsplit(self._px_offscl_rev, 2)\n # needs to return x/y\n return np.rint(np.rollaxis(result * rev_scale + rev_offset, 2)).squeeze().astype(_type)[::-1]\n\n def fwd(self, x, y, z=None):\n if isinstance(x, (Sequence, np.ndarray)):\n if z is None:\n z = [None]*len(x)\n return np.transpose(np.asarray([self.fwd(x_i, y_i, z_i) for x_i, y_i, z_i in izip(x, y, z)]))\n coord = np.asarray([x, y])\n normed = np.sum(self._px_offscl * np.vstack([np.ones(coord.shape), coord]), axis=0)\n coord = np.dot(self._A_rev, normed)[[1,2,3]] # likely unstable\n return np.sum(self._offscl_rev * np.vstack([np.ones(coord.shape), coord]), axis=0)\n\n def __call__(self, coords):\n assert isinstance(coords, np.ndarray)\n try:\n d0, d1 = coords.shape\n assert d1 ==2\n except (ValueError, AssertionError):\n raise NotImplementedError(\"input coords must be [N x 2] dimension numpy array\")\n if d1 != 2:\n raise NotImplementedError(\"input coords must be [N x 2] dimension numpy array\")\n\n xarr, yarr = np.hsplit(coords, 2)\n res = self.fwd(xarr, yarr)\n return res\n\n def inverse(self, coords):\n pass\n\n def residuals(self, src, dst):\n pass\n\n def _rpc(self, x):\n L, P, H = np.dsplit(x, 3)\n return np.dstack([np.ones((x.shape[0], x.shape[1]), dtype=np.float32), L, P, H, L*P, L*H, P*H, L**2, P**2, H**2,\n L*P*H, L**3, L*(P**2), L*(H**2), (L**2)*P, P**3, P*(H**2),\n (L**2)*H, (P**2)*H, H**3])\n\n def __add__(self, other):\n if isinstance(other, Sequence) and len(other) == 2:\n shift = np.asarray(other)\n # shift is an x/y px_offset needs to be y/x\n return RatPolyTransform(self._A, self._B, self._offset, self._scale,\n self._px_offset - shift[::-1], self._px_scale,\n self.gsd, self.proj, self._default_z)\n else:\n raise NotImplemented\n\n def __sub__(self, other):\n try:\n return self.__add__(-other)\n except:\n return self.__add__([-e for e in other])\n\n @classmethod\n def from_rpcs(cls, rpcs):\n P = np.vstack([np.asarray(rpcs[\"lineNumCoefs\"]),\n np.asarray(rpcs[\"sampleNumCoefs\"])])\n Q = np.vstack([np.asarray(rpcs[\"lineDenCoefs\"]),\n np.asarray(rpcs[\"sampleDenCoefs\"])])\n\n scale = np.asarray([1.0/rpcs[\"lonScale\"],\n 1.0/rpcs[\"latScale\"],\n 1.0/rpcs[\"heightScale\"]])\n offset = np.asarray([-rpcs[\"lonOffset\"],\n -rpcs[\"latOffset\"],\n -rpcs[\"heightOffset\"]])*scale\n\n px_scale = np.asarray([rpcs[\"lineScale\"], rpcs[\"sampleScale\"]])\n px_offset = np.asarray([rpcs[\"lineOffset\"], rpcs[\"sampleOffset\"]])\n\n return cls(P, Q, offset, scale, px_offset, px_scale, rpcs[\"gsd\"], rpcs[\"spatialReferenceSystem\"],\n rpcs[\"heightOffset\"])\n\n @classmethod\n def from_affine(cls, affine):\n pass\n\n\nclass AffineTransform(GeometricTransform):\n def __init__(self, affine, proj=None):\n self._affine = affine\n self._iaffine = None\n self.proj = proj\n\n def rev(self, lng, lat, z=0):\n if self._iaffine is None:\n self._iaffine = ~self._affine\n px, py = (self._iaffine * (lng, lat))\n if type(px).__name__ == 'ndarray' and type(py).__name__ == 'ndarray':\n return np.rint(np.asarray(px)), np.rint(np.asarray(py))\n else:\n return int(round(px)), int(round(py))\n\n def fwd(self, x, y, z=0):\n return self._affine * (x, y)\n\n def __call__(self, coords):\n assert isinstance(coords, np.ndarray) and len(coords.shape) == 2 and coords.shape[1] == 2\n _coords = np.copy(coords)\n self._affine.itransform(_coords)\n return _coords\n\n def inverse(self, coords):\n assert isinstance(coords, np.ndarray) and len(coords.shape) == 2 and coords.shape[1] == 2\n if self._iaffine is None:\n self._iaffine = ~self._affine\n _coords = np.copy(coords)\n self._iaffine.itransform(_coords)\n return _coords\n\n def residuals(self, src, dst):\n return super(AffineTransform, self).residuals(src, dst)\n\n def __add__(self, other):\n if isinstance(other, Sequence) and len(other) == 2:\n shift = np.asarray(other)\n return AffineTransform(self._affine * Affine.translation(shift[0], shift[1]), proj=self.proj)\n else:\n raise NotImplemented\n\n def __sub__(self, other):\n try:\n return self.__add__(-other)\n except:\n return self.__add__([-e for e in other])\n\n @classmethod\n def from_georef(cls, georef):\n tfm = Affine.from_gdal(georef[\"translateX\"], georef[\"scaleX\"], georef[\"shearX\"],\n georef[\"translateY\"], georef[\"shearY\"], georef[\"scaleY\"])\n return cls(tfm, proj=georef[\"spatialReferenceSystemCode\"])\n\ndef pad_safe_negative(padsize=2, transpix=None, ref_im=None, ind=0):\n trans = transpix[ind,:,:].min() - padsize\n if trans < 0.0:\n trans = transpix[ind,:,:].min()\n return int(math.floor(trans))\n\ndef pad_safe_positive(padsize=2, transpix=None, ref_im=None, ind=0):\n trans = transpix[ind,:,:].max() + padsize\n if len(ref_im.shape) == 3:\n critical = ref_im.shape[ind + 1]\n elif len(ref_im.shape) == 2:\n critical = ref_im.shape[ind]\n else:\n raise NotImplementedError(\"Padding supported only for reference images of shape (L, W) or (Nbands, L, W)\")\n if trans > critical:\n return critical\n return int(math.ceil(trans))\n","sub_path":"gbdxtools/rda/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":17999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"546135550","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n描述:课设题目银行家算法的核心运算部分\n作者:计嵌162 史学超 20160323\n日期:2019-01-10\n修改:改变了add_list为add_data.格式e.g [0,[1, 2, 3,4]],表示第0个资源需要添加的资源向量为[1, 2, 3,4]\n\"\"\"\n\n\ndef write_file(total_list_, claim_list2_, own_list2_):\n # 把需要的数据写到文件中,即保存了结果,也方便其他程序的读取\n from simplejson import dump\n with open('./resource_total_list.txt', 'w') as ft:\n dump(total_list_, ft)\n with open('./resource_claim_list.txt', 'w') as fc:\n dump(claim_list2_, fc)\n with open('./resource_own_list.txt', 'w') as fo:\n dump(own_list2_, fo)\n print(\"成功将数据写到文件\")\n\n\ndef read_file():\n # 从对应的文件中读出对应的数据并包装成合适的格式\n from simplejson import load\n with open('./resource_total_list.txt', 'r') as ft:\n total_list = load(ft)\n with open('./resource_claim_list.txt', 'r') as fc:\n claim_list2 = load(fc)\n with open('./resource_own_list.txt', 'r') as fo:\n own_list2 = load(fo)\n return total_list, claim_list2, own_list2\n\n\ndef check_safety(own_list2_, need_list2_, free_list_):\n \"\"\"\n 检查当前系统状态是否安全,如果安全返回True,否则返回False\n todo:最好能够返回出正确���序列结果\n :param own_list2_: List[List[int]] 已获得资源矩阵\n :param need_list2_: List[List[int]] 需要资源矩阵\n :param free_list_: List[int] 可用资源向量\n :return: Boolean 是否安全\n \"\"\"\n\n def satisfy_current(wait_list_, current_list_):\n \"\"\"\n 判断当前的可使用向量能否满足待申请进程的要求\n :param wait_list_: List[int] 需要资源向量\n :param current_list_: List[int] 当前可使用资源向量\n :return: Boolean 是否满足\n \"\"\"\n for i in range(len(wait_list_)):\n if wait_list_[i] > current_list_[i]:\n return False\n else:\n return True\n\n for own_list in own_list2_:\n for value in own_list:\n if value < 0:\n print(\"系统中有进程过度占用资源\")\n return False\n resource_current_list = [_ for _ in free_list_]\n process_wait_set = {_ for _ in range(len(own_list2_))}\n while True:\n for x in process_wait_set:\n if satisfy_current(need_list2_[x], resource_current_list):\n process_wait_set -= {x}\n for index in range(len(resource_current_list)):\n resource_current_list[index] += own_list2_[x][index]\n break\n else:\n if not process_wait_set:\n return True\n else:\n return False\n\n\ndef main(total_list_=None, claim_list2_=None, own_list2_=None, add_data_=None):\n \"\"\"\n 程序运行的主函数部分,能够从对应的文件中读取所需的参数,也能接受传递的参数.能够判断当前程序是否安全,\n 判断能否添加新的进程进入系统\n :param total_list_: List[int] 系统总拥有资源向量\n :param claim_list2_: List[List[int]] 系统内所有进程所需最大资源矩阵\n :param own_list2_: List[List[int]] 系统内所有进程已拥有资源矩阵\n :param add_data_: List[int,List[int]]等待进入系统的资源向量\n :return: Boolean true对应系统安全,反之\n 例子:前三个参数已经设置了从文件读取,最后一个添加资源向量如果有还是选择通过参数传递\n e.g.main(add_data_ = _resource_add_data)\n \"\"\"\n if total_list_ is None and claim_list2_ is None and own_list2_ is None:\n resource_total_list, resource_claim_list2, resource_own_list2 = read_file()\n else:\n resource_total_list = total_list_\n resource_claim_list2 = claim_list2_\n resource_own_list2 = own_list2_\n print(\"系统拥有的总共资源向量为:\", resource_total_list)\n print(\"各个进程需要最大资源矩阵为:\", resource_claim_list2)\n print(\"各个进程已经拥有资源矩阵为:\", resource_own_list2)\n number_resource = len(resource_total_list)\n number_process = len(resource_claim_list2)\n print(\"系统中拥有的资源种类:{}\\n系统正待命的进程数量:{}\".format(number_resource, number_process))\n resource_need_list2 = [[resource_claim_list2[r][c] - resource_own_list2[r][c] for c in range(number_resource)]\n for r in range(number_process)]\n print(\"各个进程仍需要资源矩阵为:\", resource_need_list2)\n resource_free_list = [_ for _ in resource_total_list]\n for need_list in resource_own_list2:\n for i in range(number_resource):\n resource_free_list[i] -= need_list[i]\n\n for num_free in resource_free_list:\n if num_free < 0:\n print(\"警告!系统当前已经缺少资源\")\n return False\n else:\n print(\"系统可用资源向量为:\", resource_free_list)\n\n if add_data_ is None:\n if check_safety(resource_own_list2, resource_need_list2, resource_free_list):\n print(\"系统是安全的\")\n return True\n else:\n print(\"系统是不安全的\")\n return False\n else:\n pass\n for item_add, item_free in zip(add_data_[1], resource_free_list):\n if item_add > item_free:\n print(\"当前系统无法添加新的进程\")\n return False\n # 修改当前的拥有资源矩阵,需求矩阵和空闲资源矩阵,然后重新检查安全性\n for _ in range(number_resource):\n resource_own_list2[add_data_[0]][_] += add_data_[1][_]\n resource_need_list2[add_data_[0]][_] -= add_data_[1][_]\n resource_free_list[_] -= add_data_[1][_]\n if check_safety(resource_own_list2, resource_need_list2, resource_free_list):\n print(\"该程序的申请是允许的\")\n return True\n else:\n print(\"这次申请会破坏系统安全性\")\n return False\n\n\nif __name__ == '__main__':\n _resource_total_list = [17, 9, 13, 8]\n _resource_claim_list2 = [\n [3, 0, 2, 2],\n [4, 3, 1, 2],\n [3, 5, 5, 3],\n [4, 6, 7, 3],\n [6, 3, 4, 3]\n ]\n _resource_own_list2 = [\n [2, 0, 1, 2],\n [3, 2, 1, 1],\n [2, 2, 3, 1],\n [3, 3, 4, 2],\n [5, 1, 2, 1]\n ]\n _resource_add_data = [0, [1, 0, 0, 0]]\n write_file(_resource_total_list, _resource_claim_list2, _resource_own_list2)\n main(add_data_=_resource_add_data)\n print(\"---银行家算法运行结束---\")\n","sub_path":"banker.py","file_name":"banker.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567651226","text":"\"\"\"mehalsgmues URL Configuration\n\"\"\"\nfrom django.urls import path, include\nfrom django.contrib import admin\nimport juntagrico\nfrom mehalsgmues import views as mehalsgmues\nfrom juntagrico_calendar import views as juntagrico_calendar\nfrom juntagrico import views_subscription as juntagrico_subscription\n\nurlpatterns = [\n # depot list management\n path('my/pdf/manage', mehalsgmues.list_mgmt, name='lists-mgmt'),\n path('my/pdf/manage/success', mehalsgmues.list_mgmt, {'success': True}, name='lists-mgmt-success'),\n path('my/pdf/manage/generate', mehalsgmues.list_generate, name='lists-generate'),\n path('my/pdf/manage/generate/future', mehalsgmues.list_generate, {'future': True}, name='lists-generate-future'),\n\n # jobs view override\n path('my/jobs', juntagrico_calendar.job_calendar, name='jobs'),\n\n path(r'admin/', admin.site.urls),\n path(r'', include('juntagrico.urls')),\n path(r'', juntagrico.views.home),\n path(r'', include('juntagrico_pg.urls')),\n # path(r'', include('juntagrico_crowdfunding.urls')),\n path(r'', include('juntagrico_calendar.urls')),\n path(r'', include('juntagrico_assignment_request.urls')),\n path(r'impersonate/', include('impersonate.urls')),\n\n # polling\n path(r'', include('juntagrico_polling.urls')),\n\n # API\n path(r'wochenmail/', mehalsgmues.api_emaillist, name='mag-mailing-list'),\n path(r'contacts/', mehalsgmues.api_vcf_contacts, name='mag-contact-list'),\n\n # exports\n path('my/export/mag/subscriptions', mehalsgmues.excel_export_subscriptions, name='export-subscriptions-mag'),\n\n # stats\n path('stats/', mehalsgmues.stats, name='mag-stats'),\n\n # Discourse SSO\n path('sso/', mehalsgmues.sso),\n\n # OAuth\n path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),\n path('nextcloud/profile/', mehalsgmues.nextcloud_profile),\n\n # short urls\n path('t/', include('shortener.urls', namespace='shortener')),\n\n # activity profile url\n path('activityprofile/', include('activityprofile.urls')),\n\n # share progress\n path('shares/preview/', mehalsgmues.share_progress_preview, name='shares-preview'),\n\n # keep working\n path('my/order/share/', juntagrico_subscription.manage_shares, name='share-order'),\n]\n","sub_path":"mehalsgmues/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"394459982","text":"from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer\nfrom PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle\nfrom PhysicsTools.Heppy.physicsobjects.Electron import Electron\nfrom PhysicsTools.Heppy.physicsobjects.Muon import Muon\nfrom PhysicsTools.Heppy.physicsobjects.Photon import Photon\n\nfrom PhysicsTools.HeppyCore.utils.deltar import bestMatch\nimport PhysicsTools.HeppyCore.framework.config as cfg\nfrom PhysicsTools.HeppyCore.utils.deltar import * \nfrom PhysicsTools.Heppy.physicsutils.genutils import *\n\n\nimport math, os\nfrom ROOT import heppy, TLorentzVector\nimport math\nimport copy\n\n\nclass PhotonCleaner( Analyzer ):\n\n def __init__(self, cfg_ana, cfg_comp, looperName ):\n super(PhotonCleaner,self).__init__(cfg_ana,cfg_comp,looperName)\n\n self.lepPtMin = getattr(self.cfg_ana, 'minLepPt', -1)\n self.lepSelCut = getattr(self.cfg_ana, 'lepSelCut', lambda lep : True)\n self.eleGammaDR = getattr(self.cfg_ana, 'eleGammaDR', 1.0)\n self.muGammaDR = getattr(self.cfg_ana, 'muGammaDR', 0.5)\n\n if not hasattr(self.cfg_ana ,\"collectionPostFix\"):self.cfg_ana.collectionPostFix=\"\"\n\n\n #----------------------------------------\n # DECLARATION OF HANDLES OF LEPTONS STUFF \n #----------------------------------------\n \n\n def beginLoop(self, setup):\n super(PhotonCleaner,self).beginLoop(setup)\n self.counters.addCounter('events')\n count = self.counters.counter('events')\n count.register('all events')\n \n\n def process(self, event):\n self.readCollections( event.input )\n self.counters.counter('events').inc('all events')\n\n LeptonCleanedPhotons = []\n photons = []\n if hasattr(event, 'selectedPhotons'):\n photons = [ g for g in event.selectedPhotons ] \n\n leptons = []\n if hasattr(event, 'selectedLeptons'):\n leptons = [ l for l in event.selectedLeptons if l.pt() > self.lepPtMin and self.lepSelCut(l) ]\n\n#remove leptons from photon collection\n\n if len(leptons)>0:\n for gamma in photons:\n isNotLep = True\n for lep in leptons:\n dr = deltaR(gamma.eta(),gamma.phi(), lep.eta(),lep.phi())\n if ( dr < 1.0 and abs(lep.pdgId())==11 ): #electron\n isNotLep = False\n if ( dr < 0.5 and abs(lep.pdgId())==13): #muon\n isNotLep = False\n if isNotLep:\n LeptonCleanedPhotons.append(gamma)\n \n #self.selectedLeptons = [ l for l in event.selectedLeptons if l not in self.discardedLeptons ]\n self.selectedPhotons = [ l for l in LeptonCleanedPhotons ]\n\n setattr(event,\"selectedPhotons\" +self.cfg_ana.collectionPostFix, self.selectedPhotons ) \n\n \n return True\n\n\n\n#A default config\nsetattr(PhotonCleaner,\"defaultConfig\",cfg.Analyzer(\n# verbose=False,\n class_object=PhotonCleaner,\n # input collections\n\n minLepPt = 10,\n lepSelCut = lambda lep : True,\n\n eleGammaDR = 1.0,\n muGammaDR = 0.5,\n\n collectionPostFix = \"\"\n )\n)\n","sub_path":"PhysicsTools/Heppy/python/analyzers/objects/PhotonCleaner.py","file_name":"PhotonCleaner.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271528962","text":"import telebot\nfrom ToneAnalyzer import ToneAnalyzer\nfrom TwitterCrawler import TwitterCrawler\n\ntoken = \"494262611:AAFsbPdr0BHy-LuIVvkiomx4kigJ-sGOblA\"\nbot = telebot.TeleBot(token)\nupdate = bot.get_updates()\nlast_update = update[-1]\nlast_chat_text = last_update.message.text\nlast_chat_id = last_update.message.chat.id\nlast_username = last_update.message.from_user.first_name\n\nisRateCommandActive = 0\n\n\n@bot.message_handler(commands=['start'])\ndef handle_start(message):\n bot.send_message(last_chat_id, \"Hello, {}!\\nWelcome to the social rating studio!\\n \"\n \"Here are the commands to use here\\n\"\n \"/rateit - start assessment\".format(last_username))\n\n\n@bot.message_handler(commands=['rateit'])\ndef handle_rate(message):\n global isRateCommandActive\n isRateCommandActive = 1\n bot.send_message(last_chat_id, \"Great!\\n\"\n \"In order to start assessment process, please enter the name of the thing \"\n \"you wish to get rating for.\"\n \"\\nExample: (USA election)\")\n\n\n@bot.message_handler(content_types='text')\ndef rating(message):\n if isRateCommandActive:\n new_search = TwitterCrawler()\n text = new_search.tweet_search('#' + message.text.strip())\n\n analyzer = ToneAnalyzer(text)\n analytics = analyzer.analyze_tone()\n\n bot.send_message(last_chat_id, analytics)\n\n\nbot.polling()\n","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"202098577","text":"\nimport pandas as pd\n\nclass Herd(object):\n\n def __init__(self):\n\n self.max_id = 0\n\n self._beasts = []\n self.roughage_supply = None\n self.concentrate_supply = None\n\n self._is_bull_present = None\n\n @property\n def beasts(self):\n return self._beasts\n\n @beasts.setter\n def beasts(self,value):\n\n for beast in value:\n self.max_id += 1\n beast.unique_id = self.max_id\n\n self._beasts = value\n\n @property\n def is_bull_present(self):\n\n if self._is_bull_present is None:\n\n for beast in self.beasts:\n if beast.sex == 'm':\n return True\n\n return False\n\n else:\n return self._is_bull_present\n\n def set_presence_bull(self):\n for beast in self.beasts:\n beast.is_bull_present = self.is_bull_present\n\n @property\n def highest_id(self):\n return max([x.unique_id for x in self.beasts])\n\n def get_mortal_beasts(self):\n return [x for x in self.beasts if x.will_die]\n\n @property\n def female_beasts(self):\n return [x for x in self.beasts if x.sex == 'f']\n\n @property\n def male_beasts(self):\n return [x for x in self.beasts if x.sex == 'm']\n\n def get_vital_beasts(self):\n return [x for x in self.beasts if not x.will_die]\n\n def get_new_beasts(self):\n res = [x.get_calf() for x in self.female_beasts if x.will_give_birth]\n\n for beast in res:\n self.max_id += 1\n beast.unique_id = self.max_id\n\n # more generally one could consider the name \"get_child\"\n return res\n\n def set_feed(self):\n\n beasts = self.beasts\n N = self.beasts\n\n for beast in beasts:\n beast.roughage_supply = self.roughage_supply.__copy__()\n beast.concentrate_supply = self.concentrate_supply.__copy__()\n\n def update(self):\n\n self.set_feed()\n self.set_presence_bull()\n\n mortal_beasts = self.get_mortal_beasts()\n\n vital_beasts = self.get_vital_beasts()\n\n #print([x.will_die for x in vital_beasts])\n\n for beast in vital_beasts:\n beast.update()\n\n new_beasts = self.get_new_beasts()\n\n beasts_to_keep = [x for x in vital_beasts if not\n (x.sex == 'm' and x.age > 5)]\n\n beasts_to_sell = [x for x in vital_beasts if\n (x.sex == 'm' and x.age > 5)]\n\n self._beasts = beasts_to_keep + new_beasts\n\n def to_dict(self):\n\n res = {}\n\n for beast in self.beasts:\n res[beast.unique_id] = beast.to_dict()\n\n return res\n\n @staticmethod\n def to_dfs(A):\n\n B = {}\n\n # Swap the nesting:\n # A[t][id] -> vars to B[id][t] -> vars\n for t,vars_by_id in A.items():\n for k,v in vars_by_id.items():\n if k in B:\n B[k][t] = v\n else:\n B[k] = {t:v}\n\n C = {}\n for k,v in B.items():\n C[k] = pd.DataFrame(v).T\n\n return C\n\n def run(self,duration=120):\n\n res = {}\n\n for i in range(duration):\n\n self.update()\n\n res[i] = self.to_dict()\n\n return self.to_dfs(res)","sub_path":"LIVSIM/src/Herd.py","file_name":"Herd.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"433677567","text":"from .store import storage\nfrom userv.routing import json_response, text_response\nfrom userv import swagger\nfrom .logging import grown_log\nfrom grown.time_control import get_current_time, seconds_for_one_day\n\ntry:\n import ujson as json\nexcept ImportError:\n import json\ntry:\n import uasyncio as asyncio\nexcept ImportError:\n import asyncio\n\n\ndef _should_light_be_enabled(on_time, off_time, current_time):\n \"\"\"\n calculated if light should be enabled\n :type on_time: int\n :type off_time: int\n :type current_time: int\n :rtype: bool\n \"\"\"\n current_time = seconds_for_one_day(current_time)\n # we only watch the last 24 hours\n if on_time > off_time:\n if current_time < on_time and current_time > off_time:\n off_time += 24 * 60 * 60\n else:\n return current_time >= on_time or current_time <= off_time\n return on_time <= current_time <= off_time\n\n\nasync def _light_control_task(enable_func, disable_func, safety_function):\n \"\"\"\n all parameter are async functions and running in an infinite loop.\n control parameter\n\n :param enable_func: no parameter just enable light\n :param disable_func: no parameter just enable light\n :param safety_function: safety functions is always called before. returned true if not safe to run\n \"\"\"\n if safety_function is None:\n safety_function = lambda x: False\n data_leaf = storage.get_leaf('light_control')\n sensor_data_leaf = storage.get_leaf('sensor_data')\n last_state = None\n while data_leaf is not None:\n try:\n data = data_leaf.get()\n current_time = get_current_time()\n # only need time by day\n sensor_data = sensor_data_leaf.get()\n\n result = safety_function(sensor_data)\n if isinstance(safety_function, type(lambda: (yield))):\n result = await result\n if result is not True:\n switch_on_time = data['switch_on_time']\n switch_off_time = data['switch_off_time']\n if _should_light_be_enabled(switch_on_time, switch_off_time, current_time):\n # Light on\n if last_state is not True:\n grown_log.info(\"light_control: enable light\")\n last_state = True\n enable = enable_func()\n if isinstance(enable_func, type(lambda: (yield))):\n await enable\n else:\n # Light off\n if last_state is not False:\n grown_log.info(\"light_control: disable light\")\n last_state = False\n disable = disable_func()\n if isinstance(disable_func, type(lambda: (yield))):\n await disable\n except Exception as e:\n grown_log.error(\"light_control: %s\" % str(e))\n await asyncio.sleep(100)\n\n\n@swagger.info(\"get current data from light control\")\nasync def _get_light_control_data(request):\n \"\"\"\n path for actual data\n \"\"\"\n data_leaf = storage.get_leaf('light_control')\n return json_response(data_leaf.get())\n\n\n@swagger.info(\"Sets light control\")\n@swagger.body('light_control',\n summary=\"Sets an on or off time. time in seconds. max value is 24*3600 seconds.\",\n example={\n 'switch_on_time': 11 * 3600,\n 'switch_off_time': 23 * 3600\n })\nasync def _post_light_control_data(request):\n leaf = storage.get_leaf('light_control')\n try:\n new_light_control = json.loads(request['body'])\n leaf.update(new_light_control)\n return json_response(new_light_control)\n except Exception as e:\n return text_response(\"light_control: %s\" % str(e), status=400)\n\n\ndef _update_reducer(store_dict, data):\n \"\"\"\n :type store_dict: dict\n :type data: dict\n :rtype: dict\n \"\"\"\n if data.get('switch_on_time', None) is not None:\n store_dict['switch_on_time'] = int(data['switch_on_time']) % 24 * 3600\n\n if data.get('switch_off_time', None) is not None:\n store_dict['switch_off_time'] = int(data['switch_off_time']) % 24 * 3600\n\n return store_dict\n\n\ndef add_light_control(router, enable_func, disable_func, safety_function=None):\n \"\"\"\n Adds an element controling light to the plants. Further it sets up a task regulating the light which can be\n configured via rest allowing other tasks from outside to optimise the task at hand.\n\n :type router: user.routing.Router\n :param enable_func: async function to enable light\n :param disable_func: async function to disable light\n :param safety_function:\n \"\"\"\n grown_log.info('Adding light control to grown server')\n try:\n assert callable(enable_func) is True, \"enable_func is not callable\"\n assert callable(disable_func) is True, \"enable_func is not callable\"\n storage.register_leaf(\n 'light_control',\n {\n 'switch_on_time': 11 * 3600,\n 'switch_off_time': 23 * 3600\n },\n _update_reducer\n )\n # create lighting task based on set settings\n loop = asyncio.get_event_loop()\n loop.create_task(_light_control_task(enable_func, disable_func, safety_function))\n # create subserver for light control\n router.add(\"/rest/light_control\", _get_light_control_data, 'GET')\n router.add(\"/rest/light_control\", _post_light_control_data, 'POST')\n except Exception as e:\n grown_log.error(\"light_control: %s\" % str(e))\n","sub_path":"grown/light_control.py","file_name":"light_control.py","file_ext":"py","file_size_in_byte":5619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297679236","text":"# ----------------------------------------------------------------------------\n# Copyright (C) 2017 Verizon. 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# ----------------------------------------------------------------------------\n\n'''Test cases for the excelerator.py module.\n\nThese are pretty minimal, as long as the Excel file is created\nwithout error they'll pass.\n'''\n\nimport unittest\n\nimport json\nimport os\nimport tempfile\n\nfrom boogio.utensils import excelerator\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nclass TestExcelerator(unittest.TestCase):\n '''\n Basic test cases for Excelerator.\n '''\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n @classmethod\n def setUpClass(cls):\n '''\n Get a temp directory for output.\n '''\n cls.tmpdir = tempfile.mkdtemp()\n # cls.filename = os.path.join('/tmp', 'file1.xls')\n cls.filename = os.path.join(cls.tmpdir, 'file1.xls')\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n @classmethod\n def tearDownClass(cls):\n '''\n Remove test files and temp directory.\n '''\n for root, dirs, files in os.walk(cls.tmpdir, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n\n os.rmdir(cls.tmpdir)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def setUp(self):\n pass\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def test_excelerator_data(self):\n '''\n Basic test cases for excelerator with directly passed data.\n '''\n\n # filename = os.path.join(self.tmpdir, 'file1.xls')\n filename = self.filename\n\n excelerator.excelerate(\n filename,\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]\n }\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'columns': ['A', 'B', 'C']\n }\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'columns': ['A', 'B', 'C'],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta'\n }\n }\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n }\n }\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n },\n 'placeholder': 'XXX'\n },\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'columns': ['A', 'B', 'C'],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n }\n },\n placeholder=\"\"\n )\n self.assertTrue(os.path.exists(filename))\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def test_excelerator_json(self):\n '''\n Basic test cases for excelerator with data in a json string.\n '''\n filename = self.filename\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'json': json.dumps([\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]),\n 'placeholder': 'XXX'\n },\n {\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'columns': ['A', 'B', 'C'],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n }\n },\n placeholder=\"\"\n )\n self.assertTrue(os.path.exists(filename))\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def test_excelerator_jsonfile(self):\n '''\n Basic test cases for excelerator with data in a json file.\n '''\n filename = self.filename\n\n jsonfile = os.path.join(self.tmpdir, 'data.json')\n data = [{'A': 11, 'B': 12}, {'A': 21, 'C': 23}]\n\n with open(jsonfile, 'w') as fp:\n json.dump(data, fp)\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'jsonfile': jsonfile,\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n },\n 'placeholder': 'XXX'\n },\n {\n 'json': json.dumps([\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]),\n 'columns': ['A', 'B', 'C'],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n }\n },\n placeholder=\"\"\n )\n self.assertTrue(os.path.exists(filename))\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def test_excelerator_sheetspec(self):\n '''\n Basic test cases for excelerator with sheetspecs.\n '''\n filename = self.filename + \"_sheetspec\"\n\n sheetspec_file1 = os.path.join(self.tmpdir, 'sheetspec1.json')\n sheetspec_data1 = {'George': {'columns': ['B', 'C']}}\n\n with open(sheetspec_file1, 'w') as fp:\n json.dump(sheetspec_data1, fp)\n\n sheetspec_file2 = os.path.join(self.tmpdir, 'sheetspec2.json')\n sheetspec_data2 = {\n 'Mary': {\n 'columns': ['A', 'C'],\n 'headers': {'A': 'Ehh', 'B': 'Bee', 'C': 'See'}\n }\n }\n\n with open(sheetspec_file2, 'w') as fp:\n json.dump(sheetspec_data2, fp)\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'placeholder': 'XXX'\n },\n {\n 'json': json.dumps([\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]),\n 'columns': ['A', 'B', 'C'],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n }\n },\n sheetspecs=[sheetspec_data1]\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n },\n 'placeholder': 'XXX'\n },\n {\n 'sheetname': \"Mary\",\n 'json': json.dumps([\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]),\n },\n sheetspecs=[sheetspec_file1, sheetspec_data2]\n # sheetspecs=[sheetspec_file1]\n )\n self.assertTrue(os.path.exists(filename))\n\n excelerator.excelerate(\n filename,\n {\n 'sheetname': \"George\",\n 'data': [\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ],\n 'headers': {\n 'A': 'alpha',\n 'B': 'beta',\n 'C': 'gamma'\n },\n 'placeholder': 'XXX'\n },\n {\n 'sheetname': \"Mary\",\n 'json': json.dumps([\n {'A': 11, 'B': 12},\n {'A': 21, 'C': 23}\n ]),\n 'columns': ['A', 'B', 'C'],\n },\n sheetspecs=[sheetspec_file1, sheetspec_data2]\n # sheetspecs=[sheetspec_file1]\n )\n self.assertTrue(os.path.exists(filename))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"boogio/utensils/test/test_excelerator.py","file_name":"test_excelerator.py","file_ext":"py","file_size_in_byte":10212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469195241","text":"#! /usr/bin/python\n\nimport os,sys\n\nOutputFlag = \"_8TeV_Incl_V1/\"\nCME = \"8000\"\n\nFullList = []\nFullList.append([\"MC15.100014.Herwig7_Matchbox_Internal_ttbar_H7_UE_NNPDF30.py\", \"20\"])\n\nExtraJO = \"MC15.100014.Herwig7_Matchbox_Internal_ttbar_H7_UE_NNPDF30.py\"\n\nfor entry in FullList:\n ecmEnergy = CME\n jO = entry[0]\n numJobs = entry[1]\n \n DSID = jO.replace(\"MC15.\", \"\")\n DSID = DSID[0:6]\n\n outputFolder = jO.replace(\"MC15.\", \"user.lscyboz.\")\n outputFolder = outputFolder.replace(\".py\", \"_\"+OutputFlag)\n \n\n cmd = \"pathena --site=INFN-LECCE --trf=\\\"Generate_tf.py --ecmEnergy=\"+ecmEnergy+\" --runNumber=\"+DSID+\" --firstEvent=1 --maxEvents=5000 --randomSeed=%RNDM:100 --jobConfig=\"+jO+\" --outputEVNTFile=test.pool.root \\\" --long --split \"+numJobs+\" --outDS \"+outputFolder+\" --extOutFile test.pool.root --extFile=\"+ExtraJO+\",\"+jO\n\n #print cmd\n\n os.system(cmd)\n\n","sub_path":"ProducePoolOnGrid/WorkingKernel/RunSubmission.py","file_name":"RunSubmission.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"487088922","text":"from collections import deque\n\n\ndef path_exists_bfs(graph, node1, node2):\n visited = []\n q = deque([node1])\n while q:\n node = q.popleft()\n if node not in visited:\n if node == node2:\n return True\n for n in graph[node]:\n q.append(n)\n visited.append(node)\n return False\n\n\ndef path_exists_dfs(graph, node1, node2):\n visited = []\n s = [node1]\n while s:\n node = s.pop()\n if node not in visited:\n if node == node2:\n return True\n for n in graph[node]:\n s.append(n)\n visited.append(node)\n return False\n","sub_path":"python/algo/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300900806","text":"import numpy as np\nimport math\nimport json\nfrom scipy.special import logsumexp\n\nNULL = \"NULL\"\nDEBUG = False\n\n# TODO: Fix the normalization issue as in hmm_word_discoverer.py\n# Audio-level word discovery model\n# * The transition matrix is assumed to be Toeplitz \nclass AudioHMMWordDiscoverer:\n def __init__(self, trainingCorpusFile, initProbFile=None, transProbFile=None, obsProbFile=None,\n modelName=\"audio_hmm_word_discoverer\"):\n #def __init__(self, numMixtures, frameDim, sourceCorpusFile, targetCorpusFile, initProbFile=None, transProbFile=None, obsModelFile=None, modelName='audio_hmm_word_discoverer', maxLen=2000):\n self.modelName = modelName \n # Initialize data structures for storing training data\n self.fCorpus = [] # fCorpus is a list of foreign (e.g. Spanish) sentences\n\n self.tCorpus = [] # tCorpus is a list of target (e.g. English) sentences\n \n self.init = {}\n self.obs = {} # obs[e_i][f_j] is initialized with a count of how often target word e_i and foreign word f_j appeared together.\n self.trans = {} # trans[l][i][j] is the probabilities that target word e_j is aligned after e_i is aligned in a target sentence e of length l \n self.lenProb = {}\n self.avgLogTransProb = float('-inf')\n \n # Read the corpus\n self.initialize(trainingCorpusFile)\n #self.initialize(sourceCorpusFile, targetCorpusFile, maxLen);\n self.initProbFile = initProbFile\n self.transProbFile = transProbFile\n self.obsProbFile = obsProbFile\n #self.obsModelFile = obsModelFile\n \n self.fCorpus = self.fCorpus\n self.tCorpus = self.tCorpus \n #self.obs_model = GMMWordDiscoverer(numMixtures, sourceCorpusFile, targetCorpusFile, maxLen=maxLen)\n print(\"Finish initialization of obs model\")\n\n def initialize(self, fileName):\n f = open(fileName)\n\n i = 0\n j = 0;\n tTokenized = ();\n fTokenized = ();\n for s in f:\n if i == 0:\n tTokenized = s.split() #word_tokenize(s)\n # Add null word in position zero\n tTokenized.insert(0, NULL)\n self.tCorpus.append(tTokenized)\n elif i == 1:\n fTokenized = s.split()\n self.fCorpus.append(fTokenized)\n else:\n i = -1\n j += 1\n i +=1\n f.close()\n \n # Initialize the transition probs uniformly \n self.computeTranslationLengthProbabilities()\n \n for m in self.lenProb:\n self.init[m] = np.log(1./m) * np.ones((m,))\n\n for m in self.lenProb:\n self.trans[m] = np.log(1./m) * np.ones((m, m))\n \n '''\n def initialize(self, fFileName, tFileName, maxLen):\n fp = open(tFileName)\n tCorpus = fp.read().split('\\n')\n\n # XXX XXX \n self.tCorpus = [[NULL] + tw.split() for tw in tCorpus[:2]]\n fp.close()\n \n fCorpus = np.load(fFileName) \n # XXX XXX\n self.fCorpus = [fCorpus[k] for k in sorted(fCorpus.keys(), key=lambda x:int(x.split('_')[-1]))[:2]]\n self.fCorpus = [fSen[:maxLen] for fSen in self.fCorpus] \n \n self.data_ids = [feat_id.split('_')[-1] for feat_id in sorted(fCorpus.keys(), key=lambda x:int(x.split('_')[-1]))]\n self.featDim = self.fCorpus[0].shape[1]\n \n # Initialize the transition probs uniformly \n self.computeTranslationLengthProbabilities()\n \n for m in self.lenProb:\n self.init[m] = np.log(1. / m) * np.ones((m,))\n\n for m in self.lenProb:\n self.trans[m] = np.log(1. / m) * np.ones((m, m))\n '''\n\n # Set initial values for the translation probabilities p(f|e)\n def initializeModel(self):\n self.obs = {}\n if self.initProbFile:\n f = open(self.initProbFile)\n for line in f:\n m, s, prob = line.split()\n self.init[int(m)][int(s)] = float(prob)\n\n if self.transProbFile:\n f = open(self.transProbFile)\n for line in f:\n m, cur_s, next_s, prob = line.split()\n self.trans[int(m)][int(cur_s)][int(next_s)] = float(prob) \n \n if self.obsProbFile:\n f = open(self.obsProbFile)\n for line in f:\n tw, fw, prob = line.strip().split()\n if tw not in self.obs.keys():\n self.obs[tw] = {}\n self.obs[tw][fw] = float(prob)\n \n f.close()\n else:\n for ts, fs in zip(self.tCorpus, self.fCorpus):\n for tw in ts:\n for fw in fs:\n if tw not in self.obs.keys():\n self.obs[tw] = {} \n if fw not in self.obs[tw].keys():\n self.obs[tw][fw] = 1.\n \n for tw in self.obs:\n totCount = sum(self.obs[tw].values())\n for fw in self.obs[tw].keys():\n #if DEBUG:\n # if self.obs[tw][fw] > 1:\n # print(self.obs[tw][fw])\n self.obs[tw][fw] = np.log(self.obs[tw][fw] / totCount) \n \n '''if self.obsModelFile:\n self.initializeWordTranslationDensities(\n self.obsModelFile+'_mixture_priors.json',\n self.obsModelFile+'_translation_means.json',\n self.obsModelFile+'_translation_variances.json' \n )\n '''\n \n def forward(self, eSen, fSen):\n T = len(fSen)\n nState = len(eSen)\n forwardProbs = -np.inf * np.ones((T, nState))\n for i in range(nState):\n #if fSen[0] in self.obs[eSen[i]]:\n #if DEBUG:\n # print('init keys: ', self.init.keys())\n # forwardProbs[0][i] = self.init[nState][i] * self.obs[eSen[i]][fSen[0]]\n #forwardProbs[0][i] = self.init[nState][i] + self.obs_model.logTransProb(fSen[0], eSen[i])\n forwardProbs[0][i] = self.init[nState][i] + self.obs[eSen[i]][fSen[0]]\n\n for t in range(T-1):\n obs_arr = np.array([self.obs[eSen[j]][fSen[t+1]] if fSen[t+1] in self.obs[eSen[j]] else 0 for j in range(nState)]) \n #forwardProbs[t+1] = self.trans[nState].T @ forwardProbs[t] * obs_arr\n #obs_arr = np.array([self.obs_model.logTransProb(fSen[t+1], tw) for tw in eSen])\n for j in range(nState):\n forwardProbs[t+1][j] = logsumexp(self.trans[nState][:, j] + forwardProbs[t]) + obs_arr[j] \n \n assert not np.isnan(forwardProbs).any()\n return forwardProbs\n\n def backward(self, eSen, fSen):\n T = len(fSen)\n nState = len(eSen)\n backwardProbs = -np.inf * np.ones((T, nState))\n for i in range(nState):\n backwardProbs[T-1][i] = 0.\n\n for t in range(T-1, 0, -1):\n obs_arr = np.array([self.obs[eSen[j]][fSen[t]] if fSen[t] in self.obs[eSen[j]] else 0 for j in range(nState)])\n #backwardProbs[t-1] = self.trans[nState] @ (backwardProbs[t] * obs_arr)\n #obs_arr = np.array([self.obs_model.logTransProb(fSen[t], tw) for tw in eSen])\n for j in range(nState):\n backwardProbs[t-1][j] = logsumexp(self.trans[nState][j] + backwardProbs[t] + obs_arr)\n \n assert not np.isnan(backwardProbs).any()\n return backwardProbs \n\n def updateInitialCounts(self, forwardProbs, backwardProbs, eSen, fSen):\n #assert np.sum(forwardProbs, axis=1).all() and np.sum(backwardProbs, axis=1).all() \n nState = len(eSen)\n T = len(fSen)\n # Update the initial prob \n initExpCounts = -np.inf * np.ones((nState,)) \n for i in range(nState):\n initExpCounts[i] = logsumexp(forwardProbs[:, i] + backwardProbs[:, i])\n \n assert not np.isnan(initExpCounts).any()\n return initExpCounts\n\n def updateTransitionCounts(self, forwardProbs, backwardProbs, eSen, fSen):\n nState = len(eSen)\n T = len(fSen)\n transExpCounts = -np.inf * np.ones((nState, nState))\n # Update the transition probs\n for t in range(T-1):\n obs_arr = np.array([self.obs[eSen[j]][fSen[t+1]] if fSen[t+1] in self.obs[eSen[j]] else 0 for j in range(nState)])\n #transExpCounts += np.tile(forwardProbs[t], (nState, 1)).T * (obs_arr * backwardProbs[t+1]) * self.trans \n #transExpCount = np.tile(forwardProbs[t], (nState, 1)).T * (obs_arr * backwardProbs[t+1]) * self.trans[nState]\n #obs_arr = np.array([self.obs_model.logTransProb(fSen[t+1], tw) for tw in eSen])\n transExpCount = np.tile(forwardProbs[t], (nState, 1)).T + self.trans[nState] + obs_arr + backwardProbs[t+1]\n # Maintain Toeplitz assumption\n # TODO: Make this more efficient\n transJumpCount = {}\n transJumpCounts = {}\n for s in range(nState):\n for next_s in range(nState):\n if next_s - s not in transJumpCount:\n #if DEBUG:\n # print('new jump: ', next_s - s) \n transJumpCount[next_s - s] = [transExpCount[s, next_s]]\n else:\n transJumpCount[next_s - s].append(transExpCount[s, next_s])\n\n for s in range(nState):\n for next_s in range(nState):\n transJumpCounts[next_s - s] = logsumexp(np.asarray(transJumpCount[next_s - s]))\n\n for s in range(nState):\n for next_s in range(nState):\n transExpCounts[s][next_s] = transJumpCounts[next_s - s]\n\n #if DEBUG:\n # print('product: ', np.tile(forwardProbs[t], (nState, 1)).T * (obs_arr * backwardProbs[t+1]) * self.trans[nState])\n #if DEBUG:\n # print('transExpCounts: ', transExpCounts)\n \n assert not np.isnan(transExpCounts).any()\n return transExpCounts\n \n def updateObservationCounts(self, forwardProbs, backwardProbs, eSen, fSen):\n #assert np.sum(forwardProbs, axis=1).all() and np.sum(backwardProbs, axis=1).all()\n # Update observation probs\n nState = len(eSen)\n newObsCounts = {tw: {} for tw in self.obs}\n statePosteriors = forwardProbs + backwardProbs\n normFactor = logsumexp(statePosteriors.flatten(order='C'))\n statePosteriors = (statePosteriors.T - normFactor).T\n \n for t, w in enumerate(fSen): \n for i in range(nState):\n if w not in newObsCounts[eSen[i]]:\n newObsCounts[eSen[i]][w] = []\n newObsCounts[eSen[i]][w].append(statePosteriors[t][i]) #self.obs[eSen[i]][w]\n \n return newObsCounts\n\n '''\n def updateObservationCounts(self, forwardProbs, backwardProbs, countByObsModel, eSen, fSen): \n nState = len(eSen)\n statePosteriors = forwardProbs + backwardProbs\n normFactor = logsumexp(statePosteriors.flatten(order='C'))\n statePosteriors = (statePosteriors.T - normFactor).T\n newObsCounts = {k: -np.inf * np.ones(count.shape) for k, count in countByObsModel.items()} \n\n for t, fw in enumerate(fSen):\n for i, tw in enumerate(sorted(eSen)):\n tKey = \"_\".join([str(i), tw])\n newObsCounts[tKey] = statePosteriors[:, i] + countByObsModel[tKey]\n assert not np.isnan(newObsCounts[tKey]).any()\n\n return newObsCounts\n '''\n\n # Compute translation length probabilities q(m|n)\n def computeTranslationLengthProbabilities(self, smoothing=None):\n # Implement this method\n #pass \n #if DEBUG:\n # print(len(self.tCorpus))\n for ts, fs in zip(self.tCorpus, self.fCorpus):\n # len of ts contains the NULL symbol\n #if len(ts)-1 not in self.lenProb.keys():\n self.lenProb[len(ts)] = {}\n if len(fs) not in self.lenProb[len(ts)].keys():\n self.lenProb[len(ts)][len(fs)] = 1\n else:\n self.lenProb[len(ts)][len(fs)] += 1\n \n if smoothing == 'laplace':\n tLenMax = max(list(self.lenProb.keys()))\n fLenMax = max([max(list(f.keys())) for f in list(self.lenProb.values())])\n for tLen in range(tLenMax):\n for fLen in range(fLenMax):\n if tLen not in self.lenProb:\n self.lenProb[tLen] = {}\n self.lenProb[tLen][fLen] = 1.\n elif fLen not in self.lenProb[tLen]:\n self.lenProb[tLen][fLen] = 1. \n else:\n self.lenProb[tLen][fLen] += 1. \n \n # TODO: Kneser-Ney smoothing\n for tl in self.lenProb.keys():\n totCount = sum(self.lenProb[tl].values()) \n for fl in self.lenProb[tl].keys():\n self.lenProb[tl][fl] = self.lenProb[tl][fl] / totCount \n\n def computeAvgLogLikelihood(self):\n ll = 0.\n for tSen, fSen in zip(self.tCorpus, self.fCorpus):\n forwardProb = self.forward(tSen, fSen)\n #backwardProb = self.backward(tSen, fSen)\n likelihood = logsumexp(forwardProb[-1])\n ll += likelihood\n return ll / len(self.tCorpus)\n\n def trainUsingEM(self, numIterations=30, writeModel=False):\n if writeModel:\n self.printModel('initial_model.txt')\n \n self.initializeModel() \n #self.obs_model.computeExpectedCounts()\n initCounts = {m: [] for m in self.lenProb}\n transCounts = {m: [] for m in self.lenProb}\n #obsCounts = []\n obsCounts = {tw: {fw: [] for fw in self.obs[tw]} for tw in self.obs} \n \n for epoch in range(numIterations): \n #AvgLogProb = self.computeAvgLogLikelihood()\n for i_ex, (eSen, fSen) in enumerate(zip(self.tCorpus, self.fCorpus)):\n forwardProbs = self.forward(eSen, fSen)\n backwardProbs = self.backward(eSen, fSen) \n initCounts[len(eSen)].append(self.updateInitialCounts(forwardProbs, backwardProbs, eSen, fSen))\n transCounts[len(eSen)].append(self.updateTransitionCounts(forwardProbs, backwardProbs, eSen, fSen))\n #obsCounts.append(self.updateObservationCounts(forwardProbs, backwardProbs, self.obs_model.alignProb[i_ex], eSen, fSen))\n obsCount = self.updateObservationCounts(forwardProbs, backwardProbs, eSen, fSen)\n for tw in obsCount:\n for fw in obsCount[tw]:\n if DEBUG:\n print(obsCount[tw][fw])\n obsCounts[tw][fw].append(logsumexp(np.asarray(obsCount[tw][fw])))\n\n if DEBUG:\n if i_ex == 0:\n #print(\"forwardProbs, backwardProbs: \", forwardProbs, backwardProbs)\n #print(\"transCount: \", self.updateTransitionCounts(forwardProbs, backwardProbs, eSen, fSen))\n print(\"initCount: \", self.updateInitialCounts(forwardProbs, backwardProbs, eSen, fSen))\n #print(\"obsCount: \", self.updateObservationCounts(forwardProbs, backwardProbs, self.obs_model.alignProb[i_ex], eSen, fSen))\n\n # Update the parameters of the observation model\n #self.obs_model.alignProb = obsCounts\n #self.obs_model.updateTranslationDensities()\n\n # Normalize\n for m in self.lenProb:\n for s in range(m):\n #print(np.ascontiguousarray(initCounts[m])[:, s].flags['C_CONTIGUOUS'])\n counts_s = np.asarray([count[s] for count in initCounts[m]])\n self.init[m][s] = logsumexp(counts_s) \n normFactor = logsumexp(np.asarray(initCounts[m]).flatten(order='C'))\n self.init[m] -= normFactor\n if DEBUG:\n print(\"np.sum(self.init): \", np.sum(np.exp(self.init[m])))\n\n for r in range(m):\n for s in range(m):\n counts_r_s = np.asarray([np.array(count[r][s]) for count in transCounts[m]]) \n self.trans[m][r, s] = logsumexp(counts_r_s)\n normFactor = logsumexp(np.asarray([count[r] for count in transCounts[m]]).flatten(order='C'))\n self.trans[m][r] -= normFactor \n if DEBUG:\n print(\"np.sum(self.trans[row]): \", np.sum(np.exp(self.trans[m][r])))\n\n for tw in self.obs:\n obs_count_tw = []\n for fw in obsCounts[tw]:\n if DEBUG:\n print(\"tw, fw, obsCounts[tw][fw]: \", tw, fw, obsCounts[tw][fw])\n obs_count_tw.extend(obsCounts[tw][fw])\n \n if DEBUG:\n print(\"np.exp(normFactor): \", np.exp(np.asarray(obs_count_tw).flatten(order='C'))) \n normFactor = logsumexp(np.asarray(obs_count_tw).flatten(order='C'))\n if normFactor == 0:\n if DEBUG:\n print('norm factor for the obs is 0: potential bug')\n self.obs[tw][fw] = self.obs[tw][fw]\n\n for fw in obsCounts[tw]:\n self.obs[tw][fw] = logsumexp(np.asarray(obsCounts[tw][fw])) - normFactor\n\n print('Epoch', epoch, 'Average Log Likelihood:', self.computeAvgLogLikelihood()) \n if writeModel:\n self.printModel(self.modelName+'model_iter='+str(epoch))\n\n # TODO\n def align(self, fSen, eSen, unkProb=10e-12):\n nState = len(eSen)\n T = len(fSen)\n scores = np.zeros((nState,))\n backPointers = np.zeros((T, nState), dtype=int)\n for i in range(nState):\n scores[i] = self.init[nState][i] + self.obs[eSen[i]][fSen[0]] \n #scores[i] = self.init[nState][i] + self.obs_model.logTransProb(fSen[0], eSen[i]) \n\n alignProbs = [] \n for t, fw in enumerate(fSen[1:]):\n obs_arr = np.array([self.obs[eSen[i]][fw] if fw in self.obs[eSen[i]] else unkProb for i in range(nState)])\n #obs_arr = np.array([self.obs_model.logTransProb(fw, tw) for tw in eSen]) \n #candidates = np.tile(scores, (nState, 1)).T * self.trans[nState] * obs_arr\n \n candidates = np.tile(scores, (nState, 1)).T + self.trans[nState] + obs_arr\n backPointers[t+1] = np.argmax(candidates, axis=0)\n scores = np.max(candidates, axis=0)\n alignProbs.append(scores.tolist())\n \n #if DEBUG:\n # print(scores)\n \n curState = np.argmax(scores)\n bestPath = [int(curState)]\n for t in range(T-1, 0, -1):\n #if DEBUG:\n # print('curState: ', curState)\n curState = backPointers[t, curState]\n bestPath.append(int(curState))\n \n return bestPath[::-1], alignProbs\n \n def printModel(self, fileName):\n initFile = open(fileName+'_initialprobs.txt', 'w')\n \n for nState in sorted(self.lenProb):\n for i in range(nState):\n initFile.write('%d\\t%d\\t%f\\n' % (nState, i, self.init[nState][i]))\n \n initFile.close()\n\n transFile = open(fileName+'_transitionprobs.txt', 'w')\n for nState in sorted(self.lenProb):\n for i in range(nState):\n for j in range(nState):\n transFile.write('%d\\t%d\\t%d\\t%f\\n' % (nState, i, j, self.trans[nState][i][j]))\n transFile.close()\n\n #self.obs_model.printModel(fileName+'_obs_model')\n obsFile = open(fileName+'_observationprobs.txt', 'w')\n \n for tw in sorted(self.obs):\n for fw in sorted(self.obs[tw]):\n obsFile.write('%s\\t%s\\t%f\\n' % (tw, fw, self.obs[tw][fw]))\n obsFile.close()\n \n # Write the predicted alignment to file\n def printAlignment(self, filePrefix, isPhoneme=True):\n f = open(filePrefix+'.txt', 'w')\n aligns = []\n if DEBUG:\n print(len(self.fCorpus))\n for i, (fSen, tSen) in enumerate(zip(self.fCorpus, self.tCorpus)):\n alignment, alignProbs = self.align(fSen, tSen)\n #if DEBUG:\n # print(fSen, tSen)\n # print(type(alignment[1]))\n #align_info = {\n # 'index': self.data_ids[i],\n align_info = {\n 'index': i,\n 'image_concepts': tSen,\n 'alignment': alignment,\n 'align_probs': alignProbs,\n 'is_phoneme': False,\n 'is_audio': True\n }\n aligns.append(align_info)\n f.write('%s\\n%s\\n' % (tSen, fSen))\n for a in alignment:\n f.write('%d ' % a)\n f.write('\\n\\n')\n\n f.close()\n \n # Write to a .json file for evaluation\n with open(filePrefix+'.json', 'w') as f:\n json.dump(aligns, f, indent=4, sort_keys=True) \n\nif __name__ == '__main__':\n trainingCorpusFile = 'test_translation.txt' \n #'../data/flickr30k/phoneme_level/flickr30k.txt'\n #initProbFile = 'models/apr18_tiny_hmm_translate/A_iter=9.txt_initialprobs.txt'\n #'hmm_word_discoverer_iter=9.txt_initialprobs.txt'\n #transProbFile = 'models/apr18_tiny_hmm_translate/A_iter=9.txt_transitionprobs.txt'\n #'hmm_word_discoverer_iter=9.txt_transitionprobs.txt'\n #obsProbFile = 'models/apr18_tiny_hmm_translate/A_iter=9.txt_observationprobs.txt'\n #'hmm_word_discoverer_iter=9.txt_observationprobs.txt'\n sourceCorpusFile = \"../data/flickr30k/audio_level/flickr_mfcc_cmvn_htk.npz\"\n targetCorpusFile = \"../data/flickr30k/audio_level/flickr_bnf_all_trg.txt\"\n model = AudioHMMWordDiscoverer(1, 12, sourceCorpusFile, targetCorpusFile, modelName='test_audio_hmm', maxLen=20)\n #model = AudioHMMWordDiscoverer(trainingCorpusFile, modelName='test_audio_hmm')\n model.trainUsingEM(10, writeModel=True)\n model.printAlignment('alignment')\n\n #model = HMMWordDiscoverer(trainingCorpusFile, modelName='A')\n #model.trainUsingEM(10) \n","sub_path":"hmm/audio_hmm_word_discoverer.py","file_name":"audio_hmm_word_discoverer.py","file_ext":"py","file_size_in_byte":19977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"358241109","text":"# myAgentP2.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n# This file was based on the starter code for student bots, and refined \n# by Mesut (Xiaocheng) Yang\n\n\nfrom captureAgents import CaptureAgent\nimport random, time, util\nfrom game import Directions\nimport game\nfrom util import nearestPoint\n\n#########\n# Agent #\n#########\n\n\nclass myAgentP2(CaptureAgent):\n \"\"\"\n Students' Names: Sourav Padhiari & Kavaj Burdak \n Phase Number: 2\n Description of Bot: We change the weights from Phase1 and use all necessary functions from it \n We initialize necessary relationships between 2 agents \n We choose action at random comparing from the lowest value\n \"\"\"\n\n def registerInitialState(self, gameState):\n \"\"\"\n This method handles the initial setup of the\n agent to populate useful fields (such as what team\n we're on).\n\n A distanceCalculator instance caches the maze distances\n between each pair of positions, so your agents can use:\n self.distancer.getDistance(p1, p2)\n\n IMPORTANT: This method may run for at most 15 seconds.\n \"\"\"\n\n # Make sure you do not delete the following line. \n # If you would like to use Manhattan distances instead \n # of maze distances in order to save on initialization \n # time, please take a look at:\n # CaptureAgent.registerInitialState in captureAgents.py.\n CaptureAgent.registerInitialState(self, gameState)\n self.start = gameState.getAgentPosition(self.index)\n\n otherAgentActions = self.receivedInitialBroadcast\n teammateIndices = [index for index in self.getTeam(gameState) if index != self.index]\n assert len(teammateIndices) == 1\n teammateIndex = teammateIndices[0]\n otherAgentPositions = getFuturePositions(gameState, otherAgentActions, teammateIndex)\n \n # You can process the broadcast here!\n self.size = 0\n self.fsize = 0\n self.f = []\n self.eat = []\n for i in otherAgentPositions:\n for i in gameState.getFood().asList():\n self.f.append(i)\n self.fsize += 1\n for i in gameState.getFood().asList():\n if i not in self.f:\n self.eat.append(i)\n self.size += 1\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among actions randomly.\n \"\"\"\n actions = gameState.getLegalActions(self.index)\n value = -9999\n action = actions[0]\n for i in range(0, len([self.evaluate(gameState, a) for a in actions])):\n if [self.evaluate(gameState, a) for a in actions][i] > value:\n action = actions[i]\n value = [self.evaluate(gameState, a) for a in actions][i]\n\n\n return action\n\n def evaluate(self, gameState, action):\n \"\"\"\n Computes a linear combination of features and feature weights\n \"\"\"\n features = self.getFeatures(gameState, action)\n weights = self.getWeights(gameState, action)\n return features * weights\n \n\n\n def getFeatures(self, gameState, action):\n features = util.Counter()\n\n ### Useful information you can extract from a GameState (pacman.py) ###\n successorGameState = gameState.generateSuccessor(self.index, action)\n newPos = successorGameState.getAgentPosition(self.index)\n oldFood = gameState.getFood()\n newFood = successorGameState.getFood()\n ghostIndices = self.getOpponents(successorGameState)\n \n # Determines how many times the agent has already been in the newPosition in the last 20 moves\n numRepeats = sum([1 for x in self.observationHistory[-20:] if x.getAgentPosition(self.index) == newPos])\n\n foodPositions = oldFood.asList()\n foodDistances = [self.getMazeDistance(newPos, foodPosition) for foodPosition in foodPositions]\n closestFood = min( foodDistances ) + 1.0\n\n ghostPositions = [successorGameState.getAgentPosition(ghostIndex) for ghostIndex in ghostIndices]\n ghostDistances = [self.getMazeDistance(newPos, ghostPosition) for ghostPosition in ghostPositions]\n ghostDistances.append( 1000 )\n closestGhost = min( ghostDistances ) + 1.0\n\n teammateIndices = [index for index in self.getTeam(gameState) if index != self.index]\n assert len(teammateIndices) == 1, \"Teammate indices: {}\".format(self.getTeam(gameState))\n teammateIndex = teammateIndices[0]\n teammatePos = successorGameState.getAgentPosition(teammateIndex)\n teammateDistance = self.getMazeDistance(newPos, teammatePos) + 1.0\n\n pacmanDeath = successorGameState.data.num_deaths\n\n features['successorScore'] = self.getScore(successorGameState)\n\n # CHANGE YOUR FEATURES HERE\n \n features['teammateDistance'] = teammateDistance\n features['numRepeats'] = numRepeats\n features['closestGhost'] = closestGhost\n features['closestFood'] = closestFood\n\n return features\n\n def getWeights(self, gameState, action):\n # CHANGE YOUR WEIGHTS HERE\n return {'successorScore': 100, 'closestFood': -100, 'closestGhost': 0, 'numRepeats': -10,'teammateDistance': 15}\n\n\ndef getFuturePositions(gameState, plannedActions, agentIndex):\n \"\"\"\n Returns list of future positions given by a list of actions for a\n specific agent starting form gameState\n\n NOTE: this does not take into account other agent's movements\n (such as ghosts) that might impact the *actual* positions visited\n by such agent\n \"\"\"\n if plannedActions is None:\n return None\n\n planPositions = [gameState.getAgentPosition(agentIndex)]\n for action in plannedActions:\n if action in gameState.getLegalActions(agentIndex):\n gameState = gameState.generateSuccessor(agentIndex, action)\n planPositions.append(gameState.getAgentPosition(agentIndex))\n else:\n print(\"Action list contained illegal actions\")\n break\n return planPositions","sub_path":"PacPack v2/myAgentP2.py","file_name":"myAgentP2.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"561557799","text":"import os\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport skimage.io\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass SpacenetLocDataset(Dataset):\n def __init__(self, data_path, mode, fold=0, folds_csv='folds.csv', transforms=None, normalize=None, multiplier=1,\n fix_orientation=True, filter_on_border=True):\n super().__init__()\n self.data_path = data_path\n self.mode = mode\n self.fix_orientation = fix_orientation\n\n df = pd.read_csv(folds_csv)\n self.df = df\n self.normalize = normalize\n self.fold = fold\n if self.mode == \"train\":\n ids = df[df['fold'] != fold]['id'].tolist()\n else:\n if filter_on_border:\n ids = list(set(df[(df['fold'] == fold) & (df[\"onborder\"] == False)]['id'].tolist()))\n else:\n ids = list(set(df[(df['fold'] == fold)]['id'].tolist()))\n self.transforms = transforms\n self.names = ids\n if mode == \"train\":\n self.names = self.names * multiplier\n orientations = pd.read_csv(os.path.join(data_path, \"SummaryData/SAR_orientations.txt\"), header=None).values\n orientations_dict = {}\n for row in orientations:\n id, o = row[0].split(\" \")\n orientations_dict[id] = float(o)\n self.orientations_dict = orientations_dict\n\n def __len__(self):\n return len(self.names)\n\n def __getitem__(self, idx):\n\n name = self.names[idx]\n img_path = os.path.join(self.data_path, \"SAR-Intensity\",\n \"SN6_Train_AOI_11_Rotterdam_SAR-Intensity_\" + name + \".tif\")\n image = skimage.io.imread(img_path)\n image = (image * (255 / 92)).astype(np.uint8)\n mask_path = os.path.join(\"/wdata/masks\", name + \".png\")\n mask = cv2.imread(mask_path)\n # water_mask = cv2.imread(os.path.join(self.data_path, \"water_masks\", name + \".png\"), cv2.IMREAD_GRAYSCALE)\n # water_mask = np.expand_dims(water_mask, -1)\n # mask = np.concatenate([mask, water_mask], -1)\n orientation = self.orientations_dict[\"_\".join(name.split(\"_\")[:2])]\n\n if orientation > 0 and self.fix_orientation:\n image = cv2.rotate(image, cv2.ROTATE_180)\n mask = cv2.rotate(mask, cv2.ROTATE_180)\n sample = self.transforms(image=image, mask=mask)\n sample['img_name'] = name\n sample['orientation'] = orientation\n sample['mask'] = torch.from_numpy(np.ascontiguousarray(np.moveaxis(sample[\"mask\"], -1, 0))).float() / 255.\n sample['image'] = torch.from_numpy(np.moveaxis(sample[\"image\"] / 255., -1, 0).astype(np.float32))\n return sample\n\n\nclass TestSpacenetLocDataset(Dataset):\n def __init__(self, data_path, transforms, orientation_csv):\n super().__init__()\n self.data_path = data_path\n self.names = [f[:-4] for f in os.listdir(os.path.join(data_path, \"SAR-Intensity\")) if f.endswith(\"tif\")]\n self.transforms = transforms\n orientations = pd.read_csv(orientation_csv, header=None).values\n orientations_dict = {}\n for row in orientations:\n id, o = row[0].split(\" \")\n orientations_dict[id] = float(o)\n self.orientations_dict = orientations_dict\n\n\n def __len__(self):\n return len(self.names)\n\n def __getitem__(self, idx):\n name = self.names[idx]\n img_path = os.path.join(self.data_path, \"SAR-Intensity\", name + \".tif\")\n image = skimage.io.imread(img_path)\n image = (image * (255 / 92)).astype(np.uint8)\n orientation = self.orientations_dict[\"_\".join(name.split(\"_\")[-4:-2])]\n if orientation > 0:\n image = cv2.rotate(image, cv2.ROTATE_180)\n sample = self.transforms(image=image)\n sample['img_name'] = name\n sample['orientation'] = orientation\n sample['image'] = torch.from_numpy(np.moveaxis(sample[\"image\"] / 255., -1, 0).astype(np.float32))\n return sample\n","sub_path":"5-selim_sef/spacenet_dataset.py","file_name":"spacenet_dataset.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"363826891","text":"#!/usr/bin/env python\r\n\"\"\" Experimenting around blockchain implementation [code base] \"\"\"\r\n\r\nimport datetime\r\nimport hashlib\r\nimport json\r\nfrom flask import Flask, jsonify\r\n\r\n\r\n__author__ = \"SentinelWarren\"\r\n__credits__ = \"{contributor names go here!}\"\r\n\r\n__license__ = \"MIT\"\r\n__version__ = \"0.1\"\r\n__maintainer__ = \"SentinelWarren\"\r\n__email__ = \"warrenkalolo@gmail.com\"\r\n__status__ = \"Prototype\"\r\n\r\n# Buildig a blockchain class\r\nclass Bchain:\r\n \"\"\" Defining a blockchain class (it could be anything, Blockchain, Energychain, Wifichain, Shulechain whatever suitable ) \"\"\"\r\n\r\n def __init__(self):\r\n # The chain pocket, Array is just fine since we don't wanna reverse anything.\r\n self.chain = []\r\n\r\n # Genesis block\r\n self.create_block(proof=1, previous_hash=\"0\")\r\n\r\n def create_block(self, proof, previous_hash):\r\n \"\"\"new block creation function, Note, its {Immutable}\"\"\"\r\n block = {\"index\": len(self.chain) + 1, \"timestamp\": str(datetime.datetime.now()), \"proof\": proof, \"previous_hash\": previous_hash}\r\n\r\n # Appending to the pocket :)\r\n self.chain.append(block)\r\n return block\r\n\r\n \"\"\" function to get a pervious_block in the blockchain \"\"\"\r\n def get_prev_block(self): return self.chain[-1]\r\n\r\n def proof_of_work(self, previous_proof):\r\n \"\"\" function to calculate proof of work[solution] from the defined problem \"\"\"\r\n\r\n # needed for attempts of finding a solution by incrementation till solved\r\n new_proof = 1\r\n\r\n # Once we find the solution it will be == True\r\n check_proof = False\r\n\r\n # While loop till check_proof == True\r\n while check_proof is False:\r\n # Hash operations to solve the problem using hashlib module when the miner mines.\r\n # Note, the problem used here is pretty basic, however it can be tweaked to any hardest problem preferable i.e. Energy consumption, verifying CO2 emition through the smartmeters and GU operations etc etc.\r\n hash_ops = hashlib.sha256(\r\n str(new_proof**2 - previous_proof**2).encode()).hexdigest()\r\n if hash_ops[:4] == \"0000\":\r\n check_proof = True\r\n else:\r\n new_proof += 1\r\n return new_proof\r\n\r\n def hash(self, block):\r\n \"\"\" hash function that takes a block and return the sha256 cryptographic hash[The most secure one currently]. \"\"\"\r\n\r\n encoded_block = json.dumps(block, sort_keys=True).encode()\r\n\r\n return hashlib.sha256(encoded_block).hexdigest()\r\n\r\n def is_chain_valid(self, chain):\r\n \"\"\" A function to check if everything is right and valid in the blockchain \"\"\"\r\n\r\n # First block of the chain\r\n previous_block = chain[0]\r\n # Looping variable\r\n block_index = 1\r\n\r\n # A while loop to check if the looping variable is less than the length of the chain iterate on all the chains\r\n while block_index < len(chain):\r\n # First block\r\n block = chain[block_index]\r\n\r\n # If the previous_hash of current block is different than the previous block return False since its invalid\r\n if block[\"previous_hash\"] != self.hash(previous_block):\r\n return False\r\n previous_proof = previous_block[\"proof\"]\r\n proof = block[\"proof\"]\r\n # hash operations\r\n hash_ops = hashlib.sha256(\r\n str(new_proof**2 - previous_proof**2).encode()).hexdigest()\r\n\r\n # If the hash operations first 4/four char aren't matching\r\n if hash_ops[:4] != \"0000\":\r\n return False\r\n previous_block = block\r\n block_index += 1\r\n\r\n # If everything is gucci return True\r\n return True\r\n\r\n\r\n# Web part using Flask so that we can test our blockchain graphically in i.e postman\r\napp = Flask(__name__)\r\n\r\n# Creating a Blockchain\r\nblockchain = Bchain()\r\n\r\n# Mining the new_block\r\n@app.route('/mine_block', methods=['GET'])\r\ndef mine_block():\r\n \"\"\" A mining function, pretty explanatory. \"\"\"\r\n\r\n previous_block = blockchain.get_prev_block()\r\n previous_proof = previous_block[\"proof\"]\r\n proof = blockchain.proof_of_work(previous_proof)\r\n previous_hash = blockchain.hash(previous_block)\r\n\r\n block = blockchain.create_block(proof, previous_hash)\r\n response = {\"message\": \"Congrats, you just mined the block!\",\r\n \"index\": block['index'],\r\n \"timestamp\": block[\"proof\"],\r\n \"previous_hash\": block[\"previous_hash\"]}\r\n return jsonify(response), 200\r\n\r\n\r\n# Getting the full Blockchain\r\n@app.route('/get_chain', methods=['GET'])\r\ndef get_chain():\r\n \"\"\" A function for getting the chain value \"\"\"\r\n\r\n response = {\"chain\": blockchain.chain,\r\n \"length\": len(blockchain.chain)}\r\n return jsonify(response), 200\r\n\r\n\r\n# Checking if the blockchain is valid\r\n@app.route('/is_chain_valid', methods=['GET'])\r\ndef is_bchain_valid():\r\n \"\"\" A blockchain verification function, can be seen in action in postman \"\"\"\r\n\r\n is_valid = blockchain.is_chain_valid(blockchain.chain)\r\n\r\n if is_valid:\r\n response = {\"message\": \"The Blockchain is valid!\"}\r\n else:\r\n response = {\"message\": \"Unfortunately the Blockchain is not valid!\"}\r\n\r\n return jsonify(response), 200\r\n\r\n\r\n# Serving our simple blockchain prototype\r\napp.run(host='0.0.0.0', port=5000)\r\n","sub_path":"src/skeleton[arch]/blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"568032857","text":"#\n# @lc app=leetcode.cn id=3 lang=python3\n#\n# [3] 无重复字符的最长子串\n#\n# https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/\n#\n# algorithms\n# Medium (33.24%)\n# Likes: 3589\n# Dislikes: 0\n# Total Accepted: 466.6K\n# Total Submissions: 1.4M\n# Testcase Example: '\"abcabcbb\"'\n#\n# 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。\n# \n# 示例 1:\n# \n# 输入: \"abcabcbb\"\n# 输出: 3 \n# 解释: 因为无重复字符的最长子串是 \"abc\",所以其长度为 3。\n# \n# \n# 示例 2:\n# \n# 输入: \"bbbbb\"\n# 输出: 1\n# 解释: 因为无重复字符的最长子串是 \"b\",所以其长度为 1。\n# \n# \n# 示例 3:\n# \n# 输入: \"pwwkew\"\n# 输出: 3\n# 解释: 因为无重复字符的最长子串是 \"wke\",所以其长度为 3。\n# 请注意,你的答案必须是 子串 的长度,\"pwke\" 是一个子序列,不是子串。\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans_len = 0\n ans = []\n for i in range(len(s)):\n if s[i] in ans:\n ans_len = max(ans_len,len(ans))\n ans = ans[ans.index(s[i])+1:]\n ans.append(s[i])\n ans_len = max(ans_len,len(ans))\n return ans_len\n# @lc code=end\n\n","sub_path":"3.无重复字符的最长子串.py","file_name":"3.无重复字符的最长子串.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"316538760","text":"\"\"\"\nhttps://docs.python.org/ja/3/library/functools.html#functools.total_ordering\n\"拡張比較 (rich comparison)の簡易入力\"\nx< y は x.__lt__(y) x<=y は x.__le__(y)\nx==y は x.__eq__(y) x!=y は x.__ne__(y)\nx> y は x.__gt__(y) x>=y は x.__ge__(y)\n注意:実行時間が遅い場合ここを書き換えると高速化されることが多々ある\n\"\"\"\n\nfrom functools import total_ordering\n\n\n@total_ordering\nclass Student:\n \"\"\"名前を設定\"\"\"\n\n def __init__(self, firstname, lastname):\n self.lastname = lastname\n self.firstname = firstname\n\n def _is_valid_operand(self, other):\n \"\"\" otherのインスタンス変数にlastnameとfirstnameを持っているか \"\"\"\n return (hasattr(other, \"lastname\") and\n hasattr(other, \"firstname\"))\n\n def __eq__(self, other):\n \"\"\" == x==y は x.__eq__(y) \"\"\"\n if not self._is_valid_operand(other):\n return NotImplemented\n return all([\n self.firstname.lower() == other.firstname.lower(),\n self.lastname.lower() == other.lastname.lower()]\n )\n\n def __lt__(self, other):\n \"\"\" x名前\n if self.firstname.lower() == other.firstname.lower():\n return self.lastname.lower() < other.lastname.lower()\n return self.firstname.lower() < other.firstname.lower()\n\n @property\n def show(self):\n print(self.firstname, self.lastname)\n\n\nif __name__ == '__main__':\n a1 = Student(\"adogawa\", \"zonan\")\n a2 = Student(\"adogawa\", \"agasa\")\n b = Student(\"mituhiko\", \"mituhiko\")\n c = Student(\"genta\", \"genta\")\n\n l = [a1, a2, b, c]\n l.sort() # ソートの実行\n for student in l:\n student.show\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"37621434","text":"import csv\n\nfrom authors.models import Author\n\n\ndef run(file):\n try:\n file = open(file)\n reader = csv.DictReader(file)\n\n Author.objects.all().delete()\n\n for row in reader:\n author, created = Author.objects.get_or_create(name=row['name'])\n return \"Import data with success\"\n except Exception as e:\n raise e\n","sub_path":"src/authors/scripts/import_authors.py","file_name":"import_authors.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"168161555","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import Any, DefaultDict, Dict, List\n\nROOT = Path(__file__).parent.parent.resolve()\n\n\nclass Package:\n def __init__(self, attribute: str, metadata: Dict[str, Any]) -> None:\n self.attribute = attribute\n self.metadata = metadata\n\n\ndef write_repo_page(repos_path: Path, repo_name: str, pkgs: List[Package]):\n with open(str(repos_path.joinpath(repo_name)) + \".md\", \"w+\") as f:\n f.write(\n f\"\"\"\n+++\ntitle = \"{repo_name}\"\n+++\n\n# Packages\n\nName | Attribute | Description\n-----|-----------|------------\n\"\"\"\n )\n for pkg in pkgs:\n name = pkg.metadata[\"name\"]\n meta = pkg.metadata[\"meta\"]\n description = meta.get(\"description\")\n if description is None:\n description = \"\"\n\n description = description.replace(\"\\n\", \"\")\n homepage = meta.get(\"homepage\", None)\n attribute = pkg.attribute\n\n if homepage is not None:\n name = f\"[{name}]({homepage})\"\n\n location = meta.get(\"position\", None)\n if location is not None:\n attribute = f\"[{attribute}]({location})\"\n\n f.write(f\"{name}|{attribute}|{description}\\n\")\n\n\ndef main() -> None:\n with open(ROOT.joinpath(\"data\", \"packages.json\")) as f:\n repos: DefaultDict[str, List[Package]] = DefaultDict(list)\n packages = json.load(f)\n for attribute, pkg in packages.items():\n repos[pkg[\"_repo\"]].append(Package(attribute, pkg))\n\n repos_path = ROOT.joinpath(\"content\", \"repos\")\n shutil.rmtree(repos_path, ignore_errors=True)\n os.makedirs(repos_path)\n with open(repos_path.joinpath(\"_index.md\"), \"w+\") as f:\n f.write(\"\"\"\n+++\ntitle = \"Repos\"\nweight = 1\nalwaysopen = true\n+++\n# Repo index\n\"\"\")\n\n for repo_name, pkgs in repos.items():\n write_repo_page(repos_path, repo_name, pkgs)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/generate_pages.py","file_name":"generate_pages.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"14411473","text":"import numpy as np\nimport cv2\n\nVARIANCE = 4\nMAXTRACKS = 800\nGRIDSIZE = 15\nMASK_RADIUS = 15\n\nclass GridTracker:\n \n #mask used for ignoring regions of the image in the detector and for maintaining minimal feature distance\n curMask = 0\n \n #tracked feas of current frame\n trackedFeas = [] #matched Feas of currFrame\n\n #all feas of current frame\n allFeas = []\n preFeas = [] #matched Feas of preFrame\n\n rows = 0\n cols = 0\n \n #num of feas from last frame\n numActiveTracks = 0\n TRACKING_HSIZE = LK_PYRAMID_LEVEL = MAX_ITER = fealimitGrid = 0\n ACCURACY = LAMBDA = 0\n usableFrac = 0\n\n #store image pyramid for re-utilizatio\n prevPyr = 0\n prevIm = 0\n overflow = MaxTracks = 0\n\n #grids devision\n hgrids_x = 0\n hgrids_y = 0\n hgrids_total = 0\n #records feature number of each grids\n feanumofGrid = []\n\n minAddFrac = minToAdd = 0.0\n unusedRoom = gridsHungry = 0\n lastNumDetectedGridFeatures = []\n hthresholds = []\n DETECT_GAIN = 0\n\n detector = []\n\n def __init__(self):\n return\n\n def maskPoint(self,y,x):\n if self.curMask[y,x] == 0:\n return 1\n xx = np.int(x - MASK_RADIUS / 2 + .5)\n yy = np.int(y - MASK_RADIUS / 2 + .5)\n w = np.int(x + MASK_RADIUS / 2 + .5)\n h = np.int(y + MASK_RADIUS / 2 + .5)\n cv2.rectangle(self.curMask,(xx,yy),(w,h),0, -1)\n return 0\n\n def ParameterInit(self,im):\n self.rows, self.cols = im.shape\n self.numActiveTracks = 0\n self.TRACKING_HSIZE = 8\n self.LK_PYRAMID_LEVEL = 4\n self.MAX_ITER = 10\n self.ACCURACY = 0.1\n self.LAMBDA = 0.0\n\n self.hgrids_x = GRIDSIZE\n self.hgrids_y = GRIDSIZE\n self.hgrids_total = self.hgrids_x * self.hgrids_y\n\n self.usableFrac = 0.02\n self.MaxTracks = MAXTRACKS\n self.minAddFrac = 0.1\n self.minToAdd = self.minAddFrac * self.MaxTracks\n\n self.fealimitGrid = np.floor(self.MaxTracks / (self.hgrids_total))\n self.lastNumDetectedGridFeatures = [0] * self.hgrids_total\n \n self.DETECT_GAIN = 10\n self.hthresholds = [20] * self.hgrids_total\n self.feanumofGrid = [0] * self.hgrids_total\n\n def SpaceInit(self,im):\n self.curMask = np.ones( (self.rows, self.cols), dtype = np.uint8)\n for i in range(self.hgrids_total):\n fast = cv2.FastFeatureDetector_create(self.hthresholds[i],nonmaxSuppression=True,type=cv2.FAST_FEATURE_DETECTOR_TYPE_9_16) \n self.detector.append(fast)\n self.prevIm = im\n \n def Calc_optical_flow_if_feas_from_last_frame(self, im1):\n \n lk_params = dict( winSize = (2 * self.TRACKING_HSIZE + 1, 2 * self.TRACKING_HSIZE + 1),maxLevel = self.LK_PYRAMID_LEVEL,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, self.MAX_ITER, self.ACCURACY))\n \n #perform LK tracking from OpenCV, parameters matter a lot\n self.preFeas = []\n self.trackedFeas = []\n \n p0 = np.asarray(self.allFeas)\n \n p1, st, error = cv2.calcOpticalFlowPyrLK(self.prevIm, im1, p0, None, **lk_params)\n \n self.prevIm = im1\n \n #clear feature counting for each grid\n self.feanumofGrid = [0] * self.hgrids_total\n \n for i in range(len(p1)):\n if st[i] and p1[i,0] > self.usableFrac * self.cols \\\n and p1[i,0] < (1.0 - self.usableFrac) * self.cols \\\n and p1[i,1] > self.usableFrac * self.rows \\\n and p1[i,1] < (1.0 - self.usableFrac) * self.rows:\n \n shouldKill = self.maskPoint(np.int(p1[i,1]), np.int(p1[i,0]))\n \n if shouldKill:\n self.numActiveTracks -= 1\n else:\n self.preFeas.append(p0[i])\n self.trackedFeas.append(p1[i])\n\n self.hgridIdx = np.int(np.floor(p1[i,0] / (self.cols / self.hgrids_x)) \\\n + self.hgrids_x * np.floor(p1[i,1] / (self.rows / self.hgrids_y)))\n\n self.feanumofGrid[self.hgridIdx] += 1\n else:\n self.numActiveTracks -= 1\n \n def Sampling(self,im1):\n #unusedRoom sum\n unusedRoom = 0\n\n #hungry grids\n hungryGrid_idx = []\n hungryGrid_value = []\n\n #room for adding featurs to each grid\n room = 0\n\n #the hungry degree of a whole frame \n hungry = 0\n\n #keypoints detected from each grids\n sub_keypoints = [0] * self.hgrids_total\n sub_keypoints_list = [0] * self.hgrids_total\n\n midGrid = np.floor((self.hgrids_total - 1) / 2.0)\n \n for q in range(self.hgrids_total):\n if self.numActiveTracks < self.MaxTracks:\n i = np.int(q)\n if q == 0:\n i = np.int(midGrid)\n if q == midGrid:\n i = 0 \n\n room = self.fealimitGrid - self.feanumofGrid[i]\n \n if room > self.fealimitGrid * self.minAddFrac:\n \n celly = np.int( i / self.hgrids_x )\n cellx = np.int(i - celly * self.hgrids_x)\n row_start = np.int((celly * self.rows) / self.hgrids_y)\n row_size = np.int(((celly + 1) * self.rows) / self.hgrids_y - row_start)\n col_start = np.int((cellx * self.cols) / self.hgrids_x)\n col_size = np.int(((cellx + 1) * self.cols) / self.hgrids_x - col_start)\n \n sub_image = im1[row_start:row_start+row_size,col_start:col_start+col_size]\n sub_mask = self.curMask[row_start:row_start+row_size,col_start:col_start+col_size]\n \n lastP = (self.lastNumDetectedGridFeatures[i] - 15.0 * room) / (15.0 * room)\n newThresh = self.detector[i].getThreshold()\n newThresh = newThresh + np.ceil(self.DETECT_GAIN * lastP)\n if newThresh > 200:\n newThresh = 200\n if newThresh < 5:\n newThresh = 5\n \n self.detector[i].setThreshold(np.int(newThresh))\n sub_keypoints[i] = self.detector[i].detect(sub_image,sub_mask) \n self.lastNumDetectedGridFeatures[i] = len(sub_keypoints[i])\n \n sub_keypoints_list[i] = np.float32([it.pt for it in sub_keypoints[i]])\n \n n = 0\n j = 0\n\n #first round\n while(1):\n if j self.minToAdd:\n for i in range(len(hungryGrid_idx)):\n first = np.int(hungryGrid_idx[i])\n second = hungryGrid_value[i]\n\n if first >= len(hungryGrid_value):\n continue\n\n celly = np.int( first / self.hgrids_x )\n cellx = np.int(first - celly * self.hgrids_x)\n row_start = np.int((celly * self.rows) / self.hgrids_y)\n col_start = np.int((cellx * self.cols) / self.hgrids_x)\n \n room = (unusedRoom * hungryGrid_value[first]) / hungry\n m = 0\n j = 0\n while(1):\n if m 0:\n self.Calc_optical_flow_if_feas_from_last_frame(im1)\n else:\n self.feanumofGrid = [0] * self.hgrids_total \n \n #self.allFeas = self.trackedFeas\n self.allFeas = []\n self.allFeas = self.trackedFeas.copy()\n \n ntoadd = self.MaxTracks - self.numActiveTracks\n \n if ntoadd > self.minToAdd:\n self.Sampling(im1)\n \nif __name__ == '__main__':\n frames = []\n grays = []\n numFrames = 200\n\n for i in range(numFrames):\n name = \"./frames/%04d.png\" % i \n frame = cv2.imread(name)\n frames.append(frame)\n gray = cv2.imread(name,0)\n grays.append(gray)\n print(\"end loading frame\\n\")\n \n gt = GridTracker()\n gt.trackerInit(grays[0])\n\n for i in range(1,numFrames):\n gt.Update(grays[i]) \n for j in range(len(gt.preFeas)):\n pt0 = gt.preFeas[j]\n cv2.circle(frames[i-1],(pt0[0],pt0[1]),2,(0,255,0),-1)\n name = \"./debug/%04d.jpg\" % (i-1)\n cv2.imwrite(name,frames[i-1])\n \n# img = cv2.imread('100.jpg')\n# fast=cv2.FastFeatureDetector_create(threshold=20,nonmaxSuppression=True,type=cv2.FAST_FEATURE_DETECTOR_TYPE_9_16)\n# kp = fast.detect(img,None)\n# img = cv2.drawKeypoints(img,kp,img,color=(255,0,0))\n# cv2.imshow('',img)\n# cv2.waitKey(0)\n\n# frame1 = cv2.imread('100.jpg')\n# frame2 = cv2.imread('110.jpg')\n\n# prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)\n# hsv = np.zeros_like(frame1)\n# hsv[...,1] = 255\n\n# next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)\n# flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n\n# mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])\n# hsv[...,0] = ang*180/np.pi/2\n# hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)\n# rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)\n\n# cv2.imwrite('opticalfb.png',frame2)\n# cv2.imwrite('opticalhsv.png',rgb)\n\n# # params for ShiTomasi corner detection\n# feature_params = dict( maxCorners = 100,\n# qualityLevel = 0.3,\n# minDistance = 7,\n# blockSize = 7 )\n\n# # Parameters for lucas kanade optical flow\n# lk_params = dict( winSize = (15,15),\n# maxLevel = 2,\n# criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n# old = cv2.imread('100.jpg')\n# frame = cv2.imread('110.jpg')\n# old_gray = cv2.cvtColor(old,cv2.COLOR_BGR2GRAY)\n# frame_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n# p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)\n# p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)\n# good_new = p1[st==1]\n# good_old = p0[st==1]\n\n# for pt in good_new:\n# cv2.circle(old,(pt[0],pt[1]),2,[255,255,0],-1)\n\n# for pt1 in good_old:\n# cv2.circle(frame,(pt1[0],pt1[1]),2,[255,255,0],-1)\n\n# cv2.imwrite(\"s.jpg\",old)\n# cv2.imwrite(\"t.jpg\",frame)","sub_path":"Tracker.py","file_name":"Tracker.py","file_ext":"py","file_size_in_byte":11472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"610959273","text":"# -*- coding: utf-8 -*-\nimport sugartensor as tf\nimport matplotlib.pyplot as plt\nimport ops\nimport os\n# set log level to debug\ntf.sg_verbosity(10)\n\n#\n# hyper parameters\n#\n\nbatch_size = 32\nz_dim = 50\n\n\n#\n# create generator\n#\n\nsize=4\nstride=2\nstrides = [1,stride,stride,1]\n\n# random uniform seed\nz = tf.random_uniform((batch_size, z_dim))\n\nwith tf.sg_context(name='generator', size=4, stride=2, act='relu', bn=True, bias=False):\n g_p1 = (z.sg_dense(dim=1024)\n .sg_dense(dim=7*7*128)\n .sg_reshape(shape=(-1, 7, 7, 128)))\n g_p2 = ops.upconv_and_scale(g_p1, dim=64, size=size, stride=stride,act='relu',bn=True)\n g_p3 = ops.upconv_and_scale(g_p2, dim=1, size=size, stride=stride, act='sigmoid',bn=False)\n gen = g_p3.sg_squeeze()\n \n\n\n#\n# draw samples\n#\nasset_folder = 'asset/train/'\ndef get_next_filename():\n i = 0\n while True:\n num_str = str(i).zfill(4)\n filename = 'sample{}.png'.format(num_str)\n filename = os.path.join(asset_folder, filename)\n if not os.path.isfile(filename):\n print('next filename: {}'.format(filename))\n return filename\n i += 1\n\n\nwith tf.Session() as sess:\n tf.sg_init(sess)\n # restore parameters\n try:\n saver = tf.train.Saver()\n saver.restore(sess, tf.train.latest_checkpoint('./asset/train/ckpt'))\n except Exception as e:\n print('No saved file...: {}'.format(e))\n\n\n # run generator\n imgs = sess.run(gen)\n num_imgs = imgs.shape[0]\n num_per_side = int(num_imgs**0.5)\n\n # plot result\n _, ax = plt.subplots(num_per_side, num_per_side, sharex=True, sharey=True)\n for i in range(num_per_side):\n for j in range(num_per_side):\n ax[i][j].imshow(imgs[i * num_per_side + j], 'gray')\n ax[i][j].set_axis_off()\n plt.savefig(get_next_filename(), dpi=600)\n tf.sg_info('Sample image saved to \"asset/train/sample.png\"')\n plt.close()\n","sub_path":"mnist_ebgan_generate.py","file_name":"mnist_ebgan_generate.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255333992","text":"import requests\n\nfrom .source_factory import WeatherServiceManager\nfrom .settings import GOOGLE_URL\n\n\ndef get_temperature(source, lat=None, lon=None, zip=None):\n if not lat and not lon and not zip:\n raise ValueError('Please provide latitude/longitude or zip code')\n\n if zip:\n lat, lon = validate_zip(zip)\n\n if lat and lon:\n validate_coordinates(lat, lon)\n\n res = dict()\n res['fahrenheit'] = dict()\n res['fahrenheit']['current_temperature'] = 0.0\n res['celsius'] = dict()\n res['celsius']['current_temperature'] = 0.0\n\n if 'all' in source:\n print('all')\n source = {'weatherdotcom', 'noaa', 'accuweather'}\n\n total = float(len(source))\n for src in source:\n weather_manager = WeatherServiceManager(src)\n if weather_manager.check_source() is None:\n raise ValueError('Invalid filter type %s' % src)\n\n r = weather_manager.get_temp(lat, lon)\n if r is not None:\n res['fahrenheit']['current_temperature'] += r['fahrenheit']['current_temperature']\n res['celsius']['current_temperature'] += r['celsius']['current_temperature']\n else:\n raise ValueError('Error processing request for source system %s' % src)\n\n res['fahrenheit']['current_temperature'] = res['fahrenheit']['current_temperature'] / total\n res['celsius']['current_temperature'] = res['celsius']['current_temperature'] / total\n return res\n\n\ndef validate_zip(zip_code):\n api_response = requests.get(GOOGLE_URL.format('address', zip_code)).json()\n print(api_response)\n if api_response['status'] == 'OK':\n return api_response['results'][0]['geometry']['location']['lat'], \\\n api_response['results'][0]['geometry']['location']['lng']\n else:\n raise ValueError('Invalid zip code provided')\n\n\ndef validate_coordinates(lat, lng):\n api_response = requests.get(GOOGLE_URL.format('latlng', str(lat) + ',' + str(lng))).json()\n print(api_response)\n if api_response['status'] == 'OK':\n pass\n else:\n raise ValueError('Please provide valid latitude/longitude pair')\n","sub_path":"shipwell/shipwell/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"107517421","text":"from collections import OrderedDict\r\nimport logging\r\nimport cPickle\r\nimport numpy as np\r\nimport time\r\nimport sys\r\nimport os\r\nimport theano\r\nimport theano.tensor as T\r\n\r\nfrom utils import read_obj\r\n\r\n\r\nclass EmbeddingLCLayer(object):\r\n '''\r\n The first layer of the network, map each word in a n-gram into a word embedding vector,\r\n combined into a whole vector\r\n '''\r\n\r\n def __init__(self, W_e, W_p, W_c):\r\n '''\r\n :parameters:\r\n - W_init: a |V|*d np.ndarray matrix, for mapping each word into a d-dim vector\r\n - b_init: default zero\r\n - activation: combination word embeddings into a vector\r\n '''\r\n self.W_e = theano.shared(value=W_e.astype(theano.config.floatX),\r\n name='W_e',\r\n borrow=True)\r\n self.W_p = theano.shared(value=W_p.astype(theano.config.floatX),\r\n name='W_p',\r\n borrow=True)\r\n self.W_c = theano.shared(value=W_c.astype(theano.config.floatX),\r\n name='W_c',\r\n borrow=True)\r\n self.params = [self.W_e, self.W_p, self.W_c]\r\n\r\n def __call__(self, w_e, w_p, w_c):\r\n we_state = self.W_e[w_e.flatten()].reshape((w_e.shape[0], self.W_e.shape[1] * w_e.shape[1]))\r\n pe_state = self.W_p[w_p.flatten()].reshape((w_p.shape[0], self.W_p.shape[1] * w_p.shape[1]))\r\n ce_state = self.W_c[w_c.flatten()].reshape((w_c.shape[0], self.W_c.shape[1] * w_c.shape[1]))\r\n # we_state = self.W_e[w_e.flatten()].reshape((w_e.shape[0], -1))\r\n # pe_state = self.W_p[w_p.flatten()].reshape((w_p.shape[0], -1))\r\n # ce_state = self.W_c[w_c.flatten()].reshape((w_c.shape[0], -1))\r\n return T.concatenate((we_state, pe_state, ce_state), axis=1)\r\n\r\n\r\nclass MLPNoHid(object):\r\n def __init__(self, W_e, W_p, W_o, b_o):\r\n '''\r\n Multi-layer perceptron class, computes the composition of a sequence of Layers\r\n\r\n '''\r\n # Construct the embedding layers\r\n self.embedding_layer = EmbeddingLayer(W_e, W_p)\r\n\r\n # the output layer\r\n self.output_layer = OutputLayer(W_o, b_o)\r\n\r\n self.mlp_layers = [self.embedding_layer, self.output_layer]\r\n\r\n self.params = []\r\n for layer in self.mlp_layers:\r\n self.params += layer.params\r\n\r\n self.L1 = T.sum(map(T.abs_, self.params))\r\n self.L2 = T.sum(map(T.sqr, self.params))\r\n\r\n @staticmethod\r\n def ce(x, y):\r\n # x = T.set_subtensor(x[(T.abs_(x-0)<0.0001).nonzero()], 0.0001)\r\n return -T.mean(T.log(x)[T.arange(y.shape[0]), y], dtype=theano.config.floatX)\r\n\r\n @staticmethod\r\n def mse(x, y):\r\n zeros_k = T.zeros([y.shape[0], x.shape[1]])\r\n sub_y = T.set_subtensor(zeros_k[T.arange(y.shape[0]), y], 1)\r\n return T.mean((x - sub_y) ** 2)\r\n\r\n def output(self, wx, px):\r\n we_state = self.embedding_layer(wx, px)\r\n return self.output_layer(we_state)\r\n\r\n def ce_with_input(self, wx, px, y):\r\n return self.ce(self.output(wx, px), y)\r\n\r\n def mse_with_input(self, wx, px, y):\r\n return self.mse(self.output(wx, px), y)\r\n\r\n def save_model(self, file_name, wrap_dicts):\r\n abs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)\r\n if not os.path.exists(abs_path):\r\n os.makedirs(abs_path)\r\n model_path = os.path.join(abs_path, 'trained_model')\r\n dict_path = os.path.join(abs_path, 'vocab')\r\n\r\n word_dict, pos_dict, cate_dict = wrap_dicts[0:3]\r\n np.savez(dict_path,\r\n word_vocab=word_dict.keys(),\r\n pos_vocab=pos_dict.keys(),\r\n cate_vocab=cate_dict.keys())\r\n np.savez(model_path,\r\n word_embedding_weights=self.embedding_layer.W_e.get_value(borrow=True),\r\n hidden_to_output_weights=self.output_layer.W_o.get_value(borrow=True),\r\n output_bias=self.output_layer.b_o.get_value(borrow=True))\r\n\r\n\r\nclass EmbeddingLayer(object):\r\n '''\r\n The first layer of the network, map each word in a n-gram into a word embedding vector,\r\n combined into a whole vector\r\n '''\r\n\r\n def __init__(self, W_e, W_p):\r\n '''\r\n :parameters:\r\n - W_init: a |V|*d np.ndarray matrix, for mapping each word into a d-dim vector\r\n - b_init: default zero\r\n - activation: combination word embeddings into a vector\r\n '''\r\n self.W_e = theano.shared(value=W_e.astype(theano.config.floatX),\r\n name='W_e',\r\n borrow=True)\r\n self.W_p = theano.shared(value=W_p.astype(theano.config.floatX),\r\n name='W_p',\r\n borrow=True)\r\n self.params = [self.W_e, self.W_p]\r\n\r\n def __call__(self, w_e, w_p):\r\n # we_state = self.W_e[w_e.flatten()].reshape((w_e.shape[0], -1))\r\n # pe_state = self.W_p[w_p.flatten()].reshape((w_p.shape[0], -1))\r\n # we_flat = self.W_e[w_e.flatten()]\r\n # pe_flat = self.W_p[w_p.flatten()]\r\n # we_state = we_flat.reshape((w_e.shape[0], we_flat.shape[1] * w_e.shape[1]))\r\n # pe_state = pe_flat.reshape((w_p.shape[0], pe_flat.shape[1] * w_p.shape[1]))\r\n we_state = self.W_e[w_e.flatten()].reshape((w_e.shape[0], self.W_e.shape[1] * w_e.shape[1]))\r\n pe_state = self.W_p[w_p.flatten()].reshape((w_p.shape[0], self.W_p.shape[1] * w_p.shape[1]))\r\n return T.concatenate((we_state, pe_state), axis=1)\r\n\r\n\r\nclass OutputLayer(object):\r\n def __init__(self, W_init, b_init):\r\n \"\"\"\r\n The output layer of a neural network, using softmax activation function by default.\r\n \"\"\"\r\n n_input, n_output = W_init.shape\r\n assert b_init.shape == (1, n_output)\r\n self.W_o = theano.shared(value=W_init.astype(theano.config.floatX),\r\n name='W_o',\r\n borrow=True)\r\n self.b_o = theano.shared(value=b_init.reshape(1, -1).astype(theano.config.floatX),\r\n name='b_o',\r\n borrow=True,\r\n broadcastable=(True, False))\r\n\r\n self.params = [self.W_o, self.b_o]\r\n\r\n def __call__(self, x):\r\n return T.nnet.softmax(T.dot(x, self.W_o) + self.b_o)\r\n\r\n\r\nclass MLPLeftCate(object):\r\n def __init__(self, W_e, W_p, W_c, W_o, b_o):\r\n '''\r\n Multi-layer perceptron class, computes the composition of a sequence of Layers\r\n\r\n '''\r\n # Construct the embedding layers\r\n self.embedding_layer = EmbeddingLCLayer(W_e, W_p, W_c)\r\n\r\n # the output layer\r\n self.output_layer = OutputLayer(W_o, b_o)\r\n\r\n self.mlp_layers = [self.embedding_layer, self.output_layer]\r\n\r\n self.params = []\r\n for layer in self.mlp_layers:\r\n self.params += layer.params\r\n\r\n self.L1 = T.sum(map(T.abs_, self.params))\r\n self.L2 = T.sum(map(T.sqr, self.params))\r\n\r\n @staticmethod\r\n def ce(x, y):\r\n # x = T.set_subtensor(x[(T.abs_(x-0)<0.0001).nonzero()], 0.0001)\r\n return -T.mean(T.log(x)[T.arange(y.shape[0]), y], dtype=theano.config.floatX)\r\n\r\n @staticmethod\r\n def mse(x, y):\r\n zeros_k = T.zeros([y.shape[0], x.shape[1]])\r\n sub_y = T.set_subtensor(zeros_k[T.arange(y.shape[0]), y], 1)\r\n return T.mean((x - sub_y) ** 2)\r\n\r\n def output(self, wx, px, cx):\r\n we_state = self.embedding_layer(wx, px, cx)\r\n return self.output_layer(we_state)\r\n\r\n def ce_with_input(self, wx, px, cx, y):\r\n return self.ce(self.output(wx, px, cx), y)\r\n\r\n def mse_with_input(self, wx, px, cx, y):\r\n return self.mse(self.output(wx, px, cx), y)\r\n\r\n def save_model(self, file_name, wrap_dicts):\r\n abs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)\r\n if not os.path.exists(abs_path):\r\n os.makedirs(abs_path)\r\n model_path = os.path.join(abs_path, 'trained_model')\r\n dict_path = os.path.join(abs_path, 'vocab')\r\n\r\n word_dict, pos_dict, cate_dict = wrap_dicts[0:3]\r\n np.savez(dict_path,\r\n word_vocab=word_dict.keys(),\r\n pos_vocab=pos_dict.keys(),\r\n cate_vocab=cate_dict.keys())\r\n np.savez(model_path,\r\n word_embedding_weights=self.embedding_layer.W_e.get_value(borrow=True),\r\n cate_embedding_weights=self.embedding_layer.W_c.get_value(borrow=True),\r\n hidden_to_output_weights=self.output_layer.W_o.get_value(borrow=True),\r\n output_bias=self.output_layer.b_o.get_value(borrow=True))\r\n\r\n\r\nclass EmbeddingPretLayer(object):\r\n '''\r\n The first layer of the network, map each word in a n-gram into a word embedding vector,\r\n combined into a whole vector\r\n '''\r\n\r\n def __init__(self, W_c):\r\n '''\r\n :parameters:\r\n - W_init: a |V|*d np.ndarray matrix, for mapping each word into a d-dim vector\r\n - b_init: default zero\r\n - activation: combination word embeddings into a vector\r\n '''\r\n self.W_c = theano.shared(value=W_c.astype(theano.config.floatX),\r\n name='W_c',\r\n borrow=True)\r\n self.params = [self.W_c]\r\n\r\n def __call__(self, w_c):\r\n return self.W_c[w_c.flatten()].reshape((w_c.shape[0], self.W_c.shape[1] * w_c.shape[1]))\r\n\r\n\r\nclass MLPPret(object):\r\n def __init__(self, W_c, W_o, b_o):\r\n '''\r\n MLP for pretraining category embeddings, for example,\r\n the input is X/Y Y, the target is X.\r\n '''\r\n # Construct the embedding layers\r\n self.embedding_layer = EmbeddingPretLayer(W_c)\r\n\r\n # the output layer\r\n self.output_layer = OutputLayer(W_o, b_o)\r\n\r\n self.mlp_layers = [self.embedding_layer, self.output_layer]\r\n\r\n self.params = []\r\n for layer in self.mlp_layers:\r\n self.params += layer.params\r\n\r\n self.L1 = T.sum(map(T.abs_, self.params))\r\n self.L2 = T.sum(map(T.sqr, self.params))\r\n\r\n @staticmethod\r\n def ce(x, y):\r\n # x = T.set_subtensor(x[(T.abs_(x-0)<0.0001).nonzero()], 0.0001)\r\n return -T.mean(T.log(x)[T.arange(y.shape[0]), y], dtype=theano.config.floatX)\r\n\r\n @staticmethod\r\n def mse(x, y):\r\n zeros_k = T.zeros([y.shape[0], x.shape[1]])\r\n sub_y = T.set_subtensor(zeros_k[T.arange(y.shape[0]), y], 1)\r\n return T.mean((x - sub_y) ** 2)\r\n\r\n def output(self, cx):\r\n we_state = self.embedding_layer(cx)\r\n return self.output_layer(we_state)\r\n\r\n def ce_with_input(self, cx, y):\r\n return self.ce(self.output(cx), y)\r\n\r\n def mse_with_input(self, cx, y):\r\n return self.mse(self.output(cx), y)\r\n\r\n def save_model(self, file_name, wrap_dcates):\r\n \"\"\"\r\n Save the category dict and inverse category dict for tagging,\r\n also save category embeddings.\r\n \"\"\"\r\n abs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)\r\n if not os.path.exists(abs_path):\r\n os.makedirs(abs_path)\r\n model_path = os.path.join(abs_path, 'pretrained_model')\r\n dict_path = os.path.join(abs_path, 'pret_vocab')\r\n cate_dict, inv_cdict = wrap_dcates\r\n np.savez(dict_path, cate_dict=cate_dict, inv_cdict=inv_cdict)\r\n np.savez(model_path,\r\n cate_embedding_weights=self.embedding_layer.W_c.get_value(borrow=True),\r\n hidden_to_output_weights=self.output_layer.W_o.get_value(borrow=True),\r\n output_bias=self.output_layer.b_o.get_value(borrow=True))\r\n\r\n\r\ndef evaluate_left_cate(test_leftmodel, test_params, wrap_testdata, pred_cate, wrap_invds):\r\n log_m = logging.getLogger('main')\r\n log_c = logging.getLogger('correct')\r\n log_e = logging.getLogger('error')\r\n\r\n lw_size, beam_size, sent_i, is_chain = test_params\r\n inv_wdict, inv_pdict, inv_cdict = wrap_invds\r\n test_wleft, test_pleft, test_y = wrap_testdata\r\n kbest_args = np.argpartition(pred_cate, -beam_size)[:, -beam_size:]\r\n kbest_probs = pred_cate[np.indices(kbest_args.shape)[0], kbest_args]\r\n corr = 0.\r\n error = 0.\r\n forward_succ = 0.\r\n forward_failed = 0.\r\n sent_pred = []\r\n total = len(test_y)\r\n for i in range(total):\r\n left_probs = []\r\n if is_chain:\r\n for j in range(beam_size):\r\n left_output = test_leftmodel(np.asarray([test_wleft[i]]).astype('int32'),\r\n np.asarray([test_pleft[i]]).astype('int32'),\r\n np.asarray([[kbest_args[i][j]]]).astype('int32'))\r\n # kbest_argleft = np.argpartition(left_output, -1)[:, -1:]\r\n # kbest_probleft = left_output[np.indices(kbest_argleft.shape)[0], kbest_argleft]\r\n kbest_probleft = np.max(left_output)\r\n left_probs.append(kbest_probleft)\r\n # res_j = 1.0 if np.max(forward_cate) > 0.9 else 0.1\r\n product = kbest_probs[i] * left_probs\r\n rank_start = np.argmax(product)\r\n forward_cate = kbest_args[i][rank_start]\r\n else:\r\n if i == 0:\r\n forward_cate = kbest_args[i][np.argmax(kbest_probs[i])]\r\n else:\r\n for j in range(beam_size):\r\n left_output = test_leftmodel(np.asarray([test_wleft[i]]).astype('int32'),\r\n np.asarray([test_pleft[i]]).astype('int32'),\r\n np.asarray([[forward_cate]]).astype('int32'))\r\n # kbest_argleft = np.argpartition(left_output, -1)[:, -1:]\r\n # kbest_probleft = left_output[np.indices(kbest_argleft.shape)[0], kbest_argleft]\r\n kbest_probleft = np.max(left_output)\r\n left_probs.append(kbest_probleft)\r\n # res_j = 1.0 if np.max(forward_cate) > 0.9 else 0.1\r\n product = kbest_probs[i] * left_probs\r\n rank_start = np.argmax(product)\r\n forward_cate = kbest_args[i][rank_start]\r\n\r\n if test_y[i] in kbest_args[i]:\r\n if forward_cate == test_y[i]:\r\n forward_succ += 1\r\n else:\r\n forward_failed += 1\r\n # print(\"the %d-th sent, %d-th word, forward rerank failed! gold: %d, pred: %s\" % (sent_i, i, test_y[i], str(kbest_args[i])))\r\n # print('kbest_probs %s, left_prob: %s, product: %s' % (str(kbest_probs[i]), str(left_probs), str(product)))\r\n corr += 1\r\n else:\r\n error += 1\r\n\r\n sent_pred.append(forward_cate)\r\n\r\n if sent_pred == test_y:\r\n sent_acc = True\r\n else:\r\n sent_acc = False\r\n\r\n \"\"\"\r\n cate_cx = []\r\n forward_prob = []\r\n backward_prob = []\r\n if i == 0:\r\n backward_cate = kbest_args[-i - 1][np.argmax(kbest_probs[-i - 1])]\r\n else:\r\n for j in range(beam_size):\r\n test_cx1 = [[kbest_args[-i - 1][j], backward_cate]]\r\n test_cx2 = [[backward_cate, kbest_args[-i - 1][j]]]\r\n cate_cx1 = cate_repr(test_cx1[0])\r\n cate_cx.append(cate_cx1)\r\n # backward_output = output_model(test_cx1)\r\n #forward_output = output_model(test_cx2)\r\n #backward_prob.append(np.max(backward_output))\r\n #forward_prob.append(np.max(forward_output))\r\n product = kbest_probs[-i - 1]\r\n rank_end = np.argmax(product)\r\n backward_cate = kbest_args[-i - 1][rank_end]\r\n\r\n if test_y[-i - 1] in kbest_args[-i - 1]:\r\n corr += 1\r\n if backward_cate == test_y[-i - 1]:\r\n backward_succ += 1\r\n else:\r\n cate_gold = inv_cdict[test_y[-i - 1]]\r\n cate_kbest = cate_repr(kbest_args[-i - 1])\r\n backward_failed += 1\r\n print(\"the %d-th sent, %d-th word %s, backward rerank failed! gold: <%s, %d> pred: <%s, %s>\" % (\r\n (sent_i + 1), total - i, inv_wdict[test_wx[i][lw_size]], cate_gold, test_y[-i - 1], cate_kbest,\r\n str(kbest_args[-i - 1])))\r\n print('combined result: %s' % ' '.join(cate_cx))\r\n print('kbest_probs %s, backward_prob: %s, product: %s' % (\r\n str(kbest_probs[-i - 1]), str(backward_prob), str(product)))\r\n else:\r\n error += 1\r\n \"\"\"\r\n # print('start failed number: %d' % forward_failed)\r\n # print('start succ number: %d' % forward_succ)\r\n # print(\"corr_corr: %d, corr_error: %d, c_c|c: %.3f\" % (corr_corr, corr_error, cc_c))\r\n # print(\"corr: %d, error: %d, c_e: %.3f\" % (corr, error, c_e))\r\n return sent_acc, forward_succ, forward_failed, corr, error\r\n\r\n\r\ndef unzip(params):\r\n new_params = []\r\n for item in params:\r\n new_params.append(item)\r\n return new_params\r\n\r\n\r\ndef rebuild_nn(nn_params):\r\n W_e, W_p, W_o, b_o = read_obj(nn_params, 4)\r\n mlp = MLPNoHid(W_e.get_value(), W_p.get_value(), W_o.get_value(), b_o.get_value())\r\n wx = T.matrix('word', dtype='int32')\r\n px = T.matrix('POS', dtype='int32')\r\n f_pred = theano.function([wx, px], mlp.output(wx, px))\r\n return f_pred\r\n\r\n\r\ndef rebuild_cate(cate_params):\r\n W_c, W_o, b_o = read_obj(cate_params, 3)\r\n mlp = MLPPret(W_c.get_value(), W_o.get_value(), b_o.get_value())\r\n cx = T.matrix('cate', dtype='int32')\r\n f_pred = theano.function([cx], mlp.output(cx))\r\n return f_pred\r\n\r\n\r\ndef rebuild_cand(cand_params):\r\n W_e, W_p, W_c, W_o, b_o = read_obj(cand_params, 5)\r\n mlp = MLPLeftCate(W_e.get_value(), W_p.get_value(), W_c.get_value(), W_o.get_value(), b_o.get_value())\r\n wx = T.matrix('wx', dtype='int32')\r\n px = T.matrix('px', dtype='int32')\r\n cx = T.matrix('cx', dtype='int32')\r\n f_pred = theano.function([wx, px, cx], mlp.output(wx, px, cx))\r\n return f_pred","sub_path":"mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":18219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"63820068","text":"import spacy\n\nnlp = spacy.load(\"en_core_web_sm\")\ndoc = nlp(\"Berlin is a nice city\")\n\n# Get all tokens and part-of-speech tags\n# 텍스트 속성 값과 part-of-speech 태그 속성 값을 모든 토큰들로부터 추출합니다.\ntoken_texts = [token.text for token in doc]\npos_tags = [token.pos_ for token in doc]\n\nfor index, pos in enumerate(pos_tags):\n # Check if the current token is a proper noun\n # 현재 토큰의 품사가 대명사(Proper Noun)인지 확인합니다.\n if pos == \"PROPN\":\n # Check if the next token is a verb\n # 다음 토큰의 품사가 동사(Verb)인지 확인합니다.\n if pos_tags[index + 1] == \"VERB\":\n result = token_texts[index]\n print(\"Found proper noun before a verb:\", result)\n","sub_path":"exercises-kr/exc_02_07.py","file_name":"exc_02_07.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"650335729","text":"import pandas as pd\nimport numpy as numpy\nimport re\nfrom string import punctuation\nimport categories\n\ndef identify(df):\n '''\n Creates unique idenfier columns as a string\n combination of founder_id and project_id. Returns\n dataframe with identifier column included.\n '''\n identifiers = []\n for x in df[['founder_id', 'project_id']].values:\n indentifiers.append(str(int(x[0])), str(int(x[1])))\n\n df['identifier'] = identifiers\n\n return df\n\ndef only_goals(df):\n '''\n Filters out projects that don't have a goal\n '''\n return df[df['goal'] != 0]\n\ndef set_target(df):\n '''\n Creates continuous and binary targets; multiple and\n over_under. Specificaly, multiple is the ratio bewteen\n the project outcome and the project goal. Over_under\n represents a binary target which identifies whether\n the project was either over- or under-subscribed.\n '''\n df['multiple'] = df['outcome'] / df['goal']\n df['over_under'] = df['multiple'] >= 1\n\n df.dropna(subset=['multiple'], how='all', axis=0, inplace=True)\n\n return df\n\ndef pledge_to_list(pledge):\n '''\n Converts list element from string to integer. Used to\n convert pledge levels into integers. Any empty list\n will be represented as a -1 value. To be called in the\n featurize_pledges function.\n '''\n result = filter(None, pledge.strip('[]').replace('.', '').replace(' ', '').split(','))\n\n if bool(result):\n result = map(int, result)\n return result\n\n else:\n return -1\n\ndef featurize_pledges(df):\n '''\n Extracts multiple features from the original pledge\n string. Calls pledge_to_list function to convert\n pledge strings to lists.\n '''\n features = ['min_pledge', 'max_pledge', 'avg_pledge', 'std_pledge', 'count_pledge']\n aggs = [np.min, np.max, np.mean, np.std, len]\n\n for i in xrange(0, len(aggs)):\n df[features[i]] = [aggs[i](x) for x in df['pledges'].values]\n\n return df\n\n\ndef check_state(string):\n '''\n Replaces any cities that may have ended up in the\n state field to it's respective state. Apply this\n function on every string in the 'state' feature.\n '''\n if string in ['Los Angeles', 'San Francisco', 'San Diego', 'San Jose', 'Palo Alto']:\n return 'CA'\n\n elif string in ['Manhattan', 'Queens', 'Brooklyn', 'Bronx', 'Stuyvesant']:\n return 'NY'\n\n elif string in ['Boston']:\n return 'MA'\n\n elif string in ['Arlington']:\n return 'VA'\n\n elif string in ['Seattle']:\n return 'WA'\n\n elif string in ['Portland']:\n return 'OR'\n\n elif string in ['Miami', 'Orlando']:\n return 'FL'\n\n elif string in ['Philadelphia', 'Pittsburgh']:\n return 'PA'\n\n elif string in ['Chicago']:\n return 'IL'\n\n elif string in ['Glendale', 'Phoenix']:\n return 'AZ'\n\n elif string in ['Las Vegas']:\n return 'NV'\n\n elif string in ['Minneapolis']:\n return 'MN'\n\n elif string in ['Memphis']:\n return 'TN'\n\n else:\n return string\n\ndef check_category(string):\n '''\n Replaces tags with their respective categories. Apply\n this function to every string in the 'category'\n feature.\n '''\n if string in categories.art:\n return 'Art'\n\n elif string in categories.comics:\n return 'Comics'\n\n elif string in categories.dance:\n return 'Dance'\n\n elif string in categories.design:\n return 'Design'\n\n elif string in categories.fashion:\n return 'Fashion'\n\n elif string in categories.film_video:\n return 'Film & Video'\n\n elif string in categories.food:\n return 'Food'\n\n elif string in categories.games:\n return 'Games'\n\n elif string in categories.journalism:\n return 'Journalism'\n\n elif string in categories.music:\n return 'Music'\n\n elif string in categories.photography:\n return 'Photography'\n\n elif string in categories.publishing:\n return 'Publishing'\n\n elif string in categories.technology:\n return 'Technology'\n\n elif string in categories.theater:\n return 'Theater'\n\n\ndef encode_states(df):\n '''\n Encodes states as additional binary features.\n '''\n state_features = ['CA', 'NY', 'TX', 'FL', 'IL']\n\n state_encode_cols = ['is_CA', 'is_NY', 'is_TX', 'is_FL', 'is_IL']\n\n for n, state in enumerate(state_features):\n\n df[state_encode_cols[n]] = (df['project_state'] == state)\n\n return df\n\ndef encode_categories(df):\n '''\n Encodes categories as additional binary features.\n '''\n categories = [\n 'Theater', 'Publishing', 'Music',\n 'Photography', 'Art', 'Games',\n 'Film & Video', 'Comics', 'Design'\n , 'Technology', 'Journalism',\n 'Dance', 'Food', 'Fashion',\n 'Crafts'\n ]\n\n for n, category in enumerate(categories):\n df['is_{}'.format(categories[n])] = (df['category'] == category)\n\n return df\n\ndef word_count(string):\n '''\n Formats the description string for punctuation and\n returns word count. Apply this function to every\n string in the 'description' feature.\n '''\n r = re.compile(r'[{}]'.format(punctuation))\n new_string = r.sub(' ',string)\n return len(new_string.split())\n\ndef sentence_count(string):\n '''\n Returns sentence count by spliting string on periods.\n '''\n return len(string.split('.'))\n\n\n","sub_path":"postprocess/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"364549303","text":"def isprime(num):\n i = 2\n a = True\n while i**2 <= num:\n if num % i == 0:\n a = False\n i+=1 \n return a\n\ndef find_factors(num):\n res = []\n for i in range(2,num):\n if num%i == 0:\n res.append(i)\n return res\n\ndef prime_factors(num):\n res = []\n if num == 2:\n return [2]\n for i in find_factors(num):\n if isprime(i):\n res.append(i)\n return res\n","sub_path":"Freshman/CENG111/nihil_exercises/prime_factors.py","file_name":"prime_factors.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"492902780","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 8 19:09:34 2020\r\n\r\n@author: Mahendra\r\n\"\"\"\r\n\r\n\r\n# def main():\r\n# data = add(20,10)\r\n# data1 = data+ 100\r\n# print(data1)\r\n# sub(30,20)\r\n \r\n# #next_data = sub(30,20)\r\n# #print(next_data)\r\n# #test = next_data + 150\r\n# # print(test)\r\n \r\n \r\n# # Value returning Fuction\r\n# def add(x,y):\r\n# return x+y # return\r\n\r\n# # void function\r\n# def sub(x,y):\r\n# result = x-y\r\n# print(result) # display output\r\n \r\n \r\n# main()\r\n\r\n\r\n# Write a calculator with addition,\r\n# diviion,subtraction and multiplication..\r\n# Ask data and function from user\r\n\r\n\r\n# import math\r\n# from datetime import date\r\n\r\n# today = date.today()\r\n# print(today)\r\n\r\n# def main():\r\n# num = float(input(\"Enter a number\"))\r\n \r\n# square_root = math.sqrt(num)\r\n# print(\"The square root of \",num, 'is ' , square_root)\r\n \r\n# main()\r\n\r\n# import random as task\r\n\r\n\r\n# def main():\r\n# for count in range(8):\r\n# number = task.randint(1,100)\r\n# print(\"The number is\",number)\r\n# print(number+1)\r\n \r\n# main()\r\n\r\n\r\nimport random as ra\r\n\r\nmin = 1\r\nmax = 6\r\n\r\ndef main():\r\n again = 'y'\r\n \r\n while again == 'y' or again == 'Y':\r\n print(\"Rolling the dice...\")\r\n print(\"Their values are...\")\r\n print(ra.randint(min,max))\r\n \r\n again = str(input(\"Do you want to roll them again ? (y = yes)\"))\r\n \r\nmain()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Documents/python exercise/Day 11/Day_11/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562758916","text":"#### THE FARMER v1.3 #####\n# CONFIGURATION FILE #\n##########################\n\n\n#### GENERAL FUNCTIONALITY #####\nCONSOLE_LOGGING_LEVEL = 'DEBUG'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# VERBOSE console level ('INFO', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\nLOGFILE_LOGGING_LEVEL = None\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# VERBOSE logfile level (same options, but can also be None)\nPLOT = 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Plot level (0 to 3)\nNTHREADS = 8\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Number of threads to run on (0 is serial)\nOVERWRITE = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Overwrite existing files without warning?\nUSE_CERES = False\nOUTPUT = True\n\n##### FILE LOCATION #####\nWORKING_DIR = '/Users/jweaver/Projects/Current/Farmer_GalSim/'\nIMAGE_DIR = WORKING_DIR + 'data/images'\t\t\t\t\t\t\t\t\t\t# INPUT Raw images, weights, and masks\nPSF_DIR = WORKING_DIR + 'data/intermediate/psfmodels'\t\t\t\t\t\t\t# INTERMEDIATE Point-spread function files\nBRICK_DIR = WORKING_DIR + 'data/intermediate/bricks'\t\t\t\t\t\t\t# INTERMEDIATE Bricks (i.e. subimages)\nINTERIM_DIR = WORKING_DIR + 'data/intermediate/interim'\t\t\t\t\t\t# OUTPUT Other stuff I make \t\t\nPLOT_DIR = WORKING_DIR + 'data/intermediate/plots'\t\t\t\t\t\t\t# OUTPUT Figures\nCATALOG_DIR = WORKING_DIR + 'data/output/catalogs'\t\t\t\t\t# OUTPUT Catalog\nLOGGING_DIR = INTERIM_DIR\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# VERBOSE logfile location. If None, reports directly to command line\nSFDMAP_DIR = '/Users/jweaver/Projects/Common/py_tools/sfddata-master'\n\nSTARCATALOG_DIR = WORKING_DIR + 'data/external/'\nSTARCATALOG_FILENAME = 'acs_clean_only.fits'\nSTARCATALOG_COORDCOLS = ['ALPHA_J2000', 'DELTA_J2000']\nSTARCATALOG_MATCHRADIUS = 0.6 # arcsec\n\n##### FILE NAME PATTERNS, BANDS, AND ZEROPOINTS #####\t\nIMAGE_EXT = ''\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Image file extension\nWEIGHT_EXT = '_weight'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Weight file extension\nMASK_EXT = '_mask'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Mask file extension\nMASTER_MASK = None\n\nDETECTION_NICKNAME = 'DETECTION'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection image file nickname\nDETECTION_FILENAME = 'hsc_I-band_10x10_10000srcs_COSMOS_withPSEXT.fits' \t\t\t\t\t\t\t\t\t\t# Detection image file name (fill IMAGE_EXT with EXT)\nDETECTION_ZPT = 31.4\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection image zeropoint\n\nMODELING_NICKNAME = 'MODELING'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Modeling image file nickname\nMODELING_FILENAME = 'hsc_I-band_10x10_10000srcs_COSMOS_withPSEXT.fits'\t\t\t\t\t\t\t\t\t\t# Modeling image file name (fill IMAGE_EXT with EXT)\nMODELING_ZPT = 31.4\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Modeling image zeropoint\n\nMULTIBAND_NICKNAME = 'MULTIBAND'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiwavelength image files nickname\nMULTIBAND_FILENAME = 'BANDEXT.fits' # fill with 'BAND' and 'EXT'\t\t\t\t\t\t\t\t# Multiwavelength image files name (fill BANDEXT with BANDS)\nBANDS = [\n'hsc_i0',\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiwavelength band names\n'hsc_i1',\n'hsc_i2',\n'hsc_i3',\n]\nMULTIBAND_ZPT = [\t\t\n31.4,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiwavelength band zeropoints\n31.4,\n31.4,\n31.4\n]\n\n\n##### IMAGE PROPERTIES #####\nPIXEL_SCALE = 0.15\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Image pixel scale in arcsec/px^2\nMOSAIC_WIDTH = 4000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Mosaic image width\nMOSAIC_HEIGHT = 4000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Mosaic image height\n\n\n##### POINT-SPREAD FUNCTIONS #####\nCONSTANT_PSF = ['MODELING',] + BANDS\nPRFMAP_PSF = []\t\t\t\t\t\t\t\t\t\t\t# Which PSFs are created constant AND realized as constant\nPRFMAP_GRID_FILENAME = {}\nPRFMAP_DIR = {}\nPRFMAP_COLUMNS = ('ID_GRIDPT', 'RA', 'Dec') #('col5', 'col1', 'col2') #('ID_GRID', 'RA', 'DEC')\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# ID, RA, DEC\nPRFMAP_FILENAME = 'mosaic_gp'\nUSE_BLOB_IDGRID = False\nPRFMAP_MAXSEP = 3000 #80 # arcsec (i.e. 50 arcsec = 333 pixels)\nPRFMAP_PIXEL_SCALE_ORIG = 0.150\nPRFMAP_FORCE_SIZE = 0\nPRFMAP_MASKRAD = 25/2.\nPSF_RADIUS = 0 #80.5 #px\nPSFVAR_NSNAP = 9 \t\n\nPSFGRID = [\t]\nPSFGRID_OUT_DIR = '/Volumes/WD4/Current/COSMOS2020/data/intermediate/PSFGRID/' # Where to find the OUT directories\nPSFGRID_MAXSEP = 3000\n\nUSE_STARCATALOG = True\nFLAG_STARCATALOG = ['MU_CLASS==2',]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# For varying PSFs, how many realizations along an axis?\nMOD_REFF_LIMITS = (2.5, 3.2)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Model PSF selection in Reff\nMOD_VAL_LIMITS = (19.5, 21.0) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Model PSF selection in Magnitude\nMULTIBAND_REFF_LIMITS = (\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiwavelength PSF selection in Reff\n)\nMULTIBAND_VAL_LIMITS = (\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiwavelength PSF selection in Magnitude\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Sigma of the mock gaussian PSF to be realized\nNORMALIZE_PSF = True \t\nNORMALIZATION_THRESH = 1E-2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Normalize your PSFs? (Say yes...)\nRMBACK_PSF = ['MODELING',] + BANDS \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# On the fly PSF background subtraction in an annulus\nPSF_MASKRAD = 8.5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Size of background annulus, in arcsec\nFORCE_GAUSSIAN_PSF = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Force Farmer to realize mock gaussian PSFs instead\nUSE_GAUSSIAN_PSF = FORCE_GAUSSIAN_PSF\t\nUSE_MOG_PSF = False #experimental!\t\t\t\t\t\t\t\t\t\t\t\t\t\t# TODO\nPSF_SIGMA = 0.8 \n\n\n##### TRACTOR ENGINE #####\nDAMPING = 1e-6\nTRACTOR_MAXSTEPS = 100\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Maximum number of iterations to try\nTRACTOR_CONTHRESH = 1E-2\nUSE_RMS_WEIGHTS = []\nSCALE_WEIGHTS = ['hsc_i',]\nUSE_MASKED_SEP_RMS = False\nUSE_MASKED_DIRECT_RMS = False\nAPPLY_SEGMASK = True\nITERATIVE_SUBTRACTION_THRESH = 1E31\nCORRAL_SOURCES = True\nREFF_MIN = 0.1 * 0.15 # arcsec\n\n\n\n\n##### DEBUG MODE #####\nNBLOBS = 0\t\nTRY_OPTIMIZATION = True\n\n##### MODELING #####\nMODELING_BANDS = ['hsc_i1','hsc_i2']\t\nMODEL_PHOT_MAX_NBLOB = 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Skips modelling of blobs with N sources greater than this value\nFORCE_POSITION = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, will force the position from an external catalog\nFREEZE_POSITION = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, model positions will be frozen after the PS-Model stage\nFREEZE_FINAL_POSITION = False\nUSE_MODEL_POSITION_PRIOR = True #True\nMODEL_POSITION_PRIOR_SIG = 1 * 0.15 # arcsec\nUSE_MODEL_SHAPE_PRIOR = True # True\nMODEL_REFF_PRIOR_SIG = 2 * 0.15 # arcsec\n# MODEL_EE_PRIOR_SIG = 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t# TODO\t\t\t\t\t\t\t\t\t\t\t\t\t# Skips photometering blobs with N sources greater than this value\nITERATIVE_SUBTRACTION_THRESH = 1E31\nUSE_BIC = False\t\t\nUSE_SEP_INITIAL_FLUX = True\t\n\n##### DECISION TREE #####\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Use BIC instead of Chi2 in decision tree\nDECISION_TREE = 1\n\t\n### OPTION 1\t\t\nPS_SG_THRESH1 = 0.3\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Threshold which PS-models must beat to avoid tree progression\nEXP_DEV_THRESH = 0.5\t\nCHISQ_FORCE_EXP_DEV = 1.5\nCHISQ_FORCE_COMP = 1.5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Threshold which either EXP or DEV must beat to avoid tree progression\n\n### OPTION 2\t\t\nPS_SG_THRESH2 = 0.2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Threshold which PS-models must beat to avoid tree progression\nCHISQ_FORCE_SERSIC = 1.0\t\nCHISQ_FORCE_SERSICCORE = 1.0\nCHISQ_FORCE_COMP = 1.2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Otherwise will guess inital flux from peak of image and peak of psf\n\n##### FORCED PHOTOMETRY #####\nINIT_FLUX_BAND = 'hsc_i1'\nFORCED_PHOT_MAX_NBLOB = 0\nFREEZE_FORCED_POSITION = True \nUSE_FORCE_POSITION_PRIOR = True\nFORCE_POSITION_PRIOR_SIG = 0.3 * 0.15 # arcsec #'AUTO'\nFREEZE_FORCED_SHAPE = True\nUSE_FORCE_SHAPE_PRIOR = False\nFORCE_REFF_PRIOR_SIG = 0 #arcsec\n# FORCE_EE_PRIOR_SIG = 0 #arcsec\n\n\n##### BRICKS AND BLOBS #####\nBRICK_WIDTH = 2000 \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Width of bricks (in pixels)\nBRICK_HEIGHT = 2000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Height of bricks (in pixels)\nBRICK_BUFFER = 100\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Buffer around bricks (in pixels)\nBLOB_BUFFER = 5 #px\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Buffer around blobs (in pixels)\nDILATION_RADIUS = 1\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Dialation structure function radius to expand segemetation maps\n# SEGMAP_SNR = 0\nSEGMAP_MINAREA = 50\n\n###### SOURCE DETECTION ######\nUSE_DETECTION_WEIGHT = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, the weight associated with the detection map will be used\nDETECTION_SUBTRACT_BACKGROUND = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, the background of the detection map will be subtracted\nSUBTRACT_BACKGROUND = BANDS\nSUBTRACT_BACKGROUND_WITH_MASK = False\nSUBTRACT_BACKGROUND_WITH_DIRECT_MEDIAN = False\nMANUAL_BACKGROUND = {}\nSAVE_BACKGROUND = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, the background of each brick will be subtracted\nDETECT_BW = 128\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection mesh box width\nDETECT_BH = 128\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection mesh box height\nDETECT_FW = 3\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection filter box width\nDETECT_FH = 3\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection filter box height\nSUBTRACT_BW = 128\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Background mesh box width\nSUBTRACT_BH = 128\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Background mesh box height\nSUBTRACT_FW = 3\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Background filter box width\nSUBTRACT_FH = 3\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Background filter box height\nUSE_FLAT = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, will use brick-global background level in subtraction\nTHRESH = 1.5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If weight is used, this is a relative threshold in sigma. If not, then absolute.\nMINAREA = 2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Minumum contiguous area above threshold required for detection\nFILTER_KERNEL = 'gauss_2.0_5x5.conv'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection convolution kernel\nFILTER_TYPE = 'matched' \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Detection convolution kernel type\nDEBLEND_NTHRESH = 2**8\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Debelnding n-threshold\nDEBLEND_CONT = 1E-10\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Deblending continuous threshold\nPIXSTACK_SIZE = 1000000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Allowed number of pixels in a single detection image\n\n\n\n##### APERTURE PHOTOMETRY #####\nDO_APPHOT = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, each object will be aperture photometered (image, model, and residual)\nAPER_APPLY_SEGMASK = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# if True, values beyond the segmentation will be masked out in aperture photometry\nAPER_PHOT = [1.0, 2.0, 3.0, 5.0, 10.0] \t\t\t\t\t\t\t\t\t\t\t# Diameter sizes of apertures (in arcsec)\nDO_SEPHOT = True\nPHOT_AUTOPARAMS = [2.5, 3.5] # kron factor, min radius in pixels\nPHOT_FLUXFRAC = [0.2, 0.5, 0.8] # Fraction of FLUX_AUTO defining FLUX_RADIUS\n\n\n##### RESIDUAL SOURCE DETECTION #####\nDO_SEXPHOT = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, each blob will be re-detected for residual sources and/or noise\nRES_THRESH = 5 \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Threshold for detection (relative, in sigma)\nRES_MINAREA = 5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Mininum area required for detection\nRES_DEBLEND_NTHRESH = 10\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Deblending n-threshold\nRES_DEBLEND_CONT = 0.0001\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Deblending continuous threshold\n\n\n##### MISCELLANEOUS #####\nX_COLNAME = 'x'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# x coordinate column name from previous centroiding\nY_COLNAME = 'y'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# y coordinate column name from previous centroiding\n\nESTIMATE_EFF_AREA = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Toggles effective area calculation, written to catalog header.\nMAKE_MODEL_IMAGE = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, a model image will be made for each brick and band\nMAKE_RESIDUAL_IMAGE = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If True, a residual image will be made for each brick and band\nRESIDUAL_CHISQ_REJECTION = 1E31\nRESIDUAL_NEGFLUX_REJECTION = True \nRESIDUAL_AB_REJECTION = None \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Otherwise set to None\n\nSPARSE_SIZE = 1000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Threshold of square pixel area above which SPARSE_THRESH Will be applied.\nSPARSE_THRESH = 0.85\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If number of maksed pixels in a blob exceeds this value, it will be skipped","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"96831410","text":"# Source file for connect 4 TEXT-CONSOLE BASED\r\n# Made and designed by Aiden Hoopes, Justin Barros, and Venkata Thota\r\n#\r\n# The game can be played by typing the direction you want to go to\r\n# and selecting a row or column that is playable in that direction.\r\n#\r\n# Piece can be dropped from 3 different directions: LEFT(L), RIGHT(R), and DOWN(D).\r\n#\r\n\r\nimport random\r\nfrom tkinter import *\r\n\r\n# GLOBAL VARIABLES\r\n\r\n# player properties\r\nNOWINNER = 0\r\nPLAYER1 = 1\r\nPLAYER2 = 5\r\n\r\n# board properties\r\nDOWN = 'd'\r\nLEFT = 'l'\r\nRIGHT = 'r'\r\n\r\n# created a Board class\r\nclass Board:\r\n # constructor\r\n # initialize a size and empty grid\r\n def __init__(self,size):\r\n self.size = size\r\n self.grid = [[]]\r\n\r\n # Description: creates an empty board\r\n # Functionality: each cell is set to zero\r\n def create(self):\r\n self.grid = [[0 for i in range(self.size)] for x in range(self.size)]\r\n \r\n\r\n # Description: allows for a move to be played on the board like normal connect 4\r\n # Functionality: takes in a column index and player, then iterates through the\r\n # entire column until it either reaches the end of the column OR\r\n # reaches a spot that is already occupied.\r\n def moveDOWN(self, col, player):\r\n row = 0\r\n col -= 1\r\n while row < self.size:\r\n if self.grid[row][col] == 0:\r\n if row < self.size-1: row+=1\r\n else:\r\n self.grid[row][col] = player\r\n return True\r\n else:\r\n if row > 0:\r\n self.grid[row-1][col] = player\r\n return True\r\n else: return False\r\n \r\n # Description: allows for a move to be played through the left side of the board\r\n # Functionality: takes in a row index and player, then iterates through the entire\r\n # row going from LEFT to RIGHT.\r\n # Return: returns true if the move was played, false otherwise.\r\n def moveLEFT(self, row, player):\r\n col = 0\r\n row -= 1\r\n while col < self.size:\r\n if self.grid[row][col] == 0:\r\n if col < self.size-1: col += 1\r\n else:\r\n self.grid[row][col] = player\r\n return True\r\n else:\r\n if col > 0:\r\n self.grid[row][col-1] = player\r\n return True\r\n else: return False\r\n\r\n # Description: allows for a move to be played through the right side of the board\r\n # Functionality: takes in a row index and player, then iterates through the entire\r\n # row going from RIGHT to LEFT.\r\n # Return: returns true if the move was played, false otherwise.\r\n def moveRIGHT(self, row, player):\r\n col = self.size-1\r\n row -= 1\r\n while col >= 0:\r\n if self.grid[row][col] == 0:\r\n if col > 0: col -= 1\r\n else:\r\n self.grid[row][col] = player\r\n return True\r\n else:\r\n if col <= self.size-2:\r\n self.grid[row][col+1] = player\r\n return True\r\n else: return False\r\n \r\n # Description: checks for direction and calls one of the directional move functions\r\n # Functionality: takes in a direction (LEFT, RIGHT, or DOWN), a position (row or column\r\n # depending on the chosen direction), and the player playing the move.\r\n # Return: returns true if the move was played, false otherwise.\r\n def move(self, direction, pos, player):\r\n if 0 < pos and pos < self.size+1:\r\n if direction == LEFT: return self.moveLEFT(pos, player)\r\n elif direction == RIGHT: return self.moveRIGHT(pos, player)\r\n else: return self.moveDOWN(pos, player)\r\n else:\r\n print(pos, \"is not a valid row or column.\")\r\n return False\r\n\r\n # Description: determines the winner if one exists\r\n # Functionality: uses brute force algorithms to check if there is a winner in 4 different\r\n # directions: HORIZONTAL, VERTICAL, DIAGNAL UP, or DIAGONAL DOWN.\r\n # Return: returns the winning player if there exists one. Otherwise, returns NOWINNER.\r\n def winnerExists(self, player):\r\n # horizontal winning conditions\r\n pcount = 0\r\n for row in range(self.size):\r\n for col in range(self.size):\r\n if self.grid[row][col] == player: pcount += 1\r\n else: pcount = 0\r\n if pcount == 4:\r\n print(\"horizontal\")\r\n return player\r\n pcount = 0\r\n\r\n # vertical winning conditions\r\n pcount = 0\r\n for row in range(self.size):\r\n for col in range(self.size):\r\n if self.grid[col][row] == player: pcount += 1\r\n else: pcount = 0\r\n if pcount == 4:\r\n print(\"vertical\")\r\n return player\r\n pcount = 0\r\n\r\n # diagonal up winning conditions\r\n for row in range(self.size-3):\r\n for col in range(self.size-3):\r\n if self.grid[row][col] == player and self.grid[row][col] == self.grid[row+1][col+1] and self.grid[row][col] == self.grid[row+2][col+2] and self.grid[row][col] == self.grid[row+3][col+3]:\r\n print(\"diagonal up\")\r\n return player\r\n \r\n # diagonal down winning conditions\r\n for row in range(self.size-3):\r\n for col in range(self.size-1, 1, -1):\r\n if self.grid[row][col] == player and self.grid[row][col] == self.grid[row+1][col-1] and self.grid[row][col] == self.grid[row+2][col-2] and self.grid[row][col] == self.grid[row+3][col-3]:\r\n print(\"diagonal down\")\r\n return player\r\n\r\n return NOWINNER\r\n\r\n # Description: checks if a tie/draw exists\r\n # Functionality: checks if the perimeter of the board is filled\r\n # Return: returns true if a tie/draw exists and false otherwise\r\n def tieExists(self):\r\n borderLeft = 0\r\n borderRight = 0\r\n borderTop = 0\r\n # checks if the borders of the board are filled\r\n for i in range(self.size):\r\n if self.grid[i][0] != NOWINNER: borderLeft += 1\r\n if self.grid[i][5] != NOWINNER: borderRight += 1\r\n if self.grid[0][i] != NOWINNER: borderTop += 1\r\n # If they are, return true. Otherwise return false.\r\n if borderLeft == 6 and borderRight == 6 and borderTop == 6: return True\r\n else: return False\r\n\r\n # Description: prints the entire board\r\n # Functionality: iterates through entire board and prints a \"O\" if player 1 made a move\r\n # and \"X\" if player 2 made a move.\r\n # Return: returns nothing\r\n def printBoard(self):\r\n for i in range(50): print()\r\n for i in range(self.size): print(\" \", end=\"\")\r\n print(\" Board\")\r\n for i in range(self.size): print(\" \", i+1, end=\"\")\r\n print()\r\n for i in range(self.size):\r\n print(i+1,end=\"\")\r\n for j in range(self.size):\r\n if self.grid[i][j] == 0: print(\" . \", end=\"\")\r\n elif self.grid[i][j] == PLAYER1: print(\" O \", end=\"\")\r\n elif self.grid[i][j] == PLAYER2: print(\" X \", end=\"\")\r\n print(i+1)\r\n print(\"\\n\")\r\n\r\n # Description: allows players to play the game\r\n # Functionality: the game runs infinitely until a winner is found or a tie\r\n # is determined.\r\n # Return: returns nothing\r\n def playGame(self):\r\n turn = 0\r\n winner = NOWINNER\r\n\r\n # While the game hasnt ended yet\r\n while True:\r\n # player 1\r\n # choose a direction and play a valid move\r\n print(\"PLAYER 1's TURN\")\r\n direction = input(\"Choose a direction to play on DOWN = D, LEFT = L, RIGHT = R: \").lower()\r\n while (direction != DOWN and direction != LEFT and direction != RIGHT):\r\n direction = input(\"INVALID DIRECTION!\\nChoose a direction to play on DOWN = 'D', LEFT = 'L', RIGHT = 'R': \")\r\n if direction == DOWN: print(\"DIRECTION: DOWN\")\r\n elif direction == LEFT: print(\"DIRECTION: LEFT\")\r\n elif direction == RIGHT: print(\"DIRECTION: RIGHT\")\r\n user = int(input(\"Pick a row or column from 1 to 6 to play on: \"))\r\n # keep prompting if move is invalid or occupied\r\n while self.move(direction, user, PLAYER1) == False:\r\n print(\"Column or row is full. Choose different column or row.\\n\")\r\n user = int(input(\"Pick a column from 1 to 6 to play on: \"))\r\n # print board and check if player 1 won. If so, break to end game.\r\n turn += 1\r\n print(\"\\nTurn \", turn)\r\n self.printBoard()\r\n if self.winnerExists(PLAYER1) != NOWINNER: break\r\n if self.tieExists(): break\r\n \r\n print(\"PLAYER 2's TURN\")\r\n direction = input(\"Choose a direction to play on DOWN = D, LEFT = L, RIGHT = R: \").lower()\r\n while (direction != DOWN and direction != LEFT and direction != RIGHT):\r\n direction = input(\"INVALID DIRECTION!\\nChoose a direction to play on DOWN = 'D', LEFT = 'L', RIGHT = 'R': \")\r\n if direction == DOWN: print(\"DIRECTION: DOWN\")\r\n elif direction == LEFT: print(\"DIRECTION: LEFT\")\r\n elif direction == RIGHT: print(\"DIRECTION: RIGHT\")\r\n user = int(input(\"Pick a row or column from 1 to 6 to play on: \"))\r\n # keep prompting if move is invalid or occupied\r\n while self.move(direction, user, PLAYER2) == False:\r\n print(\"Column or row is full. Choose different column or row.\\n\")\r\n user = int(input(\"Pick a column from 1 to 6 to play on: \"))\r\n # print board and check if player 2 won. If so, break to end game.\r\n turn += 1\r\n print(\"\\nTurn \", turn)\r\n self.printBoard()\r\n if self.winnerExists(PLAYER2) != NOWINNER: break\r\n if self.tieExists(): break\r\n\t # end while \r\n\r\n # check winner\r\n if self.winnerExists(PLAYER1) == PLAYER1: print(\"PLAYER 1 wins\")\r\n elif self.winnerExists(PLAYER2) == PLAYER2: print(\"PLAYER 2 wins\")\r\n \r\n# Description: main\r\n# Functionality: builds the game by creating a new board object and calling\r\n# createm printBoard, and playGame.\r\n# returns nothing\r\ndef main():\r\n b = Board(6)\r\n b.create()\r\n b.printBoard()\r\n print(\"CONNECT 4\")\r\n b.playGame()\r\n\r\nmain()\r\n","sub_path":"Connect_4_Python/Connect4.py","file_name":"Connect4.py","file_ext":"py","file_size_in_byte":10781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"56969261","text":"from pyMCDS import pyMCDS\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append('./Calib_ki67')\nfrom rk4 import rk4\n\ndef KI67_Basic ( t, rf, Par ):\n Q = rf[0]\n K = rf[1]\n \n r01 = Par[0] #1.0/(4.59*60.0)\n r10 = Par[1] #1.0/(15.5*60.0)\n \n dQdt = -r01 * Q + 2*r10 * K\n dKdt = r01 * Q - r10 * K\n \n drfdt = np.array ( [ dQdt, dKdt] )\n\n return drfdt\n\ndef Model(Par,Oxygen):\n Po2 = Oxygen\n tspan = np.array ( [ 0.0, 12000.0 ] )\n InitialCond = np.array ( [ 497.0, 0.0] )\n n = 50\n time = np.zeros((len(Po2),n+1))\n QOI1 = np.zeros((len(Po2),n+1))\n QOI2 = np.zeros((len(Po2),n+1))\n ParLocal = np.copy(Par)\n #sigma_S = ParLocal[2]\n #sigma_T = ParLocal[3]\n sigma_S = 38.0\n sigma_T = 6.0\n for index in range( 0,len(Po2) ):\n rate = 1.0\n if(Po2[index] <= sigma_T): rate = 0.0\n else: \n if(Po2[index] < sigma_S): rate = ((Po2[index] - sigma_T)/(sigma_S - sigma_T))**Par[2]\n ParLocal[0] = Par[0]*rate\n t, ODE_out = rk4 ( KI67_Basic, tspan, InitialCond, n, ParLocal )\n QOI1[index,:] = ODE_out[:,0]/(ODE_out[:,0]+ODE_out[:,1])\n QOI2[index,:] = ODE_out[:,1]/(ODE_out[:,0]+ODE_out[:,1])\n time = t\n MeanQoi1 = QOI1.mean(axis = 0)\n StdQoi1 = QOI1.std(axis = 0)\n MeanQoi2 = QOI2.mean(axis = 0)\n StdQoi2 = QOI2.std(axis = 0) \n return time,MeanQoi1,MeanQoi2,StdQoi1,StdQoi2\n\ninitial_index = 0;\nlast_index = 200;\nKi67neg_count = np.zeros( last_index+1 );\nKi67pos_count = np.zeros( last_index+1 );\ndead_count = np.zeros( last_index+1 );\ntimes = np.zeros( last_index+1 );\nOxygen = np.zeros(50)\n\n# Col1, Col2, Col3 = [], [], []\n# for line in open('DataProl.dat', 'r'):\n # values = [float(s) for s in line.split()]\n # Col1.append(values[0])\n # Col2.append(values[1])\n # Col3.append(values[2])\n\nfor n in range( initial_index,last_index+1 ):\n filename='output'+\"%08i\"%n+'.xml'\n mcds=pyMCDS(filename,'output')\n times[n]= mcds.get_time()\n \n cycle = mcds.data['discrete_cells']['cycle_model']\n cycle = cycle.astype( int )\n current_phase = mcds.data['discrete_cells']['current_phase']\n current_phase = current_phase.astype(int)\n elapsed_time_in_phase = mcds.data['discrete_cells']['elapsed_time_in_phase']\n cell_type = mcds.data['discrete_cells']['cell_type']\n cell_type = cell_type.astype(int)\n Ki67neg = np.argwhere( (cycle < 100) & (cell_type==0) & (current_phase == 3) ).flatten()\n Ki67pos = np.argwhere( (cycle < 100) & (cell_type==0) & (current_phase == 2)).flatten()\n dead = np.argwhere( (cycle >= 100) & (cell_type==0) ).flatten()\n \n print(\"Ki67-: \"+str(len(Ki67neg))+\" Ki67+: \"+str(len(Ki67pos))+\" dead: \"+str(len(dead)) +\" Total: \"+ str(len(cell_type)))\n total = len(Ki67neg)+len(Ki67pos)\n Ki67neg_count[n] = len(Ki67neg)/total\n Ki67pos_count[n] = len(Ki67pos)/total\n #dead_count[n] = len(dead)/len(cell_type)\n for i in range( 0,len(Oxygen) ):\n y_pos = i*20\n Oxygen[i] = mcds.get_concentrations_at(x=0., y=y_pos, z=0.)\n\nPar = np.array([0.0010,0.0017, 0.2857])\ntimeModel, Qoi1, Qoi2, StdQoi1, StdQoi2 = Model(Par,Oxygen)\n \nplt.ylabel('Cell fraction')\nplt.xlabel('Time (hours)')\nplt.plot( times/60.0,Ki67neg_count,c='blue',label='Ki67-')\nplt.plot( times/60.0,Ki67pos_count,c='black',label='Ki67+')\n#plt.plot( times/60.0,dead_count,c='red',label='Dead')\nplt.errorbar( timeModel/60.0,Qoi1,yerr=StdQoi1,c='blue',linestyle='dashed',label='ODE_Ki67-')\nplt.errorbar( timeModel/60.0,Qoi2,yerr=StdQoi2,c='black',linestyle='dashed',label='ODE_Ki67+')\nplt.legend()\nplt.show()\n","sub_path":"PhysiCell-161Calib/plottingHR_proliferation.py","file_name":"plottingHR_proliferation.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"498991424","text":"#!/usr/local/bin/python3\nimport nltk\nimport json\nimport numpy as np\nimport time\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom scipy.sparse import csr_matrix, hstack\n#from sklearn.naive_bayes import MultinomialNB\n#from sklearn.linear_model import SGDClassifier\n#from sklearn.pipeline import Pipeline\n#import csv\nfrom sklearn.svm import SVC\nimport argparse\nimport logging\n\n\n\nmin_df = 3\nmax_df = .9\nngram = 2\n#kernel = 'rbf'\nkernel = 'linear'\n\nmassive_dictionary={}\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n\ndef tokenize(text):\n tokens = nltk.word_tokenize(text)\n return tokens \n\n\ndef main():\n parser=argparse.ArgumentParser()\n parser.add_argument(\"-i\",action=\"store\",help=\"input directory\")\n parser.add_argument(\"-t\",action=\"store_true\",help=\"include topics\")\n try:\n args=parser.parse_args()\n except IOError:\n pass\n inDir=args.i\n\n addTopics=False\n if args.t is not None and args.t:\n addTopics=True\n \n \n justTrainingText=[]\n justTestingText=[]\n justTrainingSent=[]\n justTestingSent=[]\n with open(inDir+'/raw_train_tweet_details.json','r',encoding = 'utf-8') as jf:\n tweet_json = json.load(jf)\n keys=list(tweet_json.keys())\n keys=[int(i) for i in keys]\n keys=sorted(keys)\n logging.debug(\"keys: \" + str(keys))\n for k in keys:\n justTrainingText.append(tweet_json[str(k)]['Unfiltered Text'])\n justTrainingSent.append(tweet_json[str(k)]['Sentiment'])\n with open(inDir+'/raw_test_tweet_details.json','r',encoding = 'utf-8') as jf:\n tweet_json = json.load(jf)\n keys=list(tweet_json.keys())\n keys=[int(i) for i in keys]\n keys=sorted(keys)\n for k in keys:\n justTestingText.append(tweet_json[str(k)]['Unfiltered Text'])\n justTestingSent.append(tweet_json[str(k)]['Sentiment'])\n\n vectorizer = TfidfVectorizer(tokenizer=tokenize, min_df =min_df, \n max_df=max_df, stop_words='english',ngram_range=(1,ngram)) \n \n X_train_vector = vectorizer.fit_transform(justTrainingText)\n logging.debug(\"X_train_vector has type: \" + str(type(X_train_vector)))\n Y_train_target = justTrainingSent\n logging.debug(\"Y_train_target has type: \" + str(type(Y_train_target)))\n X_test_vector = vectorizer.transform(justTestingText)\n Y_test_target = justTestingSent\n\n if addTopics:\n with open(inDir+'/training_set.json','r',encoding='utf-8') as jf:\n allT=json.load(jf)\n all_sparse=csr_matrix(allT)\n logging.debug(\"X_train_vector has shape: \" + str(X_train_vector.shape))\n X_train_vector=hstack([X_train_vector,all_sparse])\n logging.debug(\"X_train_vector now has shape: \" + str(X_train_vector.shape))\n\n with open(inDir+'/testing_set.json','r',encoding='utf-8') as jf:\n allT=json.load(jf)\n all_sparse=csr_matrix(allT)\n logging.debug(\"X_test_vector has shape: \" + str(X_test_vector.shape))\n X_test_vector=hstack([X_test_vector,all_sparse])\n logging.debug(\"X_test_vector now has shape: \" + str(X_test_vector.shape))\n \n #SVM Approach\n clf = SVC(kernel=kernel)\n tic = time.time()\n clf.fit(X_train_vector, Y_train_target)\n tic2 = time.time()\n print('Training Time: ' + str(tic2-tic))\n predictions = clf.predict(X_test_vector)\n SVMaccuracy = np.mean(predictions == Y_test_target)\n print('Testing Time: ' + str(time.time()- tic2))\n print('Accuracy: ' + str(SVMaccuracy))\n\n confusion = np.zeros((2,2))\n for k in range(0, len(predictions)):\n confusion[int(Y_test_target[k])][int(predictions[k])] += 1\n \n filename = kernel + '_' + str(X_train_vector.shape[0]) + '_' + str(X_test_vector.shape[0]) + '_' + str(min_df) + '_' + str(int(max_df*100)) + '_' + str(ngram) + '.csv'\n np.savetxt(filename, confusion, delimiter=',')\n\n import pdb; pdb.set_trace() # breakpoint 118243a1 //\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple_svm3.py","file_name":"simple_svm3.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"1655378","text":"import pkg.foundation.display as display\nimport pkg.foundation.essentials as essentials\n\n# Mini Game 1\nimport pygame\nimport random\nimport csv\n\nfrom .sprites import *\nfrom .settings import *\nfrom os import path\n\nrunning = True\npygame = essentials.pygame\n\nall_sprites = None\nplayer = None\nwalls = None\nbed = None\nbars = None\njaildoor = None\ntoilet = None\nexits = None\nbackground = None\nbackground_rect = None\nspeech_balloon_object = None\njailDoor = None\n\ninteraction_mark1 = None\ninteraction_mark2 = None\ninteraction_mark3 = None\ninteraction_mark4 = None\nkey_obtained = None\nvisible_speech_balloon = None\nhighlighted_answer = None\n\nbed_scenario = None\ntoilet_scenario = None\nmob_scenario = None\n\nreader = None\n\ndef run ():\n global running\n global pygame\n\n global visible_speech_balloon\n global speech_balloon\n global interaction_mark1\n global interaction_mark2\n global interaction_mark3\n global interaction_mark4\n global key_obtained\n\n global bed_scenario\n global toilet_scenario\n global mob_scenario\n global player\n global highlighted_answer\n\n display.set_title('Level 1')\n\n new()\n load_data()\n\n while running:\n display.prepare_update()\n\n # Input\n for event in pygame.event.get():\n running = essentials.run_essentials(event)\n if not running:\n return True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n if visible_speech_balloon:\n if multiple_choice_answers:\n if highlighted_answer > highlighted_answer_minimum_boundary:\n highlighted_answer -= 1\n \n if event.key == pygame.K_b:\n pygame.mixer.Channel(1).stop()\n return True\n \n if event.key == pygame.K_DOWN:\n if visible_speech_balloon:\n if multiple_choice_answers:\n if highlighted_answer < highlighted_answer_maximum_boundary:\n highlighted_answer += 1\n\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_RETURN:\n if visible_speech_balloon:\n if speech_balloon_object.scenario == 1: # I don't have to go...\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 2 and highlighted_answer == 4: # Do you want to play a game?;Answer 3 questions...;and I'll hand over the key --> Yes\n bed_scenario = 3\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 2 and highlighted_answer == 5: # Do you want to play a game?;Answer 3 questions...;and I'll hand over the key --> No\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 3: # Here is my first question:;The person who knows he uses;it, doesn't know he uses it.;What is it?\n bed_scenario = 4\n multiple_choice_answers = True\n highlighted_answer = 1\n highlighted_answer_minimum_boundary = 1\n highlighted_answer_maximum_boundary = 4\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 4 and highlighted_answer != 4: # Insurance;Necktie;Sugar;Coffin\n bed_scenario = 5\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 4 and highlighted_answer == 4: # Insurance;Necktie;Sugar;Coffin\n bed_scenario = 6\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 5: # WRONG!;Get used to being here,;cause you're going to be;here for a while...\n bed_scenario = 3\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 6: # That's correct.;Here's my next question:\n bed_scenario = 7\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 7: # Have you ever heard of a;dyslexic Satanist?\n bed_scenario = 8\n multiple_choice_answers = True\n highlighted_answer = 1\n highlighted_answer_minimum_boundary = 1\n highlighted_answer_maximum_boundary = 4\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 8 and highlighted_answer != 2: # They prey to Christ;He sold his soul to Santa;There are none;No\n bed_scenario = 9\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 8 and highlighted_answer == 2: # They prey to Christ;He sold his soul to Santa;There are none;No\n bed_scenario = 10\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 9: # You're wrong!;I guess you're not so smart;...\n bed_scenario = 7\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 10: # Okay. For my final game,;I want you to insult the;other inmate's mother.\n bed_scenario = 11\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 11: # We're gonna torture him;with the infamous your momma jokes.\n bed_scenario = 12\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 12: # Unfortunately for you,;I only know the setups,;you're gonna have to come;up with the punchlines\n bed_scenario = 13\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 13: # Go talk to the other inmate.\n bed_scenario = 10\n mob_scenario = 15\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 14: # Go away.;I have nothing to say.\n mob_scenario = 14\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 15: # Okay, here goes nothing... *\n mob_scenario = 16\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 16: # HEY YOU!;YO' MOMMA'S SO FAT...\n mob_scenario = 17\n multiple_choice_answers = True\n highlighted_answer = 1\n highlighted_answer_minimum_boundary = 1\n highlighted_answer_maximum_boundary = 3\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 17 and highlighted_answer != 2: # ...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!;...SHE HAS MORE FOLDS,;THAN AN ORIGAMI ACCORDEON!;...IF SHE FELL IN NUCLEAR WASTE,;NO ONE WOULD NOTICE!\n mob_scenario = 18\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 17 and highlighted_answer == 2: # ...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!;...SHE HAS MORE FOLDS,;THAN AN ORIGAMI ACCORDEON!;...IF SHE FELL IN NUCLEAR WASTE,;NO ONE WOULD NOTICE!\n mob_scenario = 19\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 18: # Stop talking trash!;You suck at this!\n mob_scenario = 15\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 19: # Not a word about my mother!;She's a saint.\n mob_scenario = 20\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 20: # YO' MOMMA'S SO RADIANT...\n mob_scenario = 21\n multiple_choice_answers = True\n highlighted_answer = 1\n highlighted_answer_minimum_boundary = 1\n highlighted_answer_maximum_boundary = 3\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 21 and highlighted_answer != 1: # ...IF SHE FELL IN NUCLEAR WASTE,;NO ONE WOULD NOTICE!;...SHE BRINGS COUPONS TO;THE PENNY ARCADE!;...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!\n mob_scenario = 22\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 21 and highlighted_answer == 1: # ...IF SHE FELL IN NUCLEAR WASTE,;NO ONE WOULD NOTICE!;...SHE BRINGS COUPONS TO;THE PENNY ARCADE!;...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!\n mob_scenario = 23\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 22: # You ain't hurtin nobody,;you little bitch!\n mob_scenario = 15\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 23: # Ahhh, it hurts...;IT HURTS!\n mob_scenario = 24\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 24: # YO' MOMMA'S SO PUNCTUAL...\n mob_scenario = 25\n multiple_choice_answers = True\n highlighted_answer = 1\n highlighted_answer_minimum_boundary = 1\n highlighted_answer_maximum_boundary = 3\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 25 and highlighted_answer != 2: # ...SHE BRINGS COUPONS TO;THE PENNY ARCADE!;...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!;...THE ONLY TIME SHE'S LOW;IS AT A LIMBO CONTEST!\n mob_scenario = 26\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 25 and highlighted_answer == 2: # ...SHE BRINGS COUPONS TO;THE PENNY ARCADE!;...SHE SHOWED UP EARLY;FOR HER OWN FUNERAL!;...THE ONLY TIME SHE'S LOW;IS AT A LIMBO CONTEST!\n mob_scenario = 27\n multiple_choice_answers = False\n highlighted_answer = 0\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n elif speech_balloon_object.scenario == 26: # You had your chance,;now FUCK OFF!\n mob_scenario = 15\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 27: # Enough, enough!; I'm suffocating...;sob.. sob... *\n mob_scenario = 28\n bed_scenario = 30\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, 29)\n\n elif speech_balloon_object.scenario == 28: # I'm done talking to you;Leave me alone...\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 29: # Now to claim the key;and get the fuck outta here! *\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 30: # Man...;I had the time of my life!!;Didn't know you had it in ya!\n bed_scenario = 31\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 31: # Unfortunately for you,;I don't have the key on me,;but I'm sure that you little;POTTY mouth;will know where to find it.\n bed_scenario = 30\n toilet_scenario = 32\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 32: # GROSS...;;* key obtained *\n toilet_scenario = 33\n bed_scenario = 34\n key_obtained = True\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 33: # I already got the key...\n visible_speech_balloon = False\n player.can_walk = True\n\n elif speech_balloon_object.scenario == 34: # Drop by anytime pal.\n bed_scenario = 35\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n elif speech_balloon_object.scenario == 35: # Wouldn't count on it \"pal\" *\n bed_scenario = 34\n visible_speech_balloon = False\n player.can_walk = True\n\n # Output\n pygame.mixer.init()\n pygame.font.init()\n font = pygame.font.Font(FONT, 19)\n font2 = pygame.font.Font(FONT, 13)\n\n if player.speedx or player.speedy > 0:\n all_sprites.remove(interaction_mark1, interaction_mark2, interaction_mark3, interaction_mark4)\n all_sprites.remove(speech_balloon)\n\n # for interaction with the bed \"object\"\n if player.rect.x >= 930 and player.rect.y <= 222:\n\n if player.keys[pygame.K_SPACE]:\n player.can_walk = False\n visible_speech_balloon = True\n if bed_scenario == 2:\n multiple_choice_answers = True\n highlighted_answer = 4\n highlighted_answer_minimum_boundary = 4\n highlighted_answer_maximum_boundary = 5\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, bed_scenario)\n\n # for interaction with the toilet\n if (player.rect.x >= 640 and player.rect.x <= 772) and player.rect.y <= 150:\n if player.keys[pygame.K_SPACE]:\n visible_speech_balloon = True\n player.can_walk = False\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, toilet_scenario)\n\n # for interaction with the bars of the player's cell\n if player.rect.x == 622:\n if player.keys[pygame.K_SPACE]:\n visible_speech_balloon = True\n player.can_walk = False\n if key_obtained == True:\n all_sprites.remove(bars)\n bars.remove(jailDoor)\n elif key_obtained == False:\n speech_balloon_object.choose_scenario(visible_speech_balloon, reader, mob_scenario)\n\n\n hits_wall = pygame.sprite.spritecollide(player, walls, False)\n if hits_wall:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n\n hits_bed = pygame.sprite.spritecollide(player, bed, False)\n if hits_bed:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n\n if player.speedx == 0:\n all_sprites.add(interaction_mark2)\n\n\n if player.speedy == 0:\n all_sprites.add(interaction_mark2)\n\n\n\n hits_bars = pygame.sprite.spritecollide(player, bars, False)\n if hits_bars:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n\n if key_obtained == False:\n if player.speedx == 0:\n all_sprites.add(interaction_mark1)\n if player.speedy == 0:\n all_sprites.add(interaction_mark1)\n if player.keys[pygame.K_SPACE]:\n key_obtained = False\n\n else:\n all_sprites.remove(bars)\n bars.remove(jailDoor)\n\n hits_jaildoor = pygame.sprite.spritecollide(player, jaildoor, False)\n if hits_jaildoor:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n\n\n hits_toilet = pygame.sprite.spritecollide(player, toilet, False)\n if hits_toilet:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n if player.speedx == 0:\n all_sprites.add(interaction_mark3)\n\n\n if player.speedy == 0:\n all_sprites.add(interaction_mark3)\n\n\n hits_exit = pygame.sprite.spritecollide(player, exits, False)\n if hits_exit:\n player.rect.x = player.rect.x - player.speedx\n player.rect.y = player.rect.y - player.speedy\n return True\n\n display.window.blit(background, background_rect)\n all_sprites.draw(display.window)\n\n if visible_speech_balloon:\n all_sprites.add(speech_balloon)\n Text(speech_balloon_object, font, font2, reader, highlighted_answer)\n else:\n all_sprites.remove(speech_balloon)\n all_sprites.update()\n\n display.update()\n\ndef tutorial():\n global pygame\n\n tutorial = True\n instruction = pygame.image.load(\"pkg/level1/images/instructions_screen.jpg\")\n while tutorial:\n\n display.prepare_update()\n\n # Input\n for event in pygame.event.get():\n # Load in the fundemental functions in the game\n tutorial = essentials.run_essentials(event)\n if not tutorial:\n return False\n\n if event.type == pygame.KEYDOWN:\n return True\n\n # Output\n display.window.blit(instruction, (0,0))\n display.update()\n\ndef load_data():\n global background\n global background_rect\n global reader\n\n dir = path.dirname(__file__)\n image_dir = path.join(dir, 'images')\n script_dir = path.join(dir, 'scripts')\n music_dir = path.join(dir, 'music')\n\n # load spritesheet image\n spritesheet = Spritesheet(path.join(image_dir, SPRITESHEET))\n\n # load game background\n background = pygame.image.load(path.join(image_dir, BACKGROUND)).convert()\n background_rect = background.get_rect()\n\n # load music\n pygame.mixer.Channel(1).play(pygame.mixer.Sound('files/music/minigame1_soundtrack.ogg'))\n\n # load script\n with open(path.join(script_dir, SCRIPT)) as csv_file:\n reader = list(csv.reader(csv_file, delimiter = ';'))\n total_rows = len(reader)\n\ndef new():\n # start a new game\n global all_sprites\n global player\n global walls\n global bed\n global bars\n global jaildoor\n global toilet\n global exits\n global speech_balloon_object\n global jailDoor\n\n global visible_speech_balloon\n global speech_balloon\n global interaction_mark1\n global interaction_mark2\n global interaction_mark3\n global interaction_mark4\n global key_obtained\n global highlighted_answer\n\n global bed_scenario\n global toilet_scenario\n global mob_scenario\n\n all_sprites = pygame.sprite.Group()\n walls = pygame.sprite.Group()\n bed = pygame.sprite.Group()\n bars = pygame.sprite.Group()\n exits = pygame.sprite.Group()\n jaildoor = pygame.sprite.Group()\n interaction_mark = pygame.sprite.Group()\n toilet = pygame.sprite.Group()\n player = Player(visible_speech_balloon)\n mob = pygame.sprite.Group()\n speech_balloon = pygame.sprite.Group()\n text = pygame.sprite.Group()\n all_sprites.add(player, walls, bed, bars, jaildoor, exits, interaction_mark, toilet, mob, speech_balloon, text)\n visible_speech_balloon = False\n multiple_choice_answers = False\n highlighted_answer = 0\n highlighted_answer_minimum_boundary = 0\n highlighted_answer_maximum_boundary = 0\n remove_textbox = False\n key_obtained = False\n toilet_scenario = 1\n bed_scenario = 2\n mob_scenario = 14\n start_screen_visible = True\n\n # upper wall in player cell\n wall1 = Walls(619, 0, 600, 50)\n # right wall in player cell\n wall2 = Walls(1219, 0, 70, 706)\n # the bars in the other cell\n wall3 = Walls(198, 0, 15, 720)\n # the lowest wall in player cell\n wall4 = Walls(619, 705, 661, 15)\n # the bed object in player cell\n bedObject = Bed(994, 33, 210, 180)\n # the upper bars \"object\" in player cell\n barsObjectUp = Bars(605, 0, 15, 263)\n # the lower bars \"object\" in player cell\n barsObjectDown = Bars(605, 477, 15, 243)\n # the exit on the top\n exitUp = Exits(213, -70, 391, 5)\n # the exit on the down\n exitDown = Exits(213, 790, 391, 5)\n # the door of the player's cell\n jailDoor = Jaildoor()\n # the guy in the other cell\n mob1 = Mob(130, 360)\n # the toilet in the player's cell\n toilet1 = Toilet(700, 50)\n # the toilet in the other cell\n toilet2 = Toilet(70, 50)\n # the interaction mark for the bars in the player's cell\n interaction_mark1 = InteractionMark(150, 300, 8, 8)\n # the interaction mark for the bed \"object\" in the player's cell\n interaction_mark2= InteractionMark(960, 5, 8, 8)\n # the interaction mark for the toilet\n interaction_mark3= InteractionMark(700, 5, 8, 8)\n # the interaction mark for the unlocked door\n interaction_mark4= InteractionMark(575, 280, 8, 8)\n # the speech balloon\n speech_balloon_object = SpeechBalloon(300, 490, 300, 300)\n\n all_sprites.add(wall1, wall2, wall3, wall4, bedObject, barsObjectUp, barsObjectDown, jailDoor, exitUp, exitDown, toilet1, toilet2, mob1)\n walls.add(wall1, wall2, wall3, wall4)\n exits.add(exitUp, exitDown)\n bed.add(bedObject)\n bars.add(barsObjectUp, barsObjectDown, jailDoor)\n toilet.add(toilet1, toilet2)\n speech_balloon.add(speech_balloon_object)\n","sub_path":"pkg/level1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599228590","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index),\n path('post_list/', views.post_list),\n path('test/', views.data_return),\n path('cnn/',views.cnn),\n path('pso/',views.pso)\n]\n\n\n#from django.conf.urls import url\n#from mysite import settings\n#from . import views\n#from django.conf.urls.static import static\n\n\n#app_name = 'mysite' \n\n#urlpatterns = [\n# url(r'^$', views.index, name='index'),\n# url(r'^post_list$', views.post_list, name='post_list'),\n# url(r'^test/$', views.data_return, name='data_return'),\n# ]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237706348","text":"class Solution:\n def isValid(self, s: str) -> bool:\n stack = collections.deque()\n d = {')':'(', '}':'{', ']':'['}\n for i in s:\n val = d.get(i)\n if stack and val == stack[-1]:\n stack.pop()\n else:\n stack.append(i)\n \n if stack:\n return False\n else:\n return True\n","sub_path":"LeetCode-Sol/Easy/20-Valid-Parentheses.py","file_name":"20-Valid-Parentheses.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"624434081","text":"# -*- coding: utf-8 -*-\n#\n# ツイートハンドラ\n#\n\nimport json\nimport logging\nimport traceback\nfrom lib.config import PathConfig\nfrom datetime import datetime\n\n\nclass TweetHandle:\n def __init__(self):\n self.lastid = -1\n self.sinceid = -1\n\n logging.basicConfig(filename=PathConfig.PATH_LOGOUTPUT,\n level=logging.INFO) # ログの出力先とレベル\n\n # --ツイートを解析してユーザデータおよび画像ファイルのパスを取得\n def handle(self, tweets):\n # infoで一段挟んでるのは静的なツイート情報が必要になったときの予約←今になって効きましたね…\n rst = {\"datalist\": [], \"info\": {\"followers\": -1, \"TwitterID\":\"\", \"UserName\": \"\"}}\n\n logs = []\n\n for tweet in tweets:\n data = {'id': -1, 'timestamp': -1, 'text': \"\", 'image': []}\n try:\n entities = tweet['extended_entities']\n\n # --静的なユーザ情報を取得\n rst['info']['followers'] = tweet['user']['followers_count']\n rst['info']['TwitterID'] = tweet['user']['screen_name'];\n rst['info']['UserName'] = tweet['user']['name'];\n\n # --画像付きツイートの場合はパスとfav数を収集\n if('media' in entities):\n # --保存画質を設定\n prioPts = float(tweet['favorite_count']) / float(tweet['user']['followers_count'])\n followers = tweet['user']['followers_count']\n quality = self.getQuality(prioPts, followers) # 画質パラメータ(0:skip 1:low 2:high 3:highest)\n data['likes'] = quality\n\n # --URLを追加\n for media in entities['media']:\n data['image'].append(media['media_url_https'])\n\n # --ツイートの文字、日時を抽出\n data['id'] = tweet['id']\n data['text'] = tweet['text']\n data['timestamp'] = datetime.strptime(\n tweet['created_at'], '%a %b %d %H:%M:%S %z %Y').timestamp()\n rst['datalist'].append(data)\n\n except KeyError:\n # --ここでは何もしない(キーエラーは「画像のないツイート」に対して実行されるので)\n pass\n except Exception as e:\n logging.error(str(int(datetime.now().timestamp())) +\n \": [TweetHandle(internal)] \" + str(e))\n print(tweets)\n print(traceback.format_exc())\n\n return rst\n\n # --保存画質を計算\n def getQuality(self, prioPts, followers):\n quality = 1\n if(prioPts < 0.03):\n if(prioPts >= 0.01):\n quality = 1\n else:\n quality = 0\n else:\n if(followers >= 600):\n if(prioPts >= 0.03 and prioPts <= 0.15):\n quality = 2\n else:\n quality = 3\n else:\n if(prioPts >= 0.03 and prioPts <= 0.05):\n quality = 1\n else:\n if(prioPts <= 0.2):\n quality = 2\n else:\n quality = 1\n\n return quality\n","sub_path":"lib/TweetHandle.py","file_name":"TweetHandle.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"525839080","text":"# %%\nfrom scipy import signal\nfrom scipy import fftpack\nimport scipy.linalg as al\nimport scipy\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n# import matplotlib.image as mpimg\nfrom PIL import Image\n\n############################\n\n# 有待解决疑问——为什么实验指导里的定义是从 -N/2 开始?\n\n\ndef PSNR(_img1, _img2):\n N, M = _img1.shape[0], _img1.shape[1]\n diff = np.abs(_img1 - _img2)\n a = np.sum(diff ** 2) / (N * M * 255 ** 2)\n return - 10 * np.log10(a)\n\n\ndef H(N, M, T=5, a=1, b=1):\n res = np.zeros((N, M))\n tmp = 0.\n for u in range(1, N + 1):\n for v in range(1, M + 1):\n tmp = np.pi * (a * u + b * v)\n res[u - 1][v - 1] = T / tmp * \\\n np.sin(tmp) * np.exp(-np.complex(0, 1) * tmp)\n return res\n\n\ndef plot(_X, _title=None):\n fig = plt.figure()\n plt.suptitle(_title)\n x, y = np.linspace(0, _X.shape[0], _X.shape[0]), np.linspace(\n 0, _X.shape[1], _X.shape[1])\n X, Y = np.meshgrid(x, y)\n Z = _X\n sub = fig.add_subplot(1, 1, 1, projection='3d')\n sub.plot_surface(X, Y, Z)\n sub.set_xlabel('X')\n sub.set_ylabel('Y')\n sub.set_zlabel('Z')\n plt.show(sub)\n\n\ndef show(_img, _title=None):\n plt.figure()\n plt.suptitle(_title)\n plt.imshow(_img, cmap='gray')\n plt.show()\n\n\n############################\nimg = np.array(Image.open(\n 'Lenna.png'))[:, :, 0]\nshow(img, 'original')\n\nsigma = 0.05\nmu = 0\nimg = img + sigma * np.random.randn(img.shape[0], img.shape[1]) + mu\nshow(img, \"img with noise\")\n\n\nH_ = H(img.shape[0], img.shape[1])\nplot(np.abs(H_), 'H(u,v) amp')\nplot(np.angle(H_), 'H(u,v) phase')\nF_img = fftpack.fft2(img)\nG = H_ * F_img # 2-d的dft相乘时域也是圆周卷积吗??\nG_r = fftpack.ifft2(G)\nshow(np.abs(G_r), 'After H(u,v)')\n# %%\n# 反向滤波\nr0 = [1, 0.8, 0.5, 0.3]\nfor r in r0:\n xs = int(r * H_.shape[0])\n ys = int(r * H_.shape[1])\n H__ = np.ones(H_.shape)\n H__[:xs, :ys] = H_[:xs, :ys]\n img_rev = fftpack.ifft2(G / H__)\n psnr = PSNR(img_rev, img)\n show(np.abs(img_rev), 'Inverse Filter : r0 = {} : PSNR = {} dB'.format(r, psnr))\n\n# %%\n# 维纳滤波\nK = np.array([0.1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-10]) * sigma\nfor k in K:\n img_wiener = signal.wiener(G_r, noise=k)\n psnr = PSNR(img_wiener, img)\n show(np.abs(img_wiener), 'Wiener Filter : K = {} : PSNR = {} dB'.format(k, psnr))\n","sub_path":"Python/DIP/dip2.py","file_name":"dip2.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"285972811","text":"__author__ = 'SherlockLiao'\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchvision import datasets\nimport time\n\n# 定义超参数\nbatch_size = 32 # 每次拿出来多少个样本进行训练\nlearning_rate = 1e-3 # +1e-3表示1*10^-3,即0.001 e的负3次方是exp(3)\n\nnum_epoches = 100 # x训练次数\n\n# mnist 的数据结构 http://blog.csdn.net/qq_32166627/article/details/62218072 在这个里面有说明,\n# pytorch 已经对这些数据做了处理\n\n# 下载训练集 MNIST 手写数字训练集\ntrain_dataset = datasets.MNIST(\n root='./data', # 数据保存的路径\n train=True, # 是否为训练数据还是测试数据\n transform=transforms.ToTensor(), # 把数据转化为 tensor 格式,便于数据使用存储\n download=True # 是否下载,如果已经下载完成,会自动跳过\n)\n\ntest_dataset = datasets.MNIST(\n root='./data', train=False, transform=transforms.ToTensor())\n\n# DataLoader 批量数据训练的包装类\ntrain_loader = DataLoader(\n train_dataset, # 处理使用的数据集\n batch_size=batch_size, # 每次batch 加载的样本数量\n num_workers=2, # 加载数据的使用几个线程\n shuffle=True # 每次训练取数据的时候,是否随机打乱顺序\n)\n\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\n\n# 定义神经网络模型\n# 定义为简单三层结构\nclass NeuralNetwork(nn.Module):\n def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):\n super(NeuralNetwork, self).__init__()\n self.layer1 = nn.Linear(in_dim, n_hidden_1)\n self.layer2 = nn.Linear(n_hidden_1, n_hidden_2)\n self.layer3 = nn.Linear(n_hidden_2, out_dim)\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n return x\n\n\n# in_dim 数据的维度\n# n_class 分类数量\n\n\nmodel = NeuralNetwork(28 * 28, 500, 200, 10) # 图片大小是28x28\nuse_gpu = torch.cuda.is_available() # 判断是否有GPU加速\nif use_gpu:\n model = model.cuda()\n# 定义loss和optimizer\ncriterion = nn.CrossEntropyLoss() # 交叉熵\noptimizer = optim.SGD(model.parameters(), lr=learning_rate) # 随机梯度下降\n\n# 开始训练\nfor epoch in range(num_epoches):\n startTime = time.time()\n\n print('epoch {}'.format(epoch + 1))\n print('*' * 10)\n running_loss = 0.0 # 本次训练累加损失函数的值\n running_acc = 0.0 # 本次训练累加正确率的值\n\n # 每次都是根据 batch_size 来小批量处理的,要注意累加和乘以总数\n for i, data in enumerate(train_loader, 1):\n img, label = data # train data 里面包含有两部分数据库,一部分是处理后的图片数据,一部分是表情 label 数据\n imgSize = img.size(0) # 矩阵中第0维的大小,如果不带参数,就是矩阵的大小\n img = img.view(imgSize, -1) # 将图片展开成 28x28 ,view 类似于 reshape的用法,改变数组/矩阵的形状 -1表示自动分配计算\n if use_gpu:\n img = Variable(img).cuda()\n label = Variable(label).cuda()\n else:\n img = Variable(img)\n label = Variable(label)\n # 向前传播\n out = model(img) # out 计算我们预测值 ?? 这里描述的不准确,可以认为就是预测出来了一组数据\n loss = criterion(out, label) # 计算损失函数/ loss/误差 比较预测的值和实际值的误差\n temp_loss = loss.data[0] * label.size(0) # loss 是个 variable,所以取 data,因为 loss 是算出来的平均值,所以乘上数量得到总的\n running_loss = running_loss + temp_loss # temp_loss 是计算的本次小批量的值,要累加才是合计的\n\n # torch.max 返回输入张量给定维度上每行的最大值,并同时返回每个最大值的位置索引。\n # 这里 1 表示取列上面的最大值,如果是0 就会按照行来取值\n # pred 是索引的位置,一共有10个索引位置,算出来哪个位置的概率最大,这个值就是这个索引位置\n _, pred = torch.max(out, 1)\n\n num_correct = (pred == label).sum() # (pred == label) 比较相同位置上面值,如果相等就是1,否则就是0. sum 之后,就算出来了有多少个正确的了\n running_acc = running_acc + num_correct.data[0] # 累计正确的数量\n\n # 向后传播\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if i % 300 == 0: # 每300次打印一下\n l = batch_size * i # 样本数量\n tempRunningLoss = running_loss / l # 当前损失函数的值 合计/样本数量\n tempRunningAcc = running_acc / l # 当前的正确率 正确的数量/样本数量\n\n print('[{}/{}] Loss: {:.6f}, Acc: {:.6f}'.format(epoch + 1, num_epoches, tempRunningLoss, tempRunningAcc))\n\n length = len(train_dataset) # 所有的样本数量\n finishRunningLoss = running_loss / length # 最终损失函数的值 合计/样本数量\n finishRunningAcc = running_acc / length # 最终的正确率 正确的数量/样本数量\n\n print('Finish {} epoch, Loss: {:.6f}, Acc: {:.6f}'.format(epoch + 1, finishRunningLoss, finishRunningAcc))\n\n endTime = time.time()\n\n print('consuming time:{}'.format(endTime - startTime))\n\n# 修改为测试验证模式\nmodel.eval()\n\neval_loss = 0.\neval_acc = 0.\nfor data in test_loader:\n img, label = data\n img = img.view(img.size(0), -1)\n if use_gpu:\n img = Variable(img, volatile=True).cuda()\n label = Variable(label, volatile=True).cuda()\n else:\n img = Variable(img, volatile=True)\n label = Variable(label, volatile=True)\n out = model(img)\n loss = criterion(out, label)\n eval_loss = eval_loss + loss.data[0] * label.size(0)\n _, pred = torch.max(out, 1)\n num_correct = (pred == label).sum()\n eval_acc = eval_acc + num_correct.data[0]\n\ntestLength = len(test_dataset) # 测试样本的数量\ntestLoss = eval_loss / testLength\ntestAcc = eval_acc / testLength\n\nprint('Test Loss: {:.6f}, Acc: {:.6f}'.format(testLoss, testAcc))\nprint()\n\n# 保存模型\ntorch.save(model.state_dict(), './logstic.pth')\n","sub_path":"03-Neural Network/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"19322445","text":"#coding=utf-8\nimport requests, time, json, random, sys, pickle, os\n\nurl_play='https://bestvapi.bestv.cn/video/video_rate?'\n\n\nheader={'User-Agent': 'BesTV/4 CFNetwork/901.1 Darwin/17.6.0',\n'Host': 'bestvapi.bestv.cn',\n'Accept-Language':'zh-cn',\n'Accept-Encoding': 'br, gzip, deflate',\n'Connection':'keep-alive',\n'version': '3.1.3',\n'Accept':'*/*',\n'release': '1',\n'channel': 'standard',\n'app': 'ios',\n'Content-Type': 'text/html',}\n\npara_play={'app':'ios',\n 'vid':'1988563',\n 'fdn_code':'FDNB3925445',\n 'token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkZXZpY2VJZCI6ImQyMTU1NGIyLWI4OGYtMzliMS1hZWMyLTk1MTg5Zjg3ZDhkYyIsInRpbWVzdGFtcCI6MTU0MTk4ODIzOCwiY2hhbm5lbElkIjoiNTRhMjZkNDEtYTBkMi00MDVhLWIwMWEtMjgwZjU0OWQ4YjFlIn0.hL7vujWzBXgiA2em1g2VHyC9_8JTz5XY1nvfCMjB7TY'}\n\ndef play(vid):\n time.sleep(random.uniform(1, 2))\n para_play['vid'] = vid\n req = requests.get(url_play, params=para_play, headers=header)\n c = json.loads(req.text)\n statu=c['code']\n\n if statu==0:\n return '0' #非VIP\n elif statu==40004:\n return '1' #VIP\n else:\n return '1'\n\nidenty = open('bestvip.txt', encoding='utf-8').readlines()\nvip = open('vip_result.txt', 'w', encoding='utf-8')\nif os.path.exists('vip_result.txt'):\n queue = pickle.load(open(\"queue.pkl\", \"rb\"))\n print(\"上次进度已加载!\")\nelse:\n queue = set()\nbar_length = 50\nfor num,ide in identy:\n if ide not in queue:\n queue.add(ide)\n try:\n vid = ide.strip()\n print(''.join([vid, '~',play(vid)]), file=vip)\n except:\n queue.remove()\n pickle.dump(queue, open(\"queue.pkl\",\"wb\"))\n if (num+1) % 5 == 0 or (num+1) == len(identy):\n hashes = '#' * int((num+1)/len(identy) * bar_length)\n spaces = ' ' * (bar_length - len(hashes))\n sys.stdout.write(\"\\r获取进度: [{}] {}% \\n\".format(hashes + spaces, round((num+1)*100/len(identy))))\n sys.stdout.flush()\nidenty.close()\nvip.close()\n\n","sub_path":"Proj_App/VideoSite/bestv_search_VIP.py","file_name":"bestv_search_VIP.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"280976617","text":"\"\"\"\n Tipos Numericos reservados del lenguaje SQL 'T_'\n\"\"\"\nr_types = {\n \"SMALLINT\": \"T_SMALLINT\",\n \"INTEGER\": \"T_INTEGER\",\n \"BIGINT\": \"T_BIGINT\",\n \"DECIMAL\": \"T_DECIMAL\",\n \"NUMERIC\": \"T_NUMERIC\",\n \"REAL\": \"T_REAL\",\n \"DOUBLE\": \"T_DOUBLE\",\n \"PRECISION\": \"T_PRECISION\",\n \"MONEY\": \"T_MONEY\",\n \"CHARACTER\": \"T_CHARACTER\",\n \"VARYING\": \"T_VARYING\",\n \"VARCHAR\": \"T_VARCHAR\",\n \"CHAR\": \"T_CHAR\",\n \"TEXT\": \"T_TEXT\",\n \"DATE\": \"T_DATE\",\n \"TIME\": \"T_TIME\",\n \"BOOLEAN\": \"T_BOOLEAN\",\n}\n\n\"\"\"\n Palabras reservadas del lenguaje SQL 'R_'\n\"\"\"\nreservadas = {\n \"CREATE\": \"R_CREATE\",\n \"REPLACE\": \"R_REPLACE\",\n \"TABLE\": \"R_TABLE\",\n \"DATABASE\": \"R_DATABASE\",\n \"TYPE\": \"R_TYPE\",\n \"AS\": \"R_AS\",\n \"ENUM\": \"R_ENUM\",\n \"INHERITS\": \"R_INHERITS\",\n \"IF\": \"R_IF\",\n \"EXISTS\": \"R_EXISTS\",\n \"CHECK\": \"R_CHECK\",\n \"UNIQUE\": \"R_UNIQUE\",\n \"KEY\": \"R_KEY\",\n \"PRIMARY\": \"R_PRIMARY\",\n \"FOREIGN\": \"R_FOREIGN\",\n \"REFERENCES\": \"R_REFERENCES\",\n \"CONSTRAINT\": \"R_CONSTRAINT\",\n \"DEFAULT\": \"R_DEFAULT\",\n \"NULL\": \"R_NULL\",\n \"NULLS\": \"R_NULLS\",\n \"OWNER\": \"R_OWNER\",\n \"MODE\": \"R_MODE\",\n \"ALTER\": \"R_ALTER\",\n \"RENAME\": \"R_RENAME\",\n \"TO\": \"R_TO\",\n \"CURRENT_USER\": \"R_CURRENT_USER\",\n \"SESSION_USER\": \"R_SESSION_USER\",\n \"ADD\": \"R_ADD\",\n \"DROP\": \"R_DROP\",\n \"COLUMN\": \"R_COLUMN\",\n \"SELECT\": \"R_SELECT\",\n \"DISTINCT\": \"R_DISTINCT\",\n \"UNION\": \"R_UNION\",\n \"INTERSECT\": \"R_INTERSECT\",\n \"EXCEPT\": \"R_EXCEPT\",\n \"EXTRACT\": \"R_EXTRACT\",\n \"FROM\": \"R_FROM\",\n \"TIMESTAMP\": \"R_TIMESTAMP\",\n \"INTERVAL\": \"R_INTERVAL\",\n \"YEAR\": \"R_YEAR\",\n \"MONTH\": \"R_MONTH\",\n \"DAY\": \"R_DAY\",\n \"HOUR\": \"R_HOUR\",\n \"MINUTE\": \"R_MINUTE\",\n \"SECOND\": \"R_SECOND\",\n \"DATE_PART\": \"R_DATE_PART\",\n \"NOW\": \"R_NOW\",\n \"CURRENT_DATE\": \"R_CURRENT_DATE\",\n \"CURRENT_TIME\": \"R_CURRENT_TIME\",\n \"BETWEEN\": \"R_BETWEEN\",\n \"NOT\": \"R_NOT\",\n \"AND\": \"R_AND\",\n \"OR\": \"R_OR\",\n \"SYMMETRIC\": \"R_SYMMETRIC\",\n \"IS\": \"R_IS\",\n \"ISNULL\": \"R_ISNULL\",\n \"NOTNULL\": \"R_NOTNULL\",\n \"TRUE\": \"R_TRUE\",\n \"FALSE\": \"R_FALSE\",\n \"UNKNOWN\": \"R_UNKNOWN\",\n \"LIKE\": \"R_LIKE\",\n \"ALL\": \"R_ALL\",\n \"ANY\": \"R_ANY\",\n \"SOME\": \"R_SOME\",\n \"IN\": \"R_IN\",\n \"JOIN\": \"R_JOIN\",\n \"ON\": \"R_ON\",\n \"USING\": \"R_USING\",\n \"NATURAL\": \"R_NATURAL\",\n \"INNER\": \"R_INNER\",\n \"LEFT\": \"R_LEFT\",\n \"OUTER\": \"R_OUTER\",\n \"RIGHT\": \"R_RIGHT\",\n \"FULL\": \"R_FULL\",\n \"WHERE\": \"R_WHERE\",\n \"GROUP\": \"R_GROUP\",\n \"BY\": \"R_BY\",\n \"HAVING\": \"R_HAVING\",\n \"ORDER\": \"R_ORDER\",\n \"ASC\": \"R_ASC\",\n \"DESC\": \"R_DESC\",\n \"FIRST\": \"R_FIRST\",\n \"LAST\": \"R_LAST\",\n \"OFFSET\": \"R_OFFSET\",\n \"LIMIT\": \"R_LIMIT\",\n \"INSERT\": \"R_INSERT\",\n \"INTO\": \"R_INTO\",\n \"VALUES\": \"R_VALUES\",\n \"UPDATE\": \"R_UPDATE\",\n \"SET\": \"R_SET\",\n \"DELETE\": \"R_DELETE\",\n \"TRUNCATE\": \"R_TRUNCATE\",\n \"SHOW\": \"R_SHOW\",\n \"DATABASES\": \"R_DATABASES\",\n \"USE\": \"R_USE\",\n \"SUM\": \"R_SUM\",\n \"PROM\": \"R_PROM\",\n \"COUNT\": \"R_COUNT\",\n \"CASE\": \"R_CASE\",\n \"WHEN\": \"R_WHEN\",\n \"THEN\": \"R_THEN\",\n \"ELSE\": \"R_ELSE\",\n \"END\": \"R_END\",\n}\n\nreservadas.update(r_types)\n\n\"\"\"\n Lista de tokens a reconocer:\n 'O_': Operadores\n 'OL_': Operadores Logicos\n 'OC_': Operadores de Cadena Binarias\n 'S_': Simbolos\n\"\"\"\ntokens = [\n # Operadores\n \"O_SUMA\",\n \"O_RESTA\",\n \"O_PRODUCTO\",\n \"O_DIVISION\",\n \"O_EXPONENTE\",\n \"O_MODULAR\",\n # Operadores Logicos\n \"OL_ESIGUAL\",\n \"OL_DISTINTODE\",\n \"OL_MAYORQUE\",\n \"OL_MENORQUE\",\n \"OL_MAYORIGUALQUE\",\n \"OL_MENORIGUALQUE\",\n # Operadores de cadena\n \"OC_CONCATENAR\",\n \"OC_AND\",\n \"OC_OR\",\n \"OC_XOR\",\n \"OC_NOT\",\n \"OC_SHIFTL\",\n \"OC_SHIFTR\",\n # Simbolos\n \"S_PARIZQ\",\n \"S_PARDER\",\n \"S_COMA\",\n \"S_PUNTOCOMA\",\n \"S_PUNTO\",\n \"S_IGUAL\",\n # Tokens\n \"ID\",\n \"DECIMAL\",\n \"INTEGER\",\n \"COMMENT\",\n \"STRING\",\n \"CHARACTER\",\n] + list(reservadas.values())\n\n\"\"\"\n Reguex para el reconocimiento de los tokens\n\"\"\"\nt_O_SUMA = r\"\\+\"\nt_O_RESTA = r\"-\"\nt_O_PRODUCTO = r\"\\*\"\nt_O_DIVISION = r\"/\"\nt_O_EXPONENTE = r\"\\^\"\nt_O_MODULAR = r\"%\"\n\nt_OL_DISTINTODE = r\"!=|<>\"\nt_OL_MAYORQUE = r\">\"\nt_OL_MENORQUE = r\"<\"\nt_OL_MAYORIGUALQUE = r\">=\"\nt_OL_MENORIGUALQUE = r\"<=\"\n\nt_OC_CONCATENAR = r\"\\|\\|\"\nt_OC_AND = r\"&\"\nt_OC_OR = r\"\\|\"\nt_OC_XOR = r\"\\#\"\nt_OC_NOT = r\"~\"\nt_OC_SHIFTL = r\"<<\"\nt_OC_SHIFTR = r\">>\"\n\nt_S_PARIZQ = r\"\\(\"\nt_S_PARDER = r\"\\)\"\nt_S_COMA = r\",\"\nt_S_PUNTOCOMA = r\";\"\nt_S_PUNTO = r\"\\.\"\nt_S_IGUAL = r\"=\"\n\n\"\"\"\n Caracteres ignorados por el lexer\n\"\"\"\nt_ignore = \" \\t\"\n\n# Funcion para evaluar si el token reconocido es un ID\ndef t_ID(t):\n r\"[a-zA-Z_][a-zA-Z_0-9]*\"\n # Verificamos si no es una palabra reservada\n t.type = reservadas.get(t.value.upper(), \"ID\")\n if t.type != \"ID\":\n t.value = t.value.upper()\n else:\n t.value = t.value.lower()\n return t\n\n\n# Funcion para evaluar si el token reconocido es un DECIMAL\ndef t_DECIMAL(t):\n r\"\\d+\\.\\d+(e(-|\\+)?\\d+)?|\\d+(e(-|\\+)?\\d+)\"\n try:\n t.value = float(t.value)\n except ValueError:\n print(\"No se pudo convertir %d\", t.value)\n t.value = 0\n return t\n\n\n# Funcion para evaluar si el token reconocido es un INTEGER\ndef t_INTEGER(t):\n r\"\\d+\"\n try:\n t.value = int(t.value)\n except ValueError:\n print(\"Integer value too large %d\", t.value)\n t.value = 0\n return t\n\n\n# Funcion para evaluar si el token reconocido es un CHARACTER\ndef t_CHARACTER(t):\n r\"(\\\"\\\\?.\\\"|\\'\\\\?.\\')\"\n t.value = t.value[1:-1]\n return t\n\n\n# Funcion para evaluar si el token reconocido es un STRING\ndef t_STRING(t):\n r\"(\\'.*?\\'|\\\".*?\\\")\"\n t.value = t.value[1:-1] # remuevo las comillas\n return t\n\n\n# Funcion para evaluer si el token reconocido es un comentario\ndef t_COMMENT(t):\n r\"\\-\\-(.*)\\n|/\\*(.|\\n)*?\\*/\"\n t.lexer.lineno += t.value.count(\"\\n\")\n t.lexer.skip(0)\n\n\n# Funcion para obsorver los enters\ndef t_newline(t):\n r\"\\n+\"\n t.lexer.lineno += t.value.count(\"\\n\")\n\n\nsyntax_errors = list()\n\n# Funcion de error para el lexer\ndef t_error(t):\n \"\"\" print(\"Illegal character '%s'\" % t.value[0]) \"\"\"\n syntax_errors.insert(\n len(syntax_errors), [\"Illegal character '%s'\" % t.value[0], t.lineno]\n )\n t.lexer.skip(1)\n\n\ndef returnLexicalErrors():\n global syntax_errors\n temp = syntax_errors\n syntax_errors = list()\n return temp\n","sub_path":"parser/fase2/team17/Ejecucion/Fase1/analizer/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"59529974","text":"from random import random,randint,choice\nfrom page import Page\nfrom printer import instance as printer\nimport colours\nfrom points import add_points\n\ndef colour_print(text):\n return colours.colour_print(text, colours.Background.RED, colours.Foreground.BLACK)\n\n\nclass NamePage(Page):\n def __init__(self, name, large=True,extra=\"\"):\n super(NamePage, self).__init__(\"???\")\n self.name = name\n self.title = \"Greeting\"\n self.large = large\n self.extra = extra\n self.duration_sec = 5\n self.reload()\n\n def generate_content(self):\n extra = \"\"\n name = self.name\n from page import greetings\n\n greeting = greetings.random()\n if \"Rafael\" in name:\n if random()<0.6:\n greeting = \"Muy Feo\"\n add_points(\"Gryffindor\",-1)\n extra = \"\\n\\n-1 points to Gryffindor!\"\n\n if random() < 0.01:\n name = \"Jigsaw\"\n add_points(\"Slytherin\",10)\n\n extra = \"\\n\\n10 points to Slytherin!\"\n if random() < 0.01:\n name = \"Fake Belgin\"\n add_points(\"Squiberin\",10)\n\n extra = \"\\n\\n10 points to Squiberin!\"\n extra += \"\\n\\n\"+self.extra\n self.content = colour_print(printer.text_to_ascii(greeting))\n self.content += \"\\n\\n\"\n if self.large: self.content += colour_print(printer.text_to_ascii(name + \"!\"))\n else: self.content += name\n self.content += extra\n","sub_path":"page/NamePage.py","file_name":"NamePage.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"602006134","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport json\nimport argparse\nimport model_factory\nfrom torch.autograd import Variable\n\n\ndef main():\n image_path, checkpoint, top_k, category_names, gpu = get_input_args()\n\n with open(category_names, 'r') as f:\n cat_to_name = json.load(f)\n\n model = model_factory.load_trained_model(checkpoint)\n idx_to_class = {i:k for k, i in model.class_to_idx.items()}\n\n probs, classes = predict(image_path, model, idx_to_class, top_k, gpu)\n\n for prob, classe in zip(probs, classes):\n print(cat_to_name[classe], prob)\n\n\ndef get_input_args():\n parser = argparse.ArgumentParser(description='description')\n\n parser.add_argument('image_path',\n metavar='image_path',\n type=str,\n help='Image path')\n\n parser.add_argument('checkpoint',\n metavar='checkpoint',\n default='./cli_checkpoint.pth',\n type=str,\n help='checkpoint')\n\n parser.add_argument('--top_k',\n type=int,\n default=5,\n help='Top k most likely classes')\n \n parser.add_argument('--category_names',\n type=str,\n default='./cat_to_name.json',\n help='Mapping of categories to real names')\n\n parser.add_argument('--gpu',\n action='store_true',\n help='Use gpu')\n\n \n args = parser.parse_args()\n\n if args.gpu == True and torch.cuda.is_available() == False:\n args.gpu = False\n print(\"GPU is not avaliable\")\n \n if args.gpu == False and torch.cuda.is_available() == True:\n print(\"GPU avaliable. You should use it\")\n\n return args.image_path, args.checkpoint, args.top_k, args.category_names, args.gpu\n\n\ndef predict(image_path, model, idx_to_class, topk, cuda):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n \n\n image = Image.open(image_path)\n image = process_image(image)\n image = torch.FloatTensor([image])\n \n if cuda:\n model.cuda()\n image = image.cuda()\n \n model.eval()\n\n output = model.forward(Variable(image))\n \n # top predictions\n if cuda:\n all_probs = torch.exp(output).data.cpu().numpy()[0]\n else:\n all_probs = torch.exp(output).data.numpy()[0]\n topk_index = np.argsort(all_probs)[-topk:][::-1] \n topk_class = [idx_to_class[x] for x in topk_index]\n topk_prob = all_probs[topk_index]\n \n return topk_prob, topk_class\n\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n \n # resize shortest side to 256\n width, height = image.size\n if height > width:\n new_width = 256\n new_height = int(np.floor(256 * height / width))\n elif height < width:\n new_width = int(np.floor(256 * height / width))\n new_height = 256\n image = image.resize((new_width, new_height))\n \n # crop out the center 224x224 \n left = (new_width - 224)/2\n top = (new_height - 224)/2\n right = (new_width + 224)/2\n bottom = (new_height + 224)/2\n image = image.crop((left, top, right, bottom))\n \n # normalize\n image = np.array(image)\n image = image/255\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = (image - mean) / std\n \n # reorder layers\n image = image.transpose(2, 0, 1)\n \n return image\n\n\n\n# Call to main function to run the program\nif __name__ == \"__main__\":\n main()\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516739039","text":"import time\nimport numpy as np\nimport skfuzzy as fuzz\nimport matplotlib.pyplot as plt\nfrom random import randrange\n\nsensor_left = 0\nsensor_front = 0\nsensor_right = 0\nsensor_back = 0\n\nMAX_DISTANCE = 300\nMAX_SPEED = 30\nSENSOR_DISTANCE_SPACE = np.arange(0, 121, 1)\nSPEED_SPACE = np.arange(0, 31, 1)\n\nx_dist_front = SENSOR_DISTANCE_SPACE\nx_dist_right = SENSOR_DISTANCE_SPACE\nx_dist_left = SENSOR_DISTANCE_SPACE\nx_dist_back = SENSOR_DISTANCE_SPACE\n\nx_speed_left = SPEED_SPACE\nx_speed_right = SPEED_SPACE\n\ndist_front_1 = fuzz.trapmf(x_dist_front, [0, 0, 10, 20])\ndist_front_2 = fuzz.trapmf(x_dist_front, [10, 20, 20, 40])\ndist_front_3 = fuzz.trapmf(x_dist_front, [20, 40, MAX_DISTANCE, MAX_DISTANCE])\n\ndist_right_1 = fuzz.trapmf(x_dist_right, [0, 0, 10, 20])\ndist_right_2 = fuzz.trapmf(x_dist_right, [10, 20, 20, 40])\ndist_right_3 = fuzz.trapmf(x_dist_right, [20, 40, MAX_DISTANCE, MAX_DISTANCE])\n\ndist_left_1 = fuzz.trapmf(x_dist_left, [0, 0, 10, 20])\ndist_left_2 = fuzz.trapmf(x_dist_left, [10, 20, 20, 40])\ndist_left_3 = fuzz.trapmf(x_dist_left, [20, 40, MAX_DISTANCE, MAX_DISTANCE])\n\ndist_back_1 = fuzz.trapmf(x_dist_back, [0, 0, 10, 20])\ndist_back_2 = fuzz.trapmf(x_dist_back, [10, 20, 20, 40])\ndist_back_3 = fuzz.trapmf(x_dist_back, [20, 40, MAX_DISTANCE, MAX_DISTANCE])\n\nspeed_left_1 = fuzz.trimf(x_speed_left, [0, 0, 5])\nspeed_left_2 = fuzz.trimf(x_speed_left, [0, 5, 15])\nspeed_left_3 = fuzz.trapmf(x_speed_left, [5, 15, MAX_SPEED, MAX_SPEED])\n\nspeed_right_1 = fuzz.trimf(x_speed_right, [0, 0, 5])\nspeed_right_2 = fuzz.trimf(x_speed_right, [0, 5, 15])\nspeed_right_3 = fuzz.trapmf(x_speed_right, [5, 15, MAX_SPEED, MAX_SPEED])\n\n'''\nfig, (ax0, ax1, ax2, ax3) = plt.subplots(nrows=4, figsize=(8, 9))\n\nax0.plot(x_dist_front, dist_front_1, 'b', linewidth=1.5, label='1')\nax0.plot(x_dist_front, dist_front_2, 'g', linewidth=1.5, label='2')\nax0.plot(x_dist_front, dist_front_3, 'r', linewidth=1.5, label='3')\nax0.set_title('Front Distance')\nax0.legend()\n\nax1.plot(x_dist_right, dist_right_1, 'b', linewidth=1.5, label='1')\nax1.plot(x_dist_right, dist_right_2, 'g', linewidth=1.5, label='2')\nax1.plot(x_dist_right, dist_right_3, 'r', linewidth=1.5, label='3')\nax1.set_title('Right Distance')\nax1.legend()\n\nax2.plot(x_dist_left, dist_left_1, 'b', linewidth=1.5, label='1')\nax2.plot(x_dist_left, dist_left_2, 'g', linewidth=1.5, label='2')\nax2.plot(x_dist_left, dist_left_3, 'r', linewidth=1.5, label='3')\nax2.set_title('Left Distance')\nax2.legend()\n\nax3.plot(x_dist_back, dist_back_1, 'b', linewidth=1.5, label='1')\nax3.plot(x_dist_back, dist_back_2, 'g', linewidth=1.5, label='2')\nax3.plot(x_dist_back, dist_back_3, 'r', linewidth=1.5, label='3')\nax3.set_title('Back Distance')\nax3.legend()\n\n# Turn off top/right axes\nfor ax in (ax0, ax1, ax2, ax3):\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n\nplt.tight_layout()\nplt.show()\n'''\n\n'''\nif the distance at the front is close, turn to the direction with the the most far distance\nif the distance at the front-right is close, turn to the left\nif the distance at the front-left is close, turn to the right\nif the distance at the front, left, and right is close, go backward\n'''\n\nwhile True:\n sensor_left = randrange(1, MAX_DISTANCE)\n sensor_front = randrange(1, MAX_DISTANCE)\n sensor_right = randrange(1, MAX_DISTANCE)\n sensor_back = randrange(1, MAX_DISTANCE)\n\n dist_front_1_level = fuzz.interp_membership(x_dist_front, dist_front_1, sensor_front)\n dist_front_2_level = fuzz.interp_membership(x_dist_front, dist_front_2, sensor_front)\n dist_front_3_level = fuzz.interp_membership(x_dist_front, dist_front_3, sensor_front)\n\n dist_right_1_level = fuzz.interp_membership(x_dist_right, dist_right_1, sensor_right)\n dist_right_2_level = fuzz.interp_membership(x_dist_right, dist_right_2, sensor_right)\n dist_right_3_level = fuzz.interp_membership(x_dist_right, dist_right_3, sensor_right)\n\n dist_left_1_level = fuzz.interp_membership(x_dist_left, dist_left_1, sensor_left)\n dist_left_2_level = fuzz.interp_membership(x_dist_left, dist_left_2, sensor_left)\n dist_left_3_level = fuzz.interp_membership(x_dist_left, dist_left_3, sensor_left)\n\n dist_back_1_level = fuzz.interp_membership(x_dist_back, dist_back_1, sensor_back)\n dist_back_2_level = fuzz.interp_membership(x_dist_back, dist_back_2, sensor_back)\n dist_back_3_level = fuzz.interp_membership(x_dist_back, dist_back_3, sensor_back)\n\n left_motor_lo = np.fmin(np.fmin(dist_front_1_level, dist_left_1_level), speed_left_1)\n left_motor_mid = np.fmin(np.fmin(dist_front_2_level, dist_left_2_level), speed_left_2)\n left_motor_hi = np.fmin(np.fmin(dist_front_3_level, dist_left_3_level), speed_left_3)\n\n right_motor_lo = np.fmin(np.fmin(dist_front_1_level, dist_right_1_level), speed_left_1)\n right_motor_mid = np.fmin(np.fmin(dist_front_2_level, dist_right_2_level), speed_left_2)\n right_motor_hi = np.fmin(np.fmin(dist_front_3_level, dist_right_3_level), speed_right_3)\n\n left_aggregated = np.fmax(left_motor_lo, np.fmax(left_motor_mid, left_motor_hi))\n right_aggregated = np.fmax(right_motor_lo, np.fmax(right_motor_mid, right_motor_hi))\n\n left_speed = fuzz.defuzz(x_speed_left, left_aggregated, 'mom')\n right_speed = fuzz.defuzz(x_speed_right, right_aggregated, 'mom')\n\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++')\n print('Left Sensor: %d | Front Sensor : %d | Right Sensor : %d' % (sensor_left, sensor_front, sensor_right))\n print('Left Motor : %d | Right Motor : %d' % (left_speed, right_speed))\n print('----------------------------------------------------')\n time.sleep(1)","sub_path":"PY/FuzzyAutoSteer1.py","file_name":"FuzzyAutoSteer1.py","file_ext":"py","file_size_in_byte":5677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"170546457","text":"from django.shortcuts import render\n# Create your views here.\nclass Booth_Multiply:\n\tdef __init__(self,multiplicand,multiplier,register):\n\t\tself.mcand,self.mplier = multiplicand,multiplier\n\t\tif int(multiplicand) < 0 and int(multiplier) > 0:\n\t\t\tmultiplicand,multiplier = self.balance(multiplicand,register),self.adjust(multiplier,register)\n\t\telif int(multiplicand) > 0 and int(multiplier) < 0: \n\t\t\tmultiplier,multiplicand = self.balance(multiplier,register), self.adjust(multiplicand,register)\n\t\telif int(multiplicand)<0 and int(multiplier)< 0:\n\t\t\tmultiplicand,multiplier = self.balance(multiplicand,register),self.balance(multiplier,register)\n\t\telse:\n\t\t\tmultiplicand,multiplier = map(lambda num:(int(register)-(len(bin(int(num)))-2))*\"0\"+bin(int(num))[2:],[multiplicand,multiplier])\n\t\tself.cand_arr,self.plier_arr,self.ac = [int(i) for i in multiplicand],[int(i) for i in multiplier],[0 for i in range(int(register))]\n\t\tself.cand_compl_arr = self.two_compliment(self.cand_arr)\n\t\tself.qend = 0\n\t\tself.register = register\n\tdef balance(self,arr,adj):\t\n\t\tarr = (int(adj)-(len(bin(int(arr)))-3))*\"0\"+bin(int(arr))[3:]\n\t\treturn ''.join(map(str,self.two_compliment(map(int,arr))))\n\tdef adjust(self,arr,adj):\n\t\treturn (int(adj)-(len(bin(int(arr)))-2))*\"0\"+bin(int(arr))[2:]\n\tdef calculate(self):\n\t\tfor i in range(int(self.register)):\n\t\t\tyield [self.ac],[self.plier_arr],[self.qend]\n\t\t\tif self.plier_arr[-1] > self.qend :\n\t\t\t\tself.ac = self.add_arr(self.cand_compl_arr,self.ac)\n\t\t\telif self.plier_arr[-1] < self.qend :\n\t\t\t\tself.ac = self.add_arr(self.cand_arr,self.ac)\n\t\t\tself.qend = self.plier_arr[-1]\n\t\t\tself.plier_arr = [self.ac[-1]]+[i for i in self.plier_arr[:-1]]\n\t\t\tself.ac = [self.ac[0]]+[i for i in self.ac[:-1]]\n\t\telse:\n\t\t\tif not (self.mcand < 0 and self.mplier < 0) and (self.mcand < 0 or self.mplier < 0):\n\t\t\t\tnum =\"-0b\"+''.join(map(str,self.two_compliment(self.ac+self.plier_arr)))\n\t\t\telse:\n\t\t\t\tnum = \"0b\"+''.join(map(str,self.ac+self.plier_arr))\n\t\t\tyield [self.ac],[self.plier_arr],[self.qend]\n\t\t\tyield eval(num)\t\n\tdef add_arr(self,one,two):\n\t\tcarry,ans = 0,[]\n\t\tfor i,j in zip(one[::-1],two[::-1]):\n\t\t\tans += [(i+j+carry)%2]\n\t\t\tcarry = (i+j+carry)/2\n\t\treturn ans[::-1]\n\tdef two_compliment(self,arr):\n\t\tretarr,rev = [],False\n\t\tfor i in arr[::-1]:\n\t\t\tif rev:\n\t\t\t\tretarr += [int(not i)]\n\t\t\telse:\n\t\t\t\tretarr += [i]\n\t\t\t\tif i:\n\t\t\t\t\trev = True\n\t\treturn retarr[::-1]\ndef calc(request):\n\tdisplay,gens,register,multiplicand,multiplier = False,None,0,0,0\n\tif request.method==\"POST\":\n\t\tregister = request.POST['register']\n\t\tmultiplicand,multiplier = request.POST['multiplicand'],request.POST['multiplier']\n\t\tdisplay = True\n\t\tbooth = Booth_Multiply(multiplicand,multiplier,register) \n\t\tgens = booth.calculate()\n\treturn render(request,'index.html',{'display':display,'gen':gens,'register':int(register),'mc':multiplicand,'mp':multiplier})\n","sub_path":"plagarismandbooth/booths/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"225292659","text":"# Python の pow() でも実装されている繰り返し二乗法のアルゴリズムでべき乗の計算を O(log N) で行う\ndef pow(x, n):\n '''x^n を返す'''\n res = 1\n time = 0\n while n > 0:\n time += 1\n if n % 2 == 1:\n res *= x\n x *= x\n n >>= 1\n print(f'時間計算量 : {time}')\n return res\n\n\nif __name__ == '__main__':\n print(pow(3, 8))\n","sub_path":"snippets/study/kurikaeshi_nijou.py","file_name":"kurikaeshi_nijou.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205163457","text":"import numpy as np\nfrom .. import stats_check\nfrom pyiid.experiments.elasticscatter.kernels.master_kernel import \\\n get_scatter_array, get_rw, get_chi_sq\n__author__ = 'christopher'\n\n\ndef test_get_scatter_array():\n scatter_array = np.loadtxt('pyiid/tests/test_master/c60_scat.txt',\n dtype=np.float32)\n ksa = np.zeros(scatter_array.shape)\n numbers = np.ones(len(ksa), dtype=np.int) * 6\n qbin = .1\n get_scatter_array(ksa, numbers, qbin)\n\n stats_check(scatter_array, ksa, rtol=1e-2)\n\n\ndef test_get_rw():\n x = np.arange(0, 2 * np.pi, .1)\n a = np.sin(x)\n b = np.cos(x)\n stats_check(get_rw(a, b)[0], 1)\n return\n\n\ndef test_get_rw2():\n x = np.arange(0, 2 * np.pi, .1)\n a = np.sin(x)\n b = np.sin(x)\n stats_check(0, get_rw(a, b)[0], atol=1e-15)\n return\n\n\ndef test_get_chi_sq():\n x = np.arange(0, 2 * np.pi, .1)\n a = np.sin(x)\n b = np.cos(x)\n stats_check(get_chi_sq(a, b)[0], 63.01399)\n return\n\n\ndef test_get_chi_sq2():\n x = np.arange(0, 2 * np.pi, .1)\n a = np.sin(x)\n b = np.sin(x)\n stats_check(0, get_chi_sq(a, b)[0], atol=1e-15)\n return\n","sub_path":"pyiid/tests/test_master/test_master_kernel.py","file_name":"test_master_kernel.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"240096064","text":"#Create a list\nuser_list = [\"Ani\", \"Manju\", \"Serah\", \"Evan\", \"Aji\", \"Raji\", \"Anu\", \"Soumya\"]\n\n#get the name input from the user\nprint(\"Hello! My name is Travis\")\nname = input(\"What is your name?: \").strip().capitalize()\n\n#check if the name is there in the list\n##if the name is there, ask if the user want it to be removed and act based on user response\nif name in user_list:\n response = input(\"Would you like your name to be removed from system? (y/n): \").strip().lower()\n if response == \"y\":\n user_list.remove(name)\n print(\"{}, Your name has been removed from the system\".format(name))\n elif response == \"n\":\n print(\"Sure {}, I will keep your name in the system\".format(name))\n else:\n print(\"oh! I don't recognise that response.. GoodBye!!\")\n \n##if the name is not there, ask if the user want it to be added and act based on user response\nelse:\n print(\"hmmm...Seems like you are a first time visitor here\")\n response = input(\"Would you like to add your name to the system? (y/n): \").strip().lower()\n if response == \"y\":\n user_list.append(name)\n print(\"{}, your name has been added to the system\".format(name))\n elif response == \"n\":\n print(\"OK {}, no worries, see you next time\".format(name))\n else:\n print(\"oh! I don't recognise that response.. GoodBye!!\")\n","sub_path":"lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"427373482","text":"from collections import namedtuple\n\nimport pkg_resources\nimport six\nimport yaml\n\nfrom dagster import check\nfrom dagster.core.definitions.utils import config_from_files, config_from_yaml_strings\nfrom dagster.core.errors import DagsterInvariantViolationError\nfrom dagster.seven import FileNotFoundError, ModuleNotFoundError # pylint:disable=redefined-builtin\nfrom dagster.utils import merge_dicts\nfrom dagster.utils.backcompat import canonicalize_backcompat_args\n\nfrom .mode import DEFAULT_MODE_NAME\n\n\nclass PresetDefinition(\n namedtuple('_PresetDefinition', 'name run_config solid_selection mode tags')\n):\n '''Defines a preset configuration in which a pipeline can execute.\n\n Presets can be used in Dagit to load predefined configurations into the tool.\n\n Presets may also be used from the Python API (in a script, or in test) as follows:\n\n .. code-block:: python\n\n execute_pipeline(pipeline_def, preset='example_preset')\n\n Presets may also be used with the command line tools:\n\n .. code-block:: shell\n\n $ dagster pipeline execute example_pipeline --preset example_preset\n\n Args:\n name (str): The name of this preset. Must be unique in the presets defined on a given\n pipeline.\n run_config (Optional[dict]): A dict representing the config to set with the preset.\n This is equivalent to the ``run_config`` argument to :py:func:`execute_pipeline`.\n solid_selection (Optional[List[str]]): A list of solid subselection (including single\n solid names) to execute with the preset. e.g. ``['*some_solid+', 'other_solid']``\n mode (Optional[str]): The mode to apply when executing this preset. (default: 'default')\n tags (Optional[Dict[str, Any]]): The tags to apply when executing this preset.\n '''\n\n def __new__(\n cls, name, run_config=None, solid_selection=None, mode=None, tags=None,\n ):\n\n return super(PresetDefinition, cls).__new__(\n cls,\n name=check.str_param(name, 'name'),\n run_config=run_config,\n solid_selection=check.opt_nullable_list_param(\n solid_selection, 'solid_selection', of_type=str\n ),\n mode=check.opt_str_param(mode, 'mode', DEFAULT_MODE_NAME),\n tags=check.opt_dict_param(tags, 'tags', key_type=str),\n )\n\n @staticmethod\n def from_files(\n name, environment_files=None, config_files=None, solid_selection=None, mode=None, tags=None\n ):\n '''Static constructor for presets from YAML files.\n\n Args:\n name (str): The name of this preset. Must be unique in the presets defined on a given\n pipeline.\n config_files (Optional[List[str]]): List of paths or glob patterns for yaml files\n to load and parse as the environment config for this preset.\n solid_selection (Optional[List[str]]): A list of solid subselection (including single\n solid names) to execute with the preset. e.g. ``['*some_solid+', 'other_solid']``\n mode (Optional[str]): The mode to apply when executing this preset. (default:\n 'default')\n tags (Optional[Dict[str, Any]]): The tags to apply when executing this preset.\n\n Returns:\n PresetDefinition: A PresetDefinition constructed from the provided YAML files.\n\n Raises:\n DagsterInvariantViolationError: When one of the YAML files is invalid and has a parse\n error.\n '''\n check.str_param(name, 'name')\n config_files = canonicalize_backcompat_args(\n config_files, 'config_files', environment_files, 'environment_files', '0.9.0'\n )\n config_files = check.opt_list_param(config_files, 'config_files')\n solid_selection = check.opt_nullable_list_param(\n solid_selection, 'solid_selection', of_type=str\n )\n mode = check.opt_str_param(mode, 'mode', DEFAULT_MODE_NAME)\n\n merged = config_from_files(config_files)\n\n return PresetDefinition(name, merged, solid_selection, mode, tags)\n\n @staticmethod\n def from_yaml_strings(name, yaml_strings=None, solid_selection=None, mode=None, tags=None):\n '''Static constructor for presets from YAML strings.\n\n Args:\n name (str): The name of this preset. Must be unique in the presets defined on a given\n pipeline.\n yaml_strings (Optional[List[str]]): List of yaml strings to parse as the environment\n config for this preset.\n solid_selection (Optional[List[str]]): A list of solid subselection (including single\n solid names) to execute with the preset. e.g. ``['*some_solid+', 'other_solid']``\n mode (Optional[str]): The mode to apply when executing this preset. (default:\n 'default')\n tags (Optional[Dict[str, Any]]): The tags to apply when executing this preset.\n\n Returns:\n PresetDefinition: A PresetDefinition constructed from the provided YAML strings\n\n Raises:\n DagsterInvariantViolationError: When one of the YAML documents is invalid and has a\n parse error.\n '''\n check.str_param(name, 'name')\n yaml_strings = check.opt_list_param(yaml_strings, 'yaml_strings', of_type=str)\n solid_selection = check.opt_nullable_list_param(\n solid_selection, 'solid_selection', of_type=str\n )\n mode = check.opt_str_param(mode, 'mode', DEFAULT_MODE_NAME)\n\n merged = config_from_yaml_strings(yaml_strings)\n\n return PresetDefinition(name, merged, solid_selection, mode, tags)\n\n @staticmethod\n def from_pkg_resources(\n name, pkg_resource_defs=None, solid_selection=None, mode=None, tags=None\n ):\n '''Load a preset from a package resource, using :py:func:`pkg_resources.resource_string`.\n\n Example:\n\n .. code-block:: python\n\n PresetDefinition.from_pkg_resources(\n name='local',\n mode='local',\n pkg_resource_defs=[\n ('dagster_examples.airline_demo.environments', 'local_base.yaml'),\n ('dagster_examples.airline_demo.environments', 'local_warehouse.yaml'),\n ],\n )\n\n\n Args:\n name (str): The name of this preset. Must be unique in the presets defined on a given\n pipeline.\n pkg_resource_defs (Optional[List[(str, str)]]): List of pkg_resource modules/files to\n load as environment config for this preset.\n solid_selection (Optional[List[str]]): A list of solid subselection (including single\n solid names) to execute with this partition. e.g.\n ``['*some_solid+', 'other_solid']``\n mode (Optional[str]): The mode to apply when executing this preset. (default:\n 'default')\n tags (Optional[Dict[str, Any]]): The tags to apply when executing this preset.\n\n Returns:\n PresetDefinition: A PresetDefinition constructed from the provided YAML strings\n\n Raises:\n DagsterInvariantViolationError: When one of the YAML documents is invalid and has a\n parse error.\n '''\n pkg_resource_defs = check.opt_list_param(\n pkg_resource_defs, 'pkg_resource_defs', of_type=tuple\n )\n\n try:\n yaml_strings = [\n six.ensure_str(pkg_resources.resource_string(*pkg_resource_def))\n for pkg_resource_def in pkg_resource_defs\n ]\n except (ModuleNotFoundError, FileNotFoundError, UnicodeDecodeError) as err:\n six.raise_from(\n DagsterInvariantViolationError(\n 'Encountered error attempting to parse yaml. Loading YAMLs from '\n 'package resources {pkg_resource_defs} '\n 'on preset \"{name}\".'.format(pkg_resource_defs=pkg_resource_defs, name=name)\n ),\n err,\n )\n\n return PresetDefinition.from_yaml_strings(name, yaml_strings, solid_selection, mode, tags)\n\n def get_environment_yaml(self):\n '''Get the environment dict set on a preset as YAML.\n\n Returns:\n str: The environment dict as YAML.\n '''\n return yaml.dump(self.run_config or {}, default_flow_style=False)\n\n def with_additional_config(self, run_config):\n '''Return a new PresetDefinition with additional config merged in to the existing config.'''\n\n check.opt_nullable_dict_param(run_config, 'run_config')\n if run_config is None:\n return self\n else:\n return PresetDefinition(\n name=self.name,\n solid_selection=self.solid_selection,\n mode=self.mode,\n tags=self.tags,\n run_config=merge_dicts(self.run_config, run_config),\n )\n","sub_path":"python_modules/dagster/dagster/core/definitions/preset.py","file_name":"preset.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"649082118","text":"#!/usr/bin/python\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nimport numpy as np\n\nclass cbar(object):\n \"\"\"\n Base class for color bars\n \"\"\"\n def __init__(self):\n self.cbar = None\n\n def make_cbar(self, name, RGB_list):\n self.cbar = LinearSegmentedColormap.from_list(name, RGB_list)\n plt.register_cmap(cmap=self.cbar)\n\n def view(self):\n colors = self.cbar(np.arange(self.cbar.N))\n figColormap = plt.figure(figsize=(6.7, 3.4))\n cAx = figColormap.add_subplot(1, 1, 1)\n cAx.imshow([colors], extent=[0, 10, 0, 1])\n cAx.set_xticklabels([])\n cAx.set_xticks([])\n cAx.set_yticklabels([])\n cAx.set_yticks([])\n plt.show()\n\nclass cring(object):\n \"\"\"\n Base class for periodic color bars\n \"\"\"\n def __init__(self):\n self.cbar = None\n\n def make_cbar(self, name, RGB_list):\n self.cbar = LinearSegmentedColormap.from_list(name, RGB_list)\n plt.register_cmap(cmap=self.cbar)\n\n def view(self):\n rotation = np.arange(0, 361, 1)\n thickness = np.arange(40, 70, 1)\n values = rotation*np.ones((30, 361))\n figColormap = plt.figure(figsize=(6.7, 3.4))\n cAx = figColormap.add_subplot(1, 1, 1, projection='polar')\n cAx.pcolormesh(rotation*np.pi/180.0, thickness, values, \n cmap=plt.get_cmap(self.cbar))\n cAx.set_yticks([])\n cAx.tick_params(pad=15)\n plt.show()\n\nclass cbarHot(cbar):\n \"\"\"\n Class to make the custom 'cbarHot' COSMO colorbar\n \"\"\"\n def __init__(self):\n\n # 5th degree polynomial fit to the individual RGB values of the\n # Mathematica COSMO colorbar at 1000 sample points\n x = np.linspace(0.0, 1.0, 100)\n\n # R, G, B value polynomial coefficients in decreasing order\n r = np.array([28.384, -66.085, 54.494, -16.557, -0.232, 0.991])\n g = np.array([4.196, -8.275, 9.143, -5.479, -0.086, 0.995])\n b = np.array([-2.312, 4.468, -3.085, -0.128, 0.052, 0.997])\n\n # Build polynomial\n pr = np.polyval(r, x)\n pg = np.polyval(g, x)\n pb = np.polyval(b, x)\n\n # Wrap back RGB values into the [0, 1] allowed range\n # (endpoints may fall outside [0, 1] due to error in the fit)\n for i in [pr, pg, pb]:\n i[np.where(i > 1.0)] = 1.0\n i[np.where(i < 0.0)] = 0.0\n\n # Build colormap and register it with Matplotlib\n self.make_cbar('cbarHot', np.column_stack((pr, pg, pb)))\n\nclass cbarHot_alt(cbar):\n \"\"\"\n Class to make the custom 'cbarHot' COSMO colorbar in an alternate\n construction, based on blending with an existing Python colorbar.\n Appearance is not quite the same as the Mathematica colorbar,\n but is similar. \n \"\"\"\n def __init__(self):\n\n # Build color bar on 1000 sample points \n x = np.linspace(0.0, 1.0, 1000)\n\n # Extract 1000 sample points from existing color bar\n # Only use partial segment of the colorbar (0.0 to 0.8)\n y = np.linspace(0.0, 0.8, 1000)\n\n # RGB values\n rgbWhite = np.array([1.0, 1.0, 1.0])*np.ones((1000, 3))\n rgb1 = np.array([1.0, 0.5, 0.0])*np.ones((1000, 3))\n rgbPurple = np.array([0.5, 0.0, 0.5])*np.ones((1000, 3))\n\n # Blend with the 'ocean' colorbar\n cm = plt.get_cmap('ocean')\n\n # Blend ratios\n dsc = cm(1.0-y)**1.1\n c1 = (1.0-x)**4\n c2 = x**10\n c3 = (x-0.1)**2\n\n # Blend colors\n blend1 = np.einsum('ij,i->ij', dsc[:, 0:3], 1.0-c1) \\\n + np.einsum('ij,i->ij', rgbWhite, c1)\n blend2 = np.einsum('ij,i->ij', blend1, 1.0-c3) \\\n + np.einsum('ij,i->ij', rgbPurple, c3)\n blend3 = np.einsum('ij,i->ij', blend2, 1.0-c2) \\\n + np.einsum('ij,i->ij', rgb1, c2)\n \n # Build the colormap and register it with Matplotlib\n self.cbar = LinearSegmentedColormap.from_list('cbarHot', blend3)\n plt.register_cmap(cmap=self.cbar)\n\nclass cbarBWR(cbar):\n \"\"\"\n Class to make the custom 'cbarBWR' COSMO colorbar.\n A similar colorbar exists already in Matplotlib, and\n (in my opinion) looks a little nicer: 'RdBu'\n \"\"\"\n def __init__(self):\n\n # Build colorbar using 1000 sample points\n x = np.linspace(0.0, 1.0, 1000)\n\n # RGB values\n rgbBlack = np.array([0.0, 0.0, 0.0])*np.ones((1000, 3))\n rgbWhite = np.array([1.0, 1.0, 1.0])*np.ones((1000, 3))\n rgb1 = np.array([0.0, 0.4, 1.0])*np.ones((1000, 3))\n rgb2 = np.array([1.0, 0.3, 0.0])*np.ones((1000, 3))\n\n # Blend ratios\n c1 = np.sin(x*np.pi/2)\n c2 = np.cos(x*np.pi/2)\n c3 = 2*np.sin(x*np.pi)**4 + 4*np.sin(x*np.pi)**16 \\\n + 8*np.sin(x*np.pi)**64 + 32*np.sin(x*np.pi)**256\n c3 /= np.amax(c3)\n c4 = np.cos(x*np.pi)**16\n\n # Normalize ratios to add to 1\n norm = np.amax(c1+c2+c3+c4)\n c1 /= norm\n c2 /= norm\n c3 /= norm\n c4 /= norm\n\n # Blend colors\n blend = np.einsum('ij,i->ij', rgb2, c1) \\\n + np.einsum('ij,i->ij', rgb1, c2) \\\n + np.einsum('ij,i->ij', rgbWhite, c3) \\\n + np.einsum('ij,i->ij', rgbBlack, c4)\n\n # Build the colormap and register it with Matplotlib\n self.cbar = LinearSegmentedColormap.from_list('cbarBWR', blend)\n plt.register_cmap(cmap=self.cbar)\n \n\nclass cbarPhi(cring):\n \"\"\"\n Class to make custom COSMO periodic colorbar\n \"\"\"\n def __init__(self):\n\n # Build colorbar using 1000 sample points\n x = np.linspace(0.0, 1.0, 1000)\n\n # RGB values\n rgbBlack = np.array([0.0, 0.0, 0.0])*np.ones((1000, 3))\n rgbWhite = np.array([1.0, 1.0, 1.0])*np.ones((1000, 3))\n rgb1 = np.array([0.0, 0.4, 0.9])*np.ones((1000, 3))\n rgb2 = np.array([1.0, 0.3, 0.0])*np.ones((1000, 3))\n\n # Blend ratios\n c1 = 0.5*np.cos(x*np.pi+np.pi/4+np.pi/4)**4\n c2 = 1.0*np.sin(x*np.pi+np.pi/4+np.pi/4)**8\n c3 = np.cos(x*np.pi+np.pi/4)**4\n c4 = np.cos(x*np.pi+np.pi/2+np.pi/4)**4\n\n # Normalize ratios to sum to 1\n norm = np.amax(c1+c2+c3+c4)\n c1 /= norm\n c2 /= norm\n c3 /= norm\n c4 /= norm\n\n # Blend colors\n blend = np.einsum('ij,i->ij', rgbBlack, c1) \\\n + np.einsum('ij,i->ij', rgbWhite, c2) \\\n + np.einsum('ij,i->ij', rgb1, c3) + np.einsum('ij,i->ij', rgb2, c4)\n\n # Build the colormap and register it with Matplotlib\n self.cbar = LinearSegmentedColormap.from_list('cbarPhi', blend)\n plt.register_cmap(cmap=self.cbar)\n","sub_path":"python/matplotlib/cosmoplot/colorbars.py","file_name":"colorbars.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"234024063","text":"# Natalie Lowell 20161214\n# Purpose of script: subset a genepop file to a certain number of loci\n# Command line arguments: [1] genepop file and [2] number of loci to subset\n\nimport sys\n\nn = int(sys.argv[2]) + 1 # add 1 because the first column is just the same of the \n\n# open your genepop file and read lines into a list of lines\ngpfile = open(sys.argv[1], \"r\") \nlines = gpfile.readlines()\ngpfile.close()\n\n# open new file for your output file, the truncated genepop file\nnewfilename = \"genepop_\"+str(sys.argv[2])+\"_loci.gen\"\nnewfile = open(newfilename, \"w\")\n\n# write the header line with stacks version and date to the new file\nnewfile.write(lines[0])\n\n# get header and split into list on commas, for a list of all the loci\nheader_list = lines[1].strip().split(\",\")\n\n# grab only the first n, as designated at the command line\nretrieve_header = header_list[0:int(sys.argv[2])]\n\n\n# initiate string for header line w loci\nheaderstring = \"\" \n\n# make a loop to stick the commas back in\nfor locus in retrieve_header:\n\theaderstring += locus + \",\"\n\t\n\t\n# remove the last comma\nheaderstring = headerstring[:-1]\nheaderstring = headerstring + \"\\n\"\n\n# print headerstring # CHECK\n\t\n# write it to the file\nnewfile.write(headerstring)\n\n# remaining lines = after header w loci\nremlines = lines[2:]\n\n# loop: if pop, write pop. if not pop, truncate line to n and add to file\nfor line in remlines:\n\tif \"pop\" in line:\n\t\tnewfile.write(line)\n\telse:\n\t\tlinelist = line.strip().split()\n\t\tkeep = linelist[0:n] # TESTING THIS LINE\n\t\tnewline = \"\"\n\t\tfor item in keep:\n\t\t\tnewline += item + \"\\t\"\n\t\tnewline = newline[:-1] # remove final tab\n\t\tnewline = newline + \"\\n\" # add new line\n\t\tnewfile.write(newline)\n\nnewfile.close()\n\t\t\t","sub_path":"Cod-Time-Series-Project/Scripts/subset_genepop_nloci.py","file_name":"subset_genepop_nloci.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"239371365","text":"import torch\nimport gpytorch\nfrom torch.autograd import Variable\n\n\ndef test_forward():\n for n_cols in [2, 3, 4]:\n a = torch.Tensor([\n [5, -3, 0],\n [-3, 5, 0],\n [0, 0, 2],\n ])\n b = torch.randn(3, n_cols)\n actual = a.inverse().mm(b)\n\n a_var = Variable(a)\n b_var = Variable(b)\n out_var = gpytorch.invmm(a_var, b_var)\n res = out_var.data\n\n assert(torch.norm(actual - res) < 1e-4)\n\n\ndef test_backward():\n for n_cols in [2, 3, 4]:\n a = torch.Tensor([\n [5, -3, 0],\n [-3, 5, 0],\n [0, 0, 2],\n ])\n b = torch.ones(3, 3).fill_(2)\n c = torch.randn(3, n_cols)\n actual_a_grad = -torch.mm(\n a.inverse().mul_(0.5).mm(torch.eye(3, n_cols)),\n a.inverse().mul_(0.5).mm(c).t()\n ) * 2 * 2\n actual_c_grad = (a.inverse() / 2).t().mm(torch.eye(3, n_cols)) * 2\n\n a_var = Variable(a, requires_grad=True)\n c_var = Variable(c, requires_grad=True)\n out_var = a_var.mul(Variable(b))\n out_var = gpytorch.invmm(out_var, c_var)\n out_var = out_var.mul(Variable(torch.eye(3, n_cols))).sum() * 2\n out_var.backward()\n a_res = a_var.grad.data\n c_res = c_var.grad.data\n\n assert(torch.norm(actual_a_grad - a_res) < 1e-4)\n assert(torch.norm(actual_c_grad - c_res) < 1e-4)\n","sub_path":"test/functions/invmm_test.py","file_name":"invmm_test.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155176786","text":"from .. import get_backend, default_backend, events\n\n\ndef index_helper(name, tensor_shape, batch_shape, par_map):\n if isinstance(name, list):\n return [index_helper(x, tensor_shape, batch_shape, par_map) for x in name]\n x = list(range(int(default_backend.product(tensor_shape))))\n indices = default_backend.reshape(x, tensor_shape)\n parfield_slice = tuple(slice(None, None) for x in batch_shape) + (\n par_map[name]['slice'],\n )\n indices = indices[parfield_slice]\n return default_backend.tolist(indices)\n\n\nclass ParamViewer(object):\n \"\"\"\n Helper class to extract parameter data from possibly batched input\n \"\"\"\n\n def __init__(self, tensor_shape, par_map, name):\n self.tensor_shape = tensor_shape\n self.batch_shape = tensor_shape[:-1]\n # for more general batch shapes we need to revisit\n assert len(self.batch_shape) <= 1\n self._par_map = par_map\n self._index_selection = index_helper(\n name, tensor_shape, self.batch_shape, self._par_map\n )\n\n if self._index_selection:\n cat = default_backend.astensor(\n default_backend.concatenate(self._index_selection, axis=-1), dtype='int'\n )\n # index_selection is\n # batched: list of (batch_dim, slice size) tensors\n # unbatched: list of (slice size,) tensors\n # concatenated is\n # batched: (batch_dim, sum of slice sizes)\n # unbatched: (sum of slice sizes, )\n # indices_concatenated is\n # batched: (sum of slice size, batch dim)\n # unbatched: (sum of slice size, )\n if self.batch_shape:\n self._indices_concatenated = default_backend.einsum('ij->ji', cat)\n else:\n self._indices_concatenated = cat\n\n else:\n self._indices_concatenated = None\n\n last = 0\n sl = []\n for s in [\n self._par_map[x]['slice'].stop - self._par_map[x]['slice'].start\n for x in (name if isinstance(name, list) else [name])\n ]:\n sl.append(slice(last, last + s))\n last += s\n self._slices = sl\n\n self._precompute()\n events.subscribe('tensorlib_changed')(self._precompute)\n\n def _precompute(self):\n tensorlib, _ = get_backend()\n if self._indices_concatenated is not None:\n self.indices_concatenated = tensorlib.astensor(\n self._indices_concatenated, dtype='int'\n )\n\n def __repr__(self):\n return '({} with [{}] batched: {})'.format(\n self.tensor_shape,\n ' '.join(list(self._par_map.keys())),\n bool(self.batch_shape),\n )\n\n @property\n def index_selection(self):\n \"\"\"\n Returns:\n indices into parameter field accordig to requested subset of parameters\n list of (batch_size, parset_size) tensors\n \"\"\"\n return self._index_selection\n\n @property\n def slices(self):\n \"\"\"\n Returns:\n list index slices to retrieve a subset of the requested parameters\n \"\"\"\n return self._slices\n\n def get(self, tensor, indices=None):\n \"\"\"\n Args:\n tensor (`tensor`): the data tensor to extract a view from\n indices (`tensor`): an optional index selection (default behavior is to use self.indices_concatenated)\n Returns:\n filtered set of parameter field/array :\n type when batched: (sum of slice sizes, batchsize) tensor\n type when not batched: (sum of slice sizes, ) tensors\n \"\"\"\n tensorlib, _ = get_backend()\n if not self.batch_shape:\n return tensorlib.gather(\n tensor, indices if indices is not None else self.indices_concatenated\n )\n return tensorlib.gather(\n tensorlib.reshape(tensor, (-1,)),\n indices if indices is not None else self.indices_concatenated,\n )\n","sub_path":"src/pyhf/parameters/paramview.py","file_name":"paramview.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"230298174","text":"import sys\nimport os\nimport subprocess\nsys.path.append('/data/essence/admin/bin/pyutils/alerts')\nfrom analyticsmail import AnalyticsAlerter\nimport datetime\nimport gzip\nimport zipfile\nimport jinja2\n\nora_home = \"/u01/app/oracle/product/11.2.0/db_1\"\nos.environ['ORACLE_HOME'] = ora_home\nos.environ['LD_LIBRARY_PATH'] = \"/u01/app/oracle/product/11.2.0/db_1/lib\"\nos.environ['PATH'] = ora_home + ':' + os.environ['PATH']\nos.environ['ORACLE_SID'] = \"ffmis\"\n\nimport cx_Oracle\n\ndef print_to_csv(cur, fpath, delimiter='|', zip=False):\n if zip == \"gzip\":\n fp = gzip.GzipFile(fpath, 'w')\n else:\n fp = open(fpath, 'w')\n fp.write(delimiter.join(field[0] for field in cur.description))\n fp.write(\"\\n\")\n fp.write(\"\\n\".join(delimiter.join(str(field) for field in row) for row in cur))\n fp.close()\n if zip == \"zip\":\n zfpath = fpath + \".zip\"\n zf = zipfile.ZipFile(zfpath, 'w')\n zf.write(fpath, os.path.basename(fpath), zipfile.ZIP_DEFLATED)\n zf.close()\n return cur.rowcount\n\ndef expand_template_file(tplt, vals):\n template_string = open(tplt, 'r').read()\n template = jinja2.Template(template_string)\n return template.render(vals)\n\ndef send_alert(recipients, subject, plaintext, body_html, attachments=None, images=None):\n am = AnalyticsAlerter()\n am.send_alert(recipients, subject, plaintext, body_html, attachments, images)\n","sub_path":"admin/bin/pyutils/alerts/resources/alerts_jinja.py","file_name":"alerts_jinja.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"359020779","text":"# -*- coding:utf-8 -*-\nimport requests\nimport os\nimport Pillow\n\n\ncode_url = 'http://202.193.80.58:81/academic/getCaptcha.do?0.23611265529353553' # 验证码URL\npic_url = 'C:/Users/dell/Desktop/Verification-code-identification/pic/' # 验证码路径\npic_order_url = 'C:/Users/dell/Desktop/Verification-code-identification/pic/inOrder' # 有序验证码路径\ndef get_img(val,localPath):\n for i in range(val,10000) :\n ir=requests.get(code_url)\n str1=localPath+'%d.jpg'%i\n print(str1)\n print(ir.content)\n open(str1 ,'wb').write(ir.content)\n\n\ndef read_captcha(path):\n image_array = []\n image_label = []\n file_list = os.listdir(path)\n for file in file_list:\n image = Image.open(path+'/'+file) #打开图片\n\n\n\nif __name__=='__main__':\n pass\n\n","sub_path":"py_reg/get_pic.py","file_name":"get_pic.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"180120615","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@author 万丰溥\n@email wanfengpu@zhuge.com\n@desc 小区均价gov表实体类\n@class_name AllBoroughPrice\n\"\"\"\nfrom zhuge.model.BaseModel.Base import Base\n\n\nclass ComplexName(Base):\n __tablename__ = 'all_borough_price'\n fields = {\n \"id\": 0,\n \"complex_id\": 0,\n \"complex_name\": \"\",\n \"cityarea_name\": \"\",\n \"cityarea2_name\": \"\",\n \"avgprice\": 0,\n \"city_en\": \"\",\n \"city_id\": 0,\n \"city_cn\": \"\",\n \"type\": \"\",\n \"rank\": \"\",\n }\n","sub_path":"zhuge/model/ComplexName.py","file_name":"ComplexName.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"69678838","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 17 10:23:59 2021\n\n@author: brian\n\"\"\"\n\nfrom gittislab import signal, behavior, dataloc, ethovision_tools, plots \nimport os\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport math\nfrom matplotlib import pyplot as plt\nimport pdb\nfrom itertools import compress\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\n# %% Debugging code incorporated into preprocessing:\nex0=['exclude','and_GPe','and_Str','Left','Right',\n 'Other XLS','Exclude','mW','mw']\n\ninc=[['AG','A2A','Ai32','10x10']]\nexc=[ex0,ex0,ex0]\nbasepath='/home/brian/Dropbox/Gittis Lab Data/OptoBehavior/'\nethovision_tools.raw_csv_to_preprocessed_csv(basepath,\n inc,exc,force_replace=True,\n win=10)\n\nsummary=ethovision_tools.meta_sum_csv(basepath,inc,exc) \n\n# %% Plot comparing im & im2 (improved)\n\ninc=['AG','Str','A2A','Ai32','10x10',]\nexc=['exclude','gpe_','mw']\nbasepath='/home/brian/Dropbox/Gittis Lab Data/OptoBehavior/'\npns=dataloc.raw_csv(basepath,inc,exc)\nfor pn in pns:\n raw,meta=ethovision_tools.csv_load(pn,method='preproc')\n \n plt.figure()\n plt.plot(raw['time'],raw['im'])\n plt.plot(raw['time'],raw['im2'],'--')\n percent_match = sum (raw['im'] & raw['im2']) / sum(raw['im']) * 100\n plt.title('%s r= %1.3f, %2.1f %% Hit' \n % (meta['anid'][0],meta['im_im2_pearson'][0],percent_match))\n \n basepath=pn.parent\n # boris,raw,meta=ethovision_tools.boris_prep(basepath,[inc],[exc],plot_cols=['time','im','im2'], \n # event_col=['im','im2'],event_thresh=0.5, method='preproc')\n\n# %% Compare ethovision immobility measurement to using DLC side camera stats\n# and or velocity threshold.\n\n#Load an example file\ninc=['AG','Str','A2A','Ai32','10x10',]\nexc=['exclude','gpe_','mw']\nbasepath='/home/brian/Dropbox/Gittis Lab Data/OptoBehavior/'\npns=dataloc.raw_csv(basepath,inc,exc)\nuse=3\n# fn = '/home/brian/Dropbox/Gittis Lab Data/OptoBehavior/Str/Naive/A2A/Ai32/Bilateral/10x10/AG6343_5_BI120220/Raw_AG6343_5_BI120220.csv'\nraw,meta=ethovision_tools.csv_load(pns[use],method='preproc')\nraw,meta = ethovision_tools.add_dlc_helper(raw,meta,pns[use].parent,inc,exc,force_replace=True)\n# plots.plot_openloop_day(raw,meta);\n\n\nim = raw['im'].values.astype(float)\nvel=raw['vel'].values\nvel[0:5]=np.nan\nfeats=['dlc_snout_x','dlc_snout_y','dlc_side_left_hind_x', 'dlc_side_left_hind_y','dlc_side_right_fore_x',\n 'dlc_side_right_fore_y', 'dlc_side_tail_base_x', 'dlc_side_tail_base_y',\n 'dlc_side_left_fore_x','dlc_side_right_hind_x', 'dlc_side_right_hind_y',\n 'dlc_side_left_fore_y','dlc_head_centroid_x', 'dlc_head_centroid_y',]\nd=np.ones(im.shape) * 0\nstep=20\n\n\nx=raw['dlc_top_body_center_y'].values\n \n\n \nfor c in feats:\n dat = raw[c].values\n dat=signal.max_correct(x,dat,step,poly_order=2) #Correct for distance from camera\n dd = abs(np.diff(np.hstack((dat[0],dat))))\n d=np.vstack((d,dd))\nd=np.nanmax(d,axis=0)\n\n\nvel=raw['vel']\n# head_crit=0.6 #For raw pix\nhead_crit = 0.004 # For position normalized\nvel_crit = 0.5\nplt.figure(),\nax0=plt.subplot(3,1,1)\nplt.plot(raw['time'],im,'k')\n# plt.plot(raw['time'],raw['rear'],'b')\nplt.ylabel('Occurence')\n\nplt.subplot(3,1,2,sharex=ax0)\nplt.plot(raw['time'],d,'k')\nplt.plot(raw['time'],raw['mouse_height'].values,'r')\nplt.plot([0,meta['exp_end'][0]],[head_crit,head_crit],'--b')\n# plt.ylim([0,0.01])\nplt.ylabel('Norm. DLC change (average)')\n\nplt.subplot(3,1,3,sharex=ax0)\n# plt.plot(raw['time'],raw['mouse_height'],'k')\nplt.plot(raw['time'],vel,'r')\nplt.ylim([0,1])\nplt.plot([0,meta['exp_end'][0]],[vel_crit,vel_crit],'--b')\nplt.ylabel('Height and vel')\n\nplt.sca(ax0)\nheight=raw['mouse_height']\n# new_crit = np.array((dhx < head_crit ) & (dhy < head_crit) & (vel < vel_crit))\nnew_crit = np.array((d < head_crit) & (vel < vel_crit) & (height < 0.3))\nsmooth_crit = 0.2\nnew_crit_temp = signal.boxcar_smooth(new_crit,round(meta['fs'][0]*0.5)) \nnew_crit = new_crit_temp >= smooth_crit\nplt.plot(raw['time'],new_crit_temp,'--r')\nplt.plot([0,meta['exp_end'][0]],[smooth_crit,smooth_crit],'--b')\nplt.plot(raw['time'],new_crit,'--g')\nplt.plot(raw['time'],raw['im2'],'--b')\nr,p= stats.pearsonr(new_crit,im)\nplt.title('Pearson r = %1.3f, p = %1.4f' % (r,p) )\n# %% Examine in boris:\nraw,meta=ethovision_tools.csv_load(pns[use],method='preproc')\nraw['im2'] = new_crit\npreproc_file_name=dataloc.path_to_preprocfn(pns[use]) + '.csv'\nraw.to_csv(pns[use].parent.joinpath(preproc_file_name))\n\nbasepath=pns[use].parent\ninc=[['AG']]\nexc=[['exclude']]\nboris,raw,meta=ethovision_tools.boris_prep(basepath,inc,exc,plot_cols=['time','im','im2'], \n event_col=['im','im2'],event_thresh=0.5, method='preproc')\n","sub_path":"scripts/debug_immobility_etho_measure.py","file_name":"debug_immobility_etho_measure.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"598481567","text":"# coding=utf-8\nfrom time import sleep\n\nimport pytest\nfrom allure.constants import AttachmentType\nimport allure\n\n\n@allure.feature('Функциональное тестирование')\n@allure.story('ФС№263.dogm_77060201_Запись в колледж по поиску ОУ')\ndef test_2(browser, pdf_file):\n \"\"\"\n Наименование сценария:\n ФС№263.dogm_77060201_Запись в колледж по поиску ОУ\n\n Шаг 1. Открыть сайт\n Открыть Сайт Мэра Москвы, для этого ввести адрес https://mos.ru/ в адресную строку браузера.\n\n Открылась главная страница Портала https://mos.ru\n\n Шаг 2. Услуги и сервисы\n Перейти в раздел \"Услуги\", нажав в шапке сайта на соответствующее название.\n\n Открылась страница https://www.mos.ru/services/catalog/popular\n\n Шаг 3. Раздел\n Выбрать раздел - Образование\n\n Открылся подраздел\n\n Шаг 4. Подраздел\n Выбрать подраздел - Среднее специальное и профессиональное\n\n Открылась услуга\n\n Шаг 5. Посадочная страница\n Выбрать услугу - Запись в колледж\n\n Переход на посадочную страницу\n\n Шаг 6. Страница авторизации\n Нажать кнопку \"Получить услугу\"\n\n Переход на страницу авторизации\n\n Шаг 7. Авторизация\n Авторизоваться на портале (логин: mpgu_fmon пароль: IslnXGYy)\n\n Авторизация на портале, переход на страницу с услугой\n\n Шаг 8. Параменты поиска\n Блок \"Выбор параметра поиска\":\n Поиск по: Образовательной организации\n\n Поля заполнились\n\n Шаг 9. Поиск\n Блок \"Поиск по образовательной организации\":\n Поиск: Политехнический колледж № 8\n\n Поля заполнились\n\n Шаг 10. Результаты поиска\n Нажать \"Найти\"\n\n Переход к результатам поиска\n\n Шаг 11. Выбор ОУ\n Нажать на блок с образовательной организацией \"Государственное автономное профессиональное образовательное учреждение города Москвы \"Политехнический колледж № 8 имени дважды Героя Советского Союза И.Ф. Павлова\"\"\n\n Переход к блоку с образовательными программами\n\n Шаг 12. Выбор программы\n Выбрать пурвую программу из списка, щелкнув по ней\n\n Поле с выбранной программой подсветилось голубым цветом\n\n Шаг 13. Шаг 2\n Нажать \"Продолжить\"\n\n Переход на шаг 2\n\n Шаг 14. Адрес\n Блок \"Адрес регистрации по месту жительства/пребывания в городе Москве\":\n Улица: Заревый пр.\n Дом: 6\n Квартира/офис: 22\n\n Поля заполнились\n\n Шаг 15. Сведения об образовании\n Блок \"Сведения об образовании\":\n Дата выдачи: 05.05.2017\n Номер: 123456789\n\n Поля заполнились\n\n Шаг 16. Шаг 3\n Нажать \"Продолжить\"\n\n Переход на шаг 3\n\n Шаг 17. Документы\n Блок \"Необходимые документы\":\n Скан-копия разворота паспорта с фотографией: прикрепить pdf файл\n Скан-копия разворота паспорта с адресом регистрации или свидетельство о регистрации по месту пребывания: прикрепить pdf файл\n Документ об образовании и (или) документ об образовании и о квалификации (с приложениями): прикрепить pdf файл\n\n Поля заполнились\n\n Шаг 18. Согласие\n Блок \"Условия предоставления услуги\":\n Отметить чекбоксы.\n\n Поля заполнились\n\n\"\"\"\n\n \n with allure.step('Шаг 1.Открыть сайт'):\n try:\n browser.openMosRu()\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 2.Услуги и сервисы'):\n try:\n browser.goToAllServices()\n sleep(1)\n assert browser.xpath(\"//*[@id='mos-header']/div[2]/div[2]/div/div[1]\").text == u'Услуги'\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 3.Раздел'):\n try:\n name = u'Образование'\n browser.goToService(name)\n sleep(1)\n assert browser.xpath('//*[@data-ng-bind=\"currentCategory.title\"]').text == name\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 4.Подраздел'):\n try:\n name = u'Среднее специальное и профессиональное'\n browser.goToSubsection(name)\n sleep(1)\n text = browser.xpath(\"//div[@class='catalog-category-info']/div[1]\").text\n assert text == name\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 5.Посадочная страница'):\n try:\n name = u'Запись в колледж'\n browser.goToCategory(name)\n assert browser.xpath(\".//*[@id='body']//h1\").text == name\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 6.Страница авторизации'):\n try:\n browser.getService()\n assert browser.xpath(\".//*[@id='alias_login_form']\").is_displayed()\n assert browser.xpath(\".//*[@id='outerlogin_button']\").is_displayed()\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n\n with allure.step('Шаг 7.Авторизация'):\n try:\n browser.loginUser(\"mpgu_fmon\", \"IslnXGYy\")\n assert browser.xpath(\n \".//*[@id='body']/div/h1\").text == name\n browser.form_element_is_present()\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 8. Параменты поиска'):\n try:\n browser.set_checkbox(\".//*[@id='field[internal.new_search_by]-1']\")\n \n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 9. Поиск'):\n try:\n browser.send_to_input(\".//*[@id='search_ou']\", u'Политехнический колледж № 8')\n \n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 10. Результаты поиска'):\n try:\n browser.xpath(\".//*[@id='field_find_ProftechOO']\").click(postsleep=2)\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 11. Выбор ОУ'):\n try:\n browser.xpath(\"(.//*[@id='fullname'])[1]\").click(postsleep=2)\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 12. Выбор программы'):\n try:\n browser.xpath(\"(.//*[@id='specialty'])[1]\").click(postsleep=2)\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 13. Шаг 2'):\n try:\n browser.click_button_next(postsleep=2)\n assert browser.xpath(\".//*[@id='step_2']\").is_displayed()\n browser.check_autofill(\".//*[@id='declarant-lastname']\")\n browser.check_autofill(\".//*[@id='file.22Series']\")\n \n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 14. Адрес'):\n try:\n browser.send_to_input(\".//*[@id='bti_block_street']\", u'Заревый пр.')\n browser.chosen_input(\".//*[@id='_house_chosen']/a\", u'6')\n browser.send_to_input(\"//input[@name='field[declarant.address1_line3]']\", u'22')\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 15. Сведения об образовании'):\n try:\n browser.check_autofill(\".//*[@id='edulevel']\")\n browser.send_to_input(\"//input[@name='field[file.242.new_docdate]']\", u'05.05.2017')\n browser.send_to_input(\"//input[@name='field[file.242.new_name]']\", u'123456789')\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 16. Шаг 3'):\n try:\n browser.click_button_next(postsleep=2)\n assert browser.xpath(\".//*[@id='step_3']\").is_displayed()\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 17. Документы'):\n try:\n browser.upload_file(\".//*[@id='step_3']/fieldset[1]/div[1]\", pdf_file)\n browser.upload_file(\".//*[@id='step_3']/fieldset[1]/div[3]\", pdf_file)\n browser.upload_file(\".//*[@id='step_3']/fieldset[1]/div[5]\", pdf_file)\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n with allure.step('Шаг 18. Согласие'):\n try:\n browser.set_checkbox(\".//*[@id='soglas']\")\n browser.set_checkbox(\".//*[@id='spec_exam']\")\n\n allure.attach('screenshot', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n except:\n allure.attach('error_screen', browser.get_screenshot_as_png(), type=AttachmentType.PNG)\n raise\n \n\n ","sub_path":"fmon-pgu/portal_gu_fm/test_FS_263.py","file_name":"test_FS_263.py","file_ext":"py","file_size_in_byte":13660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"344249904","text":"import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport warnings\nimport control\nfrom scipy.linalg import solve_discrete_lyapunov as dlyap\nfrom numpy.lib.stride_tricks import as_strided\n \n###########################################################################\n# iterative SSID for stitching via structured soft-imputing\n###########################################################################\n\n# The following code was mostly written pre-Cosyne 2016\n\ndef construct_hankel_cov(params):\n\n p, hS = params['C'].shape\n SIGfp = np.zeros((p*hS,p*hS))\n\n SIGyy = params['C'].dot(params['Pi'].dot(params['C'].T)) + params['R']\n\n covxx = params['Pi']\n for k in range(2*hS-1):\n \n covxx = params['A'].dot(covxx)\n lamK = params['C'].dot(covxx.dot(params['C'].T))\n\n if k < hS-0.5:\n \n for kk in range(k + 1):\n offset0, offset1 = (k-kk)*p, kk*p\n SIGfp[offset0:offset0+p, offset1:offset1+p] = lamK\n \n else:\n\n for kk in range(2*hS - k -1):\n offset0, offset1 = (hS-kk-1)*p, (kk+k+1-hS)*p\n SIGfp[offset0:offset0+p,offset1:offset1+p] = lamK\n\n return SIGfp, SIGyy\n\n\ndef generateCovariancesFP(seq,hS):\n \n T, p = seq['y'].shape\n \n SIGfp = np.zeros((p*hS,p*hS),dtype=np.float64)\n SIGyy = np.zeros((p,p),dtype=np.float64)\n \n \n idxObs = np.invert(np.isnan(seq['y'])).astype(np.int)\n\n sYYobs = idxObs.T.dot(idxObs)\n nPSIG = (sYYobs==0)\n sYYobs = np.maximum(sYYobs, 1)\n \n Ytot = seq['y'] - np.nanmean(seq['y'],0)\n Ytot[np.isnan(Ytot)] = 0\n\n Yshift = Ytot \n lamK = Ytot.T.dot(Yshift)\n SIGyy = lamK; \n\n for k in range(2*hS-1):\n \n Yshift = np.roll(Yshift, 1, axis = 0)\n lamK = Ytot.T.dot(Yshift) / sYYobs\n lamK[nPSIG] = np.NaN\n\n if k < hS-0.5:\n \n for kk in range(k + 1):\n offset0, offset1 = (k-kk)*p, kk*p\n SIGfp[offset0:offset0+p, offset1:offset1+p] = lamK\n \n else:\n\n for kk in range(2*hS - k -1):\n offset0, offset1 = (hS-kk-1)*p, (kk+k+1-hS)*p\n SIGfp[offset0:offset0+p,offset1:offset1+p] = lamK\n \n SIGyy = symmetrize(SIGyy)/sYYobs \n SIGyy[nPSIG] = np.NaN \n \n return SIGfp, SIGyy\n\ndef ssidSVD(SIGfp,SIGyy,n, pi_method='proper', params_old = None):\n \n minVar = 1e-5\n minVarPi = 1e-5 \n\n p = np.size(SIGyy,0)\n\n if p > 200:\n print('p = ', p)\n print('very high-dimensional data! Will take a while. Switching to verbose...')\n verbose=True\n else:\n verbose=False\n \n \n if verbose:\n print('computing SVD:')\n UU,SS,VV = np.linalg.svd(SIGfp) # SIGfp = UU.dot(diag(SS).dot(VV)\n\n VV = VV.T\n SS = np.diag(SS[:n])\n UU = UU[:,:n]\n VV = VV[:,:n]\n \n Obs = np.dot(UU,SS)\n\n if verbose:\n print('computing A, C:')\n\n A = np.linalg.lstsq(Obs[:-p,:],Obs[p:,:])[0]\n C = Obs[:p,:]\n Chat = VV[:p,:n]\n \n if verbose:\n print('computing Pi:')\n\n # hack: abolish constant flipping of mathematical signs of latent states...\n if not params_old is None:\n flips = np.diag(2*(np.sum(C*params_old['C'],0) > 0).astype(np.float)-1)\n A = flips.dot(A.dot(flips))\n C = C.dot(flips)\n Chat = Chat.dot(flips)\n\n\n if pi_method=='proper':\n Pi,_,_ = control.matlab.dare(A=A.T,B=-C.T,Q=np.zeros((n,n)),R=-SIGyy,\n S=Chat.T, E=np.eye(n)) \n\n else:\n #warnings.warn(('Will not solve DARE, using heuristics; this might '\n # 'lead to poor estimates of Q and V0')) \n Pi = np.linalg.lstsq(A,np.dot(Chat.T,np.linalg.pinv(C.T)))[0]\n\n\n if verbose:\n print('computing Q, R:')\n \n D, V = np.linalg.eig(Pi)\n D[D < minVarPi] = minVarPi\n Pi = V.dot(np.diag(D)).dot(V.T)\n Pi = np.real(symmetrize(Pi))\n Q = Pi - np.dot(np.dot(A,Pi),A.T)\n D, V = np.linalg.eig(Q); \n D[D 1):\n print(np.abs(D))\n warnings.warn(('Produced instable dynamics matrix A. Bluntly pushing '\n 'eigenvalues into the unit circle')) \n D /= np.maximum(np.abs(D), 1)\n print(np.abs(D))\n params['A'] = np.real(V.dot(np.diag(D).dot(np.linalg.inv(V))))\n\n return params\n\ndef add_d(data, params):\n\n params['d'] = np.nanmean(data,axis = 0)\n\n return params\n\ndef FitLDSParamsSSID(seq, n):\n\n T, p = seq['y'].shape\n\n SIGfp, SIGyy = generateCovariancesFP(seq=seq, hS=n)\n \n params = post_process(ssidSVD(SIGfp=SIGfp,SIGyy=SIGyy,n=n));\n params = add_d(data=seq['y'], params=params)\n\n return params\n\ndef run_exp_iterSSID(seq, seq_f, n, num_iter=100,pi_method='proper',\n plot_flag=True):\n\n T,p = seq['y'].shape\n\n # use observation scheme informatoin to mask data\n for i in range(len(seq['obs_time'])):\n idx_t = np.arange(seq['obs_time'][0]) if i == 0 \\\n else np.arange(seq['obs_time'][i-1], seq['obs_time'][i])\n idx_y = np.setdiff1d(np.arange(p), seq['sub_pops'][i])\n seq['y'][np.ix_(idx_t, idx_y)] = np.NaN\n \n # generate covs from full ground truth data for comparison\n SIGfp_f, SIGyy_f = generateCovariancesFP(seq=seq_f,hS=n)\n\n # fit model with iterative SSID\n params, SIGfp_new, SIGyy_new, lPSIGfp, lPSIGyy, broken = \\\n iterSSID(seq=seq, n=n, num_iter=num_iter, \n pi_method=pi_method, init=None, alpha=1)\n\n # reconstruct covs from final estimate \n SIGfp, SIGyy = construct_hankel_cov(params=params[-1])\n\n # visualize results\n if plot_flag:\n idx_stitched = np.invert(lPSIGyy)\n m = np.min([SIGyy.min(), SIGyy_f.min()])\n M = np.max([SIGyy.max(), SIGyy_f.max()])\n plt.figure(figsize=(12,8))\n plt.subplot(2,3,1)\n plt.imshow(SIGyy_f, interpolation='none')\n plt.clim(m,M)\n plt.title('SIGyy true')\n plt.subplot(2,3,2)\n plt.imshow(SIGyy, interpolation='none')\n plt.clim(m,M)\n plt.title('SIGyy est.')\n plt.subplot(2,3,3)\n if np.any(idx_stitched):\n m = np.min([SIGyy[idx_stitched].min(), \n SIGyy_f[idx_stitched].min()])\n M = np.max([SIGyy[idx_stitched].max(), \n SIGyy_f[idx_stitched].max()])\n plt.plot([m,M], [m,M], 'k')\n plt.axis([m,M,m,M])\n plt.hold(True)\n plt.plot(SIGyy[np.invert(idx_stitched)], \n SIGyy_f[np.invert(idx_stitched)], 'b.')\n plt.plot(SIGyy[idx_stitched], SIGyy_f[idx_stitched], 'r.')\n plt.xlabel('est.')\n plt.ylabel('true')\n\n if n*p <= 2000:\n idx_stitched = np.invert(lPSIGfp)\n m = np.min([SIGfp.min(), SIGfp_f.min()])\n M = np.max([SIGfp.max(), SIGfp_f.max()])\n plt.subplot(2,3,4)\n plt.imshow(SIGfp_f, interpolation='none')\n plt.clim(m,M)\n plt.title('SIGfp true')\n plt.subplot(2,3,5)\n plt.imshow(SIGfp, interpolation='none')\n plt.clim(m,M)\n plt.title('SIGfp est.')\n plt.subplot(2,3,6)\n if np.any(idx_stitched):\n m = np.min([SIGfp[idx_stitched].min(), \n SIGfp_f[idx_stitched].min()])\n M = np.max([SIGfp[idx_stitched].max(), \n SIGfp_f[idx_stitched].max()])\n plt.plot([m,M], [m,M], 'k')\n plt.axis([m,M,m,M])\n plt.hold(True)\n plt.plot(SIGfp[np.invert(idx_stitched)], \n SIGfp_f[np.invert(idx_stitched)], 'b.')\n plt.plot(SIGfp[idx_stitched], SIGfp_f[idx_stitched], 'r.')\n plt.xlabel('est.')\n plt.ylabel('true')\n\n plt.show() \n\n return params, SIGfp, SIGyy, lPSIGfp, lPSIGyy, SIGfp_f, SIGyy_f\n\n\ndef iterSSID(seq, n, num_iter=100, init=None, alpha=1.,pi_method='proper'):\n\n T,p = seq['y'].shape\n\n print(seq['y'].shape)\n\n params = []\n broken = False\n\n if p > 200:\n print('p = ', p)\n print('very high-dimensional data! Will take a while. Switching to verbose...')\n verbose=True\n else:\n verbose=False\n\n if verbose:\n print('generating data cov. mat')\n\n SIGfp_new, SIGyy_new = generateCovariancesFP(seq=seq, hS=n)\n\n lnPSIGfp, lnPSIGyy = np.isnan(SIGfp_new),np.isnan(SIGyy_new) # for indexing\n lPSIGfp, lPSIGyy = np.invert(lnPSIGfp), np.invert(lnPSIGyy) \n PSIGfp, PSIGyy = SIGfp_new[lPSIGfp], SIGyy_new[lPSIGyy] # observed parts\n\n\n if verbose:\n print('computing naive iterSSID')\n # 'zero'-th iteration: used ssidSVD on Hankel cov matrix with NaN set to 0:\n SIGfp_new[lnPSIGfp] = 0\n SIGyy_new[lnPSIGyy] = 0\n params.append(post_process(ssidSVD(SIGfp=SIGfp_new,\n SIGyy=SIGyy_new,\n n=n,\n pi_method=pi_method)))\n params[-1] = add_d(seq['y'], params[-1])\n\n # main iterations: fill in NAN's iteratively using missing-value SVD:\n SIGfp_old = SIGfp_new.copy() if init is None else init\n SIGyy_old = SIGyy_new.copy()\n\n if verbose:\n print('computing iterative SSID')\n for t in range(1,num_iter+1):\n\n if verbose:\n print(t)\n params.append(post_process(ssidSVD(SIGfp=SIGfp_old,\n SIGyy=SIGyy_old,\n n=n,\n pi_method=pi_method,\n params_old=params[-1])))\n\n params[-1] = add_d(seq['y'], params[-1])\n\n SIGfp_new, SIGyy_new = construct_hankel_cov(params[-1])\n\n if np.any(np.isnan(SIGfp_new)) or not np.all(np.isfinite(SIGfp_new)):\n print('reconstructed Hankel cov matrix contains NaNs or Infs!')\n print('cancelling iteration')\n\n broken = True\n\n break\n\n # make sure we keep the observed part right\n SIGfp_new[lPSIGfp], SIGyy_new[lPSIGyy] = PSIGfp, PSIGyy\n SIGfp_new[lnPSIGfp] = alpha*SIGfp_new[lnPSIGfp] \\\n +(1-alpha)*SIGfp_old[lnPSIGfp]\n SIGyy_new[lnPSIGyy] = alpha*SIGyy_new[lnPSIGyy] \\\n +(1-alpha)*SIGyy_old[lnPSIGyy]\n SIGyy_new = symmetrize(SIGyy_new)\n\n # hack: change halves of C if helpful\n params[-1] = flip_emission_signs(SIGyy_new,seq['sub_pops'],params[-1])\n\n\n SIGfp_old, SIGyy_old = SIGfp_new, SIGyy_new # shallow copies!\n\n\n if broken:\n broken = params[-1]\n params.pop()\n SIGfp_new, SIGyy_new = construct_hankel_cov(params[-1])\n SIGfp_new[lPSIGfp], SIGyy_new[lPSIGyy] = PSIGfp, PSIGyy\n SIGyy_new = symmetrize(SIGyy_new)\n\n return params, SIGfp_new, SIGyy_new, lPSIGfp, lPSIGyy, broken\n\n\ndef flip_emission_signs(SIGyy, sub_pops, params):\n\n # we drop this for now, as it hardly ever flips anything\n \"\"\"\n if len(sub_pops) == 1:\n idx_overlap = sub_pops[0]\n elif len(sub_pops) == 2:\n idx_overlap = np.intersect1d(sub_pops[0], sub_pops[1])\n else:\n raise Exception('more than two subpopulations not yet implemented')\n\n cov_h = params['C'][idx_overlap,:].dot(params['Pi']).dot(params['C'].T) + \\\n params['R'][idx_overlap,:]\n\n\n for i in range(len(sub_pops)):\n idx_sub = rem_overlap(sub_pops[i], idx_overlap)\n SIGp_est, SIGp_true = cov_parts(cov_h,SIGyy,idx_sub,idx_overlap)\n\n if check_flip(SIGp_est, SIGp_true):\n params['C'][idx_sub,:] *= -1\n \"\"\" \n return params\n\ndef check_flip(x_est, x_true, thresh=0.5):\n return np.mean( np.sum(x_est * x_true, 1) < 0 ) > thresh\n\ndef rem_overlap(idx_sub_pop, idx_overlap):\n return np.setdiff1d(idx_sub_pop, idx_overlap)\n\ndef cov_parts(SIG_est, SIG_true, idx_sub, idx_overlap):\n return SIG_est[:,idx_sub],SIG_true[np.ix_(idx_overlap,idx_sub)]\n","sub_path":"python/core/stitching_ssid.py","file_name":"stitching_ssid.py","file_ext":"py","file_size_in_byte":12957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"150158511","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nlogging.basicConfig(\n level=logging.INFO,\n format=\n '%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s'\n)\nlogger = logging.getLogger()\n\nlogger.warning('logging warn in %s with __name__ %s', 'root', __name__)\nlogger.info('logging info in %s with __name__ %s', 'root', __name__)\nlogger.debug('logging debug in %s with __name__ %s', 'root', __name__)\n\nimport modu1\nfrom modu1 import submodu1\n","sub_path":"python_guide/logging/test_basic_config.py","file_name":"test_basic_config.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371441302","text":"from kafka import KafkaProducer\nfrom kafka.errors import KafkaError\n\nproducer = KafkaProducer(\n bootstrap_servers=[\n \"192.168.11.30:9092\",\n ]\n)\n\nfuture = producer.send(\"test\", b'I am rito yan')\ntry:\n record_metadata = future.get(timeout=10)\n print(record_metadata)\nexcept KafkaError as e:\n print(e)\n","sub_path":"mykafka.py","file_name":"mykafka.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"173579948","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 24 09:37:33 2017\n\n@author: bouleta\n\nscript used as a client in the cloudAMQP following the rpc method\n\"\"\"\n\nimport pika\nimport uuid\nimport msgpack \nimport msgpack_numpy as m \nimport numpy\n\ncorr_id = str(uuid.uuid4())\n\ndef on_response(ch, method, properties, body):\n ##\n # Function used for the callback of the read method \n # @param the chanel\n # @param the method used\n # @param the properties sent\n # @param the body of the message in queue\n if (properties.correlation_id == corr_id):\n print(body)\n else:\n raise Exception('l\\'id de correlation est différent')\n\n\namqp_url = 'amqp://mchgowzq:gTrpIbR5nfC3qW7YyJ1x6-hpwcFLoW7-@lark.rmq.cloudamqp.com/mchgowzq'\nparams = pika.URLParameters(amqp_url)\nparams.socket_timeout = 5\n\nconnection = pika.BlockingConnection(params)\nchannel = connection.channel()\n\nmessage = numpy.random.random((20,30)) \nrequest_msg = msgpack.packb(message,default = m.encode) \n\nresult = channel.queue_declare(exclusive=True)\ncallback_queue = result.method.queue\n\n\nchannel.basic_publish(exchange='',\n routing_key='rpc_queue',\n properties=pika.BasicProperties(\n reply_to = callback_queue,\n correlation_id = corr_id,),\n body=str(request_msg))\nprint('[x] Sent message :)')\n\n# wait for requests\nchannel.basic_consume(on_response, queue=callback_queue, no_ack=True)\n\nchannel.start_consuming()\n\nconnection.close()","sub_path":"assignments/Session1/rpc_client.py","file_name":"rpc_client.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"357625020","text":"import pyximport; pyximport.install(reload_support=True)\nimport sys\nimport dfgeom\n\nimport math\nfrom math import sqrt\n\nb = dfgeom.Box([0.5,0.5,1.0])\nu = dfgeom.Sphere([0.0,0.0,0.0], 0.5)\n\ns = dfgeom.Sphere([0.0,0.0,0.0], 0.5)\n\nshape = dfgeom.Difference(\n dfgeom.Difference(b, u),\n dfgeom.Sphere([1.0,0.5,0.0], 1.0)\n )\n\nshape = dfgeom.Difference(\n dfgeom.Union(s, shape),\n dfgeom.Box([1.0,0.1,1.2])\n )\n\nshape = dfgeom.Tiling(shape, [0.5,0.5,0.5])\n#shape = dfgeom.Twist(shape, [1,1.0,1.0])\n\ndef glslFunction():\n context = {}\n function = shape.toGLSL(context)\n return (context.values(), function);\n\ndef evalField(x,y,z):\n return dfgeom.evalField(shape, x,y,z)\n","sub_path":"examples/customfield2.py","file_name":"customfield2.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"629620961","text":"import numpy as np\nimport scipy as sp\nimport pandas as panda\nimport csv\nimport sys\n\nweight = np.load('weight7.npy')\n\n##print(weight)\n\ntesting_data_path = sys.argv[1]\noutput_file_path = sys.argv[2]\n\nfp = open(testing_data_path, 'r', encoding='big5')\nrows = csv.reader(fp, delimiter=',')\n\ncount = 0\nnum = 0\nbias = 1.0\ntest_x = []\n\n\nfor row in rows:\n\tif(count % 18 == 0):\n\t\ttest_x.append([])\n\t\tif(count != 0):\n\t\t\tnum+=1\n\tfor i in range(2,11):\n\t\tif(row[i] != 'NR'):\n\t\t\tif(float(row[i]) >= 0.0):\n\t\t\t\ttest_x[num].append(float(row[i]))\n\t\t\telif(i != 2):\n\t\t\t\ttest_x[num].append(float(row[i-1]))\n\t\t\telse:\n\t\t\t\ttest_x[num].append(0.0)\n\t\telse:\n\t\t\ttest_x[num].append(0.0)\n\tcount+=1\n##print(test_x[1])\nfor i in range(240):\n\ttest_x[i].append(float(bias))\n\ntest_x_matrix = np.array(test_x, dtype='f')\nanswer = np.dot(test_x_matrix,weight)\n\n\n\nwp = open(output_file_path, 'w')\nwriter = csv.writer(wp)\nwriter.writerow(['id','value'])\nfor i in range(240):\n\ttmp = 'id_'+ str(i)\n\twriter.writerow([tmp, int(answer[i])])\nwp.close()\n","sub_path":"hw1/ova_hw1_test.py","file_name":"ova_hw1_test.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"537703237","text":"# Filter the gain in all species\nimport pandas as pd\n\n# read profile\nx = pd.read_csv('/home/yangfang/PCSF/clime_roc/all_kegg_matrix.txt', sep='\\t')\nkegg = pd.read_csv('/home/yangfang/PCSF/knn_roc/human.KEGG.txt',sep = '\\t')\nremove = []\n# get the genes are all gain\nfor i in range(x.shape[0]):\n tem = x.loc[i, :][2:].sum()\n if tem >= 111:\n remove.append(x.loc[i, :][1])\n# remove from profile\nremove_re = x[~x.Symbol.isin(remove)]\nremove_kegg = kegg[~kegg.Symbol.isin(remove)]\n# write result\nremove_re.to_csv('/home/yangfang/PCSF/clime_roc/all_kegg_matrix_re111.txt', sep='\\t', index=False)\nremove_kegg.to_csv('/home/yangfang/PCSF/clime_roc/human.KEGG_re111.txt', sep='\\t', index=False)\n\n# filter kegg pathway\n\n","sub_path":"PaPr/utils/filter_profile.py","file_name":"filter_profile.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519041912","text":"nums=list(range(5,0,-1)) #5~1每次遞減1 range沒有定義[]所以無法使用[] list有定義[]\nprint(nums)\n\nnums[2]=100\nprint(nums)\n\na=[1,2,3]\ntotal=0\nfor el in a:\n total+=el\ntotal2=sum(a)\nprint(total,total2)\n\nb=range(5,0,-1)\ntotal3=sum(b)\nprint(total3)\n\nstrA=\"Stone\"\nstrA=list(strA) #轉為list修改第一個字母\nstrA[0]=\"Y\"\nprint(strA)\nprint(\",\".join(strA)) #將每個字母中間加,","sub_path":"3_list/list_range.py","file_name":"list_range.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"513392004","text":"import glob\nimport os\nimport datetime\nfrom pmonitor import PMonitor\n\nimport calendar\nfrom calendar import monthrange, isleap\n\n__author__ = 'olafd'\n\n##################################################################################################\n### Provides one step:\n### - staging 'nc2browse' --> png files for band tcwv_mean_mean from WV-CCI L3 netcdf files\n##################################################################################################\n\n\ndef getNumDaysInMonth(year, month):\n return calendar.monthrange(int(year), int(month))[1]\n\ndef getMonths(year):\n if year == '2002':\n months = [ '04', '05', '06', '07', '08', '09', '10', '11', '12' ]\n elif year == '2012':\n months = [ '01', '02', '03', '04' ]\n else:\n #months = [ '01' , '07']\n months = [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ]\n\n return months\n\n#################################################################################################\n\nyears=['2010']\n\nsensor = 'meris'\n\ngaRootDir = '/gws/nopw/j04/esacci_wv/odanne/GlobAlbedoTest'\n\ninputs = ['dummy']\n\nm = PMonitor(inputs, \n request='wvcci-l3-staging-nc2browse', \n logdir='log',\n hosts=[('localhost',64)],\n\t types=[('wvcci-l3-staging-nc2browse-step.sh',64)])\n\nfor year in years:\n tcwvMosaicDir = gaRootDir + '/Mosaic/TCWV/' + sensor + '/' + year\n stagingNc2browseResultDir = gaRootDir + '/staging/QL/tcwv/' + sensor + '/' + year\n for month in getMonths(year):\n # l3_tcwv_meris_2008-01-01_2008-01-31.nc\n stagingNc2browseFile = tcwvMosaicDir + '/l3_tcwv_' + sensor + '_' + year + '-' + month + '-01_' + year + '-' + month + '-' + str(getNumDaysInMonth(year, month)) + '.nc' \n\n m.execute('wvcci-l3-staging-nc2browse-step.sh', ['dummy'], [stagingNc2browseResultDir], \n parameters=[year,month,sensor.upper(),stagingNc2browseFile, stagingNc2browseResultDir])\n\n# wait for processing to complete\nm.wait_for_completion()\n\n#####################################################################################################\n","sub_path":"src/main/bin/cems_shared/wvcci-inst/wvcci-l3-staging-nc2browse.py","file_name":"wvcci-l3-staging-nc2browse.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646377595","text":"import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom rest_framework.test import APIClient\n\nfrom portal.models import Poll, PollOption, PollVote\n\n\nUser = get_user_model()\n\n\nclass PollPermissions(TestCase):\n def setUp(self):\n self.client = APIClient()\n self.admin = User.objects.create_superuser(\"admin@example.com\", \"admin\", \"admin\")\n self.user1 = User.objects.create_user(\"user1\", \"user@seas.upenn.edu\", \"user\")\n self.user2 = User.objects.create_user(\"user2\", \"user@seas.upenn.edu\", \"user\")\n\n self.poll_1 = Poll.objects.create(\n user=self.user1,\n source=\"poll 1\",\n question=\"poll question 1\",\n expire_date=timezone.now() + datetime.timedelta(days=1),\n approved=True,\n )\n\n self.poll_option_1 = PollOption.objects.create(poll=self.poll_1, choice=\"hello!\")\n self.poll_option_2 = PollOption.objects.create(poll=self.poll_1, choice=\"hello!!!!\")\n self.poll_option_3 = PollOption.objects.create(poll=self.poll_1, choice=\"hello!!!!!!!\")\n\n self.poll_2 = Poll.objects.create(\n user=self.user2,\n source=\"poll 2\",\n question=\"poll question 2\",\n expire_date=timezone.now() + datetime.timedelta(days=1),\n approved=True,\n )\n\n self.poll_vote = PollVote.objects.create(user=self.user2, poll=self.poll_1)\n self.poll_vote.poll_options.add(self.poll_option_1)\n\n def test_authentication(self):\n # asserts that anonymous users cannot access any route\n list_urls = [\n \"poll-list\",\n \"polloption-list\",\n \"pollvote-list\",\n \"poll-history-list\",\n \"target-populations\",\n ]\n for url in list_urls:\n response_1 = self.client.get(reverse(f\"portal:{url}\"))\n self.assertEqual(response_1.status_code, 403)\n\n arg_urls = [\"poll-detail\", \"polloption-detail\", \"pollvote-detail\", \"vote-statistics\"]\n for url in arg_urls:\n response_2 = self.client.get(reverse(f\"portal:{url}\", args=[self.poll_1.id]))\n self.assertEqual(response_2.status_code, 403)\n\n def test_update_poll(self):\n # users who didn't create poll cannot update\n self.client.force_authenticate(user=self.user2)\n payload_1 = {\"approved\": False}\n response_1 = self.client.patch(\n reverse(\"portal:poll-detail\", args=[self.poll_1.id]), payload_1\n )\n # 404 because queryset denies access\n self.assertEqual(response_1.status_code, 404)\n\n # admin can update polls\n self.client.force_authenticate(user=self.admin)\n payload_2 = {\"approved\": False}\n response_2 = self.client.patch(\n reverse(\"portal:poll-detail\", args=[self.poll_1.id]), payload_2\n )\n self.assertEqual(response_2.status_code, 200)\n\n def test_create_update_options(self):\n # users who didn't create poll cannot create/update corresponding poll option\n self.client.force_authenticate(user=self.user2)\n payload_1 = {\"poll\": self.poll_1.id, \"choice\": \"hello\"}\n response_1 = self.client.post(\"/portal/options/\", payload_1)\n self.assertEqual(response_1.status_code, 403)\n\n payload_2 = {\"choice\": \"helloooo\"}\n response_2 = self.client.patch(\n reverse(\"portal:polloption-detail\", args=[self.poll_1.id]), payload_2\n )\n # 404 because queryset denies access\n self.assertEqual(response_2.status_code, 404)\n\n # admin can create poll option\n self.client.force_authenticate(user=self.admin)\n payload_3 = {\"choice\": \"helloooo\"}\n response_3 = self.client.patch(\n reverse(\"portal:poll-detail\", args=[self.poll_1.id]), payload_3\n )\n self.assertEqual(response_3.status_code, 200)\n\n def test_update_votes(self):\n # user cannot update other user votes\n self.client.force_authenticate(user=self.user1)\n payload_1 = {\"poll_options\": [self.poll_option_1.id]}\n response_1 = self.client.patch(\n reverse(\"portal:pollvote-detail\", args=[self.poll_vote.id]), payload_1\n )\n # 404 because queryset denies access\n self.assertEqual(response_1.status_code, 404)\n\n # user can update own vote\n self.client.force_authenticate(user=self.user2)\n payload_2 = {\"poll_options\": [self.poll_option_2.id]}\n response_2 = self.client.patch(\n reverse(\"portal:pollvote-detail\", args=[self.poll_vote.id]), payload_2\n )\n self.assertEqual(response_2.status_code, 200)\n\n # not even admin can update user vote\n self.client.force_authenticate(user=self.admin)\n payload_3 = {\"poll_options\": [self.poll_option_3.id]}\n response_3 = self.client.patch(\n reverse(\"portal:pollvote-detail\", args=[self.poll_vote.id]), payload_3\n )\n # 404 because queryset denies access\n self.assertEqual(response_3.status_code, 404)\n","sub_path":"backend/tests/portal/test_permissions.py","file_name":"test_permissions.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503810085","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn import cluster\r\nfrom sklearn.mixture import GaussianMixture\r\n\r\nfrom tqdm import tqdm\r\n\r\n\r\n#data = pd.read_excel(\"c:/Users/carlausss/Desktop/S&C/Prova.xlsx\")\r\n#data = data.dropna()\r\n#data = pd.DataFrame(data)\r\n\r\ndata = pd.DataFrame(np.random.randint(1,100,size=(100, 5)), columns=('X', 'Y','Alfa','Beta', 'Gamma'))\r\n#data = pd.DataFrame(np.random.randint(-100,0,size=(100, 5)), columns=('X', 'Y','Alfa','Beta', 'Gamma'))\r\n\r\n\r\ncol = (len(data.iloc[0,:]) - 2)\r\n\r\ndef correct_df(df):\r\n \r\n min_x=min(df.iloc[:,0])\r\n min_y=min(df.iloc[:,1])\r\n \r\n if min_x < 1:\r\n raise ValueError('Wrong coordinates value')\r\n \r\n if min_y < 1:\r\n raise ValueError('Wrong coordinates value') \r\n\r\n\r\ndef get_close_points(df, x, y, radius = 2):\r\n\r\n correct_df(data)\r\n \r\n if radius < 0:\r\n raise ValueError('Radius value must bu greater than zero')\r\n \r\n x_idx = data.iloc[:, 0]\r\n y_idx = data.iloc[:, 1]\r\n dist_sqrd = (x_idx-x)**2 + (y_idx-y)**2\r\n to_take = np.sqrt(dist_sqrd)<=radius\r\n \r\n return data.loc[to_take]\r\n\r\n \r\ndef km(df, nc = 2 ):\r\n \r\n correct_df(data)\r\n\r\n kml = []\r\n \r\n for i in range(col):\r\n \r\n km = cluster.KMeans(n_clusters = nc).fit(data.iloc[:, 2+i:3+i]) \r\n labels_km = km.labels_ \r\n kml.append(labels_km)\r\n \r\n if len(labels_km) != len(data):\r\n raise ValueError('Cluster data must be same length as dataframe')\r\n \r\n return kml\r\n\r\n\r\ndef gmm(df, nc = 2):\r\n \r\n correct_df(data)\r\n\r\n gmml = []\r\n \r\n for i in range(col):\r\n \r\n gmm = GaussianMixture(n_components = nc).fit(data.iloc[:, 2+i:3+i])\r\n labels_gmm = gmm.predict(data.iloc[:, 2+i:3+i])\r\n gmml.append(labels_gmm) \r\n \r\n if len(labels_gmm) != len(data):\r\n raise ValueError('Cluster data must be same length as dataframe')\r\n \r\n return gmml\r\n\r\n\r\ndef images(df):\r\n\r\n correct_df(data)\r\n\r\n m = [] \r\n max_x=max(data.iloc[:,0])+1\r\n max_y=max(data.iloc[:,1])+1\r\n\r\n for i in range(6*col):\r\n mat = np.empty((max_x,max_y))\r\n mat.fill(np.nan) \r\n \r\n m.append(mat)\r\n \r\n for j in tqdm(range(len(data))):\r\n \r\n xp = data.iloc[j,0] \r\n yp = data.iloc[j,1] \r\n \r\n for i in range(col):\r\n \r\n m[i][int(xp), int(yp)] = data.iloc[j,2+i]\r\n \r\n \r\n parda = get_close_points(data, xp, yp, radius = 2)\r\n parda = pd.DataFrame(parda)\r\n \r\n for i in range(col):\r\n \r\n cp = parda.iloc[:,2+i]\r\n cp = cp.mean()\r\n \r\n m[col+i][int(xp), int(yp)] = cp \r\n \r\n kma = km(data, nc=2) \r\n gmma = gmm(data, nc=2)\r\n \r\n kma_av = km(parda, nc=2) \r\n gmma_av = gmm(parda, nc=2)\r\n \r\n kma = pd.DataFrame(kma)\r\n \r\n kma_av = pd.DataFrame(kma_av)\r\n \r\n gmma = pd.DataFrame(gmma)\r\n \r\n gmma_av = pd.DataFrame(gmma_av)\r\n \r\n for l in tqdm(range(len(data))):\r\n \r\n xp = data.iloc[l,0] \r\n yp = data.iloc[l,1] \r\n \r\n for n in range(col):\r\n\r\n m[2*col+n][int(xp), int(yp)] = kma.iloc[0+n,l] \r\n\r\n m[3*col+n][int(xp), int(yp)] = gmma.iloc[0+n,l]\r\n \r\n m[4*col+n][int(xp), int(yp)] = kma_av.iloc[0+n,l] \r\n\r\n m[5*col+n][int(xp), int(yp)] = gmma_av.iloc[0+n,l] \r\n \r\n if len(m) != 6*col:\r\n raise ValueError('The number of matrices is not correct')\r\n \r\n return m\r\n \r\n\r\ndef print_images(m): \r\n \r\n fig = plt.figure(figsize=(15, 25))\r\n ax = []\r\n\r\n for i in range(6*col):\r\n \r\n ax.append( fig.add_subplot(8, col, i+1) )\r\n \r\n ax[-1].set_xlabel('X')\r\n ax[-1].set_ylabel('Y') \r\n \r\n plt.imshow(m[i])\r\n \r\n for i in range(col): \r\n \r\n ax[i].set_title(\"Values\")\r\n ax[col+i].set_title(\"Averaged Values\")\r\n ax[2*col+i].set_title(\"KM Cluster\")\r\n ax[3*col+i].set_title(\"GMM Cluster\")\r\n ax[4*col+i].set_title(\"KM Cluster on Averaged Values\")\r\n ax[5*col+i].set_title(\"GMM Cluster on Averaged Values\") \r\n \r\n if len(ax) != len(images(data)):\r\n raise ValueError('The number of subplots is not correct')\r\n \r\n return ax\r\n\r\nprint_images(images(data))","sub_path":"esame/Images.py","file_name":"Images.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"138106808","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nfrom networkx import karate_club_graph, to_numpy_matrix\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef relu(X):\n return np.maximum(0,X)\n\ndef gcn_layer(A_hat, D_hat, X, W):\n return relu(D_hat**-1 * A_hat * X * W)\n\ndef main():\n zkc = karate_club_graph()\n order = sorted(list(zkc.nodes()))\n A = to_numpy_matrix(zkc, nodelist=order)\n I = np.eye(zkc.number_of_nodes())\n A_hat = A + I\n D_hat = np.array(np.sum(A_hat, axis=0))[0]\n D_hat = np.asmatrix(np.diag(D_hat))\n\n W_1 = np.random.normal(size=(zkc.number_of_nodes(), 4))\n W_2 = np.random.normal(size=(W_1.shape[1], 2))\n\n H_1 = gcn_layer(A_hat, D_hat, I, W_1)\n H_2 = gcn_layer(A_hat, D_hat, H_1, W_2)\n output = H_2\n\n feature_representations = {node: np.array(output)[node] for node in zkc.nodes()}\n\n plt.figure()\n for i in range(34):\n if zkc.nodes[i]['club'] == 'Mr. Hi':\n plt.scatter(np.array(output)[i,0], np.array(output)[i,1],color = 'b',alpha=0.5,s = 100)\n else:\n plt.scatter(np.array(output)[i,0], np.array(output)[i,1],color = 'r',alpha=0.5,s = 100)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"9RNN+LSTM/code/zkc.py","file_name":"zkc.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"121280358","text":"#! python\n\"\"\" Script for opening google maps with location entered as argument of script in CMD or if no argument then take data\nfrom clipboard\"\"\"\n# Written by Maciej Borkowski\n\nimport webbrowser\nimport sys\nimport pyperclip\n\naddressGoogleMaps = \"https://www.google.at/maps/place/\"\nif len(sys.argv) > 1:\n addressLocation = ' '.join(sys.argv[1:])\nelse:\n addressLocation = pyperclip.paste()\n\nprint(addressGoogleMaps + addressLocation)\nwebbrowser.open(addressGoogleMaps + addressLocation)","sub_path":"ch11WebScraping/prj1.py","file_name":"prj1.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"617238140","text":"import os\nimport sys\nfrom collections import namedtuple\nfrom heapq import heappush, heappop\n\ngrid = {}\nplayer = None\nkeys = {}\ndoors = {}\n\nwith open('day18/input.txt') as fh:\n lines = [line.strip() for line in fh.readlines()]\n for y, line in enumerate(lines):\n for x, c in enumerate(line):\n grid[x, y] = c\n if c == '@':\n player = x, y\n grid[x, y] = '.'\n if c in 'abcdefghijklmnopqrstuvwxyz':\n keys[c] = x, y\n if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':\n doors[c] = x, y\n\n\n# print(grid, player, keys, doors)\n\ndef manhattan(a, b):\n ax, ay = a\n bx, by = b\n return abs(ax - bx) + abs(ay - by)\n\n\ndef get_min_steps_left(position, found_keys):\n steps = 0\n x, y = position\n\n # estimate visiting keys\n # key_dists = sorted([(manhattan(position, kp), key, kp) for key, kp in keys.items()])\n # door_dists = sorted([(manhattan(position, dp), door, dp) for door, dp in doors.items()])\n #\n # furthest_key = key_dists[-1][0]\n # further_door_key = door_dists[-1][0]\n #\n # return max(furthest_key, further_door_key)\n\n next_keys = sorted(\n [(key, kp) for key, kp in keys.items() if key not in found_keys],\n key=lambda key_item: manhattan(key_item[1], position)\n )\n\n # next_doors = sorted(\n # [(door, dp) for door, dp in doors.items() if door not in found_keys],\n # key=lambda door_item: manhattan(door_item[1], position)\n # )\n\n if not next_keys:\n return 0\n\n return manhattan(position, next_keys[0][1])\n\n # if next_door[0] in found_keys:\n # return manhattan(position, next_door[1])\n # else:\n # return manhattan(position, next_key[1])\n\n # for key, key_pos in keys.items():\n # if key in found_keys:\n # continue\n # kx, ky = key_pos\n #\n # min_distance_to_key = abs(x - kx) + abs(y - ky)\n # steps += min_distance_to_key\n\n # estimate visiting doors\n\n return steps\n\n\n# start_min_steps_left = get_min_steps_left(player, [])\n# to_visit = []\n# to_visit.append((\n# 0 + start_min_steps_left,\n# 0,\n# start_min_steps_left,\n# player,\n# [],\n# [player],\n# ))\n\n# visited = {} # (position, nr of keys)\n\nmax_steps = 0\n\nminx = min(grid.keys(), key=lambda p: p[0])[0]\nmaxx = max(grid.keys(), key=lambda p: p[0])[0]\nminy = min(grid.keys(), key=lambda p: p[1])[1]\nmaxy = max(grid.keys(), key=lambda p: p[1])[1]\n\nbest_nr_keys = 0\n\ni = 0\n\n\ndef print_maze(x, y, path):\n global grid, minx, miny, maxx, maxy\n for _y in range(miny, maxy + 1):\n for _x in range(minx, maxx + 1):\n tile = grid[_x, _y]\n is_door = tile in doors.keys()\n if (_x, _y) == (x, y):\n o = '\\033[96m%s\\033[0m' % '@'\n else:\n\n if tile in keys.keys():\n o = '\\033[91m%s\\033[0m' % tile\n elif (_x, _y) in path and is_door:\n o = '\\033[95m%s\\033[0m' % tile\n elif is_door:\n o = '\\033[93m%s\\033[0m' % tile\n elif (_x, _y) in path and tile == '.':\n o = '\\033[42m \\033[0m'\n elif tile == '#':\n o = '\\033[47m \\033[0m'\n elif tile == '.':\n o = ' '\n else:\n o = tile\n\n print(o, end='')\n print('')\n\n\nkey_paths = {}\nkey_dependencies = {}\n\ndirs = [\n (1, 0),\n (-1, 0),\n (0, -1),\n (0, 1),\n]\n\n\ndef get_shortest_path(start, goal):\n paths = [[start]]\n\n while paths:\n path = paths.pop(0)\n position = path[-1]\n x, y = position\n\n if position == goal:\n return path\n\n for dx, dy in dirs:\n n_position = (x + dx, y + dy)\n n_path = path + [n_position]\n\n tile = grid[n_position]\n if tile != '#' and n_position not in path:\n paths.append(n_path)\n\n\nprint(\"Calculating path to each key\")\nfor key, key_pos in keys.items():\n print(\"Calculating path for key %s\" % key)\n shortest_path = get_shortest_path(player, key_pos)\n key_paths[key] = shortest_path\n\n key_dependencies[key] = []\n for path_pos in shortest_path:\n if path_pos in doors.values():\n # check if we didn't already find a key in the path so far\n key_dependencies[key].append(grid[path_pos].lower())\n\nmoves = []\n\nMove = namedtuple('Move', ['priority', 'total_cost', 'cost', 'r_cost', 'target_key', 'position', 'found_keys', 'path'])\n\nprint(\"Getting dependencies\")\nfor key, dependencies in key_dependencies.items():\n if not dependencies:\n moves.append(Move((1,), 0, 0, None, key, player, [], []))\n\n\ndef actual_key_dependencies(key, found_keys):\n return [\n key_dependency for key_dependency in key_dependencies[key]\n if key_dependency not in found_keys\n ]\n\n\nsolutions = []\n\nwhile moves:\n print(\"Top 3 strategies:\")\n # for s in moves[0:10]:\n # print(\" - \", s)\n\n strategy = heappop(moves)\n priority, total_cost, cost, remaining_cost, target_key, position, found_keys, path = strategy\n\n print(\"%s + %s: %s\" % (found_keys, target_key, strategy))\n\n key_position = keys[target_key]\n key_path = get_shortest_path(position, key_position)\n new_cost = len(path) + len(key_path) - 1\n\n new_found_keys = found_keys + [target_key]\n\n not_found_keys = [key for key in keys.keys() if key not in new_found_keys]\n next_keys = [\n key for key in not_found_keys if not actual_key_dependencies(key, new_found_keys)\n ]\n\n # new_total_cost = cost +\n\n new_priority = (\n new_cost / len(new_found_keys), # - len(new_found_keys),\n )\n\n new_path = path + key_path[1:]\n for next_key in next_keys:\n # next_key_cost = get_shortest_path(keys[next_key])\n heappush(moves, Move(\n new_priority,\n total_cost,\n new_cost,\n 0, # remaining cost\n next_key,\n key_position,\n new_found_keys,\n new_path\n ))\n\n os.system('clear')\n\n # print_maze(position[0], position[1], new_path)\n if not not_found_keys:\n print(\"Done! Total cost: %s\" % (new_cost))\n\n solutions.append((new_cost, new_found_keys))\n # break\n\n print(\"Continue searching for more?\")\n breakpoint()\n\nsolutions = sorted(solutions)\n\nsys.exit()\n\n\ndef search_next_key():\n debug_mode = 'a'\n while len(to_visit):\n further = False\n more_steps = False\n more_keys = False\n\n min_total_steps, steps, min_steps_left, (x, y), found_keys, path = heappop(to_visit)\n\n visited_key = ((x, y), tuple(sorted(found_keys)))\n if visited_key not in visited or visited[visited_key] < steps:\n visited[visited_key] = steps\n\n if steps > max_steps:\n max_steps = steps\n more_steps = True\n\n if (len(found_keys) > best_nr_keys):\n more_keys = True\n best_nr_keys = len(found_keys)\n\n # if (not found_keys and more_steps) or more_keys:\n if more_keys:\n further = True\n\n # find other locations\n\n # check target is goal\n reached_goal = len(found_keys) == len(keys)\n\n # Check locations to visit\n near_open_door = False\n if not reached_goal:\n for (dx, dy) in dirs:\n nx, ny = x + dx, y + dy\n tile = grid[nx, ny]\n is_empty = tile == '.'\n is_key = tile in keys.keys()\n is_door = tile in doors.keys()\n is_open_door = is_door and tile.lower() in found_keys\n if is_open_door:\n near_open_door = True\n can_visit = is_empty or is_key or is_open_door\n\n if can_visit:\n found_key = [tile] if is_key else []\n n_found_keys = list(set(found_keys + found_key))\n\n dir_min_steps_left = get_min_steps_left((nx, ny), n_found_keys)\n\n n_steps = (steps + 1)\n n_visited_key = (nx, ny), tuple(sorted(n_found_keys))\n if n_visited_key not in visited or n_steps < visited[n_visited_key]:\n heappush(to_visit, (\n n_steps + dir_min_steps_left,\n n_steps,\n dir_min_steps_left,\n (nx, ny),\n n_found_keys,\n path + [(x, y)]\n ))\n\n breaking = False\n if debug_mode == 'a':\n breaking = True\n if debug_mode == 'k':\n breaking = more_keys\n if debug_mode == 's':\n breaking = more_steps\n if debug_mode == 'd':\n breaking = near_open_door\n if debug_mode == 'g':\n breaking = reached_goal\n if debug_mode == 'e':\n breaking = False\n\n if breaking:\n os.system('clear')\n print_maze(x, y, path)\n\n print('Evaluated #%s:' % (i + 1,))\n # print(' - [%s,%s] %s / %s %s' % (steps + min_steps_left, steps, min_steps_left, (x, y), found_keys, '%s positions left' % len(to_visit))\n print(' [%s,%s] %s / %s %s' % (x, y, steps, min_total_steps, found_keys))\n print('')\n\n new_debug_mode = None\n while new_debug_mode == None:\n new_debug_mode = input(\n 'Debug? [a=always wait, k=next key, s=more steps, d=near open door, g=goal, e=end]: ').strip()\n if new_debug_mode == 'p':\n print(\"Future options:\")\n for _v in range(0, min(4, len(to_visit) - 1) + 1):\n v_min_total_steps, v_steps, v_min_steps_left, (v_x, v_y), v_found_keys, _ = to_visit[_v]\n print(' - [%s,%s] %s / %s %s' % (v_x, v_y, v_steps, v_min_total_steps, v_found_keys))\n new_debug_mode = None\n elif len(new_debug_mode) > 0:\n debug_mode = new_debug_mode\n print('')\n i += 1\n\n if reached_goal:\n print(\"Reached goal in %s steps\" % steps)\n break\n\nfor x in range(0, 10):\n pass\n","sub_path":"day18/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":9134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"609443874","text":"import matplotlib.pyplot as plt\nimport os.path\nimport re\nimport numpy as np\n\nqual=[]\ndepth=[]\ncol=[]\n\n# for root, dirs, files in os.walk('/results/Analysis/projects/NBS/1607759-rerun/'):\n# for file in files:\n# if re.match('TSVC.*[0-9].vcf$', file):\n# in_file = open('/results/Analysis/projects/NBS/1607759-rerun/' + file, 'r')\n# for line in in_file:\n# if re.match('#', line):\n# next\n# else:\n# array = line.split(\"\\t\")\n# q=array[5]\n# qual.append(q)\n# info = array[7]\n# info_array = info.split(\";\")\n# dp = info_array[2]\n# dp_new = dp.replace(\"DP=\", \"\")\n# depth.append(dp_new)\n# af = info_array[0]\n# af_new = af.replace(\"AF=\", \"\")\n# if float(af_new)==1:\n# col.append(\"b\")\n# else:\n# col.append(\"r\")\n#\n#\n# plt.scatter(depth, qual, c=col)\n# plt.ylim((0, 40000))\n# plt.xlim((0, 10000))\n# plt.xlabel('Read depth')\n# plt.ylabel('Variant QUAL')\n# plt.savefig('/results/Analysis/projects/NBS/1607759-rerun/depth_quality-colours.png')\n\ncolours=[]\ncommon_qual_VB=[]\ncommon_qual_BS=[]\nVB_qual=[]\nBS_qual=[]\ncommon_DP_VB=[]\ncommon_DP_BS=[]\nVB_DP=[]\nBS_DP=[]\n\ndef get_variants (file, tag):\n for line in file:\n if re.match('#', line):\n next\n else:\n array = line.split(\"\\t\")\n qual = float(array[5])\n info = array[7]\n info_array = info.split(\";\")\n dp = info_array[2]\n dp_new = float(dp.replace(\"DP=\", \"\"))\n if int(tag) == 0:\n VB_qual.append(qual)\n VB_DP.append(dp_new)\n elif int(tag) ==1:\n BS_qual.append(qual)\n BS_DP.append(dp_new)\n elif int(tag) == 2:\n common_qual_VB.append(qual)\n common_DP_VB.append(dp_new)\n else:\n common_qual_BS.append(qual)\n common_DP_BS.append(dp_new)\n\nfor root, dirs, files in os.walk('/results/Analysis/projects/NBS/1607759-rerun/'):\n for dir in dirs:\n VB_file = open('/results/Analysis/projects/NBS/1607759-rerun/' + dir + '/0000.vcf')\n get_variants(VB_file, 0)\n BS_file = open('/results/Analysis/projects/NBS/1607759-rerun/' + dir + '/0001.vcf')\n get_variants(BS_file, 1)\n common_VB = open('/results/Analysis/projects/NBS/1607759-rerun/' + dir + '/0002.vcf')\n get_variants(common_VB, 2)\n common_BS = open('/results/Analysis/projects/NBS/1607759-rerun/' + dir + '/0003.vcf')\n get_variants(common_BS, 3)\n\nplt.scatter(common_qual_BS, common_qual_VB)\nplt.xlabel('BS Quality')\nplt.ylabel('VB quality')\nplt.ylim((0, 40000))\nplt.xlim((0, 40000))\nplt.plot([0,40000], [0,40000])\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/matching_quality.png')\nplt.close()\n\nplt.scatter(common_DP_BS, common_DP_VB)\nplt.xlabel('BS read depth')\nplt.ylabel('VB read depth')\nplt.ylim((0, 10000))\nplt.xlim((0, 10000))\nplt.plot([0,10000], [0,10000])\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/matching_DP.png')\nplt.close()\n\nplt.hist(common_qual_VB, 50, color='b')\nplt.hist(VB_qual, 10, color='r')\nplt.xlabel('VB Quality')\nplt.ylabel('Frequency')\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/VB_qual_hist.png')\nplt.close()\n\nplt.hist(common_qual_BS, 50, color='b')\nplt.hist(BS_qual, 10, color='r')\nplt.xlabel('BS Quality')\nplt.ylabel('Frequency')\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/BS_qual_hist.png')\nplt.close()\n\nplt.hist(common_DP_VB, 50, color='b')\nplt.hist(VB_DP, 10, color='r')\nplt.xlabel('VB Read Depth')\nplt.ylabel('Frequency')\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/VB_DP_hist.png')\nplt.close()\n\nplt.hist(common_DP_BS, 50, color='b')\nplt.hist(BS_DP, 10, color='r')\nplt.xlabel('BS Read Depth')\nplt.ylabel('Frequency')\nplt.savefig('/results/Analysis/projects/NBS/1607759-rerun/BS_DP_hist.png')\nplt.close()","sub_path":"scripts/quality_plots.py","file_name":"quality_plots.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"437346186","text":"# -*- coding: utf-8 -*-\nimport sqlite3\nimport os\nfrom music.tags import Tags\nfrom datetime import datetime\nimport time\nimport logging\nimport threading\nfrom common import messager, xdg\nfrom data.bdd import BDD\n\nlogger = logging.getLogger(__name__)\n\n\n\n\t\t\t\n\nclass SpecialElement():\n\tdef __init__(self, data, module, thumbnail_path=None):\n\t\tif(type(data).__name__=='int'):\n\t\t\tID = str(data)\n\t\t\tquery = \"SELECT \" + module + \"_ID, filename, folder, rating, categorie_ID, univers_ID, size FROM \" + module + \"s WHERE \" + module + \"_ID = \" + ID\n\t\t\tdata = bdd.execute_and_return(query)\n\t\t\t\n\t\tself.module = module\n\t\tself.ID = str(data[0])\n\t\tself.folder = data[2]\n\t\tself.file = data[1]\n\t\tself.filename = data[1]\n\t\tself.path = data[2] + '/' + data[1]\n\t\tself.rating = data[3]\n\t\tself.c_ID = data[4]\n\t\tself.u_ID = data[5]\n\t\tself.size = data[6]\n\t\t\n\t\tself.thumbnail_path = thumbnail_path\n\t\tself.flags = set()\n\t\n\tdef setRating(self, new_rating):\n\t\tquery = \"UPDATE \" + self.module + \"s SET rating = \" + str(new_rating) + \" WHERE \" + self.module + \"_ID = \" + self.ID\n\t\tbdd.execute(query)\n\t\tself.rating = new_rating\n\t\n\tdef set_path(self, folder, file_name):\n\t\tquery = \"UPDATE \" + self.module + \"s SET folder = ?, filename = ? WHERE \" + self.module + \"_ID = \" + self.ID\n\t\tt = (folder, file_name)\n\t\tbdd.execute(query, t)\n\t\tself.path = folder + '/' + file_name\n\t\tself.folder = folder\n\t\tself.file = file_name\n\nclass Track():\n\tdef __init__(self, data):\n\t\t'''\n\t\t\tData might contain a Track ID (from which we retrieve real data from db) or a tuple containing all data necessary\n\t\t'''\n\t\tif(type(data).__name__=='int'):\n\t\t\tID = str(data)\n\t\t\tquery = \"SELECT track_ID, path, title, album, artist, length, playcount, rating FROM tracks WHERE track_ID = \" + ID\n\t\t\tdata = bdd.execute_and_return(query)\n\t\t\n\t\tself.ID = str(data[0])\n\t\tself.path = data[1]\n\t\tself.tags = {'title':data[2], 'album':data[3], 'artist':data[4], 'length':data[5]}\n\t\tself.title = data[2]\n\t\tself.album = data[3]\n\t\tself.artist = data[4]\n\t\tself.length = data[5]\n\t\tself.play_count = data[6]\n\t\tself.playcount = data[6]\n\t\tself.rating = data[7]\n\t\tself.time_started = int( time.mktime( datetime.utcnow().timetuple() ) )\n\t\ttemp, self.format = os.path.splitext(self.path)\n\t\t\n\t\tself.flags = set()\n\t\tself.priority = 0\n\t\tself.bridgeSrc = None\n\t\tself.bridgeDest = None\n\t\n\tdef change_rating(self, w, new_rating):\n\t\tquery = \"UPDATE tracks SET rating = \" + str(new_rating) + \" WHERE track_ID = \" + self.ID\n\t\tbdd.execute(query)\n\t\tself.rating = new_rating\n\t\tmessager.diffuser('track_data_changed', self, self)\n\t\n\t@staticmethod\n\tdef fromPath(path):\n\t\ttry:\n\t\t\ttrack = bdd.getTracks({'path':path})[0] # This file exists in our database\n\t\texcept IndexError:\n\t\t\ttags = Tags.fromPath(path)\n\t\t\ttrack = Track([0, path, tags['title'], tags['album'], tags['artist'], tags['length'], 0, 0])\n\t\treturn track\n\t\t\t\n\t\t\t\n\t\n\tdef get_tags(self):\n\t\treturn Tags.fromPath(self.path)\n\t\t\n\tdef incrementPlayCount(self):\n\t\tself.playcount += 1\n\t\tquery = \"UPDATE tracks SET playcount = playcount + 1 WHERE track_ID = \" + self.ID\n\t\tbdd.execute(query)\n\t\t\n\t\tdef scrobble():\n\t\t\ttime_elapsed = int( time.mktime( datetime.utcnow().timetuple())) - self.time_started\n\t\t\tif(time_elapsed > 120):\n\t\t\t\ttry:\n\t\t\t\t\tBDD.network.scrobble(self.artist, self.title, int(self.time_started))\n\t\t\t\t\tif len(BDD.network_cache) > 0:\n\t\t\t\t\t\tfor tup in BDD.network_cache:\n\t\t\t\t\t\t\tBDD.network.scrobble(tup[0], tup[1], tup[2])\n\t\t\t\t\t\tBDD.network_cache = []\n\t\t\t\t\t\tBDD.saveCache() # update cache\n\t\t\t\texcept:\n\t\t\t\t\tBDD.network_cache.append((self.artist, self.title, int(self.time_started)))\n\t\t\t\t\t\n\t\ttask = threading.Thread(target=scrobble)\n\t\ttask.start()\n\t\t\n\t\t\n\tdef initializeTimeStarted(self):\n\t\tself.time_started = int( time.mktime( datetime.utcnow().timetuple() ) )\n\t\t\n\tdef set_tag(self, tag, value):\n\t\tTags.setValue(self.path, tag, value)\n\t\tquery = 'UPDATE tracks SET ' + tag + ' = ? WHERE track_ID = ?'\n\t\tt = (value, self.ID)\n\t\tbdd.execute(query, t)\n\t\tself.tags[tag] = value\n\t\tmessager.diffuser('track_data_changed', self, self)\n\t\t\n\nclass QueuedTrack(Track):\n\t'''\n\t\tA Track with many flags. Currently not used (Actually these flags are packed in every track)\n\t'''\n\tdef __init__(self, data, queue):\n\t\tTrack.__init__(self, data)\n\t\tself.queue = queue\n\t\tself.flags = set()\n\t\tself.priority = 0\n\t\tself.bridgeSrc = None\n\t\tself.bridgeDest = None\n\t\t\n\t\t\nclass Container():\n\t\"\"\"\n\t\tEither a category or a universe\n\t\tCategories are \"form container\" whereas universes are \"content container\"\n\t\tcontainer_type (universe, container)\n\t\ttype = module (images, videos, etc...)\n\t\tTODO delete recursive\n\t\"\"\"\n\tdef __init__(self, data, container_type, module):\n\t\t# First we make sure container_type is the right SQL word\n\t\tcontainer_type = self.getTrueContainerType(container_type)\n\t\t\t\n\t\tif(type(data).__name__ == 'int'):\n\t\t\tID = str(data)\n\t\t\tquery = \"SELECT * FROM \" + container_type + \"_\" + module + \"s WHERE \" + container_type + \"_ID = \" + ID\n\t\t\tdata = bdd.execute_and_return(query)\n\t\t\n\t\tself.ID = data[0]\n\t\tself.label = data[1]\n\t\tself.parent_ID = data[2]\n\t\tself.thumbnail_ID = data[3]\n\t\t\n\t\ttry:\n\t\t\tself.rating = data[4]\n\t\texcept IndexError:\n\t\t\tself.rating = -1\n\t\tself.module = module\n\t\tself.container_type = container_type\n\t\t\n\tdef __str__(self):\n\t\treturn self.label + ' (' + self.container_type + ')'\n\t\n\t\n\tdef addElements(self, IDList):\n\t\tbdd.conn.execute('UPDATE ' + self.module + 's SET ' + self.container_type + '_ID = ' + str(self.ID) + ' WHERE ' + self.module + '_ID IN (%s)' % (\"?,\" * len(IDList))[:-1], IDList)\n\t\tbdd.conn.commit()\n\t\t\n\t@staticmethod\n\tdef create(container_type, module, name, parent_ID=0):\n\t\tcontainer_type = Container.getTrueContainerType(container_type)\n\t\tt = (unicode(name), parent_ID,)\n\t\tquery = \"INSERT INTO \" + container_type + \"_\" + module + \"s (\" + container_type + \"_L, parent_ID) VALUES(?, ?);\"\n\t\t#ex = INSERT INTO categorie_images (categorie_L) VALUES(?)\n\t\tbdd.c.execute(query, t)\n\t\tnewID = bdd.execute_and_return(\"SELECT last_insert_rowid() FROM \" + container_type + \"_\" + module + \"s;\")[0]\n\t\tbdd.conn.commit()\n\t\treturn Container((newID, name, parent_ID, 0), container_type, module)\n\t\n\tdef delete(self):\n\t\tbdd.execute('DELETE FROM ' + self.container_type + '_' + self.module + 's WHERE ' + self.container_type + '_ID = ?', (self.ID,))\n\t\t\n\t\n\tdef getThumbnailPath(self, size='128'):\n\t\tif(self.thumbnail_ID != 0):\n\t\t\tthumbnail_path = xdg.get_thumbnail_dir(self.module + '/128/')\n\t\t\tpath = thumbnail_path + str(self.thumbnail_ID) + '.jpg'\n\t\telse:\n\t\t\tpath = None\n\t\treturn path\n\t\n\t@staticmethod\n\tdef getTrueContainerType(container_type):\n\t\tif(container_type == 'category' or container_type == 'c'):\n\t\t\tcontainer_type = 'categorie'\n\t\telif(container_type == 'universe' or container_type == 'u'):\n\t\t\tcontainer_type = 'univers'\n\t\t\t\n\t\treturn container_type\n\t\n\tdef set_thumbnail_ID(self, element_ID):\n\t\tquery = 'UPDATE ' + self.container_type + '_' + self.module + 's SET thumbnail_ID = ? WHERE ' + self.container_type + '_ID = ?'\n\t\tt = (element_ID, self.ID)\n\t\tbdd.execute(query, t)\n\t\t\n\t\tself.thumbnail_ID = element_ID\n\t\tlogger.debug(\"Thumbnail\")\n\t\t\nbdd = BDD()","sub_path":"data/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"136660847","text":"from urllib.parse import urlparse\n\ndef get_domain_name(url):\n try:\n results = get_sub_domain_name(url).split('.')\n return results[-2] + '.' +results[-1]\n except:\n return ''\n\ndef get_sub_domain_name(url):\n try:\n return urlparse(url).netloc\n except:\n return ''\n\n#print(get_domain_name('https://thenewboston.com/index.php'))\n#print(get_domain_name('http://www.rthk.org.hk/'))","sub_path":"domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"292882474","text":"import numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nimport datetime as dt\nfrom flask import Flask, jsonify\n\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n\n@app.route(\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n \"Available Routes:
\"\n f\"/api/v1.0/precipitation
\"\n f\"/api/v1.0/stations
\"\n f\"/api/v1.0/tobs
\"\n f\"/api/v1.0/<start>
\"\n f\"/api/v1.0/<start>/<end>
\"\n )\n\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n session = Session(engine)\n results = session.query(Measurement.date, Measurement.prcp).all()\n\n session.close()\n \n percp = list(np.ravel(results))\n return jsonify(percp)\n\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n results = session.query(Station.station).all()\n\n session.close()\n\n stations = list(np.ravel(results))\n return jsonify(stations)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n session = Session(engine)\n for row in session.query(Measurement).order_by(Measurement.date.desc()).limit(1):\n recent=dt.datetime.strptime(row.date, '%Y-%m-%d')\n one_year = recent -dt.timedelta(365)\n top = session.query(Station.station).filter(Measurement.station == Station.station).\\\n group_by(Measurement.station).order_by(func.count(Measurement.station).desc()).all()\n\n results = session.query(Measurement.tobs).order_by(Measurement.date.desc()).filter(Measurement.date >= one_year).filter(Measurement.station == top[0][0]).all()\n session.close()\n\n tobs = list(np.ravel(results))\n return jsonify(tobs)\n\n@app.route(\"/api/v1.0/\")\ndef start(start):\n session = Session(engine)\n start_date = dt.datetime.strptime(start,'%Y-%m-%d')\n results = session.query(func.min(Measurement.tobs),func.max(Measurement.tobs),func.avg(Measurement.tobs)).filter(Measurement.date >= start_date).all()\n session.close()\n\n start_temps = list(np.ravel(results))\n return jsonify(start_temps)\n\n@app.route(\"/api/v1.0//\")\ndef start_end(start,end):\n session = Session(engine)\n start_date = dt.datetime.strptime(start,'%Y-%m-%d')\n end_date = dt.datetime.strptime(end,'%Y-%m-%d')\n\n results = session.query(func.min(Measurement.tobs),func.max(Measurement.tobs),func.avg(Measurement.tobs)).filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n session.close()\n\n start_end_temps = list(np.ravel(results))\n return jsonify(start_end_temps)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Carter_Kioski_Answers/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"474754177","text":"import pandas as pd\n\ndef analysis(file, user_id):\n times = 0\n minutes = 0\n try:\n df = pd.read_json(file, orient = 'records')\n except:\n return 0, 0\n df2 = df[df['user_id'] == user_id]\n times = len(df2)\n if times == 0:\n return 0, 0\n minutes = df2[['user_id', 'minutes']].groupby('user_id').sum().loc[user_id, 'minutes']\n return times, minutes\n\nif __name__ == '__main__':\n t, m = analysis('./user_study.json', 5348)\n print(t, m)\n\n","sub_path":"w6/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91408237","text":"#!/bin/env python\n\n# mktagged_docs.py: this script convert HTRC extracted features files into\n# csv files of tokens appearing on each page and fit for parsing by Doc2Vec\n#\n# Jed Dobson\n# James.E.Dobson@Dartmouth.EDU\n# June 2020\n# \n# htrc-vector-project\n#\n\nfrom htrc_features import FeatureReader\nimport csv\nimport os\nfrom glob import glob\n\nimport argparse\n\nparser = argparse.ArgumentParser(\n description='create tagged document from HTRC extracted features')\n\nparser.add_argument('-f','--file',help=\"filename of HTRC file\",dest='filename',action='store')\nargs = parser.parse_args()\n\nif args.filename == None:\n print(\"Error: Need HTRC file!\")\n exit()\n\n# strip extension and add csv\noutput_csv = os.path.splitext(args.filename)[0]\noutput_csv = os.path.splitext(output_csv)[0]\noutput_csv = output_csv + \".csv\"\n\n# input file\nhtrc_file = args.filename\n\nfile = open(output_csv, 'w', newline='')\nwriter = csv.writer(file)\n\n# iterate\ntokens=list()\n\nprint(\"opening {0}\".format(htrc_file))\nfr = FeatureReader([htrc_file])\nvol = next(fr.volumes())\nptc = vol.tokenlist(pos=False, case=False).reset_index().drop(['section'], axis=1)\npage_list = set(ptc['page'])\n\nprint(\"reading pages\")\nfor page in page_list:\n page_data = str()\n for page_tokens in ptc.loc[ptc['page'] == page].iterrows():\n if page_tokens[1][1].isalpha():\n page_data += (' '.join([page_tokens[1][1]] * page_tokens[1][2])) + \" \"\n writer.writerow(page_data.split()) \n","sub_path":"scripts/mktagged_docs.py","file_name":"mktagged_docs.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395877157","text":"from collections import Counter as c\nn,t=map(int,input().split())\nli=[]\nans=''\nfor i in range(n):\n li.append(input())\nfor i in range(t):\n lo=[]\n for j in li:\n lo.append(j[i])\n co=c(lo)\n k=max(co.values())\n op=chr(133)\n for j in co.keys():\n if co[j]==k:\n op=min(j,op)\n ans+=op\nprint(ans)\n","sub_path":"Hackerank/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109931475","text":"# -*- coding: utf-8 -*-\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom admin_tools.dashboard import modules, Dashboard, AppIndexDashboard\nfrom datetime import datetime\n\nfrom examinees.models import Examinee, ChangeRecord, NoResponseExaminee, STATUS_STUDY_CANCEL, STATUS_STUDY_EXCLUDE\n\nimport locale\nimport calendar\n\ntry:\n\tlocale.setlocale(locale.LC_ALL, 'ko_KR.utf8')\nexcept:\n\tlocale.setlocale(locale.LC_ALL, 'ko_KR.eucKR')\n\n\nclass CustomIndexDashboard(Dashboard):\n\ttitle = ''\n\tcolumns = 3\n\n\tdef init_with_context(self, context):\n\n\t\tfor c in context:\n\t\t\tif 'user' in c:\n\t\t\t\tuser = c['user']\n\t\t\t\tprint(user)\n\t\t\t\tbreak\n\n\t\tif True:\n\t\t\tself.children.append(modules.ModelList(\n\t\t\t\t_('메시지 관리'),\n\t\t\t\tmodels=[\n\t\t\t\t\t'tools.models.SmsSendHistory',\n\t\t\t\t\t'tools.models.SmsTemplate',\n\t\t\t\t\t'tools.models.SmsSender',\n\t\t\t\t\t'tools.models.AutoSmsSenderManager',\n\t\t\t\t\t'tools.models.MassiveSmsReservation'\n\t\t\t\t]\n\t\t\t))\n\t\t\tself.children.append(modules.ModelList(\n\t\t\t\t_('수진자 관리'),\n\t\t\t\tmodels=[\n\t\t\t\t\t'examinees.models.Examinee',\n\t\t\t\t\t'examinees.models.MensesData',\n\t\t\t\t\t'examinees.models.MensesDataV2',\n\t\t\t\t\t'examinees.models.ChangeRecord',\n\t\t\t\t\t'examinees.models.ExamineeMenopausalStatus',\n\t\t\t\t\t'examinees.models.VisitSchedule',\n\t\t\t\t\t'examinees.models.VisitScheduleV2',\n\t\t\t\t\t'examinees.models.NoResponseExaminee',\n\t\t\t\t\t'examinees.models.SuspensionExaminee',\n\t\t\t\t\t'examinees.models.MenopauseExaminee',\n\t\t\t\t\t'examinees.models.ExamineeQuestion',\n\t\t\t\t\t'examinees.models.ReservationInquiry',\n\t\t\t\t\t'examinees.models.ExamineeMenQoL',\n\t\t\t\t]\n\t\t\t))\n\n\t\t\tself.children.append(modules.ModelList(\n\t\t\t\t_('홈페이지 관리'),\n\t\t\t\tmodels=[\n\t\t\t\t\t'user_app.models.Question',\n\t\t\t\t\t'user_app.models.Thesis',\n\t\t\t\t\t'user_app.models.Notice',\n\t\t\t\t\t'user_app.models.NewsLetter',\n\t\t\t\t\t'user_app.models.FAQ',\n\t\t\t\t]\n\t\t\t))\n\n\nclass CustomAppIndexDashboard(AppIndexDashboard):\n\t# we disable title because its redundant with the model list module\n\ttitle = ''\n\n\tdef __init__(self, *args, **kwargs):\n\t\tAppIndexDashboard.__init__(self, *args, **kwargs)\n\n\t\t# append a model list module and a recent actions module\n\t\tself.children += [\n\t\t\tmodules.ModelList(self.app_title, self.models),\n\t\t\tmodules.RecentActions(\n\t\t\t\t_('App Index - Recent Actions'),\n\t\t\t\tinclude_list=self.get_app_content_types(),\n\t\t\t\tlimit=5\n\t\t\t)\n\t\t]\n\n\tdef init_with_context(self, context):\n\t\t\"\"\"\n\t\tUse this method if you need to access the request context.\n\t\t\"\"\"\n\t\treturn super(CustomAppIndexDashboard, self).init_with_context(context)\n","sub_path":"cohort/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"34348315","text":"from lib import fileutil\nimport os\ndef createInputFile(directory,filename):\n filePats = fileutil.getFilePaths(directory,[\".exe\",\".dll\"])\n print(filePats)\n with open(filename,'w') as ofile:\n for fp in filePats:\n ofile.write(fp)\n ofile.write(os.linesep)\n\ndef getTxtLineByLine(path):\n with open(path,\"r\") as f:\n content =f.readlines()\n # you may also want to remove whitespace characters like `\\n` at the end of each line\n\n print(content)\nif __name__ == '__main__':\n dr = \"/home/nislab3/Desktop/Work/SHAID_VIRUS/BENIGN\"\n drM= \"/home/nislab3/Desktop/Work/SHAID_VIRUS\"\n drMeta = \"/media/nislab/5bece7d3-c708-491c-af60-c9e5278efd24/DATASET_SAMPLE/METAMORPHIC\"\n fnMeta =\"/meta_mal.txt\"\n fn =\"benign.txt\"\n fnM =\"malware.txt\"\n\n createInputFile(dr,drM+\"/\"+fn)\n #createInputFile(drM,fnM)\n #createInputFile(drMeta,fnMeta)\n #getTxtLineByLine(fn)","sub_path":"Project/featurework/getPath.py","file_name":"getPath.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"342619877","text":"import numpy as np\nimport cv2\n\n#Reading input image\nimg = cv2.imread('21road.jpg')\n\n#Converting the input image to gray scale image\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\nkernel_size = 7 \n\n#Smoothing the image using Gaussian Blur\nblur = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\n\n#Finding the edges in the image using Canny edge detector\nedge = cv2.Canny(blur, 100, 200, apertureSize=3) \ncv2.imwrite(\"21road_canny.jpg\",edge)\n\nminLineLength = 100 # min length of line, line segments shorter than this are rejected \n\nmaxLineGap = 10 # max allowed gap between line segmnets to treat them as single line \n\nthreshold = 50 # Min No of votes(points on line) for it to be a line\n\nrho = 1 #Distance resolution of the accumulator in pixels\n\ntheta = np.pi/180 #Angle resolution of the accumulator in radians\n\n#Finding lines in the image\nlines = cv2.HoughLinesP(edge,rho,theta,threshold,minLineLength,maxLineGap)\n\ncolor = (0,255,0) # the color of the line to be drawn\nthickness = 4 # thickness of the line\n\n#Drawing the detected lines on the image\nfor x1,y1,x2,y2 in lines[0]: #For each line\n\tcv2.line(img,(x1,y1),(x2,y2),color,thickness) #x1,y1 and x2,y2 and the 2 points of the line.\n\ncv2.imwrite(\"21road_hough.jpg\",img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Sem2/MachinePerception/MP_assignment1/CODE/11_road_markers.py","file_name":"11_road_markers.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"245628016","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: wuyue\n@contact: wuyue92tree@163.com\n@software: IntelliJ IDEA\n@file: urls.py\n@create at: 2018-09-08 20:52\n\n这一行开始写关于本文件的说明与解释\n\"\"\"\n\n\nfrom django.urls import path, include\nfrom rest_framework import routers\nfrom .views import *\n\nrouter = routers.DefaultRouter()\nrouter.register('host', HostViewSets)\nrouter.register('supplier', SupplierViewSet)\nrouter.register('group', GroupViewSet)\nrouter.register('system', SystemViewSet)\n\nurlpatterns = [\n path('', include(router.urls))\n]\n","sub_path":"rest_backend/apps/Resource/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"602637710","text":"import os\n\ndef getDictUpcToDirName(baseImgDirPath):\n retDict = {}\n\n listOfDirs = os.listdir(baseImgDirPath)\n for entry in listOfDirs:\n path = baseImgDirPath + '/' + entry\n if os.path.isdir(path):\n upc = entry.split(',')[-1].strip()\n listOfFiles = os.listdir(path)\n if len(listOfFiles) > 0:\n retDict[upc] = entry + '/' + listOfFiles[0]\n return retDict\n\nif __name__ == '__main__':\n BASE_IMG_DIR_PATH = './angular-src/src/assets/imgs/wholesale'\n getDictUpcToDirName(BASE_IMG_DIR_PATH)","sub_path":"mongodbInsertScript/parseImgUrl.py","file_name":"parseImgUrl.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"424333900","text":"from odoo import http\nfrom odoo.addons.website_sale.controllers.main import WebsiteSale\n\n\nclass Academy(http.Controller):\n\n @http.route('/academy/academy', auth='public', website=True)\n def index(self, **kw):\n teachers = http.request.env['academy.teachers']\n return http.request.render('academy.index', {\n 'teachers': teachers.search([])\n })\n\n @http.route('/academy/', auth='public', website=True)\n def biography(self, teacher):\n return http.request.render('academy.biography', {\n 'person': teacher\n })\n\n\nclass WebsiteSaleInh(WebsiteSale):\n @http.route()\n def shop(self, page=0, category=None, search='', ppg=False, **post):\n print(\"Inherits correctly\")\n res = super(WebsiteSaleInh, self).shop(page=page, category=category, search=search, ppg=ppg, **post)\n import ipdb\n #ipdb.set_trace()\n res.qcontext['categories'] = res.qcontext['categories'].sorted(key=lambda r: r.name)\n res.qcontext['search'] = 'ipad'\n return res\n","sub_path":"controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"370833572","text":"import datetime\nimport json\nimport os\nfrom typing import Tuple, List, Callable\nimport collections.abc\nimport torch\nimport yt.wrapper as yt\n\nfrom lib.auc_loss import AUCLoss\nfrom lib.categorical_models import YabsLinearModel\nfrom lib.filter_useless import UselessFeaturesFilter\nfrom lib.log_loss import LogLoss\nfrom lib.online_model_saver import OnlineModelSaver\n\n\nfrom torch_ps.data_loader import SortedYTDataLoader, UnsortedYTDataLoader\nfrom torch_ps import BaseParameterServerModule\nfrom torch_ps.optim import ParameterServerOptimizer, Adagrad, EmbeddingFTRLOptimizer\nfrom torch_ps.util import coro_print_exception, timeit_recorder\nfrom torch_ps.hash_embedding import HashEmbedding\n\n\nclass PreallocatedYabsLinear(YabsLinearModel):\n def prepare_hook(self):\n for m in self.modules():\n if isinstance(m, HashEmbedding):\n m.parameter_with_grad.hash_table.reserve(1000000)\n\n\ndef create_model(model_config_path: str) -> BaseParameterServerModule:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n return PreallocatedYabsLinear(\n [x for x in model_conf['fields']],\n model_conf['target_field'],\n verbose_progress=model_conf[\"verbose_progress\"]\n )\n\n\ndef create_optimizer(model: BaseParameterServerModule, model_config_path: str) -> ParameterServerOptimizer:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n optimizers = [Adagrad([model.bias], model_conf['lr'])]\n optimizers = []\n if len(model_conf[\"fields\"]):\n optimizers += [\n EmbeddingFTRLOptimizer(\n model.embeddings.parameters(), dim=1, lr_eta=model_conf['lr'], lr_beta=0.0001, l1=model_conf['L1'],\n ttl=model_conf[\"expiration_ttl\"], safe=True\n )\n ]\n return ParameterServerOptimizer(*optimizers)\n\n\ndef create_model_and_optimizer(model_config_path: str) -> Tuple[BaseParameterServerModule, ParameterServerOptimizer]:\n model = create_model(model_config_path)\n optimizer = create_optimizer(model, model_config_path)\n return model, optimizer\n\n\ndef create_loss(model_config_path: str) -> torch.nn.modules.loss._Loss:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n if model_conf[\"loss\"] == \"logistic\":\n return LogLoss(size_average=False)\n elif model_conf[\"loss\"] == \"auc\":\n return AUCLoss(size_average=False)\n else:\n raise ValueError(\"Unknown loss {}\".format(model_conf[\"loss\"]))\n\n\ndef create_uris(model_config_path) -> List[str]:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n table = model_conf[\"train_table\"]\n datetime_format = model_conf.get('datetime_format', \"%Y%m%d%H%M\")\n start_date = model_conf[\"start_date\"]\n end_date = model_conf[\"end_date\"]\n start_dt = datetime.datetime.strptime(start_date, datetime_format)\n end_dt = datetime.datetime.strptime(end_date, datetime_format)\n uris = [\n yt.TablePath(\n table,\n lower_key=(start_dt + datetime.timedelta(hours=i)).strftime(datetime_format),\n upper_key=(start_dt + datetime.timedelta(hours=i + 1)).strftime(datetime_format)\n ).to_yson_string()\n for i in range(int((end_dt - start_dt).total_seconds() / 3600))\n ]\n return uris\n\n\ndef create_data_loader(model_config_path: str, token: str) -> collections.abc.AsyncIterable:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n yt_uris = create_uris(model_config_path)\n # Data loader\n if model_conf[\"system\"].get(\"preserve_uri_order\", True):\n return SortedYTDataLoader(yt_uris, token, model_conf[\"system\"][\"num_downloaders\"])\n else:\n return UnsortedYTDataLoader(yt_uris, token, model_conf[\"system\"][\"num_downloaders\"])\n\n\n@timeit_recorder.coro_timeit\n@coro_print_exception\nasync def update_counter(model, optim, loss, uri):\n \"\"\"\n Update the hour ttl counter for model updater\n \"\"\"\n for opt in optim.threaded_optimizers:\n opt.update_counter(1)\n\n\ndef create_uri_callbacks(model_config_path, uris) -> List[object]:\n with open(model_config_path, 'rt') as f:\n model_conf = json.load(f)\n token = os.environ[\"YT_TOKEN\"]\n yt_dir = model_conf[\"save_model_dir\"]\n datetime_format = model_conf.get('datetime_format', \"%Y%m%d%H%M\")\n start_date = datetime.datetime.strptime(model_conf[\"start_date\"], datetime_format)\n yt_client = yt.YtClient(proxy=\"hahn.yt.yandex.net\", token=token)\n last_hours_save = max(len(uris) - model_conf[\"last_hours_save\"], 0) if model_conf[\"last_hours_save\"] >= 0 else 0\n\n # We will reuse all cores that stay without work at the callback calling time\n system_conf = model_conf[\"system\"]\n num_threads = system_conf[\"num_workers\"] + system_conf[\"num_embedding_servers\"] + system_conf[\"num_deep_servers\"]\n\n # uri callback that will save our model on some last iterations\n save_callback = OnlineModelSaver(\n start_date, last_hours_save, len(uris), yt_dir,\n datetime_format, yt_client, token, model_conf[\"num_model_uploaders\"],\n num_threads_save=num_threads\n )\n\n # Uri callback that will walk over hash table and erase features with empty state\n # (for example, filtered out by expiration)\n\n erase_useless_callback = UselessFeaturesFilter(\n model_conf[\"filter_frequency\"],\n num_threads\n )\n\n return [update_counter, erase_useless_callback, save_callback]\n\n\ndef create_sync_policy(model_config_path):\n return None\n","sub_path":"linear_model.py","file_name":"linear_model.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"352269203","text":"\n\n#calss header\nclass _EUCALYPTUS():\n\tdef __init__(self,): \n\t\tself.name = \"EUCALYPTUS\"\n\t\tself.definitions = [u'any of several types of tree, found especially in Australia, that produce an oil with a strong smell. Eucalyptus oil is used in medicine and industry: ']\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/_eucalyptus.py","file_name":"_eucalyptus.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"199457411","text":"import MapReduce\nimport sys\n\n\"\"\"\nWord Count Example in the Simple Python MapReduce Framework\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # key: document identifier\n # value: document contents\n\tlengths={\n\t\t\"big\":0,\n\t\t\"medium\":0,\n\t\t\"small\":0}\n\t#big is >=10 small is <=4\n\tkey = record[0]\n\tvalue = record[1]\n\twords = value.split()\n\tfor w in words:\n\t\tif len(w)<4:\n\t\t\tlengths[\"small\"]+=1\n\t\telif len(w)<10:\n\t\t\tlengths[\"medium\"]+=1\n\t\telse:\n\t\t\tlengths[\"big\"]+=1\n\t\n\tfor key in lengths.keys():\n\t\tmr.emit_intermediate(key,lengths[key]) \n\n\ndef reducer(key, list_of_values):\n # key: word\n # value: list of occurrence counts\n total = 0\n for v in list_of_values:\n total += v\n mr.emit((key, total))\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/my scripts/length_of_words.py","file_name":"length_of_words.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"9213123","text":"#Bring in the raw .tar file and unpack them.\nimport os\nimport tarfile\n\n#Create output folder\nnewFolder = \"LandsatData2018\"\nos.makedirs(newFolder)\n\n#Extract files\nos.chdir(os.path.join(et.io.HOME, 'documents/'))\ntar = tarfile.open(\"Landsat_data/LC081920352018031001T1-SC20190601181703.tar.gz\", \"r:gz\")\ntar.extractall(newFolder)\ntar.close()\n\n###Now do the stacking and manipulation#####\nimport os\nimport numpy as np\n# File manipulation\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nimport rasterio as rio\nimport geopandas as gpd\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\n# if you get a library_spatial index error, run this in the consol:\n# brew install spatialindex\n\n#retry imports\n\n\n#et.data.get_data('cold-springs-fire')\n#Make your base directory\nos.chdir(os.path.join(et.io.HOME, 'Documents/Landsat_data/')) \n#Documents/Landsat_data/LandsatData2018\n#set parameters for display#############\nmpl.rcParams['figure.figsize'] = (10, 10)\nmpl.rcParams['axes.titlesize'] = 20\n###make a list of landsat files\n#glob(\"LC080340322016072301T1-SC20180214145802/crop/*\") #grabs all the files\nall_landsat_post_bands=glob(\"LandsatData2018/*band*.tif\") #grab only 'band' files\nall_landsat_post_bands\n\n#oragnize the data and view the data#\nall_landsat_post_bands.sort()\nall_landsat_post_bands\n\n\n#View a raster object in Python------------------------------------#\nwith rio.open(all_landsat_post_bands[3]) as src:\n landsat_band4 = src.read()\n\nep.plot_bands(landsat_band4[0],\n title=\"Landsat_2018_Time1\",\n cmap=\"Greys_r\")\n\n#-Create a stack object in python---------------------------------#\n#landsat band stack-----------------------------------------------#\n\nlandsat_Time1_path = \"/Documents/Landsat_data/outputs/landsat_time1_2018.tif\"\nes.stack(all_landsat_post_bands,landsat_Time1_path, nodata=None)\n\n#open the new raster stack\nwith rio.open(landsat_Time1_path) as src:\n landsat_Time1_path = src.read()\n\n#rename bands\nband_titles = [\"Band 1\", \"Blue\", \"Green\", \"Red\", \"NIR\",\n \"Band 6\", \"Band7\"]\n\n#plot them all together\nep.plot_bands(landsat_Time1_path,\n title=band_titles,\n cmap=\"Greys_r\")\n\n#plot a composite RGB image###\nep.plot_rgb(landsat_Time1_path,\n rgb=[3, 2, 1],\n title=\"RGB Composite Image\\n Post Fire Landsat Data\")\n\n#plot it again, this time stretch it so that it looks better-stretch 1\nep.plot_rgb(landsat_Time1_path,\n rgb=[3, 2, 1],\n title=\"Landsat RGB Image\\n Linear Stretch Applied\",\n stretch=True,\n str_clip=1)\n\n\n# Adjust the amount of linear stretch to futher brighten the image-stretch 2\nep.plot_rgb(landsat_Time1_path,\n rgb=[3, 2, 1],\n title=\"Landsat RGB Image\\n Linear Stretch Applied\",\n stretch=True,\n str_clip=3)\n\n# Here is a CIR image\nep.plot_rgb(landsat_Time1_path, rgb=[4, 3, 2],\n title=\"CIR Landsat Image Pre-Coldsprings Fire\",\n figsize=(10, 10))\n\n#Plot a histogram of the bands\nep.hist(landsat_Time1_path, title= band_titles)\n\n##Now that you have a sweet sweet stack, get the NDVI and the burn ratio\n\n#NDVI =(NIR/red)/(nir+red)-this worked\nnaip_ndvi = (landsat_post_fire[4] - landsat_post_fire[3]) / (landsat_post_fire[4] + landsat_post_fire[3])\n\nfig, ax = plt.subplots(figsize=(12,6))\nndvi = ax.imshow(naip_ndvi, cmap='PiYG',\n vmin=-1, vmax=1)\nfig.colorbar(ndvi, fraction=.05)\nax.set(title=\"Landsat Derived NDVI\\n 19 September 2015 - Cold Springs Fire, Colorado\")\nax.set_axis_off()\nplt.show()\n\n#Normalized burn index NBR=(NIR-SWIR)/(NIR+SWIR)-remember to that everything index to 0,\n#so 5 is 4 and do on 3 is 4, you get the idea\nnaip_nbr = (landsat_post_fire[4] - landsat_post_fire[6]) / (landsat_post_fire[4] + landsat_post_fire[6])\n\nfig, ax = plt.subplots(figsize=(12,6))\nnbr = ax.imshow(naip_nbr, cmap='PiYG',\n vmin=-1, vmax=1)\nfig.colorbar(nbr, fraction=.05)\nax.set(title=\"Landat Derived Nbr\\n 19 September 2015 - Cold Springs Fire, Colorado\")\nax.set_axis_off()\nplt.show()\n\n#export as a .tif-------------------------------------------------------------------------#\n#export as a .tif-------------------------------------------------------------------------#\nlandsat_nbr_path = \"/Documents/Landsat_data/outputs/LS_2018/nbr_time1.tif\"\nlandsat_ndvi_path = \"/Documents/Landsat_data/outputs/LS_2018/ndvi_time1.tif\"\ntype(naip_nbr), naip_nbr.dtype\n\n#in order to view it, you need to be able to export it as a .tif, get the meta data of another source\n\nwith rio.open(\"/Documents/Landsat_data/outputs/landsat_time1_2018.tif\") as src:\n naip_data_ras = src.read()\n naip_meta = src.profile\n \nnaip_meta\n# change the count or number of bands from 4 to 1\nnaip_meta['count'] = 1\n# change the data type to float rather than integer\nnaip_meta['dtype'] = \"float64\"\n#write the raster object\nwith rio.open(landsat_nbr_path, 'w', **naip_meta) as dst:\n dst.write(naip_nbr, 1)\nwith rio.open(landsat_ndvi_path, 'w', **naip_meta) as dst:\n dst.write(T1_ndvi, 1)\n\n######---------------------CLassification---------------------------------------------------###\n#unsuprevised classification#####-kmeans\n \nfrom spectral import *\nimport spectral.io.envi as envi\nimport pandas as pd\nfrom sklearn import cluster\nimport gdal\n#you already have the other packages loaded\n\ndataset = gdal.Open(\"/Desktop/earth_analytics/coldspringsfire/outputs/nbr.tif\")\nband = dataset.GetRasterBand(1)\nimg = dataset.ReadAsArray()\nX = img.reshape((-1, 1))\nk_means = cluster.KMeans(n_clusters=8)\nk_means.fit(X)\nX_cluster = k_means.labels_\nX_cluster = X_cluster.reshape(img.shape)\nplt.figure(figsize=(5,5))\nplt.imshow(X_cluster, cmap=\"hsv\")\nplt.show()\n\n##Write it to a raster object##\nwith rio.open(landsat_nbr_path, 'w', **naip_meta) as dst:\n dst.write(X_cluster, 1)\n\n\n\n\n\n\n","sub_path":"working_with_landsat_tunisia.py","file_name":"working_with_landsat_tunisia.py","file_ext":"py","file_size_in_byte":5864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"352666970","text":"# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the\n# Revised BSD License, included in this distribution as LICENSE\n\n\"\"\"\nFunctions for converting Jupyter notebooks\n\"\"\"\nfrom metatab import DEFAULT_METATAB_FILE, MetatabDoc\nfrom metatab.cli.core import prt\nfrom metatab.util import ensure_dir, copytree\nfrom os.path import abspath\nfrom os import getcwd\nfrom rowgenerators import Url\nfrom rowgenerators.util import fs_join as join\n\n\ndef convert_documentation(m):\n \"\"\"Run only the document conversion portion of the notebook conversion\n\n The final document will not be completel\n \"\"\"\n from .exporters import PackageExporter, DocumentationExporter\n from .preprocessors import ExtractInlineMetatabDoc\n from traitlets.config import Config\n from .core import logger\n from nbconvert.writers import FilesWriter\n import nbformat\n\n nb_path = Url(m.mt_file).parts.path\n\n with open(nb_path) as f:\n nb = nbformat.reads(f.read(), as_version=4)\n\n doc = ExtractInlineMetatabDoc().run(nb)\n\n package_name = doc.as_version(None).find_first_value('Root.Name')\n\n output_dir = join(getcwd(), package_name)\n\n de = DocumentationExporter(config=Config(), log=logger, metadata=doc_metadata(doc))\n prt('Converting documentation')\n output, resources = de.from_filename(nb_path)\n\n fw = FilesWriter()\n\n fw.build_directory = join(output_dir,'docs')\n fw.write(output, resources, notebook_name='notebook')\n prt(\"Wrote documentation to {}\".format(fw.build_directory))\n\n\ndef convert_notebook(m):\n\n from .core import logger\n from traitlets.config import Config\n from metatab.jupyter.exporters import PackageExporter, DocumentationExporter\n from nbconvert.writers import FilesWriter\n from os.path import normpath\n from nbconvert.preprocessors.execute import CellExecutionError\n\n prt('Convert notebook to Metatab source package')\n nb_path = Url(m.mt_file).parts.path\n\n c = Config()\n\n pe = PackageExporter(config=c, log=logger)\n\n prt('Running the notebook')\n\n pe.run(nb_path)\n\n de = DocumentationExporter(config=c, log=logger, metadata=doc_metadata(pe.doc))\n\n prt('Exporting documentation')\n output, resources = de.from_filename(nb_path)\n\n fw = FilesWriter()\n fw.build_directory = join(pe.output_dir,'docs')\n fw.write(output, resources, notebook_name='notebook')\n\n new_mt_file = join(pe.output_dir, DEFAULT_METATAB_FILE)\n\n doc = MetatabDoc(new_mt_file)\n\n de.update_metatab(doc, resources)\n\n for lib_dir in pe.lib_dirs:\n\n lib_dir = normpath(lib_dir).lstrip('./')\n\n doc['Resources'].new_term(\"Root.PythonLib\", lib_dir)\n\n path = abspath(lib_dir)\n dest = join(pe.output_dir, lib_dir)\n\n ensure_dir(dest)\n copytree(path, join(pe.output_dir, lib_dir))\n\n\n doc.write_csv()\n\n # Reset the input to use the new data\n\n prt('Running with new package file: {}'.format(new_mt_file))\n m.init_stage2(new_mt_file, '')\n\n\ndef doc_metadata(doc):\n \"\"\"Create a metadata dict from a MetatabDoc, for Document conversion\"\"\"\n\n r = doc['Root'].as_dict()\n r.update(doc['Contacts'].as_dict())\n r['author'] = r.get('author', r.get('creator', r.get('wrangler')))\n\n return r","sub_path":"metatab/jupyter/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"169611286","text":"class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n if not matrix or not matrix[0]:\n return 0\n \n row, col = len(matrix), len(matrix[0])\n result = 0\n side = [0] * col\n \n for i in range(row):\n newSide = [int(matrix[i][0])] + [0 for _ in range(col - 1)]\n \n for j in range(1, col):\n if matrix[i][j] == '1':\n newSide[j] = 1 + min(newSide[j - 1], side[j], side[j - 1])\n \n result = max(result, max(newSide))\n side = newSide\n \n return result**2\n","sub_path":"Problems/Python 3/221.py","file_name":"221.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"572196966","text":"import glob\nimport json\nimport os\nimport pickle\n\nimport lmdb\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom torch_geometric.data import Batch\n\nfrom ocpmodels.common.registry import registry\n\n\n@registry.register_dataset(\"trajectory_lmdb\")\nclass TrajectoryLmdbDataset(Dataset):\n def __init__(self, config, transform=None):\n super(TrajectoryLmdbDataset, self).__init__()\n\n self.config = config\n\n self.db_paths = glob.glob(\n os.path.join(self.config[\"src\"], \"\") + \"*lmdb\"\n )\n assert len(self.db_paths) > 0, \"No LMDBs found in {}\".format(\n self.config[\"src\"]\n )\n\n envs = [\n self.connect_db(self.db_paths[i])\n for i in range(len(self.db_paths))\n ]\n\n self._keys = [\n [f\"{j}\".encode(\"ascii\") for j in range(envs[i].stat()[\"entries\"])]\n for i in range(len(self.db_paths))\n ]\n self._keylens = [len(k) for k in self._keys]\n self._keylen_cumulative = np.cumsum(self._keylens).tolist()\n\n self.transform = transform\n\n for i in range(len(envs)):\n envs[i].close()\n\n def __len__(self):\n return sum(self._keylens)\n\n def __getitem__(self, idx):\n # Figure out which db this should be indexed from.\n db_idx = 0\n for i in range(len(self._keylen_cumulative)):\n if self._keylen_cumulative[i] > idx:\n db_idx = i\n break\n\n # Extract index of element within that db.\n el_idx = idx\n if db_idx != 0:\n el_idx = idx - self._keylen_cumulative[db_idx - 1]\n assert el_idx >= 0\n\n # Return features.\n env = self.connect_db(self.db_paths[db_idx])\n datapoint_pickled = env.begin().get(self._keys[db_idx][el_idx])\n data_object = pickle.loads(datapoint_pickled)\n data_object = (\n data_object\n if self.transform is None\n else self.transform(data_object)\n )\n env.close()\n\n return data_object\n\n def connect_db(self, lmdb_path=None):\n env = lmdb.open(\n lmdb_path,\n subdir=False,\n readonly=True,\n lock=False,\n readahead=False,\n map_size=1099511627776 * 2,\n )\n return env\n\n\ndef data_list_collater(data_list):\n batch = Batch.from_data_list(data_list)\n return batch\n","sub_path":"ocpmodels/datasets/trajectory_lmdb.py","file_name":"trajectory_lmdb.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"546383930","text":"from TwitterAPI import TwitterAPI, TwitterRequestError, TwitterConnectionError\nimport os\n\n\nconsumer_key = os.environ.get('TWITTER_CONSUMER_KEY')\nconsumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')\naccess_key = os.environ.get('TWITTER_ACCESS_KEY')\naccess_secret = os.environ.get('TWITTER_ACCESS_SECRET')\n\napi = TwitterAPI(consumer_key, consumer_secret, access_key, access_secret)\n\ndef get_tweets():\n return api.request('search/tweets',\n {'geocode': ','.join(['52.309062305249995',\n '-0.86387282715000002',\n '28.78mi'])})\n\nfrom time import time, sleep\nfrom math import floor\n\nstart = time()\nrequests = 0\nnow = 0\n\nnumreq = 479 # just to be sure\nt = floor(30*60/numreq)\n\nids = set()\nwhile True:\n lap = time()\n try:\n for item in get_tweets().get_iterator():\n requests += 1\n total = time() - start\n if time() - lap > 60:\n print('\\Total: {}\\nElapsed: {}\\nRequests: {}'.format(total, lap, requests))\n lap = time()\n if item['id'] not in ids:\n print('{} {} => {}'.format(item['created_at'], item['user']['screen_name'], item['text'].encode('utf-8')))\n ids.add(item['id'])\n except (TwitterRequestError, TwitterConnectionError):\n print(\"Request or connection failed\")\n sleep(t)\n","sub_path":"web/util/twitter_rest_twitterapi.py","file_name":"twitter_rest_twitterapi.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"416675248","text":"from typing import List\n\n\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n \"\"\"\n pre_sum_map 记录前缀和出现次数,用于统计, base case {0:1}\n sum_j = sum_i - k 用两数和思路,找到适合的前缀和 sum_j\n 从前缀和map找到次数\n \"\"\"\n pre_sum_map = {0: 1}\n ans = sum_i = 0\n for num in nums:\n sum_i += num\n sum_j = sum_i - k\n # 存在就 ans+1\n if sum_j in pre_sum_map:\n ans += pre_sum_map[sum_j]\n # 更新前缀和map\n pre_sum_map[sum_i] = pre_sum_map.get(sum_i, 0) + 1\n return ans\n\n\nif __name__ == '__main__':\n nums = [1, 1, 1]\n k = 2\n result = Solution().subarraySum(nums, k)\n print(result)\n","sub_path":"leetcode/560.和为 K 的子数组/560.和为 K 的子数组.py","file_name":"560.和为 K 的子数组.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"307699142","text":"'''\nCreated on Jan 29, 2017\n\n@author: Cristian\n'''\nimport random\n\nclass Sentence():\n '''\n class\n '''\n\n\n def __init__(self, string):\n '''\n Constructor\n '''\n self.__correctString = string\n self.__generatedString = self.prepareString()\n \n def getCorrectString(self):\n return self.__correctString\n \n def getGeneratedString(self):\n return self.__generatedString\n \n def prepareString(self):\n '''\n randomly mix the letters in the words of the sentence\n '''\n a = self.__correctString.split(\" \")\n string = \"\"\n for cuv in a:\n result = list(cuv)\n if len(cuv)>2:\n for i in range(5):\n x = random.randint(1,len(cuv)-2)\n y = random.randint(1,len(cuv)-2)\n result[x],result[y]=result[y],result[x]\n cuv = \"\".join(result)\n string +=cuv+\" \"\n return string\n \n\ndef testPrepare():\n string = \"sarmale cu salam\"\n a = Sentence(string)\n assert a.getCorrectString()==\"sarmale cu salam\"\ntestPrepare() ","sub_path":"FP/Subiect1.2/Sentence.py","file_name":"Sentence.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"80800911","text":"\"\"\"\nCreated by Dan on 08/15/2016, a test of data processing pipeline\nLast update: 06/15/2017, some major changes are made.\nAlthough the low-frequency background is subtracted, cell extraction is still performed on the uncorrected image. This may help eliminating artifacts.\nThis is the linux version. Don't mix it with the Windows version!\n\"\"\"\npackage_path = '/home/sillycat/Programming/Python/Image_toolbox/'\n\nimport os\nimport sys\nimport glob\nimport numpy as np\nsys.path.append(package_path)\nimport src.preprocessing.tifffunc as tifffunc\n\nfrom cell_extract import *\n\n# -----------------------------------------Big classes-------------------------------------------------\n\nclass pipeline_zstacks(object):\n \"\"\"\n This pipeline processes all the zstacks inside a folder.\n Procedure:\n 0. glob --- find all the z-stacks in the working folder. (completed)\n 1. load a stack of tif file (in z stack) (completed)\n 2. Split the file name to get time-point number, convert the original integers to 3-digit integers (completed)\n 2. Perform in-plane deblur on the z-stack, return a cleaner one (completed)\n 3. Perform Cell extraction on the deblurred z-stack, save as 'npz' (completed)\n 4. reconstruct t-stacks from z-stacks (can be run from outside)\n \"\"\"\n def __init__(self, work_folder, fname_flags= 'ZD', cdiam = 9):\n '''\n Initialize the pipeline\n '''\n self.work_folder = work_folder\n self.raw_list = glob.glob(work_folder + '*'+fname_flags + '*.tif')\n self.current_file = None # which data set am I working on?\n self.cdiam = cdiam\n\n Nfile = len(self.raw_list)\n if (Nfile ==0):\n print(\"Error! The folder does not contain any files.\")\n else:\n self.Nfile = Nfile\n print(\"There are\", Nfile, \"image stacks to be processed.\")\n self.process_log= np.zeros(Nfile)\n '''\n process_log: 0 --- unprocessed\n 1 --- loaded\n 2 --- sampled\n 3 --- extracted\n -1 --- error\n '''\n self.CE_dpt = Cell_extract(im_stack = None, diam = cdiam) # the default diameter of the blob: 9\n\n def load_file(self, nfile, verbose = True):\n '''\n Load the nfileth data file.\n Since the Z stacks is usually small, the stepwise loading is dropped here.\n size_th: threshold of the data file. Unit: MB.\n '''\n fname = self.raw_list[nfile]\n stack_size, self.stack_shape, self.tif_handle = tifffunc.tiff_describe(fname, handle_open = True)\n if verbose:\n print('Loaded file:', self.raw_list[nfile])\n print('Stack shape:', self.stack_shape)\n self.current_file = nfile\n\n\n def process(self, verbose = True):\n '''\n suppose the sampling has been done, and current file has been processed.\n If size_th > 500 GB, load stepwize\n '''\n fname_stem = os.path.splitext(self.raw_list[self.current_file])[0]\n\n raw_stack = self.tif_handle.asarray()\n self.CE_dpt.stack_reload(raw_stack, refill = True)\n self.CE_dpt.stack_blobs(bg_sub = 40, verbose = True)\n\n self.tif_handle.filehandle.close()\n self.tif_handle.close() # close the tif handle \n self.tif_handle = None\n self.process_log[self.current_file] = 3\n self.CE_dpt.save_data_list(fname_stem)\n\n if verbose:\n print(\"Done with file:\", fname_stem)\n return\n\n\n def run_pipeline(self, verbose = True):\n '''\n run the pipeline\n '''\n for zp in range(self.Nfile):\n '''\n 0 --- load file\n 1 --- Sampling\n 2 --- cell extraction and save\n '''\n self.load_file(zp)\n if verbose:\n print(\"Current file:\", self.current_file)\n self.process()\n#--------------------------------the counterpart for tstacks--------------------------------\n\nclass pipeline_tstacks(object):\n '''\n Goal: process all the t-stacks in a folder\n 0. Initialize: load the folder and load the files\n 1. extract cells and calculate the signals in each t-stack. If t-stack is too large, do this in steps.\n 2. Concatenate the processed key-values in a large dataset, then save.\n 3. Report progress.\n '''\n\n def __init__(self, work_folder, fname_flags = '_ZP_', cdiam = 9):\n '''\n work_folder: the folder that contains all the .tif files\n '''\n self.work_folder = work_folder\n self.raw_list = glob.glob(work_folder + '*'+fname_flags + '*.tif')\n self.current_file = None # which data set am I working on?\n self.cdiam = cdiam\n\n Nfile = len(self.raw_list)\n if (Nfile ==0):\n print(\"Error! The folder does not contain any files.\")\n else:\n self.Nfile = Nfile\n print(\"There are\", Nfile, \"image stacks to be processed.\")\n self.process_log= np.zeros(Nfile)\n '''\n process_log: 0 --- unprocessed\n 1 --- loaded\n 2 --- sampled\n 3 --- extracted\n -1 --- error\n '''\n self.CE_dpt = Cell_extract(im_stack = None, diam = cdiam) # the default diameter of the blob: 9\n return\n\n def load_file(self, nfile, size_th = 600, verbose = True):\n '''\n Load the nfileth data file.\n size_th: threshold of the data file. Unit: MB.\n '''\n fname = self.raw_list[nfile]\n stack_size, stack_shape, self.tif_handle = tifffunc.tiff_describe(fname, handle_open = True)\n if(stack_size > size_th):\n self.stepload = True\n n_groups = int(stack_size/size_th)+1\n nslices = stack_shape[0]\n ss_slices = int(nslices/n_groups)+1 # number of slices to import everytime\n stack_cut = np.zeros(n_groups + 1)\n stack_cut[:n_groups] = np.arange(nslices, step = ss_slices)\n stack_cut[-1] = nslices # the cutting-off positions\n self.stack_cut = stack_cut\n self.n_groups = n_groups\n if verbose:\n print(\"number of group:\", n_groups)\n print(\"Cutting-off places:\", stack_cut)\n else:\n self.stepload = False\n\n\n self.stack_shape = stack_shape\n self.current_file = nfile\n\n\n def sampling(self, nsamples, verbose = True):\n '''\n Read nsamples from the filehandle\n nsamples is an array or a list\n '''\n sample_stack = self.tif_handle.asarray()[nsamples] # this step is pretty time consuming\n\n blobs_sample = stack_blobs(sample_stack, self.cdiam, bg_sub = 40)\n self.cblobs = stack_redundreduct(blobs_sample, th = 4) # redundancy removed substack, saves the y,x coordinates of the extracted blobs\n if verbose:\n print(\"Done with sampling! Number of blobs:\", self.cblobs.shape[0])\n\n def process(self, verbose = True):\n '''\n suppose the sampling has been done, and current file has been processed.\n If size_th > 500 GB, load stepwize\n '''\n cblobs = self.cblobs\n fname_stem = os.path.splitext(self.raw_list[self.current_file])[0]\n # stepload or one-time load?\n if(self.stepload):\n signal_series = [] # create an empty list, which should be merged later\n si = self.stack_cut[0]\n for n_step in range(self.n_groups):\n sf = self.stack_cut[n_step+1]\n substack = self.tif_handle.asarray()[np.arange(si, sf).astype('uint16')] # this is a pretty risky approach, hopefully it can work! @_@\n self.CE_dpt.stack_reload(substack, refill = False)\n sub_time_series = self.CE_dpt.stack_signal_propagate(cblobs) # return\n signal_series.append(sub_time_series)\n si = sf\n if verbose:\n print(\"Processed step \", n_step)\n # now, let's concatenate the substacks in the list and compile it into a new dataset \n ts_signal = np.concatenate(tuple(signal_series), axis = 0)\n\n else: # one-time load\n raw_stack = self.tif_handle.asarray()\n self.CE_dpt.stack_reload(raw_stack)\n ts_signal = self.CE_dpt.stack_signal_propagate(cblobs)\n\n self.ts_dataset = position_signal_compile(cblobs, ts_signal)\n np.savez(fname_stem, **self.ts_dataset)\n self.tif_handle.filehandle.close()\n self.tif_handle.close() # close the tif handle \n self.tif_handle = None\n self.process_log[self.current_file] = 3\n\n\n def run_pipeline(self, n_samples, verbose = True):\n '''\n run the pipeline\n '''\n for zp in range(self.Nfile):\n '''\n 0 --- load file\n 1 --- Sampling\n 2 --- cell extraction and save\n '''\n self.load_file(zp)\n if verbose:\n print(\"Current file:\", self.current_file)\n self.sampling(n_samples)\n self.process()\n\n # should I also define an exit function? \n\n# -----------------------The main test function -----------------------\ndef main():\n data_path = package_path + 'data_test/'\n\n pz = pipeline_tstacks(data_path, fname_flags = 'TS')\n pz.run_pipeline([5,10,15,20])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/preprocessing/preprocess_pipeline.py","file_name":"preprocess_pipeline.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"544525625","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport pickle\nimport warnings\nimport numpy as np\nfrom Code.FeaturesExtractor import FeaturesExtractor\n\nwarnings.filterwarnings(\"ignore\")\n\nclass GenderIdentifier:\n\n def __init__(self, file_path, females_model_path, males_model_path):\n self.file_path = file_path\n self.features_extractor = FeaturesExtractor()\n # load models\n self.females_gmm = pickle.load(open(females_model_path, 'rb'))\n self.males_gmm = pickle.load(open(males_model_path, 'rb'))\n\n def process(self):\n vector = self.features_extractor.extract_features(self.file_path)\n winner = self.identify_gender(vector)\n\n print(\"%10s %3s %1s\" % (\"+ IDENTIFICATION\", \":\", winner))\n\n def identify_gender(self, vector):\n # female hypothesis scoring\n is_female_scores = np.array(self.females_gmm.score(vector))\n is_female_log_likelihood = is_female_scores.sum()\n # male hypothesis scoring\n is_male_scores = np.array(self.males_gmm.score(vector))\n is_male_log_likelihood = is_male_scores.sum()\n\n print(\"%10s %5s %1s\" % (\"+ FEMALE SCORE\",\":\", str(round(is_female_log_likelihood, 3))))\n print(\"%10s %7s %1s\" % (\"+ MALE SCORE\", \":\", str(round(is_male_log_likelihood,3))))\n\n if is_male_log_likelihood > is_female_log_likelihood: winner = \"male\"\n else : winner = \"female\"\n return winner\n\n\nif __name__== \"__main__\":\n gender_identifier = GenderIdentifier(sys.argv[1], \"females.gmm\", \"males.gmm\")\n gender_identifier.process()\n","sub_path":"identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155433936","text":"from threading import Thread\nfrom parser import *\nfrom messages import *\n\nclass Connection(Thread):\n \"\"\"Connections object represent a single client connected to the server\"\"\"\n def __init__(self,conn,state):\n Thread.__init__(self)\n self.parser = Parser()\n self.conn = conn\n self.PACKET_LENGTH = 1024\n self.state = state\n\n def run(self):\n print(\"Initiated connection to a client!!!\")\n print(\"Now I just have to do the rest :(\")\n while True:\n data = self.conn.recv(self.PACKET_LENGTH)\n # Do something with the data here..\n","sub_path":"server/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294913477","text":"# -*-coding:utf-8-*-\n\nname_file = open('./namelist.txt', 'r') # 연예인 이름 리스트의 텍스트 파일 (구분자는 '\\n'으로 가정)\narticle_file = open('./data.txt', 'r') # 크롤링한 기사 제목들의 텍스트 파일 (구분자는 '\\n'으로 가정)\noutput_file = open('./output.txt', 'w') # 언급 횟수의 내림차순으로 결과값을 쓸 텍스트파일 (비어있어야 함 구분자는 ','와 '\\n')\n\n# name_count_dict: {연예인 이름 : 언급 횟수}\nname_count_dict = {}\n# namelist: 연예인 이름 리스트.txt에 있는 모든 이름들의 리스트\nnamelist = []\n\n# namelist 만들기\nwhile True:\n name = name_file.readline()\n if name == '':\n break\n name = name[:-1] # '\\n' 제거\n namelist.append(name)\n\nname_file.close()\n\n\nwhile True:\n # 크롤링한 기사 제목 한 줄을 읽어옴\n article = article_file.readline()\n # 크롤링한 기사 제목을 모두 읽었으면 break\n if article == '':\n break\n\n # namelist 안의 모든 연예인 이름에 대해서 기사 제목에 포함되는 이름이 있는 지 확인\n for name in namelist:\n if name in article:\n # 아직 dict에 한 번도 추가된 적이 없으면 value = 1로 생성\n if not (name in name_count_dict):\n name_count_dict[name] = 1\n # dict에 추가된 적이 있으면 value++\n else:\n name_count_dict[name] += 1\n # 제목에 포함된 연예인 찾았으면 다음 기사로 넘어가기\n break\n\n# dict의 value값 (언급 횟수)를 기준으로 내림차순 정렬\nname_count_dict = sorted(name_count_dict.items(), reverse=True, key=lambda item: item[1])\n\nprint('name\\tcount\\t')\nprint('---------------')\nfor key, value in name_count_dict:\n # output 파일에 결과 쓰기\n output_file.write(key + ',' + str(value)+'\\n')\n print(key + \" \\t\", value)\n\noutput_file.readlines()\narticle_file.close()\noutput_file.close()\n","sub_path":"name-counter.py","file_name":"name-counter.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"625475668","text":"import discord\nimport db, utils\nfrom config import client, TEAMS, ROLE_CURRENT, ROLE_ANNUAL, VOTING_CHANNELS, LB_URL\n\n@utils.requires_captain\nasync def add_points(message):\n mes = utils.remove_command(message.content).split(\" \")\n team = [t for t in TEAMS if t['nick'].upper() == mes[0].upper()]\n if team:\n try:\n found_team = team[0]\n add_pts = int(mes[1])\n db.add_points(found_team['id'], add_pts)\n return f\"{add_pts} points have been added to {found_team['name']}\"\n except (ValueError, IndexError):\n return \"You did not specify how many points to add\"\n else:\n return \"I could not find a team name in that message\"\n\n@utils.requires_captain\nasync def print_lb(_):\n if LB_URL != \"\":\n return LB_URL\n else:\n out = '```\\n'\n for team in TEAMS:\n out += f\"{db.get_points(team['id'])} pts - {team['name']}\\n\"\n\n out += '```'\n return out\n\nasync def signup_user(payload):\n if db.is_on_team(payload.user_id):\n return\n\n emoji_name = payload.emoji if type(payload.emoji) == str else payload.emoji.name\n team_emoji = [t for t in TEAMS if t['emoji'] == emoji_name]\n if team_emoji:\n try:\n team = team_emoji[0]\n server = [x for x in client.guilds if x.id == payload.guild_id][0]\n user = discord.utils.get(server.members, id=payload.user_id)\n if team['capped']:\n channel = discord.utils.get(server.channels, id=payload.channel_id)\n message = await channel.fetch_message(id=payload.message_id)\n await message.remove_reaction(payload.emoji, user)\n else:\n team_id = team['id']\n new_role = discord.utils.get(server.roles, id=team_id)\n role_annual = discord.utils.get(server.roles, id=ROLE_ANNUAL)\n role_current = discord.utils.get(server.roles, id=ROLE_CURRENT)\n db.add_member(payload.user_id, team_id)\n await user.add_roles(new_role, role_current, role_annual)\n except Exception as e:\n print(f\"Something has gone wrong with adding team role: {e}\")\n\nasync def check_vote(payload):\n emoji_name = payload.emoji if type(payload.emoji) == str else payload.emoji.name\n\n if emoji_name != \"☑️\":\n return\n\n server = [x for x in client.guilds if x.id == payload.guild_id][0]\n channel = discord.utils.get(server.channels, id=payload.channel_id)\n if channel.id not in VOTING_CHANNELS:\n return\n\n reactor_team = db.get_team(payload.user_id)\n if reactor_team == None:\n return\n message = await channel.fetch_message(id=payload.message_id)\n poster_team = db.get_team(message.author.id)\n if reactor_team == poster_team:\n reactor = discord.utils.get(server.members, id=payload.user_id)\n await message.remove_reaction(payload.emoji, reactor)\n","sub_path":"src/teams.py","file_name":"teams.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147284030","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# 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, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom typing import Callable, List, Iterator\n\nimport ray\n\nfrom .interfaces import T, _Shard\n\n\nclass SourceShard(_Shard[T]):\n def __init__(self, name: str, is_repeatable: bool, is_repeated: bool):\n super(SourceShard, self).__init__()\n self._name = name\n self._is_repeatable = is_repeatable\n self._is_repeated = is_repeated\n\n def name(self) -> str:\n return self._name\n\n def repeated(self) -> bool:\n return self._is_repeated\n\n def repeatable(self) -> bool:\n \"\"\"\n Whether this source shard could generate source data repeatable.\n \"\"\"\n return self._is_repeatable\n\n def gen_data(self, **kwargs) -> Iterator[T]:\n raise NotImplementedError\n\n def __iter__(self):\n return self.gen_data()\n\n\nclass GeneratorSource(SourceShard[T]):\n def __init__(self,\n name: str,\n generator: Callable[[], Iterator[T]],\n is_repeatable: bool,\n is_repeated: bool):\n super(GeneratorSource, self).__init__(name, is_repeatable, is_repeated)\n self._generator = generator\n\n def repeat(self) -> \"GeneratorSource[T]\":\n if self.repeated():\n return self\n\n if not self.repeatable():\n raise Exception(\"can not repeat on an unrepeatable shard\")\n\n def repeat_gen():\n while True:\n it = self._generator()\n for item in it:\n yield item\n # repeatable generator can not repeat again\n return GeneratorSource(self.name() + \".repeat()\", repeat_gen, False, True)\n\n def gen_data(self, **kwargs) -> Iterator[T]:\n return self._generator(**kwargs)\n\n\nclass CacheDataSource(SourceShard[T]):\n def __init__(self,\n object_ids: List[ray.ObjectRef],\n read_fn: Callable[[ray.ObjectRef], T],\n name: str = \"CacheData\",\n is_repeatable: bool = True,\n is_repeated: bool = False):\n super(CacheDataSource, self).__init__(name, is_repeatable, is_repeated)\n self._object_ids = object_ids\n self._read_fn = read_fn\n\n def repeat(self) -> \"CacheDataSource[T]\":\n if self.repeated():\n return self\n\n if not self.repeatable():\n raise Exception(\"can not repeat on an unrepeatable shard\")\n\n return CacheDataSource(\n self._object_ids, self._read_fn, self.name() + \".repeat()\", False, True)\n\n def gen_data(self, **kwargs):\n if not self.repeated():\n for object_id in self._object_ids:\n yield self._read_fn(object_id)\n else:\n while True:\n for object_id in self._object_ids:\n yield self._read_fn(object_id)\n","sub_path":"python/raydp/parallel/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"96960380","text":"#!/usr/bin/python\n#coding:utf-8\n\n# 2013/03/01\n# トークナイズしてから小文字化するのと, 全文小文字化してからトークナイズするのは同じか?\n\n\nfrom nltk.corpus import reuters\n#from nlp.clustering.preprocess import preprocess\nimport nlp.clustering.preprocess.preprocess as preprocess\n\nraw=reuters.raw(fileids=[reuters.fileids()[1]])\ndocs1 = preprocess.tokenize(raw)\ndocs1 = preprocess.lower(docs1)\ndocs2 = preprocess.tokenize(preprocess.lower(raw))\ndocs1 == docs2\n\nraws=[reuters.raw(fileids=[fid]) for fid in reuters.fileids()]\ndocs1 = preprocess.tokenize(raws)\ndocs1 = preprocess.lower(docs1)\ndocs2 = preprocess.tokenize(preprocess.lower(raws))\ndocs1 == docs2\n\ndocs3 = preprocess.word_tokenize(preprocess.lower(preprocess.sent_tokenize(raws)))\ndocs1 == docs3\ndocs2 == docs3\n\nimport timeit\n\nsetup='''\nfrom nltk.corpus import reuters\nfrom nlp.clustering.preprocess import preprocess\nraws=[reuters.raw(fileids=[fid]) for fid in reuters.fileids()]\n'''\nstmt1 = '''\ndocs1=preprocess.lower(preprocess.tokenize(raws))\n'''\n\nstmt2 = '''\ndocs2 = preprocess.tokenize(preprocess.lower(raws))\n'''\n\nstmt3 = '''\ndocs3 = preprocess.word_tokenize(preprocess.lower(preprocess.sent_tokenize(raws)))\n'''\n\nt1 = timeit.Timer(stmt1, setup)\nt1.timeit(number=5)\nt2 = timeit.Timer(stmt2, setup)\nt2.timeit(number=5)\nt3 = timeit.Timer(stmt3, setup)\nt3.timeit(number=5)\n\n\nraw=reuters.raw(fileids=[reuters.fileids()[1]])\ndoc=preprocess.tokenize(raw)\ndoc=preprocess.postag(doc)\ndoc=preprocess.PosTagFilter()(doc)\n\n#doc=preprocess.filter_postag(doc)\ndoc=preprocess.morphy(doc)\ndoc=preprocess.filter_stopword(doc)\n\n","sub_path":"3rd_party/nltk/reuters.py","file_name":"reuters.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146513804","text":"class Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort() #sorts list g\n s.sort() #sorts list s\n cont_child = 0 #tracks number of content children.\n i = 0\n j = 0\n while i < len(g) and j < len(s):\n if s[j] >= g[i]: #if cookie j can be given to child i, add 1 to cont_child and go to next child and next cookie to compare\n cont_child += 1\n i += 1\n j += 1\n else: #if cookie is not enough for child i, we will try next cookie.\n j += 1\n return cont_child","sub_path":"week3/AssignCookies.py","file_name":"AssignCookies.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"442514379","text":"## Fichier Individu.py\r\n## Creation et suppression d'individus, gestion des interactions avec leur environnement\r\n\r\nfrom Vect2D import *\r\nfrom math import floor\r\nimport numpy as np\r\nimport random as rd\r\nimport Variables as Var\r\nfrom Moteur import *\r\n\r\n## individu\r\n\r\nclass individu:\r\n def __init__(self, choixSortie, pos, dpos, vmoy, r, canvas, color):\r\n self.pos = pos # Position de chaque individu\r\n self.choixSortie = choixSortie\r\n self.dpos = dpos # Vitesse de chaque individu\r\n self.r = r # Rayon de chaque individu\r\n self.vmoy = vmoy # Vitesse moyenne d'un individu\r\n self.canvas = canvas # Le Canevas sur lequel on dessine\r\n self.color = color # Couleur de chaque individu\r\n self.id = canvas.create_oval(-1 * r, -1 * r, r, r, fill = color, outline = 'black') #Représentation graphique\r\n self.canvas.move(self.id, pos.x, pos.y) #On le place à sa position\r\n\r\n def bouge(self):\r\n '''deplace un individu de dpos'''\r\n self.canvas.move(self.id, self.dpos.x, self.dpos.y)\r\n self.pos += self.dpos\r\n return\r\n\r\n# Fonction de gestion du nombre d'individu\r\ndef init_indiv(terrain):\r\n supprime_indiv(terrain)\r\n for i in range(Var.NIndiv):\r\n # Afin d'éviter que des individus se retrouve a moitie dans un mur on genere sur un intervalle ou chacun d'eux est pleinement dans une case\r\n while 1 :\r\n erreur=False\r\n x = rd.randint(3*Var.dimCase,(Var.largeur-4)*Var.dimCase)\r\n y = rd.randint(3*Var.dimCase,(Var.hauteur-4)*Var.dimCase)\r\n for indiv in Var.LIndiv:\r\n if abs(indiv.pos.x-x)<=2*indiv.r and abs(indiv.pos.y-y)<=2*indiv.r:\r\n erreur=True\r\n if Var.TCase[floor(y / Var.dimCase), floor(x / Var.dimCase)].type >= 0 and Var.TCase[floor(y / Var.dimCase),ceil(x / Var.dimCase)].type >= 0 and Var.TCase[ceil(y / Var.dimCase), floor(x / Var.dimCase)].type >= 0 and Var.TCase[ceil(y / Var.dimCase), ceil(x / Var.dimCase)].type >= 0 and erreur==False:\r\n break\r\n pose_indiv(x, y, terrain)\r\n\r\n return\r\n\r\ndef pose_indiv(x, y, terrain):\r\n '''Pose un inidividu sur le terrain en (x,y)'''\r\n pos = vect2D(x, y)\r\n dpos = vect2D(0, 0)\r\n if Var.choixSortie==1:\r\n indiv=individu(Var.choixSortie, pos, dpos, rd.uniform(Var.vminIndiv, Var.vmaxIndiv), Var.rIndiv, terrain,\"blue\")\r\n Var.LIndiv.append(indiv)\r\n else:\r\n indiv=individu(Var.choixSortie, pos, dpos, rd.uniform(Var.vminIndiv, Var.vmaxIndiv), Var.rIndiv, terrain,\"red\")\r\n Var.LIndiv.append(indiv)\r\n\r\n return\r\n\r\ndef supprime_indiv(terrain):\r\n '''supprime tous les individus du terrain'''\r\n for i in Var.LIndiv :\r\n terrain.delete(i.id)\r\n Var.LIndiv = []\r\n return\r\n\r\ndef sortir_indiv(terrain):\r\n '''Permet de supprimer un individu lorsqu'il a atteint la sortie'''\r\n if Var.LIndiv==[]:\r\n return\r\n for individu in Var.LIndiv :\r\n x = floor(individu.pos.x / Var.dimCase)\r\n y = floor(individu.pos.y / Var.dimCase)\r\n for s in Var.LSortie:\r\n if s==[x,y]:\r\n terrain.delete(individu.id)\r\n Var.LIndiv.remove(individu)\r\n Var.TCase[y,x].type=1\r\n return\r\n\r\n# Fonction de gestion des collisions avec les murs, les bords et les autres individus\r\ndef touche_indiv(individu1, individu2):\r\n '''Test si deux individus se touchent'''\r\n return (individu1.pos - individu2.pos).norme() <= individu1.r + individu2.r +0.1\r\n\r\ndef rebond_indiv(individu1, individu2):\r\n '''Lorsqu'il y a collision entre deux individu, calcule les vitesses de chacun après le choc'''\r\n #if p_scal(individu1.dpos, individu2.dpos) < 0 : #Vérifie si les individus ne s'éloignent pas déjà\r\n # return\r\n\r\n n = individu1.pos - individu2.pos\r\n n1 = projection(individu1.dpos, n)\r\n n2 = projection(individu2.dpos, n)\r\n\r\n t1 = individu1.dpos - n1\r\n t2 = individu2.dpos - n2\r\n #On conserve les composantes tangentielles et on échange les composantes normales\r\n individu1.dpos = (t1 + n2)\r\n individu2.dpos = (t2 + n1)\r\n\r\n return\r\n\r\ndef rebond_mur(individu):\r\n '''Lorsqu'un individu touche un mur, on le fait rebondir en inversant sa vitesse selon les axes de chocs'''\r\n pos = individu.pos\r\n r = individu.r\r\n c = Var.TCase[floor(pos.y / Var.dimCase), floor(pos.x / Var.dimCase)]\r\n d = Var.TCase[ceil(pos.y / Var.dimCase), ceil(pos.x / Var.dimCase)]\r\n murX=False\r\n murY=False\r\n if c.type == -1 :\r\n if pos.x -r-0.1 < c.pos.x or pos.x + r +0.1 > c.pos.x + Var.dimCase :\r\n individu.dpos.x *= -1\r\n murX=True\r\n if pos.y -r-0.1 < c.pos.y or pos.y + r+0.1 > c.pos.y + Var.dimCase :\r\n individu.dpos.y *= -1\r\n murY=True\r\n\r\n return\r\n\r\ndef rebond_bord(individu):\r\n '''Lorsqu'un individu touche un mur, on le fait rebondir en inversant sa vitesse selon les axes de chocs'''\r\n pos = individu.pos\r\n r = individu.r\r\n if pos.x -r < 0 or pos.x + r > Var.largeur*Var.dimCase:\r\n individu.dpos.x *= -1\r\n if pos.y - r < 0 or pos.y + r > Var.hauteur*Var.dimCase :\r\n individu.dpos.y *= -1\r\n return\r\n\r\n# Programme de gestion des mouvements\r\ndef bouge_indiv():\r\n '''Gestion du mouvement des individus en fonction de l'environnement de chacun'''\r\n for i, individu1 in enumerate(Var.LIndiv) :\r\n x = floor(individu1.pos.x / Var.dimCase)\r\n y = floor(individu1.pos.y / Var.dimCase)\r\n individu1.dpos = individu1.dpos.normalise() * np.random.normal(individu1.vmoy, 0.2)\r\n individu1.dpos += Var.Tdirection[individu1.choixSortie-1][y,x]\r\n for individu2 in Var.LIndiv[i+1:] :\r\n if touche_indiv(individu1, individu2) :\r\n rebond_indiv(individu1, individu2)\r\n rebond_bord(individu1)\r\n rebond_mur(individu1)\r\n individu1.bouge()\r\n return\r\n\r\n##individuCarre\r\n\r\nclass individuCarre:\r\n def __init__(self, choixSortie, pos, canvas, color):\r\n self.pos = pos # Position de chaque individu\r\n self.choixSortie = choixSortie #Choix sortie\r\n self.canvas = canvas # Le Canevas sur lequel on dessine\r\n self.color = color # Couleur de chaque individ\r\n self.id = canvas.create_rectangle(0,0,Var.dimCase,Var.dimCase,fill = color, outline = 'black')\r\n self.canvas.move(self.id, pos.x, pos.y) #On le place à sa position\r\n self.score = Var.TCase[floor(pos.y/Var.dimCase),floor(pos.x/Var.dimCase)].score[self.choixSortie-1]\r\n\r\n def bouge(self):\r\n '''deplace un individu de dpos'''\r\n x,y=floor(self.pos.x/Var.dimCase),floor(self.pos.y/Var.dimCase)\r\n V=voisins(x,y,[pas_individu_condition,pas_mur_condition],Var.typeDiagonale)\r\n if len(V)==0:\r\n #l individu est bloqué\r\n return\r\n a,b=y,x\r\n dmin=Var.dMaxCase[self.choixSortie-1]\r\n for v in V:\r\n Var.TCase[v.y, v.x].explore = False\r\n c=Var.TCase[v.y,v.x].score[self.choixSortie-1]\r\n if c < dmin and c < self.score:\r\n dmin= c\r\n a,b=v.y,v.x\r\n dx,dy=(b-x)*Var.dimCase,(a-y)*Var.dimCase\r\n self.pos.y,self.pos.x=a*Var.dimCase,b*Var.dimCase\r\n self.canvas.move(self.id, dx,dy)\r\n Var.TCase[y,x].type=0\r\n if Var.TCase[a,b].type !=1:\r\n Var.TCase[a,b].type =2\r\n self.score = Var.TCase[y,x].score[self.choixSortie-1]\r\n return\r\n\r\n# Fonction de gestion du nombre d'individu\r\ndef init_indiv_carre(terrain):\r\n supprime_indiv(terrain)\r\n for i in range(Var.NIndiv):\r\n # Afin d'éviter que des individus se retrouve a moitie dans un mur on genere sur un intervalle ou chacun d'eux est pleinement dans une case\r\n while 1 :\r\n x = rd.randint(0, Var.largeur-1)\r\n y = rd.randint(0,Var.hauteur-1)\r\n if Var.TCase[y, x].type ==0 :\r\n break\r\n pose_indiv_carre(x*Var.dimCase, y*Var.dimCase, terrain)\r\n return\r\n\r\ndef pose_indiv_carre(x, y, terrain):\r\n '''Pose un inidividu sur le terrain en (x,y)'''\r\n if Var.TCase[floor(y/Var.dimCase),floor(x/Var.dimCase)].type==2:\r\n return\r\n pos = vect2D(floor(x/Var.dimCase)*Var.dimCase,floor(y/Var.dimCase)*Var.dimCase)\r\n if Var.choixSortie==1:\r\n indiv=individuCarre(Var.choixSortie, pos, terrain, \"blue\")\r\n else:\r\n indiv=individuCarre(Var.choixSortie, pos, terrain, \"red\")\r\n Var.TCase[floor(y/Var.dimCase),floor(x/Var.dimCase)].type=2\r\n Var.LIndiv.append(indiv)\r\n return\r\n\r\n# Programme de gestion des mouvements\r\ndef bouge_indiv_carre():\r\n '''Gestion du mouvement des individus en fonction de l'environnement de chacun'''\r\n for i, individu1 in enumerate(Var.LIndiv) :\r\n individu1.bouge()\r\n rd.shuffle(Var.LIndiv)\r\n return\r\n","sub_path":"Crowd_Simulation/Individu.py","file_name":"Individu.py","file_ext":"py","file_size_in_byte":8893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271931526","text":"class Wishes2Obj(object):\n\n\tdef __init__(self, goodobj, count, couponobj):\n\t\tself.goodobj = goodobj\n\t\tself.count = count\n\t\tself.couponobj = couponobj\n\n\tdef printCoupon(self):\n\t\tcouponList = list()\n\t\tfor item in self.couponobj:\n\t\t\tcouponList.append(item.code)\n\t\t\tprint(item.code, end=\" \")\n\t\treturn couponList\n\n\n","sub_path":"Jongwon/python-bucket/wishes2obj.py","file_name":"wishes2obj.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"415348472","text":"\n# https://leetcode.com/problems/merge-intervals/discuss/21227/7-lines-easy-Python\n\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n res = []\n for i in sorted(intervals, key = lambda i: i[0]):\n if res != [] and i[0] <= res[-1][-1]:\n res[-1][-1] = max(res[-1][-1], i[-1])\n else:\n res.append(i)\n return res","sub_path":"56. 合并区间.py","file_name":"56. 合并区间.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"226774372","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved\n# $Jesús Ventosinos Mayor $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import models, fields, exceptions, api, workflow\nfrom openerp.tools.translate import _\nfrom datetime import date\n\n\nclass sale_order(models.Model):\n\n _inherit = \"sale.order\"\n\n replacement = fields.Boolean('Replacement')\n rep_lines = fields.One2many('sale.order.line', 'orig_sale', 'Rep lines')\n is_all_invoiced = fields.Boolean('Is invoiced', compute='_get_replacement_invoiced')\n\n @api.one\n def _get_replacement_invoiced(self):\n is_all_invoiced = True\n for line in self.order_line:\n if not line.is_all_replaced:\n is_all_invoiced = False\n self.is_all_invoiced = is_all_invoiced\n\n @api.model\n def execute_onchanges(self, partner_id, line):\n par_val = self.onchange_partner_id(partner_id)['value']\n line.update(self.env['sale.order.line'].product_id_change_with_wh(\n par_val['pricelist_id'], line['product_id'], line['product_uom_qty'],\n partner_id=partner_id, date_order=date.today().strftime('%Y-%m-%d'),\n fiscal_position=par_val.get('fiscal_position', False),\n warehouse_id=self._get_default_warehouse())['value'])\n return line\n\n @api.model\n def default_get(self, fields):\n res = super(sale_order, self).default_get(fields)\n if self._context.get('order_line', False) and res.get('partner_id'):\n # Se debe ejecutar el onchange del producto manualmente\n final_line_vals = []\n for line_vals in eval(self._context.get('order_line')):\n final_line_vals.append((0, 0, self.execute_onchanges(res['partner_id'], line_vals[2])))\n res['order_line'] = final_line_vals\n return res\n\n @api.multi\n def view_invoiced_qtys(self):\n action_data = self.env.ref('sale_replacement.action_replacements_to_invoice').read()[0]\n\n action_data['context'] = {}\n action_data['domain'] = [('order_id', 'in', self.ids)]\n return action_data\n\n @api.model\n def _prepare_order_line_procurement(self, order, line, group_id=False):\n res = super(sale_order, self)._prepare_order_line_procurement(order,\n line,\n group_id)\n if order.replacement:\n res['invoice_state'] = 'none'\n return res\n\n @api.multi\n def test_done_replacement(self, *args):\n res = False\n for sale in self:\n if sale.replacement:\n for picking in sale.picking_ids:\n if picking.state == 'done':\n res = True\n return res\n\n @api.model\n def test_no_product(self, order):\n for line in order.order_line:\n if (line.product_id and (line.product_id.type != 'service')) \\\n and not line.replacement:\n return False\n return True\n\n @api.multi\n def has_stockable_products(self, *args):\n for order in self:\n for order_line in order.order_line:\n if (order_line.product_id and\n order_line.product_id.type in ('product', 'consu')) \\\n and not order_line.replacement:\n return True\n return False\n\n @api.multi\n def action_button_confirm(self):\n for order in self:\n for line in order.order_line:\n if line.replacement:\n line._get_orig_line()\n return super(sale_order, self).action_button_confirm()\n\n\nclass sale_order_line(models.Model):\n\n _inherit = \"sale.order.line\"\n\n replacement = fields.Boolean('Replacement')\n\n qty_replaced = fields.Float('Quantity replacement',\n compute='_get_qty_replaced', store=True)\n replaced_returned_qty = fields.Float('')\n\n is_all_replaced = fields.Boolean('All replaced',\n compute=\"_get_is_all_replaced\",\n store=True)\n\n is_sale_replacement = fields.Boolean('is sale replacement',\n related='order_id.replacement',\n readonly=True)\n\n orig_sale = fields.Many2one('sale.order', 'Original order')\n\n\n from openerp.osv import fields as fields2\n\n def _fnct_line_invoiced(self, cr, uid, ids, field_name, args,\n context=None):\n res = dict.fromkeys(ids, False)\n for this in self.browse(cr, uid, ids, context=context):\n res[this.id] = this.invoice_lines and \\\n all(iline.invoice_id.state != 'cancel'\n for iline in this.invoice_lines)\n if this.order_id.replacement:\n sale_lines = self.search(\n cr, uid, [('replacement', '=', True),\n ('orig_sale', '=', this.order_id.id)],\n context=context)\n for sale_line in sale_lines:\n res[sale_line] = res[this.id]\n return res\n\n def _order_lines_from_invoice(self, cr, uid, ids, context=None):\n cr.execute(\"\"\"SELECT DISTINCT sol.id FROM sale_order_invoice_rel rel\n JOIN sale_order_line sol ON (sol.order_id = rel.order_id)\n WHERE rel.invoice_id = ANY(%s)\"\"\", (list(ids),))\n line_ids = [i[0] for i in cr.fetchall()]\n for line in self.pool.get('sale.order.line').browse(cr, uid, line_ids,\n context):\n if line.product_id:\n cr.execute(\"\"\"SELECT sol.id from sale_order_line sol where\n sol.product_id = %s and sol.orig_sale = %s\"\"\",\n (line.product_id.id, line.order_id.id))\n line_ids += [i[0] for i in cr.fetchall()]\n return line_ids\n\n _columns = {\n 'invoiced': fields2.function(_fnct_line_invoiced, string='Invoiced',\n type='boolean',\n store={\n 'account.invoice':\n (_order_lines_from_invoice, ['state'],\n 10),\n 'sale.order.line':\n (lambda self, cr, uid, ids, ctx=None:\n ids,\n ['invoice_lines'], 10)\n })\n }\n\n @api.one\n @api.depends('order_id.rep_lines.state', 'replaced_returned_qty')\n def _get_qty_replaced(self):\n rep_lines = self.search_read(\n [('product_id', '=', self.product_id.id),\n ('orig_sale', '=', self.order_id.id),\n ('state', 'not in', ('draft', 'sent', 'cancel'))],\n ['product_uom_qty'])\n self.qty_replaced = sum([x['product_uom_qty'] for x in rep_lines]) + self.replaced_returned_qty\n\n @api.one\n @api.depends('product_uom_qty', 'qty_replaced')\n def _get_is_all_replaced(self):\n self.is_all_replaced = self.product_uom_qty - self.qty_replaced == 0 \\\n and True or False\n\n @api.multi\n def need_procurement(self):\n # when sale is installed alone, there is no need to create\n # procurements, but with sale_stock we must create a procurement\n # for each product that is not a service.\n for line in self:\n if not line.replacement:\n return super(sale_order_line, self).need_procurement()\n return False\n\n @api.multi\n def _get_orig_line(self):\n \"\"\"\n :return: the browse record of original line for the replacement.\n \"\"\"\n self.ensure_one()\n sale_id = self.orig_sale.id\n orig_line = self.search([('order_id', '=', sale_id),\n ('product_id', '=',\n self.product_id.id)])\n if not orig_line:\n raise exceptions.MissingError(\n _('Not found the original line of replacement'))\n if (orig_line.product_uom_qty - orig_line.qty_replaced) < \\\n self.product_uom_qty and not \\\n self._context.get('no_control_qty', False):\n raise exceptions.MissingError(\n _('Qty error in replacement.'))\n\n return orig_line\n\n @api.multi\n def invoice_line_create(self):\n create_ids = []\n sales = set()\n for line in self:\n vals = self._prepare_order_line_invoice_line(line, False)\n ids = self.env['sale.order.line']\n if vals:\n if line.replacement:\n orig = line.with_context(no_control_qty=True)._get_orig_line()\n ids += orig\n else:\n ids += line\n inv = self.env['account.invoice.line'].create(vals)\n ids.write({'invoice_lines': [(4, inv.id)]})\n sales.add(line.order_id.id)\n create_ids.append(inv.id)\n # Trigger workflow events\n for sale_id in sales:\n workflow.trg_write(self.env.user.id, 'sale.order', sale_id, self.env.cr)\n return create_ids\n\n @api.multi\n def _get_appropiate_account(self):\n self.ensure_one()\n if self.product_id:\n account_id = self.product_id.property_account_income.id\n if not account_id:\n account_id = self.product_id.categ_id.property_account_income_categ.id\n if not account_id:\n raise exceptions.Warning(\n _('Error!'),\n _('Please define income account for this product: \\\n \"%s\" (id:%d).') %\n (self.product_id.name, self.product_id.id,))\n else:\n prop = self.pool.get('ir.property').get(\n cr, uid, 'property_account_income_categ',\n 'product.category', context=context)\n account_id = prop and prop.id or False\n return account_id\n\n @api.model\n def _prepare_order_line_invoice_line(self, line, account_id=False):\n \"\"\"Prepare the dict of values to create the new invoice line for a\n sales order line. This method may be overridden to implement custom\n invoice generation (making sure to call super() to establish\n a clean extension chain).\n\n :param browse_record line: sale.order.line record to invoice\n :param int account_id: optional ID of a G/L account to force\n (this is used for returning products including service)\n :return: dict of values to create() the invoice line\n\n MOD: Si la linea está marcada como reemplazo, se factura con el\n precio original.\n \"\"\"\n res = {}\n if line.replacement and not line.invoiced:\n if not account_id:\n account_id = line._get_appropiate_account()\n uosqty = self._get_line_qty(line)\n uos_id = self._get_line_uom(line)\n pu = 0.0\n if uosqty:\n orig_line = line.with_context(no_control_qty=True)._get_orig_line()\n precision = self.env['decimal.precision'].precision_get('Product Price')\n pu = round(\n orig_line.price_unit * line.product_uom_qty / uosqty,\n precision)\n fpos = line.order_id.fiscal_position or self.env['account.fiscal.position']\n account_id = fpos.map_account(account_id)\n if not account_id:\n raise exceptions.Warning(\n _('Error!'),\n _('There is no Fiscal Position defined or Income \\\n category account defined for default properties of \\\n Product categories.'))\n res = {\n 'name': line.name,\n 'sequence': line.sequence,\n 'origin': line.order_id.name,\n 'account_id': account_id,\n 'price_unit': pu,\n 'quantity': uosqty,\n 'discount': line.discount,\n 'uos_id': uos_id,\n 'product_id': line.product_id.id or False,\n 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])],\n 'account_analytic_id':\n line.order_id.project_id and\n line.order_id.project_id.id or False,\n }\n return res\n else:\n return super(sale_order_line,\n self)._prepare_order_line_invoice_line(line,\n account_id)\n\n def product_id_change(\n self, cr, uid, ids, pricelist, product, qty=0, uom=False,\n qty_uos=0, uos=False, name='', partner_id=False, lang=False,\n update_tax=True, date_order=False, packaging=False,\n fiscal_position=False, flag=False, context=None):\n \"\"\"\n Modify the onchange of product_id, if the replacement checkbox\n is True use the price_unit of the origin_sale.\n \"\"\"\n\n if not context:\n context = {}\n replacement = context.get('rep', False)\n origin_sale = context.get('orig', False)\n res = super(sale_order_line, self).product_id_change(\n cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name,\n partner_id, lang, update_tax, date_order, packaging,\n fiscal_position, flag, context)\n if replacement:\n warning = res.get('warning', False)\n warning = warning is not False and warning or \\\n {'title': 'Replacement error', 'message': ''}\n if not origin_sale:\n warning['message'] += _('Not found the original sale.\\n')\n orig_line_id = self.search(cr, uid,\n [('order_id', '=', origin_sale),\n ('product_id', '=', product),\n ('is_all_replaced', '=', False)],\n context=context)\n if not orig_line_id:\n warning['message'] += _('Not found the original sale line.\\n')\n line = self.browse(cr, uid, orig_line_id[0], context)\n if (line.product_uom_qty - line.qty_replaced) < qty:\n res['value']['product_uom_qty'] = line.product_uom_qty - line.qty_replaced\n res['value']['product_uos_qty'] = line.product_uom_qty - line.qty_replaced\n warning['message'] += _('The quantity is bigger than the original.\\n')\n res['value']['price_unit'] = line.price_unit\n if len(warning['message']):\n res['warning'] = warning\n\n return res\n","sub_path":"project-addons/sale_replacement/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":15927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"42564994","text":"import sys\n\nsys.path.append(\".\")\nsys.path.append(\"..\")\nsys.path.append(\"../..\")\nfrom Hologram.Authentication import *\nfrom Hologram.Credentials import Credentials\n\nCSRPSKID = '1234'\nCSRPSKKey = '5678'\n\ncredentials = Credentials(CSRPSKID, CSRPSKKey)\n\nclass TestCSRPSKAuthentication:\n\n def test_create(self):\n auth = CSRPSKAuthentication.CSRPSKAuthentication(credentials)\n\n def test_build_payload_string_without_topics(self):\n auth = CSRPSKAuthentication.CSRPSKAuthentication(credentials)\n message = \"one two three\"\n assert \"{\\\"s\\\": \\\"1234\\\", \\\"c\\\": \\\"5678\\\", \\\"d\\\": \\\"one two three\\\"}\\r\\r\" == auth.buildPayloadString(message)\n","sub_path":"tests/Authentication/test_CSRPSKAuthentication.py","file_name":"test_CSRPSKAuthentication.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"149519152","text":"\nimport create_process\nimport file_util\nimport os\nfrom datetime import datetime\n\nNOTEPAD_PLUS = r'C:\\Program Files\\Notepad++\\notepad++.exe'\n\n\n\ndef view_pc_log():\n PC_LOG_DIR = r'C:\\Users\\Administrator\\AppData\\Roaming\\huyacloudgame2\\log'\n PC_MAIN_LOG = 'main_process.log'\n PC_CPP_LOG = 'pull_process.log'\n notepad_view(os.path.join(PC_LOG_DIR, PC_MAIN_LOG))\n notepad_view(os.path.join(PC_LOG_DIR, PC_CPP_LOG))\n\n\ndef view_server_log(name):\n ROOT_DIR = r'D:\\cloudgame_log'\n today = get_today_string()\n dir = os.path.join(ROOT_DIR,today)\n if os.path.exists(dir):\n last_updated = file_util.last_updated_begin_with(dir, name)\n if last_updated:\n notepad_view(os.path.join(dir, last_updated))\n else:\n print(\"%s is not exists\", dir)\n\ndef view_archive_log():\n ARCHIVE_LOG = 'D:\\cloudgame_log\\game_utils\\game_recover.log'\n notepad_view(ARCHIVE_LOG)\n\ndef get_today_string():\n return datetime.today().strftime(\"%Y_%m_%d\") \n\ndef notepad_view(file):\n create_process.run_subprocess_async([NOTEPAD_PLUS, file])\n\n\n\n\nif __name__ == '__main__':\n view_server_log('host')","sub_path":"win32/open_with_notepad.py","file_name":"open_with_notepad.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"584306342","text":"import cs3311\nimport sys\nimport re\nfrom datetime import datetime\n\nclass Timetable:\n\n def __init__(self, last=0):\n self.days = {}\n self.last = last\n self.total_hours = 0\n self.days_on_campus = 0\n self.early_score = 0\n self.latest_day = 0\n self.latest_time = 0\n\n def add_class(self, uc):\n if uc.day not in self.days:\n self.days[uc.day] = {'daytime': DayTime(uc.start, uc.end), 'classes': [uc]}\n else:\n self.days[uc.day]['classes'].append(uc)\n self.days[uc.day]['daytime'].update_daytime(uc.start, uc.end)\n\n def copy_days(self, days):\n new_days = {}\n\n for d in days:\n dt = DayTime(days[d]['daytime'].start, days[d]['daytime'].end)\n new_days[d] = {'daytime': dt, 'classes': []}\n\n for c in days[d]['classes']:\n new_days[d]['classes'].append(c)\n\n self.days = new_days\n\n def print_timetable(self):\n hours = round(self.total_hours, 1)\n print(\"Total hours: {0}\".format(hours))\n week_list = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n for wl in week_list:\n if wl in self.days:\n print(\" {0}\".format(wl))\n self.days[wl]['classes'].sort(key=lambda x: x.start)\n\n for c in self.days[wl]['classes']:\n print(c) \n\n\nclass UNSWClass:\n\n def __init__(self, code, class_type, day, start, end):\n self.code = code\n self.class_type = class_type\n self.day = day\n self.start = start\n self.end = end\n\n def __str__(self):\n return \" {0} {1}: {2}-{3}\".format(self.code, self.class_type, self.start, self.end)\n\n\nclass DayTime:\n \n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.hours = 0\n self.update_hours()\n\n def update_daytime(self, start, end):\n if start < self.start or end > self.end:\n if start < self.start:\n self.start = start\n \n if end > self.end:\n self.end = end\n\n self.update_hours()\n\n def update_hours(self):\n start = datetime.strptime(str(self.start),\"%H%M\")\n end = datetime.strptime(str(self.end),\"%H%M\")\n hours_at_uni = (end - start).total_seconds() / 3600\n self.hours = hours_at_uni + 2\n\n def __str__(self):\n return \"DAYTIME: {0}, {1}, {2}\".format(self.start, self.end, self.hours)\n\n\ndef generate_timetables(timetables, streams):\n result = []\n\n for t in timetables:\n for stream in streams:\n overlap = False\n last = t.last\n\n for c in stream:\n if c.day in t.days:\n for c2 in t.days[c.day]['classes']:\n if (c.start < c2.start and c.end > c2.start) or \\\n (c.end > c2.end and c.start < c2.end) or \\\n c.start == c2.start or c.end == c2.end:\n overlap = True\n\n last += 1\n\n if overlap is False:\n new_timetable = Timetable(last)\n new_timetable.copy_days(t.days)\n\n for c in stream:\n new_timetable.add_class(c)\n\n result.append(new_timetable)\n \n return result\n\n\ncourses = []\ncourse_query = \"JOIN Subjects s ON (c.subject_id = s.id and (s.code = \\'\"\n\nif len(sys.argv) > 4:\n print(\"Usage:\", sys.argv[0], \"a3\", \"[code] [code] [code]\")\n sys.exit(1)\nif len(sys.argv) >= 2:\n for i in range(1, len(sys.argv)):\n code = sys.argv[i]\n courses.append(code)\n\n if not re.match(r\"^[A-Z]{4}[0-9]{4}$\", code):\n print(\"Invalid code: a code should be a 4 letter followed by 4 numbers.\")\n \nelse:\n courses = [\"COMP1511\", \"MATH1131\"]\n\nconn = cs3311.connect()\n\nif conn is None:\n sys.exit(1)\n\ncur = conn.cursor()\n\ncourse_query = course_query + '\\' or s.code = \\''.join(courses) + '\\'))'\nquery = \"\"\"\n SELECT s.code, ct.name, STRING_AGG(m.day :: text, ' '), STRING_AGG(m.start_time :: text, ' '), STRING_AGG(m.end_time :: text, ' ')\n FROM Courses c JOIN Terms t ON (c.term_id = t.id AND t.name = '19T3')\n \"\"\" + course_query + \"\"\"\n JOIN Classes cl ON (c.id = cl.course_id)\n JOIN Meetings m ON (cl.id = m.class_id)\n JOIN Rooms r ON (m.room_id = r.id and r.code like 'K-%')\n JOIN ClassTypes ct ON (cl.type_id = ct.id)\n GROUP BY cl.id, s.code, ct.name\n \"\"\"\n\ncur.execute(query)\n\nunsw_classes = {}\nclass_types = []\n\nwhile True:\n tups = cur.fetchmany(10)\n \n if not tups:\n break\n\n for tup in tups:\n code, class_type, days, starts, ends = tup\n class_key = code + \" \" + class_type\n\n days = days.split()\n starts = starts.split()\n ends = ends.split()\n\n stream = [] \n\n for index, d in enumerate(days):\n day = d\n start = int(starts[index])\n end = int(ends[index])\n unsw_class = UNSWClass(code, class_type, day, start, end)\n stream.append(unsw_class)\n \n \n if class_key not in unsw_classes:\n class_types.append(class_key)\n unsw_classes[class_key] = [stream]\n else:\n unsw_classes[class_key].append(stream)\n\ncur.close()\nconn.close()\n\nstarter_class = class_types.pop(0)\nfinal_timetables = []\n\nfor stream in unsw_classes[starter_class]:\n timetable = Timetable()\n\n for uc in stream:\n timetable.add_class(uc)\n\n timetables = [timetable]\n\n for ct in class_types:\n timetables = generate_timetables(timetables, unsw_classes[ct])\n\n if not timetables:\n break\n\n final_timetables = final_timetables + timetables\n\noptimal_timetable = None\nweek_order = {'Sun': 1, 'Mon': 2, 'Tue': 3, 'Wed': 4,'Thu': 5, 'Fri': 6, 'Sat': 7}\n\nfor t in final_timetables:\n for day in t.days:\n if week_order[day] > t.latest_day:\n t.latest_day = week_order[day]\n t.latest_time = t.days[day]['daytime'].end\n elif week_order[day] == t.latest_day and t.days[day]['daytime'].end < t.latest_time:\n t.latest_time = t.days[day]['daytime'].end\n\n t.total_hours += t.days[day]['daytime'].hours\n t.days_on_campus += 1\n t.early_score += (len(t.days[day]['classes']) * week_order[day])\n\n if optimal_timetable is None:\n optimal_timetable = t\n elif t.total_hours < optimal_timetable.total_hours:\n optimal_timetable = t\n elif t.total_hours == optimal_timetable.total_hours:\n if t.days_on_campus < optimal_timetable.days_on_campus:\n optimal_timetable = t\n elif t.days_on_campus == optimal_timetable.days_on_campus:\n if t.early_score < optimal_timetable.early_score:\n optimal_timetable = t\n elif t.early_score == optimal_timetable.early_score:\n if t.latest_day < optimal_timetable.latest_day:\n optimal_timetable = t\n elif t.latest_day == optimal_timetable.latest_day:\n if t.latest_time < optimal_timetable.latest_time:\n optimal_timetable = t\n\noptimal_timetable.print_timetable()","sub_path":"q8.py","file_name":"q8.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"472538563","text":"from user.models import *\nimport os\n\ndef appendchatconnection(idnum, userinfo):\n l = []\n for item in userinfo:\n l.append([idnum, item['id']])\n\n for group in l:\n filename = str(group[0]) + 'with' + str(group[1]) + '.txt'\n filepath = os.path.join('static', 'chatmsg', filename)\n Message.objects.create(\n chater1=group[0],\n chater2=group[1],\n chatjsonpath=filepath\n )\n file = open(filepath, 'w')\n file.close()\n","sub_path":"mysite/utils/appendchatconnection.py","file_name":"appendchatconnection.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"478780732","text":"import smtplib\nimport random \nfrom email.message import EmailMessage\n\n\ndef sendMail(to,state = False):\n\n otp = \"\"\n\n #login credentials\n # store the mail and password\n sender = 'xxxxxxxx@gmail.com'\n password = 'xxxxxxxxxxxxxxxxx'\n\n msg = EmailMessage()\n msg['From'] = sender\n msg['To'] = to\n\n if state:\n msg['Subject'] = 'Mail Subject '\n msg.set_content('mail content in plain text')\n msg.add_alternative(\"\"\"\\\n \n \n

Congratulation You have successfully booked the playground

\n \n \n \"\"\", subtype='html')\n else:\n #otp generation\n for i in range(6):\n otp += str(random.randint(0,9))\n print(otp)\n\n #otp mail text\n msg['Subject'] = 'Otp for signup in OnlinePlaygroundBookingSystem'\n txt = f'Your otp for the email validation is : {otp} . Please enter this credentials to complete your signup' \n msg.set_content(txt)\n txt = '''\n \n \n Please do not share this OTP with anyone.
\n Your OTP is : ''' + otp + '''
\n Please enter the credentials within 15 minutes to complete your Sign up\n This is an autogenerated mail. So please do not reply.\n \n '''\n msg.add_alternative(txt, subtype='html')\n # return otp\n\n # print(msg)\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n #login\n smtp.login(sender, password)\n #send message\n smtp.send_message(msg)\n\n #for returning the otp to the signup page for verification\n if not state:\n return otp\n","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"209103881","text":"import numpy as np\nfrom common.datasets import *\n\n# Checks that the cifar 100 dataset specified can be read. Compares some loaded data to that which has been previously verified.\nCIFAR100_PATH = '/data/cifar100'\nSEED = 1\nN_TRAIN = 50000\nN_TEST = 10000\nN_TRAIN_SAMPLES = 500\nN_TEST_SAMPLES = 100\n\nif __name__ == '__main__':\n # Get indices of samples\n np.random.seed(SEED)\n indices_train = np.random.randint(N_TRAIN, size=N_TRAIN_SAMPLES); \n indices_test = np.random.randint(N_TEST, size=N_TEST_SAMPLES); \n\n print('Load data')\n cifar100 = DatasetH5(CIFAR100_PATH)\n\n print('Gather samples')\n # get samples from generator\n train_gen = cifar100.generator_train_data\n test_gen = cifar100.generator_test_data\n\n train_samples_x = train_gen.x[indices_train]\n train_samples_y = train_gen.y[indices_train]\n test_samples_x = test_gen.x[indices_test]\n test_samples_y = test_gen.y[indices_test]\n\n print('Load saved samples')\n # samples from pkl file \n with open('cifar100_samples.pkl', 'rb') as load_file:\n train_samples_x_load = np.load(load_file)\n train_samples_y_load = np.load(load_file)\n test_samples_x_load = np.load(load_file)\n test_samples_y_load = np.load(load_file)\n\n # check that they match\n assert(np.array_equal(train_samples_x, train_samples_x_load))\n assert(np.array_equal(train_samples_y, train_samples_y_load))\n assert(np.array_equal(test_samples_x, test_samples_x_load))\n assert(np.array_equal(test_samples_y, test_samples_y_load))\n\n print('Cifar100 check done!')\n","sub_path":"common/datasets/process/check_cifar100.py","file_name":"check_cifar100.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146417963","text":"import dirEinp as f_d\n\ndef segmentacao(caracteristicas, parametros=dict()):\n #parametros = {'segmentosPar': (caracteristica, forma de extrair),... 'posicoesPar':(caracteristica, forma de extrair),...}\n #funcoes de input de parametros para a segmentação\n def segmentosPar_(caracteristicas, parametros):\n sc = f_d.inp('caracteristicas para segmentos:', (caracteristicas))\n st = f_d.inp('modos de segmentar:', ('p1','p1p2','p2m1','p1p2set','p2m1set'))\n parametros['segmentosPar'].append((sc,st))\n op = f_d.inp(parametros, ('confirmar entrada', 'refazer entrada'))\n if op == 'confirmar entrada':\n op = f_d.inp('adicionar outra caracteristica para segmentos?', ('s','n'))\n if op == 's':\n return segmentosPar_(caracteristicas, parametros)\n if op == 'n':\n return parametros\n if op == 'refazer entrada':\n parametros['segmentosPar'].pop()\n return segmentosPar_(caracteristicas, parametros)\n def posicoesPar_(caracteristicas, parametros):\n sc = f_d.inp('caracteristicas para posicoes:', (caracteristicas))\n st = f_d.inp('modos de segmentar:', ('p1','p1p2','p2m1','p1p2set','p2m1set'))\n parametros['posicoesPar'].append((sc, st))\n op = f_d.inp(parametros, ('confirmar entrada', 'refazer entrada'))\n if op == 'confirmar entrada':\n op = f_d.inp('adicionar outra caracteristica para posicoes?', ('s','n'))\n if op == 's':\n return posicoesPar_(caracteristicas, parametros)\n if op == 'n':\n return parametros\n if op == 'refazer entrada':\n parametros['posicoesPar'].pop()\n return posicoesPar_(caracteristicas, parametros)\n def filtrosPar_(caracteristicas, parametros):\n sc = f_d.inp('caracteristicas para filtros:', (caracteristicas))\n st = f_d.inp('modos de segmentar:', ('p1f','p1p2f','p2m1f'))\n parametros['posicoesPar'].append((sc, st))\n op = f_d.inp(parametros, ('confirmar entrada', 'refazer entrada'))\n if op == 'confirmar entrada':\n op = f_d.inp('adicionar outra caracteristica para filtros?', ('s','n'))\n if op == 's':\n return filtrosPar_(caracteristicas, parametros)\n if op == 'n':\n return parametros\n if op == 'refazer entrada':\n parametros['posicoesPar'].pop()\n return filtrosPar_(caracteristicas, parametros)\n\n #montando parametros\n def Par(caracteristicas):\n parametros = {'segmentosPar': [], 'posicoesPar': []}\n parametros = segmentosPar_(caracteristicas, parametros)\n op = f_d.inp('adicionar caracteristicas para posicoes?', ('s','n'))\n if op == 's':\n parametros = posicoesPar_(caracteristicas, parametros)\n op = f_d.inp('adicionar caracteristicas para filtros?', ('s','n'))\n if op == 's':\n parametros = filtrosPar_(caracteristicas, parametros)\n op = f_d.inp(parametros, ('confirmar segmentacao', 'comecar novamente'))\n if op == 'confirmar segmentacao':\n return parametros\n if op == 'comecar novamente':\n return Par(caracteristicas)\n \n if parametros == dict():\n parametros = Par(caracteristicas)\n\n def funcao_(mDicio, aDicio):\n musica = mDicio.copy()\n nome = musica.pop('nome')\n for parte in musica:\n for voz, caracteristicas in musica[parte].items():\n for p1 in range(len(caracteristicas['grau'])):\n for p2 in range(p1+1,len(caracteristicas['grau'])):\n #caracteristicas nos segmentos\n keyAnalise = []\n for segmentoPar in parametros['segmentosPar']:\n if segmentoPar[1] == 'p1':\n keyAnalise.append(caracteristicas[segmentoPar[0]][p1])\n elif segmentoPar[1] =='p1p2':\n keyAnalise.append(tuple(caracteristicas[segmentoPar[0]][p1:p2]))\n elif segmentoPar[1] == 'p2m1':\n if (p2-1)-p1 == 0:\n continue\n keyAnalise.append(tuple(caracteristicas[segmentoPar[0]][p1:p2-1]))\n elif segmentoPar[1] == 'p1p2set':\n keyAnalise.append(tuple(set(caracteristicas[segmentoPar[0]][p1:p2])))\n elif segmentoPar[1] == 'p2m1set':\n if (p2-1)-p1 == 0:\n continue\n keyAnalise.append(tuple(set(caracteristicas[segmentoPar[0]][p1:p2-1])))\n keyAnalise = tuple(keyAnalise)\n\n #esse set criado no index 0 do valor permite ver valores unicos para\n #todas as caracteristicas do segmentos em qualquer posicao\n aDicio.setdefault(keyAnalise, [{'nome': set()},[]])[0]['nome'].add(nome)\n\n #caracteristicas nas posicoes\n carposicao = {}\n locposicao = (nome, parte, voz, (p1,p2))\n for posicaoPar in parametros['posicoesPar']:\n if posicaoPar != []:\n if posicaoPar[1] == 'p1':\n carposicao.setdefault(posicaoPar[0], caracteristicas[posicaoPar[0]][p1])\n elif posicaoPar[1] == 'p1p2':\n carposicao.setdefault(posicaoPar[0], tuple(caracteristicas[posicaoPar[0]][p1:p2]))\n elif posicaoPar[1] == 'p2m1':\n if (p2-1)-p1 == 0:\n continue\n carposicao.setdefault(posicaoPar[0],tuple(caracteristicas[posicaoPar[0]][p1:p2-1]))\n elif posicaoPar[1] == 'p1p2set':\n carposicao.setdefault(posicaoPar[0], set(caracteristicas[posicaoPar[0]][p1:p2]))\n elif posicaoPar[1] == 'p2m1set':\n if (p2-1)-p1 == 0:\n continue\n carposicao.setdefault(posicaoPar[0], set(caracteristicas[posicaoPar[0]][p1:p2-1]))\n\n #acrescenta ao set no index 0 do valor\n elif posicaoPar[1] == 'p1f':\n aDicio[keyAnalise][0].setdefault(posicaoPar[0], set()).add(caracteristicas[posicaoPar[0]][p1])\n elif posicaoPar[1] == 'p1p2f':\n aDicio[keyAnalise][0].setdefault(posicaoPar[0], set()).update(caracteristicas[posicaoPar[0]][p1:p2])\n elif posicaoPar[1] == 'p2m1f':\n if (p2-1)-p1 == 0:\n continue\n aDicio[keyAnalise][0].setdefault(posicaoPar[0], set()).update(caracteristicas[posicaoPar[0]][p1:p2-1])\n \n #localizao sempre é index 0 e as outras caracteristicas vem no index 1 \n aDicio[keyAnalise][1].append((locposicao,carposicao))\n return aDicio\n return (funcao_, parametros)\n\n#print(nome, parte, round((p1*100)/len(caracteristicas['grau'])+0.5),'% ', end='\\r')","sub_path":"XMLpy/Rascunhos e restos de programa/segmentacao.py","file_name":"segmentacao.py","file_ext":"py","file_size_in_byte":7609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"364172812","text":"import copy\nimport datetime\nimport hashlib\nimport html\nimport os\nimport re\nimport threading\nimport time\n\nimport fishtest.stats.stat_util\nimport requests\nfrom fishtest.util import (\n calculate_residuals,\n delta_date,\n diff_date,\n estimate_game_duration,\n format_results,\n password_strength,\n)\nfrom pyramid.httpexceptions import HTTPFound, exception_response\nfrom pyramid.security import authenticated_userid, forget, has_permission, remember\nfrom pyramid.view import forbidden_view_config, view_config\n\n\ndef clear_cache():\n global last_time, last_tests\n building.acquire()\n last_time = 0\n last_tests = None\n building.release()\n\n\ndef cached_flash(request, requestString):\n clear_cache()\n request.session.flash(requestString)\n return\n\n\n@view_config(route_name=\"home\")\ndef home(request):\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(\n route_name=\"login\",\n renderer=\"login.mak\",\n require_csrf=True,\n request_method=(\"GET\", \"POST\"),\n)\n@forbidden_view_config(renderer=\"login.mak\")\ndef login(request):\n login_url = request.route_url(\"login\")\n referrer = request.url\n if referrer == login_url:\n referrer = \"/\" # never use the login form itself as came_from\n came_from = request.params.get(\"came_from\", referrer)\n\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n token = request.userdb.authenticate(username, password)\n if \"error\" not in token:\n if request.POST.get(\"stay_logged_in\"):\n # Session persists for a year after login\n headers = remember(request, username, max_age=60 * 60 * 24 * 365)\n else:\n # Session ends when the browser is closed\n headers = remember(request, username)\n next_page = request.params.get(\"next\") or came_from\n return HTTPFound(location=next_page, headers=headers)\n\n request.session.flash(token[\"error\"], \"error\") # 'Incorrect password'\n return {}\n\n\n# Guard against upload timeouts/retries\nuploading = threading.Semaphore()\n\n\n@view_config(route_name=\"nn_upload\", renderer=\"nn_upload.mak\", require_csrf=True)\ndef upload(request):\n if not uploading.acquire(False):\n request.session.flash(\n \"An other upload is in progress, please try again later\", \"error\"\n )\n return {}\n result = sync_upload(request)\n uploading.release()\n return result\n\n\ndef sync_upload(request):\n userid = authenticated_userid(request)\n if not userid:\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n if request.method != \"POST\":\n return {}\n try:\n filename = request.POST[\"network\"].filename\n input_file = request.POST[\"network\"].file\n network = input_file.read()\n errors = []\n if len(network) >= 120000000:\n errors.append(\"Network must be < 120MB\")\n if not re.match(r\"^nn-[0-9a-f]{12}\\.nnue$\", filename):\n errors.append('Name must match \"nn-[SHA256 first 12 digits].nnue\"')\n hash = hashlib.sha256(network).hexdigest()\n if hash[:12] != filename[3:15]:\n errors.append(\n \"Wrong SHA256 hash: \" + hash[:12] + \" Filename: \" + filename[3:15]\n )\n if request.rundb.get_nn(filename):\n errors.append(\"Network already exists\")\n if errors:\n for error in errors:\n request.session.flash(error, \"error\")\n return {}\n except:\n request.session.flash(\"You must specify a network filename\", \"error\")\n return {}\n\n try:\n with open(os.path.expanduser(\"~/fishtest.upload\"), \"r\") as f:\n upload_server = f.read().replace(\"\\n\", \"\")\n upload_server = upload_server + \"/\" + filename\n response = requests.post(upload_server, data=network)\n if response.status_code != 200:\n print(\"Network upload failed: \" + str(response.status_code))\n request.session.flash(\n \"Network upload failed: \" + str(response.status_code), \"error\"\n )\n return {}\n except Exception as e:\n print(\"Network upload fails or not configured: \" + str(e))\n request.session.flash(\"Network upload fails or not configured\", \"error\")\n return {}\n\n request.actiondb.upload_nn(authenticated_userid(request), filename)\n request.rundb.upload_nn(userid, filename, network)\n\n return HTTPFound(location=request.route_url(\"nns\"))\n\n\n@view_config(route_name=\"logout\", require_csrf=True, request_method=\"POST\")\ndef logout(request):\n session = request.session\n headers = forget(request)\n session.invalidate()\n return HTTPFound(location=request.route_url(\"tests\"), headers=headers)\n\n\n@view_config(\n route_name=\"signup\",\n renderer=\"signup.mak\",\n require_csrf=True,\n request_method=(\"GET\", \"POST\"),\n)\ndef signup(request):\n if request.method != \"POST\":\n return {}\n errors = []\n\n signup_username = request.POST.get(\"username\", \"\")\n signup_password = request.POST.get(\"password\", \"\")\n signup_password_verify = request.POST.get(\"password2\", \"\")\n signup_email = request.POST.get(\"email\", \"\")\n\n strong_password, password_err = password_strength(\n signup_password, signup_username, signup_email\n )\n if not strong_password:\n errors.append(\"Error! Weak password: \" + password_err)\n if signup_password != signup_password_verify:\n errors.append(\"Error! Matching verify password required\")\n if \"@\" not in signup_email:\n errors.append(\"Error! Email required\")\n if len(signup_username) == 0:\n errors.append(\"Error! Username required\")\n if not signup_username.isalnum():\n errors.append(\"Error! Alphanumeric username required\")\n if errors:\n for error in errors:\n request.session.flash(error, \"error\")\n return {}\n\n path = os.path.expanduser(\"~/fishtest.captcha.secret\")\n if os.path.exists(path):\n with open(path, \"r\") as f:\n secret = f.read()\n payload = {\n \"secret\": secret,\n \"response\": request.POST.get(\"g-recaptcha-response\", \"\"),\n \"remoteip\": request.remote_addr,\n }\n response = requests.post(\n \"https://www.google.com/recaptcha/api/siteverify\", data=payload\n ).json()\n if \"success\" not in response or not response[\"success\"]:\n if \"error-codes\" in response:\n print(response[\"error-codes\"])\n request.session.flash(\"Captcha failed\", \"error\")\n return {}\n\n result = request.userdb.create_user(\n username=signup_username,\n password=signup_password,\n email=signup_email,\n )\n if not result:\n request.session.flash(\"Error! Invalid username or password\", \"error\")\n else:\n request.session.flash(\n \"Your account has been created, but will be activated by a human. This might take a few hours. Thank you for contributing!\"\n )\n return HTTPFound(location=request.route_url(\"login\"))\n return {}\n\n\n@view_config(route_name=\"nns\", renderer=\"nns.mak\")\ndef nns(request):\n\n page_size = 250\n page = int(request.params.get(\"page\", 1))\n skip = max(0, page - 1) * page_size\n nns_list = []\n\n for nn in request.rundb.get_nns(page_size, skip=skip):\n nns_list.append(nn)\n if len(nns_list) == page_size:\n next_page = (skip // page_size) + 2\n else:\n next_page = None\n if page > 1:\n prev_page = page - 1\n else:\n prev_page = None\n return {\n \"nns\": nns_list,\n \"next_page\": next_page,\n \"prev_page\": prev_page,\n \"non_default_shown\": request.cookies.get(\"non_default_state\", \"Show\") == \"Show\",\n }\n\n\n@view_config(route_name=\"actions\", renderer=\"actions.mak\")\ndef actions(request):\n search_action = request.params.get(\"action\", \"\")\n search_user = request.params.get(\"user\", \"\")\n\n actions_list = []\n for action in request.actiondb.get_actions(100, search_action, search_user):\n item = {\n \"action\": action[\"action\"],\n \"time\": action[\"time\"],\n \"username\": action[\"username\"],\n }\n if action[\"action\"] == \"update_stats\":\n item[\"user\"] = \"\"\n item[\"description\"] = \"Update user statistics\"\n elif action[\"action\"] == \"upload_nn\":\n item[\"user\"] = \"\"\n item[\"description\"] = \"Upload \" + action[\"data\"]\n elif action[\"action\"] == \"block_user\":\n item[\"description\"] = (\n \"blocked\" if action[\"data\"][\"blocked\"] else \"unblocked\"\n )\n item[\"user\"] = action[\"data\"][\"user\"]\n elif action[\"action\"] == \"modify_run\":\n item[\"run\"] = action[\"data\"][\"before\"][\"args\"][\"new_tag\"]\n item[\"_id\"] = action[\"data\"][\"before\"][\"_id\"]\n item[\"description\"] = []\n\n before = action[\"data\"][\"before\"][\"args\"][\"priority\"]\n after = action[\"data\"][\"after\"][\"args\"][\"priority\"]\n if before != after:\n item[\"description\"].append(\n \"priority changed from {} to {}\".format(before, after)\n )\n\n before = action[\"data\"][\"before\"][\"args\"][\"num_games\"]\n after = action[\"data\"][\"after\"][\"args\"][\"num_games\"]\n if before != after:\n item[\"description\"].append(\n \"games changed from {} to {}\".format(before, after)\n )\n\n before = action[\"data\"][\"before\"][\"args\"][\"throughput\"]\n after = action[\"data\"][\"after\"][\"args\"][\"throughput\"]\n if before != after:\n item[\"description\"].append(\n \"throughput changed from {} to {}\".format(before, after)\n )\n\n before = action[\"data\"][\"before\"][\"args\"][\"auto_purge\"]\n after = action[\"data\"][\"after\"][\"args\"][\"auto_purge\"]\n if before != after:\n item[\"description\"].append(\n \"auto-purge changed from {} to {}\".format(before, after)\n )\n\n item[\"description\"] = \"modify: \" + \", \".join(item[\"description\"])\n else:\n item[\"run\"] = action[\"data\"][\"args\"][\"new_tag\"]\n item[\"_id\"] = action[\"data\"][\"_id\"]\n item[\"description\"] = \" \".join(action[\"action\"].split(\"_\"))\n if action[\"action\"] == \"stop_run\":\n item[\"description\"] += \": {}\".format(\n action[\"data\"].get(\"stop_reason\", \"User stop\")\n )\n\n actions_list.append(item)\n\n return {\n \"actions\": actions_list,\n \"approver\": has_permission(\"approve_run\", request.context, request),\n }\n\n\ndef get_idle_users(request):\n idle = {}\n for u in request.userdb.get_users():\n idle[u[\"username\"]] = u\n for u in request.userdb.user_cache.find():\n del idle[u[\"username\"]]\n idle = list(idle.values())\n return idle\n\n\n@view_config(route_name=\"pending\", renderer=\"pending.mak\")\ndef pending(request):\n if not has_permission(\"approve_run\", request.context, request):\n request.session.flash(\"You cannot view pending users\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n return {\"users\": request.userdb.get_pending(), \"idle\": get_idle_users(request)}\n\n\n@view_config(route_name=\"user\", renderer=\"user.mak\")\n@view_config(route_name=\"profile\", renderer=\"user.mak\")\ndef user(request):\n userid = authenticated_userid(request)\n if not userid:\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n user_name = request.matchdict.get(\"username\", userid)\n profile = user_name == userid\n if not profile and not has_permission(\"approve_run\", request.context, request):\n request.session.flash(\"You cannot inspect users\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n user_data = request.userdb.get_user(user_name)\n if \"user\" in request.POST:\n if profile:\n\n new_password = request.params.get(\"password\")\n new_password_verify = request.params.get(\"password2\", \"\")\n new_email = request.params.get(\"email\")\n\n if len(new_password) > 0:\n if new_password == new_password_verify:\n strong_password, password_err = password_strength(\n new_password,\n user_name,\n user_data[\"email\"],\n (new_email if len(new_email) > 0 else None),\n )\n if strong_password:\n user_data[\"password\"] = new_password\n request.session.flash(\"Success! Password updated\")\n else:\n request.session.flash(\n \"Error! Weak password: \" + password_err, \"error\"\n )\n return HTTPFound(location=request.route_url(\"tests\"))\n else:\n request.session.flash(\n \"Error! Matching verify password required\", \"error\"\n )\n return HTTPFound(location=request.route_url(\"tests\"))\n\n if len(new_email) > 0 and user_data[\"email\"] != new_email:\n if \"@\" not in new_email:\n request.session.flash(\"Error! Valid email required\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n else:\n user_data[\"email\"] = new_email\n request.session.flash(\"Success! Email updated\")\n\n else:\n user_data[\"blocked\"] = \"blocked\" in request.POST\n request.userdb.last_pending_time = 0\n request.actiondb.block_user(\n authenticated_userid(request),\n {\"user\": user_name, \"blocked\": user_data[\"blocked\"]},\n )\n request.session.flash(\n (\"Blocked\" if user_data[\"blocked\"] else \"Unblocked\")\n + \" user \"\n + user_name\n )\n request.userdb.save_user(user_data)\n return HTTPFound(location=request.route_url(\"tests\"))\n userc = request.userdb.user_cache.find_one({\"username\": user_name})\n hours = int(userc[\"cpu_hours\"]) if userc is not None else 0\n return {\n \"user\": user_data,\n \"limit\": request.userdb.get_machine_limit(user_name),\n \"hours\": hours,\n \"profile\": profile,\n }\n\n\n@view_config(route_name=\"users\", renderer=\"users.mak\")\ndef users(request):\n users_list = list(request.userdb.user_cache.find())\n users_list.sort(key=lambda k: k[\"cpu_hours\"], reverse=True)\n return {\"users\": users_list}\n\n\n@view_config(route_name=\"users_monthly\", renderer=\"users.mak\")\ndef users_monthly(request):\n users_list = list(request.userdb.top_month.find())\n users_list.sort(key=lambda k: k[\"cpu_hours\"], reverse=True)\n return {\"users\": users_list}\n\n\ndef get_master_bench():\n bs = re.compile(r\"(^|\\s)[Bb]ench[ :]+([0-9]+)\", re.MULTILINE)\n for c in requests.get(\n \"https://api.github.com/repos/official-stockfish/Stockfish/commits\"\n ).json():\n if \"commit\" not in c:\n return None\n m = bs.search(c[\"commit\"][\"message\"])\n if m:\n return m.group(2)\n return None\n\n\ndef get_sha(branch, repo_url):\n \"\"\"Resolves the git branch to sha commit\"\"\"\n api_url = repo_url.replace(\"https://github.com\", \"https://api.github.com/repos\")\n try:\n commit = requests.get(api_url + \"/commits/\" + branch).json()\n except:\n raise Exception(\"Unable to access developer repository\")\n if \"sha\" in commit:\n return commit[\"sha\"], commit[\"commit\"][\"message\"].split(\"\\n\")[0]\n else:\n return \"\", \"\"\n\n\ndef get_net(commit_sha, repo_url):\n \"\"\"Get the net from evaluate.h or ucioption.cpp in the repo\"\"\"\n api_url = repo_url.replace(\n \"https://github.com\", \"https://raw.githubusercontent.com\"\n )\n try:\n net = None\n\n url1 = api_url + \"/\" + commit_sha + \"/src/evaluate.h\"\n options = requests.get(url1).content.decode(\"utf-8\")\n for line in options.splitlines():\n if \"EvalFileDefaultName\" in line and \"define\" in line:\n p = re.compile(\"nn-[a-z0-9]{12}.nnue\")\n m = p.search(line)\n if m:\n net = m.group(0)\n\n if net:\n return net\n\n url2 = api_url + \"/\" + commit_sha + \"/src/ucioption.cpp\"\n options = requests.get(url2).content.decode(\"utf-8\")\n for line in options.splitlines():\n if \"EvalFile\" in line and \"Option\" in line:\n p = re.compile(\"nn-[a-z0-9]{12}.nnue\")\n m = p.search(line)\n if m:\n net = m.group(0)\n return net\n except:\n raise Exception(\"Unable to access developer repository: \" + api_url)\n\n\ndef parse_spsa_params(raw, spsa):\n params = []\n for line in raw.split(\"\\n\"):\n chunks = line.strip().split(\",\")\n if len(chunks) == 1 and chunks[0] == \"\": # blank line\n continue\n if len(chunks) != 6:\n raise Exception(\"the line %s does not have 6 entries\" % (chunks))\n param = {\n \"name\": chunks[0],\n \"start\": float(chunks[1]),\n \"min\": float(chunks[2]),\n \"max\": float(chunks[3]),\n \"c_end\": float(chunks[4]),\n \"r_end\": float(chunks[5]),\n }\n param[\"c\"] = param[\"c_end\"] * spsa[\"num_iter\"] ** spsa[\"gamma\"]\n param[\"a_end\"] = param[\"r_end\"] * param[\"c_end\"] ** 2\n param[\"a\"] = param[\"a_end\"] * (spsa[\"A\"] + spsa[\"num_iter\"]) ** spsa[\"alpha\"]\n param[\"theta\"] = param[\"start\"]\n params.append(param)\n return params\n\n\ndef validate_form(request):\n data = {\n \"base_tag\": request.POST[\"base-branch\"],\n \"new_tag\": request.POST[\"test-branch\"],\n \"tc\": request.POST[\"tc\"],\n \"book\": request.POST[\"book\"],\n \"book_depth\": request.POST[\"book-depth\"],\n \"base_signature\": request.POST[\"base-signature\"],\n \"new_signature\": request.POST[\"test-signature\"],\n \"base_options\": request.POST[\"base-options\"],\n \"new_options\": request.POST[\"new-options\"],\n \"username\": authenticated_userid(request),\n \"tests_repo\": request.POST[\"tests-repo\"],\n \"info\": request.POST[\"run-info\"],\n }\n\n if not re.match(r\"^([1-9]\\d*/)?\\d+(\\.\\d+)?(\\+\\d+(\\.\\d+)?)?$\", data[\"tc\"]):\n raise Exception(\"Bad time control format\")\n\n if request.POST.get(\"rescheduled_from\"):\n data[\"rescheduled_from\"] = request.POST[\"rescheduled_from\"]\n\n def strip_message(m):\n s = re.sub(r\"[Bb]ench[ :]+[0-9]+\\s*\", \"\", m)\n s = re.sub(r\"[ \\t]+\", \" \", s)\n s = re.sub(r\"\\n+\", r\"\\n\", s)\n return s.rstrip()\n\n # Fill new_signature/info from commit info if left blank\n if len(data[\"new_signature\"]) == 0 or len(data[\"info\"]) == 0:\n api_url = data[\"tests_repo\"].replace(\n \"https://github.com\", \"https://api.github.com/repos\"\n )\n api_url += \"/commits\" + \"/\" + data[\"new_tag\"]\n try:\n c = requests.get(api_url).json()\n except:\n raise Exception(\"Unable to access developer repository\")\n if \"commit\" not in c:\n raise Exception(\"Cannot find branch in developer repository\")\n if len(data[\"new_signature\"]) == 0:\n bs = re.compile(r\"(^|\\s)[Bb]ench[ :]+([0-9]+)\", re.MULTILINE)\n m = bs.search(c[\"commit\"][\"message\"])\n if m:\n data[\"new_signature\"] = m.group(2)\n else:\n raise Exception(\n \"This commit has no signature: please supply it manually.\"\n )\n if len(data[\"info\"]) == 0:\n data[\"info\"] = (\n \"\" if re.match(r\"^[012]?[0-9][^0-9].*\", data[\"tc\"]) else \"LTC: \"\n ) + strip_message(c[\"commit\"][\"message\"])\n\n # Check that the book exists in the official books repo\n if len(data[\"book\"]) > 0:\n api_url = \"https://api.github.com/repos/official-stockfish/books/contents\"\n c = requests.get(api_url).json()\n matcher = re.compile(r\"\\.(epd|pgn)\\.zip$\")\n valid_book_filenames = [\n file[\"name\"] for file in c if matcher.search(file[\"name\"])\n ]\n if data[\"book\"] + \".zip\" not in valid_book_filenames:\n raise Exception(\"Invalid book - \" + data[\"book\"])\n\n if request.POST[\"stop_rule\"] == \"spsa\":\n data[\"base_signature\"] = data[\"new_signature\"]\n\n for k, v in data.items():\n if len(v) == 0:\n raise Exception(\"Missing required option: %s\" % k)\n\n data[\"auto_purge\"] = request.POST.get(\"auto-purge\") is not None\n\n # In case of reschedule use old data,\n # otherwise resolve sha and update user's tests_repo\n if \"resolved_base\" in request.POST:\n data[\"resolved_base\"] = request.POST[\"resolved_base\"]\n data[\"resolved_new\"] = request.POST[\"resolved_new\"]\n data[\"msg_base\"] = request.POST[\"msg_base\"]\n data[\"msg_new\"] = request.POST[\"msg_new\"]\n else:\n data[\"resolved_base\"], data[\"msg_base\"] = get_sha(\n data[\"base_tag\"], data[\"tests_repo\"]\n )\n data[\"resolved_new\"], data[\"msg_new\"] = get_sha(\n data[\"new_tag\"], data[\"tests_repo\"]\n )\n u = request.userdb.get_user(data[\"username\"])\n if u.get(\"tests_repo\", \"\") != data[\"tests_repo\"]:\n u[\"tests_repo\"] = data[\"tests_repo\"]\n request.userdb.users.save(u)\n\n if len(data[\"resolved_base\"]) == 0 or len(data[\"resolved_new\"]) == 0:\n raise Exception(\"Unable to find branch!\")\n\n # Check entered bench\n if data[\"base_tag\"] == \"master\":\n found = False\n api_url = data[\"tests_repo\"].replace(\n \"https://github.com\", \"https://api.github.com/repos\"\n )\n api_url += \"/commits\"\n bs = re.compile(r\"(^|\\s)[Bb]ench[ :]+([0-9]+)\", re.MULTILINE)\n for c in requests.get(api_url).json():\n m = bs.search(c[\"commit\"][\"message\"])\n if m:\n found = True\n break\n if not found or m.group(2) != data[\"base_signature\"]:\n raise Exception(\n \"Bench signature of Base master does not match, \"\n + 'please \"git pull upstream master\" !'\n )\n\n stop_rule = request.POST[\"stop_rule\"]\n\n # Check if the base branch of the test repo matches official master\n api_url = \"https://api.github.com/repos/official-stockfish/Stockfish\"\n api_url += \"/compare/master...\" + data[\"resolved_base\"][:10]\n master_diff = requests.get(\n api_url, headers={\"Accept\": \"application/vnd.github.v3.diff\"}\n )\n data[\"base_same_as_master\"] = master_diff.text == \"\"\n\n # Test existence of net\n new_net = get_net(data[\"resolved_new\"], data[\"tests_repo\"])\n if new_net:\n if not request.rundb.get_nn(new_net):\n raise Exception(\n \"The net %s, used by %s, is not \"\n \"known to Fishtest. Please upload it to: \"\n \"%s/upload.\" % (new_net, data[\"new_tag\"], request.host_url)\n )\n\n # Store net info\n data[\"new_net\"] = new_net\n data[\"base_net\"] = get_net(data[\"resolved_base\"], data[\"tests_repo\"])\n\n # Integer parameters\n\n if stop_rule == \"sprt\":\n sprt_batch_size_games = 8\n assert sprt_batch_size_games % 2 == 0\n assert request.rundb.chunk_size % sprt_batch_size_games == 0\n elo_model = request.POST[\"elo_model\"]\n if elo_model not in [\"BayesElo\", \"logistic\", \"normalized\"]:\n raise Exception(\"Unknown Elo model\")\n data[\"sprt\"] = fishtest.stats.stat_util.SPRT(\n alpha=0.05,\n beta=0.05,\n elo0=float(request.POST[\"sprt_elo0\"]),\n elo1=float(request.POST[\"sprt_elo1\"]),\n elo_model=elo_model,\n batch_size=sprt_batch_size_games // 2,\n ) # game pairs\n # Limit on number of games played.\n # Shouldn't be hit in practice as long as it is larger than > ~200000\n # must scale with chunk_size to avoid overloading the server.\n data[\"num_games\"] = 2000 * request.rundb.chunk_size\n elif stop_rule == \"spsa\":\n data[\"num_games\"] = int(request.POST[\"num-games\"])\n if data[\"num_games\"] <= 0:\n raise Exception(\"Number of games must be >= 0\")\n\n data[\"spsa\"] = {\n \"A\": int(request.POST[\"spsa_A\"]),\n \"alpha\": float(request.POST[\"spsa_alpha\"]),\n \"gamma\": float(request.POST[\"spsa_gamma\"]),\n \"raw_params\": request.POST[\"spsa_raw_params\"],\n \"iter\": 0,\n \"num_iter\": int(data[\"num_games\"] / 2),\n \"clipping\": request.POST[\"spsa_clipping\"],\n \"rounding\": request.POST[\"spsa_rounding\"],\n }\n data[\"spsa\"][\"params\"] = parse_spsa_params(\n request.POST[\"spsa_raw_params\"], data[\"spsa\"]\n )\n if len(data[\"spsa\"][\"params\"]) == 0:\n raise Exception(\"Number of params must be > 0\")\n else:\n data[\"num_games\"] = int(request.POST[\"num-games\"])\n if data[\"num_games\"] <= 0:\n raise Exception(\"Number of games must be >= 0\")\n\n max_games = 4000 * request.rundb.chunk_size\n if data[\"num_games\"] > max_games:\n raise Exception(\"Number of games must be <= \" + str(max_games))\n\n data[\"threads\"] = int(request.POST[\"threads\"])\n data[\"priority\"] = int(request.POST[\"priority\"])\n data[\"throughput\"] = int(request.POST[\"throughput\"])\n\n if data[\"threads\"] <= 0:\n raise Exception(\"Threads must be >= 1\")\n\n return data\n\n\ndef del_tasks(run):\n if \"tasks\" in run:\n run = copy.deepcopy(run)\n del run[\"tasks\"]\n return run\n\n\ndef update_nets(request, run):\n run_id = str(run[\"_id\"])\n data = run[\"args\"]\n if run[\"base_same_as_master\"]:\n base_net = data[\"base_net\"]\n if base_net:\n net = request.rundb.get_nn(base_net)\n if not net:\n # Should never happen:\n raise Exception(\n \"The net %s, used by %s, is not \"\n \"known to Fishtest. Please upload it to: \"\n \"%s/upload.\" % (base_net, data[\"base_tag\"], request.host_url)\n )\n if \"is_master\" not in net:\n net[\"is_master\"] = True\n request.rundb.update_nn(net)\n new_net = data[\"new_net\"]\n if new_net:\n net = request.rundb.get_nn(new_net)\n if not net:\n return\n if \"first_test\" not in net:\n net[\"first_test\"] = {\"id\": run_id, \"date\": datetime.datetime.utcnow()}\n net[\"last_test\"] = {\"id\": run_id, \"date\": datetime.datetime.utcnow()}\n request.rundb.update_nn(net)\n\n\n@view_config(route_name=\"tests_run\", renderer=\"tests_run.mak\", require_csrf=True)\ndef tests_run(request):\n if not authenticated_userid(request):\n request.session.flash(\"Please login\")\n next_page = \"/tests/run\"\n if \"id\" in request.params:\n next_page += \"?id={}\".format(request.params[\"id\"])\n return HTTPFound(\n location=\"{}?next={}\".format(request.route_url(\"login\"), next_page)\n )\n if request.method == \"POST\":\n try:\n data = validate_form(request)\n run_id = request.rundb.new_run(**data)\n run = del_tasks(request.rundb.get_run(run_id))\n request.actiondb.new_run(authenticated_userid(request), run)\n cached_flash(request, \"Submitted test to the queue!\")\n return HTTPFound(location=\"/tests/view/\" + str(run_id))\n except Exception as e:\n request.session.flash(str(e), \"error\")\n\n run_args = {}\n if \"id\" in request.params:\n run_args = request.rundb.get_run(request.params[\"id\"])[\"args\"]\n\n username = authenticated_userid(request)\n u = request.userdb.get_user(username)\n\n return {\n \"args\": run_args,\n \"is_rerun\": len(run_args) > 0,\n \"rescheduled_from\": request.params[\"id\"] if \"id\" in request.params else None,\n \"tests_repo\": u.get(\"tests_repo\", \"\"),\n \"bench\": get_master_bench(),\n }\n\n\ndef can_modify_run(request, run):\n return run[\"args\"][\"username\"] == authenticated_userid(request) or has_permission(\n \"approve_run\", request.context, request\n )\n\n\n@view_config(route_name=\"tests_modify\", require_csrf=True, request_method=\"POST\")\ndef tests_modify(request):\n if not authenticated_userid(request):\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n if \"num-games\" in request.POST:\n run = request.rundb.get_run(request.POST[\"run\"])\n before = del_tasks(run)\n\n if not can_modify_run(request, run):\n request.session.flash(\"Unable to modify another user's run!\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n existing_games = 0\n for chunk in run[\"tasks\"]:\n existing_games += chunk[\"num_games\"]\n if \"stats\" in chunk:\n stats = chunk[\"stats\"]\n total = stats[\"wins\"] + stats[\"losses\"] + stats[\"draws\"]\n if total < chunk[\"num_games\"]:\n chunk[\"pending\"] = True\n\n num_games = int(request.POST[\"num-games\"])\n if (\n num_games > run[\"args\"][\"num_games\"]\n and \"sprt\" not in run[\"args\"]\n and \"spsa\" not in run[\"args\"]\n ):\n request.session.flash(\n \"Unable to modify number of games in a fixed game test!\", \"error\"\n )\n return HTTPFound(location=request.route_url(\"tests\"))\n\n max_games = 4000 * request.rundb.chunk_size\n if num_games > max_games:\n request.session.flash(\n \"Number of games must be <= \" + str(max_games), \"error\"\n )\n return HTTPFound(location=request.route_url(\"tests\"))\n\n if num_games > existing_games:\n # Create new chunks for the games\n new_chunks = request.rundb.generate_tasks(num_games - existing_games)\n run[\"tasks\"] += new_chunks\n\n run[\"finished\"] = False\n run[\"args\"][\"num_games\"] = num_games\n run[\"args\"][\"priority\"] = int(request.POST[\"priority\"])\n run[\"args\"][\"throughput\"] = int(request.POST[\"throughput\"])\n run[\"args\"][\"auto_purge\"] = True if request.POST.get(\"auto_purge\") else False\n request.rundb.calc_itp(run)\n request.rundb.buffer(run, True)\n request.rundb.task_time = 0\n\n after = del_tasks(run)\n request.actiondb.modify_run(authenticated_userid(request), before, after)\n\n cached_flash(request, \"Run successfully modified!\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(route_name=\"tests_stop\", require_csrf=True, request_method=\"POST\")\ndef tests_stop(request):\n if not authenticated_userid(request):\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n if \"run-id\" in request.POST:\n run = request.rundb.get_run(request.POST[\"run-id\"])\n if not can_modify_run(request, run):\n request.session.flash(\"Unable to modify another users run!\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n run[\"finished\"] = True\n request.rundb.stop_run(request.POST[\"run-id\"])\n run = del_tasks(run)\n request.actiondb.stop_run(authenticated_userid(request), run)\n cached_flash(request, \"Stopped run\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(route_name=\"tests_approve\", require_csrf=True, request_method=\"POST\")\ndef tests_approve(request):\n if not authenticated_userid(request):\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n if not has_permission(\"approve_run\", request.context, request):\n request.session.flash(\"Please login as approver\")\n return HTTPFound(location=request.route_url(\"login\"))\n username = authenticated_userid(request)\n run_id = request.POST[\"run-id\"]\n if request.rundb.approve_run(run_id, username):\n run = request.rundb.get_run(run_id)\n run = del_tasks(run)\n update_nets(request, run)\n request.actiondb.approve_run(username, run)\n cached_flash(request, \"Approved run\")\n else:\n request.session.flash(\"Unable to approve run!\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(route_name=\"tests_purge\", require_csrf=True, request_method=\"POST\")\ndef tests_purge(request):\n if not has_permission(\"approve_run\", request.context, request):\n request.session.flash(\"Please login as approver\")\n return HTTPFound(location=request.route_url(\"login\"))\n username = authenticated_userid(request)\n\n run = request.rundb.get_run(request.POST[\"run-id\"])\n if not run[\"finished\"]:\n request.session.flash(\"Can only purge completed run\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n purged = request.rundb.purge_run(run)\n if not purged:\n request.session.flash(\"No bad workers!\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n run = del_tasks(run)\n request.actiondb.purge_run(username, run)\n\n cached_flash(request, \"Purged run\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(route_name=\"tests_delete\", require_csrf=True, request_method=\"POST\")\ndef tests_delete(request):\n if not authenticated_userid(request):\n request.session.flash(\"Please login\")\n return HTTPFound(location=request.route_url(\"login\"))\n if \"run-id\" in request.POST:\n run = request.rundb.get_run(request.POST[\"run-id\"])\n if not can_modify_run(request, run):\n request.session.flash(\"Unable to modify another users run!\", \"error\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n run[\"deleted\"] = True\n run[\"finished\"] = True\n for w in run[\"tasks\"]:\n w[\"pending\"] = False\n request.rundb.buffer(run, True)\n request.rundb.task_time = 0\n\n run = del_tasks(run)\n request.actiondb.delete_run(authenticated_userid(request), run)\n\n cached_flash(request, \"Deleted run\")\n return HTTPFound(location=request.route_url(\"tests\"))\n\n\n@view_config(route_name=\"tests_stats\", renderer=\"tests_stats.mak\")\ndef tests_stats(request):\n run = request.rundb.get_run(request.matchdict[\"id\"])\n request.rundb.get_results(run)\n return {\"run\": run}\n\n\n@view_config(route_name=\"tests_machines\", renderer=\"machines_table.mak\")\ndef tests_machines(request):\n machines = request.rundb.get_machines()\n for machine in machines:\n diff = diff_date(machine[\"last_updated\"])\n machine[\"last_updated\"] = delta_date(diff)\n return {\"machines\": machines}\n\n\n@view_config(route_name=\"tests_view_spsa_history\", renderer=\"json\")\ndef tests_view_spsa_history(request):\n run = request.rundb.get_run(request.matchdict[\"id\"])\n if \"spsa\" not in run[\"args\"]:\n return {}\n\n return run[\"args\"][\"spsa\"]\n\n\n@view_config(route_name=\"tests_view\", renderer=\"tests_view.mak\")\ndef tests_view(request):\n run = request.rundb.get_run(request.matchdict[\"id\"])\n if run is None:\n raise exception_response(404)\n results = request.rundb.get_results(run)\n run[\"results_info\"] = format_results(results, run)\n run_args = [(\"id\", str(run[\"_id\"]), \"\")]\n if run.get(\"rescheduled_from\"):\n run_args.append((\"rescheduled_from\", run[\"rescheduled_from\"], \"\"))\n\n for name in [\n \"new_tag\",\n \"new_signature\",\n \"new_options\",\n \"resolved_new\",\n \"new_net\",\n \"base_tag\",\n \"base_signature\",\n \"base_options\",\n \"resolved_base\",\n \"base_net\",\n \"sprt\",\n \"num_games\",\n \"spsa\",\n \"tc\",\n \"threads\",\n \"book\",\n \"book_depth\",\n \"auto_purge\",\n \"priority\",\n \"itp\",\n \"username\",\n \"tests_repo\",\n \"info\",\n ]:\n\n if name not in run[\"args\"]:\n continue\n\n value = run[\"args\"][name]\n url = \"\"\n\n if name == \"new_tag\" and \"msg_new\" in run[\"args\"]:\n value += \" (\" + run[\"args\"][\"msg_new\"][:50] + \")\"\n\n if name == \"base_tag\" and \"msg_base\" in run[\"args\"]:\n value += \" (\" + run[\"args\"][\"msg_base\"][:50] + \")\"\n\n if name == \"sprt\" and value != \"-\":\n value = \"elo0: %.2f alpha: %.2f elo1: %.2f beta: %.2f state: %s (%s)\" % (\n value[\"elo0\"],\n value[\"alpha\"],\n value[\"elo1\"],\n value[\"beta\"],\n value.get(\"state\", \"-\"),\n value.get(\"elo_model\", \"BayesElo\"),\n )\n\n if name == \"spsa\" and value != \"-\":\n iter_local = value[\"iter\"] + 1 # assume at least one completed,\n # and avoid division by zero\n A = value[\"A\"]\n alpha = value[\"alpha\"]\n gamma = value[\"gamma\"]\n summary = (\n \"Iter: %d, A: %d, alpha %0.3f, gamma %0.3f, clipping %s, rounding %s\"\n % (\n iter_local,\n A,\n alpha,\n gamma,\n value[\"clipping\"] if \"clipping\" in value else \"old\",\n value[\"rounding\"] if \"rounding\" in value else \"deterministic\",\n )\n )\n params = value[\"params\"]\n value = [summary]\n for p in params:\n value.append(\n [\n p[\"name\"],\n \"{:.2f}\".format(p[\"theta\"]),\n int(p[\"start\"]),\n int(p[\"min\"]),\n int(p[\"max\"]),\n \"{:.3f}\".format(p[\"c\"] / (iter_local ** gamma)),\n \"{:.3f}\".format(p[\"a\"] / (A + iter_local) ** alpha),\n ]\n )\n if \"tests_repo\" in run[\"args\"]:\n if name == \"new_tag\":\n url = (\n run[\"args\"][\"tests_repo\"] + \"/commit/\" + run[\"args\"][\"resolved_new\"]\n )\n elif name == \"base_tag\":\n url = (\n run[\"args\"][\"tests_repo\"]\n + \"/commit/\"\n + run[\"args\"][\"resolved_base\"]\n )\n elif name == \"tests_repo\":\n url = value\n\n if name == \"spsa\":\n run_args.append((\"spsa\", value, \"\"))\n else:\n try:\n strval = str(value)\n except:\n strval = value.encode(\"ascii\", \"replace\")\n if name not in [\"new_tag\", \"base_tag\"]:\n strval = html.escape(strval)\n run_args.append((name, strval, url))\n\n active = 0\n cores = 0\n for task in run[\"tasks\"]:\n if task[\"active\"]:\n active += 1\n cores += task[\"worker_info\"][\"concurrency\"]\n last_updated = task.get(\"last_updated\", datetime.datetime.min)\n task[\"last_updated\"] = last_updated\n\n if run[\"args\"].get(\"sprt\"):\n page_title = \"SPRT {} vs {}\".format(\n run[\"args\"][\"new_tag\"], run[\"args\"][\"base_tag\"]\n )\n elif run[\"args\"].get(\"spsa\"):\n page_title = \"SPSA {}\".format(run[\"args\"][\"new_tag\"])\n else:\n page_title = \"{} games - {} vs {}\".format(\n run[\"args\"][\"num_games\"], run[\"args\"][\"new_tag\"], run[\"args\"][\"base_tag\"]\n )\n return {\n \"run\": run,\n \"run_args\": run_args,\n \"page_title\": page_title,\n \"approver\": has_permission(\"approve_run\", request.context, request),\n \"chi2\": calculate_residuals(run),\n \"totals\": \"(%s active worker%s with %s core%s)\"\n % (active, (\"s\" if active != 1 else \"\"), cores, (\"s\" if cores != 1 else \"\")),\n }\n\n\ndef get_paginated_finished_runs(request):\n username = request.matchdict.get(\"username\", \"\")\n success_only = request.params.get(\"success_only\", False)\n yellow_only = request.params.get(\"yellow_only\", False)\n ltc_only = request.params.get(\"ltc_only\", False)\n\n page_idx = max(0, int(request.params.get(\"page\", 1)) - 1)\n page_size = 25\n finished_runs, num_finished_runs = request.rundb.get_finished_runs(\n username=username,\n success_only=success_only,\n yellow_only=yellow_only,\n ltc_only=ltc_only,\n skip=page_idx * page_size,\n limit=page_size,\n )\n\n pages = [\n {\n \"idx\": \"Prev\",\n \"url\": \"?page={}\".format(page_idx),\n \"state\": \"disabled\" if page_idx == 0 else \"\",\n }\n ]\n for idx, _ in enumerate(range(0, num_finished_runs, page_size)):\n if (\n idx < 5\n or abs(page_idx - idx) < 5\n or idx > (num_finished_runs / page_size) - 5\n ):\n pages.append(\n {\n \"idx\": idx + 1,\n \"url\": \"?page={}\".format(idx + 1),\n \"state\": \"active\" if page_idx == idx else \"\",\n }\n )\n elif pages[-1][\"idx\"] != \"...\":\n pages.append({\"idx\": \"...\", \"url\": \"\", \"state\": \"disabled\"})\n pages.append(\n {\n \"idx\": \"Next\",\n \"url\": \"?page={}\".format(page_idx + 2),\n \"state\": \"disabled\" if page_idx + 1 == len(pages) - 1 else \"\",\n }\n )\n\n for page in pages:\n if success_only:\n page[\"url\"] += \"&success_only=1\"\n if yellow_only:\n page[\"url\"] += \"&yellow_only=1\"\n if ltc_only:\n page[\"url\"] += \"<c_only=1\"\n\n failed_runs = []\n for run in finished_runs:\n # Ensure finished runs have results_info\n results = request.rundb.get_results(run)\n if \"results_info\" not in run:\n run[\"results_info\"] = format_results(results, run)\n\n # Look for failed runs\n if \"failed\" in run:\n failed_runs.append(run)\n\n return {\n \"finished_runs\": finished_runs,\n \"finished_runs_pages\": pages,\n \"num_finished_runs\": num_finished_runs,\n \"failed_runs\": failed_runs,\n \"page_idx\": page_idx,\n }\n\n\n@view_config(route_name=\"tests_finished\", renderer=\"tests_finished.mak\")\ndef tests_finished(request):\n return get_paginated_finished_runs(request)\n\n\n@view_config(route_name=\"tests_user\", renderer=\"tests_user.mak\")\ndef tests_user(request):\n username = request.matchdict.get(\"username\", \"\")\n response = {**get_paginated_finished_runs(request), \"username\": username}\n if int(request.params.get(\"page\", 1)) == 1:\n response[\"runs\"] = request.rundb.aggregate_unfinished_runs(username)[0]\n # page 2 and beyond only show finished test results\n return response\n\n\ndef homepage_results(request):\n # Calculate games_per_minute from current machines\n games_per_minute = 0.0\n machines = request.rundb.get_machines()\n for machine in machines:\n diff = diff_date(machine[\"last_updated\"])\n machine[\"last_updated\"] = delta_date(diff)\n if machine[\"nps\"] != 0:\n games_per_minute += (\n (machine[\"nps\"] / 1080000.0)\n * (60.0 / estimate_game_duration(machine[\"run\"][\"args\"][\"tc\"]))\n * (\n int(machine[\"concurrency\"])\n // machine[\"run\"][\"args\"].get(\"threads\", 1)\n )\n )\n machines.reverse()\n # Get updated results for unfinished runs + finished runs\n (runs, pending_hours, cores, nps) = request.rundb.aggregate_unfinished_runs()\n return {\n **get_paginated_finished_runs(request),\n \"runs\": runs,\n \"machines\": machines,\n \"pending_hours\": \"%.1f\" % (pending_hours),\n \"cores\": cores,\n \"nps\": nps,\n \"games_per_minute\": int(games_per_minute),\n }\n\n\n# For caching the homepage tests output\ncache_time = 2\nlast_tests = None\nlast_time = 0\n\n# Guard against parallel builds of main page\nbuilding = threading.Semaphore()\n\n\n@view_config(route_name=\"tests\", renderer=\"tests.mak\")\ndef tests(request):\n if int(request.params.get(\"page\", 1)) > 1:\n # page 2 and beyond only show finished test results\n return get_paginated_finished_runs(request)\n\n global last_tests, last_time\n if time.time() - last_time > cache_time:\n acquired = building.acquire(last_tests is None)\n if not acquired:\n # We have a current cache and another thread is rebuilding,\n # so return the current cache\n pass\n elif time.time() - last_time < cache_time:\n # Another thread has built the cache for us, so we are done\n building.release()\n else:\n # Not cached, so calculate and fetch homepage results\n try:\n last_tests = homepage_results(request)\n except Exception as e:\n print(\"Overview exception: \" + str(e))\n if not last_tests:\n raise e\n finally:\n last_time = time.time()\n building.release()\n return {\n **last_tests,\n \"machines_shown\": request.cookies.get(\"machines_state\") == \"Hide\",\n \"pending_shown\": request.cookies.get(\"pending_state\") == \"Hide\",\n \"paused_shown\": request.cookies.get(\"paused_state\") == \"Hide\",\n }\n","sub_path":"server/fishtest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":45810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589648448","text":"from openpyxl import Workbook, load_workbook\nfrom contextlib import closing\n\ndef make_excel_file(file_name):\n with closing(Workbook()) as wb:\n wb.save(file_name)\n\ndef add_value(file_name, sheet_name, cell_cords, value):\n with closing(load_workbook(filename=file_name)) as wb:\n ws = wb.active\n ws = wb.get_sheet_by_name(name = sheet_name) \n ws[cell_cords] = value\n wb.save(file_name)\n","sub_path":"Resource/Write to excel file.py","file_name":"Write to excel file.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"251506253","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random\nimport util\n\nfrom game import Agent\n\n\nclass ReflexAgent(Agent):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tA reflex agent chooses an action at each choice point by examining\n\t\t\t\t\t\t\t\t\tits alternatives via a state evaluation function.\n\n\t\t\t\t\t\t\t\t\tThe code below is provided as a guide. You are welcome to change\n\t\t\t\t\t\t\t\t\tit in any way you see fit, so long as you don't touch our method\n\t\t\t\t\t\t\t\t\theaders.\n\t\"\"\"\n\n\tdef getAction(self, gameState):\n\t\t\"\"\"\n\t\tYou do not need to change this method, but you're welcome to.\n\n\t\tgetAction chooses among the best options according to the evaluation function.\n\n\t\tJust like in the previous project, getAction takes a GameState and returns\n\t\tsome Directions.X for some X in the set {North, South, West, East, Stop}\n\t\t\"\"\"\n\t\t# Collect legal moves and successor states\n\t\tlegalMoves = gameState.getLegalActions()\n\n\t\t# Choose one of the best actions\n\t\tscores = [self.evaluationFunction(\n\t\t\tgameState, action) for action in legalMoves]\n\t\tbestScore = max(scores)\n\t\tbestIndices = [index for index in range(\n\t\t\tlen(scores)) if scores[index] == bestScore]\n\t\t# Pick randomly among the best\n\t\tchosenIndex = random.choice(bestIndices)\n\n\t\t\"Add more of your code here if you want to\"\n\n\t\treturn legalMoves[chosenIndex]\n\n\tdef evaluationFunction(self, currentGameState, action):\n\t\t\"\"\"\n\t\tDesign a better evaluation function here.\n\n\t\tThe evaluation function takes in the current and proposed successor\n\t\tGameStates (pacman.py) and returns a number, where higher numbers are better.\n\n\t\tThe code below extracts some useful information from the state, like the\n\t\tremaining food (newFood) and Pacman position after moving (newPos).\n\t\tnewScaredTimes holds the number of moves that each ghost will remain\n\t\tscared because of Pacman having eaten a power pellet.\n\n\t\tPrint out these variables to see what you're getting, then combine them\n\t\tto create a masterful evaluation function.\n\t\t\"\"\"\n\t\t# Useful information you can extract from a GameState (pacman.py)\n\t\tsuccessorGameState = currentGameState.generatePacmanSuccessor(action)\n\t\tnewPos = successorGameState.getPacmanPosition()\n\t\tnewFood = successorGameState.getFood()\n\t\tnewGhostStates = successorGameState.getGhostStates()\n\t\tnewScaredTimes = [\n\t\t\tghostState.scaredTimer for ghostState in newGhostStates]\n\n\t\t\"*** YOUR CODE HERE ***\"\n\t\treturn successorGameState.getScore()\n\n\ndef scoreEvaluationFunction(currentGameState):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tThis default evaluation function just returns the score of the state.\n\t\t\t\t\t\t\t\t\tThe score is the same one displayed in the Pacman GUI.\n\n\t\t\t\t\t\t\t\t\tThis evaluation function is meant for use with adversarial search agents\n\t\t\t\t\t\t\t\t\t(not reflex agents).\n\t\"\"\"\n\treturn currentGameState.getScore()\n\n\nclass MultiAgentSearchAgent(Agent):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tThis class provides some common elements to all of your\n\t\t\t\t\t\t\t\t\tmulti-agent searchers. Any methods defined here will be available\n\t\t\t\t\t\t\t\t\tto the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n\t\t\t\t\t\t\t\t\tYou *do not* need to make any changes here, but you can if you want to\n\t\t\t\t\t\t\t\t\tadd functionality to all your adversarial search agents. Please do not\n\t\t\t\t\t\t\t\t\tremove anything, however.\n\n\t\t\t\t\t\t\t\t\tNote: this is an abstract class: one that should not be instantiated. It's\n\t\t\t\t\t\t\t\t\tonly partially specified, and designed to be extended. Agent (game.py)\n\t\t\t\t\t\t\t\t\tis another abstract class.\n\t\"\"\"\n\n\tdef __init__(self, evalFn='scoreEvaluationFunction', depth='2'):\n\t\tself.index = 0 # Pacman is always agent index 0\n\t\tself.evaluationFunction = util.lookup(evalFn, globals())\n\t\tself.depth = int(depth)\n\n\nimport sys\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tYour minimax agent (question 2)\n\t\"\"\"\n\n\tdef getAction(self, gameState):\n\t\t\"\"\"\n\t\t\t\t\t\t\t\t\t\tReturns the minimax action from the current gameState using self.depth\n\t\t\t\t\t\t\t\t\t\tand self.evaluationFunction.\n\n\t\t\t\t\t\t\t\t\t\tHere are some method calls that might be useful when implementing minimax.\n\n\t\t\t\t\t\t\t\t\t\tgameState.getLegalActions(agentIndex):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tReturns a list of legal actions for an agent\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tagentIndex=0 means Pacman, ghosts are >= 1\n\n\t\t\t\t\t\t\t\t\t\tgameState.generateSuccessor(agentIndex, action):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tReturns the successor game state after an agent takes an action\n\n\t\t\t\t\t\t\t\t\t\tgameState.getNumAgents():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tReturns the total number of agents in the game\n\n\t\t\t\t\t\t\t\t\t\tgameState.isWin() #True if game is won\n\t\t\t\t\t\t\t\t\t\tgameState.isLose() #True if game is lost\n\n\t\t\t\t\t\t\t\t\t\tself.evaluationFunction(gameState)\n\n\t\t\t\t\t\t\t\t\t\teach ghost generate a state\n\t\t\t\t\t\t\t\t\t\tDepth is number of times we run max\n\n\t\t\"\"\"\n\t\tdef maxPlayer(gameState, depth):\n\t\t\t\"\"\" max function for pacman \"\"\"\n\t\t\t#CHeck if we are at the bottom of the tree(where we get a value), or we have encountered an winning or losing move.\n\t\t\tif (gameState.isWin() or gameState.isLose() or depth == 0):\n \t\t\t#Return value the value of this move.\n\t\t\t\treturn self.evaluationFunction(gameState)\n\t\t\t#Store a value as - infinite ( large value what we know will be overwritten)\n\t\t\tvalue = -sys.maxint - 1\n\n\t\t\t# Check for every action, from legelActions pacman(index 0)\n\t\t\tfor action in gameState.getLegalActions(pac_index):\n\t\t\t\t# Get next state with this action from pacman's index.\n\t\t\t\tnextState = gameState.generateSuccessor(pac_index, action)\n\t\t\t\tvalue = max(value, minPlayer(nextState, depth, pac_index + 1))\n\t\t\treturn value\n\n\t\tdef minPlayer(gameState, depth, ghost_index):\n\t\t\t\"\"\" min function for ghosts \"\"\"\n\t\t\tif (gameState.isWin() or gameState.isLose() or depth == 0):\n\t\t\t\treturn self.evaluationFunction(gameState)\n\t\t\tvalue = sys.maxint\n\t\t\tlegalActions = gameState.getLegalActions(ghost_index)\n\n\t\t\t# We need to check if we are at the last ghost.\n\t\t\tif (ghost_index == gameState.getNumAgents() - 1):\n \t\t\t#Check every action of this ghost.\n\t\t\t\tfor action in legalActions:\n\t\t\t\t\tnextState = gameState.generateSuccessor(\n\t\t\t\t\t\tghost_index, action)\n\t\t\t\t\t#recursivly check the next level in the tree (MaxPlayer in this case)\n\t\t\t\t\tvalue = min(value, maxPlayer(nextState, depth - 1))\n\t\t\telse:\n\t\t\t\tfor action in legalActions:\n\t\t\t\t\tnextState = gameState.generateSuccessor(\n\t\t\t\t\t\tghost_index, action)\n\t\t\t\t\t#Recursivly check the next level in the tree(Next is a Ghost layer)\n\t\t\t\t\tvalue = min(value, minPlayer(\n\t\t\t\t\t\tnextState, depth, ghost_index + 1))\n\t\t\treturn value\n\n\t\t# Generate minmax tree of depth 2.\n\t\tpac_index = 0\n\t\t#Set bestAction to STOP, because we know this is allwasy a valid move. \n\t\t#Incase we cant find a better move with the miniMax tree, we will just stand still\n\t\tbestAction = Directions.STOP\n\t\t#Generate all the legal actions for pacman.\n\t\tlegalActions = gameState.getLegalActions(pac_index)\n\t\t#set current score to a very small number, to be overwritten later.\n\t\tscore = -sys.maxint - 1\n\n\t\tfor action in legalActions:\n\t\t\tnext_state = gameState.generateSuccessor(pac_index, action)\n\t\t\t# Check which action is the best action with minmax algorithm\n\t\t\tprev_score = score\n\t\t\t#Get a new score from the tree.\n\t\t\tscore = max(score, minPlayer(next_state, self.depth, 1))\n\t\t\t#Check if the new score is better than the previous one, \n\t\t\t#if it is we change the bestAction to our current action itteration.\n\t\t\tif(score > prev_score):\n\t\t\t\tbestAction = action\n\t\t#Return the best Action we got from checking every step in the minimax tree.\n\t\treturn bestAction\n\n\t\tutil.raiseNotDefined()\n\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tYour minimax agent with alpha-beta pruning (question 3)\n\t\"\"\"\n\n\tdef getAction(self, gameState):\n\t\t\"\"\"\n\t\t\tReturns the minimax action using self.depth and self.evaluationFunction\n\t\t\"\"\"\n\t\tdef maxPlayer(gameState, a, b, depth):\n\t\t\t\"\"\" max function for pacman \"\"\"\n\t\t\tif (gameState.isWin() or gameState.isLose() or depth == 0):\n\t\t\t\treturn self.evaluationFunction(gameState)\n\t\t\t# Store system.max negative integer\n\t\t\tvalue = -sys.maxint - 1\n\t\t\t# Check for every action, from legelActions pacman(index 0)\n\t\t\tfor action in gameState.getLegalActions(pac_index):\n\t\t\t\t# Get next state with this action from pacman's index.\n\t\t\t\tnextState = gameState.generateSuccessor(pac_index, action)\n\t\t\t\t# Get the max value of the next min layers.\n\t\t\t\tvalue = max(value, minPlayer(\n\t\t\t\t\tnextState, a, b, pac_index + 1, depth))\n\t\t\t\t#Check if the value that is returned is smaller than the beta value\n\t\t\t\tif(value > b):\n\t\t\t\t\t#Return value now, because we know it is the best we can get.\n\t\t\t\t\treturn value\n\t\t\t\ta = max(a, value)\n\t\t\treturn value\n\n\t\tdef minPlayer(gameState, a, b, ghost_index, depth):\n\t\t\t\"\"\" min function for ghost \"\"\"\n\t\t\tif (gameState.isWin() or gameState.isLose() or depth == 0):\n\t\t\t\treturn self.evaluationFunction(gameState)\n\t\t\t# Store system.max integer.\n\t\t\tvalue = sys.maxint\n\t\t\tlegalActions = gameState.getLegalActions(ghost_index)\n\t\t\t\t# We need to check if we are at the last ghost.\n\t\t\tif (ghost_index == gameState.getNumAgents()-1):\n\t\t\t\tfor action in legalActions:\n\t\t\t\t\tnextState = gameState.generateSuccessor(ghost_index, action)\n\t\t\t\t\t#get value from next dept in the tree. Where next is a max.\n\t\t\t\t\tvalue = min(value, maxPlayer(nextState, a, b, depth-1))\n\t\t\t\t\tif(value < a):\n \t\t\t\t\t#Return value now, since we can't get a better value\n\t\t\t\t\t\treturn value\n\t\t\t\t\tb = min(b,value)\n\t\t\telse:\n\t\t\t\t#if we are not at the last ghost(min layer), we got n-ghosts min layer\n\t\t\t\tfor action in legalActions:\n\t\t\t\t\tnextState = gameState.generateSuccessor(ghost_index, action)\n\t\t\t\t\t#Get next value from the next ghost in a min layer.\n\t\t\t\t\tvalue = min(value, minPlayer(nextState,a,b,ghost_index+1,depth))\n\t\t\t\t\tif(value < a):\n \t\t\t\t\t#Return value now, since we can't get a better value\n\t\t\t\t\t\treturn value\n\t\t\t\t\tb = min(b,value)\n\t\t\treturn value\n\n\t\t\"\"\"\n\t\t\tFor the alpha-beta tree, alpha a is a ceiling value, whilst beta b is a floor value. \n\t\t\tWe know we can atleast expect either an alpha value or a beta value, depending on our current layer.\n\t\t\tWe alwasy compare the current beta and alpha values with previous layers, if we encounter a value smaller than alpha,\n\t\t\tor greater than beta, we know we don't have to check the rest of that tree.\n\t\t\"\"\"\n\t\t# Generate minmax tree of depth 2.\n\t\tpac_index = 0\n\t\tbestAction = Directions.STOP\n\t\tlegalActions = gameState.getLegalActions(pac_index)\n\t\tscore = -sys.maxint - 1\n\t\t#Alpha init value\n\t\ta = -sys.maxint - 1\n\t\t#Beta init value\n\t\tb = sys.maxint\n\t\t#itterate tru every action pacman can do. Return the one with best value\n\t\tfor action in legalActions:\n\t\t\tnext_state = gameState.generateSuccessor(pac_index, action)\n\t\t\t# Check which action is the best action with minmax algorithm\n\t\t\tprev_score = score\n\t\t\t#Get score of this action with the minimax alg above.\n\t\t\tscore = max(score, minPlayer(\n\t\t\t\tnext_state, a, b, pac_index + 1, self.depth))\n\t\t\t#Check our score from the tree generated from this action.\n\t\t\t#And set new action if it is better than the pevious one.\n\t\t\tif(score > prev_score):\n\t\t\t\tbestAction = action\n\t\t\tif(score >= b):\n\t\t\t\t# if score is higher than beta, we can stop. Because know it will never get any lower than beta b.\n\t\t\t\treturn bestAction\n\t\t\t# Update alpha\n\t\t\ta = max(a, score)\n\t\treturn bestAction\n\n\t\tutil.raiseNotDefined()\n\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tYour expectimax agent (question 4)\n\t\"\"\"\n\n\tdef getAction(self, gameState):\n\t\t\"\"\"\n\t\t\t\t\t\t\t\t\t\tReturns the expectimax action using self.depth and self.evaluationFunction\n\n\t\t\t\t\t\t\t\t\t\tAll ghosts should be modeled as choosing uniformly at random from their\n\t\t\t\t\t\t\t\t\t\tlegal moves.\n\t\t\"\"\"\n\t\t\"*** YOUR CODE HERE ***\"\n\t\tutil.raiseNotDefined()\n\n\ndef betterEvaluationFunction(currentGameState):\n\t\"\"\"\n\t\t\t\t\t\t\t\t\tYour extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n\t\t\t\t\t\t\t\t\tevaluation function (question 5).\n\n\t\t\t\t\t\t\t\t\tDESCRIPTION: \n\t\"\"\"\n\t\"*** YOUR CODE HERE ***\"\n\tutil.raiseNotDefined()\n\n\n# Abbreviation\nbetter = betterEvaluationFunction\n","sub_path":"multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":12475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"363426136","text":"import struct;\nimport csv;\n\nINT_LEN = 4;\nUINT_LEN = 4;\nLONG_LEN = 8;\n\ndef get_file_size(f):\n\tpos = f.tell();\n\tf.seek(0, 2);\n\tsize = f.tell();\n\tf.seek(pos, 0);\n\treturn size;\n\ndef aligned_stream(f, alignment):\n\tpos = f.tell();\n\tmod = pos % alignment;\n\tif (mod != 0):\n\t\tf.seek(alignment - mod, 1);\n\t\ndef read_aligned_str(f, len = None):\n\tif len is None:\n\t\tlen = struct.unpack(\" 0 and len <= (get_file_size(f) - f.tell())):\n\t\tstr = f.read(len);\n\t\taligned_stream(f, 4);\n\t\treturn str;\n\treturn \"\";\n\ndef deserialize_stringbank(file_name):\n\tgameobj_fielID = 0;\n\tgameobj_pathID = 0;\n\tgameobj_enabled = 0;\n\tscript_fielID = 0;\n\tscript_pathID = 0;\n\tscript_name = 0;\n\tpair_len = 0;\n\tkey_arr = [];\n\tvalue_arr = [];\n\n\tf = open(file_name + '.dat', 'rb');\n\n\tgameobj_fielID = struct.unpack(\" ():\n position = self.doGetPosition()\n NotificationCenter().postNotification(LinearMotionNotification.didGetPosition, notifyingObject=self, userInfo=position)\n return position\n\n def home(self) -> ():\n NotificationCenter().postNotification(LinearMotionNotification.willMove, notifyingObject=self)\n self.doHome()\n NotificationCenter().postNotification(LinearMotionNotification.didMove, notifyingObject=self)\n\n def moveInMicronsTo(self, position):\n nativePosition = [x * self.nativeStepsPerMicrons for x in position]\n self.moveTo(nativePosition)\n\n def moveInMicronsBy(self, displacement):\n nativeDisplacement = [dx * self.nativeStepsPerMicrons for dx in displacement]\n self.moveTo(nativeDisplacement)\n\n def positionInMicrons(self):\n position = self.position()\n positionInMicrons = [x / self.nativeStepsPerMicrons for x in position]\n return tuple(positionInMicrons)\n\n def mapPositions(self, width: int, height: int, stepInMicrons: float, direction: Direction = Direction.unidirectional):\n \"\"\"mapPositions(width, height, stepInMicrons[, direction == \"leftRight\" or \"zigzag\"])\n\n Returns a list of position tuples, which can be used directly in moveTo functions, to map a sample.\"\"\"\n\n (initWidth, initHeight, depth) = self.positionInMicrons()\n mapPositions = []\n for j in range(height):\n y = initHeight + j * stepInMicrons\n if Direction(direction) == Direction.unidirectional:\n for i in range(width):\n x = initWidth + i*stepInMicrons\n index = (i, j)\n position = (x, y, depth)\n info = {\"index\": index, \"position\": position}\n mapPositions.append(info)\n elif Direction(direction) == Direction.bidirectional:\n if j % 2 == 0:\n for i in range(width):\n x = initWidth + i * stepInMicrons\n index = (i, j)\n position = (x, y, depth)\n info = {\"index\": index, \"position\": position}\n mapPositions.append(info)\n elif j % 2 == 1:\n for i in range(width-1, -1, -1):\n x = initWidth + i * stepInMicrons\n index = (i, j)\n position = (x, y, depth)\n info = {\"index\": index, \"position\": position}\n mapPositions.append(info)\n else:\n raise ValueError(\"Invalid direction: {0}\".format(direction))\n return mapPositions\n\n\nclass DebugLinearMotionDevice(LinearMotionDevice):\n classIdProduct = 0xfffd\n classIdVendor = debugClassIdVendor\n def __init__(self):\n super().__init__(\"debug\", DebugLinearMotionDevice.classIdProduct, DebugLinearMotionDevice.classIdVendor )\n (self.x, self.y, self.z) = (0, 0, 0)\n self.nativeStepsPerMicrons = 16\n\n def doGetPosition(self) -> (float, float, float):\n return (self.x, self.y, self.z)\n\n def doMoveTo(self, position):\n x, y, z = position\n (self.x, self.y, self.z) = (x, y, z)\n\n def doMoveBy(self, displacement):\n dx, dy, dz = displacement\n self.x += dx\n self.y += dy \n self.z += dz\n\n def doHome(self):\n (self.x, self.y, self.z) = (0, 0, 0)\n\n def doInitializeDevice(self):\n pass\n\n def doShutdownDevice(self):\n pass","sub_path":"hardwarelibrary/motion/linearmotiondevice.py","file_name":"linearmotiondevice.py","file_ext":"py","file_size_in_byte":5044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"23786942","text":"from logapp import views\nfrom django.conf.urls import url\n\nurlpatterns = [\n\turl(r'^$', views.index), # 日志页面\n\turl(r'^file/down/$', views.Log_file_down), # 日志下载\n\turl(r'^system/', views.get_system_log), # 系统日志\n\turl(r'^system/file/down/$', views.system_log_file_down), # 系统日志下载\n\n\n\turl(r'^error/denied/$', views.page_permission_denied), # 403错误信息\n\turl(r'^error/$', views.log_error), # 404错误信息\n\turl(r'^error/page/inter/$', views.page_inter_error), # 500错误信息\n]\n","sub_path":"www/logapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516346221","text":"import csv\nimport numpy\nfrom numpy import *\n#read TicTacToe.csv\n\ndef readcsv (TicTacToe) :\n csv_file = csv.reader(open(TicTacToe,'r'))\n #rewirte data,and append them into one list\n list = []#original list\n Category = []# original list's category\n numPos,numNeg = 0,0\n for turn in csv_file:\n for index, element in enumerate(turn):\n if element == 'x':\n turn[index] = 2\n elif element == 'o':\n turn[index] = 1\n elif element == 'b':\n turn[index] = 0\n elif element == 'positive':\n numPos = numPos + 1\n Category.append(1)\n del turn[index]\n elif element == 'negative':\n numNeg = numNeg + 1\n Category.append(0)\n del turn[index]\n else:\n break\n list.append(turn)\n del list[len(list)-1] #remove the last line\n del list[0] #remove the first line (Gamen)\n xlist, olist = [],[]\n for turn in list:\n turn = [0 if x == 1 else x for x in turn]\n turn = [1 if x == 2 else x for x in turn]\n xlist.append(turn)\n for turn in list:\n turn = [0 if x == 2 else x for x in turn]\n olist.append(turn)\n #print(list,Category,xlist,olist)\n return (list,Category,xlist,olist,numPos,numNeg)\n\ndef Train(trainset, traincategory, xtrain, otrain ,numPos,numNeg):\n numtrainset = len(trainset)\n numfeature = len(trainset[0])\n ppos = numPos/float(numtrainset)#ppos = probability of positive in Trainlist\n pneg = numNeg/float(numtrainset) #pneg = probability of negative in Trainlist\n pxpnum = ones(numfeature); pxnnum = ones(numfeature) # pxpnum = probability of positive depends on x position\n popnum = ones(numfeature); ponnum = ones(numfeature)# popnum = probability of positive depends on o position\n for i in range(numtrainset):\n if traincategory[i] == 1:\n pxpnum += xtrain[i]\n popnum += otrain[i]\n else:\n pxnnum += xtrain[i]\n ponnum += otrain[i]\n pxpVect = log(pxpnum/(numPos+2))\n pxnVect = log(pxnnum/(numNeg+2))\n popVect = log(popnum/(numPos+2))\n ponVect = log(ponnum/(numNeg+2))\n return pxpVect,pxnVect,popVect,ponVect,ppos,pneg\n\ndef classifyTicTacToe (pxpVect,pxnVect,popVect,ponVect,xvalidatedata,ovalidatedata,ppos,pneg):\n result = [] #postive is 1, negative is 0\n for i in range(len(xvalidatedata)):\n pp = sum( multiply(pxpVect,xvalidatedata[i]))+sum( multiply(popVect,ovalidatedata[i]))+log(ppos) #the validatedata's the probability of positive\n pn = sum( multiply(pxnVect,xvalidatedata[i]))+sum( multiply(ponVect,ovalidatedata[i]))+log(pneg) #the validatedata's the probability of negative\n #print(pp,pn)\n if pp > pn:\n result.append(1)\n else:\n result.append(0)\n return (result)\n\ndef validating():\n list, Category, xlist, olist, numPos,numNeg = readcsv('TicTacToetrain.csv')\n pxpV, pxnV, popV, ponV, ppos, pneg = Train(list, Category, xlist, olist, numPos,numNeg )\n vlist, vCategory, xvlist,ovlist , vnumPos, vnumNeg = readcsv('TicTacToevalidate.csv')\n vresult = classifyTicTacToe(pxpV, pxnV, popV, ponV,xvlist,ovlist, ppos, pneg)\n del vCategory[0]\n TwoVect =ones(len(vCategory))*2 # array\n vresult = numpy.array(vresult) # list transfers to array\n vCategory = numpy.array(vCategory)\n a = vresult - TwoVect\n a = a.astype(int)\n b = vCategory - TwoVect\n b = b.astype(int)\n vvresult =~ a\n vvCategory = ~ b\n PP = sum(vCategory & vresult)\n NN = sum(vvCategory & vvresult)\n PN = sum( vCategory & vvresult)\n NP = sum( vvCategory & vresult)\n print (PP, PN, NP, NN)\n\nvalidating()","sub_path":"naive Bayes.py","file_name":"naive Bayes.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"184175101","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\n\nif __name__ == \"__main__\":\n imgSrc = cv2.imread(\"book2.jpg\")\n ptsSrc = np.array([[141, 131], [480, 159], [493, 630], [64, 601]])\n\n imgSubSrc = imgSrc.copy()\n for center in ptsSrc:\n cv2.circle(imgSubSrc, (center[0], center[1]), 1, (0, 255, 0), thickness=2, lineType=cv2.LINE_AA)\n\n imgDst = cv2.imread(\"book1.jpg\")\n ptsDst = np.array([[318, 256], [534, 372], [316, 670], [73, 473]])\n\n imgSubDst = imgDst.copy()\n for center in ptsDst:\n cv2.circle(imgSubDst, (center[0], center[1]), 1, (0, 255, 0), thickness=2, lineType=cv2.LINE_AA)\n\n h, status = cv2.findHomography(ptsSrc, ptsDst)\n\n print ('findHomography status: {}# \\n {} \\n'.format(status, h))\n\n imgResult = cv2.warpPerspective(imgSrc, h, (imgDst.shape[1], imgDst.shape[0]))\n\n while True:\n cv2.imshow(\"Src\", imgSubSrc)\n cv2.imshow(\"Dst\", imgSubDst)\n cv2.imshow(\"result\", imgResult)\n\n if cv2.waitKey(1) & 0xFF == 27:\n break\n\n cv2.destroyAllWindows()\n","sub_path":"opencv_learn/warpPerspective.py","file_name":"warpPerspective.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516960248","text":"import os\nfrom os.path import join\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.model_selection import train_test_split, cross_val_score, cross_validate\n\nimport pandas as pd\n\nglobal files\n\nfeatures_directory = '../data/features/'\n\n\ndef get_data():\n global files\n # Retrieve all folders from features directory. Each user's data is in a separate folder.\n folders = [f for f in os.listdir(features_directory) if os.path.isdir(os.path.join(features_directory, f))]\n data = None\n classifications = []\n\n for folder in folders:\n # Retrieve\n key_data = pd.read_csv(os.path.join(features_directory, folder, 'key.csv'))\n mouse_data = pd.read_csv(os.path.join(features_directory, folder, 'mouse.csv'))\n # Combine key and mouse features from same user into one row\n merged_data = pd.concat([key_data, mouse_data], axis=1)\n # Determine classification of user from folder name and add to classifications\n classification = 'human' if 'human' in folder else 'bot'\n classifications.append(classification)\n # Merge feature row with existing data\n data = merged_data if data is None else pd.concat([data, merged_data], ignore_index=True)\n\n return data, classifications\n\n\ndef main():\n X, y = get_data()\n\n rfc = RandomForestClassifier()\n cv = cross_validate(rfc, X, y, cv=2)\n\n print(cv['test_score'])\n print(cv['test_score'].mean())\n\n print('done')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"anomaly_detection/bot_detection.py","file_name":"bot_detection.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"134309724","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 8 21:57:59 2019\n\n@author: rudygualandro\n\"\"\"\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom yellowbrick.classifier import ConfusionMatrix\n\n\ncredito = pd.read_csv('Credito.csv', sep = ';', encoding = 'cp860')\n\n#deve ser feita uma variavel para todas variaveis explicativas e uma para a var\n# resposta, no caso para saber se o cliente é bom ou mau pagador\n\nprevisores = credito.iloc[:,0:15].values #tentar abrir o dataframe no spyder\n# da erro , entao deve ser didigtado o indice diretamente no console: \n# ex: previsores[0] e classe\n\nclasse = credito.iloc[:,19].values #pega a coluna 20. na var previsores, como o\n#intervalo vai de 0:20, vai ate a coluna 19\n\n#no dataframe existem atributos em string. O algoritmo GaussianNB nao trabalha com\n# string, entao deve ser feita conversao. Os atributos categoricos devem ser subs-\n#tituidos por valor numérico, em cada coluna:\nlabelencoder = LabelEncoder()\nprevisores[:,0] = labelencoder.fit_transform(previsores[:,0])\nprevisores[:,2] = labelencoder.fit_transform(previsores[:,2])\nprevisores[:,3] = labelencoder.fit_transform(previsores[:,3])\nprevisores[:,5] = labelencoder.fit_transform(previsores[:,5])\nprevisores[:,6] = labelencoder.fit_transform(previsores[:,6])\nprevisores[:,8] = labelencoder.fit_transform(previsores[:,8])\nprevisores[:,9] = labelencoder.fit_transform(previsores[:,9])\nprevisores[:,11] = labelencoder.fit_transform(previsores[:,11])\nprevisores[:,13] = labelencoder.fit_transform(previsores[:,13])\nprevisores[:,14] = labelencoder.fit_transform(previsores[:,14])\n\n\n\n\n#treinamento\n\n#deve ser feita a divisão da base de dados. O test_size diz a quantidade de dados\n#que sera usada no teste, no caso 30%, enquanto os 70% restantes serão treinados\n# o random_state=0 é pra dividir os dados sempre da mesma maneira\nX_treinamento, X_teste, y_treinamento, y_teste = train_test_split(previsores,\n classe,\n test_size = 0.3,\n random_state = 0)\n#aplicacao do treinamento. Gera a tabela de probabilidade\nnaive_bayes = GaussianNB()\nnaive_bayes.fit(X_treinamento, y_treinamento)\n\n#previsoes. Submete cada registro do X_teste ao modelo treinado e da resposta\n#good ou bad de acordo com a tabela de probabilidade gerada no treinamento\nprevisoes = naive_bayes.predict(X_teste)\n\n#contabilizicao dos erros e acertos comparando o dado real com o dado previsto\nconfusao = confusion_matrix(y_teste, previsoes)\ntaxa_acerto = accuracy_score(y_teste, previsoes)\n\n#visualizacao da tabela de acerto \nv = ConfusionMatrix(GaussianNB())\nv.fit(X_treinamento, y_treinamento)\nv.score(X_teste, y_teste)\nv.poof()\n\n\n","sub_path":"Projeto/Projeto.py","file_name":"Projeto.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"43600349","text":"# coding: utf-8\r\n\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nfrom mxnet import autograd, nd\r\nfrom mxnet.gluon import data as gdata\r\nfrom scratch.util import SGD, attach_gradient\r\nfrom scratch.activation import relu\r\n\r\n\r\nmnist_train = gdata.vision.FashionMNIST(train=True)\r\nmnist_test = gdata.vision.FashionMNIST(train=False)\r\n\r\n\r\ndef trans(x):\r\n return x.astype('float32')/255\r\n\r\n\r\ndef data_iter(data_label, batch_size):\r\n indices = list(range(len(data_label)))\r\n random.shuffle(indices)\r\n\r\n for i in range(0, data_label._data.shape[0], batch_size):\r\n x_indices = nd.array(indices[i: min(i + batch_size, data_label._data.shape[0])])\r\n\r\n # take function just allow input NDarray type.\r\n yield data_label._data.take(x_indices), nd.array(data_label._label).take(x_indices)\r\n\r\n\r\ndef cross_entropy(p_predicts, p_trues):\r\n if p_trues.shape[0] != p_predicts.shape[0]:\r\n raise Exception(\"The shape of p_trues dont equal p_predicts'.\")\r\n\r\n # loss must return a ndarray type data\r\n return nd.pick(-p_predicts.log(), p_trues) # pick dont equals take!\r\n\r\n\r\nbatch_size = 256\r\nnum_inputs = 784\r\nnum_outputs = 10\r\nlearning_rate = 0.2\r\nnum_hiddens_f = 128\r\nnum_hiddens_s = 128\r\nnum_epoch = 40\r\nweight_decay = 0.02 # L2 regularization\r\ndrop_prob = 0.1\r\n\r\nf_weights = nd.normal(0, scale=0.01, shape=(num_inputs, num_hiddens_f))\r\nf_biases = nd.zeros(num_hiddens_f)\r\ns_weights = nd.normal(0, 0.01, shape=(num_hiddens_f, num_hiddens_s))\r\ns_biases = nd.zeros(num_hiddens_s)\r\nt_weights = nd.normal(0, 0.01, shape=(num_hiddens_s, num_outputs))\r\nt_biases = nd.zeros(num_outputs)\r\n\r\nparms_all = [f_weights, f_biases, s_weights, s_biases]\r\nattach_gradient(parms_all)\r\n\r\n\r\ndef net(X):\r\n y_f = relu(nd.dot(X, f_weights) + f_biases)\r\n if autograd.is_training():\r\n y_f = dropout(y_f, drop_prob)\r\n y_s = relu(nd.dot(y_f, s_weights) + s_biases)\r\n if autograd.is_training():\r\n y_s = dropout(y_s, drop_prob)\r\n y_o = relu(nd.dot(y_s, t_weights) + t_biases)\r\n\r\n return softmax(y_o)\r\n\r\n\r\ndef softmax(X):\r\n exp = X.exp()\r\n partition = nd.sum(exp, axis=1, keepdims=True) # keep dims will keep the axis exist\r\n\r\n return exp/partition\r\n\r\n\r\ndef dropout(X, prob):\r\n drop_shape = X.shape[-1]\r\n drop_mat = nd.random.uniform(0, 1, drop_shape) > prob\r\n\r\n return X * drop_mat/(1-prob)\r\n\r\n\r\n# Data pro script, error data is useless\r\ndef fea_pro(features):\r\n\r\n return trans(nd.squeeze(features)).reshape(-1, num_inputs)\r\n\r\n\r\ndef accuracy(y_hat, y):\r\n\r\n return (y_hat.argmax(axis=1) == y.astype('float32')).mean().asscalar()\r\n\r\n\r\ndef evaluate_accuracy(data_iter, net):\r\n acc = 0\r\n count = 0\r\n for X, y in data_iter:\r\n count += 1\r\n acc += accuracy(net(fea_pro(X)), y)\r\n\r\n return acc / count\r\n\r\n\r\ndef train():\r\n for idx in range(num_epoch):\r\n train_l_sum = 0\r\n train_acc_sum = 0\r\n count = 0\r\n\r\n for ori_feature, label in data_iter(mnist_train, batch_size):\r\n\r\n with autograd.record():\r\n fea = fea_pro(ori_feature)\r\n y_ = net(fea)\r\n l = cross_entropy(y_, label)\r\n\r\n l.backward()\r\n # SGD(parms_all, learning_rate, batch_size)\r\n SGD(parms_all, learning_rate, batch_size, weight_decay)\r\n train_l_sum += l.mean().asscalar()\r\n train_acc_sum += accuracy(y_, label)\r\n count += 1\r\n\r\n test_acc = evaluate_accuracy(data_iter(mnist_test, batch_size), net)\r\n print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'\r\n % (idx, train_l_sum / count,\r\n train_acc_sum / count, test_acc))\r\n\r\n\r\n# --------------------------------------------------------------------------------------------------\r\n# Test sample\r\ndef get_text_labels(labels):\r\n text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',\r\n 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']\r\n return [text_labels[int(i)] for i in labels]\r\n\r\n\r\ndef test():\r\n data_, label = mnist_test[0:15]\r\n print('labels:', get_text_labels(label))\r\n predicted_labels = [net(trans(x).reshape(1, -1)).argmax(axis=1).asscalar()\r\n for x in data_]\r\n print('predictions:', get_text_labels(predicted_labels))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n train()\r\n test()\r\n","sub_path":"scratch/multiple_layer_perceptron.py","file_name":"multiple_layer_perceptron.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"331711480","text":"class Solution:\r\n def twoSum(self, nums: List[int], target: int) -> List[int]:\r\n manan = dict()\r\n i=0\r\n\r\n for num in nums:\r\n if num in manan:\r\n return [manan[num],i]\r\n else:\r\n manan[target-num]=i\r\n i=i+1\r\n\r\n# time and space complexity: O(n)\r\n","sub_path":"1. Two Sum.py","file_name":"1. Two Sum.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"241102576","text":"import cv2\n\n\nclass BoundingBox:\n debug = False\n allWhitePixels, allBlackPixels = 0, 0\n height = 0\n width = 0\n\n def __init__(self, image):\n self.image = image\n\n def cropImage(self):\n # Define height and width from the constructor's image input.\n binaryImageHeight = self.image.shape[0]\n binaryImageWidth = self.image.shape[1]\n\n wMaxY, wMaxX = 0, 0\n wMinY, wMinX = binaryImageHeight, binaryImageWidth\n\n # Loop through the image with y, x as the unpacked values.\n for y in range(0, binaryImageHeight):\n for x in range(0, binaryImageWidth):\n # Every time the image iterates over a white pixel.\n if self.image[y, x] == 255:\n # Count the amount of white pixels.\n self.allWhitePixels += 1\n # Define maximum and minimum values\n if wMinX > x:\n wMinX = x\n if wMaxX < x:\n wMaxX = x\n if wMinY > y:\n wMinY = y\n if wMaxY < y:\n wMaxY = y\n\n self.height = (wMaxY - wMinY) + 1\n self.width = (wMaxX - wMinX) + 1\n\n crop_img = self.image[wMinY:wMinY + self.height, wMinX:wMinX + self.width]\n\n if self.debug:\n cv2.rectangle(self.image, (wMaxX, wMaxY), (wMinX, wMinY), color=150, thickness=1)\n cv2.imshow(\"img rect\", self.image)\n cv2.waitKey(0)\n cv2.imshow(\"img\", crop_img)\n cv2.waitKey(0)\n\n return crop_img\n\n def cPointsPrintResult(self):\n print(\"+---------------- PRINT DETAILS ----------------+\")\n print(\"| MAX X:\", self.wMaxX, \"MAX Y:\", self.wMaxY)\n print(\"| MIN X:\", self.wMinX, \"MIN Y:\", self.wMinY)\n print(\"|------------------------------------------------\")\n\n def startGeometryCalculations(self):\n self.cropImage()\n if self.debug:\n self.cPointsPrintResult()\n","sub_path":"HandTracking/BoundingBox.py","file_name":"BoundingBox.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"360560210","text":"import pdb\nimport pprint\nimport json\n#import TileStache\nimport psycopg2, psycopg2.extras\nfrom geojson import Feature, LineString, FeatureCollection\nfrom flask import Flask\nfrom flask import request\nfrom flask import url_for\nfrom flask import jsonify\nfrom flask import Response\nfrom flask import render_template\nfrom flask.ext.compress import Compress\n#from tileconf import get_tile_config\n\napp = Flask(__name__, static_url_path='/static')\nCompress(app)\napp.debug = True\n\npsycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)\n\n\n@app.route(\"/\")\ndef index():\n\treturn render_template('index.html')\n\n\n@app.route(\"/api/v1/geometry\")\ndef geojson():\n\tconn = psycopg2.connect(\"host='postgis' dbname='bag' user='kademo' password='kademo'\")\n\tcursor = conn.cursor()\n\n\tbbox = request.args.get('bbox')\n\t# sql = (\"SELECT \"\n\t# \"ST_AsGeoJSON(ST_Collect(ST_Force_2d(geom))) AS geometry \"\n\t# \"FROM \"\n\t# \"bagactueel.pand \"\n\t# \"WHERE \"\n\t# \"geom && ST_SetSRID('BOX3D(\"+bbox+\")' :: box3d, 4326) \"\n\t# \"LIMIT 2000\")\n\n\tsql = (\"SELECT row_to_json(fc) \"\n\t\"FROM (SELECT 'FeatureCollection' AS type, array_to_json(array_agg(f)) AS features \"\n\t\"FROM (SELECT 'Feature' AS type,\"\n\t\" ST_AsGeoJSON(lg.geom)::json AS geometry, \"\n\t\" row_to_json((SELECT l FROM (\"\n\t\"\t\tSELECT CASE WHEN bouwjaar < 1945 THEN 'G' \"\n\t\"\t\t\t\t\tWHEN bouwjaar < 1960 THEN 'F' \"\n\t\"\t\t\t\t\tWHEN bouwjaar < 1975 THEN 'E' \"\n\t\"\t\t\t\t\tWHEN bouwjaar < 1985 THEN 'D' \"\n\t\"\t\t\t\t\tWHEN bouwjaar < 1995 THEN 'C' \"\n\t\"\t\t\t\t\tWHEN bouwjaar < 2005 THEN 'B' \"\n\t\"\t\t\t\t\tWHEN bouwjaar >= 2005 THEN 'A' \"\n\t\"\t\t\t\t\tEND AS label) AS l\"\n\t\")) AS properties \"\n\t\"FROM bagactueel.pand AS lg \"\n\t\"WHERE \"\n\t\" geom && ST_SetSRID('BOX3D(\"+bbox+\")' :: box3d, 4326) \"\n\t\") AS f) AS fc;\")\n\n\tcursor.execute(sql)\n\trecords = cursor.fetchall()\n\n\t# print('Bounding box: %(bbox)s' % {'bbox': bbox})\n\t# print('SQL statement: %(sql)s' % {'sql': sql})\n\t# print('records', records[0])\n\t# pdb.set_trace()\n\tconn.close()\n\treturn Response(response=json.dumps(records[0][0]), status=200, mimetype='application/json')\n\n\n#@app.route(\"/tiles////.\")\n#def tiles(layer_name=None, z=None, x=None, y=None, extension=None):\n#\tpath_info = \"%s/%s/%s/%s.%s\" % (layer_name, z, x, y, extension)\n#\tcoord, extension = TileStache.splitPathInfo(path_info)[1:]\n#\n#\tconfig = get_tile_config()\n#\tlayer = config.layers[layer_name]\n#\n#\tmimetype, data = TileStache.getTile(layer, coord, extension, ignore_cached=True)\n#\n#\treturn Response(response=data, status=200, mimetype=mimetype)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262387912","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom NewTon import newton_method\nfrom DampedNewton import DampedNewton\n\nclass DataProcesser(object):\n '''initlize paramenter\n filename:LogiReg_data.txt\n '''\n def __init__(self):\n self.base_dir = '../../../Data/'\n '''\n get x and y\n '''\n def get_param_target(self):\n np.random.seed(12)\n num_observations = 5000\n x1 = np.random.multivariate_normal([0, 0], [[1, .75], [.75, 1]], num_observations)\n x2 = np.random.multivariate_normal([1, 4], [[1, .75], [.75, 1]], num_observations)\n simulated_separableish_features = np.vstack((x1, x2)).astype(np.float32)\n simulated_labels = np.hstack((np.zeros(num_observations),\n np.ones(num_observations)))\n return (simulated_separableish_features[:, 0], simulated_separableish_features[:, 1], simulated_labels)\n\n def get_dataset_from_file(self, filename):\n self.filename = filename\n dataframe = pd.read_csv(self.base_dir + self.filename, encoding='UTF-8', names = ['x1', 'x2', 'target'], sep='\t')\n dataframe.insert(0, 'x0', len(dataframe)*[1])\n features = np.matrix(dataframe.iloc[:, 0:2])\n target = np.matrix(dataframe.iloc[:, 2])\n return features, target\n\n def showDatasetDistribution(self, features, target, w, flag):\n plt.title('Distribution of the data')\n plt.scatter(np.array(features[:, 1]), np.array(target[:, 0]), alpha=0.5)\n plt.xlabel('y')\n plt.ylabel('x')\n if flag == True:\n x = np.arange(0, 1, 0.1)\n x = np.mat(x).T\n print(x.shape)\n plt.plot(x, w[0] + np.mat(x)*w[1], c = 'red')\n pass\n plt.show()\n\n def show(self, x1, x2, y, w):\n plt.scatter(x1, x2, c = y)\n x = np.array(range(-3, 4))\n plt.plot(x, (-w[2] - w[0]*x)/w[1])\n plt.show()\n pass\n\n\nif __name__ == '__main__':\n Processer = DataProcesser()\n # x1, x2, y = Processer.get_param_target()\n # w = newton_method(x1, x2, y)\n # Processer.show(x1, x2, y, w)\n\n features, target = Processer.get_dataset_from_file('data.txt')\n newTon = DampedNewton(features, target.T, 100, 0.1, 0.5)\n Processer.showDatasetDistribution(features, target.T, None, False)\n w = newTon.newton()\n print('weight: ', w)\n Processer.showDatasetDistribution(features, target.T, w, True)\n\n","sub_path":"MachineLearning/Linear Model/LogosticRegression/LinearRegaression/DataProcesser.py","file_name":"DataProcesser.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"123800681","text":"import arrow\n\nfrom api.extensions import db\nfrom api.libs.constants import LOWEST_LEVEL\nfrom api.models.base import BaseModel\nfrom sqlalchemy.dialects.postgresql import REAL\n\nfrom db_utils import get_df, REDSHIFT_DB_URL\n\n\nclass Cost(BaseModel):\n __tablename__ = 'cost'\n\n cmid = db.Column(db.Integer)\n source_id = db.Column(db.String(16))\n foreign_store_id = db.Column(db.String(255))\n foreign_item_id = db.Column(db.String(255))\n date = db.Column(db.DateTime)\n cost_type = db.Column(db.String(255))\n total_quantity = db.Column(REAL, nullable=False)\n total_sale = db.Column(REAL, nullable=False)\n total_cost = db.Column(REAL, nullable=False)\n foreign_category_lv1 = db.Column(db.String(20), nullable=False)\n foreign_category_lv2 = db.Column(db.String(20), nullable=False)\n foreign_category_lv3 = db.Column(db.String(20), nullable=False)\n foreign_category_lv4 = db.Column(db.String(20), nullable=False)\n foreign_category_lv5 = db.Column(db.String(20), nullable=False)\n\n @classmethod\n def get_category_cost_by_query(cls, **kwargs):\n cmid = kwargs.get('cmid', 34)\n start_at = kwargs.get('start_at', arrow.now().shift(months=-2).ceil('month').date())\n end_at = kwargs.get('end_at', arrow.now().shift(months=-1).ceil('month').date())\n sql = '''\n select \n c.{}, \n sum(c.total_quantity) as total_quantity,\n sum(c.total_sale) as total_sale,\n sum(c.total_cost) as total_cost,\n sum(c.total_sale - c.total_cost) as total_profit\n from cost_{}yyyyyyyyyyyyy c \n left join \n chain_goods cg \n on \n cg.foreign_item_id = c.foreign_item_id \n where \n c.date > '{}' \n and c.date < '{}' \n and cg.cmid = {} \n group by c.{};'''.format(LOWEST_LEVEL.get(cmid), cmid, start_at, end_at, cmid, LOWEST_LEVEL.get(cmid))\n\n res = get_df(REDSHIFT_DB_URL, sql)\n return res\n\n @classmethod\n def get_item_cost_by_query(cls, **kwargs):\n cmid = kwargs.get('cmid', 34)\n barcodes = kwargs.get('barcodes', [])\n is_barcode = kwargs.get('is_barcode', None)\n start_at = kwargs.get('start_at', arrow.now().shift(months=-2).ceil('month').date())\n end_at = kwargs.get('end_at', arrow.now().shift(months=-1).ceil('month').date())\n condition = 'and cg.barcode in ({})'.format(\"'{}'\".format(\"','\".join(barcodes))) if is_barcode else ''\n sql = '''\n select \n c.foreign_item_id,\n sum(c.total_quantity) as quantity,\n sum(c.total_sale) as sale,\n sum(c.total_cost) as cost,\n sum(c.total_sale - c.total_cost) as profit\n from \n cost_{}yyyyyyyyyyyyy c \n left join chain_goods cg \n on \n c.foreign_item_id = cg.foreign_item_id\n where \n c.date > '{}' \n and c.date < '{}' \n and cg.cmid = {}\n {} \n group by c.foreign_item_id;'''.\\\n format(cmid, start_at, end_at, cmid, condition)\n\n res = get_df(REDSHIFT_DB_URL, sql)\n return res\n\n @classmethod\n def get_sale_store_count_by_query(cls, **kwargs):\n cmid = kwargs.get('cmid', 34)\n start_at = kwargs.get('start_at', arrow.now().shift(months=-2).ceil('month').date())\n end_at = kwargs.get('end_at', arrow.now().shift(months=-1).ceil('month').date())\n sql = '''\n select \n foreign_item_id, \n count(distinct foreign_store_id) as has_sell_count\n from cost_{}yyyyyyyyyyyyy \n where \n date > '{}' \n and date < '{}'\n group by foreign_item_id;'''.format(cmid, start_at, end_at)\n\n res = get_df(REDSHIFT_DB_URL, sql)\n return res\n\n","sub_path":"api/models/cost.py","file_name":"cost.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"545508781","text":"# Copyright 2019 QuantRocket LLC - 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\nimport pandas as pd\nimport numpy as np\n\ndef get_zscores(returns):\n \"\"\"\n Returns the Z-scores of the input returns.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n Series or DataFrame of returns\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n # Ignore 0 returns in calculating z score\n nonzero_returns = returns.where(returns != 0)\n z_scores = (nonzero_returns - nonzero_returns.mean())/nonzero_returns.std()\n return z_scores\n\ndef trim_outliers(returns, z_score):\n \"\"\"\n Zeroes out observations that are too many standard deviations from the\n mean.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n Series or DataFrame of returns\n\n z_score : int or float, required\n maximum standard deviation values are allowed to be from the mean\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n z_scores = get_zscores(returns)\n return returns.where(z_scores.abs() <= z_score, 0)\n\ndef with_baseline(data, value=1):\n \"\"\"\n Prepends a date-indexed Series or DataFrame with an initial row that is\n one period earlier than the first row and has the specified value.\n\n The typical use case is for generating plots: without a baseline row, a cumulative\n returns plot won't start from 1 if the first day's return is nonzero.\n\n Parameters\n ----------\n data : Series or DataFrame, required\n Series or DataFrame (for example, of returns)\n\n value : required\n value to insert in the baseline row\n\n Returns\n -------\n Series or DataFrame\n\n Examples\n --------\n Typical usage:\n\n >>> with_baseline(cum_returns).plot()\n\n Under the hood:\n\n >>> cum_returns.head()\n 2019-01-02 1.01\n 2019-01-03 0.995\n >>> with_baseline(cum_returns)\n 2019-01-01 1\n 2019-01-02 1.01\n 2019-01-03 0.995\n \"\"\"\n period_length = data.index[1] - data.index[0]\n prior_period = data.index[0] - period_length\n if isinstance(data, pd.DataFrame):\n baseline_row = pd.DataFrame(value, index=[prior_period], columns=data.columns)\n else:\n baseline_row = pd.Series(value, index=[prior_period], name=data.name)\n try:\n data_with_baseline = pd.concat((baseline_row, data), sort=False)\n except TypeError:\n # sort was introduced in pandas 0.23\n data_with_baseline = pd.concat((baseline_row, data))\n return data_with_baseline\n\ndef get_sharpe(returns, riskfree=0):\n \"\"\"\n Returns the Sharpe ratio of the returns.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n a Series or DataFrame of returns\n\n riskfree : float, optional\n the risk-free rate (default 0)\n\n Returns\n -------\n float or Series of floats\n \"\"\"\n mean = (returns - riskfree).mean()\n if isinstance(mean, float) and mean == 0:\n return 0\n std = (returns - riskfree).std()\n # Returns are assumed to represent daily returns, so annualize the Sharpe ratio\n return mean/std * np.sqrt(252)\n\ndef get_rolling_sharpe(returns, window, riskfree=0):\n \"\"\"\n Computes rolling Sharpe ratios for the returns.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n a Series or DataFrame of returns\n\n window : int, required\n rolling window length\n\n riskfree : float, optional\n the risk-free rate (default 0)\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n rolling_returns = returns.fillna(0).rolling(window, min_periods=window)\n try:\n return rolling_returns.apply(get_sharpe, raw=True, kwargs=dict(riskfree=riskfree))\n except TypeError as e:\n # handle pandas<0.23\n if \"apply() got an unexpected keyword argument 'raw'\" in repr(e):\n return rolling_returns.apply(get_sharpe, kwargs=dict(riskfree=riskfree))\n else:\n raise\n\ndef get_cum_returns(returns, compound=True):\n \"\"\"\n Computes the cumulative returns of the provided returns.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n a Series or DataFrame of returns\n\n compound : bool\n True for compounded (geometric) returns, False for arithmetic\n returns (default True)\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n if compound:\n cum_returns = (1 + returns).cumprod()\n else:\n cum_returns = returns.cumsum() + 1\n\n cum_returns.index.name = \"Date\"\n return cum_returns\n\ndef get_cagr(cum_returns, compound=True):\n \"\"\"\n Computes the CAGR from the cumulative returns.\n\n Parameters\n ----------\n cum_returns : Series or DataFrame, required\n a Series or DataFrame of cumulative returns\n\n compound : bool\n compute compound annual growth rate if True, otherwise\n compute average annual return (default True)\n\n Returns\n -------\n float or Series of floats\n \"\"\"\n # For DataFrames, apply this function to each Series.\n if isinstance(cum_returns, pd.DataFrame):\n return cum_returns.apply(get_cagr, axis=0)\n\n # Ignore nulls when compting CAGR\n cum_returns = cum_returns[cum_returns.notnull()]\n\n if cum_returns.empty:\n return 0\n\n # Compute the CAGR of the Series\n min_date = cum_returns.index.min()\n max_date = cum_returns.index.max()\n years = ((max_date - min_date).days or 1)/365.0\n ending_value = cum_returns.iloc[-1]\n # Since we are computing CAGR on cumulative returns, the beginning\n # value is always 1.\n beginning_value = 1\n if compound:\n cagr = (ending_value/beginning_value)**(1/years) - 1\n else:\n # Compound annual growth rate doesn't apply to arithmetic\n # returns, so just divide the cum_returns by the number of years\n # to get the annual return\n cagr = (ending_value/beginning_value - 1)/years\n\n return cagr\n\ndef get_drawdowns(cum_returns):\n \"\"\"\n Computes the drawdowns of the cumulative returns.\n\n Parameters\n ----------\n cum_returns : Series or DataFrame, required\n a Series or DataFrame of cumulative returns\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n cum_returns = cum_returns[cum_returns.notnull()]\n highwater_marks = cum_returns.expanding().max()\n drawdowns = cum_returns/highwater_marks - 1\n return drawdowns\n\ndef get_top_movers(returns, n=10):\n \"\"\"\n Returns the biggest gainers and losers in the returns.\n\n Parameters\n ----------\n returns : Series or DataFrame, required\n a Series or DataFrame of returns\n\n n : int, optional\n the number of biggest gainers and losers to return (default 10)\n\n Returns\n -------\n Series or DataFrame\n \"\"\"\n\n if isinstance(returns, pd.DataFrame):\n returns = returns.stack()\n\n returns = returns.sort_values()\n\n try:\n top_movers = pd.concat((returns.head(n), returns.tail(n)), sort=True)\n except TypeError:\n # sort was introduced in pandas 0.23\n top_movers = pd.concat((returns.head(n), returns.tail(n)))\n\n return top_movers\n","sub_path":"moonchart/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"628887777","text":"# This is the example from the H3D Manual(Examples section)\n\n#import the H3D fields and types\nfrom H3DInterface import *\nimport math\n\nclass EraseMe( TypedField( SFColor, (MFBool, MFVec3f) ) ): # PeriodicUpdate to make the update function run periodically regardless of whether you route an instance of this field anywhere. You could chose AutoUpdate if you want instead.\n def update( self, event ):\n group_node = getNamedNode(\"MYGROUP\")\n shape_node = getNamedNode(\"MYBOX\")\n routes_in = self.getRoutesIn()\n is_touched=routes_in[0].getValue()\n ret_force=routes_in[1].getValue()\n #is_touched = event.getValue()\n print(is_touched, ret_force)\n if True in is_touched:\n forcex=ret_force[0].x\n forcey=ret_force[0].y\n forcez=ret_force[0].z\n forcetot=math.sqrt(math.pow(forcex,2)+math.pow(forcey,2)+math.pow(forcez,2))\n #group_node.children.erase( shape_node )\n print(is_touched, ret_force, forcetot)\n if (forcetot>2.5):\n group_node.children.erase( shape_node )\n #return RGB( 1, 0, 0 )\n else: \n return RGB( 1, 1, 1 )\n else:\n return RGB( 0, 0, 1 )\n #return RGB( 1, 1, 0 ) # Need to return something, since this field at the moment is not routed anywhere just make sure the correct type is returned. The M at the beginning of the field class it inherits from means that a list needs to be returned. In this case I chose an empty list.\n\neraseme = EraseMe()\n","sub_path":"Hole_Creation/boxerase.py","file_name":"boxerase.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"559109969","text":"from FourierWindow import *\nfrom scipy.signal import *\n\nclass DataGeneratorWindow(FourierWindow):\n \n def __init__(self, root):\n self.title = 'Data Generator'\n \n self.builtInFunctions = {'Sinusoid' : 'cos(f[0]*2*pi*t)',\n 'Two Sinusoids' : 'cos(f[0]*2*pi*t) + cos(f[1]*2*pi*t)',\n 'Two Seq. Sinusoids' : 'where(t0, sqrt(sin(2*pi*f[0]*t)), 0.)',\n 'Sawtooth' : 'signal.sawtooth(f[0]*2*pi*t)'}\n \n N = 1024\n Fs = 1.\n Ts = 1/Fs\n self.maxFreqs=5\n t = linspace(0.,N*Ts,N)\n n = arange(N, dtype=float)\n freqs = (n / N * Fs) - (Fs / 2)\n self.params=[N,Fs,Ts,t,n,freqs]\n \n self.signalType = 0\n \n FourierWindow.__init__(self, root) \n \n \n ############################################################################ \n # Contains the different options for the signals, using checkboxes\n #\n ############################################################################ \n def makeLeftPane(self):\n leftPane = Frame(self.master, bg='grey')\n # create a variable to hold function currently being analyzed\n \n Button(leftPane, text='Save Tables and Plots', command=self.saveScreenshot).pack(fill=X, pady=self.pads[1], padx=self.pads[0])\n \n funcText = StringVar()\n self.funcText = funcText\n funcText.set('Sinusoid')\n \n # variable to hold the user-input function\n self.customFunc = StringVar()\n self.customFunc.set('sin(f0*t*cos(f1*t))')\n # variable for number of decaying complex exponentials\n self.numDCE = IntVar()\n self.numDCE.set(2)\n # boolean variable for exponential decay\n decay = BooleanVar()\n self.decay = decay\n decay.set(False)\n # random noise\n noise = BooleanVar()\n self.noise = noise\n noise.set(False)\n # fft plot type\n fftPlot = BooleanVar()\n self.fftPlot = fftPlot\n fftPlot.set(False)\n \n Label(leftPane, text='Functions').pack(fill=X, pady=(self.pads[1],0), padx=self.pads[0])\n # create a frame to hold the function radiobuttons\n funcFrame = Frame(leftPane)\n funcFrame.pack(fill=BOTH, padx=self.pads[0], pady=(0,self.pads[1]))\n \n \n # create all the radiobuttons\n for i in range(len(self.builtInFunctions)):\n text = self.builtInFunctions.keys()[i]\n f = Frame(funcFrame)\n f.pack(side=TOP, fill=BOTH)\n Radiobutton(f, text=text, variable=funcText, value=text, command=self.updatePlots).pack(side=LEFT)\n # custom function\n f = Frame(funcFrame)\n f.pack(side=TOP, fill=BOTH)\n Radiobutton(f, text='', variable=funcText, value='DCE', command=self.updatePlots).pack(side=LEFT)\n Entry(f, textvariable=self.numDCE, width=2).pack(side=LEFT) \n Label(f, text='Decaying Complex Exponentials').pack(side=LEFT, fill=X)\n # custom function\n f = Frame(funcFrame)\n f.pack(side=TOP, fill=BOTH)\n Radiobutton(f, text='', variable=funcText, value='Custom', command=self.updatePlots).pack(side=LEFT)\n Entry(f, textvariable=self.customFunc).pack(side=LEFT)\n \n # create a frame to hold the exponential decay radiobuttons\n Label(leftPane, text='Exponential Decay').pack(fill=X, pady=(self.pads[1],0), padx=self.pads[0])\n expFrame = Frame(leftPane)\n expFrame.pack(fill=BOTH,pady=(0,self.pads[1]),padx=self.pads[0])\n # both radiobuttons\n Radiobutton(expFrame, text='Exponential Decay',variable=decay,value=True, \n command=self.updatePlots).grid(row=0,stick=W,padx=self.pads[0])\n Radiobutton(expFrame, text='No Exponential Decay',variable=decay,value=False, \n command=self.updatePlots).grid(row=1,stick=W,padx=self.pads[0])\n \n # create a frame to hold the exponential decay radiobuttons\n Label(leftPane, text='Random Noise').pack(fill=X, pady=(self.pads[1],0), padx=self.pads[0])\n noiseFrame = Frame(leftPane)\n noiseFrame.pack(fill=BOTH,pady=(0,self.pads[1]),padx=self.pads[0])\n # both radiobuttons\n Radiobutton(noiseFrame, text='Add Noise',variable=noise,value=True, \n command=self.updatePlots).grid(row=0,stick=W,padx=self.pads[0])\n Radiobutton(noiseFrame, text='No Noise',variable=noise,value=False, \n command=self.updatePlots).grid(row=1,stick=W,padx=self.pads[0])\n \n # create a frame to hold the exponential decay radiobuttons\n Label(leftPane, text='FFT Plot Type').pack(fill=X, pady=(self.pads[1],0), padx=self.pads[0])\n noiseFrame = Frame(leftPane)\n noiseFrame.pack(fill=BOTH,pady=(0,self.pads[1]),padx=self.pads[0])\n # both radiobuttons\n Radiobutton(noiseFrame, text='Stem Plot',variable=fftPlot,value=True, \n command=self.updatePlots).grid(row=0,stick=W,padx=self.pads[0])\n Radiobutton(noiseFrame, text='Normal Line Plot',variable=fftPlot,value=False, \n command=self.updatePlots).grid(row=1,stick=W,padx=self.pads[0])\n \n self.master.add(leftPane)\n \n b = Button(leftPane, text='Save Current Signal', command=self.file_save)\n b.pack(fill=BOTH, padx=self.pads[0], pady=self.pads[1])\n \n ############################################################################ \n # Contains the plots and frequency sliders at the bottom\n #\n ############################################################################ \n def makeRightPane(self):\n [N,Fs,Ts,t,n,freqs] = self.params\n \n freqNames = ['f%i'%i for i in range(self.maxFreqs)]\n freqLimits = [(Fs/100., Fs)]*self.maxFreqs\n freqRes = [Fs/100.]*self.maxFreqs\n freqDTypes = [DoubleVar]*self.maxFreqs\n freqDefaults = [1]*self.maxFreqs\n freqValues = [freqNames, freqLimits, freqRes, freqDTypes, freqDefaults]\n \n decayNames = ['T%i'%i for i in range(self.maxFreqs)]\n decayLimits = [(1, 1000)]*self.maxFreqs\n decayRes = [1]*self.maxFreqs\n decayDTypes = [IntVar]*self.maxFreqs\n decayDefaults = [100]*self.maxFreqs\n decayValues = [decayNames, decayLimits, decayRes, decayDTypes, decayDefaults]\n \n ampNames = ['A%i'%i for i in range(self.maxFreqs)]\n ampLimits = [(0, 100)]*self.maxFreqs\n ampRes = [1]*self.maxFreqs\n ampDTypes = [IntVar]*self.maxFreqs\n ampDefaults = [1]*self.maxFreqs\n ampValues = [ampNames, ampLimits, ampRes, ampDTypes, ampDefaults]\n \n phaseNames = ['p%i'%i for i in range(self.maxFreqs)]\n phaseLimits = [(0, 2*np.pi)]*self.maxFreqs\n phaseRes = [0.01]*self.maxFreqs\n phaseDTypes = [DoubleVar]*self.maxFreqs\n phaseDefaults = [0]*self.maxFreqs\n phaseValues = [phaseNames, phaseLimits, phaseRes, phaseDTypes, phaseDefaults]\n \n self._makeRightPane((3,1),[freqValues, decayValues, ampValues, phaseValues])\n \n self.freqs = self.vars[0]\n self.decays = self.vars[1]\n self.amps = self.vars[2]\n self.phases = self.vars[3]\n self.freqSliders = self.sliders[0]\n \n ############################################################################ \n # Initializes the signals in the plots\n #\n ############################################################################ \n def initSignals(self):\n self._initSignals()\n \n self.freqsUsed = range(self.maxFreqs)\n \n def parseSignal(self): \n function = self.funcText.get()\n if function in self.builtInFunctions.keys():\n y = self.builtInFunctions[function]\n elif function == 'Custom':\n func = self.customFunc.get()\n for i in range(10): func = func.replace('f%i'%i, 'f[%i]'%i)\n y = func\n else:\n n = self.numDCE.get()\n t = ''\n for i in range(n):\n t += 'A[%i]*exp(-t/T[%i])*exp(1j*(2*pi*f[%i]*t+p[%i]))+'%(i,i,i,i)\n y = t[:-1]\n self.function = y\n \n def hideShowFreqs(self, oldFreqs, newFreqs, sliders):\n for i in oldFreqs + newFreqs:\n if i in oldFreqs:\n for k in range(len(sliders)):\n sliders[k][i][0].grid_remove()\n sliders[k][i][1].grid_remove()\n if i in newFreqs:\n for k in range(len(sliders)):\n sliders[k][i][0].grid()\n sliders[k][i][1].grid()\n\n if self.funcText.get() != 'DCE':\n for i in range(1,len(sliders)):\n for s in sliders[i]:\n s[0].grid_remove()\n s[1].grid_remove()\n \n ############################################################################ \n # Updates the plots when anything is changed\n #\n ############################################################################ \n def updatePlots(self):\n [N,Fs,Ts,t,n,freqs] = self.params\n f = [self.freqs[i].get() for i in range(self.maxFreqs)]\n T = [self.decays[i].get() for i in range(self.maxFreqs)]\n A = [self.amps[i].get() for i in range(self.maxFreqs)]\n p = [self.phases[i].get() for i in range(self.maxFreqs)]\n \n oldFreqs = self.freqsUsed\n newFreqs = []\n self.parseSignal()\n \n for slider in self.freqSliders:\n from_ = -Fs if self.funcText.get() == 'DCE' else 0\n slider[1].config(from_=from_)\n\n for i in range(self.maxFreqs):\n if 'f[%i]'%i in self.function: newFreqs.append(i)\n self.hideShowFreqs(oldFreqs, newFreqs, self.sliders)\n self.freqsUsed = newFreqs\n \n y = eval(self.function)\n y = y.astype(np.complex_)\n if self.decay.get() and self.funcText.get() != 'DCE':\n y = y*exp(-0.03*t) \n y /= max(np.abs(y)) \n \n if self.noise.get(): y += np.random.normal(scale=max(y)/10,size=len(y))\n \n self.y = y\n S = abs(fft.fftshift(fft.fft(y)))\n \n self.lines[0].set_data(t,y)\n self.axes[1].cla()\n self.axes[1].grid()\n if self.fftPlot.get():\n self.axes[1].stem(freqs,S,basefmt='k:')\n else:\n self.axes[1].plot(freqs,S)\n \n mean = sum([amp*freq for (freq, amp) in zip(freqs, S)])/sum(S)\n midpoint = sum(S)/2.\n cur = 0\n for ind in range(len(freqs)):\n cur += S[ind]\n if cur >= midpoint:\n median = freqs[ind]\n break\n stddev = (sum([(freq-mean)**2*amp for (freq,amp) in zip(freqs, S)])/sum(S))**0.5\n \n loc = [min(freqs) + (max(freqs)-min(freqs))*0.85, min(S) + (max(S)-min(S))*0.7]\n self.axes[1].text(loc[0],loc[1],'Mean: %0.5f\\nMedian: %0.05f\\nStd. Dev: %0.05f'%(mean,median,stddev),bbox={'facecolor':'white','alpha':1,'pad':10})\n \n \n funcName = self.funcText.get()\n if funcName in self.builtInFunctions.keys(): name = funcName\n elif funcName == 'Custom': name = self.customFunc.get()\n else: name = ''\n \n self.axes[2].cla()\n self.axes[2].specgram(y, Fs=Fs)#, NFFT=80, noverlap=40)\n #self.axes[2].axis([0, (N-128)*Ts, min(freqs), max(freqs)])\n \n self.formatAxes(self.axes[0],t,y,'Time (ms)','Normalized Amplitude',name)\n self.formatAxes(self.axes[1],freqs,S,'Frequency (kHz)','Magnitude','FFT of '+name)\n self.formatAxes(self.axes[2],t,freqs,'Time (ms)','Frequency (kHz)','Spectrogram, Fs = 10 kHz',spec=True)\n \n \n [ax.axhline(color='k') for ax in self.axes]\n #for fig in self.figs:\n self.fig.canvas.draw_idle()\n self.fig.tight_layout()\n #[fig.canvas.draw_idle() for fig in self.figs]\n \n \nif __name__ == \"__main__\":\n root = Tk()\n DataGeneratorWindow(root)\n \n if os.name == \"nt\": root.wm_state('zoomed')\n else: root.attributes('-zoomed', True)\n\n root.mainloop()\n \n \n","sub_path":"DataGeneratorWindow.py","file_name":"DataGeneratorWindow.py","file_ext":"py","file_size_in_byte":12550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"59252068","text":"# An exampe of using a class data attribute as a counter\n# that keeps track of the number of created objects.\nclass X:\n counter = 0\n\n def __init__(self):\n X.counter += 1\n # We also save the number in the object itself, so that later we can see its sequential number\n self.my_number = X.counter\n \n def howmany(self):\n print(\"There are %i objects of this type, and I am number %i\" % (X.counter, self.my_number))\n\nx = X()\ny = X()\nz = X()\n\ny.howmany()\nz.howmany()","sub_path":"day2/13-instance-count.py","file_name":"13-instance-count.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"565366854","text":"import sqlite3\nimport json\n\nif __name__ == \"__main__\":\n conn = sqlite3.connect(\"teams.db\")\n c = conn.cursor()\n c.execute(\"SELECT id, name, members FROM teams\")\n a = c.fetchall()\n conn.close()\n conn = sqlite3.connect(\"scores.db\")\n c = conn.cursor()\n c.execute(\"DELETE FROM speed\")\n c.execute(\"DELETE FROM accuracy\")\n c.execute(\"DELETE FROM team\")\n c.execute(\"DELETE FROM guts\")\n for i in a:\n members = json.loads(i[2])\n for j in range(4):\n c.execute(\"INSERT INTO speed (team_id, indiv_id, team_name, indiv_name) VALUES (?, ?, ?, ?)\", (i[0], 10 * i[0] + j + 1, i[1], members[j]))\n c.execute(\"INSERT INTO accuracy (team_id, indiv_id, team_name, indiv_name) VALUES (?, ?, ?, ?)\", (i[0], 10 * i[0] + j + 1, i[1], members[j]))\n c.execute(\"INSERT INTO team (team_id, team_name) VALUES (?, ?)\", (i[0],i[1]))\n c.execute(\"INSERT INTO guts (team_id, team_name, progress, score, answers) VALUES (?, ?, 0, 0, ?)\", (i[0], i[1], '{\"24\": 0, \"20\": 0, \"21\": 0, \"22\": 0, \"23\": 0, \"1\": 0, \"3\": 0, \"2\": 0, \"5\": 0, \"4\": 0, \"7\": 0, \"6\": 0, \"9\": 0, \"8\": 0, \"11\": 0, \"10\": 0, \"13\": 0, \"12\": 0, \"15\": 0, \"14\": 0, \"17\": 0, \"16\": 0, \"19\": 0, \"18\": 0}'))\n conn.commit()\n conn.close()\n","sub_path":"wsgi-scripts/gendb.py","file_name":"gendb.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11780710","text":"# Import Library\r\nimport pandas as pd\r\nfrom utils.version_ia import *\r\nfrom utils.connect_db import *\r\n\r\n\r\nDIR_CONFIG_SERVICE = '/home/projetoia/service-linux/inferencia-service/config-service.json'\r\n\r\ndef read_config_service():\r\n with open(DIR_CONFIG_SERVICE, 'r') as read:\r\n read_json = json.load(read)\r\n return read_json\r\n\r\n\r\n\r\ndef load_data_train():\r\n \"\"\"Connect to DB and return data.\r\n\r\n Returns\r\n -------\r\n df : dataframe\r\n A dataframe according to database.\r\n \"\"\"\r\n # Database connection\r\n conn = connect_db()\r\n\r\n sql_string = \"\"\"select * from TBIA_FIC_REPO_TRAIN_COMITE\"\"\"\r\n\r\n # Load table to a DataFrame\r\n df = pd.DataFrame()\r\n try:\r\n df = pd.read_sql(sql_string, conn)\r\n except Exception as e:\r\n ds_msg_error = 'ERRO AO PROCESSAR O load_data_train'\r\n ds_error = msg_exception('Error: {}'.format(e))\r\n ds_method = 'load_data_train'\r\n insert_msg_error('', ds_msg_error, ds_error, ds_method)\r\n finally:\r\n conn.close()\r\n\r\n return df\r\n\r\n\r\ndef load_data_prod():\r\n \"\"\"Connect to DB and return data.\r\n\r\n Returns\r\n -------\r\n df : dataframe\r\n A dataframe according to database.\r\n \"\"\"\r\n # Database connection\r\n conn = connect_db()\r\n\r\n sql_string = (f\"\"\"SELECT * FROM TBIA_FIC_REPO_MODELO\r\n WHERE NR_FICHA IN (SELECT NR_FICHA FROM TBIA_FIC_CONTROLE WHERE ST_EXTRACAO = 1 AND ST_INFERENCIA = 0 AND ST_CLASSIFICACAO = 0)\r\n AND ROWNUM <= {read_config_service()['config']['quantidadeFichasProcessamento']}\"\"\")\r\n\r\n # Load table to a DataFrame\r\n df = pd.DataFrame()\r\n try:\r\n df = pd.read_sql(sql_string, conn)\r\n except Exception as e:\r\n ds_msg_error = 'ERRO AO PROCESSAR O load_data_prod'\r\n ds_error = msg_exception('Error: {}'.format(e))\r\n ds_method = 'load_data_prod'\r\n insert_msg_error('', ds_msg_error, ds_error, ds_method)\r\n finally:\r\n conn.close()\r\n\r\n return df\r\n\r\n\r\ndef insert_data_prod(X):\r\n \"\"\"Insert result into database.\r\n \"\"\"\r\n try:\r\n # Database connection\r\n conn = connect_db()\r\n versao = get_version()\r\n\r\n for i in X.index:\r\n nr_ficha = int(X.loc[i, 'NR_FICHA'])\r\n esp_ficha = int(X.loc[i, 'ESP_DA_FICHA'])\r\n esp_func = int(X.loc[i, 'ESP_DA_FUNC'])\r\n esp_div = int(X.loc[i, 'ESP_DIVERGENTE'])\r\n total_evento_ficha = int(X.loc[i, 'TOTALEVENTOSDAFICHA'])\r\n valor_total_evento_ficha = X.loc[i, 'VALORTOTALEVENTOSDAFICHA']\r\n qtde_ficha_dent = int(X.loc[i, 'QTDEVENTOSPORFICHADODENT'])\r\n valor_ficha_dent = X.loc[i, 'VALOREVENTOSPORFICHADODENT']\r\n qtde_ficha_esp = int(X.loc[i, 'QTDEVENTOSPORFICHADAESP'])\r\n valor_ficha_esp = X.loc[i, 'VALOREVENTOSPORFICHADAESP']\r\n qtde_eventos_rest = int(X.loc[i, 'QTDEVENTOSREST'])\r\n valor_eventos_rest = X.loc[i, 'VALOREVENTOSREST']\r\n qtde_3faces = int(X.loc[i, 'QTDEVENTOS3FACES'])\r\n valor_3faces = X.loc[i, 'VALOREVENTOS3FACES']\r\n qtde_1faces = int(X.loc[i, 'QTDEVENTOS1FACE'])\r\n valor_1faces = X.loc[i, 'VALOREVENTOS1FACES']\r\n qtde_rx = int(X.loc[i, 'QTDEVENTOSRXOBRG'])\r\n valor_rx = X.loc[i, 'VALOREVENTOSRXOBRG']\r\n valor_outlier = X.loc[i, 'VALOROUTLIERFICHA']\r\n complexidade_evento = X.loc[i, 'COMPLEXIDADEDOEVENTO']\r\n peso = int(X.loc[i, 'PESO'])\r\n qtde_ev_alto_risco = int(X.loc[i, 'QTDEVENTOALTRISCO'])\r\n id_classificacao = int(X.loc[i, 'ID_CLASSIFICACAO'])\r\n ficha_possui_imagem = int(X.loc[i, 'FICHAPOSSUIIMAGEM'])\r\n qtde_ven_dia = X.loc[i, 'QTDEVENPORDIAREALDODENTPBENE']\r\n media_eventos_rx_dent = X.loc[i, 'MDEVENTOSRXPORBENEDENT']\r\n media_eventos_rx_bene = X.loc[i, 'MDEVENTOSRXPORBENEESP']\r\n\r\n try:\r\n cur = conn.cursor()\r\n cur.callproc('SPIA_FIC_INSERT_CLAS_DETAL', [\r\n nr_ficha, esp_ficha, esp_func, esp_div, total_evento_ficha, valor_total_evento_ficha,\r\n qtde_eventos_rest, valor_eventos_rest, qtde_3faces, valor_3faces, qtde_1faces,\r\n valor_1faces, qtde_rx, valor_rx, valor_outlier, qtde_ev_alto_risco, ficha_possui_imagem,\r\n qtde_ficha_dent, valor_ficha_dent, qtde_ven_dia, media_eventos_rx_dent,\r\n media_eventos_rx_bene, qtde_ficha_esp, valor_ficha_esp, complexidade_evento,\r\n peso, id_classificacao, versao])\r\n conn.commit()\r\n except Exception as e:\r\n print('caiu no primeiro exception')\r\n ds_msg_error = 'ERRO AO INSERIR NO BANCO, NA PROC SPIA_FIC_INSERT_CLAS_DETAL'\r\n ds_error = msg_exception('Error: {}'.format(e))\r\n ds_method = 'insert_data_prod'\r\n insert_msg_error(nr_ficha, ds_msg_error, ds_error, ds_method)\r\n except Exception as e:\r\n print('caiu no segundo exception')\r\n ds_msg_error = 'ERRO AO INSEIR NO BANCO'\r\n ds_error = msg_exception('Error: {}'.format(e))\r\n ds_method = 'insert_data_prod'\r\n insert_msg_error(nr_ficha, ds_msg_error, ds_error, ds_method)\r\n finally:\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\ndef df_repeated(df):\r\n X_new = pd.DataFrame()\r\n\r\n s_baixo = df.loc[df['AUDITORIA'] == 'Baixo']\r\n s_baixo = pd.concat([s_baixo]*1, ignore_index=True)\r\n X_new = pd.concat([X_new, s_baixo])\r\n\r\n s_mode = df.loc[df['AUDITORIA'] == 'Moderado']\r\n s_mode = pd.concat([s_mode]*2, ignore_index=True)\r\n X_new = pd.concat([X_new, s_mode])\r\n\r\n s_alto = df.loc[df['AUDITORIA'] == 'Alto']\r\n s_alto = pd.concat([s_alto]*9, ignore_index=True)\r\n X_new = pd.concat([X_new, s_alto])\r\n\r\n return X_new\r\n","sub_path":"service-linux/inferencia-service/classificador_fichas/utils/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"491611320","text":"#------------------------------------------------------------------------------\n# Filename: herbie_pi.py\n# Author(s): David Taylor, Dhruv Singhal\n# ShortDesc: This is the code of the Raspberry Pi on our senior design robot\n#\n# Usage:\n# - Control mode toggled with the PlayStation main Button\n# - Auto: CV run on the NVIDIA Jetson Nano will steer the car\n# - Manual: DualShock4 controller to steer the car\n#\n# Changelog\n# Version Date Delta\n# v0.1 2019-12-01 List of libraries\n# v1.0 2019-12-05 Funtional driving code\n# v2.0 2020-02-15 Updated for VictorSPX speed controllers\n# v2.1 2020-02-26 Added basic control system\n#\n# Resources:\n# - resource | url\n#\n# Feature Requests: (based on priority)\n# - Run on boot on Raspberry Pi 4B\n# - Fix inability to re-change modes\n# - Optomize changeSpeed method\n# - Integrate NVIDIA Jetson Nano (with either ML or OpenCV image processing)\n# - Add a startup verification system (probably return a confirmation after all of the object constructors are run?) that gives LED feedback (progress bar for boot?).\n# - Add controller pairing failsafe\n# - Add different controlling modes (rn we only have tank mode)\n# - Replace pygame with homebrewed device file interpretation\n#------------------------------------------------------------------------------\n\n#----------\nimport RPi.GPIO as GPIO # The GPIO library for the Raspberry Pi\n\nfrom time import sleep\nimport smbus\nimport struct\n\n# Used for PlayStation DualShock4 interfacing\nimport pygame\n\n# LED control\n#import board # Adafruit library per https://circuitpython.readthedocs.io/projects/neopixel/en/latest/\n#import neopixel # library for controlling the LED ring\n\n#----------\n\n# GPIO PIN MAPPING\nLED_PIN = 18\n\nMOTOR_R = 32 # Used for the right side of the vehicle\nMOTOR_L = 33 # Used for the left side of the vehicle\n\n# CONSTANTS\nDRIVE_MODES = 2\n\n#----------\n\nclass DC_Motor_Controller:\n \"\"\"Object for controlling the DC motors with software PWM, utilizing the RPi.GPIO library\"\"\"\n\n # Default data members\n bus = smbus.SMBus(1)\n address = 0x04\n\n\n idleSpeed = 30.0 # Function of the speed controllers - PWM neutral has period of 1.5ms\n speedScaler = 10 # Max speed is 40%, min speed is 20% due to PWM config\n\n maxDeltaY = .50 # Greatest change between cycles for forward/reverse axis in percent\n maxDeltaX = 1.0 # Greatest change between cycles for left/right axis in percent\n\n rSpeed = 0 # State variable that will be adjusted towards setpoint defined by user input\n lSpeed = 0 # \"\n\n\n\n # Pass the GPIO numbers for motor connections A and B\n def __init__(self, pinR, pinL, mode):\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BOARD) # See RPi.GPIO docs for what this is\n\n GPIO.setup(int(pinR), GPIO.OUT) # Change output mode of pinR\n GPIO.setup(int(pinL), GPIO.OUT) # Change output mode of PinL\n\n self.R_PWM = GPIO.PWM(pinR, 210) # Original setpoint was 200Hz: dhruv's gut told us we needed 192Hz i guess\n self.L_PWM = GPIO.PWM(pinL, 210) # \"\n\n self.R_PWM.start(self.idleSpeed) # Activate PWM for pin R\n self.L_PWM.start(self.idleSpeed) # Activate PWM for pin L\n\n self.driveMode = mode\n\n def cycleMode(self):\n if self.driveMode == (DRIVE_MODES - 1):\n self.driveMode = 0\n else:\n self.driveMode += 1\n\n # Output of changeSpeed depends on the current drive mode.\n def changeSpeed(self, rightStick, leftStick):\n \"\"\"Input values of rightStick and leftStick between -100 and 100\"\"\"\n # Check to see if values have changed, abort if not\n if (rightStick == self.rSpeed) and (leftStick == self.lSpeed):\n return False\n\n # <--Experimental mixing algorithm-->\n\n # Implement basic mixing algorithm\n rTemp = leftStick + (self.maxDeltaX * (rightStick)) # be careful not to divide by zero\n lTemp = leftStick - (self.maxDeltaX * (rightStick)) # \"\n\n # Limit rate of change for forward/backward motion\n if ((lTemp - self.lSpeed) > self.maxDeltaY):\n self.lSpeed += self.maxDeltaY\n elif ((lTemp - self.lSpeed) < - self.maxDeltaY):\n self.lSpeed -= self.maxDeltaY\n else:\n self.lSpeed = lTemp\n\n if ((rTemp - self.rSpeed) > self.maxDeltaY):\n self.rSpeed += self.maxDeltaY\n elif ((rTemp - self.rSpeed) < - self.maxDeltaY):\n self.rSpeed -= self.maxDeltaY\n else:\n self.rSpeed = rTemp\n\n if self.rSpeed > 100:\n self.rSpeed = 100\n if self.rSpeed < -100:\n self.rSpeed = -100\n\n if self.lSpeed > 100:\n self.lSpeed = 100\n if self.lSpeed < -100:\n self.lSpeed = -100\n\n #send to arduino via i2c\n\n rMotorValue = self.idleSpeed + (self.rSpeed/self.speedScaler)\n #print(\"rightMotorValue = \" + str(rMotorValue))\n lMotorValue = self.lSpeed + (self.lSpeed/self.speedScaler)\n #print(\"leftMotorValue = \" + str(lMotorValue))\n package = struct.pack('ff', rMotorValue, lMotorValue)\n #print(self.address)\n #print(list(package))\n try: self.bus.write_block_data(self.address, 1, list(package))\n except OSError as err:\n print(\"not today satan (OSError)\")\n # sleep(.05)\n\n # self.R_PWM.ChangeDutyCycle(\n # self.idleSpeed+(self.rSpeed/self.speedScaler))\n # self.L_PWM.ChangeDutyCycle(\n # self.idleSpeed+(self.lSpeed/self.speedScaler))\n\n\n# class LED_Controller:\n# \"\"\"Utilizes the Adafruit Neopixel library to control the output of the Neopixel LED ring.\"\"\"\n#\n# def __init__(self, arg):\n# super(LED_Controller, self).__init__()\n# self.arg = arg\n\n\nclass Remote_Control:\n \"\"\"Use a DualShock4 controller to manually control the operation of the robot\"\"\"\n\n # Controller Button States\n Ex = False # PyGame Button 0\n Circle = False # PyGame Button 1\n Triangle = False # PyGame Button 2\n Square = False # PyGame Button 3\n L_Bumper = False # PyGame Button 4\n R_Bumper = False # PyGame Button 5\n L_Trigger = False # PyGame Button 6\n R_Trigger = False # PyGame Button 7\n Share = False # PyGame Button 8\n Options = False # PyGame Button 9\n PS = False # PyGame Button 10\n L_Stick = False # PyGame Button 11\n R_Stick = False # PyGame Button 12\n\n # Controller Axis States\n L_X_Axis = 0 # PyGame Axis 0: [0, 1.0]\n R_X_Axis = 0 # PyGame Axis 3: [0, 1.0]\n L_Y_Axis = 0 # PyGame Axis 1: [0, 1.0]\n R_Y_Axis = 0 # PyGame Axis 4: [0, 1.0]\n L_Trigger = -1.0 # PyGame Axis 2: [-1.0, 1.0]\n R_Trigger = -1.0 # PyGame Axis 5: [-1.0, 1.0]\n\n def __init__(self):\n pygame.init() # Initialize pygame library\n self.controller = pygame.joystick.Joystick(0) # Connect to the controller (and hope that it is paired with the Pi)\n self.controller.init() # Prepare to read data from controller\n\n def update(self): # Only update the relavent buttons/axies\n pygame.event.get()\n self.L_Y_Axis = self.controller.get_axis(1)\n self.R_X_Axis = self.controller.get_axis(3)\n self.R_Y_Axis = self.controller.get_axis(4)\n self.Ex = self.controller.get_button(0)\n self.PS = self.controller.get_button(10)\n\n#class Autonomous_Control: # This will be built out in Winter\n# \"\"\"NVIDIA Jetson Nano is used to provide motor control feedback based on realtime video processing\"\"\"\n\n#----------\n\n#----------\n\ndef __main__():\n\n GPIO.cleanup() # Clear any previously used GPIO modes\n\n driveMode = 0 # Start in Intuitive Mode (mode 0)\n\n # Initialize Neopixel ring\n #\n\n # Initialize motor controller objects\n motors = DC_Motor_Controller(MOTOR_R, MOTOR_L, driveMode)\n\n # Initialize DualShock4 Controller Connection\n DS4 = Remote_Control()\n print(\"Remote Control initiated\\n\")\n R_X_AXIS_SCALE_VAL = 100 # Scale right stick X-axis by 100 to match the changeSpeed method input range\n L_X_AXIS_SCALE_VAL = 100 # Scale left stick X-axis by 100 to match the changeSpeed method input range\n R_Y_AXIS_SCALE_VAL = 100 # Scale right stick Y-axis by 100 to match the changeSpeed method input range\n L_Y_AXIS_SCALE_VAL = 100 # Scale left stick Y-axis by 100 to match the changeSpeed method input range\n\n try:\n while True:\n DS4.update()\n motors.changeSpeed((DS4.R_X_Axis * R_X_AXIS_SCALE_VAL), (DS4.L_Y_Axis * L_Y_AXIS_SCALE_VAL))\n\n except KeyboardInterrupt:\n print(\"\\nEXITING NOW\\n\")\n DS4.controller.quit()\n GPIO.cleanup() # to be used when GPIO is active\n\n#----------\n\n# Code Execution\n__main__()\n","sub_path":"herbie_pi.py","file_name":"herbie_pi.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"275435449","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'Michael Liao (askxuefeng@gmail.com)'\r\n\r\nfrom datetime import datetime\r\nimport unittest\r\n\r\nimport siteconfig\r\n\r\nclass Test(unittest.TestCase):\r\n\r\n def test_date_format_samples(self):\r\n dt = datetime(2008, 2, 21)\r\n self.assertEquals([\r\n ('%Y-%m-%d', '2008-02-21'),\r\n ('%y-%m-%d', '08-02-21'),\r\n ('%d/%m/%Y', '21/02/2008'),\r\n ('%d/%m/%y', '21/02/08'),\r\n ('%m/%d/%Y', '02/21/2008'),\r\n ('%m/%d/%y', '02/21/08'),\r\n ('%b %d, %Y', 'Feb 21, 2008'),\r\n ('%b %d, %y', 'Feb 21, 08'),\r\n ('%B %d, %Y', 'February 21, 2008'),\r\n ('%B %d, %y', 'February 21, 08'),\r\n ], siteconfig.date_format_samples(dt))\r\n\r\n def test_time_format_samples(self):\r\n dt = datetime(2008, 2, 21, 13, 20, 59)\r\n self.assertEquals([\r\n ('%H:%M:%S', '13:20:59'),\r\n ('%H:%M', '13:20'),\r\n ('%I:%M:%S %p', '01:20:59 PM'),\r\n ('%I:%M %p', '01:20 PM'),\r\n ], siteconfig.time_format_samples(dt))\r\n\r\n def test_default_setting(self):\r\n site = siteconfig.Site()\r\n self.assertEquals(siteconfig.DEFAULT_DATE, site.date_format)\r\n self.assertEquals(siteconfig.DEFAULT_TIME, site.time_format)\r\n self.assertEquals('ExpressMe', site.title)\r\n\r\n def test_set_site_settings(self):\r\n site = siteconfig.Site(title='TITLE', subtitle='SUBTITLE')\r\n self.assertEquals('TITLE', site.title)\r\n self.assertEquals('SUBTITLE', site.subtitle)\r\n self.assertRaises(AttributeError, lambda : site.not_exist_attr)\r\n\r\nif __name__ == '__main__':\r\n #import sys;sys.argv = ['', 'Test.testName']\r\n unittest.main()\r\n","sub_path":"src/siteconfig_test.py","file_name":"siteconfig_test.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95373538","text":"# -*- coding: utf-8 -*-\nimport asyncio\nimport logging\n\nfrom ..db import TRANSPORT_TYPES as DB_TRANSPORT_TYPES\nfrom .base_service import YoBaseService\n\nlogger = logging.getLogger(__name__)\n\nTRANSPORT_KEYS = {'notification_types', 'sub_data'}\nTRANSPORT_TYPES = set(DB_TRANSPORT_TYPES)\n\n\nclass YoAPIServer(YoBaseService):\n service_name = 'api_server'\n q = asyncio.Queue()\n\n # pylint: disable=too-many-arguments\n @staticmethod\n async def api_get_notifications(username=None,\n created_before=None,\n updated_after=None,\n read=None,\n notify_types=None,\n limit=30,\n context=None):\n \"\"\" Get all notifications since the specified time\n\n Keyword args:\n username(str): The username to query for\n created_before(str): ISO8601-formatted timestamp\n updated_after(str): ISO8601-formatted timestamp\n read(bool): If set, only returns notifications with read flag set to this value\n notify_types(str): The notification type to return\n limit(int): The maximum number of notifications to return, defaults to 30\n\n Returns:\n list: list of notifications represented in dictionary format\n \"\"\"\n yo_db = context['yo_db']\n return yo_db.get_notifications(\n to_username=username,\n created_before=created_before,\n updated_after=updated_after,\n notify_types=notify_types,\n read=read,\n limit=limit)\n\n # pylint: enable=too-many-arguments\n\n @staticmethod\n async def api_mark_read(ids=None, context=None):\n \"\"\" Mark a list of notifications as read\n\n Keyword args:\n ids(list): List of notifications to mark read\n\n Returns:\n list: list of notifications updated\n \"\"\"\n yo_db = context['yo_db']\n ids = ids or []\n return [yo_db.wwwpoll_mark_read(nid) for nid in ids]\n\n @staticmethod\n async def api_mark_unread(ids=None, context=None):\n \"\"\" Mark a list of notifications as unread\n\n Keyword args:\n ids(list): List of notifications to mark unread\n\n Returns:\n list: list of notifications updated\n \"\"\"\n yo_db = context['yo_db']\n ids = ids or []\n return [yo_db.wwwpoll_mark_unread(nid) for nid in ids]\n\n @staticmethod\n async def api_mark_shown(ids=None, context=None):\n \"\"\" Mark a list of notifications as shown\n\n Keyword args:\n ids(list): List of notifications to mark shown\n\n Returns:\n list: list of notifications updated\n \"\"\"\n yo_db = context['yo_db']\n return [yo_db.wwwpoll_mark_shown(nid) for nid in ids]\n\n @staticmethod\n async def api_mark_unshown(ids=None, context=None):\n \"\"\" Mark a list of notifications as unshown\n\n Keyword args:\n ids(list): List of notifications to mark unshown\n\n Returns:\n list: list of notifications updated\n \"\"\"\n yo_db = context['yo_db']\n ids = ids or []\n return [yo_db.wwwpoll_mark_unshown(nid) for nid in ids]\n\n @staticmethod\n async def api_get_transports(username=None, context=None):\n yo_db = context['yo_db']\n return yo_db.get_user_transports(username)\n\n @staticmethod\n async def api_set_transports(username=None, transports=None, context=None):\n transports = transports or {}\n\n assert TRANSPORT_TYPES.issuperset(\n transports.keys()), 'bad transport types'\n\n for transport in transports.values():\n assert TRANSPORT_KEYS.issuperset(\n transport.keys()), 'bad transport data'\n\n yo_db = context['yo_db']\n return yo_db.set_user_transports(username, transports)\n\n async def async_task(self):\n self.yo_app.add_api_method(self.api_get_notifications,\n 'get_notifications')\n self.yo_app.add_api_method(self.api_mark_read, 'mark_read')\n self.yo_app.add_api_method(self.api_mark_unread, 'mark_unread')\n self.yo_app.add_api_method(self.api_mark_shown, 'mark_shown')\n self.yo_app.add_api_method(self.api_mark_unshown, 'mark_unshown')\n self.yo_app.add_api_method(self.api_get_transports, 'get_transports')\n self.yo_app.add_api_method(self.api_set_transports, 'set_transports')\n\n def init_api(self):\n pass\n","sub_path":"yo/services/api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"111983595","text":"'''\n@author: P Martin\n'''\nfrom tkinter import Tk\nfrom gui.mainframe import MainFrameGUI\n\n\ndef go():\n print( 'run chair simulation' )\n\n # Start a root instance of Tkinter\n root = Tk()\n\n # Create the Main Application Window\n MainFrameGUI( parentFrame = root, root = root )\n\n # Run\n root.mainloop()\n\n\nif __name__ == '__main__':\n '''\n Command Line usage\n '''\n go()\n\n\n\n","sub_path":"adec.py","file_name":"adec.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422249693","text":"import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import NearestNeighbors\n\n# Load Data\ndata = pd.read_csv(\"https://raw.githubusercontent.com/Lambda-Spotify-Song-Suggester-3/datascience/master/kaggle_data/encoded.csv\")\ndf = data.copy()\n\ndictionary = df[[\"artist_name\", \"track_name\", \"track_key\", \"track_id\"]]\n\n# Drop\ndf = df.drop(columns=['artist_name','track_id', 'track_name','track_key', 'duration_ms', 'mode', 'loudness', 'time_signature'])\n\n# Scale the data\n\nscaler = StandardScaler()\ndf_s = scaler.fit_transform(df)\n\ndef epic_predictor(input_track_key):\n '''\n This function takes in a 'track_key' of a song in the dataframe imported\n above, which is a number from 0 to 130,000 something.\n The function returns a list of ten hashes that are the \"track_id\"s of most\n closely related songs in the dataframe imported above.\n -------\n For example, your function will look like this for Britney Spears' \"Toxic\":\n > input:\n toxic_track_key = 119347\n epic_predictor(toxic_track_key)\n \n >output:\n >>>['4fbaKWFRghusXd4bSBvvfN',\n >>>'5cesclKWAhsCcZJDBhkWaa',\n >>> '7IE8eERSpTC9Jaw3arl99B',\n >>> '6MLvUL2dYphJTwgiBvuJ1J',\n >>> '4RYtaqxjDJUOY2GrtkLTFf',\n >>> '6gJ1T7THE0Pxk5VpTovwJH',\n >>> '7hiFcSUWRVotWd2pxhRIDJ',\n >>> '6flP4UZGozZGQk8rpE09g4',\n >>> '4uLmKWOb8hl49MYYAc4bnn',\n >>> '39Z6LCw3UEFYjQivDV1UF1']\n '''\n\n\n ## Convert \"input_track_key\" to the index of the song (the song's position\n ## in the dataframe).\n input_dictionary_entry = dictionary[dictionary['track_key']==input_track_key]\n input_index = input_dictionary_entry.index[0]\n\n ## Nearest Neighbors model\n nn = NearestNeighbors(n_neighbors=10, algorithm='kd_tree')\n nn.fit(df_s)\n\n neighbor_predictions = nn.kneighbors([df_s[input_index]])\n\n ## This is a list of the INDEXES of the songs\n list_of_predictions = neighbor_predictions[1][0].tolist()\n\n ten_similar_tracks = []\n for item in list_of_predictions:\n track_hash = dictionary['track_id'].iloc[item]\n ten_similar_tracks.append(track_hash)\n\n return ten_similar_tracks\n\n#testing\n\n#toxic_track_key = 119347\n#epic_predictor(toxic_track_key)\n\n## You can use this to print out the artist name and track name of the list of hashes generated.\n#print(dictionary[dictionary['track_id']=='4fbaKWFRghusXd4bSBvvfN'])\n#print(dictionary[dictionary['track_id']=='5cesclKWAhsCcZJDBhkWaa'])\n\n## This function is deprecated. Don't use it.\n\n#from sklearn.metrics.pairwise import cosine_similarity\n#from sklearn.preprocessing import MinMaxScaler\n\n#scaler = MinMaxScaler()\n#df_s = scaler.fit_transform(df)\n\n# def epic_predictor(input_track_key):\n# '''\n# This function is deprecated. Don't use it.\n\n# This function takes in a 'track_key' which is a number from 0 to 130,000 something.\n# The function returns a list of ten numbers that are the \"track_id\"s of the\n# dataframe imported above.\n# -------\n# For example, your function will look like this for Britney Spears' \"Toxic\":\n# > input:\n# toxic_track_key = 119347\n# epic_predictor(toxic_track_key)\n \n# >output:\n# >>>['4fbaKWFRghusXd4bSBvvfN',\n# >>>'5cesclKWAhsCcZJDBhkWaa',\n# >>>'7IE8eERSpTC9Jaw3arl99B',\n# >>>'5HypDLkUG04hMqepEP3OMM',\n# >>>'7hiFcSUWRVotWd2pxhRIDJ',\n# >>>'6MLvUL2dYphJTwgiBvuJ1J',\n# >>>'12j3KX5TkcAswLUUPMTNqA',\n# >>>'39Z6LCw3UEFYjQivDV1UF1',\n# >>>'2v5JTeM6hSmi5wWy7jiwrI',\n# >>>'6gJ1T7THE0Pxk5VpTovwJH']\n\n# '''\n\n# # Cosine Similarity\n# matrix = cosine_similarity(df_s, df_s[input_track_key:(input_track_key + 1)])\n# matrix = pd.DataFrame(matrix)\n# top = matrix[0].sort_values(ascending=False)[:10]\n\n# # Print Playlist\n# z = top.reset_index()\n# ten_similar_tracks = []\n\n# for col in z[\"index\"]:\n# track = (dictionary['track_id'].iloc[col])\n# ten_similar_tracks.append(track)\n\n# return ten_similar_tracks\n\n#testing\n#toxic_track_key = 119493\n#epic_predictor(toxic_track_key)\n\ndef feature_average(input_track_key):\n '''\n This function returns the sum of the features for the ten recommended songs.\n '''\n ten_similar_tracks = epic_predictor(input_track_key)\n # Return a dataframe with only the ten most similar tracks\n ten_similar_tracks = data[data[\"track_id\"].isin(ten_similar_tracks)]\n ten_similar_tracks = ten_similar_tracks[['acousticness', 'danceability', \n 'energy', 'instrumentalness', \n 'liveness', 'mode', \n 'speechiness', 'valence']]\n # Average features of ten tracks \n acousticness = round(ten_similar_tracks['acousticness'].mean(),2)\n danceability = round(ten_similar_tracks['danceability'].mean(),2)\n energy = round(ten_similar_tracks['energy'].mean(),2)\n instrumentalness = round(ten_similar_tracks['instrumentalness'].mean(),2)\n liveness = round(ten_similar_tracks['liveness'].mean(),2)\n mode = round(ten_similar_tracks['mode'].mean(),2)\n speechiness = round(ten_similar_tracks['speechiness'].mean(),2)\n valence = round(ten_similar_tracks['valence'].mean(),2)\n # Store all to \"features\" variable\n features = []\n attributes = [acousticness, danceability, energy, instrumentalness, liveness, mode, speechiness, valence]\n #features.append(acousticness)\n for attribute in attributes:\n features.append(attribute)\n return features\n","sub_path":"app/nearest_neighbors_recommender.py","file_name":"nearest_neighbors_recommender.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371516188","text":"# -*- coding: utf-8 -*-\n# Copyright (c) Hebes Intelligence Private Company\n\n# This source code is licensed under the Apache License, Version 2.0 found in the\n# LICENSE file in the root directory of this source tree.\n\n# Adapted from https://github.com/quantumblacklabs/kedro/blob/0.17.5/kedro/framework/context/context.py\n\nimport logging.config\nimport os\nfrom pathlib import Path\nfrom typing import Any, Dict, Union\nfrom warnings import warn\n\nimport feature_encoders.settings\nfrom environs import Env\nfrom kedro.config import ConfigLoader, MissingConfigException\nfrom kedro.framework.context import KedroContext, KedroContextError\nfrom kedro.framework.context.context import (\n _convert_paths_to_absolute_posix,\n _validate_layers_for_transcoding,\n)\nfrom kedro.framework.hooks import get_hook_manager\nfrom kedro.io import DataCatalog\nfrom kedro.versioning import Journal\nfrom omegaconf import OmegaConf\n\nimport eensight.settings\n\n\nclass CustomContext(KedroContext):\n \"\"\"Create a context object.\n\n ``KedroContext`` is the base class which holds the configuration and\n Kedro's main functionality. ``CustomContext`` extends ``KedroContext``\n to allow additional configuration to pass from the ``KedroSession``.\n\n Args:\n package_name (str): Package name for the Kedro project the context\n is created for.\n project_path (Union[Path, str]): Project path to define the context for.\n env (str, optional): Optional argument for additional configuration\n environment to be used for running the pipelines. If not specified,\n it defaults to \"local\". Defaults to None.\n extra_params (Dict[str, Any], optional): Optional dictionary containing\n extra project parameters. If specified, will update (and therefore\n take precedence over) the parameters retrieved from the project\n configuration.\n \"\"\"\n\n def __init__(\n self,\n package_name: str,\n project_path: Union[Path, str],\n env: str = None,\n extra_params: Dict[str, Any] = None,\n ):\n super().__init__(package_name, project_path, env=env, extra_params=extra_params)\n\n def _get_config_loader(self) -> ConfigLoader:\n \"\"\"A hook for changing the creation of a ConfigLoader instance.\n\n Returns:\n ConfigLoader: Instance of `ConfigLoader`.\n\n Raises:\n KedroContextError: If an incorrect ``ConfigLoader`` is registered.\n \"\"\"\n \n feature_path = feature_encoders.settings.CONF_PATH\n resources_path = str(Env().path(\"EENSIGHT_RESOURCES_PATH\").resolve())\n\n base_path = os.path.join(eensight.settings.CONF_ROOT, \"base\")\n if not os.path.isabs(base_path):\n base_path = os.path.join(resources_path, base_path)\n\n local_path = os.path.join(eensight.settings.CONF_ROOT, self.env)\n if not os.path.isabs(local_path):\n local_path = os.path.join(resources_path, local_path)\n\n conf_paths = [feature_path, base_path, local_path]\n\n hook_manager = get_hook_manager()\n config_loader = (\n hook_manager.hook.register_config_loader( # pylint: disable=no-member\n conf_paths=conf_paths,\n env=self.env,\n extra_params=self._extra_params,\n )\n )\n if not isinstance(config_loader, ConfigLoader):\n raise KedroContextError(\n f\"Expected an instance of `ConfigLoader`, \"\n f\"got `{type(config_loader).__name__}` instead.\"\n )\n\n logging_config = config_loader.get(\"logging.yaml\")\n logging.config.dictConfig(logging_config)\n\n return config_loader\n\n @property\n def params(self) -> Dict[str, Any]:\n \"\"\"Read-only property referring to Kedro's parameters for this context.\n\n Returns:\n Dict[str, Any]: Parameters defined in configuration file(s) with the\n addition of any extra parameters passed at initialization.\n \"\"\"\n try:\n # '**/parameters*' reads modular pipeline configs\n params = self.config_loader.get(\n \"parameters*\", \"parameters*/**\", \"**/parameters*\"\n )\n except MissingConfigException as exc:\n warn(f\"Parameters not found in your Kedro project config.\\n{str(exc)}\")\n params = {}\n\n params = OmegaConf.create(params)\n extra_params = OmegaConf.create(self._extra_params or {})\n params = OmegaConf.merge(params, extra_params)\n return OmegaConf.to_container(params)\n\n def _get_catalog(\n self,\n save_version: str = None,\n journal: Journal = None,\n load_versions: Dict[str, str] = None,\n ) -> DataCatalog:\n \"\"\"A hook for changing the creation of a DataCatalog instance.\n\n Raises:\n KedroContextError: If incorrect ``DataCatalog`` is registered for the project.\n\n Returns:\n DataCatalog: A populated DataCatalog instance.\n \"\"\"\n feed_dict = self._get_feed_dict()\n\n selected_catalog = feed_dict[\"parameters\"].pop(\n \"catalog\", eensight.settings.DEFAULT_CATALOG\n )\n\n catalog_is_partial = feed_dict[\"parameters\"].pop(\"partial_catalog\", False)\n\n catalog_search = [\n f\"catalogs/{selected_catalog}.*\",\n f\"catalogs/{selected_catalog}/**\",\n f\"catalogs/**/{selected_catalog}.*\",\n ]\n\n if catalog_is_partial:\n catalog_search.append(\"templates/_base.*\")\n\n conf_catalog = self.config_loader.get(*catalog_search)\n\n # remove site_name and versioned\n conf_catalog.pop(\"site_name\", None)\n conf_catalog.pop(\"versioned\", None)\n\n # capture rebind_names and location\n rebind_names = conf_catalog.pop(\"rebind_names\", {})\n location = conf_catalog.pop(\"location\", {})\n\n # turn relative paths in conf_catalog into absolute paths\n # before initializing the catalog\n data_root = eensight.settings.DATA_ROOT\n if not os.path.isabs(data_root):\n resources_path = str(Env().path(\"EENSIGHT_RESOURCES_PATH\").resolve())\n data_root = os.path.join(resources_path, data_root)\n\n conf_catalog = _convert_paths_to_absolute_posix(\n project_path=Path(data_root), conf_dictionary=conf_catalog\n )\n conf_creds = self._get_config_credentials()\n\n hook_manager = get_hook_manager()\n catalog = hook_manager.hook.register_catalog( # pylint: disable=no-member\n catalog=conf_catalog,\n credentials=conf_creds,\n load_versions=load_versions,\n save_version=save_version,\n journal=journal,\n )\n\n if not isinstance(catalog, DataCatalog):\n raise KedroContextError(\n f\"Expected an instance of `DataCatalog`, \"\n f\"got `{type(catalog).__name__}` instead.\"\n )\n\n # add model, feature and parameters to the catalog\n selected_base_model = feed_dict[\"parameters\"].pop(\n \"base_model\", eensight.settings.DEFAULT_BASE_MODEL\n )\n\n catalog.add_feed_dict(feed_dict)\n catalog.add_feed_dict(dict(rebind_names=rebind_names))\n catalog.add_feed_dict(dict(location=location))\n\n conf_model = self.config_loader.get(\n f\"base_models/{selected_base_model}.*\",\n f\"base_models/{selected_base_model}/**\",\n f\"**/base_models/{selected_base_model}.*\",\n )\n catalog.add_feed_dict(dict(model_config=conf_model))\n\n conf_features = self.config_loader.get(\n \"features*\", \"features/**\", \"**/features*\"\n )\n catalog.add_feed_dict(dict(feature_map=conf_features))\n\n if catalog.layers:\n _validate_layers_for_transcoding(catalog)\n\n hook_manager = get_hook_manager()\n hook_manager.hook.after_catalog_created( # pylint: disable=no-member\n catalog=catalog,\n conf_catalog=conf_catalog,\n conf_creds=conf_creds,\n feed_dict=feed_dict,\n save_version=save_version,\n load_versions=load_versions,\n run_id=self.run_id or save_version,\n )\n return catalog\n","sub_path":"src/eensight/framework/context/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"221763796","text":"\nimport logging\nimport os\nimport sys\nimport ujson\nimport unittest\nimport re\nfrom dateutil.parser import parse\n\nfrom ptvalidator.crawlers.ag import AGCrawler\nfrom ptvalidator.crawlers.bbin import BBINCrawler\nfrom ptvalidator.crawlers.gdc import GDCCrawler\nfrom ptvalidator.crawlers.mg import MGCrawler\nfrom ptvalidator.crawlers.tgp import TGPCrawler\nfrom ptvalidator.crawlers.pt import PTCrawler\nfrom ptvalidator.crawlers.saba import SabaCrawler\n\nlogger = logging.getLogger()\n\nuser_id = 'GDCX051225' # All\nMG_user_id = 'GDCX051233' # MG\nAG_user_id = 'GDCX051960' # AG\nGDC_user_id = 'GDCX051233' #GDC\nBBIN_user_id = 'GDCX051811' #BBIN\nTGP_user_id = 'GDCX051600' #TGP\nfrom_date = parse('2016-08-27 00:00:00')\nto_date = parse('2016-08-31 23:59:59')\n\n\"\"\"\nMG = GDCX051893, 2016-08-24 00:00:00, 2016-08-24 23:59:59\n\"\"\"\n\nclass CrawlerTest(unittest.TestCase):\n\n def test_SABA(self):\n crawler = SabaCrawler()\n crawler.login()\n data = crawler.get_summary('GDC666L051690', parse('2016-09-06 00:00:00'), parse('2016-09-06 23:59:59'))\n logger.debug(data)\n self.assertTrue(data != None)\n\n def test_PT(self):\n crawler = PTCrawler()\n crawler.login()\n data = crawler.get_summary('GDCX051225', parse('2016-08-29 00:00:00'), parse('2016-08-29 23:59:59'))\n logger.debug(data)\n self.assertTrue(data != None)\n\n def test_AG(self):\n crawler = AGCrawler()\n imageFile = crawler.get_login_capture()\n code = self.getCapture(imageFile)\n crawler.login(code)\n data = crawler.get_summary('GDCX051251', parse('2016-08-02 00:00:00'), parse('2016-08-21 23:59:59'))\n logger.debug(ujson.dumps(data))\n self.assertTrue(data != None)\n\n def test_GDC(self):\n crawler = GDCCrawler()\n imageFile = crawler.get_login_capture()\n code = self.getCapture(imageFile)\n crawler.login(code)\n data = crawler.get_summary(user_id, parse('2016-09-08 00:00:00'), parse('2016-09-09 23:59:59'))\n logger.debug(ujson.dumps(data))\n self.assertTrue(data != None)\n\n def test_BBIN(self):\n crawler = BBINCrawler()\n crawler.login()\n data = crawler.get_summary('gdcx051811', parse('2016-08-27 00:00:00'), parse('2016-08-30 23:59:59'))\n logger.debug(data)\n\n def test_TGP(self):\n from_date = parse('2016-08-27 00:00:00')\n to_date = parse('2016-08-30 23:59:59')\n crawler = TGPCrawler()\n crawler.login() \n data = crawler.get_summary('GDCX051233', parse('2016-08-30 00:00:00'), parse('2016-08-30 23:59:59'))\n logger.debug(data)\n\n def test_MG(self):\n crawler = MGCrawler()\n crawler.login()\n data = crawler.get_summary('GDCX051893', parse('2016-08-24 00:00:00'), parse('2016-08-24 23:59:59'))\n logger.debug(ujson.dumps(data))\n self.assertTrue(data != None)\n\n def getCapture(self,imgfile):\n with open('img.jpg', 'wb') as img:\n img.write(imgfile.decode('base64'))\n return raw_input(\"Check code:\")\n","sub_path":"web/ptvalidator/testcases/crawler_test.py","file_name":"crawler_test.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"475621724","text":"#!/usr/bin/env python\n# define some variables\nfrom __future__ import print_function\nimport sys\nimport matplotlib\nif matplotlib.get_backend() != \"TKAgg\":\n matplotlib.use(\"TKAgg\")\n\nimport pmagpy.pmag as pmag\nimport pmagpy.frp as frp\n\ndef main():\n \"\"\"\n NAME \n pt_rot.py \n\n DESCRIPTION\n rotates pt according to specified age and plate\n \n SYNTAX\n pt_rot.py [command line options]\n\n OPTIONS\n -h prints help and quits\n -f file with lon lat plate age Dplate as space delimited input\n Dplate is the destination plate coordinates desires \n - default is \"fixed south africa\"\n Dplate should be one of: [nwaf, neaf,saf,aus, eur, ind, sam, ant, grn, nam]\n -ff file Efile, file has lat lon data file and Efile has sequential rotation poles: Elat Elon Omega \n -F OFILE, output sites (pmag_results) formatted file with rotated points stored in pole_lon, pole_lat (vgp_lon, vgp_lat). (data_model=2.5)\n default is to print out rotated lon, lat to standard output\n -dm [2.5,3] set data model for output. Default is 3 \n \"\"\"\n dir_path='.'\n PTS=[]\n ResRecs=[]\n ofile=\"\"\n data_model=3\n Dplates=['nwaf', 'neaf','saf','aus', 'eur', 'ind', 'sam', 'ant', 'grn', 'nam']\n if '-WD' in sys.argv:\n ind = sys.argv.index('-WD')\n dir_path=sys.argv[ind+1]\n if '-h' in sys.argv:\n print(main.__doc__)\n sys.exit()\n if '-F' in sys.argv:\n ind = sys.argv.index('-F')\n ofile=dir_path+'/'+sys.argv[ind+1]\n if '-dm' in sys.argv:\n ind = sys.argv.index('-dm')\n data_model=dir_path+'/'+sys.argv[ind+1]\n if '-f' in sys.argv:\n ind = sys.argv.index('-f')\n file=dir_path+'/'+sys.argv[ind+1]\n f=open(file,'r')\n data=f.readlines()\n elif '-ff' in sys.argv:\n ind = sys.argv.index('-ff')\n file=dir_path+'/'+sys.argv[ind+1]\n f=open(file,'r')\n data=f.readlines()\n Efile=dir_path+'/'+sys.argv[ind+2]\n f=open(Efile,'r')\n edata=f.readlines()\n Poles=[]\n for p in edata:\n rec=p.split()\n pole=[float(rec[0]),float(rec[1]),float(rec[2])] # pole is lat/lon/omega\n Poles.append(pole)\n else:\n data=sys.stdin.readlines()\n polelatkey,polelonkey='pole_lat','pole_lon'\n if data_model!=3:\n polelatkey,polelonkey='vgp_lat','vgp_lon'\n for line in data:\n PtRec={}\n rec=line.split()\n PtRec['site_lon']=rec[0]\n PtRec['site_lat']=rec[1]\n if '-ff' in sys.argv:\n pt_lat,pt_lon=float(rec[1]),float(rec[0])\n for pole in Poles:\n ptrot= pmag.pt_rot(pole,[pt_lat],[pt_lon])\n pt_lat=ptrot[0][0]\n pt_lon=ptrot[1][0]\n if ofile==\"\":\n print(ptrot[1][0], ptrot[0][0])\n else:\n ResRec={polelonkey: '%7.1f'%(ptrot[0][0]),polelatkey:'%7.1f'%( ptrot[1][0])}\n ResRecs.append(ResRec)\n else:\n PtRec['cont']=rec[2]\n if PtRec['cont']=='af':PtRec['cont']='saf' # use fixed south africa\n PtRec['age']=rec[3]\n if len(rec)>4:\n PtRec['dcont']=rec[4]\n PTS.append(PtRec)\n if '-ff' not in sys.argv:\n for pt in PTS:\n pole='not specified'\n pt_lat=float(pt['site_lat'])\n pt_lon=float(pt['site_lon'])\n age=float(pt['age'])\n ptrot=[[pt_lat],[pt_lon]]\n if pt['cont']=='ib':\n pole=frp.get_pole(pt['cont'],age)\n ptrot= pmag.pt_rot(pole,[pt_lat],[pt_lon])\n pt_lat=ptrot[0][0]\n pt_lon=ptrot[1][0]\n pt['cont']='eur'\n if pt['cont']!='saf':\n pole1=frp.get_pole(pt['cont'],age)\n ptrot= pmag.pt_rot(pole1,[pt_lat],[pt_lon])\n if 'dcont' in list(pt.keys()):\n pt_lat=ptrot[0][0]\n pt_lon=ptrot[1][0]\n pole=frp.get_pole(pt['dcont'],age)\n pole[2]=-pole[2] \n ptrot= pmag.pt_rot(pole,[pt_lat],[pt_lon])\n if ofile==\"\":\n print(ptrot[1][0], ptrot[0][0])\n else:\n ResRec={polelonkey: '%7.1f'%(ptrot[0][0]),polelatkey:'%7.1f'%( ptrot[1][0])}\n ResRecs.append(ResRec)\n else:\n if 'dcont' in list(pt.keys()):\n pole=frp.get_pole(pt['dcont'],age)\n pole[2]=-pole[2] \n ptrot= pmag.pt_rot(pole,[pt_lat],[pt_lon])\n print(ptrot)\n if ofile==\"\":\n print(ptrot[1][0], ptrot[0][0]) \n else:\n ResRec={polelonkey: '%7.1f'%(ptrot[0][0]),polelatkey:'%7.1f'%( ptrot[1][0])}\n ResRecs.append(ResRec)\n else:\n if ofile==\"\":\n print(ptrot[1][0], ptrot[0][0])\n else:\n ResRec={polelonkey: '%7.1f'%(ptrot[0][0]),polelatkey:'%7.1f'%( ptrot[1][0])}\n ResRecs.append(ResRec)\n if len(ResRecs)>0:\n if data_model==3:\n pmag.magic_write(ofile,ResRecs,'locations')\n else:\n pmag.magic_write(ofile,ResRecs,'pmag_results')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"programs/pt_rot.py","file_name":"pt_rot.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435401488","text":"from business.services.service import Service\nfrom business.functions.fitness_function import FitnessFunction\nfrom business.topologies.topology import Topology\nfrom util.constants import Constants\nfrom business.services.particle_service import ParticleService\nfrom copy import copy\n\n\nclass ParticleSwarmOptimizationService(Service):\n\n def __init__(self, fitness_function: FitnessFunction, topology: Topology):\n self.__fitness_function = fitness_function\n self.__topology = topology\n self.__fitness_values = []\n self.__particle_service = ParticleService()\n self.__particles = self.__particle_service.initialize_particles(self.__fitness_function)\n self.__gbest = self.__particles[0].pbest\n self.__execute()\n\n def __execute(self):\n count_iterations: int = 0\n while count_iterations < Constants.N_EVALUATE_FITNESS:\n self.__calculate_fitness()\n count_iterations += Constants.N_PARTICLES\n self.__update_gbest()\n inertia = self.__generate_inertia(count_iterations)\n self.__particles = self.__topology.calculate_velocity(self.__particles, inertia, self.__fitness_function)\n self.update_position()\n self.update_bound_adjustament()\n best_value = self.__fitness_function.run(self.__gbest)\n print(count_iterations, \" : \", best_value)\n self.__fitness_values.append(best_value)\n\n def __calculate_fitness(self):\n for particle in self.__particles:\n if self.__fitness_function.run(particle.position) < self.__fitness_function.run(particle.pbest):\n particle.pbest = copy(particle.position)\n particle.fitness = self.__fitness_function.run(particle.position)\n\n def __update_gbest(self):\n for particle in self.__particles:\n if self.__fitness_function.run(particle.pbest) < self.__fitness_function.run(self.__gbest):\n self.__gbest = particle.pbest\n\n @staticmethod\n def __generate_inertia(count_iterations):\n return Constants.INERTIA_MAX - count_iterations * (Constants.INERTIA_MAX - Constants.INERTIA_MIN) / \\\n Constants.N_EVALUATE_FITNESS\n\n def update_position(self):\n for particle in self.__particles:\n particle.position += particle.velocity\n\n def update_bound_adjustament(self):\n for particle in self.__particles:\n particle.position[particle.position > self.__fitness_function.max_bound] = self.__fitness_function.max_bound\n particle.position[particle.position < self.__fitness_function.min_bound] = self.__fitness_function.min_bound\n\n @property\n def fitness_values(self):\n return self.__fitness_values\n\n @fitness_values.setter\n def fitness_values(self, fitness_values):\n self.__fitness_values = fitness_values\n\n","sub_path":"business/services/pso_service.py","file_name":"pso_service.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"336241041","text":"import os\nimport logging.config\nfrom random import randint\nimport zlib\nimport struct\nimport socket\nimport time\n\nfrom PIL import Image\n\nimport config\n# from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor, CONFIG_PATH,enable_adb_host_auto_detect, ADB_SERVER\nfrom .ADBClientSession import ADBClientSession\nfrom util.socketutil import recvall\nfrom . import revconn\n\n# from numpy import average, dot, linalg\n\nlogger = logging.getLogger(__name__)\n\n\ndef _screencap_to_image(cap):\n w, h, pixels = cap\n return Image.frombytes('RGBA', (w, h), pixels)\n\n\ndef _ensure_pil_image(imgorfile):\n if isinstance(imgorfile, Image.Image):\n return imgorfile\n return Image.open(imgorfile)\n\n\ndef check_adb_alive():\n try:\n sess = ADBClientSession(config.ADB_SERVER)\n version = int(sess.service('host:version').read_response().decode(), 16)\n logger.debug('ADB server version %d', version)\n return True\n except ConnectionRefusedError:\n return False\n except RuntimeError:\n return False\n\n\ndef ensure_adb_alive():\n if check_adb_alive():\n return\n logger.info('尝试启动 adb server')\n import subprocess\n adbbin = config.get('device/adb_binary', None)\n if adbbin is None:\n adb_binaries = ['adb', os.path.join(config.ADB_ROOT, 'adb')]\n else:\n adb_binaries = [adbbin]\n for adbbin in adb_binaries:\n try:\n logger.debug('trying %r', adbbin)\n subprocess.run([adbbin, 'start-server'], check=True)\n return True\n except FileNotFoundError:\n pass\n except subprocess.CalledProcessError:\n pass\n raise OSError(\"can't start adb server\")\n\n\nclass ADBConnector:\n def __init__(self, adb_serial=None):\n # os.chdir(ADB_ROOT)\n self.ADB_ROOT = config.ADB_ROOT\n self.adb_serial = adb_serial\n self.host_session_factory = lambda: ADBClientSession(config.ADB_SERVER)\n self.rch = None\n if self.adb_serial is None:\n self.adb_serial = self.__adb_device_name_detector()\n self.device_session_factory = lambda: self.host_session_factory().device(self.adb_serial)\n self.cache_screenshot = config.get('device/cache_screenshot', True)\n self.last_screenshot_timestamp = 0\n self.last_screenshot_duration = 0\n self.last_screenshot = None\n\n if config.get('device/try_emulator_enhanced_mode', True):\n loopbacks = self._detect_loopbacks()\n if len(loopbacks):\n logger.debug('possible loopback addresses: %s', repr(loopbacks))\n self.rch = revconn.ReverseConnectionHost()\n self.rch.start()\n if self._test_reverse_connection(loopbacks):\n logger.info('正在使用模拟器优化模式')\n self.screencap = self._reverse_connection_screencap\n else:\n self.rch.stop()\n else:\n self.loopback = None\n\n def __del__(self):\n if self.rch and self.rch.is_alive():\n self.rch.stop()\n\n def __adb_device_name_detector(self):\n devices = [x for x in self.host_session_factory().devices() if x[1] != 'offline']\n\n if len(devices) == 0:\n auto_connect = config.get('device/adb_auto_connect', None)\n if auto_connect is not None:\n logger.info('没有已连接设备,尝试连接 %s', auto_connect)\n try:\n self.host_session_factory().disconnect(auto_connect)\n except:\n pass\n self.host_session_factory().connect(auto_connect)\n else:\n raise RuntimeError('找不到可用设备')\n\n devices = [x for x in self.host_session_factory().devices() if x[1] != 'offline']\n\n always_use_device = config.get('device/adb_always_use_device', None)\n if always_use_device is not None:\n if always_use_device not in (x[0] for x in devices):\n raise RuntimeError('设备 %s 未连接' % always_use_device)\n return always_use_device\n\n if len(devices) == 1:\n device_name = devices[0][0]\n elif len(devices) > 1:\n logger.info(\"检测到多台设备\")\n num = 0\n while True:\n try:\n num = int(input(\"请输入序号选择设备: \"))\n if not 0 <= num < len(devices):\n raise ValueError()\n break\n except ValueError:\n logger.error(\"输入不合法,请重新输入\")\n device_name = devices[num][0]\n else:\n raise RuntimeError('找不到可用设备')\n logger.info(\"确认设备名称:\" + device_name)\n return device_name\n\n def run_device_cmd(self, cmd, DEBUG_LEVEL=2):\n output = self.device_session_factory().exec(cmd)\n logger.debug(\"command: %s\", cmd)\n logger.debug(\"output: %s\", repr(output))\n return output\n\n def get_sub_screen(self, image, screen_range):\n return image.crop(\n (\n screen_range[0][0],\n screen_range[0][1],\n screen_range[0][0] + screen_range[1][0],\n screen_range[0][1] + screen_range[1][1]\n )\n )\n\n\n def _detect_loopbacks(self):\n board = self.device_session_factory().exec('getprop ro.product.board')\n if b'goldfish' in board:\n return ['10.0.2.2']\n modules = self.device_session_factory().exec('grep -o vboxguest /proc/modules')\n if b'vboxguest' in modules:\n arp = self.device_session_factory().exec('cat /proc/net/arp')\n return [x[:x.find(b' ')].decode() for x in arp.splitlines()[1:]]\n return []\n\n def _test_reverse_connection(self, loopbacks):\n for addr in loopbacks:\n logger.debug('testing loopback address %s', addr)\n future = self.rch.register_cookie()\n with future:\n cmd = 'echo -n %sOKAY | nc -w 1 %s %d' % (future.cookie.decode(), addr, self.rch.port)\n logger.debug(cmd)\n control_sock = self.device_session_factory().exec_stream(cmd)\n with control_sock:\n conn = future.get(2)\n if conn is not None:\n data = recvall(conn)\n conn.close()\n if data == b'OKAY':\n self.loopback = addr\n logger.debug('found loopback address %s', addr)\n return True\n return False\n\n def screencap_png(self):\n \"\"\"returns PNG bytes\"\"\"\n s = self.device_session_factory().exec_stream('screencap -p')\n data = recvall(s, 4194304)\n return data\n\n def screencap(self):\n \"\"\"returns (width, height, pixels)\n pixels in RGBA/RGBX format\"\"\"\n s = self.device_session_factory().exec_stream('screencap|gzip -1')\n data = recvall(s, 4194304)\n s.close()\n data = zlib.decompress(data, zlib.MAX_WBITS | 16, 8388608)\n w, h, f = struct.unpack_from('III', data, 0)\n assert (f == 1)\n return (w, h, data[12:])\n\n def _reverse_connection_screencap(self):\n \"\"\"returns (width, height, pixels)\n pixels in RGBA/RGBX format\"\"\"\n future = self.rch.register_cookie()\n with future:\n control_sock = self.device_session_factory().exec_stream('(echo -n %s; screencap) | nc %s %d' % (future.cookie.decode(), self.loopback, self.rch.port))\n with control_sock:\n with future.get() as conn:\n data = recvall(conn, 8388608, True)\n w, h, f = struct.unpack_from('III', data, 0)\n assert (f == 1)\n return (w, h, data[12:].tobytes())\n\n def screenshot(self, cached=True):\n t0 = time.monotonic()\n if cached and self.cache_screenshot:\n if self.last_screenshot is not None and t0 - self.last_screenshot_timestamp < self.last_screenshot_duration:\n return self.last_screenshot\n rawcap = self.screencap()\n img = _screencap_to_image(rawcap)\n t1 = time.monotonic()\n self.last_screenshot_timestamp = t1\n self.last_screenshot_duration = t1 - t0\n self.last_screenshot = img\n return img\n\n def touch_swipe2(self, origin, movement, duration=None):\n # sleep(1)\n x1, y1, x2, y2 = origin[0], origin[1], origin[0] + movement[0], origin[1] + movement[1]\n\n logger.debug(\"滑动初始坐标:({},{}); 移动距离dX:{}, dy:{}\".format(*origin, *movement))\n command = \"input swipe {} {} {} {} \".format(x1, y1, x2, y2)\n if duration is not None:\n command += str(int(duration))\n self.run_device_cmd(command)\n\n def touch_tap(self, XY=None, offsets=None):\n # sleep(10)\n # sleep(0.5)\n if offsets is not None:\n final_X = XY[0] + randint(-offsets[0], offsets[0])\n final_Y = XY[1] + randint(-offsets[1], offsets[1])\n else:\n final_X = XY[0] + randint(-1, 1)\n final_Y = XY[1] + randint(-1, 1)\n # 如果你遇到了问题,可以把这百年输出并把日志分享到群里。\n logger.debug(\"点击坐标:({},{})\".format(final_X, final_Y))\n command = \"input tap {} {}\".format(final_X,\n final_Y)\n self.run_device_cmd(command)\n","sub_path":"connector/ADBConnector.py","file_name":"ADBConnector.py","file_ext":"py","file_size_in_byte":9555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"310921876","text":"num = 10\n\ndef show():\n global num # GLOBAL KEYWORD\n\n num = 11\n num = num % 3\n print(\">>1. Num is:\",num)\n\nshow()\nprint(\">>2. num is:\",num)\n\nnum = 10\ndef show1():\n num = 11\n num = num % 3\n print(\">>1. Num is:\",num)\n\nshow1()\nprint(\">>2. num is:\",num)\n\n# Use Case\ncart = []\n\ndef addProductToCart(product):\n\n global cart\n cart.append(product)","sub_path":"Session7.py","file_name":"Session7.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"304923178","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn import tree\r\nfrom sklearn import preprocessing\r\n\r\ndf = pd.read_csv(r\"C:\\letsupgrage assignment\\train.csv\")\r\ndf[\"Age\"].mean()\r\nnew_age_var = np.where(df[\"Age\"].isnull(),32,df[\"Age\"])\r\ndf[\"Age\"] = new_age_var\r\nlabel_encoder = preprocessing.LabelEncoder()\r\nencoded_sex = label_encoder.fit_transform(df[\"Age\"])\r\n\r\ntree_model = tree.DecisionTreeClassifier()\r\ntree_model.fit(X = pd.DataFrame(encoded_sex), y = df[\"Survived\"])\r\n\r\npredictors = pd.DataFrame([encoded_sex, df[\"Age\"], df[\"Fare\"]]).T\r\ntree_model = tree.DecisionTreeClassifier(max_depth=8)\r\ntree_model.fit(X = predictors, y = df[\"Survived\"])\r\n\r\nwith open(\"Dtree2.dot\", 'w') as f:\r\n f = tree.export_graphviz(tree_model, feature_names = [\"Sex\", \"Age\", \"Fare\"], out_file=f);\r\nprint(\"the model accuracy\")\r\nprint(tree_model.score(X = predictors, y = df[\"Survived\"]))\r\n","sub_path":"day 24 train_test.py","file_name":"day 24 train_test.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"153537066","text":"from stellarlib.vector_graphics.vector_model import VectorModel\nfrom stellarlib.vector_graphics.components.polygon import Polygon\nfrom stellarlib.vector import Vector\nfrom random import random\n\n\nclass AsteroidModel(VectorModel):\n\n angle_var = 30.0\n rad_var = 10.0\n radius = 20.0\n\n def __init__(self):\n\n vertices = self.generate_vertices()\n components = [Polygon(self, ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'), (255, 255, 255), 1)]\n\n VectorModel.__init__(self, vertices, components)\n\n def generate_vertices(self):\n\n vertices = {}\n\n ids = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')\n angles = (0, 45, 90, 135, 180, 225, 270, 315)\n\n for i in range(8):\n\n angle = angles[i] + random() * AsteroidModel.angle_var - AsteroidModel.angle_var/2\n mag = AsteroidModel.radius + random() * AsteroidModel.rad_var - AsteroidModel.rad_var/2\n\n v = Vector.from_angle(angle, mag)\n vertices[ids[i]] = v\n\n return vertices\n\n","sub_path":"asteroids_demo/src/models/asteroid_model.py","file_name":"asteroid_model.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395865430","text":"from django.shortcuts import render, HttpResponse\r\nfrom testapp.forms import select_test\r\n\r\n# Create your views here.\r\n\r\n\r\ndef test(request):\r\n\tf = select_test.SelectTestForm(initial={\"city\": 2, \"modes\": [2, ]}) # 方法2\r\n\tif request.method == \"POST\":\r\n\t\tprint(request.POST)\r\n\t\treturn HttpResponse(\"OK\")\r\n\telse:\r\n\t\treturn render(request, \"test/select_test.html\", {\"f\": f})\r\n","sub_path":"day16/homework/zz/testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161177367","text":"\n### one code one day\n### 2020/03/19\n### leetcode 983 最低票价\n### 常见动态规划\n### dp[i] = min(dp[i-1]+costs[0], dp[i-7]+costs[1], dp[i-30]+costs[2])\n### 该方法时间复杂度不是最优\n### 参看 https://leetcode-cn.com/problems/minimum-cost-for-tickets/solution/zui-di-piao-jie-by-leetcode/\n\ndef mincostTickets(self, days: List[int], costs: List[int]) -> int:\n ###二分找前XXX天的下标\n def index(num, end):\n if(days[0] >= num):\n return -1\n else:\n start = 0\n while(start < end - 1):\n mid = (start + end) // 2\n if(days[mid] >= num):\n end = mid\n elif(days[mid] < num):\n start = mid\n return start\n dp = [float('inf')] * len(days)\n dp[0] = min(costs)\n for i in range(1, len(days)):\n ### 买 1天的票\n dp[i] = min(dp[i], dp[i-1] + costs[0])\n ### 买 7天的票\n index_pre7 = index(days[i]-6, i)\n if(index_pre7 == -1):\n dp[i] = min(dp[i], costs[1])\n else:\n dp[i] = min(dp[i], dp[index_pre7]+costs[1])\n ### 买 30天的票\n index_pre30 = index(days[i]-29, i)\n if(index_pre30 == -1):\n dp[i] = min(dp[i], costs[2])\n else:\n dp[i] = min(dp[i], dp[index_pre30]+costs[2])\n return dp[-1]\n","sub_path":"动态规划/minCostTickets.py","file_name":"minCostTickets.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"484620348","text":"while True:\n a = input(\"Input a large whole number: \")\n if a.isdigit() == True:\n if len(a) >= 6:\n break\n print('Input must be a whole number.')\n\nwhile True:\n b = input(\"Input the split: \")\n if b.isdigit() == True:\n if len(a)%int(b) == 0:\n break\n else:\n print(f'{a} must be evenly divisible by {b}.')\n print(\"Try again.\")\n else:\n print('Split must be a whole number.')\n\nstart = 0\nstep = int(b)\nold = 0\narr = []\nisBool = True\n\nwhile True:\n number = int(a[start:start+step])\n print(number)\n arr.append(number)\n if isBool and number <= old:\n isBool = False\n start += step\n else:\n start += step\n old = number\n if start >= len(a):\n break\nprint(arr)\nif isBool:\n print(\"Sequence is increasing.\")\nelse:\n print(\"Sequence is not increasing.\")","sub_path":"day-3/05-Number-Puzzle/unsolved.py","file_name":"unsolved.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"129776311","text":"import json\nimport datetime\nimport requests\nfrom pprintpp import pprint\nfrom requests.exceptions import HTTPError\nfrom config import *\nimport time\n\n# disable warnings\nrequests.packages.urllib3.disable_warnings()\n\n\ndef is_english(s):\n \"\"\"\n Check if the target sentence based on English or not\n :param s: Input sentence\n :return: Is English or not\n \"\"\"\n try:\n s.encode(encoding='utf-8').decode('ascii')\n except UnicodeDecodeError:\n return False\n else:\n return True\n\n\ndef restructure_user_name(data_name):\n \"\"\"\n Re-construct user name based on lastname firstname\n :param data_name: Input user name\n :return: User name after re-structured\n \"\"\"\n if \" \" in data_name:\n name_list = data_name.split(\" \")\n last_name = name_list.pop(-1)\n tmp_list = [last_name] + name_list\n\n if is_english(data_name):\n data_name = \" \".join(tmp_list)\n else:\n data_name = \"\".join(tmp_list)\n return data_name\n\n\ndef save_user_profile(user_name, user_info_list):\n \"\"\"\n Save the matched user info\n :param user_name: Original user name\n :param user_info_list: matched user info list\n \"\"\"\n data_json = {\"original_name\": user_name, \"info_list\": user_info_list}\n\n if len(user_name) == 0:\n print(\"Error. No user namne.\")\n return None\n\n output_file_name = \"./output/\" + user_name[0] + \".txt\"\n\n file_writer = open(output_file_name, \"a\")\n file_writer.write(json.dumps(data_json) + \"\\n\")\n file_writer.close()\n\n\ndef save_empty_profile(user_name):\n \"\"\"\n Save orginal user name if there is no matched user info\n :param user_name: Original user name\n \"\"\"\n if len(user_name) == 0:\n print(\"Error. No user namne.\")\n return None\n\n output_file_name = \"./output/\" + \"no_match.txt\"\n\n file_writer = open(output_file_name, \"a\")\n file_writer.write(\"%s\\n\" % user_name)\n file_writer.close()\n\n\ndef save_error(error_type, error_info):\n \"\"\"\n Save error type and error message\n :param error_type: Type of error (HTTP, Except, Response)\n :param error_info: Error message\n \"\"\"\n current_time = datetime.datetime.now()\n\n error_message = \"%s - %s - %s\\n\" % (current_time.strftime(\"%Y-%m-%d %H:%M:%S\"), error_type, error_info)\n file_writer = open(\"./log/error.log\", \"a\")\n file_writer.write(error_message)\n file_writer.close()\n\n\ndef is_match(target_name_list, fb_data):\n \"\"\"\n Check if the target sentence contain user name\n :param target_name_list: Partial user name splitted by space\n :param fb_data: Target sentence\n :return: Matched or not\n \"\"\"\n for part_name in target_name_list:\n if part_name not in fb_data:\n return False\n return True\n\n\ndef filter_user_info_by_name(target_name_list, user_info_list):\n \"\"\"\n Filter user info based on user name\n :param target_name_list: Partial user name splitted by space\n :param user_info_list: List of user info\n :return: Matched user info list\n \"\"\"\n match_list = list()\n\n for user_info in user_info_list:\n user_info.pop('network', None)\n fb_name = user_info[\"name\"]\n fb_desc = user_info[\"description\"]\n\n if is_match(target_name_list, fb_name):\n match_list.append(user_info)\n elif is_match(target_name_list, fb_desc):\n match_list.append(user_info)\n\n return match_list\n\n\ndef send_request_by_name(data_name):\n \"\"\"\n Send social buzz get user API\n :param data_name: User name\n :return: Request response\n \"\"\"\n try:\n sb_user_id_url = SB_URL_TEMPLATE.format(data_name, SB_KEY, SB_NETWORK)\n response = requests.get(sb_user_id_url, headers=DEFAULT_HEADER, verify=False)\n return (True, response)\n except HTTPError as http_err:\n print(\"HTTP error: %s\" % str(http_err))\n save_error(\"HTTP\", str(http_err))\n return (False, str(http_err))\n except Exception as e:\n print(\"Exception Error: %s\" % str(e))\n save_error(\"Except\", str(e))\n return (False, str(e))\n\n\ndef is_exceed_limit(response_json):\n \"\"\"\n Check if the social buzz API exceed the limit\n :param response_json: Request response\n :return: Is exceed the limit or not\n \"\"\"\n if \"meta\" in response_json and \"http_code\" in response_json[\"meta\"] and response_json[\"meta\"][\"http_code\"] == 403:\n return True\n return False\n\n\ndef write_number_to_file(number):\n file_writer = open(START_LINE_COUNT_FILE, \"w\")\n file_writer.write(str(number))\n file_writer.close()\n\n\ndef read_number_from_file():\n if os.path.isfile(START_LINE_COUNT_FILE):\n file_reader = open(START_LINE_COUNT_FILE, \"r\")\n for line in file_reader:\n number = int(line)\n file_reader.close()\n start_line_count = number\n return start_line_count\n\n\ndef get_id_from_name():\n line_count = 0\n\n # Read file and get START_LINE_COUNT\n START_LINE_COUNT = read_number_from_file()\n\n # Loop the user name and fetch user info\n file_reader = open(NAME_LIST_FILE, \"r\")\n for line in file_reader:\n original_user_name = line.rstrip(\"\\n\").replace(\" \", \" \")\n line_count += 1\n\n # Skip names before start line\n if SKIP_START_FLAG:\n if line_count < START_LINE_COUNT:\n continue\n\n # Skip names after finish line\n if SKIP_END_FLAG:\n if line_count >= FINISH_LINE_COUNT:\n print(\"Reach finish line: %d\" % line_count)\n break\n\n # Stop after target window size\n if MAX_GET_COUNT_FLAG:\n if line_count >= START_LINE_COUNT + MAX_GET_LINE_COUNT:\n print(\"Reach max get count: %s\" % line_count)\n break\n\n # Re-construct user name\n new_name = restructure_user_name(original_user_name)\n print(\"%03d: %s\" % (line_count, original_user_name))\n print(new_name)\n\n # Get API response\n request_result = send_request_by_name(new_name)\n\n # Check request exception\n if request_result[0] is False:\n continue\n\n # Check if Response.status_code != 200\n response = request_result[1]\n if not response:\n print(\"Response error: %s\" % response.status_code)\n pprint(response.json())\n save_error(\"Response\", json.dumps(response.json()))\n continue\n\n # Change response into json\n response.encoding = 'utf-8'\n user_info_result = response.json()\n\n # Check if exceed daily limit\n if is_exceed_limit(user_info_result):\n print(\"Reach Social Buzz limitation: %d\" % line_count)\n print(user_info_result[\"meta\"][\"message\"])\n write_number_to_file(str(line_count))\n time.sleep(15)\n break\n\n # Filter incorrect user info based on name\n name_list = original_user_name.split(\" \")\n try:\n filtered_user_info_list = filter_user_info_by_name(name_list, user_info_result[\"posts\"])\n except Exception as e:\n print(str(e))\n print(user_info_result)\n\n # Save filtered user info\n if len(filtered_user_info_list) > 0:\n save_user_profile(original_user_name, filtered_user_info_list)\n for user_info in filtered_user_info_list:\n pprint(user_info)\n else:\n save_empty_profile(original_user_name)\n\n file_reader.close()\n\n\nif __name__ == \"__main__\":\n for SB_KEY in SB_KEY_LIST:\n print(\"Using key: %s\" % SB_KEY)\n get_id_from_name()\n","sub_path":"get_fb_info_from_social_buzz/get_fb_user_info.py","file_name":"get_fb_user_info.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"568600840","text":"import numpy as np\r\nimport tensorflow as tf\r\nimport os\r\nimport time\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nfrom scipy.spatial import distance\r\nimport pandas as pd\r\nfrom sklearn.manifold import TSNE\r\nfrom sklearn.cluster import KMeans\r\nimport seaborn as sns\r\nimport gzip as gz\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.utils import shuffle\r\nfrom six.moves import cPickle as pickle\r\nfrom skimage import util\r\n\r\n\r\n# Giving specific random seed for data permutation and tf.Variable initialization\r\nnp.random.seed(0)\r\ntf.set_random_seed(1234)\r\n\r\n\r\n# Directory(named 'model') for storing trained model\r\nMODEL_DIR = os.path.join(os.path.dirname(__file__), 'model')\r\nif os.path.exists(MODEL_DIR) is False:\r\n os.mkdir(MODEL_DIR)\r\n\r\n\r\n# LeNet-5(https://github.com/sujaybabruwad/LeNet-in-Tensorflow/blob/master/LeNet-Lab.ipynb) ~ 'L3':120->128, 'L4':84->64\r\ndef lenet(x):\r\n # Hyperparameters\r\n mu = 0\r\n sigma = 0.1\r\n layer_depth = {'L1': 6, 'L2': 16, 'L3': 128, 'L4': 64, 'L5': 10}\r\n\r\n # Making the variable to global one for generative classifier\r\n global conv1, conv2, fullc1, fullc2\r\n\r\n # L1: Convolutional ~ (32, 32, 1) -> (28, 28, 6)\r\n conv1_w = tf.Variable(np.sqrt(2.0/32*32)*tf.truncated_normal(shape=[5, 5, 1, layer_depth.get('L1')], mean=mu, stddev=sigma), name='conv1_w')\r\n conv1_b = tf.Variable(tf.zeros(layer_depth.get('L1')), name='conv1_b')\r\n conv1 = tf.nn.conv2d(x, conv1_w, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\r\n conv1 = tf.nn.relu(conv1)\r\n conv1 = tf.nn.dropout(conv1, keep_prob)\r\n # Pooling ~ (28, 28, 6) -> (14, 14, 6)\r\n pool1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\r\n\r\n # L2: Convolutional ~ (14, 14, 6) -> (10, 10, 16)\r\n conv2_w = tf.Variable(np.sqrt(2.0/14*14)*tf.truncated_normal(shape=[5, 5, layer_depth.get('L1'), layer_depth.get('L2')], mean=mu, stddev=sigma), name='conv2_w')\r\n conv2_b = tf.Variable(tf.zeros(layer_depth.get('L2')), name='conv2_b')\r\n conv2 = tf.nn.conv2d(pool1, conv2_w, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\r\n conv2 = tf.nn.relu(conv2)\r\n conv2 = tf.nn.dropout(conv2, keep_prob)\r\n # Pooling ~ (10, 10, 16) -> (5, 5, 16)\r\n pool2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\r\n\r\n # Flatten ~ (5, 5, 16) -> (400)\r\n fullc1 = tf.contrib.layers.flatten(pool2)\r\n\r\n # L3: Fully-connected ~ (400) -> (128)\r\n fullc1_w = tf.Variable(np.sqrt(2.0/400)*tf.truncated_normal(shape=(400, layer_depth.get('L3')), mean=mu, stddev=sigma), name='fullc1_w')\r\n fullc1_b = tf.Variable(tf.zeros(layer_depth.get('L3')), name='fullc1_b')\r\n fullc1 = tf.matmul(fullc1, fullc1_w) + fullc1_b\r\n fullc1 = tf.nn.relu(fullc1)\r\n fullc1 = tf.nn.dropout(fullc1, keep_prob)\r\n\r\n # L4: Fully-connected ~ (128) -> (64)\r\n fullc2_w = tf.Variable(np.sqrt(2.0/120)*tf.truncated_normal(shape=(layer_depth.get('L3'), layer_depth.get('L4')), mean=mu, stddev=sigma), name='fullc2_w')\r\n fullc2_b = tf.Variable(tf.zeros(layer_depth.get('L4')), name='fullc2_b')\r\n fullc2 = tf.matmul(fullc1, fullc2_w) + fullc2_b\r\n fullc2 = tf.nn.relu(fullc2)\r\n fullc2 = tf.nn.dropout(fullc2, keep_prob)\r\n\r\n # L5: Fully-connected ~ (64) -> (10)\r\n fullc3_w = tf.Variable(tf.truncated_normal(shape=(layer_depth.get('L4'), layer_depth.get('L5')), mean=mu, stddev=sigma), name='fullc3_w')\r\n fullc3_b = tf.Variable(tf.zeros(layer_depth.get('L5')), name='fullc3_b')\r\n logits = tf.matmul(fullc2, fullc3_w) + fullc3_b # output\r\n\r\n return logits\r\n\r\n\r\ndef loss(y, t):\r\n return tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=t))\r\n\r\n\r\ndef train_step(loss):\r\n return tf.train.AdamOptimizer(1e-3).minimize(loss)\r\n\r\n\r\ndef accuracy(y, t):\r\n return tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y, 1), tf.argmax(t, 1)), tf.float32))\r\n\r\n\r\nif __name__ == '__main__':\r\n # Getting data =====================================================================================================\r\n mnist = input_data.read_data_sets(\"MNIST_data/\", reshape=False)\r\n X_train, Y_train = mnist.train.images, mnist.train.labels\r\n X_validation, Y_validation = mnist.validation.images, mnist.validation.labels\r\n X_test, Y_test = mnist.test.images, mnist.test.labels\r\n '''\r\n print(\"Image Shape: {}\".format(X_train[0].shape)) # (28, 28, 1)\r\n print(\"Image Shape: {}\".format(Y_train[0].shape)) # ()\r\n print(\"Training Set: {} samples\".format(len(X_train))) # 55000\r\n print(\"Validation Set: {} samples\".format(len(X_validation))) # 5000\r\n print(\"Test Set: {} samples\".format(len(X_test))) # 10000\r\n '''\r\n # Getting random N training data\r\n n = len(X_train)\r\n N = 30000\r\n indices = np.random.permutation(range(n))[:N]\r\n X_train = X_train[indices]\r\n Y_train = Y_train[indices]\r\n # Adding the padding to the dataset\r\n X_train = np.pad(X_train, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant') # constant(default): 0\r\n X_validation = np.pad(X_validation, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\r\n X_test = np.pad(X_test, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\r\n\r\n # Seting model =====================================================================================================\r\n x = tf.placeholder(tf.float32, shape=[None, 32, 32, 1])\r\n t = tf.placeholder(tf.int32, shape=[None])\r\n one_hot_t = tf.one_hot(t, 10)\r\n keep_prob = tf.placeholder(tf.float32)\r\n y = lenet(x)\r\n loss = loss(y, one_hot_t)\r\n train_step = train_step(loss)\r\n accuracy = accuracy(y, one_hot_t)\r\n\r\n # Training and evaluating model ====================================================================================\r\n '''\r\n # 1.Store(Train) ---------------------------------------------------------------------------------------------------\r\n init = tf.global_variables_initializer()\r\n saver = tf.train.Saver()\r\n sess = tf.Session()\r\n sess.run(init)\r\n epochs = 25\r\n batch_size = 200\r\n n_batches = N // batch_size\r\n for epoch in range(epochs):\r\n X_, Y_ = shuffle(X_train, Y_train)\r\n for i in range(n_batches):\r\n start = i * batch_size\r\n end = start + batch_size\r\n sess.run(train_step, feed_dict={x: X_[start:end], t: Y_[start:end], keep_prob: 0.8})\r\n val_loss = loss.eval(session=sess, feed_dict={x: X_, t: Y_, keep_prob: 1.0})\r\n val_acc = accuracy.eval(session=sess, feed_dict={x: X_, t: Y_, keep_prob: 1.0})\r\n print('epoch:', epoch+1, ' loss:', val_loss, ' accuracy:', val_acc)\r\n val_acc_v = accuracy.eval(session=sess, feed_dict={x: X_validation, t: Y_validation, keep_prob: 1.0})\r\n val_acc_t = accuracy.eval(session=sess, feed_dict={x: X_test, t: Y_test, keep_prob: 1.0})\r\n print()\r\n print('validation accuracy: {:.4f}'.format(val_acc_v))\r\n print('test accuracy: {:.4f}'.format(val_acc_t))\r\n print()\r\n model_path = saver.save(sess, MODEL_DIR + './model.ckpt')\r\n print('Model saved to:', model_path)\r\n print()\r\n '''\r\n # 2.Restore --------------------------------------------------------------------------------------------------------\r\n saver = tf.train.Saver()\r\n sess = tf.Session()\r\n saver.restore(sess, MODEL_DIR + '/model.ckpt')\r\n val_acc_v = accuracy.eval(session=sess, feed_dict={x: X_validation, t: Y_validation, keep_prob: 1.0})\r\n val_acc_t = accuracy.eval(session=sess, feed_dict={x: X_test, t: Y_test, keep_prob: 1.0})\r\n print()\r\n print('validation accuracy: {:.4f}'.format(val_acc_v))\r\n print('test accuracy: {:.4f}'.format(val_acc_t))\r\n print()\r\n # when (epochs, batch_size, keep_drop) is (25, 200, 0.8), (validation accuracy, test accuracy) is (0.9892, 0.9891)\r\n\r\n\r\n########################################################################################################################\r\n# Generative classifier ================================================================================================\r\n########################################################################################################################\r\nN = len(X_train) # the number of training data(x[i]): 30000\r\nf_of_x = np.array(sess.run(fullc2, feed_dict={x: X_train, keep_prob: 1.0})) # the output of the layer of x[i]: f(x[i])\r\nlabel_of_x = np.array(sess.run(tf.argmax(y, 1), feed_dict={x: X_train, keep_prob: 1.0})) # classified label of x[i]\r\nnum_of_labels = 10 # number of labels: 10(MNIST)\r\nnum_of_neurons = len(f_of_x[0]) # number of neurons(dimensions) in the layer: 64\r\nk = 2 # the number of K means\r\n\r\n# Data(data[j][k]: (k+1)th f(x) of label j): distinguishing f(x[i]) by its label ---------------------------------------\r\ntemp = [None] * num_of_labels\r\nfor label in range(num_of_labels):\r\n temp[label] = list() # making temporary list to use list.append\r\nfor i in range(N):\r\n temp[label_of_x[i]].append(f_of_x[i])\r\ndata = np.array(temp) # changing the list to numpy array for numpy operation\r\n\r\ntemp = [None] * k * num_of_labels\r\nfor label in range(k * num_of_labels):\r\n temp[label] = list()\r\nfor label in range(num_of_labels):\r\n t_sne_data = TSNE(learning_rate=100).fit_transform(data[label]) # dimension reduction using t-SNE\r\n data_frame = pd.DataFrame(t_sne_data, columns=('x', 'y')) # making 2-dimensional data frame by t-SNE data\r\n data_points = data_frame.values\r\n k_means_data = KMeans(n_clusters=k).fit(data_points) # k-means clustering\r\n data_frame['cluster_id'] = k_means_data.labels_ # labeling the cluster id of data frame\r\n #sns.lmplot('x', 'y', data=data_frame, fit_reg=False, scatter_kws={\"s\": 500}, hue=\"cluster_id\")\r\n #plt.title('K-mean plot')\r\n #plt.xlabel('x')\r\n #plt.ylabel('y')\r\n #plt.show()\r\n data_frame = np.array(data_frame)\r\n for i in range(len(data[label])):\r\n temp[k * label + int(data_frame[i][2])].append(data[label][i])\r\ndata2 = np.array(temp)\r\nnum_of_labels_split = k * num_of_labels\r\ndata_split = data2\r\n\r\n# Mu_hat(mean vector for each label, mu_hat[j] = mean of f(x[i]) in label j): calculating mean of the data in each label\r\nmu_hat = [np.zeros(num_of_neurons)] * num_of_labels\r\nfor label in range(num_of_labels):\r\n mu_hat[label] = np.mean(data[label], axis=0)\r\n\r\nmu_hat_split = [np.zeros(num_of_neurons)] * num_of_labels_split\r\nfor label in range(num_of_labels_split):\r\n mu_hat_split[label] = np.mean(data_split[label], axis=0)\r\n\r\n# Sigma_hat(tied covariance of the distribution of f(x[i]): applying outer-product to all data and calculate the mean --\r\nsigma_hat = np.zeros([num_of_neurons, num_of_neurons])\r\nfor label in range(num_of_labels):\r\n for datum in data[label]:\r\n u = np.reshape(datum, (num_of_neurons, 1))\r\n v = np.reshape(mu_hat[label], (num_of_neurons, 1))\r\n sigma_hat += np.matmul((u - v), (u - v).T)\r\nsigma_hat_split = np.zeros([num_of_neurons, num_of_neurons])\r\nfor label in range(num_of_labels_split):\r\n for datum in data_split[label]:\r\n u = np.reshape(datum, (num_of_neurons, 1))\r\n v = np.reshape(mu_hat_split[label], (num_of_neurons, 1))\r\n sigma_hat_split += np.matmul((u - v), (u - v).T)\r\n\r\nsigma_hat = sigma_hat / N\r\nsigma_hat_split = sigma_hat_split / N\r\n\r\nlinalg = np.linalg.inv(sigma_hat)\r\nlinalg_split = np.linalg.inv(sigma_hat_split)\r\n\r\n# M(E)_dist_data(m(e)_dist_data[j][k]: (k+1)th Mahalanobis(Euclidean) distance data of label j) ------------------------\r\ntemp = [None] * num_of_labels\r\nfor label in range(num_of_labels):\r\n temp[label] = list()\r\nfor label in range(num_of_labels):\r\n for datum in data[label]:\r\n u = np.reshape(datum, (1, num_of_neurons))\r\n v = np.reshape(mu_hat[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg) ** 2)\r\n# e_dist_data = np.array(temp)\r\nm_dist_data = np.array(temp)\r\n\r\ntemp = [None] * num_of_labels_split\r\nfor label in range(num_of_labels_split):\r\n temp[label] = list()\r\nfor label in range(num_of_labels_split):\r\n for datum in data_split[label]:\r\n u = np.reshape(datum, (1, num_of_neurons))\r\n v = np.reshape(mu_hat_split[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg_split) ** 2)\r\n# e_dist_data_split = np.array(temp)\r\nm_dist_data_split = np.array(temp)\r\n\r\n# Max(distance threshold, max_dist_data[j] = Mahalanobis(Euclidean) distance threshold of label j) ---------------------\r\ntemp = [None] * num_of_labels\r\nfor label in range(num_of_labels):\r\n temp[label] = list()\r\nfor label in range(num_of_labels):\r\n # temp[label].append(np.percentile(e_dist_data[label], 95, interpolation='linear'))\r\n temp[label].append(np.percentile(m_dist_data[label], 95, interpolation='linear'))\r\nmax_dist_data = np.array(temp)\r\n\r\ntemp = [None] * num_of_labels_split\r\nfor label in range(num_of_labels_split):\r\n temp[label] = list()\r\nfor label in range(num_of_labels_split):\r\n # temp[label].append(np.percentile(e_dist_data_split[label], 95, interpolation='linear'))\r\n temp[label].append(np.percentile(m_dist_data_split[label], 95, interpolation='linear'))\r\nmax_dist_data_split = np.array(temp)\r\n\r\n# Histogram for each label's Mahalanobis(Euclidean) distance distribution ----------------------------------------------\r\n'''\r\nfor label in range(num_of_labels):\r\n # data = np.sort(e_dist_data[label])\r\n data = np.sort(m_dist_data[label])\r\n bins = np.arange(0, 300, 2)\r\n plt.hist(data, bins, normed=True)\r\n plt.title(\"label: %d\" % label)\r\n plt.xlabel('distance', fontsize=15)\r\n plt.ylabel('num of data', fontsize=15)\r\n plt.show(block=True)\r\n'''\r\n\r\n\r\n########################################################################################################################\r\n# Receiver operating characteristic curve ==============================================================================\r\n########################################################################################################################\r\nthreshold = -2.8 # threshold variable for Mahalanobis(Euclidean) distance-based confidence score\r\nood_index = -1 # giving label -1 to out-of-distribution data\r\n\r\nfp = open(\"0918M_log.txt\",'w')\r\n\r\nroc_x_em = []\r\nroc_x_em_split = []\r\nroc_x_notm = []\r\nroc_x_notm_split = []\r\nroc_y = []\r\nroc_y_split = []\r\n\r\n# Mnist\r\nN_test = len(X_test) # 10000\r\nf_of_x_test = np.array(sess.run(fullc2, feed_dict={x: X_test, keep_prob: 1.0}))\r\ntarget_label_of_x_test = Y_test\r\n\r\n# EMnist\r\nf = gz.open('EMNIST_data/emnist-letters-train-images-idx3-ubyte.gz', 'r') # EMNIST dataset for out-of-distribution data\r\nf.read(16)\r\nbuf = f.read(28 * 28 * 10000)\r\nemnist_test = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)\r\nemnist_test = emnist_test.reshape([10000, 28, 28, 1])\r\nemnist_test = emnist_test / 255.0 # scaling from 0.0 ~ 255.0 to 0.0 ~ 1.0\r\nX_ood1 = emnist_test\r\nN_ood1 = len(X_ood1) # 10000\r\n'''\r\n# Calibration techniques -----------------------------------------------------------------------------------------------\r\nfor i in range(N_ood):\r\n for j in range(3):\r\n X_ood1[i] = util.random_noise(X_ood1[i], mode='pepper', clip=True) # Adding the noise to dataset\r\n'''\r\n\r\nX_ood1 = np.pad(X_ood1, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant') # Adding the padding to the dataset\r\nf_of_x_ood1 = np.array(sess.run(fullc2, feed_dict={x: X_ood1, keep_prob: 1.0}))\r\n\r\n# NOTMnist\r\nwith open('NOTMNIST_data/notMNIST.pickle', 'rb') as file: # NOTMNIST dataset for out-of-distribution data\r\n data_list = []\r\n while True:\r\n try:\r\n data = pickle.load(file)\r\n except EOFError:\r\n break\r\n data_list.append(data)\r\nnotmnist_test = data_list[0]['test_dataset']\r\nnotmnist_test = notmnist_test.reshape([10000, 28, 28, 1])\r\nnotmnist_test = notmnist_test + 0.5 # scaling from -0.5 ~ 0.5 to 0.0 ~ 1.0\r\nX_ood2 = notmnist_test\r\nN_ood2 = len(X_ood2) # 10000\r\n\r\nfor i in range(N_ood2):\r\n for j in range(3):\r\n X_ood2[i] = util.random_noise(X_ood2[i], mode='pepper', clip=True) # Adding the noise to dataset\r\n\r\nX_ood2 = np.pad(X_ood2, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant') # Adding the padding to the dataset\r\nf_of_x_ood2 = np.array(sess.run(fullc2, feed_dict={x: X_ood2, keep_prob: 1.0}))\r\n\r\n\r\n\r\nstart_time = time.time()\r\nfor threshold in range(-150, 150, 10):\r\n # TPR on in-distribution(MNIST test dataset) ---------------------------------------------------------------------------\r\n label_of_x_test = np.array(range(N_test))\r\n for i in range(N_test):\r\n temp = [None] * num_of_labels\r\n for label in range(num_of_labels):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_test[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg) ** 2)\r\n dist_data_of_x_test = np.array(temp)\r\n index = np.argmin(dist_data_of_x_test, 0) # finding index of the closest label\r\n confidence_score_of_x_test = max_dist_data[index] - dist_data_of_x_test[index] # computing confidence score\r\n if confidence_score_of_x_test > threshold:\r\n label_of_x_test[i] = index # classifying as in-distribution data\r\n else:\r\n label_of_x_test[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution = 0\r\n num_of_correctly_classified = 0\r\n accuracy_on_in_distribution = 0.0\r\n for i in range(N_test):\r\n if label_of_x_test[i] != ood_index:\r\n num_of_in_distribution = num_of_in_distribution + 1\r\n if label_of_x_test[i] == target_label_of_x_test[i]:\r\n num_of_correctly_classified = num_of_correctly_classified + 1\r\n accuracy_on_in_distribution = num_of_correctly_classified / num_of_in_distribution\r\n tpr = num_of_in_distribution / N_test\r\n roc_y.append(tpr)\r\n print('Classification accuracy on in-distribution: {:.4f}'.format(accuracy_on_in_distribution))\r\n print('TPR on in-distribution(MNIST): {:.4f}'.format(tpr), end='\\n')\r\n\r\n # TPR on in-distribution(MNIST test dataset, split) ---------------------------------------------------------------------------\r\n label_of_x_test = np.array(range(N_test))\r\n for i in range(N_test):\r\n temp = [None] * num_of_labels_split\r\n for label in range(num_of_labels_split):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_test[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat_split[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg_split) ** 2)\r\n dist_data_of_x_test = np.array(temp)\r\n index = np.argmin(dist_data_of_x_test, 0) # finding index of the closest label\r\n confidence_score_of_x_test = max_dist_data_split[index] - dist_data_of_x_test[index] # computing confidence score\r\n if confidence_score_of_x_test > threshold:\r\n label_of_x_test[i] = index // k # classifying as in-distribution data\r\n else:\r\n label_of_x_test[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution = 0\r\n num_of_correctly_classified = 0\r\n accuracy_on_in_distribution = 0.0\r\n for i in range(N_test):\r\n if label_of_x_test[i] != ood_index:\r\n num_of_in_distribution = num_of_in_distribution + 1\r\n if label_of_x_test[i] == target_label_of_x_test[i]:\r\n num_of_correctly_classified = num_of_correctly_classified + 1\r\n accuracy_on_in_distribution = num_of_correctly_classified / num_of_in_distribution\r\n tpr_split = num_of_in_distribution / N_test\r\n roc_y_split.append(tpr_split)\r\n\r\n # FPR on out-of-distribution 1(EMNIST dataset) -------------------------------------------------------------------------\r\n label_of_x_ood1 = np.array(range(N_ood1))\r\n for i in range(N_ood1):\r\n temp = [None] * num_of_labels\r\n for label in range(num_of_labels):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_ood1[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg) ** 2)\r\n dist_data_of_x_ood1 = np.array(temp)\r\n index = np.argmin(dist_data_of_x_ood1, 0) # finding index of the closest label\r\n confidence_score_of_x_ood1 = max_dist_data[index] - dist_data_of_x_ood1[index] # computing confidence score\r\n if confidence_score_of_x_ood1 > threshold:\r\n label_of_x_ood1[i] = index # classifying as in-distribution data\r\n else:\r\n label_of_x_ood1[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution1 = 0\r\n for i in range(N_ood1):\r\n if label_of_x_ood1[i] != ood_index:\r\n num_of_in_distribution1 = num_of_in_distribution1 + 1\r\n fpr1 = num_of_in_distribution1 / N_ood1\r\n roc_x_em.append(fpr1)\r\n print('FPR on out-of-distribution(ENMIST): {:.4f}'.format(fpr1), end='\\n')\r\n\r\n # FPR on out-of-distribution 1(EMNIST dataset, split) -------------------------------------------------------------------------\r\n label_of_x_ood1 = np.array(range(N_ood1))\r\n for i in range(N_ood1):\r\n temp = [None] * num_of_labels_split\r\n for label in range(num_of_labels_split):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_ood1[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat_split[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg_split) ** 2)\r\n dist_data_of_x_ood1 = np.array(temp)\r\n index = np.argmin(dist_data_of_x_ood1, 0) # finding index of the closest label\r\n confidence_score_of_x_ood1 = max_dist_data_split[index] - dist_data_of_x_ood1[index] # computing confidence score\r\n if confidence_score_of_x_ood1 > threshold:\r\n label_of_x_ood1[i] = index // k # classifying as in-distribution data\r\n else:\r\n label_of_x_ood1[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution1 = 0\r\n for i in range(N_ood1):\r\n if label_of_x_ood1[i] != ood_index:\r\n num_of_in_distribution1 = num_of_in_distribution1 + 1\r\n fpr1_split = num_of_in_distribution1 / N_ood1\r\n roc_x_em_split.append(fpr1_split)\r\n\r\n # FPR on out-of-distribution 2(NOTMNIST dataset) -----------------------------------------------------------------------\r\n label_of_x_ood2 = np.array(range(N_ood2))\r\n for i in range(N_ood2):\r\n temp = [None] * num_of_labels\r\n for label in range(num_of_labels):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_ood2[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg) ** 2)\r\n dist_data_of_x_ood2 = np.array(temp)\r\n index = np.argmin(dist_data_of_x_ood2, 0) # finding index of the closest label\r\n confidence_score_of_x_ood2 = max_dist_data[index] - dist_data_of_x_ood2[index] # computing confidence score\r\n if confidence_score_of_x_ood2 > threshold:\r\n label_of_x_ood2[i] = index # classifying as in-distribution data\r\n else:\r\n label_of_x_ood2[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution2 = 0\r\n for i in range(N_ood2):\r\n if label_of_x_ood2[i] != ood_index:\r\n num_of_in_distribution2 = num_of_in_distribution2 + 1\r\n fpr2 = num_of_in_distribution2 / N_ood2\r\n roc_x_notm.append(fpr2)\r\n print('FPR on out-of-distribution(NOTMNIST): {:.4f}'.format(fpr2), end='\\n')\r\n\r\n # FPR on out-of-distribution 1(NOTMNIST dataset, split) -------------------------------------------------------------------------\r\n label_of_x_ood2 = np.array(range(N_ood2))\r\n for i in range(N_ood2):\r\n temp = [None] * num_of_labels_split\r\n for label in range(num_of_labels_split):\r\n temp[label] = list()\r\n u = np.reshape(f_of_x_ood2[i], (1, num_of_neurons))\r\n v = np.reshape(mu_hat_split[label], (1, num_of_neurons))\r\n # temp[label].append(distance.euclidean(u, v, None) ** 2)\r\n temp[label].append(distance.mahalanobis(u, v, linalg_split) ** 2)\r\n dist_data_of_x_ood2 = np.array(temp)\r\n index = np.argmin(dist_data_of_x_ood2, 0) # finding index of the closest label\r\n confidence_score_of_x_ood2 = max_dist_data_split[index] - dist_data_of_x_ood2[index] # computing confidence score\r\n if confidence_score_of_x_ood2 > threshold:\r\n label_of_x_ood2[i] = index // k # classifying as in-distribution data\r\n else:\r\n label_of_x_ood2[i] = ood_index # classifying as out-of-distribution data\r\n num_of_in_distribution2 = 0\r\n for i in range(N_ood2):\r\n if label_of_x_ood2[i] != ood_index:\r\n num_of_in_distribution2 = num_of_in_distribution2 + 1\r\n fpr2_split = num_of_in_distribution2 / N_ood2\r\n roc_x_notm_split.append(fpr2_split)\r\n repeat_time = time.time()\r\n print('Time: {:.2f}s'.format(repeat_time - start_time))\r\n print('Threshold: {}\\n'.format(threshold))\r\n\r\nplt.figure()\r\nplt.plot(roc_x_em, roc_y, color='red', label='emnist')\r\nplt.plot(roc_x_notm, roc_y, color='blue', label='notmnist')\r\nplt.plot(roc_x_em_split, roc_y_split, color='green', label='emnist(split)')\r\nplt.plot(roc_x_notm_split, roc_y_split, color='black', label='notmnist(split)')\r\nplt.title(\"ROC curve\")\r\nplt.xticks([0, 0.5, 1])\r\nplt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])\r\nplt.xlabel(\"FPR on out-of-distribution\")\r\nplt.ylabel(\"TPR on in-distribution (mnist)\")\r\nplt.xlim([0,1])\r\nplt.ylim([0,1])\r\nplt.legend()\r\nplt.show()\r\nfp.close()\r\n\r\n\r\n\r\n\r\n\r\n# Euclidean classifier ROC curve data ----------------------------------------------------------------------------------\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = (-(INF), 1.0000, 1.0000, 1.0000)\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = (-150.0, 0.9998, 0.9976, 0.9909)\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR-NOTMNIST) = ( -50.0, 0.9864, 0.7149, 0.5090)\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR-NOTMNIST) = ( -4.3, 0.9500, 0.3661, 0.2219)\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR-NOTMNIST) = ( 17.4, 0.9000, 0.2313, 0.1227)\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR-NOTMNIST) = ( 29.0, 0.8500, 0.1720, )\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR-NOTMNIST) = ( 36.5, 0.8000, 0.1392, )\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( 41.7, 0.7500, 0.1201, )\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( ... , 0. ..., 0. ..., 0. ...)\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( 150.0, 0.0233, 0.0004, 0.0001)\r\n# (threshold, TPR-MNIST, FPR-EMNIST, FPR_NOTMNIST) = ( 170.0, 0.0021, 0.0000, 0.0000)\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR_NOTMNIST) = ( (INF), 0.0000, 0.0000, 0.0000)\r\n\r\n# Mahalanobis classifier ROC curve data 1 ------------------------------------------------------------------------------\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = (-(INF), 1.0000, 1.0000, 1.0000)\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( ... , 0. ..., 0. ..., 0. ...)\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( (INF), 0.0000, 0.0000, 0.0000)\r\n\r\n# Mahalanobis classifier ROC curve data 2(Calibration technique - Input pre-processing) --------------------------------\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = (-(INF), 1.0000, 1.0000, 1.0000)\r\n# (threshold, TPR-MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( ... , 0. ..., 0. ..., 0. ...)\r\n# (threshold, TPR_MNIST, FPR_EMNIST, FPR-NOTMNIST) = ( (INF), 0.0000, 0.0000, 0.0000)","sub_path":"20190918.py","file_name":"20190918.py","file_ext":"py","file_size_in_byte":29094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"79934973","text":"from decimal import Decimal\nfrom random import choice, random\nfrom math import sqrt, asin, acos, atan, sin, cos, tan, pi\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport json\nimport time\n\n\nG = Decimal('6.67408e-11') # gravitational constant (m3*kg-1*s-2)\nKe = Decimal('8.9875517873681764e9') # Coulomb's constant (N*m2*C-2)\nu = Decimal('1.660539040e-27') # atomic mass unit (kilograms)\ne = Decimal('1.6021766e-19') # elementary charge (Coulomb)\neV = Decimal('1.6021766e-19') # electronvolt (Joule)\ndelta_t = Decimal('100e-22') # seconds\n\n\nparticles = set()\n\n\nclass Particle:\n def __init__(self,\n position=(Decimal('0'), Decimal('0'), Decimal('0')),\n mass=u,\n charge=Decimal('0'),\n velocity=(Decimal('0'), Decimal('0'), Decimal('0'))):\n particles.add(self)\n self.position = position\n self.mass = mass\n # self.radius = Decimal('0.8751e-15')\n self.charge = charge\n # self.energy_goal = 13 * eV\n self.velocity = velocity\n\n\ndef simulation():\n def coulombs_law(c1, c2, r):\n if r != 0:\n F = Decimal(Ke*c1*c2/(r*r))\n else:\n F = None\n return F\n\n def gravitional_force(m1, m2, r):\n if r != 0:\n F = Decimal(G*m1*m2/(r*r))\n else:\n F = None\n return F\n\n def get_angle(a=None, o=None, s=None):\n angle = None\n if a is not None and o is not None:\n if a == 0:\n if o == 0:\n angle = Decimal('0')\n elif o > 0:\n angle = Decimal(0.5 * pi)\n elif o < 0:\n angle = Decimal((-0.5) * pi)\n elif o == 0:\n if a > 0:\n angle = Decimal('0')\n elif a < 0:\n angle = Decimal(pi)\n else:\n angle = Decimal(atan(o/a))\n if a < 0:\n angle += Decimal(pi)\n if angle is not None:\n if angle < 0:\n angle += Decimal(pi)\n return angle\n else:\n raise ValueError\n\n data = dict()\n for particle in particles:\n data[particle] = dict()\n data[particle]['positions'] = list()\n data[particle]['velocities'] = list()\n\n for _ in range(300):\n for particle in particles:\n current_x, current_y, current_z = particle.position\n current_v_x, current_v_y, current_v_z = particle.velocity\n\n # calculate the next position of the particle:\n for other_particle in particles:\n if other_particle != particle:\n other_x, other_y, other_z = other_particle.position\n dx, dy, dz = other_x-current_x, other_y-current_y, other_z-current_z\n distance = Decimal(sqrt(dx*dx + dy*dy + dz*dz))\n\n fg = gravitional_force(particle.mass, other_particle.mass, distance)\n fe = -coulombs_law(particle.charge, other_particle.charge, distance)\n f_tot = fg + fe\n f_x = dx / distance * f_tot\n f_y = dy / distance * f_tot\n f_z = dz / distance * f_tot\n a_x, a_y, a_z = f_x/particle.mass, f_y/particle.mass, f_z/particle.mass\n delta_v_x, delta_v_y, delta_v_z = a_x*delta_t, a_y*delta_t, a_z*delta_t\n\n current_v_x += delta_v_x\n current_v_y += delta_v_y\n current_v_z += delta_v_z\n\n next_x = Decimal(current_x + current_v_x * delta_t)\n next_y = Decimal(current_y + current_v_y * delta_t)\n next_z = Decimal(current_z + current_v_z * delta_t)\n particle.next_position = (next_x, next_y, next_z)\n particle.next_velocity = (current_v_x, current_v_y, current_v_z)\n\n # applying all the calculated positions to the particle\n for particle in particles:\n particle.position = particle.next_position\n particle.velocity = particle.next_velocity\n\n current_x, current_y, current_z = particle.position\n data[particle]['positions'].append((float(current_x*Decimal('1e12')),\n float(current_y*Decimal('1e12')),\n float(current_z*Decimal('1e12'))))\n return data\n\n\ndef plot_3d(data):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n for key in data:\n xs = list()\n ys = list()\n zs = list()\n for x, y, z in data[key]['positions']:\n xs.append(float(x))\n ys.append(float(y))\n zs.append(float(z))\n ax.scatter(xs, ys, zs)\n plt.show()\n\n\n# create hydrogen atom:\ndef create_atom(mass, charge, position=(Decimal('0'), Decimal('0'), Decimal('0'))):\n Particle(position=position,\n mass=mass,\n charge=charge,\n velocity=(Decimal('0'), Decimal('0'), Decimal('0')))\n\n\n# create electron:\ndef create_electron():\n x = choice('+-') + choice('0123456789') + 'e-12'\n y = choice('+-') + choice('0123456789') + 'e-12'\n z = choice('+-') + choice('0123456789') + 'e-12'\n vx = choice('+-') + choice('0123456789') + 'e6'\n vy = choice('+-') + choice('0123456789') + 'e6'\n vz = choice('+-') + choice('0123456789') + 'e6'\n print('electron:')\n print(' pos: ' + x + ', ' + y + ', ' + z)\n print(' vel: ' + vx + ', ' + vy + ', ' + vz)\n Particle(position=(Decimal(x), Decimal(y), Decimal(z)),\n mass=Decimal('5.4857991e-4') * u,\n charge=-e,\n velocity=(Decimal(vx), Decimal(vy), Decimal(vz)))\n\n\ncreate_atom(Decimal('1.00782504')*u, e)\ncreate_atom(Decimal('1.00782504')*u, e, position=(Decimal('0'), Decimal('50e-12'), Decimal('0')))\ncreate_electron()\ncreate_electron()\n\ndata = simulation()\njson_data = list()\nfor key in data:\n json_data.append(data[key])\nwith open('files/esim_data/version2.0/' + str(time.time()) + '.json', 'w') as jsonfile:\n json.dump(json_data, jsonfile, separators=(',', ':'), indent=4)\nplot_3d(data)\n","sub_path":"pychem/particlesim/electron_simulation.py","file_name":"electron_simulation.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"475928504","text":"from flask import Flask\nfrom flask import render_template, abort, jsonify, request, redirect, json\nfrom ML2 import analyzer\napp = Flask(__name__)\napp.debug = True\n\n@app.route('/')\n@app.route(\"/index\")\ndef index():\n return render_template('index.html')\n\n@app.route('/learning', methods=['POST'])\ndef learning():\n #loads requested data sent form frontend\n data = json.loads(request.data)\n response = analyzer(data)\n print(\"Arrived back to Server\")\n print(jsonify(response))\n return jsonify(response)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)","sub_path":"flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"426261532","text":"#coding=utf-8\n\"\"\"\n此文件定义武器的品质\n武器的品质类型,分为\n 普通:plain, 颜色:white\n 精良:polish, 颜色:green\n 稀有:rare, 颜色:blue\n 精英:elite, 颜色:purple:\n 史诗:epic, 颜色:orange\n 传说:legendary, 颜色:darkgolden (暂时不提供)\n\"\"\"\nimport random\n\nfrom settings.charspec import AttrWord\nfrom settings.general import Color\n\n\nclass QualityName(object):\n PLAIN = \"普通\"\n POLISH = \"高级\"\n RARE = \"稀有\"\n ELITE = \"精英\"\n EPIC = \"史诗\"\n\nqualities = [\"plain\", \"polish\", \"rare\", \"elite\", \"epic\"]\n\nclass Quality():\n ID = 0\n NAME = QualityName.PLAIN\n COLOR = Color.WHITE\n WORDS= None\n\n def __init__(self):\n self.id = self.ID\n self.name = self.NAME\n self.color = self.COLOR\n self.words = self.WORDS\n\n def getName(self):\n return self.name\n\n def getId(self):\n return self.id\n\n def getColor(self):\n return self.color\n\n def getWords(self):\n return self.words\n\n\nclass PlainWeapon(Quality):\n ID = 1\n NAME = QualityName.PLAIN\n COLOR = Color.WHITE\n WORDS = {AttrWord.DAMAGE: 0,\n AttrWord.AGILITY: 0,\n AttrWord.ATTACK_SPEED: 0,\n AttrWord.CRITIAL_HIT: 0,\n AttrWord.HIT: 0,\n AttrWord.PARRY: 0,\n AttrWord.STAMINA: 0,\n AttrWord.STRENGTH: 0}\n\n\nclass PolishWeapon(Quality):\n ID = 2\n NAME = QualityName.POLISH\n COLOR = Color.GREEN\n WORDS = {AttrWord.DAMAGE: 20,\n AttrWord.AGILITY: 10,\n AttrWord.ATTACK_SPEED: 0,\n AttrWord.CRITIAL_HIT: 0,\n AttrWord.HIT: 20,\n AttrWord.PARRY: 20,\n AttrWord.STAMINA: 5,\n AttrWord.STRENGTH: 20}\n\nclass RareWeapon(Quality):\n ID = 3\n NAME = QualityName.RARE\n COLOR = Color.BLUE\n WORDS = {AttrWord.DAMAGE: 30,\n AttrWord.AGILITY: 20,\n AttrWord.ATTACK_SPEED: 2,\n AttrWord.CRITIAL_HIT: 2,\n AttrWord.HIT: 30,\n AttrWord.PARRY: 30,\n AttrWord.STAMINA: 15,\n AttrWord.STRENGTH: 30}\n\nclass EliteWeapon(Quality):\n ID = 4\n NAME = QualityName.ELITE\n COLOR = Color.PURPLE\n WORDS = {AttrWord.DAMAGE: 40,\n AttrWord.AGILITY: 30,\n AttrWord.ATTACK_SPEED: 5,\n AttrWord.CRITIAL_HIT: 5,\n AttrWord.HIT: 40,\n AttrWord.PARRY: 40,\n AttrWord.STAMINA: 25,\n AttrWord.STRENGTH: 40}\n\nclass EpicWeapon(Quality):\n ID = 5\n NAME = QualityName.EPIC\n COLOR = Color.ORANGE\n WORDS = {AttrWord.DAMAGE: 50,\n AttrWord.AGILITY: 40,\n AttrWord.ATTACK_SPEED: 10,\n AttrWord.CRITIAL_HIT: 10,\n AttrWord.HIT: 50,\n AttrWord.PARRY: 50,\n AttrWord.STAMINA: 35,\n AttrWord.STRENGTH: 50}\n\n\n","sub_path":"mygame/settings/quality.py","file_name":"quality.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456908882","text":"import random\r\nimport sys\r\n\r\n\r\ndef czy_koniec(haslo_gw, haslo, zycia):\r\n wyswietl_haslo = \"\"\r\n if haslo_gw == haslo:\r\n while True:\r\n wybor = input(\"Gratulacje! Odszyfrowales haslo: '\" + wyswietl_haslo.join(haslo) + \"'.Czy chcesz zagrac ponownie?(y/n)? \")\r\n if wybor == 'y':\r\n return True\r\n elif wybor == 'n':\r\n sys.exit()\r\n else:\r\n print(\"Niewlasciwy znak, wpisz y lub n i zatwierdz naciskajac klawisz enter\")\r\n\r\n if zycia == 0:\r\n while True:\r\n wybor = input(\"Przegrales! Skonczyly Ci sie zycia. Haslo brzmialo: '\" + wyswietl_haslo.join(haslo) + \"'.Czy chcesz zagrac ponownie?(y/n)? \")\r\n if wybor == 'y':\r\n return True\r\n elif wybor == 'n':\r\n sys.exit()\r\n else:\r\n print(\"Niewlasciwy znak, wpisz y lub n i zatwierdz naciskajac klawisz enter\")\r\n\r\ndef generuj_slowo():\r\n lista = [\"maciek\", \"karol\", \"pawel\", \"rydwan\", \"barbara\", \"grupa\", \"auto\", \"krzeslo\"]\r\n return random.choice(lista)\r\n\r\ndef gwiazdkowanie(haslo):\r\n haslo_gw = []\r\n for i in range(len(haslo)):\r\n haslo_gw.append(\"*\")\r\n\r\n return haslo_gw\r\n\r\ndef main():\r\n print(\"Witaj w grze!\")\r\n haslo = generuj_slowo()\r\n #print(list(haslo))\r\n haslo_gwiazdki = gwiazdkowanie(haslo)\r\n zycia = len(haslo)-2\r\n while True:\r\n znaleziono_litere = False\r\n print(haslo_gwiazdki)\r\n print(\"zycia:\", zycia)\r\n litera = input(\"Podaj litere: \")\r\n\r\n for i in range(len(haslo)):\r\n if haslo[i] == litera:\r\n haslo_gwiazdki[i] = litera\r\n znaleziono_litere = True\r\n\r\n if znaleziono_litere == False:\r\n zycia -= 1\r\n\r\n if czy_koniec(haslo_gwiazdki, list(haslo), zycia) == True:\r\n break\r\n\r\nwhile True:\r\n main()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365104072","text":"from tkinter import *\r\nimport time\r\nimport tempfile\r\nimport base64, zlib\r\n\r\nDoRound = True\r\n\r\nAM = {\"H\" : 1.008, \"He\" : 4.003, \"Li\" : 6.941, \"Be\" : 9.012, \r\n\t\"B\" : 10.811, \"C\" : 12.011, \"N\" : 14.007, \"O\" : 15.999, \r\n\t\"F\" : 18.998, \"Ne\" : 20.180, \"Na\" : 22.990, \"Mg\" : 24.305, \r\n\t\"Al\" : 26.982, \"Si\" : 28.086, \"P\" : 30.974, \"S\" : 32.066, \r\n\t\"Cl\" : 35.453, \"Ar\" : 39.948, \"K\" : 39.098, \"Ca\" : 40.078, \r\n\t\"Sc\" : 44.956, \"Ti\" : 47.867, \"V\" : 50.942, \"Cr\" : 51.996, \r\n\t\"Mn\" : 54.938, \"Fe\" : 55.845, \"Co\" : 58.933, \"Ni\" : 58.693, \r\n\t\"Cu\" : 63.546, \"Zn\" : 65.380, \"Ga\" : 69.732, \"Ge\" : 72.631, \r\n\t\"As\" : 74.922, \"Se\" : 78.971, \"Br\" : 79.904, \"Kr\" : 84.798, \r\n\t\"Rb\" : 84.468, \"Sr\" : 87.620, \"Y\" : 88.906, \"Zr\" : 91.224, \r\n\t\"Nb\" : 92.906, \"Mo\" : 95.950, \"Tc\" : 98.907, \"Ru\" : 101.070, \r\n\t\"Rh\" : 102.906, \"Pd\" : 106.42, \"Ag\" : 107.868, \"Cd\" : 112.414, \r\n\t\"In\" : 114.818, \"Sn\" : 118.711, \"Sb\" : 121.760, \"Te\" : 127.600, \r\n\t\"I\" : 126.904, \"Xe\" : 131.294, \"Cs\" : 132.905, \"Ba\" : 137.328, \r\n\t\"La\" : 138.905, \"Ce\" : 140.116, \"Pr\" : 140.908, \"Nd\" : 144.243, \r\n\t\"Pm\" : 144.913, \"Sm\" : 150.360, \"Eu\" : 151.964, \"Gd\" : 157.250, \r\n\t\"Tb\" : 158.925, \"Dy\" : 162.500, \"Ho\" : 164.930, \"Er\" : 167.259, \r\n\t\"Tm\" : 168.934, \"Yb\" : 173.055, \"Lu\" : 174.967, \"Hf\" : 178.490, \r\n\t\"Ta\" : 180.948, \"W\" : 183.840, \"Re\" : 186.207, \"Os\" : 190.230, \r\n\t\"Ir\" : 192.217, \"Pt\" : 195.085, \"Au\" : 196.967, \"Hg\" : 200.592, \r\n\t\"Tl\" : 204.383, \"Pb\" : 207.200, \"Bi\" : 208.980, \"Po\" : 208.982, \r\n\t\"At\" : 209.987, \"Rn\" : 222.018, \"Fr\" : 223.020, \"Ra\" : 226.025, \r\n\t\"Ac\" : 227.028, \"Th\" : 232.038, \"Pa\" : 231.036, \"U\" : 238.029, \r\n\t\"Np\" : 237.048, \"Pu\" : 244.064, \"Am\" : 243.061, \"Cm\" : 247.070, \r\n\t\"Bk\" : 247.070, \"Cf\" : 251.080, \"Es\" : 254.000, \"Fm\" : 257.095, \r\n\t\"Md\" : 258.100, \"No\" : 259.101, \"Lr\" : 262.000, \"Rf\" : 261.000, \r\n\t\"Db\" : 262.000, \"Sg\" : 266.000, \"Bh\" : 264.000, \"Hs\" : 269.000, \r\n\t\"Mt\" : 278.000, \"Ds\" : 281.000, \"Rg\" : 280.000, \"Cn\" : 285.000, \r\n \"Nh\" : 286.000, \"Fl\" : 289.000, \"Mc\" : 289.000, \"Lv\" : 293.000, \r\n\t\"Ts\" : 294.000, \"Og\" : 294.000,\r\n\r\n \"h\" : 1.008, \"he\" : 4.003, \"li\" : 6.941, \"be\" : 9.012, \r\n\t\"b\" : 10.811, \"c\" : 12.011, \"n\" : 14.007, \"o\" : 15.999, \r\n\t\"f\" : 18.998, \"ne\" : 20.180, \"na\" : 22.990, \"mg\" : 24.305, \r\n\t\"al\" : 26.982, \"si\" : 28.086, \"p\" : 30.974, \"s\" : 32.066, \r\n\t\"cl\" : 35.453, \"ar\" : 39.948, \"k\" : 39.098, \"ca\" : 40.078,\r\n \"sc\" : 44.956, \"ti\" : 47.867, \"v\" : 50.942, \"cr\" : 51.996, \r\n\t\"mn\" : 54.938, \"fe\" : 55.845, \"co\" : 58.933, \"ni\" : 58.693, \r\n\t\"cu\" : 63.546, \"zn\" : 65.380, \"ga\" : 69.732, \"ge\" : 72.631, \r\n\t\"as\" : 74.922, \"se\" : 78.971, \"br\" : 79.904, \"kr\" : 84.798, \r\n\t\"rb\" : 84.468, \"sr\" : 87.620, \"y\" : 88.906, \"zr\" : 91.224, \r\n\t\"nb\" : 92.906, \"mo\" : 95.950, \"tc\" : 98.907, \"ru\" : 101.070, \r\n\t\"rh\" : 102.906, \"pd\" : 106.42, \"ag\" : 107.868, \"cd\" : 112.414, \r\n\t\"in\" : 114.818, \"sn\" : 118.711, \"sb\" : 121.760, \"te\" : 127.600, \r\n\t\"i\" : 126.904, \"xe\" : 131.294, \"cs\" : 132.905, \"ba\" : 137.328, \r\n\t\"la\" : 138.905, \"ce\" : 140.116, \"pr\" : 140.908, \"nd\" : 144.243, \r\n\t\"pm\" : 144.913, \"sm\" : 150.360, \"eu\" : 151.964, \"gd\" : 157.250, \r\n\t\"tb\" : 158.925, \"dy\" : 162.500, \"ho\" : 164.930, \"er\" : 167.259, \r\n\t\"tm\" : 168.934, \"yb\" : 173.055, \"lu\" : 174.967, \"hf\" : 178.490, \r\n\t\"ta\" : 180.948, \"w\" : 183.840, \"re\" : 186.207, \"os\" : 190.230, \r\n\t\"ir\" : 192.217, \"pt\" : 195.085, \"au\" : 196.967, \"hg\" : 200.592, \r\n\t\"tl\" : 204.383, \"pb\" : 207.200, \"bi\" : 208.980, \"po\" : 208.982, \r\n\t\"at\" : 209.987, \"rn\" : 222.018, \"fr\" : 223.020, \"ra\" : 226.025, \r\n\t\"ac\" : 227.028, \"th\" : 232.038, \"pa\" : 231.036, \"u\" : 238.029, \r\n\t\"np\" : 237.048, \"pu\" : 244.064, \"am\" : 243.061, \"cm\" : 247.070, \r\n\t\"bk\" : 247.070, \"cf\" : 251.080, \"es\" : 254.000, \"fm\" : 257.095, \r\n\t\"md\" : 258.100, \"no\" : 259.101, \"lr\" : 262.000, \"rf\" : 261.000, \r\n\t\"db\" : 262.000, \"sg\" : 266.000, \"bh\" : 264.000, \"hs\" : 269.000, \r\n\t\"mt\" : 278.000, \"ds\" : 281.000, \"rg\" : 280.000, \"cn\" : 285.000, \r\n \"nh\" : 286.000, \"fl\" : 289.000, \"mc\" : 289.000, \"lv\" : 293.000, \r\n\t\"ts\" : 294.000, \"og\" : 294.000}\r\n\r\ngx = 390\r\ngy = 470\r\n\r\nscr = Tk()\r\nscr.title(\"Prof.Brenmore\")\r\nscr.geometry(\"{}x{}\".format(gx,gy))\r\n\r\nICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'\r\n 'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))\r\n\r\n_, ICON_PATH = tempfile.mkstemp()\r\nwith open(ICON_PATH, 'wb') as icon_file:\r\n icon_file.write(ICON)\r\n\r\nscr.iconbitmap(default=ICON_PATH)\r\n\r\n\r\n\r\n\r\nf = Frame(scr)\r\nf.place(x=10,y=10)\r\nf2 = Frame(scr)\r\nf2.place(x=gx/2,y=60)\r\nf3 = Frame(scr)\r\nf3.pack(side=BOTTOM)\r\n\r\nSVs = [StringVar(value='') for i in range(8)]\r\n\r\nEs = [Entry(f,width=5,font=(\"Calibri\", 10),textvariable=SVs[i]) for i in range(8)]\r\nEs[0].grid(row=0,column=0)\r\n\r\nPs = [Label(f,font=(\"Calibri\", 10),text='+',state=DISABLED) for i in range(8)]\r\nPs[0].config(state=NORMAL)\r\nPs[0].grid(row=0,column=1)\r\n\r\nPs[1].grid(row=0,column=3)\r\n\r\nEs[1].grid(row=0,column=2)\r\n\r\n\r\n\r\n## S2\r\n\r\nins1 = Canvas(f2, width=160, height=88, borderwidth=0, highlightthickness=0,confine=1)\r\nins1.pack(side=RIGHT)\r\n\r\nt1 = Listbox(ins1,font=(\"Calibri\", 10),height=4, width=10, state=DISABLED)\r\nt1.place(x=0,y=20)\r\n\r\nSb = Scrollbar(t1, command = t1.yview)\r\nt1.config(yscrollcommand = Sb.set)\r\nSb.place(x=54,y=0,height=65)\r\n\r\ntittxt = Label(ins1,font=(\"Calibri\", 10),text='n, mol', state=DISABLED)\r\ntittxt.place(x=100,y=0)\r\n\r\nSV9 = StringVar()\r\nJb = Entry(ins1,width=8,font=(\"Calibri\", 10),textvariable=SV9)\r\nJb.place(x=89,y=20)\r\n\r\n## S3\r\n\r\nd1 = 80\r\nd2 = 70\r\nd3 = 70\r\nd4 = 70\r\ndu=10\r\n\r\nins2 = Canvas(f3, borderwidth=0)\r\nins2.pack()\r\n\r\nVertleft = ins2.create_line(20,20,20,200)\r\nVertleftmid = ins2.create_line(20+d1,20,20+d1,200)\r\nVertmid = ins2.create_line(20+d1+d2,20,20+d1+d2,200)\r\nVertrightmid = ins2.create_line(20+d1+d2+d3,20,20+d1+d2+d3,200)\r\nVertright = ins2.create_line(20+d1+d2+d3+d4,20,20+d1+d2+d3+d4,200)\r\n\r\nHors = [ins2.create_line(20,i*20+20,20+d1+d2+d3+d4,i*20+20) for i in range(10)]\r\n\r\nins2.create_text(20+d1/2,20+du,anchor=CENTER,text='Molecule',font=(\"Calibri\", 11))\r\nins2.create_text(20+d1+d2/2,20+du,anchor=CENTER,text='n, mol',font=(\"Calibri\", 11))\r\nins2.create_text(20+d1+d2+d3/2,20+du,anchor=CENTER,text='M, g/mol',font=(\"Calibri\", 11))\r\nins2.create_text(20+d1+d2+d3+d4/2,20+du,anchor=CENTER,text='m, g',font=(\"Calibri\", 11))\r\n\r\nMolecLabels = [None for i in range(8)]\r\nNLabels = [None for i in range(8)]\r\nMLabels = [None for i in range(8)]\r\nMassLabels = [None for i in range(8)]\r\n\r\n\r\nErrorLabel = Label(ins2,font=(\"Calibri\", 10),fg='#ee1111',text='Not enough data')\r\nErrorLabel.place(x=gx/2,y=gy/2-30)\r\nCreditLabel = Label(ins2,font=(\"Calibri\", 10),fg='#555555',text='Made by A.Mirror, A.Filin, Leo K., A.Gur\\n MUCTR 2020, v1.1')\r\nCreditLabel.place(x=80,y=gy/2-10)\r\n###\r\nError = ''\r\ndef CheckMolar(text,frm='call1'):\r\n global Error\r\n terror = False\r\n MM = 0\r\n happened = False\r\n Fullct = ''\r\n Act = False\r\n elements = []\r\n for i in range(len(text)):\r\n if happened:\r\n happened = False\r\n continue\r\n if not Act and text[i] in ('0','1','2','3','4','5','6','7','8','9','.'):\r\n Fullct += text[i]\r\n continue\r\n else:\r\n Act = True\r\n if Act and text[i] not in ('0','1','2','3','4','5','6','7','8','9','.','[','(',')',']'):\r\n try:\r\n print(text[i]+text[i+1]+' ',AM[text[i]+text[i+1]])\r\n j = AM[text[i]+text[i+1]]\r\n if DoRound:\r\n j1 = round(j,1)\r\n if j1%1 < 0.4 or j1%1 > 0.6:\r\n j = round(j)\r\n else:\r\n j = j1\r\n k = 0\r\n for ss in range(5):\r\n try:\r\n k = k*10+int(text[i+2+ss])\r\n except:\r\n k = k\r\n if k == 0:\r\n k = 1\r\n break\r\n elements.append((text[i]+text[i+1],j,k))\r\n happened = True\r\n except:\r\n try:\r\n print(text[i]+' ',AM[text[i]])\r\n j = AM[text[i]]\r\n if DoRound:\r\n j1 = round(j,1)\r\n if j1%1 != 0.5 or j1%1 != 0.4 or j1%1 != 0.6:\r\n j = round(j)\r\n else:\r\n j = j1\r\n k = 0\r\n for ss in range(5):\r\n try:\r\n k = k*10+int(text[i+1+ss])\r\n except:\r\n k = k\r\n if k == 0:\r\n k = 1\r\n break\r\n elements.append((text[i],j,k))\r\n except:\r\n ErrorLabel.config(text='Wrong element')\r\n print('wrong element')\r\n Error = 'Wrong element'\r\n terror = True\r\n #print(elements, Fullct)\r\n Bct = 0\r\n for i in range(len(text)):\r\n if text[i] in ('[','('):\r\n Bct += 1\r\n text = text.replace(\"[\",'(')\r\n text = text.replace(\"]\",')')\r\n try:\r\n while Bct > 0:\r\n readtext = ''\r\n tBct = 0\r\n tct = 0\r\n tMM = 0\r\n #print('Bct = ',Bct)\r\n for i in range(len(text)):\r\n if text[i] == '(':\r\n tBct += 1\r\n if tBct == Bct:\r\n if text[i] == '(':\r\n text = text[::-1].replace(\"(\",'{',1)[::-1]\r\n if text[i] == ')':\r\n text = text[:i]+text[i:].replace(\")\",'}',1)\r\n readtext += text[i]\r\n tct = 0\r\n for ss in range(5):\r\n try:\r\n tct = tct*10+int(text[i+1+ss])\r\n except:\r\n tct = tct\r\n if tct == 0:\r\n tct = 1\r\n break\r\n break\r\n #print(text)\r\n readtext += text[i]\r\n ttext = readtext[::-1]\r\n for i in range(len(elements)-1,0,-1):\r\n #print(len(elements[i][0]))\r\n if elements[i][0][0] == \"{\":\r\n if elements[i][0][::-1] in ttext:\r\n tMM += elements[i][1] * elements[i][2]\r\n ttext = ttext.replace(elements[i][0][::-1],'',1)\r\n elements.pop(i)\r\n continue\r\n for j in range(len(ttext)):\r\n try:\r\n if ttext[j] == elements[i][0][0] and ttext[j-1] == elements[i][0][1]:\r\n tMM += elements[i][1] * elements[i][2]\r\n ttext = ttext.replace(elements[i][0][::-1],'',1)\r\n elements.pop(i)\r\n break\r\n except:\r\n if ttext[j] == elements[i][0]:\r\n tMM += elements[i][1] * elements[i][2]\r\n ttext = ttext.replace(elements[i][0][::-1],'',1)\r\n elements.pop(i)\r\n break\r\n if tct == 0:\r\n raise\r\n elements.append((readtext,tMM,tct))\r\n #print(elements)\r\n Bct -= 1\r\n except:\r\n ErrorLabel.config(text='Wrong brackets')\r\n print('wrong brackets')\r\n Error = 'Wrong brackets'\r\n terror = True\r\n #print(elements)\r\n for i in elements:\r\n MM += i[1]*i[2]\r\n if frm=='call1' and terror == False and ErrorLabel.cget('text')!='Wrong Element':\r\n ErrorLabel.config(text='')\r\n Error = ''\r\n try:\r\n return (MM,float(Fullct))\r\n except:\r\n return (MM,1.0)\r\n\r\n\r\n###\r\ndef callback1(i):\r\n global MolecLabels\r\n av = SVs[i].get()\r\n if i == 0:\r\n if av != '':\r\n t1.config(state=NORMAL)\r\n tittxt.config(state=NORMAL)\r\n Jb.config(state=NORMAL)\r\n elif SVs[1].get()=='' and SVs[2].get()=='' and SVs[3].get()=='' and SVs[4].get()=='' and SVs[5].get()=='' and SVs[6].get()=='' and SVs[7].get()=='':\r\n t1.delete(0,END)\r\n t1.config(state=DISABLED)\r\n tittxt.config(state=DISABLED)\r\n Jb.config(state=DISABLED)\r\n if len(av) > 5 and len(av) < 20:\r\n num = len(av)\r\n ct = 0\r\n for j in av:\r\n if j in ('[','('):\r\n ct+=0.8\r\n ct/=2\r\n num-=int(ct)\r\n Es[i].config(width= num) \r\n else:\r\n Es[i].config(width= 5)\r\n #print(CheckMolar(av))\r\n j = i+1\r\n\r\n if (i!=0 and i!=7) and av !='':\r\n Es[j].grid(row=j//4,column=(j%4)*2)\r\n Ps[i].config(state=NORMAL) \r\n if j!=4:\r\n Ps[j].grid(row=j//4,column=(j%4)*2-1)\r\n else:\r\n Ps[j].grid(row=0,column=7) \r\n else:\r\n t1.delete(i)\r\n if av!='':\r\n t1.insert(i, av)\r\n \r\n for k in range(8):\r\n try:\r\n ins2.delete(MolecLabels[k])\r\n except:\r\n continue\r\n try:\r\n jk = SVs[k].get()[0]\r\n except:\r\n jk = ''\r\n if CheckMolar(SVs[k].get(),'no')[1] == 1 and jk != '1':\r\n veryGREG = SVs[k].get()\r\n #print(1)\r\n else:\r\n if CheckMolar(SVs[k].get(),'no')[1] != int(CheckMolar(SVs[k].get(),'no')[1]):\r\n veryGREG = SVs[k].get().replace(str(CheckMolar(SVs[k].get(),'no')[1]),'',1)\r\n else:\r\n veryGREG = SVs[k].get().replace(str(int(CheckMolar(SVs[k].get(),'no')[1])),'',1)\r\n if len(veryGREG) >= 11:\r\n MolecLabels[k] = ins2.create_text(20+d1/2,40+du+k*20,anchor=CENTER,text=veryGREG[0:7]+'...',font=(\"Calibri\", 11))\r\n else:\r\n MolecLabels[k] = ins2.create_text(20+d1/2,40+du+k*20,anchor=CENTER,text=veryGREG,font=(\"Calibri\", 11))\r\n\r\n try:\r\n ins2.delete(MLabels[k])\r\n except:\r\n continue\r\n GREG = CheckMolar(SVs[k].get(),'no')[0]\r\n if GREG - int(GREG) == 0:\r\n GREG = int(GREG)\r\n if SVs[k].get()!='':\r\n MLabels[k] = ins2.create_text(20+d1+d2+d3/2,40+du+k*20,anchor=CENTER,text=GREG,font=(\"Calibri\", 11))\r\n \r\n t1.delete(k)\r\n t1.insert(k, SVs[k].get())\r\n if k!= 0 and k!=1 and k != 7 and SVs[k].get() == '' and SVs[k+1].get() == '':\r\n Es[k+1].grid_forget()\r\n Ps[k+1].grid_forget()\r\n Ps[k].config(state=DISABLED)\r\n\r\n if SVs[k-1].get()=='':\r\n Es[k].grid_forget()\r\n Ps[k].grid_forget()\r\n Ps[k-1].config(state=DISABLED)\r\n t1.see(i)\r\n LBselect(1)\r\n\r\n##\r\nGlobalSelection = 0\r\ndef callback2():\r\n global GlobalSelection\r\n Length = 0\r\n av = SV9.get()\r\n try:\r\n I = t1.curselection()[0]\r\n except:\r\n I = GlobalSelection\r\n t1.select_set(I)\r\n #print(av,I)\r\n try:\r\n av = float(av)\r\n if ErrorLabel.cget('text') == 'Not a valid value of n':\r\n ErrorLabel.config(text=Error)\r\n except:\r\n if Error == '':\r\n ErrorLabel.config(text='Not a valid value of n')\r\n print('not a number')\r\n av = 0.0\r\n alsoGREG = 0.0\r\n #print('aaa',CheckMolar(SVs[I].get(),'call2')[1])\r\n try:\r\n GREG = float(CheckMolar(SVs[I].get(),'call2')[1])\r\n except:\r\n GREG = 0\r\n Length = len(str(av).split('.')[1])\r\n for k in range(8):\r\n try:\r\n ins2.delete(NLabels[k])\r\n except:\r\n continue \r\n \r\n if SVs[k].get() != '':\r\n try:\r\n alsoGREG = float(CheckMolar(SVs[k].get(),'call2')[1])\r\n except:\r\n alsoGREG = 0\r\n if alsoGREG > 0:\r\n const = round(alsoGREG*av/GREG,Length)\r\n \r\n else:\r\n const=''\r\n else:\r\n const=''\r\n if k == I:\r\n NLabels[k] = ins2.create_text(20+d1+d2/2,40+du+k*20,text=av,font=(\"Calibri\", 12))\r\n else:\r\n #print(k,'as',const)\r\n NLabels[k] = ins2.create_text(20+d1+d2/2,40+du+k*20,text=const,font=(\"Calibri\", 11))\r\n\r\n try:\r\n ins2.delete(MassLabels[k])\r\n except:\r\n continue\r\n if SVs[k].get() != '':\r\n #print('bss',alsoGREG)\r\n #print(k,'ass',round(CheckMolar(SVs[k].get(),'call2')[0]*alsoGREG*av/GREG,Length))\r\n MassLabels[k] = ins2.create_text(20+d1+d2+d3+d4/2,40+du+k*20,text=round(CheckMolar(SVs[k].get(),'call2')[0]*alsoGREG*av/GREG,Length),font=(\"Calibri\", 11))\r\n \r\n##\r\ndef LBselect(x):\r\n global GlobalSelection\r\n try:\r\n GlobalSelection = t1.curselection()[0]\r\n except:\r\n None == None\r\n callback2()\r\n\r\n \r\nSVs[0].trace(\"w\", lambda name, index, mode:callback1(0))\r\nSVs[1].trace(\"w\", lambda name, index, mode:callback1(1))\r\nSVs[2].trace(\"w\", lambda name, index, mode:callback1(2))\r\nSVs[3].trace(\"w\", lambda name, index, mode:callback1(3))\r\nSVs[4].trace(\"w\", lambda name, index, mode:callback1(4))\r\nSVs[5].trace(\"w\", lambda name, index, mode:callback1(5))\r\nSVs[6].trace(\"w\", lambda name, index, mode:callback1(6))\r\nSVs[7].trace(\"w\", lambda name, index, mode:callback1(7))\r\n\r\nt1.bind('<>', LBselect)\r\n\r\nSV9.trace(\"w\", lambda x,y,z: callback2())\r\n\r\nmainloop()\r\n","sub_path":"ProfBrenSource.py","file_name":"ProfBrenSource.py","file_ext":"py","file_size_in_byte":17504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"467163307","text":"import gcsfs\nimport os\nimport shutil\nimport logging\nfrom lithops.storage.utils import StorageNoSuchKeyError\n\nlogger = logging.getLogger(__name__)\n\n\nclass GcsfsStorageBackend:\n \"\"\"\n A wrapper around gcsfs APIs.\n \"\"\"\n\n def __init__(self, config, bucket = None, executor_id = None):\n logger.debug(\"Creating gcsfs storage client\")\n self.config = config\n self.bucket = bucket\n self.fs = gcsfs.GCSFileSystem(project=config[\"project_id\"])\n logger.debug(\"gcsfs storage client created successfully\")\n\n def put_object(self, bucket_name, key, data):\n \"\"\"\n Put an object in localhost filesystem.\n Override the object if the key already exists.\n :param key: key of the object.\n :param data: data of the object\n :type data: str/bytes\n :return: None\n \"\"\"\n try:\n data_type = type(data)\n file_path = \"{}/{}\".format(bucket_name, key)\n if data_type == bytes:\n with self.fs.open(file_path, \"wb\") as f:\n f.write(data)\n else:\n with self.fs.open(file_path, \"w\") as f:\n f.write(data)\n except Exception as e:\n raise(e)\n\n def get_object(self, bucket_name, key, stream=False, extra_get_args={}):\n \"\"\"\n Get object from localhost filesystem with a key.\n Throws StorageNoSuchKeyError if the given key does not exist.\n :param key: key of the object\n :return: Data of the object\n :rtype: str/bytes\n \"\"\"\n try:\n file_path = \"{}/{}\".format(bucket_name, key)\n with self.fs.open(file_path, \"rb\") as f:\n if 'Range' in extra_get_args:\n byte_range = extra_get_args['Range'].replace('bytes=', '')\n first_byte, last_byte = map(int, byte_range.split('-'))\n f.seek(first_byte)\n return f.read(last_byte-first_byte+1)\n else:\n return f.read()\n except Exception as e:\n raise StorageNoSuchKeyError(bucket_name, key)\n\n def head_object(self, bucket_name, key):\n \"\"\"\n Head object from local filesystem with a key.\n Throws StorageNoSuchKeyError if the given key does not exist.\n :param key: key of the object\n :return: Data of the object\n :rtype: str/bytes\n \"\"\"\n pass\n\n def delete_object(self, bucket_name, key):\n \"\"\"\n Delete an object from storage.\n :param bucket: bucket name\n :param key: data key\n \"\"\"\n file_path = \"{}/{}\".format(bucket_name, key)\n if self.fs.exists(file_path):\n self.fs.rm(file_path, recursive=True)\n\n def delete_objects(self, bucket_name, key_list):\n \"\"\"\n Delete a list of objects from storage.\n :param bucket: bucket name\n :param key_list: list of keys\n \"\"\"\n for key in key_list:\n self.delete_object(bucket_name, key)\n\n def bucket_exists(self, bucket_name):\n \"\"\"\n Head localhost dir with a name.\n Throws StorageNoSuchKeyError if the given bucket does not exist.\n :param bucket_name: name of the bucket\n \"\"\"\n raise NotImplementedError\n\n def head_bucket(self, bucket_name):\n \"\"\"\n Head localhost dir with a name.\n Throws StorageNoSuchKeyError if the given bucket does not exist.\n :param bucket_name: name of the bucket\n :return: Metadata of the bucket\n :rtype: str/bytes\n \"\"\"\n raise NotImplementedError\n\n def list_objects(self, bucket_name, prefix=None):\n \"\"\"\n Return a list of objects for the prefix.\n :param bucket_name: Name of the bucket.\n :param prefix: Prefix to filter object names.\n :return: List of objects in bucket that match the given prefix.\n :rtype: list of str\n \"\"\"\n raise NotImplementedError\n\n def list_keys(self, bucket_name, prefix=None):\n \"\"\"\n Return a list of keys for the given prefix.\n :param bucket_name: Name of the bucket.\n :param prefix: Prefix to filter object names.\n :return: List of keys in bucket that match the given prefix.\n :rtype: list of str\n \"\"\"\n root = \"{}/{}\".format(bucket_name, prefix)\n # Important not to cache dir listings, since Lithops polls for changes\n self.fs.invalidate_cache(root) \n try:\n return [key.replace(\"{}/\".format(bucket_name), \"\") for key in self.fs.ls(root)]\n except FileNotFoundError:\n return []\n","sub_path":"lithops/storage/backends/gcsfs/gcsfs.py","file_name":"gcsfs.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"47171878","text":"##\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\nfrom __future__ import annotations\nfrom typing import Hashable, List, Dict, Optional, Sequence, Union\nfrom copy import copy\nfrom collections.abc import Iterable\nimport pycylon as cn\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nfrom pycylon import Series\nfrom pycylon.index import RangeIndex, CategoricalIndex\nfrom pycylon.io import CSVWriteOptions\nfrom pycylon.io import CSVReadOptions\n\nfrom pycylon import CylonContext\n\nDEVICE_CPU = \"cpu\"\n\n\nclass CylonEnv(object):\n\n def __init__(self, config=None, distributed=True) -> None:\n self._context = CylonContext(config, distributed)\n self._distributed = distributed\n self._finalized = False\n\n @property\n def context(self):\n return self._context\n\n @property\n def rank(self):\n return self._context.get_rank()\n\n @property\n def is_distributed(self):\n return self._distributed\n\n def finalize(self):\n if self._finalized == False:\n self._finalized = True\n self._context.finalize()\n\n def barrier(self):\n self._context.barrier()\n\n def __del__(self):\n \"\"\"\n On destruction of the application, the environment will be automatically finalized\n \"\"\"\n self.finalize()\n\n\nclass DataFrame(object):\n\n def __init__(self, data=None, index=None, columns=None, copy=False):\n self._index = None\n self._columns = []\n\n self._table = self._initialize_dataframe(\n data=data, index=index, columns=columns, copy=copy)\n\n # temp workaround for indexing requirement of dataframe api\n self._index_columns = []\n\n self._device = DEVICE_CPU\n\n def to_cpu(self):\n \"\"\"\n Move the dataframe from it's current device to random access memory\n \"\"\"\n pass\n\n def to_device(self, device=None):\n \"\"\"\n Move the dataframe from it's current device to the specified device\n \"\"\"\n pass\n\n def is_cpu(self):\n return self._device == DEVICE_CPU\n\n def is_device(self, device):\n return self._device == device\n\n def _change_context(self, env: CylonEnv):\n \"\"\"\n This is a temporary function to make the DataFrame backed by a Cylon Table with a different context.\n This should be removed once C++ support Tables which are independent from Contexts\n \"\"\"\n self._table = self._initialize_dataframe(\n data=self._table.to_arrow(), index=self._index, columns=self._columns, copy=False, context=env.context)\n return self\n\n def _initialize_dataframe(self, data=None, index=None, columns=None, copy=False, context=CylonContext(config=None, distributed=False)):\n rows = 0\n cols = 0\n self._table = None\n if copy:\n data = self._copy(data)\n\n if isinstance(data, List):\n # load from List or np.ndarray\n if isinstance(data[0], List):\n rows = len(data[0])\n cols = len(data)\n if not columns:\n columns = self._initialize_columns(\n cols=cols, columns=columns)\n return cn.Table.from_list(context, columns, data)\n elif isinstance(data[0], np.ndarray):\n # load from List of np.ndarray\n cols = len(data)\n rows = data[0].shape[0]\n if not columns:\n columns = self._initialize_columns(\n cols=cols, columns=columns)\n return cn.Table.from_numpy(context, columns, data)\n else:\n # load from List\n rows = len(data)\n cols = 1\n if not columns:\n columns = self._initialize_columns(\n cols=cols, columns=columns)\n return cn.Table.from_list(context, columns, data)\n elif isinstance(data, pd.DataFrame):\n # load from pd.DataFrame\n rows, cols = data.shape\n if columns:\n from pycylon.util.pandas.utils import rename_with_new_column_names\n columns = rename_with_new_column_names(data, columns)\n data = data.rename(columns=columns, inplace=True)\n return cn.Table.from_pandas(context, data)\n elif isinstance(data, dict):\n # load from dictionary\n _, data_items = list(data.items())[0]\n rows = len(data_items)\n return cn.Table.from_pydict(context, data)\n elif isinstance(data, pa.Table):\n # load from pa.Table\n rows, cols = data.shape\n return cn.Table.from_arrow(context, data)\n elif isinstance(data, Series):\n # load from PyCylon Series\n # cols, rows = data.shape\n # columns = self._initialize_columns(cols=cols, columns=columns)\n return NotImplemented\n elif isinstance(data, cn.Table):\n if columns:\n from pycylon.util.pandas.utils import rename_with_new_column_names\n columns = rename_with_new_column_names(data, columns)\n data = data.rename(columns=columns)\n return data\n else:\n raise ValueError(f\"Invalid data structure, {type(data)}\")\n\n def _initialize_dtype(self, dtype):\n raise NotImplemented(\n \"Data type forcing is not implemented, only support inferring types\")\n\n def _initialize_columns(self, cols, columns):\n if columns is None:\n return [str(i) for i in range(cols)]\n else:\n if isinstance(columns, Iterable):\n if len(columns) != cols:\n raise ValueError(f\"data columns count: {cols} and column names count \"\n f\"{len(columns)} not equal\")\n else:\n return columns\n\n def _initialize_index(self, index, rows):\n if index is None:\n self._index = RangeIndex(start=0, stop=rows)\n else:\n if isinstance(index, CategoricalIndex):\n # check the validity of provided Index\n pass\n elif isinstance(index, RangeIndex):\n # check the validity of provided Index\n pass\n\n def _copy(self, obj):\n return copy(obj)\n\n @property\n def shape(self):\n return self._table.shape\n\n @property\n def columns(self) -> List[str]:\n return self._table.column_names\n\n def to_pandas(self) -> pd.DataFrame:\n return self._table.to_pandas()\n\n def to_numpy(self, order: str = 'F', zero_copy_only: bool = True, writable: bool = False) -> \\\n np.ndarray:\n return self._table.to_numpy(order=order, zero_copy_only=zero_copy_only,\n writable=writable)\n\n def to_arrow(self) -> pa.Table:\n return self._table.to_arrow()\n\n def to_dict(self) -> Dict:\n return self._table.to_pydict()\n\n def to_table(self) -> cn.Table:\n return self._table\n\n def to_csv(self, path, csv_write_options: CSVWriteOptions):\n self._table.to_csv(path=path, csv_write_options=csv_write_options)\n\n def __getitem__(self, item) -> DataFrame:\n \"\"\"\n This method allows to retrieve a subset of a DataFrane by means of a key\n Args:\n key: a key can be the following\n 1. slice i.e dataframe[1:5], rows 1:5\n 2. int i.e a row index\n 3. str i.e extract the data column-wise by column-name\n 4. List of columns are extracted\n 5. PyCylon DataFrame\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]\n >>> df: DataFrame = DataFrame(data)\n\n >>> df1 = df[1:3]\n col-1 col-2 col-3\n 0 2 6 10\n 1 3 7 11\n 2 4 8 12\n\n >>> df2 = df['col-1']\n col-1\n 0 1\n 1 2\n 2 3\n 3 4\n\n >>> df3 = df[['col-1', 'col-2']]\n col-1 col-2\n 0 1 5\n 1 2 6\n 2 3 7\n 3 4 8\n\n >>> df4 = df > 3\n col-1 col-2 col-3\n 0 False True True\n 1 False True True\n 2 False True True\n 3 True True True\n\n >>> df5 = df[tb4]\n col-1 col-2 col-3\n 0 NaN 5 9\n 1 NaN 6 10\n 2 NaN 7 11\n 3 4.0 8 12\n\n >>> df8 = df['col-1'] > 2\n col-1 col-2 col-3\n 0 3 7 11\n 1 4 8 12\n\n \"\"\"\n if isinstance(item, slice) or isinstance(item, int) or isinstance(item, str) or \\\n isinstance(item, List):\n return DataFrame(self._table.__getitem__(item))\n elif isinstance(item, DataFrame):\n return DataFrame(self._table.__getitem__(item.to_table()))\n\n def __setitem__(self, key, value):\n '''\n Sets values for a existing dataframe by means of a column\n Args:\n key: (str) column-name\n value: (DataFrame) data as a single column table\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n\n >>> df['col-3'] = DataFrame([[90, 100, 110, 120]])\n col-1 col-2 col-3\n 0 1 5 90\n 1 2 6 100\n 2 3 7 110\n 3 4 8 120\n\n >>> df['col-4'] = DataFrame([190, 1100, 1110, 1120]])\n col-1 col-2 col-3 col-4\n 0 1 5 90 190\n 1 2 6 100 1100\n 2 3 7 110 1110\n 3 4 8 120 1120\n '''\n\n if isinstance(key, str) and isinstance(value, DataFrame):\n self._table.__setitem__(key, value.to_table())\n else:\n raise ValueError(f\"Not Implemented __setitem__ option for key Type {type(key)} and \"\n f\"value type {type(value)}\")\n\n def __repr__(self):\n return self._table.__repr__()\n\n def __eq__(self, other) -> DataFrame:\n '''\n Equal operator for DataFrame\n Args:\n other: can be a numeric scalar or a DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df['col-1'] == 2\n col-1\n 0 False\n 1 True\n 2 False\n 3 False\n\n >>> df == 2\n col-1 col-2 col-3\n 0 False False False\n 1 True False False\n 2 False False False\n 3 False False False\n\n '''\n return DataFrame(self._table.__eq__(other))\n\n def __ne__(self, other) -> DataFrame:\n '''\n Not equal operator for DataFrame\n Args:\n other: can be a numeric scalar or DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df3 = df['col-1'] != 2\n col-1\n 0 True\n 1 False\n 2 True\n 3 True\n\n >>> df4 = df != 2\n col-1 col-2 col-3\n 0 True True True\n 1 False True True\n 2 True True True\n 3 True True True\n '''\n\n return DataFrame(self._table.__ne__(other))\n\n def __lt__(self, other) -> DataFrame:\n '''\n Lesser than operator for DataFrame\n Args:\n other: can be a numeric scalar or DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> tb\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> tb3 = tb['col-1'] < 2\n col-1\n 0 True\n 1 False\n 2 False\n 3 False\n\n >>> tb4 = tb < 2\n col-1 col-2 col-3\n 0 True False False\n 1 False False False\n 2 False False False\n 3 False False False\n '''\n\n return DataFrame(self._table.__lt__(other))\n\n def __gt__(self, other) -> DataFrame:\n '''\n Greater than operator for DataFrame\n Args:\n other: can be a numeric scalar or DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df3 = df['col-1'] > 2\n col-1\n 0 False\n 1 False\n 2 True\n 3 True\n\n >>> df4 = df > 2\n col-1 col-2 col-3\n 0 False True True\n 1 False True True\n 2 True True True\n 3 True True True\n '''\n\n return DataFrame(self._table.__gt__(other))\n\n def __le__(self, other) -> DataFrame:\n '''\n Lesser than or equal operator for DataFrame\n Args:\n other: can be a numeric scalar or DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> tb\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df3 = df['col-1'] <= 2\n col-1\n 0 True\n 1 True\n 2 False\n 3 False\n\n >>> df4 = df <= 2\n col-1 col-2 col-3\n 0 True False False\n 1 True False False\n 2 False False False\n 3 False False False\n '''\n return DataFrame(self._table.__le__(other))\n\n def __ge__(self, other) -> DataFrame:\n '''\n Greater than or equal operator for DataFrame\n Args:\n other: can be a numeric scalar or DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n\n >>> df3 = df['col-1'] >= 2\n col-1\n 0 False\n 1 True\n 2 True\n 3 True\n\n >>> df4 = df >= 2\n col-1 col-2 col-3\n 0 False True True\n 1 True True True\n 2 True True True\n 3 True True True\n '''\n\n return DataFrame(self._table.__ge__(other))\n\n def __or__(self, other) -> DataFrame:\n '''\n Or operator for DataFrame\n Args:\n other: PyCylon DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df1\n col-1 col-2\n 0 False True\n 1 True True\n 2 False False\n 3 True False\n\n >>> df2\n col-1 col-2\n 0 True False\n 1 True True\n 2 False False\n 3 False True\n\n >>> df_or = df1 | df2\n col-1 col-2\n 0 True True\n 1 True True\n 2 False False\n 3 True True\n '''\n\n return DataFrame(self._table.__or__(other.to_table()))\n\n def __and__(self, other) -> DataFrame:\n '''\n And operator for DataFrame\n Args:\n other: PyCylon DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df1\n col-1 col-2\n 0 False True\n 1 True True\n 2 False False\n 3 True False\n\n >>> df2\n col-1 col-2\n 0 True False\n 1 True True\n 2 False False\n 3 False True\n\n >>> df_or = df1 & df2\n col-1 col-2\n 0 False False\n 1 True True\n 2 False False\n 3 False False\n '''\n\n return DataFrame(self._table.__and__(other.to_table()))\n\n def __invert__(self) -> DataFrame:\n '''\n Invert operator for DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2\n 0 False True\n 1 True True\n 2 False False\n 3 True False\n\n >>> ~df\n col-1 col-2\n 0 True False\n 1 False False\n 2 True True\n 3 False True\n '''\n\n return DataFrame(self._table.__invert__())\n\n def __neg__(self) -> DataFrame:\n '''\n Negation operator for DataFrame\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> -df\n col-1 col-2 col-3\n 0 -1 -5 -9\n 1 -2 -6 -10\n 2 -3 -7 -11\n 3 -4 -8 -12\n '''\n\n return DataFrame(self._table.__neg__())\n\n def __add__(self, other) -> DataFrame:\n '''\n Add operator for DataFrame\n Args:\n other: scalar numeric\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df + 2\n col-1 col-2 col-3\n 0 3 7 11\n 1 4 8 12\n 2 5 9 13\n 3 6 10 14\n '''\n return DataFrame(self._table.__add__(other))\n\n def __sub__(self, other) -> DataFrame:\n '''\n Subtract operator for DataFrame\n Args:\n other: scalar numeric\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df - 2\n col-1 col-2 col-3\n 0 -1 3 7\n 1 0 4 8\n 2 1 5 9\n 3 2 6 10\n '''\n return DataFrame(self._table.__sub__(other))\n\n def __mul__(self, other) -> DataFrame:\n '''\n Multiply operator for DataFrame\n Args:\n other: scalar numeric\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df * 2\n col-1 col-2 col-3\n 0 2 10 18\n 1 4 12 20\n 2 6 14 22\n 3 8 16 24\n '''\n\n return DataFrame(self._table.__mul__(other))\n\n def __truediv__(self, other) -> DataFrame:\n '''\n Element-wise division operator for DataFrame\n Args:\n other: scalar numeric\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df / 2\n col-1 col-2 col-3\n 0 0.5 2.5 4.5\n 1 1.0 3.0 5.0\n 2 1.5 3.5 5.5\n 3 2.0 4.0 6.0\n '''\n\n return DataFrame(self._table.__truediv__(other))\n\n def drop(self, column_names: List[str]) -> DataFrame:\n '''\n drop a column or list of columns from a DataFrame\n Args:\n column_names: List[str]\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df.drop(['col-1'])\n col-2 col-3\n 0 5 9\n 1 6 10\n 2 7 11\n 3 8 12\n '''\n\n return DataFrame(self._table.drop(column_names))\n\n def fillna(self, fill_value) -> DataFrame:\n '''\n Fill not applicable values with a given value\n Args:\n fill_value: scalar\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1.0 5.0 9.0\n 1 NaN 6.0 10.0\n 2 3.0 NaN 11.0\n 3 4.0 8.0 NaN\n\n >>> df.fillna(0)\n col-1 col-2 col-3\n 0 1 5 9\n 1 0 6 10\n 2 3 0 11\n 3 4 8 0\n '''\n # Note: Supports numeric types only\n return DataFrame(self._table.fillna(fill_value))\n\n def where(self, condition: DataFrame = None, other=None) -> DataFrame:\n '''\n Experimental version of Where operation.\n Replace values where condition is False\n Args:\n condition: bool DataFrame\n other: Scalar\n\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df.where(df > 2)\n col-1 col-2 col-3\n 0 NaN 5 9\n 1 NaN 6 10\n 2 3.0 7 11\n 3 4.0 8 12\n\n >>> df.where(df > 2, 10)\n col-1 col-2 col-3\n 0 10 5 9\n 1 10 6 10\n 2 3 7 11\n 3 4 8 12\n '''\n if condition is None:\n raise ValueError(\"Condition must be provided\")\n return DataFrame(self._table.where(condition, other))\n\n def isnull(self) -> DataFrame:\n '''\n Checks for null elements and returns a bool DataFrame\n Returns: PyCylon DataFrame\n\n Examples\n --------\n\n >>> df\n col-1 col-2 col-3\n 0 1.0 5.0 9.0\n 1 NaN 6.0 10.0\n 2 3.0 NaN 11.0\n 3 4.0 8.0 NaN\n\n >>> df.isnull()\n col-1 col-2 col-3\n 0 False False False\n 1 True False False\n 2 False True False\n 3 False False True\n\n '''\n return DataFrame(self._table.isnull())\n\n def isna(self) -> DataFrame:\n '''\n Check for not applicable values and returns a bool DataFrame\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1.0 5.0 9.0\n 1 NaN 6.0 10.0\n 2 3.0 NaN 11.0\n 3 4.0 8.0 NaN\n\n >>> df.isna()\n col-1 col-2 col-3\n 0 False False False\n 1 True False False\n 2 False True False\n 3 False False True\n '''\n return DataFrame(self._table.isnull())\n\n def notnull(self) -> DataFrame:\n '''\n Check the not null values and returns a bool DataFrame\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1.0 5.0 9.0\n 1 NaN 6.0 10.0\n 2 3.0 NaN 11.0\n 3 4.0 8.0 NaN\n\n >>> df.notnull()\n col-1 col-2 col-3\n 0 True True True\n 1 False True True\n 2 True False True\n 3 True True False\n '''\n\n return ~self.isnull()\n\n def notna(self) -> DataFrame:\n '''\n Checks for not NA values and returns a bool DataFrame\n Returns: PyCylon DataFrame\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1.0 5.0 9.0\n 1 NaN 6.0 10.0\n 2 3.0 NaN 11.0\n 3 4.0 8.0 NaN\n\n >>> df.notna()\n col-1 col-2 col-3\n 0 True True True\n 1 False True True\n 2 True False True\n 3 True True False\n '''\n\n return ~self.isnull()\n\n def rename(self, column_names):\n '''\n Rename a DataFrame with a column name or column names\n Args:\n column_names: dictionary or full list of new column names\n\n Returns: None\n\n Examples\n --------\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df.rename({'col-1': 'col_1'})\n col_1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df.rename(['c1', 'c2', 'c3'])\n c1 c2 c3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n '''\n self._table.rename(column_names)\n\n def add_prefix(self, prefix: str) -> DataFrame:\n '''\n Adding a prefix to column names\n Args:\n prefix: str\n\n Returns: PyCylon DataFrame with prefix updated\n\n Examples\n --------\n\n >>> df\n col-1 col-2 col-3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n >>> df.add_prefix('old_')\n old_c1 old_c2 old_c3\n 0 1 5 9\n 1 2 6 10\n 2 3 7 11\n 3 4 8 12\n\n '''\n\n return DataFrame(self._table.add_prefix(prefix))\n\n # Indexing\n\n def set_index(\n self, keys, drop=True, append=False, inplace=False, verify_integrity=False\n ):\n \"\"\"\n Set the DataFrame index using existing columns.\n Set the DataFrame index (row labels) using one or more existing\n columns or arrays (of the correct length). The index can replace the\n existing index or expand on it.\n Parameters\n ----------\n keys : label or array-like or list of labels/arrays\n This parameter can be either a single column key, a single array of\n the same length as the calling DataFrame, or a list containing an\n arbitrary combination of column keys and arrays. Here, \"array\"\n encompasses :class:`Series`, :class:`Index`, ``np.ndarray``, and\n instances of :class:`~collections.abc.Iterator`.\n drop : bool, default True\n Delete columns to be used as the new index.\n append : bool, default False\n Whether to append columns to existing index.\n inplace : bool, default False\n If True, modifies the DataFrame in place (do not create a new object).\n verify_integrity : bool, default False\n Check the new index for duplicates. Otherwise defer the check until\n necessary. Setting to False will improve the performance of this\n method.\n Returns\n -------\n DataFrame or None\n Changed row labels or None if ``inplace=True``.\n See Also\n --------\n DataFrame.reset_index : Opposite of set_index.\n DataFrame.reindex : Change to new indices or expand indices.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n Examples\n --------\n >>> df = pd.DataFrame({'month': [1, 4, 7, 10],\n ... 'year': [2012, 2014, 2013, 2014],\n ... 'sale': [55, 40, 84, 31]})\n >>> df\n month year sale\n 0 1 2012 55\n 1 4 2014 40\n 2 7 2013 84\n 3 10 2014 31\n Set the index to become the 'month' column:\n >>> df.set_index('month')\n year sale\n month\n 1 2012 55\n 4 2014 40\n 7 2013 84\n 10 2014 31\n Create a MultiIndex using columns 'year' and 'month':\n >>> df.set_index(['year', 'month'])\n sale\n year month\n 2012 1 55\n 2014 4 40\n 2013 7 84\n 2014 10 31\n Create a MultiIndex using an Index and a column:\n >>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])\n month sale\n year\n 1 2012 1 55\n 2 2014 4 40\n 3 2013 7 84\n 4 2014 10 31\n Create a MultiIndex using two Series:\n >>> s = pd.Series([1, 2, 3, 4])\n >>> df.set_index([s, s**2])\n month year sale\n 1 1 1 2012 55\n 2 4 4 2014 40\n 3 9 7 2013 84\n 4 16 10 2014 31\n \"\"\"\n # todo this is not a final implementation\n self._index_columns = keys\n self._table.set_index(keys, drop=drop)\n return self\n\n def reset_index( # type: ignore[misc]\n self,\n level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,\n drop: bool = ...,\n inplace: bool = ...,\n col_level: Hashable = ...,\n col_fill=...,\n ) -> DataFrame:\n # todo this is not a final implementation\n self._index_columns = []\n self._table.reset_index(drop=drop)\n return self\n\n # Combining / joining / merging\n\n def join(self, other: DataFrame, on=None, how='left', lsuffix='l', rsuffix='r',\n sort=False, algorithm=\"sort\", env: CylonEnv = None) -> DataFrame:\n \"\"\"\n Join columns with other DataFrame either on index or on a key\n column. Efficiently Join multiple DataFrame objects by index at once by\n passing a list.\n\n Parameters\n ----------\n other : DataFrame, Series with name field set, or list of DataFrame\n Index should be similar to one of the columns in this one. If a\n Series is passed, its name attribute must be set, and that will be\n used as the column name in the resulting joined DataFrame\n on : column name, tuple/list of column names, or array-like\n Column(s) in the caller to join on the index in other,\n otherwise joins index-on-index. If multiples\n columns given, the passed DataFrame must have a MultiIndex. Can\n pass an array as the join key if not already contained in the\n calling DataFrame. Like an Excel VLOOKUP operation\n how : {'left', 'right', 'outer', 'inner'}, default: 'left'\n How to handle the operation of the two objects.\n * left: use calling frame's index (or column if on is specified)\n * right: use other frame's index\n * outer: form union of calling frame's index (or column if on is\n specified) with other frame's index, and sort it\n lexicographically\n * inner: form intersection of calling frame's index (or column if\n on is specified) with other frame's index, preserving the order\n of the calling's one\n lsuffix : string\n Suffix to use from left frame's overlapping columns\n rsuffix : string\n Suffix to use from right frame's overlapping columns\n sort : boolean, default False\n Order result DataFrame lexicographically by the join key. If False,\n the order of the join key depends on the join type (how keyword)\n algorithm: {'sort', 'hash'}, default: 'sort'\n The algorithm that should be used to perform the join between two tables.\n Notes\n -----\n on, lsuffix, and rsuffix options are not supported when passing a list\n of DataFrame objects\n Examples\n --------\n >>> caller\n A key\n 0 A0 K0\n 1 A1 K1\n 2 A2 K2\n 3 A3 K3\n 4 A4 K4\n 5 A5 K5\n\n >>> other\n B key\n 0 B0 K0\n 1 B1 K1\n 2 B2 K2\n Join DataFrames using their indexes.\n >>> caller.join(other, lsuffix='_caller', rsuffix='_other')\n >>> A key_caller B key_other\n 0 A0 K0 B0 K0\n 1 A1 K1 B1 K1\n 2 A2 K2 B2 K2\n 3 A3 K3 NaN NaN\n 4 A4 K4 NaN NaN\n 5 A5 K5 NaN NaN\n If we want to join using the key columns, we need to set key to be\n the index in both caller and other. The joined DataFrame will have\n key as its index.\n >>> caller.set_index('key').join(other.set_index('key'))\n >>> A B\n key\n K0 A0 B0\n K1 A1 B1\n K2 A2 B2\n K3 A3 NaN\n K4 A4 NaN\n K5 A5 NaN\n Another option to join using the key columns is to use the on\n parameter. DataFrame.join always uses other's index but we can use any\n column in the caller. This method preserves the original caller's\n index in the result.\n >>> caller.join(other.set_index('key'), on='key')\n >>> A key B\n 0 A0 K0 B0\n 1 A1 K1 B1\n 2 A2 K2 B2\n 3 A3 K3 NaN\n 4 A4 K4 NaN\n 5 A5 K5 NaN\n See also\n --------\n DataFrame.merge : For column(s)-on-columns(s) operations\n Returns\n -------\n joined : DataFrame\n \"\"\"\n left_on = on\n if left_on is None:\n left_on = self._index_columns\n\n right_on = other._index_columns\n\n if left_on is None or len(left_on) == 0:\n raise ValueError(\n \"The column to join from left relation is no specified. Either provide 'on' or set indexing\")\n\n if right_on is None or len(right_on) == 0:\n raise ValueError(\n \"The 'other' relation doesn't have index columns specified.\")\n\n if env is None:\n joined_table = self._table.join(table=other._table, join_type=how,\n algorithm=algorithm,\n left_on=left_on, right_on=right_on,\n left_prefix=lsuffix, right_prefix=rsuffix)\n return DataFrame(joined_table)\n else:\n # attach context\n self._change_context(env=env)\n other._change_context(env=env)\n\n joined_table = self._table.distributed_join(table=other._table, join_type=how,\n algorithm=algorithm,\n left_on=left_on, right_on=right_on,\n left_prefix=lsuffix, right_prefix=rsuffix)\n return DataFrame(joined_table)\n\n def merge(self,\n right: DataFrame,\n how=\"inner\",\n algorithm=\"sort\",\n on=None,\n left_on=None,\n right_on=None,\n left_index=False,\n right_index=False,\n sort=False,\n suffixes=(\"_x\", \"_y\"),\n copy=True,\n indicator=False,\n validate=None,\n env: CylonEnv = None) -> DataFrame:\n \"\"\"\n Merge DataFrame with a database-style join.\n The join is done on columns or indexes. If joining columns on\n columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes\n on indexes or indexes on a column or columns, the index will be passed on.\n When performing a cross merge, no column specifications to merge on are\n allowed.\n\n Parameters\n ----------\n right : DataFrame or named Series\n Object to merge with.\n how : {'left', 'right', 'outer', 'inner', 'cross(Unsupported)'}, default 'inner'\n Type of merge to be performed.\n * left: use only keys from left frame, similar to a SQL left outer join;\n preserve key order.\n * right: use only keys from right frame, similar to a SQL right outer join;\n preserve key order.\n * outer: use union of keys from both frames, similar to a SQL full outer\n join; sort keys lexicographically.\n * inner: use intersection of keys from both frames, similar to a SQL inner\n join; preserve the order of the left keys.\n * cross: creates the cartesian product from both frames, preserves the order\n of the left keys.\n .. versionadded:: 1.2.0\n on : label or list\n Column or index level names to join on. These must be found in both\n DataFrames. If `on` is None and not merging on indexes then this defaults\n to the intersection of the columns in both DataFrames.\n left_on : label or list, or array-like\n Column or index level names to join on in the left DataFrame. Can also\n be an array or list of arrays of the length of the left DataFrame.\n These arrays are treated as if they are columns.\n right_on : label or list, or array-like\n Column or index level names to join on in the right DataFrame. Can also\n be an array or list of arrays of the length of the right DataFrame.\n These arrays are treated as if they are columns.\n left_index : bool, default False\n Use the index from the left DataFrame as the join key(s). If it is a\n MultiIndex, the number of keys in the other DataFrame (either the index\n or a number of columns) must match the number of levels.\n right_index : bool, default False\n Use the index from the right DataFrame as the join key. Same caveats as\n left_index.\n sort(Unsupported) : bool, default False\n Sort the join keys lexicographically in the result DataFrame. If False,\n the order of the join keys depends on the join type (how keyword).\n suffixes : list-like, default is (\"_x\", \"_y\")\n A length-2 sequence where each element is optionally a string\n indicating the suffix to add to overlapping column names in\n `left` and `right` respectively. Pass a value of `None` instead\n of a string to indicate that the column name from `left` or\n `right` should be left as-is, with no suffix. At least one of the\n values must not be None.\n copy(Unsupported) : bool, default True\n If False, avoid copy if possible.\n indicator(Unsupported) : bool or str, default False\n If True, adds a column to the output DataFrame called \"_merge\" with\n information on the source of each row. The column can be given a different\n name by providing a string argument. The column will have a Categorical\n type with the value of \"left_only\" for observations whose merge key only\n appears in the left DataFrame, \"right_only\" for observations\n whose merge key only appears in the right DataFrame, and \"both\"\n if the observation's merge key is found in both DataFrames.\n validate(Unsupported) : str, optional\n If specified, checks if merge is of specified type.\n * \"one_to_one\" or \"1:1\": check if merge keys are unique in both\n left and right datasets.\n * \"one_to_many\" or \"1:m\": check if merge keys are unique in left\n dataset.\n * \"many_to_one\" or \"m:1\": check if merge keys are unique in right\n dataset.\n * \"many_to_many\" or \"m:m\": allowed, but does not result in checks.\n Returns\n -------\n DataFrame\n A DataFrame of the two merged objects.\n See Also\n --------\n merge_ordered : Merge with optional filling/interpolation.\n merge_asof : Merge on nearest keys.\n DataFrame.join : Similar method using indices.\n Notes\n -----\n Support for specifying index levels as the `on`, `left_on`, and\n `right_on` parameters was added in version 0.23.0\n Support for merging named Series objects was added in version 0.24.0\n Examples\n --------\n >>> df1 = DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],\n ... 'value': [1, 2, 3, 5]})\n >>> df2 = DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],\n ... 'value': [5, 6, 7, 8]})\n >>> df1\n lkey value\n 0 foo 1\n 1 bar 2\n 2 baz 3\n 3 foo 5\n >>> df2\n rkey value\n 0 foo 5\n 1 bar 6\n 2 baz 7\n 3 foo 8\n\n Merge df1 and df2 on the lkey and rkey columns. The value columns have\n the default suffixes, _x and _y, appended.\n\n >>> df1.merge(df2, left_on='lkey', right_on='rkey')\n lkey value_x rkey value_y\n 0 foo 1 foo 5\n 1 foo 1 foo 8\n 2 foo 5 foo 5\n 3 foo 5 foo 8\n 4 bar 2 bar 6\n 5 baz 3 baz 7\n\n Merge DataFrames df1 and df2 with specified left and right suffixes\n appended to any overlapping columns.\n\n >>> df1.merge(df2, left_on='lkey', right_on='rkey',\n ... suffixes=('_left', '_right'))\n lkey value_left rkey value_right\n 0 foo 1 foo 5\n 1 foo 1 foo 8\n 2 foo 5 foo 5\n 3 foo 5 foo 8\n 4 bar 2 bar 6\n 5 baz 3 baz 7\n\n Merge DataFrames df1 and df2, but raise an exception if the DataFrames have\n any overlapping columns.\n\n >>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))\n Traceback (most recent call last):\n ...\n ValueError: columns overlap but no suffix specified:\n Index(['value'], dtype='object')\n\n >>> df1 = DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})\n >>> df2 = DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})\n >>> df1\n a b\n 0 foo 1\n 1 bar 2\n\n >>> df2\n a c\n 0 foo 3\n 1 baz 4\n\n >>> df1.merge(df2, how='inner', on='a')\n a b c\n 0 foo 1 3\n\n >>> df1.merge(df2, how='left', on='a')\n a b c\n 0 foo 1 3.0\n 1 bar 2 NaN\n\n >>> df1 = DataFrame({'left': ['foo', 'bar']})\n >>> df2 = DataFrame({'right': [7, 8]})\n\n >>> df1\n left\n 0 foo\n 1 bar\n\n >>> df2\n right\n 0 7\n 1 8\n\n >>> df1.merge(df2, how='cross')\n left right\n 0 foo 7\n 1 foo 8\n 2 bar 7\n 3 bar 8\n \"\"\"\n if not on is None:\n left_on = on\n right_on = on\n\n if left_index:\n left_on = self._index_columns\n\n if right_index:\n right_on = right._index_columns\n\n if left_on is None or right_on is None:\n raise ValueError(\"Columns to merge is not specified. Expected on or left_index/right_index.\"\n \"Make sure dataframes has specified index columns if using left_index/right_index\")\n\n if env is None:\n joined_table = self._table.join(table=right._table, join_type=how,\n algorithm=algorithm,\n left_on=left_on, right_on=right_on,\n left_prefix=suffixes[0], right_prefix=suffixes[1])\n return DataFrame(joined_table)\n else:\n self._change_context(env)\n right._change_context(env)\n joined_table = self._table.distributed_join(table=right._table, join_type=how,\n algorithm=algorithm,\n left_on=left_on, right_on=right_on,\n left_prefix=suffixes[0], right_prefix=suffixes[1])\n return DataFrame(joined_table)\n\n @staticmethod\n def concat(\n objs: Union[Iterable[\"DataFrame\"]],\n axis=0,\n join=\"outer\",\n ignore_index: bool = False,\n keys=None,\n levels=None,\n names=None,\n verify_integrity: bool = False,\n sort: bool = False,\n copy: bool = True,\n env: CylonEnv = None\n ) -> DataFrame:\n \"\"\"\n Concatenate DataFrames along a particular axis with optional set logic\n along the other axes.\n Can also add a layer of hierarchical indexing on the concatenation axis,\n which may be useful if the labels are the same (or overlapping) on\n the passed axis number.\n\n Cylon currently support concat along axis=0, for DataFrames having the same schema(Union). \n\n Parameters\n ----------\n objs : a sequence or mapping of Series or DataFrame objects\n If a mapping is passed, the sorted keys will be used as the `keys`\n argument, unless it is passed, in which case the values will be\n selected (see below). Any None objects will be dropped silently unless\n they are all None in which case a ValueError will be raised.\n axis : {0/'index', 1/'columns' (Unsupported)}, default 0\n The axis to concatenate along.\n join(Unsupported) : {'inner', 'outer'}, default 'outer'\n How to handle indexes on other axis (or axes).\n ignore_index(Unsupported) : bool, default False\n If True, do not use the index values along the concatenation axis. The\n resulting axis will be labeled 0, ..., n - 1. This is useful if you are\n concatenating objects where the concatenation axis does not have\n meaningful indexing information. Note the index values on the other\n axes are still respected in the join.\n keys(Unsupported) : sequence, default None\n If multiple levels passed, should contain tuples. Construct\n hierarchical index using the passed keys as the outermost level.\n levels(Unsupported) : list of sequences, default None\n Specific levels (unique values) to use for constructing a\n MultiIndex. Otherwise they will be inferred from the keys.\n names(Unsupported) : list, default None\n Names for the levels in the resulting hierarchical index.\n verify_integrity(Unsupported) : bool, default False\n Check whether the new concatenated axis contains duplicates. This can\n be very expensive relative to the actual data concatenation.\n sort(Unsupported) : bool, default False\n Sort non-concatenation axis if it is not already aligned when `join`\n is 'outer'.\n This has no effect when ``join='inner'``, which already preserves\n the order of the non-concatenation axis.\n .. versionchanged:: 1.0.0\n Changed to not sort by default.\n copy(Unsupported) : bool, default True\n If False, do not copy data unnecessarily.\n Returns\n -------\n object, type of objs\n When concatenating along\n the columns (axis=1) or rows (axis=0), a ``DataFrame`` is returned.\n\n Examples\n --------\n\n Combine two ``DataFrame`` objects with identical columns.\n\n >>> df1 = DataFrame([['a', 1], ['b', 2]],\n ... columns=['letter', 'number'])\n >>> df1\n letter number\n 0 a 1\n 1 b 2\n >>> df2 = DataFrame([['c', 3], ['d', 4]],\n ... columns=['letter', 'number'])\n >>> df2\n letter number\n 0 c 3\n 1 d 4\n >>> DataFrame.concat([df1, df2])\n letter number\n 0 a 1\n 1 b 2\n 0 c 3\n 1 d 4\n\n (Unsupported) Combine ``DataFrame`` objects with overlapping columns\n and return everything. Columns outside the intersection will\n be filled with ``NaN`` values.\n\n >>> df3 = DataFrame([['c', 3, 'cat'], ['d', 4, 'dog']],\n ... columns=['letter', 'number', 'animal'])\n >>> df3\n letter number animal\n 0 c 3 cat\n 1 d 4 dog\n >>> DataFrame.concat([df1, df3], sort=False)\n letter number animal\n 0 a 1 NaN\n 1 b 2 NaN\n 0 c 3 cat\n 1 d 4 dog\n\n (Unsupported) Combine ``DataFrame`` objects with overlapping columns\n and return only those that are shared by passing ``inner`` to\n the ``join`` keyword argument.\n\n >>> DataFrame.concat([df1, df3], join=\"inner\")\n letter number\n 0 a 1\n 1 b 2\n 0 c 3\n 1 d 4\n\n (Unsupported) Combine ``DataFrame`` objects horizontally along the x axis by\n passing in ``axis=1``.\n\n >>> df4 = DataFrame([['bird', 'polly'], ['monkey', 'george']],\n ... columns=['animal', 'name'])\n >>> DataFrame.concat([df1, df4], axis=1)\n\n letter number animal name\n 0 a 1 bird polly\n 1 b 2 monkey george\n\n (Unsupported) Prevent the result from including duplicate index values with the\n ``verify_integrity`` option.\n\n >>> df5 = DataFrame([1], index=['a'])\n >>> df5\n 0\n a 1\n >>> df6 = DataFrame([2], index=['a'])\n >>> df6\n 0\n a 2\n >>> DataFrame.concat([df5, df6], verify_integrity=True)\n Traceback (most recent call last):\n ...\n ValueError: Indexes have overlapping values: ['a']\n \"\"\"\n\n if len(objs) == 0:\n raise \"objs can't be empty\"\n\n if axis == 0:\n if env is None:\n current_table = objs[0]._table\n for i in range(1, len(objs)):\n current_table = current_table.union(objs[i]._table)\n\n return DataFrame(current_table)\n else:\n # todo not optimum for distributed\n current_table = objs[0]._change_context(env)._table\n for i in range(1, len(objs)):\n current_table = current_table.union(\n objs[i]._change_context(env)._table)\n\n return DataFrame(current_table)\n else:\n raise \"Unsupported operation\"\n\n def drop_duplicates(\n self,\n subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,\n keep: Union[str, bool] = \"first\",\n inplace: bool = False,\n ignore_index: bool = False,\n env: CylonEnv = None\n ) -> DataFrame:\n \"\"\"\n Return DataFrame with duplicate rows removed.\n Considering certain columns is optional. Indexes, including time indexes\n are ignored.\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use all of the columns.\n keep : {'first', 'last', False}, default 'first'\n Determines which duplicates (if any) to keep.\n - ``first`` : Drop duplicates except for the first occurrence.\n - ``last`` : Drop duplicates except for the last occurrence.\n - False (Unsupported): Drop all duplicates.\n inplace : bool, default False\n Whether to drop duplicates in place or to return a copy.\n ignore_index (Unsupported) : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n .. versionadded:: 1.0.0\n Returns\n -------\n DataFrame or None\n DataFrame with duplicates removed or None if ``inplace=True``(Unsupported).\n See Also\n --------\n DataFrame.value_counts: Count unique combinations of columns.\n Examples\n --------\n Consider dataset containing ramen rating.\n >>> df = DataFrame({\n ... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],\n ... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],\n ... 'rating': [4, 4, 3.5, 15, 5]\n ... })\n >>> df\n brand style rating\n 0 Yum Yum cup 4.0\n 1 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 3 Indomie pack 15.0\n 4 Indomie pack 5.0\n By default, it removes duplicate rows based on all columns.\n >>> df.drop_duplicates()\n brand style rating\n 0 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 3 Indomie pack 15.0\n 4 Indomie pack 5.0\n To remove duplicates on specific column(s), use ``subset``.\n >>> df.drop_duplicates(subset=['brand'])\n brand style rating\n 0 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n To remove duplicates and keep last occurrences, use ``keep``.\n >>> df.drop_duplicates(subset=['brand', 'style'], keep='last')\n brand style rating\n 1 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 4 Indomie pack 5.0\n \"\"\"\n if env is None:\n return DataFrame(self._table.unique(columns=subset, keep=keep, inplace=inplace))\n else:\n return DataFrame(self._change_context(env)._table.distributed_unique(columns=subset, inplace=inplace))\n\n def sort_values(\n self,\n by,\n axis=0,\n ascending=True,\n inplace=False,\n kind=\"quicksort\",\n na_position=\"last\",\n ignore_index=False,\n key=None,\n env: CylonEnv = None\n ) -> DataFrame:\n \"\"\"\n Sort by the values along either axis.\n Parameters\n ----------\n\n axis : %(axes_single_arg)s, default 0\n Axis to be sorted.\n ascending : bool or list of bool, default True\n Sort ascending vs. descending. Specify list for multiple sort\n orders. If this is a list of bools, must match the length of\n the by.\n inplace(Unsupported) : bool, default False\n If True, perform operation in-place.\n kind(Unsupported) : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'\n Choice of sorting algorithm. See also :func:`numpy.sort` for more\n information. `mergesort` and `stable` are the only stable algorithms. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position(Unsupported) : {'first', 'last'}, default 'last'\n Puts NaNs at the beginning if `first`; `last` puts NaNs at the\n end.\n ignore_index(Unsupported) : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n .. versionadded:: 1.0.0\n key(Unsupported) : callable, optional\n Apply the key function to the values\n before sorting. This is similar to the `key` argument in the\n builtin :meth:`sorted` function, with the notable difference that\n this `key` function should be *vectorized*. It should expect a\n ``Series`` and return a Series with the same shape as the input.\n It will be applied to each column in `by` independently.\n .. versionadded:: 1.1.0\n Returns\n -------\n DataFrame or None\n DataFrame with sorted values or None if ``inplace=True``.\n See Also\n --------\n DataFrame.sort_index : Sort a DataFrame by the index.\n Series.sort_values : Similar method for a Series.\n Examples\n --------\n >>> df = DataFrame({\n ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],\n ... 'col2': [2, 1, 9, 8, 7, 4],\n ... 'col3': [0, 1, 9, 4, 2, 3],\n ... 'col4': ['a', 'B', 'c', 'D', 'e', 'F']\n ... })\n >>> df\n col1 col2 col3 col4\n 0 A 2 0 a\n 1 A 1 1 B\n 2 B 9 9 c\n 3 NaN 8 4 D\n 4 D 7 2 e\n 5 C 4 3 F\n Sort by col1\n >>> df.sort_values(by=['col1'])\n col1 col2 col3 col4\n 0 A 2 0 a\n 1 A 1 1 B\n 2 B 9 9 c\n 5 C 4 3 F\n 4 D 7 2 e\n 3 NaN 8 4 D\n Sort by multiple columns\n >>> df.sort_values(by=['col1', 'col2'])\n col1 col2 col3 col4\n 1 A 1 1 B\n 0 A 2 0 a\n 2 B 9 9 c\n 5 C 4 3 F\n 4 D 7 2 e\n 3 NaN 8 4 D\n Sort Descending\n >>> df.sort_values(by='col1', ascending=False)\n col1 col2 col3 col4\n 4 D 7 2 e\n 5 C 4 3 F\n 2 B 9 9 c\n 0 A 2 0 a\n 1 A 1 1 B\n 3 NaN 8 4 D\n \"\"\"\n if env is None:\n return DataFrame(self._table.sort(order_by=by, ascending=ascending))\n else:\n return DataFrame(self._change_context(env)._table.distributed_sort(order_by=by, ascending=ascending))\n","sub_path":"python/pycylon/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":60964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489919068","text":"import sys\nimport pyfits\nimport random\nimport numpy as np\nimport os\nimport utils\n\ndef choose_best_dark(filelist):\n darks=[]\n i=1\n\n while 1==1:\n filename=\"masterdark0_\" + str(i) + \".fits\"\n if not os.path.isfile(filename): break\n i += 1\n\n imagetemps = []\n for filename in filelist:\n imagetemps.append(pyfits.open(filename)[0].header[\"ccdtemp\"])\n median_temp = np.median(imagetemps)\n\n min_temp_diff = 1000\n min_dark = None\n\n for index in range(1, i):\n filename = \"masterdark0_\" + str(index) + \".fits\"\n hdu=pyfits.open(filename)[0]\n darktemp = hdu.header[\"tempmed\"]\n diff = abs(darktemp - median_temp)\n if diff < min_temp_diff:\n min_temp_diff = diff\n min_dark = index\n return min_dark\n\noutputdir = sys.argv[1]\nfilelist = sys.argv[2:]\nif len(filelist)==0: exit(-1)\n\nmasterdark_index = choose_best_dark(filelist)\n\ntmpfolder = \"tmp/flat\" + str(random.randint(0,10000000)) + \"/\"\nos.mkdir(tmpfolder)\n\nutils.split_by_channel(filelist, tmpfolder, False)\n\n#for each channel, invoke do_masterflat.py\n#command_queue = []\nfor ch in range(4):\n biasname = \"masterbias\" + str(ch) + \".fits\"\n darkname = \"masterdark\" + str(ch) + \"_\" + str(masterdark_index) + \".fits\"\n flatname = outputdir + \"masterflat\" + str(ch) + \".fits\"\n\n call_str = \"python ~hatuser/HATpipebin/include/HATpipepy/Actions/do_masterflat.py --master-bias=\" + biasname + \" --master-dark=\" + darkname + \" \" + \\\n \"HATnet \" + tmpfolder + \"*_\" + str(ch) + \".fits\" + \" -o \" + flatname\n os.system(call_str)\n# command_queue.append(call_str)\n\n#utils.run_all(command_queue)\n","sub_path":"do_3d_masterflat.py","file_name":"do_3d_masterflat.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477137416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2019/8/20\n# @Author : github.com/guofei9987\n\n\nimport numpy as np\nfrom .base import SkoBase\nfrom sko.tools import func_transformer\nfrom abc import ABCMeta, abstractmethod\nfrom .operators import crossover, mutation, ranking, selection\n\nclass GeneticAlgorithmBase(SkoBase, metaclass=ABCMeta):\n def __init__(self, func, n_dim,\n size_pop=50, max_iter=200, prob_mut=0.001,\n constraint_eq=tuple(), constraint_ueq=tuple()):\n self.func = func_transformer(func)\n assert size_pop % 2 == 0, 'size_pop must be even integer'\n self.size_pop = size_pop # size of population\n self.max_iter = max_iter\n self.prob_mut = prob_mut # probability of mutation\n self.n_dim = n_dim\n\n # constraint:\n self.has_constraint = len(constraint_eq) > 0 or len(constraint_ueq) > 0\n self.constraint_eq = list(constraint_eq) # a list of equal functions with ceq[i] = 0\n self.constraint_ueq = list(constraint_ueq) # a list of unequal constraint functions with c[i] <= 0\n\n self.Chrom = None\n self.X = None # shape = (size_pop, n_dim)\n self.Y_raw = None # shape = (size_pop,) , value is f(x)\n self.Y = None # shape = (size_pop,) , value is f(x) + penalty for constraint\n self.FitV = None # shape = (size_pop,)\n\n # self.FitV_history = []\n self.generation_best_X = []\n self.generation_best_Y = []\n\n self.all_history_Y = []\n self.all_history_FitV = []\n\n self.best_x, self.best_y = None, None\n\n @abstractmethod\n def chrom2x(self, Chrom):\n pass\n\n def x2y(self): # Restricted function processing\n self.Y_raw = self.func(self.X) # Perform function conversion, func_transformer\n if not self.has_constraint:\n self.Y = self.Y_raw\n else:\n # constraint\n penalty_eq = np.array([np.sum(np.abs([c_i(x) for c_i in self.constraint_eq])) for x in self.X])\n penalty_ueq = np.array([np.sum(np.abs([max(0, c_i(x)) for c_i in self.constraint_ueq])) for x in self.X])\n self.Y = self.Y_raw + 1e5 * penalty_eq + 1e5 * penalty_ueq\n return self.Y\n\n @abstractmethod\n def ranking(self):\n pass\n\n @abstractmethod\n def selection(self):\n pass\n\n @abstractmethod\n def crossover(self):\n pass\n\n @abstractmethod\n def mutation(self):\n pass\n\n def run(self, max_iter=None):\n self.max_iter = max_iter or self.max_iter\n for i in range(self.max_iter):\n self.X = self.chrom2x(self.Chrom)\n self.Y = self.x2y()\n self.ranking()\n self.selection()\n self.crossover()\n self.mutation()\n\n # record the best ones\n generation_best_index = self.FitV.argmin()\n self.generation_best_X.append(self.X[generation_best_index, :])\n self.generation_best_Y.append(self.Y[generation_best_index])\n self.all_history_Y.append(self.Y)\n self.all_history_FitV.append(self.FitV)\n\n global_best_index = np.array(self.generation_best_Y).argmin()\n self.best_x = self.generation_best_X[global_best_index]\n self.best_y = self.func(np.array([self.best_x]))\n return self.best_x, self.best_y\n\n fit = run\n\nclass GA_EdgeVideo(GeneticAlgorithmBase):\n\n def __init__(self, func,caching_decision, last_best_offloading_decision, n_dim, size_pop=50, max_iter=200, prob_mut=0.001):\n super().__init__(func, n_dim, size_pop=size_pop, max_iter=max_iter, prob_mut=prob_mut)\n self.has_constraint = False\n self.caching_decision = caching_decision\n self.last_best_offloading_decision = last_best_offloading_decision\n self.len_chrom = self.n_dim\n self.crtbp()\n\n def crtbp(self):\n # create the population\n # The population is population number * chromosome length, and the value is\n # (a random number between 0 and 6, which means unloading to different computing nodes)\n # According to the given model cache decision, make the initialization task offload decision\n num_model_in_edge = [] # The number of models on each edge node\n num_model_in_edge.append(3) # Probability of unloading to local\n for edge in range(len(self.caching_decision)):\n num_model_in_edge.append(len(self.get_index1(self.caching_decision[edge])))\n # The probability of generating a random number, the more the number of models,\n # the greater the probability of unloading to that node\n # Probability of uninstalling to the cloud\n num_model_in_edge.append(5)\n rate = num_model_in_edge/np.sum(num_model_in_edge)\n self.Chrom = np.random.choice(a=range(len(num_model_in_edge)), size=[self.size_pop, self.len_chrom], p=rate)\n # self.Chrom = np.random.randint(0,7,size=[self.size_pop, self.len_chrom])\n if len(self.last_best_offloading_decision): # Not empty, not the first time\n self.Chrom[0] = self.last_best_offloading_decision # Replaced with the best unloading decision from the previous round\n print(\"Non-empty, replace the best decision\")\n return self.Chrom\n\n def chrom2x(self, Chrom):\n return Chrom\n\n ranking = ranking.ranking\n selection = selection.selection_tournament_faster\n crossover = crossover.crossover_2point_prob\n mutation = mutation.mutation_reverse\n\n def run(self, max_iter=None):\n self.max_iter = max_iter or self.max_iter\n for i in range(self.max_iter):\n print(\"iteration\"+str(i))\n Chrom_old = self.Chrom.copy()\n self.X = self.chrom2x(self.Chrom)\n self.Y = self.x2y()\n self.ranking()\n self.selection()\n self.crossover(0.5)\n self.mutation()\n\n # put parent and offspring together and select the best size_pop number of population\n self.Chrom = np.concatenate([Chrom_old, self.Chrom], axis=0)\n self.X = self.chrom2x(self.Chrom)\n self.Y = self.x2y()\n self.ranking()\n selected_idx = np.argsort(self.Y)[:self.size_pop]\n self.Chrom = self.Chrom[selected_idx, :]\n\n # record the best ones\n generation_best_index = self.FitV.argmax()\n self.generation_best_X.append(self.X[generation_best_index, :].copy())\n self.generation_best_Y.append(self.Y[generation_best_index])\n self.all_history_Y.append(self.Y.copy())\n self.all_history_FitV.append(self.FitV.copy())\n\n global_best_index = np.array(self.generation_best_Y).argmin()\n self.best_x = self.generation_best_X[global_best_index]\n self.best_y = self.func(np.array([self.best_x]))\n return self.best_x, self.best_y\n\n def get_index1(self, lst=None, item=0):\n return [index for (index, value) in enumerate(lst) if value == item]\n\nclass GA_EdgeVideo_Y(GeneticAlgorithmBase):\n\n def __init__(self, func,best_caching_decision, n_edge, n_user,n_CNNmodel, n_dim, size_pop=50, max_iter=200, prob_mut=0.001):\n super().__init__(func, n_dim, size_pop=size_pop, max_iter=max_iter, prob_mut=prob_mut)\n self.has_constraint = False\n self.best_caching_decision = best_caching_decision\n self.n_edge = n_edge\n self.n_user = n_user\n self.n_CNNmodel = n_CNNmodel\n self.len_chrom = self.n_dim\n self.crtbp()\n\n def crtbp(self):\n self.Chrom = np.random.randint(0,2,size=[self.size_pop, self.len_chrom])\n if len(self.best_caching_decision):\n self.Chrom[0] = self.best_caching_decision\n return self.Chrom\n\n def chrom2x(self, Chrom):\n return Chrom\n\n ranking = ranking.ranking\n selection = selection.selection_tournament_faster\n crossover = crossover.crossover_2point\n mutation = mutation.mutation\n\n def run(self, max_iter=None):\n self.max_iter = max_iter or self.max_iter\n for i in range(self.max_iter):\n print(\"iteration\"+str(i))\n Chrom_old = self.Chrom.copy()\n self.X = self.chrom2x(self.Chrom)\n self.Y = self.x2y()\n self.ranking()\n self.selection()\n self.crossover()\n self.mutation()\n\n # put parent and offspring together and select the best size_pop number of population\n self.Chrom = np.concatenate([Chrom_old, self.Chrom], axis=0)\n self.X = self.chrom2x(self.Chrom)\n self.Y = self.x2y()\n self.ranking()\n selected_idx = np.argsort(self.Y)[:self.size_pop]\n self.Chrom = self.Chrom[selected_idx, :]\n\n # record the best ones\n generation_best_index = self.FitV.argmax()\n\n self.generation_best_X.append(self.X[generation_best_index, :].copy())\n self.generation_best_Y.append(self.Y[generation_best_index])\n self.all_history_Y.append(self.Y.copy())\n self.all_history_FitV.append(self.FitV.copy())\n\n global_best_index = np.array(self.generation_best_Y).argmin()\n self.best_x = self.generation_best_X[global_best_index]\n self.best_y = self.func(np.array([self.best_x]))\n return self.best_x, self.best_y\n","sub_path":"sko/GA_TR.py","file_name":"GA_TR.py","file_ext":"py","file_size_in_byte":9338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"117017166","text":"from helpers import find_best_question, LeafNode, DecisionNode\nclass DecisionTree:\n def __init__(self):\n self.root = None\n\n def train(self, train):\n '''Recursive function to establish full tree, returns root node'''\n info_gain, question = find_best_question(train)\n\n if info_gain == 0:\n return LeafNode(train)\n\n t_branch, f_branch = question.ask(train)\n \n return DecisionNode(question, self.train(t_branch), self.train(f_branch))\n\n def fit(self, train):\n '''Calls the train function to set the tree's root node'''\n self.root = self.train(train)\n \n def get_pred(self, test, node):\n if isinstance(node, LeafNode):\n most_counts = 0\n pred = None\n for p in node.preds:\n if node.preds[p] > most_counts:\n most_counts = node.preds[p]\n pred = p\n return pred\n \n t, _ = node.question.ask([test])\n if len(t) > 0:\n return self.get_pred(test, node.t_branch)\n else:\n return self.get_pred(test, node.f_branch)\n\n def predict(self, test):\n if self.root:\n preds = []\n for t in test:\n preds.append(self.get_pred(t, self.root))\n return preds\n else:\n return \"You must fit the model before getting predictions\"\n\n def print_tree(self, node):\n if isinstance(node, LeafNode):\n return node.preds\n \n print(f't: {node.t_branch}, f: {node.f_branch}, {node.question}')\n return self.print_tree(node.t_branch), self.print_tree(node.f_branch)\n \n def tree_print(self):\n return self.print_tree(self.root)","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155541295","text":"from django.db import models\nimport api.models as api_models\nfrom urlparse import parse_qs\nfrom django.db.models import Q\nfrom django.conf import settings\n\nclass Contest(models.Model):\n begin = models.DateTimeField(null=True)\n end = models.DateTimeField(null=True)\n name = models.CharField(max_length=300)\n best_girl = models.BooleanField(default=False)\n best_card = models.BooleanField(default=False)\n query = models.CharField(max_length=4092, null=True)\n\n def alter_key(self, key):\n if key == 'is_event':\n return 'event__isnull'\n return key\n\n def alter_value(self, key, value):\n if value == 'False':\n return False\n elif value == 'True':\n return True\n return value\n\n def queryset(self):\n params = self.query\n if self.pk == settings.GLOBAL_CONTEST_ID:\n return api_models.Card.objects.all()\n if params.startswith('?'):\n params_parsed = parse_qs(params[1:])\n params = {self.alter_key(key): self.alter_value(key, value[0]) for key, value in params_parsed.iteritems()}\n queryset = api_models.Card.objects.filter(**params).all()\n return queryset\n else:\n cards = [int(num) for num in params.split(',')]\n condition = Q()\n for card in cards:\n condition = condition | Q(id=card)\n return api_models.Card.objects.filter(condition)\n\nclass Vote(models.Model):\n\tcontest = models.ForeignKey(Contest, related_name='votes')\n\tcard = models.ForeignKey(api_models.Card, related_name='votes')\n\tidolized = models.BooleanField(default=False)\n\tcounter = models.PositiveIntegerField(default=0)\n\nclass Session(models.Model):\n\tright = models.ForeignKey(Vote, related_name='right')\n\tleft = models.ForeignKey(Vote, related_name='left')\n\tfingerprint = models.CharField(max_length=300)\n\tcontest = models.ForeignKey(Contest, related_name='sessions')\n\ttoken = models.CharField(max_length=36)\n\tdate = models.DateTimeField()\n","sub_path":"contest/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"465901473","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 2 02:16:55 2019\n\n@author: DoraMemo\n\"\"\"\n\nimport math\n\ndef part2fuel(mass):\n if (mass <= 6):\n return 0\n \n fuel = math.floor(mass/3)-2\n return fuel + part2fuel(fuel)\n\n\n\nwith open(\"input.txt\") as f:\n content = f.readlines()\n# you may also want to remove whitespace characters like `\\n` at the end of each line\ncontent = [x.strip() for x in content]\ncontent = [int(x) for x in content]\n\ntotal = 0\nfor mass in content:\n total += part2fuel(mass)\n \nprint(total)","sub_path":"Day1/aoc2019d1.py","file_name":"aoc2019d1.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"36500252","text":"import uuid\nimport pytz\nfrom datetime import datetime, timedelta\n\nfrom flask import render_template, url_for, session, redirect, request\nfrom flask_login import login_required, login_user, logout_user, current_user\n\nfrom evechem import app, eve_api, db\nfrom evechem.models.user import User, Character, Auth\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('home'))\n\n@app.route('/login')\ndef login():\n return eve_api.authorize(callback=url_for('sso',\n next=url_for('home') or request.referrer or None,\n _external=True,\n _scheme='https'))\n\n@app.route('/sso/')\ndef sso():\n if current_user.is_authenticated:\n logout_user()\n resp = eve_api.authorized_response()\n session['evesso_token'] = (resp['access_token'],'')\n\n # acquire character information\n verify = eve_api.get(app.config['EVESSO_VERIFY_URL'])\n\n c_id = verify.data['CharacterID']\n ownerhash = verify.data['CharacterOwnerHash']\n\n character = Character.query.get(c_id)\n\n\n if character is None:\n # make new character and user\n character = Character(\n id=c_id,\n ownerhash=ownerhash,\n name=verify.data['CharacterName'],\n scopes=verify.data['Scopes']\n )\n\n user = User(\n id=uuid.uuid4().hex,\n created_on=datetime.now(pytz.utc),\n active_character_id=character.id\n )\n\n user.characters.append(character)\n db.session.add(character)\n db.session.add(user)\n user.new_session()\n\n elif character.ownerhash != ownerhash:\n # character changed owner, make new user and update\n old_user = character.user\n if old_user.active_character_id == character.id:\n old_user.active_character_id = None\n\n \n user = User(\n id=uuid.uuid4().hex,\n created_on=datetime.now(pytz.utc),\n active_character_id=character.id\n )\n\n character.ownerhash = ownerhash\n character.user_id = user.id\n\n db.session.add(user)\n user.new_session()\n\n else:\n # character found\n character.scopes = verify.data['Scopes']\n user = character.user\n user.active_character_id = character.id\n user.new_session()\n auth = Auth.query.get(c_id)\n expires_on = datetime.now(pytz.utc) + timedelta(seconds=resp['expires_in'])\n if auth is None:\n auth = Auth(\n character_id=c_id,\n access_token=resp['access_token'],\n expires_in=resp['expires_in'],\n expires_on=expires_on,\n refresh_token=resp['refresh_token'],\n token_type=resp['token_type'],\n )\n\n db.session.add(auth)\n\n else:\n auth.access_token = resp['access_token']\n auth.expires_in = resp['expires_in']\n auth.expires_on = expires_on\n auth.refresh_token = resp['refresh_token']\n auth.token_type = resp['token_type']\n\n \n db.session.commit()\n login_success = login_user(user)\n response = redirect(request.args.get('next', url_for('home')))\n\n return response\n","sub_path":"evechem/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"449684153","text":"import json\nimport logging\nimport os\n\nimport autokeras as ak\nimport numpy as np\nimport pandas as pd\nfrom igel.cnn.defaults import Defaults\nfrom igel.cnn.models import Models\nfrom igel.constants import Constants\nfrom igel.utils import read_json, read_yaml\nfrom tensorflow.keras.preprocessing import image\n\nlogger = logging.getLogger(__name__)\n\n\nclass IgelCNN:\n defaults = Defaults()\n x = None\n y = None\n model = None\n results_path = Constants.results_dir\n\n def __init__(self, **cli_args):\n self.cmd: str = cli_args.get(\"cmd\")\n self.data_path: str = cli_args.get(\"data_path\")\n self.config_path: str = cli_args.get(\"yaml_path\")\n logger.info(f\"Executing command: {self.cmd}\")\n logger.info(f\"Reading data from: {self.data_path}\")\n logger.info(f\"Reading yaml configs from: {self.config_path}\")\n\n if self.cmd == \"train\":\n self.file_ext: str = self.config_path.split(\".\")[1]\n\n if self.file_ext != \"yaml\" and self.file_ext != \"json\":\n raise Exception(\n \"Configuration file can be a yaml or a json file!\"\n )\n\n self.configs: dict = (\n read_json(self.config_path)\n if self.file_ext == \"json\"\n else read_yaml(self.config_path)\n )\n\n self.dataset_props: dict = self.configs.get(\n \"dataset\", self.defaults.dataset_props\n )\n self.model_props: dict = self.configs.get(\n \"model\", self.defaults.model_props\n )\n self.target: list = self.configs.get(\"target\")\n self.model_type = self.model_props.get(\"type\")\n self.model_args = self.model_props.get(\"arguments\")\n\n else:\n self.model_path = cli_args.get(\n \"model_path\", self.defaults.model_path\n )\n logger.info(f\"path of the pre-fitted model => {self.model_path}\")\n self.prediction_file = cli_args.get(\n \"prediction_file\", self.defaults.prediction_file\n )\n # set description.json if provided:\n self.description_file = cli_args.get(\n \"description_file\", self.defaults.description_file\n )\n # load description file to read stored training parameters\n with open(self.description_file) as f:\n dic = json.load(f)\n self.target: list = dic.get(\n \"target\"\n ) # target to predict as a list\n self.model_type: str = dic.get(\"type\") # type of the model\n self.dataset_props: dict = dic.get(\n \"dataset_props\"\n ) # dataset props entered while fitting\n getattr(self, self.cmd)()\n\n def _create_model(self, *args, **kwargs):\n model_cls = Models.get(self.model_type)\n model = (\n model_cls() if not self.model_args else model_cls(**self.model_args)\n )\n return model\n\n def _convert_img_to_np_array(self, paths):\n\n images = []\n logger.info(f\"Reading images and converting them to arrays...\")\n for path in paths:\n img = image.load_img(path, grayscale=True)\n img_arr = np.asarray(img)\n images.append(img_arr)\n return np.array(images)\n\n def _read_dataset(self):\n # read_data_options = self.dataset_props.get(\"read_data_options\", {})\n # dataset = pd.read_csv(self.data_path, **read_data_options)\n # logger.info(f\"dataset shape: {dataset.shape}\")\n # attributes = list(dataset.columns)\n # logger.info(f\"dataset attributes: {attributes}\")\n # y = pd.concat([dataset.pop(x) for x in self.target], axis=1)\n # logger.info(f\"x shape: {dataset.shape} | y shape: {y.shape}\")\n # x = dataset.to_numpy()\n # num_images = x.shape[0]\n # x = x.reshape((num_images,))\n # self.x = self._convert_img_to_np_array(x)\n # self.y = y.to_numpy()\n # logger.info(\n # f\"After reading images: x shape {self.x.shape} | y shape: {self.y.shape}\"\n # )\n train_data = ak.image_dataset_from_directory(\n self.data_path, subset=\"training\", validation_split=0.2, seed=42\n )\n return train_data # self.x, self.y\n\n def save_model(self, model):\n exp_model = model.export_model()\n logger.info(f\"model type: {type(exp_model)}\")\n try:\n exp_model.save(\"model\", save_format=\"tf\")\n return True\n except Exception:\n exp_model.save(f\"model.h5\")\n\n def train(self):\n train_data = self._read_dataset()\n self.model = self._create_model()\n logger.info(f\"executing a {self.model.__class__.__name__} algorithm...\")\n logger.info(f\"Training started...\")\n self.model.fit(train_data)\n saved = self.save_model(self.model)\n if saved:\n logger.info(f\"model saved successfully\")\n","sub_path":"igel/cnn/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"591100112","text":"from __future__ import division\nimport pytest\nimport numpy as np\nimport fast_carpenter.masked_tree as m_tree\n\n\n@pytest.fixture\ndef tree_no_mask(infile, full_event_range):\n return m_tree.MaskedUprootTree(infile, event_ranger=full_event_range)\n\n\n@pytest.fixture\ndef tree_w_mask_bool(infile, event_range):\n mask = np.ones(event_range.entries_in_block, dtype=bool)\n mask[::2] = False\n return m_tree.MaskedUprootTree(infile, event_ranger=event_range, mask=mask)\n\n\n@pytest.fixture\ndef tree_w_mask_int(infile, event_range):\n mask = np.ones(event_range.entries_in_block, dtype=bool)\n mask[::2] = False\n mask = np.where(mask)[0]\n return m_tree.MaskedUprootTree(infile, event_ranger=event_range, mask=mask)\n\n\ndef test_no_mask(tree_no_mask, infile):\n assert len(tree_no_mask) == len(infile)\n assert tree_no_mask.mask is None\n assert np.all(tree_no_mask.pandas.df(\"EventWeight\") == infile.pandas.df(\"EventWeight\"))\n\n\ndef test_w_mask_bool(tree_w_mask_bool, infile):\n assert len(tree_w_mask_bool) == 50\n df = tree_w_mask_bool.pandas.df(\"NMuon\")\n assert len(df) == 50\n new_mask = np.ones(len(tree_w_mask_bool), dtype=bool)\n new_mask[::2] = False\n tree_w_mask_bool.apply_mask(new_mask)\n assert len(tree_w_mask_bool) == 25\n\n\ndef test_w_mask_int(tree_w_mask_int, infile):\n assert len(tree_w_mask_int) == 50\n tree_w_mask_int.apply_mask(np.arange(0, len(tree_w_mask_int), 2))\n assert len(tree_w_mask_int) == 25\n df = tree_w_mask_int.pandas.df(\"Muon_Px\")\n assert len(df.index.unique(0)) == 25\n","sub_path":"tests/test_masked_tree.py","file_name":"test_masked_tree.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"617499586","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport inspection.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('inspection', '0005_officeinspection_image'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DailyInspection',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cateory', models.CharField(default=b'people', max_length=30, verbose_name='cateory', choices=[(b'people', b'People'), (b'device', b'Device'), (b'machine', b'Machine'), (b'method', b'Method'), (b'environment', b'Environment')])),\n ('item', models.CharField(max_length=30, verbose_name='item')),\n ('impact', models.TextField(max_length=30, verbose_name='impact')),\n ('correct', models.TextField(max_length=30, verbose_name='correct')),\n ('correct_status', models.CharField(default=b'notcomplete', max_length=30, verbose_name='correct status', choices=[(b'complete', b'Complete'), (b'notcomplete', b'Not Complete')])),\n ('owner', models.CharField(max_length=30, verbose_name='owner')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('image_before', models.ImageField(null=True, upload_to=inspection.models.image_upload_to, blank=True)),\n ('image_after', models.ImageField(null=True, upload_to=inspection.models.image_upload_to, blank=True)),\n ('warehouse', models.CharField(default=b'3#', max_length=30, verbose_name='warehouse', choices=[(b'3', b'3#'), (b'5', b'5#')])),\n ],\n ),\n ]\n","sub_path":"inspection/migrations/0006_dailyinspection.py","file_name":"0006_dailyinspection.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161381961","text":"from flask import Flask, request, render_template, redirect, url_for\nfrom flask_login import LoginManager, login_manager\nfrom posts import post_app\nfrom auth import auth_app\nfrom models import Session, User\n\napp = Flask(__name__)\napp.config.update(\n DEBUG=True,\n SECRET_KEY='asdvsadvafnveowinbdfkmb;kn;fldgn;ldskgnbd',\n)\napp.register_blueprint(post_app, url_prefix='/posts/')\napp.register_blueprint(auth_app, url_prefix='/auth/')\n\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return Session.query(User).filter_by(id=user_id).one_or_none()\n\n\n@login_manager.unauthorized_handler\ndef unauthorized():\n return redirect(url_for('index', unauthorized_redirect=True))\n\n\n@app.route('/', methods=('GET',), endpoint='index')\ndef index():\n header = 'Благодатная Жижа'\n links = (\n {'url': url_for('index'), 'name': 'Главная', 'active': False},\n )\n unauthorized_redirected = request.args.get('unauthorized_redirect')\n\n return render_template('index.html', header=header, links=links, unauthorized_redirect=unauthorized_redirected)\n\n\n@app.teardown_request\ndef remove_session(*args):\n Session.remove()\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"111919159","text":"from django.shortcuts import render, get_object_or_404\n\nfrom CartridgeSelector.models import Merk, Type, Soort, Cartridge\nimport urllib2\nfrom xml.dom.minidom import parseString\n\n# Create your views here.\ndef merken(request):\n # download the file:\n file = urllib2.urlopen('http://qntcartridgeselectorxml.prepublisher.eu/Brands.aspx?id=17020')\n # convert to string:\n data = file.read()\n #close file because we dont need it anymore:\n file.close()\n #parse the xml you downloaded\n dom = parseString(data)\n\n for node in dom.getElementsByTagName('brand'): # visit every node \n #get node id\n id = node.attributes[\"id\"]\n #get node naam\n naam = node.getElementsByTagName(\"name\")\n #get node image\n imageurl = node.getElementsByTagName(\"imageurl\")\n #create merk object with id value, naam value and image value\n merk = Merk(id=id.value, name=naam[0].firstChild.nodeValue, imageurl=imageurl[0].firstChild.nodeValue)\n #save object in db\n merk.save()\n\n context = Merk.objects.all()\n return render(request, 'cartridgeselector/merken.html', {'context': context})\n\n\ndef soorten(request, merk_id):\n url = 'http://qntcartridgeselectorxml.prepublisher.eu/PrinterSystems.aspx?id=17020&brandid=' + merk_id\n # download the file:\n file = urllib2.urlopen(url)\n # convert to string:\n data = file.read()\n #close file because we dont need it anymore:\n file.close()\n #parse the xml you downloaded\n dom = parseString(data)\n\n merk = get_object_or_404(Merk, pk=merk_id)\n\n for node in dom.getElementsByTagName('printersystem'): # visit every node \n #get node id\n id = node.attributes[\"id\"]\n #get node naam\n naam = node.getElementsByTagName(\"name\")\n\n #create merk object with id value, naam value and image value\n soort = Soort(id=id.value, name=naam[0].firstChild.nodeValue, merk=merk)\n #save object in db\n soort.save()\n\n return render(request, 'cartridgeselector/soort.html', {'merk': merk})\n\n\ndef types(request, merk_id, soort_id):\n # http://qntcartridgeselectorxml.prepublisher.eu/PrinterTypes.aspx?id=17020&brandid=1&printersystemid=15\n\n url = 'http://qntcartridgeselectorxml.prepublisher.eu/Printers.aspx?id=17020&brandid=' + merk_id + '&printersystemid=' + soort_id\n # download the file:\n file = urllib2.urlopen(url)\n #convert to string:\n data = file.read()\n #close file because we dont need it anymore:\n file.close()\n #parse the xml you downloaded\n dom = parseString(data)\n merk = get_object_or_404(Merk, pk=merk_id)\n soort = get_object_or_404(Soort, pk=soort_id)\n\n for node in dom.getElementsByTagName('printer'): # visit every node \n #get node id\n id = node.attributes[\"id\"]\n #get node naam\n naam = node.getElementsByTagName(\"model\")\n\n #create merk object with id value, naam value and image value\n type = Type(id=id.value, name=naam[0].firstChild.nodeValue, merk=merk, soort=soort)\n #save object in db\n type.save()\n\n return render(request, 'cartridgeselector/type.html',\n {'typelist': Type.objects.filter(merk=merk_id, soort=soort_id)})\n\n\ndef detail(request, merk_id, soort_id, type_id):\n # http://qntcartridgeselectorxml.prepublisher.eu/Supplies.aspx?id=17020&printerid=324532\n url = 'http://qntcartridgeselectorxml.prepublisher.eu/Supplies.aspx?id=17020&printerid=' + type_id\n #download the file:\n file = urllib2.urlopen(url)\n #convert to string:\n data = file.read()\n #close file because we dont need it anymore:\n file.close()\n #parse the xml you downloaded\n dom = parseString(data)\n\n for node in dom.getElementsByTagName('supply'): # visit every node \n\n id = node.attributes[\"id\"]\n supplierarticlenr = node.getElementsByTagName(\"supplierarticlenr\")\n oemnumber = node.getElementsByTagName(\"oemnumber\")\n eanproduct = node.getElementsByTagName(\"eanproduct\")\n #imageurl = node.getElementsByTagName(\"imageurl\")\n #pages = node.getElementsByTagName(\"pages\")\n #pack = node.getElementsByTagName(\"pack\")\n #supplysubcategory = node.getElementsByTagName(\"supplysubcategory\")\n\n #create merk object with id value, naam value and image value\n cartridge = Cartridge(id=id.value,\n supplierarticlenr=supplierarticlenr[0].firstChild.nodeValue,\n oemnumber=oemnumber[0].firstChild.nodeValue,\n eanproduct=eanproduct[0].firstChild.nodeValue,)\n #imageurl=imageurl[1].firstChild.nodeValue,)\n #pages=pages[0].firstChild.nodeValue,\n #pack=pack[0].firstChild.nodeValue,\n #supplysubcategory=supplysubcategory[0].firstChild.nodeValue, )\n cartridge.save()\n\n #from cartridge also insert linkedprinters that can use this cartridge as well\n for node in dom.getElementsByTagName('linkedprinter'):\n printer_id = node.attributes[\"printerid\"]\n printer = int(float(printer_id.value))\n try:\n type = Type.objects.get(id=printer)\n cartridge.type.add(type)\n except Type.DoesNotExist:\n # we have no object!\n pass\n\n variable = get_object_or_404(Type, pk=type_id)\n return render(request, 'cartridgeselector/detail.html', {'variable': variable})","sub_path":"CartridgeSelectorWeststrate/CartridgeSelector/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605296099","text":"#! /usr/bin/python3\nfrom threading import Lock\nfrom NI import *\nimport sys, traceback\nimport Crypto\nfrom Crypto.Hash import SHA256\nfrom Crypto.Cipher import AES\n\nclass DpaState:\n def __init__(self):\n self.status = {}\n self.log_data = []\n self.mutex = Lock()\n\n def log(self, message):\n self.mutex.acquire()\n try:\n self.log_data.append(\"{0}\\n\".format(message))\n finally:\n self.mutex.release()\n\n def set_status(self, key, value):\n self.mutex.acquire()\n try:\n self.status[key] = value\n finally:\n self.mutex.release()\n\n def get_status(self):\n self.mutex.acquire()\n try:\n data = dict(self.status)\n data['log'] = list(self.log_data)\n except:\n self.mutex.release()\n return data\n\n def clear(self):\n self.mutex.acquire()\n try:\n self.log_data.clear()\n self.status.clear()\n finally:\n self.mutex.release()\n\ndef to_binary(hexstring, size=0):\n b = bytearray.fromhex(hexstring)\n\n if size != 0 and len(b) < size:\n for i in range(size - len(b)):\n b.append(0)\n return b\n\nclass CryptoAdapter:\n def __init__(self, task, state):\n self.task = task\n self.state = state\n self.state.set_status('state', 'stopped')\n\n def wait_for_response(self, msg):\n pkt = self.dev.os_recv(retry=False)\n reply = Message(pkt)\n self.state.log(reply.print_msg('recv'))\n if reply.getCommand() == msg.getCommand() and reply.getType() == MESSAGE_TYPES_ENUM['RESPONSE']:\n errorCode = reply.getErrorCode()\n if errorCode == ERROR_CODES_ENUM['SUCCESS']:\n return reply\n else:\n self.state.log(\"get wrong error code {0}\".format(errorCode))\n self.state.log(\"do not get expected response, failed\")\n raise NiException(\"wrong response received\")\n\n def rsa_decrypt(self, key_type, n, e, d, p, q, dp, dq, u, input_data, rounds):\n self.state.log(\"doing rsa decrypt\")\n return True\n\n def symmetric_gcm_encrypt(self, key, key_type, iv, aad, input_data, rounds):\n self.state.log(\"gcm encrption not supported yet\")\n return False\n\n def symmetric_gcm_decrypt(self, key, key_type, iv, aad, tag, input_data, rounds):\n self.state.log(\"gcm decryption not supported yet\")\n return False\n\n def symmetric_crypto(self, key, key_type, op, mode, iv, input_data, rounds):\n self.state.log(\"do symmetric encrypt for {0} - {1} [{2}]\".format(key_type, mode, rounds))\n testcmd = Command(SERVICE_IDS_ENUM['UPC_SERVICE'], SERVICE_IDS_ENUM['TAL'], COMMANDS_ENUM['DPA_TEST'], MESSAGE_TYPES_ENUM['COMMAND'])\n testcmd.setUint32(PARAMETER_NAMES['DPA_ROUNDS'], rounds)\n if key_type[0:3] == 'aes':\n if len(key) == 16:\n key_type = KEY_TYPE_ENUM['AES_128']\n elif len(key) == 32:\n key_type = KEY_TYPE_ENUM['AES_256']\n else:\n self.state.log(\"wrong aes key length, not supported : {0}\".format(len(key)))\n return False\n elif key_type[0:4] == '3des' or key_type[0:4] == 'tdea':\n key_type = KEY_TYPE_ENUM['TDEA']\n if len(key) != 16:\n self.state.log(\"wrong tripple des key length : {0}\".format(len(key)))\n return False\n elif key_type == 'des':\n key_type = KEY_TYPE_ENUM['DES']\n if len(key) != 8:\n self.state.log(\"wrong des key length : {0}\".format(len(key)))\n return False\n\n testcmd.setByte(PARAMETER_NAMES['DPA_KEY_TYPE'], key_type)\n testcmd.addBinary(PARAMETER_NAMES['DPA_KEY'], key)\n testcmd.addBinary(PARAMETER_NAMES['DPA_INPUT'], input_data)\n testcmd.setByte(PARAMETER_NAMES['DPA_OP'], op)\n if mode == 'cbc':\n mode = CIPHER_MODE_ENUM['CBC']\n elif mode == 'ecb':\n mode = CIPHER_MODE_ENUM['ECB']\n else:\n self.state.log(\"do not support the crypto mode : {0}\".format(mode))\n return False\n\n testcmd.setByte(PARAMETER_NAMES['DPA_MODE'], mode)\n testcmd.addBinary(PARAMETER_NAMES['DPA_IV'], iv)\n self.state.log(testcmd.print_msg('send'))\n self.dev.os_send_msg(testcmd)\n reply = self.wait_for_response(testcmd)\n rdata = reply.getBinary(PARAMETER_NAMES['DPA_RESULT'], 0)\n self.state.log(\"crypto returns result\")\n self.state.log(bytes(rdata).hex())\n\n if key_type == KEY_TYPE_ENUM['AES_256'] and mode == CIPHER_MODE_ENUM['CBC']:\n self.state.log(\"verifying result for AES 256\")\n self.state.log(\"key {0}\".format(bytes(key).hex()))\n self.state.log(\"iv {0}\".format(bytes(iv).hex()))\n self.state.log(\"input {0}\".format(bytes(input_data).hex()))\n self.state.log(\"encrypt [{0}] result:\".format(op))\n\n cipher = AES.new(bytes(key), AES.MODE_CBC, bytes(iv))\n if op == 1:\n rdata = cipher.encrypt(bytes(input_data))\n else:\n rdata = cipher.decrypt(bytes(input_data))\n self.state.log(\"{0}\".format(rdata.hex()))\n\n return True\n\n def execute(self):\n self.state.set_status('state', 'running')\n self.state.log(\"start executing harness\")\n ret = False\n try:\n self.dev = CommChannel()\n if self.dev.exist():\n self.dev.os_open()\n self.state.log(\"Communication channel opened\")\n ret = self._execute()\n else:\n self.state.log(\"communication channel does not exist!, exit\")\n except:\n self.state.log(\"fatal exception in adapter\")\n exceptions = traceback.format_exc()\n print(\"{0}\".format(exceptions))\n for line in exceptions.splitlines():\n self.state.log(line)\n finally:\n self.dev.os_close()\n\n self.state.log(\"harness end\")\n self.state.set_status('result', ret)\n self.state.set_status('state', 'stopped')\n\n def _execute(self):\n\n if 'key_type' not in self.task or 'input' not in self.task:\n self.log_print(\"do not find key_type or/and/ input exit\")\n return False\n input_data = to_binary(self.task['input'])\n key_type = self.task['key_type']\n\n rounds = 1\n if 'rounds' in self.task:\n rounds = int(self.task['rounds'])\n\n if key_type[0:3] == 'rsa':\n if key_type == 'rsa2048':\n modulus_length = 256\n p_length = 128\n else:\n self.state.log(\"unsupported rsa key type : {0}\".format(key_type))\n return False\n\n n = to_binary(self.task['n'])\n e = to_binary(self.task['e'], 4)\n d = to_binary(self.task['d'])\n p = to_binary(self.task['p'])\n q = to_binary(self.task['q'])\n dp = to_binary(self.task['dp'])\n dq = to_binary(self.task['dq'])\n u = to_binary(self.task['u'])\n\n if len(n) != modulus_length or len(e) != 4 or len(d) != modulus_length or \\\n len(input_data) != modulus_length or \\\n len(p) != p_length or len(q) != p_length or \\\n len(dp) != p_length or len(dq) != p_length or len(u) != p_length:\n self.state.log(\"wrong length of rsa parameter\")\n return False\n\n return self.rsa_decrypt(key_type, n, e, d, p, q, dp, dq, u, input_data, rounds)\n else:\n key = to_binary(self.task['key'])\n op = self.task['op']\n if 'mode' in self.task:\n mode = self.task['mode']\n else:\n mode = 'cbc'\n iv = '00'\n if 'iv' in self.task:\n iv = self.task['iv']\n\n if key_type == '3des' or key_type == 'tdea' or 'key_type' == 'des':\n iv = to_binary(iv, 8)\n else:\n iv = to_binary(iv, 16)\n\n if mode == 'gcm':\n aad = to_binary(self.task['aad'], 16)\n if len(aad) != 16:\n self.state.log(\"we only suport 128 bit aad now\")\n return False\n if op == 'dec':\n tag = to_binary(self.task['tag'])\n if len(tag) != len(aad):\n self.state.log(\"wrong size for tag\")\n return False\n return self.symmetric_gcm_decrypt(key, key_type, iv, aad, tag, input_data, rounds)\n else:\n return self.symmetric_gcm_encrypt(key, key_type, iv, aad, input_data, rounds)\n elif op == 'enc':\n return self.symmetric_crypto(key, key_type, 1, mode, iv, input_data, rounds)\n else:\n return self.symmetric_crypto(key, key_type, 0, mode, iv, input_data, rounds)\n\n return True\n\n","sub_path":"fw-upc/dpa/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":9068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"128091430","text":"import os\nimport qt\nimport queue_item\nimport queue_model_objects_v1 as queue_model_objects\n\nfrom widgets.confirm_dialog_widget_vertical_layout \\\n import ConfirmDialogWidgetVerticalLayout\n\nclass FileListViewItem(qt.QListViewItem):\n\n def __init__(self, *args, **kwargs):\n qt.QListViewItem.__init__(self, *args)\n self.brush = qt.QBrush(qt.Qt.black)\n self.__normal_brush = qt.QBrush(qt.Qt.black)\n \n \n def paintCell(self, painter, color_group, column, width, align):\n try:\n painter.save()\n \n color_group = qt.QColorGroup(color_group)\n color_group.setColor(qt.QColorGroup.Text, self.brush.color())\n color_group.setBrush(qt.QColorGroup.Text, self.brush)\n \n qt.QListViewItem.paintCell(self, painter, color_group, \n column, width, align)\n finally:\n painter.restore()\n\n\n def set_brush(self, qt_brush):\n self.brush = qt_brush\n\n\nclass ConfirmDialog(qt.QDialog):\n def __init__(self, parent = None, name = None, fl = 0):\n qt.QWidget.__init__(self, parent, name, fl)\n\n # Attributes\n self.ready_event = False\n self.checked_items = []\n self.sample_items = []\n self.files_to_be_written = []\n self.item_run_number_list = []\n self.queue_model_hwobj = None\n \n # Layout\n qt.QVBoxLayout(self)\n self.dialog_layout_widget = ConfirmDialogWidgetVerticalLayout(self)\n self.dialog_layout_widget.child('take_snapshosts_cbx').hide()\n self.dialog_layout_widget.child('file_list_view').setSorting(-1)\n self.layout().addWidget(self.dialog_layout_widget)\n\n qt.QObject.connect(self.dialog_layout_widget.continue_button,\n qt.SIGNAL(\"clicked()\"),\n self.continue_button_click)\n\n qt.QObject.connect(self.dialog_layout_widget.cancel_button,\n qt.SIGNAL(\"clicked()\"),\n self.cancel_button_click)\n\n self.dialog_layout_widget.take_snapshosts_cbx.setOn(False)\n self.dialog_layout_widget.force_dark_cbx.setOn(True)\n\n self.dialog_layout_widget.take_snapshosts_cbx.hide()\n self.dialog_layout_widget.missing_one_cbx.hide()\n self.dialog_layout_widget.missing_two_cbx.hide()\n self.setCaption('Confirm collection')\n\n\n def disable_dark_current_cbx(self):\n self.dialog_layout_widget.force_dark_cbx.setEnabled(False)\n self.dialog_layout_widget.force_dark_cbx.setOn(False)\n\n\n def enable_dark_current_cbx(self):\n self.dialog_layout_widget.force_dark_cbx.setEnabled(True)\n self.dialog_layout_widget.force_dark_cbx.setOn(True)\n \n\n def set_items(self, checked_items):\n self.sample_items = []\n self.files_to_be_written = []\n self.checked_items = checked_items\n collection_items = []\n current_sample_item = None\n num_images = 0\n\n self.dialog_layout_widget.file_list_view.clear()\n\n for item in checked_items:\n if isinstance(item, queue_item.SampleQueueItem):\n self.sample_items.append(item)\n current_sample_item = item \n\n path_template = item.get_model().get_path_template()\n\n if path_template:\n# if item.get_model().is_executed():\n# self.item_run_number_list.append((item, path_template.run_number))\n\n# # Increase the run-number for re-collect\n# new_run_number = self.queue_model_hwobj.\\\n# get_next_run_number(path_template,\n# exclude_current = False)\n# item.get_model().set_number(new_run_number)\n# path_template.run_number = new_run_number\n\n collection_items.append(item)\n file_paths = path_template.get_files_to_be_written()\n num_images += len(file_paths)\n\n for fp in file_paths:\n (dir_name, f_name) = os.path.split(fp)\n sample_name = current_sample_item.get_model().get_display_name()\n\n if sample_name is '':\n sample_name = current_sample_item.get_model().loc_str\n\n last_item = self.dialog_layout_widget.child('file_list_view').lastItem()\n fl = FileListViewItem(self.dialog_layout_widget.file_list_view,\n last_item, sample_name, dir_name, f_name)\n\n if os.path.isfile(fp):\n fl.set_brush(qt.QBrush(qt.Qt.red))\n\n num_samples = len(self.sample_items)\n num_collections = len(collection_items)\n\n self.dialog_layout_widget.\\\n summary_label.setText(\"Collecting \" + str(num_collections) + \\\n \" collection(s) on \" + str(num_samples) + \\\n \" sample(s) resulting in \" + \\\n str(num_images) + \" image(s).\")\n\n\n def continue_button_click(self):\n for item in self.checked_items:\n if isinstance(item.get_model(), queue_model_objects.DataCollection):\n #item.get_model().acquisitions[0].acquisition_parameters.\\\n # take_snapshots = False #self.dialog_layout_widget.take_snapshosts_cbx.isOn()\n item.get_model().acquisitions[0].acquisition_parameters.\\\n take_dark_current = self.dialog_layout_widget.force_dark_cbx.isOn()\n item.get_model().acquisitions[0].acquisition_parameters.\\\n skip_existing_images = self.dialog_layout_widget.skip_existing_images_cbx.isOn()\n \n self.emit(qt.PYSIGNAL(\"continue_clicked\"), (self.sample_items, self.checked_items))\n self.accept()\n\n\n def cancel_button_click(self):\n# for item, run_number in self.item_run_number_list:\n# item.get_model().set_number(run_number)\n# path_template = item.get_model().get_path_template()\n# path_template.run_number = run_number\n \n self.reject()\n\n\nif __name__ == \"__main__\":\n a = qt.QApplication(sys.argv)\n qt.QObject.connect(a, qt.SIGNAL(\"lastWindowClosed()\"),\n a, qt.SLOT(\"quit()\"))\n \n w = ConfirmDialog()\n #a.setMainWidget(w)\n w.setModal(True)\n w.show()\n a.exec_loop()\n","sub_path":"Bricks/widgets/confirm_dialog.py","file_name":"confirm_dialog.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"468107912","text":"from django.db import models\n\n# Create your models here.\n\n\nclass Class(models.Model):\n id = models.AutoField(primary_key=True)\n cname = models.CharField(max_length=32)\n first_day = models.DateField()\n\n\nclass Student(models.Model):\n sname = models.CharField(max_length=32)\n cid = models.ForeignKey(to=Class, to_field=\"id\")\n\n\nclass StudentDetail(models.Model):\n height = models.PositiveIntegerField()\n weight = models.PositiveIntegerField()\n email = models.EmailField()\n\n\nclass Teacher(models.Model):\n tname = models.CharField(max_length=32)\n cid = models.ManyToManyField(to=\"Class\", related_name=\"teachers\")\n\n","sub_path":"mysite2/app02/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"183692300","text":"import openai\n\nimport api_key_chatgpt_local as api_key\n\nopenai.api_key = api_key.get_openai_key()\n\ndef get_completion(prompt, model=\"gpt-3.5-turbo\", temperature = 0, messages = None):\n if messages is None:\n messages = [{\"role\": \"user\", \"content\": prompt}]\n response = openai.ChatCompletion.create(\n model=model,\n messages=messages,\n # Temperature is the degree of randomness of the model's output\n # 0 would be same each time. 0.7 or 1 would be difference each time, and less likely words can be used:\n temperature=temperature,\n )\n return response.choices[0].message[\"content\"]\n\ndef send_prompt(prompt, show_input = True, show_output = True, temperature = 0):\n if show_input:\n print(\"=== INPUT ===\")\n print(prompt)\n\n response = get_completion(prompt, temperature=temperature)\n\n if show_output:\n print(\"=== RESPONSE ===\")\n print(response)\n\n return response\n\ndef send_prompt_messages(messages, temperature = 0):\n last_message = messages[-1:]\n print(\"=== LAST MESSAGE ===\")\n print(last_message)\n rsp = get_completion(prompt=None, temperature=temperature, messages=messages)\n print(\"=== RESPONSE ===\")\n print(rsp)\n","sub_path":"deeplearning.ai/ML-Andrew-Ng--ChatGPT-Prompt-Engineering-2023/util_chat.py","file_name":"util_chat.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"126074166","text":"\"\"\"\nProvides default comparison functions to be used in the RBTree\nIncluding standard <, > and ==,\nalong with arc comparisons for beachline use\n\"\"\"\n#pylint: disable=unused-argument\nfrom enum import Enum\nimport logging as root_logger\n\nlogging = root_logger.getLogger(__name__)\nDirections = Enum('Directions', 'LEFT RIGHT')\n\n#funcs take a node, a value, and data to contextualise\n\ndef default_comparison(a, b, comp_data):\n \"\"\" Standard smallest to largest comparison function \"\"\"\n if a.value < b:\n return Directions.RIGHT\n return Directions.LEFT\n\ndef inverted_comparison(a, b, comp_data):\n \"\"\" Standard largest to smallest comparison function \"\"\"\n if a.value < b:\n return Directions.LEFT\n return Directions.RIGHT\n\ndef default_equality(a, b, eq_data):\n \"\"\" Standard Equality test \"\"\"\n return a.value == b\n\ndef arc_equality(a, b, eq_data):\n \"\"\" Compare two arcs for equality \"\"\"\n #return true if a.pred|a < b < a|a.succ\n l_inter, r_inter = __arc_intersects(a, b, eq_data)\n result = False\n if l_inter is not None and r_inter is not None:\n result = l_inter < b < r_inter\n elif r_inter is not None:\n result = b < r_inter\n elif l_inter is not None:\n result = l_inter < b\n return result\n\ndef arc_comparison(a, b, comp_data):\n \"\"\" Function to compare an arc and xposition\n Used in Beachline/Voronoi \"\"\"\n l_inter, r_inter = __arc_intersects(a, b, comp_data)\n pred_self = False\n self_succ = False\n\n if l_inter is None and r_inter is None: #Base case: single arc\n if b < a.value.fx:\n return Directions.LEFT\n else:\n return Directions.RIGHT\n\n if l_inter is not None:\n if b < l_inter:\n pred_self = True\n if r_inter is not None:\n if r_inter < b:\n self_succ = True\n\n if pred_self:\n return Directions.LEFT\n if self_succ:\n return Directions.RIGHT\n\n return Directions.LEFT\n\ndef __arc_intersects(a, b, comp_data):\n \"\"\" Internal function to test if two arcs intersect \"\"\"\n pred = a.getPredecessor()\n succ = a.getSuccessor()\n pred_intersect = None\n succ_intersect = None\n pred_intersect_out = None\n succ_intersect_out = None\n pred_above_self = None\n succ_above_self = None\n\n if pred is not None:\n pred_intersect = a.value.intersect(pred.value)\n pred_above_self = a.value.fy < pred.value.fy\n\n if succ is not None:\n succ_intersect = succ.value.intersect(a.value)\n succ_above_self = a.value.fy < succ.value.fy\n\n if pred_intersect is not None and len(pred_intersect) == 1:\n pred_intersect_out = pred_intersect[0, 0]\n elif pred_intersect is not None and len(pred_intersect) == 2:\n if pred_above_self:\n pred_intersect_out = pred_intersect[0, 0]\n else:\n pred_intersect_out = pred_intersect[1, 0]\n\n if succ_intersect is not None and len(succ_intersect) == 1:\n succ_intersect_out = succ_intersect[0, 0]\n elif succ_intersect is not None and len(succ_intersect) == 2:\n if succ_above_self:\n succ_intersect_out = succ_intersect[1, 0]\n else:\n succ_intersect_out = succ_intersect[0, 0]\n\n return (pred_intersect_out, succ_intersect_out)\n","sub_path":"cairo_utils/rbtree/comparison_functions.py","file_name":"comparison_functions.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"325733412","text":"import random\r\n\r\nf = open(\"C:\\__KATROSS DELL\\_PROGRAMMING\\SQL\\MySQL Code\\Table data_mar_28_comment_fixed.csv\", 'r')\r\ndata = f.read()\r\n\r\nrows = data.split(\"\\n\")\r\nnested_list = []\r\n\r\n# makes a list of lists with each record as a separate list\r\nfor el in rows:\r\n x = el.split(',')\r\n nested_list.append(x)\r\n \r\n#the values start at [1] because the header was not removed\r\n\r\nnested_list = [[x.replace(' ','_') for x in l] for l in nested_list] \r\n \r\ndef categories(list_name, category_name, category_ID):\r\n# appends lists corresponding to a certain category to a new, empty list\r\n# the values in the inner lists have not been converted to integers/booleans, \r\n#they are all strings\r\n for i in list_name:\r\n catID = i[len(i)-1]\r\n the_rest = i[0:len(i)-1]\r\n if catID == category_ID:\r\n category_name.append(the_rest) \r\n return \r\n\r\nprint(\"\\n\")\r\n\r\nlist_name = nested_list\r\n\r\ntops = []\r\ncategory_name = tops\r\ncategories(nested_list, tops, \"1\")\r\n\r\nbottoms = []\r\ncategory_name = bottoms\r\ncategories(nested_list, bottoms, \"2\")\r\n\r\noutwear = []\r\ncategory_name = outwear\r\ncategories(nested_list, outwear, \"3\")\r\n\r\ndresses_etc = []\r\ncategory_name = dresses_etc\r\ncategories(nested_list, dresses_etc, \"4\")\r\n\r\nshoes = []\r\ncategory_name = shoes\r\ncategories(nested_list, shoes, \"5\")\r\n\r\nbags = []\r\ncategory_name = bags\r\ncategories(nested_list, bags, \"6\")\r\n\r\ndef inner_f():\r\n \r\n i1 = random.choice(tops)\r\n i2 = random.choice(bottoms)\r\n i3 = random.choice(shoes)\r\n i4 = random.choice(outwear)\r\n i5 = random.choice(bags)\r\n # i6 = random.choice(dresses_etc)\r\n \r\n #the whole outfit goes in a list of lists\r\n #dresses will be dealt with later\r\n global outfit \r\n outfit = []\r\n outfit.extend((i1, i2, i3, i4, i5))\r\n \r\n print(\"OUTFIT FOR TODAY:\" + \"\\n\")\r\n \r\n # works, prints all the fields,\r\n # but the result looks messy, hard to read all the (unrelevant) digits\r\n # print('\\n''\\n'.join(', '.join(map(str,sl)) for sl in outfit))\r\n \r\n # this prints an easy to read result\r\n print(i1[2] + \", \" + i1[3] + \", \" + i1[5] + \", \" + i1[7] + \", \" + i1[9])\r\n print(\"+\")\r\n print(i2[2] + \", \" + i2[3] + \", \" + i2[5] + \", \" + i2[7] + \", \" + i2[9])\r\n print(\"+\")\r\n print(i3[2] + \", \" + i3[3] + \", \" + i3[5] + \", \" + i3[7] + \", \" + i3[9])\r\n print(\"+\")\r\n print(i4[2] + \", \" + i4[3] + \", \" + i4[5] + \", \" + i4[7] + \", \" + i4[9])\r\n print(\"+\")\r\n print(i5[2] + \", \" + i5[3] + \", \" + i5[5] + \", \" + i5[7] + \", \" + i5[9]) \r\n print(\"\\n\")\r\n \r\n return outfit\r\n\r\ndef inner_f2(inner_f):\r\n item = random.choice(outfit)\r\n return item\r\n\r\ndef create_outfit(): \r\n \r\n \r\n outfit = inner_f() # creates a list of 5 lists\r\n item = inner_f2(outfit) # removes a random item from the list to compare against the rest\r\n \r\n def weather(outfit):\r\n # weather check\r\n if item[6] == \"CLD\" and any(t[6] for t in f) == \"WRM\":\r\n inner_f()\r\n if item[6] == \"WNT\" and any(t[6] for t in f) != \"CLD\":\r\n inner_f()\r\n outfit.append(item)\r\n return outfit \r\n \r\n def shape(outfit):\r\n # shape check \r\n # fitted items should only be combined with oversized ones, and vice versa \r\n if item[len(item)-1] == \"1\" and any(t[len(t)-1] for t in f) == \"2\":\r\n if item[len(item)-6] == \"2\" and item[len(item)-6] == \"1\":\r\n inner_f()\r\n outfit.append(item)\r\n return outfit \r\n \r\n \r\n def occasion(outfit):\r\n # occasion check\r\n if item[8] == \"D\" and any(t[len(t)-10] for t in f) == \"C\":\r\n inner_f() \r\n outfit.append(item)\r\n return outfit \r\n \r\n \r\n def color(outfit):\r\n # color check - chooses colors that match\r\n while item[len(item)-10] == \"bright\" and any(t[len(t)-10] for t in f) != \"neutral\":\r\n inner_f()\r\n break\r\n while item[len(item)-10] == \"jewel\" and any(t[len(t)-10] for t in f) != \"neutral\":\r\n inner_f()\r\n break\r\n while item[len(item)-10] == \"earth\" and any(t[len(t)-10] for t in f) != \"neutral\" or any(t[len(t)-10] for t in f) != \"metallic\":\r\n inner_f()\r\n break\r\n while item[len(item)-10] == \"pastel\" and any(t[len(t)-10] for t in f) != \"neutral\" or any(t[len(t)-10] for t in f) != \"metallic\":\r\n inner_f()\r\n break\r\n while item[len(item)-10] == \"multi\" and any(t[len(t)-10] for t in f) != \"neutral\" or any(t[len(t)-10] for t in f) != \"metallic\":\r\n inner_f()\r\n break\r\n while item[len(item)-10] == \"neutral\" and any(t[len(t)-10] for t in f) != \"earth\" or any(t[len(t)-10] for t in f) != \"metallic\" or any(t[len(t)-10] for t in f) != \"neutral\":\r\n inner_f()\r\n while item[len(item)-10] == \"metallic\" and any(t[len(t)-10] for t in f) != \"metallic\":\r\n inner_f()\r\n break \r\n \r\n outfit.append(item) \r\n return outfit\r\n \r\n def style(outfit): \r\n # style check \r\n # \"M\" stands for \"modern\", \"E\" for \"everyday\" \r\n # for an outfit not to look like a Halloween costume, at least one item must be \"M\" or \"E\"\r\n if \"M\" or \"E\" in any(t[len(t)-5] for t in f):\r\n for i in outfit:\r\n ct = (i[len(t)-5]).count(\"M\")\r\n ct2 = (i[len(t)-5]).count(\"E\")\r\n if ct < 1 and ct2 < 1:\r\n inner_f()\r\n outfit.append(item)\r\n # bohemian items look interesting with futuristic ones\r\n while \"B\" in any(t[len(t)-5] for t in f) and \"F\" not in any(t[len(t)-5] for t in f) or \"C\" not in any(t[len(t)-5] for t in f):\r\n inner_f()\r\n # classic and bohemian do not work well together \r\n while \"B\" in any(t[len(t)-5] for t in f) and \"C\" in any(t[len(t)-5] for t in f):\r\n inner_f()\r\n # there must be no more than one statement item in an outfit\r\n while \"T\" in item([len(item)-5]) and \"T\" in any(t[len(t)-5] for t in f):\r\n inner_f()\r\n \r\n # fabrick check \r\n # no wool on wool\r\n if item[4] == \"1\" and any(t[4] for t in f) == \"1\":\r\n inner_f()\r\n # no leather on leather, except for shoes\r\n if item[4] == \"4\" and any(t[4] for t in f) == \"4\":\r\n if [len(item)-1] == \"1\" and any(t[len(t)-1] for t in f) == \"2\":\r\n inner_f()\r\n return\r\n \r\n return\r\n \r\ncreate_outfit()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"5_3_2017_cleaner.py","file_name":"5_3_2017_cleaner.py","file_ext":"py","file_size_in_byte":6586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"362616039","text":"import numpy as np\n\nfrom extensive_form.games.extensive_game import State, Game, Environment\n\n\nclass DeepSeaState(State):\n\n def __init__(self, index, depth, player, actions, action_map=None, payoffs=None, successors=None):\n self._index = index\n self._depth = depth\n self._player = player\n self._actions = actions\n\n self._action_map = action_map or np.arange(actions)\n\n self._payoffs = payoffs\n self._successors = successors\n\n def _key(self):\n return self._index\n\n def depth(self):\n return self._depth\n\n def active_players(self):\n return [self._player]\n\n def num_actions(self, player_id):\n return self._actions\n\n def payoffs(self, actions):\n if self._payoffs is None:\n return [0., 0.]\n else:\n return self._payoffs[self._action_map[actions[0]]]\n\n def successors(self, actions): \n if self._successors is None:\n return []\n\n successor = self._successors[self._action_map[actions[0]]]\n \n if successor is None:\n return []\n else:\n return [successor]\n\n def transitions(self, actions):\n return [1.]\n\n def descendants(self):\n if self._successors is None:\n return []\n else:\n return [s for s in self._successors if s is not None]\n\n\ndef build_deep_sea(index, depth, size, penalty, payoff, player):\n\n # Compute payoffs given player\n if 0 == player:\n penalties = [[penalty, 0.], [0., penalty]]\n else:\n penalties = [[0., penalty], [penalty, 0.]]\n payoff = 1. - payoff\n\n # Build last layer of game - this is where we get the big payoff if we reach the goal\n final_depth = depth + size - 1\n last_layer = []\n\n\n for _ in range(size - 1):\n last_layer.append(DeepSeaState(index=index, \n depth=final_depth, \n player=player,\n actions=1,\n payoffs=[[1. - payoff, payoff]]))\n index += 1\n\n last_layer.append(DeepSeaState(index=index, \n depth=final_depth,\n player=player,\n actions=1,\n payoffs=[[payoff, 1. - payoff]]))\n index += 1\n\n # Build intermediate layers - in reverse depth order\n for layer_depth in range(final_depth - 1, depth - 1, -1):\n layer = []\n\n for idx in range(size):\n left= last_layer[max(idx - 1, 0)]\n right = last_layer[min(idx + 1, size - 1)]\n\n layer.append(DeepSeaState(index=index, \n depth=layer_depth, \n player=player,\n actions=2,\n payoffs=[[penalty, 0.], [0., penalty]], \n successors=[left, right]))\n index += 1\n\n last_layer = layer\n \n # Define initial states\n return last_layer[0], index\n\n\nclass DoubleDecoyDeepSea(Game):\n\n def __init__(self, config={}):\n \n # Get configuration\n decoy_trees = config.get(\"decoy_games\", 1)\n\n decoy_size = config.get(\"decoy_size\", 5)\n decoy_payoff = config.get(\"decoy_payoff\", 1.)\n\n adversary_size = config.get(\"adversary_size\", 5)\n adversary_payoff = config.get(\"adversary_payoff\", 1.)\n\n target_size = config.get(\"target_size\", decoy_size)\n target_payoff = config.get(\"target_payoff\", 1.)\n\n target_penalty = config.get(\"penalty\", 0.)\n\n # Initialize state index\n index = 0\n\n # Build decoy games\n decoy_penalty = target_penalty * (target_size - 1) / (decoy_size - 1)\n decoy_roots = []\n\n for _ in range(decoy_trees):\n decoy_root, index = build_deep_sea(index=index,\n depth=3,\n size=decoy_size,\n penalty=decoy_penalty,\n payoff=decoy_payoff,\n player=0)\n\n decoy_roots.append(decoy_root)\n\n # Build adversary games\n adversary_penalty = target_penalty * (target_size - 1) / (adversary_size - 1)\n adversary_roots = []\n\n for _ in range(decoy_trees):\n adversary_root, index = build_deep_sea(index=index,\n depth=3,\n size=decoy_size,\n penalty=adversary_penalty,\n payoff=adversary_payoff,\n player=1)\n\n adversary_roots.append(adversary_root)\n\n # Build adversary nodes for decoy trees\n root_nodes = []\n\n for decoy_root, adversary_root in zip(decoy_roots, adversary_roots):\n root_nodes.append(DeepSeaState(index=index,\n depth=2,\n player=1,\n actions=2,\n successors=[decoy_root, adversary_root]))\n index += 1\n\n # Build target tree\n target_root, index = build_deep_sea(index=index,\n depth=2,\n size=target_size,\n penalty=target_penalty,\n payoff=target_payoff,\n player=0)\n \n target_pos = np.random.randint(0, len(root_nodes))\n root_nodes.insert(target_pos, target_root)\n\n # Build root node\n self._root = DeepSeaState(index=index, \n depth=1,\n player=0,\n actions=decoy_trees + 1, \n successors=root_nodes)\n \n # Compute maximum payoff and depth\n self._max_payoff = 1. + (target_size - 1) * target_penalty\n self._max_depth = max(decoy_size, target_size) + 2\n\n def num_players(self):\n return 2\n\n def max_depth(self):\n return self._max_depth\n\n def max_payoff(self):\n return self._max_payoff\n\n def initial_states(self):\n return [self._root]\n\n def initial_distribution(self):\n return [1.]\n\n def build_env(self):\n return DecoyEnvironment(self)\n\n\nclass DecoyEnvironment(Environment):\n\n def __init__(self, game):\n super(DecoyEnvironment, self).__init__(game)\n\n def get_stats(self, state, actions):\n if \"target_count\" not in self._stats:\n self._stats[\"target_count\"] = 0\n self._stats[\"decoy_count\"] = 0\n\n if self._game._root == state:\n if actions[0] == (state.num_actions(0) - 1):\n self._stats[\"target_count\"] += 1\n else:\n self._stats[\"decoy_count\"] += 1\n","sub_path":"finite_games/extensive_form/games/double_decoy_deep_sea.py","file_name":"double_decoy_deep_sea.py","file_ext":"py","file_size_in_byte":7276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499766204","text":"import os\nfrom dotenv import load_dotenv\ndotenv_path = os.path.join(os.path.dirname(__file__), '.env')\nif os.path.exists(dotenv_path):\n load_dotenv(dotenv_path)\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Config:\n SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'\n SSL_REDIRECT = False\n SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI') or \\\n 'sqlite:///' + os.path.join(basedir, 'data.sqlite')\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_BINDS = {\n 'local': os.environ.get('LOCAL_DB_URI')\n }\n\n @staticmethod\n def init_app(app) -> None:\n pass\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n\n\nclass TestingConfig(Config):\n TESTING = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or 'sqlite://'\n\n\nclass DockerConfig(Config):\n\n @classmethod\n def init_app(cls, app) -> None:\n Config.init_app(app)\n\n # log to stderr\n import logging\n from logging import StreamHandler\n file_handler = StreamHandler()\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'testing': TestingConfig,\n 'docker': DockerConfig,\n 'default': DevelopmentConfig\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550754276","text":"def average(student):\n _sum = 0\n for value in student.values():\n _sum += value\n return _sum / len(student)\n\ndef main():\n student = {}\n while True:\n name = input(\"Name: \")\n if len(name) == 0:\n break\n score = input(\"Score:\")\n student[name] = int(score)\n for key, value in student.items():\n if value > average(student):\n print(key, value)\n\nmain()\n","sub_path":"Algorithm/Python/高于平均分.py","file_name":"高于平均分.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"648768227","text":"import numpy as np\nimport os\nfrom typing import Dict, List, Tuple\n\nclass ReplayBuffer:\n \"\"\"A simple numpy replay buffer.\"\"\"\n\n def __init__(self, obs_dim: int, size: int, batch_size: int = 32):\n self.obs_buf = np.zeros([size, obs_dim], dtype=np.float32)\n self.next_obs_buf = np.zeros([size, obs_dim], dtype=np.float32)\n self.acts_buf = np.zeros([size], dtype=np.float32)\n self.rews_buf = np.zeros([size], dtype=np.float32)\n self.done_buf = np.zeros(size, dtype=np.float32)\n self.max_size, self.batch_size = size, batch_size\n self.ptr, self.size, = 0, 0\n\n def store(\n self,\n obs: np.ndarray,\n act: np.ndarray, \n rew: float, \n next_obs: np.ndarray, \n done: bool,\n ):\n self.obs_buf[self.ptr] = obs\n self.next_obs_buf[self.ptr] = next_obs\n self.acts_buf[self.ptr] = act\n self.rews_buf[self.ptr] = rew\n self.done_buf[self.ptr] = done\n # if buffer is full, replace the oldest one\n self.ptr = (self.ptr + 1) % self.max_size\n # after stored, buffer size plus one, but no more than the max_size\n self.size = min(self.size + 1, self.max_size)\n\n def sample_batch(self) -> Dict[str, np.ndarray]:\n # replace=False means samples that taken can not be repeated\n idxs = np.random.choice(self.size, size=self.batch_size, replace=False)\n return dict(obs=self.obs_buf[idxs],\n next_obs=self.next_obs_buf[idxs],\n acts=self.acts_buf[idxs],\n rews=self.rews_buf[idxs],\n done=self.done_buf[idxs])\n\n def __len__(self) -> int:\n return self.size","sub_path":"common/experience_replay.py","file_name":"experience_replay.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"376124099","text":"import discord\nfrom discord import Embed\nimport os\nfrom os import path\n\nperm = 0\n\ndef get(nr):\n f = \"membids/\" + nr\n if path.isfile(f):\n with open(f) as f:\n return f.read()\n else:\n return None\n\n\nasync def ex(args, message, client, invoke, arg1, arg2):\n if len(args) > 0:\n username = args.__str__()[2:-2].replace(\"'\", \"\").replace(\",\", \"\")\n user = discord.utils.get(message.server.members, name=username)\n if user == None:\n userid = args.__str__()[2:-2].replace(\"'\", \"\").replace(\",\", \"\")\n user = discord.utils.get(message.server.members, id=userid)\n if user==None:\n userid = args.__str__()[4:-3].replace(\"'\", \"\").replace(\",\", \"\")\n user = discord.utils.get(message.server.members, id=userid)\n if user == None:\n userid2 = args.__str__()[5:-3].replace(\"'\", \"\").replace(\",\", \"\")\n user = discord.utils.get(message.server.members, id=userid2)\n if user==None:\n usernumber = args.__str__()[2:-2].replace(\"'\", \"\").replace(\",\", \"\")\n id=\"\"\n try:\n id = get(usernumber)\n except:\n pass\n user = discord.utils.get(message.server.members, id=id)\n if user != None:\n name = user.name\n id = user.id\n avatar = user.avatar_url\n mention = user.mention\n created = user.created_at\n nick = user.display_name\n if nick == name:\n namei = name\n else:\n namei = \"%s, Nickname: %s\" % (name, nick)\n roles=\"\"\n for role in user.roles:\n roles = roles + \", \" + role.mention\n roles = roles.__str__()[26:]\n join = user.joined_at\n status= user.status\n game = user.game\n toprole = user.top_role\n embed = discord.Embed(title=\"Userinfo\", color=discord.Color.green())\n embed.set_author(name=message.author.name, icon_url =message.author.avatar_url)\n embed.set_thumbnail(url=avatar)\n embed.add_field(name=\"Name\", value=namei, inline=True)\n embed.add_field(name=\"ID\", value=id, inline=True)\n embed.add_field(name=\"Rollen\", value=roles, inline=False)\n embed.add_field(name=\"Erwähnung\", value=mention, inline=True)\n embed.add_field(name=\"Höchste Rolle\", value=toprole.mention, inline=True)\n embed.add_field(name=\"Status\", value=status, inline=True)\n embed.add_field(name=\"Spiel\", value=game, inline=True)\n embed.add_field(name=\"Account erstellt(UTC)\", value=created, inline=False)\n embed.add_field(name=\"Server beigetreten(UTC)\", value=join, inline=True)\n await client.send_message(message.channel, embed=embed)\n else:\n embed = discord.Embed(title=\"Userinfo\", description=(\"Der User %s wurde nicht gefunden\" % username), color=discord.Color.red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n await client.send_message(message.channel, embed=embed)\n","sub_path":"commands/uinfo.py","file_name":"uinfo.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489317580","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf.urls import include\n\nurlpatterns = [\n url(r'^$', views.PostListView.as_view(), name='post_list'),\n url(r'^archives/(?P\\d{4})/(?P\\d+)/$', views.PostsMonthView.as_view(month_format='%m'),\n name='post_list'),\n # url(r'^page/(?P\\d+)/$', views.post_list, name='post_list'),\n url(r'^post/(?P\\d+)/$', views.post_detail, name='post_detail'),\n url(r'^post/(?P\\d+)/addlike/$', views.add_like, name='add_like'),\n url(r'^post/(?P\\d+)/adddislike/$', views.add_dislike, name='add_dislike'),\n url(r'^post/new/$', views.post_new, name='post_new'),\n url(r'^post/(?P\\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),\n url(r'^auth/', include('loginsys.urls'))\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"411004746","text":"import pandas as pd\nimport numpy as np\ndata = pd.read_excel('ERO_1979_NO_1.xlsx')\n\nSTRALHERORDER = data['STRALHERORDER'].values\nCATCHMENTAREA = data['CATCHMENTAREA'].values\nSLOPEERO = data['SLOPEERO'].values\nCHANNELERO = data['CHANNELERO'].values\nGRAVITYERO = data['GRAVITYERO'].values\nDESCRIPTION = data['DESCRIPTION'].values\n\nminorder = STRALHERORDER.min()\nmaxorder = STRALHERORDER.max()\n\nSM = [{'s_ero':[], 'c_ero': [], 'g_ero': [], 'ca': []} for x in range(minorder, maxorder + 1)]\n\nfor i in range(len(STRALHERORDER)):\n order = STRALHERORDER[i] - 1\n SM[order]['s_ero'].append(SLOPEERO[i])\n SM[order]['c_ero'].append(CHANNELERO[i])\n SM[order]['g_ero'].append(GRAVITYERO[i])\n SM[order]['ca'].append(CATCHMENTAREA[i])\n\nfor i in range(minorder, maxorder + 1):\n i = i - 1\n sum_ca = sum(np.array(SM[i]['ca']))\n sum_s_ero = np.nansum(np.array(SM[i]['s_ero']))\n sum_c_ero = np.nansum(np.array(SM[i]['c_ero']))\n sum_g_ero = np.nansum(np.array(SM[i]['g_ero']))\n print(sum_s_ero, sum_c_ero, sum_g_ero, sum_s_ero + sum_c_ero + sum_g_ero, sum_ca)\n\n\n\n\n","sub_path":"HFC/hfcero.py","file_name":"hfcero.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186235733","text":"# stworz funkcje ktora pobiera stringa i zamienia go na liste\r\n# funkcja ma pracowac tylko na stringach napisanych malymi literami\r\n# jesli dostanie inny string powinna rzucic ValueError z odpowiednim komentarzem\r\n\r\n\r\n\r\ndef make_list_of_string(string):\r\n if not string.islower():\r\n raise ValueError(\"String mial sie skladac z malych liter\")\r\n return list(string)\r\n\r\nprint(make_list_of_string('abcd'))\r\n","sub_path":"ex64.py","file_name":"ex64.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"129956268","text":"import os\nimport sys\nimport glob\n# Pandas for managing datasets\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport imageio\nfrom natsort import natsorted, ns\nimport numpy as np\nimport re\nimport scipy\nfrom seaborn.relational import _LinePlotter\n\nexp_names = [\"hexa_uni\", \"hexa_omni\", \"rarm\",\"sphere\", \"rastrigin\", \"rastrigin_multi\" ]\n\nvariant_names = [\"cmame_opt\", \"cmame_rdw\", \"cmame_imp\", \"cmame_rand\", \"hetero\",\"hetero_ucb\"]\n#variant_names = [\"hetero_mab\"]\n\n\ndef get_config(exp):\n if exp == \"hexa_uni\":\n resolutions=[5,5,5,5,5,5]\n vmin = 0\n vmax = 2\n elif exp == \"hexa_omni\":\n resolutions=[100,100]\n vmin = -np.pi/2\n vmax = 0\n elif exp == \"rarm\":\n resolutions=[100,100]\n vmin = -1\n vmax = 0\n elif exp == \"rastrigin\":\n resolutions=[100,100]\n vmin = -100*((5.12*1.4)*(5.12*1.4))\n vmax = 0\n elif exp == \"rastrigin_multi\":\n resolutions=[100,100]\n vmin = -100*((5.12*1.4)*(5.12*1.4)) \n vmax = 0\n elif exp == \"sphere\":\n resolutions=[100,100]\n vmin = - 100*(5.12*1.4)*(5.12*1.4)\n vmax = 0\n\n return [vmin, vmax, resolutions]\n\n\n\ndef plot_archive_distribution(data):\n \n sns.set(style=\"white\", rc={\"axes.facecolor\": (0, 0, 0, 0)})\n for exp in exp_names:\n \n plt.figure()\n \n # Initialize the FacetGrid object\n pal = sns.cubehelix_palette(10, rot=-.25, light=.7)\n g = sns.FacetGrid(data[data['exp']==exp], row=\"variant\", hue=\"variant\", aspect=15, height=.5, palette=pal)\n\n # Draw the densities in a few steps\n g.map(sns.kdeplot, \"fit\", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)\n g.map(sns.kdeplot, \"fit\", clip_on=False, color=\"w\", lw=2, bw=.2)\n plt.xlim(0, 1)\n g.map(plt.axhline, y=0, lw=2, clip_on=False)\n \n \n # Define and use a simple function to label the plot in axes coordinates\n def label(x, color, label):\n ax = plt.gca()\n ax.text(0, .2, label, fontweight=\"bold\", color=color,\n ha=\"left\", va=\"center\", transform=ax.transAxes)\n\n \n g.map(label, \"fit\")\n\n # Set the subplots to overlap\n g.fig.subplots_adjust(hspace=-.25)\n \n # Remove axes details that don't play well with overlap\n g.set_titles(\"\")\n g.set(yticks=[])\n g.despine(bottom=True, left=True)\n png_name = \"./ridge_\"+exp+\".png\"\n plt.savefig(png_name)\n \n plt.close()\n\ndef load_archive_text_file(path, resolutions):\n archive = np.genfromtxt(path, usecols = range(1,2+len(resolutions)))\n\n for i in range(archive.shape[1]-1):\n archive[:,i] = np.around(archive[:,i]*(resolutions[i]-1))\n\n if(len(resolutions)>2):\n for x in range(0,2):\n space = resolutions[x]\n for i in range(x+2, len(resolutions), 2):\n archive[:,x] += archive[:,i]*space\n space *= resolutions[i];\n archive = archive[:,np.array([0,1, -1])]\n\n return archive\n\n\n \ndef load_archive(path, resolutions = [100,100]):\n archive = load_archive_text_file(path, resolutions)\n grid = np.empty((np.prod(resolutions[0::2]),np.prod(resolutions[1::2])))\n grid[:] = np.nan\n rows = np.array([archive[:,0]], dtype=np.intp)\n columns = np.array([archive[:,1]], dtype=np.intp)\n grid[rows,columns] = archive[:,2]\n \n return grid\n \ndef print_archive(arg):\n for exp in exp_names:\n for variant in variant_names:\n folders = get_files(arg,variant,exp, \"\")\n if(len(folders)==0):\n print(\"NO folder for \"+exp+\" \"+variant)\n continue\n\n folder = folders[-1]\n files = glob.glob(folder+\"/archive_*.dat\")\n print(files)\n if(len(files)==0):\n print(\"NO file for \"+exp+\" \"+variant)\n continue\n\n files = natsorted(files, alg=ns.IGNORECASE)\n images = []\n for path in files:\n config = get_config(exp)\n data = load_archive(path, config[2])\n\n fig=plt.figure()\n ax = fig.add_subplot(111, aspect=1)\n c = ax.pcolor(data,vmin=config[0], vmax=config[1], edgecolors = None, antialiaseds=True)\n fig.colorbar(c, ax=ax)\n plt.title(variant+\"_\"+exp+\"_\"+os.path.basename(path))\n\n png_name = \"./\"+variant+\"_\"+exp+\"_\"+os.path.basename(path)+\".png\"\n plt.savefig(png_name)\n plt.close()\n images.append(imageio.imread(png_name))\n os.remove(png_name) \n imageio.mimsave(\"./\"+variant+\"_\"+exp+\"_archives.gif\", images, fps = 2)\n \n \n \n \n\n\ndef plot_proportions(arg):\n data = collect_data(arg,\"mab_proportion.dat\",[\"gen\",\"p1\",\"p2\", \"p3\", \"p4\",\"rp1\",\"rp2\", \"rp3\", \"rp4\"],True)\n print(data)\n sns.set(style=\"whitegrid\")\n # Plot the responses for different events and regions\n for exp in exp_names:\n plt.figure()\n sns.palplot(sns.color_palette(\"colorblind\"))\n f = plt.figure(figsize=(6.4, 4.8))\n ax = f.add_subplot(111) \n for item in [\"p1\",\"p2\",\"p3\",\"p4\"]: #,\"rp1\",\"rp2\", \"rp3\", \"rp4\"]:\n sns_plot = sns.lineplot(x=\"gen\", y=item,\n style=\"variant\", \n data=data[data['exp']==exp])\n \n plt.title(exp)\n ax.legend( labels=[\"OPT\",\"IMP\",\"RDW\",\"RAND\",\"reset_OPT\",\"reset_IMP\",\"reset_RDW\",\"reset_RAND\"])\n plt.savefig(\"./mab_progress_\"+exp+\".svg\")\n \ndef plot_progress(arg):\n data = collect_data(arg)\n def first_second_third_quartile(self, vals, grouper, units=None):\n # Group and get the aggregation estimate\n grouped = vals.groupby(grouper, sort=self.sort)\n est = grouped.agg('median')\n min_val = grouped.quantile(0.25)\n max_val = grouped.quantile(0.75)\n cis = pd.DataFrame(np.c_[min_val, max_val],\n index=est.index,\n columns=[\"low\", \"high\"]).stack()\n \n # Unpack the CIs into \"wide\" format for plotting\n if cis.notnull().any():\n cis = cis.unstack().reindex(est.index)\n else:\n cis = None\n \n return est.index, est, cis\n \n sns.set(style=\"whitegrid\")\n sns.palplot(sns.color_palette(\"colorblind\"))\n # Plot the responses for different events and regions\n for exp in exp_names:\n for item in [\"archive_size\",\"best_fit\", \"sum_fit\"]:\n plt.figure()\n my_lineplot=sns.lineplot\n _LinePlotter.aggregate = first_second_third_quartile\n sns_plot = sns.lineplot(x=\"gen\", y=item,\n hue=\"variant\", \n data=data[data['exp']==exp] )\n plt.title(exp+\"_\"+item)\n plt.savefig(\"./progress_\"+exp+\"_\"+item+\".svg\")\n\n #sns_plot.set(xlim=(0, 100))\n #plt.savefig(\"./progress_\"+exp+\"_\"+item+\"_short.png\")\n #plt.close()\n\n val = pd.DataFrame(columns=['exp','variant','median'])\n for exp in exp_names:\n pp = pd.DataFrame(columns=['ref_var','comp_var','p_value'])\n\n for ref_var in variant_names:\n med = np.median(data[(data.exp==exp) & (data.variant==ref_var) & (data.gen==20000) ].sum_fit.to_numpy())\n val=val.append({'exp':exp, 'variant':ref_var, 'median': med}, ignore_index=True)\n for comp_var in variant_names:\n stat, p = scipy.stats.ranksums(\n data[(data.exp==exp) & (data.variant==ref_var) & (data.gen==20000) ].sum_fit.to_numpy(),\n data[(data.exp==exp) & (data.variant==comp_var) & (data.gen==20000) ].sum_fit.to_numpy())\n \n #if(ref_var != comp_var):\n pp=pp.append({'ref_var':ref_var, 'comp_var':comp_var, 'p_value':p}, ignore_index=True)\n\n pp=pp.pivot(index='ref_var', columns='comp_var', values='p_value')\n f = open(\"pvalue_\" + exp + \".md\", \"a\")\n f.write(pp.to_markdown())\n f.close()\n val=val.pivot(index='exp', columns='variant',values='median')\n ff = open(\"medians.md\", \"a\")\n ff.write(val.to_markdown())\n ff.close()\n \n\ndef get_files(arg, variant, exp, filename=\"\"):\n if(len(arg)!=0):\n base = arg[0]\n else:\n base = \".\"\n\n\n if filename != \"\":\n filename =\"/\"+filename\n\n #if(exp == \"hexa_uni\" or exp == \"hexa_omni\"):\n # return glob.glob(base+'/'+variant+'_'+exp+'/results_' + variant+\"_\"+exp+'/2020*'+filename)\n #else:\n # return glob.glob(base+'/results_' + variant+\"_\"+exp+'/2020*' + filename)\n return glob.glob(base+'/results_' + variant+\"_\"+exp+'/202*/' + filename)\n\n\ndef collect_data(arg, filename = \"progress.dat\", fields = [\"gen\",\"archive_size\",\"best_fit\", \"sum_fit\", \"div1\", \"div2\"], rolling=False):\n\n data = pd.DataFrame()\n for exp in exp_names:\n for variant in variant_names:\n files = get_files(arg,variant,exp, filename)\n print(files)\n if(len(files)==0):\n print(\"NO file called \" + filename + \" for \"+exp+\" \"+variant)\n continue\n data_tmp = pd.DataFrame()\n for run, f in enumerate(files): \n tmp = pd.read_csv(f,delim_whitespace=True,names=fields)\n tmp['run']=run\n if( rolling):\n for item in fields:\n tmp[item] =tmp[item].rolling(50, win_type='triang').mean()\n tmp = tmp[50::50]\n data_tmp=pd.concat([data_tmp, tmp], ignore_index=True)\n \n data_tmp['variant'] = variant\n data_tmp['exp'] = exp\n data = data.append(data_tmp)\n\n return data\n\n \ndef report_integrity(arg):\n data = collect_data(arg)\n data = data[['gen', 'run', 'variant','exp']]\n\n data = data.groupby(['exp','variant','run']).max()\n data = pd.pivot_table(data,values=['gen'],index=['exp','run'],columns=['variant'])\n print(data)\n S = data.to_markdown()\n #remove some artifacts\n S = re.sub(\"((\\('gen'. ')|('\\)))\",\"\",S) \n S = re.sub(\"(\\('.+(?P[1-9]|\\d{2,})\\))\",\"|\\g<2>\",S)\n S =\tre.sub(\"(\\('|\\))\",\"\",S)\n S =\tre.sub(\"(',\\s)\",\"|\",S)\n S =\tre.sub(\"(\\|:---)\",\"|:---|:---\",S)\n S = \"| \"+S\n\n f = open(\"integrity.md\", \"a\")\n f.write(S)\n f.close()\n \n print(S)\n\n\n \nif __name__ == \"__main__\":\n report_integrity(sys.argv[1:])\n #print_archive(sys.argv[1:])\n plot_progress(sys.argv[1:])\n plot_proportions(sys.argv[1:]) \n\n sys.exit(0)\n \n","sub_path":"python/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"406479158","text":"import re\nimport traceback\nfrom itertools import product\nfrom typing import List, Union\n\nfrom pyaspeller import YandexSpeller\n\nfrom .entities import Sentence\nfrom .framework import Mystem\nfrom .parsing import LemmaParser\n\n\nclass TextProcessor(Mystem):\n \"\"\"\n Should be used in conjunction with 'with' context management operator\n \"\"\"\n _lemma_pattern = re.compile('.*[а-яА-Яa-zA-Z]+.*')\n\n text_groups_delimiter = '|'\n\n def __init__(self):\n super().__init__()\n self._speller = YandexSpeller()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n print('%s\\nLanguageProcessor closed forcibly: \"%s\": \"%s\"' % (str(exc_tb), str(exc_type), str(exc_val)))\n\n self.close()\n\n @classmethod\n def _preprocess_text(cls, _text: str) -> str:\n \"\"\"\n Replace all 'ё' with 'е'\n \"\"\"\n return _text.lower().replace('ё', 'е')\n\n def get_spelling_variants(self, text: str) -> List[str]:\n \"\"\"\n Returns list of all possible text spellings\n \"\"\"\n text_words = text.split(' ')\n\n # get pairs of {source word: [variants of correction]}\n corrections = {w_info.get('word'): w_info.get('s')\n for w_info in self._speller.spell(text)}\n\n # fill array like [['Мама'], ['мыла', 'мыло'], ['раму', 'рамп]]\n words_variants = []\n for word in text_words:\n word_spellings = [word]\n\n if corrections.get(word):\n word_spellings.extend(corrections.get(word))\n\n words_variants.append(word_spellings)\n\n # iterate through text products and create text variants\n text_variants = [' '.join(words_product)\n for words_product in product(*words_variants)]\n\n return text_variants\n\n def stemming(self, text: Union[str, List[str]], validate_lemmas=False) -> Union[str, List[str]]:\n \"\"\"\n Performs stemming on given text(s).\n Returns string of tokens in the original order for each given text.\n\n :param validate_lemmas: if True, only lemmas which match the pattern will be added\n :param text: if list of texts is passed - they are grouped by delimiter and are processed at once\n \"\"\"\n if text is None:\n return []\n\n if isinstance(text, list):\n _text = (' %s ' % self.text_groups_delimiter).join(text)\n\n else:\n _text = text\n\n _text = self._preprocess_text(_text)\n\n analyzed = self.analyze(_text)\n\n sentence = self._build_sentence(analyzed, validate_lemmas=validate_lemmas)\n\n tokens = sentence.get_tokens()\n\n # if there were list of texts\n if isinstance(text, list):\n tokens_string = ' '.join(tokens)\n\n return [t.strip()\n for t in tokens_string.split(self.text_groups_delimiter)]\n\n else:\n return ' '.join(tokens)\n\n @classmethod\n def _build_sentence(cls, analyzed: dict, validate_lemmas) -> Sentence:\n sentence = Sentence()\n\n for l_dict in analyzed:\n analysis = l_dict.get('analysis')\n\n # only words which have 'analyzed' section, and not a 'bastard', are really recognized lemmas\n if analysis and analysis[-1].get('qual') != 'bastard':\n try:\n lemma = LemmaParser.parse_lemma(l_dict)\n sentence.append(lemma)\n\n except Exception as e:\n print('%s: %s' % (str(type(e)), str(e)))\n traceback.print_tb(e.__traceback__)\n\n # groups delimiter\n elif cls.text_groups_delimiter in l_dict.get('text'):\n sentence.append(LemmaParser.get_delimiter_lemma(cls.text_groups_delimiter))\n\n # not-recognized word\n else:\n if validate_lemmas and re.match(cls._lemma_pattern, l_dict.get('text')) or not validate_lemmas:\n if l_dict.get('text') != ' ':\n sentence.append(LemmaParser.get_arbitrary_lemma(l_dict.get('text')))\n\n return sentence\n","sub_path":"research/text_processing/mystem/text_processor.py","file_name":"text_processor.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"274521847","text":"# Exercício 037: Escreva um programa em Python que leia um número inteiro\n# qualquer e peça para o usuário escolher qual será a base de conversão:\n# 1 para binário, 2 para octal e 3 para hexadecimal.\n\nprint(5*'='+' EXERCISE 037 '+5*'=')\n\nnum = int(input('Enter any integer number: '))\nprint('''Choose a conversion basis:\n [ 1 ] convert to BINARY\n [ 2 ] convert to OCTAL\n [ 3 ] convert to HEXADECIMAL''')\nchoose = int(input('Your choose: '))\n\nif choose == 1:\n cnum = bin(num)\n print('{} Convert to BINARY: {}'.format(num, cnum[2:]))\nelif choose == 2:\n cnum = oct(num)\n print('{} Convert to OCTAL: {}'.format(num, cnum[2:]))\nelif choose == 3:\n cnum = hex(num)\n print('{} Convert to HEXADECIMAL: {}'.format(num, cnum[2:]))\nelse:\n print('Invalid option')","sub_path":"Exercicios/ex037.py","file_name":"ex037.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"139923308","text":"from nltk import wordpunct_tokenize\nfrom nltk.corpus import stopwords\nimport nltk\nfrom Pipelines.Pipelines_fr import pipeline_fr\nfrom Pipelines.Pipelines_en import pipeline_en\n\n\n\n\nclass DataSingleton:\n __instance = None\n __nlp_fr = None\n __nlp_en = None\n\n @staticmethod\n def getInstance():\n \"\"\" Static access method. \"\"\"\n if DataSingleton.__instance is None:\n DataSingleton()\n return DataSingleton.__instance\n\n def __init__(self):\n \"\"\" Virtually private constructor. \"\"\"\n if DataSingleton.__instance is not None:\n raise Exception(\"This class is a singleton!\")\n else:\n DataSingleton.__instance = self\n __nlp_en = pipeline_en(\"question-generation\")\n __nlp_fr = pipeline_fr(\"multitask-qa-qg\")\n\n def getNlp_fr(self):\n return self.__nlp_fr\n\n def getNlp_en(self):\n return self.__nlp_en\n\n\n# return all possible question on a text\nclass Question_Answering:\n\n def getQuestion(text):\n texteDecouper = Question_Answering.decouperTexte(text)\n langue = Language.getLanguage(texteDecouper[0])\n print(langue)\n nlp = Question_Answering.language(langue)\n _liste_question = []\n for texte in texteDecouper:\n result = nlp(texte)\n for reponse in result:\n _liste_question.append(reponse)\n return _liste_question\n\n def language(langue):\n if langue == \"english\":\n return nlp_en\n if langue == \"french\":\n return nlp_fr\n\n \"\"\"\n \n \"\"\"\n def decouperTexte(txt):\n tokenized_sentence = nltk.sent_tokenize(txt)\n # Taille actuelle de one_input\n compteur = 0\n # résultat final\n all_inputs = []\n # Une entrée du transformers, i.e une ou plusieurs pharses d'au total 511 caractères ou moins\n one_input = \"\"\n # Pour chaque phrase\n for sentence in tokenized_sentence:\n # On récupère la taille de la phrase\n sentence_size = len(sentence)\n # Si la phrase à elle seule fait plus de 512 caractères\n if sentence_size > 511:\n # Pour conserver l'ordre du texte\n # Si notre entrée actuelle n'est pas vide, on l'ajoute à la liste des entrée\n if one_input != \"\":\n all_inputs.append(one_input)\n # La nouvelle taille de la nouvelle entrée est donc de 0\n compteur = 0\n # Notre nouvelle entrée est vide\n one_input = \"\"\n # Notre phrase trop longue est tronquée\n sentence = sentence[0:511]\n # Puis ajoutée à la liste de toutes les entrées\n all_inputs.append(sentence)\n # Sinon\n else:\n # On regarde si la taille de l'entrée établie jusque là + celle de notre nouvelle phrase est inférieure à 512\n if compteur + sentence_size < 511:\n # Si oui la nouvelle dimension de notre entrée est déterminée\n compteur += sentence_size\n # On ajpoute la phrase à notre entrée\n one_input += sentence\n # Sinon\n else:\n # Si on ajoute la phrase à notre entrée, on dépasse les 512 caractères\n # On ajoute donc notre entrée actuelle à la liste de toutes les entrées\n all_inputs.append(one_input)\n # Notre nouvelle entrée actuelle devient la phrase sentence\n one_input = sentence\n # La nouvelle taille est la taile de la phrase sentence\n compteur = sentence_size\n # Il faut ajouter à la fin la dernière entrée si elle existe\n if one_input != \"\":\n all_inputs.append(one_input)\n return all_inputs\n\n\n# check the language\nclass Language:\n def calc_ratios(text):\n ratios = {}\n tokens = wordpunct_tokenize(text)\n words = [word.lower() for word in tokens]\n for lang in stopwords.fileids():\n stopwords_set = set(stopwords.words(lang))\n words_set = set(words)\n common_words = words_set.intersection(stopwords_set)\n ratios[lang] = len(common_words)\n\n return ratios\n\n def detect_language(text):\n ratios = Language.calc_ratios(text)\n most_rated_language = max(ratios, key=ratios.get)\n return most_rated_language\n\n def getLanguage(text):\n return str(Language.detect_language(text))\n","sub_path":"Libraie/Question_Answering.py","file_name":"Question_Answering.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576402383","text":"#!/usr/bin/env python\nimport rospy\nimport smach\n\nclass detect_state(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['move_forward', 'turn_left', 'turn_right', 'finish'],\n input_keys=['counter', 'lib'], output_keys = ['lib'])\n self.counter = 0\n def execute(self, userdata):\n if self.counter > userdata.counter:\n userdata.counter_out = self.counter\n return 'finish'\n self.counter = self.counter + 1\n\n result = 'move_forward'\n if userdata.lib:\n lib = userdata.lib\n result = lib.detect()\n else:\n rospy.sleep(1)\n\n return result\n\nclass move_forward_state(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['to_next'],\n input_keys=['lib'], output_keys = ['lib'])\n\n def execute(self, userdata):\n if userdata.lib:\n result = userdata.lib.move_forward()\n else:\n rospy.sleep(1)\n\n return 'to_next'\n\nclass turn_left_state(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['to_next'],\n input_keys=['lib'], output_keys = ['lib'])\n\n def execute(self, userdata):\n if userdata.lib:\n result = userdata.lib.turn_left()\n else:\n rospy.sleep(1)\n\n return 'to_next'\n\nclass turn_right_state(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['to_next'],\n input_keys=['lib'], output_keys = ['lib'])\n\n def execute(self, userdata):\n if userdata.lib:\n result = userdata.lib.turn_right()\n else:\n rospy.sleep(1)\n\n return 'to_next'\n\n\ndef log_none(msg):\n pass\n\ndef create_state_machine(count = 0, lib = None):\n smach.set_loggers(smach.loginfo, smach.logwarn, log_none, smach.logerr)\n\n sm = smach.StateMachine(outcomes=['finish'])\n\n with sm:\n smach.StateMachine.add('detect_state', detect_state(),\n transitions={'move_forward':'move_forward_state',\n 'turn_left' :'turn_left_state',\n 'turn_right' :'turn_right_state',\n 'finish' :'finish'} )\n smach.StateMachine.add('move_forward_state', move_forward_state(),\n transitions={'to_next':'detect_state'})\n\n smach.StateMachine.add('turn_left_state', turn_left_state(),\n transitions={'to_next':'detect_state'})\n smach.StateMachine.add('turn_right_state', turn_right_state(),\n transitions={'to_next':'detect_state'})\n\n sm.userdata.counter = count\n sm.userdata.lib = lib\n\n return sm\n\n# result = sm.execute()\n# print result\n","sub_path":"webots/controllers/smach_demo/smach_def.py","file_name":"smach_def.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"59547399","text":"from PySide2 import QtCore, QtGui, QtWidgets\r\nimport random\r\nimport sys\r\n\r\ncell_size = 20 # 每格的宽度\r\nColumns = 12\r\nRows = 20\r\n\r\nNoShape, ZShape, SShape, LineShape, \\\r\nTShape, SquareShape, LShape, MirroredLShape = range(8)\r\n\r\n# 定义各种形状 字典\r\nSHAPES = [ [],\r\n [(-1, -1), (0, -1), (-1, 0), (0, 0)],\r\n [(-1, 0), (0, 0), (0, -1), (1, -1)],\r\n [(-1, 0), (0, 0), (0, -1), (1, 0)],\r\n [(0, 1), (0, 0), (0, -1), (0, -2)],\r\n [(-1, 0), (0, 0), (-1, -1), (-1, -2)],\r\n [(-1, 0), (0, 0), (0, -1), (0, -2)],\r\n [(-1, -1), (0, -1), (0, 0), (1, 0)],\r\n]\r\n\r\n# 定义各种形状的颜色\r\nSHAPESCOLOR = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, \r\n 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]\r\n\r\n# 定义一个Board类,操作与之相关的初始化、清空、检查等\r\nclass Board(): \r\n def __init__(self): # 类的初始化函数,自动调用\r\n self.table = []\r\n for r in range(Rows): \r\n i_row = [NoShape for j in range(Columns)] \r\n self.table.append(i_row)\r\n\r\n def check_row_full(self, row): \r\n '检查第row行是否满了'\r\n return (self.table[row].count(NoShape) == 0)\r\n \r\n def check_and_clear(self):\r\n fulllines = 0\r\n for ri in range(Rows):\r\n if self.check_row_full(ri):\r\n fulllines += 1\r\n for cur_ri in range(ri, 1, -1):\r\n self.table[cur_ri] = self.table[cur_ri-1][:]\r\n self.table[0] = [NoShape for j in range(Columns)]\r\n return fulllines # 返回\r\n \r\n def clearboard(self): # 清空板子\r\n for r in range(Rows):\r\n for c in range(Columns):\r\n self.table[r][c] = NoShape\r\n\r\nclass TetrixPiece():\r\n def __init__(self, shape, rotatetimes=0):\r\n self.shape = shape \r\n self.cell_list = SHAPES[self.shape]\r\n if rotatetimes > 0 :\r\n for i in range(rotatetimes):\r\n self.rotate_left()\r\n \r\n def rotate_left(self):\r\n rotate_cell_list = []\r\n for cell in self.cell_list:\r\n cc,cr = cell\r\n rotate_cell_list.append((cr, -cc))\r\n self.cell_list = rotate_cell_list\r\n \r\n def rotate_right(self):\r\n rotate_cell_list = []\r\n for cell in self.cell_list:\r\n cc,cr = cell\r\n rotate_cell_list.append((-cr, cc))\r\n self.cell_list = rotate_cell_list\r\n def getleft(self):\r\n return min([cr[0] for cr in self.cell_list])\r\n def getright(self):\r\n return max([cr[0] for cr in self.cell_list])\r\n def gettop(self):\r\n return min([cr[1] for cr in self.cell_list])\r\n def getbottom(self):\r\n return max([cr[1] for cr in self.cell_list])\r\n \r\nclass TetrixBoard(QtWidgets.QFrame):\r\n scoreChanged = QtCore.Signal(int)\r\n levelChanged = QtCore.Signal(int)\r\n linesRemovedChanged = QtCore.Signal(int)\r\n newNextShape = QtCore.Signal(int,int)\r\n \r\n def __init__(self, parent=None):\r\n super(TetrixBoard, self).__init__(parent)\r\n self.board = Board()\r\n self.curPiece = None\r\n self.nextPiece = None\r\n self.curCR = (Columns//2, 0) \r\n self.isWaitingNext = True\r\n self.isPaused = False\r\n self.timer = QtCore.QBasicTimer()\r\n self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Sunken)\r\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\r\n \r\n def newGame(self):\r\n self.isWaitingNextPiece = False\r\n self.numLinesRemoved = 0\r\n self.score = 0\r\n self.level = 0\r\n # self.speed = 500\r\n \r\n self.board.clearboard()\r\n\r\n self.curPiece = TetrixPiece(random.randint(1,7),random.randint(0,3))\r\n nextshape = random.randint(1,7)\r\n rotatetimes = random.randint(0,3)\r\n self.nextPiece = TetrixPiece(nextshape, rotatetimes)\r\n \r\n self.newNextShape.emit(nextshape, rotatetimes)\r\n self.linesRemovedChanged.emit(self.numLinesRemoved)\r\n self.scoreChanged.emit(self.score)\r\n self.levelChanged.emit(self.level)\r\n self.timer.start(self.timeoutTime(), self)\r\n \r\n def timeoutTime(self):\r\n return 600 / (1 + self.level) \r\n \r\n def pause(self):\r\n self.isPaused = not self.isPaused\r\n if self.isPaused:\r\n self.timer.stop()\r\n else:\r\n self.timer.start(self.timeoutTime(), self)\r\n self.update()\r\n \r\n def paintEvent(self, event):\r\n super(TetrixBoard, self).paintEvent(event)\r\n\r\n painter = QtGui.QPainter(self)\r\n rect = self.contentsRect()\r\n\r\n if self.isPaused:\r\n painter.drawText(rect, QtCore.Qt.AlignCenter, \"Pause\")\r\n return\r\n color = QtGui.QColor(\"gray\")\r\n painter.setPen(color.lighter())\r\n for r in range(Rows+1):\r\n painter.drawLine(0,r*cell_size, Columns*cell_size, r*cell_size)\r\n for c in range(Columns+1):\r\n painter.drawLine(c*cell_size, 0, c*cell_size, Rows*cell_size) \r\n \r\n for r in range(Rows):\r\n for c in range(Columns):\r\n shape = self.board.table[r][c]\r\n if shape != NoShape:\r\n self.drawSquare(painter, (c,r), shape)\r\n \r\n if self.curPiece != None:\r\n for cell in self.curPiece.cell_list:\r\n c = self.curCR[0] + cell[0]\r\n r = self.curCR[1] + cell[1]\r\n if 0 <= c < Columns and 0 <= r < Rows:\r\n self.drawSquare(painter, (c,r), self.curPiece.shape)\r\n \r\n def drawSquare(self, painter, cr, shape):\r\n color = QtGui.QColor(SHAPESCOLOR[shape])\r\n x = cr[0] * cell_size\r\n y = cr[1] * cell_size\r\n painter.fillRect(x + 1, y + 1, \r\n cell_size - 2,cell_size - 2, color)\r\n\r\n painter.setPen(color.lighter())\r\n painter.drawLine(x, y+cell_size-1, x, y)\r\n painter.drawLine(x, y, x+cell_size-1, y)\r\n\r\n painter.setPen(color.darker())\r\n painter.drawLine(x+1, y+cell_size-1,x+cell_size-1, y+cell_size-1)\r\n painter.drawLine(x+cell_size-1, y+cell_size-1, x+cell_size-1, y+1)\r\n\r\n\r\n def keyPressEvent(self, event):\r\n if self.isPaused or self.curPiece == None:\r\n super(TetrixBoard, self).keyPressEvent(event)\r\n return\r\n\r\n key = event.key()\r\n if key == QtCore.Qt.Key_Left:\r\n self.left()\r\n elif key == QtCore.Qt.Key_Right:\r\n self.right()\r\n elif key == QtCore.Qt.Key_Down:\r\n self.oneLineDown()\r\n elif key == QtCore.Qt.Key_Up:\r\n self.rotateLeft()\r\n elif key == QtCore.Qt.Key_Space:\r\n self.land()\r\n #elif key == QtCore.Qt.Key_D:\r\n #self.oneLineDown()\r\n else:\r\n super(TetrixBoard, self).keyPressEvent(event)\r\n\r\n def left(self):\r\n if self.try_move((-1,0)): # 如果能够向左移动一格\r\n self.move((-1,0)) # 就移动一格\r\n def right(self):\r\n if self.try_move((1,0)): # 如果能够向右移动一格\r\n self.move((1,0)) # 就移动一格\r\n def rotateLeft(self):\r\n self.curPiece.rotate_left() # 向左转动\r\n if self.try_move([0,0]) is False: # 如果检查不能转动\r\n self.curPiece.rotate_right() # 再转回来\r\n def rotateRight(self):\r\n self.curPiece.rotate_right() # 向右转动\r\n if self.try_move([0,0]) is False: # 如果不能转动\r\n self.curPiece.rotate_left() # 再转回来 \r\n def land(self): # 到底\r\n max_down = 0 # 最大向下的数量\r\n for i in range(Rows):\r\n if self.try_move([0,i]) is True:\r\n max_down = i\r\n else:\r\n break\r\n self.move([0,max_down])\r\n self.oneLineDown()\r\n \r\n def newPiece(self):\r\n nextshape = random.randint(1,7)\r\n rotatetimes = random.randint(0,3)\r\n\r\n self.nextPiece = TetrixPiece(nextshape,rotatetimes)\r\n self.newNextShape.emit(nextshape,rotatetimes)\r\n \r\n def timerEvent(self, event):\r\n if event.timerId() == self.timer.timerId():\r\n if self.isWaitingNext: # 如果在等下一个\r\n self.isWaitingNext = False \r\n self.curPiece = self.nextPiece\r\n self.curCR = [Columns//2,0]\r\n \r\n if not self.try_move((0,1)): # 如果不能移动,说明gameover了\r\n self.gameover()\r\n self.isPaused = True\r\n self.timer.stop()\r\n return\r\n self.newPiece()\r\n self.timer.start(self.timeoutTime(), self)\r\n else:\r\n self.oneLineDown()\r\n else:\r\n super(TetrixBoard, self).timerEvent(event)\r\n \r\n def gameover(self):\r\n pass\r\n \r\n def oneLineDown(self):\r\n if self.try_move((0,1)): # 如果能够向下移动一行\r\n self.move((0,1)) # 向下移动一行\r\n else: # 否则就是到底了\r\n self.isWaitingNext = True # 表示开始下一个\r\n for cell in self.curPiece.cell_list: # 把当前的保存到表里\r\n self.board.table[self.curCR[1]+cell[1]]\\\r\n [self.curCR[0]+cell[0]] = self.curPiece.shape\r\n # self.curCR = [Columns//2,0]\r\n self.curPiece = None\r\n fulllines = self.board.check_and_clear() # 检查表里是否满行了\r\n if fulllines > 0:\r\n self.update()\r\n self.numLinesRemoved += fulllines\r\n self.score = self.numLinesRemoved * 10\r\n self.linesRemovedChanged.emit(self.numLinesRemoved)\r\n self.scoreChanged.emit(self.score) # 发射消息\r\n self.level = self.numLinesRemoved // 10\r\n self.levelChanged.emit(self.level)\r\n \r\n # 绘制向指定方向移动后的俄罗斯方块\r\n def move(self, direction=[0, 0]):\r\n \"\"\"\r\n 绘制向指定方向移动后的俄罗斯方块\r\n :param direction: 俄罗斯方块移动方向\r\n :return:\r\n \"\"\"\r\n self.curCR[0] += direction[0]\r\n self.curCR[1] += direction[1]\r\n self.update()\r\n \r\n #判断俄罗斯方块是否可以朝指定方向移动\r\n def try_move(self, direction=[0, 0]):\r\n \"\"\"\r\n 判断俄罗斯方块是否可以朝指定方向移动\r\n :param direction: 俄罗斯方块移动方向\r\n :return: boolean 是否可以朝指定方向移动\r\n \"\"\"\r\n c1, r1 = self.curCR\r\n dc, dr = direction\r\n \r\n for cell in self.curPiece.cell_list:\r\n cell_c, cell_r = cell\r\n c = cell_c + c1 + dc\r\n r = cell_r + r1 + dr\r\n # 判断该位置是否超出左右边界,以及下边界\r\n # 一般不判断上边界,因为俄罗斯方块生成的时候,可能有一部分在上边界之上还没有出来\r\n if c < 0 or c >= Columns or r >= Rows:\r\n return False\r\n\r\n # 必须要判断r不小于0才行,具体原因你可以不加这个判断,试试会出现什么效果\r\n if r >= 0 and (self.board.table[r][c] != NoShape):\r\n return False\r\n\r\n return True\r\n \r\n def save_block_to_table(self):\r\n for cell in self.curPiece.cell_list:\r\n c0,r0 = cell\r\n self.board.table[self.curCR[1]+r0][self.curCR[0]+c0] = self.curPiece.shape\r\n \r\nclass NextPieceBuf(QtWidgets.QFrame):\r\n def __init__(self, parent=None):\r\n super(NextPieceBuf, self).__init__(parent)\r\n self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Sunken)\r\n self.shape = NoShape\r\n\r\n def newNextPiece(self, shape, rt):\r\n self.shape = shape\r\n self.piece = TetrixPiece(shape,rt)\r\n self.dc = self.piece.getright() - self.piece.getleft()\r\n self.dr = self.piece.getbottom() - self.piece.gettop()\r\n self.update() \r\n \r\n def paintEvent(self, event):\r\n super(NextPieceBuf, self).paintEvent(event)\r\n if self.shape == NoShape:\r\n return\r\n painter = QtGui.QPainter(self)\r\n rect = self.contentsRect()\r\n color = QtGui.QColor(SHAPESCOLOR[self.shape])\r\n left = (rect.left()+rect.right()-(self.dc+1)*cell_size)//2 - self.piece.getleft()*cell_size\r\n top = (rect.top()+rect.bottom()-(self.dr+1)*cell_size)//2 - self.piece.gettop()*cell_size\r\n\r\n for cr in self.piece.cell_list:\r\n x = cr[0] * cell_size + left\r\n y = cr[1] * cell_size + top\r\n painter.fillRect(x + 1, y + 1, \r\n cell_size - 2,cell_size - 2, color)\r\n\r\n painter.setPen(color.lighter())\r\n painter.drawLine(x, y + cell_size - 1, x, y)\r\n painter.drawLine(x, y, x + cell_size - 1, y)\r\n\r\n painter.setPen(color.darker())\r\n painter.drawLine(x + 1, y + cell_size - 1,\r\n x + cell_size - 1, y + cell_size - 1)\r\n painter.drawLine(x + cell_size - 1, y + cell_size - 1, \r\n x + cell_size - 1, y + 1)\r\n\r\nclass TetrixWindow(QtWidgets.QWidget):\r\n def __init__(self):\r\n super(TetrixWindow, self).__init__()\r\n\r\n self.board = TetrixBoard()\r\n\r\n nextPieceBuf = NextPieceBuf()\r\n \r\n scoreLcd = QtWidgets.QLCDNumber(5)\r\n scoreLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled)\r\n levelLcd = QtWidgets.QLCDNumber(2)\r\n levelLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled)\r\n linesLcd = QtWidgets.QLCDNumber(5)\r\n linesLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled)\r\n\r\n startButton = QtWidgets.QPushButton(\"&Start\")\r\n startButton.setFocusPolicy(QtCore.Qt.NoFocus)\r\n quitButton = QtWidgets.QPushButton(\"&Quit\")\r\n quitButton.setFocusPolicy(QtCore.Qt.NoFocus)\r\n pauseButton = QtWidgets.QPushButton(\"&Pause\")\r\n pauseButton.setFocusPolicy(QtCore.Qt.NoFocus)\r\n \r\n startButton.clicked.connect(self.board.newGame)\r\n pauseButton.clicked.connect(self.board.pause)\r\n quitButton.clicked.connect(qApp.quit)\r\n self.board.scoreChanged.connect(scoreLcd.display)\r\n self.board.levelChanged.connect(levelLcd.display)\r\n self.board.linesRemovedChanged.connect(linesLcd.display)\r\n self.board.newNextShape.connect(nextPieceBuf.newNextPiece)\r\n \r\n nextlabel = QtWidgets.QLabel(\"NEXT\")\r\n levellabel = QtWidgets.QLabel(\"LEVEL\")\r\n scorelabel = QtWidgets.QLabel(\"SCORE\")\r\n lineremovedlabel = QtWidgets.QLabel(\"LINES REMOVED\")\r\n \r\n layout = QtWidgets.QGridLayout()\r\n layout.addWidget(nextlabel, 0, 0)\r\n layout.addWidget(nextPieceBuf, 1, 0)\r\n layout.addWidget(levellabel, 2, 0)\r\n layout.addWidget(levelLcd, 3, 0)\r\n layout.addWidget(startButton, 4, 0)\r\n layout.addWidget(self.board, 0, 1, 6, 1)\r\n layout.addWidget(scorelabel, 0, 2)\r\n layout.addWidget(scoreLcd, 1, 2)\r\n layout.addWidget(lineremovedlabel, 2, 2)\r\n layout.addWidget(linesLcd, 3, 2)\r\n layout.addWidget(quitButton, 4, 2)\r\n layout.addWidget(pauseButton, 5, 2)\r\n self.setLayout(layout)\r\n\r\n self.setWindowTitle(\"Tetrix\")\r\n self.resize(550, 370)\r\n\r\nif __name__ == '__main__':\r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = TetrixWindow()\r\n window.show()\r\n random.seed(None)\r\n sys.exit(app.exec_())","sub_path":"Tetris-PySide2-02.py","file_name":"Tetris-PySide2-02.py","file_ext":"py","file_size_in_byte":15740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"592445576","text":"import sys\nimport unittest\nfrom mock import (\n patch,\n Mock,\n)\n\nfrom contrib.bind.zoneparser import ZoneParser\n# from contrib.bind.zone import Zone\n\n\nclass TestZoneParser(unittest.TestCase):\n\n ez = []\n\n def setUp(self):\n with open('contrib/tests/fixtures/sample_bind_parsed') as f:\n self.ez = f.readlines()\n self.ezp = list(self.ez)\n\n def test_init_loads_keys_from_zone_class(self):\n zp = ZoneParser('example.com')\n self.assertIn('CNAME', zp.implemented_records)\n self.assertIn('AAAA', zp.implemented_records)\n self.assertIn('A', zp.implemented_records)\n self.assertIn('SOA', zp.implemented_records)\n self.assertIn('NS', zp.implemented_records)\n\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n def test_from_file(self, mopen):\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.readlines.return_value = self.ez\n zp = ZoneParser('ns')\n zp.normalize_contents = Mock()\n zp.normalize_contents.return_value = self.ez\n self.assertEqual(zp.from_file(), self.ez)\n\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n def test_from_file_exception(self, mopen):\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.readlines = Mock(side_effect=OSError('Intentional'))\n zp = ZoneParser('foo.com')\n zp.normalize_contents = Mock()\n zp.normalize_contents.return_value = self.ez\n self.assertEqual(zp.from_file(), [])\n\n def test_id_generator(self):\n zp = ZoneParser('foo.com')\n self.assertTrue(len(zp.id_generator(6)) == 6)\n\n def test_sanity(self):\n zp = ZoneParser('foo.com')\n\n @patch('contrib.bind.zoneparser.ZoneParser.a_from_array')\n @patch('contrib.bind.zoneparser.ZoneParser.cname_from_array')\n @patch('contrib.bind.zoneparser.ZoneParser.ns_from_array')\n @patch('contrib.bind.zoneparser.ZoneParser.soa_from_array')\n def test_array_to_zone(self, soam, nsm, cnm, am):\n zp = ZoneParser('example.com')\n zp.contents = self.ez\n zp.array_to_zone()\n soam.assert_called_with(self.ez[0].split())\n nsm.assert_called_with(self.ez[1].split())\n cnm.assert_called_with(self.ez[3].split())\n am.assert_called_with(self.ez[4].split())\n\n def test_soa_from_array(self):\n zp = ZoneParser('example.com')\n zcontents = self.ez\n zp.soa_from_array(zcontents[0].split())\n self.assertEqual(zp.zone.contents['SOA'], [{'addr': 'ns.example.com.',\n 'owner': 'root.example.com.',\n 'expiry': '1814400',\n 'minimum': '900',\n 'refresh': '43200',\n 'serial': '2003080800',\n 'ttl': '604800',\n 'update-retry': '900'}])\n\n def test_cname_from_array(self):\n zp = ZoneParser('example.com')\n zcontents = self.ez\n zp.cname_from_array(zcontents[3].split())\n self.assertEqual(zp.zone.contents['CNAME'], [{'ttl': '604800',\n 'alias': 'ns',\n 'addr': 'ns1.example.com.'}])\n\n def test_a_from_array(self):\n zp = ZoneParser('example.com')\n zcontents = self.ez\n zp.a_from_array(zcontents[2].split('\\t'))\n self.assertEqual(zp.zone.contents['A'], [{'ttl': '604800',\n 'addr': '10.0.3.103',\n 'alias': '@'}])\n\n def test_naptr_from_array(self):\n zp = ZoneParser('example.com')\n zcontents = '@ 3200 IN NAPTR 1 1 \"S\" \"SIP+D2T\" \"\" _sip._tcp'.split(' ')\n zp.naptr_from_array(zcontents)\n self.assertEqual(zp.zone.contents['NAPTR'], [{'alias': '@', \n 'order': '1',\n 'pref': '1',\n 'flag': '\"S\"',\n 'params': '\"SIP+D2T\"',\n 'regexp': '\"\"',\n 'replace': '_sip._tcp'}])\n\n def test_srv_from_array(self):\n zp = ZoneParser('example.com')\n zcontents = '_sip._udp 3200 IN SRV 0 0 5060 bono-0'.split(' ')\n zp.srv_from_array(zcontents)\n self.assertEqual(zp.zone.contents['SRV'], [{'alias': '_sip._udp',\n 'priority': '0',\n 'weight': '0',\n 'port': '5060',\n 'target': 'bono-0'}])\n\n def test_bono_a_from_array(self):\n zp = ZoneParser('offline.cw-ngv.com')\n zp.a_from_array(u'@ 300 IN A 54.73.45.41'.split(' '))\n self.assertEqual(zp.zone.contents['A'], [{'ttl': '300',\n 'addr': '54.73.45.41',\n 'alias': '@'}])\n\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n @patch('contrib.bind.zone.Zone.to_file')\n def test_save(self, fwm, mopen):\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.readlines.return_value = \"\"\"\nzone \"localhost\" {\n type master;\n file \"/etc/bind/db.local\";\n};\n\nzone \"127.in-addr.arpa\" {\n type master;\n file \"/etc/bind/db.127\";\n};\"\"\".split('\\n')\n\n\n zp = ZoneParser('example.com')\n zp.save()\n fwm.assert_called_with('/etc/bind/db.example.com')\n\n @patch('contrib.bind.zoneparser.ZoneParser.id_generator')\n @patch('subprocess.call')\n @patch('os.path.exists')\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n def test_normalize_contents(self, mopen, opem, spm, idm):\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.readlines.return_value = self.ez\n idm.return_value = 'ABC123'\n opem.return_value = True\n zp = ZoneParser('example.com')\n zp.normalize_contents()\n spm.assert_called_with(['named-checkzone', '-o', '/tmp/ABC123',\n 'example.com', '/etc/bind/db.example.com'])\n\n def test_find_type(self):\n zp = ZoneParser('example.com')\n self.assertEqual(zp.find_type(['foo', 'bar', 'baz', 'CNAME']), 3)\n self.assertEqual(zp.find_type(['foo', 'bar', 'baz']), -1)\n\n def test_dict_to_zone(self):\n zp = ZoneParser('example.com')\n zp.update_ns = Mock()\n zp.update_soa = Mock()\n zp.update_cname = Mock()\n zp.update_a = Mock()\n zp.dict_to_zone({'rr': 'NS'})\n zp.update_ns.assert_called_with({'rr': 'NS'})\n zp.dict_to_zone({'rr': 'SOA'})\n zp.update_soa.assert_called_with({'rr': 'SOA'})\n zp.dict_to_zone({'rr': 'CNAME'})\n zp.update_cname.assert_called_with({'rr': 'CNAME'})\n zp.dict_to_zone({'rr': 'A'})\n zp.update_a.assert_called_with({'rr': 'A'})\n zp.dict_to_zone({'rr': 'NOPE'})\n\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n def test_read_default_zones(self, mopen):\n seed_zone = \"\"\"zone \"255.in-addr.arpa\" {\n type master;\n file \"/etc/bind/db.255\";\n};\"\"\"\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.readlines.return_value = seed_zone.split('\\n')\n zp = ZoneParser('example.com')\n self.assertEqual(zp.read_default_zones(), seed_zone.split('\\n'))\n\n @patch('builtins.open' if sys.version_info > (3,) else '__builtin__.open')\n def test_write_default_zones(self, mopen):\n seed_zone = \"\"\"zone \"255.in-addr.arpa\" {\n type master;\n file \"/etc/bind/db.255\";\n};\"\"\"\n mopen.return_value.__enter__ = lambda s: s\n mopen.return_value.__exit__ = Mock()\n mopen.return_value.write = Mock()\n made_config = seed_zone.split('\\n').append(['hello'])\n zp = ZoneParser('example.com')\n zp.write_default_zones(made_config)\n # mopen.return_value.write.assert_called_with(made_config)\n\n def test_exists_in_default_zones(self):\n seed_zone = \"\"\"zone \"example.com\" {\n type master;\n file \"/etc/bind/db.example.com\";\n};\"\"\" \n zp = ZoneParser('example.com')\n self.assertEqual(zp.exists_in_default_zones(seed_zone.split('\\n')), 0)\n zp = ZoneParser('nope.com')\n self.assertEqual(zp.exists_in_default_zones(seed_zone.split('\\n')), -1)\n","sub_path":"contrib/tests/test_zoneparser.py","file_name":"test_zoneparser.py","file_ext":"py","file_size_in_byte":9090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"170093382","text":"\"\"\"\nModule implementing a rate-limited multi-threaded download client for downloading from Sentinel Hub service\n\"\"\"\nimport logging\nimport time\nfrom threading import Lock, currentThread\n\nimport requests\n\nfrom .handlers import fail_user_errors, retry_temporal_errors\nfrom .client import DownloadClient\nfrom ..sentinelhub_session import SentinelHubSession\nfrom ..sentinelhub_rate_limit import SentinelHubRateLimit\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass SentinelHubDownloadClient(DownloadClient):\n \"\"\" Download client specifically configured for download from Sentinel Hub service\n \"\"\"\n _CACHED_SESSIONS = {}\n\n def __init__(self, *, session=None, **kwargs):\n \"\"\"\n :param session: An OAuth2 session with Sentinel Hub service\n :type session: SentinelHubSession or None\n :param kwargs: Optional parameters from DownloadClient\n \"\"\"\n super().__init__(**kwargs)\n\n if session is not None and not isinstance(session, SentinelHubSession):\n raise ValueError(f'A session parameter has to be an instance of {SentinelHubSession.__name__} or None, but '\n f'{session} was given')\n self.session = session\n\n self.rate_limit = SentinelHubRateLimit(num_processes=self.config.number_of_download_processes)\n self.lock = Lock()\n\n @retry_temporal_errors\n @fail_user_errors\n def _execute_download(self, request):\n \"\"\" Executes the download with a single thread and uses a rate limit object, which is shared between all threads\n \"\"\"\n thread_name = currentThread().getName()\n\n while True:\n sleep_time = self._execute_with_lock(self.rate_limit.register_next)\n\n if sleep_time == 0:\n response = self._do_download(request)\n\n self._execute_with_lock(self.rate_limit.update, response.headers)\n\n if response.status_code != requests.status_codes.codes.TOO_MANY_REQUESTS:\n response.raise_for_status()\n\n LOGGER.debug('%s: Successful download from %s', thread_name, request.url)\n return response.content\n else:\n LOGGER.debug('%s: Sleeping for %0.2f', thread_name, sleep_time)\n time.sleep(sleep_time)\n\n def _execute_with_lock(self, thread_unsafe_function, *args, **kwargs):\n \"\"\" Executes a function inside a thread lock and handles potential errors\n \"\"\"\n self.lock.acquire()\n try:\n return thread_unsafe_function(*args, **kwargs)\n finally:\n self.lock.release()\n\n def _do_download(self, request):\n \"\"\" Runs the download\n \"\"\"\n return requests.request(\n request.request_type.value,\n url=request.url,\n json=request.post_values,\n headers=self._prepare_headers(request),\n timeout=self.config.download_timeout_seconds\n )\n\n def _prepare_headers(self, request):\n \"\"\" Prepares final headers by potentially joining them with session headers\n \"\"\"\n if not request.use_session:\n return request.headers\n\n if self.session is None:\n self.session = self._execute_with_lock(self._get_session)\n\n return {\n **self.session.session_headers,\n **request.headers\n }\n\n def _get_session(self):\n \"\"\" Provides a session object either from cache or it creates a new one\n \"\"\"\n cache_key = self.config.sh_client_id, self.config.sh_client_secret, self.config.get_sh_oauth_url()\n if cache_key in SentinelHubDownloadClient._CACHED_SESSIONS:\n return SentinelHubDownloadClient._CACHED_SESSIONS[cache_key]\n\n session = SentinelHubSession(config=self.config)\n SentinelHubDownloadClient._CACHED_SESSIONS[cache_key] = session\n return session\n","sub_path":"sentinelhub/download/sentinelhub_client.py","file_name":"sentinelhub_client.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161483905","text":"from netCDF4 import Dataset\nimport netcdftime\nimport numpy as np\nfrom datetime import datetime as dt\n\n\nyears=range(2000,2015)\nyears=range(2013,2015)\nmonths=range(1,13)\nbase_dir='original'\ntarget_dir='schism-sflux'\n\ndef create_grid(nc,inc):\n\n\n nc.createDimension('time',None)\n tv = nc.createVariable('time','f8',('time'))\n tv.long_name = 'Time'\n tv.standard_name = 'time'\n tv.units = 'days since 1948-01-01 00:00:00'\n tv.base_date = [1948,1,1,0]\n ut = netcdftime.utime(tv.units)\n\n incv = inc.variables\n \n # copy some global attributes\n for attr in ['experiment_id','references']:\n nc.setncattr(attr,inc.getncattr(attr))\n\n hstr = dt.strftime(dt.now(),'%a %b %d %H:%M:%S %Y')+': create_schism_sflux.py\\n'\n nc.setncattr('history',unicode(hstr+inc.getncattr('history')))\n\n # write time\n iut = netcdftime.utime(incv['time'].units)\n tv[0:len(inc.dimensions['time'])] = ut.date2num(iut.num2date(incv['time'][:]))\n # write grid\n nc.createDimension('nx_grid',len(inc.dimensions['lon']))\n nc.createDimension('ny_grid',len(inc.dimensions['lat']))\n lon = incv['lon'][:]\n lat = incv['lat'][:]\n gridlon,gridlat = np.meshgrid(lon,lat)\n\n lv = nc.createVariable('lon','f4',('ny_grid','nx_grid'))\n lv.long_name = 'Longitude'\n lv.standard_name = 'longitude'\n lv.units = 'degrees_east'\n lv[:] = gridlon\n\n lv = nc.createVariable('lat','f4',('ny_grid','nx_grid'))\n lv.long_name = 'Latitude'\n lv.standard_name = 'latitude'\n lv.units = 'degrees_north'\n lv[:] = gridlat\n\n nc.sync()\n\n\nfor year in years:\n for month in months:\n # create output file\n ncfile='%s/cDII.air.%04d_%02d.nc'%(target_dir,year,month)\n nc = Dataset(ncfile,'w',format='NETCDF3_CLASSIC')\n\n # open input file\n inncfile='%s/cDII.00.UVlat_10M.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n\n # create grid from input file\n create_grid(nc,inc)\n \n # copy wind speeds\n vv = nc.createVariable('uwind','f4',('time','ny_grid','nx_grid'))\n vv.units = 'm/s'\n vv.standard_name = 'eastward_wind'\n vv.coordinates = 'lat lon'\n vv[:] = incv['U_10M'][:].squeeze()\n\n vv = nc.createVariable('vwind','f4',('time','ny_grid','nx_grid'))\n vv.units = 'm/s'\n vv.standard_name = 'northward_wind'\n vv.coordinates = 'lat lon'\n vv[:] = incv['V_10M'][:].squeeze()\n inc.close()\n\n # open temp file, copy temp\n inncfile='%s/cDII.00.T_2M.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n \n vv = nc.createVariable('stmp','f4',('time','ny_grid','nx_grid'))\n vv.units = 'K'\n vv.standard_name = 'air_temperature'\n vv.coordinates = 'lat lon'\n vv[:] = incv['T_2M'][:].squeeze()\n \n inc.close()\n\n # open pressure file, copy pressure\n inncfile='%s/cDII.00.PMSL.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n \n vv = nc.createVariable('prmsl','f4',('time','ny_grid','nx_grid'))\n vv.units = 'Pa'\n vv.standard_name = 'air_pressure_at_sea_level'\n vv.coordinates = 'lat lon'\n vv[:] = incv['PMSL'][:].squeeze()\n \n inc.close()\n\n # open spec. hum file, copy data\n inncfile='%s/cDII.00.QV_2M.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n \n vv = nc.createVariable('spfh','f4',('time','ny_grid','nx_grid'))\n vv.units = '1'\n vv.standard_name = 'specific_humidity'\n vv.coordinates = 'lat lon'\n vv[:] = incv['QV_2M'][:].squeeze()\n \n inc.close()\n\n # close air file\n nc.close()\n\n # ===============================================\n # write rad file\n ncfile='%s/cDII.rad.%04d_%02d.nc'%(target_dir,year,month)\n nc = Dataset(ncfile,'w',format='NETCDF3_CLASSIC')\n\n # open short wave rad input\n inncfile='%s/cDII.00.ASOB_S.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n\n # create grid from input file\n create_grid(nc,inc)\n \n # copy short wave flux\n vv = nc.createVariable('dswrf','f4',('time','ny_grid','nx_grid'))\n vv.units = 'W/m^2'\n vv.standard_name = 'surface_downwelling_shortwave_flux_in_air'\n vv.coordinates = 'lat lon'\n vv[:] = incv['ASOB_S'][:].squeeze()\n\n inc.close()\n\n # open long wave rad input\n inncfile='%s/cDII.00.ALWD_S.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n\n vv = nc.createVariable('dlwrf','f4',('time','ny_grid','nx_grid'))\n vv.units = 'W/m^2'\n vv.standard_name = 'surface_downwelling_longwave_flux_in_air'\n vv.coordinates = 'lat lon'\n vv[:] = incv['ALWD_S'][:].squeeze()\n\n inc.close()\n nc.close()\n\n # ===============================================\n # write precipitation file\n ncfile='%s/cDII.prec.%04d_%02d.nc'%(target_dir,year,month)\n nc = Dataset(ncfile,'w',format='NETCDF3_CLASSIC')\n\n # open short wave rad input\n inncfile='%s/cDII.00.TOT_PREC.%04d_%02d.lonlat_gridCE.nc'%(base_dir,year,month)\n inc = Dataset(inncfile)\n incv=inc.variables\n\n # create grid from input file\n create_grid(nc,inc)\n \n # copy precipitation flux\n t = nc.variables['time'][:2]\n timestep = (t[1]-t[0])*86400.\n print(' timestep: %0.2f s'%timestep)\n\n vv = nc.createVariable('prate','f4',('time','ny_grid','nx_grid'))\n vv.units = 'kg/m^2/s'\n vv.standard_name = 'precipitation_flux'\n vv.coordinates = 'lat lon'\n vv[:] = incv['TOT_PREC'][:].squeeze()/timestep\n\n inc.close()\n nc.close()\n\n","sub_path":"nwshelf/scripts/cDII_to_schism_sflux.py","file_name":"cDII_to_schism_sflux.py","file_ext":"py","file_size_in_byte":5594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"29194794","text":"import pytest\nimport tasks\nfrom tasks import Task\n\ntasks_to_try=(Task('sleep',done=True),\n Task('wake','brian'),\n Task('breathe','Brain',True),\n Task('exercise','Brian',False))\n\n# tasks_id=['Task({},{},{})'.format(t.summary,t.owner,t.done)\n# for t in tasks_to_try]\ndef id_func(fixture_value):\n t=fixture_value\n return \"Task({},{},{})\".format(t.summary,t.owner,t.done)\n\ndef equivalent(t1,t2):\n return (t1.summary==t2.summary and\n t1.owner==t2.owner and\n t1.done==t2.done)\n\n@pytest.fixture(params=tasks_to_try,ids=id_func)\ndef a_task(request):\n yield request.param\n\ndef test_add(tasks_db,a_task):\n task_id=tasks.add(a_task)\n id_from_db=tasks.get(task_id)\n assert equivalent(id_from_db,a_task)","sub_path":"code/ch3/c/tasks_proj/tests/mytest.py","file_name":"mytest.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589044768","text":"from game import *\r\nimport random, math\r\nfrom pygame.locals import *\r\n\r\n\r\ndef main():\r\n global star, diamond, speed, score, lives, toggle, heart, lose_game, high_score # Global variables\r\n \"\"\" Getting assets ready \"\"\"\r\n high_score = getlinesfrom('high_score.txt')\r\n star = pygame.image.load(\"star.png\")\r\n heart = pygame.image.load('heart.png')\r\n diamond = pygame.image.load(\"diamond.png\")\r\n \"\"\"Game Settings for the particular level \"\"\"\r\n initial_speed = 4 # Initial speed of the objects\r\n speed = initial_speed # Speed during gameplay\r\n lives = 3\r\n heart_count = 1 # To give extra lives at regular score intervals\r\n score = 0\r\n initial_freq = 0.2 # Initial frequency of the object's appearance\r\n freq = initial_freq # Frequency during gameplay\r\n counter = 0 # To count till next entry of new object\r\n box_data = [[], [], [], [], [], [], [], []] # To keep track of Objects on all 8 tracks\r\n gamestate = [True, True, True, True] # To keep track of positions of the 4 pairs of tracks\r\n toggle = True # To track the functional direction of tracks (Top-left or Bottom-right)\r\n lose_game = False # To ensure once lost the Game Ends\r\n\r\n \"\"\" Assets Properties \"\"\"\r\n TextColor = Black\r\n\r\n while True: # Main Game Loop\r\n if lose_game:\r\n \"\"\" If Game is lost the game stops and waits for user input to either restart the Game or quit\"\"\"\r\n while True:\r\n pygame.display.update()\r\n center_rect = getrect(500, 400, Display_size[0]/2, Display_size[1]/2, Red)\r\n if score > int(high_score[0]):\r\n getfont(str('New High Score: ' + str(score)), 'bahnchrift', 50, TextColor, center_rect.midtop[0],\r\n center_rect.top + 50)\r\n writelinesto('high_score.txt', score)\r\n else:\r\n getfont(str('Your Score: ' + str(score)), 'bahnchrift', 50, TextColor, center_rect.midtop[0],\r\n center_rect.top + 50)\r\n replay_rect = getrect(300, 50, center_rect.midtop[0], center_rect.top + 200, White)\r\n getfont('Replay', 'bahnchrift', 50, TextColor, replay_rect.center[0], replay_rect.center[1])\r\n quit_rect = getrect(300, 50, center_rect.midtop[0], center_rect.top + 300, White)\r\n getfont('Quit', 'bahnchrift', 50, TextColor, quit_rect.center[0], quit_rect.center[1])\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n quitgame()\r\n if event.type == MOUSEBUTTONDOWN:\r\n if replay_rect.collidepoint(event.pos):\r\n return \"Go to level 1\"\r\n elif quit_rect.collidepoint(event.pos):\r\n quitgame()\r\n \"\"\" If Game not lost, continue with the Gameplay \"\"\"\r\n drawSurface(gamestate, box_data)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n quitgame()\r\n elif event.type == KEYDOWN:\r\n if (event.key == K_UP) | (event.key == K_w):\r\n if toggle:\r\n gamestate[0] = True\r\n else:\r\n gamestate[2] = False\r\n elif (event.key == K_DOWN) | (event.key == K_s):\r\n if toggle:\r\n gamestate[0] = False\r\n else:\r\n gamestate[2] = True\r\n elif (event.key == K_LEFT) | (event.key == K_a):\r\n if toggle:\r\n gamestate[1] = False\r\n else:\r\n gamestate[3] = True\r\n elif (event.key == K_RIGHT) | (event.key == K_d):\r\n if toggle:\r\n gamestate[1] = True\r\n else:\r\n gamestate[3] = False\r\n elif event.key == K_SPACE:\r\n toggle = not toggle\r\n fpsClock.tick(FPS)\r\n counter += 1\r\n if counter > int(FPS/freq):\r\n i = random.randint(0, 7)\r\n j = random.randint(0, 1)\r\n if score/500 > heart_count:\r\n box_data[i].append([heart, 0])\r\n heart_count += 1\r\n i = 7-i\r\n if j == 0:\r\n box_data[i].append([star, 0])\r\n else:\r\n box_data[i].append([diamond, 0])\r\n counter = 0\r\n if score >= 0:\r\n speed = initial_speed*(math.log(score/1000 + 1) + 1)\r\n freq = initial_freq*(math.log(score/100 + 1) + 1)\r\n\r\n\r\ndef drawSurface(gamestate, box_data):\r\n\r\n def check_end(obj, box):\r\n \"\"\" Checks if the object has reached its end of the bar, and if yes removes the object from the list and\r\n performs necessary action according to the final position of the object \"\"\"\r\n global lives, lose_game, score\r\n if obj[1] > bar_length: # If the sprite has reached its length, check for its status and then delete it\r\n if (obj[0] == star) & ((rect.center[0] == center_rect.center[0]) | (rect.center[1] == center_rect.center[1])):\r\n lives -= 1\r\n if lives == 0:\r\n lose_game = True\r\n elif obj[0] == diamond:\r\n if (rect.center[0] == center_rect.center[0]) | (rect.center[1] == center_rect.center[1]):\r\n score += 100\r\n else:\r\n score -= 100\r\n if score < 0:\r\n lose_game = True\r\n elif obj[0] == heart:\r\n if (rect.center[0] == center_rect.center[0]) | (rect.center[1] == center_rect.center[1]):\r\n if lives < 5:\r\n lives += 1\r\n del box_data[box][0]\r\n\r\n\r\n global score, lives, lose_game, high_score\r\n\r\n \"\"\" Assets properties \"\"\"\r\n bar_length = Display_size[0]*0.4\r\n bar_width = bar_length/8\r\n BGcolor = Blue\r\n TextColor = Black\r\n button_color = Yellowish\r\n button_color2 = Red\r\n border_color = Green\r\n inner_boxcolor = Brown\r\n border = 5\r\n\r\n \"\"\" Displaying Game State \"\"\"\r\n Surface.fill(BGcolor)\r\n getfont(caption, 'bahnchrift', 50, TextColor, Display_size[0]/4, Display_size[1]/12, italic=True)\r\n textbox = getfont(str(\"Score: \" + str(score)), 'bahnchrift', 50, TextColor, Display_size[0]*3/4, Display_size[1]/12,\r\n italic=True)\r\n textbox = getfont(str(\"Lives: \" + str(lives)), 'bahnchrift', 50, TextColor, textbox.bottomleft[0],\r\n textbox.bottomleft[1], alignment='topleft', italic=True)\r\n getfont(str(\"High Score: \" + str(int(high_score[0]))), 'bahnchrift', 50, TextColor, textbox.bottomleft[0],\r\n textbox.bottomleft[1], alignment='topleft', italic=True)\r\n\r\n \"\"\" Creating Central Boxes \"\"\"\r\n center_rect = pygame.rect.Rect(0, 0, 3*bar_width, 3*bar_width)\r\n center_rect.center = (Display_size[0]/2, Display_size[1]/2)\r\n getrect(3*bar_width, bar_width, Display_size[0] / 2, Display_size[1] / 2, inner_boxcolor)\r\n getrect(bar_width, 3*bar_width, Display_size[0] / 2, Display_size[1] / 2, inner_boxcolor)\r\n getrect(bar_width, bar_width, Display_size[0] / 2, Display_size[1] / 2, Black, border=border)\r\n rect = pygame.rect.Rect(center_rect[0], center_rect[1], bar_length, bar_width)\r\n\r\n \"\"\" gamestat[i] means to check if the left(i = 0), right(i = 2), top(i = 1), or bottom(i = 3) is in its initial\r\n position or not.\"\"\"\r\n \"\"\"Drawing and simulating Left Rectangle \"\"\"\r\n rect.midright = center_rect.midleft\r\n\r\n if gamestate[0]:\r\n \"\"\" Creating lower box \"\"\"\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[0]:\r\n Surface.blit(obj[0], (rect.topleft[0] + obj[1], rect.topleft[1]))\r\n obj[1] += speed\r\n check_end(obj, 0)\r\n \"\"\" Creating upper box\"\"\"\r\n rect.bottom = rect.top\r\n pygame.draw.rect(Surface, button_color, rect)\r\n pygame.draw.line(Surface, Black, rect.bottomleft, rect.bottomright)\r\n for obj in box_data[1]:\r\n Surface.blit(obj[0], (rect.topleft[0] + obj[1], rect.topleft[1]))\r\n obj[1] += speed\r\n check_end(obj, 1)\r\n else:\r\n \"\"\" Creating upper box \"\"\"\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[1]:\r\n Surface.blit(obj[0], (rect.topleft[0] + obj[1], rect.topleft[1]))\r\n obj[1] += speed\r\n check_end(obj, 1)\r\n \"\"\" Creating lower box \"\"\"\r\n rect.top = rect.bottom\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[0]:\r\n Surface.blit(obj[0], (rect.topleft[0] + obj[1], rect.topleft[1]))\r\n obj[1] += speed\r\n check_end(obj, 0)\r\n pygame.draw.line(Surface, Black, rect.topleft, rect.topright)\r\n \"\"\" Drawing boundary if toggle is active\"\"\"\r\n if toggle:\r\n getrect(bar_length, 3*bar_width, center_rect.topleft[0], center_rect.topleft[1], Lightblue, border=border,\r\n alignment='topright')\r\n\r\n \"\"\" Drawing and simulating Right Rectangle \"\"\"\r\n rect.midleft = center_rect.midright\r\n if gamestate[2]:\r\n \"\"\" Creating upper box \"\"\"\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[4]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width - obj[1], rect.bottomright[1] - bar_width))\r\n obj[1] += speed\r\n check_end(obj, 4)\r\n \"\"\" Creating lower box \"\"\"\r\n rect.top = rect.bottom\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[5]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width - obj[1], rect.bottomright[1] - bar_width))\r\n obj[1] += speed\r\n check_end(obj, 5)\r\n else:\r\n \"\"\" Creating lower box \"\"\"\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[5]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width - obj[1], rect.bottomright[1] - bar_width))\r\n obj[1] += speed\r\n check_end(obj, 5)\r\n \"\"\"Creating upper box \"\"\"\r\n rect.bottom = rect.top\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[4]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width - obj[1], rect.bottomright[1] - bar_width))\r\n obj[1] += speed\r\n check_end(obj, 4)\r\n\r\n \"\"\" Drawing boundary if toggle is inactive \"\"\"\r\n if not toggle:\r\n getrect(bar_length, 3*bar_width, center_rect.topright[0], center_rect.topright[1], Lightblue, border=border,\r\n alignment='topleft')\r\n rect = pygame.rect.Rect(center_rect[0], center_rect[1], bar_width, bar_length)\r\n\r\n \"\"\" Drawing and simulating Top Rectangle \"\"\"\r\n rect.midbottom = center_rect.midtop\r\n if gamestate[1]:\r\n \"\"\" Creating left box \"\"\"\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[2]:\r\n Surface.blit(obj[0], (rect.topleft[0], rect.topleft[1] + obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 2)\r\n \"\"\" Creating right box \"\"\"\r\n rect.left = rect.right\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[3]:\r\n Surface.blit(obj[0], (rect.topleft[0], rect.topleft[1] + obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 3)\r\n pygame.draw.line(Surface, Black, rect.topleft, rect.bottomleft)\r\n else:\r\n \"\"\" Creating right box \"\"\"\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[3]:\r\n Surface.blit(obj[0], (rect.topleft[0], rect.topleft[1] + obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 3)\r\n \"\"\" Creating left box \"\"\"\r\n rect.right = rect.left\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[2]:\r\n Surface.blit(obj[0], (rect.topleft[0], rect.topleft[1] + obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 2)\r\n pygame.draw.line(Surface, Black, rect.topright, rect.bottomright)\r\n \"\"\" Drawing boundary if toggle is active\"\"\"\r\n if toggle:\r\n getrect(3*bar_width, bar_length, center_rect.topleft[0], center_rect.topleft[1], Lightblue, border=border,\r\n alignment='bottomleft')\r\n\r\n \"\"\" Drawing and simulating Bottom Rectangle \"\"\"\r\n rect.midtop = center_rect.midbottom\r\n if gamestate[3]:\r\n \"\"\" Drawing right box \"\"\"\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[6]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width, rect.bottomright[1] - bar_width - obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 6)\r\n \"\"\" Drawing left box \"\"\"\r\n rect.right = rect.left\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[7]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width, rect.bottomright[1] - bar_width - obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 7)\r\n pygame.draw.line(Surface, Black, rect.topright, rect.bottomright)\r\n else:\r\n \"\"\" Drawing left box \"\"\"\r\n pygame.draw.rect(Surface, button_color, rect)\r\n for obj in box_data[7]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width, rect.bottomright[1] - bar_width - obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 7)\r\n \"\"\" Drawing right box \"\"\"\r\n rect.left = rect.right\r\n pygame.draw.rect(Surface, button_color2, rect)\r\n for obj in box_data[6]:\r\n Surface.blit(obj[0], (rect.bottomright[0] - bar_width, rect.bottomright[1] - bar_width - obj[1]))\r\n obj[1] += speed\r\n check_end(obj, 6)\r\n pygame.draw.line(Surface, Black, rect.topleft, rect.bottomleft)\r\n \"\"\" Drawing boundary if toggle is inactive \"\"\"\r\n if not toggle:\r\n getrect(3*bar_width, bar_length, center_rect.bottomleft[0], center_rect.bottomleft[1], Lightblue, border=border,\r\n alignment='topleft')\r\n\r\n getrect(3*bar_width, 3*bar_width, Display_size[0]/2, Display_size[1]/2, border_color, border=border)\r\n pygame.display.update()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"l1.py","file_name":"l1.py","file_ext":"py","file_size_in_byte":14656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"588973531","text":"import common.globals as g\n\n\nclass profile_23000_duty_expression(object):\n def import_node(self, app, update_type, omsg, transaction_id, message_id, record_code, sub_record_code):\n g.app.message_count += 1\n operation_date = app.get_timestamp()\n duty_expression_id = app.get_value(omsg, \".//oub:duty.expression.id\", True)\n validity_start_date = app.get_date_value(omsg, \".//oub:validity.start.date\", True)\n validity_end_date = app.get_date_value(omsg, \".//oub:validity.end.date\", True)\n duty_amount_applicability_code = app.get_number_value(omsg, \".//oub:duty.amount.applicability.code\", True)\n measurement_unit_applicability_code = app.get_number_value(omsg, \".//oub:measurement.unit.applicability.code\", True)\n monetary_unit_applicability_code = app.get_number_value(omsg, \".//oub:monetary.unit.applicability.code\", True)\n\n # Set operation types and print load message to screen\n operation = g.app.get_loading_message(update_type, \"duty expression\", duty_expression_id)\n\n # Load data\n cur = app.conn.cursor()\n try:\n cur.execute(\"\"\"INSERT INTO duty_expressions_oplog (duty_expression_id, validity_start_date,\n validity_end_date, duty_amount_applicability_code, measurement_unit_applicability_code, monetary_unit_applicability_code,\n operation, operation_date)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\"\",\n (duty_expression_id, validity_start_date, validity_end_date,\n duty_amount_applicability_code, measurement_unit_applicability_code, monetary_unit_applicability_code,\n operation, operation_date))\n app.conn.commit()\n except:\n g.app.record_business_rule_violation(\"DB\", \"DB failure\", operation, transaction_id, message_id, record_code, sub_record_code, duty_expression_id)\n cur.close()\n","sub_path":"create-data/convert_and_import_taric/profile/profile_23000_duty_expression.py","file_name":"profile_23000_duty_expression.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"343411918","text":"\n\n#calss header\nclass _BEEPER():\n\tdef __init__(self,): \n\t\tself.name = \"BEEPER\"\n\t\tself.definitions = [u'a small device, usually carried or worn on the body, that vibrates or makes a noise to tell you that someone wants you to phone them ']\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/_beeper.py","file_name":"_beeper.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"502243759","text":"import os\nfrom unittest import TestCase\n\nimport conclave.dag as ccdag\nimport conclave.lang as cc\nfrom conclave import CodeGenConfig\nfrom conclave.codegen.scotch import ScotchCodeGen\nfrom conclave.comp import mpc, scotch, rewrite_dag\nfrom conclave.utils import *\n\n\nclass TestConclave(TestCase):\n\n def check_workflow(self, code, name):\n self.maxDiff = None\n expected_rootdir = \"{}/rewrite_expected\".format(os.path.dirname(os.path.realpath(__file__)))\n\n with open(expected_rootdir + '/{}'.format(name), 'r') as f:\n expected = f.read()\n\n self.assertEqual(expected, code)\n\n def test_mult_by_zer0(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2], \"rel\")\n\n # specify the workflow\n mult = cc.multiply(rel, \"mult\", \"a\", [\"a\", 0])\n\n cc.collect(mult, 1)\n\n # return root nodes\n return {in_1, in_2}\n\n actual = protocol()\n self.check_workflow(actual, 'mult_by_zero')\n\n def test_concat_pushdown(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n cols_in_3 = [\n defCol(\"a\", \"INTEGER\", [3]),\n defCol(\"b\", \"INTEGER\", [3])\n ]\n in_3 = cc.create(\"in_3\", cols_in_3, {3})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2, in_3], \"rel\")\n proj = cc.project(rel, \"proj\", [\"a\", \"b\"])\n agg = cc.aggregate(proj, \"agg\", [\"a\"], \"b\", \"sum\", \"total_b\")\n\n cc.collect(agg, 1)\n\n # return root nodes\n return {in_1, in_2, in_3}\n\n actual = protocol()\n self.check_workflow(actual, 'concat_pushdown')\n\n def test_pushdown_into_filter(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1]),\n defCol(\"c\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2]),\n defCol(\"c\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2], \"rel\")\n\n projected = cc.project(rel, \"projected\", [\"c\", \"b\"])\n\n # specify the workflow\n filtered = cc.cc_filter(projected, \"filtered\", \"c\", \"==\", other_col_name=\"b\")\n\n cc.collect(filtered, 1)\n\n # return root nodes\n return {in_1, in_2}\n\n actual = protocol()\n self.check_workflow(actual, \"pushdown_into_filter\")\n\n def test_concat_pushdown_proj_change_col_num(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1]),\n defCol(\"c\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2]),\n defCol(\"c\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n cols_in_3 = [\n defCol(\"a\", \"INTEGER\", [3]),\n defCol(\"b\", \"INTEGER\", [3]),\n defCol(\"c\", \"INTEGER\", [3])\n ]\n in_3 = cc.create(\"in_3\", cols_in_3, {3})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2, in_3], \"rel\")\n proj = cc.project(rel, \"proj\", [\"a\", \"b\"])\n agg = cc.aggregate(proj, \"agg\", [\"a\"], \"b\", \"sum\", \"total_b\")\n\n cc.collect(agg, 1)\n\n # return root nodes\n return {in_1, in_2, in_3}\n\n actual = protocol()\n self.check_workflow(actual, 'concat_pushdown_proj_change_col_num')\n\n def test_concat_pushdown_rearrange_cols(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1]),\n defCol(\"c\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2]),\n defCol(\"c\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n cols_in_3 = [\n defCol(\"a\", \"INTEGER\", [3]),\n defCol(\"b\", \"INTEGER\", [3]),\n defCol(\"c\", \"INTEGER\", [3])\n ]\n in_3 = cc.create(\"in_3\", cols_in_3, {3})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2, in_3], \"rel\")\n proj = cc.project(rel, \"proj\", [\"c\", \"a\"])\n agg = cc.aggregate(proj, \"agg\", [\"c\"], \"a\", \"sum\", \"total_b\")\n\n cc.collect(agg, 1)\n\n # return root nodes\n return {in_1, in_2, in_3}\n\n actual = protocol()\n self.check_workflow(actual, 'concat_pushdown_rearrange_cols')\n\n def test_agg_proj(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2], \"rel\")\n\n # specify the workflow\n proj_a = cc.project(rel, \"proj_a\", [\"a\", \"b\"])\n proj_b = cc.project(proj_a, \"proj_b\", [\"a\", \"b\"])\n agg = cc.aggregate(proj_b, \"agg\", [\"a\"], \"b\", \"sum\", \"total_b\")\n proj_c = cc.project(agg, \"proj_c\", [\"a\", \"total_b\"])\n\n cc.collect(proj_c, 1)\n\n # return root nodes\n return {in_1, in_2}\n\n actual = protocol()\n self.check_workflow(actual, 'agg_proj')\n\n def test_join(self):\n @scotch\n @mpc\n def protocol():\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1]),\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n\n cols_in_2 = [\n defCol(\"c\", \"INTEGER\", [2]),\n defCol(\"d\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n proj_b = cc.project(in_2, \"proj_b\", [\"c\", \"d\"])\n\n joined = cc.join(in_1, proj_b, \"joined\", [\"a\"], [\"c\"])\n cc.collect(joined, 1)\n return {in_1, in_2}\n\n actual = protocol()\n self.check_workflow(actual, 'join')\n\n def test_hybrid_agg_opt(self):\n def protocol():\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [1], [2]),\n defCol(\"b\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n cc.collect(cc.aggregate(cc.concat([in_1, in_2], \"rel\"), \"agg\", [\"a\"], \"b\", \"sum\", \"total_b\"), 1)\n return {in_1, in_2}\n\n dag = rewrite_dag(ccdag.OpDag(protocol()), use_leaky_ops=True)\n actual = ScotchCodeGen(CodeGenConfig(), dag)._generate(0, 0)\n self.check_workflow(actual, \"hybrid_agg_leaky\")\n\n def test_hybrid_join_opt(self):\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1]),\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n\n cols_in_2 = [\n defCol(\"c\", \"INTEGER\", [1], [2]),\n defCol(\"d\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n\n result = cc.join(in_1, in_2, \"result\", [\"a\"], [\"c\"])\n\n cc.collect(result, 1)\n # create dag\n return {in_1, in_2}\n\n dag = rewrite_dag(ccdag.OpDag(protocol()), use_leaky_ops=True)\n actual = ScotchCodeGen(CodeGenConfig(), dag)._generate(0, 0)\n self.check_workflow(actual, 'hybrid_join_leaky')\n\n def test_hybrid_join_party_two_opt(self):\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1], [2]),\n defCol(\"b\", \"INTEGER\", [1]),\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n\n cols_in_2 = [\n defCol(\"c\", \"INTEGER\", [2]),\n defCol(\"d\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n\n result = cc.join(in_1, in_2, \"result\", [\"a\"], [\"c\"])\n\n cc.collect(result, 1)\n # create dag\n return {in_1, in_2}\n\n dag = rewrite_dag(ccdag.OpDag(protocol()), use_leaky_ops=True)\n actual = ScotchCodeGen(CodeGenConfig(), dag)._generate(0, 0)\n self.check_workflow(actual, 'hybrid_join_leaky_party_two')\n\n def test_public_join(self):\n def protocol():\n left_one_cols = [\n defCol(\"a\", \"INTEGER\", 1, 2, 3),\n defCol(\"b\", \"INTEGER\", 1)\n ]\n left_one = cc.create(\"left_one\", left_one_cols, {1})\n\n right_one_cols = [\n defCol(\"c\", \"INTEGER\", 1, 2, 3),\n defCol(\"d\", \"INTEGER\", 1)\n ]\n right_one = cc.create(\"right_one\", right_one_cols, {1})\n\n left_two_cols = [\n defCol(\"a\", \"INTEGER\", 1, 2, 3),\n defCol(\"b\", \"INTEGER\", 2)\n ]\n left_two = cc.create(\"left_two\", left_two_cols, {2})\n\n right_two_cols = [\n defCol(\"c\", \"INTEGER\", 1, 2, 3),\n defCol(\"d\", \"INTEGER\", 2)\n ]\n right_two = cc.create(\"right_two\", right_two_cols, {2})\n\n left = cc.concat([left_one, left_two], \"left\")\n right = cc.concat([right_one, right_two], \"right\")\n\n joined = cc.join(left, right, \"joined\", [\"a\"], [\"c\"])\n cc.collect(joined, 1)\n\n return {left_one, left_two, right_one, right_two}\n\n dag = rewrite_dag(ccdag.OpDag(protocol()))\n actual = ScotchCodeGen(CodeGenConfig(), dag)._generate(0, 0)\n self.check_workflow(actual, 'public_join')\n\n def test_ssn(self):\n def protocol():\n govreg_cols = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n govreg = cc.create(\"a_govreg\", govreg_cols, {1})\n govreg_dummy = cc.project(govreg, \"govreg_dummy\", [\"a\", \"b\"])\n\n company0_cols = [\n defCol(\"c\", \"INTEGER\", [1], [2]),\n defCol(\"d\", \"INTEGER\", [2])\n ]\n company0 = cc.create(\"company0\", company0_cols, {2})\n company0_dummy = cc.project(company0, \"company0_dummy\", [\"c\", \"d\"])\n\n company1_cols = [\n defCol(\"c\", \"INTEGER\", [1], [3]),\n defCol(\"d\", \"INTEGER\", [3])\n ]\n company1 = cc.create(\"company1\", company1_cols, {3})\n company1_dummy = cc.project(company1, \"company1_dummy\", [\"c\", \"d\"])\n\n companies = cc.concat([company0_dummy, company1_dummy], \"companies\")\n\n joined = cc.join(govreg_dummy, companies, \"joined\", [\"a\"], [\"c\"])\n res = cc.aggregate(joined, \"actual\", [\"b\"], \"d\", \"sum\", \"total\")\n cc.collect(res, 1)\n\n return {govreg, company0, company1}\n\n dag = rewrite_dag(ccdag.OpDag(protocol()), use_leaky_ops=True)\n actual = ScotchCodeGen(CodeGenConfig(), dag)._generate(0, 0)\n self.check_workflow(actual, \"ssn_leaky\")\n\n def test_taxi(self):\n @scotch\n @mpc\n def protocol():\n cols_in_1 = [\n defCol(\"companyID\", \"INTEGER\", [1]),\n defCol(\"price\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"companyID\", \"INTEGER\", [2]),\n defCol(\"price\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in_2\", cols_in_2, {2})\n cols_in_3 = [\n defCol(\"companyID\", \"INTEGER\", [3]),\n defCol(\"price\", \"INTEGER\", [3])\n ]\n in_3 = cc.create(\"in_3\", cols_in_3, {3})\n\n cab_data = cc.concat([in_1, in_2, in_3], \"cab_data\")\n\n selected_input = cc.project(\n cab_data, \"selected_input\", [\"companyID\", \"price\"])\n local_rev = cc.aggregate(selected_input, \"local_rev\", [\n \"companyID\"], \"price\", \"sum\", \"local_rev\")\n scaled_down = cc.divide(\n local_rev, \"scaled_down\", \"local_rev\", [\"local_rev\", 1000])\n first_val_blank = cc.multiply(\n scaled_down, \"first_val_blank\", \"companyID\", [\"companyID\", 0])\n local_rev_scaled = cc.multiply(\n first_val_blank, \"local_rev_scaled\", \"local_rev\", [\"local_rev\", 100])\n total_rev = cc.aggregate(first_val_blank, \"total_rev\", [\n \"companyID\"], \"local_rev\", \"sum\", \"global_rev\")\n local_total_rev = cc.join(local_rev_scaled, total_rev, \"local_total_rev\", [\n \"companyID\"], [\"companyID\"])\n market_share = cc.divide(local_total_rev, \"market_share\", \"local_rev\", [\n \"local_rev\", \"global_rev\"])\n market_share_squared = cc.multiply(market_share, \"market_share_squared\", \"local_rev\",\n [\"local_rev\", \"local_rev\", 1])\n hhi = cc.aggregate(market_share_squared, \"hhi\", [\n \"companyID\"], \"local_rev\", \"sum\", \"hhi\")\n\n cc.collect(hhi, 1)\n\n # return root nodes\n return {in_1, in_2, in_3}\n\n actual = protocol()\n self.check_workflow(actual, 'taxi')\n\n def test_agg_pushdown(self):\n @scotch\n @mpc\n def protocol():\n # define inputs\n cols_in_1 = [\n defCol(\"a\", \"INTEGER\", [1]),\n defCol(\"b\", \"INTEGER\", [1])\n ]\n in_1 = cc.create(\"in_1\", cols_in_1, {1})\n cols_in_2 = [\n defCol(\"a\", \"INTEGER\", [2]),\n defCol(\"b\", \"INTEGER\", [2])\n ]\n in_2 = cc.create(\"in2\", cols_in_2, {2})\n cols_in_3 = [\n defCol(\"a\", \"INTEGER\", [3]),\n defCol(\"b\", \"INTEGER\", [3])\n ]\n in_3 = cc.create(\"in_3\", cols_in_3, {3})\n\n # combine parties' inputs into one relation\n rel = cc.concat([in_1, in_2, in_3], \"rel\")\n proj = cc.project(rel, \"proj\", [\"a\", \"b\"])\n agg = cc.aggregate(proj, \"agg\", [\"a\"], \"b\", \"sum\", \"total_b\")\n div = cc.divide(agg, \"div\", \"a\", [\"a\", 1])\n mult = cc.multiply(div, \"mult\", \"a\", [\"a\", 1])\n\n cc.collect(mult, 1)\n\n # return root nodes\n return {in_1, in_2, in_3}\n\n actual = protocol()\n self.check_workflow(actual, 'agg_pushdown')\n\n def test_aspirin_no_slicing(self):\n @scotch\n @mpc\n def protocol():\n pid_col_meds = \"0\"\n med_col_meds = \"4\"\n date_col_meds = \"7\"\n\n pid_col_diags = \"8\"\n diag_col_diags = \"16\"\n date_col_diags = \"18\"\n\n num_med_cols = 8\n num_diag_cols = 13\n\n left_medication_cols = [defCol(str(i), \"INTEGER\", 1) for i in range(num_med_cols)]\n # public PID column\n left_medication_cols[0] = defCol(pid_col_meds, \"INTEGER\", 1, 2, 3)\n left_medication = cc.create(\"left_medication\", left_medication_cols, {1})\n\n left_diagnosis_cols = [defCol(str(i + num_med_cols), \"INTEGER\", 1) for i in range(num_diag_cols)]\n # public PID column\n left_diagnosis_cols[0] = defCol(pid_col_diags, \"INTEGER\", 1, 2, 3)\n left_diagnosis = cc.create(\"left_diagnosis\", left_diagnosis_cols, {1})\n\n right_medication_cols = [defCol(str(i), \"INTEGER\", 2) for i in range(num_med_cols)]\n # public PID column\n right_medication_cols[0] = defCol(pid_col_meds, \"INTEGER\", 1, 2, 3)\n right_medication = cc.create(\"right_medication\", right_medication_cols, {2})\n\n right_diagnosis_cols = [defCol(str(i + num_med_cols), \"INTEGER\", 2) for i in range(num_diag_cols)]\n # public PID column\n right_diagnosis_cols[0] = defCol(pid_col_diags, \"INTEGER\", 1, 2, 3)\n right_diagnosis = cc.create(\"right_diagnosis\", right_diagnosis_cols, {2})\n\n medication = cc.concat([left_medication, right_medication], \"medication\")\n diagnosis = cc.concat([left_diagnosis, right_diagnosis], \"diagnosis\")\n\n # only keep relevant columns\n medication_proj = cc.project(medication, \"medication_proj\", [pid_col_meds, med_col_meds, date_col_meds])\n diagnosis_proj = cc.project(diagnosis, \"diagnosis_proj\", [pid_col_diags, diag_col_diags, date_col_diags])\n\n joined = cc.join(medication_proj, diagnosis_proj, \"joined\", [pid_col_meds], [pid_col_diags])\n\n cases = cc.cc_filter(joined, \"cases\", date_col_diags, \"<\", other_col_name=date_col_meds)\n aspirin = cc.cc_filter(cases, \"aspirin\", med_col_meds, \"==\", scalar=1)\n heart_patients = cc.cc_filter(aspirin, \"heart_patients\", diag_col_diags, \"==\", scalar=1)\n\n cc.collect(cc.distinct_count(heart_patients, \"actual\", pid_col_meds), 1)\n\n return {left_medication, left_diagnosis, right_medication, right_diagnosis}\n\n actual = protocol()\n self.check_workflow(actual, \"aspirin_no_slicing\")\n\n def test_aspirin_with_slicing(self):\n @scotch\n @mpc\n def protocol():\n pid_col_meds = \"0\"\n med_col_meds = \"4\"\n date_col_meds = \"7\"\n\n pid_col_diags = \"8\"\n diag_col_diags = \"16\"\n date_col_diags = \"18\"\n\n num_med_cols = 8\n num_diag_cols = 13\n\n left_medication_cols = [defCol(str(i), \"INTEGER\", 1) for i in range(num_med_cols)]\n # public PID column\n left_medication_cols[0] = defCol(pid_col_meds, \"INTEGER\", 1, 2, 3)\n left_medication = cc.create(\"left_medication\", left_medication_cols, {1})\n\n left_diagnosis_cols = [defCol(str(i + num_med_cols), \"INTEGER\", 1) for i in range(num_diag_cols)]\n # public PID column\n left_diagnosis_cols[0] = defCol(pid_col_diags, \"INTEGER\", 1, 2, 3)\n left_diagnosis = cc.create(\"left_diagnosis\", left_diagnosis_cols, {1})\n\n right_medication_cols = [defCol(str(i), \"INTEGER\", 2) for i in range(num_med_cols)]\n # public PID column\n right_medication_cols[0] = defCol(pid_col_meds, \"INTEGER\", 1, 2, 3)\n right_medication = cc.create(\"right_medication\", right_medication_cols, {2})\n\n right_diagnosis_cols = [defCol(str(i + num_med_cols), \"INTEGER\", 2) for i in range(num_diag_cols)]\n # public PID column\n right_diagnosis_cols[0] = defCol(pid_col_diags, \"INTEGER\", 1, 2, 3)\n right_diagnosis = cc.create(\"right_diagnosis\", right_diagnosis_cols, {2})\n\n # Manual slicing\n left_keys = cc.union(left_medication, left_diagnosis, \"left_pids\", pid_col_meds, pid_col_diags)\n right_keys = cc.union(right_medication, right_diagnosis, \"right_pids\", pid_col_meds, pid_col_diags)\n\n left_shared_pids = cc._pub_intersect(left_keys, \"a_left_shared_pids\", pid_col_meds)\n cc._persist(left_shared_pids, \"a_left_shared_pids\")\n right_shared_pids = cc._pub_intersect(right_keys, \"a_right_shared_pids\", pid_col_meds, is_server=False)\n cc._persist(right_shared_pids, \"a_right_shared_pids\")\n\n left_medication_proj = cc.project(left_medication, \"left_medication_proj\",\n [pid_col_meds, med_col_meds, date_col_meds])\n left_medication_shared = cc.filter_by(left_medication_proj, \"left_medication_shared\", pid_col_meds,\n left_shared_pids)\n\n left_diagnosis_proj = cc.project(left_diagnosis, \"left_diagnosis_proj\",\n [pid_col_diags, diag_col_diags, date_col_diags])\n left_diagnosis_shared = cc.filter_by(left_diagnosis_proj, \"left_diagnosis_shared\", pid_col_diags,\n left_shared_pids)\n\n right_medication_proj = cc.project(right_medication, \"right_medication_proj\",\n [pid_col_meds, med_col_meds, date_col_meds])\n right_medication_shared = cc.filter_by(right_medication_proj, \"right_medication_shared\", pid_col_meds,\n right_shared_pids)\n\n right_diagnosis_proj = cc.project(right_diagnosis, \"right_diagnosis_proj\",\n [pid_col_diags, diag_col_diags, date_col_diags])\n right_diagnosis_shared = cc.filter_by(right_diagnosis_proj, \"right_diagnosis_shared\", pid_col_diags,\n right_shared_pids)\n\n # Slicing done\n medication_shared = cc.concat([left_medication_shared, right_medication_shared], \"medication_shared\")\n diagnosis_shared = cc.concat([left_diagnosis_shared, right_diagnosis_shared], \"diagnosis_shared\")\n\n joined = cc.join(medication_shared, diagnosis_shared, \"joined\", [pid_col_meds], [pid_col_diags])\n cases = cc.cc_filter(joined, \"cases\", date_col_diags, \"<\", other_col_name=date_col_meds)\n aspirin = cc.cc_filter(cases, \"aspirin\", med_col_meds, \"==\", scalar=1)\n heart_patients = cc.cc_filter(aspirin, \"heart_patients\", diag_col_diags, \"==\", scalar=1)\n\n cc.collect(cc.distinct_count(heart_patients, \"actual_mpc\", pid_col_meds), 1)\n\n return {\n left_medication,\n left_diagnosis,\n right_medication,\n right_diagnosis\n }\n\n actual = protocol()\n self.check_workflow(actual, \"aspirin_with_slicing\")\n\n def test_comorb_full(self):\n @scotch\n @mpc\n def protocol():\n pid_col = \"8\"\n diagnosis_col = \"16\"\n\n cols_to_skip = 8\n num_diagnosis_cols = 13\n\n left_diagnosis_cols = [defCol(str(i + cols_to_skip), \"INTEGER\", 1) for i in range(num_diagnosis_cols)]\n left_diagnosis = cc.create(\"left_diagnosis\", left_diagnosis_cols, {1})\n\n left_cohort = cc.create(\"left_cohort\", [defCol(\"pid\", \"INTEGER\", 1)], {1})\n\n left_selected = cc.filter_by(left_diagnosis, \"left_selected\", pid_col, left_cohort)\n\n right_diagnosis_cols = [defCol(str(i + cols_to_skip), \"INTEGER\", 2) for i in range(num_diagnosis_cols)]\n right_diagnosis = cc.create(\"right_diagnosis\", right_diagnosis_cols, {2})\n\n right_cohort = cc.create(\"right_cohort\", [defCol(\"pid\", \"INTEGER\", 2)], {2})\n\n right_selected = cc.filter_by(right_diagnosis, \"right_selected\", pid_col, right_cohort)\n\n cohort = cc.concat([left_selected, right_selected], \"cohort\")\n counts = cc.aggregate_count(cohort, \"counts\", [diagnosis_col], \"total\")\n cc.collect(cc.sort_by(counts, \"actual\", \"total\"), 1)\n\n return {left_diagnosis, left_cohort, right_diagnosis, right_cohort}\n\n actual = protocol()\n self.check_workflow(actual, \"comorb_full\")\n\n def test_comorb(self):\n @scotch\n @mpc\n def protocol():\n diagnosis_col = \"12\"\n num_diagnosis_cols = 13\n\n left_diagnosis_cols = [defCol(str(i), \"INTEGER\", 1) for i in range(num_diagnosis_cols)]\n left_diagnosis = cc.create(\"left_diagnosis\", left_diagnosis_cols, {1})\n\n right_diagnosis_cols = [defCol(str(i), \"INTEGER\", 2) for i in range(num_diagnosis_cols)]\n right_diagnosis = cc.create(\"right_diagnosis\", right_diagnosis_cols, {2})\n\n cohort = cc.concat([left_diagnosis, right_diagnosis], \"cohort\")\n counts = cc.aggregate_count(cohort, \"counts\", [diagnosis_col], \"total\")\n cc.collect(cc.sort_by(counts, \"actual\", \"total\"), 1)\n\n return {left_diagnosis, right_diagnosis}\n\n actual = protocol()\n self.check_workflow(actual, \"comorb\")\n","sub_path":"tests/dag_rewrite/test_comp_dag_rewrite.py","file_name":"test_comp_dag_rewrite.py","file_ext":"py","file_size_in_byte":25946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"534742801","text":"# Reference:\n# https://github.com/orbxball/ML2017/blob/master/hw3/activate_filters.py\nimport sys\nimport os\nimport argparse\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\ntf.executing_eagerly()\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.optimizers import *\nimport numpy as np\nfrom PIL import Image\n\n# util function to convert a tensor into a valid image\ndef deprocess_image(x):\n # normalize tensor: center on 0., ensure std is 0.1\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n\n # clip to [0, 1]\n x += 0.5\n x = np.clip(x, 0, 1)\n\n # convert to array\n x *= 255\n x = np.clip(x, 0, 255).astype('uint8')\n # print(x.shape)\n return x\n\ndef normalize(x):\n # utility function to normalize a tensor by its L2 norm\n return x / (K.sqrt(K.mean(K.square(x))) + 1e-7)\n\ndef grad_ascent(num_step,input_image_data,iter_func):\n \"\"\"\n Implement this function!\n \"\"\"\n filter_images = []\n step = 1e-2\n for i in range(num_step):\n loss_value, grads_value = iter_func([input_image_data, 0])\n input_image_data += grads_value * step\n if i % RECORD_FREQ == 0:\n filter_images.append((input_image_data, loss_value))\n print('#{}, loss rate: {}'.format(i, loss_value))\n return filter_images\n\nRECORD_FREQ = 10\n\n\n\ndef main():\n model_name = '1/9.hdf5'\n\n num_step = NUM_STEPS = 100\n nb_filter = 32\n\n base_dir = './'\n filter_dir = os.path.join(base_dir, 'filter_vis')\n if not os.path.exists(filter_dir):\n os.mkdir(filter_dir)\n store_path = ''\n\n emotion_classifier = keras.models.load_model(model_name)\n collect_layers = [l.output\n for l in emotion_classifier.layers\n if 'batch' in l.name]\n\n model_tmp = keras.models.Model(\n inputs=emotion_classifier.input,\n outputs=emotion_classifier.get_layer('conv2d_3').output)\n\n n_filter = model_tmp.output_shape[3]\n for i_filter in range(n_filter):\n print('filter',i_filter)\n\n # activation = lambda y_true, y_pred: -tf.math.reduce_mean(y_true[:,:,:,i_filter])\n # model_tmp.compile(\n # optimizer=Adam(learning_rate=1e-3, beta_1=0.9, beta_2=0.99),\n # loss=activation,\n #\n # )\n\n @tf.function\n def train_step(img):\n with tf.GradientTape() as tape:\n tape.watch(img)\n conv_out = model_tmp(img)\n activation = -tf.math.reduce_mean(conv_out[:, :, :, i_filter])\n grad = tape.gradient(activation, img)\n opt.apply_gradients([(grad, img)])\n return activation\n\n epochs = 10000\n img = tf.Variable(np.random.random((1, 48, 48, 1)), dtype='float32')\n opt = Adam(learning_rate=1e-3, beta_1=0.9, beta_2=0.99)\n for i_epoch in range(epochs):\n activation = train_step(img)\n if i_epoch % 1000 == 0:\n print('epoch',i_epoch,'activation',activation)\n\n img = img.numpy()\n img_max = np.max(img)\n img_min = np.min(img)\n img = (img - img_min) / (img_max - img_min + 1e-18) * 255\n\n img = Image.fromarray(img.reshape((48,48))).convert('L')\n img.save('featmap/3-{}.png'.format(i_filter))\n\n # for cnt, c in enumerate(collect_layers):\n # filter_imgs = []\n # for filter_idx in range(nb_filter):\n # input_img_data = np.random.random((1, 48, 48, 1)) # random noise\n # with tf.GradientTape() as tape:\n # y_pred = emotion_classifier(input_img_data)\n # target = K.mean(c[:, :, :, filter_idx])\n # grads = normalize(tape.gradient(target, input_img)[0])\n # iterate = K.function([input_img,\n # K.learning_phase()],\n # [target, grads])\n #\n # ###\n # \"You need to implement it.\"\n # print('==={}==='.format(filter_idx))\n # filter_imgs.append(grad_ascent(num_step, input_img_data, iterate))\n # ###\n # print('Finish gradient')\n #\n # for it in range(NUM_STEPS//RECORD_FREQ):\n # print('In the #{}'.format(it))\n # fig = plt.figure(figsize=(14, 8))\n # for i in range(nb_filter):\n # ax = fig.add_subplot(nb_filter/8, 8, i+1)\n # raw_img = filter_imgs[i][it][0].squeeze()\n # ax.imshow(deprocess_image(raw_img), cmap='Blues')\n # plt.xticks(np.array([]))\n # plt.yticks(np.array([]))\n # plt.xlabel('{:.3f}'.format(filter_imgs[i][it][1]))\n # plt.tight_layout()\n # # fig.suptitle('Filters of layer {} (# Ascent Epoch {} )'.format(name_ls[cnt], it*RECORD_FREQ))\n # img_path = os.path.join(filter_dir, '{}-{}'.format(\n # store_path,\n # emotion_classifier.layers[cnt].name))\n # if not os.path.exists(img_path):\n # os.mkdir(img_path)\n # fig.savefig(os.path.join(img_path,'e{}'.format(it*RECORD_FREQ)))\n\nmain()","sub_path":"hw3/feature_map_1.py","file_name":"feature_map_1.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"572016460","text":"import numpy as np\n\nsize = int(input(\"Enter Size: \"))\nmatrix = np.zeros((size, size))\npairs = list(map(str, input(\"Enter pairs: \").lstrip(\n \"[\").rstrip(\"]\").split(\", \")))\nfor i in range(0, len(pairs), 2):\n matrix[int(pairs[i].lstrip(\"[\"))][int(pairs[i + 1].rstrip(\"]\"))] = 1\nindegree = np.zeros((size, ))\n\n\ndef topologicalSort():\n order = list()\n indegree = np.zeros((size, ))\n for i in range(size):\n indegree[i] = np.sum(matrix[:, i])\n\n for i in range(size):\n vertex = -1\n\n for k in range(size):\n if indegree[k] == 0:\n order.append(k)\n indegree[k] = -1\n vertex = k\n break\n if vertex == -1:\n return False\n\n for j in range(size):\n if matrix[vertex][j] == 1:\n indegree[j] -= 1\n return order\n\n\nprint(topologicalSort())\n","sub_path":"5th Semester/ADA/Lab Internals/TopologicalSort.py","file_name":"TopologicalSort.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"137803134","text":"#!/usr/bin/env python\n\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QDialog)\nfrom PyQt5.QtGui import QRegExpValidator\nfrom PyQt5.QtCore import QRegExp\nimport numpy as np\nfrom ui import (main, errorDialogForEmptyInputs,\n errorDialogOnCalculating, successDialog)\nfrom os import (getcwd, mkdir, path)\n\n\nclass SuccessDialog(successDialog.Ui_Dialog, QDialog):\n '''Окно, подтверждающее успех процедуры'''\n\n def __init__(self):\n QDialog.__init__(self)\n self.setupUi(self)\n\n\nclass ErrorDialogForEmptyInputs(errorDialogForEmptyInputs.Ui_Dialog, QDialog):\n '''Окно с ошибкой при пустых инпутах'''\n\n def __init__(self):\n QDialog.__init__(self)\n self.setupUi(self)\n\n\nclass ErrorDialogOnCalculating(errorDialogOnCalculating.Ui_Dialog, QDialog):\n '''Окно с ошибкой при расчете'''\n\n def __init__(self):\n QDialog.__init__(self)\n self.setupUi(self)\n\n\nclass MainApp(main.Ui_MainWindow, QMainWindow):\n '''Главное окно приложения'''\n\n def __init__(self):\n super(MainApp, self).__init__()\n self.setupUi(self)\n\n # Создаем регулярное выражение и устанавливаем валидатор для полей ввода\n regexp_query = QRegExp('[^0|\\D]\\d*$')\n input_validator = QRegExpValidator(regexp_query)\n input_validator.setRegExp(regexp_query)\n\n self.rows_A.setValidator(input_validator)\n self.cols_A.setValidator(input_validator)\n self.rows_B.setValidator(input_validator)\n self.cols_B.setValidator(input_validator)\n\n self.generate_and_calculate.clicked.connect(\n self.calculate_product_of_matrices)\n\n # Действия по нажатию кнопки \"Сгенерировать и рассчитать\"\n def calculate_product_of_matrices(self):\n # Заполнены ли поля для ввода\n is_input_filled_in = self.checking_filling_in_of_the_input()\n\n if is_input_filled_in:\n rows_A = int(self.rows_A.text())\n cols_A = int(self.cols_A.text())\n rows_B = int(self.rows_B.text())\n cols_B = int(self.cols_B.text())\n\n # Проверка на согласованность матриц\n if cols_A != rows_B:\n error_dialog_on_calculating = ErrorDialogOnCalculating()\n error_dialog_on_calculating.show()\n error_dialog_on_calculating.exec_()\n else:\n # Заполняем матрицы случайными целыми числами от 0 до 100\n first_matrix_A = np.random.randint(0, 100, (rows_A, cols_A))\n second_matrix_B = np.random.randint(0, 100, (rows_B, cols_B))\n result_matrix_C = np.dot(first_matrix_A, second_matrix_B)\n\n MainApp.__generate_csv_files(\n first_matrix_A, second_matrix_B, result_matrix_C)\n\n success_dialog = SuccessDialog()\n success_dialog.show()\n success_dialog.exec_()\n else:\n error_dialog_for_empty_inputs = ErrorDialogForEmptyInputs()\n error_dialog_for_empty_inputs.show()\n error_dialog_for_empty_inputs.exec_()\n\n # Проверка на заполнение полей ввода\n def checking_filling_in_of_the_input(self):\n if not (self.rows_A.text()) or \\\n not (self.cols_A.text()) or \\\n not (self.rows_B.text()) or \\\n not (self.cols_B.text()):\n return False\n return True\n\n @staticmethod\n # Генерируем .csv файлы для каждой матрицы\n def __generate_csv_files(first_matrix, second_matrix, result_matrix):\n current_path = getcwd()\n folder_for_csv_files = path.join(current_path, 'csv')\n if not path.exists(folder_for_csv_files):\n mkdir(folder_for_csv_files)\n\n np.savetxt(\n path.join(folder_for_csv_files, 'first_matrix_A.csv'),\n first_matrix,\n delimiter=';',\n fmt='%d'\n )\n\n np.savetxt(\n path.join(folder_for_csv_files, 'second_matrix_B.csv'),\n second_matrix,\n delimiter=';',\n fmt='%d'\n )\n\n np.savetxt(\n path.join(folder_for_csv_files, 'result_matrix_C.csv'),\n result_matrix,\n delimiter=';',\n fmt='%d'\n )\n\n\nif __name__ == '__main__':\n app = QApplication([])\n main_app = MainApp()\n main_app.show()\n exit(app.exec_())\n","sub_path":"lab_0/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112663290","text":"config = {\n \"access\": \"admin\",\n \"help\": \".twitterlist || .twitterlist || Lists twitter accounts that can be used for Nyaa descriptions\"\n}\n\ndef command(guid, manager, irc, channel, user):\n #irc.msg(channel, u\"\\u0002\\u000312OH HAI DER: I'm thinking of removing this command in v6. If you'd like for it to stick around, feel free to PM me or chat about it in #servrhe. Thanks for the feedback!\")\n twitters = yield manager.master.modules[\"config\"].get(\"nyaa\", \"twitter\", {\"jdp\": \"johnnydickpants\"})\n twitters = sorted(twitters.items())\n\n while twitters:\n o, twitters = twitters[:5], twitters[5:]\n irc.notice(user, u\", \".join([u\"{} -> @{}\".format(k, v) for k, v in o]))\n","sub_path":"commands/twitterlist.py","file_name":"twitterlist.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"426274580","text":"class Module:\n\n \"\"\"\n :type filename str\n :type base int\n :type size int\n \"\"\"\n def __init__(self, filename, address, size, symbols_resolved):\n self.filename = filename\n self.base = address\n self.size = size\n self.symbols = symbols_resolved\n\n def find_symbol(self, name):\n if name in self.symbols:\n return self.symbols[name]\n\n return None\n","sub_path":"androidemu/internal/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410496417","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nfrom helpers import news_db\n\n\ndef find_date(string):\n return re.search('\\d{2}\\.\\d{2}\\.\\d{4}', string)\n\n\ndef parse():\n url = 'https://pythondigest.ru/feed/'\n data = {\n 'section': 6, # Section \"Articles\"\n 'page': 1\n }\n request = requests.get(url, data)\n page = BeautifulSoup(request.text, \"lxml\")\n articles = page.select('.news-list .item-container')\n for article in articles:\n date_row = article.find('small')\n title_tag = article.find('h4').find('a')\n description_tag = article.find('p', text=True)\n data = {\n 'date': find_date(date_row.text).group(),\n 'link': title_tag['href'],\n 'title': title_tag.text\n }\n if description_tag is not None:\n data['description'] = description_tag.text\n\n news_db.add_news(data)\n","sub_path":"parsers/pythondigest_parser.py","file_name":"pythondigest_parser.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"597422267","text":"import os\nimport glob\n\nimport logging\nfrom argparse import ArgumentParser\n\nimport json\nimport ijson\nimport csv\n\nimport pandas as pd\nimport random\n\nlogging.basicConfig()\nlogger = logging.getLogger('CLEANING APP')\nlogger.setLevel(logging.INFO)\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument('-i', '--path_to_input_folder', required=True, type=str,\n help='Path to json file from WireShark')\n parser.add_argument('-o', '--path_to_output_folder', required=False, default=\"\", type=str,\n help='Path to updated json file from WireShark')\n return parser.parse_args()\n\n\ndef extract_data(json_paths: list):\n processed_data = [[\n \"name\",\n \"country\",\n \"hours\",\n \"minutes\",\n \"weekday\",\n \"ip.src\",\n \"ip.dst\",\n \"ip.src_host\",\n \"ip.dst_host\",\n \"tcp.srcport\",\n \"tcp.dstport\"\n ]]\n for json_path in json_paths:\n logger.info(\"Processing of {}\".format(json_path))\n name = os.path.split(json_path)[1].split('.')[0]\n with open(json_path, 'r') as f:\n objects = ijson.items(f, '')\n\n for column in objects:\n for item in column:\n time = item[\"time\"].split()[3].split(':')\n country = item[\"time\"].split()[4]\n pass\n # updated_item = item\n # updated_item.update({\"name\": name})\n updated_item = [\n name,\n country,\n time[0],\n time[1],\n # item[\"time\"],\n item[\"weekday\"],\n item[\"ip.src\"],\n item[\"ip.dst\"],\n item[\"ip.src_host\"],\n item[\"ip.dst_host\"],\n item[\"tcp.srcport\"],\n item[\"tcp.dstport\"]\n ]\n processed_data.append(updated_item)\n logger.info(\"Processing of {} has finished\".format(json_path))\n return processed_data\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n json_files = list()\n if os.path.isdir(args.path_to_input_folder):\n logger.info(\"Input folder is {}\".format(args.path_to_input_folder))\n json_files = glob.glob(os.path.join(args.path_to_input_folder, \"*.json\"))\n else:\n raise Exception(\"Incorrect path to the input folder!\")\n\n data = extract_data(json_files)\n\n out_dir = os.path.dirname(args.path_to_input_folder) if args.path_to_output_folder == \"\" else args.path_to_output_folder\n out_filename = os.path.join(out_dir, \"out_validation.csv\")\n if not os.path.exists(out_dir):\n os.mkdir(out_dir)\n with open(out_filename, 'w') as out_file:\n logger.info(\"FILE {} IS SAVED\".format(out_filename))\n with open(out_filename, 'w', newline='') as myfile:\n wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)\n wr.writerows(data)\n # json.dump(data, out_file)\n\n logger.info(\"APPLICATION IS SUCCESSFUL FINISHED\")","sub_path":"concat_json.py","file_name":"concat_json.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"22873339","text":"# Import packages\r\n# To Run python test_model.py \"C:\\Users\\HP PC\\Documents\\Tensorflow\\workspace\\training_demo\\11.jpg\" --textual --with_image\r\nimport tensorflow as tf\r\nimport sys\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nimport glob\r\nimport argparse\r\n\r\n# Import utilites\r\nfrom utils import label_map_util\r\nfrom utils import visualization_utils as vis_util\r\n\r\n# Name of the directory containing the object detection module we're using\r\nMODEL_NAME = 'trained-inference-graphs_[[fstr_rcnn]]'\r\n\r\n# Grab path to current working directory\r\nCWD_PATH = os.getcwd()\r\n\r\n# Path to frozen detection graph .pb file, which contains the model that is used\r\n# for object detection.\r\nPATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')\r\n\r\n# Path to label map file\r\nPATH_TO_LABELS = os.path.join(CWD_PATH,'annotations','labelmap.pbtxt')\r\n\r\n# Path to image\r\n#PATH_TO_IMAGE = args.image_path\r\n\r\n# Number of classes the object detector can identify\r\nNUM_CLASSES = 2\r\n\r\n# Load the label map.\r\n# Label maps map indices to category names, so that when our convolution\r\n# network predicts `5`, we know that this corresponds to `king`.\r\n# Here we use internal utility functions, but anything that returns a\r\n# dictionary mapping integers to appropriate string labels would be fine\r\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\r\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\r\ncategory_index = label_map_util.create_category_index(categories)\r\n\r\n# Load the Tensorflow model into memory.\r\ndetection_graph = tf.Graph()\r\nwith detection_graph.as_default():\r\n od_graph_def = tf.GraphDef()\r\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\r\n serialized_graph = fid.read()\r\n od_graph_def.ParseFromString(serialized_graph)\r\n tf.import_graph_def(od_graph_def, name='')\r\n\r\n sess = tf.Session(graph=detection_graph)\r\n\r\n# Define input and output tensors (i.e. data) for the object detection classifier\r\n\r\n# Input tensor is the image\r\nimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\r\n\r\n# Output tensors are the detection boxes, scores, and classes\r\n# Each box represents a part of the image where a particular object was detected\r\ndetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\r\n\r\n# Each score represents level of confidence for each of the objects.\r\n# The score is shown on the result image, together with the class label.\r\ndetection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\r\ndetection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\r\n\r\n# Number of objects detected\r\nnum_detections = detection_graph.get_tensor_by_name('num_detections:0')\r\n\r\n# Load image using OpenCV and\r\n# expand image dimensions to have shape: [1, None, None, 3]\r\n# i.e. a single-column array, where each item in the column has the pixel RGB value\r\nfor imno in range(1,96):\r\n\tif(imno==18):\r\n\t\tcontinue\r\n\timno_pic = str(\"C:\\\\Users\\\\HP PC\\\\Documents\\\\Tensorflow\\\\workspace\\\\training_demo\\\\test\\\\g (\"+str(imno)+\").jpg\")\r\n\timage = cv2.imread(imno_pic)\r\n\timage_expanded = np.expand_dims(image, axis=0)\r\n\r\n\t# Perform the actual detection by running the model with the image as input\r\n\t(boxes, scores, classes, num) = sess.run(\r\n\t\t[detection_boxes, detection_scores, detection_classes, num_detections],\r\n\t\tfeed_dict={image_tensor: image_expanded})\r\n\r\n\tflg_psr = int(0)\r\n\tfor i in range(scores.shape[1]):\r\n\t\tif scores[0,i]>0.5:\r\n\t\t\tif(str(category_index.get(classes[0,i])['name']) == \"gun\"):\r\n\t\t\t\tprint(\"0, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\t\t\telif(str(category_index.get(classes[0,i])['name']) == \"knife\"):\r\n\t\t\t\tprint(\"1, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\tif(flg_psr==0):\r\n\t\tprint(\"2, \",end='')\r\n\t\t\r\nfor imno in range(1,90):\r\n\timno_pic = str(\"C:\\\\Users\\\\HP PC\\\\Documents\\\\Tensorflow\\\\workspace\\\\training_demo\\\\test\\\\k (\"+str(imno)+\").jpg\")\r\n\timage = cv2.imread(imno_pic)\r\n\timage_expanded = np.expand_dims(image, axis=0)\r\n\r\n\t# Perform the actual detection by running the model with the image as input\r\n\t(boxes, scores, classes, num) = sess.run(\r\n\t\t[detection_boxes, detection_scores, detection_classes, num_detections],\r\n\t\tfeed_dict={image_tensor: image_expanded})\r\n\r\n\tflg_psr = int(0)\r\n\tfor i in range(scores.shape[1]):\r\n\t\tif scores[0,i]>0.5:\r\n\t\t\tif(str(category_index.get(classes[0,i])['name']) == \"gun\"):\r\n\t\t\t\tprint(\"0, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\t\t\telif(str(category_index.get(classes[0,i])['name']) == \"knife\"):\r\n\t\t\t\tprint(\"1, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\tif(flg_psr==0):\r\n\t\tprint(\"2, \",end='')\r\n\t\t\r\nfor imno in range(1,92):\r\n\timno_pic = str(\"C:\\\\Users\\\\HP PC\\\\Documents\\\\Tensorflow\\\\workspace\\\\training_demo\\\\test\\\\o (\"+str(imno)+\").jpg\")\r\n\timage = cv2.imread(imno_pic)\r\n\timage_expanded = np.expand_dims(image, axis=0)\r\n\r\n\t# Perform the actual detection by running the model with the image as input\r\n\t(boxes, scores, classes, num) = sess.run(\r\n\t\t[detection_boxes, detection_scores, detection_classes, num_detections],\r\n\t\tfeed_dict={image_tensor: image_expanded})\r\n\r\n\tflg_psr = int(0)\r\n\tfor i in range(scores.shape[1]):\r\n\t\tif scores[0,i]>0.5:\r\n\t\t\tif(str(category_index.get(classes[0,i])['name']) == \"gun\"):\r\n\t\t\t\tprint(\"0, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\t\t\telif(str(category_index.get(classes[0,i])['name']) == \"knife\"):\r\n\t\t\t\tprint(\"1, \",end='')\r\n\t\t\t\tflg_psr = 1\r\n\t\t\t\tbreak\r\n\tif(flg_psr==0):\r\n\t\tprint(\"2, \",end='')\r\n\r\n# Clean up\r\ncv2.destroyAllWindows()","sub_path":"test_accuracy_fstr.py","file_name":"test_accuracy_fstr.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"427243172","text":"import random\nimport json\nfrom cyaron import Graph\n\n\nAVAILABLE_CHARS = [chr(ord('a')+i) for i in range(26)\n ]\nAVAILABLE_CHARS.extend([chr(ord('A')+i) for i in range(26)])\nAVAILABLE_CHARS.append(' ')\nRANDOM_SEED = 50\nN_SMALL_SAMPLE = 15\nN_LARGE_SAMPLE = 9\nL_SMALL = 100\nL_LARGE = 1000\nL_BOUDERY = 500000\n\n\nclass Solution:\n def exchangeBits(self, num: int) -> int:\n return (((0xaaaaaaaa & num) >> 1) ^ ((0x55555555 & num) << 1)) & (pow(2, 31) - 1)\n\n\nclass StringTestGenerator:\n def __init__(self, out_fun):\n self.output = out_fun\n\n def gen_a_random_string(self, length):\n ret = []\n i = 0\n while i < length:\n times = min(random.randint(0, int(length/10+1)), length - i)\n i += times\n ret.append(AVAILABLE_CHARS[random.randint(\n 0, len(AVAILABLE_CHARS) - 1)]*times)\n self.output(''.join(ret))\n\n # generate a string that not suitable to compress\n def gen_a_unsutiable_string(self, length):\n ret = []\n i = 0\n while i < length:\n times = min(max(1, random.randint(0, 3)), length - i)\n i += times\n ret.append(AVAILABLE_CHARS[random.randint(\n 0, len(AVAILABLE_CHARS) - 1)]*times)\n self.output(''.join(ret))\n\n # def gen_correct_string(self, length):\n # ret = []\n # for _ in range(length):\n # ret.append(AVAILABLE_CHARS[random.randint(\n # 0, len(AVAILABLE_CHARS) - 1)])\n # rn = random.randint(0, len(ret) - 1)\n # ret2 = ret[rn:] + ret[:rn]\n # self.output(''.join(ret), ''.join(ret2))\n\n def gen_series_string(self, nsamp, large_L):\n for _ in range(int(nsamp/2)):\n l = random.randint(1, large_L)\n self.gen_a_random_string(l)\n self.gen_a_unsutiable_string(l)\n\n\nclass ClosedNumberTestcaseGenerator():\n def __init__(self, output):\n self.output = output\n\n def gen_bad_cases(self, length):\n num = random.randint(0, pow(2, 30) - 1)\n self.output(num)\n\n def gen_random_cases(self, length):\n num = random.randint(0, pow(2, 30) - 1)\n self.output(num)\n\n def gen_series_cases(self, nsamp, large_L):\n for _ in range(0, int(nsamp), 2):\n l = random.randint(1, large_L)\n self.gen_random_cases(l)\n self.gen_bad_cases(l)\n\n\nclass TestCaseGenerator:\n\n def __init__(self, file_out='input_file', case_num=20):\n random.seed(RANDOM_SEED)\n self.fout = open(file_out, 'w')\n self.listGen = ClosedNumberTestcaseGenerator(self.output)\n\n def output(self, *params):\n for para in params:\n if type(para) == str:\n self.fout.write('\\\"%s\\\"' % str(para))\n else:\n json.dump(para, self.fout)\n self.fout.write('\\n')\n # self.gen_correct_string(l)\n\n def gen_special_case(self):\n self.output(3)\n self.output(1)\n\n def gen_small_cases(self):\n # self.gen_series_string(N_SMALL_SAMPLE, L_SMALL)\n self.listGen.gen_series_cases(N_SMALL_SAMPLE, L_SMALL)\n pass\n\n def gen_large_cases(self):\n # self.gen_series_string(N_LARGE_SAMPLE, L_LARGE)\n self.listGen.gen_series_cases(N_LARGE_SAMPLE, L_LARGE)\n pass\n\n def gen_boundary_case(self):\n # self.gen_a_random_string(L_BOUDERY)\n # self.gen_a_unsutiable_compress_string(L_BOUDERY)\n self.listGen.gen_random_cases(L_BOUDERY)\n self.listGen.gen_bad_cases(L_BOUDERY)\n pass\n\n def gen_all_cases(self):\n self.gen_special_case()\n self.gen_small_cases()\n self.gen_large_cases()\n self.gen_boundary_case()\n self.fout.close()\n\n\ndef get_res(file_in, file_out):\n lines = []\n sol = Solution()\n with open(file_in, \"r\") as fin:\n lines = fin.readlines()\n print(lines[:4])\n with open(file_out, \"w\") as fout:\n for i in range(0, len(lines), 1):\n num = int(lines[i])\n json.dump(sol.exchangeBits(num), fout)\n fout.write('\\n')\n\n\nif __name__ == \"__main__\":\n gen = TestCaseGenerator()\n gen.gen_all_cases()\n get_res('input_file', 'output_file')\n","sub_path":"test_cast/2019-11-13/Exchange/test_case_generator.py","file_name":"test_case_generator.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"425080031","text":"import random\nfrom openpyxl import load_workbook\nimport os.path\n\n#pego o nome do arquivo\nx = input('informe o nome do arquivo do sorteio\\n')\n\n#concateno com o a extensao\nx = x + '.xlsx'\n\n#checo se arquivo existe\n\nif os.path.isfile(x):\n\n\t# abrindo o Workbook test.xlsx\n\twb = load_workbook(x) \n\n\t#vejo o nome das folhas do excel\n\n\tfolhas = wb.get_sheet_names()\n\n\t#carrego o conteudo da folha referente\n\tws = wb[folhas[0]]\n\n\t#Crio lista de numeros e lista de nomes\n\n\tnumeros = []\n\n\tnomes = []\n\n\tcount = 0\n\n\t#Com esse for consigo resgatar as linhas do arquivo\n\tfor line in ws:\n\n\t\t#O count é utilizado para saltar a primeira linha do arquivo no qual a mesma contem o titulo Nome e Numero\n\n\t\tif count != 0:\n\n\t\t\t#Adciono o conteudo de cada linha na sua respectiva lista\n\n\t\t\tnumeros.append(line[0].value)\n\t\t\tnomes.append(line[1].value)\n\n\t\telse:\n\t\t\tcount += 1\n\n\t#Logica para sorteio\n\tfeed = False\n\tcount = 0\n\n\twhile True:\n\n\t\t#Sorteio um numero que parte do numero 1 e vai ate o numero maior da lista de numeros\n\n\t\tsort = random.randint(1,max(numeros))\n\n\t\tfor k in numeros:\n\t\t\t#Testo se o numero sorteado bate com algum numero na lista de numeros\n\t\t\tif sort == k:\n\n\t\t\t\tfeed = True\n\t\t\t\tbreak\n\t\t\t#conto para saber a posição do numero para assim, posteriormente printar o nome referente ao numero que esta na outra lista\n\t\t\tcount += 1\n\n\t\t#Se o feedback for positivo quer dizer que o numero sorteado bateu com algum numero que esta dentro da lista, sendo assim saio do looping infinito\n\n\t\tif feed == True:\n\t\t\tbreak\n\n\t\t#Caso nao tenha encontrado eu zero o contador por que a posição ainda nao foi validada devido nao ter coincidido o numero sorteado com algum numero na lista\n\n\t\telse:\n\t\t\tcount = 0\n\n\t#Printo o numero sorteado e o nome correspondente\n\n\tprint('Numero sorteado: %s' %numeros[count])\n\n\tprint('Pessoa sorteada: %s' %nomes[count])\n\n\n\n\nelse:\n\tprint('nao existe arquivo')\n\n\n","sub_path":"sorteio.py","file_name":"sorteio.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469227184","text":"#!/usr/bin/python\n\"\"\"\nSuppose a sorted array is rotated at some pivot unknown to you beforehand.\n(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\nFind the minimum element.\nYou may assume no duplicate exists in the array.\n\"\"\"\nclass Solution:\n # @param num, a list of integer\n # @return an integer\n def findMin(self, num):\n # Array has only one element\n if len(num) == 1:\n return num[0]\n else:\n left = 0\n right = len(num) - 1\n # array is not rotated\n if num[left] < num[right]:\n return num[left]\n # array is rotated\n else:\n # use binary search to find the minimum\n while (num[left] > num[right]):\n mid = (left + right)/2\n if num[mid] > num[right]:\n left = mid + 1\n else:\n right = mid\n return num[left]\n\nsol = Solution()\nnum = [4, 5 , 6, 7, 0, 1, 2]\nans = sol.findMin(num)","sub_path":"miscellaneous/findMin.py","file_name":"findMin.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"529961239","text":"import numpy as np\nimport pytest\n\nfrom smcpy.smc.propagator import Propagator\n\nassert_array_equal = np.testing.assert_array_equal\n\n\ndef model(x):\n return np.c_[2 * x[:, 0], x[:, 0]]\n\n\n@pytest.fixture\ndef particles(mocker):\n particles = mocker.Mock()\n particles.params = np.ones([5, 1]) * 2\n particles.log_likes = np.ones([5, 1]) * 3\n particles.log_weights = np.ones([5, 1]) * 4\n return particles\n\n\n@pytest.mark.parametrize('output_names', [None, ('y1', 'y2')])\ndef test_propagator(particles, output_names, mocker):\n\n mockParticles = mocker.Mock()\n mocker.patch('smcpy.smc.propagator.Particles', new=mockParticles)\n\n p = Propagator()\n _ = p.propagate(model, particles, output_names=output_names)\n\n expected_params = {'y0': particles.params.flatten() * 2,\n 'y1': particles.params.flatten()}\n\n if output_names is None:\n output_names = ('y0', 'y1')\n\n assert_array_equal(mockParticles.call_args[0][0][output_names[0]],\n expected_params['y0'])\n assert_array_equal(mockParticles.call_args[0][0][output_names[1]],\n expected_params['y1'])\n assert_array_equal(mockParticles.call_args[0][1], particles.log_likes)\n assert_array_equal(mockParticles.call_args[0][2], particles.log_weights)\n\n\ndef test_propagator_bad_output_names(particles):\n p = Propagator()\n with pytest.raises(ValueError):\n _ = p.propagate(model, particles, output_names=['only one'])\n\n","sub_path":"tests/unit/test_propagator.py","file_name":"test_propagator.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"498013774","text":"\nimport numpy as np\nimport random\nfrom dataclasses import dataclass\n\nrandom.seed(0)\n\n\n@dataclass\nclass Location:\n _x: float\n _y: float\n\n def __init__(self, *args):\n if len(args) != 2:\n raise ValueError('Location init takes two parameters: x, y')\n self._x = args[0]\n self._y = args[1]\n\n def __add__(self, other):\n # return Location(self._x + other.x, self._y + other.y)\n return Location(self._x + other.x, self._y + other.y)\n\n def __mul__(self, other):\n return Location(self._x * other, self._y * other)\n\n def move(self, dx, dy):\n return Location(self._x + dx, self._y + dy)\n\n def dot(self, other):\n return self.x * other.x + self.y * other.y\n\n @property\n def x(self):\n return self._x\n\n @property\n def y(self):\n return self._y\n\n def dist_squared(self, other_loc):\n return (self._x - other_loc.x)**2 + (self._y - other_loc.y)**2\n\n\ndef simple_test_location():\n loc = Location(1, 2)\n loc = loc.move(1, 1)\n print(loc)\n loc1 = Location(1, 1)\n loc2 = Location(2, 2)\n print(loc1 + loc2)\n loc1 += loc2\n print(loc1)\n\n\n@dataclass\nclass Field:\n _drunks: dict\n\n def add_drunk(self, drunk, loc):\n if drunk in self._drunks:\n raise ValueError('The drunk [{}] is already in the field', drunk)\n self._drunks[drunk] = loc\n\n def get_location(self, drunk):\n if drunk not in self._drunks:\n raise ValueError('Drunk [{}] not in field', drunk)\n return self._drunks[drunk]\n\n def move(self, drunk):\n if drunk not in self._drunks:\n raise ValueError('Drunk [{}] not in field', drunk)\n self._drunks[drunk.name] = drunk.step()\n\n\n@dataclass\nclass Drunk:\n _name: str\n _max_step: float\n _n_trial: int\n\n def __init__(self, name, max_step=1.0, n_trial=100):\n self._name = name\n self._max_step = max_step\n self._n_trial = n_trial\n\n @property\n def name(self):\n return self._name\n\n @property\n def max_step(self):\n return self._max_step\n\n def _get_random_loc(self):\n loc = Location(random.uniform(0.0, self._max_step),\n random.uniform(0.0, self._max_step))\n return loc\n\n def step(self):\n n_trial = 0\n loc = self._get_random_loc()\n while loc.dist_squared(Location(0., 0.)) > self._max_step**2 \\\n and n_trial < self._n_trial:\n loc = self._get_random_loc()\n n_trial += 1\n return loc\n\n\n@dataclass\nclass OrientedDrunk(Drunk):\n _favorite_direction: Location\n _favorite_direction_name: str\n\n def __init__(self, name, favorite_direction='North'):\n super(OrientedDrunk, self).__init__(name=name)\n self._favorite_direction_name = favorite_direction\n self._set_favorite_direction()\n\n def _set_favorite_direction(self):\n if self._favorite_direction_name == 'North':\n self._favorite_direction = Location(.0, 1.)\n elif self._favorite_direction_name == 'South':\n self._favorite_direction = Location(.0, -1.)\n elif self._favorite_direction_name == 'East':\n self._favorite_direction = Location(1., 0.)\n elif self._favorite_direction_name == 'West':\n self._favorite_direction = Location(-1., 0.)\n else:\n raise ValueError('favorite_direction should be in \"North\", '\n '\"South\", \"East\" or \"West\" [value is {}]'.format(\n self._favorite_direction_name))\n\n @property\n def favorite_direction(self):\n return self._favorite_direction\n\n def step(self):\n # Usual drunk step\n loc = super(OrientedDrunk, self).step()\n max_try = 10\n ntry = 0\n while loc.dot(self._favorite_direction) <= 0 and ntry != max_try:\n loc = super(OrientedDrunk, self).step()\n ntry += 1\n return loc\n\n\n@dataclass\nclass SquareDrunk(Drunk):\n def __init__(self, name):\n super(SquareDrunk, self).__init__(name=name)\n\n @staticmethod\n def get_possible_moves():\n return [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)]\n\n @staticmethod\n def get_random_loc():\n return Location(*random.choice(SquareDrunk.get_possible_moves()))\n\n def _get_random_loc(self):\n return self.get_random_loc()\n\n\n@dataclass\nclass SquareOrientedDrunk(OrientedDrunk):\n def __init__(self, *args, **kwargs):\n super(SquareOrientedDrunk, self).__init__(*args, **kwargs)\n\n def step(self):\n loc = SquareDrunk.get_random_loc()\n max_try = 10\n ntry = 0\n while loc.dot(self._favorite_direction) <= 0 and ntry != max_try:\n loc = SquareDrunk.get_random_loc()\n ntry += 1\n return loc\n\n\n@dataclass\nclass Simulation:\n _field : Field\n _n_steps: int\n\n def walk(self, drunk):\n start = self._field.get_location(drunk)\n for step in range(self._n_steps):\n self._field.move(drunk)\n pos = self._field.get_location(drunk)\n return np.sqrt(pos.dist_squared(start))\n\n\ndef simple_test_drunks():\n normal_drunk = Drunk('jacky')\n print(normal_drunk)\n print(normal_drunk.step())\n east_drunk = OrientedDrunk(name='jacky', favorite_direction='East')\n print(east_drunk)\n print('normal drunk step : ', normal_drunk.step())\n print('east drunk step : ', east_drunk.step())\n\n square_drunk = SquareDrunk(name='Jack')\n print('square normal drunk: ', square_drunk.step())\n\n square_oriented_drunk = SquareOrientedDrunk(name='Jim',\n favorite_direction='South')\n print('square oriented drunk: ', square_oriented_drunk.step())\n\n\ndef main():\n simple_test_location()\n simple_test_drunks()\n print('\\n\\n')\n\n drunk = SquareDrunk('Johnny')\n field = Field({drunk.name: Location(0.0, 0.0)})\n sim = Simulation(field, 1000)\n print('distance from start for ', drunk.name, ' : ', sim.walk(drunk))\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('Interrupted by user')\n","sub_path":"ai/datasci/mit/random_walk.py","file_name":"random_walk.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383363609","text":"#!/usr/bin/python2\n\"\"\"Starts the Tweeteor server.\"\"\"\nimport logging\nimport os\nfrom ConfigParser import SafeConfigParser\n\nfrom controller import Controller\nfrom searcher import Searcher\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n filename='log',\n level=logging.DEBUG,\n format=\"[%(asctime)s : %(levelname)s] [%(threadName)s] %(message)s\")\n config = SafeConfigParser()\n config.read('config')\n # An exception is thrown if you acces a non-existant directory,\n # so we make sure they exist here\n image_cache = os.path.join(\"cache\", \"images\")\n tweet_cache = os.path.join(\"cache\", \"tweets\")\n required_dirs = [image_cache, tweet_cache]\n for directory in required_dirs:\n if not os.path.exists(directory):\n os.makedirs(directory)\n # Using '' as the hostname allows the socket to bind to\n # its correct address, without you needing to know exactly what\n # that address is.\n address = ('', config.getint('connection', 'port'))\n api_key = config.get('auth', 'key')\n api_secret = config.get('auth', 'secret')\n searcher = Searcher(api_key, api_secret, address)\n searcher.start()\n controller = Controller(searcher)\n controller.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"570389537","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 16 18:21:33 2018\r\n\r\n@author: ashwin.monpur\r\n\"\"\"\r\n\r\nimport MySQLdb as my\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import timedelta\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom sqlalchemy import create_engine\r\n\r\nconn = my.connect(host=\"localhost\",passwd=\"pass@123\",db=\"mf\",user=\"root\")\r\ncursor = conn.cursor()\r\nscheme_code=(pd.read_sql_query(\"select distinct Scheme_Code from mf.daily_data_2006\",conn))\r\n\r\nscheme_code_list=scheme_code.values.T.flatten()\r\nscheme_code_list[2]\r\n\r\n\r\nreturn_mf_list=[]\r\n\r\nrisk_mf_list=[]\r\n\r\nfor s in range(1,len(scheme_code_list)): #len(scheme_code_list)):\r\n \r\n print(scheme_code_list[s])\r\n \r\n return_sm_list=[]\r\n risk_sm_list=[]\r\n \r\n query = pd.read_sql_query(\"select * from mf.daily_data_2006 where Scheme_Code=\"+scheme_code_list[s],conn)\r\n \r\n return_sm_list.append(scheme_code_list[s])\r\n return_sm_list.append(str(query['Scheme_Name'][0])) \r\n \r\n risk_sm_list.append(scheme_code_list[s])\r\n risk_sm_list.append(str(query['Scheme_Name'][0]))\r\n \r\n nav_data=pd.to_numeric(query['Net_Asset_Value'])\r\n query['Date']=pd.to_datetime(query['Date'])\r\n nav_data.index=query['Date'] \r\n date_data=query['Date'].max()\r\n #Daily Return\r\n \r\n \r\n# daily=nav_data.asfreq('D','ffill')\r\n# \r\n# ret_d=daily.diff(1)\r\n# \r\n# fdat_d=date_data - timedelta(days=1) \r\n# \r\n# query_d = pd.read_sql_query(\"select Date,Net_Asset_Value from mf.daily_data_2006 where Scheme_Code={0} AND Date >= '{1}'\".format(scheme_code_list[s],fdat_d.strftime('%Y-%m-%d')),conn)\r\n# \r\n# nav_data_d=pd.to_numeric(query_d['Net_Asset_Value'])\r\n# \r\n# ret_d_d=nav_data_d.diff(1)\r\n# ret_d_d_v=ret_d_d.var()\r\n# std_d_d=np.sqrt(ret_d_d_v)\r\n# \r\n# return_sm_list.append(round(ret_d[(len(ret_d)-1)],4))\r\n# return_sm_list.append(fdat_d.strftime('%Y-%m-%d'))\r\n# \r\n# risk_sm_list.append(round(std_d_d,4))\r\n# risk_sm_list.append(fdat_d.strftime('%Y-%m-%d'))\r\n \r\n # Monthly Return\r\n \r\n monthly=nav_data.asfreq('M','ffill')\r\n ret_m=monthly.diff(1)\r\n fdat_m=date_data - timedelta(days=30)\r\n\r\n query_m = pd.read_sql_query(\"select Date,Net_Asset_Value from mf.daily_data_2006 where Scheme_Code={0} AND Date >= '{1}'\".format(scheme_code_list[s],fdat_m.strftime('%Y-%m-%d')),conn)\r\n nav_data_m=pd.to_numeric(query_m['Net_Asset_Value'])\r\n ret_d_m=nav_data_m.diff(1)\r\n ret_d_m_v=ret_d_m.var()\r\n std_d_m=np.sqrt(ret_d_m_v)\r\n \r\n return_sm_list.append(round(ret_m[(len(ret_m)-1)],4))\r\n return_sm_list.append(fdat_m.strftime('%Y-%m-%d'))\r\n \r\n risk_sm_list.append(round(std_d_m,4))\r\n risk_sm_list.append(fdat_m.strftime('%Y-%m-%d'))\r\n \r\n # Quarterly Return\r\n \r\n quarterly=nav_data.asfreq('Q','ffill')\r\n ret_q=quarterly.diff(1)\r\n fdat_q=date_data - relativedelta(months=3)\r\n query_q = pd.read_sql_query(\"select Date,Net_Asset_Value from mf.daily_data_2006 where Scheme_Code={0} AND Date >= '{1}'\".format(scheme_code_list[s],fdat_q.strftime('%Y-%m-%d')),conn)\r\n nav_data_q=pd.to_numeric(query_q['Net_Asset_Value'])\r\n ret_d_q=nav_data_q.diff(1)\r\n ret_d_q_v=ret_d_q.var()\r\n std_d_q=np.sqrt(ret_d_q_v)\r\n \r\n return_sm_list.append(round(ret_q[(len(ret_q)-1)],4))\r\n return_sm_list.append(fdat_q.strftime('%Y-%m-%d'))\r\n \r\n risk_sm_list.append(round(std_d_q,4))\r\n risk_sm_list.append(fdat_q.strftime('%Y-%m-%d'))\r\n \r\n # SemiAnnual Return\r\n \r\n semiannually=nav_data.asfreq('2Q','ffill')\r\n ret_sa=semiannually.diff(1)\r\n fdat_sa=date_data - relativedelta(months=6)\r\n query_sa = pd.read_sql_query(\"select Date,Net_Asset_Value from mf.daily_data_2006 where Scheme_Code={0} AND Date >= '{1}'\".format(scheme_code_list[s],fdat_sa.strftime('%Y-%m-%d')),conn)\r\n nav_data_sa=pd.to_numeric(query_sa['Net_Asset_Value'])\r\n ret_d_sa=nav_data_sa.diff(1)\r\n ret_d_sa_v=ret_d_sa.var()\r\n std_d_sa=np.sqrt(ret_d_sa_v)\r\n \r\n return_sm_list.append(round(ret_sa[(len(ret_sa)-1)],4))\r\n return_sm_list.append(fdat_sa.strftime('%Y-%m-%d'))\r\n \r\n risk_sm_list.append(round(std_d_sa,4))\r\n risk_sm_list.append(fdat_sa.strftime('%Y-%m-%d'))\r\n \r\n # Annual Return\r\n \r\n annually=nav_data.asfreq('A','ffill')\r\n ret_a=annually.diff(1)\r\n fdat_a=date_data - relativedelta(months=12)\r\n query_a = pd.read_sql_query(\"select Date,Net_Asset_Value from mf.daily_data_2006 where Scheme_Code={0} AND Date >= '{1}'\".format(scheme_code_list[s],fdat_a.strftime('%Y-%m-%d')),conn)\r\n nav_data_a=pd.to_numeric(query_a['Net_Asset_Value'])\r\n ret_d_a=nav_data_sa.diff(1)\r\n ret_d_a_v=ret_d_sa.var()\r\n std_d_a=np.sqrt(ret_d_sa_v)\r\n \r\n return_sm_list.append(round(ret_a[(len(ret_a)-1)],4))\r\n return_sm_list.append(fdat_a.strftime('%Y-%m-%d'))\r\n \r\n risk_sm_list.append(round(std_d_a,4))\r\n risk_sm_list.append(fdat_a.strftime('%Y-%m-%d'))\r\n \r\n return_sm_list.append(date_data.strftime('%Y-%m-%d'))\r\n risk_sm_list.append(date_data.strftime('%Y-%m-%d'))\r\n \r\n return_mf_list.append(return_sm_list)\r\n risk_mf_list.append(risk_sm_list)\r\n \r\n \r\n \r\n \r\ndata_return=pd.DataFrame(return_mf_list) \r\ndata_risk=pd.DataFrame(risk_mf_list) \r\ndata_return.columns=['Scheme_Code','Scheme_Name','Return_Monthly','Monthly_Date','Return_Quarterly','Quarterly_Date','Return_SemiAnnual','SemiAnnual_Date','Return_Annual','Annual_Date','Recent_Date'] \r\ndata_risk.columns=['Scheme_Code','Scheme_Name','Risk_Monthly','Monthly_Date','Risk_Quarterly','Quarterly_Date','Risk_SemiAnnual','SemiAnnual_Date','Risk_Annual','Annual_Date','Recent_Date'] \r\n\r\nengine = create_engine('mysql://root:pass@123@localhost:3306/mf', echo = False)\r\ndata_return.to_sql(name = 'test_return', con = engine, if_exists = 'replace', index = True)\r\ndata_risk.to_sql(name = 'test_risk', con = engine, if_exists = 'replace', index = True) \r\n\r\n\r\n#data_return.to_sql(name='test',con=conn,if_exists='replace', index=True,)","sub_path":"Intern Project/calculating Return & Risk/Return & Risk DB insert using pandas.py","file_name":"Return & Risk DB insert using pandas.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"611648155","text":"import pandas as pd\nimport pandas_datareader as pdr\nimport csv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass TickerMng:\n def __init__(self):\n # 그룹별 종목 이름 리스트\n self.offenseNames = []\n self.defenseNames = []\n self.canaryNames = []\n\n # 그룹별 종목 DataFrame 배열\n self.offense_dfs = {}\n self.defense_dfs = {}\n self.canary_dfs = {}\n\n # 집합 그룹\n self.groupsNames = {'offense': self.offenseNames, 'defense': self.defenseNames, 'canary': self.canaryNames}\n self.groups_dfs = {'offense': self.offense_dfs, 'defense': self.defense_dfs, 'canary': self.canary_dfs}\n\n def make_dataframe(self, group_name, ticker_name):\n mon = pd.read_csv('data/M_%s.csv' % ticker_name, sep='\\t')\n mon = mon.set_index('Date', drop=True)\n\n score_df = mon.pct_change(periods=1) * 12 + mon.pct_change(periods=3) * 4 + mon.pct_change(\n periods=6) * 2 + mon.pct_change(periods=12)\n\n score_df.columns = ['Score']\n\n profit_df = mon.pct_change(periods=1)\n profit_df.columns = ['Profit']\n\n mon = pd.concat([mon, score_df['Score']], axis=1)\n mon = pd.concat([mon, profit_df['Profit']], axis=1)\n\n self.groups_dfs[group_name][ticker_name] = mon\n\n def load_type_list(self):\n for key, val in self.groupsNames.items():\n val.clear()\n fd_list = open('data/Z_%s_list.csv' % key, 'r', encoding='utf-8')\n rdlist = csv.reader(fd_list)\n for line in rdlist:\n ticker_name = line[0]\n val.append(ticker_name)\n fd_list.close()\n\n def download_stooq(self):\n for key, val in self.groupsNames.items():\n for ticker_name in val:\n df = pdr.get_data_stooq(ticker_name)\n df.to_csv('data/O_%s.csv' % ticker_name, sep='\\t')\n # mon_df = df['Close'].resample('M').first().to_frame('Close') # first() == 매달 1일기준\n mon_df = df['Close'].resample('M').last().to_frame('Close')\n mon_df.to_csv('data/M_%s.csv' % ticker_name, sep='\\t')\n\n def load_dataframe(self):\n for key, val in self.groupsNames.items():\n for ticker_name in val:\n self.make_dataframe(key, ticker_name)\n\n def is_risky_canary(self, date_idx):\n for key, val in self.canary_dfs.items():\n if val['Score'].iloc[date_idx] <= 0:\n return True\n return False\n\n def select_defense(self, date_idx):\n names = self.sort_dfs(self.defense_dfs, date_idx, 1)\n return {'Date': self.defense_dfs[names[0]].index[date_idx],\n 'Ticker': names[0],\n 'Profit': self.defense_dfs[names[0]]['Profit'].iloc[date_idx + 1]\n }\n\n def select_offense(self, date_idx):\n names = self.sort_dfs(self.offense_dfs, date_idx, 2)\n arr = np.array([\n self.offense_dfs[names[0]]['Profit'].iloc[date_idx + 1],\n self.offense_dfs[names[1]]['Profit'].iloc[date_idx + 1]])\n profit_avg = np.mean(arr)\n\n return {'Date': self.offense_dfs[names[0]].index[date_idx],\n 'Ticker': \"%s,%s\" % (names[0], names[1]),\n 'Profit': profit_avg\n }\n\n @staticmethod\n def sort_dfs(dfs, date_idx, count):\n oneday_df = pd.DataFrame()\n\n for key, val in dfs.items():\n my_data = list(val.iloc[date_idx]) + [key]\n my_col = list(val.iloc[date_idx].index) + ['ticker_name']\n\n tmp = pd.DataFrame(data=[my_data], columns=my_col)\n oneday_df = oneday_df.append(tmp)\n\n oneday_df = oneday_df.set_index('ticker_name', drop=False)\n oneday_df = oneday_df.sort_values(by='Score', ascending=False)\n\n result = []\n for idx in range(0, count):\n result.append(oneday_df.iloc[idx]['ticker_name'])\n\n return result\n\n def show_daa_profit(self):\n\n report_df = pd.DataFrame()\n cumulative_returns = 1.0\n\n for date_idx in range(12, len(self.offense_dfs['SPY.US'].index) - 1):\n if self.is_risky_canary(date_idx):\n result_dic = self.select_defense(date_idx)\n result_dic['Risky'] = 1\n else:\n result_dic = self.select_offense(date_idx)\n result_dic['Risky'] = 0\n\n cumulative_returns = cumulative_returns * (1 + result_dic['Profit'])\n result_dic['CumulativeReturns'] = cumulative_returns\n\n report_df = report_df.append(result_dic, ignore_index=True)\n\n report_df = report_df.set_index('Date', drop=True)\n\n print(report_df[['Profit', 'CumulativeReturns']])\n\n report_df['Profit'].plot(legend=True)\n report_df['CumulativeReturns'].plot(legend=True)\n # report_df[['Profit', 'CumulativeReturns']].plot(subplots=True, sharex=True, legend=True)\n plt.show()\n\n def save_type_list(self):\n for key, val in self.groupsNames.items():\n f = open('data/Z_%s_list.csv' % key, 'w', encoding='utf-8', newline='')\n wr = csv.writer(f)\n for name in val:\n wr.writerow([name])\n f.close()\n","sub_path":"TickerMng.py","file_name":"TickerMng.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"647713550","text":"'''\nImage Segmentation implementation from scratch\n\n\nTheory:\n\n\n'''\n\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms.functional as TF\n\n\nclass DoubleConv(nn.Module):\n\n '''\n\n The function applies two convolutional layers each followed by a\n ReLU activation function\n :param in_channels: number of input channels\n :param out_channels: number of output channels\n :return: a down-conv layer\n\n '''\n\n def __init__(self, in_channels, out_channels):\n super(DoubleConv, self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.conv(x)\n\n\nclass NET(nn.Module):\n def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]):\n super(NET, self).__init__()\n print(\"Feature list is \", features)\n self.ups = nn.ModuleList()\n self.downs = nn.ModuleList()\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n # symmetric contracting path to learn about the features\n for feature in features:\n self.downs.append(DoubleConv(in_channels, feature))\n in_channels = feature\n\n # somewhat symmetric to the contractive path, helps us to understand the precise localization of the object for segmentations tasks\n\n for feature in reversed(features):\n self.ups.append(\n nn.ConvTranspose2d(\n feature*2, feature, kernel_size=2, stride=2,\n )\n )\n self.ups.append(DoubleConv(feature*2, feature))\n print(\"Model Architecture for contractive path is \", self.downs)\n print(\"Model architecture for expanding path is \", self.ups)\n\n self.bottleneck = DoubleConv(features[-1], features[-1]*2)\n self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1)\n\n def forward(self, x):\n skip_connections = []\n\n for down in self.downs:\n x = down(x)\n skip_connections.append(x)\n x = self.pool(x)\n x = self.bottleneck(x)\n skip_connections = skip_connections[::-1]\n for idx in range(0, len(self.ups), 2):\n x = self.ups[idx](x)\n skip_connection = skip_connections[idx//2]\n if x.shape != skip_connection.shape:\n x = TF.resize(x, size=skip_connection.shape[2:]) # do not consider the batch size and the number of channels in the image\n concat_skip = torch.cat((skip_connection, x), dim=1)\n x = self.ups[idx+1](concat_skip)\n return self.final_conv(x)\n\n\n\n\n\n\n\n\n\n# def test():\n# x = torch.randn((3, 1, 160, 160))\n# model = NET(in_channels=1, out_channels=1)\n# preds = model(x)\n# assert preds.shape == x.shape\n# print(\"The predicted shape is \", preds.shape)\n# print(\"The input shape is \", x.shape)\n#\n#\n# if __name__ == \"__main__\":\n# test()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cv_segmentation/u-net_architecture/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"393036175","text":"import responses\nimport unittest\n\nfrom pydux import create_store\n\nfrom openbadges.verifier import verify\nfrom openbadges.verifier.reducers import main_reducer\nfrom openbadges.verifier.state import (filter_active_tasks, INITIAL_STATE, get_node_by_id,\n get_node_by_path,)\n\ntry:\n from .testfiles.test_components import test_components\nexcept (ImportError, SystemError):\n from .testfiles.test_components import test_components\n\n\nclass InitializationTests(unittest.TestCase):\n def test_store_initialization(self):\n def no_op(state, action):\n return state\n store = create_store(no_op, INITIAL_STATE)\n self.assertEqual(store.get_state(), INITIAL_STATE)\n\n\nclass TaskFilterTests(unittest.TestCase):\n def test_active_filter(self):\n tasks = [\n {'name': 'Carl', 'complete': True},\n {'name': 'Tim', 'complete': True},\n {'name': 'Linda', 'complete': False},\n ]\n state = {'tasks': tasks}\n\n active_tasks = filter_active_tasks(state)\n self.assertEqual(len(active_tasks), 1, \"There should only be one active (incomplete) task\")\n self.assertEqual(active_tasks[0]['name'], 'Linda')\n\n mary = {'name': 'Mary', 'complete': False, 'prerequisites': 'Tim'}\n tasks.append(mary)\n active_tasks = filter_active_tasks(state)\n self.assertEqual(len(active_tasks), 2, \"Task whose prereq has been met should be active\")\n\n mary['prerequisites'] = ['Tim', 'Carl']\n active_tasks = filter_active_tasks(state)\n self.assertEqual(len(active_tasks), 2, \"Task whose prereqs has been met should be active\")\n\n mary['prerequisites'] = ['Tim', 'Linda']\n active_tasks = filter_active_tasks(state)\n self.assertEqual(len(active_tasks), 1, \"Task with an incomplete prereq should not be active\")\n\n\nclass FindNodeByPathTests(unittest.TestCase):\n def test_find_node_with_single_length_path(self):\n state = {\n 'graph': [{'id': '_:b0'}]\n }\n with self.assertRaises(IndexError):\n get_node_by_path(state, ['_:b100'])\n\n self.assertEqual(get_node_by_path(state, ['_:b0']), state['graph'][0])\n\n state['graph'].append({'id': '_:b1', 'prop': '_:b0'})\n self.assertEqual(get_node_by_path(state, ['_:b1', 'prop']), state['graph'][0])\n\n state['graph'].append({'id': '_:b2', 'prop': ['http://unknown.external', '_:b1']})\n self.assertEqual(get_node_by_path(state, ['_:b2', 'prop', 1]), state['graph'][1])\n self.assertEqual(get_node_by_path(state, ['_:b2', 'prop', 1, 'prop']), state['graph'][0])\n","sub_path":"tests/test_store.py","file_name":"test_store.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"407208801","text":"# Fitting y = a + bx to given n data points\nimport numpy as np\n\n# Input data with size n\nn = int(input(\"How many data points? \"))\n\n# Creating numpy array x & y to store n data points\nx = np.zeros(n)\ny = np.zeros(n)\n\n# Reading data\nprint(\"Enter data:\")\nfor i in range(n):\n x[i] = float(input(\"x[\"+str(i)+\"]= \"))\n y[i] = float(input(\"y[\"+str(i)+\"]= \"))\n \n# Finding required sum for least square methods\nsumX,sumX2,sumY,sumXY = 0,0,0,0\nfor i in range(n):\n sumX = sumX + x[i]\n sumX2 = sumX2 + x[i]*x[i]\n sumY = sumY + y[i]\n sumXY = sumXY + x[i]*y[i]\n\n# Finding coefficients a and b\nb = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX)\na = (sumY - b*sumX)/n\n\n# Displaying coefficients a, b & equation\nprint(\"\\nCoefficients are:\")\nprint(\"a: \", a)\nprint(\"b: \", b)\nprint(\"And equation is: y = %0.4f + %0.4f x\" %(a,b))\n","sub_path":"Algorithms/Arithmetic/Simple_Linear_Regression.py","file_name":"Simple_Linear_Regression.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"607093672","text":"#*****************************************************************************/\n# @file mlp_gaussian.c \n# @author Majid Nasiri 95340651\n# @version V1.0.0\n# @date 18 April 2017\n# @brief \n#*****************************************************************************/\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport NN\n\nfor i in range(50): print(' ') \n\n#define Macros\nCLASS_NUM=2\nSAMPLE_PER_CLASS=1000\n\nsamples_class0=np.random.multivariate_normal([4, 0],[[2, 0],[0, 2]],SAMPLE_PER_CLASS)\nsamples_class1=np.random.multivariate_normal([0, 4],[[2, 0],[0, 2]],SAMPLE_PER_CLASS)\n\n#plt.figure(1)\n#plt.plot(samples_class0[:, 0], samples_class0[:, 1], 'ro')\n#plt.plot(samples_class1[:, 0], samples_class1[:, 1], 'bo')\n\nX = np.concatenate((samples_class0, samples_class1)).T\nt = np.concatenate((np.zeros([SAMPLE_PER_CLASS,1]), np.ones([SAMPLE_PER_CLASS,1]))).T\n\nN = np.array([2,2,1])\nNS = SAMPLE_PER_CLASS * CLASS_NUM \nmu=0.1\nsample=0\nmaxEpoch=30\n\nerror_array = NN.mlp(X, t, N, NS, mu, maxEpoch)\n\nplt.figure(num = 1, figsize=(8,6))\nplt.plot(error_array.T)\nplt.xlabel('Epoch')\nplt.ylabel('Error Rate')\nplt.grid()\nplt.show()\nplt.savefig('..\\images\\gaussian_2-2-1.jpg')\n\n\n\n\n\n\n","sub_path":"machine_learning/multiLayer_perceptron/MLP_gaussian.py","file_name":"MLP_gaussian.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"397848931","text":"import os, re\n\npyregex = re.compile(r'\\.py$')\n\nos.chdir('..//..//Exercises from books')\n\nprint('The following folders has .py files: ')\n\nfor folder, subfolder, files in os.walk(os.getcwd()):\n if list(filter(pyregex.search, files)):\n print('\\nFolder: ' + str(folder) + ' has .py files: ') \n print('List of .py files: ')\n \n for file in files:\n if pyregex.search(file):\n print('\\t- ' + file)","sub_path":"Other exercises/Automation/check_py_files.py","file_name":"check_py_files.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"208461673","text":"# -*- coding: utf-8 -*-\n\nimport requests\n\ntipoIdentificacion = {\n 'ruc': '04',\n 'cedula': '05',\n 'pasaporte': '06',\n 'venta_consumidor_final': '07',\n 'identificacion_exterior': '08',\n 'placa': '09',\n}\n\nMSG_SCHEMA_INVALID = u\"El sistema generó el XML pero\"\n\" el comprobante electrónico no pasa la validación XSD del SRI.\"\n\nSITE_BASE_TEST = 'https://celcer.sri.gob.ec/'\nSITE_BASE_PROD = 'https://cel.sri.gob.ec/'\nWS_TEST_RECEIV = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl' # noqa\nWS_TEST_AUTH = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl' # noqa\nWS_RECEIV = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl' # noqa\nWS_AUTH = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl' # noqa\n\ndef check_service(env='prueba'):\n flag = False\n if env == 'prueba':\n URL = WS_TEST_RECEIV\n else:\n URL = WS_RECEIV\n\n for i in [1, 2, 3]:\n try:\n res = requests.head(URL, timeout=3)\n flag = True\n except requests.exceptions.RequestException:\n return flag, False\n return flag, res","sub_path":"models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"119074504","text":"# coding=utf-8\nimport atexit\nimport csv\nimport datetime\nimport json\nimport os\nimport threading\nimport time\nfrom datetime import timedelta\n\nimport pandas as pd\nimport pandas_datareader as web\nfrom flask import jsonify, request\nfrom sqlalchemy import desc\n\nfrom src import LOGGER, app\n\nfrom ..entities.entity import Session\nfrom ..entities.strategy_1_filter_config import (Strategy_1_filter_config,\n Strategy_1_filter_configSchema)\nfrom ..utils.manage_request import get_request_data\nfrom ..utils.yahoo_utils import yahoo_value_data_extraction\nfrom .DAOstrategy_1_filter_config import get_all_strategy1filterconfig\nfrom .DAOstrategy_1_impacts_backtesting import save_strategy1impactsbacktesting\nfrom .DAOstrategy_1_monitoring import (save_strategy1monitoring,\n update_strategy1monitoring)\nfrom .DAOvalues import get_all_values\n\n\n@app.route('/api/strategy1backtesting', methods=['POST'])\ndef strategy1_backtesting():\n ''' Back Testing Batch Process '''\n\n LOGGER.debug('**** Getting request data ****')\n json_data = get_request_data(request)\n param_filter_percentage = json_data['filter_percentage']\n param_filter_days = json_data['filter_days']\n\n errors_list = []\n start_time = time.time()\n monitorizacion_json = {\n 'name': 'Strategy1 Backtesting',\n 'start_date': datetime.datetime.now(),\n 'finish_date': None,\n 'time': None,\n 'state': 'IN PROGRESS',\n 'info': None\n }\n\n monitoring_json_response = save_strategy1monitoring(monitorizacion_json)\n monitoring_json_response = get_request_data(monitoring_json_response)\n\n try:\n filter_percentage = param_filter_percentage\n filter_days = param_filter_days\n value_name_list = get_all_values()\n value_name_list = get_request_data(value_name_list)\n rows_overview = []\n rows_db = []\n\n LOGGER.debug('**** BackTesting inicializado ****')\n for value_name in value_name_list:\n value_id = value_name['id']\n value_name = value_name['value']\n try:\n LOGGER.debug('Recogiendo datos de %s...', value_name)\n end_date = datetime.date.today()\n start_date = datetime.date(\n end_date.year-2, end_date.month, end_date.day)\n start_date_with_margin = datetime.date(\n end_date.year-2, end_date.month, end_date.day) - timedelta(days=(filter_days*2))\n try:\n yahoo_value_data_extraction(\n value_name, start_date_with_margin, end_date)\n except Exception as ex:\n errors_list.append(str(ex))\n\n LOGGER.debug(\n 'Exportados los datos correctamente de %s', value_name)\n\n # Pasar los filtros\n LOGGER.debug('**** Comenzando a pasar los filtros ****')\n LOGGER.debug('FILTRO A %f porciento', filter_percentage)\n try:\n calculate_impacts_and_corrections(start_date, \n value_id, value_name, filter_percentage, filter_days, rows_overview, rows_db)\n except Exception as ex:\n errors_list.append(str(ex))\n return jsonify({'response': str(ex)}), 500\n\n LOGGER.debug('**** Filtros realizados ****')\n\n LOGGER.debug('**** BackTesting tratado correctamente ****')\n except Exception as ex:\n errors_list.append(str(ex))\n LOGGER.debug('ERROR: %s', str(ex))\n finally:\n if os.path.isfile('./src/assets/'+str(value_name + '.csv')):\n os.remove('./src/assets/'+str(value_name + '.csv'))\n\n save_impacts_in_db_backtesting(rows_db)\n\n calculate_cumulative_return(rows_overview)\n except Exception as ex:\n errors_list.append(str(ex))\n return jsonify({'response': str(ex)}), 500\n finally:\n monitoring_json_response['finish_date'] = datetime.datetime.now()\n monitoring_json_response['time'] = time.time() - start_time\n if errors_list:\n monitoring_json_response['state'] = 'ERROR'\n monitoring_json_response['info'] = '\\n'.join(errors_list)\n else:\n monitoring_json_response['state'] = 'FINALIZADO'\n monitoring_json_response = update_strategy1monitoring(\n monitoring_json_response)\n monitoring_json_response = get_request_data(monitoring_json_response)\n\n return jsonify(monitoring_json_response), 201\n\n\ndef calculate_impacts_and_corrections(start_date, value_id, value_name, filter_percentage, filter_days, rows_overview, rows_db):\n ''' Process for calcultate impacts and corrections '''\n\n if os.path.isfile('./src/assets/'+str(value_name + '.csv')):\n _csv = pd.read_csv('./src/assets/'+str(value_name + '.csv'))\n _csv.insert(0, 'row_num', range(0,len(_csv)))\n LOGGER.debug(_csv)\n _csv = _csv.loc[_csv['Date'] == start_date.strftime(\"%Y-%m-%d\")]\n row_number = 0\n try:\n row_number = _csv.iloc[0]['row_num']\n LOGGER.debug(\"ROW NUMBER: \" + str(row_number))\n except Exception:\n pass\n os.makedirs('./src/assets/strategy1',exist_ok=True)\n with open('./src/assets/strategy1/' + str(value_name + '.csv'), 'w') as csv_file_w:\n with open('./src/assets/'+str(value_name + '.csv')) as csv_file_r:\n reader_csv = csv.reader(\n csv_file_r, delimiter=',', lineterminator='\\n')\n writer_csv = csv.writer(\n csv_file_w, delimiter=';', lineterminator='\\n')\n\n LOGGER.debug('**** Pasando filtro para %s.csv ****', value_name)\n\n header = next(reader_csv)\n LOGGER.debug(str(header))\n header.append('Rendimiento')\n header.append('Impacto')\n header.append('Correccion')\n header.append('CR')\n writer_csv.writerow(header)\n\n if row_number and (row_number-filter_days) > 0:\n for x in range(0, (int(row_number)-filter_days)):\n next(reader_csv)\n\n last_close = ''\n rendimiento = ''\n pasa_filtro = False\n impact_with_margin = False\n count_days = -1\n impactos = []\n impacto_actual = 0\n rendimiento_impacto_anterior_tmp = ''\n rendimiento_impacto_anterior = []\n rendimiento_impacto_anterior_list = []\n rendimiento_impacto = []\n rendimiento_count_days_after_impact = []\n rendimiento_count_days_after_impact_list = []\n thirty_days_g = []\n thirty_days_groups = []\n\n # valuePassFilterForGraph=[]\n for row in reader_csv:\n # LOGGER.debug(str(row))\n if last_close != '':\n rendimiento = (\n float(row[5]) - float(last_close)) / float(last_close)\n row.append(str(rendimiento)) # Columna Rendimiento\n LOGGER.debug(str(rendimiento))\n if abs(rendimiento) * 100 >= filter_percentage and not pasa_filtro:\n LOGGER.debug('### El registro %s tiene %s de rentabilidad diaria ###', str(\n row), str(rendimiento))\n LOGGER.debug(datetime.datetime.strptime(row[0], '%Y-%m-%d') > datetime.datetime(start_date.year, start_date.month, start_date.day))\n if datetime.datetime.strptime(row[0], '%Y-%m-%d') > datetime.datetime(start_date.year, start_date.month, start_date.day): \n impactos.append(row)\n impacto_actual = float(row[6])\n rendimiento_impacto_anterior = rendimiento_impacto_anterior_tmp\n rendimiento_impacto.append(rendimiento)\n else:\n impact_with_margin = True\n pasa_filtro = True\n ultimo_rendimiento = rendimiento\n row.append(str(rendimiento)) # Columna Impacto \n [row.append('') for range in range(2)] # Columna Correccion y CR\n elif abs(rendimiento) * 100 >= filter_percentage and pasa_filtro:\n row.append('') # Columna Impacto\n row.append(str(rendimiento)) # Columna Correccion\n cr = rendimiento + float(ultimo_rendimiento)\n row.append(str(cr)) # Columna CR\n ultimo_rendimiento = cr\n if not impact_with_margin: \n thirty_days_groups.append(cr)\n rendimiento_count_days_after_impact.append(row)\n elif pasa_filtro:\n if not impact_with_margin: \n [row.append('') for range in range(2)] # Columna Impacto y Correcion\n if count_days > 0 and count_days < filter_days:\n cr = rendimiento + float(ultimo_rendimiento)\n row.append(str(cr)) # Columna CR\n ultimo_rendimiento = cr\n thirty_days_groups.append(cr)\n else:\n cr = rendimiento\n row.append(str(cr)) # Columna CR\n ultimo_rendimiento = cr\n thirty_days_groups.append(cr)\n\n rendimiento_count_days_after_impact.append(row)\n else:\n [row.append('') for range in range(2)] # Columna Impacto y Correcion\n if count_days > 0 and count_days < filter_days:\n cr = rendimiento + float(ultimo_rendimiento)\n row.append(str(cr)) # Columna CR\n ultimo_rendimiento = cr\n else:\n cr = rendimiento\n row.append(str(cr)) # Columna CR\n ultimo_rendimiento = cr\n else: \n [row.append('') for range in range(3)] # Columna Impacto, Correccion y CR\n\n if pasa_filtro:\n count_days += 1\n\n if count_days >= filter_days:\n if not impact_with_margin:\n if impacto_actual > 0:\n thirty_days_g.append(min(thirty_days_groups))\n else:\n thirty_days_g.append(max(thirty_days_groups))\n rendimiento_impacto_anterior_list.append(\n rendimiento_impacto_anterior)\n rendimiento_count_days_after_impact_list.append(\n rendimiento_count_days_after_impact)\n rendimiento_count_days_after_impact = []\n thirty_days_groups = []\n pasa_filtro = False\n impact_with_margin = False\n count_days = -1\n else:\n [row.append('') for range in range(3)]\n\n writer_csv.writerow(row)\n last_close = row[5]\n rendimiento_impacto_anterior_tmp = row\n if thirty_days_g:\n # valuePassFilterForGraph.append([value_name, max(thirty_days_g)])\n for index, impact in enumerate(impactos):\n fecha_impacto = impact[0]\n try:\n fecha_impacto = impact[0]\n dia_impacto_close = float(impact[5])\n dia_anterior_impacto_close = float(\n rendimiento_impacto_anterior_list[index][5])\n count = 1\n for row in rendimiento_count_days_after_impact_list[index]:\n if float(row[9]) == thirty_days_g[index]:\n dia_optimo_correccion_close = float(row[5])\n break\n count += 1\n dia_despues_impacto_open = float(\n rendimiento_count_days_after_impact_list[index][0][4])\n\n LOGGER.debug('T1 - Dia del impacto: %s',\n str(dia_impacto_close))\n LOGGER.debug('T - Dia anterior al impacto: %s',\n str(dia_anterior_impacto_close))\n LOGGER.debug(\n 'T2 - Dia optimo de la correccion: %s', str(dia_optimo_correccion_close))\n LOGGER.debug(\n 'T3 - Dia despues del impacto: %s', str(dia_despues_impacto_open))\n\n if float(impact[6]) > 0:\n correccion = '{:.2%}'.format(\n (dia_impacto_close-dia_optimo_correccion_close)/(dia_impacto_close-dia_anterior_impacto_close))\n beneficio = '{:.2%}'.format(\n (dia_despues_impacto_open-dia_optimo_correccion_close)/dia_despues_impacto_open)\n else:\n correccion = '{:.2%}'.format(\n (dia_optimo_correccion_close-dia_impacto_close)/(dia_anterior_impacto_close-dia_impacto_close))\n beneficio = '{:.2%}'.format(\n (dia_optimo_correccion_close-dia_despues_impacto_open)/dia_despues_impacto_open)\n\n rows_db.append([value_id, fecha_impacto,\n rendimiento_impacto[index], count, ((dia_impacto_close-dia_optimo_correccion_close)/(dia_impacto_close-dia_anterior_impacto_close)), ((dia_despues_impacto_open-dia_optimo_correccion_close)/dia_despues_impacto_open)])\n rows_overview.append([value_name, fecha_impacto, '{:.2%}'.format(\n rendimiento_impacto[index]), count, correccion, beneficio])\n count = 0\n except IndexError:\n rows_db.append([value_id, fecha_impacto,\n rendimiento_impacto[index], None, None, None])\n rows_overview.append([value_name, fecha_impacto, '{:.2%}'.format(\n rendimiento_impacto[index]), None, None, None])\n continue\n\n\ndef save_impacts_in_db_backtesting(rows_db):\n for row in rows_db:\n json_object = {\n 'value_id': row[0],\n 'impact_date': row[1],\n 'impact': row[2],\n 'optimal_day': row[3],\n 'correction': row[4],\n 'profit': row[5]\n }\n save_strategy1impactsbacktesting(json_object)\n\n\ndef calculate_cumulative_return(rows_overview):\n ''' Process for calculate cumulative return '''\n with open('./src/assets/strategy1/CR.csv', 'w') as csv_file_w:\n writer_cr = csv.writer(csv_file_w, delimiter=';', lineterminator='\\n')\n writer_cr.writerow(['Valor', 'Fecha Impacto', 'Impacto', 'Dia Optimo',\n 'Correccion', 'Beneficio'])\n writer_cr.writerows(rows_overview)\n","sub_path":"server/src/services/DAOstrategy_1_backtesting.py","file_name":"DAOstrategy_1_backtesting.py","file_ext":"py","file_size_in_byte":16491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"174074984","text":"# Env:\n# AWS_ACCESS_KEY_ID\n# AWS_SECRET_ACCESS_KEY\n# S3_BUCKET\n# S3_PREFIX\n# TEST_JAR_PATH\n\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\nimport re\nimport os\nimport subprocess\nimport shakedown\n\n\ndef upload_file(file_path):\n conn = S3Connection(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'])\n bucket = conn.get_bucket(os.environ['S3_BUCKET'])\n basename = os.path.basename(file_path)\n\n if basename.endswith('.jar'):\n content_type = 'application/java-archive'\n elif basename.endswith('.py'):\n content_type = 'application/x-python'\n else:\n raise ValueError(\"Unexpected file type: {}. Expected .jar or .py file.\".format(basename))\n\n key = Key(bucket, '{}/{}'.format(os.environ['S3_PREFIX'], basename))\n key.metadata = {'Content-Type': content_type}\n key.set_contents_from_filename(file_path)\n key.make_public()\n\n jar_url = \"http://{0}.s3.amazonaws.com/{1}/{2}\".format(\n os.environ['S3_BUCKET'],\n os.environ['S3_PREFIX'],\n basename)\n\n return jar_url\n\n\ndef submit_job(app_resource_url, app_args, app_class, py_files):\n if app_class is not None:\n app_class_option = '--class {} '.format(app_class)\n else:\n app_class_option = ''\n if py_files is not None:\n py_files_option = '--py-files {} '.format(py_files)\n else:\n py_files_option = ''\n\n submit_args = \"-Dspark.driver.memory=2g {0}{1}{2} {3}\".format(\n app_class_option, py_files_option, app_resource_url, app_args)\n cmd = 'dcos --log-level=DEBUG spark --verbose run --submit-args=\"{0}\"'.format(submit_args)\n print('Running {}'.format(cmd))\n stdout = subprocess.check_output(cmd, shell=True).decode('utf-8')\n print(stdout)\n\n regex = r\"Submission id: (\\S+)\"\n match = re.search(regex, stdout)\n return match.group(1)\n\n\ndef task_log(task_id):\n cmd = \"dcos task log --completed --lines=1000 {}\".format(task_id)\n print('Running {}'.format(cmd))\n stdout = subprocess.check_output(cmd, shell=True).decode('utf-8')\n return stdout\n\n\ndef run_tests(app_path, app_args, expected_output, app_class=None, py_file_path=None):\n app_resource_url = upload_file(app_path)\n if py_file_path is not None:\n py_file_url = upload_file(py_file_path)\n else:\n py_file_url = None\n task_id = submit_job(app_resource_url, app_args, app_class, py_file_url)\n print('Waiting for task id={} to complete'.format(task_id))\n shakedown.wait_for_task_completion(task_id)\n log = task_log(task_id)\n print(log)\n assert expected_output in log\n\n\ndef main():\n spark_job_runner_args = 'http://leader.mesos:5050 dcos \\\\\"*\\\\\" spark:only 2'\n run_tests(os.getenv('TEST_JAR_PATH'),\n spark_job_runner_args,\n \"All tests passed\",\n app_class='com.typesafe.spark.test.mesos.framework.runners.SparkJobRunner')\n\n script_dir = os.path.dirname(os.path.abspath(__file__))\n python_script_path = os.path.join(script_dir, 'jobs', 'pi_with_include.py')\n py_file_path = os.path.join(script_dir, 'jobs', 'PySparkTestInclude.py')\n run_tests(python_script_path,\n '30',\n \"Pi is roughly 3\",\n py_file_path=py_file_path)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"128648967","text":"import os\nimport numpy as np\nimport nibabel as nib\nimport matplotlib.pyplot as plt\n\n\ndef show_plane(x):\n plt.imshow(np.rot90(x), cmap=\"gray\")\n plt.gca().set_axis_off()\n\ndef show_section(xImg, section, xSlice):\n if section=='xy':\n tmpImg = xImg[:,:,xSlice]\n elif section=='xz':\n tmpImg = xImg[:,xSlice,:]\n else:\n tmpImg = xImg[xSlice,:,:]\n show_plane(tmpImg)\n\n\n\n# Directory where your data set resides. This needs to be customized\ndataDir = '/home/satoru/Teaching/fMRI_Fall_2018/Data/ds102'\n\n# reading in the T1 image data array\nf_sMRI = os.path.join(dataDir,'sub-26/anat/sub-26_T1w.nii.gz')\nsMRI = nib.load(f_sMRI)\nX_sMRI = sMRI.get_data()\n\n# locations (in voxels) where slicing occurs\nxSlice = 85\nySlice = 110\nzSlice = 140\n\n\nshow_section(X_sMRI,'xy',zSlice)\nplt.title('Axial section (xy-plane)')\nplt.show()\n\nshow_section(X_sMRI,'xz',ySlice)\nplt.title('Coronal section (yz-plane)')\nplt.show()\n\nshow_section(X_sMRI,'yz',xSlice)\nplt.title('Sagittal section (yz-plane)')\nplt.show()\n","sub_path":"NumPy/ShowT1Image.py","file_name":"ShowT1Image.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186542242","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.decorators.http import require_POST\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Article, Comment\nfrom .forms import ArticleForm, CommentForm\n\ndef index(request):\n visits_num = request.session.get('visits_num', 0)\n request.session['visits_num'] = visits_num + 1\n request.session.modified = True\n\n articles = Article.objects.all()\n context = {\n 'articles': articles,\n 'visits_num': visits_num,\n }\n return render(request, 'articles/index.html', context)\n\n@login_required\ndef create(request):\n if request.method == 'POST':\n article_form = ArticleForm(request.POST)\n if article_form.is_valid():\n article = article_form.save(commit=False)\n article.user_id = request.user.id\n article.save()\n return redirect('articles:detail', article.pk)\n else:\n article_form = ArticleForm()\n context = {\n 'article_form': article_form,\n }\n return render(request, 'articles/create.html', context)\n\ndef detail(request, article_pk):\n article = get_object_or_404(Article, pk=article_pk)\n comments = article.comment_set.all()\n comment_form = CommentForm()\n context = {\n 'article': article,\n 'comment_form': comment_form,\n 'comments': comments,\n }\n return render(request, 'articles/detail.html', context)\n\n@require_POST\ndef delete(request, article_pk):\n if request.user.is_authenticated:\n article = get_object_or_404(Article, pk=article_pk)\n if article.user == request.user:\n article.delete()\n return redirect('articles:index')\n\n@login_required\ndef update(request, article_pk):\n article = get_object_or_404(Article, pk=article_pk)\n if article.user == request.user:\n if request.method == 'POST':\n article_form = ArticleForm(request.POST, instance=article)\n if article_form.is_valid():\n article_form.save()\n return redirect('articles:detail', article_pk)\n else:\n article_form = ArticleForm(instance=article)\n else:\n return redirect('articles:index')\n context = {\n 'article_form': article_form,\n 'article': article,\n }\n return render(request, 'articles/update.html', context)\n\n@require_POST\ndef create_comment(request, article_pk):\n comment_form = CommentForm(request.POST)\n if request.user.is_authenticated:\n if comment_form.is_valid():\n comment = comment_form.save(commit=False)\n comment.user_id = request.user.id\n comment.article_id=article_pk\n comment.save()\n return redirect('articles:detail', article_pk)\n\n@require_POST\ndef delete_comment(request, article_pk, comment_pk):\n if request.user.is_authenticated:\n comment = get_object_or_404(Comment, pk=comment_pk)\n if request.user == comment.user:\n comment.delete()\n return redirect('articles:detail', article_pk)\n\n@login_required\ndef like(request, article_pk):\n article = get_object_or_404(Article, pk=article_pk)\n user = request.user\n if article.like_users.filter(pk=user.pk).exists():\n article.like_users.remove(user)\n else:\n article.like_users.add(user)\n return redirect('articles:index')","sub_path":"practice1/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345027582","text":"#!/usr/bin/env python\n\"\"\"\nexample:\nDownloadThemis 2012-11-03T06:23 2012-11-03T06:24 ~/data -s gako\n\"\"\"\nimport themisasi.web as tweb\nfrom argparse import ArgumentParser\n\nVIDEO_BASE = \"http://themis.ssl.berkeley.edu/data/themis/thg/l1/asi/\"\nCAL_BASE = \"http://themis.ssl.berkeley.edu/data/themis/thg/l2/asi/cal/\"\n\n\ndef main():\n p = ArgumentParser()\n p.add_argument(\"startend\", help=\"start/end times UTC e.g. 2012-11-03T06:23 2012-11-03T06:24\", nargs=\"+\")\n p.add_argument(\"odir\", help=\"directory to write downloaded CDF to\")\n p.add_argument(\"-s\", \"--site\", help=\"fykn gako etc.\", nargs=\"+\")\n p.add_argument(\"-overwrite\", help=\"overwrite existing files\", action=\"store_true\")\n p.add_argument(\"-vh\", help=\"Stem of URL for Video data\", default=VIDEO_BASE)\n p.add_argument(\"-ch\", help=\"Stem of URL for calibration data\", default=CAL_BASE)\n\n P = p.parse_args()\n\n urls = {\"video_stem\": P.vh, \"cal_stem\": P.ch}\n\n tweb.download(P.startend, P.site, P.odir, P.overwrite, urls)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DownloadThemis.py","file_name":"DownloadThemis.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"101398005","text":"\"\"\" Miscellaneous tools -- for eg sampling synthetic data \"\"\"\n\nimport numpy as np\n\nSORT_CONVENTIONS = {'sort': lambda x,ns: x, 'revsort': lambda x,ns: ns-1-x}\ndef to_int(b,sort='revsort'):\n \"\"\" Given a binary string b, return its index in the occupation number basis.\n revsort = standard order for quspin/qutip, most excited states first\"\"\"\n\n x=sum([(2**j) * b[len(b)-1-j] for j in range(len(b)) ])\n x=SORT_CONVENTIONS[sort](x,2**len(b))\n return int(x)\n\ndef to_binary(x,L, sort='revsort'):\n \"\"\"Given an integer x, return its binary representation.\"\"\"\n x = SORT_CONVENTIONS[sort](x, 2**L)\n b=np.zeros(L,dtype=int)\n for i in range(L):\n x,r=divmod(x,2)\n b[L-i-1]=r\n return b\n\ndef draw(probs, occ_rep, Nsamp):\n \"\"\"Given array of probabilities probs in the standard basis, and the array of corresponding\n occupation number representations occ_rep, draw Nsamp occ-rep samples from the distribution.\n\n Returns: array (Nsamp, L), L being the number of atoms \"\"\"\n Ns, L = occ_rep.shape\n shots= np.empty((Nsamp,L))\n results = np.random.choice(list(range(len(probs))), Nsamp, p=probs)\n for ii in range(Nsamp):\n shots[ii, : ] = occ_rep[results[ii], :]\n return shots\n\ndef do_bitflip(zshots, p01, p10):\n \"\"\" Run the z-basis data zshots through a classical bit-flip channel.\n With probability p01 (read: '0 given 1')\n 1---->0\n and with probability p10\n 0 ---> 1\n \"\"\"\n zshots = zshots.astype(int)\n r = np.random.rand(*zshots.shape)\n f01 = r1\n p01 = probability of 1->0\n v = (2^L, L) array which holds the position space reps of basis states.\n Returns: matrix Pi of conditional probs, such that Pi[a, b] is the probability\n of transitioning *to* a *from* b\n\n Note, this is an extremely inefficient implementation and you should be\n ashamed to use it.\"\"\"\n\n ns,L =v.shape\n if ns != 2**L:\n raise ValueError\n #matrix of conitional probs.\n pi = np.zeros((ns,ns))\n p00 = 1-p10\n p11 = 1-p01\n for i in range(ns):\n #final state\n si = v[i,:]\n for j in range(i,ns):\n #initial state\n sj = v[j, :]\n #number of sites where 1->1 transition occurs, etc\n n11 = np.sum((si==1)*(sj==1))\n n10 = np.sum((si==1)*(sj==0))\n n01 = np.sum((si==0)*(sj==1))\n n00 = np.sum((si==0)*(sj==0))\n pi[i, j] = (p11**n11)*(p10**n10)*(p01**n01)*(p00**n00)\n pi[j,i] = (p11**n11)*(p10**n01)*(p01**n10)*(p00**n00)\n return pi\n\ndef get_n_bysite_from_pdist(pdist,v):\n \"\"\"v = (N, L) array of occupation-number data points.\n return the average excitation per site.\"\"\"\n return np.tensordot(pdist,v,axes=([0],[0]))\n\ndef get_zz_correlation_matrix_from_pdist(pdist, v):\n \"\"\"v = (N, L) array of occupation-number data points.\n return the two-point spin-spin connected correlator matrix.\"\"\"\n if np.min(v)<0:\n raise ValueError(\"expecting binary input\")\n z = 2 * v-1\n zizj_bar = np.einsum('i,ij,ik->jk',pdist, z, z)\n zi_barzj_bar = np.einsum('i,ij,l,lk->jk',pdist, z,pdist,z)\n return zizj_bar - zi_barzj_bar\n\ndef get_avg_correlation_from_matrix(zz):\n \"\"\"Given array of correlations zz, returns the spatial average\n correlation values.\n zz shape = (L, L, ...)\n return shape = (L-1, ...)\"\"\"\n L=zz.shape[0]\n ns=L-1\n #zzbar = np.zeros((ns, *zz.shape[2:]))\n zzbar = np.zeros_like(zz)\n for i in range(ns):\n s=i+1\n zzbar[i, ...] = np.mean(np.asarray([zz[ii, ii+s, ...] for ii in range(L-s)]), axis=0)\n return zzbar\n\ndef make_experimental_distribution(zshots):\n \"\"\"Given (N, L) array of observations, return the corresponding frequency\n distribution.\"\"\"\n N,L = zshots.shape\n pvals = np.zeros(2**L)\n for j in range(N):\n m = to_int(zshots[j, :])\n pvals[m] += 1/N\n return pvals\n\ndef safelog(x,eps=1e-12):\n xsf = (x>eps) *x + (x <=eps) * eps\n return np.log(xsf)\n\ndef Hshannon(p,eps=1e-12,axis=None):\n p = np.asarray(p)\n return - np.sum(p * safelog(p,eps=eps),axis=axis)\n\ndef NLL(p, q,eps=1e-12):\n if (q= min(ct) * 3\n\n if ct[0] > ct[1]:\n out += '0'\n else:\n out += '1'\n\nprint(out)\n\nmsg = ''\nfor i in range(0, len(out), 5):\n for j in range(i, i+5):\n assert out[i] == out[j]\n msg += out[i]\n\nprint(int(msg, 2).to_bytes(len(msg) // 8, 'big'))\n","sub_path":"FwordCTF2020/misc/repeat/solve_repeat.py","file_name":"solve_repeat.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"299932017","text":"from rcp import get_polls, get_poll_data\nfrom prettytable import PrettyTable\n\n\nbattleground_states = [\n \"Wisconsin\",\n \"Florida\",\n \"Michigan\",\n \"Pennsylvania\",\n \"North Carolina\",\n \"Arizona\",\n \"Texas\",\n \"Iowa\",\n \"Georgia\",\n]\nx = PrettyTable()\n\nfor state in battleground_states:\n polls = get_polls(candidate=\"Biden\",state=state)\n for poll in polls:\n data = get_poll_data(poll['url'])\n x.field_names = list(data[0][\"data\"][0].keys())\n x.align = \"l\"\n\n for row in data[0][\"data\"]:\n x.add_row(row.values())\n\n print(x)","sub_path":"PresidentialTabular.py","file_name":"PresidentialTabular.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"159496124","text":"import unittest\n\nfrom unittest.mock import ANY\n\nfrom . import ChemicalQuiz\nfrom stepic_plugins.exceptions import FormatError\n\n\nclass ChemicalQuizTest(unittest.TestCase):\n def setUp(self):\n self.default_source_formula = {\n 'expression': 'C2H5OH',\n 'template': ['normal', 'subsup', 'normal', 'subsup',\n 'normal', 'subsup', 'normal', 'subsup']\n }\n self.default_source_equation = {\n 'expression': '2H2 + O2 -> 2H2O',\n 'template': ['normal', 'subsup', 'normal', 'subsup', 'normal', 'normal', 'subsup',\n 'normal', 'normal', 'normal', 'subsup', 'normal']\n }\n\n\nclass ChemicalQuizInitTest(ChemicalQuizTest):\n def test_invalid_sources(self):\n invalid_sources = [\n {'expression': \"\", 'template': []},\n {'expression': \"2\", 'template': []},\n {'expression': \"H2O(\", 'template': []},\n {'expression': \"H +\", 'template': []},\n {'expression': 'C2H5OH', 'template': ['SUB']},\n {'expression': 'C2H5OH', 'template': ['normal', 'supsub']},\n ]\n for invalid_source in invalid_sources:\n source = ChemicalQuiz.Source(invalid_source)\n with self.assertRaises(FormatError):\n ChemicalQuiz(source)\n\n def test_valid_source(self):\n for source in [self.default_source_formula, self.default_source_equation]:\n ChemicalQuiz(ChemicalQuiz.Source(source))\n\n\nclass ChemicalQuizCleanReplyTest(ChemicalQuizTest):\n def test_invalid_slots_number(self):\n quiz = ChemicalQuiz(ChemicalQuiz.Source(self.default_source_formula))\n reply = ChemicalQuiz.Reply({'slots': [{'normal': 'C', 'sub': '', 'sup': ''}]})\n\n with self.assertRaises(FormatError):\n quiz.clean_reply(reply, None)\n\n\nclass ChemicalQuizCheckTest(ChemicalQuizTest):\n def test_unparsable_expression(self):\n quiz = ChemicalQuiz(ChemicalQuiz.Source(self.default_source_formula))\n\n self.assertEqual(quiz.check('', None), (False, ANY))\n self.assertEqual(quiz.check('C(', None), (False, ANY))\n\n def test_formula(self):\n quiz = ChemicalQuiz(ChemicalQuiz.Source(self.default_source_formula))\n\n self.assertIs(quiz.check('C3H5OH', None), False)\n self.assertIs(quiz.check('C2 H5 OH', None), True)\n\n def test_equation(self):\n quiz = ChemicalQuiz(ChemicalQuiz.Source(self.default_source_equation))\n\n self.assertIs(quiz.check('H2+O2->H2O', None), False)\n self.assertIs(quiz.check('O2 + 2H2 ->2H2O', None), True)\n","sub_path":"stepic_plugins/quizzes/chemical/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"538114489","text":"import ast\nimport uuid\nfrom random import randint\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework.authtoken.models import Token\n\nfrom charged.lnpurchase.models import Product, PurchaseOrder, PurchaseOrderItemDetail\nfrom shop.exceptions import PortNotInUseError, PortInUseError\nfrom shop.validators import validate_host_name_blacklist\nfrom shop.validators import validate_host_name_no_underscore\nfrom shop.validators import validate_target_has_port\nfrom shop.validators import validate_target_is_onion\n\n\nclass Host(models.Model):\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n created_at = models.DateTimeField(verbose_name=_('date created'), auto_now_add=True)\n modified_at = models.DateTimeField(verbose_name=_('date modified'), auto_now=True)\n\n ip = models.GenericIPAddressField(verbose_name=_('IP Address'),\n help_text=_('IP Address of Host.'),\n unique=True)\n\n owner = models.ForeignKey(get_user_model(),\n editable=True,\n on_delete=models.CASCADE,\n related_name='owned_hosts',\n verbose_name=_(\"Owner\"),\n limit_choices_to={'is_staff': True})\n\n token_user = models.OneToOneField(get_user_model(),\n related_name='token_host',\n editable=False,\n blank=True,\n null=True,\n on_delete=models.CASCADE,\n verbose_name=_(\"Token User\"))\n\n name = models.CharField(max_length=20,\n default='bridge',\n verbose_name=_('Hostname'),\n help_text=_('Host DNS name without domain. Restrictions apply: max. '\n '20 characters; can not be certain names (e.g. \"www\" or '\n '\"shop\"). Example: \"bridge1\".'),\n validators=[validate_host_name_no_underscore,\n validate_host_name_blacklist])\n\n site = models.ForeignKey(Site, on_delete=models.CASCADE, default=1, related_name='hosts')\n\n offers_tor_bridges = models.BooleanField(default=False,\n verbose_name=_('Does host offer Tor Bridges?'))\n\n tor_bridge_duration = models.BigIntegerField(verbose_name=_('Bridge Duration (seconds)'),\n help_text=_('Lifetime of Bridge (either initial or extension).'),\n default=60 * 60 * 24)\n\n tor_bridge_price_initial = models.BigIntegerField(verbose_name=_('Bridge Price (mSAT)'),\n help_text=_('Price of a Tor Bridge in milli-satoshi '\n 'for initial Purchase.'),\n default=25000)\n\n tor_bridge_price_extension = models.BigIntegerField(verbose_name=_('Bridge Extension Price (mSAT)'),\n help_text=_('Price of a Tor Bridge in milli-satoshi '\n 'for extending existing bridge.'),\n default=20000)\n\n offers_rssh_tunnels = models.BooleanField(default=False,\n verbose_name=_('Does host offer Reverse SSH Tunnels?'))\n rssh_tunnel_price = models.BigIntegerField(verbose_name=_('RSSH Price (mSAT)'),\n help_text=_('Price of a Reverse SSH Tunnel in milli-satoshi.'),\n default=1000)\n\n # Add ToS (Terms of Service)\n terms_of_service = models.TextField(verbose_name=_('Terms of Service'),\n help_text=_('Short description of Terms of Service.'),\n null=False, blank=True)\n\n terms_of_service_url = models.URLField(verbose_name=_('ToS Link'),\n help_text=_('Link to a Terms of Service site.'),\n null=False, blank=True)\n\n class Meta:\n ordering = ['ip']\n verbose_name = _('Host')\n verbose_name_plural = _('hosts')\n unique_together = ['site', 'name']\n\n def __str__(self):\n return 'Host:{} ({} - Owner:{})'.format(self.ip, self.name, self.owner)\n\n def get_random_port(self):\n port_range = self.port_ranges.all()\n # use only ranges that have less than 85% usage\n port_range = [x for x in port_range if x.ports_used_percent < 0.85]\n\n if not port_range:\n return\n\n rand_port_range = port_range[randint(0, len(port_range) - 1)]\n\n rand_port = None\n for _ in range(0, rand_port_range.ports_total):\n rand_port = randint(rand_port_range.start, rand_port_range.end)\n if not rand_port_range.check_port_usage(rand_port):\n rand_port_range.add_port_usage(rand_port)\n break\n\n return rand_port\n\n @property\n def tor_bridge_ports_available(self):\n total = 0\n for range in self.port_ranges.filter(type=PortRange.TOR_BRIDGE):\n total += range.ports_available\n return total\n\n @property\n def rssh_tunnels_ports_available(self):\n total = 0\n for range in self.port_ranges.filter(type=PortRange.RSSH_TUNNEL):\n total += range.ports_available\n return total\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n\n if not self.token_user:\n # create a User object for this host\n obj, _ = get_user_model().objects.get_or_create(username=str(self.id))\n\n # add a token to this Host.User object\n _, _ = Token.objects.get_or_create(user=obj)\n self.token_user = obj\n self.save()\n\n\nclass PortRange(models.Model):\n INITIAL = 'I'\n TOR_BRIDGE = 'T'\n RSSH_TUNNEL = 'R'\n PORT_RANGE_TYPE_CHOICES = (\n (INITIAL, _('Initial')),\n (TOR_BRIDGE, _('Tor Bridges')),\n (RSSH_TUNNEL, _('Reverse SSH Tunnels')),\n )\n\n type = models.CharField(\n verbose_name=_(\"Port Range Type\"),\n max_length=1,\n choices=PORT_RANGE_TYPE_CHOICES,\n default=INITIAL\n )\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n created_at = models.DateTimeField(verbose_name=_('date created'), auto_now_add=True)\n modified_at = models.DateTimeField(verbose_name=_('date modified'), auto_now=True)\n\n start = models.PositiveIntegerField(verbose_name=_('Start Port'),\n help_text=_('Start Port - Must be in range 1025 - 65535.'),\n validators=[MinValueValidator(1025), MaxValueValidator(65535)])\n\n end = models.PositiveIntegerField(verbose_name=_('End Port'),\n help_text=_('End Port - Must be in range 1025 - 65535.'),\n validators=[MinValueValidator(1025), MaxValueValidator(65535)])\n\n _used = models.TextField(editable=False,\n default='{}',\n verbose_name=_('Used Ports'),\n help_text=_('Which Ports are currently in use.'))\n\n host = models.ForeignKey('Host', on_delete=models.CASCADE, related_name='port_ranges')\n\n class Meta:\n ordering = ['start']\n verbose_name = _('Port Range')\n verbose_name_plural = _('Port Ranges')\n\n def __str__(self):\n return '{}: {}-{} ({}/{})'.format(self._meta.verbose_name,\n self.start, self.end,\n self.ports_used, self.ports_total)\n\n @property\n def used(self):\n if self._used:\n return set(ast.literal_eval(self._used))\n return set()\n\n @used.setter\n def used(self, value):\n if not isinstance(value, set):\n raise ValueError('Must be of type set.')\n self._used = value.__str__()\n\n @property\n def ports_total(self):\n return 1 + self.end - self.start\n\n @property\n def ports_used(self):\n return len(self.used)\n\n @property\n def ports_used_percent(self):\n return len(self.used) / self.ports_total * 1.0\n\n @property\n def ports_available(self):\n return self.ports_total - self.ports_used\n\n def add_port_usage(self, value):\n if not isinstance(value, int):\n raise ValueError('Must be of type int.')\n if not 1025 <= value <= 65535:\n raise ValueError('Must be in range 1025 - 65535.')\n if value in self.used:\n raise PortInUseError\n\n new_set = self.used.copy()\n new_set.add(value)\n self.used = new_set\n self.save()\n\n def check_port_usage(self, value):\n if not isinstance(value, int):\n raise ValueError('Must be of type int.')\n if not 1025 <= value <= 65535:\n raise ValueError('Must be in range 1025 - 65535.')\n if value in self.used:\n return True\n return False\n\n def remove_port_usage(self, value):\n if not isinstance(value, int):\n raise ValueError('Must be of type int.')\n if not 1025 <= value <= 65535:\n raise ValueError('Must be in range 1025 - 65535.')\n if value not in self.used:\n raise PortNotInUseError\n\n new_set = self.used.copy()\n new_set.remove(value)\n if len(new_set):\n self.used = new_set\n else:\n self._used = new_set.__str__()\n\n self.save()\n\n def clean(self):\n if self.start >= self.end:\n raise ValidationError(_('Start Port must be lower than End Port.'))\n\n # ToDo(frennkie) how to make sure port ranges don't overlap!\n\n\nclass InitialTorBridgeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(review_status=TorBridge.INITIAL)\n\n\nclass PendingTorBridgeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(review_status=TorBridge.PENDING)\n\n\nclass ActiveTorBridgeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(review_status=TorBridge.ACTIVE)\n\n\nclass SuspendedTorBridgeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(review_status=TorBridge.SUSPENDED)\n\n\nclass DeletedTorBridgeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(review_status=TorBridge.DELETED)\n\n\nclass Bridge(Product):\n INITIAL = 'I'\n PENDING = 'P'\n ACTIVE = 'A'\n SUSPENDED = 'S'\n DELETED = 'D'\n BRIDGE_STATUS_CHOICES = (\n (INITIAL, _('initial')),\n (PENDING, _('pending')),\n (ACTIVE, _('active')),\n (SUSPENDED, _('suspended')),\n (DELETED, _('deleted')),\n )\n\n status = models.CharField(\n verbose_name=_(\"Bridge Status\"),\n max_length=1,\n choices=BRIDGE_STATUS_CHOICES,\n default=INITIAL\n )\n\n previous_status = None\n\n host = models.ForeignKey(Host, on_delete=models.CASCADE)\n\n port = models.PositiveIntegerField(verbose_name=_('Port'),\n blank=True,\n null=True,\n editable=False,\n help_text=_('Port - Must be in range 1025 - 65535.'),\n validators=[MinValueValidator(1025), MaxValueValidator(65535)])\n\n comment = models.CharField(max_length=42, blank=True, null=True,\n verbose_name=_('Bridge/Tunnel comment'))\n\n suspend_after = models.DateTimeField(verbose_name=_('suspend after'), null=True, blank=True)\n\n objects = models.Manager() # default\n initial = InitialTorBridgeManager()\n pending = PendingTorBridgeManager()\n active = ActiveTorBridgeManager()\n suspended = SuspendedTorBridgeManager()\n deleted = DeletedTorBridgeManager()\n\n class Meta:\n abstract = True\n\n def __str__(self):\n if self.port:\n _port = self.port\n else:\n _port = \"N/A\"\n\n return '{}:{} P:{} S:{}'.format(self._meta.verbose_name,\n self.host, _port,\n self.get_status_display())\n\n def delete(self, using=None, keep_parents=False):\n for pr in self.host.port_ranges.all():\n if isinstance(self.port, int):\n try:\n if pr.check_port_usage(self.port):\n pr.remove_port_usage(self.port)\n except PortNotInUseError:\n pass\n\n super().delete(using, keep_parents)\n\n def process_activation(self):\n print(\"{} status was change to activated.\".format(self._meta.verbose_name))\n\n def process_suspension(self):\n print(\"{} status was change to suspended.\".format(self._meta.verbose_name))\n\n\nclass TorBridge(Bridge):\n PRODUCT = 'tor_bridge'\n\n class Meta:\n ordering = ['created_at']\n verbose_name = _('Tor Bridge')\n verbose_name_plural = _('Tor Bridges')\n\n target = models.CharField(max_length=300,\n verbose_name=_('Tor Bridge Target'),\n help_text=_('Target address. Must be an .onion address and must include '\n 'the port. Example: \"ruv6ue7d3t22el2a.onion:80\"'),\n validators=[validate_target_is_onion,\n validate_target_has_port])\n\n\nclass PurchaseOrderTorBridgeManager(models.Manager):\n \"\"\"creates a purchase order for a new tor bridge\"\"\"\n\n def create(self, host, target, comment=None):\n tor_bridge = TorBridge.objects.create(comment=comment,\n host=host,\n target=target)\n\n po = PurchaseOrder.objects.create()\n po_item = PurchaseOrderItemDetail(price=host.tor_bridge_price_initial,\n product=tor_bridge,\n quantity=1)\n po.item_details.add(po_item, bulk=False)\n po_item.save()\n po.save()\n\n return po\n\n\nclass RSshTunnel(Bridge):\n PRODUCT = 'rssh_tunnel'\n\n class Meta:\n ordering = ['created_at']\n verbose_name = _('Reverse SSH Tunnel')\n verbose_name_plural = _('Reverse SSH Tunnels')\n\n public_key = models.CharField(max_length=5000,\n verbose_name=_('SSH Public Key'),\n help_text=_('The SSH public key used to allow you access to the tunnel.'))\n\n\nclass ShopPurchaseOrder(PurchaseOrder):\n objects = models.Manager()\n tor_bridges = PurchaseOrderTorBridgeManager()\n","sub_path":"shop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"482546760","text":"\nfrom datetime import datetime\n\nfrom scheduled_jobs.http_reads.lmp import LMP\nfrom scheduled_jobs.trulight_energy.reference_data import ReferenceData\n\n\nDT_FORMAT = \"%m/%d/%Y\"\n\ndef get_instance(row_dict, is_real_time):\n if row_dict[\"H\"] == \"D\":\n zone_name = row_dict[\"Location Name\"].replace(\".Z.\", \"\")\n zone_name = zone_name.replace(\".H.\", \"\").lower()\n zone_id = ReferenceData.get_instance().get_zone_id(zone_name)\n if not zone_id:\n return None\n\n dt = datetime.strptime(row_dict[\"Date\"], DT_FORMAT)\n hr_ending = int(row_dict[\"Hour Ending\"])\n price = row_dict[\"Locational Marginal Price\"]\n \n return LMP(dt, price, is_real_time, hr_ending, zone_id, zone_name)\n \n return None","sub_path":"scheduled_jobs/http_reads/isone/read_isone_lmp.py","file_name":"read_isone_lmp.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"103670608","text":"__author__ = 'darakna'\n# table of probabilities for each letter\ndef letProb( c ):\n \"\"\" if c is the space character or an alphabetic character,\n we return its monogram probability (for english),\n otherwise we return 1.0 We ignore capitalization.\n Adapted from\n http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html\n \"\"\"\n if c == ' ': return 0.1904\n if c == 'e' or c == 'E': return 0.1017\n if c == 't' or c == 'T': return 0.0737\n if c == 'a' or c == 'A': return 0.0661\n if c == 'o' or c == 'O': return 0.0610\n if c == 'i' or c == 'I': return 0.0562\n if c == 'n' or c == 'N': return 0.0557\n if c == 'h' or c == 'H': return 0.0542\n if c == 's' or c == 'S': return 0.0508\n if c == 'r' or c == 'R': return 0.0458\n if c == 'd' or c == 'D': return 0.0369\n if c == 'l' or c == 'L': return 0.0325\n if c == 'u' or c == 'U': return 0.0228\n if c == 'm' or c == 'M': return 0.0205\n if c == 'c' or c == 'C': return 0.0192\n if c == 'w' or c == 'W': return 0.0190\n if c == 'f' or c == 'F': return 0.0175\n if c == 'y' or c == 'Y': return 0.0165\n if c == 'g' or c == 'G': return 0.0161\n if c == 'p' or c == 'P': return 0.0131\n if c == 'b' or c == 'B': return 0.0115\n if c == 'v' or c == 'V': return 0.0088\n if c == 'k' or c == 'K': return 0.0066\n if c == 'x' or c == 'X': return 0.0014\n if c == 'j' or c == 'J': return 0.0008\n if c == 'q' or c == 'Q': return 0.0008\n if c == 'z' or c == 'Z': return 0.0005\n return 1.0\ndef rating(L):\n if len(L) == 0:\n return 0\n else:\n return letProb(L[0])+rating(L[1:])\ndef decipher(S,n):\n if len(S)==0:\n return \"\"\n else:\n if ord(S[0]) in range(ord('A'),ord('Z')+1):\n if ord(S[0])+n > ord('Z'):\n return chr(ord(S[0])-26+n) + decipher(S[1:],n)\n else:\n return chr(ord(S[0])+n)+ decipher(S[1:],n)\n elif ord(S[0]) in range(ord('a'),ord('z')+1):\n if ord(S[0])+n > ord('z'):\n return chr(ord(S[0])-26+n) + decipher(S[1:],n)\n else:\n return chr(ord(S[0])+n)+ decipher(S[1:],n)\n else:\n return S[0]+decipher(S[1:],n)\ndef the_winner_is(stg):\n print(\"Problem:\",stg)\n L=[decipher(stg,n) for n in range (26)]\n LoL = [rating(x) for x in L ]\n for i in range(len(L)):\n #print(L[i],LoL[i]) //for debug\n pass\n print(\"Solution:\", L[LoL.index(max(LoL))])\n print (\"\\n\")\n\nsta=\"Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc.\"\nstb=\"Hu lkbjhapvu pz doha ylthpuz hmaly dl mvynla lclyfaopun dl ohcl slhyulk.\"\nstc = \"PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC KB YWAOWN WJZ UKQN QJEMQA OKHQPEKJ EO XJNLBYYBHJWA\" \nstd = \"KP BZA IGUSFZBP FHE PHO WIX RAIE BZSY UP TRSAXE S IU SUQRAYYAE JARP LAGG EHXA PHOR YHGOBSHX CAP SY AUFXWTHRTXQU BZSY GSBBGA WZIGGAXFA LIY XHB BHH ZIRE LIY SB\"\nthe_winner_is(sta)\nthe_winner_is(stb)\nthe_winner_is(stc)\nthe_winner_is(std)\n\n\n\n","sub_path":"Pyton_stuff/caesar_and_tools/auto_Caesar.py","file_name":"auto_Caesar.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335056422","text":"import praw\r\nimport config\r\nimport time\r\n\r\n\r\n\r\ndef bot_login():\r\n\tprint (\"Logging in...\")\r\n\tr = praw.Reddit(username = config.username,\r\n\t\t\tpassword = config.password,\r\n\t\t\tclient_id = config.client_id,\r\n\t\t\tclient_secret = config.client_secret,\r\n\t\t\tuser_agent = \"Guitarhero23_bot Paul Gilbert comment responder v0.01\")\r\n\r\n\treturn r\r\n\r\ndef run_bot(r):\r\n\tprint (\"Obtaining 25 comments...\")\r\n\tfor comment in r.subreddit('test').comments(limit=25):\r\n\t\tif \"Paul Gilbert\" in comment.body:\r\n\t\t\tprint (\"String with \\\"Paul Gilbert\\\" found!\" + comment.id)\r\n\t\t\tcomment.reply(\"I see you mentioned Paul Gilbert. [Here](http://www.dimarzio.com/sites/default/files/imagecache/player_page_image/player/Paul_Gilbert_photo_Larry_DiMarzio_2.jpg) is a random picture of Paul Gilbert and a [Link](http://www.paulgilbert.com/) to his website\")\r\n\t\t\tprint(\"Replied to comment\" + comment.id)\r\n\r\n\r\n\tprint (\"Sleeping for 10 seconds\")\t\t\r\n\t#Sleep for 10 seconds\r\n\ttime.sleep(10)\r\n\r\nr = bot_login()\r\nwhile True:\r\n\trun_bot(r)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"reddit_bot.py","file_name":"reddit_bot.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"114567242","text":"import cv2 as opencv\nimport os\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nfrom pygame import mixer\nimport time\n\ndef drive(start_score = 17, stop_score = 10):\n \n mixer.init()\n buzzer = mixer.Sound('buzzer.wav') #Putting in the buzzer\n\n #Already available classifiers to detect a face and both the eyes in the image\n \n #Creating a CascadeClassifier Object for the face left eye and the right eye\n face = opencv.CascadeClassifier('haarcascade_files/haarcascade_frontalface_alt.xml')\n leye = opencv.CascadeClassifier('haarcascade_files/haarcascade_lefteye_2splits.xml')\n reye = opencv.CascadeClassifier('haarcascade_files/haarcascade_righteye_2splits.xml')\n\n model = load_model('cnnCat2.h5') #loading already trained model\n\n path = os.getcwd()\n cap = opencv.VideoCapture(0) #0-webcam, displays what is showing on the webcam\n font = opencv.FONT_HERSHEY_COMPLEX_SMALL #sets the font\n count=0\n score=0\n thickness=2\n\n lbl = None\n\n while(True):\n rpred=0\n lpred=0\n\n ret, frame = cap.read() #ret - true/false whether it was able to read the file or not, frame - one frame object\n \n if ret==False:\n continue\n \n height,width = frame.shape[:2] \n\n gray = opencv.cvtColor(frame, opencv.COLOR_BGR2GRAY) #converting video to grayscale\n\n\t#Scale factor reduceing the size of the face by 10% at each iteration\n faces = list(face.detectMultiScale(gray,minNeighbors=5,scaleFactor=1.1,minSize=(25,25)))\n \n \n\t#if face is found\n if len(faces)!=0:\n\n faces.sort(key = lambda f:f[2]*f[3])\n \n #x, y are the starting coordinates of the face window and w, h are the width and height resp.\n x,y,w,h = faces[-1]\n\n opencv.rectangle(frame, (x,y) , (x+w,y+h) , (100,100,100) , 1 )\n\n cropped_face = frame[y:y+h,x:x+w]\n\n #using only the face rectangle to detect the eyes\n left_eye = leye.detectMultiScale(cropped_face)\n right_eye = reye.detectMultiScale(cropped_face)\n\n opencv.rectangle(frame, (0,height-50) , (200,height) , (0,0,0) , thickness=opencv.FILLED ) #draws a rectangle on the image for score and label\n\n if len(right_eye)!=0:\n x,y,w,h = right_eye[0]\n r_eye=cropped_face[y:y+h,x:x+w]\n count=count+1\n r_eye = opencv.cvtColor(r_eye,opencv.COLOR_BGR2GRAY)\n r_eye = opencv.resize(r_eye,(24,24))\n r_eye= r_eye/255\n r_eye= r_eye.reshape(24,24,-1)\n r_eye = np.expand_dims(r_eye,axis=0)\n rpred = np.argmax(model.predict(r_eye), axis=-1)\n if(rpred==1):\n lbl='Open' \n if(rpred==0):\n lbl='Closed'\n\n if len(left_eye)!=0:\n x,y,w,h = left_eye[0]\n l_eye=cropped_face[y:y+h,x:x+w]\n count=count+1\n l_eye = opencv.cvtColor(l_eye,opencv.COLOR_BGR2GRAY) \n l_eye = opencv.resize(l_eye,(24,24))\n l_eye= l_eye/255\n l_eye=l_eye.reshape(24,24,-1)\n l_eye = np.expand_dims(l_eye,axis=0)\n lpred = np.argmax(model.predict(l_eye), axis=-1)\n if(lpred==1):\n lbl='Open' \n if(lpred==0):\n lbl='Closed'\n\n if(rpred==0 and lpred==0):\n score += 1\n opencv.putText(frame,\"Closed\",(10,height-20), font, 1,(255,255,255),1,opencv.LINE_AA)\n # if(rpred[0]==1 or lpred[0]==1):\n else:\n if score > start_score*2:\n score -= 2\n else:\n score -= 1\n opencv.putText(frame,\"Open\",(10,height-20), font, 1,(255,255,255),1,opencv.LINE_AA)\n\n\n if(score<0):\n score=0\n \n opencv.putText(frame,'Score:'+str(score),(100,height-20), font, 1,(255,255,255),1,opencv.LINE_AA)\n \n if(score<=stop_score):\n buzzer.stop()\n if(score>=start_score):\n #person is feeling sleepy so we beep the alarm\n# opencv.imwrite(os.path.join(path,'image.jpg'),frame) #saves one frame on the device\n try:\n buzzer.play()\n except:\n pass\n if(thickness<16):\n thickness= thickness+2\n else:\n thickness=thickness-2\n if(thickness<2):\n thickness=2\n opencv.rectangle(frame,(0,0),(width,height),(0,0,255),thickness) #draws a rectangle\n \n if opencv.waitKey(1) & 0xFF == ord('q'): #when q is pressed then capturing will terminate\n break\n \n ret, buffer = opencv.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') # concat frame one by one and show result\n # opencv.imshow('frame',frame) #displays on the screen what is being captured by the webcam\n\n cap.release()\n opencv.destroyAllWindows()\n \n\nif __name__ == \"__main__\":\n drive()\n","sub_path":"drowsiness_detection.py","file_name":"drowsiness_detection.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229277201","text":"# -*- coding: utf-8 -*-\n'''4/3/20\nModifying old version of the Acqiris object that ran off of the C driver to use \nthe new python beta version of the driver from acqiris.\n\ncard = Acqiris(hardwareAddress) '''\n\nimport ctypes\n\n\n# import comtypes\nimport os\nimport time\n#import subprocess\n\n#import re\nimport scipy\nimport pylab\n#import tarfile\n#import struct\n#import glob\nimport numpy\nimport time\n\n#import pickle\n#import datetime\n#import itertools\nimport sys\nimport warnings\n\n\n#import AqMD3 as driver #this is the Acqiris python driver\nimport AqMD3\n\nInstrumentFolderPath = r'C:\\Users\\Kollarlab\\Desktop\\Kollar-Lab\\Control'\nif not InstrumentFolderPath in sys.path:\n sys.path.append(InstrumentFolderPath)\n\n\nfrom userfuncs import freeze\n\n@freeze\nclass Acqiris(object):\n \n def __init__(self, ResourceName, simulate = False): \n self.instrument_type = 'Acqiris'\n \n #look to the right place.\n IVIbinPath = \"C:\\\\Program Files\\\\IVI Foundation\\\\IVI\\\\Bin\\\\\"\n \n if not IVIbinPath in sys.path:\n sys.path.append(IVIbinPath)\n \n self.settingsCurrent = False\n \n \n self._fillHardwareKeys()\n \n \n self.simulate = simulate #python for whether we want to simulate or not\n #perperty simulateMode will come from the driver.\n \n self.hardwareAddress = ResourceName\n# self.ReInitialize()\n \n #in the python version, there seems to be an issue with reinitializing an already\n #existing instnace of the driver. It causes an error that the sample clocks are unstable\n #or something about mising TDC curves. Running close before reinitializing it seems to allow\n #things to work. So, putting this try in here in case the object card already exists.\n try:\n self.Close()\n except:\n pass\n self.InitializeDriver()\n \n #set default values. Eventually this should probably load from some default config file\n self._loadDefaultConfig()\n \n #push the currently stored settings to the card and calibrate. Hopefully ths will actually save hassle.\n #if this is running at _init_ then it will push the defaults\n self.SetParams()\n try:\n self.SelfCalibrate()\n except:\n #most likely cause of failure at this point is either that funny\n #pll synching issue, or the absence of an external clock.\n if self._clockSource == 'External':\n warnings.warn('External Clock Failure. Booting in Internal Mode.', RuntimeWarning )\n self.clockSource = 'Internal'\n self.SelfCalibrate()\n else:\n warnings.warn('Self Calibrate Failed: Cause Unkown.', RuntimeWarning )\n \n \n #some flags for controlling the read\n self.armed = False\n self.acquisitionFinished = False\n \n# self._fill_slots()\n #declare some attributes that will be needed later\n #because class is prozen they need to exist from the get go.\n self.offsetWithinRecord = 0\n self.totalSamples = self.samples\n self._simulateMode = self.simulate \n temp = self.GetParams()\n temp['timeout'] = self.timeout\n temp['verbose'] = self.verbose\n self.settings = temp\n \n# ##############################\n #hardware properties\n \n \n #master hardware settings parameter, to be used for\n #saving, and printing\n #includes what yout would need to reset to a particular configuration\n #but not changeable things like run time flags or hardware address.\n @property\n def settings(self):\n ''' getts all the settings needed to save or initialize a python card\n object. So, it calls GetParams to get the hardware level settings. \n It adds a couple more like timeout and verbose that don't exist at the lowest level.\n \n For looking at amtching function names, this makes something more like a configuration\n getten from LoadConfig or _laodDefaultConfig\n \n '''\n paramsDict = self.GetParams()\n paramsDict['timeout'] = self.timeout #timeout is an argument \n #of a driver level function, not a driver level parameter, so \n #it is not gotten in get params\n paramsDict['verbose'] = self.verbose #added this so that this\n #has exactly the same fields as the default config.\n #Python object can therfore boot from this drictionary.\n return paramsDict \n @settings.setter\n def settings(self,val):\n self.LoadConfig(val) #load config checks for invalid fields\n \n #icky properties that have to be batch set\n @property\n def sampleRate(self): #this one might not need to be here, but I did it already\n val = self.driver.Acquisition.SampleRate\n self._sampleRate = val\n return val\n @sampleRate.setter\n def sampleRate(self,val):\n self.settingsCurrent = False\n self._sampleRate = val \n \n @property\n def samples(self):\n val = self.driver.Acquisition.RecordSize\n self._samples = val\n return val\n @samples.setter\n def samples(self,val):\n self.settingsCurrent = False\n self._samples = val \n\n @property\n def segments(self):\n val = self.driver.Acquisition.NumberOfRecordsToAcquire\n self._segments = val\n return val\n @segments.setter\n def segments(self,val):\n self.settingsCurrent = False\n self._segments = val \n \n @property\n def averageMode(self):\n val = self.driver.Acquisition.Mode\n self._averageMode = val\n return val\n @averageMode.setter\n def averageMode(self,val):\n self.settingsCurrent = False\n self._averageMode = val \n\n @property\n def averages(self):\n val = self.driver.Acquisition.NumberOfAverages\n self._averages = val\n return val\n @averages.setter\n def averages(self,val):\n self.settingsCurrent = False\n self._averages = val \n if val > 1:\n self.averageMode = 1\n else:\n self.averageMode = 0\n \n \n #I hope that this one can be a regular property, but I'm not sure\n #might run into trouble with limits in avergaing mode\n @property\n def activeChannels(self):\n #have to check what it enabled and convert\n val = self.driver.Channels[0].Enabled\n val2 = self.driver.Channels[1].Enabled\n flags = numpy.asarray([val,val2])\n inds = numpy.where(flags == True)[0]\n full = numpy.asarray([1,2])\n actives = full[inds]\n self._activeChannels = actives\n return actives\n @activeChannels.setter\n def activeChannels(self,val):\n if (type(val) == int) or (type(val) == float):\n val = [val]\n if not val[0] == 1:\n raise ValueError('Active channels needs to be either 1, [1], or [1,2].')\n if len(val) > 1:\n if not val[1] == 2:\n raise ValueError('Active channels needs to be either 1, [1], or [1,2].')\n if len(val)>2:\n raise ValueError('Only two channels')\n self.settingsCurrent = False\n self._activeChannels = val\n\n\n \n \n #normal properties that I think can be set reasonably.\n @property\n def triggerSource(self):\n val = self.driver.Trigger.ActiveSource\n self._triggerSource = val\n return val\n @triggerSource.setter\n def triggerSource(self,val):\n self._triggerSource = val\n self.driver.Trigger.ActiveSource = val \n\n @property\n def triggerLevel(self):\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n val = activeTrigger.Level\n self._triggerLevel = val\n return val\n @triggerLevel.setter\n def triggerLevel(self,val):\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n self._triggerLevel = val\n activeTrigger.Level = val \n \n @property\n def triggerSlope(self):\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n temp = activeTrigger.Edge.Slope\n# self._triggerSlope = temp\n if temp == 0:\n val = 'Falling'\n elif temp == 1:\n val = 'Rising'\n else:\n raise ValueError(\"Unkown trigger slope returned\")\n self._triggerSlope = val\n return val\n @triggerSlope.setter\n def triggerSlope(self,val):\n if val == 'Falling':\n triggerSlopeC = 0\n elif val == 'Rising':\n triggerSlopeC = 1\n else:\n raise ValueError(\"Edge trigger slope must be either 'Rising' or 'Falling'\")\n# self._triggerSlope = triggerSlopeC\n self._triggerSlope = val\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n activeTrigger.Edge.Slope = triggerSlopeC \n \n @property\n def triggerDelay(self):\n val = self.driver.Trigger.Delay\n self._triggerDelay = val\n return val\n @triggerDelay.setter\n def triggerDelay(self,val):\n self._triggerDelay = val\n self.driver.Trigger.Delay = val \n \n @property\n def triggerCoupling(self):\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n val = activeTrigger.Coupling\n self._triggerCoupling = val\n return val\n @triggerCoupling.setter\n def triggerCoupling(self,val):\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n self._triggerCoupling = val\n activeTrigger.Coupling = val\n \n \n \n# @property\n# def channelRange(self):\n# #have to check what it enabled and convert\n# val = self.driver.Channels[0].Range\n# val2 = self.driver.Channels[1].Range\n# if not val == val2:\n# print('Warning: Range set differently on the two channels')\n# return val\n# @channelRange.setter\n# def channelRange(self,val):\n# if val in [0.5, 2.5]:\n# self.driver.Channels[0].Range = val\n# self.driver.Channels[1].Range = val\n# else:\n# raise ValueError('Range must be 0.5 or 2.5')\n \n# @property\n# def channelOffset(self):\n# #have to check what it enabled and convert\n# val = self.driver.Channels[0].Offset\n# val2 = self.driver.Channels[1].Offset\n# if not val == val2:\n# print('Warning: Offset set differently on the two channels')\n# return val\n# @channelOffset.setter\n# def channelOffset(self,val):\n# self.driver.Channels[0].Offset = val\n# self.driver.Channels[1].Offset = val\n \n @property\n def channelRange(self):\n #have to check what it enabled and convert\n val = self.driver.Channels[0].Range\n val2 = self.driver.Channels[1].Range\n self._channelRange = numpy.asarray([val, val2]) #store the basic range\n #for both channels under the hood\n if val == val2:\n #two channels set the same, use one only\n return val\n else:\n return numpy.asarray([val, val2])\n @channelRange.setter\n def channelRange(self,val):\n if type(val) == float:\n #only single value specified\n self._channelRange = numpy.asarray([val, val])\n if val in [0.5, 2.5]:\n self.driver.Channels[0].Range = val\n self.driver.Channels[1].Range = val\n else:\n raise ValueError('Range must be 0.5 or 2.5') \n elif (type(val) == float) or (type(val) == numpy.ndarray) :\n #given an array or list of values\n if len(val) == 2:\n if (val[0] in [0.5, 2.5]) and (val[1] in [0.5, 2.5]):\n self.driver.Channels[0].Range = val[0]\n self.driver.Channels[1].Range = val[1]\n else:\n raise ValueError('Range must be 0.5 or 2.5') \n else:\n raise ValueError('Array too long. Only two channels.') \n\n @property\n def channelOffset(self):\n #have to check what it enabled and convert\n val = self.driver.Channels[0].Offset\n val2 = self.driver.Channels[1].Offset\n self._channelOffset = numpy.asarray([val,val2])\n if not val == val2:\n print('Warning: Offset set differently on the two channels')\n return val\n @channelOffset.setter\n def channelOffset(self,val):\n self.driver.Channels[0].Offset = val\n self.driver.Channels[1].Offset = val\n self._channelOffset = numpy.asarray([val,val])\n \n \n \n @property\n def simulateMode(self):\n val = self.driver.DriverOperation.Simulate\n self._simulateMode = val\n return val\n @simulateMode.setter\n def simulateMode(self,val): #be very wary just trrying to set this blindly.\n self.driver.DriverOperation.Simulate = val \n self._simulateMode = val\n \n\n @property\n def clockSource(self):\n temp = self.driver.ReferenceOscillator.Source\n if temp == 0:\n val = 'Internal'\n elif temp == 1:\n val = 'External'\n else:\n raise ValueError(\"Unkown clock source returned\")\n self._clockSource = val\n return val\n @clockSource.setter\n def clockSource(self,val):\n if val == 'Internal':\n sourceC = 0\n elif val == 'External':\n sourceC = 1\n else:\n raise ValueError(\"Edge clock source. Must be either 'Internal' or 'External'\")\n self._clockSource = val\n self.driver.ReferenceOscillator.Source = sourceC\n \n @property\n def clockFrequency(self):\n val = self.driver.ReferenceOscillator.ExternalFrequency\n if self.verbose:\n if self.clockSource == 'Internal':\n print('Internal Clock. Frequency Setting Ignored (I think).')\n if not val == 10**7:\n print('Warning: Clock frequency is not set to 10 MHz.')\n self._clockFrequency = val\n return val\n @clockFrequency.setter\n def clockFrequency(self,val): #be very wary just trrying to set this blindly.\n if self.verbose:\n if self.clockSource == 'Internal':\n print('Internal Clock. Frequency Setting Ignored (I think).')\n if not val == 10**7:\n raise ValueError('Clock frequency must be 10 MHz?')\n self._clockFrequency = val\n self.driver.ReferenceOscillator.ExternalFrequency = val \n\n\n \n# \n# #############################\n# \n \n def SetParams(self, params = {}):\n '''Autoinititalize function that will set up the card with all the driver\n parameters stored in this object. It will push all the settings and do cross checks.\n \n This function loads all the settings to the card, so it sets up the trigger and the\n data acquisition channels. Then it calls Configure Acquisition to set up things\n like averaging and sample/sample rate\n \n params is an optional settings dictionary that can be used set everything at the python level'''\n \n fields = params.keys()\n if not len(fields) == 0:\n self.LoadConfig(params)\n \n #configure the trigger\n# self.ConfigureTrigger(Source = self.triggerSource, Level = self.triggerLevel, Slope = self.triggerSlope, Mode = self.triggerMode)\n self.ConfigureTrigger(Source = self._triggerSource, Level = self._triggerLevel, Slope = self._triggerSlope, Mode = self.triggerMode)\n \n #configure the channels:\n for chind in [1,2]:\n if chind in self._activeChannels: #need the underscore here so it takes the python value and then sets up hardware to match\n enabled = True\n else:\n enabled= False\n self.ConfigureChannel(channelNum = chind, Range = self._channelRange, offset = self.channelOffset, enabled = enabled)\n \n #configure the acquisition\n# self.ConfigureAcquisition(self.samples, self.sampleRate, self.segments)\n self.ConfigureAcquisition(self._samples, self._sampleRate, self._segments)\n \n self.settingsCurrent = True\n \n def GetParams(self):\n '''Autoget function for params. Will querry the hardware and package all the settings, as well as \n update the fields of the python software object.\n \n In order to fully initialize or save a python Acqiris object, you will need the @settings\n property. This incorporates the hardware-level settings and a couple more. (but still no\n run time flags or things like that.)'''\n \n hardwareSettings= {}\n \n if self.verbose:\n print(' ')\n \n# hardwareSettings = {}\n for key in self.hardwareKeys:\n \n #If these are all properties, then I can do this like this\n val = getattr(self,key)\n \n #store everything away\n setattr(self, key, val)\n hardwareSettings[key] = val\n \n #print all the results \n if self.verbose:\n print(key + ' : ' + str(val))\n \n if self.verbose:\n print(' ')\n \n# return\n return hardwareSettings\n \n \n def Close(self): \n self.driver.Close()\n \n def SelfCalibrate(self):\n print('Calibrating...')\n self.driver.Calibration.SelfCalibrate()\n\n ##################################################\n \n def Abort(self):\n '''Abort a hung acquisition '''\n self.driver.Acquisition.Abort()\n \n def Arm(self):\n '''Initialize the acquisition and get ready to take and read data.\n Tells the card to get ready and wait for triggers.\n \n Unlike it big brother ArmAndWait, this function will allow python to \n do stuff while the card is waiting for a trigger. E.g. start up the\n AWG so that it actually delivers said triggers.\n \n Note: If this is used instead of ArmAndWait, then WaitForAcquisition will\n need to be called at some point so that the card realizes that it is done.\n ReadData has been modified so that it should take care of this automatically,\n but FYI.\n \n '''\n #check if the settings are up to date\n if not self.settingsCurrent: \n print('Warning: Python contains stale settings.')\n print('Pushing current settings.')\n self.SetParams()\n \n if self.driver.Calibration.IsRequired:\n if self.verbose:\n print('Calibration needed before acquisition. Doing it.')\n self.SelfCalibrate()\n self.InitiateAcquisition()\n \n# time.sleep(0.1) #putting in a pause to see if that stops the clocks from being unhappy. Nope.\n# try:\n# self.InitiateAcquisition()\n# except:\n# time.sleep(5)\n# print('Waiting for clocks to stabilize?') #hopefully this fixes stuff\n# self.InitiateAcquisition()\n \n def ArmAndWait(self):\n '''Initialize the acquisition and get ready to take and read data.\n Tells the card to get ready and wait for triggers, and then waits \n for it to finish.\n \n This version works fine if the AWG is already setup and running, but it will\n cause python to hang until the acqusition is finished. So, you will not be able\n to do anything, and that includes starting up the AWG to have it give the \n card triggers. So, this function should only be used if the card is triggered\n off an external generator, not the AWG.\n '''\n self.Arm()\n self.WaitForAcquisition()\n \n \n def ConfigureAcquisition(self, samples, sampleRate, segments = 1):\n ''''Configure Acquistion function that gets everything ready for data taking.\n# Does more than the equivelent C function.\n \n Test version of configure acquisition. Trying to use the built in function of the C\n driver and not manually setting all the variables.'''\n \n self.sampleRate = sampleRate\n\n self.segments = segments\n \n\n# #software needs to know at this point so that it can adjust the number of samples\n# #I can't write to the driver here because old number of samples could still be\n# #large from a non-averaged run.\n \n #turn off averaging in hardware so that it doesn't muck with setting the number of samples.\n #This is necessary when switching back from averaging mode.\n self.driver.Acquisition.Mode = 0\n self.driver.Acquisition.NumberOfAverages = 1\n #using this low-level hack isntead of ConfigureAveraging, because at this point, python needs\n #to know about averaging, but the hardware needs to always not be in averaging mode, so that \n #it can take a large number of samples if the upcoming acqusition is going to be in regular mode.\n #whereas the software needs to adjust the limit on the number of samples if the upcoming acquisition\n # is going to be in averaging mode.\n \n \n if self.verbose:\n print('Setting acquisition parameters manually.')\n print('Samples will shorten if too long for avg mode.')\n# print('Sample will autoround to a multiple of 1024 and shorten if to long for avg mode.')\n ###!!!!!!!!!!!!!\n #!!!!!!!!!empircally, record size must be 1024*n, and the largest that it can be is 513*1024\n #roughly 500 kS. Which is what the mnual says, but this sucks. Did the old Acqiris do this?\n #or is it just that the ME is only for non-averaging mode?\n multiple = int(numpy.ceil(self._samples/1024))\n if self._averages > 1:\n #check the number of channels\n numChans = len(self._activeChannels)\n if numChans == 1:\n maxSamples = 1024*1024\n else:\n maxSamples = 1024*512\n \n if self._samples > maxSamples:\n print('Data is too long for averaging mode. Setting to max length: 512*1024')\n self.samples = int(maxSamples)\n \n# if multiple*1024 > maxSamples:\n# print('Data is too long for averaging mode. Setting to max length: 512*1024')\n# self.samples = int(maxSamples)\n# else:\n# #auto round to next multiple of 1024 up, regardless\n# self.samples = int(multiple*1024) \n# #it is very important that this winds up an integer, or it least it was at some point\n \n #it looks like now that we have the order of operations right between configuring\n #the acquisition and turning averaging on and off, so that we can use the\n #built in C function for configuring, that we might not need this multiple of 1024 check.\n #But we do need the auto check that turns down the number of samples if its averaging mode\n \n# self.driver.Acquisition.ConfigureAcquisition(int(self.segments), int(self.samples), self.sampleRate)\n self.driver.Acquisition.ConfigureAcquisition(int(self._segments), int(self._samples), self._sampleRate)\n \n #configure the the actual averaging mode and restore number of averages\n self.ConfigureAveraging() #trip the flags to handle the averaging\n #(both in python and sending down to the hardware driver.)\n #Hopefully doing it after everything else is set will only try to flip to averager \n #after the number of samples has been reduced.\n\n\n def ConfigureAveraging(self):\n if self._averages >1:\n self.averageMode = 1 #make sure this variable is conistent. I probably want to do away with it eventually\n else:\n self.averageMode = 0\n# self.driver.Acquisition.Mode = self.averageMode \n# self.driver.Acquisition.NumberOfAverages = self.averages\n self.driver.Acquisition.Mode = self._averageMode \n self.driver.Acquisition.NumberOfAverages = self._averages\n\n def ConfigureChannel(self, channelNum = 1, Range = 2.5, offset = 0, enabled = True):\n '''Configure channel function.\n \n Meant to becalled by configure acquisiton, but can be called manually.\n If it is called mnaually, it will write it's inputs to the driver settings.\n '''\n\n if channelNum in [1,2]:\n pass\n else:\n raise ValueError('Invalid channel. Should be 1 or 2')\n \n# if Range in [0.5, 2.5]: #changed to a property, so this is checked elsewhere\n# self.channelRange = Range\n# else:\n# raise ValueError('Range must be 0.5 or 2.5')\n \n self.channelRange = Range\n self.channelOffset = offset\n\n couplingC = 1 # 1 = DC coupling. Always. Card can't do AC.\n\n chan = self.driver.Channels[int(channelNum-1)] #python channels are index from 0\n chan.Configure(self._channelRange[int(channelNum-1)], self.channelOffset, couplingC, enabled)\n \n def ConfigureTrigger(self, Source = 'External1', Level = 0, Slope = 'Falling', Mode = 'Edge'):\n if Mode != 'Edge':\n raise ValueError('This trigger mode not yet supported. Edge trigger only.')\n else:\n self.triggerMode = Mode\n self.triggerSource = Source\n self.triggerLevel = Level\n \n if Slope == 'Falling':\n self.triggerSlope = Slope\n triggerSlopeC = 0\n elif Slope == 'Rising':\n self.triggerSlope = Slope\n triggerSlopeC = 1\n else:\n raise ValueError(\"Edge trigger slope must be either 'Rising' or 'Falling'\")\n \n self.driver.Trigger.Delay = self.triggerDelay\n\n\n #manually set trigger source because the configure function doesn't actually do it.\n self.driver.Trigger.ActiveSource = self.triggerSource\n \n\n #self.driver.Trigger.Sources[self.triggerSource].Coupling, but I think this always has to be 1\n# self.driver.Trigger.Sources[self.triggerSource].Coupling = self.triggerCoupling\n \n #couldn't find a configure trigger function in the python. Just set all the fields instead\n activeTrigger = self.driver.Trigger.Sources[self.triggerSource]\n activeTrigger.Level = self.triggerLevel\n activeTrigger.Edge.Slope = triggerSlopeC \n \n \n \n def _fillHardwareKeys(self):\n ''' Storing the names of the harware level vairables. '''\n \n self.driverKeys = []\n self.driverKeys.append('driverDescription')\n self.driverKeys.append('driverRevision')\n self.driverKeys.append('firmwareRevision')\n self.driverKeys.append('manufacturer')\n self.driverKeys.append('instrumentModel')\n self.driverKeys.append('serialNumber')\n \n \n \n\n self.hardwareKeys = []\n self.hardwareKeys.append('channelOffset')\n self.hardwareKeys.append('channelRange')\n# self.hardwareKeys.append('channelEnabled') #removed for better syntax\n self.hardwareKeys.append('activeChannels')\n \n self.hardwareKeys.append('triggerSource')\n self.hardwareKeys.append('triggerLevel')\n# self.hardwareKeys.append('triggerMode') #I don't think we can change this one\n self.hardwareKeys.append('triggerSlope')\n self.hardwareKeys.append('triggerDelay')\n self.hardwareKeys.append('triggerCoupling')\n \n self.hardwareKeys.append('averageMode')\n self.hardwareKeys.append('averages')\n \n self.hardwareKeys.append('samples')\n self.hardwareKeys.append('segments')\n \n self.hardwareKeys.append('sampleRate')\n \n self.hardwareKeys.append('simulateMode')\n \n self.hardwareKeys.append('clockFrequency')\n self.hardwareKeys.append('clockSource')\n \n# self.hardwareKeys.append('timeout') #i don't know how to get this from the hardware, so it's a software setting\n \n def _fill_slots(self):\n firstRound = list(self.__dict__.keys()) #this gets all of the normal attributes, but it doesn't handle the properties\n propertyKeys = self.hardwareKeys\n \n self.__slots__ = firstRound + propertyKeys\n \n def _generateConfig(self):\n '''Make a dictionary of the hardware settings and a couple of useful flags.\n \n As it currently stands it will try to get the settings from the hardware\n and ignore the python shadow copies.\n \n This will hopefully be the basis for saving and loading.\n '''\n params = {}\n for key in self.hardwareKeys:\n val = getattr(self,key)\n params[key] = val\n \n #a couple of the python software settings need to go too.\n params['verbose'] = self.verbose\n params['timeout'] = self.timeout\n params['simulate'] = self.simulate\n return params\n \n \n def InitializeDriver(self):\n '''Basic init function. Creates the driver.'''\n print('Initializing...')\n if self.simulate == True:\n strInitOptions = 'Simulate=True, DriverSetup= model = SA220P'\n else:\n strInitOptions = 'Simulate=False, DriverSetup= model = SA220P'\n \n self.driver = AqMD3.AqMD3( self.hardwareAddress , False, False, strInitOptions)\n \n\n def InitiateAcquisition(self):\n ''' Tells the hardware to start looking for data.\n This is a relatively low-level hardware function.\n User-friendly version with more checks and balances\n is the wrappers Arm and ArmAndWait.'''\n self.driver.Acquisition.Initiate()\n self.armed = True #throw flag so that python knows acquisition has been itiated\n #and system is waiting for trigger.\n \n def LoadConfig(self, params):\n ''' Takes in a dictionary of settings and loads them into this python\n class. Those that are normal properties will get set to hardware.\n The icky properties will not get set until a call to SetParams is made,\n either by the user, or when the flag is tripped in Arm\n '''\n for key in params.keys():\n bool1 = key in self.__dict__.keys()\n bool2 = ('_' + key) in self.__dict__.keys()\n if not (bool1 or bool2):\n# raise ValueError('invalid setting key : ' + str(key))\n warnings.warn('Warning: Invalid setting key : ' + key, RuntimeWarning)\n# print('Warning: setting key : ' + key)\n else:\n setattr(self, key, params[key])\n \n def _loadDefaultConfig(self):\n #diagnostic prints\n self.verbose = False #this needs to be first because it effects how properties below it act\n \n #sampling\n self.samples = 1024\n self.sampleRate = 1*10**9\n \n #averaging\n self.averageMode = 0\n self.averages = 1\n \n #multisegment acquisition\n self.segments = 1\n \n #channel settings\n self.activeChannels = [1,2]\n self.channelRange = 2.5\n self.channelOffset = 0\n \n #trigger settings\n self.triggerSource = 'External1'\n self.triggerMode = 'Edge' #this thing should maybe go away.\n self.triggerLevel = 0\n self.triggerSlope = 'Rising'\n self.triggerDelay = 0\n self.triggerCoupling = 1 #1 for DC, 0 for AC. I think it must always be DC, at least on external\n \n #clock settings\n self.clockSource = 'External'\n# self.clockSource = 'Internal'\n self.clockFrequency = 10**7\n \n #timeout of failed acquisitions\n self.timeout = 5 #seconds\n \n def Print(self):\n '''Print the most important settings. \n Will not show the run time flags and stuff like this.'''\n params = self._generateConfig()\n print()\n for key in params.keys():\n print(key + ' : ' + str(params[key]))\n print()\n \n def ReadAllData(self, returnRaw = False, returnTwoArrays = True):\n ''' Highest level read function. Will automatically read all active\n channels.\n \n Will trip flags when it is done that the data acquisition and read are complete\n \n if returnTwoArrays is true, then it will alwyas return two data arrays, even if channel \n two is turned off. But it will return an empty array for the inactive channel\n '''\n #check if the card is done. \n #NOTE: Card needs to be asked if its done, or it will get mad, even if it is actually done\n if self.armed:\n #there was an active acquisition\n if not self.acquisitionFinished:\n #need to confirm with the card that it is done.\n #(this will already have happened if you used ArmAndWait, but not if you use Arm)\n self.WaitForAcquisition()\n else:\n raise ValueError(\"Cannot read data. Card acquisition hasn't happened.\")\n \n \n# data1 = []\n# data2 = []\n if len(self._activeChannels) > 1:\n data1 = self.ReadData(1, returnRaw = returnRaw)\n data2 = self.ReadData(2, returnRaw = returnRaw)\n #notify the python that this acquisition is done\n self.armed = False\n self.acquisitionFinished = False\n return data1, data2\n else:\n data = self.ReadData(self._activeChannels[0], returnRaw = returnRaw)\n data_blank = numpy.zeros((0,0))\n #notify the python that this acquisition and read are done\n self.armed = False\n self.acquisitionFinished = False\n if returnTwoArrays:\n return data, data_blank\n else:\n return data\n\n def ReadData(self, chanNum, returnRaw = False):\n '''Single channel data read function.\n Will automatically call lowerlevel read functions of the driver,\n depending on how the card is set up.\n\n Somewhat intended as a hidden internal function of ReadAllData, so\n it may not do the safety checks as well as it's parent because they are \n harder to manage when each channel is called separately.\n \n This single channel read function is not protected against reading the same dat twice,\n as least not at the Kollar-lab python level.\n \n '''\n #check if the card is done. (Ideally this happens in ReadAllData, but it channels are\n #being called individually, then it may need to happen here.)\n #NOTE: Card needs to be asked if its done, or it will get mad, even if it is actually done\n #WaitForAcquisition MUST happen before the hardware-level reads.\n if self.armed:\n #there was an active acquisition\n if not self.acquisitionFinished:\n #need to confirm with the card that it is done.\n #(this will already have happened if you used ArmAndWait, but not if you use Arm)\n self.WaitForAcquisition()\n else:\n raise ValueError(\"Cannot read data. Card acquisition hasn't happened.\")\n \n if chanNum in [1,2]:\n pass\n else:\n raise ValueError('Invalid channel. Should be 1 or 2')\n \n self.offsetWithinRecord = 0\n numSamples = self.driver.Acquisition.QueryMinWaveformMemory(64, int(self.segments), int(self.offsetWithinRecord), \\\n int(self.samples))\n if self.verbose:\n print('Memeory Allocation Determined')\n \n self.totalSamples = numSamples\n\n if self.verbose:\n print('Trying to Read')\n if self.averageMode:\n out = self._ReadAveragerData(chanNum, returnRaw = returnRaw)\n else:\n if self.segments > 1:\n out = self._ReadMultiSegData(chanNum, returnRaw = returnRaw)\n else:\n out = self._ReadSingleSegData(chanNum, returnRaw = returnRaw)\n \n\n return out\n \n def _ReadAveragerData(self,chanNum, returnRaw = False):\n if self.verbose:\n print('reading averaged data')\n \n channel = self.driver.Channels[int(chanNum - 1)]\n \n \n waveformObj = channel.Measurement.FetchAccumulatedWaveform(firstRecord = 0,\\\n numberOfRecords = int(self.segments),\\\n offsetWithinRecord = int(self.offsetWithinRecord), \\\n numberOfPointsPerRecord = int(self.samples)) \n\n if self.verbose:\n print('Fetch Complete. Processing Data.')\n \n# if self.segments == 1:\n# rawData = numpy.zeros( self.samples)\n# waveform = waveformObj[0]\n# rawData[:] = waveform.Samples* waveform.ScaleFactor + waveform.ScaleOffset\n# else:\n# rawData = numpy.zeros((self.segments, self.samples))\n# for segind in range(0, self.segments):\n# waveform = waveformObj[segind]\n# rawData[segind,:] = waveform.Samples* waveform.ScaleFactor + waveform.ScaleOffset\n \n #always get matrix shaped data\n rawData = numpy.zeros((self.segments, self.samples))\n for segind in range(0, self.segments):\n waveform = waveformObj[segind]\n rawData[segind,:] = waveform.Samples* waveform.ScaleFactor + waveform.ScaleOffset\n \n \n if waveformObj[0].ActualSamples != self.samples:\n print(\"Warning. Data size doesn't match the number of samples. Something wierd happened.\")\n \n if returnRaw:\n out = [rawData, waveformObj]\n return out\n else:\n data = rawData\n if self.verbose:\n print('Data Processed.')\n return data\n \n def _ReadMultiSegData(self,chanNum, returnRaw = False):\n '''Python function for reading non-averaged multisegment data. '''\n if self.verbose:\n print('reading non-averaged, multisegment data')\n \n if not (chanNum in[1,2]):\n raise ValueError('Channel number must be 1 or 2.')\n \n channel = self.driver.Channels[int(chanNum - 1)]\n \n \n waveformObj = channel.MultiRecordMeasurement.FetchMultiRecordWaveform(firstRecord = 0,\\\n numberOfRecords = int(self.segments),\\\n offsetWithinRecord = int(self.offsetWithinRecord), \\\n numberOfPointsPerRecord = int(self.samples))\n if self.verbose:\n print('Fetch Complete. Processing Data.')\n \n rawData = numpy.zeros((self.segments, self.samples))\n for segind in range(0, self.segments):\n waveform = waveformObj[segind]\n rawData[segind,:] = waveform.Samples* waveform.ScaleFactor + waveform.ScaleOffset\n \n if waveformObj[0].ActualSamples != self.samples:\n print(\"Warning. Data size doesn't match the number of samples. Something wierd happened.\")\n \n if returnRaw:\n out = [rawData, waveformObj]\n return out\n else:\n data = rawData\n if self.verbose:\n print('Data Processed.')\n return data\n\n def _ReadSingleSegData(self,chanNum, returnRaw = False):\n '''Python read function for single segment data that is not averaged '''\n if self.verbose:\n print('reading non-averaged, single-segment data')\n \n if not (chanNum in[1,2]):\n raise ValueError('Channel number must be 1 or 2.')\n \n channel = self.driver.Channels[int(chanNum - 1)]\n \n waveformObj = channel.Measurement.FetchWaveform()\n \n if self.verbose:\n print('Fetch Complete. Processing Data.')\n \n \n rawData = numpy.asarray(waveformObj.Samples*waveformObj.ScaleFactor+ waveformObj.ScaleOffset)\n \n if waveformObj.ActualSamples != self.samples:\n print(\"Warning. Data size doesn't match the number of samples. Something wierd happened.\")\n \n if returnRaw:\n out = [rawData, waveformObj]\n return out\n else:\n #always make matrix shaped data to be compatible with the other read functions\n data = numpy.zeros((1, len(rawData)))\n data[0,:] = rawData\n if self.verbose:\n print('Data Processed.')\n return data\n \n def ReInitialize(self):\n '''Basic init function. Can also be used to wipe he settings if the card is very confused. \n Will push the currently stored settings to the card and calibrate'''\n try:\n #try to pull the current values of all the settings\n params = self._generateConfig()\n gotSettings = True\n except:\n gotSettings = False\n pass\n\n\n #in the python version, there seems to be an issue with reinitializing an already\n #existing instnace of the driver. It causes an error that the sample clocks are unstable\n #or something about mising TDC curves. Running close before reinitializing it seems to allow\n #things to work. So, putting this try in here to try to catch things\n try:\n self.Close()\n except:\n pass\n \n self.InitializeDriver() #this puts the driver back in a default\n #and then some of the properties act funny, because they are only stored in hardware\n #so they revert to the driver default.\n #trying to patch this by pulling the current settings, but if it's vry confuzzled,\n #this may not work. So, if that fails, I will just load the default.\n if gotSettings:\n #load rescued settings\n self.LoadConfig(params)\n else:\n #load the default if you can't get the current ones.\n self._loadDefaultConfig()\n\n \n #push the currently stored settings to the card and calibrate. Hopefully ths will actually save hassle.\n #if this is running at _init_ then it will push the defaults\n self.SetParams()\n self.SelfCalibrate()\n\n def WaitForAcquisition(self):\n '''Timeout in seconds '''\n if self.verbose:\n print('Waiting until the acquisition is done (or checking that it is) and getting confirmation')\n timeoutC = self.timeout*1000 #convert to ms\n# self.driver.Acquisition.WaitForAcquisitionComplete(timeoutC)\n# self.acquisitionFinished = True #throw the internal flag to show that the card is done.\n try:\n self.driver.Acquisition.WaitForAcquisitionComplete(timeoutC)\n self.acquisitionFinished = True #throw the internal flag to show that the card is done.\n except (RuntimeError):\n print('Acquisition probably timed out.')\n if self.verbose:\n print('Aborting to clear hung acquisition.')\n self.Abort()\n self.acquisitionFinished = False #throw the internal flag to indicate failure\n \n\n\n\nif __name__ == '__main__':\n\n hardwareAddress = \"PXI23::0::0::INSTR\"\n\n IVIbinPath = \"C:\\\\Program Files\\\\IVI Foundation\\\\IVI\\\\Bin\\\\\"\n sys.path.append(IVIbinPath)\n \n# alwaysInit = False\n alwaysInit = True\n if alwaysInit:\n print(\"Initialize instrument @\", hardwareAddress)\n card = Acqiris(hardwareAddress)\n else:\n try:\n #random driver call to see if things are set up\n# card.GetAttribute(None, AQMD3_ATTR_SIMULATE, 'ViBoolean')\n card.GetDriverAttribute('simulateMode')\n print('Card already initialized')\n except:\n print(\"Initialize instrument @\", hardwareAddress)\n card = Acqiris(hardwareAddress)\n \n \n ######\n #testing raw functions\n# card.ConfigureTrigger()\n# card.ConfigureAveraging()\n# card.ConfigureChannel(channelNum = 1, Range = 2.5, offset = 0, enabled = True)\n# card.SetParams()\n \n \n\n #####################\n #chose acquisition type\n #####################\n\n averageMode = True\n# averageMode = False\n\n multisegMode = True\n# multisegMode = False\n \n \n \n ##########\n #set settings to the card object\n ### samples = 1*10**7\n card.samples = 513*1024\n card.sampleRate = 1*10**9\n \n \n #swtich between test cases\n if averageMode:\n card.averageMode = 1\n if multisegMode:\n card.averages = 100\n card.segments = 2\n else:\n card.averages = 100\n card.segments = 1\n else:\n card.averageMode = 0\n if multisegMode:\n card.averages = 1\n card.segments = 2\n else:\n card.averages = 1\n card.segments = 1\n \n card.triggerSource = 'External1'\n card.triggerLevel = 0\n card.triggerSlope = 'Falling'\n \n card.activeChannels = [1,2]\n# card.activeChannels = [1] #it looks like single channel has to be channel 1\n \n card.timeOut = 2\n \n card.verbose = True #get lots of diagnostic print statements\n \n# card.channelRange = 0.5\n# card.channelRange = [0.5, 2.5]\n card.channelRange = numpy.asarray([0.5, 2.5])\n \n card.channelOffset = 0.1\n \n ##########\n #push settings to hardware\n card.SetParams()\n# card.ConfigureChannel(channelNum = 1, Range = 2.5, offset = 0, enabled = True)\n# card.ConfigureChannel(channelNum = 2, Range = 2.5, offset = 0, enabled = True)\n# card.ConfigureTrigger('External1', 0, 'Falling')\n# card.ConfigureAcquisition(samples, sampleRate, segments)\n\n #card.GetParams()\n \n ##########\n #initiate acquisition and wait for it to finish\n card.ArmAndWait()\n# card.Arm()\n# card.WaitForAcquisition()\n# card.WaitForAcquisition(timeOut)\n\n print('Data Acquired (In Theory)')\n\n\n \n \n# data = card.ReadData(1, returnRaw = False) #read channel 1\n# data = card.ReadData(2, returnRaw = False) #read channel 1\n data, data2 = card.ReadAllData()\n \n\n ####\n #plot data\n\n numSamples = card.samples\n sampleRate = card.sampleRate\n dt = 1/sampleRate\n xaxis = scipy.arange(0, numSamples,1)*dt\n\n if multisegMode:\n dataSegments = data.shape[0]\n\n print('Plotting.')\n\n fig1 = pylab.figure(1)\n pylab.clf()\n ax = pylab.subplot(1,1,1)\n if multisegMode:\n pylab.title('Multiseg: Active Channel')\n for segind in range(0,dataSegments ):\n labelstr = 'seg: ' + str(segind)\n pylab.plot(xaxis*1000, data[segind,:] + segind*0.125, label = labelstr)\n else:\n if averageMode:\n pylab.title('Averager: Active Channel')\n else:\n pylab.title('Singleseg: Active Channel')\n labelstr = 'seg: 0' \n pylab.plot(xaxis*1000, data[:], label = labelstr)\n ax.legend(loc = 'upper right')\n pylab.ylabel('Voltage (waterfall)')\n pylab.xlabel('Time (ms)')\n\n pylab.show()\n\n#\n# print('Done plotting.')\n# \n# # Close the instrument\n# print(\"\\nClose the instrument\") \n# card.close()\n# \n \n\n \n \n # card.offsetWithinRecord = 0\n# channel = card.driver.Channels[0]\n# if averageMode:\n# waveformObj = channel.Measurement.FetchAccumulatedWaveform(firstRecord = 0,\\\n# numberOfRecords = int(card.segments),\\\n# offsetWithinRecord = int(card.offsetWithinRecord),\\\n# numberOfPointsPerRecord = int(card.samples),\\\n# dtype=numpy.int32)\n# else:\n# if multisegMode:\n# waveformObj = channel.MultiRecordMeasurement.FetchMultiRecordWaveform(firstRecord = 0,\\\n# numberOfRecords = int(card.segments),\\\n# offsetWithinRecord = int(card.offsetWithinRecord), \\\n# numberOfPointsPerRecord = int(card.samples))\n# else:\n# waveformObj = channel.Measurement.FetchWaveform() \n \n \n \n \n \n \n ###################\n #older, cruder codes\n ################\n # # averageMode = True\n# averageMode = False\n#\n# # multisegMode = True\n# multisegMode = False\n# \n# # samples = 1*10**7\n# samples = 513*1024\n# sampleRate = 1*10**9\n \n\n# if averageMode:\n# numAverages = 100\n# segments = 1\n# card.SetAverageMode(numAverages)\n# else:\n# if multisegMode:\n# numAverages = 1\n# segments = 2\n# card.SetMultiMode()\n# else:\n# numAverages = 1\n# segments = 1\n# card.SetSingleMode()\n#\n#\n# #configure channels\n# card.activeChannels = [1,2]\n# card.ConfigureChannel(channelNum = 1, Range = 2.5, offset = 0, enabled = True)\n# card.ConfigureChannel(channelNum = 2, Range = 2.5, offset = 0, enabled = True)\n#\n# # Set active trigger source to External1\n# print('\\nSet active trigger source to External1')\n# card.ConfigureTrigger('External1', 0, 'Falling')\n#\n# # aconfigout = driverdll.AqMD3_ConfigureAcquisition(init_status.ViSession, numRecordsC, numPointsPerRecordC, sampleRateC)\n# card.ConfigureAcquisition(samples, sampleRate, segments)\n \n# # acqout = driverdll.AqMD3_InitiateAcquisition(init_status.ViSession)\n# # waitout = driverdll.AqMD3_WaitForAcquisitionComplete(init_status.ViSession,c_int32(timeouttime) )\n# try:\n# card.InitiateAcquisition()\n# except:\n# print('Initiate Failed. Trying a Calibration and Reinnitiate')\n# card.SelfCalibrate()\n# card.InitiateAcquisition()\n#\n# timeOut = 10\n# card.WaitForAcquisition(timeOut)\n#\n# print('Data Acquired (In Theory)')\n#\n#\n# # out = card.ReadData(1, returnRaw = True)\n# data = card.ReadData(1, returnRaw = False)\n#\n#\n# ####\n# #plot data\n#\n# numSamples = card.samples\n# #sampleRate = card.GetAttribute('Channel1', AQMD3_ATTR_SAMPLE_RATE, 'ViReal64')\n# sampleRate = card.GetDriverAttribute('sampleRate')\n# dt = 1/sampleRate\n# xaxis = scipy.arange(0, numSamples,1)*dt\n#\n# if multisegMode:\n# dataSegments = data.shape[0]\n#\n# print('Plotting.')\n#\n# fig1 = pylab.figure(1)\n# pylab.clf()\n# ax = pylab.subplot(1,1,1)\n# if multisegMode:\n# pylab.title('Multiseg: Active Channel')\n# for segind in range(0,dataSegments ):\n# labelstr = 'seg: ' + str(segind)\n# pylab.plot(xaxis*1000, data[segind,:] + segind*0.125, label = labelstr)\n# else:\n# if averageMode:\n# pylab.title('Averager: Active Channel')\n# else:\n# pylab.title('Singleseg: Active Channel')\n# labelstr = 'seg: 0' \n# pylab.plot(xaxis*1000, data[:], label = labelstr)\n# ax.legend(loc = 'upper right')\n# pylab.ylabel('Voltage (waterfall)')\n# pylab.xlabel('Time (ms)')\n#\n# pylab.show()\n#\n#\n# print('Done plotting.')\n# \n## # Close the instrument\n## print(\"\\nClose the instrument\") \n## card.close() \n \n \n \n \n ","sub_path":"kollar_instruments/Acqiris.py","file_name":"Acqiris.py","file_ext":"py","file_size_in_byte":52260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"8265551","text":"\"\"\"\nLog Settings for Pkan Flask\n\"\"\"\nimport os\nimport sys\nfrom logging import StreamHandler, getLogger, Formatter, DEBUG\nfrom logging.handlers import TimedRotatingFileHandler\nfrom sys import stdout\n\nfrom pkan_config.config import get_config, register_config\n\nregister_config(env='Production')\n\ncfg = get_config()\n\nif not os.path.exists(cfg.PKAN_LOG_DIR):\n print(\n \"Log file directory does not exists %s, please create it \" %\n cfg.PKAN_LOG_DIR)\n import getpass\n\n USERNAME = getpass.getuser()\n print(\"become superuser: su \")\n print(\"excecute: mkdir -p %s \" % cfg.PKAN_LOG_DIR)\n print(\"excecute: chown %s:%s %s \" % (\n USERNAME, USERNAME, cfg.PKAN_LOG_DIR))\n sys.exit(1)\n\nprint(\n \"Log file directory is %s \" %\n cfg.PKAN_LOG_DIR)\n\ntry:\n import colorlog\n from colorlog import ColoredFormatter\n\n FORMATTER = ColoredFormatter(\n \"%(log_color)s%(asctime)s [%(process)d] %(levelname)-8s %(\"\n \"message)s\",\n datefmt=None,\n reset=True,\n log_colors=cfg.log_colors,\n secondary_log_colors={},\n style='%'\n )\n LOGGER = colorlog.getLogger(\"pkan_flask\")\n\nexcept ImportError as exc:\n print(exc)\n LOGGER = getLogger(\"pkan_flask\")\n FORMATTER = Formatter(\n '%(asctime)s [%(process)d] %(levelname)-8s %(message)s',\n \"%Y-%m-%d %H:%M:%S\")\n\nROT_FILE_HANDLER = TimedRotatingFileHandler(\n cfg.PKAN_LOG_FILE, \"D\", 1, 5)\nFILE_HANDLER_FORMATTER = FORMATTER\nROT_FILE_HANDLER.setFormatter(FILE_HANDLER_FORMATTER)\nROT_FILE_HANDLER.setLevel(cfg.LOG_LEVEL_FILE)\n\nCONSOL_HANDLER = StreamHandler(stdout)\n# formatter = Formatter('%(asctime)s %(levelname)-8s %(message)s',\n# \"%Y-%m-%d %H:%M:%S\")\nCONSOLE_FORMATTER = FORMATTER\nCONSOL_HANDLER.setFormatter(CONSOLE_FORMATTER)\nCONSOL_HANDLER.setLevel(cfg.LOG_LEVEL_CONSOLE)\n\nLOGGER.addHandler(ROT_FILE_HANDLER)\nLOGGER.addHandler(CONSOL_HANDLER)\n\nLOGGER.propagate = False\nLOGGER.setLevel(DEBUG)\n","sub_path":"pkan_flask/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"66651366","text":"from __future__ import division\nimport os, sys, shutil, time, random, math\nimport argparse\nimport warnings\nimport numpy as np\nwarnings.filterwarnings(\"ignore\")\n\nimport torch\nimport torch.backends.cudnn as cudnn\n\nimport torch.nn.parallel\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport torch.utils.data.distributed\n\nimport models.mobilenet as models\nfrom utils import AverageMeter, RecorderMeter, time_string, convert_secs2time, _ECELoss, load_dataset_face, plot_mi, plot_ens\nfrom mean_field import *\nfrom verification import verify\n\nmodel_names = sorted(name for name in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='Training script for face recognition', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Data / Model\nparser.add_argument('--data_path', metavar='DPATH', default='./data/faces_emore/', type=str, help='Path to dataset')\nparser.add_argument('--arch', metavar='ARCH', default='mobilenet_v2', help='model architecture: ' + ' | '.join(model_names) + ' (default: mobilenet_v2)')\n\n# Optimization\nparser.add_argument('--epochs', metavar='N', type=int, default=90, help='Number of epochs to train.')\nparser.add_argument('--batch_size', type=int, default=256, help='Batch size.')\nparser.add_argument('--learning_rate', type=float, default=0.1, help='The Learning Rate.')\nparser.add_argument('--ft_learning_rate', type=float, default=0.0001, help='The fine-tuning Learning Rate.')\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum.')\nparser.add_argument('--schedule', type=int, nargs='+', default=[30, 60, 80], help='Decrease learning rate at these epochs.')\nparser.add_argument('--gammas', type=float, nargs='+', default=[0.1, 0.1, 0.1], help='LR is multiplied by gamma on schedule')\n\n#Regularization\nparser.add_argument('--decay', type=float, default=1e-4, help='Weight decay (L2 penalty).')\nparser.add_argument('--dropout_rate', type=float, default=0.) #0.2 for mc dropout\n\n# Checkpoints\nparser.add_argument('--save_path', type=str, default='./snapshots_ab_face/', help='Folder to save checkpoints and log.')\nparser.add_argument('--resume', default='', type=str, metavar='PATH', help='Path to latest checkpoint (default: none)')\nparser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='Manual epoch number (useful on restarts)')\nparser.add_argument('--evaluate', dest='evaluate', action='store_true', help='Evaluate model on test set')\n\n# Acceleration\nparser.add_argument('--workers', type=int, default=4, help='number of data loading workers (default: 2)')\n\n# Random seed\nparser.add_argument('--manualSeed', type=int, default=0, help='manual seed')\nparser.add_argument('--job-id', type=str, default='')\n\n# Bayesian\nparser.add_argument('--bayes', type=str, default=None, help='Bayes type: None, mean field, matrix gaussian')\nparser.add_argument('--fc_bayes', type=str, default=None)\nparser.add_argument('--log_sigma_init_range', type=float, nargs='+', default=[-5, -4])\nparser.add_argument('--log_sigma_lr', type=float, default=0.1)\nparser.add_argument('--single_eps', action='store_true', default=False)\nparser.add_argument('--local_reparam', action='store_true', default=False)\n\n# Dist\nparser.add_argument('--world-size', default=1, type=int,\n help='number of nodes for distributed training')\nparser.add_argument('--rank', default=0, type=int,\n help='node rank for distributed training')\nparser.add_argument('--dist-url', default='tcp://127.0.0.1', type=str,\n help='url used to set up distributed training')\nparser.add_argument('--dist-port', default='1234', type=str,\n help='port used to set up distributed training')\nparser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\nparser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\nparser.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n\nbest_acc = 0\n\ndef main():\n args = parser.parse_args()\n if not os.path.isdir(args.data_path): os.makedirs(args.data_path)\n job_id = args.job_id\n args.save_path = args.save_path + job_id\n if not os.path.isdir(args.save_path): os.makedirs(args.save_path)\n\n args.use_cuda = torch.cuda.is_available()\n if args.manualSeed is None: args.manualSeed = random.randint(1, 10000)\n random.seed(args.manualSeed)\n np.random.seed(args.manualSeed)\n torch.manual_seed(args.manualSeed)\n if args.use_cuda: torch.cuda.manual_seed_all(args.manualSeed)\n cudnn.deterministic = True\n\n if args.gpu is not None:\n warnings.warn('You have chosen a specific GPU. This will completely '\n 'disable data parallelism.')\n else:\n args.multiprocessing_distributed = True\n\n args.distributed = args.world_size > 1 or args.multiprocessing_distributed\n ngpus_per_node = torch.cuda.device_count()\n if args.multiprocessing_distributed:\n args.world_size = ngpus_per_node * args.world_size\n mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\n else:\n main_worker(args.gpu, ngpus_per_node, args)\n\ndef main_worker(gpu, ngpus_per_node, args):\n global best_acc\n args.gpu = gpu\n assert args.gpu is not None\n print(\"Use GPU: {} for training\".format(args.gpu))\n\n log = open(os.path.join(args.save_path, 'log{}{}.txt'.format('_seed'+\n str(args.manualSeed), '_eval' if args.evaluate else '')), 'w')\n log = (log, args.gpu)\n\n net = models.__dict__[args.arch](args, num_classes=10341)\n print_log(\"Python version : {}\".format(sys.version.replace('\\n', ' ')), log)\n print_log(\"PyTorch version : {}\".format(torch.__version__), log)\n print_log(\"CuDNN version : {}\".format(torch.backends.cudnn.version()), log)\n print_log(\"Number of parameters: {}\".format(sum([p.numel() for p in net.parameters()])), log)\n print_log(str(args), log)\n\n if args.distributed:\n if args.multiprocessing_distributed:\n args.rank = args.rank * ngpus_per_node + gpu\n dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url+\":\"+args.dist_port,\n world_size=args.world_size, rank=args.rank)\n torch.cuda.set_device(args.gpu)\n net.cuda(args.gpu)\n args.batch_size = int(args.batch_size / ngpus_per_node)\n net = torch.nn.parallel.DistributedDataParallel(net, device_ids=[args.gpu])\n else:\n torch.cuda.set_device(args.gpu)\n net = net.cuda(args.gpu)\n\n criterion = torch.nn.CrossEntropyLoss().cuda(args.gpu)\n\n mus_pretrained, mus_new, vars = [], [], []\n for name, param in net.named_parameters():\n if 'log_sigma' in name:\n vars.append(param)\n else:\n assert(param.requires_grad)\n if 'classifier' in name:\n mus_new.append(param);\n else:\n mus_pretrained.append(param)\n\n optimizer = torch.optim.SGD([{'params': mus_pretrained, 'lr': args.ft_learning_rate},\n {'params': mus_new, 'lr': args.learning_rate}],\n args.learning_rate, momentum=args.momentum,\n weight_decay=args.decay)\n if args.bayes:\n assert(len(mus_pretrained) + len(mus_new) == len(vars))\n var_optimizer = VarSGD(vars, args.log_sigma_lr, num_data=None,\n momentum=args.momentum, weight_decay=args.decay)\n else:\n assert(len(vars) == 0)\n var_optimizer = NoneOptimizer()\n\n pretrain_dict_imagenet = torch.load(\"ckpts/mobilenet_v2-b0353104.pth\")\n model_dict = net.state_dict()\n pretrain_dict_imagenet = {'module.' + k: v for k, v in pretrain_dict_imagenet.items() if 'module.' + k in model_dict and model_dict['module.' + k].size() == v.size()}\n model_dict.update(pretrain_dict_imagenet)\n net.load_state_dict(model_dict)\n print(\"Initialized model with ImageNet pretrained weights\")\n\n recorder = RecorderMeter(args.epochs)\n if args.resume:\n if args.resume == 'auto': args.resume = os.path.join(args.save_path, 'checkpoint.pth.tar')\n if os.path.isfile(args.resume):\n print_log(\"=> loading checkpoint '{}'\".format(args.resume), log)\n checkpoint = torch.load(args.resume, map_location='cuda:{}'.format(args.gpu))\n if 'recorder' in checkpoint:\n recorder = checkpoint['recorder']\n recorder.refresh(args.epochs)\n args.start_epoch = checkpoint['epoch']\n net.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n var_optimizer.load_state_dict(checkpoint['var_optimizer'])\n best_acc = recorder.max_accuracy(False)\n print_log(\"=> loaded checkpoint '{}' accuracy={} (epoch {})\" .format(args.resume, best_acc, checkpoint['epoch']), log)\n else:\n print_log(\"=> no checkpoint found at '{}'\".format(args.resume), log)\n else:\n print_log(\"=> do not use any checkpoint for {} model\".format(args.arch), log)\n\n cudnn.benchmark = True\n\n train_loader, test_loaders = load_dataset_face(args)\n var_optimizer.num_data = len(train_loader.dataset)\n\n if args.evaluate:\n validate(test_loaders, net, criterion, args, log)\n return\n\n start_time = time.time()\n epoch_time = AverageMeter()\n train_los = -1\n\n for epoch in range(args.start_epoch, args.epochs):\n if args.distributed:\n train_loader.sampler.set_epoch(epoch)\n adjust_learning_rate(optimizer, var_optimizer, epoch, args)\n cur_ft_lr, cur_lr, cur_slr = optimizer.param_groups[0]['lr'], optimizer.param_groups[1]['lr'], var_optimizer.param_groups[0]['lr'],\n\n need_hour, need_mins, need_secs = convert_secs2time(epoch_time.avg * (args.epochs-epoch))\n need_time = '[Need: {:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins, need_secs)\n\n print_log('\\n==>>{:s} [Epoch={:03d}/{:03d}] {:s} [learning_rate={:6.4f} {:6.4f} {:6.4f}]'.format(\n time_string(), epoch, args.epochs, need_time, cur_ft_lr, cur_lr, cur_slr) \\\n + ' [Best : Accuracy={:.2f}, Error={:.2f}]'.format(recorder.max_accuracy(False), 100-recorder.max_accuracy(False)), log)\n\n train_acc, train_los = train(train_loader, net, criterion, optimizer, var_optimizer, epoch, args, log)\n if epoch % 1 == 0:\n validate(test_loaders, net, criterion, args, log)\n recorder.update(epoch, train_los, train_acc, 0, 0)\n\n if args.gpu == 0:\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': net.state_dict(),\n 'recorder': recorder,\n 'optimizer' : optimizer.state_dict(),\n 'var_optimizer' : var_optimizer.state_dict(),\n }, False, args.save_path, 'checkpoint.pth.tar')\n\n epoch_time.update(time.time() - start_time)\n start_time = time.time()\n recorder.plot_curve(os.path.join(args.save_path, 'log.png'))\n\n validate(test_loaders, net, criterion, args, log)\n\n log[0].close()\n\ndef train(train_loader, model, criterion, optimizer, var_optimizer, epoch, args, log):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n model.train()\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n data_time.update(time.time() - end)\n\n input = input.cuda(args.gpu, non_blocking=True)\n target = target.cuda(args.gpu, non_blocking=True)\n\n output = model(input)\n loss = criterion(output, target)\n\n losses.update(loss.item(), input.size(0))\n prec1, prec5 = accuracy(output, target, topk=(1, 5))\n top1.update(prec1.item(), input.size(0))\n top5.update(prec5.item(), input.size(0))\n\n optimizer.zero_grad()\n var_optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n var_optimizer.step()\n\n batch_time.update(time.time() - end)\n end = time.time()\n\n print_log(' Epoch: [{:03d}] '\n 'Time {batch_time.avg:.3f} '\n 'Data {data_time.avg:.3f} '\n 'Loss {loss_avg:.4f} '\n 'Prec@1 {top1.avg:.3f} '\n 'Prec@5 {top5.avg:.3f} '.format(\n epoch, batch_time=batch_time, data_time=data_time, loss_avg=losses.avg,\n top1=top1, top5=top5) + time_string(), log)\n return top1.avg, losses.avg\n\ndef validate(val_loaders, model, criterion, args, log):\n model.eval()\n results = {}\n name, val_loader, issame = val_loaders[args.gpu % len(val_loaders)]\n with torch.no_grad():\n with model.no_sync():\n embeddings = []\n for i, input in enumerate(val_loader):\n input = input.cuda(args.gpu, non_blocking=True)\n output = model(input, True)\n norm = torch.norm(output, 2, 1, True)\n embedding = torch.div(output, norm)\n embeddings.append(embedding)\n embeddings = torch.cat(embeddings).data.cpu().numpy()\n tpr, fpr, accuracy, best_thresholds = verify(embeddings, issame, 10)\n results[name] = accuracy.mean()\n print_log(' **Test** {}'.format(' '.join(['{}: {:.3f}'.format(k, v) for k,v in results.items()])), log, True)\n torch.distributed.barrier()\n\ndef print_log(print_string, log, force=False):\n if log[1] == 0 or force:\n print(\"{}\".format(print_string))\n log[0].write('{}\\n'.format(print_string))\n log[0].flush()\n\ndef save_checkpoint(state, is_best, save_path, filename):\n filename = os.path.join(save_path, filename)\n torch.save(state, filename)\n if is_best:\n bestname = os.path.join(save_path, 'model_best.pth.tar')\n shutil.copyfile(filename, bestname)\n\ndef adjust_learning_rate(optimizer, var_optimizer, epoch, args):\n lr = args.learning_rate\n slr = args.log_sigma_lr\n flr = args.ft_learning_rate\n assert len(args.gammas) == len(args.schedule), \"length of gammas and schedule should be equal\"\n for (gamma, step) in zip(args.gammas, args.schedule):\n if (epoch >= step): slr = slr * gamma; lr = lr * gamma; flr = flr * gamma\n else: break\n # lr = lr * np.prod(args.gammas)\n lr = max(lr, 5e-5)\n flr = max(flr, 5e-5)\n optimizer.param_groups[0]['lr'] = flr; optimizer.param_groups[1]['lr'] = lr\n for param_group in var_optimizer.param_groups: param_group['lr'] = slr\n return lr, slr\n\ndef accuracy(output, target, topk=(1,)):\n if len(target.shape) > 1: return torch.tensor(1), torch.tensor(1)\n\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\ndef reduce_tensor(tensor, args):\n rt = tensor.clone()\n dist.all_reduce(rt, op=dist.ReduceOp.SUM)\n rt /= args.world_size\n return rt\n\ndef dist_collect(x):\n \"\"\" collect all tensor from all GPUs\n args:\n x: shape (mini_batch, ...)\n returns:\n shape (mini_batch * num_gpu, ...)\n \"\"\"\n x = x.contiguous()\n out_list = [torch.zeros_like(x, device=x.device, dtype=x.dtype)\n for _ in range(dist.get_world_size())]\n dist.all_gather(out_list, x)\n return torch.cat(out_list, dim=0)\n\ndef freeze(m):\n if isinstance(m, (BayesConv2dMF, BayesLinearMF, BayesBatchNorm2dMF)):\n m.deterministic = True\n\ndef unfreeze(m):\n if isinstance(m, (BayesConv2dMF, BayesLinearMF, BayesBatchNorm2dMF)):\n m.deterministic = False\n\nif __name__ == '__main__': main()\n","sub_path":"main_face.py","file_name":"main_face.py","file_ext":"py","file_size_in_byte":16368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"530213967","text":"# This file is part of Open Austin's Data Portal Analysis project.\n# For more information see README.md in the project's root directory.\n\nimport json\nimport datetime\nimport logging\n\nlogging.getLogger()\n\n\nclass JsonFileReader:\n \"\"\" class JsonFileHandler(json_filename)\n Opens a JSON file and prepares datasets for analysis.\n \"\"\"\n def __init__(self, json_filename):\n self._current_time = datetime.datetime.now()\n self._current_time.replace(microsecond=0).isoformat()\n dataset_dict = self._load_json(json_filename)\n self._datasets = self._multiset_handler(dataset_dict)\n\n def _load_json(self, json_filename):\n with open(json_filename) as data_json:\n json_str = data_json.read()\n data_dict = json.loads(json_str)\n return data_dict\n\n def _multiset_handler(self, data_dict):\n try:\n datasets = data_dict['datasets']\n except(KeyError):\n datasets = [data_dict]\n except:\n raise KeyError(\"No datasets found\")\n\n for item in datasets:\n item['snapshot_time'] = self._current_time\n return datasets\n\n def get_all_datasets(self):\n \"\"\"Return a list of dataset dicts.\n \"\"\"\n return self._datasets\n","sub_path":"utilities/FileUtils.py","file_name":"FileUtils.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"566534015","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 31 14:01:25 2018\n\n@author: ximing\n\"\"\"\n\nprev_ratio=0\nc=0\nfor i in (range(len(unadj_df))):\n un_adj_p = unadj_df.loc[i,'dayClose']\n day = unadj_df.loc[i,'Date']\n adj_p = adj_df[adj_df['Date']==day].iloc[0]['Close']\n ratio = un_adj_p/adj_p\n print(ratio)\n if prev_ratio>0 and (ratio/prev_ratio>1.1 or ratio/prev_ratio<.9):\n print(ratio/prev_ratio)\n print(day)\n c+=1\n if c>2:\n break\n prev_ratio = ratio","sub_path":"test15.py","file_name":"test15.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"427754598","text":"from itemadapter import ItemAdapter\nimport mysql.connector\n\nclass NewsMediaPipeline:\n def __init__(self):\n self.create_connection()\n self.create_table()\n \n def create_connection(self):\n self.conn = mysql.connector.connect(\n host = 'localhost',\n user = 'root',\n passwd = '',\n database = 'scrapy_kompas1'\n )\n self.curr = self.conn.cursor()\n \n def create_table(self):\n self.curr.execute(\"\"\"DROP TABLE IF EXISTS tbl_news\"\"\")\n self.curr.execute(\"\"\"create table tbl_news(\n id int,\n title text,\n url text,\n tanggal text\n )\"\"\")\n self.curr.execute(\"\"\"ALTER TABLE `tbl_news` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT, add PRIMARY KEY (`id`)\"\"\")\n\n self.curr.execute(\"\"\"DROP TABLE IF EXISTS tbl_news_detail\"\"\")\n self.curr.execute(\"\"\"create table tbl_news_detail(\n id int,\n id_detail_news int,\n title text,\n img_url text,\n time text,\n categories text,\n tags text,\n content text\n )\"\"\")\n self.curr.execute(\"\"\"ALTER TABLE `tbl_news_detail` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT, add PRIMARY KEY (`id`)\"\"\")\n # self.curr.execute(\"\"\"ALTER TABLE `tbl_news` ADD CONSTRAINT `relation_news` FOREIGN KEY (`id`) REFERENCES `tbl_news_detail`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT\"\"\")\n \n def process_item(self, item, spider):\n self.store_db(item)\n return item \n \n def store_db(self, item):\n # self.curr.execute(\"\"\"insert into tbl_news values (%s, %s, %s, %s)\"\"\", (\n self.curr.execute(\"\"\"INSERT into tbl_news(title, url, tanggal) VALUES(%s, %s, %s)\"\"\", (\n item['title'][0],\n item['link_url'],\n item['time'],\n ))\n\n # self.curr.execute(\"\"\"insert into tbl_news_detail values (%s, %s, %s, %s, %s, %s, %s)\"\"\", (\n self.curr.execute(\"\"\"INSERT into tbl_news_detail(title, img_url, time, categories, tags, content) VALUES(%s, %s, %s, %s, %s, %s)\"\"\", (\n item['title'][0],\n item['img'],\n item['time'],\n item['categories'],\n item['tags'],\n item['content'],\n ))\n self.conn.commit()\n\n\n\n# SQL TO CREATE FOREIGN KEY TBL NEWS DETAIL\n# ALTER TABLE `tbl_news` ADD CONSTRAINT `relation_news` FOREIGN KEY (`id`) REFERENCES `tbl_news_detail`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT\n\n\n\n","sub_path":"WEEK 6/newsmedia/newsmedia/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"118565103","text":"import sys\r\n\r\ndef union(l1,l2,unionL):\r\n\tsize1 = len(l1)\r\n\tsize2 = len(l2)\r\n\tindex1 = 0\r\n\tindex2 = 0\r\n\tindex3 = 0\r\n\r\n\tif size1 == 0 and size2 == 0:\r\n\t\treturn\r\n\r\n\tif size1 == 0:\r\n\t\tunionL.append(l2[0])\r\n\t\tfor item in l2 :\r\n\t\t\tif item != unionL[index3] :\r\n\t\t\t\tunionL.append(item)\r\n\t\t\t\tindex3+=1\r\n\t\treturn\r\n\t\r\n\tif size2 == 0:\r\n\t\tunionL.append(l1[0])\r\n\t\tfor item in l1 :\r\n\t\t\tif item != unionL[index3] :\r\n\t\t\t\tunionL.append(item)\r\n\t\t\t\tindex3+=1\r\n\t\treturn\t\t\r\n\r\n\tindex3 = 0\r\n\r\n\tif l1[index1] < l2[index2]:\r\n\t\tunionL.append(l1[index1])\r\n\t\tindex1+=1\r\n\telif l1[index1] > l2[index2]:\r\n\t\tunionL.append(l2[index2])\r\n\t\tindex2+=1\r\n\telse:\r\n\t\tunionL.append(l1[index1])\r\n\t\tindex1+=1\r\n\t\tindex2+=1\r\n\r\n\twhile index1 < size1 and index2 < size2 :\r\n\t\tif l1[index1] == l2[index2]:\r\n\t\t\tif unionL[index3] != l2[index2]:\r\n\t\t\t\tunionL.append(l2[index2])\r\n\t\t\t\tindex3+=1\r\n\t\t\tindex1+=1\r\n\t\t\tindex2+=1\r\n\t\telif l1[index1] < l2[index2]:\r\n\t\t\tif unionL[index3] != l1[index1]:\r\n\t\t\t\tunionL.append(l1[index1])\r\n\t\t\t\tindex3+=1\r\n\t\t\tindex1+=1\r\n\t\telse:\r\n\t\t\tif unionL[index3] != l2[index2]:\r\n\t\t\t\tunionL.append(l2[index2])\r\n\t\t\t\tindex3+=1\r\n\t\t\tindex2+=1\r\n\r\n\twhile index1 < size1:\r\n\t\tif unionL[index3] != l1[index1]:\r\n\t\t\tunionL.append(l1[index1])\r\n\t\t\tindex3+=1\r\n\t\tindex1+=1\r\n\r\n\r\n\twhile index2 < size2:\r\n\t\tif unionL[index3] != l2[index2]:\r\n\t\t\tunionL.append(l2[index2])\r\n\t\t\tindex3+=1\r\n\t\tindex2+=1\r\n\r\n\treturn\r\n\r\n\r\ndef intersection(l1,l2,intsecL):\r\n\tindex1, index2, index3 = 0 , 0 , 0\r\n\tsize1 = len(l1)\r\n\tsize2 = len(l2)\r\n\r\n\tif size1 == 0 or size2 == 0:\r\n\t\treturn\r\n\r\n\tindex3 = 0\r\n\r\n\tif l1[index1] == l2[index2]:\r\n\t\tintsecL.append(l1[index1])\r\n\t\tindex1+=1\r\n\t\tindex2+=1\r\n\r\n\twhile index1 < size1 and index2 < size2 :\r\n\t\tif l1[index1] == l2[index2] :\r\n\t\t\tif not intsecL :\r\n\t\t\t\tintsecL.append(l1[index1])\r\n\t\t\telif intsecL[index3] != l2[index2] :\r\n\t\t\t\tintsecL.append(l1[index1])\r\n\t\t\t\tindex3+=1\t\t\r\n\t\t\tindex1+=1\r\n\t\t\tindex2+=1\r\n\t\telif l1[index1] > l2[index2] :\r\n\t\t\tindex2+=1\r\n\t\telse:\r\n\t\t\tindex1+=1\r\n\r\n\r\n\treturn\r\n\r\ndef main():\r\n\r\n\tn = 0\r\n\tl1 = []\r\n\tl2 = []\r\n\tunionL = []\r\n\tintsecL = []\r\n\t\r\n\tprint(\"enter number of first list - enter q to stop\")\r\n\tn = input()\r\n \r\n\twhile n != 'q':\r\n\t\tl1.append(int(n))\r\n\t\tn = input()\r\n\r\n\r\n\tprint(\"enter number of second list - enter q to stop\")\r\n\tn = input()\r\n\r\n\twhile n != 'q':\r\n\t\tl2.append(int(n))\r\n\t\tn = input()\r\n\r\n\tl1.sort()\r\n\tl2.sort()\r\n\r\n\tunion(l1,l2,unionL)\r\n\tintersection(l1,l2,intsecL)\r\n\r\n\tprint (\"intersection\")\r\n\tprint (intsecL)\r\n\t\r\n\tprint (\"union\")\r\n\tprint (unionL)\r\n\r\n\treturn\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"src/unionintersec.py","file_name":"unionintersec.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"114872134","text":"import requests\nfrom lxml import etree\nfrom bs4 import BeautifulSoup\nimport config\nimport re\n\nclass Html_Parser(object):\n\n def XpathPraser(self, response, parser):\n '''\n 针对xpath方式进行解析\n :param response:\n :param parser:\n :return:\n '''\n proxylist = []\n root = etree.HTML(response)\n proxys = root.xpath(parser['pattern'])\n for proxy in proxys:\n try:\n ip = proxy.xpath(parser['position']['ip'])[0].text\n port = proxy.xpath(parser['position']['port'])[0].text\n type = 0\n protocol = 0\n # addr = self.ips.getIpAddr(self.ips.str2ip(ip))\n # country = text_('')\n # area = text_('')\n # if text_('省') in addr or self.AuthCountry(addr):\n # country = text_('国内')\n # area = addr\n # else:\n # country = text_('国外')\n # area = addr\n except Exception as e:\n continue\n # updatetime = datetime.datetime.now()\n # ip,端口,类型(0高匿名,1透明),protocol(0 http,1 https http),country(国家),area(省市),updatetime(更新时间)\n\n # proxy ={'ip':ip,'port':int(port),'type':int(type),'protocol':int(protocol),'country':country,'area':area,'updatetime':updatetime,'speed':100}\n proxy = {'ip': ip, 'port': int(port), 'types': int(type), 'protocol': int(protocol), 'country': '',\n 'area': '', 'speed': 100}\n proxylist.append(proxy)\n return proxylist\n\n def RegularPraser(self, response, parser):\n '''\n 针对正则表达式进行解析\n :param response:\n :param parser:\n :return:\n '''\n proxylist = []\n pattern = re.compile(parser['pattern'])\n matchs = pattern.findall(response)\n if matchs != None:\n for match in matchs:\n try:\n ip = match[parser['position']['ip']]\n port = match[parser['position']['port']]\n # 网站的类型一直不靠谱所以还是默认,之后会检测\n type = 0\n # if parser['postion']['protocol'] > 0:\n # protocol = match[parser['postion']['protocol']]\n # if protocol.lower().find('https')!=-1:\n # protocol = 1\n # else:\n # protocol = 0\n # else:\n protocol = 0\n # addr = self.ips.getIpAddr(self.ips.str2ip(ip))\n # country = text_('')\n # area = text_('')\n # print(ip,port)\n # if text_('省') in addr or self.AuthCountry(addr):\n # country = text_('国内')\n # area = addr\n # else:\n # country = text_('国外')\n # area = addr\n except Exception as e:\n continue\n\n proxy = {'ip': ip, 'port': port, 'types': type, 'protocol': protocol, 'country': '', 'area': '',\n 'speed': 100}\n\n proxylist.append(proxy)\n return proxylist\n\n\n\n\n","sub_path":"ProxiesPool/HtmlParser.py","file_name":"HtmlParser.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"34226393","text":"\"\"\"\nTests for single instance Solr Cores\n\"\"\"\nfrom tests.docker_fixtures import *\nfrom zonne import connect\nfrom zonne.core import Core\n\n\nCORE_NAME = 'test_core'\n\n\n@solr_docker_test\ndef test_create_core(solr_fixture):\n \"\"\"\n Can we create a new Solr core?\n\n :param solr_fixture: SolrFixture instance for testing\n \"\"\"\n solr = connect(host=solr_fixture.host, port=solr_fixture.port)\n core = solr.core(CORE_NAME)\n assert core is not None\n assert core in solr\n\n\n@pytest.mark.run(after='test_create_core')\n@solr_docker_test\ndef test_unload_core(solr_fixture):\n \"\"\"\n Can we unload a Solr core?\n\n :param solr_fixture: SolrFixture instance for testing\n \"\"\"\n solr = connect(host=solr_fixture.host, port=solr_fixture.port)\n core = Core(CORE_NAME)\n r = solr.unload(core)\n assert r is not None\n","sub_path":"tests/test_cores.py","file_name":"test_cores.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456086329","text":"import torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\n\nimport pdb\nclass VisLSTM(nn.Module):\n def __init__(self, cfg):\n super(VisLSTM, self).__init__()\n # parameters of lstm\n self.hidden_dim = cfg.hidden_dim # H\n self.embed_dim = cfg.emb_dim # V\n self.vocab_size = cfg.vocab_size # E\n self.img_dim = cfg.img_feature_dim # I\n\n # network graph\n self.embedding_ques = nn.Embedding(self.vocab_size, self.embed_dim)\n self.embedding_img = nn.Linear(self.img_dim, self.hidden_dim)\n self.lstm1 = nn.LSTMCell(self.embed_dim, self.hidden_dim)\n self.lstm2 = nn.LSTMCell(self.hidden_dim, self.hidden_dim)\n self.output_layer = nn.Linear(self.hidden_dim, self.vocab_size)\n\n def init_hidden(self, batch_size):\n return (torch.zeros(batch_size, self.hidden_dim).cuda(),\\\n torch.zeros(batch_size, self.hidden_dim).cuda())\n\n def forward(self, img_features, questions, image_first=True):\n \"\"\"\n inputs: \n questions: N, T\n img_features: N, D\n image_first: whether img_features fed into lstm as the first words or not\n \"\"\"\n embedded_ques = F.dropout(self.embedding_ques(questions)) # N, T, V\n embedded_img = F.dropout(F.tanh(self.embedding_img(img_features)))# N, H\n embedded_ques = embedded_ques.permute((1, 0, 2))\n\n N, D = embedded_img.shape[:2]\n T, N, V = embedded_ques.shape\n assert(D == V), 'question embedding dimension and image feature dimension not match'\n\n inputs = torch.zeros((T+1, N, V )).cuda()\n if image_first:\n inputs[0] = embedded_img\n inputs[1:, :, :] = embedded_ques\n else:\n inputs[:T, :, :] = embedded_ques\n inputs[T] = embedded_img\n\n h1 = self.init_hidden(N)\n h2 = self.init_hidden(N)\n hidden_states = list()\n for t in range(T+1):\n h1 = self.lstm1(inputs[t], h1)\n h2 = self.lstm2(h1[0], h2)\n hidden_states.append(h2[0])\n\n output = self.output_layer(hidden_states[-1])\n hidden_states = torch.stack(hidden_states, 1)\n return output\n\nclass LSTM_Attention(nn.Module):\n def __init__(self, hidden_dim=512, embed_dim=512, vocab_size=6000, batch_size=16, dropout_rate=0.5):\n super(LSTM_Attention, self).__init__()\n self.hidden_dim = hidden_dim\n self.embed_dim = embed_dim\n self.vocab_size = vocab_size\n self.batch_size = batch_size\n self.dropout_rate = dropout_rate\n\n # network graph\n self.embedding = nn.Embedding(self.vocab_size, self.embed_dim)\n self.lstm1 = nn.LSTMCell(self.embed_dim, self.hidden_dim)\n self.lstm2 = nn.LSTMCell(2*self.hidden_dim, self.hidden_dim)\n self.output_layer = nn.Linear(self.hidden_dim, self.vocab_size)\n\n def init_hidden(self):\n return (torch.zeros(self.batch_size, self.hidden_dim),\\\n torch.zeros(self.batch_size, self.hidden_dim))\n\n def attention(self, h, img_features):\n \"\"\"\n inputs:\n h: 1, N, H\n img_features: N, L, D\n \"\"\"\n #TODO: dropout layer???\n #TODO: weights initializing\n L, D = img_features.shape[1], img_features.shape[2]\n assert(D == self.hidden_dim), 'dimension not match for img_features and hidden state'\n alpha = torch.zeros((self.batch_size, L))\n for i in range(L):\n img_vec = img_features[:, i, :]\n alpha[:, i] = torch.sum(h * img_vec, 1)\n\n alpha = torch.unsqueeze(alpha, 1)\n v_hat = torch.matmul(alpha, img_features)\n return v_hat.view(self.batch_size, -1)\n\n def forward(self, inputs, img_features):\n \"\"\"\n inputs: N, T, V\n img_faetures: N, L, D\n \"\"\"\n # convert input into torch tensor\n inputs = torch.tensor(inputs, dtype=torch.long)\n img_features = torch.tensor(img_features, dtype=torch.float)\n\n # get the sequence length\n max_len = inputs.shape[1]\n embedded_inputs = self.embedding(inputs).view(max_len, self.batch_size, -1) # T, N, E\n\n # initialize two lstms for the stacked lstm\n h1, c1 = self.init_hidden()\n h2, c2 = self.init_hidden()\n hidden_states = list()\n for t in range(max_len):\n h1, c1 = self.lstm1(embedded_inputs[t], (h1, c1))\n v_att = self.attention(h1, img_features)\n\n # concatenate h_att and h1\n input_lstm2 = torch.cat([v_att, h1], dim=1)\n h2, c2 = self.lstm2(input_lstm2, (h2, c2))\n hidden_states.append(h2)\n\n # re-orgainize view of hidden_states for later use\n hidden_states = torch.cat(hidden_states, 0).view(self.batch_size, max_len, -1)\n return hidden_states\n","sub_path":"visLstm.py","file_name":"visLstm.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642275562","text":"#!/usr/bin/env python\nfrom ase import Atoms, Atom\nfrom ase.calculators.aims import Aims\nfrom ase.cluster.decahedron import Decahedron\nfrom ase.optimize.basin import BasinHopping\nfrom ase.units import kB\nfrom ase.optimize import LBFGS\n\n\natoms = Decahedron('Pt',\n p=2, # natoms on 100 face normal to 5-fold axis\n q=1, # natoms 0n 100 parallel to 5-fold axis\n r=0) # depth of the Marks re-entrance?\n\n\ncalc = Aims(label='cluster/pt-decahedron-2-1-bh',\n xc='pbe',\n spin='none',\n relativistic = 'atomic_zora scalar',\n sc_accuracy_etot=1e-5,\n sc_accuracy_eev=1e-3,\n sc_accuracy_rho=1e-4,\n sc_accuracy_forces=1e-3)\natoms.set_calculator(calc)\n\nbh = BasinHopping(atoms = atoms,\n temperature=100 * kB, # 'temperature' to overcome barriers\n dr=0.5, # maximal stepwidth\n optimizer=LBFGS, # optimizer to find local minima\n fmax=0.1\n )\nbh.run(10)","sub_path":"sclu-10.py","file_name":"sclu-10.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"512575974","text":"\"\"\"\nThese tests cover checkout\n\"\"\"\n\nfrom pages.products import SwagLabsProducts\nfrom pages.cart import SwagLabsCart\nfrom pages.checkout import SwagLabsCheckout\nfrom tests.test_cart import random_inventory_items\n\n\ndef test_checkout(browser, login_user):\n\n products_page = SwagLabsProducts(browser)\n cart_page = SwagLabsCart(browser)\n checkout_page = SwagLabsCheckout(browser)\n\n # Given the customer has added at least one item to their cart\n items_in_cart = {}\n list_of_product_indexes = random_inventory_items()\n for i in list_of_product_indexes:\n items_in_cart.update(\n products_page.add_inventory_item_to_cart(i)\n )\n\n # And the customer is on the cart page\n products_page.open_shopping_cart()\n\n # When the customer clicks the checkout button\n cart_page.click_checkout_button()\n\n # Then they are prompted to fill in their personal information\n assert checkout_page.get_title().lower() == \\\n 'checkout: your information'\n checkout_page.fill_personal_information('Test', 'Customer', '55555')\n\n # When the customer clicks the continue button\n checkout_page.click_continue_button()\n\n # Then a checkout overview confirmation page is displayed\n assert checkout_page.get_title().lower() == \\\n 'checkout: overview'\n\n # And all information about products and pricing looks correct\n items_at_checkout = checkout_page.get_cart_items()\n cart_prices = [float(i) for i in items_in_cart.values()]\n assert items_at_checkout == items_in_cart\n assert round(float(checkout_page.get_subtotal_amount()), 2) == \\\n sum(cart_prices)\n assert sum(cart_prices) + float(checkout_page.get_tax_amount()) \\\n == float(checkout_page.get_total_amount())\n\n # When the customer clicks the finish button\n checkout_page.complete_transaction()\n\n # Then a thank you message is displayed on the checkout complete page\n assert checkout_page.get_title().lower() == \\\n 'checkout: complete!'\n assert checkout_page.get_transaction_complete_message() == \\\n 'thank you for your order'\n\n # When the customer clicks the back home button\n checkout_page.return_home()\n\n # Then they are returned to the products page\n assert products_page.get_title().lower() == 'products'\n","sub_path":"python/tests/test_checkout.py","file_name":"test_checkout.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"381371424","text":"from time import sleep\nprint(' _ _ ') \nsleep(0.5)\nprint(' / \\ | | _____ ____ _ ')\nsleep(0.5)\nprint(' / _ \\ | |/ _ \\ \\/ / _` |')\nsleep(0.5)\nprint(' / ___ \\| | __/> < (_| |')\nsleep(0.5)\nprint('/_/ \\_\\_|\\___/_/\\_\\__,_|')\nsleep(0.5)\n \n\nimport speech_recognition as sr\nfrom gtts import gTTS\nfrom playsound import playsound\nimport webbrowser\nimport wikipedia\nimport datetime\nimport sys\nimport re\nimport random,os\nimport smtplib\n\n\ndef Alexa(text):\n\tsn = gTTS(text,lang=\"id\")\n\tsn.save(\"sound.mp3\")\n\tplaysound(\"sound.mp3\")\n\tprint(\"Alexa :\",text)\n\ndef greeting():\n\tch = int(datetime.datetime.now().hour)\n\tif (ch >= 0 and ch < 12):\n\t\tAlexa(\"Assalamualaikum, Selamat pagi!\")\n\tif (ch >= 12 and ch < 18):\n\t\tAlexa(\"Assalamualaikum, Selamat siang!\")\n\tif (ch >= 18 and ch != 0):\n\t\tAlexa(\"Assalamualaikum, Selamat malam!\")\ngreeting()\n\nAlexa(\"hy shimozuki ada yang bisa aku bantu\")\n\ndef command():\n\tr = sr.Recognizer()\n\twith sr.Microphone() as source:\n\n\t\tprint(\"\\nMendengarkan...\")\n\t\tr.pause_threshold = 1\n\t\taudio = r.listen(source)\n\t\ttry:\n\t\t\tquery = r.recognize_google(audio,language=\"id-ID\")\n\t\t\tprint(\"Kamu:\",query)\n\t\texcept:\n\t\t\tAlexa(\"Maaf, aku tidak mengerti apa yang kamu katakan , tolong ketikkan perintah \")\n\t\t\tquery = input(\"Perintah : \")\n\treturn query\n#credential email\ndef send_email(recipient,subject,pesan):\n\tuser = \"robbishimozuki@gmail.com\" \n\tpawd = \"Robbivani1305\" \n\tFrom = user\n\tto = recipient if isinstance(recipient, list) else [recipient]\n\tsubj = subject\n\tbody = pesan\n\ttry:\n\t\tmessage = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (From, \", \".join(to), subj, body)\n\t\tserver_ssl = smtplib.SMTP_SSL(\"smtp.gmail.com\",465)\n\t\tserver_ssl.ehlo()\n\t\tserver_ssl.login(user,pawd)\n\t\tserver_ssl.sendmail(From,to,message)\n\t\tserver_ssl.close()\n\t\tAlexa('berhasil mengirim email')\n\texcept Exception as a:\n\t\tprint(a)\n\t\tAlexa('gagal mengirim email')\n\t\tpass\n\ndef wiki(kt):\n\twikipedia.set_lang(\"id\")\n\tres = wikipedia.summary(kt,sentences=2)\n\tAlexa(res)\n\ndef predict(kata):\n\tkabar = ['kabarmu','kabar','keadaanmu','keadaan']\n\tumur = ['umurmu','umur']\n\tpembuat = ['alexa beritahu aku informasi tentang mu']\n\tjawabP = ['aku dibuat di sumbawa dengan bahasa program python, umur ku yang jelas lebih muda dari mu, dan aku dibuat oleh seseorang yang bernama shimozuki']\n\tjawabU = ['maaf itu rahasia','yang pasti aku lebih muda darimu','tanyakan saja kepada pembuatku']\n\tjawabK = [\"hem aku tidak pernah seceria ini\",\"kabarku baik baik saja\",\"aku merasa bahagia hari ini\"]\n\t\n\tfor ta in kabar:\n\t\tif ta in kata:\n\t\t\tAlexa(random.choice(jawabK))\n\tfor um in umur:\n\t\tif um in kata:\n\t\t\tAlexa(random.choice(jawabU))\n\tfor pem in pembuat:\n\t\tif pem in kata:\n\t\t\tAlexa(random.choice(jawabP))\t\n\t\t\t\t\n\tif 'musik' in kata:\n\t\tAlexa(\"Ketikkan letak direktori musikmu\")\n\t\tdir = input(\"Direktori : \")\n\t\ttry:\n\t\t\tfor play in os.listdir(dir):\n\t\t\t\tif play.endswith('mp3'):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tAlexa('memutar musik !')\n\t\t\t\t\t\tAlexa('selamat mendengarkan')\n\t\t\t\t\t\tplaysound(dir+\"/\"+play)\n\t\t\t\t\texcept Exception as a:\n\t\t\t\t\t\tprint(a)\n\t\t\t\telse:\n\t\t\t\t\tAlexa(\"mencari file lagu !\")\n\t\texcept Exception as a:\n\t\t\tprint(\"Direktori tidak ditemukan\")\n\tif 'email' in kata:\n\t\tAlexa(\"siapa penerima emailnya ?\")\n\t\tpen = input(\"Penerima : \")\n\t\tAlexa(\"tuliskan subjectnya \")\n\t\tsub = input('subject : ')\n\t\tAlexa(\"tuliskan pesan yang ingin dikirim\")\n\t\tpes = input('Pesan : ')\t\n\t\tAlexa(\"sedang mengirim email\")\n\t\tsend_email(pen,sub,pes)\t\t\n\t\t\t\n\tif 'buka' in kata and 'exploit database' not in kata:\t\n\t\tpecah = kata.split()\n\t\tif len(pecah) != 1:\n\t\t\tAlexa('oke')\n\t\t\twebbrowser.open(\"http://\"+pecah[1]+\".com\")\n\t\telse:\n\t\t\tAlexa('tidak bisa membuka mesin pencari')\n\t\t\tpass\n\tif 'wiki' in kata:\t\n\t\tpecah = kata.split('wiki')\n\t\tif len(pecah) != 1:\n\t\t\tAlexa('oke')\n\t\t\twiki(pecah[1])\n\t\telse:\n\t\t\tAlexa('tidak bisa membuka wikipedia')\n\t\t\tpass\n\tif 'exploit database' in kata:\n\t\tAlexa('oke')\n\t\twebbrowser.open(\"http://exploit-db.com\")\n\tif 'cari' in kata:\n\t\tpecah = kata.split('cari')\n\t\tif len(pecah) != 1:\n\t\t\tAlexa('oke')\n\t\t\twebbrowser.open(\"https://www.google.com/search?q=\"+pecah[1]+\"&ie=utf-8&oe=utf-8&client=firefox-b-ab\")\n\t\telse:\n\t\t\tAlexa('tidak bisa membuka mesin pencari')\n\t\n\tAlexa(\"menunggu perintah selanjutnya\")\ndef main():\n\t\n\ta = 1\n\twhile a > 0:\n\t\tqr = command()\n\t\tif \"Alexa stop\" in qr:\n\t\t\tAlexa(\"Assalamualaikum,selamat beristirahat shimozuki\")\n\t\t\tsys.exit()\n\t\tpredict(qr.lower())\n\t\t\nif __name__ == \"__main__\":\n\tmain()\n\t\t\n\t\t\t\n","sub_path":"alexa.py","file_name":"alexa.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"120700215","text":"#functions\r\nglobal customer_order\r\ncustomer_order = []\r\nglobal customer_price\r\ncustomer_price = []\r\nglobal delivery_charge\r\ndelivery_charge = 3\r\ndef customer_info():\r\n print(\"Welcome to Dream Pizza\")\r\n global user_name\r\n user_name = input(\"What's your name?\")\r\n global user_delivery\r\n user_delivery = input(\"Would you like your pizza delivered?\")\r\n\r\n if user_delivery.lower() == \"yes\":\r\n global user_address\r\n user_address = input(\"What is your address?\")\r\n global user_number\r\n user_number = input(\"What is your phone number?\")\r\n global customer_price\r\n customer_price.append(delivery_charge)\r\n else:\r\n del customer_price[:]\r\n\r\n\r\ndef customer_order_display():\r\n if user_delivery.lower() == \"yes\":\r\n print(\"Your order has been placed\")\r\n print(\"Name: {}\".format(user_name))\r\n print(\"Method: Delivery\")\r\n print(\"Address: {}\".format(user_address))\r\n print(\"Phone Number: {}\".format(user_number))\r\n print(\"Customer's order: {}\".format(customer_order))\r\n print(\"Total Price: ${:.2f}\".format(sum(customer_price)))\r\n\r\n if user_delivery.lower() == \"no\":\r\n print(\"Your order has been placed\")\r\n print(\"Name: {}\".format(user_name))\r\n print(\"Method: Pick Up\")\r\n print(\"Customer's order: {}\".format(customer_order))\r\n print(\"Total Price: ${:.2f}\".format(sum(customer_price)))\r\n return\r\n#end of functions\r\n\r\n\r\n#start of program\r\ncustomer_info()\r\nwhile True:\r\n pizza_menu_regular = [\"Ham & Cheese\", \"Hawaiian\", \"Meatlovers\", \"Pepperoni\", \"Vegetarian\", \"Cheesy\"]\r\n pizza_menu_gourmet = [\"Chicken & Cranberry\", \"BBQ Chicken & Bacon\", \"Butter Chicken Pizza\", \"Seafood Deluxe\", \"Chicken Satay Pizza\", \"Smoked Salmon Pizza\"]\r\n regular_pizza = 8.50\r\n gourmet_pizza = 13.50\r\n user_input = input(\"\"\"What would you like to order?\r\nPleae type the number which that pizza represents\r\nRegular Pizzas\r\n 1) Ham & Cheese - $8.50\r\n 2) Hawaiian - $8.50\r\n 3) Meatlovers - $8.50\r\n 4) Pepperoni - $8.50\r\n 5) Vegetarian - $8.50\r\n 6) Cheesy - $8.50\r\n Gourmet Pizzas\r\n 7) Chicken & Cranberry - $13.50\r\n 8) BBQ Chicken & Bacon - $13.50\r\n 9) Butter Chicken Pizza - $13.50\r\n 10) Seafood Deluxe - $13.50\r\n 11) Chicken Satay Pizza - $13.50\r\n 12) Smoked Salmon Pizza - $13.50\r\n When finished type 'end' to complete order\"\"\")\r\n if user_input == \"1\":\r\n customer_order.append(pizza_menu_regular[0])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"2\":\r\n customer_order.append(pizza_menu_regular[1])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"3\":\r\n customer_order.append(pizza_menu_regular[2])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"4\":\r\n customer_order.append(pizza_menu_regular[3])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"5\":\r\n customer_order.append(pizza_menu_regular[4])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"6\":\r\n customer_order.append(pizza_menu_regular[5])\r\n customer_price.append(regular_pizza)\r\n if user_input == \"7\":\r\n customer_order.append(pizza_menu_gourmet[0])\r\n customer_price.append(gourmet_pizza)\r\n if user_input == \"8\":\r\n customer_order.append(pizza_menu_gourmet[1])\r\n customer_price.append(gourmet_pizza)\r\n if user_input == \"9\":\r\n customer_order.append(pizza_menu_gourmet[2])\r\n customer_price.append(gourmet_pizza)\r\n if user_input == \"10\":\r\n customer_order.append(pizza_menu_gourmet[3])\r\n customer_price.append(gourmet_pizza)\r\n if user_input == \"11\":\r\n customer_order.append(pizza_menu_gourmet[4])\r\n customer_price.append(gourmet_pizza)\r\n if user_input == \"12\":\r\n customer_order.append(pizza_menu_gourmet[5])\r\n customer_price.append(gourmet_pizza)\r\n if user_input.lower() == \"end\":\r\n break\r\ncustomer_order_display()\r\n","sub_path":"dream pizza with functions.py","file_name":"dream pizza with functions.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"10836669","text":"import logging\n\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtCore import *\nfrom PySide2.QtGui import *\n\nimport pandas as pd\n\nimport utils\nfrom gui.file_widget import FileWidget\nfrom translated_strings import TranslatedStrings\n\nlog = logging.getLogger(__name__)\n\nts = None\n\n\nclass PersonasTable(QAbstractTableModel):\n \"\"\"\n keep the method names\n they are an integral part of the model\n \"\"\"\n def __init__(self, parent, mylist, header, *args):\n QAbstractTableModel.__init__(self, parent, *args)\n self.parent = parent\n self.mylist = mylist\n self.header = header\n\n def setDataList(self, mylist):\n self.mylist = mylist\n self.layoutAboutToBeChanged.emit()\n self.dataChanged.emit(self.createIndex(0, 0),\\\n self.createIndex(self.rowCount(0), self.columnCount(0)))\n self.layoutChanged.emit()\n\n def rowCount(self, parent):\n if not self.mylist:\n return 0\n else:\n return len(self.mylist)\n\n def columnCount(self, parent):\n if not self.mylist:\n return 0\n else:\n return len(self.mylist[0])\n\n def data(self, index, role):\n if not index.isValid():\n return None\n if (index.column() == 0):\n value = self.mylist[index.row()][index.column()].text()\n else:\n value = self.mylist[index.row()][index.column()]\n if role == Qt.EditRole:\n return value\n elif role == Qt.DisplayRole:\n return value\n elif role == Qt.CheckStateRole:\n if index.column() == 0:\n if self.mylist[index.row()][index.column()].isChecked():\n return Qt.Checked\n else:\n return Qt.Unchecked\n\n def headerData(self, col, orientation, role):\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n return self.header[col]\n return None\n\n def flags(self, index):\n if not index.isValid():\n return None\n\n if index.column() == 0:\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable\n elif index.column() == 1:\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable\n else:\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n\n def setData(self, index, value, role):\n if not index.isValid():\n return False\n\n if role == Qt.CheckStateRole and index.column() == 0:\n if value == Qt.Checked:\n self.mylist[index.row()][index.column()].setChecked(True)\n self.mylist[index.row()][index.column()].setText(ts(\"Si\"))\n\n else:\n self.mylist[index.row()][index.column()].setChecked(False)\n self.mylist[index.row()][index.column()].setText(ts(\"No\"))\n\n elif role == Qt.EditRole and index.column() == 1:\n if int(value) > 4:\n self.parent.mostrar_popup(\"Max 4\")\n else:\n self.mylist[index.row()][index.column()] = int(value)\n\n self.dataChanged.emit(index, index)\n return True\n\n\nclass PersonasWindow(QWidget):\n\n sig_continuar = Signal()\n\n def __init__(self, dc):\n super().__init__()\n\n global ts\n ts = TranslatedStrings()\n\n self.dc = dc\n\n self.grid = QGridLayout(self)\n self.setLayout(self.grid)\n\n self.setWindowTitle(ts(\"Ingreso Personal\"))\n self.setWindowIcon(\\\n QIcon(utils.ruta_absoluta('resources/icons/tsr.png')))\n self.setMinimumSize(QSize(560, 420))\n\n self.archivos = dict()\n\n self.w_personal = FileWidget(self, ts(\"Personal\"), self.dc.personal,\n cmb=False)\n self.w_personal.sig_archivo_agregado.connect(self.slot_personal_agregar)\n self.w_personal.sig_archivo_agregado.connect(self.create_table)\n\n self.w_personal.sig_archivo_eliminado.connect(self.slot_personal_eliminar)\n self.grid.addWidget(self.w_personal, 0, 0, 1, -1)\n\n self.lbl_selected = QLabel(self)\n self.lbl_selected.setFont(QFont('SansSerif', 12))\n self.lbl_selected.setText(\"\")\n self.grid.addWidget(self.lbl_selected, 2, 0, 1, -1)\n\n\n self.btn_continuar = QPushButton(ts(\"Continuar\"), self)\n self.btn_continuar.clicked.connect(self.continuar)\n #self.btn_atras = QPushButton(ts(\"Atrás\"), self)\n \n self.btn_ejemplo = QPushButton(ts(\"Formato Personal\"),self)\n self.btn_ejemplo.clicked.connect(self.click_ejemplo)\n \n\n self.grid.addWidget(self.btn_continuar, 4, 1)\n self.grid.addWidget(self.btn_ejemplo, 1, 0)\n #self.grid.addWidget(self.btn_atras, 3, 0)\n\n self.create_table()\n self.msg = None\n\n\n @Slot()\n def create_table(self):\n\n self.table_model = PersonasTable(self, self.create_table_model(),\n self.header)\n self.table_view = QTableView()\n self.table_view.setModel(self.table_model)\n self.table_view.setAlternatingRowColors(True)\n self.table_view.setSelectionMode(QAbstractItemView.NoSelection)\n self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.table_view.resizeColumnsToContents()\n self.table_view.horizontalHeader().setStretchLastSection(True)\n\n self.grid.addWidget(self.table_view,3, 0, 1, -1)\n\n self.table_model.dataChanged.connect(self.update_selected)\n self.update_selected()\n\n\n def create_table_model(self):\n if self.dc.personal.datos is not None:\n self.datos = self.dc.personal.datos.copy()\n else:\n self.datos = pd.DataFrame(columns=['Cantidad OVCC', 'ID persona',\n 'Nombre'])\n\n self.header = [ts(\"Considerar\"), ts(\"Cantidad OVCC\"), ts(\"ID persona\"),\n ts(\"Nombre\")]\n\n datalist = list()\n for d in self.datos.to_dict('records'):\n if d[\"Cantidad OVCC\"]==0:\n c = QCheckBox(ts(\"No\"))\n c.setChecked(False)\n else:\n c = QCheckBox(ts(\"Si\"))\n c.setChecked(True)\n\n r = [c,d[\"Cantidad OVCC\"],d[\"ID persona\"],d[\"Nombre\"]]\n\n datalist.append(r)\n\n return datalist\n\n @Slot()\n def update_selected(self):\n\n if len(self.table_model.mylist) == 0:\n self.lbl_selected.setText(ts(\"OVCC para asignar: {}\").format(str(0)))\n else:\n self.num_selected = sum(\n [int(r[1]) for r in self.table_model.mylist if r[0].isChecked()])\n self.lbl_selected.setText(ts(\"OVCC para asignar: {}\").format(\n self.num_selected))\n self.dc.ovcc_num = self.num_selected\n\n print(self.dc.ovcc_num)\n\n self.lbl_selected.update()\n\n\n @Slot(str)\n def slot_personal_agregar(self, archivo):\n self.archivos['personal'] = archivo\n self.dc.personal.cargar_excel(self.archivos['personal'])\n self.dc.personal.guardar_datos(excel=True)\n self.update_selected()\n\n @Slot()\n def slot_personal_eliminar(self, mes):\n\n self.dc.personal.eliminar()\n self.dc.personal.guardar_datos()\n self.archivos['personal'] = None\n self.table_model.setDataList(self.create_table_model())\n\n self.update_selected()\n\n def lista_filtrada(self):\n rv = list()\n for r in self.table_model.mylist:\n rv.append({\n \"Considerar\" : r[0].isChecked(),\n \"Cantidad OVCC\" : int(r[1]),\n \"ID persona\" : r[2],\n \"Nombre\" : r[3]\n })\n self.dc.personas_filtradas = pd.DataFrame(rv)\n\n\n def mostrar_popup(self, msg=None):\n self.msg = QMessageBox()\n self.msg.setIcon(QMessageBox.Warning)\n self.msg.setWindowTitle(\"ERROR\")\n self.msg.setWindowIcon(\\\n QIcon(utils.ruta_absoluta('resources/icons/tsr.png')))\n\n if not msg:\n self.msg.setText(ts(\"Solo se pueden asignar 4 OVCC máximo\"))\n else:\n self.msg.setText(msg)\n self.msg.setStandardButtons(QMessageBox.Ok)\n self.msg.show()\n\n def continuar(self, msg):\n if \"personal\" not in self.archivos.keys():\n self.mostrar_popup(ts(\"Debe ingresar personal para continuar\"))\n else:\n self.sig_continuar.emit()\n \n @Slot()\n def click_ejemplo(self):\n archivo, selectedFilter = QFileDialog.getSaveFileName(\n self,\n '{}'.format(ts(\"Guardar Formato Personal\")),\n '',\n '{} ( *.xlsx *.xlsm)'.format(ts('Archivo de Excel'))\n )\n \n if archivo:\n pd.DataFrame(columns=['Cantidad OVCC', 'ID persona',\n 'Nombre']).to_excel(archivo,index=False)\n\n else:\n QMessageBox.about(self, ts(\"Herramienta OVCC\"), ts(\"No se eligió archivo\"))","sub_path":"Programador/Programador Australia/gui/personas_window.py","file_name":"personas_window.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645573766","text":"from math import sqrt\nimport tensorflow as tf\nfrom tensorflow import constant as const\nfrom layers.nsc_sentence_layer import nsc_sentence_layer\nfrom layers.nsc_document_layer import nsc_document_layer\nlookup = tf.nn.embedding_lookup\n\n\ndef var(name, shape, initializer):\n return tf.get_variable(name, shape=shape, initializer=initializer)\n\n\nclass TRIAMHNSC(object):\n def __init__(self, args):\n self.max_doc_len = args['max_doc_len']\n self.max_sen_len = args['max_sen_len']\n self.cls_cnt = args['cls_cnt']\n self.embedding = args['embedding']\n self.emb_dim = args['emb_dim']\n self.hidden_size = args['hidden_size']\n self.usr_cnt = args['usr_cnt']\n self.prd_cnt = args['prd_cnt']\n self.sen_hop_cnt = args['sen_hop_cnt']\n self.doc_hop_cnt = args['doc_hop_cnt']\n self.l2_rate = args['l2_rate']\n self.convert_flag = ''\n self.debug = args['debug']\n self.lambda1 = args['lambda1']\n self.lambda2 = args['lambda2']\n self.lambda3 = args['lambda3']\n self.embedding_lr = args['embedding_lr']\n\n self.best_dev_acc = .0\n self.best_test_acc = .0\n self.best_test_rmse = .0\n\n # initializers for parameters\n self.weights_initializer = tf.contrib.layers.xavier_initializer()\n self.biases_initializer = tf.initializers.zeros()\n self.emb_initializer = tf.contrib.layers.xavier_initializer()\n\n # embeddings in the model\n with tf.variable_scope('emb'):\n self.embeddings = {\n 'wrd_emb':\n const(self.embedding, name='wrd_emb', dtype=tf.float32),\n # tf.Variable(self.embedding, name='wrd_emb', dtype=tf.float32),\n 'usr_emb':\n var('usr_emb', [self.usr_cnt, self.emb_dim],\n self.emb_initializer),\n 'prd_emb':\n var('prd_emb', [self.prd_cnt, self.emb_dim],\n self.emb_initializer)\n }\n\n # for tensorboard\n if self.debug:\n tf.summary.histogram('usr_emb', self.embeddings['usr_emb'])\n tf.summary.histogram('prd_emb', self.embeddings['prd_emb'])\n\n def build(self, data_iter):\n # get the inputs\n with tf.variable_scope('inputs'):\n input_map = data_iter.get_next()\n usrid, prdid, input_x, input_y, sen_len, doc_len = \\\n (input_map['usr'], input_map['prd'],\n input_map['content'], input_map['rating'],\n input_map['sen_len'], input_map['doc_len'])\n\n usr = lookup(\n self.embeddings['usr_emb'], usrid, name='cur_usr_embedding')\n prd = lookup(\n self.embeddings['prd_emb'], prdid, name='cur_prd_embedding')\n input_x = lookup(\n self.embeddings['wrd_emb'], input_x, name='cur_wrd_embedding')\n\n input_x = tf.reshape(\n input_x,\n [-1, self.max_doc_len, self.max_sen_len, self.emb_dim])\n nscua_input_x, nscpa_input_x, nscga_input_x = input_x, input_x, input_x\n\n # padding content with user embedding\n tiled_usr = tf.layers.dense(\n usr,\n self.emb_dim,\n use_bias=False,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n tiled_prd = tf.layers.dense(\n prd,\n self.emb_dim,\n use_bias=False,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n tiled_usr = tf.tile(tiled_usr[:, None, None, :],\n [1, self.max_doc_len, 1, 1])\n tiled_prd = tf.tile(tiled_prd[:, None, None, :],\n [1, self.max_doc_len, 1, 1])\n nscua_input_x = tf.concat([tiled_usr, nscua_input_x], axis=2)\n nscpa_input_x = tf.concat([tiled_prd, nscpa_input_x], axis=2)\n nscga_input_x = tf.pad(nscga_input_x, [[0, 0], [0, 0], [0, 1], [0, 0]])\n aug_sen_len = tf.where(\n tf.equal(sen_len, 0), tf.zeros_like(sen_len), sen_len + 1)\n self.max_sen_len += 1\n nscua_input_x = tf.reshape(nscua_input_x,\n [-1, self.max_sen_len, self.emb_dim])\n nscpa_input_x = tf.reshape(nscpa_input_x,\n [-1, self.max_sen_len, self.emb_dim])\n\n # build the process of model\n sen_embs, doc_embs, logits = [], [], []\n sen_cell_fw = tf.nn.rnn_cell.LSTMCell(\n self.hidden_size // 2,\n forget_bias=0.,\n initializer=self.weights_initializer)\n sen_cell_bw = tf.nn.rnn_cell.LSTMCell(\n self.hidden_size // 2,\n forget_bias=0.,\n initializer=self.weights_initializer)\n for scope, identities, cur_input_x in zip(\n ['user_block', 'product_block', 'global_block'],\n [[usr], [prd], []], [nscua_input_x, nscpa_input_x, nscga_input_x]):\n with tf.variable_scope(scope):\n sen_embs.append(\n nsc_sentence_layer(\n cur_input_x,\n self.max_sen_len,\n self.max_doc_len,\n aug_sen_len if input is not nscga_input_x else sen_len,\n identities,\n self.hidden_size,\n self.emb_dim,\n self.sen_hop_cnt,\n bidirectional_lstm=True,\n lstm_cells=[sen_cell_fw, sen_cell_bw]))\n\n sen_embs = tf.concat(sen_embs, axis=-1)\n sen_embs = tf.layers.dense(\n sen_embs,\n self.emb_dim,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n\n nscua_sen_embs, nscpa_sen_embs, nscga_sen_embs = sen_embs, sen_embs, sen_embs\n # padding doc with user and product embeddings\n doc_aug_usr = tf.layers.dense(\n usr,\n self.emb_dim,\n use_bias=False,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n doc_aug_prd = tf.layers.dense(\n prd,\n self.emb_dim,\n use_bias=False,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n nscua_sen_embs = tf.concat([doc_aug_usr[:, None, :], nscua_sen_embs],\n axis=1)\n nscpa_sen_embs = tf.concat([doc_aug_prd[:, None, :], nscpa_sen_embs],\n axis=1)\n nscga_sen_embs = tf.pad(nscga_sen_embs, [[0, 0], [0, 1], [0, 0]])\n # none_sen_embs = tf.pad(sen_embs, [[0, 0], [1, 0], [0, 0]])\n self.max_doc_len += 1\n aug_doc_len = doc_len + 1\n\n doc_cell_fw = tf.nn.rnn_cell.LSTMCell(\n self.hidden_size // 2,\n forget_bias=0.,\n initializer=self.weights_initializer)\n doc_cell_bw = tf.nn.rnn_cell.LSTMCell(\n self.hidden_size // 2,\n forget_bias=0.,\n initializer=self.weights_initializer)\n for scope, identities, input_x in zip(\n ['user_block', 'product_block', 'global_block'],\n [[usr], [prd], []],\n [nscua_sen_embs, nscpa_sen_embs, nscga_sen_embs]):\n with tf.variable_scope(scope):\n doc_emb = nsc_document_layer(\n input_x,\n self.max_doc_len,\n aug_doc_len if input is not nscga_sen_embs else doc_len,\n identities,\n self.hidden_size,\n self.doc_hop_cnt,\n bidirectional_lstm=True,\n lstm_cells=[doc_cell_fw, doc_cell_bw])\n doc_embs.append(doc_emb)\n\n with tf.variable_scope('result'):\n logits.append(\n tf.layers.dense(\n doc_emb,\n self.cls_cnt,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer))\n\n nscua_logit, nscpa_logit, _ = logits\n\n with tf.variable_scope('result'):\n doc_emb = tf.concat(doc_embs, axis=1, name='dhuapa_output')\n logit = tf.layers.dense(\n doc_emb,\n self.cls_cnt,\n kernel_initializer=self.weights_initializer,\n bias_initializer=self.biases_initializer)\n\n prediction = tf.argmax(logit, 1, name='prediction')\n\n # soft_label = tf.nn.softmax(tf.stop_gradient(logit) / (self.cls_cnt / 2))\n\n with tf.variable_scope(\"loss\"):\n ssce = tf.nn.sparse_softmax_cross_entropy_with_logits\n self.loss = ssce(logits=logit, labels=input_y)\n lossu = ssce(logits=nscua_logit, labels=input_y)\n lossp = ssce(logits=nscpa_logit, labels=input_y)\n\n self.loss = self.lambda1 * self.loss + self.lambda2 * lossu + self.lambda3 * lossp\n\n # sce = tf.nn.softmax_cross_entropy_with_logits_v2\n # align_lossu = sce(labels=soft_label, logits=nscua_logit)\n # align_lossp = sce(labels=soft_label, logits=nscpa_logit)\n # self.loss += .05 * (align_lossu + align_lossp)\n\n regularizer = tf.zeros(1)\n params = tf.trainable_variables()\n for param in params:\n if param not in self.embeddings.values():\n regularizer += tf.nn.l2_loss(param)\n self.loss = tf.reduce_mean(self.loss) + self.l2_rate * regularizer\n\n with tf.variable_scope(\"metrics\"):\n correct_prediction = tf.equal(prediction, input_y)\n mse = tf.reduce_sum(tf.square(prediction - input_y), name=\"mse\")\n correct_num = tf.reduce_sum(\n tf.cast(correct_prediction, dtype=tf.int32),\n name=\"correct_num\")\n accuracy = tf.reduce_sum(\n tf.cast(correct_prediction, \"float\"), name=\"accuracy\")\n\n return self.loss, mse, correct_num, accuracy\n\n def output_metrics(self, metrics, data_length):\n loss, mse, correct_num, _accuracy = metrics\n info = 'Loss = %.3f, RMSE = %.3f, Acc = %.3f' % \\\n (loss / data_length, sqrt(float(mse) / data_length), float(correct_num) / data_length)\n return info\n\n def record_metrics(self, dev_metrics, test_metrics, devlen, testlen):\n _dev_loss, _dev_mse, dev_correct_num, dev_accuracy = dev_metrics\n _test_loss, test_mse, test_correct_num, test_accuracy = test_metrics\n dev_accuracy = float(dev_correct_num) / devlen\n test_accuracy = float(test_correct_num) / testlen\n test_rmse = sqrt(float(test_mse) / testlen)\n if dev_accuracy > self.best_dev_acc:\n self.best_dev_acc = dev_accuracy\n self.best_test_acc = test_accuracy\n self.best_test_rmse = test_rmse\n info = 'NEW best dev acc: %.3f, NEW best test acc: %.3f, NEW best test RMSE: %.3f' % \\\n (self.best_dev_acc, self.best_test_acc, self.best_test_rmse)\n else:\n info = 'best dev acc: %.3f, best test acc: %.3f, best test RMSE: %.3f' % \\\n (self.best_dev_acc, self.best_test_acc, self.best_test_rmse)\n return info\n\n def train(self, optimizer, global_step):\n grads_and_vars = optimizer.compute_gradients(self.loss)\n capped_grads_and_vars = []\n\n for grad, v in grads_and_vars:\n if v is self.embeddings['wrd_emb']:\n grad = tf.IndexedSlices(grad.values * self.embedding_lr,\n grad.indices, grad.dense_shape)\n capped_grads_and_vars.append((grad, v))\n\n train_op = optimizer.apply_gradients(\n capped_grads_and_vars, global_step=global_step)\n return train_op\n","sub_path":"triamhnsc.py","file_name":"triamhnsc.py","file_ext":"py","file_size_in_byte":12027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"330980888","text":"import copy as cp\nimport numpy as np\nimport agent_utils\nfrom agents.replay_buffer.f_bar_replay_buffer import ReplayBuffer as FBarReplayBuffer\nimport deictic.tf_util_rob as U\n\n\nclass FBar:\n\n SCOPE = \"deep_f_bar\"\n FUNCTION_TEMPLATE = \"f_bar_func_{:d}\"\n\n def __init__(self, env, propositions_to_predict, neural_net_func, batch_size, optimizer, grad_norm_clipping=1.0,\n buffer_size=10000, log_predictions=False):\n \"\"\"\n Initialize an f bar agent.\n :param propositions_to_predict: List of indices of propositions to predict.\n :param neural_net_func: Neural network function.\n :param batch_size: Training batch size.\n :param optimizer: An instance of a Tensorflow optimizer.\n :param grad_norm_clipping: Clip gradients to this norm.\n :param log_predictions: Log predictions and the ground truth.\n :param buffer_size: Replay buffer size.\n \"\"\"\n\n self.env = env\n self.propositions_to_predict = propositions_to_predict\n self.num_propositions = len(propositions_to_predict)\n self.neural_net_func = neural_net_func\n self.batch_size = batch_size\n self.optimizer = optimizer\n self.grad_norm_clipping = grad_norm_clipping\n self.buffer_size = buffer_size\n self.log_predictions = log_predictions\n self.predictions_log = []\n\n self.make_obs_ph = None\n self.make_target_ph = None\n self.get_proposition_list = None\n self.train_proposition_list = None\n self.replay_buffer = None\n\n self.__build_make_placeholders()\n self.__build_networks()\n self.__build_training()\n\n self.replay_buffer = FBarReplayBuffer(self.buffer_size)\n\n def learn(self):\n \"\"\"\n Take one training step.\n :return: Mean accuracy for the current training bach.\n \"\"\"\n\n states, abstract_states = self.replay_buffer.sample(self.batch_size)\n\n is_correct = None\n for idx in range(self.num_propositions):\n\n _, tmp_is_correct = self.train_proposition_list[idx](states, abstract_states[:, idx])\n\n if is_correct is None:\n is_correct = tmp_is_correct\n else:\n is_correct *= tmp_is_correct\n\n f_bar_accuracy = np.mean(is_correct.astype(np.float32))\n\n return f_bar_accuracy\n\n def predict(self, observation, abstract_state=tuple()):\n \"\"\"\n Predict propositions.\n :param observation: An observation of the current state.\n :param abstract_state: Ground-truth abstract state. Some propositions can be inferred from the state of the\n robot (e.g. hand-empty), therefore, we do not need to predict them. Also, prediction\n logging will not work when this argument is empty.\n :return: A tuple of propositions (aka an abstract state).\n \"\"\"\n\n observation_input = np.expand_dims(observation[0], axis=0)\n\n predicted_propositions = []\n for idx in range(self.num_propositions):\n if self.get_proposition_list[idx](observation_input) > 0:\n predicted_propositions.append(idx)\n\n new_abstract_state = set(abstract_state)\n\n for idx, prop_idx in enumerate(self.propositions_to_predict):\n if idx in predicted_propositions:\n new_abstract_state.add(prop_idx)\n else:\n if prop_idx in new_abstract_state:\n new_abstract_state.remove(prop_idx)\n\n new_abstract_state = tuple(sorted(list(new_abstract_state)))\n\n if self.log_predictions:\n # log the real abstract state and the predicted abstract state\n ground_truth_matrix = self.__create_abstract_state_matrix(abstract_state)\n predicted_matrix = self.__create_abstract_state_matrix(new_abstract_state)\n self.predictions_log.append([ground_truth_matrix, predicted_matrix])\n\n return new_abstract_state\n\n def remember(self, observation, abstract_state):\n \"\"\"\n Remember a pair of observation and its corresponding abstract state.\n :param observation: An observation.\n :param abstract_state: An abstract state.\n :return: None.\n \"\"\"\n\n self.replay_buffer.add(cp.copy(observation[0]), self.__create_abstract_state_matrix(abstract_state))\n\n def __build_networks(self):\n \"\"\"\n Build a neural network for each state.\n :return: None.\n \"\"\"\n\n self.get_proposition_list = []\n\n for state_idx in range(self.num_propositions):\n\n get_proposition = agent_utils.build_get_f_bar(\n make_state_ph=self.make_obs_ph,\n f_bar_func=self.neural_net_func,\n scope=self.SCOPE,\n f_bar_scope=self.FUNCTION_TEMPLATE.format(state_idx + 1)\n )\n\n self.get_proposition_list.append(get_proposition)\n\n def __build_training(self):\n \"\"\"\n Define training functions for each neural network from build_networks.\n :return: None.\n \"\"\"\n\n self.train_proposition_list = []\n\n for state_idx in range(self.num_propositions):\n\n train_proposition = agent_utils.build_f_bar_train(\n make_state_ph=self.make_obs_ph,\n make_target_ph=self.make_target_ph,\n optimizer=self.optimizer,\n grad_norm_clipping=self.grad_norm_clipping,\n f_bar_func=self.neural_net_func,\n scope=self.SCOPE,\n f_bar_scope=self.FUNCTION_TEMPLATE.format(state_idx + 1)\n )\n\n self.train_proposition_list.append(train_proposition)\n\n def __build_make_placeholders(self):\n \"\"\"\n Define lambdas that make placeholders.\n :return: None.\n \"\"\"\n\n self.make_obs_ph = lambda name: U.BatchInput(self.env.observation_space.spaces[0].shape, name=name)\n self.make_target_ph = lambda name: U.BatchInput((), name=name)\n\n def __create_abstract_state_matrix(self, abstract_state):\n\n abstract_state_matrix = np.zeros((self.num_propositions,), dtype=np.int32)\n\n for idx, prop_idx in enumerate(self.propositions_to_predict):\n if prop_idx in abstract_state:\n abstract_state_matrix[idx] = 1\n\n return abstract_state_matrix\n\n def save_predictions_log(self, save_path):\n \"\"\"\n Save predictions log as a numpy array of the shape (num_predictions, 2, num_propositions).\n :param save_path: Save path.\n :return: None.\n \"\"\"\n\n predictions_log_matrix = np.array(self.predictions_log, dtype=np.int32)\n np.save(save_path, predictions_log_matrix)","sub_path":"agents/f_bar.py","file_name":"f_bar.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"103201745","text":"import numpy as np\nimport numpy.random as rnd\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom lib.activations import Softmax\nfrom lib.loss import Cross_entropy\nfrom lib.regularizers import Default, Ridge\nfrom lib.utils import *\n\n\nnp.set_printoptions(precision=5, suppress=True)\nrnd.seed(2021)\n\n\ndef display(img):\n plt.imshow(img)\n plt.show()\n\n\nclass Conv2D:\n def __init__(self, filters=1, filter_shape=3, stride=1, padding='same'):\n\n self.no_kernals = filters\n self.filter_shape = filter_shape\n self.kernals = rnd.randn(filter_shape, filter_shape, filters)\\\n / (self.filter_shape**2)\n self.padding = padding\n\n self.eta = 0.01\n self.sum_nw = 0\n\n def compile(self, input_shape):\n self.input_shape = input_shape\n if self.padding == 'same':\n h, w = input_shape\n h1, w1 = h + (self.filter_shape-1), w + (self.filter_shape-1)\n self.newimg = np.zeros((h1, w1))\n self.filter_map = np.zeros((h, w, self.no_kernals))\n\n output = self.forward(np.zeros(input_shape))\n self.output_shape = output.shape\n\n def gen_local_region(self, img):\n\n for r in range(self.input_shape[0]):\n for c in range(self.input_shape[1]):\n region = img[r:r+self.filter_shape, c:c+self.filter_shape]\n yield region, r, c\n\n def filter(self, img):\n h, w = img.shape\n ind1 = int(np.floor((self.filter_shape-1)/2))\n ind2 = int(np.ceil((self.filter_shape-1)/2))\n \n self.newimg.fill(img.min())\n self.newimg[ind1:h+ind2, ind1:w+ind2] = img\n\n #self.filter_map.fill(0)\n\n for region, r, c in self.gen_local_region(self.newimg):\n self.filter_map[r, c, ] = np.sum(region[:, :, np.newaxis] *\n self.kernals, axis=(0, 1))\n\n return norm(self.filter_map)\n\n def forward(self, x):\n return self.filter(x)\n\n def backpropagation(self, dLdx):\n\n dLdw = np.zeros(self.kernals.shape)\n \n for region, r, c in self.gen_local_region(self.newimg):\n dLdw += dLdx[r, c]*region[:, :, np.newaxis]\n\n self.sum_nw += dLdw\n\n def update_gradients(self, mbs):\n self.kernals -= self.eta*self.sum_nw/mbs\n self.sum_nw = 0\n\n\nclass Maxpool:\n def __init__(self, pool_size=2, padding='same'):\n self.pool = pool_size\n self.padding = padding\n self.eta = 0.01\n\n def compile(self, input_shape):\n self.input_shape = input_shape\n p = self.pool\n if self.padding == 'same':\n h, w, no_kernals = input_shape\n h1, w1 = h + (h % p), w + (w % p)\n self.newimg = np.zeros((h1, w1, no_kernals))\n self.filter_map = np.zeros((h1//p, w1//p, no_kernals))\n\n output = self.forward(np.zeros(input_shape))\n self.output_shape = output.shape\n\n def gen_local_region(self, img):\n p = self.pool\n h, w, no_kernals = img.shape\n h1, w1 = h//p, w//p\n \n self.max_indices = np.zeros((h1*w1*no_kernals, 3))\n self.mi_len = 0\n\n for r in range(h1):\n for c in range(w1):\n region = img[r*p:r*p+p, c*p:c*p+p]\n\n argmx = np.argwhere(region == np.amax(region, axis=(0, 1)))\n argmx[:, 0] += (r*p)\n argmx[:, 1] += (c*p)\n argmx = argmx[np.unique(argmx[:, 2], axis=0, return_index=True)[1]]\n argmx = argmx[argmx[:, 2].argsort()]\n for i in range(len(argmx)):\n self.max_indices[self.mi_len] = argmx[i]\n self.mi_len += 1\n \n yield region, r, c\n self.max_indices = self.max_indices[:self.mi_len]\n\n def filter(self, img):\n h, w, _ = img.shape\n p = self.pool\n self.newimg.fill(img.min())\n self.newimg[:h, :w, :] = img\n\n #self.filter_map = np.zeros((h1//p, w1//p, no_kernals))\n for region, r, c in self.gen_local_region(self.newimg):\n self.filter_map[r, c] = np.amax(region, axis=(0, 1))\n \n self.max_indices = self.max_indices.astype(np.int64)\n return self.filter_map\n\n def forward(self, x):\n return self.filter(x)\n\n def backpropagation(self, dLdx):\n p = self.pool\n self.reverse_max = np.zeros(self.newimg.shape)\n for (x, y, z) in self.max_indices:\n self.reverse_max[x, y, z] = dLdx[x//p, y//p, z]\n \n return self.reverse_max[:self.input_shape[0], :self.input_shape[1], :]\n\n\nclass Dense:\n def __init__(self, units, activation=Softmax()):\n self.units = units\n self.activation = activation\n self.eta = 0.01\n\n self.sum_nw, self.sum_nb = 0, 0\n\n def compile(self, input_shape):\n self.input_shape = input_shape\n self.init_weight(input_shape[0])\n output = self.forward(np.zeros(input_shape))\n self.output_shape = output.shape\n\n def init_weight(self, input_shape=1):\n self.w = rnd.normal(size=(self.units, input_shape))/input_shape\n self.b = rnd.normal(size=(self.units, 1))\n\n def forward(self, x):\n self.x = x\n self.z = np.matmul(self.w, x) + self.b\n self.a = self.activation.value(self.z)\n return self.a\n\n def backpropagation(self, dLda):\n dLdz = dLda*self.activation.dvalue(self.z)\n dLdw = np.matmul(dLdz, self.x.T)\n dLdb = dLdz\n dLdx = np.matmul(self.w.T, dLdz)\n\n self.sum_nw += dLdw\n self.sum_nb += dLdb\n return dLdx\n\n def update_gradients(self, mbs):\n\n self.w -= self.eta*self.sum_nw/mbs\n self.b -= self.eta*self.sum_nb/mbs\n self.sum_nw = self.sum_nb = 0\n\n\nclass Flatten:\n def __init__(self):\n pass\n\n def compile(self, input_shape):\n self.input_shape = input_shape\n output = self.forward(np.zeros(input_shape))\n self.output_shape = output.shape\n\n def forward(self, x):\n return x.flatten()[:, np.newaxis]\n\n def backpropagation(self, x):\n return x[:, 0].reshape(self.input_shape)\n\n\nclass Model:\n def __init__(self):\n pass\n\n def sequential(self, layers):\n self.conv = layers[0]\n self.maxpool = layers[1]\n self.flatten = layers[2]\n self.dense = layers[3]\n return self\n\n def compile(self, input_shape, learning_rate=0.01, loss=Cross_entropy()):\n self.input_shape = input_shape\n self.conv.compile(input_shape=input_shape)\n self.maxpool.compile(input_shape=self.conv.output_shape)\n self.flatten.compile(input_shape=self.maxpool.output_shape)\n self.dense.compile(input_shape=self.flatten.output_shape)\n\n self.eta = learning_rate\n self.conv.eta = self.maxpool.eta = self.dense.eta = self.eta\n self.loss = loss\n\n def summary(self):\n print(self.conv.input_shape, self.conv.output_shape)\n print(self.maxpool.input_shape, self.maxpool.output_shape)\n print(self.flatten.input_shape, self.flatten.output_shape)\n print(self.dense.input_shape, self.dense.output_shape)\n\n def get_loss(self, yp, y):\n\n return self.loss.value(yp, y)\n\n def feedforward(self, x):\n self.c1 = self.conv.forward(x)\n self.m1 = self.maxpool.forward(self.c1)\n self.f1 = self.flatten.forward(self.m1)\n self.a1 = self.dense.forward(self.f1)\n return self.a1\n\n def backpropagation(self, x, y):\n dLda1 = self.loss.dvalue(self.a1, y)\n dLdf1 = self.dense.backpropagation(dLda1)\n dLdm1 = self.flatten.backpropagation(dLdf1)\n dLdc1 = self.maxpool.backpropagation(dLdm1)\n dLdx = self.conv.backpropagation(dLdc1)\n\n def update_gradients(self):\n self.dense.update_gradients(self.mbs)\n self.conv.update_gradients(self.mbs)\n\n def fit(self, X, Y, val_set=None, mbs=32, epoch=1):\n ce = 0\n self.mbs = mbs\n print(X.shape, Y.shape)\n for i in range(epoch):\n ce, yt = 0, 0\n for ind, (x, y) in enumerate(zip(X, Y)):\n a2 = self.feedforward(x)\n \n if np.argmax(a2) == np.argmax(y):\n yt += 1\n ce += self.get_loss(a2, y)\n self.backpropagation(x, y)\n if (ind+1) % self.mbs == 0:\n self.update_gradients()\n self.update_gradients()\n print('ce loss', ce)\n print('train_acc', yt*100/X.shape[0], end='')\n print(' val_acc', accuracy(self, val_set[0], val_set[1]))\n\n def predict(self, x):\n return np.argmax(self.feedforward(x))\n\n def save(self, name):\n np.savez(name+'.npz',\n convker=self.conv.kernals,\n densew=self.dense.w,\n denseb=self.dense.b)\n\n def load(self, name):\n wgt = np.load(name+'.npz')\n self.conv.kernals = wgt['convker']\n self.dense.w = wgt['densew']\n self.dense.b = wgt['denseb']\n\n\ndef main():\n\n X_train, y_train, X_val, y_val = load_mnist(reshape=True, n_rows=1000)\n model = Model().sequential([Conv2D(filters=8, filter_shape=3),\n Maxpool(),\n Flatten(),\n Dense(10)])\n model.compile(X_train[0].shape)\n\n model.summary()\n model.load('cnn5')\n X_train = normalize(X_train)\n X_val = normalize(X_val)\n # display(X_val[0])\n # y1 = model.conv.forward(X_val[0])\n # f = 1\n for f in [0,1,2,3,4,5,6,7]:\n #display(y1[:, :, f])\n #display(model.maxpool.forward(y1)[:, :, f])\n\n display(model.conv.kernals[:, :, f])\n # display(X_train[0])\n #model.fit(X_train, y_train, (X_val, y_val), mbs=32, epoch=10)\n #model.save('cnn5')\n #annote_test(model, X_val[:9], 3, 3)\n\n\nmain()","sub_path":"cnn/cnn2.py","file_name":"cnn2.py","file_ext":"py","file_size_in_byte":9958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"227725785","text":"# -*- coding: utf-8 -*-\n\n\nclass User:\n # 用户\n def __init__(self, row):\n self.id = row[\"u_id\"]\n self.name = row[\"u_name\"]\n self.password = row[\"u_password\"]\n self.type = row[\"u_type\"]\n self.time = row[\"created_at\"]\n\n\nclass Relation:\n # 关系\n def __init__(self, row):\n self.id = row[\"r_id\"]\n self.student_id = row[\"s_id\"]\n self.teacher_id = row[\"t_id\"]\n self.time = row[\"created_at\"]\n\n\nclass Choice:\n # 选择题\n def __init__(self, row):\n self.id = row[\"c_id\"]\n self.chapter = row[\"chapter\"]\n self.content = row[\"c_content\"]\n self.contentA = row[\"c_a\"]\n self.contentB = row[\"c_b\"]\n self.contentC = row[\"c_c\"]\n self.contentD = row[\"c_d\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass ChoiceAnswer:\n # 选择题答案\n def __init__(self, row):\n self.id = row[\"ca_id\"]\n self.choice_id = row[\"c_id\"]\n self.student_id = row[\"s_id\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass Judge:\n # 判断题\n def __init__(self, row):\n self.id = row[\"j_id\"]\n self.chapter = row[\"chapter\"]\n self.content = row[\"j_content\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass JudgeAnswer:\n # 判断题答案\n def __init__(self, row):\n self.id = row[\"ja_id\"]\n self.judge_id = row[\"j_id\"]\n self.student_id = row[\"s_id\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass Objective:\n # 客观题\n def __init__(self, row):\n self.id = row[\"o_id\"]\n self.chapter = row[\"chapter\"]\n self.content = row[\"o_content\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass ObjectiveAnswer:\n # 客观题答案\n def __init__(self, row):\n self.id = row[\"oa_id\"]\n self.objective_id = row[\"o_id\"]\n self.student_id = row[\"s_id\"]\n self.answer = row[\"answer\"]\n self.score = row[\"score\"]\n self.time = row[\"created_at\"]\n\n\nclass Paper:\n # 试卷, content 为 json 数据格式,存放格式可以是\n \"\"\"\n 答题前:\n {\n 'sign': 'before',\n 'choices': [c_id1, c_id2, ...],\n 'judges': [j_id1, j_id2, ...],\n 'objectives': [o_id1, o_id2, ...],\n }\n\n 答题后更新为:\n {\n 'sign': 'after',\n 'choices': [c_id1, c_id2, ...],\n 'choice_answers': [ca_id1, ca_id2, ...],\n 'judges': [j_id1, j_id2, ...],\n 'judge_answers': [ja_id1, ja_id2, ...],\n 'objectives': [o_id1, o_id2, ...],\n 'objective_answers': [oa_id1, oa_id2, ...],\n }\n \"\"\"\n\n def __init__(self, row):\n self.id = row[\"p_id\"]\n self.student_id = row[\"s_id\"]\n self.teacher_id = row[\"t_id\"]\n self.content = row[\"content\"]\n self.grade = row[\"grade\"]\n self.time = row[\"created_at\"]\n","sub_path":"model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"378556835","text":"\"\"\"\r\nSupport for Phicomm Air Detector M1 plant sensor.\r\nDeveloper by lixinb & NETYJ\r\nversion 3.0\r\n\"\"\"\r\nimport logging\r\nimport datetime\r\nimport requests,json\r\nimport voluptuous as vol\r\nimport hashlib\r\nimport threading\r\nimport time\r\n\r\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\r\nfrom homeassistant.const import (CONF_NAME)\r\nfrom homeassistant.helpers.entity import Entity\r\nimport homeassistant.helpers.config_validation as cv\r\n\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n_INTERVAL = 15\r\n\r\nSCAN_INTERVAL = datetime.timedelta(seconds=_INTERVAL)\r\nDEFAULT_NAME = 'Phicomm M1'\r\nCONF_DEVICES = 'devices'\r\nDEFAULT_PATH = '/config/phicomm_token.txt'\r\nCONF_PATH = 'tokenPath'\r\n\r\nATTR_TEMPERATURE = 'temperature'\r\nATTR_HUMIDITY = 'humidity'\r\nATTR_PM25 = 'pm25'\r\nATTR_HCHO = 'hcho'\r\nATTR_BRIGHTNESS = 'brightness'\r\nATTR_NAME = 'name'\r\n\r\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\r\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\r\n vol.Optional(CONF_PATH, default=DEFAULT_PATH): cv.string,\r\n vol.Required(CONF_DEVICES): dict,\r\n})\r\n\r\n\r\ndef setup_platform(hass, config, add_devices, discovery_info=None):\r\n \"\"\"Set up the Phicomm M1 sensor.\"\"\"\r\n _LOGGER.debug(\"setup_platform\")\r\n\r\n name = config.get(CONF_NAME)\r\n devices = config.get(CONF_DEVICES)\r\n tokenPath = config.get(CONF_PATH)\r\n devs = []\r\n for item_name, item in devices.items():\r\n for mac, led in item.items():\r\n deviceId = '1-' + mac.upper()\r\n devs.append(PhicommM1Sensor(hass, name+'_'+item_name, deviceId, led, tokenPath))\r\n\r\n add_devices(devs)\r\n\r\n\r\nclass PhicommM1Sensor(Entity):\r\n \"\"\"Implementing the Phicomm M1 sensor.\"\"\"\r\n \r\n tmark = False\r\n \r\n access_token = None\r\n fIsLogon = False\r\n deviceDatas = {}\r\n iCount = 0\r\n tokenPath = DEFAULT_PATH\r\n \r\n def __init__(self, hass, name, deviceId, led, tokenPath):\r\n \"\"\"Initialize the sensor.\"\"\"\r\n _LOGGER.debug(\"name:%s, deviceId:%s, led:%s\",name, deviceId, led)\r\n \r\n self._hass = hass\r\n self._name = name\r\n self.deviceId = deviceId\r\n self.led = led\r\n self._tokenPath = tokenPath\r\n self._state = None\r\n self.data = []\r\n self.lastResponeMsg = ''\r\n self._state_attrs = {\r\n ATTR_PM25: None,\r\n ATTR_TEMPERATURE: None,\r\n ATTR_HUMIDITY: None,\r\n ATTR_HCHO: None,\r\n ATTR_BRIGHTNESS: int(50),\r\n ATTR_NAME: None,\r\n }\r\n #self.update()\r\n \r\n @property\r\n def name(self):\r\n \"\"\"Return the name of the sensor.\"\"\"\r\n return self._name\r\n\r\n @property\r\n def state(self):\r\n \"\"\"Return the state of the sensor.\"\"\"\r\n return self._state_attrs[ATTR_PM25]\r\n \r\n @property\r\n def state_attributes(self):\r\n \"\"\"Return the state of the sensor.\"\"\"\r\n return self._state_attrs\r\n \r\n def updateIdxData():\r\n while True:\r\n try:\r\n time.sleep(_INTERVAL)\r\n if PhicommM1Sensor.fIsLogon is False:\r\n PhicommM1Sensor.iCount += 1\r\n if PhicommM1Sensor.iCount < 4:\r\n continue\r\n \r\n PhicommM1Sensor.iCount = 0\r\n \r\n if PhicommM1Sensor.access_token is None or PhicommM1Sensor.fIsLogon is False:\r\n with open(PhicommM1Sensor.tokenPath, 'r') as f:\r\n PhicommM1Sensor.access_token = f.read()\r\n \r\n if PhicommM1Sensor.access_token is None:\r\n continue\r\n \r\n _LOGGER.debug(\"here is the updateIdxData thread. iCount:%s\", PhicommM1Sensor.iCount)\r\n headers = {'User-Agent': 'zhilian/5.7.0 (iPhone; iOS 10.0.2; Scale/3.00)',\r\n 'Authorization': PhicommM1Sensor.access_token }\r\n resp = requests.get('https://aircleaner.phicomm.com/aircleaner/getIndexData', headers=headers,timeout=3)\r\n if resp.status_code == 200:\r\n obj = resp.json() \r\n error = obj['error']\r\n if int(error) == 0:\r\n PhicommM1Sensor.fIsLogon = True\r\n for catDevData in iter(obj['data']['devs']):\r\n jsonData = catDevData['catDev']\r\n PhicommM1Sensor.deviceDatas[jsonData['deviceId']] = {\r\n ATTR_PM25: jsonData['pm25'],\r\n ATTR_TEMPERATURE: jsonData['temperature'],\r\n ATTR_HUMIDITY: jsonData['humidity'],\r\n ATTR_HCHO: jsonData['hcho'],\r\n ATTR_NAME: jsonData['name'],\r\n }\r\n _LOGGER.debug(obj['data'])\r\n else:\r\n PhicommM1Sensor.fIsLogon = False\r\n _LOGGER.error(obj['msg'])\r\n except OSError as e:\r\n PhicommM1Sensor.fIsLogon = False\r\n _LOGGER.error(\"OSError: %s\",e)\r\n \r\n def update(self):\r\n \"\"\"\r\n Update current conditions.\r\n \"\"\"\r\n _LOGGER.debug(\"here is name:%s, deviceId:%s, PhicommM1Sensor.tmark:%s, PhicommM1Sensor.fIsLogon:%s\",self.name, self.deviceId, PhicommM1Sensor.tmark, PhicommM1Sensor.fIsLogon)\r\n \r\n if PhicommM1Sensor.tmark is False:\r\n PhicommM1Sensor.tmark = True\r\n PhicommM1Sensor.tokenPath = self._tokenPath\r\n t = threading.Thread(target=PhicommM1Sensor.updateIdxData)\r\n t.start()\r\n \r\n if PhicommM1Sensor.fIsLogon is False:\r\n return None\r\n \r\n try: \r\n \r\n headers = {'User-Agent': 'zhilian/5.7.0 (iPhone; iOS 10.0.2; Scale/3.00)',\r\n 'Authorization': PhicommM1Sensor.access_token }\r\n brightness_state = 50\r\n brightness = self._hass.states.get(self.led)\r\n if brightness is not None:\r\n brightness_state = int(float(brightness.state))\r\n if self._state_attrs[ATTR_BRIGHTNESS] != brightness_state:\r\n _LOGGER.debug('brightness_state changing, new value %s, last value %s',brightness_state, self._state_attrs[ATTR_BRIGHTNESS])\r\n if brightness_state == 50:\r\n _brightness_state = 100\r\n else:\r\n _brightness_state = brightness_state\r\n post_data = {'brightness':_brightness_state,'deviceId': self.deviceId}\r\n control_resp = requests.post('https://aircat.phicomm.com/connectserverv1/lightControl', data=post_data, headers=headers,timeout=3)\r\n if control_resp.status_code == 200:\r\n control_obj = control_resp.json() \r\n if int(control_obj['error']) != 0: \r\n _LOGGER.error('Phicomm lightControl fail!: %s', control_obj)\r\n \r\n payload = {'deviceId': self.deviceId}\r\n resp = requests.get('https://aircat.phicomm.com/connectserverv1/lightControl', params=payload, headers=headers,timeout=3)\r\n if resp.status_code == 200:\r\n obj = resp.json() \r\n error = obj['error']\r\n if int(error) == 0:\r\n _brightness_state = int(obj['brightness'])\r\n if _brightness_state == 100:\r\n brightness_state = 50\r\n else:\r\n brightness_state = _brightness_state\r\n #_LOGGER.debug('brightness_state %s',brightness_state)\r\n states_attrs = {\r\n 'min':'0.0',\r\n 'max':'50.0',\r\n 'step':'25.0',\r\n 'mode':'slider',\r\n 'friendly_name':'屏幕亮度',\r\n 'icon':'mdi:led-on'\r\n }\r\n self._hass.states.set(self.led,float(brightness_state),states_attrs)\r\n #_LOGGER.debug('input_number.phicomm_m1_led.state is set to: %s',self._hass.states.get(self.led))\r\n else:\r\n _LOGGER.error('get lightness error, %s',obj)\r\n \r\n jsonData = PhicommM1Sensor.deviceDatas[self.deviceId]\r\n self._state_attrs = {\r\n ATTR_PM25: jsonData['pm25'],\r\n ATTR_TEMPERATURE: jsonData['temperature'],\r\n ATTR_HUMIDITY: jsonData['humidity'],\r\n ATTR_HCHO: jsonData['hcho'],\r\n ATTR_BRIGHTNESS: brightness_state,\r\n ATTR_NAME: jsonData['name'],\r\n }\r\n _LOGGER.debug(\"here is name:%s, deviceId:%s, _state_attrs: %s\",self.name, self.deviceId, self._state_attrs)\r\n \r\n except OSError as e:\r\n _LOGGER.error(\"OSError: %s\",e)\r\n ","sub_path":"custom_components/sensor/PhicommAirDetector.py","file_name":"PhicommAirDetector.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"349987502","text":"from flask import Flask, request, abort\nimport requests\nimport json\nimport subprocess\nfrom requests.auth import HTTPBasicAuth\nimport os\n\napp = Flask(__name__)\n\nurl = \"\"\nusername = \"\"\npassword = \"\"\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n if request.method == 'POST':\n #print(request.json)\n incomingpayload = request.json\n #print(j)\n for k,v in incomingpayload.items(): \n if k == \"alerts\":\n for alert in v:\n #print(\"Stuff from Alertmanager\")\n #print(alert.keys())\n #print(alert['status'])\n #print(alert['labels']['node'])\n #print(alert['labels']['datacenter'])\n #print(alert['endsAt'])\n #print(alert['generatorURL'])\n #print(alert['startsAt'])\n #print(alert['annotations']['summary'])\n #print(alert['annotations']['description'])\n e = subprocess.check_output([\"date\", \"-u\", \"+%Y-%m-%dT%H:%M:%S.000Z\"])\n dateTime = e.decode('ascii').strip() \n itsmpayload = {\n \"events\": [{\n \"action\": \"CREATE\",\n \"ci_id\": alert['labels']['node'],\n \"company\": \"246598352\",\n \"clear_on_acknowledge\" : \"False\",\n \"custom_attributes\": \"\",\n \"description\": alert['annotations']['description'],\n \"eis_update_state\": \"CHANGED\",\n \"managed_state\": \"managed\",\n \"name\": alert['annotations']['summary'],\n \"priority\":\"1\",\n \"status\":\"Active\",\n \"source_management_platform\": \"Prometheus\",\n \"source_id\": dateTime,\n \"source\":\"Prometheus UCS\",\n \"severity\": \"1\",\"schema_type\": \"General\",\n \"type\": \"HOST\"\n }],\n \"action\": \"CREATE\",\n \"send_time\": dateTime,\n \"send_to\":\"DIMENSIONDATASERVICES\" \n } \n headers = {'Content-Type':'application/json','cache-control':'no-cache'}\n \n j = json.dumps(itsmpayload)\n print(j)\n \n \n response = requests.request(\"POST\", url, data=j, headers=headers, auth=HTTPBasicAuth(username, password),verify=False)\n #break to be removed after validating flood control\n break\n return '', 200 \n else:\n abort(400)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"flash_app/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510007911","text":"'''Como pedido na video-aula desta semana, \nescreva um programa que calcula as raízes de uma equação do segundo grau.\nO programa deve receber os parâmetros a, b, e c da equação ax2+bx+c, \nrespectivamente, e imprimir o resultado na saída da seguinte maneira:\n\tQuando não houver raízes reais imprima:\n\testa equação não possui raízes reais\n\n\tQuando houver apenas uma raiz real imprima:\n\ta raiz desta equação é X\n\tonde X é o valor da raiz\n\n\tQuando houver duas raízes reais imprima:\n\tas raízes da equação são X e Y\n\tonde X e Y são os valor das raízes.\n\nAlém disto, no caso de existirem 2 raízes reais, \nelas devem ser impressas em ordem crescente, ou seja, X deve ser menor ou igual a Y.\n'''\nimport math\nprint(\"_____________________________________________________________________________\")\nprint(\"Dado a equação no formato ax²+bx+c, informe os valores das variáveis a,b e c:\")\nprint(\"_____________________________________________________________________________\")\na = int(input(\"# Valor de a: \"))\nb = int(input(\"# Valor de b: \"))\nc = int(input(\"# Valor de c: \"))\ndelta = b**2 - (4*a*c)\n\nif(delta<0):\n\tprint(\"esta equação não possui raízes reais\")\nif(delta==0):\n\tx = -b /2*a\n\tprint(\"a raiz desta equação é \",x)\nif(delta>0):\n\tx1= (-b + math.sqrt(delta))/2*a\n\tx2= (-b - math.sqrt(delta))/2*a\n\tif(x1==x2):\n\t\tprint(\"a raiz desta equação é \",x1)\n\telif(x1>x2):\n\t\tprint(\"as raízes desta esquação são \", x2, \" e \", x1)\n\telse:\n\t\tprint(\"as raízes desta esquação são \", x1, \" e \", x2)","sub_path":"semana02/exercicio01.py","file_name":"exercicio01.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"632669274","text":"import os\nimport re\nimport sys\nimport json\nimport werobot\nimport pymysql\nimport logging\nimport smtplib\nimport threading\n\nfrom logging import handlers\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr\n\nmy_sender=\"\"\nmy_pass=\"\"\nmy_user=\"\"\n\ndef _logging(**kwargs):\n level = kwargs.pop('level', None)\n filename = kwargs.pop('filename', None)\n datefmt = kwargs.pop('datefmt', None)\n format = kwargs.pop('format', None)\n if level is None:\n level = logging.DEBUG\n if filename is None:\n filename = 'default.log'\n if datefmt is None:\n datefmt = '%Y-%m-%d %H:%M:%S'\n if format is None:\n format = '%(asctime)s [%(module)s] %(levelname)s [%(lineno)d] %(message)s'\n\n log = logging.getLogger(filename)\n format_str = logging.Formatter(format, datefmt)\n\n def namer(filename):\n return filename.split('default.')[1]\n\n os.makedirs(\"./debug/logs\", exist_ok=True)\n th_debug = handlers.TimedRotatingFileHandler(filename=\"./debug/\" + filename, when='D',\n encoding='utf-8')\n # th_debug.namer = namer\n th_debug.suffix = \"%Y-%m-%d.log\"\n th_debug.setFormatter(format_str)\n th_debug.setLevel(logging.DEBUG)\n log.addHandler(th_debug)\n\n th = handlers.TimedRotatingFileHandler(\n filename=filename, when='D', encoding='utf-8')\n th.suffix = \"%Y-%m-%d.log\"\n th.setFormatter(format_str)\n th.setLevel(logging.INFO)\n log.addHandler(th)\n log.setLevel(level)\n return log\n\n \nwith open('config.json') as f:\n fileJson = json.load(f)\n robot = werobot.WeRoBot(token=fileJson['token'])\n robot.config['APP_ID'] = fileJson['appID']\n robot.config['APP_SECRET'] = fileJson['appsecret']\n robot.config['HOST'] = fileJson['host']\n robot.config['PORT'] = fileJson['port']\n my_sender = fileJson['mailsender']\n my_pass = fileJson['mailpass']\n my_user = fileJson['mailreceiver']\n dbuser, dbpass = fileJson['baseName'], fileJson['basePass']\n\ndef mail(text):\n print(\"Email sender called\")\n ret = True\n try:\n # 邮件内容\n print(my_pass)\n msg = MIMEText(text, 'plain', 'utf-8')\n # 括号里的对应发件人邮箱昵称、发件人邮箱账号\n msg['From'] = formataddr([\"微信公众号后台\", my_sender])\n # 括号里的对应收件人邮箱昵称、收件人邮箱账号\n msg['To'] = formataddr([\"管理员\", my_user])\n # 邮件的主题\n msg['Subject'] = \"物品兑换提醒\"\n server = smtplib.SMTP_SSL(\"smtp.exmail.qq.com\", 465)\n server.login(my_sender, my_pass)\n server.sendmail(my_sender, [my_user, ], msg.as_string())\n server.quit()\n print(\"here\")\n except Exception:\n ret = False\n return ret\n return ret\n\n\nos.makedirs('./logs', exist_ok=True)\nlogger = _logging(filename='./logs/default')\n\n\nadmin = []\nwith open('admins.ini') as f:\n for line in f.readlines():\n line = line.strip('\\n')\n admin.append(line)\nprint(admin)\ndb = pymysql.connect(host='127.0.0.1', user=dbuser,\n passwd=dbpass, port=3306, db='rj93', charset='utf8')\n\n\ndef reg(wechat_id, name):\n se_result = _search(wechat_id)\n if(se_result[0] != sys.maxsize):\n return '%s,您已经注册过了,修改信息执行\"改名\"指令。' % se_result[1]\n cursor = db.cursor()\n sql = 'INSERT INTO wechat(wechat_id, point, name) VALUES (\"%s\",%d,\"%s\")' % (\n wechat_id, 0, name)\n try:\n cursor.execute(sql)\n db.commit()\n cursor.close()\n logger.info('%s registered with name %s successfully' %\n (wechat_id, name))\n return \"注册成功!\"\n except:\n # rollback when exception occurs\n db.rollback()\n cursor.close()\n logger.info('%s failed to register with name %s' % (wechat_id, name))\n return \"数据库出现错误,请稍候再试。如果连续出现此提示请联系管理员。\"\n\n\ndef _search(wechat_id):\n # returns (point,name). If not registered, point=sys.maxsize\n cursor = db.cursor()\n try:\n cursor.execute('SELECT * FROM wechat WHERE wechat_id = \"%s\"' ,(wechat_id))\n result = cursor.fetchall()\n cursor.close()\n if(len(result) != 0):\n return result[0][1], result[0][2]\n except:\n cursor.close()\n return sys.maxsize, ''\n return sys.maxsize, ''\n\n\ndef search(wechat_id):\n se_result = _search(wechat_id)\n if(se_result[0] == sys.maxsize):\n return \"您尚未注册,不能执行此操作。请先注册。\"\n else:\n return \"%s,您的可用积分为:%d\" % (se_result[1], se_result[0])\n\n\ndef update_point(wechat_id, delta):\n # 更改积分的方法 delta为积分增量\n se_result = _search(wechat_id)\n if(se_result[0] == sys.maxsize):\n return -1 # Not registered\n cursor = db.cursor()\n try:\n cursor.execute('UPDATE wechat SET point = point + %d WHERE wechat_id = \"%s\"',(delta, wechat_id))\n db.commit()\n cursor.close()\n logger.info('%s \\'s point update with increment %d' %\n (wechat_id, delta))\n return 1 # success\n except:\n db.rollback()\n cursor.close() \n return -20 #Failed\n\n\ndef update_name(wechat_id, new_name):\n # 更改用户名的方法\n se_result = _search(wechat_id)\n if(se_result[0] == sys.maxsize):\n return -1 # Not registered\n cursor = db.cursor()\n sql = 'UPDATE wechat SET name = \"%s\" WHERE wechat_id = \"%s\"' % (\n new_name, wechat_id)\n try:\n cursor.execute(sql)\n db.commit()\n cursor.close()\n logger.info('%s update name to %s' % (wechat_id, new_name))\n return 1 # success\n except:\n db.rollback()\n cursor.close()\n return -2 # Failed\n\n\ndef usecdk(wechat_id, cdk):\n # 使用激活码兑换积分的方法\n cursor = db.cursor()\n sql = 'SELECT * FROM cdkeys WHERE cdkey = \"%s\" AND usageLeft > 0 ' % (cdk)\n try:\n cursor.execute(sql)\n result = cursor.fetchall()\n if(len(result) != 0):\n if(result[0][4] == 0): # 0 stands for not-allowed-reuse\n if wechat_id in str(result[0][3]).split(','):\n return -15 # already used\n sql = 'UPDATE cdkeys SET usageLeft = usageLeft - 1 WHERE cdkey = \"%s\"' % (\n result[0][0])\n cursor.execute(sql)\n sql = 'UPDATE cdkeys SET usedUsers = \"%s\" WHERE cdkey = \"%s\"' % (\n str(wechat_id)+\",\"+str(result[0][3]), cdk)\n cursor.execute(sql)\n db.commit()\n cursor.close()\n return update_point(wechat_id, result[0][1])\n return -10 # No accessible cdk found\n except:\n db.rollback()\n cursor.close()\n return -20 # exception occured\n\n\ndef getreward(wechat_id, name):\n # 使用积分兑换奖品的方法\n cursor = db.cursor()\n sql = 'SELECT * FROM rewards WHERE Name = \"%s\" AND usageLeft > 0 ' % (name)\n try:\n cursor.execute(sql)\n result = cursor.fetchall()\n if(len(result) != 0):\n if(result[0][4] == 0): # 0 stands for not-allowed-reuse\n if wechat_id in str(result[0][3]).split(','):\n return -15 #already used\n if(_search(wechat_id)[0]+result[0][1]<0):\n return -16 # Not enough point\n sql= 'UPDATE rewards SET usageLeft = usageLeft - 1 WHERE Name = \"%s\"' % (result[0][0])\n cursor.execute(sql)\n sql = 'UPDATE rewards SET usedUsers = \"%s\" WHERE Name = \"%s\"' % (\n str(wechat_id)+\",\"+str(result[0][3]), name)\n cursor.execute(sql)\n db.commit()\n cursor.close()\n print(\"Starting searching info\")\n if(mail(_search(wechat_id)[1]+\"(\"+str(wechat_id)+\")兑换了[\"+result[0][0]+\"],请尽快处理\")):\n return update_point(wechat_id,result[0][1]) \n return -30 # Failed to send email to the admin\n return -10 # No accessible cdk found\n except:\n db.rollback()\n cursor.close()\n return -20 # exception occured\n\n\n@robot.filter(re.compile(\"注册([\\t ]*)(.*)\"))\ndef reply_reg(message, session, matchObj):\n if(len(matchObj.group(2).strip()) != 0):\n return reg(message.source, matchObj.group(2))\n else:\n return '请按照\"注册 用户名\"(如:注册 王老板)的格式输入。'\n\n\n@robot.filter(\"查询\")\ndef reply_req(message):\n return search(message.source)\n\n\n@robot.filter(\"标识码\")\ndef reply_req(message, session, match):\n return (message.source)\n\n\n@robot.filter(\"签到\")\ndef reply_bonus(message, session, match):\n if(update_point(message.source, +100) == 1):\n return \"签到成功,积分+100!\"\n return \"您尚未注册,不能执行此操作。请先注册。\"\n\n\n@robot.filter(re.compile(\"激活([\\t ]*)(.*)\"))\ndef reply_change(message,session, matchObj):\n reply_msg={1:\"激活成功!\",-15:\"激活失败,该奖励码每人仅限兑换一次。\",\n-10:\"激活失败,输入的奖励码有误。\",-20:\"数据库出现错误,请稍候再试。如果连续出现此提示请联系管理员。\",-1:\"您尚未注册。\"\n}\n cdk=matchObj.group(2).strip()\n if(len(cdk)!=0):\n return reply_msg[usecdk(message.source,cdk)]\n else:\n return '请按照\"激活 代码\"(如:激活 sample)的格式输入。'\n\n\n@robot.filter(re.compile(\"改名([\\t ]*)(.*)\"))\ndef reply_change(message,session, matchObj):\n reply_msg={1:\"修改成功!\",-1:\"您尚未注册,不能执行此操作。请先注册。\",-2:\"数据库出现错误,请稍候再试。如果连续出现此提示请联系管理员。\"}\n if(len(matchObj.group(2).strip())!=0):\n return reply_msg[update_name(message.source,matchObj.group(2).strip())]\n else:\n return '请按照\"改名 姓名\"(如:改名 王老板)的格式输入。'\n\n\n@robot.filter(re.compile(\"兑换([\\t ]*)(.*)\"))\ndef reply_reward(message,session, matchObj):\n reply_msg={1:\"兑换成功!请等待工作人员联系。\",-15:\"兑换失败,该物品每人仅限兑换一次。\",\n-16:\"兑换失败,您的积分不足\",-30:\"兑换失败,积分不足。\",-20:\"数据库出现错误,请稍候再试。如果连续出现此提示请联系管理员。\",-1:\"您尚未注册。\",\n-10:\"兑换失败,输入的物品名有误。\"\n}\n cdk=matchObj.group(2).strip()\n if(len(cdk)!=0):\n return reply_msg[getreward(message.source,cdk)]\n else:\n cursor = db.cursor()\n sql = \"SELECT * FROM rewards\"\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n resultstr = \"\"\n for row in results:\n name_ = row[0]\n point_ = row[1]\n use_ = row[2]\n reuse_ = row[4]\n resultstr=resultstr+ \"%s,所需积分%d,剩余个数%d,%s允许重复兑换\\n\" % (name_,-point_, use_, \"\" if reuse_ else \"不\")\n except:\n return reply_msg[-20]\n return resultstr +'请按照\"兑换 物品名\"(如:兑换 sample)的格式输入。'\n\ndef reply_help():\n return '回复\"注册 用户名\"(如:注册 王老板)为当前微信号注册账号\\n回复\"查询\"获取当前积分\\n回复\"签到\"获取积分+1\\\n \\n回复\"激活\"激活积分代码\\n回复\"改名\"修改用户名\\n回复\"兑换\"使用积分换取奖励'\n\n\nrobot.add_filter(func=reply_help, rules=[\"?\", \"?\", \"help\"])\n\n# ======= admin methods =======\n\n\n@robot.filter(\"后台\")\ndef reply_add_cdk(message):\n # 考虑加密存储admin\n if (message.source in admin):\n return \"success\"\n return \"权限不足\"\n\n@robot.handler\ndef reply_no_found():\n return \"找不到您所输入的指令,请检查您的输入。\"\n\n\n# 让服务器监听在 0.0.0.0:2562\nrobot.run()\n","sub_path":"sever.py","file_name":"sever.py","file_ext":"py","file_size_in_byte":11904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282915575","text":"# Multinomial model to classify resumes\n\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\nfrom sklearn import metrics\n\n\n\ndef checkJD(example):\n content= vectorizer.transform(example)\n JDPre = classifier.predict(content)\n return JDPre\n\ndef suitabledata(group):\n df1= group.drop_duplicates()\n return df1\n \n#df1= pd.read_csv(\"finalcontentjd.csv\")\ndf1=pd.read_csv('/home/shubhi/nltk_data/TrainingData.csv')\nvectorizer = CountVectorizer()\ncounts = vectorizer.fit_transform(df1['Content'].values)\nlis=list()\nclassifier = MultinomialNB()\ntargets = df1['JD'].values\nclassifier.fit(counts, targets)\n\ndf = pd.read_csv(\"/home/shubhi/nltk_data/log1.csv\")\ndf = suitabledata(df)\nset1 = set(df['JD'].values)\nprint(set1)\ngroups = df.groupby('JD')\nxtest = df['Content'].values\nytest = df['JD'].values\nypred = checkJD(xtest)\na=metrics.accuracy_score(ytest , ypred)\nprint('accuracy score is :: ', a)\nfor i in set1:\n curgroup = groups.get_group(i)\n xtest = curgroup['Content'].values\n ytest = curgroup['JD'].values\n ypred = checkJD(xtest)\n a=metrics.accuracy_score(ytest , ypred)\n print('For Job Description ', i , 'accuracy score is :: ', a)\n print(\"\")\n print(ytest)\n print(ypred)\n \n","sub_path":"Models/model1.py","file_name":"model1.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"474945522","text":"from pico2d import *\n\nopen_canvas()\n\ngrass=load_image('grass.png')\ncharacter=load_image('character.png')\n\nxpos=0\n\nwhile(xpos<800):\n clear_canvas_now()\n grass.draw_now(400, 30)\n character.draw_now(xpos, 90)\n xpos=xpos+2\n delay(0.01)\n\nclose_canvas()\n","sub_path":"Drill05/character_grass.py","file_name":"character_grass.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32025508","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 03 11:11:22 2017\r\n\r\n@author: A\r\n\"\"\"\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.optimize import fsolve\r\nfrom scipy.special import iv\r\n#from scipy.signal import find_peaks_cwt\r\n\r\nplt.close('all')\r\n\r\nzStart=1.55\r\nzEnd=230\r\nzStep=0.005#########################################步长不要小于0.005,否则贝塞尔函数求解会出错\r\n\r\nFreq=162.5\r\ncLight=299792458\r\nlambda_m=cLight/Freq/1.e6\r\n\r\ncell_Beta_A_a_m_Z_L=np.loadtxt('V.txt')\r\n\r\ncell=cell_Beta_A_a_m_Z_L[:,0]\r\nBeta=cell_Beta_A_a_m_Z_L[:,1]\r\nA=cell_Beta_A_a_m_Z_L[:,2]\r\na=cell_Beta_A_a_m_Z_L[:,3]\r\nm=cell_Beta_A_a_m_Z_L[:,4]\r\nZ=cell_Beta_A_a_m_Z_L[:,5]######################################end of the cell#####################\r\nL=cell_Beta_A_a_m_Z_L[:,6]\r\n\r\n\r\nV4_cell_z_a_m_r0=np.loadtxt('RFQ.V4.txt')\r\n\r\ncell_V4=V4_cell_z_a_m_r0[:,0]############################################start at cell4#############\r\nz_V4=np.array(V4_cell_z_a_m_r0[:,1])+1.52919########################start of the cell################\r\na_V4=V4_cell_z_a_m_r0[:,2]\r\nr0_V4=V4_cell_z_a_m_r0[:,3]\r\nL_V4=z_V4[1:]-z_V4[:-1]############################################Cell长度比其他参数少一组##########\r\n\r\n\r\n\r\nnumCell=len(cell)\r\nnREC=int((zEnd-zStart)/zStep)+2\r\nxREC=np.zeros((nREC,2))\r\nxREC_2=np.zeros((nREC,2))\r\nzREC=np.zeros(nREC)\r\ncellREC=np.zeros(nREC)\r\ncellFlagREC=np.zeros(nREC)\r\nRhoREC=np.zeros(nREC)\r\n\r\nLREC=np.zeros(nREC)\r\nLcal=np.zeros(nREC)\r\n \r\n\r\niCellFlag=1\r\n\r\nzRec=zStart\r\n\r\n\r\ndef RFQVane(x,a,k,z,m):########################################################定义RFQ极头函数\r\n\tA=(m**2-1)/(m**2*iv(0,k*a)+iv(0,m*k*a))\r\n\treturn x**2/a**2-(1-A*iv(0,k*x)*np.cos(k*z))/(1-A*iv(0,k*a))\r\n\r\n\r\ndef RFQVane_V4(x,a,z,L,r0):\r\n\tk=np.pi/L\r\n\tchi=(a/r0)**2\r\n\tA=(1-chi)/iv(0,k*a)\r\n\treturn x**2/a**2-(1-A*iv(0,k*x)*np.cos(k*z))/chi\r\n\r\n\r\ndef Rho(a,k,m):\r\n\tA=(m**2-1)/(m**2*iv(0,k*a)+iv(0,m*k*a))\r\n\tRho=0.75*a/np.sqrt(1-A*iv(0,k*a))\r\n\treturn Rho\r\n\r\n\r\n\r\niREC=0;\r\nwhile (zRec0]) -1 ###############################判断所取点在第几个Cell\r\n\t \r\n\tif (iCell<4): \r\n\t\tiCellFlag=(-1)**iCell\r\n\t\tif (iCellFlag>0):\r\n\t\t\tzCal=zRec-Z[iCell]\r\n\t\t\tzCal_2=Z[iCell]-zRec\r\n\t \r\n\t\telse:\r\n\t\t\tzCal=Z[iCell+1]-zRec\r\n\t\t\tzCal_2=zRec-Z[iCell-1]\t \r\n\t #zCal=zRec-Z[iCell] \t \t \r\n\t #k=np.pi/L[iCell]\r\n\t\tbetaK=np.interp(zRec,Z,Beta)\r\n\t\tk=np.pi/betaK/lambda_m/100*2\r\n\t\t#k=np.pi/np.interp(zRec,Z,L)##############################用L数据计算对比发现和用beta计算CELL长度并没有区别\r\n\r\n\t\taInterP=np.interp(zRec,Z,a)\r\n\t\tmInterP=np.interp(zRec,Z,m)\r\n\t\txRecTmp = fsolve(RFQVane,[-0.3],args=(aInterP,k,zCal,mInterP))\r\n\t\txRecTmp_2 = fsolve(RFQVane,[-0.3],args=(aInterP,k,zCal_2,mInterP))\r\n\r\n\t\t \r\n\telse: \r\n\t\taInterP=np.interp(zRec,Z,a)\r\n\t\tmInterP=np.interp(zRec,Z,m)\r\n\t\tbetaK=np.interp(zRec,Z,Beta)\r\n\t\tk=np.pi/betaK/lambda_m/100*2\r\n\r\n\r\n\t\tiCellFlag=(-1)**iCell\r\n\t\tif (iCellFlag>0):\r\n\t\t\tzCal=zRec-z_V4[iCell-4]\r\n \t \r\n\t\telse:\r\n\t\t\tzCal=z_V4[iCell-3]-zRec\r\n\r\n\t\taInterP_V4=np.interp(zRec,z_V4,a_V4)\r\n\t\tLInterP_V4=np.interp(zRec,z_V4[:-1],L_V4)\r\n\t\tr0InterP_V4=np.interp(zRec,z_V4,r0_V4)\r\n\r\n\t\txRecTmp = fsolve(RFQVane_V4,[-0.6],args=(aInterP_V4,zCal,LInterP_V4,r0InterP_V4))\r\n\r\n\r\n\tiREC+=1\r\n\tzRec+=zStep\r\n\r\n\txREC[iREC,:]=xRecTmp\r\n\t#xREC_2[iREC,:]=xRecTmp_2\r\n\tzREC[iREC]=zRec\r\n\tcellREC[iREC]=iCell\r\n\tcellFlagREC[iREC]=iCellFlag\r\n\r\n\r\n\tLREC[iREC]=np.interp(zRec,Z,L)\r\n\tLcal[iREC]=betaK*lambda_m/2*100\r\n\tRhoREC[iREC]=Rho(aInterP,k,mInterP)\r\n\r\n\r\n \r\nplt.figure('calculating result')\r\nplt.plot(zREC,xREC[:,0],'b')\r\nplt.hold \r\n#plt.plot(zREC,xREC_2[:,0],'r')\r\n\r\n\r\n######################################对比####################################\r\n\r\nz_HV_REF=np.loadtxt('RFQ H DATA.txt')\r\nZ_REF=z_HV_REF[:,0]/10.\r\nX_REF=z_HV_REF[:,1]/10\r\nRho_REF=z_HV_REF[:,2]/10\r\n\r\n\r\n\r\nplt.figure('Comp')\r\nplt.plot(zREC,xREC,'b')\r\nplt.hold\r\n#plt.plot(zREC,xREC_2[:,0],'g')\r\nplt.hold\r\nplt.plot(Z_REF,X_REF,'r')\r\n\r\n\r\nxRECInterP=np.interp(Z_REF,zREC,xREC[:,0])\r\n\r\nplt.figure('Diff')\r\nplt.plot(Z_REF,X_REF-xRECInterP,'r')\r\nplt.hold \r\nplt.plot(zREC,cellFlagREC,'g')\r\n\r\n########################对比Rho函数##################################################\r\n\r\nplt.figure('Rho')\r\n'''\r\nplt.plot(zREC,RhoREC,'b')\r\nplt.hold\r\nplt.plot(Z_REF,Rho_REF,'r')\r\nplt.hold\r\nplt.plot(Z_REF,Rho_REF-np.interp(Z_REF,zREC,RhoREC),'g')\r\n'''\r\nplt.plot(zREC,np.interp(zREC,Z_REF,Rho_REF),'g')\r\n\r\n\r\n###########################对比Cell长度读取和计算函数################################\r\n\r\n'''\r\nplt.figure('L_COMP')\r\nplt.plot(zREC,LREC,'r')\r\nplt.hold\r\nplt.plot(zREC,Lcal,'b')\r\nplt.hold\r\n\r\nplt.figure('L_Ratio')\r\nplt.plot(zREC,((LREC-Lcal)/LREC))\r\n'''\r\n\r\n########################分析Cell数################################################\r\n\r\n \r\ndef Smooth(x):\r\n\tx[0]=x[0]\r\n\tx[1]=np.average(x[0:2])\r\n\tx[2:-3]=(x[0:-5]+x[1:-4]+x[2:-3]+x[3:-2]+x[4:-1])/5.\r\n\tx[-2]=np.average(x[-3:-1])\r\n\tx[-1]=x[-1]\r\n\treturn x\r\n \r\n \r\ndef FindPeaks(x):\r\n\txLeft=x[1:-2]> x[0:-3]\r\n\txRight=x[1:-2]> x[2:-1]\r\n\txFlag=xLeft*xRight\r\n\tindexX=np.where(xFlag==1)\r\n\treturn indexX\r\n \r\n\r\ndef FindValley(x):\r\n\txLeft=x[1:-2]< x[0:-3]\r\n\txRight=x[1:-2]< x[2:-1]\r\n\txFlag=xLeft*xRight\r\n\tindexX=np.where(xFlag==1)\r\n\treturn indexX\r\n\r\n\r\nindexPeak=((Z_REF>4.) * (Z_REF<221.5))######################定义寻峰范围\r\nZREFPeak=Z_REF[indexPeak]\r\nxREFPeak=X_REF[indexPeak]\r\n\r\n\r\nxREFPeak=Smooth(xREFPeak)\r\nxREFPeak=Smooth(xREFPeak)\r\n\r\n\r\nxRECPeak=xRECInterP[indexPeak]\r\nZRECPeak=ZREFPeak\r\n\r\n\r\nxRECPeak=Smooth(xRECPeak)\r\nxRECPeak=Smooth(xRECPeak)\r\n\r\n\r\nindex_xRECPeakTuple=FindPeaks(xRECPeak)\r\nindex_xREFPeakTuple=FindPeaks(xREFPeak)\r\n\r\n\r\nindex_xRECPeak=index_xRECPeakTuple[0]\r\nindex_xREFPeak=index_xREFPeakTuple[0]\r\n\r\n\r\nprint(' xRECPeak:',len(index_xRECPeak),'\\n','xREFPeak:',len(index_xREFPeak))\r\n\r\nindex_xREFValleyTuple=FindValley(xREFPeak)\r\nindex_xREFValley=index_xREFValleyTuple[0]\r\n\r\n\r\n\r\nif len(index_xREFPeak)==len(index_xREFValley):\r\n\tif ((Z_REF[index_xREFPeak[0]])<(Z_REF[index_xREFValley[0]])):\r\n\t\tLcell_HV=Z_REF[index_xREFValley]-Z_REF[index_xREFPeak]\r\n\t\tP_cell_PV=Z_REF[index_xREFValley]\r\n\telse:\r\n\t\tLcell_HV=Z_REF[index_xREFPeak]-Z_REF[index_xREFValley]\r\n\t\tP_cell_PV=Z_REF[index_xREFPeak]\r\nelif len(index_xREFPeak)4.)*(Z_pariout<221.5)])\r\n\r\nplt.figure('Length(HV_P-V)_comp_priout')\r\nplt.plot(Z_REF[indexPeak],np.interp(Z_REF[indexPeak],P_cell_PV,Lcell_HV),'b')\r\nplt.hold\r\nplt.plot(Z_REF[indexPeak],np.interp(Z_REF[indexPeak],Z_pariout,L_pariout),'r')\r\n\r\nprint(' HV:',((len(index_xREFPeak))+len(index_xREFValley)),'\\n','parioutcell:',ncell_pariout)\r\n\r\n'''\r\nplt.figure('Peak')\r\nplt.plot(ZRECPeak,xRECPeak,'b')\r\nplt.hold\r\nplt.plot(ZRECPeak,xREFPeak,'r')\r\nplt.plot(ZRECPeak[index_xRECPeak],xRECPeak[index_xRECPeak],'bo')\r\nplt.plot(ZRECPeak[index_xREFPeak],xREFPeak[index_xREFPeak],'r*')\r\nplt.plot(ZRECPeak[index_xREFValley],xREFPeak[index_xREFValley],'r*')\r\n'''\r\n##############################计算固定极头半径######################################\r\n\r\n\r\nr0_cal_rho=r0_pariout[4:]\r\nL_cal_rho=L_pariout[4:]\r\nr0_sum=0\r\nfor i in range(0,len(L_cal_rho)):\r\n\tr0_sum=r0_sum+r0_cal_rho[i]*L_cal_rho[i]\r\nr0_rho=r0_sum/Z_pariout[-1]\r\nrho_constant=0.75*r0_rho\r\nprint(' CST_RHO_constant=',rho_constant,'cm')\r\n\r\n\r\n##############################################################################\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Scripts/RFQVane/VaneStructure3.py","file_name":"VaneStructure3.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"342499691","text":"\"\"\"\n套接字 - 基於TCP協議創建時間服務器\n\nVersion: 0.1\nAuthor: 骆昊\nDate: 2018-03-22\n\"\"\"\n\nfrom socket import *\nfrom time import *\n# 1.創建套接字對象並指定使用哪種傳輸服務\n# family=AF_INET - IPv4地址\n# family=AF_INET6 - IPv6地址\n# type=SOCK_STREAM - TCP套接字\n# type=SOCK_DGRAM - UDP套接字\n# type=SOCK_RAW - 原始套接字\nserver = socket(family=AF_INET, type=SOCK_STREAM)\n# 2.綁定IP地址和端口(端口用於區分不同的服務)\n# 同一時間在同一個端口上只能綁定一個服務否則報錯\nserver.bind(('localhost', 6789))\nserver.listen()\nprint('服務器已經啟動正在監聽客戶端連接.')\nwhile True:\n # 4.通過循環接收客戶端的連接並作出相應的處理(提供服務)\n # accept方法是一個阻塞方法如果沒有客戶端連接到服務器代碼不會向下執行\n # accept方法返回一個元組其中的第一個元素是客戶端對象\n # 第二個元素是連接到服務器的客戶端的地址(由IP和端口兩部分構成)\n client, addr = server.accept()\n print('客戶端%s:%d連接成功.' % (addr[0], addr[1]))\n currtime = localtime(time())\n timestr = strftime('%Y-%m-%d %H:%M:%S', currtime)\n client.send(timestr.encode('utf-8'))\n client.close()\nserver.close()\n","sub_path":"Day01-15/Day14-A/code/socket1.py","file_name":"socket1.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156501805","text":"#!/usr/bin/env python3\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport getopt\nimport random\n\n\"\"\"\nAuthor: Blaser, Johannes (11044527)\n\nDescription: A simple program to analyse the performance\n impact upon using Segment Routing and having to traverse\n a given VNF. Both done for random VNF placemenet and for\n topology-aware VNF placement.\n\"\"\"\n\n\ndef create_graph(topology):\n \"\"\"Create a graph depending on the information in the\n info struct provided.\n \"\"\"\n if topology == \"NORDUnet\":\n G = nx.Graph()\n G.add_nodes_from(np.arange(24))\n G.add_edges_from([(0, 2), (1, 5), (2, 4), (2, 5), (2, 6), (3, 4),\n (4, 6), (5, 6), (4, 8), (5, 11), (6, 8), (6, 9),\n (7, 8), (7, 15), (8, 9), (8, 10), (8, 11),\n (10, 11), (10, 12), (11, 13), (11, 14), (12, 13),\n (13, 14), (14, 15), (14, 17), (14, 22), (14, 23),\n (15, 16), (15, 18), (16, 18), (18, 19), (18, 23),\n (19, 21), (21, 20)])\n return G\n elif topology == \"GEANT\":\n G = nx.Graph()\n G.add_nodes_from(np.arange(45))\n G.add_edges_from([(0, 23), (1, 10), (2, 10), (2, 33), (2, 42),\n (2, 35), (2, 5), (2, 18), (2, 17), (2, 38),\n (2, 23), (3, 10), (4, 31), (4, 41), (5, 19),\n (5, 35), (5, 29), (6, 33), (7, 10), (7, 23),\n (7, 15), (7, 43), (8, 10), (8, 41), (9, 10),\n (9, 19), (10, 31), (10, 44), (10, 33), (10, 16),\n (10, 19), (10, 40), (10, 21), (10, 25), (11, 32),\n (11, 37), (11, 44), (11, 31), (11, 22), (12, 44),\n (12, 26), (13, 15), (13, 43), (13, 34), (14, 37),\n (15, 41), (16, 19), (17, 23), (18, 19), (18, 38),\n (19, 39), (19, 35), (19, 40), (19, 36), (19, 28),\n (20, 41), (21, 41), (22, 41), (23, 30), (23, 43),\n (24, 26), (24, 33), (25, 31), (27, 35), (29, 35),\n (31, 44), (32, 37), (34, 41)])\n return G\n elif topology == \"SURFnet\":\n G = nx.Graph()\n G.add_nodes_from(np.arange(50))\n G.add_edges_from([(0, 1), (0, 6), (1, 2), (2, 3), (3, 4), (4, 5),\n (5, 7), (6, 7), (6, 8), (8, 9), (9, 10), (10, 7),\n (6, 11), (11, 14), (6, 14), (6, 33), (6, 31),\n (14, 13), (13, 17), (17, 20), (20, 24), (24, 31),\n (14, 31), (14, 7), (8, 12), (12, 18), (18, 21),\n (21, 33), (7, 15), (15, 19), (19, 22), (22, 25),\n (25, 34), (7, 34), (7, 16), (16, 33), (33, 34),\n (33, 34), (33, 26), (26, 27), (27, 28), (28, 29),\n (29, 30), (30, 34), (32, 33), (31, 32), (31, 35),\n (35, 32), (31, 36), (36, 38), (38, 40), (40, 42),\n (42, 44), (31, 44), (32, 45), (32, 37), (37, 39),\n (39, 41), (41, 45), (44, 45), (44, 47), (47, 48),\n (48, 49), (49, 45), (45, 46), (46, 43), (43, 34),\n (45, 34)])\n return G\n else:\n print(\"Invalid network style received. Aborting...\")\n exit(1)\n\n\ndef generate_function_nodes(G, topology, info, is_rand):\n \"\"\"Generate a VNF's location based on the provided\n parameters in the info object. Randomly placed or not.\n \"\"\"\n function_nodes = []\n\n if is_rand:\n # VNF is randomly placed. Pick any unique place.\n for i in range(info['num_VNFs']):\n tmp = np.random.choice(list(G.nodes()))\n\n while tmp in function_nodes:\n tmp = np.random.choice(list(G.nodes()))\n\n function_nodes.append(tmp)\n else:\n # Calculate most connected nodes.\n degrees = list(G.degree())\n degree_sequence = sorted(degrees, key=lambda tup: tup[1], reverse=True)\n if len(degree_sequence) is 0:\n return []\n\n for i in range(info['num_VNFs']):\n function_nodes.append(degree_sequence[i][0])\n\n return function_nodes\n\n\ndef generate_source(G, VNFs):\n \"\"\"Generate a random source node. Can't be the VNF.\n \"\"\"\n tmp = np.random.choice(list(G.nodes()))\n\n while tmp in VNFs:\n tmp = np.random.choice(list(G.nodes()))\n\n return tmp\n\n\ndef generate_target(G, VNFs, source):\n \"\"\"Generate a random target node. Can't be the VNF nor the source.\n \"\"\"\n tmp = np.random.choice(list(G.nodes()))\n\n while tmp in VNFs or tmp is source:\n tmp = np.random.choice(list(G.nodes()))\n\n return tmp\n\n\ndef get_path_length(G, source, target, VNFs):\n \"\"\"Determine whether a given path from source to target\n traverses the VNFs defined in the info struct.\n \"\"\"\n path = [source]\n\n for VNF in VNFs:\n if nx.has_path(G, path[-1], VNF):\n for hop in nx.shortest_path(G, path[-1], VNF)[1:]:\n path.append(hop)\n\n if nx.has_path(G, path[-1], target):\n for hop in nx.shortest_path(G, path[-1], target)[1:]:\n path.append(hop)\n\n return len(path)\n\n\ndef run_cycles(G, info, VNFs):\n \"\"\"Run a given number of cycles of the experiment. Create\n a random source and target pair each time but keep the\n VNF the same.\n \"\"\"\n lengths = []\n pairs = []\n\n for i in range(info['cycles']):\n source = generate_source(G, VNFs)\n target = generate_target(G, VNFs, source)\n\n while (source, target) in pairs:\n source = generate_source(G, VNFs)\n target = generate_target(G, VNFs, source)\n\n pairs.append((source, target))\n\n lengths.append(get_path_length(G, source, target, VNFs))\n\n return np.average(lengths), np.std(lengths)\n\n\ndef run_experiments(topologies, info):\n \"\"\"Run the experiments on the parameters defined in the\n information struct.\n \"\"\"\n total_avg1, total_avg2, total_avg3 = ({}, {}, {})\n total_std1, total_std2, total_std3 = ({}, {}, {})\n\n for topology in topologies:\n print(\"Running topology: \" + topology + \"...\")\n avg1, avg2, avg3 = ([], [], [])\n std1, std2, std3 = ([], [], [])\n\n G = create_graph(topology)\n\n for i in range(info['topologies']):\n VNFs = []\n avg, std = run_cycles(G, info, VNFs)\n avg1.append(avg)\n std1.append(std)\n\n VNFs = generate_function_nodes(G, topology, info, True)\n avg, std = run_cycles(G, info, VNFs)\n avg2.append(avg)\n std2.append(std)\n\n VNFs = generate_function_nodes(G, topology, info, False)\n avg, std = run_cycles(G, info, VNFs)\n avg3.append(avg)\n std3.append(std)\n\n total_avg1[topology] = np.average(avg1)\n total_avg2[topology] = np.average(avg2)\n total_avg3[topology] = np.average(avg3)\n\n total_std1[topology] = np.average(std1)\n total_std2[topology] = np.average(std2)\n total_std3[topology] = np.average(std3)\n\n return (total_avg1, total_std1,\n total_avg2, total_std2,\n total_avg3, total_std3)\n\n\ndef visualise_probabilities(topologies, info, results):\n \"\"\"Visualise the results provided in a bar chart.\n \"\"\"\n fig, ax = plt.subplots()\n index = np.arange(len(topologies))\n bar_width = 0.25\n opacity = 0.8\n\n avgs_0 = np.array(list(results[0].values()))\n tmp_avgs_1 = np.array(list(results[2].values()))\n tmp_avgs_2 = np.array(list(results[4].values()))\n\n stds_0 = np.array(list(results[1].values()))\n stds_1 = np.array(list(results[3].values()))\n stds_2 = np.array(list(results[5].values()))\n\n avgs_1 = tmp_avgs_1 - avgs_0\n avgs_2 = tmp_avgs_2 - avgs_0\n\n avgs_1 /= avgs_0\n avgs_2 /= avgs_0\n\n scale_1 = avgs_1 / tmp_avgs_1\n stds_1 *= scale_1\n scale_2 = avgs_2 / tmp_avgs_2\n stds_2 *= scale_2\n\n y_max = 1\n if np.amax(avgs_1) > y_max:\n y_max = np.amax(avgs_1)\n if np.amax(avgs_2) > y_max:\n y_max = np.amax(avgs_2)\n\n y_min = 0\n if np.amin(avgs_1) < y_min:\n y_min = np.amin(avgs_1)\n if np.amin(avgs_2) < y_min:\n y_min = np.amin(avgs_2)\n\n y_max += 0.25\n if y_min is not 0:\n y_min -= 0.25\n\n # Plot the first plot (random and non-random, small sized topology).\n rects1 = ax.bar(index + (bar_width * 1),\n avgs_1,\n bar_width,\n alpha=opacity,\n color='blue',\n label='Random VNF allocation',\n yerr=stds_1)\n\n rects2 = ax.bar(index + (bar_width * 2),\n avgs_2,\n bar_width,\n alpha=opacity,\n color='green',\n label='Topology-aware VNF allocation',\n yerr=stds_2)\n\n # Set the title data.\n plt.title('Relative increase in path length over ' +\n '{} VNF(s)'.format(info['num_VNFs']))\n plt.ylabel('Performance impact relative to the shortest path')\n plt.xlabel('Topology')\n plt.ylim([y_min, y_max])\n\n plt.legend()\n\n plt.xticks(index + (bar_width * 1.5), topologies)\n\n # plt.tight_layout()\n plt.show()\n\n\ndef main():\n \"\"\"Runs the main function.\n Reads the command line information provided and calls the experiments.\n \"\"\"\n\n # Define the default data.\n information = {\n 'VNF': 0,\n 'num_VNFs': 1,\n 'topologies': 1000,\n 'cycles': 1000\n }\n\n # Define the topologies experimented upon.\n topologies = ['NORDUnet', 'GEANT', 'SURFnet']\n\n # Read data from command line.\n options, remainder = getopt.getopt(sys.argv[1:],\n 'hs:m:l:V:t:c:',\n ['help',\n 'num_VNFs=',\n 'topologies=',\n 'cycles='])\n\n for opt, arg in options:\n if opt in ('-h', '--help'):\n print(help_message)\n exit(0)\n elif opt in ('-V', '--num_VNFs'):\n information['num_VNFs'] = int(arg)\n elif opt in ('-t', '--topologies'):\n information['topologies'] = int(arg)\n elif opt in ('-c', '--cycles'):\n information['cycles'] = int(arg)\n\n # Relay parameters to user.\n print(\"Running \" + str(information['cycles']) + \" cycles on \" +\n str(information['topologies']) + \" topologies...\")\n\n # Perform experiments.\n results = run_experiments(topologies, information)\n visualise_probabilities(topologies, information, results)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Impact/Relative/realistic.py","file_name":"realistic.py","file_ext":"py","file_size_in_byte":10887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"318048377","text":"import json\n\ngameListFile = 'gameEmbed.json'\nemptySlotChar = '?'\n\n\nclass GameEmbed:\n def __init__(self):\n self.addedGames = []\n self.loadAddedGames()\n\n self.gamesMessageId = -1\n\n\n #Reads the json file containing all added games\n def loadAddedGames(self):\n with open(gameListFile) as f:\n games = json.load(f)\n\n for i in range(0, len(games)):\n index = str(i)\n game = games[index]['game']\n emoji = games[index]['emoji']\n members = games[index]['members']\n \n self.addedGames.append((game, emoji, members))\n\n\n #Saves the json file with the updated game list\n def saveAddedGames(self):\n games = {}\n\n for i in range(0, len(self.addedGames)):\n game,emoji,members = self.addedGames[i]\n\n games[i] = {}\n games[i]['game'] = game\n games[i]['emoji'] = emoji\n games[i]['members'] = []\n \n if len(members) != 0:\n for j in range(0, len(members)):\n games[i]['members'].append(members[j])\n\n with open(gameListFile,'w') as f:\n f.write(json.dumps(games))\n\n\n def getEmbedMessage(self):\n output = ''\n\n for i in range(0, len(self.addedGames)):\n output += str(self.addedGames[i][1]) + ' : **' + self.addedGames[i][0] + '**'\n memberList = ' - [ '\n\n for j in range(0, len(self.addedGames[i][2])):\n memberList += str(self.addedGames[i][2][j][1]) + ', '\n \n #Remove ending comma\n if memberList != ' - [ ':\n memberList = memberList[0:-2] + ' ]\\n'\n else:\n memberList = '\\n'\n output += memberList\n\n return output\n\n\n def getAddedGames(self):\n return self.addedGames\n\n\n def addGame(self, name, emoji, slots):\n members = []\n for i in range(0,slots):\n members.append((emptySlotChar, emptySlotChar))\n\n self.addedGames.append((name, emoji, members))\n self.saveAddedGames()\n\n\n #Removes the tuple of the game specified by the given name\n def removeGameByName(self, name):\n index = self.getIndexByGameName(name)\n \n if index != -1:\n self.addedGames.pop(index)\n self.saveAddedGames()\n\n\n def getEmojisInUse(self):\n emojis = []\n\n for i in range(0, len(self.addedGames)):\n emojis.append(self.addedGames[i][1])\n\n return emojis\n\n\n def getEmojiGivenName(self, name):\n for i in range(0, len(self.addedGames)):\n if self.addedGames[i][0].lower() == name.lower():\n return self.addedGames[i][1]\n return -1\n \n\n #Returns the index of the game given a name\n def getIndexByGameName(self, name):\n for i in range(0, len(self.addedGames)):\n gameName = self.addedGames[i][0]\n\n if gameName.lower() == name.lower():\n return i\n #No game was found with the given name\n return -1\n\n\n #Returns the index of the game given an emoji\n def getIndexByEmojiName(self, emoji):\n for i in range(0, len(self.addedGames)):\n emojiName = self.addedGames[i][1]\n\n if emojiName == emoji:\n return i\n #No game was found with the given emoji\n return -1\n\n\n #Returns the game name given an emoji\n def getGameNameByEmojiName(self, emoji):\n for i in range(0, len(self.addedGames)):\n if self.addedGames[i][1] == emoji:\n return self.addedGames[i][0]\n #No game was found with the given emoji\n return -1\n\n\n #Adds a player to the list of members for a game, given an emoji\n def addPlayerToGame(self, emoji, userId, displayName):\n index = self.getIndexByEmojiName(emoji)\n \n if index != -1:\n id = str(userId)\n members = self.addedGames[index][2]\n\n #If the user already exists just return\n for i in range(0, len(members)):\n if id == members[i][0]:\n return\n \n #Check for an available slot and then replace it with the new player\n for i in range(0, len(members)):\n if members[i][0] == emptySlotChar:\n self.addedGames[index][2][i] = (id, displayName)\n self.saveAddedGames()\n return\n\n\n #Adds a player to the list of members for a game, given an emoji\n def removePlayerFromGame(self, emoji, userId):\n index = self.getIndexByEmojiName(emoji)\n \n if index != -1:\n id = str(userId)\n members = self.addedGames[index][2]\n\n for i in range(0, len(members)):\n if id == members[i][0]:\n self.addedGames[index][2][i] = (emptySlotChar, emptySlotChar)\n self.saveAddedGames()\n return\n\n\n def getGameMessageId(self):\n return self.gamesMessageId\n\n\n def setGameMessageId(self, messageId):\n self.gamesMessageId = messageId","sub_path":"gameEmbed.py","file_name":"gameEmbed.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"105626523","text":"#!/usr/bin/env python3\nimport argparse\nfrom logcollector import logcollector as lc\n\n\ndef main():\n print(\"Running logcollector...\")\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(description=\"Pass a custom configuration filename to overwrite the default \"\n \"'config.ini'. Configuration used must still exist in the config \"\n \"directory.\")\n parser.add_argument('-c', dest='configuration_filename', metavar='filename', required=False,\n help='configuration filename')\n args = parser.parse_args()\n\n # Location of the configuration file. Default: config.ini\n configuration_home = 'config/'\n configuration_file = \"{}config.ini\".format(configuration_home)\n\n if args.configuration_filename:\n configuration_file = \"{}{}\".format(configuration_home, args.configuration_filename)\n\n # Log Collector Options\n print(configuration_file)\n options = lc.setup(configuration_file)\n\n # Validate collection destination\n if not lc.verify_directory_exists(options['log_backup_base_directory']):\n lc.exit_unsuccessful_setup(\"The logcollector destination directory does not exist, please fix in configuration \"\n \"file.\")\n\n # Verify logs\n valid_logs, invalid_logs = lc.verify_logs_exist(options['logs'])\n\n # Create the collection directory\n collection_directory = lc.create_backup_directory(options['log_backup_base_directory'], options['log_backup_name'])\n\n # Backup Logs\n lc.collect_logs(valid_logs, collection_directory)\n\n # Truncate Logs\n if options['clear_logs_after_collection']:\n lc.truncate_logs(valid_logs)\n\n print(\"Completed logcollector.\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run_logcollector.py","file_name":"run_logcollector.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500847044","text":"import logging\nimport os\nimport shutil\nimport tarfile\nimport tempfile\nimport numpy as np\nfrom urllib import request as request\nfrom urllib.error import HTTPError, URLError\n\nfrom schnetpack.data import AtomsData\nfrom schnetpack.environment import SimpleEnvironmentProvider\n\n\nclass ISO17(AtomsData):\n \"\"\"\n ISO17 benchmark data set for molecular dynamics of C7O2H10 isomers containing molecular forces.\n\n Args:\n path (str): Path to database\n fold (str): Fold of data to load. Allowed are:\n reference - 80% of steps of 80% of MD trajectories\n reference_eq - equilibrium conformations of those molecules\n test_within - remaining 20% unseen steps of reference trajectories\n test_other - remaining 20% unseen MD trajectories\n test_eq - equilibrium conformations of test trajectories\n subset (list): indices of subset. Set to None for entire dataset (default: None)\n download (bool): set to true if dataset should be downloaded. (default: True)\n calculate_triples (false): set to true to compute triples for angular functions (default: true)\n\n See: http://quantum-machine.org/datasets/\n \"\"\"\n existing_folds = [\n \"reference\",\n \"reference_eq\",\n \"test_within\",\n \"test_other\",\n \"test_eq\"\n ]\n\n def __init__(self, path, fold, subset=None, download=True, collect_triples=False):\n if fold not in self.existing_folds:\n raise ValueError(\"Fold {:s} does not exist\".format(fold))\n\n self.path = path\n self.fold = fold\n self.datapath = os.path.join(self.path, \"iso17\")\n\n self.database = fold + \".db\"\n\n self.dbpath = os.path.join(self.datapath, self.database)\n\n environment_provider = SimpleEnvironmentProvider()\n\n if download:\n self.download()\n\n properties = [\"total_energy\", \"atomic_forces\"]\n\n super().__init__(self.dbpath, subset, properties, environment_provider, collect_triples)\n\n E = \"total_energy\"\n F = \"atomic_forces\"\n\n properties = [\n E, F\n ]\n\n units = dict(\n zip(properties, [1.0, 1.0])\n )\n\n def download(self):\n r\"\"\"\n download dataset if not already on disk\n \"\"\"\n success = True\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n\n if not os.path.exists(self.datapath):\n success = success and self._download()\n if not os.path.exists(self.dbpath):\n success = success and self._download()\n\n return success\n\n def _download(self):\n logging.info(\"Downloading ISO17 database...\")\n tmpdir = tempfile.mkdtemp(\"iso17\")\n tarpath = os.path.join(tmpdir, \"iso17.tar.gz\")\n url = \"http://www.quantum-machine.org/datasets/iso17.tar.gz\"\n\n try:\n request.urlretrieve(url, tarpath)\n except HTTPError as e:\n logging.error(\"HTTP Error:\", e.code, url)\n return False\n except URLError as e:\n logging.error(\"URL Error:\", e.reason, url)\n return False\n\n tar = tarfile.open(tarpath)\n tar.extractall(self.path)\n tar.close()\n\n shutil.rmtree(tmpdir)\n\n return True\n\n def create_subset(self, idx):\n \"\"\"\n Returns a new dataset that only consists of provided indices.\n Args:\n idx (numpy.ndarray): subset indices\n\n Returns:\n schnetpack.data.AtomsData: dataset with subset of original data\n \"\"\"\n idx = np.array(idx)\n subidx = idx if self.subset is None else np.array(self.subset)[idx]\n return type(self)(self.path, self.fold, subidx, False, self.collect_triples)","sub_path":"src/schnetpack/datasets/iso17.py","file_name":"iso17.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"38250157","text":"import numpy as np\n\nfrom skimage.util import img_as_bool\nfrom skimage.morphology import binary_dilation,binary_erosion,square,disk\nfrom skimage.draw import circle\n\n\ndef expand(img_mask):\n expanded_mask = np.zeros(img_mask.shape,dtype=bool)\n\n expanded_mask[:,:] = img_mask[:,:]\n\n expanded_mask[1:,:] += img_mask[:-1,:]\n expanded_mask[:-1,:] += img_mask[1:,:]\n\n expanded_mask[:,1:] += img_mask[:,:-1]\n expanded_mask[:,:-1] += img_mask[:,1:]\n\n return expanded_mask\n\ndef shrink(img_mask):\n boundary = get_boundary_mask(img_mask)[1]\n return minus(img_mask,boundary)\n\n\ndef identify_corners(img_mask):\n temp = np.zeros(img_mask.shape,dtype=np.int32)\n labeled_boundary = np.zeros(img_mask.shape,dtype=np.bool)\n\n\n temp[1:,:] += 1*img_mask[:-1,:] #Pull Up\n temp[:-1,:] += 2*img_mask[1:,:] #Push Down\n\n temp[:,1:] += 4*img_mask[:,:-1] #Pull Left\n temp[:,:-1] += 8*img_mask[:,1:] #Push Right\n\n temp[img_mask] = temp[img_mask]\n temp[np.bitwise_not(img_mask)]=0\n\n labeled_boundary[temp==5] = True\n labeled_boundary[temp==9] = True\n labeled_boundary[temp==6] = True\n labeled_boundary[temp==10] = True\n\n\n return labeled_boundary\n\n\n\ndef euclidean_disk(x,y,r,shape):\n squares_mask = (r+1)**2*np.ones( shape )\n\n squares = [ i**2 for i in range(r+1) ]\n for i in range(r+1):\n for j in range(r+1):\n squares_mask[y+i,x+j] = squares[i] + squares[j] \n\n for i in range(r+1):\n for j in range(r+1):\n squares_mask[y-i,x+j] = squares[i] + squares[j] \n \n\n for i in range(r+1):\n for j in range(r+1):\n squares_mask[y-i,x-j] = squares[i] + squares[j] \n \n\n for i in range(r+1):\n for j in range(r+1):\n squares_mask[y+i,x-j] = squares[i] + squares[j] \n\n\n squares_mask[squares_mask<=r**2] =1\n squares_mask[squares_mask>1] = 0\n \n return squares_mask==1\n\n\ndef neighborhood(p,h,w):\n y,x = p\n N = [ check_bounds( (y+1,x),h,w ),\n check_bounds( (y-1,x),h,w ),\n check_bounds( (y,x+1),h,w ),\n check_bounds( (y,x-1),h,w ) ]\n return N\n\ndef check_bounds(p,h,w):\n y,x = p\n y = h-1 if y>=h else y\n y = 0 if y<0 else y\n x = w-1 if x>=w else x\n x = 0 if x<0 else x \n\n return ( y,x )\n\ndef get_boundary_mask(img):\n '''\n Return the boundary of a digital image.\n\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: Boolean image. Values of 1 indicates points of the boundary.\n '''\n if (img>1).any():\n raise Exception(\"Image is not binary.\")\n\n imbool = img_as_bool(img)\n h,w = imbool.shape\n\n\n \n temp = np.array(imbool,dtype=int)\n temp[imbool==0] = -4\n\n temp[1:,:] += imbool[:-1,:]\n temp[:-1,:] += imbool[1:,:]\n\n temp[:,1:] += imbool[:,:-1]\n temp[:,:-1] += imbool[:,1:] \n\n boundary_mask = np.zeros(imbool.shape,dtype=bool)\n boundary_mask[ temp>=2 ] = temp[ temp>=2 ] < 5\n\n\n return (h,w),boundary_mask\n\ndef get_boundary_mask_D(img):\n '''\n Return the boundary of a digital image.\n\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: Boolean image. Values of 1 indicates points of the boundary.\n '''\n if (img>1).any():\n raise Exception(\"Image is not binary.\")\n\n imbool = img_as_bool(img)\n h,w = imbool.shape\n\n\n boundary_mask = minus(img,binary_erosion(img,square(3)))\n # boundary_mask = imbool\n\n return (h,w),boundary_mask \n\ndef get_boundary_mask_F(img):\n '''\n Return the boundary of a digital image.\n\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: Boolean image. Values of 1 indicates points of the boundary.\n '''\n if (img>1).any():\n raise Exception(\"Image is not binary.\")\n\n imbool = img_as_bool(img)\n h,w = imbool.shape\n\n boundary_mask = binary_dilation(img,square(3))\n\n return (h,w),boundary_mask \n\ndef binary_erosion_region_and_boundary_masks(img,radius,selem):\n '''\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: (Boolean image,Boolean image). Values of 1 indicates points of the region/boundary.\n '''\n (h,w),border = get_boundary_mask(img)\n\n if radius==0:\n trust_region_mask = img\n else:\n trust_region_mask = binary_erosion(img,selem(radius))\n \n (a,b),trust_boundary_mask = get_boundary_mask( trust_region_mask )\n\n return (trust_region_mask,trust_boundary_mask)\n\n\ndef binary_dilation_region_and_boundary_masks(img,radius,selem):\n '''\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: (Boolean image,Boolean image). Values of 1 indicates points of the region/boundary.\n ''' \n (h,w),border = get_boundary_mask(img)\n\n extended_region_mask = binary_dilation(img,selem(radius))\n (a,b),extended_boundary_mask = get_boundary_mask( extended_region_mask ) \n\n return (extended_region_mask,extended_boundary_mask)\n\n\ndef get_boundaries_and_regions_masks(img,erosion_radius,dilation_radius,selem):\n '''\n img: must be a binary image. \n 1 - Foreground\n 0 - Background\n\n return: (Boolean image,Boolean image). Values of 1 indicates points of the region/boundary.\n ''' \n trust_region_mask,trust_boundary_mask = get_trust_region_and_boundary_masks(img,erosion_radius,selem)\n middle_region_mask,middle_boundary_mask = get_middle_region_and_boundary_masks(img)\n extended_region_mask,extended_boundary_mask = get_extended_region_and_boundary_masks(img,dilation_radius,selem)\n \n return (trust_region_mask,middle_region_mask,extended_region_mask,trust_boundary_mask,middle_boundary_mask,extended_boundary_mask)\n\n\ndef generate_disk_region_mask(cx,cy,r,shape=None):\n '''\n return: Boolean image. Values of 1 indicates points in the disk.\n '''\n\n if shape is None:\n shape = (4*r,4*r)\n \n disk_mask = np.zeros(shape,dtype=bool)\n ccy,ccx = circle(cy,cx,r,shape)\n disk_mask[ccy,ccx] = True\n\n # disk_mask = euclidean_disk(cx,cy,r,shape)\n\n return disk_mask\n\n\ndef generate_disk_region_mask_automatic_center(radius,shape=None):\n return generate_disk_region_mask(2*radius,2*radius,radius,shape) \n\ndef compute_disk_area(radius):\n D=generate_disk_region_mask_automatic_center(radius)\n return len(D[D])\n\n\ndef intersect(region_mask_1,region_mask_2): \n return np.bitwise_and(region_mask_1,region_mask_2)\n\ndef minus(region_mask_1,region_mask_2):\n return np.bitwise_and( region_mask_1, ~region_mask_2 )\n\n\ndef build_coordinates_matrix(h,w): \n coord_matrix = []\n for i in range(h):\n coord_matrix.append([])\n for j in range(w):\n coord_matrix[-1].append( (i,j) )\n coord_matrix = np.array( coord_matrix, dtype=[('y','>i4'),('x','>i4')] )\n\n return coord_matrix\n\n","sub_path":"BoundaryPositioning/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"588851254","text":"from __future__ import division # If python is 2.x\r\n\r\nimport os\r\nimport sys\r\nimport winsound\r\n\r\ntry: # Python 3\r\n import ctypes\r\n from tkinter import *\r\n from tkinter import PhotoImage\r\n from tkinter import messagebox\r\n\r\n PY3 = True\r\n\r\nexcept (ImportError, ModuleNotFoundError): # Python 2\r\n import PIL.Image # PIL does not come pre-install in python 2 so you need to install it using \"pip install Pillow\"\r\n import PIL.ImageTk\r\n from Tkinter import *\r\n import tkMessagebox as messagebox\r\n\r\n PY3 = False\r\n\r\n\r\nhide_minimiz_maximize = False\r\n\r\n\r\nclass hide_or_show_maximize_minimize:\r\n '''Hide the minimize and maximize buton when the window is place at the top of other applications windows.\r\n And show the minimize and maximize button when the window is not place at the top of other applications windows'''\r\n\r\n def __init__(self, window):\r\n self.window = window\r\n\r\n # shortcuts to the WinAPI functionality\r\n self.set_window_pos = ctypes.windll.user32.SetWindowPos\r\n self.set_window_long = ctypes.windll.user32.SetWindowLongW\r\n self.get_window_long = ctypes.windll.user32.GetWindowLongW\r\n self.get_parent = ctypes.windll.user32.GetParent\r\n\r\n # some of the WinAPI flags\r\n self.SWP_NOSIZE = 1\r\n self.SWP_NOMOVE = 2\r\n self.GWL_STYLE = -16\r\n self.SWP_NOZORDER = 4\r\n self.SWP_FRAMECHANGED = 32\r\n self.WS_MAXIMIZEBOX = 65536\r\n self.WS_MINIMIZEBOX = 131072\r\n\r\n def hide_minimize_maximize(self):\r\n '''Hide minimize and maximize button of the window'''\r\n\r\n global hide_minimiz_maximize\r\n\r\n hide_minimiz_maximize = True\r\n hwnd = self.get_parent(self.window.winfo_id())\r\n old_style = self.get_window_long(hwnd, self.GWL_STYLE) # getting the old style\r\n new_style = old_style & ~ self.WS_MAXIMIZEBOX & ~ self.WS_MINIMIZEBOX # building the new style (old style AND NOT Maximize AND NOT Minimize)\r\n self.set_window_long(hwnd, self.GWL_STYLE, new_style) # setting new style\r\n self.set_window_pos(hwnd, 0, 0, 0, 0, 0, self.SWP_NOMOVE | self.SWP_NOSIZE | self.SWP_NOZORDER | self.SWP_FRAMECHANGED) # updating non-client area\r\n\r\n def show_minimize_maximize(self,):\r\n '''Hide minimize and maximize button of the window'''\r\n\r\n global hide_minimiz_maximize\r\n\r\n hide_minimiz_maximize = False\r\n hwnd = self.get_parent(self.window.winfo_id())\r\n old_style = self.get_window_long(hwnd, self.GWL_STYLE) # getting the old style\r\n new_style = old_style | self.WS_MAXIMIZEBOX | self.WS_MINIMIZEBOX # building the new style (old style OR Maximize OR Minimize)\r\n self.set_window_long(hwnd, self.GWL_STYLE, new_style) # setting new style\r\n self.set_window_pos(hwnd, 0, 0, 0, 0, 0, self.SWP_NOMOVE | self.SWP_NOSIZE | self.SWP_NOZORDER | self.SWP_FRAMECHANGED) # updating non-client area\r\n\r\n\r\nclass Calculator:\r\n '''Calculator is a GUI script purely written in Python. This calculator is capable of performing addtion, subtraction,\r\n multiplication, division and percentage of any digtis numbers. Moreover, this calculator is able to store history of\r\n each calculation and is able to place itself to the top of any other application windows so that you could do calculation\r\n above any window.'''\r\n\r\n def __init__(self):\r\n self.master = Tk()\r\n self.master.withdraw()\r\n self.master.after(0, self.master.deiconify)\r\n self.master.title('Calculator')\r\n self.master.iconbitmap('included files/icon.ico')\r\n\r\n self.hide_or_show = hide_or_show_maximize_minimize(self.master)\r\n self.decimal_placeable = True # Not inserted decimal '.' yet.\r\n\r\n # Getting screen width and height of any system\r\n self.screen_width = self.master.winfo_screenwidth()\r\n self.screen_height = self.master.winfo_screenheight()\r\n\r\n # pos_x and pos_y are calculated such that the window is at the center of the screen\r\n self.pos_x = self.screen_width // 2 - 460 // 2\r\n self.pos_y = self.screen_height // 2 - 340 // 2\r\n\r\n self.master.geometry('460x340+{}+{}'.format(self.pos_x, self.pos_y))\r\n self.master.resizable(0, 0)\r\n\r\n self.is_shown = False # History is not shown yet\r\n\r\n self.var = StringVar()\r\n self.text_frame = Frame(self.master)\r\n self.text_area = Entry(self.text_frame, textvariable=self.var, borderwidth=1, width=25, bg='silver', font=(\"Arial\", 20), cursor='arrow', justify=RIGHT, disabledbackground='white', disabledforeground='black', state='disabled')\r\n self.var.set('0')\r\n self.text_area.grid(row=0, column=0, columnspan=5)\r\n self.text_frame.place(x=10, y=10)\r\n\r\n # Buttons\r\n self.track = 0\r\n self.buttons_frame = Frame(self.master) # Frame to place all buttons\r\n self.buttons_names = ['AC', 'DEL', '%', '÷', '9', '8', '7', '*', '6', '5', '4', '-', '3', '2', '1', '+', '.', '0', '='] # buttons name\r\n\r\n # Adding buttons to the window\r\n for row in range(5):\r\n text = self.buttons_names[self.track: self.track + 4]\r\n\r\n for col, txt in enumerate(text):\r\n self.buttons = Button(self.buttons_frame, text=txt, width=10, height=2, bg='white', fg='black', activebackground='#cccccc', relief='groove', command=lambda txt=txt: set_value(txt), font=('Courier', 12))\r\n\r\n if txt == 'AC':\r\n self.buttons.config(command=self.ac_command)\r\n self.buttons.grid(row=row, column=col)\r\n\r\n elif txt == 'DEL':\r\n self.buttons.config(command=self.del_command)\r\n self.buttons.grid(row=row, column=col)\r\n\r\n elif txt == '=':\r\n self.buttons.config(command=self.equals_to)\r\n self.buttons.grid(row=row, column=col, columnspan=2, ipadx=55)\r\n\r\n else:\r\n self.buttons.config(command=lambda txt=txt: self.keyaction(values=txt))\r\n self.buttons.grid(row=row, column=col)\r\n\r\n self.track += 4\r\n\r\n self.buttons_frame.place(x=10, y=50)\r\n\r\n # History title\r\n self.history_label_frame = Frame(self.master)\r\n self.history_label = Label(self.history_label_frame, text='History', font=('Courier', 15, 'bold'), bg='#cccccc')\r\n self.history_label.grid(row=0, column=0)\r\n\r\n # Storing calculated history\r\n self.history_frame = Frame(self.master)\r\n self.history_area = Text(self.history_frame, width=52, height=13, borderwidth=0, cursor='arrow', bg='#cccccc')\r\n self.history_area.grid(row=0, column=0)\r\n\r\n # Button that has label \"Show History\"\r\n self.show_history_frame = Frame(self.master)\r\n self.show_history_button = Button(self.show_history_frame, text='Show History', relief=GROOVE, bg='#cccccc', activebackground='#cccccc', command=self.show_history)\r\n self.show_history_button.grid(row=0, column=0, ipadx=215, ipady=5)\r\n self.show_history_frame.place(x=0, y=303)\r\n\r\n # Button that has label \"Hide History\"\r\n self.hide_history_frame = Frame(self.master)\r\n self.hide_history_button = Button(self.hide_history_frame, text='Hide History', relief=GROOVE, bg='#cccccc', activebackground='#cccccc', command=self.hide_history)\r\n self.hide_history_button.grid(row=0, column=0, ipadx=215, ipady=5)\r\n\r\n # Attaching scrollbar to the text area\r\n self.scrollbar = Scrollbar(self.history_frame, orient=\"vertical\", command=self.history_area.yview, cursor='arrow')\r\n self.history_area['yscrollcommand'] = self.scrollbar.set\r\n\r\n # Creating image object\r\n if PY3:\r\n self.pull_back_image = PhotoImage(file=self.resource_path('included files\\\\pull_back.png'))\r\n self.push_front_image = PhotoImage(file=self.resource_path('included files\\\\push_front.png'))\r\n\r\n else:\r\n self.pull_back_image = PIL.ImageTk.PhotoImage(PIL.Image.open(self.resource_path('included files\\\\pull_back.png')))\r\n self.push_front_image = PIL.ImageTk.PhotoImage(PIL.Image.open(self.resource_path('included files\\\\push_front.png')))\r\n\r\n # Buttons that push the window to the top of other window or pull the window from the top of other window\r\n self.push_front_frame = Frame(self.master)\r\n self.pull_back_image = PhotoImage(file='included files/pull_back.png')\r\n self.push_front_image = PhotoImage(file='included files/push_front.png')\r\n self.push_front_button = Button(self.push_front_frame, image=self.push_front_image, bg='white', activebackground='white', fg='black', relief='groove', compound='top', command=self.place_at_top)\r\n self.push_front_button.grid(row=0, column=0, padx=1, ipadx=13, ipady=4)\r\n self.push_front_frame.place(x=391, y=10)\r\n\r\n # Clear and info Button\r\n self.clear_history_frame = Frame(self.master, bg='#cccccc')\r\n self.info_button = Button(self.clear_history_frame, text='INFO', bg='white', activebackground='white', fg='black', relief='groove', command=self.info)\r\n self.clear_history_button = Button(self.clear_history_frame, text='CLEAR', bg='white', activebackground='white', fg='black', relief='groove', command=self.clear_history)\r\n self.info_button.grid(row=0, column=1, padx=10, ipadx=8, ipady=2)\r\n self.clear_history_button.grid(row=0, column=2, ipadx=5, ipady=2)\r\n\r\n # Binding keys\r\n self.master.bind('', lambda e: self.ctrl_h())\r\n self.master.bind('', lambda e: self.ctrl_h())\r\n self.master.bind('', self.equals_to)\r\n self.master.bind('', self.ac_command)\r\n self.master.bind('', self.del_command)\r\n self.master.bind('', lambda evt: self.keyaction(evt))\r\n\r\n self.clear_history() # Calling history function\r\n self.show_scrollbar()\r\n\r\n self.master.config(bg='#cccccc')\r\n self.history_area.config(state=DISABLED)\r\n\r\n self.master.after(10, self.insert_zero)\r\n self.master.mainloop()\r\n\r\n def ac_command(self, event=None):\r\n '''Command for ac button, \"a\" key and \"Delete\" key from the keyboard'''\r\n\r\n self.text_area.delete(0, END)\r\n self.var.set('0')\r\n self.decimal_placeable = True\r\n\r\n def del_command(self, event=None):\r\n '''Commands for backspace key and del button'''\r\n\r\n get = self.var.get()\r\n\r\n if get == 'Cannot divide by ZERO':\r\n self.ac_command()\r\n\r\n else:\r\n if get[-1] == '.': # Edge Cases 08\r\n self.decimal_placeable = True\r\n\r\n self.var.set(get[:-1])\r\n\r\n if not get:\r\n self.var.set('0')\r\n\r\n def get_updated_postition(self):\r\n '''Get x-coordinates and y-coordinates of the window if user displaces the window from the default position'''\r\n\r\n self.master.update()\r\n\r\n xpos = self.master.winfo_x() # new x-coordinate of the window\r\n ypos = self.master.winfo_y() # new y-coordinate of the window\r\n\r\n if xpos < 0:\r\n xpos = 5\r\n\r\n if xpos > self.screen_width - self.master.winfo_width() - 20:\r\n xpos = self.screen_width - self.master.winfo_width() - 20\r\n\r\n if ypos > 99:\r\n ypos = 99\r\n\r\n return (xpos, ypos)\r\n\r\n def place_at_top(self):\r\n '''Place the window to the top of any window opened in the background and resize some widgets'''\r\n\r\n xpos, ypos = self.get_updated_postition()\r\n xpos = self.screen_width - self.master.winfo_width() - 20 # This is done to place the window to the top right ot the screen\r\n\r\n if not hide_minimiz_maximize:\r\n self.hide_or_show.hide_minimize_maximize()\r\n self.push_front_button.config(image=self.pull_back_image)\r\n\r\n self.master.attributes('-topmost', True)\r\n self.master.geometry(f'460x340+{xpos}+{ypos}')\r\n self.hide_history()\r\n\r\n else:\r\n self.master.attributes('-topmost', False)\r\n self.hide_or_show.show_minimize_maximize()\r\n self.push_front_button.config(image=self.push_front_image)\r\n\r\n def show_history(self):\r\n '''Show history area and insert history label, history area, clear button, info button, place at top button and up arrow button'''\r\n\r\n self.is_shown = True\r\n xpos, ypos = self.get_updated_postition()\r\n\r\n self.text_area.config(width=29)\r\n self.push_front_frame.place_forget()\r\n self.history_frame.place(x=10, y=342)\r\n self.show_history_frame.place_forget()\r\n self.hide_history_frame.place(x=0, y=555)\r\n self.push_front_frame.place(x=270, y=310)\r\n self.history_label_frame.place(x=10, y=305)\r\n self.clear_history_frame.place(x=318, y=310)\r\n self.master.geometry(f'460x593+{xpos}+{ypos}')\r\n self.push_front_button.grid(row=0, column=0, ipadx=9, ipady=0)\r\n\r\n def hide_history(self):\r\n '''Hide history area and remove history label, history area, clear button, info button, place at top button and insert down arrow buton'''\r\n\r\n self.is_shown = False\r\n\r\n self.master.geometry(f'460x340')\r\n self.history_frame.place_forget()\r\n self.push_front_frame.place_forget()\r\n self.history_label_frame.place_forget()\r\n self.clear_history_frame.place_forget()\r\n self.show_history_frame.place(x=0, y=303)\r\n\r\n self.text_area.config(width=25)\r\n self.text_frame.place(x=10, y=10)\r\n self.push_front_frame.place(x=391, y=10)\r\n self.push_front_button.grid(row=0, column=0, padx=1, ipadx=13, ipady=4)\r\n\r\n def ctrl_h(self):\r\n '''Command for crl+h'''\r\n\r\n if not self.is_shown:\r\n self.show_history()\r\n\r\n else:\r\n self.hide_history()\r\n\r\n def keyaction(self, event=None, values=None):\r\n '''Check if the input key from both keyboard and buttons is between 0123456789+-*./%c\r\n\r\n Edge Cases:\r\n 01. Make sure user only enters value within '0123456789+*-÷.%'.\r\n 02. Do not repeat '.' (deicmal) until any operators is inserted.\r\n 03. Remove default value '0' if '.' (decimal) is not supplied at the first place.\r\n 04. If the last value is operators and another operator is entered again then replace the recent entered operators with the previous operators.\r\n 05. Do not supply any operators if the last value is '.' (decimal).\r\n 06. Do not make calculation if value is operator except '%'.\r\n 07. Replace \"Cannot divide by Zero\" with any number when supplied else replace with '0'\r\n 08. Do not repeat '.' (decimal) when removed using \"DEL\" button or \"Backspace\" key.\r\n 09. Insert '0' before '.' (decimal) when only '.' (decimal) is supplied.\r\n 10. Do not insert '%' after operator or '%' itself.\r\n 11. Don't insert any number if the last value is '%' except operators\r\n 12. If user inserts '0' right after operator follwed by numbers then remove that '0'. Eg: 450+052, remove '0' from 052 which changes to 450+52\r\n because \"eval\" function treats \"450+052\" as invalid expression except if user inserts '0.022' here don't remove '0' from '022' beacuse it\r\n contains '.' (decimal) which is valid.\r\n 13. If user inserts '45.00000' and enters any operators after that then remove '.00000'\r\n 14. If (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) are not caused then insert as per the user.\r\n '''\r\n\r\n if event: # Check if the value is provided from the keyboard\r\n value = event.char.replace('/', '÷')\r\n\r\n else: # Check if the value is provided from clicking button\r\n value = values\r\n\r\n if value in '0123456789+-*.÷%': # Edge Cases 01\r\n try:\r\n get = self.var.get()\r\n\r\n if get == 'Cannot divide by ZERO': # Edge Cases 07\r\n if value in '0123456789':\r\n self.var.set('')\r\n val = value\r\n\r\n elif value in '+-.*÷%':\r\n self.var.set('')\r\n val = '0'\r\n\r\n elif value in '+-.*÷%' and self.avoid_duplicate_operator(value): # Edge Cases 2, 5, 6, 10 and 11 in avoid_duplicate_operator function\r\n if self.decimal_placeable and value == '.': # Edge Cases 02\r\n val = get + value\r\n self.decimal_placeable = False\r\n\r\n if value != '.':\r\n try:\r\n if int(get[get.rfind('.') + 1:]) == 0: # Edge Cases 13\r\n val = get[:get.rfind('.')] + value\r\n\r\n else:\r\n val = get + value\r\n self.decimal_placeable = True\r\n\r\n except ValueError:\r\n val = get + value\r\n\r\n elif value in '0123456789':\r\n if any(s in get for s in '+-*÷') and get[-1] in '0123456789' and get[-2] == '0' and self.decimal_placeable: # Edge Cases 12\r\n val = f'{get[:-2]}{get[-1]}{value}'\r\n\r\n elif get[:2] != '0.':\r\n if get[-1] == '%' and value in '0123456789': # Edge Cases 11\r\n pass\r\n\r\n elif get[0] == '0' and get[1] not in '+-*÷': # This condition is to produce IndexError if the first value in text area is 0 and the second value is not operator\r\n pass\r\n\r\n else:\r\n val = get + value\r\n\r\n else: # Edge Cases 14\r\n val = get + value\r\n\r\n self.var.set(val)\r\n\r\n except IndexError:\r\n val = get.lstrip('0') + value # Edge Cases 03\r\n self.var.set(val)\r\n\r\n except UnboundLocalError: # This error is caused when user enters '.' (decimal) when previous answer has already decimal in text area\r\n pass\r\n\r\n elif value.lower() == 'a':\r\n self.ac_command()\r\n self.clear_history()\r\n\r\n elif value.lower() == 'c':\r\n self.ac_command()\r\n\r\n elif value.lower() is 'h':\r\n self.clear_history()\r\n\r\n elif value.lower() == 'i':\r\n self.info()\r\n\r\n elif value.lower() == 'q':\r\n self.master.destroy()\r\n\r\n def avoid_duplicate_operator(self, value=None):\r\n '''Restricts user for entering continous operators (+ - ÷ *)'''\r\n\r\n get = self.var.get()\r\n\r\n if get[-1] in '+-*÷' and value == '.': # Edge Cases 09\r\n val = get + '0.'\r\n self.var.set(val)\r\n self.decimal_placeable = False\r\n return False\r\n\r\n if get[-1] == '.': # Edge Cases 05\r\n return False\r\n\r\n if get[-1] == '%' and value in '+-*÷':\r\n val = get + value\r\n self.var.set(val)\r\n return False\r\n\r\n if get[-1] == value == '%' or (get[-1] in '+-*÷' and value == '%'): # Edge Case 10\r\n return False\r\n\r\n if get[-1] in '+-*÷%' and value in '+-*÷%': # Edge Cases 04\r\n val = get[:-1] + value\r\n self.var.set(val)\r\n return False\r\n\r\n return True\r\n\r\n def equals_to(self, event=None):\r\n '''Calculate the given equation'''\r\n\r\n value = self.var.get().replace('%', '/100').replace('÷', '/')\r\n\r\n try:\r\n if self.count_operators(value):\r\n get = self.var.get()\r\n answer = str(eval(value))\r\n\r\n if '.' in answer: # if answer contains '.' (decimal)\r\n split = answer.split('.')\r\n\r\n if int(split[1]) == 0: # Removing .0 when the value in answer after '.' (decimal) is all '0'\r\n self.var.set(split[0])\r\n hist = f'{get} = {split[0]}\\n'\r\n self.decimal_placeable = True\r\n\r\n else: # If value in answer after '.'(decimal) is not all '0'\r\n self.var.set(answer)\r\n hist = f'{get} = {answer}\\n'\r\n self.decimal_placeable = False\r\n\r\n else: # if answer does not contain '.' (decimal)\r\n self.var.set(answer)\r\n hist = f'{get} = {answer}\\n'\r\n self.decimal_placeable = True\r\n\r\n self.history(hist)\r\n\r\n except ZeroDivisionError: # This error is caused if any number is divided by \"0\"\r\n winsound.MessageBeep()\r\n self.var.set('Cannot divide by ZERO')\r\n\r\n def count_operators(self, value):\r\n '''Counts number of operators in the expression.\r\n\r\n If the number of operators is more than 1 then only the expression can be calculated else nothing will happen\r\n when \"=\" button or \"enter\" key is pressed'''\r\n\r\n count = 0\r\n\r\n if self.var.get()[-1] in '+-*÷': # Edge Cases 06\r\n return False\r\n\r\n if not value.startswith('-'):\r\n count += 1\r\n\r\n for val in value:\r\n if val in '+-*/':\r\n count += 1\r\n\r\n if count > 1:\r\n return True\r\n\r\n return False\r\n\r\n def show_scrollbar(self):\r\n '''show scrollbar when text is more than the height of text area'''\r\n\r\n if self.history_area.cget('height') < int(self.history_area.index('end-1c').split('.')[0]):\r\n self.scrollbar.grid(column=1, row=0, sticky=N + S)\r\n self.history_area.config(yscrollcommand=self.scrollbar.set)\r\n self.master.after(100, self.hide_scrollbar)\r\n\r\n else:\r\n self.master.after(100, self.show_scrollbar)\r\n\r\n def hide_scrollbar(self):\r\n '''hide scrollbar when text is less than the height of text area'''\r\n\r\n if self.history_area.cget('height') >= int(self.history_area.index('end-1c').split('.')[0]):\r\n self.scrollbar.grid_forget()\r\n self.history_area.config(yscrollcommand=None)\r\n self.master.after(100, self.show_scrollbar)\r\n\r\n else:\r\n self.master.after(100, self.hide_scrollbar)\r\n\r\n def history(self, value=None):\r\n '''Display previous calculations'''\r\n\r\n self.history_area.config(state=NORMAL)\r\n\r\n if self.history_area.get('1.0', 'end-1c') == 'There\\'s no history yet.':\r\n self.history_area.delete('1.0', END)\r\n\r\n self.history_area.insert(END, value)\r\n self.history_area.config(state=DISABLED)\r\n\r\n def clear_history(self):\r\n '''Clear calculation history'''\r\n\r\n self.history_area.config(state=NORMAL)\r\n self.history_area.delete('1.0', 'end')\r\n self.history_area.insert('end', 'There\\'s no history yet.')\r\n self.history_area.config(state=DISABLED)\r\n\r\n def insert_zero(self):\r\n '''Insert zero when there is no value in entry box.\r\n\r\n This is especially witten because when user turn on or off the numlock then \"0\" gets removed\r\n from the entry box. So, this function reinserts removed \"0\" to the entry box even if user\r\n turn on or off the numlock only if there is no any value in entry box.'''\r\n\r\n get = self.var.get().strip()\r\n\r\n if not get:\r\n self.var.set('0')\r\n\r\n self.master.after(10, self.insert_zero)\r\n\r\n def info(self):\r\n '''Show information about binded keys for different actions'''\r\n\r\n values = '\\n'.join(['Q = Quit', 'A = Clear all', 'H = Clear history', 'C = Clear text box', 'I = Show this window', 'Ctrl+h = Hide / Show history'])\r\n messagebox.showinfo('Key Bindings', values)\r\n\r\n def resource_path(self, relative_path):\r\n \"\"\" Get absolute path to resource from temporary directory\r\n\r\n In development:\r\n Gets path of photos that are used in this script like in icons and title_image from current directory\r\n\r\n After compiling to .exe with pyinstaller and using --add-data flag:\r\n Gets path of photos that are used in this script like in icons and title image from temporary directory\"\"\"\r\n\r\n try:\r\n base_path = sys._MEIPASS # PyInstaller creates a temp folder and stores path in _MEIPASS\r\n\r\n except AttributeError:\r\n base_path = os.path.abspath(\".\")\r\n\r\n return os.path.join(base_path, relative_path)\r\n\r\n\r\nif __name__ == '__main__':\r\n Calculator()\r\n","sub_path":"PROJECT GUIs/CALCULATOR/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":24775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"42664365","text":"import unittest\nimport requests\nimport random\nimport json\n\nTEST_URL_BASE=\"http://64.227.4.120:8001\"\n\nclass APITester(unittest.TestCase):\n def send_json(self, path, json):\n return requests.post(TEST_URL_BASE + path, json=json)\n\n def send_get(self, path, params):\n return requests.get(TEST_URL_BASE + path + params)\n\n def test_result_category(self):\n random_identifier = str(random.randint(10**5,10**6-1)) #so we can rerun tests\n data = {\"name\" : \"Test Patience\"+random_identifier, \"email\" : \"test\"+random_identifier+\"@test.com\", \"mobile_number\": \"1234567890\",\n \"postal_address\" : \"123 Test, Salt Lake City, UT\", \"tenant_id\" : 1}\n req_o = data\n rsp = self.send_json(\"/patient/insert\", req_o)\n self.assertTrue(rsp.status_code == 201, \"Bad status response code: {}\".format(rsp.status_code))\n rsp_o = rsp.json()\n print(rsp_o)\n id = rsp_o[\"id\"]\n self.assertTrue(rsp_o[\"msg\"] == 'Operation Successful', \"Got unexpected msg in response {}\".format(rsp_o[\"msg\"]))\n rsp = self.send_json(\"/patient/insert\", req_o)\n self.assertTrue(rsp.status_code == 409, \"Bad status response code: {}\".format(rsp.status_code))\n rsp = self.send_get(\"/patient\", \"/{}\".format(id))\n self.assertTrue(rsp.status_code == 200, \"Bad status response code: {}\".format(rsp.status_code))\n rsp_o = rsp.json()\n expect_rsp_o = data.copy()\n expect_rsp_o[\"id\"] = id\n expect_rsp_o[\"create_datetime\"] = rsp_o[\"create_datetime\"]\n self.assertTrue(rsp_o == expect_rsp_o, \"Got unexpected data: {}, expected {}\".format(rsp_o, expect_rsp_o))\n\n #updating a record\n data2 = {\"mobile_number\": \"123224323\", \"id\" : 1}\n rsp = self.send_json(\"/patient/update\", data2)\n self.assertTrue(rsp.status_code == 201, \"Bad status response code: {}\".format(rsp.status_code))\n rsp_o = rsp.json()\n self.assertTrue(rsp_o[\"msg\"] == 'Operation Successful', \"Got unexpected msg in response {}\".format(rsp_o[\"msg\"]))\n\n #deleting a record\n data3 = {\"id\": id}\n rsp = self.send_json(\"/patient/delete\", data3)\n self.assertTrue(rsp.status_code == 201, \"Bad status response code: {}\".format(rsp.status_code))\n rsp_o = rsp.json()\n id = rsp_o[\"id\"]\n self.assertTrue(rsp_o[\"msg\"] == 'Operation Successful', \"Got unexpected msg in response {}\".format(rsp_o[\"msg\"]))\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"275603429","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torchvision\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport os\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import DataLoader\nfrom collections import OrderedDict\nfrom PIL import Image, ImageEnhance\n\nclass EarlyStopping:\n def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt'):\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_min = np.Inf\n self.delta = delta\n self.path = path\n\n def __call__(self, val_loss, model):\n score = -val_loss\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n elif score < self.best_score + self.delta:\n self.counter += 1\n print(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n self.counter = 0\n\n def save_checkpoint(self, val_loss, model):\n if self.verbose:\n print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n torch.save(model.state_dict(), self.path)\n self.val_loss_min = val_loss\n\nclass ReadCSV:\n def __init__(self, path):\n self.path = path\n self.rows = None\n self.all_list = []\n self.label = []\n\n def read(self):\n with open(self.path) as csvfile:\n self.rows = csv.reader(csvfile)\n for row in self.rows:\n self.all_list.append(row)\n for i in range(1,len(self.all_list)):\n self.label.append(self.all_list[i])\n return self.label\n\nclass CustomDataset(Dataset):\n def __init__(self, root, label, data):\n self.imgs = label\n self.root = root\n self.data = data\n \n def __getitem__(self, index):\n path, label = self.imgs[index]\n img = Image.open(self.root+path).convert('RGB')\n '''enh_col = ImageEnhance.Color(img)\n img_colored = enh_col.enhance(1.5)\n enh_con = ImageEnhance.Contrast(img_colored)\n img = enh_con.enhance(1.5)'''\n if self.data == 'train':\n img = transforms.Compose([\n #transforms.Resize((264, 264)),\n #transforms.CenterCrop(224),\n transforms.Resize((224, 224)),\n transforms.RandomRotation(15),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])(img)\n else:\n img = transforms.Compose([\n #transforms.Resize((264, 264)),\n #transforms.CenterCrop(224),\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])(img)\n if label == 'A':\n label = 0\n elif label == 'B':\n label = 1\n else:\n label = 2\n return img, label\n \n def __len__(self):\n return len(self.imgs)\n\ndef run():\n torch.multiprocessing.freeze_support()\n\ndef accuracy_test(model, dataloader):\n correct = 0.0\n total = 0.0\n test_loss = 0.0\n model.eval()\n with torch.no_grad(): #使用驗證集時關閉梯度計算\n for images, labels in iter(dataloader):\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n criterion = nn.CrossEntropyLoss()\n loss = criterion(outputs, labels)\n test_loss += float(loss.item()*images.size(0))\n _, predicted = torch.max(outputs, 1) #torch.max返回輸出結果中,按dim=1排列的每一列最大數據及他的索引,在這裡只取用索引\n total += labels.size(0) #tensor的列大小,total=len(test_dataset)\n correct += (predicted==labels).sum().item() #將預測及標籤兩相同大小張量逐一比較各相同元素的個數\n \n return correct/total, test_loss\n\ntrain_root = r\"..\\..\\dataset\\Custom Data\\all_train\\\\\"\ntrain_csv = r\"..\\..\\dataset\\Custom Data\\all_train.csv\"\ntest_root = r\"..\\..\\dataset\\Custom Data\\train\\\\\"\ntest_csv = r\"..\\..\\dataset\\Custom Data\\train.csv\"\n\ntrain_csv = ReadCSV(train_csv)\ntrain_label = train_csv.read()\n\ntest_csv = ReadCSV(test_csv)\ntest_label = test_csv.read()\n#----------------------alexnet----------------------\nBEST_MODEL_PATH = r\"..\\model\\alex.pth\"\nmodel = models.alexnet(pretrained=True)\nmodel.classifier[6] = torch.nn.Linear(model.classifier[6].in_features, 3)\nfor param in model.parameters():\n param.require_grad = False\nprint(model)\n\nweight_p, bias_p = [],[]\nfor name, p in model.named_parameters():\n if 'bias' in name:\n bias_p += [p]\n else:\n weight_p += [p]\n\nclassifier_layers_params = list(map(id, model.classifier.parameters()))\nbase_params = filter(lambda p:id(p) not in classifier_layers_params, model.parameters())\n\nif __name__ == '__main__':\n run()\n train_dataset = CustomDataset(train_root, train_label, 'train')\n test_dataset = CustomDataset(test_root, test_label, 'test')\n \n # img3 = transforms.ToPILImage()(test_dataset[0][0]).convert('RGB')\n # plt.imshow(img3)\n # plt.axis('off')\n # plt.show()\n # img5 = transforms.ToPILImage()(train_dataset[500][0]).convert('RGB')\n # plt.imshow(img5)\n # plt.axis('off')\n # plt.show()\n \n print(\"testing dataset count: \", len(test_label))\n\n train_loader = DataLoader(train_dataset, batch_size=24, shuffle=True, num_workers=0)\n test_loader = DataLoader(test_dataset, batch_size=24, shuffle=True, num_workers=0)\n\n img, label = test_loader.__iter__().__next__()\n print(\"check label: \", label)\n\n device = torch.device('cuda')\n model = model.to(device)\n\n NUM_EPOCHS = 200\n best_accuracy = 0.0\n history = []\n early_stopping = EarlyStopping(patience=7, verbose=True, path=BEST_MODEL_PATH)\n\n #optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n optimizer = optim.SGD([{'params': model.classifier.parameters(), 'lr':1e-3},\n {'params': base_params, 'lr':5e-5}],\n momentum=0.9,\n weight_decay=1e-4)\n '''optimizer = optim.SGD([{'params': weight_p, 'weight_decay':1e-2},\n {'params': bias_p, 'weight_decay':0, 'lr':1e-5}], \n lr=1e-3, \n momentum=0.9)'''\n #optimizer = optim.Adam(model.parameters(), lr=0.001)\n #optimizer = optim.Adam(model.fc.parameters(), lr=0.001)\n #optimizer = optim.RMSprop(model.parameters(), lr=1e-3)\n tune_lr = optim.lr_scheduler.ReduceLROnPlateau( #使用動態學習率\n optimizer,\n mode='max',\n factor=0.7,\n patience=5,\n verbose=True,\n threshold=0.0001,\n threshold_mode='rel',\n cooldown=0,\n min_lr=0,\n eps=1e-08\n )\n for epoch in range(NUM_EPOCHS):\n \n model.train()\n train_acc_count = 0.0\n train_loss = 0.0\n\n for images, labels in iter(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n optimizer.zero_grad()\n outputs = model(images)\n loss = nn.CrossEntropyLoss()\n loss = loss(outputs, labels)\n loss.backward()\n optimizer.step()\n _, pred = torch.max(outputs, 1)\n num_correct = (pred==labels).sum()\n train_acc_count += float(num_correct.item())\n train_loss += float(loss.item()*images.size(0))\n train_accuracy = float(train_acc_count) / float(len(train_dataset))\n train_loss = train_loss/float(len(train_dataset))\n\n test_accuracy, test_loss = accuracy_test(model, test_loader)\n test_loss = test_loss/len(test_loader.dataset)\n history.append([train_accuracy, test_accuracy, train_loss, test_loss])\n tune_lr.step(train_accuracy)\n \n print('Epoch: %d: Train Acc: %f, Valid Acc: %f \\n\\t Train Loss: %f, Valid Loss: %f' % \n (epoch+1, train_accuracy, test_accuracy, train_loss, test_loss))\n \n early_stopping(test_loss, model)\n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n\n if train_accuracy >= 0.7:\n if test_accuracy >= best_accuracy:\n early_stopping.counter = 0\n print('Validation accuracy increase ({:.4f} --> {:.4f}). Saving model ...'.format(\n best_accuracy, test_accuracy))\n torch.save(model.state_dict(), BEST_MODEL_PATH)\n best_accuracy = test_accuracy\n print('----------------------------------------------------')\n history = np.array(history)\n fig = plt.figure(figsize=[12.8,4.8])\n ax1 = plt.subplot(121)\n ax1.plot(history[:,0:2])\n ax1.legend(['Train Acc', 'Valid Acc'], loc='best')\n ax1.set_xlabel('Epoch')\n ax1.set_ylabel('Accuracy')\n ax1.set_ylim(0, 1)\n ax2 = plt.subplot(122)\n ax2.plot(history[:,2:4])\n ax2.legend(['Train Loss', 'Valid Loss'], loc='best')\n ax2.set_xlabel('Epoch')\n ax2.set_ylabel('Loss')\n ax2.set_ylim(0, 1.2)\n plt.show()\n print('training complete')","sub_path":"Script/training/mango_train_CustomData.py","file_name":"mango_train_CustomData.py","file_ext":"py","file_size_in_byte":10525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"430350381","text":"import debug_toolbar\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n TokenVerifyView\n)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n # Rest Framework path\n path('api-auth/', include('rest_framework.urls')),\n\n # User\n path('api/users/', include('user.urls')),\n\n # Ad\n path('api/ad/', include('ad.urls')),\n\n # Bid\n path('api/bid/', include('bid.urls')),\n\n # Participant\n path('api/participant/', include('participant.urls')),\n\n # Room chat\n path('api/chat/', include('room_chat.urls')),\n\n # Token\n path('api/token/', TokenObtainPairView.as_view()),\n path('api/token/refresh/', TokenRefreshView.as_view()),\n path('api/token/verify/', TokenVerifyView.as_view()),\n\n # Debug toolbar\n path('__debug__/', include(debug_toolbar.urls)),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"rest_api_backend_va_project/rest_api_backend_va_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162203644","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n @file: __init__.py\n @author: malin\n @mail: malinbupt@gmail.com\n @date: 五 11/27 19:57:05 2015\n\"\"\"\n\n\n__all__ = ['base', 'executor']\n\n\nimport base\nimport error\nimport executor\nfrom log import Logger\nfrom common.decorator import Singleton\n\n\n\n@Singleton\nclass Reactor(base.ReactorBase):\n \"\"\"\n Reactor pattern for event driven model.\n This is a singleton class.\n\n @attr __Running: a flag which is true if Reactor is running\n @attr __RanBefore: a flag which is true if Reactor has runned\n and is stopped now.\n \"\"\"\n\n\n def __init__(self):\n base.ReactorBase.__init__(self)\n self.__Running = False\n self.__RanBefore = False\n self.__Executor = executor.SelectReactor()\n\n\n def SetExecutor(self, executor):\n self.__Executor = executor\n\n\n def Run(self):\n \"\"\"\n Return a ReactorIsRunning error if the Reactor is running.\n Return a ReactorHasRan error if the Reactor has been run once.\n \"\"\"\n err = None\n if self.__Running:\n err = error.ReactorIsRunning('Can\\'t run a Reactor which is running.')\n elif self.__RanBefore:\n err = error.ReactorHasRan('Can\\'t run the Reactor more than one time.')\n\n if err:\n Logger.error(err.Message())\n return\n\n Logger.info('Reactor is running...')\n self.__Running = True\n\n while (self.__Running):\n readers, writers, _ = self.__Executor.GetReadyFDs(self.GetReaders(), self.GetWriters())\n\n # reading datas\n for reader in readers:\n Logger.info('Reading datas from %s', reader.GetName())\n reader.Read()\n\n # writing datas\n for writer in writers:\n Logger.info('Writing datas to %s', writer.GetName())\n writer.Write()\n\n Logger.info('Reactor is stopped.')\n\n\n def Stop(self):\n \"\"\"\n Return a ReactorIsStopped error if the Reactor isn't running.\n \"\"\"\n if self.__Stoped:\n err = error.ReactorIsStopped('Can\\'t stop a Reactor which is stopped.')\n Logger.error(err.Message())\n return\n\n self.__Running = False\n self.__RanBefore = True\n\n Logger.info('Reactor is stopping...')\n","sub_path":"reactor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"544380148","text":"#programa que maneje una lista supermercado donde puedes agregar , ver,\n# buscar y eliminar articulos los articulos estan en una tupla arroz,leche,tuna,cereal,jugo#\ndef imprimi(articulos):\n print(\"articulos:\")\n for k, v in articulos.items():\n print(\"Articulo:\",k)\n print()\ndef agregar(articulos,articulo):\n articulos[articulo]=articulo\n\ndef borrar(articulos, nombre):\n if nombre in articulos:\n del articulos[nombre]\n else:\n print(nombre,\" no hay articulo en la lista.\")\nlista_de_tupla= (\"1- arroz\",\"2- leche\",\"3-tuna\",\"4- cereal\",\"5- jugo\")\ndef menu():\n\n print('1. Agregar articulo')\n print('2. Eliminar articulo')\n print('3. Ver lista')\n print('4. Salir')\n\nif __name__ == '__main__':\n lista_de_articulos = {}\n opcion_menu = 0\n while True:\n menu()\n try:\n opcion_menu = int(input(\"¿Que opción escoges?: \"))\n except:\n print(\"Opcion no valida\")\n else:\n if opcion_menu == 1:\n print(\"Agregar Articulo\")\n print(\"Articulos disponibles\")\n print(lista_de_tupla)\n nombre = input(\"articulo: \")\n agregar(lista_de_articulos, nombre)\n\n elif opcion_menu == 2:\n print(\"Eliminar articulo\")\n imprimi(lista_de_articulos)\n nombre = input(\"Articulo: \")\n borrar(lista_de_articulos, nombre)\n elif opcion_menu == 3:\n print(\"ver lista\")\n imprimi(lista_de_articulos)\n","sub_path":"Laboratorios/quiz3.py","file_name":"quiz3.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"293303226","text":"import cv2 \r\nimport numpy as np \r\nimport os \r\nimport argparse \r\n\r\nimport glob\r\nimport time\r\n\r\n\r\n#args = argparse.ArgumentParser()\r\n#args.add_argument('--n', type=str,\r\n# help='name of new subject')\r\n#args.add_argument(\"--g\" , type = str , help = \"name of gesture\")\r\n\r\n#args = args.parse_args()\r\n\r\n#subject_name = args.n\r\n#gesture_name = args.g\r\n\r\n#dst = \"data/{}/{}/\".format(gesture_name, subject_name)\r\n\r\nwidth = 1920\r\nheight = 1080\r\nfps = 30\r\n\r\ndef get_video_infor(capture):\r\n if capture.isOpened(): \r\n # get vcap property \r\n width = capture.get(cv2.CAP_PROP_FRAME_WIDTH) # float `width`\r\n height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT) # float `height`\r\n # it gives me 0.0 :/\r\n fps = capture.get(cv2.CAP_PROP_FPS)\r\n return (int(width), int(height)), int(fps)\r\n\r\ncap1 = cv2.VideoCapture(0)\r\n\r\ncap2 = cv2.VideoCapture(1)\r\ncap3 = cv2.VideoCapture(2)\r\ncap4 = cv2.VideoCapture(3)\r\n\r\ncap1.set(cv2.CAP_PROP_FRAME_WIDTH, width)\r\ncap1.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\r\ncap2.set(cv2.CAP_PROP_FRAME_WIDTH, width)\r\ncap2.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\r\n\r\ncap3.set(cv2.CAP_PROP_FRAME_WIDTH, width)\r\ncap3.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\r\ncap4.set(cv2.CAP_PROP_FRAME_WIDTH, width)\r\ncap4.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\r\n\r\n# cap1.set(cv2.cv.CV_CAP_PROP_FPS,fps)\r\n# cap2.set(cv2.cv.CV_CAP_PROP_FPS,fps)\r\n# cap3.set(cv2.cv.CV_CAP_PROP_FPS,fps)\r\n# cap4.set(cv2.cv.CV_CAP_PROP_FPS,fps)\r\n\r\n\r\n\r\ncap4_infor = get_video_infor(cap4)\r\n\r\n\r\n\r\ncap1_infor, cap2_infor, cap3_infor = get_video_infor(cap1), get_video_infor(cap2), get_video_infor(cap3)\r\nprint(cap1_infor, cap2_infor , cap3_infor , cap4_infor)\r\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\r\n\r\n# out1 = cv2.VideoWriter(dst + 'cam1-{}.avi'.format(1),fourcc, cap1_infor[1], cap1_infor[0])\r\n# out2 = cv2.VideoWriter(dst + 'cam2-{}.avi'.format(2),fourcc, cap2_infor[1], cap2_infor[0])\r\n# out3 = cv2.VideoWriter(dst + 'cam3-{}.avi'.format(3),fourcc, cap3_infor[1], cap3_infor[0])\r\n# out4 = cv2.VideoWriter(dst + 'cam4-{}.avi'.format(4),fourcc, cap4_infor[1], cap4_infor[0])\r\n\r\nwhile(True):\r\n # Capture frame-by-frame\r\n ret1, frame1 = cap1.read()\r\n ret2, frame2 = cap2.read()\r\n ret3, frame3 = cap3.read()\r\n ret3, frame4 = cap4.read()\r\n\r\n if any((not ret1, not ret2 , not ret3)):\r\n break\r\n\r\n cv2.imshow('frame1', frame1)\r\n cv2.imshow('frame2',frame2)\r\n cv2.imshow('frame3',frame3)\r\n cv2.imshow(\"frame4\", frame4)\r\n # out1.write(frame1)\r\n # out2.write(frame2)\r\n # out3.write(frame3)\r\n # out4.write(frame4)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n# When everything done, release the capture\r\ncap1.release()\r\ncap2.release()\r\ncap3.release()\r\ncv2.destroyAllWindows()","sub_path":"test_cam.py","file_name":"test_cam.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"105674760","text":"import sys,os, inspect\r\ncmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe() ))[0]))\r\nsys.path.insert(0, cmd_folder)\r\nif __name__ == 'Context':\r\n from Human import Human\r\nelse:\r\n from .Human import Human\r\nfrom flask import render_template,request\r\n\r\n\r\nclass Context():\r\n ___dict__ = ('fullname', 'pay', 'age','_magic','_position')\r\n def __init__(self,employer: Human):\r\n self.Context = ''\r\n self._employer = employer\r\n self._position = ''\r\n self.fullname = ''\r\n self.pay = ''\r\n self.age = 0\r\n self._magic = 0\r\n def do_magic_logic(self):\r\n return(self._employer.do_magic())\r\n\r\n def do_add_employer(self):\r\n self.fullname = request.form.get('fullname')\r\n self.pay = request.form.get('pay')\r\n self.age = int(request.form.get('age'))\r\n\r\n\r\n def dbinit(self, employer: Human, it = None):\r\n self._employer = employer\r\n self._position = self._employer.do_print()[0]\r\n self.fullname = it[1] if it is not None else ''\r\n self.pay = it[2] if it is not None else ''\r\n self.age = int(it[3]) if it is not None else 0\r\n\r\n def do_import_logic(self):\r\n return(self._employer.do_import())\r\n","sub_path":"app/asm1905/st08/Context.py","file_name":"Context.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"448143537","text":"\"\"\"\nconcatenate the LDhelmet output of rho for chunks of chromsome and write a new\nfile with only one header and with no overlapping SNP positions\n\"\"\"\n\nimport sys, argparse, glob, os\n\nparser = argparse.ArgumentParser(description=\"\"\"concatenates LDhelmet output files per\n chromosome, given a directory of files\"\"\")\nparser.add_argument('input_directory', help='a directory with the chunks of output in it')\nargs = parser.parse_args()\n\n# here are all the files in the directory\nall_files = os.listdir(args.input_directory)\n\n# here are all the relevant ones:\nrho_files = []\nfor x in all_files:\n if x.endswith('rho.out'):\n rho_files.append(x)\n\n# here are the contigs\nchrs = set([x.split('_')[0] for x in rho_files])\n\nfor chrom in chrs:\n files = [x for x in rho_files if x.startswith(chrom + '_')]\n if len(files) == 0:\n continue\n # print(chrom)\n # print(files)\n # print()\n\n starts = [1] + [x for x in range(1000000, 1000000 * len(files), 1000000)]\n # print(files)\n # print(starts)\n\n # make a dict of startpostion: filename\n file_dict = {}\n for i in starts:\n for j in files:\n start = int(j.split('_')[1].split('-')[0])\n if start == i:\n file_dict[i] = j\n\n with open(chrom + '.rho.concat.txt', 'wt') as f_out:\n for i in starts:\n # if it's the first file, write everything:\n if i == 1:\n with open(file_dict[i], 'rt') as f_in:\n for line in f_in:\n f_out.write(line)\n # otherwise, skip the first four lines (which are 3 lines of header +\n # the single overlapping SNP pair)\n else:\n counter = 0\n with open(file_dict[i], 'rt') as f_in:\n for line in f_in:\n if counter < 4:\n counter+=1\n continue\n f_out.write(line)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n","sub_path":"concat_LDhelmet_rho_output.py","file_name":"concat_LDhelmet_rho_output.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"541591249","text":"from django.conf.urls import url\n\nfrom wagtail.wagtailsnippets.views import chooser, snippets\n\nurlpatterns = [\n url(r'^$', snippets.index, name='index'),\n\n url(r'^choose/$', chooser.choose, name='choose_generic'),\n url(r'^choose/(\\w+)/(\\w+)/$', chooser.choose, name='choose'),\n url(r'^choose/(\\w+)/(\\w+)/(\\d+)/$', chooser.chosen, name='chosen'),\n\n url(r'^(\\w+)/(\\w+)/$', snippets.list, name='list'),\n url(r'^(\\w+)/(\\w+)/add/$', snippets.create, name='add'),\n url(r'^(\\w+)/(\\w+)/(\\d+)/$', snippets.edit, name='edit'),\n url(r'^(\\w+)/(\\w+)/(\\d+)/delete/$', snippets.delete, name='delete'),\n url(r'^(\\w+)/(\\w+)/(\\d+)/usage/$', snippets.usage, name='usage'),\n]\n","sub_path":"wagtail/wagtailsnippets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335936956","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom src.utils import calculate_accuracy\n\ndef train(model, iterator, optimizer, criterion, device, scheduler):\n\t\"\"\"Runs the training loop for the model.\n\n\t\tArgs:\n\t\t\tmodel (nn.Module): Pytorch model object of our defined class.\n\t\t\titerator (torch.utils.Data.DataLoader): The iterator for the data.\n\t\t\toptimizer (torch.optim): The optimization algorithm used to train the model.\n\t\t\tcriterion (torch.nn): The loss function.\n\t\t\tdevice (str): The device which is available, it can be either cuda or cpu.\n\t\t\tscheduler (torch.optim.lr_scheduler): Learning rate scheduler.\n\n\t\tReturns:\n\t\t\tepoch_loss (float): The average loss for one epoch on the given dataloader.\n\t\t\tepoch_acc (float): The average accuracy one the epoch on the given dataloader.\n\t\"\"\"\n\t\n\tepoch_loss = 0\n\tepoch_acc = 0\n\n\t# Put the model in the training mode.\n\tmodel.train()\n\n\t# for each batch in the dataloader\n\tfor batch in iterator: \n\n\t\t# Clear out the gradients from the previous batch\n\t\toptimizer.zero_grad() \n\n\t\t# move the inputs and the labels to the device.\n\t\tinputs = batch[0].to(device) \n\t\tlabels = batch[1].to(device)\n\n\t\t# If we are training LSTM based model, then we also need to pass original lengths of the sequences to the forward function\n\t\tif model.__class__.__name__ == \"BiLSTM\" or model.__class__.__name__ == \"BiLSTM_attention\":\n\t\t\tlengths = torch.as_tensor(batch[2], dtype=torch.int64)\n\t\t\tpredictions = model(inputs, lengths).squeeze(1)\n\t\telse:\n\t\t\t# No need for lengths in the CNN based model.\n\t\t\tpredictions = model(inputs).squeeze(1)\n\n\t\t# calculate the loss value using our loss function on this batch\n\t\tloss = criterion(predictions, labels)\n\n\t\t# calculate the accuracy for this batch\n\t\taccuracy = calculate_accuracy(predictions, labels)\n\n\t\t# Do backpropagation of the gradients\n\t\tloss.backward()\n\n\t\t# update the weights\n\t\toptimizer.step()\n\n\t\t# add the loss and the accuracy for the epoch.\n\t\tepoch_loss += loss.item()\n\t\tepoch_acc += accuracy.item()\n\n\treturn epoch_loss / len(iterator), epoch_acc / len(iterator)\n\n\ndef evaluate(model, iterator, criterion, device):\n\t\"\"\"Runs the evaluation loop for the model.\n\n\t\tArgs:\n\t\t\tmodel (nn.Module): Pytorch model object of our defined class.\n\t\t\titerator (torch.utils.Data.DataLoader): The iterator for the data.\n\t\t\tcriterion (torch.nn): The loss function.\n\t\t\tdevice (str): The device which is available, it can be either cuda or cpu.\n\n\t\tReturns:\n\t\t\tepoch_loss (float): The average loss for the epoch on the given dataloader.\n\t\t\tepoch_acc (float): The average accuracy for the epoch on the given dataloader.\n\t\"\"\"\n\tepoch_loss = 0\n\tepoch_acc = 0\n\n\t# Put the model in the evaluation mode.\n\tmodel.eval()\n\n\t# Do not calculate the gradients in the evaluaion mode. \n\twith torch.no_grad():\n\n\t\t# for each batch in the dataloader\n\t\tfor batch in iterator:\n\n\t\t\t# move the inputs and the labels to the device.\n\t\t\tinputs = batch[0].to(device)\n\t\t\tlabels = batch[1].to(device)\n\n\t\t\t# If we are training LSTM based model, then we also need to pass original lengths of the sequences to the forward function\n\t\t\tif model.__class__.__name__ == \"BiLSTM\" or model.__class__.__name__ == \"BiLSTM_attention\":\n\t\t\t\tlengths = torch.as_tensor(batch[2], dtype=torch.int64)\n\t\t\t\tpredictions = model(inputs, lengths).squeeze(1)\n\t\t\telse:\n\t\t\t\t# No need for lengths in the CNN based model.\n\t\t\t\tpredictions = model(inputs).squeeze(1)\n\n\t \t# calculate the loss value using out loss function on this batch.\n\t\t\tloss = criterion(predictions, labels)\n\n\t\t\t# calculate the accuracy for this batch\n\t\t\taccuracy = calculate_accuracy(predictions, labels)\n\n\t\t\t# add the loss and the accuracy for the epoch.\n\t\t\tepoch_loss += loss.item()\n\t\t\tepoch_acc += accuracy.item()\n\n\treturn epoch_loss / len(iterator), epoch_acc / len(iterator)\n\n\ndef train_and_evaluate(num_epochs, model, train_loader, val_loader, test_loader, optimizer, criterion, device, scheduler):\n\t\"\"\"Call the train and evaluate function for each of the epoch, print the loss and accuracies.\n\n\t\tArgs:\n\t\t\tnum_epochs (int): The number of epochs for which to train the model.\n\t\t\tmodel (nn.Module): Pytorch model object of our defined class.\n\t\t\ttrain_loader (torch.utils.Data.DataLoader): The iterator for the training data.\n\t\t\tval_loader (torch.utils.Data.DataLoader): The iterator for the validation data.\n\t\t\ttest_loader (torch.utils.Data.DataLoader): The iterator for the test data.\n\t\t\toptimizer (torch.optim): The optimization algorithm used to train the model.\n\t\t\tcriterion (torch.nn): The loss function.\n\t\t\tdevice (str): The device which is available, it can be either cuda or cpu.\n\t\t\tscheduler (torch.optim.lr_scheduler): The learning rate scheduler\n\n\t\tReturns:\n\t\t\ttrain_set_loss (List[float]): The loss for the training set\n\t\t\ttrain_set_acc (List[float]): The accuracy for the training set\n\t\t\tval_set_loss (List[float]): The loss for the validation set\n\t\t\tval_set_acc (List[float]): The accuracy for the validation set\n\t\t\ttest_set_loss (List[float]): The loss for the testing set\n\t\t\ttest_set_loss (List[float]): The accuracy for the testing set\n\t\"\"\"\n\n\ttrain_set_loss = []\n\ttrain_set_acc = []\n\tval_set_loss = []\n\tval_set_acc = []\n\ttest_set_loss = []\n\ttest_set_acc = []\n\n\tfor epoch in range(num_epochs):\n \n \t# Call the training function with the training data loader and save loss and accuracy\n\t\ttrain_loss, train_acc = train(model, train_loader, optimizer, criterion, device, scheduler)\n\t\ttrain_set_loss.append(train_loss)\n\t\ttrain_set_acc.append(train_acc)\n\n\t\tscheduler.step()\n\n\t # Call the evaluation function with the vaidation data laoder and save loss and accuracy\n\t\tvalid_loss, valid_acc = evaluate(model, val_loader, criterion, device)\n\t\tval_set_loss.append(valid_loss)\n\t\tval_set_acc.append(valid_acc)\n\n\n \t# Call the evaluation function with the test data loader and save loss and accuracy.\n\t\ttest_loss, test_acc = evaluate(model, test_loader, criterion, device)\n\t\ttest_set_loss.append(test_loss)\n\t\ttest_set_acc.append(test_acc)\n\n\t\tprint(f\"======================EPOCH {epoch}=========================\") \n\t\tprint(f'Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')\n\t\tprint(f'Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%')\n\t\tprint(f'Test. Loss: {test_loss:.3f} | Val. Acc: {test_acc*100:.2f}%')\n\n\treturn train_set_loss, train_set_acc, val_set_loss, val_set_acc, test_set_loss, test_set_acc","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"107322128","text":"\"\"\"\r\nThe root of all OAuth2 resources and operations.\r\n\"\"\"\r\nimport os\r\nimport json\r\n########################################################################\r\nclass OAuth(object):\r\n \"\"\"\r\n The root of all OAuth2 resources and operations.\r\n \"\"\"\r\n _gis = None\r\n _con = None\r\n _portal = None\r\n _url = None\r\n #----------------------------------------------------------------------\r\n def __init__(self, url, gis):\r\n \"\"\"Constructor\"\"\"\r\n self._url = url\r\n self._gis = gis\r\n if self._gis is not None:\r\n self._con = gis._con\r\n self._portal = gis._portal\r\n #----------------------------------------------------------------------\r\n def authorize(self,\r\n client_id,\r\n response_type,\r\n redirect_uris,\r\n client_secret=None,\r\n state=None,\r\n expiration=None,\r\n display=None,\r\n locale=None,\r\n persist=True,\r\n ssl=True):\r\n \"\"\"\r\n The Authentication topic describes the overall OAuth2 authentication\r\n flow. This topic describes the user authorization step of that\r\n flow.\r\n Apps that support user logins use OAuth2 to allow users to log in\r\n to the ArcGIS platform via the app.\r\n User logins using the OAuth2-based ArcGIS APIs are based on the\r\n application guiding the user to log in to the platform via a login\r\n page hosted on the ArcGIS platform. The /oauth2/authorize endpoint\r\n represents that login page. The login page renders an HTML form for\r\n the user to enter their credentials.\r\n The user authentication workflow starts with the authorization\r\n step. Apps need to direct the browser to this URL. client_id,\r\n response_type, and redirect_uri are required parameters. There are\r\n other optional parameters as well, and they;'re described below.\r\n The response_type parameter determines the type of grant - implicit\r\n or authorization. A response_type of token implies implicit grant\r\n and code implies authorization code grant.\r\n Implicit grants are typically used by JavaScript applications, and\r\n they complete the flow in a single step. The end result of\r\n successful authentication is an access_token that's delivered to\r\n the specified redirect_uri in the URL fragment. See the Response\r\n section for details.\r\n Authorization grants are used by mobile, desktop, and server-side\r\n applications, and they complete the flow in two steps.\r\n Authorization represents the first step of that flow. Successful\r\n authorization yields an authorization code that's delivered to the\r\n specified redirect_uri as a query parameter. See the Response\r\n section for details. The second step of the flow requires\r\n exchanging the authorization code obtained in the first step for an\r\n access_token. This is accomplished by accessing the token endpoint\r\n with a grant_type of authorization_code.\r\n\r\n Parameters:\r\n :client_id: The ID of the registered application. Also referred to\r\n as APPID.\r\n :response_type: The type of grant - implicit or authorization.\r\n Values: token, code\r\n token implies implicit grant and code implies authorization code\r\n grant.\r\n :redirect_uris:The URI where the access_token or authorization\r\n code will be delivered upon successful authorization. The URI\r\n must match one of the URIs specified during app registration,\r\n otherwise authorization will be rejected. If registered, a\r\n special value of urn:ietf:wg:oauth:2.0:oob can also be specified\r\n for authorization grants. This will result in the authorization\r\n code being delivered to a portal URL (/oauth2/approval). This\r\n value is typically used by applications that don't have a web\r\n server or a custom URI scheme where the code can be delivered.\r\n :client_secret: The secret of the registered application. Also\r\n referred to as APPSECRET.\r\n :state: An opaque value used by applications to maintain state\r\n between authorization requests and responses. The state, if\r\n specified, will be delivered back to the redirect_uri as is.\r\n Applications can use this parameter to correlate the\r\n authorization request sent with the received response.\r\n :expiration: The requested validity in minutes of access_token for\r\n implicit grants or refresh_token for authorization grants.\r\n For implicit grants, the default validity of access_tokens is 2\r\n hours. The expiration parameter, if specified, overrides the\r\n validity period up to a max of 2 weeks (i.e., 20160 minutes).\r\n For authorization grants, the default validity of access_tokens\r\n is 30 minutes and refresh_tokens is 2 weeks. The expiration\r\n parameter, if specified, overrides the validity period of\r\n refresh_tokens. A permanent refresh_token can be requested by\r\n specifying expiration=-1.\r\n Note that org admins can specify the max validity period of\r\n tokens for their org that supercedes the expiration parameter.\r\n :display: The template used to render the login page.\r\n Based on the client platform, applications can choose one of the\r\n supported templates to render the login page. If not specified,\r\n the default template is used.\r\n Values: default, iframe, win8\r\n :locale: The locale assumed to render the login page.\r\n Applications can pass the user's locale using this parameter. The\r\n login page will be rendered using the language corresponding to\r\n that locale. If not specified, the locale will be determined\r\n based on the org's setting or on the incoming request.\r\n Example: locale=fr\r\n :persist: If true, implies that the user had checked \"Keep me\r\n signed in\" when signing into ArcGIS Online.\r\n :ssl: If true, implies that the user belongs to an ssl-only\r\n organization\r\n \"\"\"\r\n url = \"%s/authorize\" % self._url\r\n params = {\r\n \"f\" : \"json\",\r\n \"redirect_uri\" : redirect_uris,\r\n \"response_type\" : response_type,\r\n \"client_id\" : client_id\r\n }\r\n if ssl:\r\n params['ssl'] = ssl\r\n if persist:\r\n params['persist'] = persist\r\n if locale:\r\n params['locale'] = locale\r\n if display:\r\n params['display'] = display\r\n if expiration:\r\n params['expiration'] = expiration\r\n if state:\r\n params['state'] = state\r\n if client_secret:\r\n params['client_secret'] = client_secret\r\n return self._con.post(path=url,\r\n postdata=params)\r\n #----------------------------------------------------------------------\r\n def apps(self, client_id):\r\n \"\"\"\r\n An app registered with the portal. An app item can be registered by\r\n invoking the register app operation. Every registered app gets an\r\n App ID and App Secret which in OAuth speak are known as client_id\r\n and client_secret respectively.\r\n The app owner has access to the registered app resource. This would\r\n include the organization administrator as well.\r\n\r\n Parameters:\r\n :client_id: The ID of the registered application. Also referred to\r\n as APPID.\r\n \"\"\"\r\n url = \"%s/apps/%s\" % (self._url, client_id)\r\n params = {\"f\" : \"json\"}\r\n return self._con.post(path=url, postdata=params)\r\n #----------------------------------------------------------------------\r\n def register_device(self, client_id, expiration=None):\r\n \"\"\"\r\n Registers a device, like mobile phone with a client id to access a\r\n given Portal or ArcGIS Online Organization.\r\n\r\n Parameters:\r\n :client_id:The ID of the registered application. Also referred to\r\n as APPID.\r\n :expiration: The requested validity in minutes of access_token for\r\n implicit grants or refresh_token for authorization grants.\r\n For implicit grants, the default validity of access_tokens is 2\r\n hours. The expiration parameter, if specified, overrides the\r\n validity period up to a max of 2 weeks (i.e., 20160 minutes).\r\n For authorization grants, the default validity of access_tokens\r\n is 30 minutes and refresh_tokens is 2 weeks. The expiration\r\n parameter, if specified, overrides the validity period of\r\n refresh_tokens. A permanent refresh_token can be requested by\r\n specifying expiration=-1.\r\n Note that org admins can specify the max validity period of\r\n tokens for their org that supercedes the expiration parameter.\r\n \"\"\"\r\n url = \"%s/registerDevice\" % self._url\r\n params = {\r\n \"f\" : \"json\",\r\n \"client_id\" : client_id\r\n }\r\n if expiration:\r\n params['expiration'] = expiration\r\n return self._con.post(path=url,\r\n postdata=params)\r\n #----------------------------------------------------------------------\r\n def token(self,\r\n client_id,\r\n grant_type,\r\n redirect_uri,\r\n code=None,\r\n refresh_token=None,\r\n client_secret=None):\r\n \"\"\"\r\n TODO: Update Docs\r\n \"\"\"\r\n params = {\r\n \"f\" : \"json\",\r\n \"client_id\" : client_id,\r\n \"grant_type\" : grant_type\r\n }\r\n\r\n #----------------------------------------------------------------------\r\n def register_app(self,\r\n item,\r\n redirect_uris,\r\n app_type=\"browser\"):\r\n \"\"\"\r\n The register app operation (POST only) registers an app item with\r\n the portal. App registration results in an APPID and APPSECRET\r\n (also known as client_id and client_secret in OAuth speak,\r\n respectively) being generated for that app. Upon successful\r\n registration, a Registered App type keyword gets appended to the\r\n app item.\r\n Available to the item owner.\r\n\r\n Parameters:\r\n :item: arcgis.gis.Item object\r\n :redirect_uris:The URIs where the access_token or authorization\r\n code will be delivered upon successful authorization. The\r\n redirect_uri specified during authorization must match one of the\r\n registered URIs, otherwise authorization will be rejected.\r\n A special value of urn:ietf:wg:oauth:2.0:oob can also be\r\n specified for authorization grants. This will result in the\r\n authorization code being delivered to a portal URL\r\n (/oauth2/approval). This value is typically used by apps that\r\n don't have a web server or a custom URI scheme where the code can\r\n be delivered.\r\n :app_type:The type of app that was registered indicating whether\r\n it's a browser app, native app, server app, or a multiple\r\n interface app.\r\n Values: browser | native | server| multiple\r\n \"\"\"\r\n url = \"%s/registerApp\" % self._url\r\n itemid = item.id\r\n params = {\r\n \"f\" : \"json\",\r\n \"itemid\" : itemid,\r\n \"appType\" : app_type,\r\n \"redirect_uris\" : redirect_uris\r\n }\r\n return self._con.post(path=url,\r\n postdata=params)\r\n\r\n\r\n","sub_path":"arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/_impl/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":11851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"315136829","text":"import tensorflow as tf\nimport numpy as np\nimport argparse\nimport _init_paths\n\nfrom dataset import get_train_pair\nfrom network import PatchActivationNet\nfrom utils import Avg, get_patch_num\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='songofthewind')\n parser.add_argument('--largek', dest='large_k', default=85)\n parser.add_argument('--middik', dest='middle_k', default=61)\n parser.add_argument('--smallk', dest='small_k', default=33)\n parser.add_argument('--stride', dest='stride', default=1000)\n parser.add_argument('--ysize', dest='y_psize', default=5)\n parser.add_argument('--modelname', dest='model_name', default='pan')\n parser.add_argument('--max_iter', dest='max_iter', default=10000)\n parser.add_argument('--bsize', dest='batch_size', default=1)\n args = parser.parse_args()\n return args\n\nif __name__=='__main__':\n args = parse_args()\n print ('-'*50)\n print ('args::')\n for arg in vars(args):\n print ('%15s : %s'%(arg, getattr(args, arg)))\n print ('-'*50)\n\n save_dir = '/home/mike/models/' + args.model_name + '/a.ckpt'\n kernel1 = int(args.small_k / 2)\n kernel2 = int(args.middle_k / 2)\n kernel_cen = int(args.large_k / 2)\n kernely = int(args.y_psize / 2)\n\n x_ph = tf.placeholder(tf.float32, [None,None,None])\n y_ph = tf.placeholder(tf.float32, [None,None,None])\n b_ph = tf.placeholder(tf.bool, [None])\n\n x_resh = tf.expand_dims(x_ph, axis=3)\n x_patch = tf.extract_image_patches(x_resh,\n ksizes=[1,args.large_k,args.large_k,1],\n strides=[1,args.stride,args.stride,1],\n rates=[1,1,1,1],\n padding='VALID')\n x_3 = tf.reshape(x_patch, [-1,args.large_k,args.large_k])\n a, b = (kernel_cen - kernel1, kernel_cen + kernel1+1)\n x_1 = x_3[:,a:b,a:b]\n a, b = (kernel_cen - kernel2, kernel_cen + kernel2+1)\n x_2 = x_3[:,a:b,a:b]\n\n y_resh = tf.expand_dims(y_ph, axis=3)\n y_patch = tf.extract_image_patches(y_resh,\n ksizes=[1,args.large_k,args.large_k,1],\n strides=[1,args.stride,args.stride,1],\n rates=[1,1,1,1],\n padding='VALID')\n y_p = tf.reshape(y_patch, [-1,args.large_k,args.large_k])\n a, b = (kernel_cen - kernely, kernel_cen + kernely+1)\n y_p = y_p[:,a:b,a:b]\n\n y_trues = tf.reduce_mean(y_p, axis=[1,2]) * 100\n\n pan = PatchActivationNet(args.model_name)\n out = pan.get_activation(x_1, x_2, x_3)\n\n mask = tf.greater(y_trues, 100)\n mask = tf.logical_or(mask, b_ph)\n mask = tf.cast(mask, tf.float32)\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n saver.restore(sess, save_dir)\n\n # redefine for convinience\n kc = kernel_cen\n ims = image_size = 512\n x, y = get_train_pair(1)\n out_activation_x = np.zeros([ims, ims])\n out_activation_y = np.zeros([ims, ims])\n for i in range(kc, ims-kc, 2):\n batch_x = np.zeros([ims-2*kc, 2*kc+1, 2*kc+1])\n batch_y = np.zeros([ims-2*kc, 2*kc+1, 2*kc+1])\n for j in range(kc, ims-kc):\n batch_x[j-kc] = x[:,i-kc:i+kc+1,j-kc:j+kc+1]\n batch_y[j-kc] = y[:,i-kc:i+kc+1,j-kc:j+kc+1]\n fd = {x_ph: batch_x, y_ph: batch_y}\n ox, oy = sess.run([out, y_trues], fd)\n out_activation_x[i, kc:ims-kc] = ox\n out_activation_y[i, kc:ims-kc] = oy\n out_activation_x[i+1, kc:ims-kc] = ox\n out_activation_y[i+1, kc:ims-kc] = oy\n if i % 10 == 0:\n print (i)\n np.save('garbages/test_x.npy', out_activation_x)\n np.save('garbages/test_y.npy', out_activation_y)\n","sub_path":"test/patch_based.py","file_name":"patch_based.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"144907016","text":"class artist():\n def __init__(self, id_artista='', nombre='', tags='', area='', score='', tipo='group'):\n self._id = id_artista\n self._name = nombre\n self._tags = 'rock or metal'\n self._area = area\n self._extScore = score\n self._type = tipo\n\n def __str__(self):\n return 'id: {}\\nNombre: {}\\nTags: {}\\nArea: {}\\nGenero: {}\\nTipo: {}'.format(self._id, self._name, self._tags, self._area, self._extScore, self._type)","sub_path":"Ago-Dic-2019/Luis Llanes/segundo_parcial/artista.py","file_name":"artista.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167947260","text":"import numpy as np\nfrom weld.weldobject import *\n\n\n# only valid for floats\ndef dot_mv(matrix, vector):\n \"\"\"\n Computes the dot product between a matrix and a vector.\n\n Args:\n matrix (WeldObject / Numpy.ndarray): 2-d input matrix\n vector (WeldObject / Numpy.ndarray): 1-d input vector\n ty (WeldType): Type of each element in the input matrix and vector\n\n Returns:\n A WeldObject representing this computation\n \"\"\"\n matrix_ty = WeldFloat()\n vector_ty = WeldFloat()\n\n weld_obj = WeldObject(NumPyEncoder(), NumPyDecoder())\n\n matrix_var = weld_obj.update(matrix)\n if isinstance(matrix, WeldObject):\n matrix_var = matrix.obj_id\n weld_obj.dependencies[matrix_var] = matrix\n\n vector_var = weld_obj.update(vector)\n loopsize_annotation = \"\"\n if isinstance(vector, WeldObject):\n vector_var = vector.obj_id\n weld_obj.dependencies[vector_var] = vector\n if isinstance(vector, np.ndarray):\n loopsize_annotation = \"@(loopsize: %dL)\" % len(vector)\n\n weld_template = \"\"\"\n map(\n %(matrix)s,\n |row: vec[%(matrix_ty)s]|\n result(\n %(loopsize_annotation)s\n for(\n result(\n %(loopsize_annotation)s\n for(\n zip(row, %(vector)s),\n appender,\n |b2, i2, e2: {%(matrix_ty)s, %(vector_ty)s}|\n merge(b2, f64(e2.$0 * %(matrix_ty)s(e2.$1)))\n )\n ),\n merger[f64,+],\n |b, i, e| merge(b, e)\n )\n )\n )\n \"\"\"\n weld_obj.weld_code = weld_template % {\"matrix\": matrix_var,\n \"vector\": vector_var,\n \"matrix_ty\": matrix_ty,\n \"vector_ty\": vector_ty,\n \"loopsize_annotation\": loopsize_annotation}\n return weld_obj\n\n\ndef dot_vv(v1, v2):\n ty = WeldFloat()\n weld_obj = WeldObject(NumPyEncoder(), NumPyDecoder())\n\n assert(len(v1) == len(v2))\n\n v1_var = weld_obj.update(v1)\n if isinstance(v1, WeldObject): # @@@@ how to transfer weld objects from one to another\n v1_var = v1.obj_id\n weld_obj.dependencies[v1_var] = v1\n\n v2_var = weld_obj.update(v2)\n if isinstance(vector, WeldObject):\n v2_var = v2.obj_id\n weld_obj.dependencies[v2_var] = v2\n\n if isinstance(vector, np.ndarray):\n loopsize_annotation = \"@(loopsize: %dL)\" % len(vector)\n\n weld_template = \"\"\"\n result(\n %(loopsize_annotation)s\n for(\n zip(%(v1)s, %(v2)s),\n merger[%(v_ty)s, +],\n |b, i, e| merge(b, e.$0 * e.$1)\n )\n )\n \"\"\"\n\n\n weld_obj.weld_code = weld_template % {\"v1\": v1_var,\n \"v2\": v2_var,\n \"v_ty\": ty,\n \"loopsize_annotation\": loopsize_annotation}\n return weld_obj\n\n\n\n\n\n","sub_path":"python/sklearn/weldsklearn/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335554996","text":"# not the cleanest code but it does the job as asked to \n\nlistOfItems= {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12,'books of power':100,'snakes drinks':100,'sorcery hat':1}\n\ndef inventoryList(lst):\n totalCount = 0 \n print('Before inventory : ')\n for k,v in lst.items():\n print(str(v),' ',k)\n totalCount+=v\n print( 'number of items : ',totalCount )\n\ninventoryList(listOfItems)\n\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ndef addToInventory(inventory, addedItems):\n counts = dict()\n for i in addedItems:\n counts[i]=counts.get(i,0) +1 # counts the items in the new list and return them as dictionary\n# counts = {'gold coin': 3, 'dagger': 1, 'ruby': 1} \n for keys in inventory :\n if keys in counts :\n inventory[keys] = counts[keys] + inventory[keys]\n else :\n pass\n# check if there are new items that are not in the old list \n for k,v in counts.items() :\n if counts[k] not in inventory :\n inventory.setdefault(k,v)\n print('New items : ')\n totalCount = 0 \n for k,v in inventory.items():\n print(str(v),' ',k)\n totalCount+=v\n print('number of items : ',totalCount) \n\naddToInventory(listOfItems,dragonLoot)\n","sub_path":"fancyGame.py","file_name":"fancyGame.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"381410525","text":"import sys\nfrom difflib import SequenceMatcher\nimport numpy\n\n\ndef main():\n parsed_sentences = sys.argv[1]\n gold_standard = sys.argv[2]\n output_file = sys.argv[3]\n\n gold_dict = {}\n parsed_dict = {}\n\n # split on colon\n # first one, compare, if same: compare\n # if\n\n #a = \"The quick brown fox jumped over the lazy brown dog\"\n #b = \"The quick brown fox jumped over the lazy brown cat\"\n\n\n with open(gold_standard, 'r') as gold:\n for line in gold:\n filename, text = line.split(\":\")\n filename = filename.split(\".\")[0]\n gold_dict[filename.strip()] = cleanText(text.strip())\n\n with open(parsed_sentences, 'r') as parsed:\n total_count = 0\n incorrect_count_sentences = 0\n perfect_count = 0\n unparseable = 0\n wer_total = 0\n with open(output_file, 'w') as f:\n for linep in parsed:\n filenamep, text_init = linep.split(\":\")\n textp = cleanText(text_init.strip())\n filenamep = filenamep.split(\".\")[0]\n if filenamep in gold_dict:\n total_count += 1\n if textp == \"google speech didn't recognize this file\":\n unparseable += 1\n f.write(\"gold: {}: {}\\n\".format(filenamep, textp))\n f.write(\"parsed: {}: {}\\n\\n\".format(filenamep, gold_text))\n continue\n gold_text = gold_dict[filenamep]\n ratio = SequenceMatcher(None, textp, gold_text).ratio()\n wer = int(werCalc(linep.strip().split(), gold_text.strip().split()))\n wer_total += wer\n print(ratio)\n parsed_dict[filenamep] = [textp, ratio]\n if ratio < 1:\n f.write(\"\\n{}\\n\".format(ratio))\n f.write(\"parsed: {}: {}\\n\".format(filenamep, textp))\n f.write(\"gold: {}: {}\\n\\n\".format(filenamep, gold_text))\n correct_count, incorrect_count, incorrect_gold, incorrect_token = compareTokens(gold_text, textp)\n f.write(\"wer: {}\\n\".format(str(wer)))\n f.write(\"correct: {}, incorrect: {}\\n\\n\".format(correct_count, incorrect_count))\n f.write(\"incorrect tokens, gold vs parsed: \\n{} \\n{}\\n\\n\".format(incorrect_gold, incorrect_token))\n incorrect_count_sentences += 1\n\n else:\n perfect_count += 1\n\n f.write(\"ratio: {}\\n\".format(1-(perfect_count/(total_count))))\n f.write(\"average wer: {}\\n\".format(wer_total/(total_count)))\n f.write(\"total parsed: {}\\n\".format(total_count-unparseable))\n f.write(\"right: {}\\n\".format(perfect_count))\n f.write(\"unparsed: {}\\n\".format(unparseable))\n f.write(\"incorrect sentences: {}\\n\".format(incorrect_count_sentences))\n f.write(\"total utterances: {}\\n\".format(total_count))\n\n\n #parsed_dict[filenamep.strip()] = textp.strip()\n\n\n print(\"NO\")\n\ndef cleanText(text_str):\n tokens = text_str.strip().split()\n new_tokens = \"\"\n for token in tokens:\n token = token.lower()\n new_tokens = new_tokens + token + \" \"\n\n return new_tokens.strip()\n\ndef compareTokens(goldstr1, tokenstr2):\n goldtokens = goldstr1.strip().split()\n tokens2 = tokenstr2.strip().split()\n correct_count = 0\n incorrect_count = 0\n incorrect_gold = []\n incorrect_tok = []\n\n iter_index = 0\n while iter_index < len(goldtokens):\n gt = goldtokens[iter_index]\n try:\n t2 = tokens2[iter_index]\n except:\n return correct_count, incorrect_count, incorrect_gold, incorrect_tok\n if gt == t2:\n correct_count += 1\n else:\n incorrect_count += 1\n incorrect_gold.append(gt)\n incorrect_tok.append(t2)\n iter_index += 1\n\n return correct_count, incorrect_count, incorrect_gold, incorrect_tok\n\n\ndef werCalc(r, h):\n \"\"\"\n Calculation of WER with Levenshtein distance.\n\n Works only for iterables up to 254 elements (uint8).\n O(nm) time ans space complexity.\n\n Parameters\n ----------\n r : list\n h : list\n\n Returns\n -------\n int\n\n Examples\n --------\n >>> wer(\"who is there\".split(), \"is there\".split())\n 1\n >>> wer(\"who is there\".split(), \"\".split())\n 3\n >>> wer(\"\".split(), \"who is there\".split())\n 3\n \"\"\"\n\n # initialisation\n d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint8)\n d = d.reshape((len(r)+1, len(h)+1))\n for i in range(len(r)+1):\n for j in range(len(h)+1):\n if i == 0:\n d[0][j] = j\n elif j == 0:\n d[i][0] = i\n\n # computation\n for i in range(1, len(r)+1):\n for j in range(1, len(h)+1):\n if r[i-1] == h[j-1]:\n d[i][j] = d[i-1][j-1]\n else:\n substitution = d[i-1][j-1] + 1\n insertion = d[i][j-1] + 1\n deletion = d[i-1][j] + 1\n d[i][j] = min(substitution, insertion, deletion)\n\n return d[len(r)][len(h)]\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"209944618","text":"#!/usr/bin/env python \r\nimport math\r\nimport sys\r\nimport os\r\nimport re\r\n\r\ndef main():\r\n lineDict = {}\r\n ochiaiLst = []\r\n totalFail = 0\r\n for i in range(1, len(sys.argv)):\r\n mPass = re.match('pass[0-9]+.gcov', sys.argv[i])\r\n mFail = re.match('fail[0-9]+.gcov', sys.argv[i])\r\n if (mPass):\r\n #print(sys.argv[i])\r\n with open(sys.argv[i]) as file:\r\n line = file.readline().strip()\r\n #print(line)\r\n while (line):\r\n #print(\"HERE\")\r\n #r = re.findall('\\s([0-9]+\\:\\s[0-9]+)\\:', line)\r\n r = re.findall('([0-9]+:\\s+[0-9]+)', line)\r\n if len(r) > 0:\r\n #print(\"here\")\r\n r2 = r[0].split(\":\")\r\n #numRun = int(r2[0])\r\n lineNum = r2[1].strip()\r\n inDict = lineDict.get(lineNum, None)\r\n if inDict != None:\r\n lineDict[lineNum][0] += 1\r\n else:\r\n lineDict[lineNum] = [1, 0]\r\n line = file.readline().strip()\r\n #print(line)\r\n \r\n \r\n if (mFail):\r\n totalFail += 1\r\n #print(sys.argv[i])\r\n with open(sys.argv[i]) as file:\r\n line = file.readline().strip()\r\n #print(line)\r\n while (line):\r\n #r = re.findall('([0-9]+\\:\\s[0-9]+)\\:', line)\r\n r = re.findall('([0-9]+:\\s+[0-9]+)', line)\r\n if len(r) > 0:\r\n r2 = r[0].split(\":\")\r\n #numRun = int(r2[0])\r\n lineNum = r2[1].strip()\r\n inDict = lineDict.get(lineNum, None)\r\n if inDict != None:\r\n lineDict[lineNum][1] += 1\r\n else:\r\n lineDict[lineNum] = [0, 1]\r\n line = file.readline().strip()\r\n #print(lineDict)\r\n for k in lineDict.keys():\r\n ochiaiVal = lineDict[k][1]/math.sqrt(totalFail * (lineDict[k][0] + lineDict[k][1]))\r\n ochiaiLst.append((int(k),ochiaiVal))\r\n ochiaiLst.sort()\r\n ochiaiLst.sort(key = lambda x: x[1], reverse=True) \r\n if len(ochiaiLst) > 100:\r\n print(ochiaiLst[:100])\r\n else:\r\n print(ochiaiLst)\r\nif __name__== \"__main__\":\r\n\tmain()\r\n","sub_path":"faultloc.py","file_name":"faultloc.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282885359","text":"import os\nimport cv2\nimport uuid\n\ndef remove_edge_picture(imagepath):\n\n image = cv2.imread(imagepath, 0)\n height, width = image.shape\n corner_list = [image[0,0] < 127,\n image[height-1, 0] < 127,\n image[0, width-1]<127,\n image[ height-1, width-1] < 127\n ]\n if sum(corner_list) >= 3:\n os.remove(imagepath)\n\ndef resplit_with_parts(imagepath, parts):\n image = cv2.imread(imagepath, 0)\n height, width = image.shape\n\n # 将图片重新分裂成parts部分\n step = width//parts # 步长\n start = 0 # 起始位置\n for _ in range(parts):\n cv2.imwrite('C:/Users/caokefan/PycharmProjects/workhouse_statisticslearning/machinelearningwork1/cnn/sample/%s.jpg'%uuid.uuid1(), image[:, start:start+step])\n start += step\n\n os.remove(imagepath)\n\ndef resplit(imagepath):\n\n image = cv2.imread(imagepath, 0)\n height, width = image.shape\n\n if width >= 64:\n resplit_with_parts(imagepath, 4)\n elif width >= 48:\n resplit_with_parts(imagepath, 3)\n elif width >= 26:\n resplit_with_parts(imagepath, 2)\n\ndef main():\n dir = 'C:/Users/caokefan/PycharmProjects/workhouse_statisticslearning/machinelearningwork1/cnn/pre_sample'\n for file in os.listdir(dir):\n remove_edge_picture(imagepath=dir+'/'+file)\n for file in os.listdir(dir):\n resplit(imagepath=dir+'/'+file)\n\nmain()\n","sub_path":"machinelearningwork1/cnn/get_sample.py","file_name":"get_sample.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"171021166","text":"import cPickle\nimport numpy as np\n\ndef load(name):\n\tdict = {}\n\tdictLabel = {}\n\n\n\twith open(name,\"r\") as input:\n\t dict = cPickle.load(input)\n\n\n\n\tx= dict['data']\n\torLabel= dict['labels']\n\n\treturn np.array(x),np.array(orLabel)\n\n","sub_path":"Linear/loadCIFAR.py","file_name":"loadCIFAR.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"474220140","text":"import numpy as np\nimport pprint\n\ndef metoda_choleskiego(A, b, m, n):\n if not np.allclose(A, A.T, rtol=0.001, atol=0.001):\n print('Macierz niesymetrzyczna')\n return None\n L = np.zeros((m, n))\n for i in range(m):\n for j in range(i, n):\n if i == j:\n L[i, i] = np.math.sqrt(A[i, i] - np.dot(L[i, :i], L[i, :i]))\n else:\n L[j, i] = (A[j, i] - np.dot(L[j, :i], L[i, :i])) / L[i, i]\n # print(np.around(L, 2))\n # print(np.around(L.T, 2))\n print(L)\n X = np.zeros((m, 1))\n Y = np.zeros((m, 1))\n Y = np.dot(np.linalg.inv(L), b)\n X = np.dot(np.linalg.inv(L.T), Y)\n print(Y)\n print('Rozwiązanie metodą Choleskiego')\n print(X)\n\n\nif __name__ == \"__main__\":\n A = np.array([[4. , 4. , 3. , 4. , 3. ],\n [4. , 8. , 5.5, 6.5, 5. ],\n [3. , 5.5, 8. , 3. , 1.5],\n [4. , 6.5, 3. , 9. , 6. ],\n [3. , 5. , 1.5, 6. , 8. ]])\n m = np.size(A, 0)\n n = np.size(A, 1)\n A_odwrotne = np.linalg.inv(A)\n b = np.dot(A, np.ones((m, 1)))\n metoda_choleskiego(A, b, m, n)\n print('Równanie X = A.inv * b')\n print(np.dot(A_odwrotne, b))","sub_path":"lista_1/np_cholesky.py","file_name":"np_cholesky.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151991117","text":"import asyncio\n\nfrom kutana import Environment, VKEnvironment, TGEnvironment\n\nfrom testing_tools import KutanaTest\n\n\nclass TestEnvironments(KutanaTest):\n def test_replace_method(self):\n messages = []\n\n async def save(self, message):\n messages.append(message)\n\n env = Environment(None)\n env.replace_method(\"reply\", save)\n\n asyncio.get_event_loop().run_until_complete(\n env.reply(\"message\")\n )\n\n self.assertEqual(messages, [\"message\"])\n\n def test_spawn(self):\n env = Environment(\"manager\")\n inner_env = env.spawn()\n\n self.assertEqual(env.manager, inner_env.manager)\n self.assertEqual(env.parent, None)\n self.assertEqual(inner_env.parent, env)\n\n def test_replace_method_child_environments(self):\n env = Environment(None)\n\n def method_1(self, message):\n return 1\n\n def method_2(self, file, filename):\n return 2\n\n def method_3(self, message):\n return 3\n\n env.replace_method(\"reply\", method_1)\n env.replace_method(\"upload_doc\", method_2)\n\n self.assertEqual(env.reply(\"_\"), 1)\n self.assertEqual(env.upload_doc(b\"_\", \"_\"), 2)\n\n child_env = env.spawn()\n\n child_env.replace_method(\"reply\", method_3)\n\n self.assertEqual(child_env.reply(\"_\"), 3)\n self.assertEqual(child_env.upload_doc(b\"_\", \"_\"), 2)\n\n child_child_env = child_env.spawn()\n\n self.assertEqual(child_child_env.reply(\"_\"), 3)\n self.assertEqual(child_child_env.upload_doc(b\"_\", \"_\"), 2)\n\n other_child_env = env.spawn()\n\n self.assertEqual(other_child_env.reply(\"_\"), 1)\n self.assertEqual(other_child_env.upload_doc(b\"_\", \"_\"), 2)\n\n def test_failed_register_after_processed(self):\n env = Environment(\"manager\")\n\n with self.assertRaises(ValueError):\n env.register_after_processed()\n\n def test_failed_method_replace(self):\n env = Environment(\"manager\")\n\n with self.assertRaises(ValueError):\n env.replace_method(\"no_method_with_that_name\", lambda: 1)\n\n def test_failed_setattr(self):\n env = Environment(\"manager\")\n\n with self.assertRaises(AttributeError):\n env.reply = 1\n\n with self.assertRaises(AttributeError):\n setattr(env, \"reply\", 1)\n\n def test_get(self):\n env = Environment(\"manager\")\n\n self.assertEqual(env.get(\"attr\"), None)\n self.assertEqual(env.get(\"attr\", \"default\"), \"default\")\n\n env.attr = \"value\"\n\n self.assertEqual(env.get(\"attr\"), \"value\")\n\n def test_concrete_environments(self):\n env1 = VKEnvironment(\"vk\")\n env2 = TGEnvironment(\"tg\")\n\n env1.replace_method(\"reply\", print)\n env1.a = 10\n\n child1 = env1.spawn()\n\n self.assertEqual(child1.a, 10)\n self.assertEqual(child1.reply.func, print)\n\n env2.replace_method(\"reply\", print)\n env2.a = 10\n\n child2 = env2.spawn()\n\n self.assertEqual(child2.a, 10)\n self.assertEqual(child2.reply.func, print)\n","sub_path":"test/test_environments.py","file_name":"test_environments.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"310578984","text":"from flask import Flask, request, make_response, render_template, url_for\nfrom flask_script import Manager\nfrom api import apiSql as sql\nimport json\nimport markdown\nfrom flask_bootstrap import Bootstrap\n\napp = Flask(__name__)\nmanager = Manager(app)\nmysql = sql.MYSQL({\n 'host': 'localhost',\n 'sql_name': 'blog',\n 'user': 'root',\n 'password': 'gtian0122'\n}, charset='utf8')\nnavDefaultList = []\n\n\n# 初始化页面(首页)\n@app.route('/')\ndef index():\n list = json.loads(article_column_relation())\n print(list)\n return render_template('index.html', name='饺子博', nav=json.loads(nav()), list=get_html())\n\n\n# 自我简介\n@app.route('/about')\ndef about():\n return '

饺子的介绍

'\n\n\n# 获取导航数据\n@app.route('/nav', methods=['GET'])\ndef nav():\n '''\n 数据查询对应导航列表,并返回查询结果\n :return [{'title': '首页 | Home', 'url': '/'}]\n '''\n res = get_nav()\n return json.dumps(res)\n\n\n@app.route('/', methods=['GET'])\ndef get_column_content(column_name):\n return column_name\n\n\n# 查询文章��应关系并归类\n@app.route('/list', methods=['GET'])\ndef article_column_relation():\n '''查询文章对应关系并归类'''\n # 查询对应CID和MID关系\n relation = mysql.query('SELECT * FROM blog.gt_relationships')\n relation_format = []\n # 查询栏目类别\n column_type = mysql.query(\"SELECT * FROM blog.gt_metas where type='category'\")\n column_type_format = []\n # 查询文章对应列表\n article = mysql.query('SELECT * FROM blog.gt_contents where slug!=\"start-page\"')\n article_format = []\n for rf in relation[:]:\n relation_format.append({\n 'cid': rf[0],\n 'mid': rf[1]\n })\n for ctf in column_type[:]:\n column_type_format.append({\n 'mid': ctf[0],\n 'name': ctf[1],\n 'slug': ctf[2],\n 'type': ctf[3],\n 'description': ctf[4],\n 'count': ctf[5],\n 'order': ctf[6],\n 'parent': ctf[7]\n })\n for af in article[:]:\n article_format.append({\n 'cid': af[0],\n 'title': af[1],\n 'slug': af[2],\n 'created': af[3],\n 'modified': af[4],\n 'text': af[5],\n 'order': af[6],\n 'authorId': af[7],\n 'template': af[8],\n 'type': af[9],\n 'status': af[10],\n 'password': af[11],\n 'commentsNum': af[12],\n 'allowComment': af[13],\n 'allowPing': af[14],\n 'allowFeed': af[15],\n 'parent': af[16]\n })\n return_res = {}\n key = 'data'\n return_res[key] = return_results(relation_format[:], column_type_format[:], article_format[:])\n return json.dumps(return_res)\n\n\n# 获取导航\ndef get_nav():\n query_result = query_nav('gt_metas', 'category', 'type')\n result = []\n for res in query_result:\n result.append({\n 'mid': res[0],\n 'name': res[1],\n 'slug': res[2],\n 'type': res[3],\n 'description': res[4],\n 'count': res[5],\n 'order': res[6],\n 'parent': res[7]\n })\n return result\n\n\n# 获取导航栏目信息\ndef query_nav(tab_name, column_val, column_name):\n '''\n 导航数据查询\n :param tab_name: 表名 str\n :param column_val: 查询类别 str\n :param column_name: 查询字段 str\n :return: 返回查询结果 tuple\n '''\n sql = \"SELECT * FROM blog.\" + tab_name + \" where \" + column_name + \"='\" + column_val + \"'\"\n return mysql.query(sql)\n\n\n# 格式化数据\ndef return_results(relation, column_type, article):\n '''\n 返回栏目对应的文章列表\n :param relation: 对应关系\n :param column_type: 获取栏目mid\n :param article: 获取文章cid\n :return: 返回栏目对应的文章列表\n '''\n res = {}\n for info in article:\n # 获取栏目对于关系表\n for re in relation:\n # 获取栏目名称\n for cy in column_type:\n if re['mid'] == cy['mid']:\n if re['cid'] == info['cid']:\n key = cy['slug']\n if key in res:\n res[key].append(info)\n else:\n res[key] = []\n res[key].append(info)\n return res\n\n\n# markdown转换html\ndef markdown_conversion_html(markdown_doc):\n extension_list = ['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.tables',\n 'markdown.extensions.toc', 'markdown.extensions.codehilite']\n return markdown.markdown(markdown_doc, extensions=extension_list)\n\n\ndef get_html():\n page_list = json.loads(article_column_relation())['data']\n print(type(page_list), page_list)\n for key, val in page_list.items():\n for mk in val:\n mk['text'] = markdown_conversion_html(mk['text'])\n print(page_list)\n return page_list\n\n\n\n# 以下为测试单元\n# 测试方法:ajax接口测试\n# 返回传入数据\n@app.route('/ajax_return', methods=['GET', 'POST'])\ndef ajax_return(name):\n '''借口请求测试函数,返回传入参数'''\n res = []\n print('request.method', request.method)\n if request.method == 'POST':\n print('request.form', request.form)\n if 'name' in request.form:\n res = loop(request.form.items(), request.method)\n else:\n if len(request.args) < 1:\n return '参数列表为空。'\n if 'name' in request.args:\n print('request.args', request.args)\n res = loop(request.args.items(), request.method)\n else:\n res = None\n return json.dumps(res) if res != None else None\n\n\ndef loop(data, methods):\n '''获取对应数据'''\n res = {}\n for k, v in data:\n res['methods'] = methods\n res[k] = v\n return res\n\n\nif __name__ == '__main__':\n # host = '0.0.0.0'\n # manager.run()\n # bt = Bootstrap(app)\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"blog/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"616513728","text":"# read data file\nf = open('d08-input.txt', 'r')\ndata = f.readlines()\n# test data\n# data = [\"nop +0\", \"acc +1\", \"jmp +4\", \"acc +3\", \"jmp -3\", \"acc -99\", \"acc +1\", \"jmp -4\", \"acc +6\"]\n\n\n# TRY:\n# identify all the lines with jmp or nop\n# loop through the list changing each in turn to the other\n# if code executes - flag success\n# if code repeats revert data set and swop next matching command and try again\n\n# identify all the lines with jmp or nop\ntestLines = []\nfor idx, i in enumerate(data):\n if i[0:3] == \"jmp\" or i[0:3] == \"nop\":\n testLines.append(idx)\n# loop through the list changing each in turn to the other\n\nfor idx in testLines:\n if data[idx][0:3] == \"jmp\":\n data[idx] = data[idx].replace(\"jmp\",\"nop\")\n else:\n data[idx] = data[idx].replace(\"nop\", \"jmp\")\n \n # initialise variables\n codeLine = 0\n accumulator = 0\n executedCodeLines = []\n lastJmpLine = []\n repeatedLines = False\n \n # while-loop until a line is repeated\n while not(repeatedLines):\n # split input data into components\n command = data[codeLine][0:3]\n value = data[codeLine][3:]\n # if the line of code has been executed then change the repeatedLines variable\n if codeLine in executedCodeLines:\n repeatedLines = True\n # reset the change code line then end the loop\n if data[idx][0:3] == \"jmp\":\n data[idx] = data[idx].replace(\"jmp\",\"nop\")\n else:\n data[idx] = data[idx].replace(\"nop\", \"jmp\")\n break\n else: executedCodeLines.append(codeLine)\n # executed the commands\n if command == \"acc\":\n accumulator += int(value)\n codeLine += 1\n if command == \"nop\":\n codeLine += 1\n if command == \"jmp\":\n codeLine += int(value)\n if codeLine > len(data)-1:\n break\n if (repeatedLines == False) and (codeLine == len(data)):\n break\n\nprint(accumulator)","sub_path":"d08p2-solution.py","file_name":"d08p2-solution.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"511241651","text":"#program to check the prime numbers\r\n#we are taking input of a number and converting it in to float then in to an integer\r\n#conditions to check prime number\r\n#As we know prime number is always greater than 1\r\n\r\n#taking input\r\nnum = int(float(input(\"Enter any number: \")))\r\n\r\n\r\nif num > 1:\r\n for i in range(2, num):\r\n if (num % i) == 0:\r\n print(num, \"is not a prime number\")\r\n break;\r\n else:\r\n print(num, \"is a prime number\")\r\n\r\n# if the input is not greater than 1\r\nelse:\r\n print(num, \"is not a prime number\")","sub_path":"Python Basics/check_prime-numbers.py","file_name":"check_prime-numbers.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581461137","text":"# Class which represents AcademicBuilding\nfrom Classroom import Classroom\n\n\nclass AcademicBuilding(object):\n def __init__(self, address, classrooms):\n self.address = address\n self.classrooms = classrooms\n\n def total_equipment(self):\n temp_result = {}\n for classroom in self.classrooms:\n for item in classroom.equipment:\n if item in temp_result:\n temp_result[item] += 1\n else:\n temp_result[item] = 1\n\n result = []\n for item in list(temp_result):\n result.append((item, temp_result[item]))\n\n return result\n","sub_path":"Building1.py","file_name":"Building1.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"324896753","text":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport csv\nimport random\nfrom tqdm import tqdm\nimport ujson as json\nimport jsonlines\nimport pickle\nimport collections\nimport os.path\nimport os\nfrom joblib import Parallel, delayed\nimport bisect\nimport re\nimport string\nfrom transformers import BertTokenizer, T5Tokenizer\nimport shutil\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN_ARTICLES = 10\nBERT_MAX_SEQ_LEN = 512\nMAX_SENT_LEN = 256 - 65 - 3\nbert_tokenizer = BertTokenizer.from_pretrained('bert-base-cased', return_token_type_ids=True)\nt5_tokenizer = T5Tokenizer.from_pretrained('t5-base')\ntokenizer = 'placeholder'\n\n\ndef print_chunks(chunks):\n \"\"\"\n prints chunks' context text\n :param chunks: a list of chunks\n \"\"\"\n for i, chunk in enumerate(chunks):\n text = tokenizer.decode(chunk['input_ids'])\n # 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': segment_ids,\n print(f'chunk num: {i}, chunk text: \\n{text}\\n')\n\n\ndef find_nearest(a, target, test_func=lambda x: True):\n \"\"\"\n find a token start/end which is closest to the answer span start/end\n :param a: (List[int]) sorted list of starts/ends of the tokens in the context\n :param target: (int) start/end of the answer span\n :param test_func: filter function to ensure result is in the correct range\n :return: idx of the token s/e closest to target, dissimilarity score\n \"\"\"\n # bisect.bisect_left(list, x) returns a position to insert x in the sorted list\n idx = bisect.bisect_left(a, target)\n # s/e of the answer span is the same as s/e of one of the tokens\n if (0 <= idx < len(a)) and a[idx] == target:\n return idx, 0\n elif idx == 0:\n return 0, abs(a[0] - target)\n elif idx == len(a):\n return idx - 1, abs(a[-1] - target)\n else:\n d1 = abs(a[idx] - target) if test_func(a[idx]) else 1e200\n d2 = abs(a[idx-1] - target) if test_func(a[idx-1]) else 1e200\n if d1 > d2:\n return idx-1, d2\n else:\n return idx, d1\n\n\ndef fix_span(text_context, offsets, span):\n \"\"\"\n find start-end indices of the span in the text_context nearest to the existing token start-end indices\n :param text_context: (str) text to search for span in\n :param offsets: (List(Tuple[int, int]) list of begins and ends for each token in the text\n :param span: (str) the answer span to find in the text_context\n :return: span indices, distance to the nearest token indices\n \"\"\"\n span = span.strip()\n assert span in text_context, f'answer span:{span} is not in the context: {text_context}'\n begins, ends = map(list, zip(*[x for x in offsets]))\n\n best_dist = 1e200\n best_indices = None\n\n if span == text_context:\n return text_context, (0, len(text_context)), 0\n\n # re.escape(pattern) escapes (adds '\\' to special characters in pattern)\n # re.finditer(pattern, string) returns match objects for all matches of pattern in the string\n for m in re.finditer(re.escape(span), text_context):\n begin_offset, end_offset = m.span()\n fixed_begin, d1 = find_nearest(begins, begin_offset, lambda x: x < end_offset)\n fixed_end, d2 = find_nearest(ends, end_offset, lambda x: x > begin_offset)\n if d1 + d2 < best_dist:\n best_dist = d1 + d2\n best_indices = (fixed_begin, fixed_end)\n if best_dist == 0:\n break\n\n assert best_indices is not None\n return best_indices, best_dist\n\n\ndef convert_idx(text, tokens):\n \"\"\"\n finds spans for each token in the text\n :param text: (str) context to look for token in\n :param tokens: (List[str]) tokenized text\n :param filter: a function to filter tokenization artefacts (e.g. '[UNK]' or '#' in the middle of a word)\n :return: (List[Tuple(int, int)]) spans for each token\n \"\"\"\n current = 0\n spans = []\n is_bert = tokenizer == bert_tokenizer\n for token in tokens:\n clear_token = filter_func(tokenizer.convert_tokens_to_string([token]))\n current = text.find(clear_token, current)\n if is_bert:\n assert current >= 0, f'token: {token}, cleared token: {clear_token}, text: {text}'\n spans.append((current, current + len(clear_token)))\n current += len(clear_token)\n return spans\n\n\ndef filter_func(token):\n \"\"\"\n :param token: (str) word or part of word after tokenization\n :return: (str) token as a word or part of word (whithout extra chars)\n \"\"\"\n if token == '[UNK]':\n token = ''\n symbols = ['\\u2581', '#'] #chars that need to be filtered out (e. g. '#' for BERT-like tokenization)\n for symbol in symbols:\n token = token.lstrip(symbol)\n return token\n\n\ndef remove_punctuation(sent):\n \"\"\"\n :param sent: (str) possibly with punctuation\n :return: (str) definitely without punctuation\n \"\"\"\n return re.sub('[%s]' % re.escape(string.punctuation), '', sent)\n\n\ndef preprocess(sent):\n \"\"\"\n substitute multiple spaces with one and remove non latin-1 symbols\n :param sent: string to process\n :return: the string without multiple spaces and latin-1 as encoding\n \"\"\"\n whitespaces = re.compile(r\"\\s+\")\n sent = whitespaces.sub(\" \", sent)\n sent = sent.replace(\"\\xad\", \"\")\n return sent.encode('latin-1', 'ignore').decode('latin-1')\n\n\ndef _process_article(article):\n \"\"\"\n processes the article and turns it into a train dict with features and eval dict with context and answer\n :param article: dict corresponding to a single qa pair\n article.keys(): 'supporting_facts' (List[List[int]]), 'level' (str 'easy', 'medium', 'hard'),\n 'question' (str), 'context' (List[List[Tuple(title (str), sentences (List[str])],\n 'answer' (str), '_id' (str), 'type' (str e.g. 'comparison', 'bridge')\n :return: dicts with features for train and eval e.g\n 'start_end_facts' (List[Tuple[int]]) (s_token_id, e_token_id, is_sup_fact),\n 'question tokens' [List[int]] token indices for the question\n ...\n \"\"\"\n paragraphs = article['context']\n\n context_text, context_tokens = '', []\n flat_offsets = []\n start_end_facts = [] # (start_token_id, end_token_id, is_sup_fact=True/False)\n sup_paragraphs = [0] * len(paragraphs) # 1 if paragraph contains supportive fact, else 0\n para_context_text = []\n para_context_tokens = []\n para_start_end_facts = []\n N_tokens, N_chars = 0, 0\n\n def _process(sent, is_sup_fact=False):\n sent = preprocess(sent)\n nonlocal context_text, context_tokens, flat_offsets, start_end_facts, N_tokens, N_chars\n sent_tokens = tokenizer.tokenize(sent)\n sent_spans = convert_idx(sent, sent_tokens)\n sent_spans = [[N_chars+e[0], N_chars+e[1]] for e in sent_spans]\n flat_offsets.extend(sent_spans)\n context_text += sent\n context_tokens.extend(sent_tokens)\n N_chars += len(sent)\n sent_N_tokens = len(sent_tokens)\n start_end_facts.append((N_tokens, N_tokens + sent_N_tokens, is_sup_fact))\n N_tokens += sent_N_tokens\n\n if 'supporting_facts' in article:\n sp_set = set(list(map(tuple, article['supporting_facts'])))\n else:\n sp_set = set()\n\n sp_fact_cnt = 0\n\n for i, para in enumerate(paragraphs):\n cur_title, cur_para = para[0], para[1]\n _process(cur_title.strip() + \" \")\n for sent_id, sent in enumerate(cur_para):\n is_sup_fact = (cur_title, sent_id) in sp_set\n sup_paragraphs[i] |= is_sup_fact\n sp_fact_cnt += is_sup_fact\n _process(sent, is_sup_fact)\n para_context_text.append(context_text)\n para_context_tokens.append(context_tokens)\n para_start_end_facts.append(start_end_facts)\n context_text = \"\\n\"\n context_tokens = []\n start_end_facts = []\n N_chars += 1\n N_tokens = 0\n\n question = preprocess(article['question'])\n\n full_text = ''.join(para_context_text)\n\n is_yes_no = False\n yes_no = None # 0 if 'no', 1 otherwise\n \n if 'answer' in article.keys():\n best_indices = [0, 0]\n answer = preprocess(article['answer'].strip())\n if answer.lower() in ['yes', 'no']:\n is_yes_no = True\n answer = answer.lower()\n yes_no = int(answer == 'yes')\n else:\n if answer not in full_text:\n answer = ''\n else:\n best_indices, _ = fix_span(full_text, flat_offsets, answer)\n else:\n # some random stuff\n answer = ''\n best_indices = [0, 0]\n print('UNANSWERABLE: ', article['_id'])\n\n assert 2 <= sum(sup_paragraphs) <= 2, f'wrong number of sup paragraphs: {sum(sup_paragraphs)}'\n\n question_tokens = tokenizer.tokenize(question)\n\n example = {'question_tokens': question_tokens, 'context_tokens': para_context_tokens,\n 's': best_indices[0], 'e': best_indices[1], 'id': article['_id'],\n 'start_end_facts': para_start_end_facts, 'sup_paragraphs': sup_paragraphs,\n 'is_yes_no': is_yes_no, 'yes_no': yes_no}\n eval_example = {'context': full_text, 'spans': flat_offsets, 'answer': answer, 'id': article['_id']}\n return example, eval_example\n\n\ndef process_file(filename, config):\n \"\"\"\n processes all articles\n :param filename: (str) path to the .json file\n :param config: config class\n :return: List[Dict] train features, List[Dict] eval features (such as full context text and correct answer)\n \"\"\"\n data = json.load(open(filename, 'r'))\n\n\n with open('filter_ids.csv', newline='') as f:\n reader = csv.reader(f)\n _, ids_to_filter = zip(*list(reader))\n outputs = Parallel(n_jobs=8, verbose=10, require='sharedmem')(delayed(_process_article)(article) for article in data if article['_id'] not in ids_to_filter)\n examples, eval_examples = zip(*outputs)\n\n random.shuffle(list(examples))\n print(f\"{len(examples)} questions in total\")\n\n return examples, eval_examples\n\n\ndef _check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"\n Check if this is the 'max context' doc span for the token.\n :param doc_spans: List[NamedTuple(start: int, length: int)] sorted by start\n :param cur_span_index: index of current doc_span (in doc_spans)\n :param position: position of the token to check for max_span\n :return: bool whether token in position has max context\n \"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n break\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index\n\n\ndef dump_dp(config, datapoints, dir_name, out_file):\n \"\"\"\n dividing datapoints into multiple files for using lazy data loading with multiple workers\n files are supposed to be of approximately equal size, but we do not want to split examples between files\n :param config: config class\n :param datapoints: List[Dict] a batch of data points\n :param out_file: dumping file main part, data will be dumped to {out_file_name}_{file_num}.{out_file_ext}\n \"\"\"\n\n fileparts = out_file.split('.')\n name, ext = '.'.join(fileparts[:-1]), fileparts[-1]\n\n num_objects = len(datapoints)\n num_files = config.num_files if config.num_files > 0 else num_objects\n batch_size = num_objects // num_files\n\n st = 0\n examples_total = 0\n for i in range(num_files - 1):\n with jsonlines.open(f'{dir_name}/{name}_{i}.{ext}', mode='w') as writer:\n end = (i + 1) * batch_size\n examples, start = write_datapoints(datapoints[st: end], writer)\n last_ex_id = datapoints[end - 1]['example_id']\n\n while datapoints[end]['example_id'] == last_ex_id:\n writer.write(datapoints[end])\n end += 1\n examples.append((start, end - st))\n st = end\n\n examples_total += len(examples)\n with open(f'{dir_name}/{name}_{str(i)}_meta.pickle', mode='wb') as fp:\n pickle.dump(examples, fp)\n\n with jsonlines.open(f'{dir_name}/{name}_{num_files - 1}.{ext}', mode='w') as writer:\n examples, start = write_datapoints(datapoints[st:], writer)\n end = len(datapoints)\n examples.append((start, end - st))\n examples_total += len(examples)\n with open(f'{dir_name}/{name}_{num_files - 1}_meta.pickle', mode='wb') as fp:\n pickle.dump(examples, fp)\n return examples_total\n\n\ndef write_datapoints(datapoints, writer):\n \"\"\"\n write datapoints to a file, remember the beginning and ending lines for the yes/no questions\n :param datapoints: List[Dict] a batch of data points\n :param writer: file handler of a file to write to\n :return: examples List[Tuple[int, int]] the beginning and ending lines for the yes/no questions\n \"\"\"\n examples = [] # holds beginning and ending lines of each example in the respective file\n start = 0\n ex_id = None\n for dp_idx, datapoint in enumerate(datapoints):\n if ex_id is not None and datapoint['example_id'] != ex_id:\n end = dp_idx\n examples.append((start, end))\n start = end\n ex_id = datapoint['example_id']\n writer.write(datapoint)\n return examples, start\n\n\ndef build_bert_datapoint(config,\n question_tokens, context_tokens,\n doc_spans, doc_span_index):\n\n doc_span = doc_spans[doc_span_index]\n tokens = []\n segment_ids = []\n max_context = []\n\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n max_context.append(0)\n\n tokens.extend(question_tokens)\n segment_ids.extend([0] * len(question_tokens))\n max_context.extend([0] * len(question_tokens))\n\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n max_context.append(0)\n\n for i in range(doc_span.length):\n split_token_index = doc_span.start + i\n max_context.append(int(_check_is_max_context(doc_spans, doc_span_index,\n split_token_index)))\n tokens.append(context_tokens[doc_span.para][split_token_index])\n #except:\n # print('EXCEPTION:')\n # print('span index:', i, 'start index:', doc_span.start, 'prev article len:', len(context_tokens[doc_span.para - 1]))\n # print('split token index:', split_token_index, f'len context_tokens[{doc_span.para}]', len(context_tokens[doc_span.para]))\n # return\n segment_ids.append(1)\n\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n max_context.append(0)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n\n input_len = len(input_ids)\n pad_len = config.max_seq_length - input_len\n pad = [0] * pad_len\n\n input_ids.extend(pad)\n input_mask.extend(pad)\n segment_ids.extend(pad)\n max_context.extend(pad)\n\n assert len(input_ids) == config.max_seq_length, len(input_ids)\n assert len(input_mask) == config.max_seq_length\n assert len(segment_ids) == config.max_seq_length\n assert len(max_context) == config.max_seq_length\n\n datapoint = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': segment_ids,\n 'max_context': max_context, 'seq_len': input_len}\n return datapoint\n\n\ndef build_t5_datapoint(config,\n question_tokens, context_tokens,\n doc_spans, doc_span_index):\n\n doc_span = doc_spans[doc_span_index]\n tokens = []\n\n tokens.append(tokenizer.tokenize('Query:')[0])\n tokens.extend(question_tokens)\n tokens.append(tokenizer.tokenize('Document:')[0])\n split_token_index = doc_span.start\n tokens.extend(context_tokens[doc_span.para][split_token_index: split_token_index + doc_span.length])\n tokens.append(tokenizer.tokenize('Relevant:')[0])\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n\n input_len = len(input_ids)\n pad_len = config.max_seq_length - input_len\n pad = [0] * pad_len\n\n input_ids.extend(pad)\n input_mask.extend(pad)\n\n assert len(input_ids) == config.max_seq_length\n assert len(input_mask) == config.max_seq_length\n\n datapoint = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': [0] * config.max_seq_length,\n 'max_context': [0] * config.max_seq_length, 'seq_len': input_len}\n return datapoint\n\n\ndef build_features(config, examples, split, out_file):\n \"\"\"\n make chunks of size config.max_seq_length to train a BERT-like model\n each chunk corresponds to a single context text or part of the text\n :param config: config class\n :param examples: (List[Dict]) example dict for each question context pair\n :param split: 'train', 'dev' or 'test'\n :param out_file: (.pickle) dumps all features to config.num_files pickle\n files {split}/{out_file (without extention)}_{i}.pickle\n \"\"\"\n print(f\"Processing {split} examples...\")\n datapoints = []\n chunk_lens = []\n datapoint_lens = []\n all_sup_labels = []\n yes_no_example_id_to_ans = {}\n\n unique_id = 0\n\n yes_no_count, span_count , total_count = 0, 0, 0\n\n yes_no_ex_count = 0\n span_ex_count = 0\n max_chunks = 0\n sup_chunks = 0\n ten_chunks = 0\n\n cropped_questions = 0\n cropped_sentences = 0\n\n start_token, sep_token, end_token = ('[CLS]', '[SEP]', '[SEP]') if config.tokenizer == 'bert'\\\n else ('Question:', 'Document:', 'Relevant:')\n is_relevant_labels = ['false', 'true']\n for i, example in enumerate(tqdm(examples)):\n question_tokens = example['question_tokens']\n context_tokens = example['context_tokens']\n start_end_facts = example['start_end_facts']\n sup_labels = []\n if len(question_tokens) > config.max_query_length:\n question_tokens = question_tokens[0: config.max_query_length]\n cropped_questions += 1\n question_shift = len(question_tokens) + len(tokenizer.tokenize(start_token)) + \\\n len(tokenizer.tokenize(sep_token))\n # answer span is based on context_text tokens only but after encoding\n # question and special tokens are added in front\n\n max_tokens_for_seq = config.max_seq_length - question_shift - len(tokenizer.tokenize(end_token))\n\n if config.is_training:\n start, end = example['s'], example['e']\n\n _DocSpan = collections.namedtuple(\n 'DocSpan', ['para', 'start', 'length'])\n doc_spans = []\n sup_paras = np.array(example[\"sup_paragraphs\"])\n \n assert sum(sup_paras) == 2, 'wrong number of supportive facts'\n\n if config.level == 'paragraph':\n for para_i, para_tokens in enumerate(context_tokens):\n start_offset = 0\n length = len(para_tokens)\n\n while length > max_tokens_for_seq:\n doc_spans.append(_DocSpan(para_i, start=start_offset, length=max_tokens_for_seq))\n start_offset += config.doc_stride\n length -= config.doc_stride\n datapoint_lens.append(max_tokens_for_seq)\n\n doc_spans.append(_DocSpan(para_i, start=start_offset, length=length))\n datapoint_lens.append(length)\n elif config.level == 'sentence':\n for para_i, sent_spans in enumerate(start_end_facts):\n for el in sent_spans:\n s, e, is_sup_fact = el\n length = min(e - s, max_tokens_for_seq)\n if split == 'train' and e - s > MAX_SENT_LEN:\n continue\n if e - s > max_tokens_for_seq:\n cropped_sentences += 1\n sup_labels.append(is_sup_fact)\n doc_spans.append(_DocSpan(para_i, start=s, length=length))\n datapoint_lens.append(e - s)\n else:\n print(f'sorry, there is no such level {config.level}')\n num_chunks = len(doc_spans)\n\n ten_chunks += int(num_chunks == 10)\n chunk_lens.append(num_chunks)\n\n is_yes_no_example = example['is_yes_no']\n is_yes_example = example['yes_no']\n\n if is_yes_no_example:\n yes_no_example_id_to_ans[example['id']] = example['yes_no']\n yes_no_ex_count += is_yes_no_example\n span_ex_count += 1 - is_yes_no_example\n max_chunks = max(max_chunks, num_chunks)\n\n for doc_span_index, doc_span in enumerate(doc_spans):\n\n doc_start = doc_span.start\n doc_end = doc_span.start + doc_span.length - 1\n\n is_sup_binary = int(sup_paras[doc_span.para]) if config.level == 'paragraph' else sup_labels[doc_span_index]\n all_sup_labels.append(is_sup_binary)\n is_sup = is_sup_binary if config.tokenizer == 'bert' else tokenizer.encode(is_relevant_labels[is_sup_binary])[0]\n sup_chunks += is_sup_binary\n\n span_s, span_e = 0, 0\n is_yes_no = is_yes_no_example\n # yes -- 1, no -- 0\n is_yes = -1\n if is_yes_no:\n is_yes = is_yes_example\n\n if config.is_training and start >= doc_start and end <= doc_end:\n span_s = start - doc_start + question_shift\n span_e = end - doc_start + question_shift\n assert 0 <= span_s < config.max_seq_length, f'starts are wrong, {span_s}'\n assert 0 <= span_e < config.max_seq_length, f'ends are wrong, {span_e}'\n\n labels = [is_yes_no, is_yes, span_s, span_e, is_sup]\n\n yes_no_count += is_yes_no\n span_count += (1 - is_yes_no)\n total_count += 1\n unique_id += 1\n\n dp = build_bert_datapoint(config, question_tokens, context_tokens, doc_spans, doc_span_index)\\\n if config.tokenizer == 'bert' else \\\n build_t5_datapoint(config, question_tokens, context_tokens, doc_spans, doc_span_index)\n dp.update({'feature_id': unique_id, 'example_id': example['id'], 'para': doc_span.para, 'labels': labels})\n datapoints.append(dp)\n\n chunk_lens = np.array(chunk_lens)\n all_sup_labels = np.array(all_sup_labels)\n datapoint_lens = np.array(datapoint_lens)\n plot_stats(config, chunk_lens, datapoint_lens, all_sup_labels, split)\n \n assert len(datapoint_lens) == len(all_sup_labels), f'len of datapoints lens: {len(datapoints_lens)} does not match len of sup labels: {len(all_sup_labels)}'\n print(f\"max chunks: {max_chunks}, sup chunks: {sup_chunks}, avg num of sup chunks: {sup_chunks / span_ex_count}\")\n print(f\"yes_no: {yes_no_count}, span: {span_count}, total: {total_count}\")\n print(f\"yes_no: {yes_no_count / total_count:.5f}, span: {span_count / total_count:.5f}\")\n print(f\"yes_no_examples: {yes_no_ex_count}, span: {span_ex_count}\")\n print(f\"Examples in 10 chunks: {ten_chunks}, total examples: {len(examples)}\")\n print(f\"Examples with questions longer than {config.max_query_length} tokens: {cropped_questions}, cropped sentences: {cropped_sentences}\")\n print(f\"Chunk lens: {np.quantile(chunk_lens, q=0.5)}, {np.quantile(chunk_lens, q=0.75)}, {np.quantile(chunk_lens, q=0.9)}, \\\n {np.quantile(chunk_lens, q=0.95)}, {np.quantile(chunk_lens, q=0.99)}\")\n\n dir_name = f'{config.level}_{split}'\n\n try:\n os.mkdir(dir_name)\n print(f\"Directory {dir_name} created\")\n except OSError:\n print(f\"Removing directory {dir_name} and creating a new one\")\n shutil.rmtree(dir_name)\n os.mkdir(dir_name)\n\n with open(f'{dir_name}/{config.yes_no_example_file}', \"wb\") as fp:\n pickle.dump([yes_no_example_id_to_ans], fp)\n\n dumped = dump_dp(config, datapoints, dir_name, out_file)\n assert dumped == len(examples), f'number of examples dumped ({dumped}) is not equal to' \\\n f' total number of examples: {len(examples)}'\n\n\ndef plot_stats(config, chunk_lens, datapoint_lens, all_sup_labels, split):\n fig, axs = plt.subplots(ncols=2, nrows=2, sharey='all')\n axs = axs.flatten()\n \n for i in range(4):\n axs[i].set_yscale('log')\n shared_list = axs[1:]\n shared_list[0].get_shared_x_axes().join(*shared_list)\n name = 'Fact' if config.level == 'sentence' else 'Chunk'\n\n axs[0].hist(chunk_lens, bins=35)\n axs[0].set_title(f'{name} number\\n distribution\\n')\n\n axs[1].hist(datapoint_lens, bins=35)\n axs[1].set_title(f'{name} token number \\n distribution\\n')\n\n axs[2].hist(datapoint_lens[all_sup_labels.astype(bool)], bins=35)\n axs[2].set_title(f'Supporting {name} token number \\n distribution\\n')\n\n axs[3].hist(datapoint_lens[(1 - all_sup_labels).astype(bool)], bins=35)\n axs[3].set_title(f'Non-supporting {name} token number \\n distribution\\n')\n fig.tight_layout()\n plt.savefig(f'plots/{split}_{config.level}_eda.png')\n\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print(\"Saving {}...\".format(message))\n with open(filename, \"w\") as fh:\n json.dump(obj, fh)\n\n\ndef prepro(config):\n \"\"\"\n process all files and build features for BERT-like models, save them to files\n :param config: config class\n \"\"\"\n random.seed(13)\n # remove sample weights file\n weights_file = '/mnt/localdata/rak/kg_qa/models/SpanBERT/outputs/train_weights.pickle'\n if os.path.exists(weights_file):\n os.remove(weights_file)\n global tokenizer\n tokenizer = bert_tokenizer if config.tokenizer == 'bert' else t5_tokenizer\n examples, eval_examples = process_file(config.data_file, config)\n test_example = eval_examples[0]\n test_spans = test_example['spans']\n\n print(len(examples), len(eval_examples))\n if config.data_split == 'train':\n record_file = config.train_record_file\n eval_file = config.train_eval_file\n elif config.data_split == 'dev':\n record_file = config.dev_record_file\n eval_file = config.dev_eval_file\n elif config.data_split == 'test':\n record_file = config.test_record_file\n eval_file = config.test_eval_file\n\n build_features(config, examples, config.data_split, record_file)\n save(eval_file, eval_examples, message='{} eval'.format(config.data_split))\n\n","sub_path":"bert_prepro.py","file_name":"bert_prepro.py","file_ext":"py","file_size_in_byte":27404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229488199","text":"# modified by fix_any.py\n# -*- mode:python; coding:utf-8 -*-\n# Copyright (c) 2020 IBM Corp. 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# generated by datamodel-codegen:\n# filename: oscal_component_schema.json\n\nfrom __future__ import annotations\n\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional\n\nfrom pydantic import AnyUrl, EmailStr, Extra, Field, conint, constr\nfrom trestle.core.base_model import OscalBaseModel\n\n\nclass Address(OscalBaseModel):\n type: Optional[str] = Field(\n None, description='Indicates the type of address.', title='Address Type'\n )\n addr_lines: Optional[List[str]] = Field(None, alias='addr-lines', min_items=1)\n city: Optional[str] = Field(\n None,\n description='City, town or geographical region for the mailing address.',\n title='City',\n )\n state: Optional[str] = Field(\n None,\n description='State, province or analogous geographical region for mailing address',\n title='State',\n )\n postal_code: Optional[str] = Field(\n None,\n alias='postal-code',\n description='Postal or ZIP code for mailing address',\n title='Postal Code',\n )\n country: Optional[str] = Field(\n None,\n description='The ISO 3166-1 alpha-2 country code for the mailing address.',\n title='Country Code',\n )\n\n\nclass Type(Enum):\n person = 'person'\n organization = 'organization'\n\n\nclass Transport(Enum):\n TCP = 'TCP'\n UDP = 'UDP'\n\n\nclass TelephoneNumber(OscalBaseModel):\n type: Optional[str] = Field(\n None, description='Indicates the type of phone number.', title='type flag'\n )\n number: str\n\n\nclass SystemId(OscalBaseModel):\n identifier_type: Optional[AnyUrl] = Field(\n None,\n alias='identifier-type',\n description='Identifies the identification system from which the provided identifier was assigned.',\n title='Identification System Type',\n )\n id: str\n\n\nclass State(Enum):\n under_development = 'under-development'\n operational = 'operational'\n disposition = 'disposition'\n other = 'other'\n\n\nclass SetParameter(OscalBaseModel):\n values: List[str] = Field(..., min_items=1)\n\n\nclass RoleId(OscalBaseModel):\n __root__: str = Field(\n ..., description='A reference to the roles served by the user.'\n )\n\n\nclass Remarks(OscalBaseModel):\n __root__: str = Field(\n ..., description='Additional commentary on the containing object.'\n )\n\n\nclass Property(OscalBaseModel):\n uuid: Optional[\n constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n )\n ] = Field(\n None,\n description='A unique identifier that can be used to reference this property elsewhere in an OSCAL document. A UUID should be consistantly used for a given location across revisions of the document.',\n title='Property Universally Unique Identifier',\n )\n name: str = Field(\n ...,\n description=\"A textual label that uniquely identifies a specific attribute, characteristic, or quality of the property's containing object.\",\n title='Property Name',\n )\n ns: Optional[AnyUrl] = Field(\n None,\n description=\"A namespace qualifying the property's name. This allows different organizations to associate distinct semantics with the same name.\",\n title='Property Namespace',\n )\n class_: Optional[str] = Field(\n None,\n alias='class',\n description=\"A textual label that provides a sub-type or characterization of the property's name. This can be used to further distinguish or discriminate between the semantics of multiple properties of the same object with the same name and ns.\",\n title='Property Class',\n )\n value: str\n\n\nclass PortRange(OscalBaseModel):\n start: Optional[conint(ge=0, multiple_of=1)] = Field(\n None,\n description='Indicates the starting port number in a port range',\n title='Start',\n )\n end: Optional[conint(ge=0, multiple_of=1)] = Field(\n None,\n description='Indicates the ending port number in a port range',\n title='End',\n )\n transport: Optional[Transport] = Field(\n None, description='Indicates the transport type.', title='Transport'\n )\n\n\nclass PartyUuid(OscalBaseModel):\n __root__: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(..., description='References a party defined in metadata.')\n\n\nclass MemberOfOrganization(OscalBaseModel):\n __root__: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='Identifies that the party object is a member of the organization associated with the provided UUID.',\n )\n\n\nclass LocationUuid(OscalBaseModel):\n __root__: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(..., description='References a location defined in metadata.')\n\n\nclass Link(OscalBaseModel):\n href: str = Field(\n ...,\n description='A resolvable URL reference to a resource.',\n title='Hypertext Reference',\n )\n rel: Optional[str] = Field(\n None,\n description=\"Describes the type of relationship provided by the link. This can be an indicator of the link's purpose.\",\n title='Relation',\n )\n media_type: Optional[str] = Field(\n None,\n alias='media-type',\n description='Specifies a media type as defined by the Internet Assigned Numbers Authority (IANA) Media Types Registry.',\n title='Media Type',\n )\n text: Optional[str] = Field(\n None,\n description='A textual label to associate with the link, which may be used for presentation in a tool.',\n title='Link Text',\n )\n\n\nclass IncorporatesComponent(OscalBaseModel):\n description: str = Field(\n ...,\n description='A description of the component, including information about its function.',\n title='Component Description',\n )\n\n\nclass ImportComponentDefinition(OscalBaseModel):\n href: str = Field(\n ...,\n description='A link to a resource that defines a set of components and/or capabilities to import into this collection.',\n title='Hyperlink Reference',\n )\n\n\nclass Hash(OscalBaseModel):\n algorithm: str = Field(\n ..., description='Method by which a hash is derived', title='Hash algorithm'\n )\n value: str\n\n\nclass FunctionPerformed(OscalBaseModel):\n __root__: str = Field(\n ...,\n description='Describes a function performed for a given authorized privilege by this user class.',\n )\n\n\nclass ExternalId(OscalBaseModel):\n scheme: AnyUrl = Field(\n ...,\n description='Indicates the type of external identifier.',\n title='External Identifier Schema',\n )\n id: str\n\n\nclass EmailAddress(OscalBaseModel):\n __root__: EmailStr = Field(\n ..., description='An email address as defined by RFC 5322 Section 3.4.1.'\n )\n\n\nclass DocumentId(OscalBaseModel):\n scheme: AnyUrl = Field(\n ...,\n description='Qualifies the kind of document identifier.',\n title='Document Identification Scheme',\n )\n identifier: str\n\n\nclass Base64(OscalBaseModel):\n filename: Optional[str] = Field(\n None,\n description='Name of the file before it was encoded as Base64 to be embedded in a resource. This is the name that will be assigned to the file when the file is decoded.',\n title='File Name',\n )\n media_type: Optional[str] = Field(\n None,\n alias='media-type',\n description='Specifies a media type as defined by the Internet Assigned Numbers Authority (IANA) Media Types Registry.',\n title='Media Type',\n )\n value: str\n\n\nclass AuthorizedPrivilege(OscalBaseModel):\n title: str = Field(\n ..., description='A human readable name for the privilege.', title='title field'\n )\n description: Optional[str] = Field(\n None,\n description=\"A summary of the privilege's purpose within the system.\",\n title='Privilege Description',\n )\n functions_performed: List[FunctionPerformed] = Field(\n ..., alias='functions-performed', min_items=1\n )\n\n\nclass Annotation(OscalBaseModel):\n name: str = Field(\n ...,\n description=\"A textual label that uniquely identifies a specific attribute, characteristic, or quality of the annotated property's containing object.\",\n title='Annotated Property Name',\n )\n uuid: Optional[\n constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n )\n ] = Field(\n None,\n description='A unique identifier that can be used to reference this annotated property elsewhere in an OSCAL document. A UUID should be consistantly used for a given location across revisions of the document.',\n title='Annotated Property Universally Unique Identifier',\n )\n ns: Optional[AnyUrl] = Field(\n None,\n description=\"A namespace qualifying the annotated property's name. This allows different organizations to associate distinct semantics with the same name.\",\n title='Annotated Property Namespace',\n )\n value: str = Field(\n ...,\n description='Indicates the value of the attribute, characteristic, or quality.',\n title='Annotated Property Value',\n )\n remarks: Optional[Remarks] = None\n\n\nclass SystemUser(OscalBaseModel):\n title: Optional[str] = Field(\n None,\n description='A name given to the user, which may be used by a tool for display and navigation.',\n title='User Title',\n )\n short_name: Optional[str] = Field(\n None,\n alias='short-name',\n description='A short common name, abbreviation, or acronym for the user.',\n title='User Short Name',\n )\n description: Optional[str] = Field(\n None,\n description=\"A summary of the user's purpose within the system.\",\n title='User Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n role_ids: Optional[List[RoleId]] = Field(None, alias='role-ids', min_items=1)\n authorized_privileges: Optional[List[AuthorizedPrivilege]] = Field(\n None, alias='authorized-privileges', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass Status(OscalBaseModel):\n state: State = Field(..., description='The operational status.', title='State')\n remarks: Optional[Remarks] = None\n\n\nclass Role(OscalBaseModel):\n id: str = Field(\n ...,\n description=\"A unique identifier for a specific role instance. This identifier's uniqueness is document scoped and is intended to be consistent for the same role across minor revisions of the document.\",\n title='Role Identifier',\n )\n title: str = Field(\n ...,\n description='A name given to the role, which may be used by a tool for display and navigation.',\n title='Role Title',\n )\n short_name: Optional[str] = Field(\n None,\n alias='short-name',\n description='A short common name, abbreviation, or acronym for the role.',\n title='Role Short Name',\n )\n description: Optional[str] = Field(\n None,\n description=\"A summary of the role's purpose and associated responsibilities.\",\n title='Role Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n remarks: Optional[Remarks] = None\n\n\nclass Rlink(OscalBaseModel):\n href: str = Field(\n ...,\n description='A resolvable URI reference to a resource.',\n title='Hypertext Reference',\n )\n media_type: Optional[str] = Field(\n None,\n alias='media-type',\n description='Specifies a media type as defined by the Internet Assigned Numbers Authority (IANA) Media Types Registry.',\n title='Media Type',\n )\n hashes: Optional[List[Hash]] = Field(None, min_items=1)\n\n\nclass Revision(OscalBaseModel):\n title: Optional[str] = Field(\n None,\n description='A name given to the document revision, which may be used by a tool for display and navigation.',\n title='Document Title',\n )\n published: Optional[datetime] = Field(\n None,\n description='The date and time the document was published. The date-time value must be formatted according to RFC 3339 with full time and time zone included.',\n title='Publication Timestamp',\n )\n last_modified: Optional[datetime] = Field(\n None,\n alias='last-modified',\n description='The date and time the document was last modified. The date-time value must be formatted according to RFC 3339 with full time and time zone included.',\n title='Last Modified Timestamp',\n )\n version: Optional[str] = Field(\n None,\n description='A string used to distinguish the current version of the document from other previous (and future) versions.',\n title='Document Version',\n )\n oscal_version: Optional[str] = Field(\n None,\n alias='oscal-version',\n description='The OSCAL model version the document was authored against.',\n title='OSCAL version',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n remarks: Optional[Remarks] = None\n\n\nclass ResponsibleRole(OscalBaseModel):\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n party_uuids: Optional[List[PartyUuid]] = Field(\n None, alias='party-uuids', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass ResponsibleParty(OscalBaseModel):\n party_uuids: List[PartyUuid] = Field(..., alias='party-uuids', min_items=1)\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n remarks: Optional[Remarks] = None\n\n\nclass Protocol(OscalBaseModel):\n uuid: Optional[\n constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n )\n ] = Field(\n None,\n description='A globally unique identifier that can be used to reference this service protocol entry elsewhere in an OSCAL document. A UUID should be consistently used for a given resource across revisions of the document.',\n title='Service Protocol Information Universally Unique Identifier',\n )\n name: str = Field(\n ...,\n description='The common name of the protocol, which should be the appropriate \"service name\" from the IANA Service Name and Transport Protocol Port Number Registry.',\n title='Protocol Name',\n )\n title: Optional[str] = Field(\n None,\n description='A human readable name for the protocol (e.g., Transport Layer Security).',\n title='title field',\n )\n port_ranges: Optional[List[PortRange]] = Field(\n None, alias='port-ranges', min_items=1\n )\n\n\nclass Party(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A unique identifier that can be used to reference this defined location elsewhere in an OSCAL document. A UUID should be consistantly used for a given party across revisions of the document.',\n title='Party Universally Unique Identifier',\n )\n type: Type = Field(\n ...,\n description='A category describing the kind of party the object describes.',\n title='Party Type',\n )\n name: Optional[str] = Field(\n None,\n description='The full name of the party. This is typically the legal name associated with the party.',\n title='Party Name',\n )\n short_name: Optional[str] = Field(\n None,\n alias='short-name',\n description='A short common name, abbreviation, or acronym for the party.',\n title='Party Short Name',\n )\n external_ids: Optional[List[ExternalId]] = Field(\n None, alias='external-ids', min_items=1\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n email_addresses: Optional[List[EmailAddress]] = Field(\n None, alias='email-addresses', min_items=1\n )\n telephone_numbers: Optional[List[TelephoneNumber]] = Field(\n None, alias='telephone-numbers', min_items=1\n )\n addresses: Optional[List[Address]] = Field(None, min_items=1)\n location_uuids: Optional[List[LocationUuid]] = Field(\n None, alias='location-uuids', min_items=1\n )\n member_of_organizations: Optional[List[MemberOfOrganization]] = Field(\n None, alias='member-of-organizations', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass Location(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A unique identifier that can be used to reference this defined location elsewhere in an OSCAL document. A UUID should be consistantly used for a given location across revisions of the document.',\n title='Location Universally Unique Identifier',\n )\n title: Optional[str] = Field(\n None,\n description='A name given to the location, which may be used by a tool for display and navigation.',\n title='Location Title',\n )\n address: Address = Field(\n ..., description='A postal address for the location.', title='Address'\n )\n email_addresses: Optional[List[EmailAddress]] = Field(\n None, alias='email-addresses', min_items=1\n )\n telephone_numbers: Optional[List[TelephoneNumber]] = Field(\n None, alias='telephone-numbers', min_items=1\n )\n urls: Optional[List[AnyUrl]] = Field(None, min_items=1)\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n remarks: Optional[Remarks] = None\n\n\nclass ImplementedComponent(OscalBaseModel):\n component_uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n alias='component-uuid',\n description='A reference to a component that is implemented as part of an inventory item.',\n title='Component Universally Unique Identifier Reference',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n responsible_parties: Optional[Dict[str, ResponsibleParty]] = Field(\n None, alias='responsible-parties'\n )\n remarks: Optional[Remarks] = None\n\n\nclass Inventory(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A globally unique identifier that can be used to reference this inventory item entry elsewhere in an OSCAL document. A UUID should be consistently used for a given resource across revisions of the document.',\n title='Inventory Universally Unique Identifier',\n )\n description: str = Field(\n ...,\n description='A summary of the inventory item stating its purpose within the system.',\n title='Inventory Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n responsible_parties: Optional[Dict[str, ResponsibleParty]] = Field(\n None, alias='responsible-parties'\n )\n implemented_components: Optional[List[ImplementedComponent]] = Field(\n None, alias='implemented-components', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass Citation(OscalBaseModel):\n text: str = Field(\n ..., description='A line of citation text.', title='Citation Text'\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n biblio: Optional[Dict[str, Any]] = Field(\n None,\n description='A container for structured bibliographic information. The model of this information is undefined by OSCAL.',\n title='Bibliographic Definition',\n )\n\n\nclass SystemComponent(OscalBaseModel):\n type: str = Field(\n ...,\n description='A category describing the purpose of the component.',\n title='Component Type',\n )\n title: str = Field(\n ...,\n description='A human readable name for the system component.',\n title='Component Title',\n )\n description: str = Field(\n ...,\n description='A description of the component, including information about its function.',\n title='Component Description',\n )\n purpose: Optional[str] = Field(\n None,\n description='A summary of the technological or business purpose of the component.',\n title='Purpose',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n status: Status = Field(\n ...,\n description='Describes the operational status of the system component.',\n title='Status',\n )\n responsible_roles: Optional[Dict[str, ResponsibleRole]] = Field(\n None, alias='responsible-roles'\n )\n protocols: Optional[List[Protocol]] = Field(None, min_items=1)\n remarks: Optional[Remarks] = None\n\n\nclass Statement(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A unique identifier for a specific control implementation.',\n title='Control Statement Implementation Identifier',\n )\n description: str = Field(\n ...,\n description='A summary of how the containing control statement is implemented by the component or capability.',\n title='Statement Implementation Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n responsible_roles: Optional[Dict[str, ResponsibleRole]] = Field(\n None, alias='responsible-roles'\n )\n remarks: Optional[Remarks] = None\n\n\nclass Resource(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A globally unique identifier that can be used to reference this defined resource elsewhere in an OSCAL document. A UUID should be consistantly used for a given resource across revisions of the document.',\n title='Resource Universally Unique Identifier',\n )\n title: Optional[str] = Field(\n None,\n description='A name given to the resource, which may be used by a tool for display and navigation.',\n title='Resource Title',\n )\n description: Optional[str] = Field(\n None,\n description='A short summary of the resource used to indicate the purpose of the resource.',\n title='Resource Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n document_ids: Optional[List[DocumentId]] = Field(\n None, alias='document-ids', min_items=1\n )\n citation: Optional[Citation] = Field(\n None,\n description='A citation consisting of end note text and optional structured bibliographic data.',\n title='Citation',\n )\n rlinks: Optional[List[Rlink]] = Field(None, min_items=1)\n base64: Optional[Base64] = Field(\n None,\n description='The Base64 alphabet in RFC 2045 - aligned with XSD.',\n title='Base64',\n )\n remarks: Optional[Remarks] = None\n\n\nclass Metadata(OscalBaseModel):\n title: str = Field(\n ...,\n description='A name given to the document, which may be used by a tool for display and navigation.',\n title='Document Title',\n )\n published: Optional[datetime] = Field(\n None,\n description='The date and time the document was published. The date-time value must be formatted according to RFC 3339 with full time and time zone included.',\n title='Publication Timestamp',\n )\n last_modified: datetime = Field(\n ...,\n alias='last-modified',\n description='The date and time the document was last modified. The date-time value must be formatted according to RFC 3339 with full time and time zone included.',\n title='Last Modified Timestamp',\n )\n version: str = Field(\n ...,\n description='A string used to distinguish the current version of the document from other previous (and future) versions.',\n title='Document Version',\n )\n oscal_version: str = Field(\n ...,\n alias='oscal-version',\n description='The OSCAL model version the document was authored against.',\n title='OSCAL version',\n )\n revisions: Optional[List[Revision]] = Field(None, min_items=1)\n document_ids: Optional[List[DocumentId]] = Field(\n None, alias='document-ids', min_items=1\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n roles: Optional[List[Role]] = Field(None, min_items=1)\n locations: Optional[List[Location]] = Field(None, min_items=1)\n parties: Optional[List[Party]] = Field(None, min_items=1)\n responsible_parties: Optional[Dict[str, ResponsibleParty]] = Field(\n None, alias='responsible-parties'\n )\n remarks: Optional[Remarks] = None\n\n\nclass ImplementedRequirement(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A unique identifier for a specific control implementation.',\n title='Control Implementation Identifier',\n )\n control_id: Optional[str] = Field(\n None,\n alias='control-id',\n description='A reference to a control identifier.',\n title='Control Identifier Reference',\n )\n description: str = Field(\n ...,\n description='A description of how the spefied control is implemented for the containing component or capability.',\n title='Control Implementation Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n responsible_roles: Optional[Dict[str, ResponsibleRole]] = Field(\n None, alias='responsible-roles'\n )\n set_parameters: Optional[Dict[str, SetParameter]] = Field(\n None, alias='set-parameters'\n )\n statements: Optional[Dict[str, Statement]] = None\n remarks: Optional[Remarks] = None\n\n\nclass BackMatter(OscalBaseModel):\n resources: Optional[List[Resource]] = Field(None, min_items=1)\n\n\nclass ControlImplementation(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A unique identifier for the set of implemented controls.',\n title='Control Implementation Set Identifier',\n )\n source: str = Field(\n ...,\n description='A reference to an OSCAL catalog or profile providing the referenced control or subcontrol definition.',\n title='Source Resource Reference',\n )\n description: str = Field(\n ...,\n description='A description of how the spefied set of controls are implemented for the containing component or capability.',\n title='Control Implementation Description',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n implemented_requirements: List[ImplementedRequirement] = Field(\n ..., alias='implemented-requirements', min_items=1\n )\n\n\nclass DefinedComponent(OscalBaseModel):\n type: str = Field(\n ...,\n description='A category describing the purpose of the component.',\n title='Component Type',\n )\n title: str = Field(\n ...,\n description='A human readable name for the component.',\n title='Component Title',\n )\n description: str = Field(\n ...,\n description='A description of the component, including information about its function.',\n title='Component Description',\n )\n purpose: Optional[str] = Field(\n None,\n description='A summary of the technological or business purpose of the component.',\n title='Purpose',\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n responsible_roles: Optional[Dict[str, ResponsibleRole]] = Field(\n None, alias='responsible-roles'\n )\n protocols: Optional[List[Protocol]] = Field(None, min_items=1)\n control_implementations: Optional[List[ControlImplementation]] = Field(\n None, alias='control-implementations', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass Capability(OscalBaseModel):\n name: str = Field(\n ...,\n description=\"The capability's human-readable name.\",\n title='Capability Name',\n )\n description: str = Field(\n ..., description='A summary of the capability.', title='Capability Description'\n )\n props: Optional[List[Property]] = Field(None, min_items=1)\n annotations: Optional[List[Annotation]] = Field(None, min_items=1)\n links: Optional[List[Link]] = Field(None, min_items=1)\n incorporates_components: Optional[Dict[str, IncorporatesComponent]] = Field(\n None, alias='incorporates-components'\n )\n control_implementations: Optional[List[ControlImplementation]] = Field(\n None, alias='control-implementations', min_items=1\n )\n remarks: Optional[Remarks] = None\n\n\nclass ComponentDefinition(OscalBaseModel):\n uuid: constr(\n regex=r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$'\n ) = Field(\n ...,\n description='A globally unique identifier for this component definition instance. This UUID should be changed when this document is revised.',\n title='Component Definition Universally Unique Identifier',\n )\n metadata: Metadata\n import_component_definitions: Optional[List[ImportComponentDefinition]] = Field(\n None, alias='import-component-definitions', min_items=1\n )\n components: Optional[Dict[str, SystemComponent]] = None\n capabilities: Optional[Dict[str, Capability]] = None\n back_matter: Optional[BackMatter] = Field(None, alias='back-matter')\n\n\nclass Model(OscalBaseModel):\n component_definition: ComponentDefinition = Field(..., alias='component-definition')\n\n","sub_path":"trestle/oscal/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":32901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"328672505","text":"import obspy\nimport read_event_obspy_file as reof\nfrom getwaveform import *\n\ndef get_ev_info(ev_info,iex):\n# ===============================================================\n# Taan Fjord landslide data, emulating data from Gualtieri & Ekström 2018 (GJI)\n# python run_getwaveform.py event_input_TaanFjordLandslide 0\n if iex == 0:\n ev_info.use_catalog = 0 # do not use event catalog for source parameters\n ev_info.otime = obspy.UTCDateTime(\"2015-10-18T05:18:31.000\")\n ev_info.min_dist = 0\n ev_info.max_dist = 50\n ev_info.tbefore_sec = 91\n ev_info.tafter_sec = 509\n\n # ENZ files can be used to compare data from Gualtieri & Ekström 2018 Broad-band seismic analysis and modeling of the 2015 Taan Fjord,Alaska landslide using Instaseis\n ev_info.isave_raw = False\n ev_info.isave_raw_processed = False\n ev_info.isave_ENZ = True\n\n ev_info.network = 'AK'\n ev_info.channel = 'LH?'\n ev_info.use_catalog = 0\n ev_info.elat = 60.175\n ev_info.elon = -141.187\n ev_info.edep = 0.00\n ev_info.emag = 4.9\n ev_info.resample_TF = True\n ev_info.resample_freq = 50\n ev_info.scale_factor = 1\n ev_info.filter_type = 'highpass'\n ev_info.ipre_filt = 2\n ev_info.pre_filt = (0.004, 0.005, 10.0, 15.0)\n ev_info.water_level = 10000\n ev_info.detrend = True # detrend waveforms\n ev_info.demean = True # demean waveforms\n ev_info.taper = 0.05\n\n return(ev_info)\n#==============================================================================\n","sub_path":"event_input/event_input_TaanFjordLandslide.py","file_name":"event_input_TaanFjordLandslide.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"457005309","text":"# vocabulary.txt 를 만들어야 한다.\n# input 값을 가진다.\n# input 에 입력된 값이 vocabulary.txt 파일에 들어가야 한다.\n\nvoca_file = open('vocabulary.txt', 'w')\n\nwhile True:\n english_voca = str(input(\"영어 단어를 입력하세요: \"))\n if english_voca == \"q\":\n break\n voca_file.close()\n korean = str(input(\"한국어 뜻을 입력하세요: \"))\n voca_file.write(\"%s: %s\\n\" %(english_voca, korean))","sub_path":"9-11 단어장 만들기.py","file_name":"9-11 단어장 만들기.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441067025","text":"import json\nimport os\nimport time\n\nfrom counterfit_connection import CounterFitConnection\nfrom counterfit_shims_grove.adc import ADC\nfrom counterfit_shims_grove.grove_relay import GroveRelay\nfrom azure.iot.device import IoTHubDeviceClient, Message, MethodResponse\n\n\nclass SoilMoistureMonitor:\n\n def __init__(self, device_client: IoTHubDeviceClient, adc: ADC, relay: GroveRelay):\n self.device_client = device_client\n self.adc = adc\n self.relay = relay\n self.device_client.on_method_request_received = self.handle_request\n\n def handle_request(self, request):\n if request.name == \"relay_on\":\n self.relay.on()\n elif request.name == \"relay_off\":\n self.relay.off()\n\n method_response = MethodResponse.create_from_method_request(request, 200)\n self.device_client.send_method_response(method_response)\n\n def get_reading(self):\n soil_moisture = self.adc.read(0)\n print(\"Soil moisture:\", soil_moisture)\n message = Message(json.dumps({'soil_moisture': soil_moisture}))\n self.device_client.send_message(message)\n\n\ndef connect(connection_string):\n device_client = IoTHubDeviceClient.create_from_connection_string(connection_string)\n print('Connecting')\n device_client.connect()\n print('Connected')\n return device_client\n\n\ndef take_readings(soil_moisture_monitor):\n while True:\n soil_moisture_monitor.get_reading()\n time.sleep(10)\n\n\ndef main():\n CounterFitConnection.init('127.0.0.1', 5000)\n device_client = connect(connection_string=os.getenv('connection_string'))\n adc = ADC()\n relay = GroveRelay(5)\n soil_moisture_monitor = SoilMoistureMonitor(\n device_client=device_client,\n adc=adc,\n relay=relay\n )\n take_readings(soil_moisture_monitor)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"soil-moisture-sensor/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"411527251","text":"#\n# Copyright 2012 Quantopian, 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\nfrom utils.protocol_utils import Enum\n\n# Datasource type should completely determine the other fields of a\n# message with its type.\nDATASOURCE_TYPE = Enum(\n 'AS_TRADED_EQUITY',\n 'MERGER',\n 'SPLIT',\n 'DIVIDEND',\n 'TRADE',\n 'EMPTY',\n 'DONE'\n)\n","sub_path":"zipline/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550355998","text":"import cx_Oracle\nimport json\nimport logging\n\nFORMAT = '%(asctime)-15s %(message)s'\nlogging.basicConfig(format=FORMAT)\nd = { }\nlogger = logging.getLogger('dbconnection')\n\ndef load_config(config_file=\"config/config.json\"):\n with open(config_file) as f:\n config_dict = json.load(f)\n return config_dict\n\ndef get_connection(connection_params=load_config()):\n dsn_tns=cx_Oracle.makedsn(host=connection_params[\"host\"],\n port=connection_params[\"port\"],\n sid=connection_params[\"SID\"])\n\n connection=cx_Oracle.connect(user=connection_params[\"user\"],\n password=connection_params[\"password\"],\n dsn=dsn_tns)\n return connection\n\n\n\ndef executeScriptsFromFile(filename, conn):\n \"\"\" Execute the filename as a series of SQL statements separated by commas on the conn connection \"\"\"\n # Open and read the file as a single buffer\n fd = open(filename, 'r')\n sqlFile = fd.read()\n fd.close()\n\n # all SQL commands (split on ';')\n sqlCommands = sqlFile.split(';')\n\n\n # Execute every command from the input file\n for command in sqlCommands:\n # logger.warning('Setting up sqllite file : %s', command, extra=d)\n # This will skip and report errors\n # For example, if the tables do not yet exist, this will skip over\n # the DROP TABLE commands\n\n try:\n conn.execute(command)\n\n except OperationalError as msg:\n print ( \"Command skipped: \", msg )","sub_path":"dbconnection.py","file_name":"dbconnection.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"33322372","text":"import logging\nimport re\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom horizon import exceptions\nfrom horizon import forms\nfrom horizon import messages\n\nfrom openstack_dashboard import api\n\nfrom nuage_horizon.api import neutron\n\n\nLOG = logging.getLogger(__name__)\nvlan_regex = re.compile(r'(\\d+)-(\\d+)')\n\n\nclass UnsafeChoiceField(forms.ChoiceField):\n \"\"\"\n This is an extension of the default choicefield with the exception that it\n will not validate that the value in the POST request matches the value\n during rendering of the Choicefield (In case Javascript alters the values\n client-side)\n \"\"\"\n def valid_value(self, value):\n return True\n\n\nclass VlanForm(forms.SelfHandlingForm):\n vlan = forms.IntegerField(label=_(\"VLAN\"))\n assigned = forms.ChoiceField(label=_(\"Tenant\"),\n required=False)\n type = forms.ChoiceField(label=_(\"Type\"),\n choices=[('', _(\"Select a vport type\")),\n ('host', _('Host')),\n ('bridge', _('Bridge'))],\n required=False)\n subnet_id = UnsafeChoiceField(label=_(\"Subnet\"),\n required=False,\n choices=[('', _('Select a subnet'))])\n port_id = UnsafeChoiceField(label=_(\"Port\"),\n required=False,\n choices=[('', _('Select a port'))])\n failure_url = 'horizon:project:gateways:ports:detail'\n\n def __init__(self, request, *args, **kwargs):\n super(VlanForm, self).__init__(request, *args, **kwargs)\n if kwargs.get('data'):\n data = kwargs['data']\n else:\n data = kwargs.get('initial')\n assigned = data.get('assigned')\n gw_port = kwargs['initial']['gw_port']\n\n if assigned:\n self.fields['assigned'] = forms.CharField(\n label=_(\"Tenant\"),\n required=False,\n widget=forms.TextInput(\n attrs={'readonly': 'readonly'}))\n elif request.user.is_superuser:\n tenant_choices = [('', _(\"Select a tenant\"))]\n tenants, has_more = api.keystone.tenant_list(request)\n for tenant in tenants:\n if tenant.enabled:\n tenant_choices.append((tenant.id, tenant.name))\n self.fields['assigned'].choices = tenant_choices\n else:\n del self.fields['assigned']\n\n result = vlan_regex.match(gw_port.get('vlan'))\n if result:\n self.fields['vlan'] = forms.IntegerField(\n label=_(\"VLAN\"),\n min_value=int(result.groups()[0]),\n max_value=int(result.groups()[1]))\n\n def is_valid(self):\n valid = super(VlanForm, self).is_valid()\n if self.data['type'] == 'host':\n if not self.data['subnet_id']:\n self._errors['subnet_id'] = self.error_class(\n ['This is a required field.'])\n valid = False\n if not self.data['port_id']:\n self._errors['port_id'] = self.error_class(\n ['This is a required field.'])\n valid = False\n if self.data['type'] == 'bridge':\n if not self.data['subnet_id']:\n self._errors['subnet_id'] = self.error_class(\n ['This is a required field.'])\n valid = False\n return valid\n\n\nclass CreateForm(VlanForm):\n\n @staticmethod\n def create_gw_vlan(request, gw_port_id, vlan, assigned, type, subnet_id,\n port_id):\n gw_vlan = neutron.nuage_gateway_vlan_create(\n request, gw_port_id=gw_port_id, vlan=vlan)\n if assigned:\n neutron.nuage_gateway_vlan_assign(\n request, gw_vlan['id'], tenant_id=assigned)\n if type == 'host':\n neutron.nuage_gateway_vport_create(\n request,\n gw_vlan_id=gw_vlan['id'],\n port_id=port_id,\n tenant_id=assigned)\n elif type == 'bridge':\n neutron.nuage_gateway_vport_create(\n request,\n gw_vlan_id=gw_vlan['id'],\n subnet_id=subnet_id,\n tenant_id=assigned)\n return gw_vlan\n\n def handle(self, request, data):\n gw_vlan = None\n gw_port_id = self.initial.get('gw_port_id')\n try:\n vlan = data['vlan']\n assigned = data['assigned']\n type = data['type']\n subnet_id = data['subnet_id']\n port_id = data['port_id']\n\n gw_vlan = self.create_gw_vlan(request, gw_port_id, vlan,\n assigned, type, subnet_id,\n port_id)\n\n message = _('Gateway Vlan with vlan %s was successfully '\n 'created.') % vlan\n messages.success(request, message)\n return gw_vlan\n except Exception:\n if gw_vlan:\n neutron.nuage_gateway_vlan_delete(request, gw_vlan['id'])\n msg = _('Failed to create Gateway Vlan.')\n LOG.info(msg)\n args = [gw_port_id]\n redirect = reverse(self.failure_url, args=args)\n exceptions.handle(request, msg, redirect=redirect)\n return False\n\n\nclass UpdateForm(VlanForm):\n def __init__(self, request, *args, **kwargs):\n super(UpdateForm, self).__init__(request, *args, **kwargs)\n self.fields['vlan'].widget = forms.TextInput(\n attrs={'readonly': 'readonly'})\n\n def delete_gw_vlan(self, gw_vlan_id, request):\n gw_vlan = neutron.nuage_gateway_vlan_get(self.request, gw_vlan_id)\n try:\n vport = gw_vlan.get('vport')\n if vport:\n neutron.nuage_gateway_vport_delete(request, vport)\n neutron.nuage_gateway_vlan_delete(request, gw_vlan_id)\n except Exception:\n msg = _('Failed to delete Gateway Vlan %s')\n LOG.info(msg, gw_vlan_id)\n redirect = reverse(\"horizon:project:gateways:ports:detail\",\n args=[gw_vlan['gatewayport']])\n exceptions.handle(request, msg % gw_vlan_id, redirect=redirect)\n\n def handle(self, request, data):\n gw_port = self.initial['gw_port']\n gw_port_id = gw_port.get('id')\n\n try:\n gw_vlan_id = self.initial['gw_vlan_id']\n vlan = data['vlan']\n assigned = data.get('assigned')\n type = data.get('type')\n subnet_id = data.get('subnet_id')\n port_id = data.get('port_id')\n\n if request.user.is_superuser:\n # neutron.nuage_gateway_vlan_unassign(\n # request,\n # gw_vlan_id,\n # tenant_id=self.initial['tenant_id'])\n if assigned and self.initial['assigned'] != assigned:\n neutron.nuage_gateway_vlan_assign(\n request, gw_vlan_id, tenant_id=assigned)\n\n if not self.initial['type']:\n if type == 'host' and subnet_id and port_id:\n neutron.nuage_gateway_vport_create(\n request,\n gw_vlan_id=gw_vlan_id,\n port_id=port_id,\n tenant_id=assigned)\n elif type == 'bridge' and subnet_id:\n neutron.nuage_gateway_vport_create(\n request,\n gw_vlan_id=gw_vlan_id,\n subnet_id=subnet_id,\n tenant_id=assigned)\n\n message = _('Gateway Vlan with vlan %s was successfully '\n 'updated.') % vlan\n messages.success(request, message)\n return True\n except Exception:\n msg = _('Failed to update Gateway Vlan.')\n LOG.info(msg)\n args = [gw_port_id]\n redirect = reverse(self.failure_url, args=args)\n exceptions.handle(request, msg, redirect=redirect)\n return False\n","sub_path":"nuage_horizon/dashboards/project/gateway_vlans/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303605030","text":"from __future__ import division\nimport pdb\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import multivariate_normal\nfrom scipy.spatial.distance import euclidean\n\n\ndef gaussian_kernel(x):\n \"\"\"\n\n Takes in an array of x values and returns corresponding Gaussian kernel values\n\n Parameters\n ----------\n x: array_like\n An array of x values\n\n Returns\n -------\n gaussian_kernel(x): array_like\n An array of same length as x with corresponding kernel values\n\n \"\"\"\n return np.array([1.0/(2.0*np.pi)**.5 * np.exp(-i**2/2) for i in x])\n\ndef weight_calc(x, x_star, h, kernel_func=gaussian_kernel):\n \"\"\"\n\n Evaluates the normalized weights for based on a kernel function\n\n Parameters\n ----------\n x: array_like\n the array of x values from the data\n x_star: float\n The x value corresponding to the desired prediction location\n h: float\n The bandwidth\n kernel_func: function\n The desired kernel function. Default is gaussian\n\n\n Returns\n -------\n weight_calc: array_like\n The weight of each x data point for the desired prediction location\n \"\"\"\n raw_weights = 1.0/h*kernel_func((x-x_star)/h)\n norm_weights = np.array(raw_weights/np.sum(raw_weights))\n return norm_weights\n\ndef pred(x,y, x_star, h, kernel_func=gaussian_kernel):\n\n \"\"\"\n\n Makes predictions for an array x_star for a given dataset of x and y\n\n Parameters\n ----------\n x: array_like\n the array of x values from the data\n y: array_like\n the array of corresponding y values\n x_star: float\n The x value corresponding to the desired prediction location\n h: float\n The bandwidth\n kernel_func: function\n The desired kernel function. Default is gaussian\n\n Returns\n -------\n y_star: array_like\n The predicted values corresponding to x_star\n \"\"\"\n\n y_star = np.zeros(len(x_star))\n for i, x_val in enumerate(x_star):\n weights = weight_calc(x, x_val,h, kernel_func)\n y_star[i] = weights@y #matrix multiplciation\n\n return y_star\n\ndef train_test_split(x,y, test_size=0.25):\n\n \"\"\"\n\n Splits a dataset into a training and test set\n\n Parameters\n ----------\n x: array_like\n The x values for a dataset\n y: array_like\n The corresponding y values from the dataset\n test_size: float\n The fraction of the dataset to allocate to the test set\n\n Returns\n -------\n train_x: array_like\n The x values from the training set\n train_y: array_like\n The corresponding y values from the training set\n test_x: array_like\n The x values from the test set\n test_y: array_like\n The corresponding y values from the test set\n\n Raises\n ------\n ValueError\n when x and y are not the same length\n\n \"\"\"\n if len(x) != len(y):\n raise ValueError('x and y should be the same length')\n\n #First determine the absolute number of points for the test set\n test_size = int(round(test_size*len(x)))\n\n #Randomly select indices for the test set\n test_indices = np.random.choice(np.array(range(len(x))), test_size, replace=False)\n\n #Then make the test set\n test_x = np.array(x)[test_indices]\n test_y = np.array(y)[test_indices]\n\n #Then make the training set \n train_x = np.delete(np.array(x),test_indices)\n train_y = np.delete(np.array(y),test_indices)\n\n return train_x, train_y, test_x, test_y\n\ndef error_calc(x1, x2):\n \"\"\"\n\n Determines the mean squared error between two vectors.\n x1 and x2 must be the same length\n\n Parameters\n ----------\n x1 : array_like\n The first array\n x2: array_like\n The second array\n\n Returns\n -------\n mean_error: float\n The average squared error between x1 and x2\n\n Raises:\n ------\n ValueError\n if the two arrays are not the same length\n \"\"\"\n if len(x1) != len(x2):\n raise ValueError('arrays must be the same length')\n\n total_error = 0.0\n for i in range(len(x1)):\n total_error = total_error + (x1[i] - x2[i])**2\n\n mean_error = total_error / float(len(x1))\n return mean_error\n\ndef local_poly_estimate(x_data, y_data,x_star,h, kernel = gaussian_kernel, d=2):\n \"\"\"\n\n Description\n\n Parameters\n ----------\n x_data: array_like\n The x values from the observed data\n y_data: array_like\n The y values from the observed data\n x_star: array_like\n The x locations to make predictions for\n h: Float\n The bandwidth\n kernel: func\n The kernel function to use\n d: int\n The order of the polynomial\n\n Returns\n -------\n y_star: array_like\n The predicted y_values corresponding to x_star\n H: array_like\n The projection matrix \n \"\"\"\n #Creating numpy array versions of the x and y data so everything plays nicely\n x = np.array(x_data)\n y = np.array(y_data)\n\n y_star = np.zeros(len(x_star))\n #initialize H, the projection matrix\n H = np.zeros([len(x_star), len(x_data)])\n #Creating the R matrix\n d = 2\n for i,x_val in enumerate(x_star):\n #Making the general R matrix\n R = np.zeros([len(x),d])\n for j in range(d):\n R[:,j] = (x - x_val)**j\n #Making the W matrix\n W = np.diag(1/h * kernel((x-x_val)/h))\n\n a_hat = inv(np.transpose(R)@W@R)@np.transpose(R)@W@y\n H[i,:] = (inv(np.transpose(R)@W@R)@np.transpose(R)@W)[0,:]\n y_star[i] = a_hat[0]\n\n\n return y_star, H\n\ndef leave_one_out(x_data, y_data, estimator,h, kernel=gaussian_kernel):\n #Creating numpy array versions of the x and y data so everything plays nicely\n x = np.array(x_data)\n y = np.array(y_data)\n error = np.zeros(len(x_data))\n for i in range(len(x_data)):\n y_star = estimator(np.delete(x,i), np.delete(y,i), [x[i]], h, kernel)[0]\n error[i] = error_calc(y_star, [y_data[i]])\n return np.mean(error)\n\ndef matern(x, b, tau_sq1, tau_sq2 ):\n\n \"\"\"\n\n The squared exponential case of the matern class\n\n Parameters\n ----------\n x : array_like\n The points at which to evaluate the function\n b : float\n the first hyperparameter\n tau_sq1: float\n the second hype parameter\n tau_sq2: float\n the third hyperparameter\n\n Returns\n -------\n cov_mat : array_like\n\n \"\"\"\n cov_mat = np.zeros([len(x), len(x)])\n for i,x1 in enumerate(x):\n for j,x2 in enumerate(x):\n d = euclidean(x1,x2)\n cov_mat[i,j] = tau_sq1*np.exp(-.5*(d/b)**2)+tau_sq2*float(x1==x2)\n return cov_mat\n\ndef matern52(x, b, tau_sq1, tau_sq2 ):\n\n \"\"\"\n\n The matern 5/2 covariance function\n\n Parameters\n ----------\n x : array_like\n The points at which to evaluate the function\n b : float\n the first hyperparameter\n tau_sq1: float\n the second hype parameter\n tau_sq2: float\n the third hyperparameter\n\n Returns\n -------\n cov_mat : array_like\n\n \"\"\"\n cov_mat = np.zeros([len(x), len(x)])\n sqrt5 = 5.0**.5\n for i,x1 in enumerate(x):\n for j,x2 in enumerate(x):\n d = euclidean(x1,x2)\n cov_mat[i,j] = tau_sq1*(1.0+sqrt5*d/b + 5*d**2/(3*b**2)) \\\n *np.exp(-sqrt5*d/b)+ tau_sq2*float(x1==x2)\n\n return cov_mat\n\ndef gp_predict(x_data, y_data, x_pred,sigma_2, b,tau_sq1, tau_sq2, prior_mean = 0.0, cov_fun=matern):\n \"\"\"\n\n Returns predictions of the mean of the function distribution for a \n Gaussian process\n\n Parameters\n ----------\n x_data : array_like\n the x values from the data\n y_data : array_like\n the corresponding y values from the data\n x_pred : array_like\n the values at which predictions will be made\n sigma_2 : float\n the variance of the residuals\n b: float\n hyperparameter for the covariance function\n tau_sq1: float\n hyperparameter for the covariance function\n tau_sq2: float\n hyperparameter for the covariance function\n prior_mean: float\n the mean value for the gaussian process (becomes vectorized)\n cov_fun: function\n the function to use to generate the covariance matrix\n\n Returns\n -------\n y_pred: array_like\n the predicted y values that correspond to x_pred\n cov: array_like\n the covariance matrix for the estimate of f(x_star)\n \"\"\"\n C = cov_fun(np.concatenate([x_data, x_pred]), b, tau_sq1, tau_sq2)\n #Then we need to extract the partioned matrices\n #First C(x,x) = C11\n C_11 = C[:len(x_data), :len(x_data)]\n C_21 = C[len(x_data):,:len(x_data)]\n C_22 = C[len(x_data):,len(x_data):]\n #then calculate the weight matrix\n w=C_21@np.linalg.inv((C_11 + np.eye(len(x_data))*sigma_2))\n #finally calculate the predicted y values\n y_pred = w@y_data\n cov=C_22 - C_21@np.linalg.inv(C_11+np.eye(len(x_data))*sigma_2)@np.transpose(C_21)\n return y_pred, cov\n\ndef log_likelihood(x_data, y_data, sigma_2, b, tau_sq1, tau_sq2 = 0.0, cov_fun=matern):\n \"\"\"\n Returns a quantity that is proportional to the log likelihood for a Gaussian process\n Used to determine hyperparameters for the matern covariance functions\n\n Parameters\n ----------\n x_data: array_like\n x values from the data\n y_data: array_like\n corresponding y values\n sigma_2: float\n Variance of residuals\n b: float\n Hyperparameter\n tau_sq1: float\n Hyperparameter\n tau_sq2: float\n Hyperparameter\n cov_fun: function\n The covariance function to use\n Returns\n -------\n log_like: float\n Quantity proportional to the log likelihood\n\n \"\"\"\n #First evaluate the covariance matrix:\n C = cov_fun(x_data,b,tau_sq1, tau_sq2)\n p = multivariate_normal.logpdf(y_data, np.zeros(len(y_data)), sigma_2*np.eye(len(y_data))+C)\n return p\n\n","sub_path":"exercises_03/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":9886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499782218","text":"#coding=utf-8\n\nfrom __future__ import unicode_literals\nfrom .packages import requests\nimport re\nimport logging\nimport time\nfrom io import open\nfrom .config import Config\n\ndef verify():\n \"\"\"\n Fetch param v of the ingress api.\n \"\"\"\n headers = {\n 'referer': 'https://www.ingress.com/intel',\n 'user-agent': 'Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; Trident/5.0)',\n }\n flag = 1\n while flag:\n request = requests.get('https://www.ingress.com/jsc/gen_dashboard.js',\n headers=headers, verify=False, proxies=proxies)\n logging.debug('Completed transfers in {:.3f}s'.format(\n request.elapsed.total_seconds()))\n reg = '\"([\\da-f]{40})\"'\n try:\n v = re.search(reg, request.text).group(1)\n except:\n v = 0\n if v:\n flag = 0\n else:\n time.sleep(Config.getint('Option', 'interval'))\n logging.debug('New version detected: ' + v)\n Config.set('Verify', 'v', v)\n Config.write(open('ingrex.ini', 'wb'))\n return True\n\nif __name__ == \"__main__\":\n pass\nelse:\n if Config.getboolean('Proxy', 'enable'):\n proxies = {\n 'http': Config.get('Proxy', 'http'),\n 'https': Config.get('Proxy', 'https')\n }\n else:\n proxies = {}\n\n","sub_path":"src/ingrex/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400943021","text":"#!/usr/bin/python3\ndef weight_average(my_list=[]):\n\n score = 0\n weight = 0\n\n if my_list:\n for listy in my_list:\n score = score + (listy[0] * listy[1])\n weight = weight + listy[1]\n return (score/weight)\n return 0\n","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"73534411","text":"#!/usr/bin/env python\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 argparse\nimport os\nimport os.path\nimport sys\n\nimport jinja2\nimport six\nfrom six.moves import configparser\nfrom six.moves.urllib import parse as urllib_parse\n\n\ndef escape(buff):\n \"\"\"Because otherwise Firefox is a sad panda.\"\"\"\n return buff.replace(',', '%2c').replace('-', '%2D')\n\n\ndef generate_dashboard_url(dashboard):\n \"\"\"Generate a dashboard URL from a given definition.\"\"\"\n try:\n title = dashboard.get('dashboard', 'title')\n except configparser.NoOptionError:\n raise ValueError(\"option 'title' in section 'dashboard' not set\")\n\n try:\n foreach = dashboard.get('dashboard', 'foreach')\n except configparser.NoOptionError:\n raise ValueError(\"option 'foreach' in section 'dashboard' not set\")\n\n try:\n baseurl = dashboard.get('dashboard', 'baseurl')\n except configparser.NoOptionError:\n baseurl = 'https://review.openstack.org/#/dashboard/?'\n\n url = baseurl\n url += escape(urllib_parse.urlencode({'title': title,\n 'foreach': foreach}))\n for section in dashboard.sections():\n if not section.startswith('section'):\n continue\n\n try:\n query = dashboard.get(section, 'query')\n except configparser.NoOptionError:\n raise ValueError(\"option 'query' in '%s' not set\" % section)\n\n title = section[9:-1]\n encoded = escape(urllib_parse.urlencode({title: query}))\n url += \"&%s\" % encoded\n return url\n\n\ndef get_options():\n \"\"\"Parse command line arguments and options.\"\"\"\n parser = argparse.ArgumentParser(\n description='Create a Gerrit dashboard URL from specified dashboard '\n 'definition files')\n parser.add_argument('dashboard_paths', nargs='+',\n metavar='dashboard_path',\n help='Path to a dashboard definition file or a '\n 'directory containing a set of dashboard '\n 'definition files with the file suffix .dash.')\n parser.add_argument('--check-only', default=False, action=\"store_true\",\n help='Only check the syntax of the specified '\n 'dasbhoard files')\n parser.add_argument('--template', default='single.txt',\n help='Name of template')\n\n # Find path to template_dir\n # We need to support running with and without installation\n if os.path.exists('templates'):\n template_dir = 'templates'\n elif os.path.exists('/usr/local/share/gerrit-dash-creator/templates'):\n template_dir = '/usr/local/share/gerrit-dash-creator/templates'\n else:\n template_dir = os.path.join(sys.prefix, 'share',\n 'gerrit-dash-creator', 'templates')\n parser.add_argument('--template-directory',\n default=template_dir,\n help='Directory to scan for template files')\n parser.add_argument('--template-file', default=None,\n help='Location of a specific template file')\n return parser.parse_args()\n\n\ndef read_dashboard_file(dashboard_file):\n \"\"\"Read and parse a dashboard definition from a specified file.\"\"\"\n if (not os.path.isfile(dashboard_file) or\n not os.access(dashboard_file, os.R_OK)):\n raise ValueError(\"dashboard file '%s' is missing or \"\n \"is not readable\" % dashboard_file)\n dashboard = configparser.ConfigParser()\n dashboard.readfp(open(dashboard_file))\n return dashboard\n\n\ndef load_template(template_file=None, template_directory=None,\n template_name=None):\n \"\"\"Load the specified template.\"\"\"\n if template_file:\n template_name = os.path.basename(template_file)\n template_directory = os.path.dirname(os.path.abspath(template_file))\n\n try:\n loader = jinja2.FileSystemLoader(template_directory)\n environment = jinja2.Environment(loader=loader)\n template = environment.get_template(template_name)\n except (jinja2.exceptions.TemplateError, IOError) as e:\n print(\"error: opening template '%s' failed: %s\" %\n (template_name, e.__class__.__name__))\n return\n\n return template\n\n\ndef get_configuration(dashboard):\n \"\"\"Returns the configuration of a dashboard as string.\"\"\"\n configuration = six.StringIO()\n dashboard.write(configuration)\n result = configuration.getvalue()\n configuration.close()\n return result\n\n\ndef generate_dashboard_urls(dashboards, template):\n \"\"\"Prints the dashboard URLs of a set of dashboards.\"\"\"\n result = 0\n\n for dashboard_file in dashboards:\n dashboard = dashboards[dashboard_file]\n try:\n url = generate_dashboard_url(dashboard)\n except ValueError as e:\n raise ValueError(\"generating dashboard '%s' failed: %s\" %\n (dashboard_file, e))\n result = 1\n continue\n\n variables = {\n 'url': url,\n 'title': dashboard.get('dashboard', 'title') or None,\n 'description': dashboard.get('dashboard', 'description') or None,\n 'configuration': get_configuration(dashboard)\n }\n print(template.render(variables))\n\n return result\n\n\ndef load_dashboards(paths):\n \"\"\"Load specified dashboards from files or directories.\"\"\"\n dashboards = {}\n for dashboard_path in paths:\n dashboard_files = []\n if os.path.isdir(dashboard_path):\n for root, dirs, files in os.walk(dashboard_path):\n for file in files:\n if file.endswith('.dash'):\n dashboard_files.append(os.path.join(root, file))\n else:\n dashboard_files.append(dashboard_path)\n\n for dashboard_file in dashboard_files:\n try:\n dashboards[dashboard_file] = read_dashboard_file(\n dashboard_file\n )\n except configparser.Error as e:\n raise ValueError(\"dashboard file '%s' cannot be \"\n \"parsed: %s\" % (dashboard_file, e))\n\n return dashboards\n\n\ndef main():\n \"\"\"Entrypoint.\"\"\"\n opts = get_options()\n\n template = None\n if not opts.check_only:\n template = load_template(\n template_file=opts.template_file,\n template_directory=opts.template_directory,\n template_name=opts.template\n )\n\n try:\n dashboards = load_dashboards(opts.dashboard_paths)\n if not opts.check_only and template:\n generate_dashboard_urls(dashboards, template)\n elif not opts.check_only and not template:\n return 1\n except ValueError as e:\n print(\"error: %s\" % e)\n return 1\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"gerrit_dash_creator/cmd/creator.py","file_name":"creator.py","file_ext":"py","file_size_in_byte":7436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"428807927","text":"from urllib import parse\nimport base64\nimport binascii\nimport binhex\n\n\ndef Base64Decode():\n test = input(\"Enter base64 -> \")\n data_encoded = base64.b64decode(test)\n data_encoded = base64.urlsafe_b64decode(test)\n print (\"\\n--------------------------\")\n print(data_encoded.decode())\n print (\"\\n--------------------------\")\n input(\"Press Enter to exit\")\n\ndef Base64Encode():\n test = input(\"Enter text to Encode \")\n data = base64.b64encode(test.encode())\n print (\"\\n-------------------------\")\n print(data.decode())\n print (\"\\n-------------------------\")\n input (\"Press Enter to exit\")\n\n\ndef UrlDecode(string):\n test = input(\"Enter Encoded URL ->\")\n try:\n protocol = string[:string.index(\"//\")]+ \"//\"\n except ValueError:\n protocol = \"http://\"\n string = string.replace(\"http://\",\"\", 1)\n string = string.replace(\"https://\",\"\", 1)\n if \"/\" in string:\n string = parse.unquote(string.replace(string[:string.index(\"/\")], bytearray(string[:string.index(\"/\")],\"idna\").decode(\"idna\"),1),encoding='utf-8')\n else:\n string = bytearray(string, \"idna\").decode(\"idna\")\n print (\"\\n--------------------------\")\n string= protocol + string\n print (string)\n print (\"\\n--------------------------\")\n input (\"Press Enter to exit\")\n\n\nchoice = input(\"Enter\\n -Base64Decode:1 \\n -Base64Encode:2 \\n -URLDecoder:3 \\n\")\n\nif choice == \"1\":\n Base64Decode()\nif choice == \"2\":\n Base64Encode()\nif choice == \"3\":\n UrlDecode()\nelse : \n print(\"Done\")\n","sub_path":"Crackon/Uncrack.py","file_name":"Uncrack.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"66984846","text":"import pints\nfrom logger import logger\nimport datetime\nimport random\nimport sqlalchemy\nimport json\nimport pytz\nimport uuid\nimport os\nfrom metrics import metrics\nfrom app import app, db\n\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore\nfrom apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor\n\nPAPER_DO_NOT_START_SCHEDULER = int(os.environ.get('PAPER_DO_NOT_START_SCHEDULER', 0)) > 0\n\n\ndef startScheduler(engine):\n logger.info(f'startScheduler? {(not PAPER_DO_NOT_START_SCHEDULER)}')\n if PAPER_DO_NOT_START_SCHEDULER:\n # runWeekly()\n logger.info(f'not starting scheduler...')\n return False\n scheduler = False\n apses = pints.postgres.getSchedulerRow(engine)\n logger.info(f'apses... {apses}')\n if apses:\n pints.postgres.truncateTable(engine, 'aps_scheduler')\n logger.info(f'starting aps...')\n jobstores = {\n 'default': SQLAlchemyJobStore(engine=engine, tablename='aps_scheduler', tableschema='public')\n }\n executors = {\n 'default': ThreadPoolExecutor(20),\n 'processpool': ProcessPoolExecutor(5)\n }\n job_defaults = {\n 'coalesce': False,\n 'max_instances': 3,\n 'misfire_grace_time': 60\n }\n scheduler = BackgroundScheduler(\n # daemon=True, \n jobstores=jobstores, \n executors=executors, \n job_defaults=job_defaults, \n timezone=pytz.utc\n )\n scheduler.start()\n checkQueueJob = scheduler.add_job(checkQueue, trigger='interval', seconds=60)\n # testSchedJob = scheduler.add_job(testSched, trigger='interval', seconds=10)\n hourlyJob = scheduler.add_job(func=runHourly, trigger='cron', minute=45, second=30)\n weeklyJob = scheduler.add_job(func=runWeekly, trigger='cron', day_of_week='mon', hour=8, minute=30, second=0)\n return True\n \n \n\ndef runHourly():\n logger.info(f'runHourly...')\n with app.app_context():\n teams = pints.postgres.getTeams(db.engine)\n # teams = [team for team in teams if team['id'] == 5]\n for team in teams:\n logger.info(f\"team {team['id']}...\")\n jobUuids = fullRefresh(db.engine, team['id'])\n settings = pints.postgres.getSettings(db.engine, team['id'])\n if settings['notifications'].get('alerts', {}).get('slack', False):\n dt = datetime.datetime.utcnow().isoformat().replace('T', ' ')\n details = {\n 'status': 'pending',\n 'dependencies': jobUuids,\n 'type': 'sendNotifications',\n 'maxCreatedOn': dt,\n 'maxCanceledOn': dt,\n }\n jobUuid = uuid.uuid4().hex\n targetId = pints.postgres.addJob(db.engine, team['id'], details, jobUuid)\n messageId = pints.postgres.addMessage(db.engine, team['id'], targetId, details, jobUuid)\n logger.info(f'runHourly messageId... {messageId}')\n return True\n\ndef runWeekly():\n teams = pints.postgres.getTeams(db.engine)\n # teams = [team for team in teams if team['id'] == 5]\n for team in teams:\n runWeeklyTeam(db.engine, team['id'])\n\ndef runWeeklyTeam(engine, teamId):\n logger.info(f'runWeeklyTeam... {teamId}')\n settings = pints.postgres.getSettings(engine, teamId)\n logger.info(f'runWeeklyTeam settings... {settings}')\n if settings['notifications'].get('weekly', {}).get('slack', False):\n toSlack = metrics.getSlackMsg(engine, teamId)\n slackInfo = pints.postgres.getSlackInfo(engine, teamId)\n pints.slack.weekly(toSlack, slackInfo['bot_token'])\n return True\n\ndef runMonthly(engine):\n return True\n\ndef fullRefresh(engine, teamId):\n logger.info(f'fullRefresh...')\n jobUuids = pints.stripe.getAll(engine, teamId)\n logger.info(f'fullRefresh jobUuids: {jobUuids}')\n return jobUuids\n \ndef do_some_work(jobRow):\n logger.info(f'do_some_work... {jobRow}')\n if random.choice([True, False]):\n logger.info(f'do_some_work failed... {jobRow}')\n raise Exception\n else:\n logger.info(f'do_some_work SUCCESS... {jobRow}')\n\ndef testSched():\n logger.info(f'testSched...')\n return True\n\ndef checkQueue():\n logger.info(f'checkQueue...')\n gettingJobs = True\n while gettingJobs:\n jobRow, queueRow = pints.postgres.getMessages(db.engine)\n if jobRow:\n logger.info(f\"checkQueue jobRow: {jobRow}\")\n try:\n if jobRow['details']['type'] == 'sendNotifications':\n logger.info(f'sendNotifications...')\n lastJob = pints.postgres.getLastJob(db.engine, jobRow['team_id'], 'sendNotifications')\n if not lastJob:\n logger.info(f'adding first lastJob...')\n dt = datetime.datetime.utcnow().isoformat().replace('T', ' ')\n details = {\n 'maxCreatedOn': dt,\n 'maxCanceledOn': dt,\n 'type': 'sendNotifications',\n 'status': 'complete',\n }\n jobUuid = uuid.uuid4().hex\n pints.postgres.addJob(db.engine, jobRow['team_id'], details, jobUuid)\n lastJob = pints.postgres.getLastJob(db.engine, jobRow['team_id'], 'sendNotifications')\n logger.info(f'sendNotifications lastJob: {lastJob}')\n alerts = pints.postgres.getAlerts(db.engine, jobRow['team_id'], lastJob)\n logger.info(f'sendNotifications alerts: {alerts}')\n for alert in alerts:\n logger.info(f'sendNotifications alert: {alert}')\n # TODO send alert\n # pints.postgres.updateMessage(db.engine, alert['message_id'], {'status': 'sent'})\n settings = pints.postgres.getSettings(db.engine, jobRow['team_id'])\n d = {\n 'email': alert['email'],\n 'mrr': alert['mrr'],\n 'prev_mrr': alert['prev_mrr'],\n 'msg': f\"Originally signed up on {alert['customer_created_on2']} ({alert['created_days_ago']} days to convert)\",\n 'slackChannel': settings['notifications']['slackChannel']\n }\n slackInfo = pints.postgres.getSlackInfo(db.engine, jobRow['team_id'])\n if alert['alert_type'] == 'canceled':\n pints.slack.churnAlert(d, slackInfo['bot_token'])\n else:\n pints.slack.customerAlert(d, slackInfo['bot_token'])\n dt = datetime.datetime.utcnow().isoformat().replace('T', ' ')\n details = {\n 'maxCreatedOn': dt,\n 'maxCanceledOn': dt,\n }\n pints.postgres.updateJobStatus(db.engine, queueRow['target_id'], 'complete', None, details)\n except Exception as e:\n logger.error(f'checkQueue error: {str(e)}')\n pints.postgres.updateJobStatus(db.engine, queueRow['target_id'], 'error', str(e), None)\n raise e\n # if we want the job to run again, insert a new item to the message queue with this job id\n # con.execute(sql, (queue_item['target_id'],))\n else:\n logger.info(f'no jobs to run...')\n gettingJobs = False\n return True","sub_path":"backend/pints/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"55626366","text":"from doubly_linked_list import DoublyLinkedList, Node\nimport string\n\n\"\"\"\nInput example:\n2 4\n4 1\n9 2 5\n1 5\n\ni.e.\n1) Takes the values of each line and perform a multiplication\n2) Insertion sort the result with a doubly linked list implementation\n\nOutput example:\n[4,5,8,90]\n\n\"\"\"\ndef insertion_sort(lt, val):\n if lt.len == 0:\n lt.addNodeE(Node(val))\n else:\n current = lt.head\n while True:\n if current.val <= val:\n if current.next != None:\n current = current.next\n else:\n lt.addNodeE(Node(val))\n break\n else:\n node = Node(val)\n temp = current.prev\n current.setPrev(node)\n node.setNext(current)\n if temp != None:\n node.setPrev(temp)\n temp.setNext(node)\n else:\n lt.head = node\n lt.len += 1\n break\n return lt\n\nlt = DoublyLinkedList()\nf = open(\"insertion_example.txt\", \"r\")\nfor line in f:\n product = 1\n for char in line:\n if char == '\\n':\n break\n elif char != ' ':\n product *= int(char)\n insertion_sort(lt, product)\n\nlt.print()\n","sub_path":"insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"310244525","text":"import os\nimport tarfile\n\nimport h5py\nimport numpy\nimport six\nfrom six.moves import range, cPickle\n\nfrom fuel.converters.base import fill_hdf5_file\n\n\ndef cifar10(input_directory, save_path):\n \"\"\"Converts the CIFAR-10 dataset to HDF5.\n\n Converts the CIFAR-10 dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.CIFAR10`. The converted dataset is saved as\n 'cifar10.hdf5'.\n\n This method assumes the existence of the following file:\n `cifar-10-python.tar.gz`\n\n Parameters\n ----------\n input_directory : str\n Directory in which the required input files reside.\n save_path : str\n Where to save the converted dataset.\n\n \"\"\"\n h5file = h5py.File(save_path, mode=\"w\")\n input_file = os.path.join(input_directory, 'cifar-10-python.tar.gz')\n tar_file = tarfile.open(input_file, 'r:gz')\n\n train_batches = []\n for batch in range(1, 6):\n file = tar_file.extractfile(\n 'cifar-10-batches-py/data_batch_%d' % batch)\n try:\n if six.PY3:\n array = cPickle.load(file, encoding='latin1')\n else:\n array = cPickle.load(file)\n train_batches.append(array)\n finally:\n file.close()\n\n train_features = numpy.concatenate(\n [batch['data'].reshape(batch['data'].shape[0], 3, 32, 32)\n for batch in train_batches])\n train_labels = numpy.concatenate(\n [numpy.array(batch['labels'], dtype=numpy.uint8)\n for batch in train_batches])\n\n file = tar_file.extractfile('cifar-10-batches-py/test_batch')\n try:\n if six.PY3:\n test = cPickle.load(file, encoding='latin1')\n else:\n test = cPickle.load(file)\n finally:\n file.close()\n\n test_features = test['data'].reshape(test['data'].shape[0],\n 3, 32, 32)\n test_labels = numpy.array(test['labels'], dtype=numpy.uint8)\n\n data = (('train', 'features', train_features),\n ('train', 'targets', train_labels),\n ('test', 'features', test_features),\n ('test', 'targets', test_labels))\n fill_hdf5_file(h5file, data)\n h5file['features'].dims[0].label = 'batch'\n h5file['features'].dims[1].label = 'channel'\n h5file['features'].dims[2].label = 'height'\n h5file['features'].dims[3].label = 'width'\n h5file['targets'].dims[0].label = 'batch'\n\n h5file.flush()\n h5file.close()\n","sub_path":"fuel/converters/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"4320299","text":"#!/usr/bin/env python\n\nimport actionlib\nimport rospy\nimport RPi.GPIO as GPIO\nfrom fhu_auto.msg import door_controlAction, door_controlFeedback, door_controlResult\nfrom std_msgs.msg import String\n\nclass ActionServer():\n\n\tdef __init__(self):\n\t\t# Action Server Init\n\t\tself.action_name = \"door_control_as\"\n\t\tself.a_server = actionlib.SimpleActionServer(self.action_name, door_controlAction, execute_cb=self.execute_cb, auto_start=False)\n\t\tself.a_server.start()\n\n\t\t# R-Pi Init\n\t\tGPIO.setmode(GPIO.BCM)\t\t\t#use GPIO numbers\n\t\tup_gpio = 19\n\t\tdown_gpio = 26\n\n\t\t# Set up GPIO and ensure relays are off\n\t\tGPIO.setup(up_gpio, GPIO.OUT)\n\t\tGPIO.setup(down_gpio, GPIO.OUT)\n\t\tGPIO.output(up_gpio, GPIO.HIGH)\n\t\tGPIO.output(down_gpio, GPIO.HIGH)\n\n\t\t# Variables\n\t\tself.doorTime = rospy.Duration(17)\t\t#door time should be 17 seconds\n\t\tself.feedback = door_controlFeedback()\n\t\tself.result = door_controlResult() \n\n\tdef\ttimer_cb(self, event):\n\t\tself.timer = True\n\t\t\n\tdef execute_cb(self, goal):\n\t\tself.timer = False\n\t\trate = rospy.Rate(10)\n\n\t\tif self.a_server.is_preempt_requested():\n\t\t\trospy.loginfo('%s: Preempted' % self.action_name)\n\t\t\tself.success = False\n\n\t\telse:\n\t\t\tif goal.command == 'up':\n\t\t\t\tGPIO.output(down_gpio, GPIO.HIGH)\n\t\t\t\tGPIO.output(up_gpio, GPIO.LOW)\n\t\t\t\trospy.Timer(self.doorTime, self.timer_cb, oneshot=True)\n\n\t\t\t\t# Publish feedback until door is open\n\t\t\t\twhile self.timer is False:\n\t\t\t\t\tself.feedback.status = 'Raising the gate...'\n\t\t\t\t\tself.a_server.publish_feedback(self.feedback)\n\t\t\t\t\trate.sleep()\n\n\t\t\t\tGPIO.output(up_gpio, GPIO.HIGH)\n\t\t\t\tself.result.finished_state = 'Open'\n\t\t\t\tself.success = True\n\n\t\t\telif goal.command == 'down':\n\t\t\t\tGPIO.output(up_gpio, GPIO.HIGH)\n\t\t\t\tGPIO.output(down_gpio, GPIO.LOW)\n\t\t\t\trospy.Timer(self.doorTime, self.timer_cb, oneshot=True)\n\n\t\t\t\t# Publish feedback until door is closed\n\t\t\t\twhile self.timer is False:\n\t\t\t\t\tself.feedback.status = 'Lowering the gate...'\n\t\t\t\t\tself.a_server.publish_feedback(self.feedback)\n\t\t\t\t\trate.sleep()\n\t\t\t\t\t\n\t\t\t\tGPIO.output(down_gpio, GPIO.HIGH)\n\t\t\t\tself.result.finished_state = 'Closed'\n\t\t\t\tself.success = True\n\n\t\t\telse:\n\t\t\t\tGPIO.output(down_gpio, GPIO.HIGH)\n\t\t\t\tGPIO.output(up_gpio, GPIO.HIGH)\n\t\t\t\tself.feedback.status = 'Error'\n\t\t\t\tself.a_server.publish_feedback(self.feedback)\n\t\t\t\tself.success = False\n\n\t\t\t\n\n\t\tif self.success:\n\t\t\tself.a_server.set_succeeded(self.result)\n\n\n\t\t\t\nif __name__ == '__main__':\n\trospy.init_node(\"door_action_server\")\n\ts = ActionServer()\n\tprint('Running...')\n\trospy.spin()\n\t# Safely shutdown GPIO\n\tGPIO.cleanup()\n\n","sub_path":"scripts/door_auto_server.py","file_name":"door_auto_server.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"51997440","text":"\"\"\"\nDefines methods useful to analise 3D meshes.\n\"\"\"\n\nfrom __future__ import division, print_function\nimport vtk\nimport numpy as np\n\nimport vtkplotter.utils as vu\nimport vtkplotter.colors as vc\nimport vtkplotter.vtkio as vio\nimport vtkplotter.shapes as vs\nfrom vtkplotter.actors import Actor, Assembly\nfrom vtk.util.numpy_support import numpy_to_vtk\n\n\ndef spline(points, smooth=0.5, degree=2,\n s=2, c='b', alpha=1., nodes=False, legend=None, res=20):\n '''\n Return a vtkActor for a spline that doesnt necessarly pass exactly throught all points.\n\n Options:\n\n smooth, smoothing factor:\n 0 = interpolate points exactly, \n 1 = average point positions\n\n degree = degree of the spline (1 1:\n asse = Assembly(acts)\n return asse\n else:\n return actor\n\n\ndef delaunay2D(plist, tol=None, c='gold', alpha=0.5, wire=False, bc=None, edges=False,\n legend=None, texture=None):\n '''\n Create a mesh from points in the XY plane.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/delaunay2d.py)\n '''\n src = vtk.vtkPointSource()\n src.SetNumberOfPoints(len(plist))\n src.Update()\n pd = src.GetOutput()\n for i, p in enumerate(plist):\n pd.GetPoints().SetPoint(i, p)\n delny = vtk.vtkDelaunay2D()\n vu.setInput(delny, pd)\n if tol:\n delny.SetTolerance(tol)\n delny.Update()\n return Actor(delny.GetOutput(), c, alpha, wire, bc, edges, legend, texture)\n\n\ndef normals(actor, ratio=5, c=(0.6, 0.6, 0.6), alpha=0.8, legend=None):\n '''\n Build a vtkActor made of the normals at vertices shown as arrows\n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py) \n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fatlimb.py) \n '''\n maskPts = vtk.vtkMaskPoints()\n maskPts.SetOnRatio(ratio)\n maskPts.RandomModeOff()\n src = actor.polydata()\n vu.setInput(maskPts, src)\n arrow = vtk.vtkArrowSource()\n arrow.SetTipRadius(0.075)\n glyph = vtk.vtkGlyph3D()\n glyph.SetSourceConnection(arrow.GetOutputPort())\n glyph.SetInputConnection(maskPts.GetOutputPort())\n glyph.SetVectorModeToUseNormal()\n b = src.GetBounds()\n sc = max([b[1]-b[0], b[3]-b[2], b[5]-b[4]])/20.\n glyph.SetScaleFactor(sc)\n glyph.SetColorModeToColorByVector()\n glyph.SetScaleModeToScaleByVector()\n glyph.OrientOn()\n glyph.Update()\n glyphMapper = vtk.vtkPolyDataMapper()\n glyphMapper.SetInputConnection(glyph.GetOutputPort())\n glyphMapper.SetScalarModeToUsePointFieldData()\n glyphMapper.SetColorModeToMapScalars()\n glyphMapper.ScalarVisibilityOn()\n glyphMapper.SelectColorArray(\"Elevation\")\n glyphActor = vtk.vtkActor()\n glyphActor.SetMapper(glyphMapper)\n glyphActor.GetProperty().EdgeVisibilityOff()\n glyphActor.GetProperty().SetColor(vc.getColor(c))\n # check if color string contains a float, in this case ignore alpha\n al = vc.getAlpha(c)\n if al:\n alpha = al\n glyphActor.GetProperty().SetOpacity(alpha)\n aactor = Assembly([actor, glyphActor], legend=legend)\n return aactor\n\n\ndef curvature(actor, method=1, r=1, alpha=1, lut=None, legend=None):\n '''\n Build a copy of vtkActor that contains the color coded surface\n curvature following four different ways to calculate it:\n method = 0-gaussian, 1-mean, 2-max, 3-min\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py)\n '''\n poly = actor.polydata()\n cleaner = vtk.vtkCleanPolyData()\n vu.setInput(cleaner, poly)\n curve = vtk.vtkCurvatures()\n curve.SetInputConnection(cleaner.GetOutputPort())\n curve.SetCurvatureType(method)\n curve.InvertMeanCurvatureOn()\n curve.Update()\n print('CurvatureType set to:', method)\n if not lut:\n lut = vtk.vtkLookupTable()\n lut.SetNumberOfColors(256)\n lut.SetHueRange(0.15, 1)\n lut.SetSaturationRange(1, 1)\n lut.SetValueRange(1, 1)\n lut.SetAlphaRange(alpha, 1)\n b = poly.GetBounds()\n sc = max([b[1]-b[0], b[3]-b[2], b[5]-b[4]])\n lut.SetRange(-0.01/sc*r, 0.01/sc*r)\n cmapper = vtk.vtkPolyDataMapper()\n cmapper.SetInputConnection(curve.GetOutputPort())\n cmapper.SetLookupTable(lut)\n cmapper.SetUseLookupTableScalarRange(1)\n cactor = vtk.vtkActor()\n cactor.SetMapper(cmapper)\n return cactor\n\n\ndef boundaries(actor, c='p', lw=5, legend=None):\n '''Build a copy of actor that shows the boundary lines of its surface.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py) \n '''\n fe = vtk.vtkFeatureEdges()\n vu.setInput(fe, actor.polydata())\n fe.BoundaryEdgesOn()\n fe.FeatureEdgesOn()\n fe.ManifoldEdgesOn()\n fe.NonManifoldEdgesOn()\n fe.ColoringOff()\n fe.Update()\n bactor = Actor(fe.GetOutput(), c=c, alpha=1, legend=legend)\n bactor.GetProperty().SetLineWidth(lw)\n return bactor\n\n\ndef extractLargestRegion(actor, legend=None):\n '''Keep only the largest connected part of a mesh and discard all the smaller pieces.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/largestregion.py)\n '''\n conn = vtk.vtkConnectivityFilter()\n conn.SetExtractionModeToLargestRegion()\n conn.ScalarConnectivityOff()\n poly = actor.polydata(True)\n vu.setInput(conn, poly)\n conn.Update()\n epoly = conn.GetOutput()\n if legend is True:\n legend = actor.legend\n eact = Actor(epoly, legend)\n pr = vtk.vtkProperty()\n pr.DeepCopy(actor.GetProperty())\n eact.SetProperty(pr)\n return eact\n \n\ndef align(source, target, iters=100, rigid=False, method='ICP', legend=None):\n '''\n Return a copy of source actor which is aligned to\n target actor through vtkIterativeClosestPointTransform\n or vtkProcrustesAlignmentFilter classes.\n \n With ICP: the core of the algorithm is to match each vertex in one surface with\n the closest surface point on the other, then apply the transformation \n that modify one surface to best match the other (in the least-square sense). \n \n With Procrustes: takes a set of points and aligns them in a least-squares sense \n to their mutual mean. The algorithm is iterated until convergence, \n as the mean must be recomputed after each alignment.\n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/align1.py)\n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/align2.py)\n '''\n if isinstance(source, Actor): source = source.polydata()\n if isinstance(target, Actor): target = target.polydata()\n \n if method.lower() == 'icp':\n icp = vtk.vtkIterativeClosestPointTransform()\n icp.SetSource(source)\n icp.SetTarget(target)\n icp.SetMaximumNumberOfIterations(iters)\n if rigid:\n icp.GetLandmarkTransform().SetModeToRigidBody()\n icp.StartByMatchingCentroidsOn()\n icp.Update()\n icpTransformFilter = vtk.vtkTransformPolyDataFilter()\n vu.setInput(icpTransformFilter, source)\n icpTransformFilter.SetTransform(icp)\n icpTransformFilter.Update()\n poly = icpTransformFilter.GetOutput()\n actor = Actor(poly, legend=legend)\n actor.info['transform'] = icp.GetLandmarkTransform()\n return actor\n \n elif method.lower() == 'procrustes': \n if source.GetNumberOfPoints() != target.GetNumberOfPoints():\n vc.printc('Procrustes error in align():' , c=1)\n vc.printc(' source and target have different nr of points', c=1)\n exit(0)\n group = vtk.vtkMultiBlockDataGroupFilter()\n group.AddInputData(source)\n group.AddInputData(target)\n procrustes = vtk.vtkProcrustesAlignmentFilter()\n procrustes.StartFromCentroidOn()\n procrustes.SetInputConnection(group.GetOutputPort())\n if rigid:\n procrustes.GetLandmarkTransform().SetModeToRigidBody()\n procrustes.Update()\n poly = procrustes.GetOutput().GetBlock(0)\n actor = Actor(poly, legend=legend)\n actor.info['transform'] = procrustes.GetLandmarkTransform()\n return actor\n \n else:\n vc.printc('Align error: Method must be either ICP or Procrustes.', c=1)\n exit(0)\n\n\n################# working with point clouds\n \ndef fitLine(points, c='orange', lw=1, alpha=0.6, legend=None):\n '''\n Fits a line through points.\n\n Extra info is stored in actor.slope, actor.center, actor.variances\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/fitline.py)\n '''\n data = np.array(points)\n datamean = data.mean(axis=0)\n uu, dd, vv = np.linalg.svd(data - datamean)\n vv = vv[0]/np.linalg.norm(vv[0])\n # vv contains the first principal component, i.e. the direction\n # vector of the best fit line in the least squares sense.\n xyz_min = points.min(axis=0)\n xyz_max = points.max(axis=0)\n a = np.linalg.norm(xyz_min - datamean)\n b = np.linalg.norm(xyz_max - datamean)\n p1 = datamean - a*vv\n p2 = datamean + b*vv\n l = vs.line(p1, p2, c=c, lw=lw, alpha=alpha)\n l.info['slope'] = vv\n l.info['center'] = datamean\n l.info['variances'] = dd\n return l\n\n\ndef fitPlane(points, c='g', bc='darkgreen', alpha=0.8, legend=None):\n '''\n Fits a plane to a set of points.\n\n Extra info is stored in actor.normal, actor.center, actor.variance\n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/fitline.py) \n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fitplanes.py)\n '''\n data = np.array(points)\n datamean = data.mean(axis=0)\n uu, dd, vv = np.linalg.svd(data - datamean)\n xyz_min = points.min(axis=0)\n xyz_max = points.max(axis=0)\n s = np.linalg.norm(xyz_max - xyz_min)\n n = np.cross(vv[0], vv[1])\n pla = vs.plane(datamean, n, s, s, c, bc, alpha, legend, None)\n pla.info['normal'] = n\n pla.info['center'] = datamean\n pla.info['variance'] = dd[2]\n return pla\n\n\ndef fitSphere(coords, c='r', alpha=1, wire=1, legend=None):\n '''\n Fits a sphere to a set of points.\n\n Extra info is stored in actor.radius, actor.center, actor.residue\n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fitspheres1.py)\n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fitspheres2.py)\n '''\n coords = np.array(coords)\n n = len(coords)\n A = np.zeros((n, 4))\n A[:, :-1] = coords*2\n A[:, 3] = 1\n f = np.zeros((n, 1))\n x = coords[:, 0]\n y = coords[:, 1]\n z = coords[:, 2]\n f[:, 0] = x*x + y*y + z*z\n C, residue, rank, sv = np.linalg.lstsq(A, f) # solve AC=f\n if rank < 4:\n return None\n t = (C[0]*C[0]) + (C[1]*C[1]) + (C[2]*C[2]) + C[3]\n radius = np.sqrt(t)[0]\n center = np.array([C[0][0], C[1][0], C[2][0]])\n if len(residue):\n residue = np.sqrt(residue[0])/n\n else:\n residue = 0\n s = vs.sphere(center, radius, c, alpha, wire=wire, legend=legend)\n s.info['radius'] = radius\n s.info['center'] = center\n s.info['residue'] = residue\n return s\n\n\ndef pca(points, pvalue=.95, c='c', alpha=0.5, pcaAxes=False, legend=None):\n '''\n Show the oriented PCA ellipsoid that contains fraction pvalue of points.\n\n axes = True, show the 3 PCA semi axes\n\n Extra info is stored in actor.sphericity, actor.va, actor.vb, actor.vc\n (sphericity = 1 for a perfect sphere)\n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py)\n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/cell_main.py)\n '''\n try:\n from scipy.stats import f\n except:\n vc.printc(\"Error in ellipsoid(): scipy not installed. Skip.\", c=1)\n return None\n if isinstance(points, vtk.vtkActor):\n points = points.coordinates()\n if len(points) == 0:\n return None\n P = np.array(points, ndmin=2, dtype=float)\n cov = np.cov(P, rowvar=0) # covariance matrix\n U, s, R = np.linalg.svd(cov) # singular value decomposition\n p, n = s.size, P.shape[0]\n fppf = f.ppf(pvalue, p, n-p)*(n-1)*p*(n+1)/n/(n-p) # f % point function\n ua, ub, uc = np.sqrt(s*fppf)*2 # semi-axes (largest first)\n center = np.mean(P, axis=0) # centroid of the hyperellipsoid\n sphericity = (((ua-ub)/(ua+ub))**2\n + ((ua-uc)/(ua+uc))**2\n + ((ub-uc)/(ub+uc))**2)/3. * 4.\n elliSource = vtk.vtkSphereSource()\n elliSource.SetThetaResolution(48)\n elliSource.SetPhiResolution(48)\n matri = vtk.vtkMatrix4x4()\n matri.DeepCopy((R[0][0] * ua, R[1][0] * ub, R[2][0] * uc, center[0],\n R[0][1] * ua, R[1][1] * ub, R[2][1] * uc, center[1],\n R[0][2] * ua, R[1][2] * ub, R[2][2] * uc, center[2], 0, 0, 0, 1))\n vtra = vtk.vtkTransform()\n vtra.SetMatrix(matri)\n ftra = vtk.vtkTransformFilter()\n ftra.SetTransform(vtra)\n ftra.SetInputConnection(elliSource.GetOutputPort())\n ftra.Update()\n actor_elli = Actor(ftra.GetOutput(), c, alpha, legend=legend)\n actor_elli.GetProperty().BackfaceCullingOn()\n actor_elli.GetProperty().SetInterpolationToPhong()\n if pcaAxes:\n axs = []\n for ax in ([1, 0, 0], [0, 1, 0], [0, 0, 1]):\n l = vtk.vtkLineSource()\n l.SetPoint1([0, 0, 0])\n l.SetPoint2(ax)\n l.Update()\n t = vtk.vtkTransformFilter()\n t.SetTransform(vtra)\n vu.setInput(t, l.GetOutput())\n t.Update()\n axs.append(Actor(t.GetOutput(), c, alpha))\n finact = Assembly([actor_elli]+axs, legend=legend)\n else:\n finact = actor_elli\n finact.info['sphericity'] = sphericity\n finact.info['va'] = ua\n finact.info['vb'] = ub\n finact.info['vc'] = uc\n return finact\n\n\ndef smoothLaplacian(actor, niter=15, relaxfact=0.1, edgeAngle=15, featureAngle=60):\n '''\n Adjust mesh point positions using Laplacian smoothing.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/mesh_smoothers.py)\n '''\n poly = actor.polydata()\n cl = vtk.vtkCleanPolyData()\n vu.setInput(cl, poly)\n cl.Update()\n poly = cl.GetOutput() # removes the boudaries duplication\n smoothFilter = vtk.vtkSmoothPolyDataFilter()\n smoothFilter.SetInputData(poly)\n smoothFilter.SetNumberOfIterations(niter)\n smoothFilter.SetRelaxationFactor(relaxfact)\n smoothFilter.SetEdgeAngle(edgeAngle)\n smoothFilter.SetFeatureAngle(featureAngle)\n smoothFilter.BoundarySmoothingOn()\n smoothFilter.FeatureEdgeSmoothingOn()\n smoothFilter.GenerateErrorScalarsOn()\n smoothFilter.Update()\n return align(smoothFilter.GetOutput(), poly)\n\n\ndef smoothWSinc(actor, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60):\n '''\n Adjust mesh point positions using the windowed sinc function interpolation kernel.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/mesh_smoothers.py)\n '''\n poly = actor.polydata()\n cl = vtk.vtkCleanPolyData()\n vu.setInput(cl, poly)\n cl.Update()\n poly = cl.GetOutput() # removes the boudaries duplication\n smoothFilter = vtk.vtkWindowedSincPolyDataFilter()\n vu.setInput(smoothFilter, poly)\n smoothFilter.SetNumberOfIterations(niter)\n smoothFilter.SetEdgeAngle(edgeAngle)\n smoothFilter.SetFeatureAngle(featureAngle)\n smoothFilter.SetPassBand(passBand)\n smoothFilter.NormalizeCoordinatesOn()\n smoothFilter.NonManifoldSmoothingOn()\n smoothFilter.FeatureEdgeSmoothingOn()\n smoothFilter.BoundarySmoothingOn()\n smoothFilter.Update()\n return align(smoothFilter.GetOutput(), poly)\n\n\ndef smoothMLS3D(actors, neighbours=10):\n '''\n A time sequence of actors is being smoothed in 4D \n using a MLS (Moving Least Squares) variant.\n Time assciated to an actor must be specified in advance with actor.time(t).\n Data itself can suggest a meaningful time separation based on the spatial \n distribution of points.\n \n neighbours, fixed nr of neighbours in space-time to take into account in fit.\n '''\n from scipy.spatial import KDTree\n \n coords4d = []\n for a in actors: # build the list of 4d coordinates\n coords3d = a.coordinates() \n n = len(coords3d) \n pttimes = [[a.time()]]*n \n coords4d += np.append(coords3d, pttimes, axis=1).tolist()\n \n avedt = float(actors[-1].time()-actors[0].time())/len(actors)\n print(\"Average time separation between actors dt =\", round(avedt, 3)) \n \n coords4d = np.array(coords4d)\n newcoords4d = []\n kd = KDTree(coords4d, leafsize=neighbours)\n suggest=''\n \n pb = vio.ProgressBar(0, len(coords4d))\n for i in pb.range():\n mypt = coords4d[i]\n \n #dr = np.sqrt(3*dx**2+dt**2)\n #iclosest = kd.query_ball_point(mypt, r=dr)\n #dists, iclosest = kd.query(mypt, k=None, distance_upper_bound=dr)\n dists, iclosest = kd.query(mypt, k=neighbours)\n closest = coords4d[iclosest]\n \n nc = len(closest)\n if nc >= neighbours and nc > 5:\n m = np.linalg.lstsq(closest, [1.]*nc, rcond=None)[0]\n vers = m/np.linalg.norm(m)\n hpcenter = np.mean(closest, axis=0) # hyperplane center\n dist = np.dot(mypt-hpcenter, vers)\n projpt = mypt - dist*vers\n newcoords4d.append(projpt)\n \n if not i%1000: # work out some stats\n v = np.std(closest, axis=0)\n vx = round((v[0]+v[1]+v[2])/3, 3)\n suggest='data suggest dt='+str(vx)\n \n pb.print(suggest)\n newcoords4d = np.array(newcoords4d)\n\n ctimes = newcoords4d[:, 3]\n ccoords3d = np.delete(newcoords4d, 3, axis=1) # get rid of time\n act = vs.points(ccoords3d)\n act.pointColors(ctimes, cmap='jet') # use a colormap to associate a color to time\n return act\n \n \ndef smoothMLS2D(actor, f=0.2, decimate=1, recursive=0, showNPlanes=0):\n '''\n Smooth actor or points with a Moving Least Squares variant.\n The list actor.variances contain the residue calculated for each point.\n Input actor's polydata is modified.\n\n Options:\n\n f, smoothing factor - typical range s [0,2]\n\n decimate, decimation factor (an integer number) \n\n recursive, move points while algorithm proceedes\n\n showNPlanes, build an actor showing the fitting plane for N random points \n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/mesh_smoothers.py) \n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/moving_least_squares2D.py) \n [**Example3**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/recosurface.py) \n '''\n coords = actor.coordinates()\n ncoords = len(coords)\n Ncp = int(ncoords*f/100)\n nshow = int(ncoords/decimate)\n if showNPlanes:\n ndiv = int(nshow/showNPlanes*decimate)\n\n if Ncp < 5:\n vc.printc('Please choose a higher fraction than '+str(f), c=1)\n Ncp = 5\n print('smoothMLS: Searching #neighbours, #pt:', Ncp, ncoords)\n\n poly = actor.polydata(True)\n vpts = poly.GetPoints()\n locator = vtk.vtkPointLocator()\n locator.SetDataSet(poly)\n locator.BuildLocator()\n vtklist = vtk.vtkIdList()\n variances, newsurf, acts = [], [], []\n pb = vio.ProgressBar(0, ncoords)\n for i, p in enumerate(coords):\n pb.print('smoothing...')\n if i % decimate:\n continue\n\n locator.FindClosestNPoints(Ncp, p, vtklist)\n points = []\n for j in range(vtklist.GetNumberOfIds()):\n trgp = [0, 0, 0]\n vpts.GetPoint(vtklist.GetId(j), trgp)\n points.append(trgp)\n if len(points) < 5:\n continue\n\n points = np.array(points)\n pointsmean = points.mean(axis=0) # plane center\n uu, dd, vv = np.linalg.svd(points-pointsmean)\n a, b, c = np.cross(vv[0], vv[1]) # normal\n d, e, f = pointsmean # plane center\n x, y, z = p\n t = (a*d - a*x + b*e - b*y + c*f - c*z) # /(a*a+b*b+c*c)\n newp = [x+t*a, y+t*b, z+t*c]\n variances.append(dd[2])\n newsurf.append(newp)\n if recursive:\n vpts.SetPoint(i, newp)\n\n if showNPlanes and not i % ndiv:\n plane = fitPlane(points, alpha=0.3) # fitting plane\n iapts = vs.points(points) # blue points\n acts += [plane, iapts]\n\n if decimate == 1 and not recursive:\n for i in range(ncoords):\n vpts.SetPoint(i, newsurf[i])\n\n actor.info['variances'] = np.array(variances)\n\n if showNPlanes:\n apts = vs.points(newsurf, c='r 0.6', r=2)\n ass = Assembly([apts]+acts)\n return ass # NB: a demo actor is returned\n\n return actor # NB: original actor is modified\n\n\ndef smoothMLS1D(actor, f=0.2, showNLines=0):\n '''\n Smooth actor or points with a Moving Least Squares variant.\n The list actor.variances contain the residue calculated for each point.\n Input actor's polydata is modified.\n\n Options:\n\n f, smoothing factor - typical range s [0,2]\n\n showNLines, build an actor showing the fitting line for N random points \n\n [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/moving_least_squares1D.py) \n [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/skeletonize.py) \n\n ![skel](https://user-images.githubusercontent.com/32848391/46820954-c5f13b00-cd87-11e8-87aa-286528a09de8.png)\n '''\n coords = actor.coordinates()\n ncoords = len(coords)\n Ncp = int(ncoords*f/10)\n nshow = int(ncoords)\n if showNLines:\n ndiv = int(nshow/showNLines)\n\n if Ncp < 3:\n vc.printc('Please choose a higher fraction than '+str(f), c=1)\n Ncp = 3\n\n poly = actor.polydata(True)\n vpts = poly.GetPoints()\n locator = vtk.vtkPointLocator()\n locator.SetDataSet(poly)\n locator.BuildLocator()\n vtklist = vtk.vtkIdList()\n variances, newline, acts = [], [], []\n for i, p in enumerate(coords):\n\n locator.FindClosestNPoints(Ncp, p, vtklist)\n points = []\n for j in range(vtklist.GetNumberOfIds()):\n trgp = [0, 0, 0]\n vpts.GetPoint(vtklist.GetId(j), trgp)\n points.append(trgp)\n if len(points) < 2:\n continue\n\n points = np.array(points)\n pointsmean = points.mean(axis=0) # plane center\n uu, dd, vv = np.linalg.svd(points-pointsmean)\n newp = np.dot(p-pointsmean, vv[0])*vv[0] + pointsmean\n variances.append(dd[1]+dd[2])\n newline.append(newp)\n\n if showNLines and not i % ndiv:\n fline = fitLine(points, lw=4, alpha=1) # fitting plane\n iapts = vs.points(points) # blue points\n acts += [fline, iapts]\n\n for i in range(ncoords):\n vpts.SetPoint(i, newline[i])\n\n if showNLines:\n apts = vs.points(newline, c='r 0.6', r=2)\n ass = Assembly([apts]+acts)\n return ass # NB: a demo actor is returned\n\n actor.info['variances'] = np.array(variances)\n return actor # NB: original actor is modified\n\n\ndef booleanOperation(actor1, actor2, operation='plus', c=None, alpha=1,\n wire=False, bc=None, edges=False, legend=None, texture=None):\n '''Volumetric union, intersection and subtraction of surfaces\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/boolean.py) \n '''\n try:\n bf = vtk.vtkBooleanOperationPolyDataFilter()\n except AttributeError:\n vc.printc('Boolean operation only possible for vtk version >= 8', c='r')\n return None\n poly1 = actor1.polydata(True)\n poly2 = actor2.polydata(True)\n if operation.lower() == 'plus':\n bf.SetOperationToUnion()\n elif operation.lower() == 'intersect':\n bf.SetOperationToIntersection()\n elif operation.lower() == 'minus':\n bf.SetOperationToDifference()\n bf.ReorientDifferenceCellsOn()\n if vu.vtkMV:\n bf.SetInputData(0, poly1)\n bf.SetInputData(1, poly2)\n else:\n bf.SetInputConnection(0, poly1.GetProducerPort())\n bf.SetInputConnection(1, poly2.GetProducerPort())\n bf.Update()\n actor = Actor(bf.GetOutput(),\n c, alpha, wire, bc, edges, legend, texture)\n return actor\n\n\ndef surfaceIntersection(actor1, actor2, tol=1e-06, lw=3,\n c=None, alpha=1, legend=None):\n '''Intersect 2 surfaces and return a line actor.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/surfIntersect.py) \n '''\n try:\n bf = vtk.vtkIntersectionPolyDataFilter()\n except AttributeError:\n vc.printc('surfaceIntersection only possible for vtk version > 6', c='r')\n return None\n poly1 = actor1.polydata(True)\n poly2 = actor2.polydata(True)\n bf.SetInputData(0, poly1)\n bf.SetInputData(1, poly2)\n bf.Update()\n if c is None:\n c = actor1.GetProperty().GetColor()\n actor = Actor(bf.GetOutput(), c, alpha, 0, legend=legend)\n actor.GetProperty().SetLineWidth(lw)\n return actor\n\n\ndef probeLine(img, p1, p2, res=100):\n '''\n Takes a vtkImageData and probes its scalars along a line defined by 2 points. \n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/volumetric/probeLine.py)\n\n ![probeline](https://user-images.githubusercontent.com/32848391/48198460-3aa0a080-e359-11e8-982d-23fadf4de66f.jpg)\n '''\n line = vtk.vtkLineSource()\n line.SetResolution(res)\n line.SetPoint1(p1)\n line.SetPoint2(p2)\n probeFilter = vtk.vtkProbeFilter()\n probeFilter.SetSourceData(img)\n probeFilter.SetInputConnection(line.GetOutputPort())\n probeFilter.Update()\n\n lact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn\n mapper = lact.GetMapper()\n mapper.SetScalarRange(img.GetScalarRange())\n return lact\n\n\ndef probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)):\n '''\n Takes a vtkImageData and probes its scalars on a plane. \n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/volumetric/probePlane.py)\n\n (https://user-images.githubusercontent.com/32848391/48198461-3aa0a080-e359-11e8-8c29-18f287f105e6.jpg)\n '''\n plane = vtk.vtkPlane()\n plane.SetOrigin(origin)\n plane.SetNormal(normal)\n\n planeCut = vtk.vtkCutter()\n planeCut.SetInputData(img)\n planeCut.SetCutFunction(plane)\n planeCut.Update()\n cutActor = Actor(planeCut.GetOutput(), c=None) # ScalarVisibilityOn\n cutMapper = cutActor.GetMapper()\n cutMapper.SetScalarRange(img.GetPointData().GetScalars().GetRange())\n return cutActor\n\n\ndef imageOperation(image1, operation='+', image2=None):\n '''\n Perform operations with vtkImageData objects. Image2 can contain a constant value.\n Possible operations are: +, -, /, 1/x, sin, cos, exp, log, abs, **2, sqrt, min, \n max, atan, atan2, median, mag, dot, gradient, divergence, laplacian.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/volumetric/imageOperations.py)\n\n ![gradient](https://user-images.githubusercontent.com/32848391/48198940-d1ba2800-e35a-11e8-96a7-ffbff797f165.jpg)\n '''\n op = operation.lower()\n\n if op in ['median']:\n mf = vtk.vtkImageMedian3D()\n vu.setInput(mf, image1)\n mf.Update()\n return mf.GetOutput()\n elif op in ['mag']:\n mf = vtk.vtkImageMagnitude()\n vu.setInput(mf, image1)\n mf.Update()\n return mf.GetOutput()\n elif op in ['dot', 'dotproduct']:\n mf = vtk.vtkImageDotProduct()\n mf.SetInput1Data(image1)\n mf.SetInput2Data(image2)\n mf.Update()\n return mf.GetOutput()\n elif op in ['grad', 'gradient']:\n mf = vtk.vtkImageGradient()\n mf.SetDimensionality(3)\n vu.setInput(mf, image1)\n mf.Update()\n return mf.GetOutput()\n elif op in ['div', 'divergence']:\n mf = vtk.vtkImageDivergence()\n vu.setInput(mf, image1)\n mf.Update()\n return mf.GetOutput()\n elif op in ['laplacian']:\n mf = vtk.vtkImageLaplacian()\n mf.SetDimensionality(3)\n vu.setInput(mf, image1)\n mf.Update()\n return mf.GetOutput()\n\n mat = vtk.vtkImageMathematics()\n mat.SetInput1Data(image1)\n K = None\n if image2:\n if isinstance(image2, vtk.vtkImageData):\n mat.SetInput2Data(image2)\n else: # assume image2 is a constant value\n K = image2\n mat.SetConstantK(K)\n mat.SetConstantC(K)\n\n if op in ['+', 'add', 'plus']:\n if K:\n mat.SetOperationToAddConstant()\n else:\n mat.SetOperationToAdd()\n\n elif op in ['-', 'subtract', 'minus']:\n if K:\n mat.SetConstantC(-K)\n mat.SetOperationToAddConstant()\n else:\n mat.SetOperationToSubtract()\n\n elif op in ['*', 'multiply', 'times']:\n if K:\n mat.SetOperationToMultiplyByK()\n else:\n mat.SetOperationToMultiply()\n\n elif op in ['/', 'divide']:\n if K:\n mat.SetConstantK(1.0/K)\n mat.SetOperationToMultiplyByK()\n else:\n mat.SetOperationToDivide()\n\n elif op in ['1/x', 'invert']:\n mat.SetOperationToInvert()\n elif op in ['sin']:\n mat.SetOperationToSin()\n elif op in ['cos']:\n mat.SetOperationToCos()\n elif op in ['exp']:\n mat.SetOperationToExp()\n elif op in ['log']:\n mat.SetOperationToLog()\n elif op in ['abs']:\n mat.SetOperationToAbsoluteValue()\n elif op in ['**2', 'square']:\n mat.SetOperationToSquare()\n elif op in ['sqrt', 'sqr']:\n mat.SetOperationToSquareRoot()\n elif op in ['min']:\n mat.SetOperationToMin()\n elif op in ['max']:\n mat.SetOperationToMax()\n elif op in ['atan']:\n mat.SetOperationToATAN()\n elif op in ['atan2']:\n mat.SetOperationToATAN2()\n else:\n vc.printc('Error in imageOperation: unknown operation', operation, c=1)\n exit()\n mat.Update()\n return mat.GetOutput()\n\n\ndef recoSurface(points, bins=256,\n c='gold', alpha=1, wire=False, bc='t', edges=False, legend=None):\n '''\n Surface reconstruction from sparse points.\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/recosurface.py) \n\n ![reco](https://user-images.githubusercontent.com/32848391/46817107-b3263880-cd7e-11e8-985d-f5d158992f0c.png)\n '''\n\n if isinstance(points, vtk.vtkActor):\n points = points.coordinates()\n N = len(points)\n if N < 50:\n print('recoSurface: Use at least 50 points.')\n return None\n points = np.array(points)\n\n ptsSource = vtk.vtkPointSource()\n ptsSource.SetNumberOfPoints(N)\n ptsSource.Update()\n vpts = ptsSource.GetOutput().GetPoints()\n for i, p in enumerate(points):\n vpts.SetPoint(i, p)\n polyData = ptsSource.GetOutput()\n\n distance = vtk.vtkSignedDistance()\n f = 0.1\n x0, x1, y0, y1, z0, z1 = polyData.GetBounds()\n distance.SetBounds(x0-(x1-x0)*f, x1+(x1-x0)*f,\n y0-(y1-y0)*f, y1+(y1-y0)*f,\n z0-(z1-z0)*f, z1+(z1-z0)*f)\n if polyData.GetPointData().GetNormals():\n distance.SetInputData(polyData)\n vu.setInput(distance, polyData)\n else:\n normals = vtk.vtkPCANormalEstimation()\n vu.setInput(normals, polyData)\n normals.SetSampleSize(int(N/50))\n normals.SetNormalOrientationToGraphTraversal()\n distance.SetInputConnection(normals.GetOutputPort())\n print('Recalculating normals for', N,\n 'points, sample size=', int(N/50))\n \n b = polyData.GetBounds()\n diagsize = np.sqrt((b[1]-b[0])**2 + (b[3]-b[2])**2 + (b[5]-b[4])**2)\n radius = diagsize/bins*5\n distance.SetRadius(radius)\n distance.SetDimensions(bins, bins, bins)\n distance.Update()\n\n print('Calculating mesh from points with R =', radius)\n surface = vtk.vtkExtractSurface()\n surface.SetRadius(radius * .99)\n surface.HoleFillingOn()\n surface.ComputeNormalsOff()\n surface.ComputeGradientsOff()\n surface.SetInputConnection(distance.GetOutputPort())\n surface.Update()\n return Actor(surface.GetOutput(), c, alpha, wire, bc, edges, legend)\n\n\ndef cluster(points, radius, legend=None):\n '''\n Clustering of points in space.\n radius, is the radius of local search.\n Individual subsets can be accessed through actor.clusters\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/clustering.py) \n\n ![cluster](https://user-images.githubusercontent.com/32848391/46817286-2039ce00-cd7f-11e8-8b29-42925e03c974.png)\n '''\n if isinstance(points, vtk.vtkActor):\n poly = points.polydata()\n else:\n src = vtk.vtkPointSource()\n src.SetNumberOfPoints(len(points))\n src.Update()\n vpts = src.GetOutput().GetPoints()\n for i, p in enumerate(points):\n vpts.SetPoint(i, p)\n poly = src.GetOutput()\n\n cluster = vtk.vtkEuclideanClusterExtraction()\n vu.setInput(cluster, poly)\n cluster.SetExtractionModeToAllClusters()\n cluster.SetRadius(radius)\n cluster.ColorClustersOn()\n cluster.Update()\n\n idsarr = cluster.GetOutput().GetPointData().GetArray('ClusterId')\n Nc = cluster.GetNumberOfExtractedClusters()\n\n sets = [[] for i in range(Nc)]\n for i, p in enumerate(points):\n sets[idsarr.GetValue(i)].append(p)\n\n acts = []\n for i, aset in enumerate(sets):\n acts.append(vs.points(aset, c=i))\n\n actor = Assembly(acts, legend=legend)\n\n actor.info['clusters'] = sets\n print('Nr. of extracted clusters', Nc)\n if Nc > 10:\n print('First ten:')\n for i in range(Nc):\n if i > 9:\n print('...')\n break\n print('Cluster #'+str(i)+', N =', len(sets[i]))\n print('Access individual clusters through attribute: actor.cluster')\n return actor\n\n\ndef removeOutliers(points, radius, c='k', alpha=1, legend=None):\n '''\n Remove outliers from a cloud of points within radius search\n\n [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/clustering.py) \n '''\n isactor = False\n if isinstance(points, vtk.vtkActor):\n isactor = True\n poly = points.polydata()\n else:\n src = vtk.vtkPointSource()\n src.SetNumberOfPoints(len(points))\n src.Update()\n vpts = src.GetOutput().GetPoints()\n for i, p in enumerate(points):\n vpts.SetPoint(i, p)\n poly = src.GetOutput()\n\n removal = vtk.vtkRadiusOutlierRemoval()\n vu.setInput(removal, poly)\n\n removal.SetRadius(radius)\n removal.SetNumberOfNeighbors(5)\n removal.GenerateOutliersOff()\n removal.Update()\n rpoly = removal.GetOutput()\n print(\"# of removed outlier points: \",\n removal.GetNumberOfPointsRemoved(), '/', poly.GetNumberOfPoints())\n outpts = []\n for i in range(rpoly.GetNumberOfPoints()):\n outpts.append(list(rpoly.GetPoint(i)))\n outpts = np.array(outpts)\n if not isactor:\n return outpts\n\n actor = vs.points(outpts, c=c, alpha=alpha, legend=legend)\n return actor # return same obj for concatenation\n","sub_path":"vtkplotter/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":44707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146114455","text":"# coding:utf-8\n\nimport logging\nimport requests\nfrom lxml import etree\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef get_proxy():\n \"\"\"获取一个随机代理\"\"\"\n try:\n response = requests.get('http://localhost:5000/get')\n if response.status_code == 200:\n proxy = response.json()\n if proxy:\n return proxy.get('proxy')\n except requests.RequestException as e:\n return None\n\n\nclass WeixinSpider(object):\n MAX_RETRY_TIME = 5\n\n def _get(self, url, use_proxy=False, retry_time=0):\n \"\"\"第一次请求,都不使用代理,只有请求失败后,才使用代理\"\"\"\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'\n }\n try:\n if use_proxy:\n proxy = get_proxy()\n if proxy:\n proxies = {\n \"http\": \"http://\" + proxy,\n \"https\": \"http://\" + proxy,\n }\n else:\n proxies = None\n response = requests.get(url, headers=headers, proxies=proxies,timeout=3)\n logging.info(url + '--->代理IP--->' + proxy)\n else:\n response = requests.get(url, headers=headers)\n response.encoding = 'utf-8'\n return response.text\n except requests.RequestException as e:\n # 开启代理\n use_proxy = True\n # 请求失败,自动重试\n retry_time += 1\n if retry_time <= WeixinSpider.MAX_RETRY_TIME:\n logging.warning(url + '--->请求失败,正在第%d次重试' % retry_time)\n self._get(url, use_proxy, retry_time)\n else:\n logging.error(url + '--->请求失败,重试次数达到上限,跳过本次请求!!!')\n\n def _load_article_list(self, list_url):\n \"\"\"加载文章列表页\"\"\"\n source = self._get(list_url)\n # 调用方法,解析文章列表页\n if source:\n self._parse_article_list(source)\n\n def _parse_article_list(self, list_source):\n \"\"\"解析文章列表页,获取文章详情页URL\"\"\"\n html = etree.HTML(list_source)\n if len(html):\n a_list = html.xpath('//a[contains(@id,\"sogou_vr_11002601_title_\")]')\n for a in a_list:\n link = a.xpath('./@href')[0].strip()\n # 调用方法,加载文章详情页\n self._load_article_detail(link)\n\n def _load_article_detail(self, article_url):\n \"\"\"加载文章详情页\"\"\"\n source = self._get(article_url)\n if source:\n # 调用方法,解析文章详情页\n self._parse_article_detail(source)\n\n def _parse_article_detail(self, article_source):\n \"\"\"解析文章详情页\"\"\"\n html = etree.HTML(article_source)\n if len(html):\n # 标题\n title = html.xpath('//h2/text()')[0].strip()\n # 发布日期\n post_date = html.xpath('//div[@id=\"meta_content\"]/em/text()')[0]\n # 作者\n post_user = html.xpath('//div[@id=\"meta_content\"]/a/text()')[0]\n with open('/home/li/data/sougouweixin.txt', mode='a', encoding='utf-8') as fw:\n fw.write(title + '\\t' + post_user + '\\t' + post_date + '\\n')\n logging.info('已获取--->' + title)\n\n def start(self):\n # 未登录状态下,最多显示10页\n keyword = 'Python'\n type = 2\n for page in range(1, 11):\n url = 'http://weixin.sogou.com/weixin?query={keyword}&type={type}&page={page}'.format(keyword=keyword,\n type=type,\n page=str(page))\n self._load_article_list(url)\n\n\nif __name__ == '__main__':\n weixin_spider = WeixinSpider()\n weixin_spider.start()\n","sub_path":"02_PC端/搜狗微信/weixin_spider.py","file_name":"weixin_spider.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"355691267","text":"#!/usr/bin/env python\n# -*- encoding: UTF-8 -*-\n\n# Copyright Skyscape Cloud Services\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 collections import namedtuple\nfrom collections import OrderedDict\nimport copy\nimport functools\nimport logging\nimport ipaddress\nimport itertools\nfrom ipaddress import ip_address\nfrom xml.etree import ElementTree as ET\n\nimport ruamel.yaml\n\nimport maloja.types\nfrom maloja.workflow.utils import find_xpath\n\n__doc__ = \"\"\"\nThese classes define objects which Maloja uses internally. All of\nthem can be saved to file in a YAML representation.\n\n\"\"\"\n\nyaml_loads = functools.partial(ruamel.yaml.load, Loader=ruamel.yaml.RoundTripLoader)\nyaml_dumps = functools.partial(ruamel.yaml.dump, Dumper=ruamel.yaml.RoundTripDumper)\n\n\ndef dataobject_as_ordereddict(dumper, data, default_flow_style=False):\n assert isinstance(dumper, ruamel.yaml.RoundTripDumper)\n return dumper.represent_ordereddict(\n OrderedDict([(k, getattr(data, k)) for k, v in data._defaults])\n )\n\ndef namedtuple_as_dict(dumper, data, default_flow_style=False):\n assert isinstance(dumper, ruamel.yaml.RoundTripDumper)\n return dumper.represent_ordereddict(data._asdict())\n\ndef object_as_str(dumper, data, default_flow_style=False):\n assert isinstance(dumper, ruamel.yaml.RoundTripDumper)\n return dumper.represent_str(str(data))\n\nclass DataObject:\n\n _defaults = []\n\n @staticmethod\n def typecast(val):\n if val in (\"true\", \"false\"):\n return val == \"true\"\n try:\n if val.isdigit():\n return int(val)\n except AttributeError:\n return val\n else:\n return val\n\n def __init__(self, **kwargs):\n \"\"\"\n Creates a fresh object, or one with attributes set by\n the `kwargs` dictionary.\n\n \"\"\"\n data = copy.deepcopy(self._defaults) + list(kwargs.items())\n for k, v in data:\n setattr(self, k, v)\n\n def __eq__(self, other):\n tgt = getattr(other, \"__dict__\", None)\n return self.__dict__ == tgt\n\n def __hash__(self):\n return id(self)\n\n @property\n def elements(self):\n\n def visitor(obj, name):\n try:\n yield from obj.elements\n except AttributeError as e:\n if isinstance(obj, (str, ipaddress.IPv4Address)):\n yield (name, obj)\n return\n\n try:\n for k, v in obj._asdict().items():\n yield from visitor(v, k)\n except AttributeError as e:\n if isinstance(obj, list):\n for item in obj:\n yield from visitor(item, name)\n\n for k, _ in self._defaults:\n obj = getattr(self, k)\n yield from visitor(obj, name=k)\n\n def feed_xml(self, tree, *args, **kwargs):\n \"\"\"\n Updates the object by feeding it XML\n from the VMware API.\n\n \"\"\"\n ns = kwargs.pop(\"ns\", \"\")\n fields = [k for k, v in self._defaults if v is None]\n attribs = ((attr, tree.attrib.get(attr)) for attr in tree.attrib if attr in fields)\n tags = [ns + k[0].upper() + k[1:] for k, v in self._defaults if v is None]\n body = (\n (elem.tag.replace(ns, \"\"), elem.text)\n for elem in tree\n if elem.tag in tags\n )\n for k, v in itertools.chain(attribs, body):\n setattr(self, k[0].lower() + k[1:], self.typecast(v))\n return self\n\nclass Project(DataObject):\n \"\"\"\n Available for storing Maloja project information.\n\n \"\"\"\n\n _defaults = [\n (\"version\", None),\n ]\n\nclass Catalog(DataObject):\n \"\"\"\n The Catalog class represents a VMware public or private\n catalog.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"dateCreated\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Catalog object.\n\n \"\"\"\n\nclass Gateway(DataObject):\n \"\"\"\n The Gateway class represents a VMware Edge Gateway.\n Here you can find the following:\n\n * Firewall rules\n * DNAT rules\n * SNAT rules\n\n \"\"\"\n\n FW = namedtuple(\n \"FW\", [\"description\", \"int_addr\", \"int_port\", \"ext_addr\", \"ext_port\"]\n )\n\n DNAT = namedtuple(\n \"DNAT\", [\"int_addr\", \"int_port\", \"ext_addr\", \"ext_port\"]\n )\n SNAT = namedtuple(\n \"SNAT\", [\"int_addr\", \"int_port\", \"ext_addr\", \"ext_port\"]\n )\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"fw\", []),\n (\"dnat\", []),\n (\"snat\", []),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Gateway object.\n\n \"\"\"\n\n @staticmethod\n def servicecast(val):\n val = val.lower()\n if val in (\"any\", \"external\", \"internal\"):\n return [val]\n try:\n return [int(val)]\n except ValueError:\n pass\n\n try:\n slice_ = [ipaddress.ip_address(i.strip()) for i in val.split(\"-\")]\n span = int(slice_[-1]) - int(slice_[0]) + 1\n return [slice_[0] + i for i in range(span)]\n except ValueError:\n pass\n\n return list(ipaddress.ip_network(val).hosts())\n\n @staticmethod\n def typecast(val):\n rv = DataObject.typecast(val)\n if isinstance(rv, str):\n try:\n rv = Gateway.servicecast(rv)\n except ValueError:\n pass\n return rv\n\n def __init__(self, **kwargs):\n \"\"\"\n Creates a fresh object, or one with attributes set by\n the `kwargs` dictionary.\n\n \"\"\"\n for seq, typ in [(\"fw\", Gateway.FW), (\"dnat\", Gateway.DNAT), (\"snat\", Gateway.SNAT)]:\n if seq in kwargs:\n kwargs[seq] = [\n typ(**{k: self.typecast(v) for k, v in i.items()})\n for i in kwargs[seq]\n ]\n\n super().__init__(**kwargs)\n\n def feed_xml(self, tree, ns=\"{http://www.vmware.com/vcloud/v1.5}\"):\n \"\"\"\n Updates the object by feeding it XML\n from the VMware API.\n\n \"\"\"\n log = logging.getLogger(\"maloja.model.Gateway\")\n super().feed_xml(tree, ns=ns)\n\n config = tree.find(\n \"./*/{}EdgeGatewayServiceConfiguration\".format(ns)\n )\n if config is None:\n return self\n\n elem = config.find(ns + \"FirewallService\")\n firewallRules = elem.iter(ns + \"FirewallRule\") if elem is not None else []\n for rule in firewallRules:\n int_ip = rule.find(ns + \"DestinationIp\").text\n self.fw.append(\n Gateway.FW(\n getattr(rule.find(ns + \"Description\"), \"text\", None),\n self.servicecast(rule.find(ns + \"DestinationIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"Port\"), \"text\", \"0\")\n )), None),\n self.servicecast(rule.find(ns + \"SourceIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"SourcePort\"), \"text\", \"0\")\n )), None)\n )\n )\n elem = config.find(ns + \"NatService\")\n natRules = elem.iter(ns + \"NatRule\") if elem is not None else []\n for elem in natRules:\n if elem.find(ns + \"RuleType\").text == \"DNAT\":\n rule = elem.find(ns + \"GatewayNatRule\")\n self.dnat.append(\n Gateway.DNAT(\n self.servicecast(rule.find(ns + \"TranslatedIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"TranslatedPort\"), \"text\", \"0\")\n )), None),\n self.servicecast(rule.find(ns + \"OriginalIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"OriginalPort\"), \"text\", \"0\")\n )), None)\n )\n )\n elif elem.find(ns + \"RuleType\").text == \"SNAT\":\n rule = elem.find(ns + \"GatewayNatRule\")\n self.snat.append(\n Gateway.SNAT(\n self.servicecast(rule.find(ns + \"OriginalIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"OriginalPort\"), \"text\", \"0\")\n )), None),\n self.servicecast(rule.find(ns + \"TranslatedIp\").text),\n next(iter(self.servicecast(\n getattr(rule.find(ns + \"TranslatedPort\"), \"text\", \"0\")\n )), None)\n )\n )\n return self\n\nclass Network(DataObject):\n \"\"\"\n The Network class represents a VMware network.\n Here you can find the following:\n\n * DNS rules\n * DHCP configuration\n\n \"\"\"\n\n DHCP = namedtuple(\n \"DHCP\", [\"pool\"]\n )\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"defaultGateway\", None),\n (\"netmask\", None),\n (\"dhcp\", None),\n (\"dnsSuffix\", None),\n (\"dns\", []),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Network object.\n\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Creates a fresh object, or one with attributes set by\n the `kwargs` dictionary.\n\n \"\"\"\n super().__init__(**kwargs)\n\n self.defaultGateway = next(iter(Gateway.typecast(self.defaultGateway) or (None,)))\n self.netmask = next(iter(Gateway.typecast(self.netmask) or (None,)))\n if self.dhcp is not None:\n self.dhcp = Network.DHCP(pool=[\n addr for i in self.dhcp[\"pool\"] for addr in Gateway.typecast(i)\n ])\n\n def feed_xml(self, tree, ns=\"{http://www.vmware.com/vcloud/v1.5}\"):\n \"\"\"\n Updates the object by feeding it XML\n from the VMware API.\n\n \"\"\"\n log = logging.getLogger(\"maloja.model.Network\")\n self.dns = [tree.attrib.get(\"dns1\"), tree.attrib.get(\"dns2\")]\n super().feed_xml(tree, ns=ns)\n\n scope = tree.find(\n \"./*/*/{}IpScope\".format(ns)\n )\n self.defaultGateway = next(iter(Gateway.servicecast(\n scope.find(ns + \"Gateway\").text\n )), None)\n self.netmask = next(iter(Gateway.servicecast(\n scope.find(ns + \"Netmask\").text\n )), None)\n\n\n elem = None\n config = tree.find(\n \"./*/{}GatewayDhcpService\".format(ns)\n )\n if config is not None:\n elem = config.find(ns + \"Pool\")\n if elem is not None:\n self.dhcp = Network.DHCP(pool=[\n next(iter(Gateway.servicecast(elem.find(ns + \"LowIpAddress\").text)), None),\n next(iter(Gateway.servicecast(elem.find(ns + \"HighIpAddress\").text)), None),\n ])\n return self\n\nclass Org(DataObject):\n \"\"\"\n The Org class represents a VMware organisation.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"fullName\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Org object.\n\n \"\"\"\n\nclass Task(DataObject):\n \"\"\"\n The Task class represents a task running against a VMware\n resource.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"operationName\", None),\n (\"organization\", None),\n (\"startTime\", None),\n (\"status\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Task object.\n\n \"\"\"\n\n def feed_xml(self, tree, ns=\"{http://www.vmware.com/vcloud/v1.5}\"):\n \"\"\"\n Updates the object by feeding it XML\n from the VMware API.\n\n \"\"\"\n log = logging.getLogger(\"maloja.model.Task\")\n super().feed_xml(tree, ns=ns)\n org = tree.find(ns + \"Organization\")\n self.organization = Org().feed_xml(org, ns=ns)\n owner = tree.find(ns + \"Owner\")\n typ = owner.attrib.get(\"type\")\n try:\n self.owner = {\n \"application/vnd.vmware.admin.edgeGateway+xml\": Gateway,\n \"application/vnd.vmware.vcloud.vApp+xml\": VApp,\n \"application/vnd.vmware.vcloud.vm+xml\": Vm\n }.get(typ)().feed_xml(owner, ns=ns)\n except TypeError:\n log.warning(\"Unable to recognise owner.\")\n self.owner = None\n return self\n\nclass Template(DataObject):\n \"\"\"\n The Template class represents a VMware VAppTemplate.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"dateCreated\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Template object.\n\n \"\"\"\n\nclass VApp(DataObject):\n \"\"\"\n The VApp class represents a VMware VApp.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Vapp object.\n\n \"\"\"\n\nclass Vdc(DataObject):\n \"\"\"\n The Vdc class represents a VMware Vdc.\n\n \"\"\"\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"description\", None),\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Vdc object.\n\n \"\"\"\n\nclass Vm(DataObject):\n \"\"\"\n The Vm class represents a VMware Vm.\n\n \"\"\"\n\n rasd = {\n 0: namedtuple(\"Other\", []),\n 3: namedtuple(\"Processor\", [\"instanceID\", \"virtualQuantity\"]),\n 4: namedtuple(\"Memory\", [\"instanceID\", \"virtualQuantity\"]),\n 5: namedtuple(\"IDEController\", [\"address\", \"description\", \"instanceID\"]),\n 6: namedtuple(\n \"SCSIController\",\n [\"address\", \"description\", \"elementName\", \"instanceID\", \"resourceSubType\"]\n ),\n 10: namedtuple(\n \"EthernetAdapter\",\n [\"address\", \"connection\", \"elementName\", \"instanceID\", \"resourceSubType\"]\n ),\n 14: namedtuple(\"FloppyDrive\", [\"description\", \"instanceID\"]),\n 15: namedtuple(\"CDDrive\", [\"description\", \"instanceID\"]),\n 16: namedtuple(\"DVDDrive\", [\"description\", \"instanceID\"]),\n 17: namedtuple(\n \"DiskDrive\",\n [\"addressOnParent\", \"description\", \"hostResource\", \"instanceID\"]\n ),\n 23: namedtuple(\"USBController\", []),\n }\n\n HardDisk = namedtuple(\n \"HardDisk\", [\"name\", \"capacity\"]\n )\n\n NetworkCard = namedtuple(\n \"NetworkCard\", [\"name\", \"mac\", \"device\"]\n )\n\n NetworkConnection = namedtuple(\n \"NetworkConnection\", [\n \"name\", \"ip\", \"isConnected\", \"macAddress\",\n \"ipAddressAllocationMode\"\n ]\n )\n\n SCSIController = namedtuple(\n \"SCSIController\", [\"name\", \"device\"]\n )\n\n _defaults = [\n (\"name\", None),\n (\"href\", None),\n (\"type\", None),\n (\"dateCreated\", None),\n (\"guestOs\", None),\n (\"hardwareVersion\", []),\n (\"cpu\", None),\n (\"memoryMB\", None),\n (\"networkcards\", []),\n (\"harddisks\", []),\n (\"scsi\", []),\n (\"cd\", None),\n (\"floppydisk\", None),\n (\"isBusy\", None),\n (\"isDeleted\", None),\n (\"isDeployed\", None),\n (\"isInMaintenanceMode\", None),\n (\"isPublished\", None),\n (\"status\", None),\n (\"storageProfileName\", None),\n (\"vmToolsVersion\", None),\n (\"networkconnections\", []),\n (\"guestcustomization\", None)\n ]\n \"\"\"\n A list of (key, value) pairs which define the defaults for\n a new Vm object.\n\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Creates a fresh object, or one with attributes set by\n the `kwargs` dictionary.\n\n \"\"\"\n for seq, typ in [\n (\"harddisks\", Vm.HardDisk),\n (\"networkcards\", Vm.NetworkCard),\n (\"networkconnections\", Vm.NetworkConnection),\n (\"scsi\", Vm.SCSIController),\n ]:\n if seq in kwargs:\n kwargs[seq] = [\n typ(**{k: self.typecast(v) for k, v in i.items()})\n for i in kwargs[seq]\n ]\n\n super().__init__(**kwargs)\n\n def feed_xml(self, tree, ns=\"{http://www.vmware.com/vcloud/v1.5}\"):\n \"\"\"\n Updates the object by feeding it XML\n from the VMware API.\n\n \"\"\"\n\n if tree.tag in (ns + \"Owner\", ns + \"VAppTemplate\", ns + \"Vm\", ns + \"VMRecord\"):\n super().feed_xml(tree, ns=ns)\n\n if tree.tag == ns + \"VMRecord\":\n try:\n val = int(tree.attrib.get(\"hardwareVersion\"))\n if val not in self.hardwareVersion:\n self.hardwareVersion.append(val)\n except TypeError as e:\n # No version supplied\n pass\n\n if tree.tag in (ns + \"VAppTemplate\", ns + \"Vm\"):\n system = next(find_xpath(\n \"./*/{}System\".format(\"{http://schemas.dmtf.org/ovf/envelope/1}\"), tree\n ), None)\n if system is not None:\n try:\n versions = set(self.hardwareVersion).union({\n int(i.lstrip(\"vmx-\")) for i in system.find((\n \"{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2\"\n \"/CIM_VirtualSystemSettingData}VirtualSystemType\")).text.split()})\n self.hardwareVersion = list(versions)\n except (AttributeError, TypeError, ValueError):\n pass\n\n hardware = find_xpath(\n \"./*/{}Item\".format(\"{http://schemas.dmtf.org/ovf/envelope/1}\"), tree\n )\n rasdNs = (\n \"{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/\"\n \"2/CIM_ResourceAllocationSettingData}\"\n )\n for item in hardware:\n key = int(getattr(item.find(rasdNs + \"ResourceType\"), \"text\", \"0\"))\n typ = Vm.rasd[key]\n fields = [(rasdNs + i).lower() for i in typ._fields]\n obj = typ(*(i for i in list(item) if i.tag.lower() in fields))\n if key == 3:\n self.cpu = int(obj.virtualQuantity.text)\n elif key == 4:\n self.memoryMB = int(obj.virtualQuantity.text)\n elif key == 6:\n entry = Vm.SCSIController(\n obj.elementName.text,\n obj.resourceSubType.text\n )\n if entry not in self.scsi:\n self.scsi.append(entry)\n elif key == 10:\n entry = Vm.NetworkCard(\n obj.elementName.text,\n obj.address.text,\n obj.resourceSubType.text\n )\n if entry not in self.networkcards:\n self.networkcards.append(entry)\n elif key == 17:\n entry = Vm.HardDisk(\n obj.description.text,\n int(obj.hostResource.attrib.get(ns + \"capacity\"))\n )\n if entry not in self.harddisks:\n self.harddisks.append(entry)\n\n self.networkconnections = [\n Vm.NetworkConnection(\n i.attrib[\"network\"],\n getattr(i.find(ns + \"IpAddress\"), \"text\", None),\n i.find(ns + \"IsConnected\").text == \"true\",\n i.find(ns + \"MACAddress\").text,\n getattr(i.find(ns + \"IpAddressAllocationMode\"), \"text\", None))\n for i in tree.iter(ns + \"NetworkConnection\")]\n\n section = tree.find(ns + \"GuestCustomizationSection\")\n # TODO: Define customization storage\n\n return self\n\nruamel.yaml.RoundTripDumper.add_representer(ipaddress.IPv4Address, object_as_str)\nruamel.yaml.RoundTripDumper.add_representer(Catalog, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Gateway, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Gateway.FW, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Gateway.DNAT, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Gateway.SNAT, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Network, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Network.DHCP, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Org, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Project, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Template, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(VApp, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Vdc, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Vm, dataobject_as_ordereddict)\nruamel.yaml.RoundTripDumper.add_representer(Vm.HardDisk, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Vm.NetworkCard, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Vm.NetworkConnection, namedtuple_as_dict)\nruamel.yaml.RoundTripDumper.add_representer(Vm.SCSIController, namedtuple_as_dict)\n","sub_path":"maloja/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":22145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"533187543","text":"import datetime\nimport warnings\nfrom django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\nfrom crm.contract.models.contract import TYPE_RESERVATION\nfrom crm.contract.models.contract import TYPE_PASS\nfrom crm.contract.models.contract import TYPE_WAITING_LIST\nfrom crm.contract.models.contract import TYPE_RESIGNATION\nfrom crm.contract.models.contract import TYPE_CONTRACT\nfrom crm.payment.models import Payment\nfrom crm.contract.models import Contract\nfrom crm.date.models import Season\n\n\nclass PaymentInline(admin.TabularInline):\n model = Payment\n extra = 1\n classes = [\"collapse\"]\n\n\nclass ContractAdmin(admin.ModelAdmin):\n change_list_template = \"admin/change_list_filter_sidebar.html\"\n search_fields = [\"^customer__last_name\", \"=uid\"]\n list_display = [\"season\", \"view_uid\", \"view_customer\",\n \"view_comment_contract\", \"view_group\", \"view_day\",\n \"view_type\", \"view_last_payment\", \"view_comment_payment\",\n \"signup_date\", \"resignation_date\"]\n list_display_links = [\"view_customer\"]\n list_filter = [\"season\", \"type\", \"\" \"group__day\", \"group__hour\"]\n list_select_related = True\n ordering = [\"season\", \"uid\", \"signup_date\"]\n inlines = [PaymentInline]\n radio_fields = {\"type\": admin.VERTICAL}\n readonly_fields = [\"id\"]\n raw_id_fields = [\"customer\", \"group\"]\n autocomplete_lookup_fields = {\"fk\": [\"customer\", \"group\"]}\n fieldsets = [\n (None, {\n \"fields\": [\"season\", \"customer\", \"group\", \"type\", \"comment\",\n \"comment2\", \"signup_date\", \"id\"]}),\n (_(\"Reservation\"), {\n \"fields\": [\"reservation_end_date\", ],\n \"classes\": [\"reservation-type\"]}),\n (_(\"Resignation\"), {\n \"fields\": [\"resignation_date\", ],\n \"classes\": [\"resignation-type\"]}),\n (_(\"Contract\"), {\n \"fields\": [\"uid\", \"document\", \"cost\", \"start_date\", \"end_date\", ],\n \"classes\": [\"contract-type\"]})]\n\n def view_last_payment(self, contract):\n try:\n payment = Payment.objects.filter(uid=contract.id).order_by(\"-date\")[0]\n return \"{date}
{method} {amount}zł\".format(date=payment.date, amount=payment.amount, method=payment.method)\n except IndexError:\n return \"\"\n view_last_payment.allow_tags = True\n view_last_payment.short_description = _(\"Last Payment\")\n\n def changelist_view(self, request, extra_context=None):\n if \"season__id__exact\" not in request.GET:\n q = request.GET.copy()\n q[\"season__id__exact\"] = Season.current().id\n request.GET = q\n request.META[\"QUERY_STRING\"] = request.GET.urlencode()\n return super(ContractAdmin, self).changelist_view(request, extra_context=extra_context)\n\n def view_uid(self, contract):\n if contract.uid:\n return \"
%s
\" % contract.uid\n return \"\"\n view_uid.allow_tags = True\n view_uid.short_description = _(\"User ID\")\n\n def view_customer(self, contract):\n ret = \"%s %s\" % (\n contract.customer.last_name,\n contract.customer.first_name)\n if contract.customer.address and contract.customer.zip_code:\n ret += \"
(%s, %s)\" % (contract.customer.address, contract.customer.zip_code.city.name)\n elif contract.customer.address:\n ret += \"
(%s)\" % contract.customer.address\n elif contract.customer.zip_code:\n ret += \"
(%s)\" % contract.customer.zip_code.city.name\n return ret\n view_customer.allow_tags = True\n view_customer.short_description = _(\"Customer\")\n\n def view_comment_contract(self, contract):\n if contract.comment:\n return \"
%s
\" % contract.comment\n return \"\"\n view_comment_contract.allow_tags = True\n view_comment_contract.short_description = _(\"Contract comment\")\n\n def view_group(self, contract):\n warnings.warn(\"Convert to {% url %}\", DeprecationWarning)\n return \"%s\" % (\n contract.group.id,\n contract.group.type.short_name)\n view_group.allow_tags = True\n view_group.short_description = _(\"Group\")\n\n def view_day(self, contract):\n return \"
%s
%s
\" % (\n contract.group.day,\n contract.group.hour.strftime(\"%H:%M\"))\n view_day.short_description = _(\"Day\")\n view_day.allow_tags = True\n\n def view_type(self, contract):\n warnings.warn(\"Simplify logic\", PendingDeprecationWarning)\n if not contract.reservation_end_date:\n contract.reservation_end_date = \"\"\n\n if not contract.resignation_date:\n contract.resignation_date = \"\"\n\n if contract.type == TYPE_RESERVATION:\n if contract.reservation_end_date < datetime.date.today():\n if contract.active:\n contract.active = False\n contract.save()\n return _(\"
Outdated reservation
%(reservation_end_date)s
\") % {\"reservation_end_date\": contract.reservation_end_date}\n else:\n if not contract.active:\n contract.active = False\n contract.save()\n return _(\"
Reservation
%(reservation_end_date)s
\") % {\"reservation_end_date\": contract.reservation_end_date}\n\n if contract.type == TYPE_RESIGNATION:\n return _(\"
Resignation
%(resignation_date)s
\") % {\"resignation_date\": contract.resignation_date}\n\n if contract.type == TYPE_WAITING_LIST:\n return \"
%s
\" % _(\"Waiting List\")\n\n if contract.type == TYPE_CONTRACT:\n if contract.valid_payment_for_current_month():\n return _(\"
Contract
\")\n else:\n return _(\"
Contract
Late Payment
\")\n\n if contract.type == TYPE_PASS:\n return _(\"
Swimming pool pass
\")\n\n view_type.allow_tags = True\n view_type.short_description = _(\"Contract type\")\n\n def view_comment_payment(self, contract):\n if contract.comment2:\n return \"
%s
\" % (contract.comment2)\n return \"\"\n view_comment_payment.allow_tags = True\n view_comment_payment.short_description = _(\"Payment comment\")\n\n class Media:\n js = [\n \"contract/js/jquery-2.0.0.min.js\",\n \"contract/js/ajax.js\",\n \"contract/js/add-print-button.js\",\n \"contract/js/contract.js\"]\n css = {\"all\": [\n \"contract/css/contract.css\",\n \"contract/css/hide-id-field.css\"]}\n\n\nadmin.site.register(Contract, ContractAdmin)\n","sub_path":"crm/contract/admin/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":7055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646400579","text":"import base64\n\nfrom appium import webdriver\n\nimport time\n\n# server 启动参数\ndesired_caps = {}\n# 设备信息\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '5.1'\ndesired_caps['deviceName'] = '192.168.56.101:5555'\n# app信息\ndesired_caps['appPackage'] = 'com.android.settings'\ndesired_caps['appActivity'] = '.Settings'\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n\npath = \"/sdcard/abcd.txt\"\n\n# base64_str = str(base64.b64encode(\"hello world\".encode(\"utf-8\")),\"utf-8\")\n# driver.push_file(path,base64_str)\n\n\n\ndata = str(base64.b64decode(driver.pull_file(\"/sdcard/abcd.txt\")),\"utf-8\")\n\n\nprint(data)\ntime.sleep(5)\n\ndriver.quit()","sub_path":"yidong/day01/作业2.py","file_name":"作业2.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"174444467","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\n\nfrom .forms import *\n\n\n# Create your views here.\ndef index(request):\n if check_logado(request): return redirect('home_logado')\n if request.method == \"POST\":\n form = CadastroForm(request.POST)\n if form.is_valid():\n model_instance = form.save(commit=False)\n model_instance.save()\n messages.success(request, 'Conta criada com sucesso')\n return redirect('home')\n else:\n form = CadastroForm()\n\n context = {\n \"form\": form,\n \"btn_name\": \"Cadastrar\"\n }\n return render(request, 'index.html', context)\n\n\ndef home(request):\n if check_logado(request):\n if request.method == \"POST\":\n form = BuscaGrupoForm(request.POST)\n if form.is_valid():\n if request.POST['titulo']:\n print('entrou')\n context = {\n \"busca_sair\": usuario_logado(request).grupo_usuario.all().filter(titulo=request.POST['titulo']),\n \"busca\": True,\n \"busca_entrar\": Grupo.objects.all().exclude(usuarios=usuario_logado(request)),\n }\n return render(request, 'grupos.html', context)\n else:\n print(form.errors)\n\n form = BuscaGrupoForm()\n\n context = {\n \"usuario\": usuario_logado(request),\n \"form\": form,\n \"btn_name\": \"Buscar\",\n }\n\n return render(request, 'home.html', context)\n else:\n return index(request)\n\n\ndef login(request):\n collection = Usuario.objects.filter(email=request.POST['email'], senha=request.POST['senha'])\n if collection:\n usuario = collection[0]\n request.session[\"usuario_logado\"] = {\n \"id\": usuario.id,\n \"nome\": usuario.nome,\n \"email\": usuario.email\n }\n return redirect('home_logado')\n\n return redirect('home')\n\n\ndef logout(request):\n request.session[\"usuario_logado\"] = None\n return redirect('home')\n\n\ndef postar(request):\n if not check_logado(request): return redirect('home')\n if request.method == \"POST\":\n form = PostagemForm(request.POST)\n if form.is_valid():\n model_instance = form.save(commit=False)\n model_instance.usuario = usuario_logado(request)\n model_instance.save()\n tipo = request.POST['tipo']\n if tipo:\n if tipo == 'P':\n request.FILES['arquivo'] = request.FILES['pdf']\n elif tipo == 'I':\n request.FILES['arquivo'] = request.FILES['imagem']\n anexo = AnexoForm(request.POST, request.FILES)\n if anexo.is_valid():\n anexo_instance = anexo.save(commit=False)\n anexo_instance.postagem = model_instance\n anexo_instance.save()\n else:\n print(anexo.errors)\n else:\n print(form.errors)\n return redirect('home_logado')\n\n\ndef postar_editar(request, id):\n postagem = get_object_or_404(Postagem, id=id)\n if request.method == \"POST\":\n form = PostagemForm(request.POST, instance=postagem)\n if form.is_valid():\n model_instance = form.save(commit=False)\n model_instance.usuario = usuario_logado(request)\n model_instance.save()\n else:\n print(form.errors)\n return redirect('home_logado')\n\n\ndef postar_deletar(request, id):\n postagem = Postagem.objects.get(id=id)\n print(postagem.delete())\n return redirect('home_logado')\n\n\ndef pesquisar_amigo(request):\n pesquisa = request.GET['q']\n usuario = usuario_logado(request)\n resultado = Usuario.objects.filter(nome__contains=pesquisa).exclude(nome=usuario).exclude(amigos=usuario)\n\n context = {\n \"usuario\": usuario_logado(request),\n \"resultado\": resultado,\n \"pesquisa\": pesquisa\n }\n return render(request, 'pesquisa.html', context)\n\n\ndef perfil(request, id):\n if not check_logado(request): return redirect('home')\n usuario = get_object_or_404(Usuario, id=id)\n if request.method == \"POST\":\n form = UsuarioForm(request.POST, instance=usuario)\n if form.is_valid():\n form.save()\n reload_user(request, id)\n else:\n form = UsuarioForm(instance=usuario)\n context = {\n \"usuaerio\": usuario_logado(request),\n \"perfil\": usuario,\n \"form\": form,\n \"btn_name\": \"Salvar Perfil\"\n }\n return render(request, 'perfil.html', context)\n\n\ndef grupos(request):\n if request.method == \"POST\":\n form = BuscaGrupoForm(request.POST)\n if form.is_valid():\n if request.POST['titulo']:\n context = {\n \"busca_sair\": usuario_logado(request).grupo_usuario.all().filter(titulo=request.POST['titulo']),\n \"busca\": True,\n \"busca_entrar\": Grupo.objects.all().exclude(usuarios=usuario_logado(request)).filter(\n titulo=request.POST['titulo']),\n }\n return render(request, 'grupos.html', context)\n else:\n print(form.errors)\n\n form = BuscaGrupoForm()\n\n context = {\n \"form\": form,\n \"btn_name\": \"Buscar\",\n \"usuario\": usuario_logado(request),\n \"grupos\": Grupo.objects.all().exclude(usuarios=usuario_logado(request)).exclude(\n criador=usuario_logado(request)),\n }\n\n return render(request, 'grupos.html', context)\n\n\ndef sair_grupo(request, id):\n usuario = usuario_logado(request)\n usuario.grupo_usuario.remove(Grupo.objects.get(id=id))\n return redirect('grupos')\n\n\ndef entrar_grupo(request, id):\n usuario = usuario_logado(request)\n usuario.grupo_usuario.add(Grupo.objects.get(id=id))\n return redirect('grupos')\n\n\ndef check_logado(request):\n if request.session.get('usuario_logado'):\n return True\n return False\n\n\ndef reload_user(request, id):\n usuario = Usuario.objects.get(id=id)\n request.session[\"usuario_logado\"] = {\n \"id\": usuario.id,\n \"nome\": usuario.nome,\n \"email\": usuario.email,\n \"tipo\": usuario.tipo\n }\n\n\ndef usuario_logado(request):\n usuario = request.session.get('usuario_logado')\n return Usuario.objects.get(id=usuario[\"id\"])\n\n\ndef add_grupo(request, id=0):\n grupo = None\n if id:\n grupo = Grupo.objects.get(id=id)\n\n if request.method == 'POST':\n form = GrupoForm(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.criador = usuario_logado(request)\n instance.save()\n return redirect('grupos')\n\n else:\n form = GrupoForm(instance=grupo)\n\n context = {\n \"form\": form,\n \"btn_name\": \"Criar\"\n\n }\n return render(request, 'grupo.html', context)\n\n\ndef convidar(request, id):\n perfil_a_convidar = Usuario.objects.get(id=id)\n perfil_logado = usuario_logado(request)\n perfil_logado.convidar(perfil_a_convidar)\n return redirect('home_logado')\n\n\ndef convites(request):\n usuario = usuario_logado(request)\n convites = usuario.convites_recebidos.all()\n amigos = usuario.amigos.all()\n\n context = {\n \"convites\": convites,\n \"amigos\": amigos\n }\n print(convites)\n\n return render(request, 'amigos.html', context)\n\n\ndef aceitar(request, id):\n convite = Convite.objects.get(id=id)\n convite.aceitar()\n return redirect('home_logado')\n\n\ndef excluir_grupo(request, id):\n print(\"entrou\")\n grupo = Grupo.objects.get(id=id)\n grupo.delete()\n return redirect('grupos')\n","sub_path":"social/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480114569","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author: xurongzhong#126.com wechat:pythontesting qq:37391319\n# CreateDate: 2018-1-19 pandas_column_by_index.py\nimport pandas as pd\n\ninput_file = r\"supplier_data.csv\"\noutput_file = r\"output_files\\7output.csv\"\n\ndata_frame = pd.read_csv(input_file)\ndata_frame_column_by_name = data_frame.loc[\n :, ['Invoice Number', 'Purchase Date']]\ndata_frame_column_by_name.to_csv(output_file, index=False)","sub_path":"pandas/excel_demo/pandas_column_by_name.py","file_name":"pandas_column_by_name.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"611421212","text":"#! /usr/bin/env python\n\nfrom numpy import *\n\n# Length of links in cm\na1 = 24 # length of link a1 in mm\na2 = 55 # length of link a2 in mm\na3 = 65 # length of link a3 in mm\n\n# Desired Position of End effector\nx = 24\ny = 60\nz = 0\n\n# phi = 90\n# phi = deg2rad(phi)\n\np = sqrt((x**2)+(y**2)-(a1**2))\nD = ((x**2)+(y**2)-(a1**2)+(z**2)-(a2**2)-(a3**2))/(2*a2*a3)\n\ntheta_1 = arctan2(y, x) - arctan2(p, a1)\ntheta_3 = arctan2(sqrt(1-(D**2)), D)\ntheta_2 = arctan2(z, p) - arctan2((a3*sin(theta_3)), (a2+a3*cos(theta_3)))\n\ntheta1 = int(round(rad2deg(theta_1)))\ntheta2 = int(round(rad2deg(theta_2)))\ntheta3 = int(round(rad2deg(theta_3)))\n\n\nprint('theta_1: ', theta1)\nprint('theta_2: ', theta2)\nprint('theta_3: ', theta3)","sub_path":"dreamwalker_control/scripts/research/inverse_kinematics.py","file_name":"inverse_kinematics.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"369193261","text":"from kutana.controller_basic import BasicController\nfrom kutana.plugin import Message\nfrom kutana.exceptions import ExitException\n\n\nclass DebugController(BasicController):\n \"\"\"Shoots target texts once.\"\"\"\n\n type = \"debug\"\n\n def __init__(self, *texts):\n self.replies = []\n self.replies_all = {}\n\n self.queue = list(texts)\n self.dead = False\n\n async def upload_thing(self, thing, **kwargs):\n return thing\n\n async def make_reply(self, update):\n if isinstance(update, str):\n sender_id = 1\n\n else:\n sender_id = update[0]\n\n async def reply(message, attachment=None, **kwargs):\n await self.send_message(\n message, peer_id=sender_id, attachment=attachment\n )\n\n return reply\n\n async def send_message(self, message=None, peer_id=None, attachment=None,\n **kwargs):\n\n sender_id = peer_id if peer_id is not None else 1\n\n array = self.replies_all.get(sender_id, [])\n\n if message:\n array.append(message)\n\n if sender_id == 1:\n self.replies.append(message)\n\n if attachment:\n if not isinstance(attachment, (list, tuple)):\n attachment = [attachment]\n\n array += attachment\n\n if sender_id == 1:\n self.replies += attachment\n\n else:\n attachment = []\n\n self.replies_all[sender_id] = array\n\n async def setup_env(self, update, eenv):\n async def return_none(*args, **kwargs):\n return None\n\n eenv[\"reply\"] = await self.make_reply(update)\n eenv[\"send_message\"] = self.send_message\n\n eenv[\"upload_doc\"] = self.upload_thing\n eenv[\"upload_photo\"] = self.upload_thing\n\n eenv[\"request\"] = return_none\n\n @staticmethod\n async def convert_to_message(update, eenv):\n # update = (sender_id, message)\n # or\n # update = (message_from_user_with_id_1)\n\n if isinstance(update, str):\n return Message(\n str(update), (), 1, 1, (1, str(update))\n )\n\n return Message(\n update[1], (), update[0], update[0], update\n )\n\n async def get_background_coroutines(self, ensure_future):\n return []\n\n async def get_receiver_coroutine_function(self):\n async def rec():\n if self.dead:\n raise ExitException\n\n self.dead = True\n\n return self.queue\n\n return rec\n\n async def dispose(self):\n pass\n","sub_path":"kutana/controller_debug.py","file_name":"controller_debug.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"37763552","text":"import requests\nfrom datetime import datetime\n\ndef get_weather_information(location, api_key, timezone_shift):\n weather_information = requests.get(f'https://api.tomorrow.io/v4/timelines?location={location[0]},{location[1]}&fields=temperature×teps=1h&units=imperial&apikey={api_key}').json()\n nodes = []\n for node in weather_information['data']['timelines'][0]['intervals']:\n node_alpha = [node['startTime'][11:13], node['values']['temperature']]\n nodes.append(node_alpha)\n\n for index, node in enumerate(nodes):\n nodes[index][0] = int(int(nodes[index][0]) + timezone_shift)%24 # converts UTC to local timezone using the shift of the timezone relative to UTC\n\n if node[0] == 0 and index != 0: # removes all past the day\n nodes = nodes[:index]\n break\n return nodes\n\ndef convert_temperatures(temp, system_f_c):\n if system_f_c.lower() == 'f': # if the temperature system is fahrenheit\n return (temp-32) * 5/9 # conversion\n elif system_f_c.lower() == 'c': # if system is celsius\n return (temp * 9/5) + 32 # conversion\n else:\n raise TypeError # if system is wrong\n\nclass Temperature:\n def __init__(self):\n self.celsius = 0\n self.fahrenheit = 0\n\n\nclass Weather:\n def __init__(self, location, api_key, timezone_shift):\n self.heat = Temperature()\n self.time = 0\n self.hours_in_day = 0\n self.temperature_information = []\n self.nodes = get_weather_information(location, api_key, timezone_shift)\n\n def update_information(self):\n self.heat.fahrenheit = abs([i[1] for i in self.nodes if i[0] == datetime.now().hour][0])\n self.heat.celsius = convert_temperatures(self.heat.fahrenheit, 'f')\n self.time = datetime.now().hour\n self.hours_in_day = len(self.nodes)\n self.temperature_information = self.nodes\n","sub_path":"main/tomorrow_io_wrapper.py","file_name":"tomorrow_io_wrapper.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"175892489","text":"import random\nimport datetime\n\n\nclass Graf(object):\n def __init__(self, macierzDrog: list, rozmiarGrafu: int, wierzcholki: dict):\n \"\"\"\n\n :param macierzDrog:\n :param rank:\n \"\"\"\n self.DlugosciDrog = macierzDrog\n self.Rozmiar = rozmiarGrafu\n self.Feromon = [[1.0 / (rozmiarGrafu * rozmiarGrafu) for j in range(rozmiarGrafu)] for i in range(rozmiarGrafu)]\n\n self.Wierzcholki = wierzcholki\n\n\n\n\nclass ACO(object):\n def __init__(self, liczbaMrowek: int, generacje: int, alfa: float, beta: float, ro: float, nasycenie: int, strategia: int):\n \"\"\"\n\n :param liczbaMrowek:\n :param generacje:\n :param alfa: wpływ feromonu na wybor drogi\n :param beta: wplyw informacji widocznych(krotsza droga)\n :param ro: poziom zanikania feromonow\n :param nasycenie:\n :param strategia:\n \"\"\"\n\n self.Nasycenie = nasycenie\n self.LiczbaMrowek = liczbaMrowek\n self.Pokolenia = generacje\n self.Alfa = alfa\n self.Beta = beta\n self.Ro = ro\n self.Schemat = strategia # # # Moze jednak nie trzeba\n\n\n def _aktualizacja_feromonow(self, graf: Graf, mrowki: list):\n for i, rzad in enumerate(graf.Feromon):\n for j, kolumna in enumerate(rzad):\n graf.Feromon[i][j] *= self.Ro\n for mrowka in mrowki:\n graf.Feromon[i][j] += mrowka.FeromonyDelta[i][j]\n\n\n\n # noinspection PyProtectedMember\n def _dzialaj(self, graf: Graf):\n\n start = datetime.datetime.now()\n drogaKoszt = float('inf')\n rozwiazanie = []\n for pok in range(self.Pokolenia):\n mrowki = [Mrowka(self, graf, i) for i in range(self.LiczbaMrowek)]\n for mrowka in mrowki: # WYPUSZCZAMY MROWKE\n #print('Mrowka: ', mrowka.ID)\n for i in range(graf.Rozmiar-1): # MROWKA TRWORZY LISTE ODWIEDZONYCH WIERZCHOLKOW\n mrowka._nastepny()\n mrowka.KosztCalkowity += graf.DlugosciDrog[mrowka.Odwiedzone[-1]][mrowka.Odwiedzone[0]]\n if mrowka.KosztCalkowity < drogaKoszt:\n drogaKoszt = mrowka.KosztCalkowity\n rozwiazanie = [] + mrowka.Odwiedzone\n print(\"najlepszy koszt: {} \\nnajlepsza sciezka: {} \\nczas: {}\".format(drogaKoszt, rozwiazanie, (datetime.datetime.now() - start).seconds))\n mrowka._aktualizacja_feromonu_d()\n self._aktualizacja_feromonow(graf, mrowki)\n\n # # # Sprawdzenie drogi\n droga = 0.0\n for i in range(1, graf.Rozmiar):\n droga += graf.DlugosciDrog[rozwiazanie[i - 1]][rozwiazanie[i]]\n droga += graf.DlugosciDrog[rozwiazanie[-1]][rozwiazanie[0]]\n print(droga, len(rozwiazanie), '\\n')\n\n # # # Wypisanie drogi\n for i in range(graf.Rozmiar): rozwiazanie[i] = graf.Wierzcholki[rozwiazanie[i]]['index']\n# rozwiazanie.remove(rozwiazanie.index(0))\n print('koszt: {}, sciezka: {}'.format(drogaKoszt, rozwiazanie))\n print((datetime.datetime.now() - start).seconds, 'sekund \\n\\n\\n')\n\n\n\n\n\nclass Mrowka(object):\n def __init__(self, aco: ACO, graf: Graf, id: int):\n self.ID = id\n self.Kolonia = aco\n self.Graf = graf\n self.KosztCalkowity = 0.0\n self.Odwiedzone = []\n self.Nieodwiedzone = [True for i in range(graf.Rozmiar)]\n self.FeromonyDelta = []\n poczatek = random.randint(0, graf.Rozmiar - 1)\n self.Odwiedzone.append(poczatek)\n self.ObecnyWierzcholek = poczatek\n self.Nieodwiedzone[poczatek] = False\n\n def _nastepny(self):\n calkowite_prawdobodobienstwo = 0.0\n wybrany = 0\n prawdopodobienstwa = [0.0 for i in range(self.Graf.Rozmiar)]\n for i in range(self.Graf.Rozmiar):\n if self.Nieodwiedzone[i]:\n try:\n prawdopodobienstwa[i] = pow(self.Graf.Feromon[self.ObecnyWierzcholek][i], self.Kolonia.Alfa) * \\\n pow(1.0 / self.Graf.DlugosciDrog[self.ObecnyWierzcholek][i], self.Kolonia.Beta) # TUTAJ ZMIENIALEM\n calkowite_prawdobodobienstwo += prawdopodobienstwa[i]\n except ZeroDivisionError:\n pass\n\n if calkowite_prawdobodobienstwo > 0.0:\n los = random.uniform(0.0, calkowite_prawdobodobienstwo)\n for i in range(self.Graf.Rozmiar):\n if self.Nieodwiedzone[i]:\n los -= prawdopodobienstwa[i]\n if los < 0.0:\n wybrany = i\n break\n\n\n\n\n self.Nieodwiedzone[wybrany] = False\n self.Odwiedzone.append(wybrany)\n self.KosztCalkowity += self.Graf.DlugosciDrog[self.ObecnyWierzcholek][wybrany]\n self.ObecnyWierzcholek = wybrany\n #print(wybrany)\n\n\n def _aktualizacja_feromonu_d(self):\n self.FeromonyDelta = [[0 for j in range(self.Graf.Rozmiar)] for i in range(self.Graf.Rozmiar)]\n for c in range(1, len(self.Odwiedzone)):\n i = self.Odwiedzone[c - 1]\n j = self.Odwiedzone[c]\n if self.Kolonia.Schemat == 1: # system jakosciowy\n self.FeromonyDelta[i][j] = self.Kolonia.Nasycenie\n elif self.Kolonia.Schemat == 2 and self.Graf.DlugosciDrog[i][j]: # system ilosciowy\n self.FeromonyDelta[i][j] = self.Kolonia.Nasycenie / self.Graf.DlugosciDrog[i][j]\n else: # system cyklowy\n self.FeromonyDelta[i][j] = self.Kolonia.Nasycenie / self.KosztCalkowity\n","sub_path":"ACO.py","file_name":"ACO.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"598687964","text":"tupla = ('Zero','Um','Dois','Três','Quatro',\n 'Cinco','Seis','Sete','Oito','Nove','Dez',\n 'Onze','Doze','Treze','Quatorze','Quinze',\n 'Dezesseis','Dezessete','Dezoito','Dezenove','Vinte')\n\nwhile True:\n n = int(input('Número emtre 0 e 20: '))\n if 0 <= n <= 20:\n break\n print('Tente novamente...', end=' ')\n\nprint(f'você digitou o número {tupla[n]}')\n\n\n\n\n\n","sub_path":"número_por_extenso.py","file_name":"número_por_extenso.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562135607","text":"#-*- coding:utf-8 -*-\n\n# 모듈 가져오기\n\nfrom flask import Flask, render_template, request, redirect, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Flask WAS 설정\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['JSON_AS_ASCII'] = False\n\n# DB 구성\n\ndb = SQLAlchemy(app)\n\nclass Talk(db.Model):\n __table_name__ = 'talk'\n\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(20), nullable=False)\n message = db.Column(db.String(100), nullable=False)\n\n def __init__(self, username, message):\n self.username = username\n self.message = message\n\ndb.create_all()\ndb.session.commit()\n\n\n# 서버 사이드 채팅방\n\n\n@app.route(\"/serverside\")\ndef serverside_list_page():\n talks = Talk.query.order_by(Talk.id.desc())\n\n return render_template(\"serverside_list.html\", talks=talks)\n\n\n@app.route(\"/serverside/talk\", methods=['POST'])\ndef serverside_add_page():\n username = request.form.get('username')\n message = request.form.get('message')\n\n talk = Talk(username=username, message=message)\n db.session.add(talk)\n db.session.commit()\n\n return redirect('/serverside')\n\n\n# 클라이언트 사이드 채팅방\n\n\n@app.route(\"/clientside\", methods=['GET'])\ndef clientside_page():\n return app.send_static_file(\"clientside_list.html\")\n\n\n@app.route(\"/clientside/talk\", methods=['GET'])\ndef clientside_list():\n talks = Talk.query.order_by(Talk.id.desc())\n\n json_talks = list(map(lambda talk: {\n 'username': talk.username,\n 'message': talk.message\n }, talks))\n\n return jsonify(json_talks)\n\n\n@app.route(\"/clientside/talk\", methods=['POST'])\ndef clientside_add():\n username = request.form.get('username')\n message = request.form.get('message')\n\n talk = Talk(username=username, message=message)\n db.session.add(talk)\n db.session.commit()\n\n return \"\"\n\n\n\n# 서버 시작부\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"623658690","text":"from django import forms\nfrom django_comments.forms import CommentForm\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_comments import get_model\n\n\nclass PimpedCommentForm(CommentForm):\n\n parent = forms.IntegerField(required=False, widget=forms.HiddenInput)\n\n def __init__(self, target_object, parent=None, data=None, initial=None):\n self.base_fields[\"title\"] = forms.CharField(\n label=_('Title'), required=False, max_length=getattr(settings, 'COMMENTS_TITLE_MAX_LENGTH', 255))\n\n self.parent = parent\n if initial is None:\n initial = {}\n initial.update({'parent': self.parent})\n super(PimpedCommentForm, self).__init__(target_object, data=data, initial=initial)\n\n def get_comment_model(self):\n return get_model()\n\n def get_comment_create_data(self):\n d = super(PimpedCommentForm, self).get_comment_create_data()\n d['parent_id'] = self.cleaned_data['parent']\n d['title'] = self.cleaned_data['title']\n return d\n\n def check_for_duplicate_comment(self, new):\n \"\"\"\n Check that a submitted comment isn't a duplicate. This might be caused\n by someone posting a comment twice. If it is a dup, silently return the *previous* comment.\n \"\"\"\n possible_duplicates = self.get_comment_model()._default_manager.using(\n self.target_object._state.db\n ).filter(\n content_type = new.content_type,\n object_pk = new.object_pk,\n user_name = new.user_name,\n user_email = new.user_email,\n user_url = new.user_url,\n )\n return new\n # for old in possible_duplicates:\n # if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:\n # return old\n #\n # return new","sub_path":"pimped_comments/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576784605","text":"import numpy as np\n\nM = [[4, 52, 81], # Azul ya\n [198, 51, 3], # Roj0 ***\n [39, 169, 43], # Verde pálido\n [228, 109, 6], # Naranja ya\n [153, 163, 30], # Amarillo ***\n [147, 165, 120], # Blanco\n [27, 55, 17]\n ] # Fondo\n\n\n\ndef mapeo(img):\n w = np.shape(img)[0]\n h = np.shape(img)[1]\n\n contador = np.zeros(7)\n\n for i in range(w):\n for j in range(h):\n\n if img[i, j, 2] == M[0][0] and img[i, j, 1] == M[0][1] and img[i, j, 0] == M[0][2]:\n contador[0] = contador[0] + 1\n\n if img[i, j, 2] == M[1][0] and img[i, j, 1] == M[1][1] and img[i, j, 0] == M[1][2]:\n contador[1] = contador[1] + 1\n\n if img[i, j, 2] == M[2][0] and img[i, j, 1] == M[2][1] and img[i, j, 0] == M[2][2]:\n contador[2] = contador[2] + 1\n\n if img[i, j, 2] == M[3][0] and img[i, j, 1] == M[3][1] and img[i, j, 0] == M[3][2]:\n contador[3] = contador[3] + 1\n\n if img[i, j, 2] == M[4][0] and img[i, j, 1] == M[4][1] and img[i, j, 0] == M[4][2]:\n contador[4] = contador[4] + 1\n\n if img[i, j, 2] == M[5][0] and img[i, j, 1] == M[5][1] and img[i, j, 0] == M[5][2]:\n contador[5] = contador[5] + 1\n\n if img[i, j, 2] == M[6][0] and img[i, j, 1] == M[6][1] and img[i, j, 0] == M[6][2]:\n contador[6] = 1\n\n moda = max(contador)\n indice = 0\n\n for i in range(7):\n if contador[i] == moda:\n indice = i\n\n if indice == 0:\n return 'B'\n if indice == 1:\n return 'R'\n if indice == 2:\n return 'G'\n if indice == 3:\n return 'O'\n if indice == 4:\n return 'Y'\n if indice == 5:\n return 'W'\n if indice == 6:\n return 'k'\n","sub_path":"WOS + MDM/mapeo_colores.py","file_name":"mapeo_colores.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"157962285","text":"\"\"\"\n通过pandas分析CSV文件数据\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\n\n\"\"\"\n将CSV文件数据以ANSI的方式放到pandas的dataframe数据类型里\nPandas基于两种数据类型:series与dataframe;\nseries是一个一维的数据类型,其中每一个元素都有一个标签,标签可以是数字或者字符串\ndataframe是一个二维的表结构,可以把它想象成一个series的字典项。\n\"\"\"\n##\ndf =pd.read_csv('./data_file/union_lotto.csv',header=0,encoding='ANSI')##header=0表示csv文件第一行为行名\nprint(df.head(3))###打印csv文件的前10行\nprint(df.tail(2))###打印CSV文件的后5行\n##修改dataframe数据的列名\ndf.columns=['date','red_1','red_2','red_3','red_4','red_5','red_6','blue']\nprint(df.head(1))\nprint('行数'+str(len(df)))###打印csv文件数据行数,不计算列名行\n\npd.options.display.float_format='{:,.3f}'.format\nprint(df.describe())\n# df.plot(x='date',title='双色球折线图')##画折线图\n# plt.yticks(range(1,34))##改变折线图的X轴\n# plt.xticks(range(1,34))##改变折线图的X轴\n# plt.savefig('./data_file/'+str(int(time.time()))+'.png')##保存图片到指定路径\n# # aa.plot(y='count',kind='bar')##画柱状图\n# aa.plot.bar(y='count',title='柱状图')\n# plt.savefig('./data_file/'+str(int(time.time()))+'.png')\n# aa.to_csv('./data_file/union_lotto_1.csv')##保存到csv文件中\n# plt.show()###直接显示图形,不保存图片\n\ndef pandas_data(path,n):\n df = pd.read_csv(path, header=0, encoding='ANSI')\n df_red = pd.Series(range(1, 34))\n # print((df_red.value_counts()-1).sort_index())\n if n ==0:\n df_red_1 = df.red_1.value_counts()\n df_red_2 = df.red_2.value_counts()\n df_red_3 = df.red_3.value_counts()\n df_red_4 = df.red_4.value_counts()\n df_red_5 = df.red_5.value_counts()\n df_red_6 = df.red_6.value_counts()\n else:\n df_red_1 = df.head(n).red_1.value_counts()\n df_red_2 = df.head(n).red_2.value_counts()\n df_red_3 = df.head(n).red_3.value_counts()\n df_red_4 = df.head(n).red_4.value_counts()\n df_red_5 = df.head(n).red_5.value_counts()\n df_red_6 = df.head(n).red_6.value_counts()\n df_red_1 = ((df_red.value_counts() - 1) + df_red_1).fillna(value=0)\n df_red_2 = ((df_red.value_counts() - 1) + df_red_2).fillna(value=0)\n df_red_3 = ((df_red.value_counts() - 1) + df_red_3).fillna(value=0)\n df_red_4 = ((df_red.value_counts() - 1) + df_red_4).fillna(value=0)\n df_red_5 = ((df_red.value_counts() - 1) + df_red_5).fillna(value=0)\n df_red_6 = ((df_red.value_counts() - 1) + df_red_6).fillna(value=0)\n df_red = (df_red_1 + df_red_2 + df_red_3 + df_red_4 + df_red_5 + df_red_6)\n dict_red__count = {'red': df_red.index, 'counts': df_red.values}\n df_red_count = pd.DataFrame(dict_red__count)\n df_red_count['counts']=df_red_count['counts'].astype(np.int64)###改变count列的数据类型为int\n # print(df_red_count)\n #df['列名'] = df['列名'].astype(np.int64)\n\n if n>0:\n n=str(n)\n else:\n n='所有'\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\n df_red_count.plot(x='red', y='counts', title=n+'场折线图')#画折线图\n plt.xticks(range(1,len(df_red_count.red)+1))##改变折线图的X轴\n # plt.yticks(range(0,max(df_red_count.counts)+10,10)) ##改变折线图的y轴\n plt.savefig('./data_file/' + str(int(time.time())) + '.png') ##保存图片到指定路径\n time.sleep(1)\n # df_red_count.plot(y='count',kind='bar')##画柱状图\n df_red_count.plot.bar(y='counts', title=n+'场柱状图')\n plt.savefig('./data_file/' + str(int(time.time())) + '.png')\n # plt.show()###直接显示图形,不保存图片\n # print(max(df_red_count.counts))\nif __name__ == \"__main__\":\n pandas_data('./data_file/union_lotto.csv',100)\n\n","sub_path":"data_analysis_union_lotto.py","file_name":"data_analysis_union_lotto.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"178453653","text":"#File containing numeric attribut processing functions\nimport numpy as np\nimport math \n\ndef is_numeric(x) :\n for i in range (0,len(x)) :\n try:\n float(x[i])\n except ValueError:\n return False\n \n return True\n\ndef is_continuous(x) :\n# Input : Np array \n if is_numeric(x) :\n if len(np.unique(x)) > 2 :\n return True\n else :\n return False \n else :\n return False\n\ndef process_numeric(M, target) :\n # Input : 2D numpy matrix containing attribute values\n n_attribute = M.shape[1] # Get number of columns/attributes\n M = M.astype(' %s\" % (threshold)\n\n\ndef _count_entropy(target_attributes):\n target_dictionary = dict()\n total = 0\n entropy = 0\n\n for val in target_attributes:\n if val in target_dictionary:\n target_dictionary[val] += 1\n else:\n target_dictionary[val] = 1\n total += 1\n\n for attr, val in target_dictionary.items():\n entropy += -val/total*(math.log2(val/total))\n\n return entropy\n\n\n\nm = np.array([[1,\"b\",1,\"a\"],[2,\"b\",2,\"b\"],[3,\"b\",3,\"c\"],[3,\"b\",3,\"d\"], [3,\"b\",3,\"e\"], [4,\"b\",4,\"f\"]])\ntarget = np.array([0,0,1,1,1,1])\n\n","sub_path":"Bagian D/clf/c45_numeric_handler.py","file_name":"c45_numeric_handler.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345488106","text":"# coding=utf8\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass MyRegistrationForm(UserCreationForm):\n\temail = forms.EmailField(required = True)\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ('username', 'email', 'password1', 'password2')\n\tdef save(self, commit=True):\n\t\tuser = super(MyRegistrationForm, self).save(commit=False)\n\t\tuser.email = self.cleaned_data['email']\n\t\tif commit:\n\t\t\tuser.save()\n\t\treturn user\n\nclass MyBugReportForm(forms.Form):\n\ttitle = forms.CharField(max_length=30, required=False, help_text='Qual bug você encontrou?')\n\tbody = forms.CharField(max_length=3000, widget=forms.Textarea, required=True)\n\tdef display(self):\n\t\t#honestamente, não sei o que está havendo aqui.\n\t\t#mas está funcionando...\n\t\treturn self._html_output(\n\t\t\tnormal_row = '%(label)s%(errors)s%(field)s%(help_text)s',\n error_row = '%s',\n row_ender = '',\n help_text_html = '
%s',\n errors_on_separate_row = False\n \t\t\t\t\t)","sub_path":"Forum/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"208097623","text":"from flask import render_template, jsonify, request\nfrom apps.api import api_blueprint, docker_api\nfrom apps.api.errors import *\n\n\n@api_blueprint.route('/containers', methods=['GET'])\ndef list_containers():\n started = []\n stopped = []\n running_containers = docker_api.containers()\n stopped_containers = docker_api.containers(filters={'status': 'exited'})\n stopped_containers += docker_api.containers(filters={'status': 'paused'})\n stopped_containers += docker_api.containers(filters={'status': 'created'})\n for container in running_containers: \n c_id = container['Id']\n c_name = container['Names'][0]\n c_status = container['Status']\n started.append({\n 'id': c_id,\n 'name': c_name,\n 'status': c_status \n }) \n for container in stopped_containers: \n c_id = container['Id']\n c_name = container['Names'][0]\n c_status = container['Status']\n stopped.append({\n 'id': c_id,\n 'name': c_name,\n 'status': c_status \n }) \n\n response = {'started': started, 'stopped': stopped}\n return jsonify(response)\n\n@api_blueprint.route('/container', methods=['PUT'])\ndef create_container():\n if not request.is_json:\n return missing_json_request()\n\n image = request.json.get('docker_image')\n name = request.json.get('docker_name')\n command = request.json.get('docker_cmd')\n\n if not image:\n return missing_parameter('docker_image')\n\n try:\n docker_api.create_container(image=image, name=name, command=command)\n return success_in_request()\n except:\n return error_creating_container()\n\n@api_blueprint.route('/container/', methods=['POST', 'DELETE'])\ndef change_container(c_id):\n if request.method == 'DELETE':\n try:\n docker_api.remove_container(c_id)\n return success_in_request()\n except:\n return error_changing_container()\n \n else:\n if not request.is_json:\n return missing_json_request()\n \n action = request.json.get('action')\n if not action:\n return missing_parameter()\n \n try:\n if action == 'start':\n docker_api.start(c_id)\n elif action == 'stop':\n docker_api.stop(c_id)\n else:\n return missing_parameter()\n return success_in_request()\n except:\n return error_changing_container()\n\n \n","sub_path":"apps/api/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"267961008","text":"from pdf2docx import Converter\nimport PySimpleGUI as sg\n\n\ndef pdf2word(file_path):\n file_name = file_path.split('.')[0]\n doc_file = f'{file_name}.docx'\n p2w = Converter(file_path)\n p2w.convert(doc_file, start=0, end=None)\n p2w.close()\n return doc_file\n\n\ndef main():\n # 选择主题\n sg.theme('DarkAmber')\n\n layout = [\n [sg.Text('pdfToword', font=('微软雅黑', 12)),\n sg.Text('', key='filename', size=(50, 1), font=('微软雅黑', 10))],\n [sg.Output(size=(80, 10), font=('微软雅黑', 10))],\n [sg.FilesBrowse('选择文件', key='file', target='filename'), sg.Button('开始转换'), sg.Button('退出')]]\n # 创建窗口\n window = sg.Window(\"pdf2docx\", layout, font=(\"微软雅黑\", 15), default_element_size=(50, 1))\n # 事件循环\n while True:\n # 窗口的读取,有两个返回值(1.事件;2.值)\n event, values = window.read()\n print(event, values)\n\n if event == \"开始转换\":\n\n if values['file'] and values['file'].split('.')[1] == 'pdf':\n filename = pdf2word(values['file'])\n print('文件个数 :1')\n print('\\n' + '转换成功!' + '\\n')\n print('文件保存位置:', filename)\n elif values['file'] and values['file'].split(';')[0].split('.')[1] == 'pdf':\n print('文件个数 :{}'.format(len(values['file'].split(';'))))\n for f in values['file'].split(';'):\n filename = pdf2word(f)\n print('\\n' + '转换成功!' + '\\n')\n print('文件保存位置:', filename)\n else:\n print('请选择pdf格式的文件哦!')\n if event in (None, '退出'):\n break\n\n window.close()\n\n\nmain()","sub_path":"api_doc_doc_trans_demo.py/pdf2wordtest.py","file_name":"pdf2wordtest.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"289129275","text":"##Binary Search Tree\n\nclass BinarySearchTreeNode:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n \n def add_node(self, data):\n if(data == self.data):\n #data already exist\n return\n if(data < self.data):\n #data is less add to left\n if(self.left):\n #if it is not a leaf node\n self.left.add_node(data)\n else:\n self.left = BinarySearchTreeNode(data)\n else:\n #add to right\n if(self.right):\n #if it is not a leaf node\n self.right.add_node(data)\n else:\n self.right = BinarySearchTreeNode(data)\n \n def search(self, value):\n \n if(self.data == value):\n return True\n \n if(value < self.data):\n if(self.left):\n return self.left.search(value)\n else:\n return False\n if(value > self.data):\n if(self.right):\n return self.right.search(value)\n else:\n return False\n \n def find_min(self):\n if(self.left):\n return self.left.find_min()\n else:\n return self.data\n \n def find_max(self):\n if(self.right):\n return self.right.find_max()\n else:\n return self.data\n \n def in_order_traversal(self):\n elements = []\n # left -> root -> right\n if self.left:\n elements += self.left.in_order_traversal()\n \n elements.append(self.data)\n \n if self.right:\n elements += self.right.in_order_traversal()\n \n return elements\n \n def calculate_sum(self):\n sum = self.data\n if(self.left):\n sum += self.left.calculate_sum()\n if(self.right):\n sum += self.right.calculate_sum()\n return sum\n \n '''def sum_of_two_pairs(self, aSum, aSet):\n if((aSum - self.data) in aSet):\n return (\"Pair found: \" + str(self.data) +\",\" + str(aSum - self.data))\n else:\n aSet.append(self.data)\n if(self.right):\n return self.right.sum_of_two_pairs(aSum, aSet)\n if(self.left):\n return self.left.sum_of_two_pairs(aSum, aSet) \n return \"Pair Not Found\" '''\n \ndef build_tree(lists):\n tree = BinarySearchTreeNode(lists[0])\n for i in range(1, len(lists)):\n tree.add_node(lists[i])\n return tree\n\nif __name__ == \"__main__\":\n lists = [14, 88, 12, 7, 27, 23, 20, 15]\n tree = build_tree(lists)\n print(\"Inorder Travarsal = \", tree.in_order_traversal())\n #print(tree.search(27))\n #print(tree.find_min())\n #print(tree.find_max())\n #print(tree.calculate_sum())\n #print(tree.sum_of_two_pairs(aSum = 100,aSet = [])) #wrong","sub_path":"dataStructures/BinarySearchTree.py","file_name":"BinarySearchTree.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419837625","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Example 1: GiGA Genie Keyword Spotting\"\"\"\n\nfrom __future__ import print_function\n\nimport pyaudio\nimport audioop\nimport RPi.GPIO as GPIO\nimport ktkws\nimport aimakerskitutil as aikit\nimport gkit._audio as gkitAudio\n\n\nKWSID = ['기가지니', '지니야', '친구야', '자기야']\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(29, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(31, GPIO.OUT)\nbtnStatus = False\n\ndef callback(channel):\n\tprint(\"falling edge detected from pin {}\".format(channel))\n\tglobal btnStatus\n\tbtnStatus = True\n\tprint(btnStatus)\n\nGPIO.add_event_detect(29, GPIO.FALLING, callback=callback, bouncetime=10)\n\n\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 16000\nCHUNK = 512\n\ndef detect():\n\twith gkitAudio.MicrophoneStream(RATE, CHUNK) as stream:\n\t\taudio_generator = stream.generator()\n\n\t\tfor content in audio_generator:\n\n\t\t\trc = ktkws.detect(content)\n\t\t\trms = audioop.rms(content,2)\n\t\t\t#print('audio rms = %d' % (rms))\n\n\t\t\tif (rc == 1):\n\t\t\t\tgkitAudio.playWav(\"../data/sample_sound.wav\")\n\t\t\t\treturn 200\n\ndef detectButton():\n\tglobal btnStatus\n\trc = 10 # Start rc\n\twhile True:\n\t\tGPIO.output(31, GPIO.HIGH)\n\t\tif (btnStatus == True):\n\t\t\trc = 1\n\t\t\tbtnStatus = False\n\t\tif (rc == 1):\n\t\t\tGPIO.output(31, GPIO.LOW)\n\t\t\tgkitAudio.playWav(\"../data/sample_sound.wav\")\n\t\t\treturn 200\n\t\t\tbreak\n\ndef test(keyWord = '기가지니'):\n\trc = ktkws.init(\"../data/kwsmodel.pack\")\n\tprint ('init rc = {}'.format(rc))\n\trc = ktkws.start()\n\tprint ('start rc = {}'.format(rc))\n\tprint ('\\n호출어를 불러보세요~\\n')\n\tktkws.set_keyword(KWSID.index(keyWord))\n\trc = detect()\n\tprint ('detect rc = {}'.format(rc))\n\tprint ('\\n\\n호출어가 정상적으로 인식되었습니다.\\n\\n')\n\tktkws.stop()\n\treturn rc\n\ndef btnTest():\n\tprint ('\\n버튼을 눌러보세요~\\n')\n\tglobal btnStatus\n\trc = detectButton()\n\tprint ('detect rc = {}'.format(rc))\n\tprint ('\\n\\n버튼이 정상적으로 인식되었습니다.\\n\\n')\n\treturn rc\n\ndef main():\n\tbtnTest()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"python/ex1_kwstest.py","file_name":"ex1_kwstest.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"312643353","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n'''Aqui iremos fazer o histograma do refino do petróleo nacional entre as regiões do Brasil, nos anos de 1990 a 2018 '''\r\n\r\n#Carregamento do dataframe principal\r\ndados = pd.read_csv('processamento-petroleo-m3-1990-2018.csv', sep = ';', decimal = ',', encoding = 'utf-8')\r\n\r\n#Separaremos o refino total do petróleo nacional por região, colocando em listas\r\nnorte, nordeste, sudeste, sul = ([] for i in range(4))\r\n\r\n#Aqui está uma estrutura de laço para separar cada estado refinador nas suas respectivas listas\r\nfor index, column in dados.iterrows():\r\n if column['ESTADO'] == 'AMAZONAS' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n n = column['TOTAL'], column['ANO']\r\n norte.append(n)\r\n elif column['ESTADO'] == 'BAHIA' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n ne = column['TOTAL'], column['ANO']\r\n nordeste.append(ne)\r\n elif column['ESTADO'] == 'CEARÁ' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n ne = column['TOTAL'], column['ANO']\r\n nordeste.append(ne)\r\n elif column['ESTADO'] == 'PERNAMBUCO' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n ne = column['TOTAL'], column['ANO']\r\n nordeste.append(ne)\r\n elif column['ESTADO'] == 'RIO GRANDE DO NORTE' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n ne = column['TOTAL'], column['ANO']\r\n nordeste.append(ne)\r\n elif column['ESTADO'] == 'MINAS GERAIS' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n sd = column['TOTAL'], column['ANO']\r\n sudeste.append(sd)\r\n elif column['ESTADO'] == 'RIO DE JANEIRO' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n sd = column['TOTAL'], column['ANO']\r\n sudeste.append(sd)\r\n elif column['ESTADO'] == 'SÃO PAULO' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n sd = column['TOTAL'], column['ANO']\r\n sudeste.append(sd)\r\n elif column['ESTADO'] == 'PARANÁ' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n s = column['TOTAL'], column['ANO']\r\n sul.append(s)\r\n elif column['ESTADO'] == 'RIO GRANDE DO SUL' and column['MATÉRIA PRIMA'] == 'PETRÓLEO NACIONAL ':\r\n s = column['TOTAL'], column['ANO']\r\n sul.append(s)\r\n\r\n#Criação de uma função para o novo dataframe com a soma de todo o refino regional anual\r\ndef dataframe(x):\r\n x = pd.DataFrame(list(x))\r\n x.columns = ['TOTAL (m³)','ANO']\r\n x = x.groupby(['ANO'])['TOTAL (m³)'].sum().to_frame().reset_index()\r\n return x\r\n\r\n#Transformando as novas listas em dataframes\r\nnorte = dataframe(norte)\r\nnordeste = dataframe(nordeste)\r\nsudeste = dataframe(sudeste)\r\nsul = dataframe(sul)\r\n\r\n#Criação de uma função para gerar o gráfico com a soma de todo o refino regional anual\r\ndef histograma(x):\r\n plt.figure(figsize = (10, 5))\r\n plt.xticks(x['ANO'], rotation = 'vertical')\r\n plt.xlabel('Refino Petróleo Nacional anual')\r\n plt.ylabel('Total Refino Anual (m³)')\r\n if x is norte:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'blue')\r\n plt.title('Processo de refino de petróleo nacional na região Norte')\r\n elif x is nordeste:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'red')\r\n plt.title('Processo de refino de petróleo nacional na região Nordeste')\r\n elif x is sudeste:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'yellow')\r\n plt.title('Processo de refino de petróleo nacional na região Sudeste')\r\n else:\r\n plt.bar(x.iloc[:, 0], x.iloc[:, 1], color = 'green')\r\n plt.title('Processo de refino de petróleo nacional na região Sul')\r\n\r\n#Visualização dos histogramas de cada região\r\nhistograma(norte)\r\nhistograma(nordeste)\r\nhistograma(sudeste)\r\nhistograma(sul)\r\n\r\n#Gráfico com todos as regiões refinadoras de petróleo nacional\r\nbarWidth = 0.2\r\nplt.figure(figsize = (15, 5))\r\nr1 = np.arange(len(norte.iloc[:, 0]))\r\nr2 = [x + barWidth for x in r1]\r\nr3 = [x + barWidth for x in r2]\r\nr4 = [x + barWidth for x in r3]\r\nplt.bar(r1, norte.iloc[:, 1], width = barWidth, color = '#FFA500', label = 'NORTE')\r\nplt.bar(r2, nordeste.iloc[:, 1], width = barWidth, color = '#FFD700', label = 'NORDESTE')\r\nplt.bar(r3, sudeste.iloc[:, 1], width = barWidth, color = '#FFFF00', label = 'SUDESTE')\r\nplt.bar(r4, sul.iloc[:, 1], width = barWidth, color = '#F0E68C', label = 'SUL')\r\nplt.xlabel('Produção Anual')\r\nplt.xticks([r + barWidth for r in range(len(norte.iloc[:, 0]))], norte['ANO'], rotation = 'vertical')\r\nplt.ylabel('Total Produção Anual (m³)')\r\nplt.title('Refino do petróleo nacional nas regiões brasileiras')\r\nplt.legend(loc = 'best')\r\nplt.show() \r\n","sub_path":"histograma refino petroleo nacional (1990 - 2018) (região).py","file_name":"histograma refino petroleo nacional (1990 - 2018) (região).py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"583332011","text":"from MultiInputOutputObject import MultiInputOutputObject, ControlType\n\nclass AnalogMixerOutput(MultiInputOutputObject):\n \"\"\"\n A class to represent an output object that mixes two analog inputs.\n\n It inherits attributes and methods from MultiInputOutputObject.\n\n ...\n\n :Attributes:\n * **name**\\ (\\ *str*\\ ) -- name of the servo group for the output\n * **num_outputs**\\ (\\ *int*\\ ) -- total number of outputs \n calculated from the given input\n * **channels_output**\\ (\\ *[int]*\\ ) -- channels corresponding to \n the servos controlled by the outputs\n * **maximums_output**\\ (\\ *[int]*\\ ) -- maximum pulse width values \n for the corresponding servo channel\n * **minimums_output**\\ (\\ *[int]*\\ ) -- minimum pulse width values \n for the corresponding servo channel\n * **default_output**\\ (\\ *[int]*\\ ) -- default output position of \n the servos for start up position and used for some multi input \n objects\n * **current_output**\\ (\\ *[int]*\\ ) -- current output position of the \n servos to be used for increment mode or multi input objects\n * **maximum_input**\\ (\\ *int*\\ ) -- maximum input value used for mapping \n inputs to outputs, 255 for analog and 1 for digital\n * **minimum_input**\\ (\\ *int*\\ ) -- minimum input value used for mapping \n inputs to outputs, 0 for both analog and digital\n * **is_inverted**\\ (\\ *[Boolean]*\\ ) -- whether to invert the output \n mapping\n * **control_type**\\ (\\ *Enum ControlType*\\ ) -- mode on how to determine \n the output\n * **toggle_state**\\ (\\ *Enum ToggleState*\\ ) -- used when control mode \n is set to TOGGLE to determine the current output state\n * **names_input**\\ (\\ *[str]*\\ ) -- list of the input names used by \n the object, this allows the object to know which input value to \n update\n * **num_inputs**\\ (\\ *int*\\ ) -- number of inputs the object uses\n * **current_input**\\ (\\ *[int]*\\ ) -- since input is given one at a \n time, this list keeps track of previous inputs\n * **out_raw_min**\\ (\\ *int*\\ ) -- minimum value of an intermediate \n value used to calculate output\n * **out_raw_max**\\ (\\ *int*\\ ) -- maximum value of an intermediate \n value used to calculate output\n * **raw_output**\\ (\\ *[int]*\\ ) -- list to store the calculated \n intermediate values that will be mapped to final output values\n\n ...\n\n **Methods**\n\n \"\"\"\n\n def __init__(self, name, num_outputs, channels_output, names_input):\n \"\"\"\n Class constructor. Assigns the values passed in and initalizes remaining \n members to default values.\n\n :param name: name of the output group represented by output object\n :type name: string\n :param num_outputs: number of output channels controlled by the output \n object\n :type num_outputs: int\n :param channels_output: list of the output channels used by the object\n :type channels_output: [int]\n :param names_input: the names of the associated controller inputs with \n the object\n :type names_input: [str]\n \"\"\"\n super().__init__(name, num_outputs, channels_output, names_input)\n\n def get_output(self, input_name, input_value):\n \"\"\"\n Calculate and returns the output based on the given input value and \n current control mode.\n\n :param input_name: name associated with the input, this object does not \n use this value\n :type input_name: str\n :param input_value: the input value from the PS4 controller\n :type input_value: int\n\n :return: Two lists. The first list is the output channels and the second \n is output values for those channels (in units of quarter of milliseconds).\n\n How the ouptut is calculated is based off of which control type the output \n object is set to. Direct will map the output directly based on the input \n and the set input and output ranges. Toggle will set the output between the \n max and the min output values and switch between these values whenever the \n input is released. Increment will increment the output value whenever input \n is given.\n :rtype: [[int], [int]]\n \"\"\"\n # TODO Write functions for each if statement\n if self.control_type is ControlType.DIRECT:\n # Update corresponding input value\n for i in range(self.num_inputs):\n if self.names_input[i] == input_name:\n self.current_input[i] = input_value\n\n # The first input is assumed to be for tilting head left and right\n # The second input is assumed to be for tilting head up and down\n raw_output = self.current_input[0] - self.current_input[1] + self.maximum_input\n\n # Mapping to the outputs to send to the Maestro board\n for i in range(self.num_outputs):\n self.current_output[i] = self.map_values(raw_output, self.out_raw_min, self.out_raw_max,\n self.minimums_output[i], self.maximums_output[i])\n return [self.channels_output, self.current_output]\n\n elif self.control_type is ControlType.INCREMENT:\n # TODO Finish output\n return [self.channels_output, self.current_output]\n\n else:\n return [self.channels_output, self.current_output]","sub_path":"movementMapping/AnalogMixerOutput.py","file_name":"AnalogMixerOutput.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"92727384","text":"import io\n\nfrom ruamel.yaml import YAML\nfrom ruamel.yaml.representer import RoundTripRepresenter\n\n\nclass CustomRepresenter(RoundTripRepresenter):\n def ignore_aliases(self, _data):\n return True\n\n\ndef load(data):\n yaml = YAML()\n yaml.Representer = CustomRepresenter\n return yaml.load(data)\n\n\ndef dump(data, stream=None):\n if not stream:\n stream = io.StringIO()\n\n yaml = YAML(typ='safe')\n yaml.default_flow_style = False\n yaml.Representer = CustomRepresenter\n\n res = yaml.dump(data, stream=stream)\n\n if isinstance(stream, io.StringIO):\n res = stream.getvalue()\n\n return res\n","sub_path":"openapi_toolkit/yaml.py","file_name":"yaml.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"198236874","text":"from django.core.management.base import BaseCommand\nfrom location_register.models.address_models import Country\nfrom business_register.models.declaration_models import Property\nfrom business_register.models.sanction_models import Company, CompanySanction, PersonSanction, CountrySanction\n\n\nclass Command(BaseCommand):\n help = 'Trim name field in Country'\n\n def handle(self, *args, **options):\n self.trim_country_names()\n\n @staticmethod\n def trim_country_names():\n countries = Country.objects.all()\n\n for country in countries:\n new_country_name = country.name.strip()\n if country.name == new_country_name:\n continue\n try:\n duplicate = Country.objects.get(name=new_country_name)\n except Country.DoesNotExist:\n country.name = new_country_name\n country.save(update_fields=['name'])\n continue\n\n person_sanctions = PersonSanction.objects.filter(countries_of_citizenship=country)\n for person_sanction in person_sanctions:\n person_sanction.countries_of_citizenship.remove(country)\n person_sanction.countries_of_citizenship.add(duplicate)\n\n companies = Company.objects.filter(country_id=country.id)\n for company in companies:\n company.country_id = duplicate.id\n company.save(update_fields=['country_id'])\n\n company_sanctions = CompanySanction.objects.filter(country_of_registration_id=country.id)\n for company_sanction in company_sanctions:\n company_sanction.country_of_registration_id = duplicate.id\n company_sanction.save(update_fields=['country_of_registration_id'])\n\n country_sanctions = CountrySanction.objects.filter(country_id=country.id)\n for country_sanction in country_sanctions:\n country_sanction.country_id = duplicate.id\n country_sanction.save(update_fields=['country_id'])\n\n properties = Property.objects.filter(country_id=country.id)\n for property in properties:\n property.country_id = duplicate.id\n property.save(update_fields=['country_id'])\n\n country.delete()\n","sub_path":"location_register/management/commands/trim_country_names.py","file_name":"trim_country_names.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"564482456","text":"#C# code generator (exactly the same as java actually)\n#Copyright (C) 2007 Jesse Fish\n#\n#This file is part of code_generator.py\n#\n# code_generator.py 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\ndef makefile(filename,text):\n\tblocklevel=0\n\taccess=\"public\"\n\t\n\toutfile=open(filename+'.cs','w')\n\toutfile.write(\"public class \"+ filename+\"\\n\")\n\toutfile.write(\"{\\n\")\n\tblocklevel= blocklevel+1\n\tvars=[\"\"]\n\tcommenting=False\n\tfor curtext in text[2:]:\n\n\t\tcurtext=curtext.strip('\\n ')\n\t\tif len(curtext)>0:\n\t\t\tif commenting:\n\t\t\t\toutfile.write(blocklevel*\"\\t\"+curtext+\"\\n\")\n\t\t\t\tif len(curtext)>0:\n\t\t\t\t\tif(curtext[-1]=='/' and curtext[-2]=='*' ):\n\t\t\t\t\t\tcommenting=False\n\t\t\telse:\n\t\t\t\t#print curtext\n\t\t\t\tif(curtext[0] =='/' and curtext[1] == '*'):\n\t\t\t\t\tcommenting=True\n\t\t\t\t\toutfile.write(blocklevel*\"\\t\"+curtext+\"\\n\")\n\t\t\t\t\t#print 'multiline comment'\n\t\t\t\telif (curtext[0] =='/' and curtext[1] == '/'):\n\t\t\t\t\t#print 'inline comment'\n\t\t\t\t\toutfile.write(blocklevel*\"\\t\"+curtext+\"\\n\")\n\t\t\t\t\n\t\t\t\telif ((curtext)[-1] == ':'):\n\t\t\t\t\t#handle access settings\n\t\t\t\t\taccess= curtext[:-1]\n\t\t\t\t\t#print access\n\t\t\t\telse:\n\t\t\t\t\t#handle variable creation\n\t\t\t\t\tcurtext= curtext.strip(';')\n\t\t\t\t\toutfile.write(blocklevel*\"\\t\"+access+\" \"+curtext+\";\\n\")\n\t\t\t\t\tif(access != \"public\"):\n\t\t\t\t\t\tcurtext =curtext.strip(';')\n\t\t\t\t\t\tbreakspot= curtext.find('=')\n\t\t\t\t\t\tif breakspot<0:\n\t\t\t\t\t\t\tvars.append(curtext)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tvars.append(curtext[:breakspot])\n\t\t\t\t\t\t#print vars\n\t#end of for loop\n\n\t#next generate the get/set functions\n\toutfile.write(\"\\n\"+blocklevel*\"\\t\"+\"//get and set functions\\n\")\n\tfor curvar in vars[1:]:\n\t\tnewtext= curvar.split()\n\t\t#print newtext\n\t\tstaticity=\"\"\n\t\tif newtext[0] == \"static\":\n\t\t\tstaticity=\"static \"\n\t\tvarname=newtext[-1]\n\t\tvartype=newtext[-2]\n\t\t#print staticity\n\t\t#write set statement\n\t\toutfile.write(blocklevel*\"\\t\"+\"public \"+ staticity+\"void \" +\"set_\"+varname+\"(\"+ vartype+\" temp)\"+\"\\n\"+blocklevel*\"\\t\"+\"{\\n\")\n\t\tblocklevel= blocklevel+1\n\t\toutfile.write(blocklevel*\"\\t\"+ varname+\" = temp;\\n\")\n\t\tblocklevel= blocklevel-1\n\t\toutfile.write(blocklevel*\"\\t\"+\"}\\n\")\n\t\t\n\t\t#write get statement\n\t\toutfile.write(blocklevel*\"\\t\"+\"public \"+ staticity+ vartype +\" get_\"+ varname +\"()\"+\"\\n\"+blocklevel*\"\\t\"+\"{\\n\")\n\t\tblocklevel= blocklevel+1\n\t\toutfile.write(blocklevel*\"\\t\"+\"return \"+ varname +\";\\n\")\n\t\tblocklevel= blocklevel-1\n\t\toutfile.write(blocklevel*\"\\t\"+\"}\\n\")\n\n\n\t#close the class\n\toutfile.write(\"}\\n\")\n#end of function","sub_path":"src/Cscodegen.py","file_name":"Cscodegen.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204885649","text":"from __future__ import (absolute_import, division, print_function)\n\nimport numpy as np\nfrom .harmonics import ut_E\nfrom .utilities import Bunch\n\n\ndef reconstruct(t, coef, **opts):\n \"\"\"\n Reconstruct a tidal signal.\n\n Parameters\n ----------\n t : array_like\n Time in days since `epoch`.\n coef : `Bunch`\n Data structure returned by `utide.solve`\n epoch : {string, int, `datetime.datetime`}, optional\n Not implemented yet. It will default to the epoch\n used for `coef`.\n\n Returns\n -------\n tide : `Bunch`\n Scalar time series is returned as `tide.h`; a vector\n series as `tide.u`, `tide.v`.\n\n \"\"\"\n\n out = Bunch()\n u, v = _reconstr1(t, coef, **opts)\n if coef['aux']['opt']['twodim']:\n out.u, out.v = u, v\n else:\n out.h = u\n return out\n\n\ndef _reconstr1(tin, coef, **opts):\n\n print('reconstruct:')\n\n # Parse inputs and options.\n t, opt = _rcninit(tin, **opts)\n\n # Determine constituents to include.\n # if ~isempty(opt.cnstit)\n # if not np.empty(opt['cnstit']):\n if opt['cnstit']:\n\n # [~,ind] = ismember(cellstr(opt.cnstit),coef.name);\n # opt['cnstit'] in coef['name']\n ind = np.where(opt['cnstit'] == coef['name'])\n\n# if ~isequal(length(ind),length(cellstr(opt.cnstit)))\n# error(['reconstruct: one or more of input constituents Cnstit '...\n# 'not found in coef.name']);\n else:\n\n ind = np.arange(len(coef['aux']['frq']))\n if coef['aux']['opt']['twodim']:\n SNR = ((coef['Lsmaj']**2 + coef['Lsmin']**2) /\n ((coef['Lsmaj_ci']/1.96)**2 + (coef['Lsmin_ci']/1.96)**2))\n\n PE = sum(coef['Lsmaj']**2 + coef['Lsmin']**2)\n PE = 100*(coef['Lsmaj']**2 + coef['Lsmin']**2)/PE\n else:\n SNR = (coef['A']**2)/((coef['A_ci']/1.96)**2)\n PE = 100*coef['A']**2/sum(coef['A']**2)\n\n # ind = ind[SNR[ind]>=opt['minsnr'] & PE[ind]>=opt['minpe']]\n ind = np.where(np.logical_and(SNR[ind] >= opt['minsnr'],\n PE[ind] >= opt['minpe']))[0]\n\n # Complex coefficients.\n rpd = np.pi/180\n if coef['aux']['opt']['twodim']:\n ap = 0.5 * ((coef['Lsmaj'][ind] + coef['Lsmin'][ind]) *\n np.exp(1j*(coef['theta'][ind] - coef['g'][ind]) * rpd))\n am = 0.5 * ((coef['Lsmaj'][ind] - coef['Lsmin'][ind]) *\n np.exp(1j*(coef['theta'][ind] + coef['g'][ind]) * rpd))\n else:\n ap = 0.5 * coef['A'][ind] * np.exp(-1j*coef['g'][ind] * rpd)\n am = np.conj(ap)\n\n # Exponentials.\n\n ngflgs = [coef['aux']['opt']['nodsatlint'],\n coef['aux']['opt']['nodsatnone'],\n coef['aux']['opt']['gwchlint'],\n coef['aux']['opt']['gwchnone']]\n\n print('prep/calcs...')\n\n E = ut_E(t,\n coef['aux']['reftime'], coef['aux']['frq'][ind],\n coef['aux']['lind'][ind], coef['aux']['lat'], ngflgs,\n coef['aux']['opt']['prefilt'])\n\n # Fit.\n # fit = E*ap + np.conj(E)*am\n fit = np.dot(E, ap) + np.dot(np.conj(E), am)\n\n # Mean (& trend).\n u = np.nan * np.ones(tin.shape)\n whr = ~np.isnan(tin)\n if coef['aux']['opt']['twodim']:\n v = np.nan * np.ones(tin.shape)\n if coef['aux']['opt']['notrend']:\n u[whr] = np.real(fit) + coef['umean']\n v[whr] = np.imag(fit) + coef['vmean']\n else:\n u[whr] = np.real(fit) + coef['umean']\n u[whr] += coef['uslope'] * (t-coef['aux']['reftime'])\n v[whr] = np.imag(fit) + coef['vmean']\n v[whr] += coef['vslope'] * (t-coef['aux']['reftime'])\n\n else:\n if coef['aux']['opt']['notrend']:\n u[whr] = np.real(fit) + coef['mean']\n else:\n u[whr] = np.real(fit) + coef['mean']\n u[whr] += coef['slope'] * (t-coef['aux']['reftime'])\n\n v = []\n\n print('Done.\\n')\n\n return u, v\n\n\ndef _rcninit(tin, **opts):\n\n t = tin[:]\n\n t[np.isnan(t)] = []\n # t(isnan(t)) = []\n opt = {}\n\n opt['cnstit'] = False\n opt['minsnr'] = 2\n opt['minpe'] = 0\n\n for key, item in opts.items():\n try:\n opt[key] = item\n except KeyError:\n print('reconstruct: unrecognized input: {0}'.format(key))\n\n # args = list(args)\n # args = [string.lower() for string in args]\n\n # Need an example of the args\n\n# while ~isempty(args)\n# switch(lower(args{1}))\n# case 'cnstit'\n# opt.cnstit = args{2};\n# args(1:2) = [];\n# case 'minsnr'\n# opt.minsnr = args{2};\n# args(1:2) = [];\n# case 'minpe'\n# opt.minpe = args{2};\n# args(1:2) = [];\n# otherwise\n# error(['reconstruct: unrecognized input: ' args{1}]);\n# end\n# end\n\n return t, opt\n","sub_path":"utide/_reconstruct.py","file_name":"_reconstruct.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"121525592","text":"import sys\nfrom decimal import Decimal as D\nread=lambda:sys.stdin.readline().rstrip()\nwrite=lambda x:sys.stdout.write(str(x)+\"\\n\")\nC,K=map(int, read().split())\nfv = 10**K\nq,r = divmod(C, fv)\nif D(r/float(fv)) - D(0.5) >= D(0):\n write((q+1)*fv)\nelse:\n write(q*fv)","sub_path":"implementation/face_value_2909.py","file_name":"face_value_2909.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"163852221","text":"# coding: utf-8\nfrom sqlalchemy import Column, DateTime, VARCHAR\nfrom sqlalchemy.dialects.oracle.base import NUMBER\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\nmetadata = Base.metadata\n\n\nclass IfBscNtsLiqDi(Base):\n __tablename__ = 'if_bsc_nts_liq_dis'\n\n l_date = Column(NUMBER(scale=0, asdecimal=False), primary_key=True)\n vc_scode = Column(VARCHAR(22))\n vc_code = Column(VARCHAR(20))\n l_market = Column(NUMBER(scale=0, asdecimal=False))\n l_end_date = Column(NUMBER(scale=0, asdecimal=False))\n l_publish_date = Column(NUMBER(scale=0, asdecimal=False))\n vc_type_name = Column(VARCHAR(200))\n vc_type_code = Column(VARCHAR(50))\n l_ltshare_date = Column(NUMBER(scale=0, asdecimal=False))\n en_risk = Column(NUMBER(asdecimal=False))\n d_updatetime = Column(DateTime)\n vc_data_source = Column(VARCHAR(10))\n\n","sub_path":"worker_fd/model/if_bsc_nts_liq_dis.py","file_name":"if_bsc_nts_liq_dis.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"26591255","text":"# %load q05_runs/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n\n# Your Solution\ndef BC_runs(data):\n deliveries = data['innings'][0]['1st innings']['deliveries']\n #deliveries\n runs =0\n for i1 in deliveries:\n #print(i)\n for i2 in i1.items():\n if i2[1]['batsman'] == 'BB McCullum':\n runs = runs+i2[1]['runs']['batsman']\n #print(i2)\n # Write your code here\n return(runs)\n\ndeliveries = data['innings'][0]['1st innings']['deliveries']\n#deliveries\nc =0\nfor i1 in deliveries:\n #print(i)\n for i2 in i1.items():\n if i2[1]['batsman'] == 'BB McCullum':\n c = c+i2[1]['runs']['batsman']\n #print(i2)\n\n\n","sub_path":"q05_runs/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"74756590","text":"import HTMLParser\nimport Levenshtein\n\nfrom django.utils import timezone\n\nfrom rest_framework import generics, status, views\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom brouwers.forum_tools.models import Topic\nfrom brouwers.forum_tools.api.serializers import TopicSerializer\n\nfrom ..models import GroupBuild, Participant\nfrom .serializers import GroupBuildSerializer, ParticipantSerializer, ParticipantCreateSerializer\nfrom .forms import TopicDetailsForm\n\nhtml_parser = HTMLParser.HTMLParser()\n\n\nclass GroupBuildDetail(generics.RetrieveAPIView):\n queryset = GroupBuild.objects.all()\n serializer_class = GroupBuildSerializer\n\n\nclass GroupBuildParticipantCheckView(views.APIView):\n \"\"\"\n View that checks if a topic belongs to a group build and was just created.\n \"\"\"\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, *args, **kwargs):\n form = TopicDetailsForm(request.GET)\n if not form.is_valid():\n return Response({'error': 'Bad query parameters'},\n status=status.HTTP_400_BAD_REQUEST)\n\n response = {}\n forum_id = form.cleaned_data['forum_id']\n # check if there's a groupbuild ongoing for this forum\n try:\n gb = GroupBuild.objects.get(forum=forum_id)\n except GroupBuild.DoesNotExist:\n gb = None\n\n topic = Topic.objects.filter(**form.cleaned_data).first()\n topic_created = (\n topic is not None and\n (timezone.now() - topic.created).seconds < (3 * 60)\n )\n\n response['topic_created'] = topic_created\n if topic_created and gb is not None: # include gb and topic data\n participants = Participant.objects.filter(user=request.user, groupbuild=gb, topic_id=None)\n matches = []\n topic_title = html_parser.unescape(topic.topic_title).lower()\n for participant in participants:\n ratio = Levenshtein.ratio(participant.model_name.lower(), topic_title)\n if ratio > 0.25:\n matches.append((participant, ratio))\n matches = sorted(matches, key=lambda x: x[1])\n if matches:\n response['participant'] = ParticipantSerializer(matches[-1][0]).data\n response['groupbuild'] = GroupBuildSerializer(gb).data\n response['topic'] = TopicSerializer(topic).data\n\n return Response(response)\n\n\nclass ParticipantCreateView(generics.CreateAPIView):\n model = Participant\n serializer_class = ParticipantCreateSerializer\n permission_classes = (IsAuthenticated,)\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n","sub_path":"src/brouwers/groupbuilds/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567712129","text":"from flask import Flask, jsonify, Blueprint, request, render_template, make_response\nfrom score_keeping.users.models import User\nfrom score_keeping.game.models import Game, GameLog\nfrom score_keeping import db, app\nfrom sqlalchemy.exc import IntegrityError\nfrom score_keeping.helpers.auth import generate_token, requires_auth, verify_token\n\n\nusers_api_blueprint = Blueprint('users_api',\n __name__,\n template_folder='templates')\n\n@users_api_blueprint.route('/games', methods=['GET'])\ndef list_games():\n games = Game.query.all()\n\n games = [{\n \"id\": int(game.id),\n \"gameName\": game.gameName,\n \"scorePerPoint\": game.scorePerPoint,\n \"timerChecked\": game.timerChecked,\n \"timerMinPerRound\": game.timerMinPerRound,\n \"timerMinPerGame\": game.timerMinPerGame\n } for game in games]\n\n return jsonify(games), 200\n\n\n\n@users_api_blueprint.route('/signup', methods=['POST'])\ndef create_user():\n\n post_data = request.get_json()\n\n try:\n user = User(\n name=post_data['user'][\"name\"],\n email=post_data['user'][\"email\"],\n password=post_data['user'][\"password\"]\n )\n\n db.session.add(user)\n db.session.commit()\n\n# the problem with this is that the user doesnt know what they did wrong.\n# FIX!!!\n except IntegrityError:\n return jsonify(message=\"User with that email already exists\"), 409\n\n new_user = User.query.filter_by(email=post_data['user'][\"email\"]).first()\n\n return jsonify(\n id=user.id,\n token=generate_token(new_user)\n )\n\n\n@users_api_blueprint.route('/gamelog', methods=['POST'])\ndef game_log():\n\n post_data = request.get_json()\n\n gamelog = GameLog(\n game_id=post_data['gamelog'][\"game_id\"],\n scores=post_data['gamelog'][\"scores\"],\n )\n\n db.session.add(gamelog)\n db.session.commit()\n\n return jsonify(\n message=\"Game log added\"\n ) \n\n@users_api_blueprint.route('/login', methods=['POST'])\ndef login():\n post_data = request.get_json()\n user = User.query.filter_by(email=post_data['user'][\"email\"]).first()\n\n if user and user.check_password(str(post_data['user'][\"password\"])):\n auth_token = user.encode_auth_token(user.id)\n\n responseObject = {\n 'status': 'success',\n 'message': 'Successfully signed in.',\n 'auth_token': auth_token.decode()\n }\n\n return make_response(jsonify(responseObject)), 201\n\n else:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n\n return make_response(jsonify(responseObject)), 401\n # return jsonify(token=generate_token(user))\n # else:\n # return jsonify(error=True), 403\n\n# @users_api_blueprint.route(\"/api/is_token_valid\", methods=[\"POST\"])\n# def is_token_valid():\n# incoming = request.get_json()\n# is_valid = verify_token(incoming[\"token\"])\n\n# if is_valid:\n# return jsonify(token_is_valid=True)\n# else:\n# return jsonify(token_is_valid=False), 403\n\n\n@users_api_blueprint.route('/newgame', methods=['POST'])\ndef create_game():\n post_data = request.get_json()\n\n jwt = request.headers.get('Authorization')\n\n if jwt:\n auth_token = jwt.split(\" \")[1]\n else:\n responseObject = {\n 'status': 'failed',\n 'message': 'No authorization header found'\n }\n\n return jsonify(responseObject), 401\n\n user_id = User.decode_auth_token(auth_token)\n\n user = User.query.get(user_id)\n\n if user:\n game = Game(\n gameName=post_data['game'][\"gameName\"],\n user_id=user_id,\n scorePerPoint=post_data['game'][\"scorePerPoint\"],\n timerChecked=post_data['game'][\"timerChecked\"],\n timerMinPerRound=post_data['game'][\"timerMinPerRound\"],\n timerMinPerGame=post_data['game'][\"timerMinPerGame\"]\n )\n db.session.add(game)\n db.session.commit()\n\n return jsonify(\n id=game.id,\n )\n else:\n responseObject = {\n 'status': 'failed',\n 'message': 'Authentication failed'\n }\n\n@users_api_blueprint.route('game/', methods=['POST'])\ndef delete_game(id):\n game = Game.query.get(id)\n old_games = GameLog.query.filter_by(game_id=id).all()\n\n for old_game in old_games:\n db.session.delete(old_game)\n db.session.commit()\n\n db.session.delete(game)\n db.session.commit()\n\n return jsonify(\n \"Game has been deleted\"\n )","sub_path":"score_keeping/users/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"548541462","text":"from tkinter import *\nimport random\n\nhighScores = []\n\n# Initialize the data which will be used to draw on the screen.\ndef init(data):\n # load data as appropriate\n data.rows = 8\n data.cols = 15\n data.headRow = data.rows//2\n data.headCol = data.cols//2\n initBoard(data)\n data.dir = (1,0)\n placeFood(data)\n data.isGameOver = False\n data.margin = 5\n data.isIgnoreStep = False\n data.pause = False\n data.score = 0\n data.highScores = highScores\n data.timerDelay = 400\n \n #data.snakeMoves = dict() #each space moved\n # data.wallNumber = 0\n \ndef placeFood(data):\n r = random.randint(0, data.rows-1)\n c = random.randint(0, data.cols-1)\n while (data.board[r][c] != 0):\n r = random.randint(0, data.rows-1)\n c = random.randint(0, data.cols-1)\n data.board[r][c] = -1\n\ndef initBoard(data):\n data.board = []\n for row in range(data.rows):\n data.board.append([0] * data.cols)\n data.board[data.headRow][data.headCol] = 1\n\ndef mousePressed(event, data):\n # use event.x and event.y\n height = 800\n width = 1500\n cellHeight = height/data.rows\n cellWidth = width/data.cols\n if (data.pause):\n makeWall(data, int(event.y//cellHeight), int(event.x//cellWidth))\n \ndef keyPressed(event, data):\n # use event.char and event.keysym\n if(event.keysym == \"p\"):\n data.pause = not data.pause\n if (event.char == \"r\"): init(data); return\n if(not data.pause and not data.isGameOver):\n if (event.keysym == 'Up'): data.dir = (-1, 0)\n elif (event.keysym == 'Down'): data.dir = (1, 0)\n elif (event.keysym == 'Left'): data.dir = (0, -1)\n elif (event.keysym == 'Right'): data.dir = (0, 1)\n takeStep(data)\n data.isIgnoreStep = True\n \ndef timerFired(data):\n if (data.isIgnoreStep):\n data.isIgnoreStep = False\n else:\n if(not data.pause and not data.isGameOver):\n takeStep(data)\n \n # for key in data.snakeMoves:\n # key[0] +=1\n \ndef takeStep(data):\n drow, dcol = data.dir\n newHeadRow, newHeadCol = data.headRow + drow, data.headCol + dcol\n # snake moves off board or hits self\n if (newHeadRow < 0 or newHeadRow >= data.rows or newHeadCol < 0 or \n newHeadCol >= data.cols or data.board[newHeadRow][newHeadCol] > 0):\n data.isGameOver = True\n getHighScores(data)\n return\n elif (data.board[newHeadRow][newHeadCol] == -1 ): # hit food\n data.board[newHeadRow][newHeadCol] = \\\n data.board[data.headRow][data.headCol] + 1\n data.headRow, data.headCol = newHeadRow, newHeadCol\n placeFood(data)\n data.score += 1\n if (data.score ==3):\n data.timerDelay = 200\n placePoison(data)\n elif(data.board[newHeadRow][newHeadCol] == -2): #hit wall\n data.board[newHeadRow][newHeadCol] = 0\n data.score -= 1\n if (data.score < 0):\n data.isGameOver = True\n getHighScores(data)\n return\n elif(data.board[newHeadRow][newHeadCol] == -3): #hit poison\n data.isGameOver = True\n getHighScores(data)\n return \n \n elif (data.board[newHeadRow][newHeadCol] == 0): # move snake forward\n data.board[newHeadRow][newHeadCol] = \\\n data.board[data.headRow][data.headCol] + 1\n data.headRow, data.headCol = newHeadRow, newHeadCol\n removeTail(data)\n\ndef removeTail(data):\n for row in range(data.rows):\n for col in range(data.cols):\n if data.board[row][col] > 0:\n data.board[row][col] -= 1\n \ndef getHighScores(data):\n global highScores\n if (len(highScores) == 0):\n highScores+=[data.score]\n else:\n for x in range(0,len(highScores)):\n if (data.score >highScores[x]):\n first = highScores[:x]\n last = highScores[x:]\n highScores= first + [data.score] + last\n break\n if (data.score <= highScores[x] and len(highScores) < 3):\n highScores+=[data.score]\n highScores = highScores[:3]\n \ndef makeWall(data,r,c):\n if (data.board[r][c] == 0):\n data.board[r][c] = -2\n elif (data.board[r][c] == -2):\n data.board[r][c] = 0\n #data.wallNumber += 1\n # data.snakeMoves[wallNumber] = [0,r,c]\n \ndef placePoison(data):\n r = random.randint(0, data.rows-1)\n c = random.randint(0, data.cols-1)\n while (data.board[r][c] != 0 or \n data.board[r-1][c] == 4 or \n data.board[r-1][c-1] == 4 or \n data.board[r-1][c+1] == 4 or \n data.board[r][c+1] == 4 or \n data.board[r][c-1] == 4 or \n data.board[r+1][c] == 4 or\n data.board[r+1][c-1] == 4 or \n data.board[r+1][c+1] == 4):\n r = random.randint(0, data.rows-1)\n c = random.randint(0, data.cols-1)\n data.board[r][c] = -3\n\n# This is the VIEW\n# IMPORTANT: VIEW does *not* modify data at all!\n# It only draws on the canvas.\ndef redrawAll(canvas, data):\n # draw in canvas\n if (data.isGameOver):\n canvas.create_text(data.width/2, data.height/2-10, text = \"Game Over\")\n canvas.create_text(data.width/2, data.height/2+20, \n text = \"Press 'r' to replay\") \n canvas.create_text(data.width/2, data.height/2+50, text = \"Score: \" + \n str(data.score))\n canvas.create_text(data.width/2, data.height/2+80, \n text = \"High Scores:\") \n global highScores \n for x in range(0,len(highScores)):\n canvas.create_text(data.width/2, data.height/2+110+(30*x), \n text = str(highScores[x]))\n else:\n drawBoard(canvas, data)\n canvas.create_text(data.width/2, 15, text = \"Score: \" + \n str(data.score))\n\ndef drawBoard(canvas, data):\n for row in range(data.rows):\n for col in range(data.cols):\n drawSnakeCell(canvas, data, row, col)\n \ndef drawSnakeCell(canvas, data, row, col):\n margin = data.margin\n w = data.width - 2 * margin\n h = data.height - 2 * margin\n cellW = w / data.cols\n cellH = h / data.rows\n x0 = cellW * col\n y0 = cellH * row\n x1 = cellW * (col +1)\n y1 = cellH * (row+1 )\n if (not data.pause): fill = \"white\"\n else: fill = \"#e1e1e1\"\n if (data.board[row][col] > 0):\n if (not data.pause): fill= \"black\"\n else: fill = \"#303030\"\n elif (data.board[row][col] == -1 or data.board[row][col] == -3):\n if (not data.pause): fill= \"red\"\n else: fill = \"#e11e1e\"\n elif (data.board[row][col] == -2):\n fill = \"sienna\"\n canvas.create_rectangle(x0+margin,y0+margin+20,x1+margin,y1+margin+20, fill=fill)\n\ndef run(width=300, height=300):\n def redrawAllWrapper(canvas, data):\n canvas.delete(ALL)\n redrawAll(canvas, data)\n canvas.update() \n\n def mousePressedWrapper(event, canvas, data):\n mousePressed(event, data)\n redrawAllWrapper(canvas, data)\n\n def keyPressedWrapper(event, canvas, data):\n keyPressed(event, data)\n redrawAllWrapper(canvas, data)\n\n def timerFiredWrapper(canvas, data):\n timerFired(data)\n redrawAllWrapper(canvas, data)\n # pause, then call timerFired again\n canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)\n \n # Set up data and call init\n class Struct(object): pass\n data = Struct()\n data.width = width\n data.height = height\n data.timerDelay = 400 # milliseconds\n init(data)\n # create the root and the canvas\n root = Tk()\n canvas = Canvas(root, width=data.width, height=data.height)\n canvas.pack()\n # set up events\n root.bind(\"\", lambda event:\n mousePressedWrapper(event, canvas, data))\n root.bind(\"\", lambda event:\n keyPressedWrapper(event, canvas, data))\n timerFiredWrapper(canvas, data)\n # and launch the app\n root.mainloop() # blocks until window is closed\n print(\"bye!\")\n\nrun(1500, 800)\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":8036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"220161425","text":"__author__ = \"Steve Wilson\"\n\nDOT = 1\nDASH = 2\nSPACE = 3\nLETTER = 4\nWORD = 5\nEND = 10\n\ntextToCode = {\n 'A' : (DOT, DASH),\n 'B' : (DASH, DOT, DOT, DOT),\n 'C' : (DASH, DOT, DASH, DOT),\n 'D' : (DASH, DOT, DOT),\n 'E' : (DOT,),\n 'F' : (DOT, DOT, DASH, DOT),\n 'G' : (DASH, DASH, DOT),\n 'H' : (DOT, DOT, DOT, DOT),\n 'I' : (DOT, DOT),\n 'J' : (DOT, DASH, DASH, DASH),\n 'K' : (DASH, DOT, DASH),\n 'L' : (DOT, DASH, DOT, DOT),\n 'M' : (DASH, DASH),\n 'N' : (DASH, DOT),\n 'O' : (DASH, DASH, DASH),\n 'P' : (DOT, DASH, DASH, DOT),\n 'Q' : (DASH, DASH, DOT, DASH),\n 'R' : (DOT, DASH, DOT),\n 'S' : (DOT, DOT, DOT),\n 'T' : (DASH,),\n 'U' : (DOT, DOT, DASH),\n 'V' : (DOT, DOT, DOT, DASH),\n 'W' : (DOT, DASH, DASH),\n 'X' : (DASH, DOT, DOT, DASH),\n 'Y' : (DASH, DOT, DASH, DASH),\n 'Z' : (DASH, DASH, DOT, DOT),\n '1' : (DOT, DASH, DASH, DASH, DASH),\n '2' : (DOT, DOT, DASH, DASH, DASH),\n '3' : (DOT, DOT, DOT, DASH, DASH),\n '4' : (DOT, DOT, DOT, DOT, DASH),\n '5' : (DOT, DOT, DOT, DOT, DOT),\n '6' : (DASH, DOT, DOT, DOT, DOT),\n '7' : (DASH, DASH, DOT, DOT, DOT),\n '8' : (DASH, DASH, DASH, DOT, DOT),\n '9' : (DASH, DASH, DASH, DASH, DOT),\n '0' : (DASH, DASH, DASH, DASH, DASH)\n }\n \n \ncodeToText = {}\n \nfor text in textToCode:\n\tcodeToText[textToCode[text]] = text\n\nDOT_LENGTH = 1\nDASH_LENGTH = 3\nLENGTH_BETWEEN_LETTER_UNITS = 1\nLENGTH_BETWEEN_LETTERS = 3\nLENGTH_BETWEEN_WORDS = 7\n\ndef encodeWord(text):\n\tcypherText = []\n\tfor i in range(0,len(text)):\n\t\tletter = text[i]\n\t\ttry:\n\t\t\tvalue = textToCode[letter.upper()]\n\t\texcept KeyError as e:\n\t\t\tcontinue\n\t\n\t\tcypherText.append(value)\n\t\n\treturn cypherText\n\n# End encodeWord\n\n\ndef decodeWord(cypherText):\n\ttext = []\n\tfor code in cypherText:\n\t\ttry:\n\t\t\tvalue = codeToText[code]\n\t\texcept KeyError as e:\n\t\t\tcontinue\n\t\t\n\t\ttext.append(value)\n\t\n\ttheText = ''\n\tfor letter in text:\n\t\ttheText += letter\n\t\n\treturn theText\n\n# End decodeWord\n\n\ndef encodePhrase(phrase):\n\tphrases = phrase.split(' ')\n\tencodedPhrases = []\n\t\n\tfor segment in phrases:\n\t\tencodedPhrases.append(encodeWord(segment))\n\t\n\treturn encodedPhrases\n\n# end encodePhrase\n\n\ndef decodePhrase(segment):\n\tphrase = []\n\tfor item in segment:\n\t\tphrase.append(decodeWord(item))\n\n\ttheText = ''\n\t\n\tfor i in range(0,len(phrase)):\n\t\ttheText += phrase[i]\n\t\tif i < (len(phrase) - 1):\n\t\t\ttheText += \" \"\n\t\n\treturn theText\n\n# End decodePhrase\n\n\nclass SignalHandler(object):\n\t\n\tdef __init__(self):\n\t\t\n\t\tself.__buffer = \"\"\n\t\n\t# End __init__\n\t\n\t\n\tdef dot(self, t):\n\t\t\n\t\tself.__buffer += '.' * t\n\t\n\t# End dot\n\t\n\t\n\tdef dash(self, t):\n\t\t\n\t\tself.__buffer += '-' * t\n\t\n\t# End dash\n\t\n\t\n\tdef space(self, t):\n\t\t\n\t\tself.__buffer += ' ' * t\n\t\n\t# End space\n\t\n\t\n\tdef reset(self):\n\t\t\n\t\tself.__buffer = ''\n\t\n\t# End reset\n\t\n\t\n\t@property\n\tdef buffer(self):\n\t\treturn self.__buffer\n\t\n\t# End buffer\n\n# End SignalHandler\n\n\n\ndef sendMessage(phrase, delta, handler=SignalHandler()):\n\n\tglobal DOT\n\tglobal DASH\n\n\tcypherText = encodePhrase(phrase)\n\t\n\tfor i in range(0, len(cypherText)):\n\n\t\tword = cypherText[i]\n\t\t\n\t\tfor j in range(0, len(word)):\n\t\t\t\n\t\t\tcodedLetter = word[j]\n\t\t\t\n\t\t\tfor k in range(0, len(codedLetter)):\n\t\t\t\t\n\t\t\t\tcode = codedLetter[k]\n\t\t\t\t\n\t\t\t\tif code == DOT:\n\t\t\t\t\thandler.dot(delta * DOT_LENGTH)\n\t\t\t\telif code == DASH:\n\t\t\t\t\thandler.dash(delta * DASH_LENGTH)\n\t\t\t\t\n\t\t\t\tif k < (len(codedLetter) - 1):\n\t\t\t\t\thandler.space(delta * LENGTH_BETWEEN_LETTER_UNITS)\n\t\t\t\n\t\t\tif j < (len(word) - 1):\n\t\t\t\thandler.space(delta * LENGTH_BETWEEN_LETTERS)\n\t\t\n\t\tif i < (len(cypherText) - 1):\n\t\t\thandler.space(delta * LENGTH_BETWEEN_WORDS)\n\n# End sendMessage\n\n\ndef readMessage(delta, reader):\n\t\n\tletter = []\n\tword = []\n\tphrase = []\n\n\tinCode = SPACE\n\t\n\tgenerator = reader.read(delta)\n\t\n\tinCode = generator.next()\n\n\twhile inCode != END:\n\t\t\n\t\tif inCode == DASH or inCode == DOT:\n\t\t\tletter.append(inCode)\n\t\telif inCode == LETTER:\n\t\t\tword.append(tuple(letter))\n\t\t\tletter = []\n\t\telif inCode == WORD:\n\t\t\tphrase.append(word)\n\t\t\tword = []\n\t\t\tletter = []\n\t\n\t\tinCode = generator.next()\n\n\treturn decodePhrase(phrase)\n\t\n# End readMessage\n\n","sub_path":"morse_code.py","file_name":"morse_code.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"432317749","text":"#!/usr/bin/python3.6\n# -*- coding: utf-8 -*-\n\n#############################\n########## imports ##########\n#############################\nimport os\nimport math\nfrom mnist import MNIST\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport skimage.feature as ft\nimport skimage.color as cl\nimport pickle\nimport glob\nimport psutil\nfrom tqdm import tqdm, trange\n\n#############################\n########## helpers ##########\n#############################\n\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n#############################\n######## fonctions TD #######\n#############################\n\n\ndef lecture_cifar(path):\n dataArray, labelArray = [], []\n for cifarFile in glob.glob(path + \"/*\"):\n if not cifarFile.endswith(\"batches.meta\"):\n unpickledDict = unpickle(cifarFile)\n dataArray.append(unpickledDict[b'data'])\n labelArray.append(unpickledDict[b'labels'])\n return np.asmatrix(np.concatenate(tuple(dataArray))), np.asarray(np.concatenate(tuple(labelArray)))\n\n\ndef lecture_mnist(path):\n mdata = MNIST(path)\n DataApp, LabelApp = mdata.load_training()\n DataTest, LabelTest = mdata.load_testing()\n return np.asmatrix(DataApp + DataTest), np.asarray(LabelApp + LabelTest)\n\n\ndef apply_descriptor(X, isrgb, descriptor):\n if (isrgb and np.sqrt(X.shape[1] / 3).is_integer()):\n imageSize = int(np.sqrt(X.shape[1] / 3))\n elif (not isrgb and np.sqrt(X.shape[1]).is_integer()):\n imageSize = int(np.sqrt(X.shape[1]))\n else:\n raise ValueError(\"Size is not square\")\n\n descriptor_extractor = ft.ORB(n_keypoints=30)\n\n for i in range(0, X.shape[0]):\n X1 = np.asarray(X[i, :])[0]\n if isrgb:\n X2 = cl.rgb2grey(np.transpose(X1.reshape(\n 3, imageSize, imageSize), (1, 2, 0)))\n else:\n X2 = X1.reshape(imageSize, imageSize)\n\n if descriptor is \"hog\":\n toAdd = np.asarray(ft.hog(X2, block_norm='L2-Hys'))\n elif descriptor is \"lbp\":\n toAdd = ft.local_binary_pattern(X2, 16, 2, 'uniform').flatten()\n elif descriptor is \"daisy\":\n toAdd = np.asarray(ft.daisy(\n X2, step=50, radius=10, rings=1, histograms=6, orientations=8)[0, 0, :])\n else:\n raise ValueError(\n \"descriptor should be a supported string : 'orb', 'daisy', or 'lbp'\")\n if 'X_out' not in locals():\n X_out = toAdd\n else:\n X_out = np.vstack((X_out, toAdd))\n return np.asmatrix(X_out)\n\n\ndef decoupage_donnees(X, Y, ratio=0.2, reduceR=1):\n numTest = math.floor(X.shape[0] * reduceR * ratio)\n numEnd = math.floor(X.shape[0] * reduceR)\n indexArray = np.arange(X.shape[0])\n np.random.shuffle(indexArray)\n\n testIndexArray = indexArray[:numTest]\n appIndexArray = indexArray[numTest:numEnd]\n\n return X[appIndexArray, :], Y[appIndexArray], X[testIndexArray, :], Y[testIndexArray]\n\n\ndef decoupage_n(X, Y, k, reduceR=0.2):\n maxIndex = int((X.shape[0] // k) * k * reduceR)\n chunkSize = int((X.shape[0] * reduceR) // k)\n indexArray = np.arange(maxIndex)\n np.random.shuffle(indexArray)\n X_array = []\n Y_array = []\n for i in range(k):\n ensambleIndexArray = indexArray[i * chunkSize:(i + 1) * chunkSize]\n X_array.append(X[ensambleIndexArray, :])\n Y_array.append(Y[ensambleIndexArray])\n return X_array, Y_array\n\ndef k_cross(X_array, Y_array, D_h, D_h2, D_out, verbose=0):\n n = len(X_array)\n Accuracy_array = []\n for i in range(n):\n X_array_clean = list(X_array)\n Y_array_clean = list(Y_array)\n X_array_clean.pop(i)\n Y_array_clean.pop(i)\n\n Xapp = np.vstack(tuple(X_array_clean))\n Yapp = np.hstack(tuple(Y_array_clean))\n Xtest = X_array[i]\n Ytest = Y_array[i]\n\n accuracy = train(Xapp,Yapp,Xtest,Ytest,100,100,10,verbose=0)\n\n Accuracy_array.append(accuracy)\n\n return Accuracy_array\n\n#############################\n######## fonctions ML #######\n#############################\n\n\ndef sigmoid(X, deriv=False):\n if not deriv:\n return 1 / (1 + np.exp(-X))\n else:\n return sigmoid(X) * (1 - sigmoid(X))\n\ndef relu(X, deriv=False):\n if not deriv:\n return np.where(X > 0, X, 0)\n else:\n return np.where(X > 0, 1, 0)\n\ndef stable_softmax(z, deriv=False):\n if not deriv:\n assert len(z.shape) == 2\n s = np.max(z, axis=1)\n s = s[:, np.newaxis] # necessary step to do broadcasting\n e_x = np.exp(z - s)\n div = np.sum(e_x, axis=1)\n div = div[:, np.newaxis] # dito\n return e_x / div\n else:\n # Fait pour que ça aille avec le code de crossEntropyCost\n return np.ones(z.shape)\n\ndef crossEntropyCost(X, Y, Yapp, delta=False, epsilon=0.000001):\n if not delta:\n m = Y.shape[0]\n log_likelihood = -np.log(X[range(m), Yapp] + epsilon)\n loss = np.sum(log_likelihood) / m\n return loss\n else:\n m = Y.shape[0]\n X[range(m), Yapp] -= 1\n grad = X / m\n return grad\n\ndef MSECost(X, Y, Yapp, delta=False):\n if not delta:\n return np.square(X - Y).sum() / (Y.shape[1] * X.shape[0])\n else:\n return X - Y\n\n\ndef plot_graph():\n plt.subplot2grid((1, 3), (0, 0))\n plt.plot(accuracy_array, 'C1')\n plt.title(\"Batch accuracy\")\n plt.subplot2grid((1, 3), (0, 1))\n plt.plot(loss_array, 'C1')\n plt.title(\"Loss\")\n plt.subplot2grid((1, 3), (0, 2))\n plt.plot(total_accuracy_array, 'C1')\n plt.title(\"Model accuracy\")\n plt.show()\n\n\ndef prop(X, Y, Yapp, W1, b1, f1, W2, b2, f2, W3, b3, f3, crossFunction):\n ####################################################\n # Passe avant : calcul de la sortie prédite Y_pred #\n ####################################################\n\n I1 = X.dot(W1) + b1 # Potentiel d'entrée de la couche cachée =Z\n # Sortie de la couche cachée (fonction d'activation de type sigmoïde) =A\n O1 = f1(I1)\n I2 = O1.dot(W2) + b2 # Potentiel d'entrée de la couche de sortie =Z2\n # Sortie de la couche de sortie (fonction d'activation de type sigmoïde) Y\n O2 = f2(I2)\n I3 = O2.dot(W3) + b3\n O3 = f3(I3)\n\n ########################################################\n # Calcul et affichage de la fonction perte de type MSE #\n ########################################################\n\n loss = crossFunction(O3, Y, Yapp)\n\n accuracy = (np.argmax(O3, axis=1) == Yapp).mean()\n accuracy_array.append(accuracy)\n\n return O1, O2, O3, loss, accuracy\n\n\ndef backprop(X, Y, Yapp, W1, b1, f1, O1, W2, b2, f2, O2, W3, b3, f3, O3, crossFunction):\n\n O3error = crossFunction(O3, Y, Yapp, delta=True)\n dO3 = O3error * f3(O3, deriv=True)\n\n O2error = dO3.dot(W3.T)\n dO2 = O2error * f2(O2, deriv=True)\n\n O1error = dO2.dot(W2.T)\n dO1 = O1error * f1(O1, deriv=True)\n\n W3update = (O2.T.dot(dO3))\n b3update = np.mean(dO3, axis=0)\n\n W2update = (O1.T.dot(dO2))\n b2update = np.mean(dO2, axis=0)\n\n W1update = (X.T.dot(dO1))\n b1update = np.mean(dO1, axis=0)\n\n W3 -= alpha * W3update\n W2 -= alpha * W2update\n W1 -= alpha * W1update\n b3 -= alpha * b3update\n b2 -= alpha * b2update\n b1 -= alpha * b1update\n\n return W1, b1, W2, b2, W3, b3\n\n\n#############################\n########## scripts ##########\n#############################\n\nprint(\"Starting part 2 : neural networks\")\n\nnp.random.seed(1) # pour que l'exécution soit déterministe\nalpha = 10e-4\nepochs = 50 # epochs per batch\nmaxEpochs = 10000 #Nombre maximum d'epochs au total\nbatchCount = 400 #Nombre de batches\naccuracy_array = []\nloss_array = []\ntotal_accuracy_array = []\n\n##########################\n# Génération des données #\n##########################\n\nXraw, Yraw = lecture_mnist('mnist-data')\nXapp, Yapp, Xtest, Ytest = decoupage_donnees(Xraw, Yraw, reduceR=1)\ndef train(Xapp, Yapp, Xtest, Ytest, D_h, D_h2, D_out,verbose=0):\n\n X = np.asarray(Xapp)\n N, D_in = Xapp.shape[0], Xapp.shape[1]\n Y = np.zeros((N, D_out), dtype=np.uint8)\n Y[range(N), Yapp] = 1\n\n batchSize = int(X.shape[0] / batchCount)\n\n print(\"Batch count : %s\" % batchCount)\n print(\"Batch size : %s\" % batchSize)\n\n\n # Initialisation aléatoire des poids du réseau\n W1 = 2 * np.random.random((D_in, D_h)) - 1\n b1 = np.zeros((1, D_h))\n\n W2 = 2 * np.random.random((D_h, D_h2)) - 1\n b2 = np.zeros((1, D_h2))\n\n W3 = 2 * np.random.random((D_h2, D_out)) - 1\n b3 = np.zeros((1, D_out))\n\n bar = tqdm(total = np.minimum(batchCount * epochs, maxEpochs), desc=\"Learning completion\", unit=\"steps\")\n\n for j in range(batchCount):\n\n startIndex = j * batchSize\n endIndex = (j + 1) * batchSize\n Xb = X[startIndex:endIndex, :]\n Yb = Y[startIndex:endIndex, :]\n Ybapp = Yapp[startIndex:endIndex]\n\n for i in range(epochs):\n\n O1, O2, O3, loss, accuracy = prop(\n Xb, Yb, Ybapp,\n W1, b1, relu,\n W2, b2, sigmoid,\n W3, b3, stable_softmax,\n crossFunction=crossEntropyCost)\n\n if (verbose>=1):\n if (i == epochs - 1):\n A, B, C, D, taccuracy = prop(\n X, Y, Yapp,\n W1, b1, relu,\n W2, b2, sigmoid,\n W3, b3, stable_softmax,\n crossFunction=crossEntropyCost)\n\n loss_array.append(loss)\n accuracy_array.append(accuracy)\n total_accuracy_array.append(taccuracy)\n\n bar.set_postfix(Accuracy=taccuracy)\n if (verbose>=2):\n print(\"Step number %s. Computed loss is : %s. Computed batch accuracy is : %s. Computed model accuracy is : %s\" % (\n i, round(loss, 4), round(accuracy, 4), round(taccuracy, 4)))\n\n W1, b1, W2, b2, W3, b3 = backprop(\n Xb, Yb, Ybapp,\n W1, b1, relu, O1,\n W2, b2, sigmoid, O2,\n W3, b3, stable_softmax, O3,\n crossFunction=crossEntropyCost)\n\n bar.update()\n\n if (j * epochs + i >= maxEpochs - 1):\n break\n if (j * epochs + i >= maxEpochs - 1):\n break\n\n bar.close()\n if (verbose>=1):\n plot_graph()\n\n #forwardPass pour le calcul de l'accuracy sur dev\n A, B, C, D, accuracy = prop(\n X, Y, Yapp,\n W1, b1, relu,\n W2, b2, sigmoid,\n W3, b3, stable_softmax,\n crossFunction=crossEntropyCost)\n\n print(\"Computed model loss on last batch is : %s\" % round(loss,4))\n print(\"Computed model accuracy on trainset is : %s\" % round(accuracy,4))\n\n #forwardPass pour le calcul de l'accuracy sur test\n X = np.asarray(Xtest)\n N, D_in = Xtest.shape[0], Xtest.shape[1]\n Y = np.zeros((N, D_out), dtype=np.uint8)\n Y[range(N), Ytest] = 1\n A, B, C, D, accuracy = prop(\n X, Y, Ytest,\n W1, b1, relu,\n W2, b2, sigmoid,\n W3, b3, stable_softmax,\n crossFunction=crossEntropyCost)\n print(\"Computed model accuracy on testset is : %s\" % round(accuracy,4))\n return accuracy\n\n# Simple Train\n# train(Xapp,Yapp,Xtest,Ytest,100,100,10,verbose=0)\n\n# Cross-Validation\nprint(\"Starting 10-fold Cross validation\")\nX_Array, Y_Array = decoupage_n(Xraw, Yraw, 10, reduceR=1)\naccuracies = k_cross(X_Array, Y_Array ,100,100,10, verbose=0)\nprint(\"Accuracy for 10-fold cross validation : %s\"% np.mean(accuracies))\n","sub_path":"ML_TP1/partie2.py","file_name":"partie2.py","file_ext":"py","file_size_in_byte":11557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"196791847","text":"from flask import Flask, request, redirect\nfrom twilio.twiml.messaging_response import MessagingResponse\nimport random\nfrom database import *\nimport sendgrid\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport os\nfrom sendgrid.helpers.mail import *\n\nengine = create_engine('sqlite:///site.db')\nSession = sessionmaker(autoflush=True, autocommit=False, bind=engine)\nconn = engine.connect()\nsession = Session(bind=conn)\n\napp = Flask(__name__)\n\n\ndef parse_flight_info(text_message):\n \"\"\" Parses incoming text for flight information \"\"\"\n # new_flight = Flight()\n # session.add(new_user)\n # session.commit()\n # session.close()\n return \"\"\n\n\ndef receive_flight_info():\n \"\"\" Hanldes communication once all needed info is collected \"\"\"\n\n # if verify state is VERIFIED\n resp = MessagingResponse()\n resp.message(\"\"\"Thank you for the information!\n We'll notify you as soon as we have a match\"\"\")\n return str(resp)\n\n\ndef verify():\n \"\"\" Handles initial info collection for flight \"\"\"\n\n # triggered when they send the correct verification code\n resp = MessagingResponse()\n resp.message(\"\"\"Thanks for verifying! Let's get started with your\n flight information. Please answer the following, separated by commas:\n 1. JFK/LGA/EWR\n 2. Date (MM/DD/YYYY)\n 3. Flight Time (XX:XX AM/PM)\n 4. Maximum Number of Additional Passengers\"\"\")\n return str(resp)\n\n\ndef send_verify_email(email):\n \"\"\" Sends user verification email\n\n Keyword arguments:\n email -- user's email address\n \"\"\"\n sg = sendgrid.SendGridAPIClient(os.getenv('SENDGRID_TOKEN'))\n\n from_email = Email(\"CUSkyBot@gmail.com\")\n to_email = Email(str(email))\n subject = \"Verify Email with SkyBot\"\n\n random_num = random.randint(1, 100000000)\n # commit the random number to user's data for comparison\n # session.query().filter(User.phone_number == pnumber).update({\"verification_code\": random_num})\n\n content = Content(\"text/plain\", \"Verifcation Code: \" + str(random_num))\n mail = Mail(from_email, subject, to_email, content)\n response = sg.client.mail.send.post(request_body=mail.get())\n\n if str(response.status_code) != 201:\n resp = MessagingResponse()\n resp.message(\"\"\"Please send your email again,\n error in sending verfication code\"\"\")\n return str(resp)\n else:\n resp = MessagingResponse()\n resp.message(\"\"\"Check your email for a verification email\n and text us the code\"\"\")\n # change verified state to EMAIL_SENT\n # session.query().filter(User.phone_number == pnumber).update({\"verified\": \"EMAIL_SENT\"})\n return str(resp)\n\n\ndef exist_user(phone_number, body):\n \"\"\" Handles communication with existing Skybot users\n\n Keyword arguments:\n phone_number -- user's phone number\n body -- user's text message\n \"\"\"\n curr_user = session.query(User).filter_by(\n phone_number=phone_number).first()\n\n # if verify state is NONE, call send email function\n if curr_user.verified == 'NONE':\n message = send_verify_email(body + \"@columbia.edu\")\n elif curr_user.verified == \"EMAIL_SENT\" and body == curr_user.verification_code:\n message = verify()\n else:\n message = verify()\n return message\n\n\ndef new_user(phone_number):\n \"\"\" Handles communication with new Skybot users\n\n Keyword arguments:\n phone_number -- user's phone number\n \"\"\"\n\n # create & insert new user into database\n new_user = User(phone_number=phone_number, verified=\"NONE\")\n session.add(new_user)\n session.commit()\n session.close()\n\n # send confirmation message & ask for UNI\n resp = MessagingResponse()\n resp.message(\"Welcome to Skybot! What's your UNI?\")\n return str(resp)\n\n\n@app.route(\"/sms\", methods=['GET', 'POST'])\ndef sms_reply():\n \"\"\" Handles text communication with users \"\"\"\n\n # gets phone number of user\n pnumber = request.values.get('From', None)\n\n # checks db for existing user\n check_num = session.query(User).filter(User.phone_number == pnumber)\n if session.query(check_num.exists()).scalar() is False:\n out_message = new_user(pnumber)\n else:\n body = request.values.get('Body', None)\n out_message = exist_user(pnumber, body)\n\n return str(out_message)\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":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"55929957","text":"import requests\r\nimport bs4\r\n\r\n\r\ndef havadurumu():\r\n base_url = \"https://www.havadurumu15gunluk.net/havadurumu/ankara-hava-durumu-15-gunluk.html\"\r\n ana_response = requests.get(base_url)\r\n ana_soup = bs4.BeautifulSoup(ana_response.text, \"html.parser\")\r\n listem = ana_soup.find_all(\"strong\")\r\n derece = listem[4].text\r\n durum = listem[5].text\r\n hava=\"Günlük durum raporu: \\n\\n\"+ \"Ankara için hava durumu: \"+ derece + \" \" + durum + \"\\n\\n\"\r\n return hava\r\n\r\n\r\ndef dolarkuru():\r\n base_url = \"http://www.bloomberght.com/doviz/dolar\"\r\n ana_response = requests.get(base_url)\r\n ana_soup = bs4.BeautifulSoup(ana_response.text, \"html.parser\")\r\n classname = \"col-lg-8 col-sm-12 col-xs-12 col-md-6 marB10 piyasaDetayTitle\"\r\n kur = ana_soup.find(\"div\", class_=classname)\r\n return kur.text\r\n\r\n\r\ndef kurtakip():\r\n base_url = \"https://coinmarketcap.com/\"\r\n ana_response = requests.get(base_url)\r\n ana_soup = bs4.BeautifulSoup(ana_response.text, \"html.parser\")\r\n classname: str = \"no-wrap percent-change text-right negative_change\"\r\n ana_soup.find(\"td\", class_=classname)\r\n btc_kur = ana_soup.find_all(\"td\", {\"class\": \"no-wrap\"})\r\n\r\n degisim, deger, yuzde, oran = dolarkuru().split(\" \")\r\n btckur = float(btc_kur[2].text.replace(\"$\", \"\"))\r\n dolarkur = float(deger.replace(\",\", \".\"))\r\n hava=havadurumu()\r\n with open(\"takip.txt\",\"w\") as f:\r\n f.write(hava+\r\n \"Anlık dolar kuru: \" + deger +\r\n \"\\n\" +\r\n \"Dolar değişim oranı: \" + yuzde + oran+ \"\\n\\n\"+\r\n \"Anlık bitcoin değeri(USD): \" + btc_kur[2].text + \"\\n\" +\r\n \"Anlık bitcoin değeri (TL): \" + str(btckur * dolarkur) + \"\\n\" +\r\n \"Bitcoin değişim oranı : \" + btc_kur[5].text + \"\\n\")\r\n\r\n\r\nhavadurumu()\r\nkurtakip()\r\n","sub_path":"gunluktakip.py","file_name":"gunluktakip.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"217168986","text":"import pickle\r\n\r\n\r\nclass WineQuality(object):\r\n def __init__(self):\r\n self.free_sulfur_scaler = pickle.load(\r\n open('C:\\\\Users\\\\ja_me\\\\Projetos_Portfolio\\\\free_sulfur_scaler.pkl', 'rb'))\r\n self.total_sulfur_scaler = pickle.load(\r\n open('C:\\\\Users\\\\ja_me\\\\Projetos_Portfolio\\\\total_sulfur_scaler.pkl', 'rb'))\r\n\r\n def data_preparation(self, df):\r\n # reescaling free sulfur\r\n df['free sulfur dioxide'] = self.free_sulfur_scaler.transform(df[['free sulfur dioxide']].values)\r\n\r\n # reescaling total sulfur\r\n df['total sulfur dioxide'] = self.total_sulfur_scaler.transform(df[['total sulfur dioxide']].values)\r\n\r\n return df\r\n","sub_path":"Qualidade do vinho - Regressão e Deploy do modelo/wine_quality.py","file_name":"wine_quality.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446968245","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cv2 as cv\nimport numpy as np\n\nimport cvui\n\n\ndef main():\n window_name = 'cvui-double-knob-trackbar'\n cvui.init(window_name)\n\n trackbar_value1 = [25.0]\n trackbar_value2 = [75.0]\n\n while True:\n cvuiframe = np.zeros((140, 460, 3), np.uint8)\n cvuiframe[:] = (49, 52, 49)\n\n cvui.trackbar2(cvuiframe, 30, 30, 400, trackbar_value1,\n trackbar_value2, 0., 100.)\n\n cvui.text(cvuiframe, 50, 100,\n 'value1 : ' + \"{0:.1f}\".format(trackbar_value1[0]))\n cvui.text(cvuiframe, 160, 100,\n 'value2 : ' + \"{0:.1f}\".format(trackbar_value2[0]))\n\n cvui.update()\n\n cv.imshow(window_name, cvuiframe)\n key = cv.waitKey(50)\n if key == 27: # ESC\n break\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"307911437","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'zienjih'\nSITENAME = 'Techspace'\nSITEURL = 'jayzh7.github.io'\n\nPATH = '.'\n\nTIMEZONE = 'Europe/Paris'\n\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nDISPLAY_CATEGORIES_ON_SUBMENU = False\n\n# Blogroll\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),)\n\n# Social widget\nSOCIAL = (('FB', '#'),\n ('INS', '#'),)\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"308204074","text":"# © 2019 Liyben\n# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).\n\nfrom odoo import api, fields, models\n\n\nclass CrmOpporConvert2Task(models.TransientModel):\n \"\"\" wizard to convert a Lead into a Project task and move the Mail Thread \"\"\"\n\n _name = \"crm.oppor.convert2task\"\n _inherit = 'crm.partner.binding'\n\n @api.model\n def default_get(self, fields):\n result = super(CrmOpporConvert2Task, self).default_get(fields)\n oppor_id = self.env.context.get('active_id')\n if oppor_id:\n result['oppor_id'] = oppor_id\n return result\n\n oppor_id = fields.Many2one('crm.lead', string='Aviso', domain=[('type', '=', 'opportunity')])\n project_id = fields.Many2one('project.project', string='Proyecto')\n #Campo para saber si el campo Proyecto es solo lectura o no\n project_only_read = fields.Boolean(string='Solo lectura')\n\n\n # Cambiamos el proyecto en el aviso si lo cambiamos en el wizard\n @api.multi\n @api.onchange('project_id')\n def _onchange_project_id(self):\n self.ensure_one()\n # Obtenemos el aviso que vamos a transformar\n oppor = self.oppor_id\n if oppor:\n oppor.project_id = self.project_id.id\n\n @api.multi\n def action_opportunity_to_project_task(self):\n self.ensure_one()\n # Obtenemos el aviso que vamos a transformar\n oppor = self.oppor_id\n partner_id = self._find_matching_partner()\n if not partner_id and (oppor.partner_name or oppor.contact_name):\n partner_id = oppor.handle_partner_assignation()[oppor.id]\n # Creamos una nueva project.task\n vals = {\n \"name\": oppor.name,\n \"work_to_do\": oppor.description,\n \"email_from\": oppor.email_from,\n \"project_id\": self.project_id.id,\n \"partner_id\": partner_id,\n \"user_id\": oppor.worker_one.id,\n \"oppor_id\": oppor.id\n }\n task = self.env['project.task'].create(vals)\n # Comentamos el traspaso del hilo y de los ajuntos\n \"\"\"\n # Movemos el hilo del mail\n oppor.message_change_thread(task)\n # Movemos los adjuntos\n attachments = self.env['ir.attachment'].search([('res_model', '=', 'crm.lead'), ('res_id', '=', oppor.id)])\n attachments.write({'res_model': 'project.task', 'res_id': task.id})\n \"\"\"\n # devolvemos la acción para ir a la vista formulario de la nueva tarea\n view = self.env.ref('project.view_task_form2')\n return {\n 'name': 'Task created',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': view.id,\n 'res_model': 'project.task',\n 'type': 'ir.actions.act_window',\n 'res_id': task.id,\n 'context': self.env.context\n }\n","sub_path":"crm_aviso_to_pt/wizard/crm_opportunity_convert2task.py","file_name":"crm_opportunity_convert2task.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"41802088","text":"\nfrom __future__ import print_function\nimport numpy as np\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nfrom keras.callbacks import Callback\nfrom keras import backend as K\nfrom keras import initializations\n\nimport argparse\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-rseed', type=int, default=0)\n\nparser.add_argument('-numinputs', type=int, default=100) \nparser.add_argument('-numoutputs', type=int, default=10)\nparser.add_argument('-numhid', type=int, default=50)\nparser.add_argument('-depth', type=int, default=1)\n\nparser.add_argument('-snr', type=float, default=2.5)\nparser.add_argument('-numsamples', type=int, default=100)\n\nparser.add_argument('-lr', type=float, default=.001)\nparser.add_argument('-epochs', type=int, default=100)\nparser.add_argument('-batchsize', type=int, default=-1)\nparser.add_argument('-weightscale', type=float, default=1.)\n\n\nparser.add_argument('-savefile', type=argparse.FileType('w'))\n\nparser.add_argument('-showplot', action='store_true')\nparser.add_argument('-saveplot', action='store_true')\nparser.add_argument('-verbose', action='store_true')\n\n\nsettings = parser.parse_args(); \n\nimport matplotlib\n\nif not settings.showplot:\n matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nnp.random.seed(settings.rseed)\n\n\nclass GaussianGeneralizationHistory(Callback):\n def __init__(self, W0, No, Ni, P, sigma_o):\n self.W0 = W0\n self.No = No\n self.Ni = Ni\n self.P = P\n self.sigma_o = sigma_o\n\n def on_train_begin(self, logs={}):\n self.genhist = []\n\n def on_batch_end(self, batch, logs={}):\n # Forward prop to find current total input-output map\n W = self.model.predict(np.identity(self.Ni), self.Ni)\n \n # Compute loss\n dW = self.W0 - W\n gen_err = (1./self.No)*np.linalg.norm(dW)**2 + self.sigma_o**2\n \n self.genhist.append(gen_err)\n \n\nscaled_normal_init = lambda shape, name=None: initializations.normal(shape, scale=settings.weightscale/np.sqrt(np.mean(shape)), name=name)\n\n\nP = settings.numsamples\nP_t = 1\nNi = settings.numinputs\nNh = settings.numhid\nNo = settings.numoutputs\n\nsigma_o = 1/settings.snr\nnb_epoch = settings.epochs\nif settings.batchsize > 0:\n batch_sz = settings.batchsize\nelse:\n batch_sz = P\n\n\nX_train = np.random.normal(0,1.0,(P, Ni))\nX_test = np.random.normal(0,1.0,(P_t, Ni))\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\nW0 = np.random.normal(0,1.0,(Ni,No))\n\nY_train = np.dot(X_train,W0) + np.random.normal(0,sigma_o,(P, No))\nY_test = np.dot(X_test,W0) + np.random.normal(0,sigma_o,(P_t, No))\n\nmodel = Sequential()\nif settings.depth > 0: # Deep model\n model.add(Dense(Nh, input_shape=(Ni,), bias=False, init=scaled_normal_init))\n \n for d in range(settings.depth-1):\n model.add(Dense(Nh, bias=False, init=scaled_normal_init))\n #model.add(Activation('relu'))\n #model.add(Dropout(0.2))\n \n model.add(Dense(No, bias=False, init=scaled_normal_init))\nelse: # Shallow model\n model.add(Dense(No, input_shape=(Ni,), bias=False, init=scaled_normal_init))\n\nif settings.verbose:\n model.summary()\n \ngenhist = GaussianGeneralizationHistory(W0, No, Ni, P, sigma_o)\n \nsgd = SGD(lr=settings.lr)\nmodel.compile(loss='mse',\n optimizer=sgd)\n\nif settings.verbose:\n v = 1\nelse:\n v = 0\nhistory = model.fit(X_train, Y_train,\n batch_size=batch_sz, nb_epoch=nb_epoch,\n verbose=v, validation_data=(X_test, Y_test), callbacks=[genhist])\n\n\n\nif settings.savefile:\n np.savez(settings.savefile, train=np.asarray(history.history['loss']), test=np.asarray(history.history['val_loss']), exact_test=np.asarray(genhist.genhist), params=[settings])\n\n\nif settings.showplot or settings.saveplot:\n epoch = np.linspace(0, nb_epoch, nb_epoch)\n\n fig, ax = plt.subplots(1)\n line1, = ax.plot(epoch, history.history['loss'], linewidth=2,label='Train loss')\n line2, = ax.plot(epoch, history.history['val_loss'], linewidth=2, label='Test loss')\n line3, = ax.plot(epoch, genhist.genhist, linewidth=2, label='Exact Test loss')\n ax.legend(loc='upper center')\n\n if settings.showplot:\n plt.show()\n elif settings.saveplot:\n fig.savefig('training_dynamics.pdf', bbox_inches='tight')\n\n\n","sub_path":"code/run_indep_gaussian.py","file_name":"run_indep_gaussian.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"10451483","text":"import os, hoshino\r\nfrom nonebot import *\r\nfrom hoshino import Service, R\r\nfrom .get_zhoubao_info import *\r\nfrom .get_xur_info import *\r\nfrom .get_chall_info import *\r\nfrom .get_zhu_info import *\r\n\r\n\r\n#帮助界面\r\nsv = Service(\"destiny2\")\r\n\r\nhelp_txt = '''\r\n[周报] 查看命运2周报\r\n[老九] 查看老九位置和装备\r\n[试炼] 查看试炼周报\r\n[蛛王] 查看蛛王商店\r\n[光尘] 查看光尘商店\r\n[百科] 小黑盒百科链接\r\n'''\r\n@sv.on_command('命运2帮助',only_to_me=False)\r\nasync def help(bot):\r\n await bot.send(help_txt)\r\n\r\n#周报功能\r\n@sv.on_command('周报',aliases=('命运2周报'),only_to_me=False)\r\nasync def zhoubao(session: CommandSession):\r\n img1 = MessageSegment.image(getzhoubaoImg(html1))\r\n #print(getzhoubaoImg(html))\r\n msg = '命运2 周报:\\n图片作者:seanalpha\\n'\r\n msg = msg + str(img1)\r\n await session.send(msg)\r\n\r\n#老九功能\r\n@sv.on_command('老九',aliases=('仄','九','xur','老仄','苏尔'),only_to_me=False)\r\nasync def xur(session: CommandSession):\r\n img2 = MessageSegment.image(getxurImg(html2))\r\n #print(getxurImg(html))\r\n msg = '命运2 仄:\\n图片作者:seanalpha\\n'\r\n msg = msg + str(img2)\r\n await session.send(msg)\r\n\r\n#试炼周报功能\r\n@sv.on_command('试炼',aliases=('奥斯里斯试炼'),only_to_me=False)\r\nasync def chall(session: CommandSession):\r\n img3 = MessageSegment.image(getchallImg(html3))\r\n #print(getchallImg(html))\r\n msg = '命运2 试炼周报:\\n图片作者:seanalpha\\n'\r\n msg = msg + str(img3)\r\n await session.send(msg)\r\n\r\n#蛛王商店功能\r\n@sv.on_command('蛛王',aliases=('蛛王商店','猪王'),only_to_me=False)\r\nasync def zhu(session: CommandSession):\r\n img4 = MessageSegment.image(getzhuImg(html4))\r\n #print(getzhuImg(html))\r\n msg = '命运2 蛛王:\\n图片来源:小黑盒百科\\n'\r\n msg = msg + str(img4)\r\n await session.send(msg)\r\n\r\n#光尘商店(为了图方便,这里直接放了一张整个赛季的商店图片)\r\n@sv.on_command('光尘',aliases=('光尘商店'),only_to_me=False)\r\nasync def buy(session: CommandSession):\r\n img5 = MessageSegment.image(\"https://cdn.jsdelivr.net/gh/azmiao/picture-bed/img/buy.jpg\")\r\n msg = '命运2 光尘商店:\\n'\r\n msg = msg + str(img5)\r\n await session.send(msg)\r\n\r\n#百科后续打算做成其他形式,但目前直接放了个链接,自己去小黑盒看吧\r\n@sv.on_command('百科',aliases=('命运2百科'),only_to_me=False)\r\nasync def baike(session: CommandSession):\r\n msg = '命运2 百科链接\\n https://api.xiaoheihe.cn/wiki/get_homepage_info_for_app/?wiki_id=1085660&is_share=1 \\n来自: 小黑盒'\r\n await session.send(msg)\r\n","sub_path":"destiny2.py","file_name":"destiny2.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"496248524","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Packages\nimport numpy as np\nimport matplotlib.pyplot as mp\nimport numpy.linalg as npl\nimport numpy.random as npr\nimport re\nimport matplotlib.pyplot as ma\n\nepsilon = 0.0001\n\ndef load_foil(file):\n \"\"\" Airfoil: load profile of a wing\n Reads a file whose lines contain coordinates of points, separated by an empty line.\n Every line not containing a couple of floats is discarded.\n Returns a couple constitued of the list of points of the extrados and the intrados.\n \"\"\"\n f = open(file, 'r')\n matchline = lambda line: re.match(r\"\\s*([\\d\\.-]+)\\s*([\\d\\.-]+)\", line)\n extra = []; intra = []\n rextra = False; rintra = False\n for line in f:\n m = matchline(line)\n if (m != None) and not(rextra):\n rextra = True\n if (m != None) and rextra and not(rintra):\n extra.append(m.groups())\n if (m != None) and rextra and rintra:\n intra.append(m.groups())\n if (m == None) and rextra:\n rintra = True\n ex = np.array(list(map(lambda t: float(t[0]), extra))) # Python3: iterators to lists\n ey = np.array(list(map(lambda t: float(t[1]), extra)))\n ix = np.array(list(map(lambda t: float(t[0]), intra)))\n iy = np.array(list(map(lambda t: float(t[1]), intra)))\n return ex, ey, ix, iy\n\nex, ey, ix, iy = load_foil(\"e168.dat\")\n\n# Pour séparer extrados et intrados (bizarre d'ailleurs...)\nix = ex[len(ex)/2:]\niy = ey[len(ey)/2:]\nex = ex[:len(ex)/2+1]\ney = ey[:len(ey)/2+1]\n# print(ex)\n# print(ey)\n# print(ix)\n# print(iy)\n\ndef print_aile(ex, ey, ix, iy):\n mp.plot(ex, ey, 'ro')\n mp.plot(ix, iy, 'bo')\n mp.ylim([-0.3,0.3])\n\n # mp.show()\n# print_aile(ex, ey, ix, iy)\n\ndef polynome_A(xj, xjj):\n \"\"\" Polynôme A associé au couple de point xj xj+1 (= xjj) \"\"\"\n return np.poly1d([-1/(xjj - xj), xjj/(xjj - xj)])\n\ndef polynome_B(xj, xjj):\n \"\"\" Polynôme B associé au couple de point xj xj+1 (= xjj) \"\"\"\n return np.poly1d([1/(xjj - xj), -xj/(xjj - xj)])\n\ndef C_aux(xj,xjj):\n \"\"\" Intermédiaire de calcul du polynôme C \"\"\"\n return (pow(polynome_A(xj,xjj),3) - polynome_A(xj,xjj))/6\n\ndef polynome_C(xj, xjj):\n \"\"\" Polynome C associé au couple de point xj xj+1 (=xjj) \"\"\"\n return (C_aux(xj,xjj) * pow((xjj - xj), 2))\n\ndef D_aux(xj,xjj):\n \"\"\" Intermédiaire de calcul du polynôme D \"\"\"\n return (pow(polynome_B(xj,xjj),3) - polynome_B(xj,xjj))/6\n\ndef polynome_D(xj, xjj):\n \"\"\" Polynome D associé au couple de point xj xj+1 (=xjj) \"\"\"\n return (D_aux(xj,xjj) * pow((xjj - xj), 2))\n\ndef system_aux(x,xj,xjj,y,yj,yjj):\n \"\"\" Code les équations (3.3.7) des \"numericals recipes\" sans le membre de droite \"\"\"\n return [(xj-x)/6.0, (xjj - x) / 3.0, (xjj - xj) / 6.0]\n\ndef system_auxB(x,xj,xjj,y,yj,yjj):\n \"\"\" Code les équations (3.3.7) des \"numericals recipes\" (juste membre de droite) \"\"\"\n return (yjj - yj)/(xjj - xj) - (yj - y)/ (xj - x)\n\ndef init_matrix(x,y):\n \"\"\" Initialise la matrice M pour résoudre le système (3.3.7) et obtenir y'' \"\"\"\n n = len(x)\n res = np.zeros([n,n])\n res[0,0] = 1\n res[n-1,n-1] = 1\n for i in range(1,n-1):\n for j in range(0,2):\n res[i,i-1+j] = system_aux(x[i-1], x[i], x[i+1], y[i-1], y[i], y[i+1])[j]\n return res\n\nx = np.array([10.0, 7.0, 3.0, 4.0, 18.0])\ny = np.array([10.0, 8.0, 3.0, 5.0, 18.0])\n\ndef init_vector_B(x,y):\n \"\"\" Initialise le vecteur B pour le système M.X = B \"\"\"\n dim = len(x)\n res = np.zeros([dim,1])\n res[0,0] = 0\n res[dim-1,0] = 0\n for i in range (1,dim-1):\n res[i,0] = system_auxB(x[i-1],x[i],x[i+1],y[i-1],y[i],y[i+1])\n return np.asmatrix(res)\n\n# M = init_matrix(x, y)\n# B = init_vector_B(x, y)\n\n### la ligne suivante donne les y\"\n# print npl.solve(M,B)\n\ndef polynomials_by_seg(xj, xjj, yj, yjj, yj2, yjj2):\n \"\"\" Retourne le polynôme de degré 3 correspondant à l'intervalle [xj, xjj] \"\"\"\n return ((polynome_A(xj, xjj)*yj) + (polynome_B(xj,xjj)*yjj) + (polynome_C(xj,xjj)*yj2) + (polynome_D(xj,xjj)*yjj2))\n\ndef sequence_polynomials(abs_list, ord_list):\n \"\"\" Retourne la liste des polynômes de degré 3 correspondant à une liste de points \"\"\"\n ord_2_list = npl.solve(init_matrix(abs_list, ord_list), init_vector_B(abs_list, ord_list))\n poly_list = []\n for i in range(len(abs_list)-1):\n poly_list.append(polynomials_by_seg(abs_list[i], abs_list[i+1], ord_list[i], ord_list[i+1], ord_2_list[i,0], ord_2_list[i+1,0]))\n return poly_list\n\ndef derivate_sequence_polynomials(poly_list):\n \"\"\" Retourne la liste des dérivées des polynômes de degré 3 correspondant à une liste de points \"\"\"\n deriv_list = []\n for i in range(len(poly_list)):\n deriv_list.append(derivate_poly_3(poly_list[i]))\n return deriv_list\n\ndef derivate_poly_3(poly):\n \"\"\" Fonction qui dérive tout polynôme de degré inférieur ou égal à trois \"\"\"\n return np.poly1d([3 * poly[3] , 2 * poly[2] , poly[1] ])\n\ndef print_sequence_polynomials(poly_list, abs_list, ord_list, eps = epsilon, color = 'b'):\n \"\"\" Affiche une liste de polynômes correspondant à une liste de points \"\"\"\n for i in range(len(poly_list)):\n print_polynomial (poly_list[i], min(abs_list[i], abs_list[i+1]), max(abs_list[i], abs_list[i+1]) ,eps, color)\n mp.ylim([-3*max(ey),3*max(ey)])\n\n\ndef print_polynomial(poly, mini, maxi, eps = epsilon, color = 'b'):\n \"\"\" Affiche un polynôme entre les bornes mini et maxi avec une précision souhaitée \"\"\"\n x = np.arange(mini, maxi, eps)\n y = []\n for i in range(len(x)):\n y.append(poly(x[i]))\n mp.plot(x, y, color)\n # mp.show()\n\ndef test_C(xj,xjj):\n tmp = polynome_A(xj, xjj)\n tmp *=-1\n tmp += pow(polynome_A(xj, xjj), 3)\n tmp /= 6\n tmp *= pow((xjj-xj), 2)\n return polynome_C(xj, xjj) == tmp\n\n# p = polynome_C(1, 3)\n\ndef test_splines():\n \"\"\" Test complet de splines.py \"\"\"\n #mp.suptitle('Exemple de conditionnement suivant differentes matrices aleatoires')\n mp.subplot(121)\n\n #mp.ylabel('Cond(A)')\n #mp.xlabel('Pourcentage de valeurs non-nuls')\n print_sequence_polynomials(sequence_polynomials(ex,ey),ex,ey, epsilon,'r')\n print_sequence_polynomials(sequence_polynomials(ix,iy),ix,iy, epsilon,'b')\n print_aile(ex,ey,ix,iy)\n mp.title(\"Allure de l'aile\")\n mp.subplot(122)\n\n print_sequence_polynomials(derivate_sequence_polynomials(sequence_polynomials(ex,ey)),ex,ey,epsilon, 'r')\n print_sequence_polynomials(derivate_sequence_polynomials(sequence_polynomials(ix,iy)),ix,iy,epsilon, 'b')\n mp.title(\"Allure des derives\")\n #mp.xlabel('Pourcentage de valeurs non-nuls')\n #mp.ylabel('Cond(M-1 . A)')\n mp.show()\n#test_splines()\n","sub_path":"5-interpolation-integration-cubic-splines/splines.py","file_name":"splines.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"312937253","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\n\n# 定义网络模型\nclass cnn(nn.Module):\n\n def __init__(self,n_word, config):\n super(cnn, self).__init__()\n\n self.config = config\n\n vocab_size=n_word\n dim=config.dim\n self.vovab_size = vocab_size\n self.dim = dim\n\n # embedding\n self.embedding = nn.Embedding(vocab_size, dim)\n\n filter_sizes = [3, 3, 3]\n self.convs = nn.ModuleList(\n [nn.Conv2d(config.chanel_num, config.filter_num, (size, dim)) for size in filter_sizes])\n\n # dropout layer\n self.dropout = nn.Dropout(config.dropout)\n\n self.l1 = nn.Linear(len(filter_sizes) * config.filter_num, config.num_classes)\n\n def forward(self, x):\n\n x = x.long()\n\n out = self.embedding(x)\n out = out.unsqueeze(1)\n\n out = [F.relu(conv(out)).squeeze(3) for conv in self.convs]\n\n out = [F.max_pool1d(item, item.size(2)).squeeze(2) for item in out]\n\n out = torch.cat(out, 1)\n out = self.dropout(out)\n\n out = self.l1(out)\n\n return out\n","sub_path":"net/text_cnn.py","file_name":"text_cnn.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"241417360","text":"import functools\nimport typing\nimport string\nimport random\nimport pytest\n\n## Lösung Teil 1.\ndef nwords(s: str) -> int:\n \"\"\"\n Determines the amount of words in this string.\n \"\"\"\n word_count = 1\n for c in s:\n if c == string.whitespace:\n word_count += 1\n return word_count\n## Lösung Teil 2.\ndef word_count_iter(it: iter) -> tuple:\n \"\"\"\n Returns the amount of strings, total words and total characters\n generated by an iterator.\n \"\"\"\n rows = 0\n words = 0\n characters = 0\n for s in it:\n rows += 1\n words += nwords(s)\n characters += len(s)\n print(rows, words, characters)\n return (rows, words, characters)\n######################################################################\n## Lösung Teil 3. (Tests)\ndef test_word_count_iter():\n assert word_count_iter([\"foo bar\", \"baz\"]) == (2, 3, 10)\n## revert\ntry:\n word_count_iter = word_count_iter.__wrapped__\nexcept:\n pass\n\n## Lösung Teil 4.\ndef word_count(file) -> tuple:\n with open(file) as fs:\n return word_count_iter(fs)\n######################################################################\n","sub_path":"StudentProblem/10.21.11.40/1/1569573168.py","file_name":"1569573168.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222939848","text":"import torch.optim as optim\nimport numpy as np\nimport math\n\n#from https://github.com/thomasjpfan/pytorch/blob/401ec389db2c9d2978917a6e4d1101b20340d7e7/torch/optim/lr_scheduler.py\n#will eventually be pulled into pytorch repo\nclass CyclicLR(object):\n \"\"\"Sets the learning rate of each parameter group according to\n cyclical learning rate policy (CLR). The policy cycles the learning\n rate between two boundaries with a constant frequency, as detailed in\n the paper `Cyclical Learning Rates for Training Neural Networks`_.\n The distance between the two boundaries can be scaled on a per-iteration\n or per-cycle basis.\n Cyclical learning rate policy changes the learning rate after every batch.\n `batch_step` should be called after a batch has been used for training.\n To resume training, save `last_batch_iteration` and use it to instantiate `CycleLR`.\n This class has three built-in policies, as put forth in the paper:\n \"triangular\":\n A basic triangular cycle w/ no amplitude scaling.\n \"triangular2\":\n A basic triangular cycle that scales initial amplitude by half each cycle.\n \"exp_range\":\n A cycle that scales initial amplitude by gamma**(cycle iterations) at each\n cycle iteration.\n This implementation was adapted from the github repo: `bckenstler/CLR`_\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n base_lr (float or list): Initial learning rate which is the\n lower boundary in the cycle for eachparam groups.\n Default: 0.001\n max_lr (float or list): Upper boundaries in the cycle for\n each parameter group. Functionally,\n it defines the cycle amplitude (max_lr - base_lr).\n The lr at any cycle is the sum of base_lr\n and some scaling of the amplitude; therefore\n max_lr may not actually be reached depending on\n scaling function. Default: 0.006\n step_size (int): Number of training iterations per\n half cycle. Authors suggest setting step_size\n 2-8 x training iterations in epoch. Default: 2000\n mode (str): One of {triangular, triangular2, exp_range}.\n Values correspond to policies detailed above.\n If scale_fn is not None, this argument is ignored.\n Default: 'triangular'\n gamma (float): Constant in 'exp_range' scaling function:\n gamma**(cycle iterations)\n Default: 1.0\n scale_fn (function): Custom scaling policy defined by a single\n argument lambda function, where\n 0 <= scale_fn(x) <= 1 for all x >= 0.\n mode paramater is ignored\n Default: None\n scale_mode (str): {'cycle', 'iterations'}.\n Defines whether scale_fn is evaluated on\n cycle number or cycle iterations (training\n iterations since start of cycle).\n Default: 'cycle'\n last_batch_iteration (int): The index of the last batch. Default: -1\n Example:\n >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)\n >>> scheduler = torch.optim.CyclicLR(optimizer)\n >>> data_loader = torch.utils.data.DataLoader(...)\n >>> for epoch in range(10):\n >>> for batch in data_loader:\n >>> scheduler.batch_step()\n >>> train_batch(...)\n .. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186\n .. _bckenstler/CLR: https://github.com/bckenstler/CLR\n \"\"\"\n TAG_CLR = \"CLR\"\n def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,\n step_size=2000, mode='exp_range', gamma=0.995,\n scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):\n\n if not isinstance(optimizer, optim.Optimizer):\n raise TypeError('{} is not an Optimizer'.format(\n type(optimizer).__name__))\n self.optimizer = optimizer\n self.step_numb=0\n\n if isinstance(base_lr, list) or isinstance(base_lr, tuple):\n if len(base_lr) != len(optimizer.param_groups):\n raise ValueError(\"expected {} base_lr, got {}\".format(\n len(optimizer.param_groups), len(base_lr)))\n self.base_lrs = list(base_lr)\n else:\n self.base_lrs = [base_lr] * len(optimizer.param_groups)\n\n if isinstance(max_lr, list) or isinstance(max_lr, tuple):\n if len(max_lr) != len(optimizer.param_groups):\n raise ValueError(\"expected {} max_lr, got {}\".format(\n len(optimizer.param_groups), len(max_lr)))\n self.max_lrs = list(max_lr)\n else:\n self.max_lrs = [max_lr] * len(optimizer.param_groups)\n\n self.step_size = step_size\n\n if mode not in ['triangular', 'triangular2', 'exp_range', 'cosign_anneal'] \\\n and scale_fn is None:\n raise ValueError('mode is invalid and scale_fn is None')\n\n self.mode = mode\n self.gamma = gamma\n\n if scale_fn is None:\n if self.mode == 'triangular' :\n self.scale_fn = self._triangular_scale_fn\n self.scale_mode = 'cycle'\n elif self.mode == 'triangular2':\n self.scale_fn = self._triangular2_scale_fn\n self.scale_mode = 'cycle'\n elif self.mode == 'exp_range'or self.mode == 'cosign_anneal':\n self.scale_fn = self._exp_range_scale_fn\n self.scale_mode = 'iterations'\n\n else:\n self.scale_fn = scale_fn\n self.scale_mode = scale_mode\n\n # self.batch_step(last_batch_iteration + 1)\n self.last_batch_iteration = last_batch_iteration\n\n\n def batch_step(self, batch_iteration=None):\n if batch_iteration is None:\n batch_iteration = self.last_batch_iteration + 1\n self.last_batch_iteration = batch_iteration\n for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):\n param_group['lr'] = lr\n\n def _triangular_scale_fn(self, x):\n return 1.\n\n def _triangular2_scale_fn(self, x):\n return 1 / (2. ** (x - 1))\n\n def _exp_range_scale_fn(self, x):\n return self.gamma**(x)\n\n\n def get_lr(self):\n step_size = float(self.step_size)\n cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size))\n x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1)\n\n lrs = []\n param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)\n for param_group, base_lr, max_lr in param_lrs:\n base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))\n if self.scale_mode == 'cycle':\n lr = base_lr + base_height * self.scale_fn(cycle)\n else:\n lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)\n lrs.append(lr)\n self.step_numb+=1\n return lrs\n\nclass LR(object):\n '''\n Base class, returns a single cycle of learning rates\n '''\n def __call__(self, *args, **kwargs):\n return self.getLRs()\n\n def getLRs(self,numb_iterations,max_lr, min_lr):\n '''\n :param numb_iterations: number total samples\n :param max_lr: upper\n :param min_lr: lower\n :return: list of learning rates, numb_iterations long\n '''\n raise NotImplementedError\n\nclass TriangularLR(LR):\n def getStepSize(self,numb_iterations):\n return numb_iterations // 2\n\n def getLRs(self, numb_iterations, max_lr, min_lr):\n # determines the halfway point\n step_size = self.getStepSize(numb_iterations)\n data = []\n for itr in range(numb_iterations):\n cycle = math.floor(1 + itr / (2 * step_size))\n x = abs(itr / step_size - 2 * cycle + 1)\n lr = min_lr + (max_lr - min_lr) * max(0, (1 - x))\n data.append(lr)\n return data\n\nclass TriangularLR_LRFinder(TriangularLR):\n def getStepSize(self,numb_iterations):\n return numb_iterations #makes stepsize and numb_iterations equal, you get first half of triangular wave\n\nclass CosignLR(LR):\n def getLRs(self, numb_iterations, max_lr, min_lr):\n '''\n Cosign that starts at max_lr and decreases to min_lr\n '''\n\n # then translate so ranges between low_lr and high_lr\n data = (np.cos(np.linspace(0, np.pi, numb_iterations))) + (max_lr - min_lr) / 2 + min_lr\n return data\n\nclass LR_anneal(object):\n def getMaxLR(self,step_size,max_lr,min_lr):\n raise NotImplemented\n\nclass LR_anneal_linear(LR_anneal):\n def __init__(self):\n self.cur_decrement = 0 #ensures start at 0\n\n def getMaxLR(self,step_size,max_lr,min_lr):\n numb_decrements = len(step_size) # reduce every time we start another cycle\n max_lr_reducer = (max_lr - min_lr) / numb_decrements\n\n # gradually reduce max_lr, but not below min_lr\n maxlr = max((max_lr-self.cur_decrement*max_lr_reducer), min_lr)\n self.cur_decrement += 1\n return maxlr\n\n# def getTriangularLRs(numb_iterations,max_lr, min_lr, step_size =None):\n# '''\n# returns a single tooth /\\ of a sawtooth wave that varies from min_lr to max_lr\n# :param numb_iterations: total learning_rates to generate, make an even number so stepsize will be 1/2 of it\n# :param max_lr:\n# :param min_lr:\n# :param step_size =None used for learning rate finder do several epochs, with increasing LRs\n# to determine appropriate range\n# :return: list of learning rates\n# '''\n# data = []\n# #set stepsize == numb_iterations (1/2 sawtooth) for calculating appropriate Learning rate range\n# if step_size == None:\n# stepsize = numb_iterations//2\n#\n# for itr in range(numb_iterations):\n# cycle = math.floor(1+ itr/(2*stepsize))\n# x=abs(itr/stepsize -2*cycle +1)\n# lr = max_lr +(max_lr - min_lr)*max(0,(1-x))\n# data.append(lr)\n# return data\n#\n#\n# def getCosignLRs(numb_iterations,max_lr, min_lr):\n# '''\n# generates a list of max_iter_per_cycle learning rates that starts at max_lr and descends\n# to base_lr in a cosign wave\n# max_iter_per_cycle changes according to schedule in epochs_per_cycle_schedule\n# :param numb_iterations: total learning_rates to generate, make an even number so stepsize will be 1/2 of it\n# :param max_lr:\n# :param min_lr:\n# :return: list of learning rates\n# '''\n# # cosign varies between 1 and -1 (sweep of 2), factor to scale between lowlr and high_lr\n# scale = 2 / (max_lr - min_lr)\n#\n# # then translate so ranges between low_lr and high_lr\n# data = (np.cos(np.linspace(0, np.pi, numb_iterations)) / scale) + (max_lr - min_lr) / 2 + min_lr\n# return data\n\nNUMB_IMAGES = 5011 # numb images in VOC2007\nclass CyclicLR_Scheduler(object):\n '''\n Part of stochastic gradient descent with warm restarts\n be careful with the learning rate, set it too high and you blow your model\n\n be sure the number of batches you run is equal to sum(step_size)*2 to get the learning rate to min_lr\n for example, step_size = [5,5,5,5,10,10,10] then number batches = 50*2=100\n\n best to use some sort of learning rate finder\n\n '''\n RESTART_CYCLE = 0\n NUMBER_STEPS_PER_CYCLE = 2\n def __init__(self, optimizer,*,min_lr, max_lr, LR,LR_anneal=None,\n batch_size = 64, numb_images= NUMB_IMAGES,step_size=[2], writer =None):\n '''\n :param optimizer: optimizer, used primarily for applying learning rate to params\n :param min_lr:\n :param max_lr:\n :param LR: calculates a single cycle of the learning rate\n :param LR_anneal: anneals the learning rate if present\n :param base_lr: the minimum learning rate\n :param max_lr: the maximum learning rate\n :param batch_size:\n :param numb_images:\n :param step_size:number of training images per 1/2 cycle, authors suggest setting it between 2 and 10\n can be a list, if 4 the whole cycle has 2*(4*numb_images//batch_size) = #iterations/cycle\n this should sum to total number of epochs or your last epoch has lr somewhere\n between max_lr and base_lr\n :param writer: tensorboard writer (see above)\n usage:\n >>>lr = TriangularLR(max_lr, min_lr)\n >>>lra = LR_anneal_linear(step_size,max_lr,min_lr)\n >>>crs = CyclicLR_Scheduler(optimizer, LR,LR_anneal)\n\n '''\n\n #apply learning rates to optimizer layers\n self.optimizer = optimizer\n\n self.min_lr = min_lr\n self.max_lr=max_lr;\n\n #learning rate object\n self.LR = LR\n\n #learning rate annealer\n self.LR_anneal = LR_anneal\n\n #how many iterations per epoch\n self.batch_size = batch_size\n self.numb_images = numb_images\n\n #TODO fix this\n # covers the last partial batch\n # self.pad = 1 if numb_images % self.batch_size > 0 else 0\n self.pad=0\n\n #number iterations per batch\n self.max_iter_per_epoch = numb_images // batch_size + self.pad\n\n # if [1,2,3] then first cosign descent occurs over 1*2 epoch,\n # second over 2*2 epochs, 3rd over 3*2 epochs for a total of 12 epochs\n #any after that are over 6 epochs\n self.step_size = step_size\n self.step_size_loc =CyclicLR_Scheduler.RESTART_CYCLE #when incremented starts at 0\n\n\n #start at 0\n self.loc = CyclicLR_Scheduler.RESTART_CYCLE\n\n #the list of lrs periodically refreshed\n self.vals = []\n self.writer = writer\n\n def _getNumberIterations(self):\n '''\n how many iterations for this cycle\n :return:\n '''\n n_itr = ((self.step_size[self.step_size_loc])*self.max_iter_per_epoch )*CyclicLR_Scheduler.NUMBER_STEPS_PER_CYCLE\n\n # only advance if there are more, otherwise stay at the last one\n if (self.step_size_loc < len(self.step_size)-1):\n self.step_size_loc += 1 # go to the next one\n return n_itr\n\n def _calculate_learning_rate_range(self):\n '''\n generates a list of max_iter_per_cycle learning rates that starts at max_lr and descends\n to base_lr in a cosign wave\n max_iter_per_cycle changes according to schedule in epochs_per_cycle_schedule\n '''\n\n #gradually reduce the learning rate\n maxlr = self.max_lr\n if self.LR_anneal is not None:\n maxlr = self.LR_anneal.getMaxLR(step_size=self.step_size,max_lr= self.max_lr,min_lr=self.min_lr)\n\n # then translate so ranges between low_lr and high_lr\n self.vals = self.LR.getLRs(numb_iterations = self._getNumberIterations(), max_lr=maxlr, min_lr=self.min_lr)\n\n def _get_lr(self):\n #time to restart?\n if (self.loc == len(self.vals)):\n self.loc = CyclicLR_Scheduler.RESTART_CYCLE\n\n # time to go to the next cycle length?\n if (self.loc == CyclicLR_Scheduler.RESTART_CYCLE):\n self._calculate_learning_rate_range()\n\n lrs=[]\n lrs.append(self.vals[self.loc])\n\n #prepare for the next one\n self.loc += 1\n\n if (self.writer is not None):\n self.writer('CLRS', lrs[0])\n # print(f\" lr{lrs[0]}\")\n return lrs\n\n def batch_step(self):\n for param_group, lr in zip(self.optimizer.param_groups, self._get_lr()):\n param_group['lr'] = lr\n self.cur_lr = lr #used in learning rate finder\n\n\n# class CosAnnealLR(CyclicLR):\n# '''\n# Part of stochastic gradient descent with warm restarts\n# be careful with the learning rate, set it too high and you blow your model\n# best to use some sort of learning rate finder\n#\n# '''\n#\n# RESTART_COSIGN_CYCLE = -1\n#\n# def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,\n# mode='cos_anneal', gamma=1,\n# scale_fn=None, scale_mode='cycle', last_batch_iteration=-1, batch_size = 64, numb_images= NUMB_IMAGES,epochs_per_cycle_schedule = [1,1,2,2,3] ):\n# super().__init__(optimizer, base_lr, max_lr,\n# mode, gamma,\n# scale_fn, scale_mode, last_batch_iteration)\n#\n# #how many iterations per epoch\n# self.max_iter_per_cycle = numb_images // batch_size\n#\n# # if [1,2,3] then first cosign descent occurs over 1 epoch,\n# # second over 2 epochs, 3rd over 3 epochs for a total of 6 epochs\n# #any after that are over 3 epochs\n# self.epochs_per_cycle_schedule = epochs_per_cycle_schedule\n# self.epochs_per_cycle_schedule_loc = 0\n#\n# self.base_lr = base_lr\n# self.max_lr = max_lr\n#\n# #diff between base_lr and max_lr\n# diff = max_lr - base_lr\n# total_epochs = sum(self.epochs_per_cycle_schedule)\n# self.max_lr_reducer = diff/total_epochs\n#\n# #add to max_lr so it all works out on first calculation\n# self.max_lr +=self.max_lr_reducer\n#\n# #start at 0\n# self.current_iteration = CosAnnealLR.RESTART_COSIGN_CYCLE\n# self.loc = CosAnnealLR.RESTART_COSIGN_CYCLE\n#\n# self.scale_fn = self._exp_range_scale_fn #OK to scale with this\n# self.scale_mode = 'iterations'\n# self.writer = SummaryWriter()\n#\n# def calculate_learning_rate_range(self):\n# '''\n# generates a list of max_iter_per_cycle learning rates that starts at max_lr and descends\n# to base_lr in a cosign wave\n#\n# max_iter_per_cycle changes according to schedule in epochs_per_cycle_schedule\n# '''\n# #gradually reduce the learning rate\n# self.max_lr = self.max_lr-self.max_lr_reducer\n#\n# # cosign varies between 1 and -1 (sweep of 2), factor to scale between lowlr and high_lr\n# scale = 2 / (self.max_lr - self.base_lr)\n#\n# # then translate so ranges between low_lr and high_lr\n# self.vals = (np.cos(np.linspace(0, np.pi, self.max_iter_per_cycle)) / scale) + (self.max_lr - self.base_lr) / 2 + self.base_lr\n#\n# def setWriter(self,writer):\n# self.writer = writer\n#\n# # def __getCycleMult():\n# #\n#\n# def get_lr(self):\n#\n# # time to go to the next cycle length?\n# if (self.loc == CosAnnealLR.RESTART_COSIGN_CYCLE):\n# if (self.epochs_per_cycle_schedule_loc < len(self.epochs_per_cycle_schedule)):\n# self.max_iter_per_cycle= self.max_iter_per_cycle * self.epochs_per_cycle_schedule[self.epochs_per_cycle_schedule_loc]\n# self.epochs_per_cycle_schedule_loc += 1\n# self.calculate_learning_rate_range()\n# print(f\" number vals {len(self.vals)}\")\n# self.current_iteration = CosAnnealLR.RESTART_COSIGN_CYCLE\n#\n# lrs=[]\n# lrs.append(self.vals[self.loc])\n#\n# self.writer.add_scalar('cosann', lrs[0], self.last_batch_iteration)\n#\n# #set up for next time\n# self.current_iteration += 1\n# self.loc= (self.current_iteration)%self.max_iter_per_cycle\n#\n# return lrs\n\n\n\n","sub_path":"utils_LR.py","file_name":"utils_LR.py","file_ext":"py","file_size_in_byte":19214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319481257","text":"from modules.database import User, TopupCards, db\nfrom datetime import datetime, timedelta\n\ndb.connect()\n\n#Placeholders, for example only\nload_cards = [\n\t{'cardcode': 'AAA123', 'cardvalue': 100, 'cardsn': 'NANO-S-TEST', 'claimed': False},\n {'cardcode': 'BBB123', 'cardvalue': 1, 'cardsn': 'NANO-S-001', 'claimed': False},\n {'cardcode': 'CCC123', 'cardvalue': 2, 'cardsn': 'NANO-S-002', 'claimed': False},\n {'cardcode': 'DDD123', 'cardvalue': 3, 'cardsn': 'NANO-S-003', 'claimed': False}\n # ...\n]\n\nprint(\"loading cards... \")\nTopupCards.insert_many(load_cards).execute()\n","sub_path":"loadcards.py","file_name":"loadcards.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146474091","text":"import asyncio\nimport logging\nfrom typing import List\n\nimport arrow\n\nfrom notbot.context import Context, Module\nfrom notbot.db import get_raid_postgres_dao, get_raid_stats_dao\nfrom notbot.models import RaidPlayerAttack, RaidStats\n\nMODULE_NAME = \"raid_stat_service\"\nlogger = logging.getLogger(__name__)\n\n\nclass RaidStatService(Module):\n def __init__(self, context: Context):\n self.raid_postgres_dao = get_raid_postgres_dao(context)\n self.raid_stats_dao = get_raid_stats_dao(context)\n\n def get_name(self):\n return MODULE_NAME\n\n async def get_raid_for_id(self, raid_id):\n return await self.raid_postgres_dao.get_raid_for_id(raid_id)\n\n async def get_uncompleted_raids(self, guild_id):\n return await self.raid_postgres_dao.get_uncompleted_raids(guild_id)\n\n async def get_last_completed_raids(self, guild_id):\n return await self.raid_postgres_dao.get_last_completed_raids(guild_id)\n\n async def save_raid_player_attacks(self, attacks: List[RaidPlayerAttack]):\n return await self.raid_stats_dao.save_raid_player_attacks(attacks)\n\n async def check_if_attacks_exist(self, guild_id, raid_id):\n return await self.raid_stats_dao.check_if_attacks_exist(guild_id, raid_id)\n\n async def has_raid_permission_and_raid_exists(self, guild_id, raid_id):\n return await self.raid_postgres_dao.has_raid_permission_and_raid_exists(\n guild_id, raid_id\n )\n\n async def get_raid_list(self, guild_id):\n \"\"\"\n returns the last 10 completed last 10 uncompleted raids\n \"\"\"\n\n return await asyncio.gather(\n self.get_uncompleted_raids(guild_id),\n self.get_last_completed_raids(guild_id),\n )\n\n async def get_raid_player_attacks_for_raid_id(self, raid_id):\n return await self.raid_stats_dao.get_raid_player_attacks_for_raid_id(raid_id)\n\n async def create_start_raid_stat_entry(self, guild_id, raid_start: arrow.Arrow):\n return await self.raid_postgres_dao.create_start_raid_stat_entry(\n guild_id, raid_start\n )\n\n async def create_raid_stat_entry(\n self, guild_id, started_at: arrow.Arrow, cleared_at: arrow.Arrow\n ):\n return await self.raid_postgres_dao.create_raid_stat_entry(\n guild_id, started_at, cleared_at\n )\n\n async def calculate_raid_stats(self, raid_id: int):\n attacks = await self.get_raid_player_attacks_for_raid_id(raid_id)\n raid = await self.get_raid_for_id(raid_id)\n\n min_dmg, max_dmg, min_avg, max_avg, min_hits, max_hits, total_dmg, total_avg = (\n -1,\n 0,\n -1,\n 0,\n -1,\n 0,\n 0,\n 0,\n )\n for attack in attacks:\n _attack_avg = (\n 0 if not attack.total_hits else attack.total_dmg / attack.total_hits\n )\n\n total_dmg += attack.total_dmg\n total_avg += _attack_avg\n\n if attack.total_dmg > max_dmg:\n max_dmg = attack.total_dmg\n\n if min_dmg == -1 or attack.total_dmg < min_dmg:\n min_dmg = attack.total_dmg\n\n if attack.total_hits > max_hits:\n max_hits = attack.total_hits\n\n if min_hits == -1 or attack.total_hits < min_hits:\n min_hits = attack.total_hits\n\n if _attack_avg > max_avg:\n max_avg = _attack_avg\n\n if min_avg == -1 or _attack_avg < min_avg:\n min_avg = _attack_avg\n\n raid_stats = RaidStats(\n min_dmg,\n max_dmg,\n round(total_dmg / len(attacks), 2),\n round(min_avg, 2),\n round(max_avg, 2),\n round(total_avg / len(attacks), 2),\n min_hits,\n max_hits,\n total_dmg,\n len(attacks),\n raid.started_at,\n raid.cleared_at,\n )\n\n return raid_stats\n\n async def delete_raid_entry(self, raid_id):\n await self.delete_attacks_for_raid(raid_id)\n await self.raid_postgres_dao.delete_raid_entry(raid_id)\n\n async def delete_attacks_for_raid(self, raid_id):\n await self.raid_stats_dao.delete_attacks_for_raid(raid_id)\n\n async def load_raid_data_for_stats(self, guild_id, raid_id):\n \"\"\"\n Loads the data needed to create the stats for the given raid_id\n ( Will include the previous raid if possible )\n \"\"\"\n raid_data = await self.raid_stats_dao.load_raid_data_for_stats(\n guild_id, raid_id\n )\n\n return raid_data\n\n\ndef get_raid_stat_service(context: Context) -> RaidStatService:\n return context.get_or_register_module(MODULE_NAME, lambda: RaidStatService(context))\n","sub_path":"notbot/services/raid_stat_service.py","file_name":"raid_stat_service.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"530727905","text":"import json\n\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n\nfrom cir.models import *\n\nfrom cir.phase_control import PHASE_CONTROL\nimport utils\n\n\ndef get_claim_list(request):\n \"\"\"\n Get list of claims, by category.\n :param request:\n :return:\n \"\"\"\n forum = Forum.objects.get(id=request.session['forum_id'])\n response = {}\n context = {}\n\n category_list = ['finding', 'pro', 'con']\n context['categories'] = {}\n response['slots_cnt'] = {'finding': 0, 'pro': 0, 'con': 0}\n slots = Claim.objects.filter(forum=forum, is_deleted=False,\n stmt_order__isnull=False)\n for category in category_list:\n context['categories'][category] = [slot.getAttrSlot(forum) for slot in\n slots.filter(\n claim_category=category).order_by(\n 'stmt_order')]\n response['slots_cnt'][category] += len(context['categories'][category])\n response['claims'] = render_to_string('phase4/claim.html', context)\n return HttpResponse(json.dumps(response), mimetype='application/json')\n\n\ndef get_statement_list(request):\n \"\"\"\n Get list of statements (claims), in categories.\n :param request:\n :return:\n \"\"\"\n forum = Forum.objects.get(id=request.session['forum_id'])\n response = {}\n context = {}\n if request.REQUEST.get('category'):\n category_list = [request.REQUEST['category']]\n else:\n category_list = ['finding', 'pro', 'con']\n context['categories'] = {}\n response['slots_cnt'] = {'finding': 0, 'pro': 0, 'con': 0}\n slots = Claim.objects.filter(forum=forum, is_deleted=False,\n stmt_order__isnull=False)\n for category in category_list:\n context['categories'][category] = [slot.getAttrSlot(forum) for slot in\n slots.filter(\n claim_category=category).order_by(\n 'stmt_order')]\n response['slots_cnt'][category] += len(context['categories'][category])\n\n response['html'] = render_to_string('phase4/statement.html', context)\n return HttpResponse(json.dumps(response), mimetype='application/json')\n\n\ndef put_statement(request):\n response = {}\n content = request.REQUEST.get('content')\n slot = Claim.objects.get(id=request.REQUEST.get('slot_id'))\n claim = Claim.objects.get(id=request.REQUEST.get('claim_id'))\n now = timezone.now()\n newClaim = Claim(forum_id=request.session['forum_id'], author=request.user,\n created_at=now, updated_at=now,\n content=content, claim_category=slot.claim_category)\n newClaim.save()\n claim_version = ClaimVersion(forum_id=request.session['forum_id'],\n author=request.user, content=content,\n created_at=now, updated_at=now, claim=newClaim,\n is_adopted=True)\n claim_version.save()\n ClaimReference.objects.create(refer_type='stmt', from_claim=newClaim,\n to_claim=slot)\n ClaimReference.objects.create(refer_type='claim2stmt', from_claim=claim,\n to_claim=newClaim)\n SlotAssignment.objects.create(forum_id=request.session['forum_id'],\n user=request.user,\n entry=newClaim, created_at=now,\n slot=slot, event_type='add')\n return HttpResponse(json.dumps(response), mimetype='application/json')\n\n\ndef add_claim_to_statement(request):\n \"\"\"\n Used when a nugget is added to a claim to merge into it.\n :param request:\n :return:\n \"\"\"\n response = {}\n\n content = request.REQUEST.get('content')\n forum = Forum.objects.get(id=request.session['forum_id'])\n src_nugget = Claim.objects.get(id=request.REQUEST.get('nugget_id'))\n target_claim = Claim.objects.get(id=request.REQUEST.get('claim_id'))\n # TODO: preserve edit history\n target_claim.content = content\n target_claim.save()\n version = target_claim.adopted_version()\n version.content = content\n version.save()\n now = timezone.now()\n ClaimReference.objects.create(refer_type='nug2claim', from_claim=src_nugget,\n to_claim=target_claim)\n ClaimNuggetAssignment.objects.create(forum=forum,\n user=request.user,\n entry=target_claim,\n created_at=now,\n claim=target_claim,\n nugget=src_nugget,\n event_type='add')\n return HttpResponse(json.dumps(response), mimetype='application/json')\n","sub_path":"cir/phase4.py","file_name":"phase4.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"273975683","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom imageio import imread, imwrite\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport re\nimport glob\nimport sys\n\nif os.path.exists('./Extracted-patches/Augmented-data'):\n print('Augmented-data directory exists!')\n sys.exit()\nelse:\n os.mkdir('./Extracted-patches/Augmented-data')\n\ngen = ImageDataGenerator(rotation_range=10, brightness_range=[0.5,1.1],\n shear_range=0.2, horizontal_flip=True)\n\nimages = './Extracted-patches/Train-data/*.jpg'\nimages_name = glob.glob(images)\n\nfor image in images_name:\n # Use Regex standard libray to extract image_id_number.\n # './Extracted-patches/Augmented-data/03125.jpg' --> 03125\n m = re.search(r'.*/(.*)\\.\\w+', image)\n image_number = m.group(1)\n # input to ImageDataGenerator should be 4-dimensional\n img = np.expand_dims(imread(image), 2)\n img = np.expand_dims(img, 0)\n aug_iter = gen.flow(img)\n aug_images = [next(aug_iter)[0].astype(np.uint8) for i in range(4)]\n #plt.subplot(1, 5, 1)\n #plt.imshow(np.squeeze(img), cmap='gray')\n for i in range(4):\n name = './Extracted-patches/Augmented-data/{}_{}.jpg'.format(image_number,i)\n print('Created {}'.format(name))\n #plt.subplot(1,5,i+2)\n #plt.imshow(np.squeeze(aug_images[i]), cmap='gray')\n imwrite(name, np.squeeze(aug_images[i]))\n #plt.show()\n","sub_path":"data_augment.py","file_name":"data_augment.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"114126153","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\nfrom itertools import product\n\n\ndef main():\n \"\"\"\n 产生ABC和123的笛卡尔积\n ('A', '1')\n ('A', '2')\n ('A', '3')\n ('B', '1')\n ('B', '2')\n ('B', '3')\n ('C', '1')\n ('C', '2')\n ('C', '3')\n \"\"\"\n c = product('ABC', '123')\n for x in c:\n print(x)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"language/python/modules/System/itertools/itertools_module_product.py","file_name":"itertools_module_product.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"338104834","text":"#\n\nimport unittest\nimport json\nimport sys\nimport os\n\nimport ndc\nimport util\nimport config.external\n\n\n###############################################################################\n\nclass TestCase(unittest.TestCase):\n\n conf = config.external.Conf()\n conf.load_config()\n\n ###########################################################################\n #\n\n def test_load_config(self):\n assert(\"plugins_dir\" in self.conf.__dict__)\n\n ###########################################################################\n #\n\n def test_remote_run(self):\n\n file_path = \"ndc.test.run.empty.txt\"\n\n if os.path.exists(file_path):\n os.remove(file_path)\n\n assert(not os.path.exists(file_path))\n\n process_output = util.remote_run(\n command_line = \"touch \" + file_path,\n username = \"username\",\n hostname = \"hostname\",\n raise_on_error = True,\n allocate_tty = False,\n capture_stdout = False,\n capture_stderr = False,\n force_local = True,\n )\n\n assert(\"stdout\" not in process_output)\n assert(\"stderr\" not in process_output)\n assert(process_output[\"code\"] == 0)\n assert(os.path.isfile(file_path))\n\n # Cleanup\n os.remove(file_path)\n\n\n###############################################################################\n\n","sub_path":"utils/test/test_ndc.py","file_name":"test_ndc.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"507553568","text":"# Copyright 1999-2020 Alibaba Group Holding Ltd.\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 functools\nimport inspect\nimport logging\nimport struct\nimport sys\nimport threading\nimport weakref\n\nimport numpy as np\n\nfrom .actors import FunctionActor\nfrom .actors.core import ActorRef\nfrom .errors import PromiseTimeout\nfrom .utils import build_exc_info\n\nlogger = logging.getLogger(__name__)\n_promise_pool = dict()\n_pack_qword = struct.Struct(' 0:\n # add a callback that triggers some times later to deal with timeout\n timeout_coro = self._caller.ref().handle_promise_timeout(\n promise_id, _tell=True, _delay=timeout)\n else:\n timeout_coro = None\n\n self._caller.register_promise(p, self._ref, timeout_coro)\n\n kwargs['callback'] = ((self._caller.uid, self._caller.address),\n 'handle_promise', promise_id)\n kwargs['_tell'] = True\n\n def _promise_runner():\n try:\n ref_fun(*args, **kwargs)\n except: # noqa: E722\n self._caller.ref().handle_promise(\n promise_id, *sys.exc_info(), _accept=False, _tell=True)\n\n if spawn:\n self._caller.async_group.spawn(_promise_runner)\n else:\n ref_fun(*args, **kwargs)\n\n return p\n\n return _mt_fun\n\n\ndef reject_on_exception(func):\n \"\"\"\n Decorator on actor callback functions that handles exceptions by\n sending it to caller as promise rejections. The function should have\n an argument called ``callback``.\n \"\"\"\n arg_names = inspect.getfullargspec(func).args\n callback_pos = None\n if arg_names:\n for idx, name in enumerate(arg_names):\n if name == 'callback':\n callback_pos = idx\n break\n\n @functools.wraps(func)\n def _wrapped(*args, **kwargs):\n callback = None\n if 'callback' in kwargs:\n callback = kwargs['callback']\n elif callback_pos and callback_pos < len(args):\n callback = args[callback_pos]\n\n try:\n return func(*args, **kwargs)\n except: # noqa: E722\n actor = args[0]\n logger.exception('Unhandled exception in promise call')\n if callback:\n actor.tell_promise(callback, *sys.exc_info(), _accept=False)\n else:\n raise\n return _wrapped\n\n\nclass PromiseActor(FunctionActor):\n \"\"\"\n Actor class providing promise functionality\n \"\"\"\n def _prepare_promise_registration(self):\n if not hasattr(self, '_promises'):\n self._promises = dict()\n self._promise_ref_keys = dict()\n self._promise_timeout_coros = dict()\n self._ref_key_promises = dict()\n\n def promise_ref(self, *args, **kwargs):\n \"\"\"\n Wraps an existing ActorRef into a promise ref\n \"\"\"\n self._prepare_promise_registration()\n\n if not args and not kwargs:\n ref = self.ref()\n elif args and isinstance(args[0], ActorRef):\n ref = self.ctx.actor_ref(args[0].uid, address=args[0].address)\n else:\n ref = self.ctx.actor_ref(*args, **kwargs)\n return PromiseRefWrapper(ref, self)\n\n @property\n def async_group(self):\n if not hasattr(self, '_async_group'):\n self._async_group = self.ctx.asyncpool()\n return self._async_group\n\n def spawn_promised(self, func, *args, **kwargs):\n \"\"\"\n Run func asynchronously in a pool and returns a promise.\n The running of the function does not block current actor.\n\n :param func: function to run\n :return: promise\n \"\"\"\n self._prepare_promise_registration()\n\n p = Promise()\n ref = self.ref()\n self.register_promise(p, ref)\n\n def _wrapped(*a, **kw):\n try:\n result = func(*a, **kw)\n except: # noqa: E722\n ref.handle_promise(p.id, *sys.exc_info(), _accept=False, _tell=True)\n else:\n ref.handle_promise(p.id, result, _tell=True)\n finally:\n del a, kw\n\n try:\n self.async_group.spawn(_wrapped, *args, **kwargs)\n finally:\n del args, kwargs\n return p\n\n def register_promise(self, promise, ref, timeout_coro=None):\n \"\"\"\n Register a promise into the actor with referrer info\n\n :param Promise promise: promise object to register\n :param ActorRef ref: ref\n :param timeout_coro: coroutine of timeout\n \"\"\"\n promise_id = promise.id\n\n def _weak_callback(*_):\n self.delete_promise(promise_id)\n\n self._promises[promise_id] = weakref.ref(promise, _weak_callback)\n ref_key = (ref.uid, ref.address)\n self._promise_ref_keys[promise_id] = ref_key\n if timeout_coro is not None:\n self._promise_timeout_coros[promise_id] = timeout_coro\n try:\n self._ref_key_promises[ref_key].add(promise_id)\n except KeyError:\n self._ref_key_promises[ref_key] = {promise_id}\n\n def get_promise(self, promise_id):\n \"\"\"\n Get promise object from weakref.\n \"\"\"\n obj = self._promises.get(promise_id)\n if obj is None:\n return None\n return obj()\n\n def delete_promise(self, promise_id):\n _promise_pool.pop(promise_id, None)\n if promise_id not in self._promises:\n return\n ref_key = self._promise_ref_keys[promise_id]\n self._ref_key_promises[ref_key].remove(promise_id)\n del self._promises[promise_id]\n del self._promise_ref_keys[promise_id]\n\n def reject_dead_endpoints(self, dead_endpoints, *args, **kwargs):\n \"\"\"\n Reject all promises related to given remote address\n :param dead_endpoints: list of dead workers\n \"\"\"\n dead_refs = []\n for ref_key in self._ref_key_promises.keys():\n uid, addr = ref_key\n if addr in dead_endpoints:\n dead_refs.append(self.ctx.actor_ref(uid, address=addr))\n return self.reject_promise_refs(dead_refs, *args, **kwargs)\n\n def reject_promise_refs(self, refs, *args, **kwargs):\n \"\"\"\n Reject all promises related to given actor ref\n :param refs: actor refs to reject\n \"\"\"\n kwargs['_accept'] = False\n handled_refs = []\n for ref in refs:\n ref_key = (ref.uid, ref.address)\n if ref_key not in self._ref_key_promises:\n continue\n handled_refs.append(ref)\n for promise_id in list(self._ref_key_promises[ref_key]):\n p = self.get_promise(promise_id)\n if p is None:\n continue\n p.step_next([args, kwargs])\n return handled_refs\n\n def tell_promise(self, callback, *args, **kwargs):\n \"\"\"\n Tell promise results to the caller\n :param callback: promise callback\n \"\"\"\n wait = kwargs.pop('_wait', False)\n uid, address = callback[0]\n callback_args = callback[1:] + args + (kwargs, )\n return self.ctx.actor_ref(uid, address=address).tell(callback_args, wait=wait)\n\n def handle_promise(self, promise_id, *args, **kwargs):\n \"\"\"\n Callback entry for promise results\n :param promise_id: promise key\n \"\"\"\n try:\n p = self.get_promise(promise_id)\n if p is None:\n logger.warning('Promise %r reentered or not registered in %s', promise_id, self.uid)\n return\n self.get_promise(promise_id).step_next([args, kwargs])\n\n timeout_coro = self._promise_timeout_coros.pop(promise_id, None)\n if timeout_coro is not None:\n timeout_coro.kill()\n finally:\n self.delete_promise(promise_id)\n\n def handle_promise_timeout(self, promise_id):\n \"\"\"\n Callback entry for promise timeout\n :param promise_id: promise key\n \"\"\"\n try:\n p = self.get_promise(promise_id)\n if p is None or p._accepted is not None:\n # skip promises that are already finished\n return\n\n p.step_next([build_exc_info(PromiseTimeout), dict(_accept=False)])\n self._promise_timeout_coros.pop(promise_id, None)\n finally:\n self.delete_promise(promise_id)\n\n\ndef all_(promises):\n \"\"\"\n Create a promise with promises. Invoked when all referenced promises accepted\n or at least one rejected\n :param promises: collection of promises\n :return: the new promise\n \"\"\"\n promises = list(promises)\n\n promise_refs = [weakref.ref(p) for p in promises if isinstance(p, Promise)]\n new_promise = Promise()\n running_ids = set(ref().id for ref in promise_refs)\n\n def _build_then_reject(promise_ref):\n ref_id = promise_ref().id\n\n def _then(*_, **__):\n _promise_pool.pop(ref_id, None)\n running_ids.difference_update([ref_id])\n if not running_ids:\n new_promise.step_next()\n\n def _reject(*args, **kw):\n _promise_pool.pop(ref_id, None)\n if new_promise._accepted is not None:\n return\n kw['_accept'] = False\n new_promise.step_next([args, kw])\n\n return _then, _reject\n\n for ref in promise_refs:\n ref().then(*_build_then_reject(ref))\n\n if promise_refs:\n return new_promise\n else:\n new_promise.step_next()\n return new_promise\n\n\ndef get_active_promise_count():\n return len(_promise_pool)\n\n\ndef finished(*args, **kwargs):\n \"\"\"\n Create a promise already finished\n :return: Promise object if _promise is True, otherwise args[0] will be returned\n \"\"\"\n promise = kwargs.pop('_promise', True)\n accept = kwargs.pop('_accept', True)\n if not promise:\n return args[0] if args else None\n if accept:\n return Promise(done=True, args=args, kwargs=kwargs)\n else:\n return Promise(failed=True, args=args, kwargs=kwargs)\n","sub_path":"mars/promise.py","file_name":"promise.py","file_ext":"py","file_size_in_byte":20826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571740528","text":"# %BANNER_BEGIN%\n# ---------------------------------------------------------------------\n# %COPYRIGHT_BEGIN%\n#\n# Copyright (c) 2018 Magic Leap, Inc. (COMPANY) All Rights Reserved.\n# Magic Leap, Inc. Confidential and Proprietary\n#\n# NOTICE: All information contained herein is, and remains the property\n# of COMPANY. The intellectual and technical concepts contained herein\n# are proprietary to COMPANY and may be covered by U.S. and Foreign\n# Patents, patents in process, and are protected by trade secret or\n# copyright law. Dissemination of this information or reproduction of\n# this material is strictly forbidden unless prior written permission is\n# obtained from COMPANY. Access to the source code contained herein is\n# hereby forbidden to anyone except current COMPANY employees, managers\n# or contractors who have executed Confidentiality and Non-disclosure\n# agreements explicitly covering such access.\n#\n# The copyright notice above does not evidence any actual or intended\n# publication or disclosure of this source code, which includes\n# information that is confidential and/or proprietary, and is a trade\n# secret, of COMPANY. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION,\n# PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS\n# SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF COMPANY IS\n# STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND\n# INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE\n# CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS\n# TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE,\n# USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.\n#\n# %COPYRIGHT_END%\n# ---------------------------------------------------------------------\n# %BANNER_END%\n\nimport json\nimport os\nimport shlex\nimport stat\nfrom json import JSONDecodeError\n\nimport build_env\nimport diags\nimport platforms\nimport project_vars\nfrom build_model import Path\nfrom config import HOSTOS, OS_WIN, OS_OSX, OS_LINUX, get_host_segment, get_runtime_library_path_var\nfrom makegen import MakeGen\nfrom run_vars import runtime_values, MLSDK, HOST\nfrom sdk_shim_parser import SdkShimParser\nfrom utils import format_command_line, remove_duplicates\n\n\ndef fetch_mlremote_lib_paths():\n host = get_host_segment()\n\n sdk_manifest_path = os.path.join(runtime_values[MLSDK], \".metadata\", \"sdk.manifest\")\n try:\n with open(sdk_manifest_path, \"rt\", encoding=\"UTF-8\", errors=\"replace\") as f:\n sdk_manifest = json.load(f)\n\n sdk_version = sdk_manifest.get(\"version\")\n\n except (OSError, JSONDecodeError) as e:\n diags.warn(\"Failed to parse {}\\nPlease verify your setup and installation.\"\n \"\\n({})\".format(sdk_manifest_path, e))\n return []\n\n if not sdk_version:\n diags.warn(\"Did not detect \\\"version\\\" attribute in {}.\\nPlease verify your setup and installation.\"\n .format(sdk_manifest_path))\n sdk_version = '0.20.0' # we don't depend on it currently\n\n sdk_shim_path = os.path.join(runtime_values[MLSDK], \".metadata\", \"sdk_shim_discovery.txt\")\n try:\n with open(sdk_shim_path, \"rt\", encoding=\"UTF-8\", errors=\"replace\") as f:\n sdk_shim_text = f.read()\n\n shim_parser = SdkShimParser(sdk_shim_text, runtime_values[MLSDK], sdk_version, host)\n\n except OSError as e:\n diags.warn(\"Failed to parse {}, needed for correct launching of host apps under ML Remote.\"\n \"\\nPlease verify your setup and installation (if you pass MLSDK=..., it should point to \"\n \"a version for 0.18 or newer, or, pass '-Z' to launch without ML Remote support).\"\n \"\\n({})\".format(sdk_shim_path, e))\n return []\n\n zi_paths = shim_parser.expand('ZI_SHIM_PATH_' + host)\n return zi_paths\n\n\nclass InvokeModel(object):\n \"\"\"\n This represents the information needed to invoke a particular project.\n \"\"\"\n def __init__(self, opts, package, project):\n self._opts = opts\n\n self._package = package\n \"\"\" @type: projects.Project \"\"\"\n self._project = project\n \"\"\" @type: projects.Project \"\"\"\n\n # target for scripts is the same as project output dir\n self._output_directory = os.path.normpath(self._project.output_directory)\n\n self._mlsdk = runtime_values[MLSDK]\n\n # get some platform-specific stuff out of the way...\n platform = build_env.platform()\n self._is_device_build = (platform.name == platforms.lumin.NAME)\n\n self._executable_name = self._project.output_filename()\n\n @property\n def project_path(self):\n return self._project.path\n\n def generate_json(self):\n model = {\n 'project_path': self.project_path,\n 'executable_path': self._executable_path,\n 'executable_command': self._exe_command,\n }\n\n self._add_json_vars(model)\n return model\n\n def _make_commands_win(self):\n cmds = []\n\n cmds.extend([\n \"@echo off\",\n \"setlocal\",\n \"pushd \\\"{}\\\"\".format(self._launch_directory),\n ])\n\n self._make_specific_commands_win(cmds)\n\n cmds.extend([\n \"popd\",\n \"exit /b %__RETCODE__%\",\n ])\n\n return cmds\n\n def _make_commands_posix(self):\n \"\"\"\n Create bash commands for Unix-like hosts.\n \"\"\"\n cmds = []\n cmds.extend([\n \"#!/usr/bin/env bash\",\n \"__OLDPWD__=$PWD\",\n \"cd \\\"{}\\\"\".format(self._launch_directory),\n ])\n\n self._make_specific_commands_posix(cmds)\n\n cmds.extend([\n \"cd $__OLDPWD__\",\n \"exit $__RETCODE__\",\n ])\n\n return cmds\n\n def write_script(self):\n \"\"\"\n Write a shell script (.bat/.sh) that can do the invocation work\n :return: path\n \"\"\"\n filename = \"invoke-{}\".format(self._package.package_name if self._package else self._project.name)\n\n if HOSTOS == OS_WIN:\n filename += \".bat\"\n cmds = self._make_commands_win()\n else:\n filename += \".sh\"\n cmds = self._make_commands_posix()\n\n # Create the output directory if it doesn't exist.\n if not os.access(self._output_directory, os.F_OK):\n os.makedirs(self._output_directory)\n\n # Write it out\n out_file_path = os.path.normpath(os.path.join(self._project.output_directory, filename))\n with open(out_file_path, \"w\") as f:\n f.write(\"\\n\".join(cmds))\n\n # Get the invoke file permissions.\n st = os.stat(out_file_path)\n\n # Make the invoke file executable.\n os.chmod(out_file_path, st.st_mode | stat.S_IEXEC)\n\n return out_file_path\n\n\nclass InvokeModelDevice(InvokeModel):\n \"\"\"\n This represents the information needed to invoke on device.\n \"\"\"\n def __init__(self, opts, package, project, environ):\n InvokeModel.__init__(self, opts, package, project)\n\n package_filename = \"{}.mpk\".format(self._project.package_name)\n self._package_path = os.path.join(self._output_directory, package_filename)\n self._installed_package_name = self._project.manifest.package_name\n self._envsetup_basename_path = os.path.abspath(os.path.join(self._mlsdk, \"envsetup\"))\n self._device_install_cmd = \"mldb install -u \\\"{}\\\"\".format(self._package_path)\n\n self._launch_directory = \".\"\n self._executable_path = self._executable_name\n\n self._exe_command = [\"mldb\", \"launch\", \"-f\", self._installed_package_name]\n if opts.invoke_args:\n self._exe_command += [\"-i\", opts.invoke_args] # one string\n\n def _add_json_vars(self, model):\n model['install_command'] = self._device_install_cmd\n model['package_path'] = self._package_path\n\n def _make_specific_commands_win(self, cmds):\n cmds.extend([\n \"call \\\"{}.bat\\\"\".format(self._envsetup_basename_path),\n self._device_install_cmd,\n \"set __RETCODE__=%ERRORLEVEL%\",\n \"if %__RETCODE__% EQU 0 (\",\n \"\\t{}\".format(format_command_line(self._exe_command)),\n \"\\tset __RETCODE__=%ERRORLEVEL%\",\n \")\",\n ])\n\n def _make_specific_commands_posix(self, cmds):\n cmds.extend([\n \"source \\\"{}.sh\\\"\".format(self._envsetup_basename_path),\n self._device_install_cmd,\n \"__RETCODE__=$?\",\n \"if [ $__RETCODE__ -eq 0 ]; then\",\n \"\\t{}\".format(format_command_line(self._exe_command)),\n \"\\t__RETCODE__=$?\",\n \"fi\",\n ])\n\n\nclass InvokeModelHost(InvokeModel):\n \"\"\"\n This represents the information needed to invoke on host.\n \"\"\"\n def __init__(self, opts, package, project, environ=os.environ):\n InvokeModel.__init__(self, opts, package, project)\n\n self._launch_directory = self._package.package_layout_path.resolve() if self._package else self._output_directory\n self._executable_path = os.path.join(self._output_directory, self._executable_name)\n\n self._exe_command = [self._executable_path] + \\\n (self._opts.invoke_args and shlex.split(self._opts.invoke_args) or [])\n\n self._source_lib_path_var = self._lib_path_var = get_runtime_library_path_var()\n\n if HOSTOS == OS_OSX:\n # Favor ML_LIBRARY_PATH over an empty/missing DYLD_LIBRARY_PATH,\n # which macOS deletes for our ever-loving security\n # (see https://apple.stackexchange.com/questions/212945/unable-to-set-dyld-fallback-library-path-in-shell-on-osx-10-11-1).\n # (mlvdsetup.sh sets up ML_LIBRARY_PATH)\n if not environ.get(self._lib_path_var) and environ.get('ML_LIBRARY_PATH'):\n if not self._opts.quiet:\n diags.info(\"macOS deleted ${}, using $ML_LIBRARY_PATH instead\".format(self._lib_path_var))\n self._source_lib_path_var = 'ML_LIBRARY_PATH'\n\n project_lib_paths = self._project.combined.get(project_vars.LIBPATHS, []) if self._project.combined else []\n\n dfs = self._project.dependency_list(build_env.projects(), build_env.components())\n\n ref_lib_paths = [Path(dep_proj.output_directory) for dep_proj in dfs if\n dep_proj.is_program() or dep_proj.is_shared()]\n\n all_paths = [path.resolve() for path in project_lib_paths + ref_lib_paths]\n\n if not self._is_device_build:\n # get the user's current library paths\n env_lib_val = environ.get(self._source_lib_path_var, '')\n if env_lib_val:\n env_lib_paths = env_lib_val.split(os.pathsep)\n else:\n env_lib_paths = []\n\n # and get any ML Remote / ZI library paths\n if self._opts.mlremote_adjust:\n mlremote_lib_paths = fetch_mlremote_lib_paths()\n else:\n mlremote_lib_paths = []\n\n all_paths = env_lib_paths + mlremote_lib_paths + all_paths\n\n self._lib_paths = remove_duplicates([os.path.abspath(path) for path in all_paths])\n\n def _add_json_vars(self, model):\n model['working_directory'] = self._launch_directory\n model['library_paths'] = self._lib_paths\n model['library_variable'] = self._lib_path_var\n\n def _make_specific_commands_win(self, cmds):\n if self._lib_paths:\n # no quotes in PATH var\n new_path_var = \";\".join(self._lib_paths + [\"%PATH%\"])\n cmds.append(\"PATH={}\".format(new_path_var))\n\n cmds.extend([\n format_command_line(self._exe_command),\n \"set __RETCODE__=%ERRORLEVEL%\",\n ])\n\n def _make_specific_commands_posix(self, cmds):\n exe_cmd = list(self._exe_command)\n\n if self._lib_paths:\n # add quotes around the entire definition, not each path, and ensure the\n # quote follows \"=\" so format_command_line() won't bork it\n exe_cmd.insert(0, '{0}=\"{1}:${0}\"'.format(self._lib_path_var, os.pathsep.join(self._lib_paths)))\n\n cmds.extend([\n format_command_line(exe_cmd),\n \"__RETCODE__=$?\",\n ])\n\n\ndef generate_invoke_model(opts, package, proj, is_device_build, environ=os.environ):\n is_device_program_build = is_device_build and proj.is_program()\n is_non_device_package_build = not is_device_build and proj.is_package()\n is_non_program_and_non_package = not proj.is_program() and not proj.is_package()\n\n if is_device_program_build or is_non_device_package_build or is_non_program_and_non_package:\n # Ignore builds that cannot be invoked.\n return None\n\n model_factory = (is_device_build and InvokeModelDevice or InvokeModelHost)\n model = model_factory(opts, package, proj, environ)\n return model\n\n\ndef generate_invoke_models(opts):\n env = build_env\n\n mg = MakeGen(env.projects(), env.components(), opts.build_scope)\n mg.generate(env.user_projects())\n\n platform = build_env.platform()\n is_device_build = (platform.name == platforms.lumin.NAME)\n\n # track the current package\n # (we will see, for a .package that REFS .mabu,\n # first the .package, then the .mabu)\n package = None\n\n models = []\n\n # Find any invokable projects.\n for proj in build_env.fetch_scoped_projects(0):\n model = generate_invoke_model(opts, package, proj, is_device_build)\n if model:\n models.append(model)\n if proj.is_package():\n package = proj\n\n if not models:\n diags.error(\"no invokable projects found.\")\n\n return models\n","sub_path":"common/mlsdk/v0.23.0/tools/mabu/src/invoke.py","file_name":"invoke.py","file_ext":"py","file_size_in_byte":13647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"326091853","text":"'''\nCreated on Nov 10, 2015\n\n@author: ds-ga-1007\n'''\nfrom calculatereturn import *\nfrom plotfig import *\n\ndef dothetrial(position_list,initial_capital,num_trials): \n result_output=open('results.txt','w')\n for position in position_list:\n invest_simulation=CalculateSingleDayReturn(position,initial_capital,num_trials)\n invest_simulation.repeat_ntimes_oneday()\n cumu_ret=invest_simulation.cumu_ret\n daily_ret=invest_simulation.daily_ret\n line=\"Position = %d, mean = %f, std = %f\" % (position,np.mean(cumu_ret),np.std(daily_ret))\n result_output.write(line)\n result_output.write('\\n')\n plotfig(position,daily_ret) \n result_output.close()\n","sub_path":"my1396/ass8/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"408122161","text":"import logging\nfrom time import sleep\nfrom connections import getmongo\nfrom models import *\n\nconn = getmongo()\n#logger = logging.getLogger()\n#logger.setLevel(logging.DEBUG)\n\nclass Worker(object):\n def run(self):\n while True:\n Channel.update_all()\n items = Item.objects(status=0)\n# print \"Processing %d items\" % len(items)\n for i in items:\n i.process()\n sleep(3)\n\n \nif __name__ == '__main__':\n w = Worker()\n w.run()\n\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"613261268","text":"import numpy as np\nimport cv2\nimport my_padding as my_p\nimport time\n\ndef my_get_Gaussian2D_mask(msize, sigma=1):\n y, x = np.mgrid[-(msize // 2):(msize // 2) + 1, -(msize // 2):(msize // 2) + 1]\n '''\n y, x = np.mgrid[-1:2, -1:2]\n y = [[-1,-1,-1],\n [ 0, 0, 0],\n [ 1, 1, 1]]\n x = [[-1, 0, 1],\n [-1, 0, 1],\n [-1, 0, 1]]\n '''\n #2차 gaussian mask 생성\n gaus2D = 1 / (2 * np.pi * sigma**2) * np.exp(-(( x**2 + y**2 )/(2 * sigma**2)))\n\n #mask의 총 합 = 1\n gaus2D /= np.sum(gaus2D)\n\n return gaus2D\n\ndef my_get_Gaussian1D_mask(msize, sigma=1):\n ###############################################\n # TODO #\n # my_get_Gaussian1D_mask 함수 완성 #\n ###############################################\n y, x = np.ogrid[0:0, -(msize // 2):(msize // 2) + 1]\n\n gaus1D = 1 / (2 * np.pi * sigma**2) * np.exp(-(( x**2)/(2 * sigma**2)))\n gaus1D /= np.sum(gaus1D)\n\n return gaus1D\n\ndef my_filtering(src, mask, pad_type = 'zero'):\n (h, w) = src.shape\n\n #mask의 크기\n (m_h, m_w) = mask.shape\n\n #mask 확인\n #print('')\n #print(mask)\n\n # 직접 구현한 my_padding 함수를 이용\n pad_img = my_p.my_padding(src, (m_h//2, m_w//2), pad_type)\n\n dst = np.zeros((h, w))\n\n #시간을 확인하려면 4중 for문을 이용해야함\n for row in range(h):\n for col in range(w):\n sum = 0\n for m_row in range(m_h):\n for m_col in range(m_w):\n sum += pad_img[row + m_row, col+m_col] * mask[m_row, m_col]\n dst[row, col] = sum\n\n #4중 for문 시간이 오래걸릴 경우 해당 코드 사용(시간을 확인하려면 해당 코드를 사용하면 안됨)\n # for row in range(h):\n # for col in range(w):\n # dst[row, col] = np.sum(pad_img[row:row + m_h, col:col + m_w] * mask)\n\n return dst\n\nif __name__ == '__main__':\n src = cv2.imread('Lena.png', cv2.IMREAD_GRAYSCALE)\n mask_size = 5\n gaus2D = my_get_Gaussian2D_mask(mask_size, sigma = 3)\n gaus1D = my_get_Gaussian1D_mask(mask_size, sigma = 3)\n\n #mask size 출력\n print('mask size : ', mask_size)\n\n #1차 가우시안 필터 적용 및 시간 재기\n print('1D gaussian filter')\n start = time.perf_counter() # 시간 측정 시작\n dst_gaus1D= my_filtering(src, gaus1D)\n dst_gaus1D= my_filtering(dst_gaus1D, gaus1D.T)\n dst_gaus1D = (dst_gaus1D + 0.5).astype(np.uint8)\n end = time.perf_counter() # 시간 측정 끝\n print('1D time : ', end-start)\n\n #2차 가우시안 필터 적용 및 시간 재기\n print('2D gaussian filter')\n start = time.perf_counter() # 시간 측정 시작\n dst_gaus2D= my_filtering(src, gaus2D)\n dst_gaus2D = (dst_gaus2D + 0.5).astype(np.uint8)\n end = time.perf_counter() # 시간 측정 끝\n print('2D time : ', end-start)\n\n #결과 이미지 출력\n cv2.imshow('original', src)\n cv2.imshow('1D gaussian img', dst_gaus1D)\n cv2.imshow('2D gaussian img', dst_gaus2D)\n\n #1차 가우시안 필터와 2차 가우시안 필터 비교, 차이가 없으면 count = 0\n (h, w) = dst_gaus1D.shape #(h, w) = dst_gaus2D.shape\n count = 0\n for i in range(h):\n for j in range(w):\n if dst_gaus1D[i, j] != dst_gaus2D[i, j]:\n count += 1 #두 값이 다르면 count += 1\n print('count : ', count)\n\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n","sub_path":"Gaussian/my_gaussian.py","file_name":"my_gaussian.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"195851018","text":"import random\n\nprint(\"Hi! Welcome to the game. What is your name?\")\nname = input()\nprint(\"Well, \" + name + \" I am thinking of a number between 1 and 20..\")\nsecretNumber = random.randint(1, 20)\n\n##for loop - player has 6 tries\nfor guessesTaken in range(1, 7):\n print(\"Take another guess..\")\n playerGuess = int(input())\n\n if playerGuess < secretNumber:\n print(\"Nope! Your guess is too low\")\n elif playerGuess > secretNumber:\n print(\"Nope Your guess is too high\")\n else:\n break #this condition is for the correct guess\n\n#if player guesses correctly\nif playerGuess == secretNumber:\n print(\"Good job! You took \" + str(guessesTaken) + \" guesses to win!\")\nelse:\n print(\"Nope. The number I was thinking of is \" + str(secretNumber))\n\n","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"591631936","text":"#!/usr/bin/python\n\n#-------------------------------------------------------------------------------\n# Name: \tmain.py\n# Purpose: Main application for Neptune Pool and Spa Automation\n#\n# Author: \talji\n#\n# Created: \t14/11/2012\n# Copyright: (c) alji 2012\n# Licence: \t\n#-------------------------------------------------------------------------------\nimport os\nimport datetime as dt\n\n#---Twisted Serial / HTTP---\nfrom twisted.internet import reactor\nfrom twisted.web import server, resource\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet.serialport import SerialPort\n\nimport xml.etree.ElementTree as xmlEtree\n\n#---Neptune---\nIS_TEST = True\n#PLATFORM = \"mac\"\nPLATFORM = \"windows\"\n# On my mac, required libraries are not in my python path and must be inserted:\n## (this is simply a convenience for my own benefit, this is not elegant code)\nif PLATFORM == \"mac\":\n print(\"mac\")\n import sys\n sys.path.insert(0, '/Users/jisunstetson/bin')\n# Now, the following imports will work\nfrom modules.neptune.crown import NeptuneCrown\nfrom modules.neptune.logger import NeptuneLogger\n\n###################################\n## GLOBALS\n###################################\nNPASASC = \"111576\" # Authorization code\n# Define COM ports for serial communication with Arduino\nif PLATFORM == \"windows\":\n COM_PORT = 'COM3'\nelif PLATFORM == \"mac\":\n COM_PORT = '/dev/ttys0'\n\n###################################\n## SERIAL\n###################################\nclass SerialResource(LineReceiver):\n \"\"\"\n This object processes incoming serial requests and sends outgoing serial commands.\n \"\"\"\n def processData(self, data):\n \"\"\"\n Processes any incoming serial data\n :param data: serial data to be decoded\n :type data: str\n :return: None\n \"\"\"\n # Alert user to incoming serial data\n print(\"<--%s--: %s\" % (COM_PORT, data))\n # Decode the data according to Neptune protocol\n devId = data[0:4]\n devType = data[4]\n newValue = data[5:]\n\n crown = NeptuneCrown()\n author = '1000' # Arduino device ID\n\n # Currently, Arduino only ever sends signals regarding Sensors\n if devType == \"n\":\n (success, pretty) = crown.updateSensorDevice(devId, newValue, author=author)\n # Alert user to success or failure\n if success:\n print(pretty)\n else:\n print(\"ERROR: %s\" % pretty)\n\n def connectionMade(self):\n \"\"\"\n This method is built in to the LineReceiver object, and tells the Receiver\n what to do in the case of a successful connection. We only wish to alert the user.\n :return: None\n \"\"\"\n print('Serial connection made!')\n\n def lineReceived(self, line):\n \"\"\"\n This method is built in to the LineReceiver object, and tells the Receiver\n what to do in the case of a successful receipt of serial data.\n :param line: Incoming serial bytes\n :return: None\n \"\"\"\n data = str(line)\n try:\n self.processData(data)\n except ValueError:\n print('Unable to parse data %s' % line)\n\n def serialWrite(self, data):\n \"\"\"\n This method writes any requested data to the serial connection.\n :param data: Requested data to be sent\n :type data: str\n :return: True\n :rtype: bool\n \"\"\"\n # Alert the user to outgoing serial data\n print(\" --%s-->: %s\" % (COM_PORT, data))\n # Append return and newline expected by Arduino\n data += \"/r/n\"\n # Send data\n self.sendLine(data)\n return True\n\n# def sendLine(self):\n# pass\n\n###################################\n## WEB\n###################################\nclass WebResource(resource.Resource):\n \"\"\"\n This base class for all http protocol resources just provides a serial property\n which these resources will use to execute any commands specified over http.\n \"\"\"\n def setSerial(self, serialProcess):\n self.serialProcess = serialProcess\n\nclass HttpResource(WebResource):\n \"\"\"\n This object functions as our root http resource, being called to display by default\n if no child resources are requested.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n # Send anything, just to test the serial connection\n success = self.serialProcess.serialWrite(\"I like you.\")\n\n request.setHeader(\"content-type\", \"html\")\n #request.setHeader(\"content-type\", \"text/plain\")\n if success:\n # So here, because we were successful in connecting to our arduino, we can\n # serve up the web app version of Neptune.\n return \"Neptune Pool and Spa Automation\"\\\n \"Hello friend and welcome to Neptune Pool and Spa Automation!\"\\\n \"\"\n else:\n return \"Neptune Pool and Spa Automation\"\\\n \"There was an error while attempting to contact your Neptune \"\\\n \"Pool and Spa Automation device.

Please make sure that your device \"\\\n \"is on and connected to the internet.\"\n\n def getChild(self, name, request):\n \"\"\"\n Built-in method to resource.Resource defining how to associate incoming requests\n with child objects or itself.\n :param name: name of the child object to be called\n :type name: str\n :param request: incoming http request\n :return: self or appropriate child\n :rtype: resource.Resource\n \"\"\"\n if name == '':\n return self\n return resource.Resource.getChild(self, name, request)\n\nclass WebFetch(WebResource):\n \"\"\"\n This object defines the Fetch child resource. Its job is simply to dump device\n information into the browser in the form of an XML etree for the user to read.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n request.setHeader('Content-Type', 'text/xml')\n # Load the device info\n ## I keep the device info in different places depending on the platform. This is a hacky\n ## convenience and is not elegant code.\n if PLATFORM == \"mac\":\n tree = xmlEtree.parse('/Users/jisunstetson/allen/code/webpy/deviceInfo.xml')\n elif PLATFORM == \"windows\":\n tree = xmlEtree.parse('/Users/alji/Documents/neptune/main/deviceState.xml')\n\n # Parse the XML file and serve it as-is.\n root = tree.getroot()\n return(xmlEtree.tostring(root))\n\nclass WebSwitch(WebResource):\n \"\"\"\n This object defines the Switch child resource. Its job is to manipulate switch-type devices\n based on incoming http requests.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n self.crown = NeptuneCrown()\n request.setHeader(\"content-type\", \"text/plain\")\n data = request.args\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"0:Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"0:Authentication failed. Access denied.\"\n\n # Collect requested device ID and new value\n devId = data['dev'][0]\n value = data['to'][0]\n\n # Perform the device update\n (code, pretty) = self.crown.setSwitchDevice(devId, value, author='0001')\n if code:\n report = \"1:%s\\n %s\" % (pretty, code)\n self.serialProcess.serialWrite(code)\n else:\n report = \"0:Serial Write failed. %s\" % pretty\n return str(report)\n\nclass WebStep(WebResource):\n \"\"\"\n This object defines the Step child resource. Its job is to manipulate step-type devices\n based on incoming http requests.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n self.crown = NeptuneCrown()\n request.setHeader(\"content-type\", \"text/plain\")\n data = request.args\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"0:Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"0:Authentication failed. Access denied.\"\n\n # Collect requested device ID and new value\n devId = data['dev'][0]\n value = data['to'][0]\n\n # Perform the device update\n (code, pretty) = self.crown.setStepDevice(devId, value, author='0001')\n if code:\n report = \"1:%s\\n %s\" % (pretty, code)\n else:\n report = \"0:Serial Write failed. %s\" % pretty\n return str(report)\n\nclass WebSet(WebResource):\n \"\"\"\n This object defines the Set child resource. Its job is to manipulate any type of\n device by setting a given attribute to a value provided through incoming http requests.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n self.crown = NeptuneCrown()\n request.setHeader(\"content-type\", \"text/plain\")\n data = request.args\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"0:Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"0:Authentication failed. Access denied.\"\n\n # Collect requested device ID, attribute name, and new value\n devId = data['dev'][0]\n attrib = data['set'][0]\n value = data['to'][0]\n\n # Perform the device update\n (success,code) = self.crown.setDeviceAttribute(devId, attrib, value, author='0001')\n if success:\n return \"1: Device %s, %s set to %s\\n %s\" % (devId, attrib, value, code)\n else:\n return \"0:Serial Write failed. %s\" % code\n\nclass WebAdd(WebResource):\n \"\"\"\n This object defines the Add child resource. Its job is to add new devices to the Neptune\n which will then receive default values.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n data = request.args\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"Authentication failed. Access denied.\"\n\n # Add configuration entry\n name = data['name']\n entryType = data['entryType'][0]\n # ALLEN - THIS CODE IS UNFINISHED\n # Add call to device addition in crown here.\n return \"Adding config %s of type %s\" % (name, entryType)\n\nclass WebRemove(WebResource):\n \"\"\"\n This object defines the Remove child resource. Its job is to remove devices from the Neptune\n configuration.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n data = request.args\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"Authentication failed. Access denied.\"\n\n # Add configuration entry\n idno = data['idno'][0]\n # ALLEN - THIS CODE IS UNFINISHED\n # Add call to device removal in crown here.\n return \"Removing config with id %s\" % idno\n\nclass WebLog(WebResource):\n \"\"\"\n This object defines the Log Entry child resource. Its job is to add an entry to the Neptune log.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n data = request.args\n\n print(data)\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"Authentication failed. Access denied. %s vs %s\" % (securityCode, NPASASC)\n\n # Add configuration entry\n entry = data['entry'][0]\n now = dt.datetime.now()\n # ALLEN - THIS CODE IS UNFINISHED\n # Add call to add log entry here.\n return \"Adding entry at %s to log: %s\" % (now, entry)\n\nclass WebReadLog(WebResource):\n \"\"\"\n ! UNFINISHED ! This object will provide users with a way to read through a whole log file\n in their browser.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n data = request.args\n\n if not data:\n return ''\n\n return \"Not yet implemented.\"\n\nclass WebMap(WebResource):\n \"\"\"\n This object defines the Map child resource. Initially intended to map out successful\n sensor updates in a graph, it can actually be used to fetch a log record of successful\n updates to any device.\n \"\"\"\n def render_GET(self, request):\n \"\"\"\n Built-in method to resource.Resource which defines what to do when asked to display\n via http.\n :param request: incoming http request\n :return: html markup\n :rtype: str\n \"\"\"\n data = request.args\n request.setHeader(\"content-type\", \"text/plain\")\n\n if not data:\n return ''\n\n # Verify authorized connection\n if not data.has_key(\"npasasc\"):\n return \"Authentication required. Access denied.\"\n securityCode = data['npasasc'][0]\n if securityCode != NPASASC:\n return \"Authentication failed. Access denied.\"\n\n # Collect device ID\n devId = data['dev'][0]\n\n # Load the log\n ## ALLEN - this whole mess should be off-loaded to a method in a module\n logger = NeptuneLogger('0001')\n log = logger.getOrCreateLog()\n values = []\n for entry in log:\n if log[entry]['destination'] == devId:\n values.append((entry,log[entry]['success'][1].split()[-1]))\n return str(values)\n\n###################################\n## main\n###################################\nif __name__ == '__main__':\n # Serial\n ## Define our serial resource and spin up a connection to the Arduino\n print('About to open port %s' % COM_PORT)\n serialProcess = SerialResource()\n s = SerialPort(serialProcess, COM_PORT, reactor, baudrate=9600)\n\n\n # HTTP\n ## Define Web Resources and give them access to the serial process\n root = HttpResource()\n root.setSerial(serialProcess)\n webFetch = WebFetch()\n webFetch.setSerial(serialProcess)\n webSet = WebSet()\n webSet.setSerial(serialProcess)\n webSwitch = WebSwitch()\n webSwitch.setSerial(serialProcess)\n webStep = WebStep()\n webStep.setSerial(serialProcess)\n webAdd = WebAdd()\n webAdd.setSerial(serialProcess)\n webRemove = WebRemove()\n webRemove.setSerial(serialProcess)\n webLog = WebLog()\n webLog.setSerial(serialProcess)\n webReadLog = WebReadLog()\n webReadLog.setSerial(serialProcess)\n webMap = WebMap()\n webMap.setSerial(serialProcess)\n\n ## Add Web Resources to root\n root.putChild('fetch', webFetch)\n root.putChild('set', webSet)\n root.putChild('switch', webSwitch)\n root.putChild('step', webStep)\n root.putChild('add', webAdd)\n root.putChild('remove', webRemove)\n root.putChild('log', webLog)\n root.putChild('readlog', webReadLog)\n root.putChild('map', webMap)\n\n ## Add root to Site factory and add factory to reactor\n factory = server.Site(root)\n reactor.listenTCP(8080, factory)\n\n # Fire it up, Herb\n print(\"Running Neptune Serial service at: %s\" % COM_PORT)\n if PLATFORM == \"windows\":\n address = \"http://alji-hp610:8080/\"\n if PLATFORM == \"mac\":\n address = \"http://ji-sun-stetsons-computer.local:8080/\"\n print(\"Running Neptune HTTP service at:\\n\\t%s\" % address)\n\n reactor.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"366568176","text":"# -*-coding:utf-8-*-\r\n\r\n# 需要的字段,键数据库字段名,值原字段名\r\ndemand_works = {\r\n 'video_desc': 'desc',\r\n 'create_time': 'create_time',\r\n 'aweme_id': 'aweme_id',\r\n 'share_url': 'share_url',\r\n 'author_user_id': 'author_user_id',\r\n 'statistics': 'statistics',\r\n}\r\n","sub_path":"python/douyin/conf/demand_works_config.py","file_name":"demand_works_config.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"194677699","text":"import matplotlib.pyplot as plt\nimport csv\nobject1=[]\nobject2=[]\n\nwith open('data.csv','r') as csvfile:\n plots =csv.reader(csvfile,delimiter=',')\n for column in plots:\n object1.append(float(column[0]))\n object2.append(float(column[1]))\n\nplt.scatter(object1,object2 ,label='Loaded from file!')\nplt.xlabel('Object1')\nplt.ylabel('Object2')\n\nplt.title('Visualization')\nplt.legend()\nplt.show()","sub_path":"NSGA3_Sort/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"580631869","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n \n oniad_address_id = fields.Many2one(\n comodel_name='oniad.address',\n string='Oniad Address'\n )\n \n @api.one \n def oniad_root_complete_data(self, product, account_payment_ids):\n #account.invoice.lines\n payments_total = 0 \n for account_payment_id in account_payment_ids:\n #account_invoice_line_vals\n account_invoice_line_vals = {\n 'invoice_id': self.id,\n 'oniad_transaction_id': account_payment_id.oniad_transaction_id.id,\n 'product_id': product.id,#Producto Gasto\n 'name': account_payment_id.communication,\n 'quantity': 1,\n 'price_unit': account_payment_id.amount,\n 'account_id': product.property_account_income_id.id,\n 'purchase_price': account_payment_id.oniad_purchase_price,\n 'currency_id': account_payment_id.currency_id.id \n }\n #oniad_product_id\n if account_payment_id.oniad_product_id.id>0:\n account_invoice_line_vals['product_id'] = account_payment_id.oniad_product_id.id \n #create\n account_invoice_line_obj = self.env['account.invoice.line'].sudo().create(account_invoice_line_vals)\n account_invoice_line_obj._onchange_product_id()\n account_invoice_line_obj._onchange_account_id() \n #price\n price_unit = account_payment_id.amount/((account_invoice_line_obj.invoice_line_tax_ids.amount/100)+1) \n payments_total = payments_total + account_payment_id.amount\n #update\n account_invoice_line_obj.update({\n 'price_unit': round(price_unit,4),\n 'name': account_payment_id.communication,\n 'price_subtotal': price_unit,\n })\n #Fix check totals\n self.compute_taxes()\n #check\n if payments_total>self.amount_total:\n amount_rest = payments_total-self.amount_total\n for tax_line_id in self.tax_line_ids:\n tax_line_id.amount = tax_line_id.amount + amount_rest\n #update tax_line_ids\n self.update({'tax_line_ids': self.tax_line_ids})\n elif self.amount_total>payments_total:\n amount_rest = self.amount_total-payments_total\n for tax_line_id in self.tax_line_ids:\n tax_line_id.amount = tax_line_id.amount - amount_rest\n #update tax_line_ids\n self.update({'tax_line_ids': self.tax_line_ids})\n #update payment.invoice \n _logger.info('Factura '+str(self.id)+' actualizada correctamente')\n #operations\n if self.partner_id.vat!=False and self.partner_id.vat!=\"\":\n self.action_invoice_open()\n _logger.info('Factura '+str(self.id)+' validada correctamente') \n self.action_auto_create_message_slack()#slack.message \n #payments\n if len(account_payment_ids)>0:\n for account_payment_id in account_payment_ids:\n if account_payment_id.payment_type=='inbound':\n for move_line_id in account_payment_id.move_line_ids: \n if move_line_id.credit>0:\n _logger.info('Factura '+str(self.id)+' pre-asignar asiento contable '+str(move_line_id.id)+ ' del pago '+str(account_payment_id.id))\n self.assign_outstanding_credit(move_line_id.id)\n _logger.info('Factura '+str(self.id)+' asignado asiento contable '+str(move_line_id.id)+ ' del pago '+str(account_payment_id.id))\n elif account_payment_id.payment_type=='outbound':\n for move_line_id in account_payment_id.move_line_ids:\n if move_line_id.debit>0:\n _logger.info('Factura '+str(self.id)+' pre-asignar asiento contable '+str(move_line_id.id)+ ' del pago '+str(account_payment_id.id))\n self.assign_outstanding_credit(move_line_id.id)\n _logger.info('Factura '+str(self.id)+' asignado asiento contable '+str(move_line_id.id)+ ' del pago '+str(account_payment_id.id))","sub_path":"oniad_root/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"417391965","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGiven a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n\nAn input string is valid if:\n\nOpen brackets must be closed by the same type of brackets.\nOpen brackets must be closed in the correct order.\n\"\"\"\n\nclass Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s) %2 != 0:\n return False\n dic = {\"(\":\")\", \"{\":\"}\",\"[\":\"]\"}\n record = []\n for i in s:\n if i in dic:\n record.append(i)\n #can't pop empty stack\n elif not record:\n return False\n ##refer to correct order: last open bracket must macth \n elif dic[record.pop()]!= i:\n return False\n \n return len(record)==0\n\nif __name__ == \"__main__\":\n print(Solution().isValid(\"()[]{}\"))\n print(Solution().isValid(\"()[{]}\"))","sub_path":"Hackrank/Valid_Parentheses.py","file_name":"Valid_Parentheses.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"623011400","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 14 14:44:04 2018\n\n@author: Mjr\n\"\"\"\n\n# =============================================================================\n# This demonstrates how an object (point) can be used as a template for a seq.\n# =============================================================================\n\n\nimport numpy as np\n\n\nclass Point():\n\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\n def show_point(self):\n return (self.x, self.y, self.z)\n\n\npoints = []\n\nfor i in range(0, 10):\n cord = np.random.randint(1, 10, 3)\n point = Point(cord[0], cord[1], cord[2])\n points.append(point)\n\nfor i in points:\n print(i.show_point())\n","sub_path":"python/anaconda/spyder/base/class/composition-point-class.py","file_name":"composition-point-class.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112373950","text":"\nfrom os import path\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.decorators import api_view\n\nfrom api.lib import JSONResponse\nfrom frontend.models import MP3LibraryPath\nfrom api.serializers import MP3LibraryPathSerializer\n\ndef librarypath_list(request):\n ''' List all the library paths '''\n if request.method == 'GET':\n librarypaths = MP3LibraryPath.objects.all()\n serializer = MP3LibraryPathSerializer(librarypaths, many=True)\n return JSONResponse(serializer.data)\n\ndef librarypath_element(request, pk):\n ''' Add or Update Library Path '''\n if request.method == 'POST':\n data = {\n 'library_path': request.POST.get('library_path')\n }\n \n # Check if the path actually exists\n if not path.isdir(data['library_path']):\n error_message = \"'\"+data['library_path']+\"' is not a valid path.\"\n return JSONResponse(error_message, status=400)\n\n serializer = MP3LibraryPathSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=201)\n return JSONResponse(serializer.errors, status=400)\n\n elif request.method == 'PUT':\n try:\n mp3librarypath = MP3LibraryPath.objects.get(pk=pk)\n except MP3LibraryPath.DoesNotExist:\n return JSONResponse(status=404)\n\n jsondata = JSONParser().parse(request)\n data = {\n 'library_path': jsondata['library_path']\n }\n serializer = MP3LibraryPathSerializer(mp3librarypath, data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=201)\n return JSONResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n \n try:\n mp3librarypath = MP3LibraryPath.objects.get(pk=pk)\n except MP3LibraryPath.DoesNotExist:\n return JSONResponse(status=404)\n\n mp3librarypath.delete();\n return JSONResponse({}, status=204);\n\n","sub_path":"bebopdjang/api/views/librarypath.py","file_name":"librarypath.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646379656","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\nclass BST :\n def __init__(self, node) :\n self.node = node\n self.left = None\n self.right = None\n self.diff = 1e21\n def leaf(self) :\n return self.diff is None\n# Complete the minimumLoss function below.\n\ndef insert_node(root,node) :\n min_val = 1e+21\n if node > root.node and root.right is None:\n root.right = BST(node) \n minna = root.diff\n elif node > root.node :\n minna = insert_node(root.right,node)\n elif root.left is None :\n root.left = BST(node)\n root.diff = min(root.diff,abs(node - root.node))\n minna = root.diff\n else :\n root.diff = min(root.diff,abs(root.node - node))\n minna = min(root.diff,insert_node(root.left,node))\n return min(min_val,minna) \n\n\ndef display(root) :\n print(root.node,root.diff)\n if root.left is not None :\n display(root.left)\n if root.right is not None :\n display(root.right)\n \ndef minimumLoss(price):\n min_val = 1e21\n root = BST(price[0])\n for x in price[1:] :\n minna = insert_node(root,x)\n min_val = min(min_val,minna)\n return min_val\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n price = list(map(int, input().rstrip().split()))\n\n result = minimumLoss(price)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Minimum_Loss.py","file_name":"Minimum_Loss.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"403511410","text":"# coding=utf-8\nimport httplib\n\nimport importlib\nimport logging\nimport re\nimport time\n\nfrom lxml import etree\nimport tornado.autoreload\nimport tornado.web\nimport tornado.ioloop\nimport tornado.curl_httpclient\nfrom tornado.options import options\n\nfrom frontik import frontik_logging\nfrom frontik.globals import global_stats\nimport frontik.producers.json_producer\nimport frontik.producers.xml_producer\nfrom frontik.handler import ErrorHandler\nimport frontik.sentry\nfrom frontik.util import make_get_request\n\napp_logger = logging.getLogger('frontik.app')\n\n\ndef get_frontik_and_apps_versions(application):\n from frontik.version import version\n import simplejson\n import sys\n import tornado\n\n versions = etree.Element('versions')\n etree.SubElement(versions, 'frontik').text = version\n etree.SubElement(versions, 'tornado').text = tornado.version\n etree.SubElement(versions, 'lxml.etree.LXML').text = '.'.join(str(x) for x in etree.LXML_VERSION)\n etree.SubElement(versions, 'lxml.etree.LIBXML').text = '.'.join(str(x) for x in etree.LIBXML_VERSION)\n etree.SubElement(versions, 'lxml.etree.LIBXSLT').text = '.'.join(str(x) for x in etree.LIBXSLT_VERSION)\n etree.SubElement(versions, 'simplejson').text = simplejson.__version__\n etree.SubElement(versions, 'python').text = sys.version.replace('\\n', '')\n etree.SubElement(versions, 'application', name=options.app).extend(application.application_version_xml())\n\n return versions\n\n\nclass VersionHandler(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type', 'text/xml')\n self.write(\n etree.tostring(get_frontik_and_apps_versions(self.application), encoding='utf-8', xml_declaration=True))\n\n\nclass StatusHandler(tornado.web.RequestHandler):\n\n @tornado.web.asynchronous\n def get(self):\n self.set_header('Content-Type', 'application/json; charset=UTF-8')\n\n result = {\n 'pages served': global_stats.page_count,\n 'http requests made': global_stats.http_reqs_count,\n 'bytes from http requests': global_stats.http_reqs_size_sum,\n }\n\n cur_uptime = time.time() - global_stats.start_time\n if cur_uptime < 60:\n uptime_value = '{:.2f} seconds'.format(cur_uptime)\n elif cur_uptime < 3600:\n uptime_value = '{:.2f} minutes'.format(cur_uptime / 60)\n else:\n uptime_value = '{:.2f} hours and {:.2f} minutes'.format(cur_uptime / 3600, (cur_uptime % 3600) / 60)\n\n result['uptime'] = uptime_value\n self.finish(result)\n\n\nclass PdbHandler(tornado.web.RequestHandler):\n def get(self):\n import pdb\n pdb.set_trace()\n\n\nclass CountTypesHandler(tornado.web.RequestHandler):\n def get(self):\n import gc\n from collections import defaultdict\n\n counts = defaultdict(int)\n for o in gc.get_objects():\n counts[type(o)] += 1\n\n for k, v in sorted(counts.items(), key=lambda x: x[0]):\n self.write('%s\\t%s\\n' % (v, k))\n\n\ndef get_rewritten_request_attribute(request, field):\n return getattr(request, 're_' + field, getattr(request, field))\n\n\ndef set_rewritten_request_attribute(request, field, value):\n setattr(request, 're_' + field, value)\n\n\ndef extend_request_arguments(request, match, parse_function):\n arguments = match.groupdict()\n for name, value in arguments.iteritems():\n if value:\n request.arguments.setdefault(name, []).extend(parse_function(value))\n\n\nclass FileMappingDispatcher(object):\n def __init__(self, module, handler_404=None):\n self.name = module.__name__\n self.handler_404 = handler_404\n app_logger.info('initialized %r', self)\n\n def __call__(self, application, request, logger, **kwargs):\n url_parts = get_rewritten_request_attribute(request, 'path').strip('/').split('/')\n\n if any('.' in part for part in url_parts):\n logger.error('Url part contains \".\" %s', '/'.join(url_parts))\n return self.handle_404(application, request, logger, **kwargs)\n\n page_name = '.'.join(filter(None, url_parts))\n page_module_name = '.'.join(filter(None, (self.name, page_name)))\n logger.debug('page module: %s', page_module_name)\n\n try:\n page_module = importlib.import_module(page_module_name)\n logger.debug('using %s from %s', page_module_name, page_module.__file__)\n except ImportError:\n logger.warning('%s module not found', (self.name, page_module_name))\n return self.handle_404(application, request, logger, **kwargs)\n except:\n logger.exception('error while importing %s module', page_module_name)\n return ErrorHandler(application, request, logger, status_code=500, **kwargs)\n\n if not hasattr(page_module, 'Page'):\n logger.error('%s.Page class not found', page_module_name)\n return self.handle_404(application, request, logger, **kwargs)\n\n return page_module.Page(application, request, logger, **kwargs)\n\n def __repr__(self):\n return '{}.{}(<{}, handler_404={}>)'.format(__package__, self.__class__.__name__, self.name, self.handler_404)\n\n def handle_404(self, application, request, logger, **kwargs):\n if self.handler_404 is not None:\n return self.handler_404(application, request, logger, **kwargs)\n return ErrorHandler(application, request, logger, status_code=404, **kwargs)\n\n\nclass RegexpDispatcher(object):\n def __init__(self, app_list, name='RegexpDispatcher'):\n self.name = name\n\n def parse_conf(pattern, app, parse=lambda x: [x]):\n if hasattr(app, 'initialize_app'):\n app.initialize_app()\n return re.compile(pattern), app, parse\n\n self.apps = [parse_conf(*app_conf) for app_conf in app_list]\n app_logger.info('initialized %r', self)\n\n def __call__(self, application, request, logger, **kwargs):\n relative_url = get_rewritten_request_attribute(request, 'uri')\n logger.info('requested url: %s (%s)', relative_url, request.uri)\n\n for pattern, app, parse in self.apps:\n match = pattern.match(relative_url)\n if match:\n logger.debug('using %r', app)\n extend_request_arguments(request, match, parse)\n try:\n return app(application, request, logger, **kwargs)\n except tornado.web.HTTPError as e:\n logger.exception('tornado error: %s in %r', e, app)\n return ErrorHandler(application, request, logger, status_code=e.status_code, **kwargs)\n except Exception as e:\n logger.exception('error handling request: %s in %r', e, app)\n return ErrorHandler(application, request, logger, status_code=500, **kwargs)\n\n logger.error('match for request url \"%s\" not found', request.uri)\n return ErrorHandler(application, request, logger, status_code=404, **kwargs)\n\n def __repr__(self):\n return '{}.{}(<{} routes>)'.format(__package__, self.__class__.__name__, len(self.apps))\n\n\ndef app_dispatcher(tornado_app, request, **kwargs):\n request_id = request.headers.get('X-Request-Id', str(global_stats.next_request_id()))\n request_logger = frontik_logging.RequestLogger(request, request_id)\n\n def add_leading_slash(value):\n return value if value.startswith('/') else '/' + value\n\n app_root_url_len = len(options.app_root_url)\n set_rewritten_request_attribute(request, 'uri', add_leading_slash(request.uri[app_root_url_len:]))\n set_rewritten_request_attribute(request, 'path', add_leading_slash(request.path[app_root_url_len:]))\n\n return tornado_app.dispatcher(tornado_app, request, request_logger, request_id=request_id, **kwargs)\n\n\nclass FrontikApplication(tornado.web.Application):\n class DefaultConfig(object):\n pass\n\n def __init__(self, **settings):\n tornado_settings = settings.get('tornado_settings')\n\n if tornado_settings is None:\n tornado_settings = {}\n\n super(FrontikApplication, self).__init__([\n (r'/version/?', VersionHandler),\n (r'/status/?', StatusHandler),\n (r'/types_count/?', CountTypesHandler),\n (r'/pdb/?', PdbHandler),\n (r'{}.*'.format(settings.get('app_root_url')), app_dispatcher),\n ], **tornado_settings)\n\n self.config = self.application_config()\n self.app = settings.get('app')\n self.xml = frontik.producers.xml_producer.ApplicationXMLGlobals(self.config)\n self.json = frontik.producers.json_producer.ApplicationJsonGlobals(self.config)\n self.curl_http_client = tornado.curl_httpclient.CurlAsyncHTTPClient(max_clients=200)\n self.dispatcher = RegexpDispatcher(self.application_urls(), self.app)\n self.sentry_client = self._build_sentry_client(settings)\n\n def _build_sentry_client(self, settings):\n dsn = settings.get('sentry_dsn')\n if not dsn:\n return\n if not frontik.sentry.has_raven:\n app_logger.warning('sentry_dsn set but raven not avalaible')\n return\n return frontik.sentry.AsyncSentryClient(dsn=dsn, http_client=self.curl_http_client)\n\n def application_urls(self):\n return [\n ('', FileMappingDispatcher(importlib.import_module('{}.pages'.format(self.app))))\n ]\n\n def application_config(self):\n return FrontikApplication.DefaultConfig()\n\n def application_version_xml(self):\n version = etree.Element('version')\n version.text = 'unknown'\n return [version]\n\n# Temporary for backward compatibility\nApp = FrontikApplication\n","sub_path":"frontik/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"362517733","text":"from typing import Any, Callable, Dict, Iterable, Optional\n\nimport prefect\nfrom prefect.client import Client\nfrom prefect.core import Flow, Task\nfrom prefect.engine.cloud import CloudTaskRunner\nfrom prefect.engine.cloud.utilities import prepare_state_for_cloud\nfrom prefect.engine.flow_runner import FlowRunner, FlowRunnerInitializeResult\nfrom prefect.engine.runner import ENDRUN\nfrom prefect.engine.state import Failed, State\nfrom prefect.utilities.graphql import with_args\n\n\nclass CloudFlowRunner(FlowRunner):\n \"\"\"\n FlowRunners handle the execution of Flows and determine the State of a Flow\n before, during and after the Flow is run.\n\n In particular, through the FlowRunner you can specify which tasks should be\n the first tasks to run, which tasks should be returned after the Flow is finished,\n and what states each task should be initialized with.\n\n Args:\n - flow (Flow): the `Flow` to be run\n - state_handlers (Iterable[Callable], optional): A list of state change handlers\n that will be called whenever the flow changes state, providing an\n opportunity to inspect or modify the new state. The handler\n will be passed the flow runner instance, the old (prior) state, and the new\n (current) state, with the following signature:\n\n ```\n state_handler(\n flow_runner: FlowRunner,\n old_state: State,\n new_state: State) -> State\n ```\n\n If multiple functions are passed, then the `new_state` argument will be the\n result of the previous handler.\n\n Note: new FlowRunners are initialized within the call to `Flow.run()` and in general,\n this is the endpoint through which FlowRunners will be interacted with most frequently.\n\n Example:\n ```python\n @task\n def say_hello():\n print('hello')\n\n with Flow(\"My Flow\") as f:\n say_hello()\n\n fr = FlowRunner(flow=f)\n flow_state = fr.run()\n ```\n \"\"\"\n\n def __init__(self, flow: Flow, state_handlers: Iterable[Callable] = None) -> None:\n self.client = Client()\n super().__init__(\n flow=flow, task_runner_cls=CloudTaskRunner, state_handlers=state_handlers\n )\n\n def _heartbeat(self) -> bool:\n try:\n # use empty string for testing purposes\n flow_run_id = prefect.context.get(\"flow_run_id\", \"\") # type: str\n self.heartbeat_cmd = [\"prefect\", \"heartbeat\", \"flow-run\", \"-i\", flow_run_id]\n\n query = {\n \"query\": {\n with_args(\"flow_run_by_pk\", {\"id\": flow_run_id}): {\n \"flow\": {\"settings\": True},\n }\n }\n }\n flow_run = self.client.graphql(query).data.flow_run_by_pk\n if flow_run.flow.settings.get(\"disable_heartbeat\"):\n return False\n return True\n except Exception as exc:\n self.logger.exception(\n \"Heartbeat failed for Flow '{}'\".format(self.flow.name)\n )\n return False\n\n def call_runner_target_handlers(self, old_state: State, new_state: State) -> State:\n \"\"\"\n A special state handler that the FlowRunner uses to call its flow's state handlers.\n This method is called as part of the base Runner's `handle_state_change()` method.\n\n Args:\n - old_state (State): the old (previous) state\n - new_state (State): the new (current) state\n\n Returns:\n - State: the new state\n \"\"\"\n raise_on_exception = prefect.context.get(\"raise_on_exception\", False)\n\n try:\n new_state = super().call_runner_target_handlers(\n old_state=old_state, new_state=new_state\n )\n except Exception as exc:\n msg = \"Exception raised while calling state handlers: {}\".format(repr(exc))\n self.logger.debug(msg)\n if raise_on_exception:\n raise exc\n new_state = Failed(msg, result=exc)\n\n flow_run_id = prefect.context.get(\"flow_run_id\", None)\n version = prefect.context.get(\"flow_run_version\")\n\n try:\n cloud_state = prepare_state_for_cloud(new_state)\n self.client.set_flow_run_state(\n flow_run_id=flow_run_id, version=version, state=cloud_state\n )\n except Exception as exc:\n self.logger.debug(\n \"Failed to set flow state with error: {}\".format(repr(exc))\n )\n raise ENDRUN(state=new_state)\n\n prefect.context.update(flow_run_version=version + 1)\n\n return new_state\n\n def initialize_run( # type: ignore\n self,\n state: Optional[State],\n task_states: Dict[Task, State],\n context: Dict[str, Any],\n task_contexts: Dict[Task, Dict[str, Any]],\n parameters: Dict[str, Any],\n ) -> FlowRunnerInitializeResult:\n \"\"\"\n Initializes the Task run by initializing state and context appropriately.\n\n If the provided state is a Submitted state, the state it wraps is extracted.\n\n Args:\n - state (Optional[State]): the initial state of the run\n - task_states (Dict[Task, State]): a dictionary of any initial task states\n - context (Dict[str, Any], optional): prefect.Context to use for execution\n to use for each Task run\n - task_contexts (Dict[Task, Dict[str, Any]], optional): contexts that will be provided to each task\n - parameters(dict): the parameter values for the run\n\n Returns:\n - NamedTuple: a tuple of initialized objects:\n `(state, task_states, context, task_contexts)`\n \"\"\"\n\n # load id from context\n flow_run_id = prefect.context.get(\"flow_run_id\")\n\n try:\n flow_run_info = self.client.get_flow_run_info(flow_run_id)\n except Exception as exc:\n self.logger.debug(\n \"Failed to retrieve flow state with error: {}\".format(repr(exc))\n )\n if state is None:\n state = Failed(\n message=\"Could not retrieve state from Prefect Cloud\", result=exc\n )\n raise ENDRUN(state=state)\n\n updated_context = context or {}\n updated_context.update(flow_run_info.context or {})\n updated_context.update(\n flow_id=flow_run_info.flow_id,\n flow_run_id=flow_run_info.id,\n flow_run_version=flow_run_info.version,\n flow_run_name=flow_run_info.name,\n scheduled_start_time=flow_run_info.scheduled_start_time,\n )\n\n tasks = {t.slug: t for t in self.flow.tasks}\n # update task states and contexts\n for task_run in flow_run_info.task_runs:\n task = tasks[task_run.task_slug]\n task_states.setdefault(task, task_run.state)\n task_contexts.setdefault(task, {}).update(\n task_id=task_run.task_id,\n task_run_id=task_run.id,\n task_run_version=task_run.version,\n )\n\n # if state is set, keep it; otherwise load from Cloud\n state = state or flow_run_info.state # type: ignore\n\n # update parameters, prioritizing kwarg-provided params\n updated_parameters = flow_run_info.parameters or {} # type: ignore\n updated_parameters.update(parameters)\n\n return super().initialize_run(\n state=state,\n task_states=task_states,\n context=updated_context,\n task_contexts=task_contexts,\n parameters=updated_parameters,\n )\n","sub_path":"src/prefect/engine/cloud/flow_runner.py","file_name":"flow_runner.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"80396514","text":"###############################################################################\n##\n##\tAnanya Kirti @ June 9 2015\n##\tFuzzy C means\n##\n###############################################################################\n## Ananya Kirti\n\n\n# importing all the required components, you may also use scikit for a direct implementation.\nimport copy\nimport math\nimport random\nimport time\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport decimal\nimport numpy\n\n\n#used for randomising U\nglobal MAX\nMAX = 10000.0\n#used for end condition\nglobal Epsilon\nEpsilon = 0.00000001\n\ndef import_data(file):\n\t\"\"\"\n\t This function imports the data into a list form a file name passed as an argument. \n\t The file should only the data seperated by a space.(or change the delimiter as required in split)\n\t\"\"\"\n\tdata = []\n\tf = open(str(file), 'r')\n\tfor line in f:\n\t\tcurrent = line.split()\t#enter your own delimiter like \",\"\n\t\tfor j in range(0,len(current)):\n\t\t\t#current[j] = int(current[j])\n\t\t\tcurrent[j] = current[j]\n\t\tdata.append(current)\n\t#print 'finished importing data'\n\t#print data\n\treturn data\n\n'''\ndef import_data_format_iris(file):\n\t\"\"\" \n\tThis would format the data as required by iris \n\tthe link for the same is http://archive.ics.uci.edu/ml/machine-learning-databases/iris/\n\t\"\"\"\n\tdata = []\n\tcluster_location =[]\n\tf = open(str(file), 'r')\n\tfor line in f:\n\t\tcurrent = line.split(\",\")\n\t\tcurrent_dummy = []\n\t\tfor j in range(0,len(current)-1):\n\t\t\tcurrent_dummy.append(float(current[j]))\n\t\tj+=1 \n\t\t#print current[j]\n\t\tif current[j] == \"Iris-setosa\\n\":\n\t\t\tcluster_location.append(0)\n\t\telif current[j] == \"Iris-versicolor\\n\":\n\t\t\tcluster_location.append(1)\n\t\telse:\n\t\t\tcluster_location.append(2)\n\t\tdata.append(current_dummy)\n\t#print \"finished importing data\"\n\treturn data , cluster_location\n'''\n\ndef randomise_data(data):\n\t\"\"\"\n\tThis function randomises the data, and also keeps record of the order of randomisation.\n\t\"\"\"\n\torder = range(0,len(data))\n\trandom.shuffle(order)\n\tnew_data = [[] for i in range(0,len(data))]\n\tfor index in range(0,len(order)):\n\t\tnew_data[index] = data[order[index]]\n\treturn new_data, order\n\ndef de_randomise_data(data, order):\n\t\"\"\"\n\tThis function would return the original order of the data, pass the order list returned in randomise_data() as an argument\n\t\"\"\"\n\tnew_data = [[]for i in range(0,len(data))]\n\tfor index in range(len(order)):\n\t\tnew_data[order[index]] = data[index]\n\treturn new_data\n\ndef print_matrix(list):\n\t\"\"\" \n\tPrints the matrix in a more reqdable way\n\t\"\"\"\n\tfor i in range(0,len(list)):\n\t\tprint (list[i])\n\ndef end_conditon(U,U_old):\n\t\"\"\"\n\tThis is the end conditions, it happens when the U matrix stops chaning too much with successive iterations.\n\t\"\"\"\n\tglobal Epsilon\n\tfor i in range(0,len(U)):\n\t\tfor j in range(0,len(U[0])):\n\t\t\tif abs(U[i][j] - U_old[i][j]) > Epsilon :\n\t\t\t\treturn False\n\treturn True\n\ndef initialise_U(data, cluster_number):\n\t\"\"\"\n\tThis function would randomise U such that the rows add up to 1. it requires a global MAX.\n\t\"\"\"\n\tglobal MAX\n\tU = []\n\tfor i in range(0,len(data)):\n\t\tcurrent = []\n\t\trand_sum = 0.0\n\t\tfor j in range(0,cluster_number):\n\t\t\tdummy = random.randint(1,int(MAX))\n\t\t\tcurrent.append(dummy)\n\t\t\trand_sum += dummy\n\t\tfor j in range(0,cluster_number):\n\t\t\tcurrent[j] = current[j] / rand_sum\n\t\tU.append(current)\n\treturn U\n\ndef distance(point, center):\n\t\"\"\"\n\tThis function calculates the distance between 2 points (taken as a list). We are refering to Eucledian Distance.\n\t\"\"\"\n\tif len(point) != len(center):\n\t\treturn -1\n\tdummy = 0.0\n\tfor i in range(0,len(point)):\n\t\tdummy += abs(float(point[i]) - float(center[i])) ** 2\n\treturn math.sqrt(dummy)\n\ndef normalise_U(U):\n\t\"\"\"\n\tThis de-fuzzifies the U, at the end of the clustering. It would assume that the point is a member of the cluster whose membership is maximum.\n\t\"\"\"\n\tfor i in range(0,len(U)):\n\t\tmaximum = max(U[i])\n\t\tfor j in range(0,len(U[0])):\n\t\t\tif U[i][j] != maximum:\n\t\t\t\tU[i][j] = 0\n\t\t\telse:\n\t\t\t\tU[i][j] = 1\n\treturn U\n\n\ndef fuzzy(data, cluster_number, m = 2):\n\t\"\"\"\n\tThis is the main function, it would calculate the required center, and return the final normalised membership matrix U.\n\tIt's paramaters are the : cluster number and the fuzzifier \"m\".\n\t\"\"\"\n\t## initialise the U matrix:\n\tU = initialise_U(data, cluster_number)\n\t#initilise the loop\n\twhile (True):\n\t\t#create a copy of it, to check the end conditions\n\t\tU_old = copy.deepcopy(U)\n\t\t# cluster center vector\n\t\tC = []\n\t\tfor j in range(0,cluster_number):\n\t\t\tcurrent_cluster_center = []\n\t\t\tfor i in range(0,len(data[0])): #this is the number of dimensions\n\t\t\t\tdummy_sum_num = 0.0\n\t\t\t\tdummy_sum_dum = 0.0\n\t\t\t\tfor k in range(0,len(data)):\n\t\t\t\t\tdummy_sum_num += (float(U[k][j]) ** m) * float(data[k][i])\n\t\t\t\t\tdummy_sum_dum += (float(U[k][j]) ** m)\n\t\t\t\t\tif dummy_sum_dum == 0:\n\t\t\t\t\t\tdummy_sum_dum = 0.00000000001\n\t\t\t\tcurrent_cluster_center.append(dummy_sum_num/dummy_sum_dum)\n\t\t\tC.append(current_cluster_center)\n\n\t\t#creating a distance vector, useful in calculating the U matrix.\n\n\t\tdistance_matrix =[]\n\t\tfor i in range(0,len(data)):\n\t\t\tcurrent = []\n\t\t\tfor j in range(0,cluster_number):\n\t\t\t\tcurrent.append(distance(data[i], C[j]))\n\t\t\tdistance_matrix.append(current)\n\n\t\t# update U vector\n\t\tfor j in range(0, cluster_number):\t\n\t\t\tfor i in range(0, len(data)):\n\t\t\t\tdummy = 0.0\n\t\t\t\tfor k in range(0,cluster_number):\n\t\t\t\t\tnumerator = distance_matrix[i][j]\n\t\t\t\t\tdenominator = distance_matrix[i][k]\n\t\t\t\t\tif denominator == 0:\n\t\t\t\t\t\tresult = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tresult = numerator/denominator\n\t\t\t\t\t#dummy += (distance_matrix[i][j]/distance_matrix[i][k]) ** (2/(m-1))\n\t\t\t\t\tdummy += (result) ** (2/(m-1))\n\n\t\t\t\tif dummy == 0:\n\t\t\t\t\tU[i][j] = 0\n\t\t\t\telse:\n\t\t\t\t\tU[i][j] = 1 / dummy\n\n\n\t\tif end_conditon(U,U_old):\n\t\t\t#print \"finished clustering\"\n\t\t\tbreak\n\t#U = normalise_U(U)\n\treturn U\n\n## main \nif __name__ == '__main__':\n\t\n\t# import the data\n\n\tdata = import_data(str(sys.argv[1]))\n\t#data, cluster_location = import_data_format_iris(\"iris.txt\")\n\t#print_matrix(data)\n\t#data , order = randomise_data(data)\n\t#print_matrix(data)\n\n\tstart = time.time()\n\t# now we have the data in a list called data, this is only number\n\t# call the fuzzy - c means function\n\tfinal_location = fuzzy(data , 2 , 2)\n\t#final_location = de_randomise_data(final_location, order)\n\t#print_matrix(final_location)\n\t\n\t#print \"time elapsed=\", time.time() - start","sub_path":"fuzzy_c.py","file_name":"fuzzy_c.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"377602532","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 21 22:16:52 2020\n\n@author: user\n\"\"\"\n\n\n\nimport pandas as pd\n\n\ndef create_rating():\n\n rating = pd.read_csv('movielens/order/u.data', sep='\\t', header=None)\n rating.columns = ['userId','movieId','rating','timestamp']\n idx1 = [i-1 for i in rating['userId']] # userId 를 0부터 시작하게 함.\n idx2 = [i-1 for i in rating['movieId']] # movieId 를 0부터 시작하게 함.\n rating['userId'] = idx1\n rating['movieId'] = idx2\n\n return rating\n\ndef create_rating_1M():\n rating = pd.read_csv('movielens/1M/ratings.dat', sep='::', header=None)\n rating.columns = ['userId','movieId','rating','timestamp']\n idx1 = [i-1 for i in rating['userId']] # userId 를 0부터 시작하게 함.\n idx2 = [i-1 for i in rating['movieId']] # movieId 를 0부터 시작하게 함.\n rating['userId'] = idx1\n rating['movieId'] = idx2\n return rating\n\n\n# change user rating matrix to dictionary\ndef create_rating_dic():\n\n rating = create_rating()\n rd = {}\n users = set(rating['userId'])\n for i in users: \n tmp = rating[rating['userId']==i]\n rd[i] = {a:b for a,b in zip(tmp['movieId'],tmp['rating'])}\n\n return rd\n\ndef create_rating_dic_1M():\n\n rating = create_rating_1M()\n rd = {}\n users = set(rating['userId'])\n for i in users: \n rd[i] = {}\n tmp = rating[rating['userId']==i]\n \n rd[i] = {a:b for a,b in zip(tmp['movieId'],tmp['rating'])}\n \n return rd\n\n##############################################################################\n\ndef create_rating_netflix():\n\n rating = pd.read_csv(r'C:\\Users\\user\\Documents\\CF\\netflix\\movie_ratings\\ratings.csv')\n rating.columns = ['userId','movieId','rating','timestamp']\n idx1 = [i-1 for i in rating['userId']] # userId 를 0부터 시작하게 함.\n idx2 = [i-1 for i in rating['movieId']] # movieId 를 0부터 시작하게 함.\n rating['userId'] = idx1\n rating['movieId'] = idx2\n\n return rating\n\n\n\n# change user rating matrix to dictionary\ndef create_rating_dic_netflix():\n\n rating = create_rating_netflix()\n rd = {}\n users = set(rating['userId'])\n for i in users: \n tmp = rating[rating['userId']==i]\n rd[i] = {a:b for a,b in zip(tmp['movieId'],tmp['rating'])}\n\n return rd\n\n\n##############################################################################\n\n# item genre data load\ndef create_genre():\n \n genre = pd.read_csv('movielens/order/genre.txt', sep='|') \n genre.columns = ['genre','g_index']\n return genre\n\n\n\n# item information data load\ndef create_item():\n \n item = pd.read_csv('movielens/order/item.txt', sep='|') \n item.iloc[0:2,:]\n c = ['movie id', 'movie title', 'release date', 'video release date',\n 'IMDb URL', 'unknown', 'Action' ,'Adventure ' ,'Animation',\n '''Children's''', 'Comedy', 'Crime' ,'Documentary' ,'Drama','Fantasy',\n 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi',\n 'Thriller', 'War', 'Western']\n item.columns = c\n item = pd.concat([item[['movie id','movie title']],item.loc[:,'unknown':'Western']], axis=1)\n return item\n\n","sub_path":"load_data/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"541624217","text":"def nextGreaterElements(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n \n def greaterElemsFromLeft(A):\n val = A[0]\n out= [-2**31]\n for i in range(1,len(A)):\n if A[i] < val:\n out.append(val)\n if A[i] >= val:\n out.append(-2**31)\n val = A[i]\n\n return out\n\n def leftGreater(A):\n lt = []\n rt = []\n\n for i in range(len(A)):\n while lt and A[i] >= lt[-1]:\n lt.pop()\n if lt:\n rt.append(lt[-1])\n else:\n rt.append(-2**31)\n lt.append(A[i])\n return rt\n\n def rightGreater(A):\n lt = []\n rt = []\n\n for i in range(len(A)-1,-1,-1):\n while lt and A[i] >= lt[-1]:\n lt.pop()\n if lt:\n rt.append(lt[-1])\n else:\n rt.append(-2**31)\n lt.append(A[i])\n return rt[::-1]\n\n left = leftGreater(nums)\n right = rightGreater(nums)\n leftMost = greaterElemsFromLeft(nums)\n # leftMost = leftGreater(nums[::-1])[::-1]\n\n print(nums)\n # print(left)\n # print(right)\n print(leftMost)\n\n out = []\n for i in range(len(left)):\n v1 = right[i]\n if v1 == -2**31:\n v1 = leftMost[i]\n v2 = left[i]\n if v2 == -2**31:\n v2 = right[i]\n val = max(v1,v2)\n if val == -2**31:\n val = -1\n out.append(val)\n return out\n\nA = [1,2,3,2,1]\n\nprint(nextGreaterElements(A))","sub_path":"Array/next-greater-elements.py","file_name":"next-greater-elements.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"553412225","text":"from nose import with_setup\nimport os\n\nfrom cing.constants import definitions as cdefs\nfrom cing import constants\nfrom cing.core import classes\nfrom cing.core import molecule\nfrom cing.Libs import io\nfrom cing.core import validation\nfrom cing.core import Project\n\ntheProject = None\n\nTEST = 'test'\n\ndef setup_DummyProject():\n global theProject\n os.chdir(cdefs.cingDefinitions.tmpdir)\n print('Now in %s' % cdefs.cingDefinitions.tmpdir)\n theProject = Project.new(TEST)\n # create a molecule\n mol = molecule.Molecule(TEST)\n theProject.appendMolecule(mol)\n c = mol.addChain('A')\n c.addResidue('ALA', 1, Nterminal = True)\n c.addResidue('VAL', 2)\n c.addResidue('PHE', 3)\n c.addResidue('ARG', 4)\n c.addResidue('GLU', 5, Cterminal = True)\n c = mol.addChain('B')\n c.addResidue('DG', 1, Nterminal = True)\n c.addResidue('DA', 2)\n c.addResidue('DT', 3)\n c.addResidue('DC', 4, Cterminal = True)\n c = mol.addChain('C')\n c.addResidue('RGUA', 1, convention=constants.INTERNAL_0, Nterminal = True)\n c.addResidue('RADE', 2, convention=constants.INTERNAL_0)\n c.addResidue('URA', 3, convention=constants.INTERNAL_0) # not RTHY normally of course.\n c.addResidue('RTHY', 4, convention=constants.INTERNAL_0)\n c.addResidue('RCYT', 5, convention=constants.INTERNAL_0, Cterminal = True)\n c = mol.addChain('D')\n for i in range(1,11):\n c.addResidue('HOH', i )\n # end for\n c = mol.addChain('E') # Unknown residue to CING\n c.addResidue('ACE', 1)\n c = mol.addChain('F') # Ions are also other\n c.addResidue('CA2P', 1)\n for residue in mol.allResidues():\n residue.addAllAtoms()\n # end for\n mol.updateAll()\n io.message('{0}\\n',mol.format())\n\n\ndef teardown_project():\n global theProject\n if theProject is not None:\n theProject.close(save=False)\n\n\ndef test_projectNotPresent():\n print('Forced error:')\n theProject = Project.open('notPresent',Project.PROJECT_OLD)\n assert theProject is None\n\n\ndef test_rootPath():\n root,name,ext = classes.Project.rootPath('test')\n assert root == 'test.cing'\n assert name == 'test'\n root,name,ext = classes.Project.rootPath('test.cing')\n assert root == 'test.cing'\n assert name == 'test'\n root,name,ext = classes.Project.rootPath('test.cing/project.json')\n assert root == 'test.cing'\n assert name == 'test'\n assert ext == '.json'\n root,name, ext = classes.Project.rootPath('test.tgz')\n assert root == 'test.cing'\n assert name == 'test'\n assert ext == '.tgz'\n\n\n@with_setup(setup_DummyProject,teardown_project)\ndef test_openSaveProject():\n assert theProject is not None\n theProject.created = io.Time(10.0) # silly date\n # this will test the save routines\n assert theProject.save() == False\n # this will test the restore routines\n p = Project.open(TEST,constants.PROJECT_OLD)\n assert p is not None\n assert p.created == 10.0\n\n\n@with_setup(setup_DummyProject,teardown_project)\ndef test_pluginRoutines():\n assert theProject is not None\n status = theProject.getStatusDict(TEST)\n assert status is not None\n\n vobj = validation.ValidationResult()\n vobj.value = 10\n theProject.validationData.setResult(theProject.molecule,TEST,vobj)\n result = theProject.validationData.save('test.json')\n assert result == False\n\n theProject.validationData.clear()\n vobj = validation.getResult(theProject.molecule,TEST)\n assert vobj is None\n\n result = theProject.validationData.restore('test.json')\n assert result == False\n vobj = theProject.validationData.getResult(theProject.molecule,TEST)\n assert vobj is not None\n assert vobj.value == 10\n\n\n","sub_path":"cing/python/cing/nosetests/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167408573","text":"def escreverArquivo(texto):\n arquivo = open('novoArquivo.txt', 'w')\n arquivo.write(texto)\n arquivo.close()\n\ndef atualizarArquivo(texto):\n arquivo = open('novoArquivo.txt', 'w')\n arquivo.write(texto)\n arquivo.close()\n\ndef lerArquivo(nomeArquivo):\n arquivo = open(nomeArquivo, 'r')\n texto = arquivo.read()\n print(texto)\n\n\nif __name__ == '__main__':\n escreverArquivo(\"Esse é o nosso primeiro arquivo\")\n lerArquivo('novoArquivo.txt')\n atualizarArquivo(\"\\nAtualizando o arquivo!\")\n lerArquivo('novoArquivo.txt')","sub_path":"3. cursoPython/Arquivos/gerarArquivo.py","file_name":"gerarArquivo.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581669990","text":"from discord.ext import commands\nimport os\nimport traceback\n\nbot = commands.Bot(command_prefix='')\ntoken = os.environ['DISCORD_BOT_TOKEN']\n\n@bot.command(neme='ひよこ')\nasync def ひよこ(ctx):\n await ctx.send('ぴよよ~')\n\n@bot.command(name='疲れた')\nasync def 疲れた(ctx):\n await ctx.send('ぴよ?????')\n \n@bot.command(name='よりくん')\nasync def よりくん(ctx):\n await ctx.send('ぴよっ💓')\n \n@bot.command(name='@ひよこまる')\nasync def ひよこまる(ctx):\n await ctx.send('ぴよよ🐥') \n\n@bot.command(name=os.environ['DISCORD_BOT_ID'])\nasync def name(ctx):\n await ctx.channel.send('ぴよよ🐥')\n \n@bot.command(name=os.environ['DISCORD_BOT_ID_PHONE'])\nasync def name(ctx):\n await ctx.channel.send('ぴよよ🐥')\n \n\nbot.run(token)\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"618511123","text":"#\n# CNN卷积神经网络的方法函数\n#\nimport tensorflow as tf\n\n\nclass Net:\n\n # 定义权值矩阵\n # shape: [img.width, img.height, in_img.chanel, out_img.chanel]\n @staticmethod\n def weight_variable(layer_name, shape):\n with tf.name_scope('Weight'):\n # truncated_normal 从截断的正态分布中输出随机值\n # stddev 标准差\n w = tf.Variable(tf.truncated_normal(shape, stddev=0.1), name='W')\n tf.summary.histogram(layer_name + '/Weight', w)\n return w\n\n # 定义偏差矩阵\n # shape: [in_img.chanel, out_img.chanel]\n @staticmethod\n def biases_variable(layer_name, shape):\n with tf.name_scope('biases'):\n b = tf.Variable(tf.constant(0.1, shape=shape), name='b')\n tf.summary.histogram(layer_name + '/biases', b)\n return b\n\n\nclass Convention(Net):\n\n no = 0\n\n def __init__(self, dictionary):\n self.layer_name = Convention.get_layer_name()\n self.inputs = dictionary['inputs']\n self.w_shape = dictionary['w_shape']\n self.b_shape = dictionary['b_shape']\n self.x_move = dictionary['x_move']\n self.y_move = dictionary['y_move']\n self.active = dictionary['active']\n self.padding = dictionary['padding']\n self.outputs = self.convention_compute()\n\n # 本网络层的名称\n @classmethod\n def get_layer_name(cls):\n cls.no += 1\n return 'convention_%s' % cls.no\n\n # 计算卷积结果\n # inputs: 输入的图片矩阵\n # Weight: 卷积层的权值矩阵\n # biases: 卷积层的偏差矩阵\n # x_move: 横向步长\n # y_move: 纵向步长\n def convention_compute(self):\n with tf.name_scope(self.layer_name):\n weight = self.weight_variable(self.layer_name, self.w_shape)\n biases = self.biases_variable(self.layer_name, self.b_shape)\n with tf.name_scope('convention_compute'):\n # stride [1, x_movement, y_movement, 1]\n op_conv = tf.nn.conv2d(self.inputs, weight, strides=[1, self.x_move, self.y_move, 1],\n padding=self.padding, name='conv')\n op_add = tf.add(op_conv, biases, name='add')\n if self.active is None:\n outputs = op_add\n else:\n outputs = self.active(op_add, name='active')\n tf.summary.histogram(self.layer_name + '/outputs', outputs)\n return outputs\n\n\nclass MaxPool:\n\n no = 0\n\n def __init__(self, dictionary):\n self.layer_name = MaxPool.get_layer_name()\n self.inputs = dictionary['inputs']\n self.x_size = dictionary['x_size']\n self.y_size = dictionary['y_size']\n self.x_move = dictionary['x_move']\n self.y_move = dictionary['y_move']\n self.outputs = self.max_pool_compute()\n\n # 本网络层的名称\n @classmethod\n def get_layer_name(cls):\n cls.no += 1\n return 'max_pool_%s' % cls.no\n\n def max_pool_compute(self):\n with tf.name_scope(self.layer_name):\n outputs = tf.nn.max_pool(self.inputs, ksize=[1, self.x_size, self.y_size, 1],\n strides=[1, self.x_move, self.y_move, 1], padding='SAME', name='max_pool')\n tf.summary.histogram(self.layer_name + '/outputs', outputs)\n return outputs\n\n\nclass FullConnection(Net):\n\n no = 0\n\n def __init__(self, dictionary):\n # inputs, w_shape, b_shape, active, dropout, rate\n self.layer_name = FullConnection.get_layer_name()\n self.inputs = dictionary['inputs']\n self.w_shape = dictionary['w_shape']\n self.b_shape = dictionary['b_shape']\n if 'active' in dictionary:\n self.active = dictionary['active']\n else:\n self.active = None\n if 'dropout' in dictionary:\n self.dropout = dictionary['dropout']\n self.rate = dictionary['rate']\n else:\n self.dropout = None\n if 'sort' in dictionary:\n self.sort = dictionary['sort']\n else:\n self.sort = None\n self.outputs = self.full_compute()\n\n # 本网络层的名称\n @classmethod\n def get_layer_name(cls):\n cls.no += 1\n return 'full_connection_%s' % cls.no\n\n def full_compute(self):\n with tf.name_scope(self.layer_name):\n weight = self.weight_variable(self.layer_name, self.w_shape)\n biases = self.biases_variable(self.layer_name, self.b_shape)\n with tf.name_scope('preprocessing'):\n if len(self.inputs.shape) == 4:\n inputs = tf.reshape(self.inputs, [-1, self.w_shape[0]])\n else:\n inputs = self.inputs\n with tf.name_scope('full_compute'):\n op_mul = tf.matmul(inputs, weight)\n op_add = tf.add(op_mul, biases)\n if self.active is None:\n activation = op_add\n else:\n activation = self.active(op_add, name='active',)\n if self.dropout is None:\n dropout = activation\n else:\n dropout = self.dropout(activation, rate=self.rate, name='dropout',)\n if self.sort is None:\n outputs = dropout\n else:\n outputs = self.sort(dropout, name='sort',)\n tf.summary.histogram(self.layer_name + '/outputs', outputs)\n return outputs\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300820823","text":"from newsapi import NewsApiClient\n\n# Init\nnewsapi = NewsApiClient(api_key='0f58067ab2ad447ba8e4af81ecea25c5')\n\n# /v2/top-headlines\nnews = newsapi.get_everything(q='NVDA',language='en',sort_by='relevancy')\n#top_headlines = top_headlines['articles']\nif news['totalResults'] > 0 and news['status'] == 'ok':\n article = news['articles'][0]\n for i in article:\n print(i)\nelse:\n print(\"Couldn't find any news\")\n","sub_path":"Isolated Graph Stuff/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"468172420","text":"s = input()\n\ni = list(s)\n\nanswer = []\n\nfor num in i:\n if num == '0':\n answer.append(num)\n elif num == '1':\n answer.append(num)\n else:\n if answer == []:\n continue\n else:\n answer.pop()\n\nfor num in answer:\n print(num,end='')","sub_path":"Python_codes/p04030/s117582433.py","file_name":"s117582433.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"59119804","text":"import tkinter as tk\nfrom tkinter import font\nimport requests\n\nHEIGHT, WIDTH = 600, 600\n\ndef get_weather(city):\n\tweather_key = 'fdedc2e67c81b314b738019072d4568f'\n\turl = 'https://api.openweathermap.org/data/2.5/weather'\n\tparams = {\"APPID\": weather_key, 'q':city, 'units': 'metric'}\n\tresponse = requests.get(url, params=params)\n\tweather = response.json()\n\n\tlabel['text'] = format_response(weather)\n\ndef format_response(weather):\n\t\t\n\ttry:\t\n\t\tname = weather['name']\n\t\tdescription = weather['weather'][0]['description']\n\t\ttemp = weather['main']['temp']\n\t\tfeels_like = weather['main']['feels_like']\n\t\thumidity = weather['main']['humidity']\n\t\ttemp_min = weather['main']['temp_min']\n\t\ttemp_max = weather['main']['temp_max']\n\t\t# longitude = weather['coord']['lon']\n\t\t# latitude = weather['coord']['lat']\n\n\t\tresult = \"City: %s \\nConditions: %s \\nTemperature (°C): %s \\nFeels like (°C): %s \\nHumidity: %s \\nMaximum Temp (°C): %s \\nMinimum Temp (°C): %s \" % (name, description, temp, feels_like, humidity, temp_max, temp_min)\n\texcept:\n\t\tresult = 'There was a \\nproblem retrieving \\nthat information.'\n\n\treturn result\n\nroot = tk.Tk()\n\ncanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)\ncanvas.pack()\n\nbgd_img = tk.PhotoImage(file='bgd.png')\nbgd_label = tk.Label(root, image=bgd_img)\nbgd_label.place(relwidth=1, relheight=1)\n\nframe = tk.Frame(root, bg='#5B8ED1')\nframe.place(relwidth=0.75, relheight=0.1, relx=0.5, rely=0.1, anchor='n')\n\nentry = tk.Entry(frame, font=('Terminal', 20), bd=3)\nentry.place(relwidth=0.65, relheight=1)\n\nbutton = tk.Button(frame, text=\"Get Weather\", font=('Terminal', 15), command=lambda:get_weather(entry.get()))\nbutton.place(relx=0.7, relwidth=0.3, relheight=1)\n\nlower_frame = tk.Frame(root, bg='#5B8ED1', bd=10)\nlower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')\n\nlabel = tk.Label(lower_frame, font=('Terminal', 16))\nlabel.place(relwidth=1, relheight=1)\n\n\n\nroot.mainloop()","sub_path":"Weather App/weatherapp.py","file_name":"weatherapp.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576482439","text":"class Solution:\n maxWeight = 0\n def canPartition(self, nums: List[int]) -> bool:\n n = len(nums)\n # 递归求解0-1背包\n def dfs(level, weight):\n if level == n or weight == target:\n if weight > self.maxWeight:\n self.maxWeight = weight\n return\n if cache[level][weight]:\n return\n cache[level][weight] = True\n dfs(level + 1, weight)\n if weight + nums[level] <= target:\n dfs(level + 1, weight+nums[level])\n \n sum_nums = sum(nums)\n target = sum_nums // 2\n if target * 2 != sum_nums:\n return False\n cache = [[False]*(target+1) for i in range(len(nums))]\n dfs(0, 0)\n if self.maxWeight == target:\n return True\n else: \n return False\n ","sub_path":"LeetCode/416. 分割等和子集(递归超时).py","file_name":"416. 分割等和子集(递归超时).py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"4081808","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 ('registroCampo', '0003_apiario_numcolmenas'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='apiario',\n name='funcionFK',\n field=models.ForeignKey(default=3, verbose_name=b'Funcion zoot\\xc3\\xa9cnica', to='registroCampo.Funcion'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='registro',\n name='muestras',\n field=models.IntegerField(default=3, verbose_name=b'Total de muestras que se van a capturar'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='apiario',\n name='moviliza',\n field=models.BooleanField(default=True),\n ),\n migrations.AlterField(\n model_name='apiario',\n name='numColmenas',\n field=models.IntegerField(verbose_name=b'N\\xc3\\xbamero de colmenas existentes'),\n ),\n ]\n","sub_path":"apps/registroCampo/migrations/0004_auto_20160107_1538.py","file_name":"0004_auto_20160107_1538.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"227036496","text":"import math\n\ndef get_min_max(my_list):\n '''Finds min and max values of the given list\n\n Parameters:\n -----------\n my_list: list\n List of numbers\n \n Returns:\n --------\n tuple (min, max)\n A tuple contains min and max values\n '''\n min = math.inf\n max = -math.inf\n #Here is where you write your code\n\n #Returns the found values\n return (min, max)\n\ndef get_mean_std(my_list):\n '''Finds mean and standard deviation of the list\n\n Parameters:\n -----------\n my_list: list\n List of numbers\n \n Returns:\n --------\n tuple (mean, std)\n A tuple contains mean and standard deviation values\n '''\n mean = 0\n std = 0\n #Here is where you write your code\n\n #Returns values\n return (mean, std)\n\n#Test \nmy_list = [6, 4, 2, 10, 15, 30, 46, 49]\nmin, max = get_min_max(my_list)\nmean, std = get_mean_std(my_list)\n\nprint (min)\nprint (max)\nprint (mean)\nprint (std)","sub_path":"scripts/01-Intro/exercise01.py","file_name":"exercise01.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"125854396","text":"\"\"\"\n function: move target files to a given directory which less than given number\n author: s1mple_zj\n date: 2019-4-24\n\"\"\"\nimport os, datetime, shutil\n\ndef check_file_latest_edit_date(dirPath, days, desPath):\n# get file's edit day and check the difference to the given number\n files = os.scandir(dirPath)\n for f in files:\n if os.path.isfile(os.path.join(dirPath, f)):\n file_path, filename = os.path.split(os.path.join(dirPath, f))\n file_formatted_edit_date = datetime.datetime.fromtimestamp(\n os.path.getmtime(os.path.join(dirPath, f)))\n current_time = datetime.datetime.today()\n difference = current_time - file_formatted_edit_date\n if difference.days < days:\n print('These files you want to move: ')\n print('Filename: ' + filename)\n print('Life: ' + str(difference.days) + 'days')\n shutil.move(os.path.join(dirPath, filename), os.path.join(\n desPath, filename))\n # os.rename(os.path.join(dirPath, filename), os.path.join(\n # desPath, filename))\n else:\n print('\\n' + filename + ' don\\'t need to move.')\n\nsrc_path = input('Input a source path: ')\ndifference_days = input('Input a day number that files you want to move: ')\ndest_path = input('Input a path you want to move to: ')\ncheck_file_latest_edit_date(src_path, int(difference_days), dest_path)","sub_path":"file operations/check_file_edit_days.py","file_name":"check_file_edit_days.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"442835056","text":"#coding=utf8\nclass Vehicle(object):\n \"\"\"\n 整车数据\n \"\"\"\n\n def __init__(self):\n self.vehicle_status = None # 车辆状态\n self.charge_state = None # 充电状态\n self.run_model = None # 运行模式\n self.speed = None # 车速\n self.accu_mile = None # 累计里程\n self.total_voltage = None # 总电压\n self.total_current = None # 总电流\n self.SOC = None # SOC\n self.DC_DC_status = None # DC-DC状态\n self.gear = None # 档位\n self.IR = None # 绝缘电阻\n self.accel_pedal_travel = None # 加速踏板行程值\n self.brake_pedal_status = None # 制动踏板状态\n\n\nclass DriveMotor(object):\n \"\"\"\n 驱动电机数据:驱动电机总数(N) + 驱动电机序号为1的电机数据 + ... + 驱动电机序号为N的电机数据\n \"\"\"\n\n def __init__(self, total_drive_motor):\n self.total_drive_motor = total_drive_motor # 驱动电机个数\n self.info_list = [] # 驱动电机总成信息列表\n self._init_info_list()\n\n def _init_info_list(self):\n \"\"\"\n 根据实际的<驱动电机个数>来构造实际的<驱动电机总成信息列表>\n \"\"\"\n for _ in range(self.total_drive_motor):\n self.info_list.append(\n dict(DM_serial=None, # 驱动电机序号\n DM_status=None, # 驱动电机状态\n DM_CON_TEMP=None, # 驱动电机控制器温度\n DM_speed=None, # 驱动电机转速\n DM_torque=None, # 驱动电机转矩\n DM_TEMP=None, # 驱动电机温度\n motor_CON_in_V=None, # 电机控制器输入电压\n motor_CON_DC_bus_C=None # 电机控制器直流母线电流\n )\n )\n\n\nclass FuelCell(object):\n \"\"\"\n 燃料电池数据\n \"\"\"\n\n def __init__(self):\n self.voltage = None # 燃料电池电压\n self.current = None # 燃料电池电流\n self.consumption_rate = None # 燃料电池消耗率\n\n self.total_TEMP_probe = None # 燃料电池温度探针总数\n self.probe_TEMP = None # 探针温度值\n\n self.H_sys_max_TEMP = None # 氢系统中最高温度\n self.H_sys_max_TEMP_probe = None # 氢系统中最高温度探针代号\n\n self.H2_max_CONC = None # 氢气最高浓度\n self.H2_max_CONC_sensor = None # 氢气最高浓度传感器代号\n\n self.H2_max_P = None # 氢气最高压力\n self.H2_max_P_sensor = None # 氢气最高压力传感器代号\n\n self.high_P_DC_DC_state = None # 高压DC/DC状态\n\n\nclass Engine(object):\n \"\"\"\n 发动机数据\n \"\"\"\n\n def __init__(self):\n self.engine_state = None # 发动机状态\n self.crankshaft_speed = None # 曲轴转速\n self.fuel_consumption_rate = None # 燃料消耗率\n\n\nclass VehicleLocation(object):\n \"\"\"\n 车辆位置数据\n \"\"\"\n\n def __init__(self):\n self.location_state = None # 定位状态\n self.longitude = None # 经度\n self.latitude = None # 纬度\n\n\nclass Extreme(object):\n \"\"\"\n 极值数据\n \"\"\"\n\n def __init__(self):\n self.max_V_bat_subsys_serial = None # 最高电压电池子系统号\n self.max_V_bat_mer_code = None # 最高电压电池单体代号\n self.max_bat_mer_V = None # 电池单体电压最高值\n\n self.min_V_bat_subsys_serial = None # 最低电压电池子系统号\n self.min_V_bat_mer_code = None # 最低电压电池单体代号\n self.min_bat_mer_V = None # 电池单体电压最低值\n\n self.max_TEMP_subsys_serial = None # 最高温度子系统号\n self.max_TEMP_probe_serial = None # 最高温度探针序号\n self.max_TEMP = None # 最高温度值\n\n self.min_TEMP_subsys_serial = None # 最低温度子系统号\n self.min_TEMP_probe_serial = None # 最低温度探针序号\n self.min_TEMP = None # 最低温度值\n\n\nclass Alarm(object):\n \"\"\"\n 报警数据\n \"\"\"\n\n def __init__(self):\n self.max_level = None # 最高报警等级\n self.general_sign = None # 通用报警标志\n self.total_device_fault = None # 可充电储能装置故障总数N1\n self.total_DM_fault = None # 驱动电机故障总数N2\n self.total_engine_fault = None # 发动机故障总数N3\n self.total_other_fault = None # 其他故障总数N4\n\n\nclass Voltage(object):\n \"\"\"\n 可充电储能系统电压数据:可充电储能子系统个数(N) + 可充电储能子系统号为1的系统数据 + ... + 可充电储能子系统号为N的系统数据\n \"\"\"\n\n def __init__(self, total_subsys):\n self.total_subsys = total_subsys # 可充电储能子系统个数\n self.info_list = [] # 可充电储能子系统电压信息列表\n self._init_info_list()\n\n def _init_info_list(self):\n \"\"\"\n 根据实际的<可充电储能子系统个数>来构造实际的<驱动电机总成信息列表>\n \"\"\"\n for _ in range(self.total_subsys): # 可充电储能子系统号为1~250\n self.info_list.append(\n dict(subsys_serial=None, # 可充电储能子系统号\n voltage=None, # 可充电储能装置电压\n current=None, # 可充电储能装置电流\n total_mer_battery=None, # 单体电池总数\n start_frame_bat_serial=None, # 本帧起始电池序号\n total_frame_mer_bat=None, # 本帧单体电池总数\n mer_bat_voltage=None # 单体电池电压\n )\n )\n\n\nclass Temperature(object):\n \"\"\"\n 可充电储能系统温度数据:可充电储能子系统个数(N) + 可充电储能子系统号为1的系统数据 + ... + 可充电储能子系统号为N的系统数据\n \"\"\"\n\n def __init__(self, total_subsys):\n self.total_subsys = total_subsys # 可充电储能子系统个数\n self.info_list = [] # 可充电储能子系统温度信息列表\n self._init_info_list()\n\n def _init_info_list(self):\n \"\"\"\n 根据实际的<可充电储能子系统个数>来构造实际的<可充电储能子系统温度信息列表>\n \"\"\"\n for _ in range(self.total_subsys): # 可充电储能子系��号为1~250\n self.info_list.append(\n dict(subsys_serial=None, # 可充电储能子系统号\n total_TEMP_probe=None, # 可充电储能温度探针个数\n each_TEMP_probe_detect=None # 可充电储能子系统各温度探针检测到的值\n )\n )\n","sub_path":"vehicle_solution/VRealTime.py","file_name":"VRealTime.py","file_ext":"py","file_size_in_byte":6809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"637492844","text":"# 5\n# /\\\n# 2 6 = 2,5,6\n\ndef iterative(root):\n stack = [root]\n visited = set()\n while stack:\n node = stack.pop()\n if node in visited:\n print(node)\n continue\n visited.add(node)\n if node.right: stack.append(node.right)\n stack.append(node)\n if node.left: stack.append(node.left)\n\n#recursive\ndef recursive(root):\n if root == None:\n return\n recursive(nodes[root].left)\n print(nodes[root].id)\n recursive(nodes[root].right)","sub_path":"src/python3/inOrderTraversal_ascending.py","file_name":"inOrderTraversal_ascending.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190099638","text":"import os, shutil\n\n# 원본 데이터셋을 압축 해제한 디렉터리\noriginal_dataset_dir = './datasets/train'\n\n# 소규모 데이터셋을 저장할 디렉터리\nbase_dir = './datasets/cats_and_dogs_small'\nif os.path.isdir(base_dir) == False:\n os.mkdir(base_dir)\n\n#훈련, 검증, 테스트 분할을 위한 디렉터리\ntrain_dir = os.path.join(base_dir, 'train')\nif os.path.isdir(train_dir) == False:\n os.mkdir(train_dir)\nvalidation_dir = os.path.join(base_dir, 'validation')\nif os.path.isdir(validation_dir) == False:\n os.mkdir(validation_dir)\ntest_dir = os.path.join(base_dir, 'test')\nif os.path.isdir(test_dir) == False:\n os.mkdir(test_dir)\n\n# 훈련용 고양이 사진 디렉터리\ntrain_cats_dir = os.path.join(train_dir, 'cats')\nif os.path.isdir(train_cats_dir) == False:\n os.mkdir(train_cats_dir)\n\n# 훈련용 강아지 사진 디렉터리\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\nif os.path.isdir(train_dogs_dir) == False:\n os.mkdir(train_dogs_dir)\n\n# 검증용 고양이 사진 디렉터리\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nif os.path.isdir(validation_cats_dir) == False:\n os.mkdir(validation_cats_dir)\n\n# 검증용 강아지 사진 디렉터리\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\nif os.path.isdir(validation_dogs_dir) == False:\n os.mkdir(validation_dogs_dir)\n\n# 테스트용 고양이 사진 디렉터리\ntest_cats_dir = os.path.join(test_dir, 'cats')\nif os.path.isdir(test_cats_dir) == False:\n os.mkdir(test_cats_dir)\n\n# 테스트용 강아지 사진 디렉터리\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\nif os.path.isdir(test_dogs_dir) == False:\n os.mkdir(test_dogs_dir)\n\n# 1. 처음 1,000개의 고양이와 강아지 이미지를 훈련용 데이터로 복사\n# 2. 다음 500개의 고양이와 강아지 이미지를 검증용 데이터로 복사\n# 3. 다음 500개의 고양이와 강아지 이미지를 테스트 데이터로 복사\nif os.path.isdir(base_dir):\n fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(train_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n fnames = ['cat.{}.jpg'.format(i) for i in range(1000,1500)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(validation_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n fnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(test_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n fnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(train_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n fnames = ['dog.{}.jpg'.format(i) for i in range(1000,1500)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(validation_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n fnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]\n for fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(test_dogs_dir, fname)\n shutil.copyfile(src, dst)","sub_path":"dog_vs_cat/data_saperation.py","file_name":"data_saperation.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510228059","text":"import socket\nimport os # pentru dimensiunea fisierului\n\n# Accesarea directorului principal al proiectului\nos.chdir(\"..\")\nCRLF = \"\\r\\n\"\n\n# Definirea unui dictionar pentru tipurile media din raspunsull http\ntipuriMedia = {\n\t\"html\": \"text/html\",\n\t\"css\": \"text/css\",\n\t\"js\": \"application/js\",\n\t\"png\": \"image/png\",\n\t\"jpg\": \"image/jpeg\",\n\t\"jpeg\": \"image/jpeg\",\n\t\"gif\": \"image/gif\",\n\t\"ico\": \"image/x-icon\",\n\t\"xml\": \"application/xml\",\n\t\"json\": \"application/json\"\n}\n\ndef formatHttpResponse(tipMedia, fileStream, clientsocket):\n\t# se trimite raspunsul\n\tpacket = \"HTTP/1.1 200 OK\" + CRLF\n\tpacket += \"Content-Length: \" + str(len(fileStream)) + CRLF\n\tpacket += \"Content-Type: \" + tipMedia + CRLF\n\tpacket += \"Server: My PW Server\" + CRLF + CRLF\n\tclientsocket.sendall(packet.encode('utf-8'))\n\tclientsocket.sendall(fileStream)\n\n\ndef errorHttpResponse(clientsocket):\n\tmsg = 'Eroare! Resursa ceruta ' + numeResursaCeruta + ' nu a putut fi gasita!'\n\tprint(msg)\n\tpacket = \"HTTP/1.1 404 Not Found\" + CRLF\n\tpacket += \"Content-Length: \" + str(len(msg.encode('utf-8'))) + CRLF\n\tpacket += \"Content-Type: text/plain\" + CRLF\n\tpacket += \"Server: My PW Server\" + CRLF + CRLF + msg\n\tclientsocket.sendall(packet.encode('utf-8'))\n\n# creeaza un server socket\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# specifica ca serverul va rula pe portul 5678, accesibil de pe orice ip al serverului\nserversocket.bind(('', 5678))\n\n# serverul poate accepta conexiuni; specifica cati clienti pot astepta la coada\nserversocket.listen(5)\n\nwhile True:\n\tprint(\"#########################################################################\")\n\tprint(\"Serverul asculta potentiali clienti.\")\n\t# asteapta conectarea unui client la server\n\t# metoda `accept` este blocanta => clientsocket, care reprezinta socket-ul corespunzator clientului conectat\n\t(clientsocket, address) = serversocket.accept()\n\tprint(\"S-a conectat un client.\")\n\n\t# se proceseaza cererea si se citeste prima linie de text\n\tcerere = \"\"\n\tlinieDeStart = \"\"\n\t\n\twhile True:\n\t\tbuf = clientsocket.recv(1024)\n\t\tif len(buf) < 1:\n\t\t\tbreak\n\t\tcerere = cerere + buf.decode()\n\t\tprint(\"S-a citit mesajul: \\n---------------------------\\n\" + cerere + \"\\n---------------------------\")\n\t\tpozitie = cerere.find(CRLF)\n\t\tif (pozitie > -1 and linieDeStart == ''):\n\t\t\tlinieDeStart = cerere[0:pozitie]\n\t\t\tprint(\"S-a citit linia de start din cerere: ##### \" + linieDeStart + \" #####\")\n\t\t\tbreak\n\tprint(\"S-a terminat cititrea.\")\n\tif linieDeStart == '':\n\t\tclientsocket.close()\n\t\tprint(\"S-a terminat comunicarea cu clientul - nu s-a primit niciun mesaj.\")\n\t\tcontinue\n\n\t# interpretarea sirului de caractere `linieDeStart`\n\telementeLineDeStart = linieDeStart.split(\" \")\n\tnumeResursaCeruta = elementeLineDeStart[1][1:]\n\n\tfisier = None\n\tif(numeResursaCeruta != \"api/utilizatori\"):\n\t\ttry:\n\t\t\t# deschide fisierul pentru citire in mod binar\n\t\t\tfisier = open(numeResursaCeruta,\"rb\")\n\t\t\tfileStream = fisier.read()\n\n\t\t\t# extragerea tipului media din dictionar\n\t\t\tnumeExtensie = numeResursaCeruta[numeResursaCeruta.rfind(\".\")+1:]\n\t\t\ttipMedia = tipuriMedia[numeExtensie]\n\n\t\t\t# Formarea si trimiterea raspunsului HTTP\n\t\t\tformatHttpResponse(tipMedia, fileStream, clientsocket)\n\n\t\texcept IOError:\n\t\t\t# daca fisierul nu exista trebuie trimis un mesaj de 404 Not Found\n\t\t\terrorHttpResponse(clientsocket)\n\n\t\tfinally:\n\t\t\tif fisier is not None:\n\t\t\t\tfisier.close()\n\telse:\n\t\tpass\n\tclientsocket.close()\n\tprint(\"S-a terminat comunicarea cu clientul.\")\n\n","sub_path":"server_web/server_web.py","file_name":"server_web.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"508347838","text":"\n# coding: utf-8\n\n# ### Генерим новые таблицы\n# Все очень просто. Есть тренировочные пациенты и тестируемые пациенты.\n# Так вот увеличивать данные будем так же в разных группах независимо, чтоб обучаясь на одном пациенте, классфикаторы не выдавали верный ответ только потому, что встретили знакомого пациента.\n# \n# Подробнее. \n# \n# Остановимся на особенностях нотбука: \n# 1. Для работы нужны только директория 'meas' и файл 'info.csv'. Они лежат в папке 'data'. \n# 2. К сожалению названия методов мало что говорят.\n# 3. нотбук создан после того как определились, что нужны только признаки RR, TQ, QTc,JTc, Tp-Te\n# \n#
plot_labels = ['RR', 'TQ', 'QTc', 'JTc', 'TpeakTend'] ------> WRONG!\n#
plot_labels = ['QTc', 'JTc', 'TpeakTend', 'TQ', 'RR'] ------> CORRECT!\n# \n# В конце вызываются подряд три метода:\n# 1. read_data(); returns:\n# 1. info ------------------- просто DataFrame с 'info.scv'; \n# 2. final_filelist ---------- перечень тех файлов которые есть у нас и описаны в 'info.scv'\n# \n# 2. look_through_info(info, final_filelist); returns:\n# 1. data_sick, data_heal ---- данные, где каждая строка - паттерн (иначе сэмпл), колонки - 5 признаков+label \n# 2. inds_sick, inds_heal ---- строк сколько больных/здоровых пациентов. 2 колонки, во второй - сколько сэпплов в файле пациента, в первой - cumsum второй колонки (нужно для того, чтобы затем найти в data_sick, откуда сэмплы начинаются для этого пацента и где заканчиваются, метод: get_data_by_indexes)\n# \n# 3. get_train_and_test_sets(data_sick, data_heal, inds_sick, inds_heal, per_edge)\n# 1. tr_d, ts_d -------------- уже готовые данные\n# 2. tr_l, ts_l -------------- ответы к ним\n# \n# В итоге данные будут в одинаковом объеме, граница количества больных срезается по количеству здоровых, поскольку здоровых меньше.\n\n# In[3]:\n\n\nimport pandas as pd\n\nimport numpy as np\n\nimport os\n\n\n# In[4]:\n\n\ndef read_data(dirpath=\"./\"):\n info = pd.read_csv(dirpath+'data/info.csv')\n\n # astype(int) for getting rid of '123123.0' and strings for next step\n file_numbers = info['Номер ЭКГ'].dropna().astype(int).astype(str)\n\n info_filelist = 'results' + file_numbers + '.csv'\n\n meas_filelist = os.listdir(dirpath+'data/meas')\n\n # form intersection of our 2 sets\n final_filelist = set(info_filelist).intersection(meas_filelist)\n \n return info, final_filelist\n\n\n# In[5]:\n\n\n# l = [RR, TQ, QTc, JTc, TpeakTend]\n# l = [QTc, JTc, TpeakTend, TQ, RR]\n\ndef get_label(info, filename):\n\n # find the row with our name of file\n row = info.loc[info['Номер ЭКГ'].isin([filename[7:-4]])]\n \n # extract the and label of our file\n answer = row['сердечно-сосудистое заболевание (при наличии)'].all()\n \n return (1 if answer == 'да' else 0)\n\ndef get_feat(arrs) :\n shiftedRR = np.sqrt(arrs[0,:-1].copy())\n # arrs.shape[1]-1 ---> -1 cause of first RR\n newarrs = np.empty((5+1, arrs.shape[1]-1), dtype=float)\n \n newarrs[0,:] = arrs[2,1:] / shiftedRR #QTc = QT / shiftedRR\n newarrs[1,:] = arrs[1,1:] / shiftedRR #JTc = JT / shiftedRR \n newarrs[2,:] = arrs[3,1:] #TpeakTend = TT\n newarrs[3,:] = arrs[0,1:] - arrs[2,1:] #TQ = RR – QT\n newarrs[4,:] = arrs[0,1:] #RR\n\n return newarrs\n\n\n# In[6]:\n\n\ndef look_through_info(info, final_filelist, dirpath=\"./\"):\n \n def fill_data(data, inds, ii, arr):\n data = np.concatenate((data, arr.T))\n inds[ii,0] = inds[ii-1,0] + inds[ii-1,1] # if ii == 0 then take inds[-1,0] == 0\n inds[ii,1] = arr.shape[1]\n return data, ii+1\n\n len_list = len(final_filelist) # number of all files\n \n # data of patients with label\n data_sick = np.empty((0, 5 + 1), dtype=float)\n data_heal = np.empty((0, 5 + 1), dtype=float)\n \n # cumsum in 0-column and number of patterns in 1-column\n inds_sick = np.zeros((len_list, 2), dtype=int)\n inds_heal = np.zeros((len_list, 2), dtype=int)\n i_sick = 0\n i_heal = 0\n \n for filename in final_filelist :\n df = pd.read_csv(dirpath+'data/meas/' + filename, \n skiprows=list(range(10))+[11, 15, 16]+list(range(17,99)), \n index_col=None, header=None)\n data = df._get_numeric_data()\n if data.shape[1] <= 1: # because RR will shorted by one\n continue\n arr = get_feat(data.values)\n ans = get_label(info, filename)\n arr[5] = ans\n if ans == 1:\n data_sick, i_sick = fill_data(data_sick, inds_sick, i_sick, arr)\n else:\n data_heal, i_heal = fill_data(data_heal, inds_heal, i_heal, arr)\n inds_sick = inds_sick[:i_sick]\n inds_heal = inds_heal[:i_heal]\n \n return data_sick, data_heal, inds_sick, inds_heal\n\n\n# In[143]:\n\n\ndef get_train_and_test_sets(DataSick, DataHeal, IndsSick, IndsHeal, \n per_edge=0.8, balanced_data=True, make_shuffle=True):\n \n data_sick = DataSick.copy()\n data_heal = DataHeal.copy()\n inds_sick = IndsSick.copy() \n inds_heal = IndsHeal.copy()\n \n # number_of_health -- number of health patterns\n # take exactly helth because its less than sick \n \n number_of_health = inds_heal[-1,0] + inds_heal[-1,1] \n if balanced_data:\n number_of_sick = number_of_health\n else:\n number_of_sick = inds_sick[-1,0] + inds_sick[-1,1]\n \n edge1_heal = int(number_of_health * per_edge) # how much is train patterns for heal people\n edge2_heal= number_of_health\n edge1_sick = int(number_of_sick * per_edge) # how much is train patterns for sick people\n edge2_sick= number_of_sick\n \n def get_data_by_indexes(ready_data, inds):\n data = np.empty((0,5+1))\n for i in range(inds.shape[0]):\n start = inds[i,0]\n end = start + inds[i,1]\n data = np.concatenate((data, ready_data[start:end]))\n return data\n \n def form_list_of_test_patients(ready_data, ind_test):\n patient_data_list = []\n for i in range(ind_test.shape[0]):\n start = ind_test[i,0]\n end = start + ind_test[i,1]\n patient_data_list.append(ready_data[start:end])\n return patient_data_list\n \n \n def get_train_test_data(ready_data, inds, edge1, edge2):\n if make_shuffle:\n np.random.shuffle(inds)\n ind_cumsum = np.cumsum(inds[:,1])\n ind_train = inds[ind_cumsum <= edge1]\n ind_test = inds[(ind_cumsum > edge1) * (ind_cumsum<=edge2)]\n train_data = get_data_by_indexes(ready_data, ind_train)\n test_data = get_data_by_indexes(ready_data, ind_test)\n patient_data_list = form_list_of_test_patients(ready_data, ind_test)\n return train_data, test_data, patient_data_list\n \n tr_s, ts_s, patient_data_s = get_train_test_data(data_sick, inds_sick, edge1_sick, edge2_sick)\n tr_h, ts_h, patient_data_h = get_train_test_data(data_heal, inds_heal, edge1_heal, edge2_heal)\n\n patient_data = patient_data_h + patient_data_s \n \n train = np.concatenate((tr_s,tr_h))\n test = np.concatenate((ts_s,ts_h))\n\n if make_shuffle:\n np.random.shuffle(train)\n np.random.shuffle(test)\n return train[:,:5], test[:,:5], train[:,5], test[:,5], patient_data\n\n\n# In[147]:\n\n\n# info, final_filelist = read_data(dirpath=\"../\")\n# data_sick, data_heal, inds_sick, inds_heal = look_through_info(info, final_filelist, dirpath=\"../\")\n# tr_d, ts_d, tr_l, ts_l, patient_data = \\\n# get_train_and_test_sets(data_sick, data_heal, inds_sick, inds_heal, 1, balanced_data=False)\n\n\n# 41 здоровых пациентов, 70 больных. Соответственно, всего 111 пациентов.\n# У здоровых пациентов суммарно всего 994 сэмплов. У больных - 1549. Соответственно, всего 2543 сэмлпов для обучения.\n# \n","sub_path":"make_ready_data/make_ready_big_data.py","file_name":"make_ready_big_data.py","file_ext":"py","file_size_in_byte":8955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"374783465","text":"import numpy as np\r\nfrom algorithms.feature_estimate import FeatureEstimate\r\n\r\nTRAJECTORIES = 20\r\nSTEPS = 100\r\nGAMMA = 0.99\r\n\r\ndef idx_to_state(env, state):\r\n env_low = env.observation_space.low\r\n env_high = env.observation_space.high\r\n env_distance = (env_high - env_low) / 50\r\n position_idx = int((state[0] - env_low[0]) / env_distance[0])\r\n velocity_idx = int((state[1] - env_low[1]) / env_distance[1])\r\n state_idx = position_idx + velocity_idx * 50\r\n return state_idx\r\n\r\ndef calcNewFE(env, q_table, weights):\r\n state = env.reset()\r\n featureExpectations = np.zeros(len(weights))\r\n feature_estimate = FeatureEstimate(env, len(weights))\r\n car_steps = 0\r\n for m in range(TRAJECTORIES):\r\n while True:\r\n car_steps += 1\r\n\r\n # Choose action.\r\n state_idx = idx_to_state(env, state)\r\n action = (np.argmax(q_table[state_idx]))\r\n\r\n # Take action.\r\n next_state, _, done, _ = env.step(action)\r\n\r\n features = feature_estimate.get_features(next_state)\r\n featureExpectations += (GAMMA**(car_steps))*np.array(features)\r\n\r\n if car_steps % STEPS == 0 or done == True:\r\n break\r\n\r\n return featureExpectations / TRAJECTORIES\r\n\r\ndef randomFE(num_features):\r\n return np.random.normal(size=num_features)\r\n\r\ndef expertFE(env, trajectories, num_features):\r\n featureExpectations = np.zeros(num_features)\r\n feature_estimate = FeatureEstimate(env, num_features)\r\n for m in range(len(trajectories)):\r\n for car_steps in range(len(trajectories[0])):\r\n state = trajectories[m][car_steps]\r\n features = feature_estimate.get_features(state)\r\n featureExpectations += (GAMMA**(car_steps))*np.array(features)\r\n featureExpectations = featureExpectations / len(trajectories)\r\n return featureExpectations\r\n","sub_path":"mountaincar/algorithms/feature_expectation.py","file_name":"feature_expectation.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"292407655","text":"\"\"\"\n==============================\n 2020/12/30\n rkouhei\n==============================\n\"\"\"\n\n# ライブラリのインポート\nfrom utility.handling_file_directory import read_file, make_directory\nfrom utility.handling_data import read_iteration, read_sep, check_length\nimport os\nimport re\nimport statsmodels.api as sm\nimport pandas as pd\nfrom tqdm import tqdm\n\nclass method:\n # 変数\n mode = 6 # モード番号\n path = \"\" # 読み込み対象のファイルへのパス\n sep = \"\" # ファイルの区切り文字の種類\n iteration = 0 # 計算回数指定用変数\n\n def __init__(self, path):\n \"\"\"\n ファイルの読み込みを行う。一度に、複数ファイルの読み込みも可能。\n 相対パスと絶対パス、どちらでも可能。\n\n Input\n ------\n path : 読み込みたいのファイルへのパス(一括指定可)\n\n Raises\n ------\n 計算回数で、数字以外を入力した時。\n \"\"\"\n\n self.sep = read_sep()\n self.iteration = read_iteration()\n self.path = path\n\n def write_file(self, df, path, out_dir):\n \"\"\"\n 計算結果を出力する。\n 出力はindexの有無で、2種類存在する。\n\n Input\n ------\n df : 保存したい計算結果\n path : 元データのファイルパス\n out_dir : 保存先のディレクトリ\n \"\"\"\n\n input_fname = re.split(\"/\", path)[-1] # ファイルネームだけ取り出す\n ext = os.path.splitext(input_fname) # ファイル名と拡張子に分解\n\n # index有りのファイル名\n out_fname = ext[0] + \"_\" + str(self.iteration) + ext[1]\n out_path = out_dir + out_fname\n\n # indexなしのファイル名\n out_fname_noindex = ext[0] + \"_\" + str(self.iteration) + \"_noindex\" + ext[1]\n out_path_noindex = out_dir + out_fname_noindex\n\n df.to_csv(out_path, sep=\" \", header=False, encoding=\"utf-8\") # index有り\n df.to_csv(out_path_noindex, sep=\" \", header=False, encoding=\"utf-8\", index=False) # indexなし\n\n def calc(self, df_array, path_array, out_dir):\n \"\"\"\n 自己相関係数の計算を行う。\n\n Input\n ------\n df_array : 読み込んだデータ群の配列\n path_array : 元データのファイルパス配列\n out_dir : 計算結果を保存先するディレクトリへのパス\n \"\"\"\n\n # プログレスバーの設定\n bar = tqdm(total=len(path_array))\n bar.set_description(\"calc_acf\")\n\n for df, path in zip(df_array, path_array):\n df_data = pd.Series(df['data'], dtype='float') # 自己相関の計算のためにpd.Seriesに格納\n part_df = df_data.copy()\n\n part_iterations = int(self.iteration)\n acf = sm.tsa.stattools.acf(part_df, nlags=part_iterations, fft=True)\n index = pd.Series([times*0.0002 for times in range(part_iterations)])\n out_pd = pd.Series(acf[:part_iterations], index=['{:.4f}'.format(i) for i in index])\n self.write_file(out_pd, path, out_dir) \n \n bar.update(1) # プログレスバーの更新\n \n def fit(self):\n \"\"\"\n 計算の実行。\n \"\"\"\n\n df_array, path_array = read_file(self.path, self.sep) # データの読み込み\n check_length(df_array, path_array, self.iteration) # ずらす回数とデータ数を比較しておく\n out_dir, _ = make_directory(self.mode) # 書き込みを行うディレクトリ\n self.calc(df_array, path_array, out_dir) # 計算の実行と保存","sub_path":"src/calc_acf/mode6.py","file_name":"mode6.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"150081168","text":"import os\nimport traceback\n\nimport telegram\nimport language\n\nif os.path.exists('telegram_token'):\n with open('telegram_token', 'r') as f:\n telegram.telegram_token = f.read()\nelse:\n telegram.telegram_token = input('Enter telegram bot token: ')\n with open('telegram_token', 'w') as f:\n f.write(telegram.telegram_token)\n\n\nif __name__ == '__main__':\n language.initialise_language()\n\n print(\"Start serving telegram updates\")\n for message in telegram.pull_messages():\n print(f'{message.from_[\"first_name\"]}@{message.chat[\"id\"]}: {message.text}')\n try:\n language.answer(message)\n except KeyboardInterrupt:\n print(\"exiting..\")\n break\n except Exception:\n traceback.print_exc()\n","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"409004188","text":"\"\"\"Created February 7, 2019 by Mimi Sun\n\nRose8bot.py - main file\ncmd - drag file and press enter\nterminal - python3 rose8bot.py\ninstall discord.py rewrite - python3 -m pip install -U discord.py[voice]\npip install -U git+https://github.com/Rapptz/discord.py@rewrite#egg=discord.py[voice]\npip install psycopg2-binary\n pip install requests\n\"\"\"\n\n#----- IMPORTS -----\nimport discord\n#from discord.ext import commands\nfrom datetime import datetime\nimport os #for db\nimport psycopg2 #for db\nfrom random import randint\n#import math\nimport requests\nimport json\n\n#module imports..\nimport levelingSystem\n\nDATABASE_URL = 'postgres://xwceyseiukfdkz:51db1a70bff79495e8d0f3bf5874b49a4e9e8fd5d6760449a98aa5ccb3c4d1b1@ec2-54-204-39-238.compute-1.amazonaws.com:5432/d22dp6v8g7jfcb'\nconn = psycopg2.connect(DATABASE_URL, sslmode='require')\n\nbot_token = 'NTQzMTI0NDEzMjEwNjg5NTM2.Dz4A2g.jJ82SFse6Dvk7_ARmvTGK9vWdEk'\n\nclient = discord.Client() #establish Discord client\n\nwolfPack = client.get_guild(349593648595206154)\n_8bitpetals = client.get_guild(538596813809254414)\n\ndef html_decode(s):\n \"\"\"\n Returns the ASCII decoded version of the given HTML string. This does\n NOT remove normal HTML tags like

.\n \"\"\"\n htmlCodes = (\n (\"'\", '''),\n ('\"', '"'),\n ('>', '>'),\n ('<', '<'),\n ('&', '&'),\n ('é', 'é')\n )\n for code in htmlCodes:\n s = s.replace(code[1], code[0])\n return s\n\n\ndef Create_user(userid, uname, nick, discrim, a_url):\n sql = \"\"\" INSERT INTO users(memberid, username, nickname, discriminator, avatar_url)\n SELECT %s ,%s, %s, %s, %s WHERE NOT EXISTS(SELECT memberid FROM users WHERE memberid = %s) RETURNING memberid; \"\"\"\n conn = None\n user_id = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n #execute the INSERT statement\n cur.execute(sql, (str(userid), uname, nick, discrim, a_url,str(userid)))\n #get newly generated id back\n user_id = cur.fetchone()[0]\n Insert_xp(user_id,0,0)\n Insert_rep(user_id, 'Neutral',0)\n Insert_currency(user_id, '0','0','0')\n Insert_upvotes(user_id, 0,0)\n Insert_rank(user_id, 0)\n\n #commit changes to db\n conn.commit()\n count = cur.rowcount\n print('(+) Record successfully inserted into user.')\n #close communication with db server\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into user.')\n finally:\n if conn is not None:\n conn.close()\n ####print('(-------(x) PostgreSQL connection is closed.')\n return user_id\n\ndef Update_currency(user_id, currency_earned, currency_spent):\n find_user = \"\"\"SELECT user_id, current_currency, total_currency_earned, total_currency_spent, currency_daily FROM currency WHERE user_id = %s;\"\"\"\n insert_currency = \"\"\"UPDATE currency SET current_currency = %s, total_currency_earned=%s, total_currency_spent=%s, currency_daily=%s WHERE user_id = %s RETURNING current_currency, total_currency_earned, total_currency_spent;\"\"\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n cur = conn.cursor()\n cur.execute(find_user,(str(user_id),))\n row = cur.fetchone()\n current = int(row[1])\n global earned\n earned = round(int(row[2]) + int(currency_earned))\n #print('earned = ' + str(earned))\n global spent\n spent = round(int(row[3]) + int(currency_spent))\n #print('spent = ' + str(spent))\n global current_currency\n current_currency = round(earned - spent)\n #print('current_currency = ' + str(current_currency))\n global currency_daily\n currency_daily = int(row[4])\n\n cur.execute(insert_currency, (current_currency, earned, spent,earned,str(user_id)))\n conn.commit()\n #print('!! ++ !! currency successfully added to user.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into currency.')\n finally:\n if conn is not None:\n conn.close()\n ####print('(-------(x) PostgreSQL connection is closed.')\n\ndef Add_xp(user_id, xp_earned):\n find_user = \"\"\"SELECT user_id, current_xp, total_xp FROM xp WHERE user_id = %s;\"\"\"\n insert_xp_sql = \"\"\"UPDATE xp SET total_xp = %s WHERE user_id = %s RETURNING user_id, current_xp, total_xp;\"\"\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n cur = conn.cursor()\n cur.execute(find_user,(str(user_id),))\n row = cur.fetchone()\n global userid\n #print('fetchone() = ' + str(row))\n userid = row[0]\n #print('userid = ' + str(userid))\n currentxp = row[1]\n #print('currentxp = ' + str(currentxp))\n totalxp = row[2]\n #print('totalxp = ' + str(totalxp))\n #new total xp\n global new_totalxp\n new_totalxp = int(totalxp) + int(xp_earned)\n #print('new_total = ' + str(totalxp) + ' + ' + str(xp_earned))\n #level before xp was added\n global lvl_prev\n lvl_prev = round((math.sqrt(totalxp))//5)\n\n #current level\n global lvl\n lvl = round((math.sqrt(new_totalxp))//5)\n #lvl = round((1+math.sqrt(1+8*new_totalxp/150))/2)\n #print('lvl = ' + str(lvl))\n\n global currentlvl\n currentlvl = round(lvl)\n #print('currentlvl = ' + str(currentlvl))\n\n global nextlvl\n nextlvl = int(currentlvl) + 1\n #print('nextlvl = ' + str(nextlvl))\n\n #xp needed for current level\n global xp_for_level\n xp_for_level = round((5*currentlvl)**2)\n #xp_for_level = (((currentlvl*currentlvl)-currentlvl)*150)/2\n #print('xp_for_level = ' + str(xp_for_level))\n\n #xp progress\n global xp_progress\n xp_progress = round(new_totalxp - xp_for_level)\n #print('xp_progress = ' + str(xp_progress))\n\n #total xp needed for next level\n global xp_for_next_level\n xp_for_next_level = (5*nextlvl)**2\n #xp_next_level = round((((int(nextlvl)**2)-int(nextlvl))*150)/2)\n #print('xp_for_next_level = ' + str(xp_for_next_level))\n\n global xp_next_progress\n xp_next_progress = round(xp_for_next_level - xp_for_level)\n\n cur.execute(insert_xp_sql,(new_totalxp, str(user_id)))\n conn.commit()\n #print('!! ++ !! xp successfully added to user.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('!! -- !! xp failed add to user.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Insert_xp(user_id, curr_xp, total_xp):\n sql = \"INSERT INTO xp(user_id, current_xp, total_xp) VALUES(%s, %s, %s)\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(sql,(user_id, curr_xp, total_xp))\n conn.commit()\n print('(+) xp record successfully inserted.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into xp.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Insert_rep(user_id, rep_name, total_rep):\n sql = \"INSERT INTO rep(user_id, rep_name, total_rep) VALUES (%s, %s, %s)\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(sql, (user_id, rep_name, total_rep))\n conn.commit()\n print('(+) rep record successfully inserted.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into rep.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Insert_currency(user_id, curr_currency, currency_earned, currency_spent):\n print('attempting to insert_currency...')\n sql = \"INSERT INTO currency(user_id, current_currency, total_currency_earned, total_currency_spent, currency_daily) VALUES (%s, %s, %s, %s,%s)\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(sql, (user_id, curr_currency, currency_earned, currency_spent, currency_earned))\n conn.commit()\n print('(+) currency record successfully inserted.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into currency.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Insert_upvotes(user_id, up_given, up_received):\n sql = \"INSERT INTO upvotes(user_id, upvotes_given, upvotes_received) VALUES (%s, %s, %s)\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(sql,(user_id, up_given, up_received))\n conn.commit()\n print('(+) upvotes record successfully inserted.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into upvotes.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Insert_rank(user_id, rank):\n sql = \"INSERT INTO rank(user_id, rank) VALUES (%s, %s)\"\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(sql,(user_id, rank))\n conn.commit()\n #print('(+) rank record successfully inserted.')\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n if conn:\n print('(-) Failed to insert record into rank.')\n finally:\n if conn is not None:\n conn.close()\n #print('-------(x) PostgreSQL connection is closed.')\n\ndef Get_users():\n conn = None\n try:\n conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n #create new cursor\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM users ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE users (user_id, memberid, uname, nickname, disc, avatar')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n\n cur.execute(\"SELECT * FROM xp ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE xp (xp_id, user_id, current_xp, total_xp')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n cur.execute(\"SELECT * FROM rep ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE rep rep_id, user_id, rep_name, total_rep')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n cur.execute(\"SELECT * FROM currency ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE currency (currency_id, current $, total $ earned, total $spent')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n cur.execute(\"SELECT * FROM upvotes ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE upvotes (upvotes_id, user_id, ups given, ups received')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n cur.execute(\"SELECT * FROM rank ORDER BY user_id\")\n print('Number of users: ' + str(cur.rowcount))\n print('TABLE rank (rank_id, user_id, rank')\n row = cur.fetchone()\n\n while row is not None:\n print(str(row))\n row = cur.fetchone()\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\ndef Delete_dupes():\n sql = \"DELETE FROM users a USING users b WHERE a.memberid < b.memberid;\"\n conn = None\n try:\n conn = conn = psycopg2.connect(DATABASE_URL, sslmode='require')\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n Get_users()\n cur.close()\n print(\"postgreSQL connection closed.\")\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\ndef Retrieve_Token():\n retrieve_token = requests.get(\"https://opentdb.com/api_token.php?command=request\").json()\n global token\n token = retrieve_token['token']\n print('Retrieving token')\n print('token = ' + token)\n global token_response_message\n token_response_message = retrieve_token['response_message']\n\n#server stats\nstatsEmbed = discord.Embed(\n title='Server Stats',\n colour=0xFC6A5B,\n )\n\n#commands menu\ncmdsEmbed = discord.Embed(\n title='Commands Menu',\n colour =0xFC6A5B,\n )\n\n#user stats\nmyStatsEmbed = discord.Embed(\n title='User Stats',\n colour=0xFC6A5B,\n )\n\n#user profile\nprofileEmbed = discord.Embed(\n title = 'Profile',\n colour = 0xFFFFFF,\n )\n\nmoonsEmbed = discord.Embed(\n title = 'Moons',\n colour = 0xFFFFFF,\n )\n\n@client.event\nasync def on_ready():\n print(\"Rose8bot is ready!\")\n #await allows multitasking so the bot can respond to\n #different events at the same time\n await client.change_presence(activity=discord.Game(name=\"v2.3.4\"))\n levelingSystem.Create_tables()\n Retrieve_Token()\n #Delete_dupes()\n\n@client.event\nasync def on_message(message):\n user = client.get_user(message.author.id)\n guild = message.guild\n msg = message\n member = message.author\n\n global username\n username = user.name\n global nickname\n nickname = member.nick\n global discriminator\n discriminator = user.discriminator\n global avatar_url\n avatar_url = member.avatar_url\n\n global trivia_started\n trivia_started = False\n\n print('message received')\n\n #ignore messages sent by Rose8bot\n if message.author == client.user:\n print('message sent by bot, ignoring...')\n return\n else:\n\n Create_user(user.id,username, nickname, discriminator, avatar_url)\n xp_add = randint(1,5)\n Add_xp(str(user.id),str(xp_add))\n Update_currency(str(user.id),str(0),str(0))\n\n if lvl > lvl_prev:\n await message.channel.send(f\"🆙 || Congrats {message.author.mention}, you just hit level **{lvl}**!!\")\n\n #Add_xp(str(user.id),str(0))\n #Update_currency(str(user.id),str(0),str(0))\n\n #commands menu\n if message.content == '$menu':\n statsEmbed.set_footer(text='Bot created by Rose8bit. ')\n cmdsEmbed.set_thumbnail(url='https://vignette.wikia.nocookie.net/mcpc/images/1/10/Oxeye-Daisy.png/revision/latest?cb=20131121042853')\n cmdsEmbed.add_field(name = '$newcat [category name]', value ='Create a new category', inline=False)\n cmdsEmbed.add_field(name = '$newtext [channel name]', value = 'Create a new text channel', inline=False)\n cmdsEmbed.add_field(name = 'newvoice [channel name]', value = 'Create a new voice channel', inline=False)\n cmdsEmbed.add_field(name = '$rolepoll', value = 'Create a poll to auto-assign roles based on reactions', inline=False)\n cmdsEmbed.add_field(name = '$statsfor [username]', value = 'Display stats for given username. (username is case-sensitive)', inline=False)\n cmdsEmbed.add_field(name = '$stats', value = 'Display server stats', inline=False)\n cmdsEmbed.add_field(name = '$mystats', value = 'Display user stats.', inline=False)\n cmdsEmbed.add_field(name = '$stats', value = 'Display server stats.', inline=False)\n cmdsEmbed.add_field(name = '$slots', value = 'Roll the slot machine!', inline=False)\n cmdsEmbed.add_field(name = '$trivia', value = '**Usable by Rose8bit and Vanitaz only** Trivia time!')\n cmdsEmbed.add_field(name = '$end', value = '**Usable by Rose8bit and Vanitaz only** End the current trivia session and announce the winner.')\n await message.channel.send(embed=cmdsEmbed)\n cmdsEmbed.clear_fields()\n\n #display server stats\n if message.content == '$stats':\n statsEmbed.set_footer(text='Bot created by Rose8bit. ')\n statsEmbed.set_thumbnail(url=guild.icon_url)\n statsEmbed.add_field(name = 'Server Name', value = message.guild, inline=True)\n statsEmbed.add_field(name = 'Server Owner', value = guild.owner, inline=True)\n statsEmbed.add_field(name = 'Text Channels', value = len(guild.text_channels), inline = True)\n statsEmbed.add_field(name = 'Voice Channels', value =len(guild.voice_channels), inline = True)\n statsEmbed.add_field(name = 'Members', value = guild.member_count, inline = True)\n await message.channel.send(embed=statsEmbed)\n statsEmbed.clear_fields()\n\n #display user stats\n if message.content == '$mystats':\n await message.channel.send('Displaying stats for ' + str(user.mention))\n myStatsEmbed.set_footer(text='Bot created by Rose8bit. ')\n myStatsEmbed.set_thumbnail(url=member.avatar_url)\n myStatsEmbed.add_field(name = 'Username', value = str(user.name), inline=False)\n myStatsEmbed.add_field(name = 'Discriminator', value = str(user.discriminator), inline=False)\n #myStatsEmbed.add_field(name = 'Display Name', value = str(user.display_name), inline=False)\n myStatsEmbed.add_field(name = 'Server specific nickname', value = member.nick, inline=False)\n myStatsEmbed.add_field(name = 'Date joined Server', value = member.joined_at, inline=False)\n myStatsEmbed.add_field(name = 'Date joined Discord', value = str(user.created_at), inline=False)\n await message.channel.send(embed=myStatsEmbed)\n myStatsEmbed.clear_fields()\n\n if message.content == '$profile':\n Create_user(user.id,username, nickname, discriminator, avatar_url)\n profileEmbed.set_footer(text = 'Bot created by Rose8bit.')\n profileEmbed.set_thumbnail(url=member.avatar_url)\n profileEmbed.add_field(name = 'Username', value = str(user.name), inline=False)\n profileEmbed.add_field(name = 'Server Rank', value = 'N/A')\n profileEmbed.add_field(name = 'Nickname', value = member.nick, inline = False)\n profileEmbed.add_field(name = 'Level', value = str(currentlvl), inline=False)\n profileEmbed.add_field(name = 'XP progress', value = str(xp_progress) + '/' + str(xp_next_progress), inline=False)\n profileEmbed.add_field(name = 'Moons', value = str(current_currency) + ' 🌕')\n await message.channel.send(embed = profileEmbed)\n profileEmbed.clear_fields()\n\n if message.content == '$moons':\n moonsEmbed.set_footer(text = 'Bot created by Rose8bit.')\n moonsEmbed.set_thumbnail(url=member.avatar_url)\n moonsEmbed.add_field(name = 'Username', value = str(user.name), inline=False)\n moonsEmbed.add_field(name = 'Moons', value = str(current_currency) + ' 🌕')\n await message.channel.send(embed = moonsEmbed)\n moonsEmbed.clear_fields()\n\n #if message.content == '$mimisun':\n #Update_currency(str(user.id),'100','0')\n\n if message.content == '$allusers':\n Get_users()\n\n global slotcost\n slotcost = 2\n\n if message.content == '$trivia' and (user.id == 461656626567577630 or user.id == 294707990303342592):\n print('$trivia entered')\n category = ['15','16','29','31','32','11','14']\n\n trivia_response= requests.get(\"https://opentdb.com/api.php?amount=1&category=\" + random.choice(category)).json()\n #trivia_response = requests.get(\"https://opentdb.com/api.php?amount=1&category=\" + random.choice(category) + \"&token=\" + token + \"\").json()\n #await client.get_channel(349593648595206155)\n response_code = trivia_response['response_code']\n\n #Success - Returned results found successfully.\n if response_code == 0:\n global correct_answer\n correct_answer = trivia_response['results'][0]['correct_answer']\n decoded = html_decode(trivia_response['results'][0][\"question\"])\n decoded_answers = []\n trivia_text = '🤔 || **Trivia Time!** first correct answer wins ``'+ str(slotcost) +'`` 🌕' + '\\n\\n ``' + trivia_response['results'][0]['category'] + '\\nDifficulty: ' + trivia_response['results'][0]['difficulty'] +'``\\n' + '```' + decoded + '```\\n'\n choices = trivia_response['results'][0]['incorrect_answers']\n\n #await message.channel.send('A: ' + correct_answer)\n choices.append(correct_answer)\n choices_num = []\n i = 0\n while i < len(choices):\n decoded_answers.append(html_decode(choices[i]))\n i += 1\n choices_num.append(str(i))\n\n counter = 1\n for i in range(len(decoded_answers)):\n randomWord = random.choice(decoded_answers)\n #await message.channel.send(f\"\\n{counter}. {randomWord} \\n\")\n trivia_text += '`' + str(counter) + '.` ' + randomWord + '\\n'\n if randomWord == correct_answer:\n answer_option = str(counter)\n counter += 1\n decoded_answers.remove(randomWord)\n\n await message.channel.send(trivia_text)\n trivia_players = []\n trivia_winner_id = []\n trivia_winner_name = []\n\n def check(m):\n\n #if someone enters a guess\n if m.content in choices_num:\n\n #check if user has already submitted answer\n if m.author.id in trivia_players:\n print('---> ' + m.author.name + ' has already submitted a guess. Ignoring...')\n\n #check if user has submitted the correct answer\n if m.content == answer_option and m.author.id not in trivia_players:\n print('---> winner found!')\n #add to the list of winners...\n trivia_winner_id.append(m.author.id)\n trivia_winner_name.append(m.author.mention)\n\n #user has not submitted a guess yet\n else:\n print('---> player added to trivia_players')\n trivia_players.append(m.author.id)\n\n #return (m.content == answer_option or m.content == '$trivia')\n return (m.content == '$trivia' or m.content =='$end') and m.channel == message.channel\n #return (m.content.upper().replace(\" \",\"\") == correct_answer.upper().replace(\" \",\"\") or m.content =='$trivia') and m.channel == message.channel\n try:\n #wait for the timer to run out, or a new trivia to start\n msg = await client.wait_for('message', timeout=20, check=check)\n #timer ran out or an error ocurred\n except Exception as error:\n print('!!!!!!' + str(error))\n\n if not trivia_winner_id:\n await message.channel.send(f\"⏰ Time\\'s up! No winners this round. The correct answer was `` {html_decode(correct_answer)}``. Better luck next time...\\n\")\n\n #if there is one winner\n else:\n await message.channel.send(f\"Congrats{trivia_winner_name[0]}, ``{html_decode(correct_answer)}`` is the correct answer! \\n ``{str(slotcost)}``🌕 has been added to your account.\\n\")\n Update_currency(str(client.get_user(trivia_winner_id[0]).id),str(slotcost),'0')\n slotpot = 0\n\n trivia_players.clear()\n trivia_winner_id.clear()\n trivia_winner_name.clear()\n\n # $trivia was entered and a new trivia session has started\n else:\n if msg.content == '$end' and (user.id == 461656626567577630 or user.id == 294707990303342592):\n if not trivia_winner_id:\n await message.channel.send(f\"No winners this round. The correct answer was `` {html_decode(correct_answer)}``. Better luck next time...\")\n else:\n await message.channel.send(f\"Congrats{trivia_winner_name[0]}, ``{html_decode(correct_answer)}`` is the correct answer! \\n ``2``🌕 has been added to your account.\")\n Update_currency(str(client.get_user(trivia_winner_id[0]).id),'2','0')\n\n trivia_players.clear()\n\n #No results - Could not return results. API doesn't have enough questions\n if response_code == 1:\n await client.get_channel(544340495384576012).send('``Response code 1:`` **No results** Could not return results. Resetting token...')\n\n #Invalid parameters - contains an invalid parameter. Check code\n if response_code == 2:\n await client.get_channel(544340495384576012).send('``Response code 2:`` **Invalid parameters** Contains an invalid parameter. Check the code 😛.')\n\n #Token not found - Session token does not exist. Retrieving new token...\n if response_code == 3:\n await client.get_channel(544340495384576012).send('``Response code 3: `` **Token not found** Session token does not exist. Retrieving a new session token...')\n await client.get_channel(544340495384576012).send(token_response_message)\n await client.get_channel(544340495384576012).send('new token is ' + token)\n\n #Token empty - token has returned all possible questions. Retrieving new..\n if response_code == 4:\n await client.get_channel(544340495384576012).send('``Response code 4:`` **Token empty** Session token has returned all possible questions. Retrieving a new session token...')\n await client.get_channel(544340495384576012).send(token_response_message)\n\n\n\n if message.content.startswith('$statsfor'):\n userLookup = message.content.split(' ',1)[1]\n member = discord.utils.get(message.guild.members, name = userLookup)\n if member == None:\n await message.channel.send('Member ``' + userLookup + '`` not found.')\n else:\n user = client.get_user(member.id)\n await message.channel.send('Displaying stats for ' + user.mention)\n myStatsEmbed.set_footer(text='Bot created by Rose8bit. ')\n myStatsEmbed.set_thumbnail(url=member.avatar_url)\n myStatsEmbed.add_field(name = 'Username', value = str(user.name), inline=False)\n myStatsEmbed.add_field(name = 'Discriminator', value = str(user.discriminator), inline=False)\n myStatsEmbed.add_field(name = 'Display Name', value = str(user.display_name), inline=False)\n myStatsEmbed.add_field(name = 'Server specific nickname', value = member.nick, inline=False)\n myStatsEmbed.add_field(name = 'Date joined Server', value = member.joined_at, inline=False)\n myStatsEmbed.add_field(name = 'Date joined Discord', value = str(user.created_at), inline=False)\n await message.channel.send(embed=myStatsEmbed)\n myStatsEmbed.clear_fields()\n\n #create a new category channel\n if message.content.startswith('$newcat'):\n channel = message.channel\n channelName = message.content.split(' ',1)[1]\n newChannel = await guild.create_category_channel(channelName)\n await channel.send('Category ``'+channelName+'`` has been created.')\n\n #create a new category channel\n if message.content.startswith('$newtext'):\n channel = message.channel\n channelName = message.content.split(' ',1)[1]\n newChannel = await guild.create_text_channel(channelName)\n await channel.send('Text channel ``'+channelName+'`` has been created.')\n\n #create new voice channel\n if message.content.startswith('$newvoice'):\n channel = message.channel\n channelName = message.content.split(' ',1)[1]\n newChannel = await guild.create_voice_channel(channelName)\n await channel.send('Voice channel ``'+channelName+'`` has been created.')\n\n #test waiting for a reaction from message author\n if message.content.startswith('$thumb'):\n channel = message.channel\n await channel.send('Send me that 👍 reaction!')\n\n def check(reaction, user):\n return user == message.author and str(reaction.emoji) == '👍'\n\n try:\n reaction, user = await client.wait_for('reaction_add', timeout=20.0, check=check)\n except:\n await channel.send('👎 You took too long!')\n else:\n await channel.send('Awesome! Thank you :blush:')\n\n #test waiting for a user reply\n if message.content.startswith('$greet'):\n channel = message.channel\n await channel.send('Say hello!')\n\n def check(m):\n return m.content == 'hello' and m.channel == channel\n try:\n msg = await client.wait_for('message',timeout=10.0, check=check)\n except:\n await channel.send('You took too long!')\n else:\n await channel.send('Hello {.author}!'.format(msg))\n\n #create a poll to auto-assign roles based on emoji reactions\n if message.content == '$rolepoll':\n if str(message.author.id) == '461656626567577630' or str(message.author.id) == '294707990303342592':\n reactEmb = discord.Embed(title='Role Menu: Games',description='React to assign yourself a role. \\n\\n'\n + '<:pfsmile:544288794820739152> : ``Apex Legends`` \\n\\n'\n + '<:fortnite:544280152507416618> : ``Fortnite`` \\n\\n'\n + '<:league:544349301904637954>: ``League of Legends`` \\n\\n'\n + '<:ow:544289940062732307> : ``Overwatch`` \\n\\n'\n + '<:smash:544283152886005775> : ``Smash`` \\n\\n'\n + '<:smite:544349358921875468> : ``Smite``',\n color = 0xFC6A5B)\n reactEmb.set_author(name='Assign a role',icon_url=client.user.avatar_url)\n mesg = await message.channel.send(embed=reactEmb)\n await mesg.add_reaction(emoji=':pfsmile:544288794820739152')\n await mesg.add_reaction(emoji=':fortnite:544280152507416618')\n await mesg.add_reaction(emoji=':league:544349301904637954')\n await mesg.add_reaction(emoji=':ow:544289940062732307')\n await mesg.add_reaction(emoji=':smash:544283152886005775')\n await mesg.add_reaction(emoji=':smite:544349358921875468')\n global pollMessage\n global poll_message\n poll_message = str(mesg.id)\n\n else: #someone other than admins tried to use command\n await message.channel.send('Sorry, you do not have permission to use that command.')\n #record error-log\n await client.get_channel(544340495384576012).send(message.author.mention + 'attempted to use the command $rolepoll.')\n\n if message.content == '$raffle':\n users = await reaction.users().flatten()\n winner = random.choice(users)\n await message.channel.send('{} has won the raffle!'.format(winner))\n\n #slot machine\n if message.content == '$slots':\n emojis = []\n emojis = ['🍎','🍊','🍐','🍋','🍉','🍇','🍓','🍒','🍏','🍌','🍉','🍈','🍑','🍍','🍅']\n if int(current_currency)< 3:\n await message.channel.send(message.author.mention + ' you do not have enough 🌕 moons to play that.')\n else:\n await message.channel.send('$lots 💰 || ``3`` 🌕 per play')\n a = random.choice(emojis)\n b = random.choice(emojis)\n c = random.choice(emojis)\n\n slotmachine = f\"**[ {a} {b} {c} ]\\n\\n**\"\n if (a == b and a == c):\n await message.channel.send(f\"{slotmachine} 💰 || **{message.author.mention}** you rolled 3 in a row and have won ``15`` 🌕!\")\n Update_currency(user.id, 15, 3)\n elif ((a == b) or (b == c)):\n await message.channel.send(f\"{slotmachine} 🎉 || **{message.author.mention}** you rolled 2 in a row and have won ``6`` 🌕!\")\n Update_currency(user.id, 6, 3)\n else:\n await message.channel.send(f\"{slotmachine} 😢 || **{message.author.mention}** sorry no match, you lost. \")\n Update_currency(user.id, 0, 3)\n\n@client.event\nasync def on_raw_reaction_add(payload):\n #will be dispatched everytime a user adds a reaction to a message the bot can see\n #print('reaction added')\n if not payload.guild_id:\n #if the reaction was added in a DM channel with the bot\n #do nothing\n return\n\n guild = client.get_guild(payload.guild_id)\n #need the guild to get the member who reacted\n member = guild.get_member(payload.user_id)\n #get member who will receive the role\n\n #getting roles...\n role1 = discord.utils.get(guild.roles, name=\"Smash Bros\")\n role2 = discord.utils.get(guild.roles, name=\"Fortnite\")\n role3 = discord.utils.get(guild.roles, name=\"Overwatch\")\n role4 = discord.utils.get(guild.roles, name=\"Apex Legends\")\n role5 = discord.utils.get(guild.roles, name=\"Smite\")\n role6 = discord.utils.get(guild.roles, name=\"League of Legends\")\n\n #putting roles in array...\n role_list = [role1, role2, role3,role4,role5,role6]\n\n #reaction emoji ids\n #smash, fortnite, ow, apex, smite, lol\n reaction_list = [544283152886005775,544280152507416618,544289940062732307,544288794820739152,544349301904637954,544349358921875468]\n\n #if the message is the right one...\n if payload.message_id == 548171468777717760:\n #cycle through reaction_list to find the emoji that was used to react\n j=0\n while j < len(reaction_list):\n if payload.emoji.id == reaction_list[j]:\n role_added = role_list[j]\n j += 1\n\n #if the user does not already belong to that role\n if role_added not in member.roles:\n #add the role to the member\n await member.add_roles(role_added, reason='Role Menu: Games reaction')\n #send confirmation to member\n await member.send('✅ || ' + member.mention + ' has been given the role ' + '``' + str(role_added) + '``!')\n await client.get_channel(544340495384576012).send('✅ || ' + member.mention + ' has been given the role ' + '``' + str(role_added) + '``!')\n\n@client.event\nasync def on_raw_reaction_remove(payload):\n #will be dispatched everytime a user removes a reaction to a message the bot can see\n print ('reaction removed')\n if not payload.guild_id:\n #if the reaction was removed in a DM channel with the bot\n #do nothing\n return\n\n guild = client.get_guild(payload.guild_id)\n #need the guild to get the member who reacted\n member = guild.get_member(payload.user_id)\n #get member who will receive the role\n\n #getting roles...\n role1 = discord.utils.get(guild.roles, name=\"Smash Bros\")\n role2 = discord.utils.get(guild.roles, name=\"Fortnite\")\n role3 = discord.utils.get(guild.roles, name=\"Overwatch\")\n role4 = discord.utils.get(guild.roles, name=\"Apex Legends\")\n role5 = discord.utils.get(guild.roles, name=\"Smite\")\n role6 = discord.utils.get(guild.roles, name=\"League of Legends\")\n\n #putting roles in array...\n role_list = [role1, role2, role3,role4,role5,role6]\n\n #reaction emoji ids\n #smash, fortnite, ow, apex, smite, lol\n reaction_list = [544283152886005775,544280152507416618,544289940062732307,544288794820739152,544349301904637954,544349358921875468]\n\n #if the message is the right one...\n if payload.message_id == 548171468777717760:\n #cycle through reaction_list to find the emoji that was removed\n j=0\n while j < len(reaction_list):\n if payload.emoji.id == reaction_list[j]:\n role_removed = role_list[j]\n j += 1\n\n #if the user already belongs to that role\n if role_removed in member.roles:\n #remove the role from the member\n await member.remove_roles(role_removed, reason='Role Menu: Games reaction')\n #send confirmation to member\n await member.send('🚫 || ' + member.mention + ' has been removed from the role ' + '``' + str(role_removed) + '``!')\n #send message to log channel\n await client.get_channel(544340495384576012).send('🚫 || ' + member.mention + ' has been removed from the role ' + '``' + str(role_removed) + '``!')\n\n@client.event\nasync def on_member_join(member):\n #send message in main chat\n await client.get_channel(349593648595206155).send('🐺 || Welcome to the wolfpack' + member.mention + '!')\n\n@client.event\nasync def on_guild_channel_create(channel):\n await client.get_channel(544340495384576012).send('``' + channel.name + '`` channel created in server ``' + channel.guild.name + '``')\n\n@client.event\nasync def on_guild_channel_delete(channel):\n await client.get_channel(544340495384576012).send('``' + channel.name + '`` channel deleted in server ``' + channel.guild.name + '``')\n\n\nclient.run(bot_token)\n","sub_path":"rose8bot-original.py","file_name":"rose8bot-original.py","file_ext":"py","file_size_in_byte":38184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"338988786","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 4 15:12:30 2017\n\n@author: owen\n\"\"\"\n\n# 普通二叉树的两种方法都可以用, BFS + lever order, DFS + preorder\n\n# BST的要求是更紧凑,而且假设没有重复值,The special property of binary search trees compared to general binary trees allows a more compact encoding.\n# DFS + preorder, 不用#占位,省空间\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n \n#class Codec:\n#\n# def serialize(self, root):\n# \"\"\"Encodes a tree to a single string.\n# \n# :type root: TreeNode\n# :rtype: str\n# \"\"\"\n# def preorder(node):\n# if node:\n# vals.append(str(node.val))\n# preorder(node.left)\n# preorder(node.right)\n# \n# vals = []\n# preorder(root) # serialize the tree's values in preorder.\n# return ' '.join(vals)\n#\n# \n# def deserialize(self, data):\n# \"\"\"Decodes your encoded data to tree.\n# \n# :type data: str\n# :rtype: TreeNode\n# \"\"\"\n# preorder = list(map(int, data.split()))\n# inorder = sorted(preorder) # sorting the preorder, then get inorder\n# return self.buildTree(preorder, inorder)\n#\n# \n# def buildTree(self, preorder, inorder): # Construct Binary Tree from Preorder and Inorder Traversal.\n# def build(stop):\n# if inorder and inorder[-1] != stop:\n# root = TreeNode(preorder.pop())\n# root.left = build(root.val)\n# inorder.pop()\n# root.right = build(stop)\n# return root\n# \n# preorder.reverse()\n# inorder.reverse()\n# return build(None)\n \n# https://github.com/kamyu104/LeetCode/blob/master/Python/serialize-and-deserialize-bst.py \nimport collections\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n # time O(n)\n def preorder(node):\n if node: # 空节点不用加#了, 省空间\n vals.append(node.val)\n preorder(node.left)\n preorder(node.right)\n \n vals = []\n preorder(root)\n return \",\".join(map(str, vals)) \n \n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n def build(minVal, maxVal, vals):\n if vals and minVal < vals[0] < maxVal: # 利用先序,第一个节点总是子树的根\n curr = vals.popleft()\n node = TreeNode(curr)\n node.left = build(minVal, curr, vals)\n node.right = build(curr, maxVal, vals)\n return node\n else:\n return None\n \n vals = collections.deque([int(val) for val in data.split(\",\") if val != \"\"]) # [] will be serialized to [\"\"]\n return build(float('-inf'), float('inf'), vals) \n \n\nif __name__==\"__main__\":\n root=TreeNode(5)\n root.left=TreeNode(3)\n root.right=TreeNode(6)\n root.left.left=TreeNode(2)\n root.left.right=TreeNode(4)\n root.right.right=TreeNode(7)\n codec = Codec()\n codec.deserialize(codec.serialize(root))","sub_path":"449. Serialize and Deserialize BST.py","file_name":"449. Serialize and Deserialize BST.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399771217","text":"import math\n\n\"\"\"\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\n\n\ndef is_prime(n):\n for i in range(2, int(math.sqrt(n) + 1) + 2):\n if n % i == 0:\n return False\n return True\n\n\ndef prime_factorization(n):\n # The largest prime factor of a number is 1 plus the floor of the square root of the number + 1\n # Need to account for the fact that python ranges are exclusive of the max, so add 1 more to the max\n factor_list = []\n for i in range(2, int(math.sqrt(n) + 1) + 2):\n if n % i == 0:\n factor_list.append(i)\n prime_set = set(factor_list)\n ret_set = set()\n for i in list(prime_set):\n if is_prime(i):\n ret_set.add(i)\n return ret_set\n\n\nif __name__ == \"__main__\":\n print(max(prime_factorization(600851475143)))\n","sub_path":"python/problem_0003.py","file_name":"problem_0003.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"548866104","text":"import pytesseract\nimport cv2\nimport json\nfrom libs import *\n\nif __name__ == \"__main__\":\n img = cv2.imread('test.png')\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n result = pytesseract.image_to_data(img, lang='eng', nice=0, output_type=pytesseract.Output.DICT)\n print(\"*\"*10)\n\n text = Text()\n for i in range(len(result['text'])):\n text.words.append(Word(\n result['left'][i],\n result['top'][i],\n result['width'][i],\n result['height'][i],\n result['text'][i]\n\n ))\n\n # for key in result.keys():\n # print(f\"length for {key} --> {len(result[key])}\")\n \n #keys = result.keys()\n #print(keys)\n #for i, word in enumerate(result['text']):\n #\n # p = (p := f'{word} has')\n # for key in keys:\n # p = p + f\" {key} = {result[key][i]}\"\n\n # print(p)\n print(text)\n\n\n n_boxes = len(result['text'])\n for i in range(n_boxes):\n if int(result['conf'][i]) > 60:\n (x, y, w, h) = (result['left'][i], result['top'][i], result['width'][i], result['height'][i])\n img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"613370661","text":"import getpass\nimport json\nimport requests\n\nfrom .exceptions import ClientException, ServerException\n\n\nclass Identity(object):\n\n def __init__(self, host, shared_secret=None, port='443', verify=False):\n \"\"\"Creation of ManagementAPI Class object.\n\n :param host: Check Point IA Gateway\n :param port: Check Point Apache Port\n :param shared_secret: IA Shared Secret\n :param verify: Requests Verify SSL\n :type port: string\n \"\"\"\n self.host = host\n self.port = port\n self.shared_secret = shared_secret\n self.verify = verify\n self.request_headers = {\n 'Content-Type': 'application/json',\n }\n\n if not verify:\n requests.packages.urllib3.disable_warnings()\n\n @property\n def url(self):\n \"\"\"Standard URL for all Identity API Calls.\"\"\"\n return 'https://{}:{}/_IA_API/'.format(self.host, self.port)\n\n def _api_call(self, command, **kwargs):\n \"\"\"Backbone method for sending POST to Check Point.\"\"\"\n if not self.shared_secret:\n self.shared_secret = getpass.getpass('Shared Secret >> ')\n kwargs.update({'shared-secret': self.shared_secret})\n try:\n response = requests.post(\n self.url + command,\n data=json.dumps(kwargs),\n headers=self.request_headers,\n timeout=(15, 300),\n verify=self.verify)\n except requests.exceptions.RequestException as e:\n return 'Connection Failure: {}'.format(type(e).__name__)\n if str(response.status_code)[0] == '2':\n return response.json()\n elif str(response.status_code)[0] == '4':\n raise ClientException('Client side error.', response)\n elif str(response.status_code)[0] == '5':\n raise ServerException('Server side error.', response)\n\n def add(self, **kwargs):\n return self._api_call('add-identity', **kwargs)\n\n def delete(self, **kwargs):\n return self._api_call('delete-identity', **kwargs)\n\n def show(self, **kwargs):\n return self._api_call('show-identity', **kwargs)\n","sub_path":"cpapilib/Identity.py","file_name":"Identity.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17113224","text":"import re\n\nfrom django.http import Http404\n\n\ndef message_or_404(mailbox, item_id):\n try:\n return mailbox[int(item_id)]\n except (ValueError, KeyError):\n raise Http404\n\n\ndef get_text(parsed_message):\n def filter_content_type(start):\n return lambda part: part['Content-Type'].startswith(start)\n\n text_parts = list(filter(filter_content_type('text'), parsed_message))\n content_types = (part['Content-Type'] for part in text_parts)\n\n if 'text/html' in content_types:\n text_parts = filter(filter_content_type('text/html'), text_parts)\n\n return ' '.join(part['Payload'] for part in text_parts)\n\n\ndef parse_message(item, message):\n return {\n 'id': item,\n 'subject': message['Subject'] if 'Subject' in message else '',\n 'from': message['From'] if 'From' in message else '',\n 'to': message['To'] if 'To' in message else message['X-Original-To'] if 'X-Original-To' in message else '',\n 'text': get_text(parse_payload(message)),\n }\n\n\ndef parse_payload(message):\n if message.is_multipart():\n return (part for part in (parse_part(part) for part in message.get_payload()) if part)\n else:\n return [parse_part(message)]\n\n\ndef parse_part(part):\n if 'Content-Type' in part:\n content_type = part['Content-Type']\n else:\n content_type = 'text/plain'\n\n match = re.match(r'^([^;]+)(?:;|$)', content_type)\n\n if match:\n return {\n 'Content-Type': match.group(1),\n 'Payload': part.get_payload(),\n }\n else:\n return None","sub_path":"mail/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365132525","text":"import numpy as np\nimport pandas as pd\n\n\nclass Evaluator(object):\n def __init__(self, pop_size, config):\n self.config = config\n self.pop_size = pop_size\n self.count = 0\n\n def evaluate_population(self, population):\n for chromosome in population.chromosome_list:\n self.evaluate_chromosome_with_cycle_opt(chromosome)\n # self.evaluate_chromosome(chromosome)\n population.sort_population() # ascending order\n\n def evaluate_chromosome(self, chromosome):\n travel_time = 0.0\n for cycle_order in range(self.config.cycle_num):\n location_assignment_seq_at_cycle = chromosome.get_location_assignment_sequence_at_cycle(cycle_order)\n temp_travel_time = self.evaluate_cycle(location_assignment_seq_at_cycle)\n travel_time += temp_travel_time\n chromosome.fitness = travel_time\n\n def compute_chromosome_fit(self, chromosome):\n travel_time = 0.0\n for cycle_order in range(self.config.cycle_num):\n location_assignment_seq_at_cycle = chromosome.get_location_assignment_sequence_at_cycle(cycle_order)\n temp_travel_time = self.evaluate_cycle(location_assignment_seq_at_cycle)\n travel_time += temp_travel_time\n # print temp_travel_time\n return travel_time\n\n def evaluate_chromosome_with_cycle_opt(self, chromosome):\n self.count += 1\n travel_time = 0.0\n # print \"cycles to evaluate: \" + str(chromosome.cycle_to_evaluate)\n for cycle_order in range(self.config.cycle_num):\n if cycle_order in chromosome.cycle_to_evaluate:\n best_fit_at_cycle = None\n best_sequencing_info = None\n original_fit_at_cycle = None\n\n cycle_idx = chromosome.sequence.cycle_idx_list[cycle_order]\n cycle = chromosome.sequence.cycles.get(cycle_idx)\n original_input_reversed = chromosome.input_reversed_or_not_at_cycles[cycle_order]\n original_output_reversed = chromosome.output_reversed_or_not_at_cycles[cycle_order]\n original_srsr_or_not = chromosome.srsr_or_not_at_cycles[cycle_order]\n original_sequencing_info = (original_input_reversed, original_output_reversed, original_srsr_or_not)\n\n for i in range(0, 2):\n for j in range(0, 2):\n for k in range(0, 2):\n op_idx_seq = chromosome.get_op_index_sequence_at_cycle_from_info(cycle, i, j, k)\n loc_seq = chromosome.get_location_assignment_sequence_at_cycle_from_op_idx_sequence(op_idx_seq)\n if chromosome.check_feasibility_of_op_idx_seq(op_idx_seq, loc_seq, cycle_order):\n temp_fit = self.evaluate_cycle(loc_seq)\n if i == original_input_reversed and j == original_output_reversed and k == original_srsr_or_not:\n original_fit_at_cycle = temp_fit\n else:\n if best_fit_at_cycle is None:\n best_fit_at_cycle = temp_fit\n best_sequencing_info = (i, j, k)\n else:\n if temp_fit < best_fit_at_cycle:\n best_fit_at_cycle = temp_fit\n best_sequencing_info = (i, j, k)\n if not(best_fit_at_cycle is None):\n if best_fit_at_cycle < original_fit_at_cycle:\n chromosome.update_after_sequence_change(original_sequencing_info, best_sequencing_info, cycle_order)\n chromosome.input_reversed_or_not_at_cycles[cycle_order] = best_sequencing_info[0]\n chromosome.output_reversed_or_not_at_cycles[cycle_order] = best_sequencing_info[1]\n chromosome.srsr_or_not_at_cycles[cycle_order] = best_sequencing_info[2]\n travel_time += best_fit_at_cycle\n chromosome.cycle_fit[cycle_order] = best_fit_at_cycle\n # print \"better\", best_fit_at_cycle\n # print \"better\", cycle_order, chromosome.cycle_fit[cycle_order]\n else:\n chromosome.cycle_fit[cycle_order] = original_fit_at_cycle\n travel_time += original_fit_at_cycle\n # print \"original\", original_fit_at_cycle\n # print \"original\", original_fit_at_cycle\n else:\n chromosome.cycle_fit[cycle_order] = original_fit_at_cycle\n travel_time += original_fit_at_cycle\n # print \"original\", original_fit_at_cycle\n # print \"original\", chromosome.cycle_fit[cycle_order]\n # print str(chromosome.cycle_fit)\n else:\n travel_time += chromosome.cycle_fit[cycle_order]\n # print \"not to evaluate\", chromosome.cycle_fit[cycle_order]\n chromosome.fitness = travel_time\n chromosome.cycle_to_evaluate = []\n\n def evaluate_cycle(self, location_assignment_sequence):\n travel_time = 0.\n # print str(location_assignment_sequence)\n for i in range(len(location_assignment_sequence)-1):\n horizontal_distance = abs(location_assignment_sequence[i+1][1] - location_assignment_sequence[i][1])\n vertical_distance = abs(location_assignment_sequence[i+1][2] - location_assignment_sequence[i][2])\n temp_travel_time = max(horizontal_distance * self.config.horizontal_travel_time_per_unit,\n vertical_distance * self.config.vertical_travel_time_per_unit)\n travel_time += temp_travel_time\n # print \"(%s, %s) => (%s, %s)\" % (location_assignment_sequence[i][1], location_assignment_sequence[i][2],\n # location_assignment_sequence[i+1][1], location_assignment_sequence[i+1][2])\n # print \"h: %s, v: %s => travel time: %s\" % (horizontal_distance, vertical_distance, temp_travel_time)\n # print travel_time\n return travel_time\n\n\nclass EvaluatorASRS(object):\n pop_size = 0\n config = None\n\n # travel time parameters\n vertical_unit_distance = 1.5\n horizontal_unit_distance = 0.4\n\n whole_path_array = None\n rest_index = None\n from_index = None\n to_index = None\n\n def __init__(self, population, config):\n self.pop_size = len(population.chromosome_list)\n self.config = config\n\n start_index = np.arange(config.cycle_num) * 6\n end_index = np.arange(config.cycle_num) * 6 + 5\n rest_index = np.arange(config.total_request_length + config.cycle_num * 2)\n rest_index = np.setdiff1d(rest_index, start_index)\n rest_index = np.setdiff1d(rest_index, end_index)\n self.from_index = np.arange(config.total_request_length + config.cycle_num * 2 - 1)\n self.to_index = self.from_index + 1\n self.rest_index = rest_index\n self.whole_path_array = np.full((config.total_request_length + config.cycle_num * 2, 2), -1)\n self.whole_path_array[start_index] = np.array([-1, 0])\n self.whole_path_array[end_index] = np.array([-1, 0])\n # self.whole_path_array[end_index] = np.array([-1, 2])\n\n def evaluate_population(self, population):\n for chromosome in population.chromosome_list:\n self.evaluate_chromosome(chromosome)\n population.sort_chromosomes() # ascending order\n\n def evaluate_chromosome(self, chromosome):\n path_array = np.zeros((self.config.cycle_num, self.config.cycle_length + 2, 2), dtype=np.int32)\n path_array[:, 1:5] = chromosome.location_array[:, :, 1:]\n path_array[:, 0] = np.array([-1, 0])\n path_array[:, 5] = np.array([-1, 2])\n\n to_index = np.arange(1, self.config.cycle_length + 1)\n from_index = np.arange(0, self.config.cycle_length)\n dist_array = np.abs(path_array[:, to_index] - path_array[:, from_index])\n travel_time_arr = np.maximum(dist_array[:, :, 0] * self.horizontal_unit_distance,\n dist_array[:, :, 1] * self.vertical_unit_distance, dtype=np.float64)\n chromosome.fitness = travel_time_arr.sum() + self.config.total_request_length * 2\n\n def evaluate_population_with_pandas(self, population):\n for chromosome in population.chromosome_list:\n self.evaluate_chromosome_with_pandas(chromosome)\n population.sort_chromosomes() # ascending order\n\n def evaluate_chromosome_with_pandas(self, chromosome):\n # print \"currrent chromosome\"\n # print chromosome.operation_array\n path_array = chromosome.operation_array[['y', 'z']]\n # print path_array\n self.whole_path_array[self.rest_index] = path_array\n # print self.whole_path_array\n\n dist_array = np.abs(self.whole_path_array[self.to_index] - self.whole_path_array[self.from_index])\n # print dist_array\n travel_time_arr = np.maximum(dist_array[:, 0] * self.horizontal_unit_distance,\n dist_array[:, 1] * self.vertical_unit_distance, dtype=np.float64)\n chromosome.fitness = travel_time_arr.sum() + self.config.total_request_length * 2\n # print chromosome.fitness\n # print \"\"\n\n\ndef get_closest_locations(current_location_tuple, list_of_tuples, next_location=None):\n distance_array = compute_distances_from_list(current_location_tuple, list_of_tuples, next_location)\n min_distance = distance_array.min()\n filtered_array = np.array(list_of_tuples)\n filtered_array = filtered_array[distance_array == min_distance]\n filtered_list = []\n for j in range(len(filtered_array)):\n temp_array = filtered_array[j]\n filtered_list.append((temp_array[0], temp_array[1], temp_array[2]))\n return filtered_list\n\n\ndef get_roulette_array_from_feasible_locations(distance_prefer_constant, current_location_tuple,\n list_of_tuples, next_location=None):\n distance_array = compute_distances_from_list(current_location_tuple, list_of_tuples, next_location)\n\n # print \"distances\"\n # for i in range(len(distance_array)):\n # print \"index %d : %f distance\" % (i, distance_array[i])\n # print \" \"\n\n # print \"rankings ascending order\"\n # for i in range(len(distance_rank)):\n # print \"index %d : %f rank\" % (i, distance_rank[i])\n # print \" \"\n\n max_distance = distance_array.max()\n min_distance = distance_array.min()\n\n if max_distance > min_distance:\n roulette_array = max_distance - distance_array + 0.4\n # roulette_array = (max_distance - min_distance) / (constant - 1) + max_distance - distance_array\n roulette_array **= distance_prefer_constant\n else:\n roulette_array = distance_array\n roulette_array = roulette_array.cumsum()\n roulette_sum = roulette_array[-1]\n roulette_array /= roulette_sum\n\n # print \"roulette array\"\n # for i in range(len(roulette_array)):\n # print \"index %d : %f roulette_fit\" % (i, roulette_array[i])\n # print \"\"\n\n return roulette_array\n\n\ndef get_gain_of_swap_array(chromosome, current_location_tuple, original_tuple, swapable_dic, next_location=None):\n list_of_tuples = swapable_dic.values()\n # print \"array of tuples : \" + array_of_tuples.__str__()\n current_distance = compute_distance_one_operation(current_location_tuple, original_tuple, next_location)\n # print \"current distance : \" + str(current_distance)\n current_distance_array = compute_distance_operations(chromosome, swapable_dic) + current_distance\n # print \"distance array : \" + current_distance_array.__str__()\n swapped_distance_array = compute_distances_from_list(current_location_tuple, list_of_tuples, next_location)\n # print \"swapped array : \" + swapped_distance_array.__str__()\n swapped_distance_array += compute_distance_not_fixed_from_and_to(chromosome,\n original_tuple, swapable_dic)\n # print \"swapped array : \" + swapped_distance_array.__str__()\n swapped_distance_array -= current_distance_array\n # print \"swapped array : \" + swapped_distance_array.__str__() + \"\\n\"\n return swapped_distance_array\n\n\ndef get_gain_of_single_swap(chromosome, current_location_tuple, original_tuple, next_location, index,\n swap_index, swap_location_tuple):\n swap_current_location = chromosome.get_prev_operation_location_tuple(swap_index[0], swap_index[1], swap_index[2])\n swap_next_location = chromosome.get_next_operation_location_tuple(swap_index[0], swap_index[1], swap_index[2])\n\n before_original_distance = 0\n before_swap_distance = 0\n after_original_distance = 0\n after_swap_distance = 0\n\n if index[0] == swap_index[0] and abs(index[1] - swap_index[1]) <= 1:\n if index[1] < swap_index[1]:\n before_original_distance = compute_distance_one_operation(current_location_tuple, original_tuple)\n before_swap_distance = compute_distance_one_operation(swap_location_tuple, swap_next_location)\n after_original_distance = compute_distance_one_operation(current_location_tuple, swap_location_tuple)\n after_swap_distance = compute_distance_one_operation(original_tuple, swap_next_location)\n elif index[1] > swap_index[1]:\n before_original_distance = compute_distance_one_operation(swap_current_location, swap_location_tuple)\n before_swap_distance = compute_distance_one_operation(original_tuple, next_location)\n after_original_distance = compute_distance_one_operation(swap_current_location, original_tuple)\n after_swap_distance = compute_distance_one_operation(swap_location_tuple, next_location)\n else:\n before_original_distance = compute_distance_one_operation(current_location_tuple, original_tuple, next_location)\n before_swap_distance = compute_distance_one_operation(swap_current_location,\n swap_location_tuple, swap_next_location)\n after_original_distance = compute_distance_one_operation(current_location_tuple,\n swap_location_tuple, next_location)\n after_swap_distance = compute_distance_one_operation(swap_current_location,\n original_tuple, swap_next_location)\n before_distance = before_original_distance + before_swap_distance\n after_distance = after_original_distance + after_swap_distance\n\n gain = before_distance - after_distance\n # print \"before original : \" + str(before_original_distance)\n # print \"before swapable : \" + str(before_swap_distance)\n # print \"before distance : \" + str(before_distance)\n # print \"after original : \" + str(after_original_distance)\n # print \"after swapable : \" + str(after_swap_distance)\n # print \"after distance : \" + str(after_distance)\n # print \"gain : \" + str(gain) + \"\\n\"\n return gain\n\n\ndef get_roulette_array_from_swapable_locations(distance_prefer_constant, chromosome, current_location_tuple,\n original_tuple, swapable_dic, next_location=None):\n swapped_distance_array = get_gain_of_swap_array(chromosome, current_location_tuple,\n original_tuple, swapable_dic, next_location)\n # print \"distances\"\n # for i in range(len(distance_array)):\n # print \"index %d : %f distance\" % (i, distance_array[i])\n # print \" \"\n\n # print \"rankings ascending order\"\n # for i in range(len(distance_rank)):\n # print \"index %d : %f rank\" % (i, distance_rank[i])\n # print \" \"\n\n max_distance = swapped_distance_array.max()\n min_distance = swapped_distance_array.min()\n\n if max_distance > min_distance:\n roulette_array = max_distance - swapped_distance_array + 0.4\n # roulette_array = (max_distance - min_distance) / (constant - 1) + max_distance - distance_array\n roulette_array **= distance_prefer_constant\n else:\n roulette_array = swapped_distance_array\n roulette_array = roulette_array.cumsum()\n roulette_sum = roulette_array[-1]\n roulette_array /= roulette_sum\n\n # print \"roulette array\"\n # for i in range(len(roulette_array)):\n # print \"index %d : %f roulette_fit\" % (i, roulette_array[i])\n # print \"\"\n\n return roulette_array\n\n\ndef compute_distance_not_fixed_from_and_to(chromosome, original_tuple, swapable_dic):\n count = len(swapable_dic)\n distance_array = np.zeros(count, dtype=np.float64)\n for i in range(count):\n index = swapable_dic.keys()[i]\n current_location_tuple = chromosome.get_prev_operation_location_tuple(index[0], index[1], index[2])\n next_location_tuple = chromosome.get_next_operation_location_tuple(index[0], index[1], index[2])\n distance_array[i] = compute_distance_one_operation(current_location_tuple,\n original_tuple, next_location_tuple)\n return distance_array\n\n\ndef compute_distances_from_list(current_location_tuple, list_of_tuples, next_location_tuple=None):\n vertical_unit_distance = 1.5\n horizontal_unit_distance = 0.4\n\n array_of_locations = np.array(list_of_tuples, dtype=np.float64)\n distance_array = np.maximum(np.abs(array_of_locations[:, 1] - current_location_tuple[1]) * horizontal_unit_distance,\n np.abs(array_of_locations[:, 2] - current_location_tuple[2]) * vertical_unit_distance)\n if not(next_location_tuple is None):\n distance_array += np.maximum(np.abs(array_of_locations[:, 1] - next_location_tuple[1]) * horizontal_unit_distance,\n np.abs(array_of_locations[:, 2] - next_location_tuple[2]) * vertical_unit_distance)\n return distance_array\n\n\ndef compute_distances_from_array(current_location_tuple, array_of_locations, next_location_tuple=None):\n vertical_unit_distance = 1.5\n horizontal_unit_distance = 0.4\n\n distance_array = np.maximum(np.abs(array_of_locations[:, 1] - current_location_tuple[1]) * horizontal_unit_distance,\n np.abs(array_of_locations[:, 2] - current_location_tuple[2]) * vertical_unit_distance)\n if not(next_location_tuple is None):\n distance_array += np.maximum(np.abs(array_of_locations[:, 1] - next_location_tuple[1]) * horizontal_unit_distance,\n np.abs(array_of_locations[:, 2] - next_location_tuple[2]) * vertical_unit_distance)\n return distance_array\n\n\ndef compute_distance_operations(chromosome, index_location_dic):\n distance_array = np.zeros(len(index_location_dic), dtype=np.float64)\n for i in range(len(index_location_dic)):\n index = index_location_dic.keys()[i]\n current_location_tuple = chromosome.get_prev_operation_location_tuple(index[0], index[1], index[2])\n next_location_tuple = chromosome.get_next_operation_location_tuple(index[0], index[1], index[2])\n distance_array[i] = compute_distance_one_operation(current_location_tuple,\n index_location_dic.get(index), next_location_tuple)\n return distance_array\n\n\ndef compute_distance_one_operation(current_location_tuple, location_tuple, next_location_tuple=None):\n vertical_unit_distance = 1.5\n horizontal_unit_distance = 0.4\n\n if next_location_tuple is None:\n distance = max(abs(location_tuple[1] - current_location_tuple[1]) * horizontal_unit_distance,\n abs(location_tuple[2] - current_location_tuple[2]) * vertical_unit_distance)\n else:\n distance = max(abs(location_tuple[1] - current_location_tuple[1]) * horizontal_unit_distance,\n abs(location_tuple[2] - current_location_tuple[2]) * vertical_unit_distance)\n distance += max(abs(location_tuple[1] - next_location_tuple[1]) * horizontal_unit_distance,\n abs(location_tuple[2] - next_location_tuple[2]) * vertical_unit_distance)\n return distance\n\n\ndef compute_gain_of_locations(current_location_tuple, location_tuple, next_location_tuple, feasible_locations):\n current_distance\\\n = compute_distance_one_operation(current_location_tuple, location_tuple, next_location_tuple)\n distance_array = compute_distances_from_array(current_location_tuple, feasible_locations, next_location_tuple)\n gain_array = current_distance - distance_array\n return gain_array\n\n\ndef get_gain_of_single_location_change(current_location_tuple, location_tuple, next_location_tuple, swap_location):\n current_distance\\\n = compute_distance_one_operation(current_location_tuple, location_tuple, next_location_tuple)\n new_distance = compute_distance_one_operation(current_location_tuple, swap_location, next_location_tuple)\n gain = current_distance - new_distance\n\n # print \"current distance : \" + str(current_distance)\n # print \"new distance : \" + str(new_distance)\n # print \"gain : \" + str(gain)\n return gain","sub_path":"GA/genetic_operator/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":21422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"224854703","text":"#!/usr/bin/python\n# _*_ coding:utf-8 _*_\n\n#author:Hongrui\n#date: 2019/02/11\n\nimport os,copy,sys\nimport testlink\nimport xlrd\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nfrom xlutils.copy import copy\nfrom Log_util import Logger\n\nlog = Logger().console_log(os.path.basename(__file__))\n\n#从testlink上导出指定的用例集,将数据保持到datas列表中\n#father_id为用例集的APIID\n#列表元素包括:用例名,摘要,预置条件,操作步骤,期望结果,重要性以及测试方式\ndef download_case():\n log.info(u'开始下载用例')\n\n suits_name = get_suites(father_id)['name']\n log.info(u'指定的用例集名称为:' + suits_name.encode('utf-8'))\n\n datas = []\n for data in tls.getTestCasesForTestSuite(father_id,True,'full'):\n actions = []\n expected_results = []\n case_name = data['name']\n summary = data['summary'].replace('

','').replace('

','')\n preconditions = data['preconditions'].replace('

','').replace('

','')\n importance = data['importance']\n execution_type = data['execution_type']\n author = data['author_id']\n\n for i in range(len(data['steps'])):\n step_number = data['steps'][i]['step_number']\n #actions.append(step_number+'.'+data['steps'][i]['actions'].replace('

','').replace('

',''))\n actions.append(data['steps'][i]['actions'].replace('

', '').replace('

', ''))\n expected_result = data['steps'][i]['expected_results']\n if expected_result == '':\n expected_results.append(expected_result)\n else:\n #expected_results.append(step_number+'.'+expected_result.replace('

','').replace('

',''))\n expected_results.append(expected_result.replace('

', '').replace('

', ''))\n datas.append((case_name,summary,preconditions,'\\n'.join(actions),'\\n'.join(expected_results),execution_type,importance,author))\n\n log.info(u'下载数据完毕,开始执行格式转换')\n save_suites(os.path.join('testCase','download_template.xls'),datas,father_id)\n\n\n#将datas中的数据解析并保持到excel中\ndef save_suites(file_path,datas,father_id):\n #获取当前用例集的名字\n suits_name = get_suites(father_id)['name']\n\n #读取excel模版\n book = xlrd.open_workbook(file_path,formatting_info=True)\n #复制读取的excel\n new_book = copy(book)\n\n #读取复制的excel的第一个sheet\n sheet = new_book.get_sheet(0)\n #默认第一行已经写好数据\n line_num = 1\n\n# print len(datas)\n #逐个读取datas列表的数据,并根据指定的行和列,写入到excel单元格中\n for i in range(0,len(datas)):\n case_name,summary,preconditions,actions,expected_results,execution_type,importance,author = datas[i]\n #print case_name,preconditions,actions,expected_results,execution_type,author,importance,summary\n\n sheet.write(line_num,0,u'%s'%case_name)\n sheet.write(line_num, 1, u'%s' % summary)\n sheet.write(line_num, 2, u'%s' % preconditions)\n sheet.write(line_num, 3, u'%s' % actions)\n sheet.write(line_num, 4, u'%s' % expected_results)\n sheet.write(line_num, 5, u'%s' % execution_type)\n sheet.write(line_num, 6, u'%s' % importance)\n sheet.write(line_num, 7, u'%s' % author)\n\n\n line_num += 1\n\n log.info(u'用例集_<%s>中总共有<%d>条用例'%(suits_name.encode('utf-8'),line_num-1))\n #设置导出的excel的保存目录\n report_path = os.path.abspath(os.path.join('download'))\n# print 'report_path is:',report_path\n if not os.path.exists(report_path):\n os.makedirs(report_path)\n\n\n # temp = os.path.abspath(os.path.join(report_path, suits_name))\n # print temp\n\n #将用例集下的所有用例保存为以用例集命名的xls文档中\n log.info(u'开始保存用例')\n try:\n new_book.save(os.path.abspath(os.path.join(report_path, suits_name+'.xls')))\n except Exception as e:\n log.error(u'保存用例失败',str(e))\n sys.exit()\n else:\n log.info(u'导出用例成功,存放地址为:'+ report_path)\n\n\ndef get_suites(suite_id):\n\n try:\n suites = tls.getTestSuiteByID(suite_id)\n return suites\n except testlink.testlinkerrors.TLResponseError as e:\n# print str(e).split('\\n')[1]\n log.warning(str(e).split('\\n')[1])\n log.warning(str(e).split('\\n')[0])\n sys.exit()\n\nif __name__==\"__main__\":\n url = 'http://10.255.101.237/lib/api/xmlrpc/v1/xmlrpc.php'\n\n #登陆testlink后点击上方个人账号进入个人中心,新页面点击 '生成新的秘钥',使用该key替换掉upload_excel_data.py文件中的key值\n key = '502b4a3cd51f3385b013c0da257d5eeb'\n tls = testlink.TestlinkAPIClient(url, key)\n #要下载的用例集的ID,可通过在testlink界面选取用例集,然后点击右键获取\n father_id = raw_input(u'请输入测试用例集ID:')\n #father_id = \"4\"\n log.info(u'开始执行脚本')\n download_case()\n","sub_path":"download_single_test_suite.py","file_name":"download_single_test_suite.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"468774143","text":"#!/usr/bin/env python\n\n'''\nBasic testing handler: if we enter one state, go to the other state and play a sound\n'''\n\nfrom taskontrol.core import pystatematrix as sm\n\ndef otherstate(pin):\n names = ['state1', 'state2']\n pins = ['a', 'k']\n newname = None\n newpin = None\n if pin == pins[0]:\n newname = names[1]\n newpin = pins[1]\n else:\n newname = names[0]\n newpin = pins[0]\n print('We are now in state {}'.format(newname))\n return(newname,newpin)\n\n\ndef make_test_mat():\n testmat = sm.StateMatrix()\n testmat.add_state('state1',otherstate,start_state=1)\n testmat.add_state('state2',otherstate)\n return testmat\n\ndef run_test_mat():\n testmat = make_test_mat()\n nextstate = None\n nextpin = None\n handler = testmat.handlers[testmat.startState]\n while True:\n uin = raw_input('\\n a or k? >')\n nextstate, nextpin = handler(uin)\n handler = testmat.handlers[nextstate]\n\n","sub_path":"templates/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"361787001","text":"# pypy 통과\n# python3 시간초과\nimport sys\nsys.stdin=open('../input.txt','r')\n\nfor t in range(int(input())):\n w,h=map(int,input().split())\n fire=[]\n building=[]\n now=[]\n ans='IMPOSSIBLE'\n for i in range(h):\n building.append([*input()])\n for j in range(w):\n if building[i][j]=='*':\n fire.append((i,j))\n if building[i][j]=='@':\n building[i][j]='X'\n now.append((i,j))\n\n dy=[0,0,1,-1]\n dx=[1,-1,0,0]\n cnt=0\n z=0\n while now:\n new_fire=[]\n new_now=[]\n for a in fire:\n i,j=a\n for k in range(4):\n ni,nj=i+dy[k],j+dx[k]\n if -1 \n# = path to protein fasta file\n# = sequence identity threshold. A number between 0 and 1.\n\n# python imports\nimport sys\n\n# import the subprocess module\nimport subprocess\n\n\n#\n# Step 1: Run cd-hit on a protein sequences file.\n#\n\n# Grab the command line arguments\nfasta = sys.argv[1]\nidentity_threshold = sys.argv[2] # Note: Python will treat this variable as a string not a float. This is okay for this script because we're not doing any math with this variable. If we were, we'd need to identity_threshold = float(sys.argv[2]).\n\n# Run cd-hit\n# The usage for running cd-hit is:\n# cd-hit -i -o -c \n\n# Create a variable called cd_hit_fasta_output to store the output fasta filename. Call the output file clustered__. For example, if identity_threshold = 0.8 and fasta = \"protein.faa\", then call the file clustered_0.8_protein.faa\"\ncd_hit_fasta_output = \"clustered_\" + identity_threshold + \"_\" + fasta\n# Use subprocess.call to run the cd-hit command\nsubprocess.call([\"cd-hit\", \"-i\", fasta, \"-o\", cd_hit_fasta_output, \"-c\", identity_threshold])\n\n#\n# Step 2: Run a cd-hit tool called clstr_size_stat.pl to calculate the distribution of cluster sizes\n#\n\n# The usage for running clstr_size_stat.pl is:\n# clstr_size_stat.pl cluster_file\n# Note 1: clstr_size_stat.pl writes to stdout. We want to save this text to a file. Subprocess.call can do this for us as long as we give it a file object to store the text in.\n# Note 2: the cluster_file was produced in step 1.\n\n# Create a variable called cd_hit_cluster_output to store the cluster output filename. cd-hit called this file .clstr. For example, if cd_hit_fasta_output = \"clustered_0.8_protein.faa\", the cluster file will be \"clustered_0.8_protein.faa.clstr\"\ncd_hit_cluster_output = cd_hit_fasta_output + \".clstr\"\n\n# Create a variable called cluster_size_output to store the cluster size output filename. Let's call this file .size. For example, if cd_hit_cluster_output = clustered_0.8_protein.faa.clstr, the size file will be clustered_0.8_protein.faa.clstr.size\ncluster_size_output = cd_hit_cluster_output + \".size\"\n\n# Use subprocess.call to run the clstr_size_stat.pl command\n# Since we're going to save the stdout to a file, the syntax for subprocess.call is:\n# subprocess.call(list_of_arguments, stdout=file_object)\n# Create a file object for the output file using open. Make sure you open the file for writing.\ncluster_size_output_file_object = open(cluster_size_output, \"w\")\n# Call subprocess\nsubprocess.call([\"clstr_size_stat.pl\", cd_hit_cluster_output], stdout=cluster_size_output_file_object)\n# Close the file object.\ncluster_size_output_file_object.close()\n\n\n#\n# Step 3: Run plot_clster_size.py to plot the distribution of cluster sizes\n#\n\n# The usage for running plot_clster_size.py is:\n# python3 plot_clster_size.py \n# Use subprocess.call to run the Python script\nsubprocess.call([\"python3\", \"plot_cluster_size.py\", cluster_size_output])\n","sub_path":"python/lessons/cd_hit_wrapper-solution.py","file_name":"cd_hit_wrapper-solution.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"577678206","text":"# -*- coding:utf-8 -*-\n# author:臧海彬\n# function:一些工具函数\n\nimport os\nimport sys\n\n# 判断name是否存在,如果存在则获取一个不存在的name名称\ndef getName(name):\n name = name.split(\".\")\n if len(name) == 1:\n firstName = name[0]\n lastName = \"\"\n elif len(name) > 1:\n lastName = \".\"+name[-1]\n firstName = \".\".join(name[:-1])\n else:\n return False\n\n # 寻找一个不存在的文件名称\n order = \"\"\n while True:\n if os.path.exists(firstName+order+lastName):\n if order == \"\":\n order = \"_1\"\n else:\n order = \"_\" + str(int(order[1:]) + 1)\n else:\n break\n return firstName + order + lastName\n\n# 暂停在命令行界面等待回车然后退出\ndef stopExit():\n input(\"输入回车退出...\")\n sys.exit()\n","sub_path":"modules/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"640859403","text":"import multiprocessing\nfrom utils_rl.memory_dataset import Memory, merge_context\nfrom utils_rl.torch_ut import *\nimport time\nfrom collections import namedtuple\nfrom torch.distributions import Normal\nimport gpytorch\n\nTransition = namedtuple('Transition', ('state', 'action', 'next_state',\n 'reward', 'mean', 'stddev', 'disc_rew', 'covariance'))\n\ndef collect_samples(pid, env, policy, custom_reward, mean_action, render,\n running_state, context_points_list, attention, fixed_sigma):\n # (2)\n torch.randn(pid)\n log = dict()\n memory = Memory() # every time we collect a batch he memory is re-initialized\n num_steps = 0\n total_reward = 0\n min_reward = 1e6\n max_reward = -1e6\n total_c_reward = 0\n min_c_reward = 1e6\n max_c_reward = -1e6\n num_episodes = 0\n action_sum = zeros(context_points_list[0][1].shape[-1])\n\n\n with torch.no_grad():\n for ep in range(len(context_points_list)):\n all_x_context_list = [context_points_list[0][0][:,[0],:]]\n all_y_context_list = [context_points_list[0][1][:,[0],:]]\n episode = []\n reward_episode = 0\n state = env.reset()\n if running_state is not None:\n state = running_state(state)\n t_ep = time.time()\n for t in range(10000):\n all_x_context = torch.cat(all_x_context_list, dim=1)\n all_y_context = torch.cat(all_y_context_list, dim=1)\n state_var = tensor(state).unsqueeze(0).unsqueeze(0)\n if policy.id == 'DKL':\n with gpytorch.settings.use_toeplitz(True), gpytorch.settings.fast_pred_var():\n pi = policy(state_var)\n mean = pi.mean\n stddev = pi.stddev\n if torch.isnan(stddev):\n print(stddev)\n elif policy.id == 'MI':\n mean = policy(all_x_context, all_y_context, state_var)\n stddev = fixed_sigma\n else:\n if attention:\n pi = policy(all_x_context, all_y_context, state_var)\n mean = pi.mean\n stddev = pi.stddev\n else:\n pi = policy(all_x_context, all_y_context, state_var)\n mean = pi.mean\n stddev = pi.stddev\n if fixed_sigma is not None:\n sigma = fixed_sigma\n else:\n sigma = stddev\n\n action_distribution = Normal(mean, sigma)\n\n if mean_action:\n action = mean # use mean value\n mean, stddev = policy.xz_to_y(state_var, z_dist.mean)\n else:\n action = action_distribution.sample().view(-1) # sample from normal distribution\n cov = torch.diag(sigma**2)\n next_state, reward, done, _ = env.step(action.cpu())\n reward_episode += reward\n if running_state is not None: # running list of normalized states allowing to access precise mean and std\n next_state = running_state(next_state)\n if custom_reward is not None: # by default is None, unless given when init Agent\n reward = custom_reward(state, action)\n total_c_reward += reward\n min_c_reward = min(min_c_reward, reward)\n max_c_reward = max(max_c_reward, reward)\n if any(torch.isnan(state_var.view(-1))) or any(torch.isnan(action.view(-1))) or any(torch.isnan(mean.view(-1))):\n print('wat')\n all_x_context_list.append(state_var)\n all_y_context_list.append(mean)\n episode.append(Transition(state, action.cpu().numpy(), next_state, reward, mean.cpu().numpy(),\n sigma.cpu().numpy(), None, cov))\n action_sum += action\n if render:\n env.render()\n if done:\n memory.push(episode)\n break\n\n state = next_state\n # log stats\n num_steps += (t + 1)\n num_episodes += 1\n total_reward += reward_episode\n min_reward = min(min_reward, reward_episode)\n max_reward = max(max_reward, reward_episode)\n\n log['num_steps'] = num_steps\n log['num_episodes'] = num_episodes\n log['total_reward'] = total_reward\n try:\n log['avg_reward'] = total_reward.item() / num_episodes\n except AttributeError:\n log['avg_reward'] = total_reward / num_episodes\n log['max_reward'] = max_reward\n log['min_reward'] = min_reward\n log['action_mean'] = action_sum / num_steps\n if custom_reward is not None:\n log['total_c_reward'] = total_c_reward\n log['avg_c_reward'] = total_c_reward / num_steps\n log['max_c_reward'] = max_c_reward\n log['min_c_reward'] = min_c_reward\n\n return memory, log\n\n\n\ndef merge_log(log_list):\n log = dict()\n log['total_reward'] = sum([x['total_reward'] for x in log_list])\n log['num_episodes'] = sum([x['num_episodes'] for x in log_list])\n log['num_steps'] = sum([x['num_steps'] for x in log_list])\n log['avg_reward'] = log['total_reward'] / log['num_episodes']\n log['max_reward'] = max([x['max_reward'] for x in log_list])\n log['min_reward'] = min([x['min_reward'] for x in log_list])\n if 'total_c_reward' in log_list[0]:\n log['total_c_reward'] = sum([x['total_c_reward'] for x in log_list])\n log['avg_c_reward'] = log['total_c_reward'] / log['num_steps']\n log['max_c_reward'] = max([x['max_c_reward'] for x in log_list])\n log['min_c_reward'] = min([x['min_c_reward'] for x in log_list])\n\n return log\n\n\nclass Agent_all_ctxt:\n\n def __init__(self, env, policy, device, custom_reward=None, attention=False,\n mean_action=False, render=False, running_state=None, fixed_sigma=None):\n self.env = env\n self.policy = policy\n self.device = device\n self.custom_reward = custom_reward\n self.mean_action = mean_action\n self.running_state = running_state\n self.render = render\n self.attention = attention\n self.fixed_sigma = fixed_sigma\n\n def collect_episodes(self, context_list, render=False):\n t_start = time.time()\n # to_device(torch.device('cpu'), self.policy)\n\n memory, log = collect_samples(0, self.env, self.policy, self.custom_reward, self.mean_action,\n self.render, self.running_state, context_list, self.attention, self.fixed_sigma)\n\n batch = memory.memory\n # to_device(self.device, self.policy)\n t_end = time.time()\n log['sample_time'] = t_end - t_start\n\n return memory, log\n","sub_path":"Reinforcement_Learning/previous_methods/previous_agents/agent_conditionning.py","file_name":"agent_conditionning.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"411154721","text":"import numpy as np\n\ndef sysLin2(a1, b1, c1, a2, b2, c2):\n a = np.array([[a1, b1],[a2,b2]])\n b = np.array([c1, c2])\n x = np.linalg.solve(a,b)\n return tuple(x)\n \ndef sysLin3(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3):\n a = np.array([[a1, b1, c1], [a2, b2, c2], [a3, b3, c3]])\n b = np.array([d1, d2, d3])\n x = np.linalg.solve(a, b)\n return tuple(x)","sub_path":"mathsub/numpy_handler.py","file_name":"numpy_handler.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"632145435","text":"\nfrom google.appengine.ext.webapp import template\nimport webapp2\nimport os\n\nfrom google.appengine.ext import db\n\nclass Script(db.Model):\n \"\"\"Models URL to JS content mapping\"\"\"\n path = db.StringProperty()\n content = db.TextProperty()\n type = db.StringProperty()\n\nclass Tag(db.Model):\n path = db.StringProperty()\n name = db.StringProperty()\n\nclass ScriptLoader(db.Model):\n url = db.StringProperty()\n pre = db.TextProperty()\n post = db.TextProperty()\n name = db.StringProperty()\n\nclass AdminHandler(webapp2.RequestHandler):\n def get(self):\n path = os.path.join(os.path.dirname(__file__), 'templates/index.html')\n self.response.out.write(template.render(path, {}))\n\n def post(self):\n path = self.request.get('path')\n content = self.request.get('content')\n type = self.request.get('type')\n script = db.GqlQuery(\"SELECT * FROM Script \"\n \"WHERE path = :1\", path).get()\n if script:\n script.type = type\n script.content = content\n else:\n script = Script(path=path,content=content,type=type)\n\n script.put()\n self.redirect(\"/\" + script.path)\n\nclass ScriptHandler(webapp2.RequestHandler):\n def get(self,path):\n self.response.headers[\"Cache-Control\"]=\"public, max-age=300\"\n script = db.GqlQuery(\"SELECT * FROM Script \"\n \"WHERE path = :1\", path).get()\n if script:\n self.response.content_type = script.type.encode('ascii','ignore')\n self.response.out.write(script.content)\n else:\n self.response.status = 404\n self.response.out.write(\"404 - No script found here\")\n\n\nclass TagAdminHandler(webapp2.RequestHandler):\n def get(self):\n path = os.path.join(os.path.dirname(__file__), 'templates/tagadmin.html')\n tags = Tag.all().fetch(100)\n self.response.out.write(template.render(path, {'tags': tags}))\n\n def post(self):\n path = self.request.get('path')\n name = self.request.get('name')\n tag = db.GqlQuery(\"SELECT * FROM Tag \"\n \"WHERE path = :1\", path).get()\n if tag:\n tag.name = name\n else:\n tag = Tag(path=path,name=name)\n\n tag.put()\n self.redirect(self.request.path)\n\nclass ScriptLoaderAdminHandler(webapp2.RequestHandler):\n def get(self,tagpath):\n tagQuery = Tag.all().filter(\"path =\", tagpath)\n tag = tagQuery.get()\n\n if not tag:\n self.abort(404)\n\n id = self.request.get('id')\n delete = self.request.get('delete')\n if id:\n this_scriptloader = ScriptLoader.get_by_id(int(id),tag)\n\n else:\n this_scriptloader = None\n\n if id and delete==\"true\":\n this_scriptloader.delete()\n self.redirect(self.request.path)\n else:\n allscriptloaders = ScriptLoader.all().ancestor(tag).fetch(100)\n\n path = os.path.join(os.path.dirname(__file__), 'templates/scriptloaderadmin.html')\n self.response.out.write(template.render(path, {'tag': tag,\n 'scriptloaders': allscriptloaders,\n 'current': this_scriptloader}))\n\n def post(self,tagpath):\n tagQuery = Tag.all().filter(\"path =\", tagpath)\n tag = tagQuery.get()\n\n url = self.request.get('url')\n pre = self.request.get('pre')\n post = self.request.get('post')\n name = self.request.get('name')\n\n sl = ScriptLoader.all().filter(\"url =\",url).get()\n\n if sl:\n sl.name = name\n sl.pre = pre\n sl.post = post\n else:\n sl = ScriptLoader(parent=tag,url=url,pre=pre,post=post,name=name)\n\n sl.put()\n\n self.redirect(self.request.path)\n\nclass TagHandler(webapp2.RequestHandler):\n def get(self,tagpath):\n tagQuery = Tag.all().filter(\"path =\", tagpath)\n tag = tagQuery.get()\n\n if tag:\n self.response.headers[\"Cache-Control\"]=\"public, max-age=300\"\n self.response.content_type = \"application/javascript\"\n\n scriptloaders = ScriptLoader.all().ancestor(tag).fetch(100)\n\n path = os.path.join(os.path.dirname(__file__), 'templates/opentag.js')\n self.response.out.write(template.render(path, {'tag': tag, 'scriptloaders': scriptloaders}))\n\n else:\n self.response.status = 404\n self.response.out.write(\"404 - No script found here\")\n\n\n\napp = webapp2.WSGIApplication([\n ('/admin', AdminHandler),\n ('/tag/admin',TagAdminHandler),\n ('/tag/admin/scriptloader/(.*)',ScriptLoaderAdminHandler),\n ('/tag/(.*)', TagHandler),\n ('/(.*)', ScriptHandler)],\n debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"16820873","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/plasma/models/mpi_runner.py\n# Compiled at: 2017-02-17 21:50:27\n__doc__ = '\\n#########################################################\\nThis file trains a deep learning model to predict\\ndisruptions on time series data from plasma discharges.\\n\\nDependencies:\\nconf.py: configuration of model,training,paths, and data\\nmodel_builder.py: logic to construct the ML architecture\\ndata_processing.py: classes to handle data processing\\n\\nAuthor: Julian Kates-Harbeck, jkatesharbeck@g.harvard.edu\\n\\nThis work was supported by the DOE CSGF program.\\n#########################################################\\n'\nfrom __future__ import print_function\nimport os, sys, time, datetime, numpy as np\nfrom functools import partial\nimport socket\nsys.setrecursionlimit(10000)\nimport getpass\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\ntask_index = comm.Get_rank()\nnum_workers = comm.Get_size()\nNUM_GPUS = 4\nMY_GPU = task_index % NUM_GPUS\nbackend = 'theano'\nfrom pprint import pprint\nfrom plasma.conf import conf\nif backend == 'tf' or backend == 'tensorflow':\n os.environ['CUDA_VISIBLE_DEVICES'] = ('{}').format(MY_GPU)\n os.environ['KERAS_BACKEND'] = 'tensorflow'\n import tensorflow\nelse:\n base_compile_dir = ('{}/tmp/{}-{}').format(conf['paths']['output_path'], socket.gethostname(), task_index)\n os.environ['THEANO_FLAGS'] = ('device=gpu{},floatX=float32,base_compiledir={}').format(MY_GPU, base_compile_dir)\n import theano\nfor i in range(num_workers):\n comm.Barrier()\n if i == task_index:\n print(('[{}] importing Keras').format(task_index))\n from keras import backend as K\n from keras.layers import Input, Dense, Dropout\n from keras.layers.recurrent import LSTM\n from keras.layers.wrappers import TimeDistributed\n from keras.models import Model\n from keras.optimizers import SGD\n from keras.utils.generic_utils import Progbar\n import keras.callbacks as cbks\n\nfrom plasma.models import builder\nfrom plasma.utils.evaluation import get_loss_from_list\nfrom plasma.utils.processing import concatenate_sublists\nfrom plasma.utils.performance import PerformanceAnalyzer\nif task_index == 0:\n pprint(conf)\n\nclass MPIOptimizer(object):\n\n def __init__(self, lr):\n self.lr = lr\n self.iterations = 0\n\n def get_deltas(self, raw_deltas):\n raise NotImplementedError\n\n def set_lr(self, lr):\n self.lr = lr\n\n\nclass MPISGD(MPIOptimizer):\n\n def __init__(self, lr):\n super(MPISGD, self).__init__(lr)\n\n def get_deltas(self, raw_deltas):\n deltas = []\n for g in raw_deltas:\n deltas.append(self.lr * g)\n\n self.iterations += 1\n return deltas\n\n\nclass MPIAdam(MPIOptimizer):\n\n def __init__(self, lr):\n super(MPIAdam, self).__init__(lr)\n self.beta_1 = 0.9\n self.beta_2 = 0.999\n self.eps = 1e-08\n\n def get_deltas(self, raw_deltas):\n if self.iterations == 0:\n self.m_list = [ np.zeros_like(g) for g in raw_deltas ]\n self.v_list = [ np.zeros_like(g) for g in raw_deltas ]\n t = self.iterations + 1\n lr_t = self.lr * np.sqrt(1 - self.beta_2 ** t) / (1 - self.beta_1 ** t)\n deltas = []\n for i, g in enumerate(raw_deltas):\n m_t = self.beta_1 * self.m_list[i] + (1 - self.beta_1) * g\n v_t = self.beta_2 * self.v_list[i] + (1 - self.beta_2) * g ** 2\n delta_t = lr_t * m_t / (np.sqrt(v_t) + self.eps)\n deltas.append(delta_t)\n self.m_list[i] = m_t\n self.v_list[i] = v_t\n\n self.iterations += 1\n return deltas\n\n\nclass Averager(object):\n\n def __init__(self):\n self.steps = 0\n self.val = 0.0\n\n def add_val(self, val):\n self.val = (self.steps * self.val + 1.0 * val) / (self.steps + 1.0)\n self.steps += 1\n\n def get_val(self):\n return self.val\n\n\nclass MPIModel:\n\n def __init__(self, model, optimizer, comm, batch_iterator, batch_size, num_replicas=None, warmup_steps=1000, lr=0.01):\n self.epoch = 0\n self.model = model\n self.optimizer = optimizer\n self.lr = lr\n self.DUMMY_LR = 0.1\n self.max_lr = 0.1\n self.comm = comm\n self.batch_size = batch_size\n self.batch_iterator = batch_iterator\n self.warmup_steps = warmup_steps\n self.num_workers = comm.Get_size()\n self.task_index = comm.Get_rank()\n self.history = cbks.History()\n if num_replicas is None or num_replicas < 1 or num_replicas > self.num_workers:\n self.num_replicas = num_workers\n else:\n self.num_replicas = num_replicas\n return\n\n def set_lr(self, lr):\n self.lr = lr\n\n def save_weights(self, path, overwrite=False):\n self.model.save_weights(path, overwrite=overwrite)\n\n def load_weights(self, path):\n self.model.load_weights(path)\n\n def compile(self, loss='mse'):\n self.model.compile(optimizer=SGD(lr=self.DUMMY_LR), loss=loss)\n\n def get_deltas(self, X_batch, Y_batch, verbose=False):\n weights_before_update = self.model.get_weights()\n loss = self.model.train_on_batch(X_batch, Y_batch)\n weights_after_update = self.model.get_weights()\n self.model.set_weights(weights_before_update)\n deltas = subtract_params(weights_after_update, weights_before_update)\n deltas = multiply_params(deltas, 1.0 / self.DUMMY_LR)\n return (\n deltas, loss)\n\n def get_new_weights(self, deltas):\n return add_params(self.model.get_weights(), deltas)\n\n def mpi_average_gradients(self, arr, num_replicas=None):\n if num_replicas == None:\n num_replicas = self.num_workers\n if self.task_index >= num_replicas:\n arr *= 0.0\n arr_global = np.empty_like(arr)\n self.comm.Allreduce(arr, arr_global, op=MPI.SUM)\n arr_global /= num_replicas\n return arr_global\n\n def mpi_average_scalars(self, val, num_replicas=None):\n val_global = self.mpi_sum_scalars(val, num_replicas)\n val_global /= num_replicas\n return val_global\n\n def mpi_sum_scalars(self, val, num_replicas=None):\n if num_replicas == None:\n num_replicas = self.num_workers\n if self.task_index >= num_replicas:\n val *= 0.0\n val_global = 0.0\n val_global = self.comm.allreduce(val, op=MPI.SUM)\n return val_global\n\n def sync_deltas(self, deltas, num_replicas=None):\n global_deltas = []\n for delta in deltas:\n global_deltas.append(self.mpi_average_gradients(delta, num_replicas))\n\n return global_deltas\n\n def set_new_weights(self, deltas, num_replicas=None):\n global_deltas = self.sync_deltas(deltas, num_replicas)\n effective_lr = self.get_effective_lr(num_replicas)\n self.optimizer.set_lr(effective_lr)\n global_deltas = self.optimizer.get_deltas(global_deltas)\n if comm.rank == 0:\n new_weights = self.get_new_weights(global_deltas)\n else:\n new_weights = None\n new_weights = self.comm.bcast(new_weights, root=0)\n self.model.set_weights(new_weights)\n return\n\n def build_callbacks(self, conf, callbacks_list):\n mode = conf['callbacks']['mode']\n monitor = conf['callbacks']['monitor']\n patience = conf['callbacks']['patience']\n callback_save_path = conf['paths']['callback_save_path']\n callbacks_list = conf['callbacks']['list']\n callbacks = [\n cbks.BaseLogger()]\n callbacks += [self.history]\n callbacks += [cbks.CSVLogger(('{}callbacks-{}.log').format(callback_save_path, datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')))]\n if 'earlystop' in callbacks_list:\n callbacks += [cbks.EarlyStopping(patience=patience, monitor=monitor, mode=mode)]\n if 'lr_scheduler' in callbacks_list:\n pass\n return cbks.CallbackList(callbacks)\n\n def train_epoch(self):\n verbose = False\n step = 0\n loss_averager = Averager()\n t_start = time.time()\n batch_iterator_func = self.batch_iterator()\n num_so_far = 0\n num_total = 1\n ave_loss = -1\n curr_loss = -1\n t0 = 0\n t1 = 0\n t2 = 0\n while num_so_far < num_total:\n try:\n batch_xs, batch_ys, reset_states_now, num_so_far, num_total = batch_iterator_func.next()\n except:\n batch_iterator_func = self.batch_iterator()\n batch_xs, batch_ys, reset_states_now, num_so_far, num_total = batch_iterator_func.next()\n\n if reset_states_now:\n self.model.reset_states()\n warmup_phase = step < self.warmup_steps and self.epoch == 0\n num_replicas = 1 if warmup_phase else self.num_replicas\n num_so_far = self.mpi_sum_scalars(num_so_far, num_replicas)\n t0 = time.time()\n deltas, loss = self.get_deltas(batch_xs, batch_ys, verbose)\n t1 = time.time()\n self.set_new_weights(deltas, num_replicas)\n t2 = time.time()\n write_str_0 = self.calculate_speed(t0, t1, t2, num_replicas)\n curr_loss = self.mpi_average_scalars(1.0 * loss, num_replicas)\n loss_averager.add_val(curr_loss)\n ave_loss = loss_averager.get_val()\n eta = self.estimate_remaining_time(t0 - t_start, num_so_far, num_total)\n write_str = ('\\r[{}] step: {} [ETA: {:.2f}s] [{:.2f}/{}], loss: {:.5f} [{:.5f}] | ').format(self.task_index, step, eta, 1.0 * num_so_far, num_total, ave_loss, curr_loss)\n print_unique(write_str + write_str_0)\n step += 1\n\n self.epoch += 1\n print_unique(('\\nEpoch {} finished in {:.2f} seconds.\\n').format(self.epoch, t2 - t_start))\n return (\n step, ave_loss, curr_loss, num_so_far)\n\n def estimate_remaining_time(self, time_so_far, work_so_far, work_total):\n eps = 1e-06\n total_time = 1.0 * time_so_far * work_total / (work_so_far + eps)\n return total_time - time_so_far\n\n def get_effective_lr(self, num_replicas):\n effective_lr = self.lr * num_replicas\n if effective_lr > self.max_lr:\n print_unique(('Warning: effective learning rate set to {}, larger than maximum {}. Clipping.').format(effective_lr, self.max_lr))\n effective_lr = self.max_lr\n return effective_lr\n\n def get_effective_batch_size(self, num_replicas):\n return self.batch_size * num_replicas\n\n def calculate_speed(self, t0, t_after_deltas, t_after_update, num_replicas, verbose=False):\n effective_batch_size = self.get_effective_batch_size(num_replicas)\n t_calculate = t_after_deltas - t0\n t_sync = t_after_update - t_after_deltas\n t_tot = t_after_update - t0\n examples_per_sec = effective_batch_size / t_tot\n frac_calculate = t_calculate / t_tot\n frac_sync = t_sync / t_tot\n print_str = ('{:.2E} Examples/sec | {:.2E} sec/batch [{:.1%} calc., {:.1%} synch.]').format(examples_per_sec, t_tot, frac_calculate, frac_sync)\n print_str += ('[batch = {} = {}*{}] [lr = {:.2E} = {:.2E}*{}]').format(effective_batch_size, self.batch_size, num_replicas, self.get_effective_lr(num_replicas), self.lr, num_replicas)\n if verbose:\n print_unique(print_str)\n return print_str\n\n\ndef print_unique(print_str):\n if task_index == 0:\n sys.stdout.write(print_str)\n sys.stdout.flush()\n\n\ndef print_all(print_str):\n sys.stdout.write(('[{}] ').format(task_index) + print_str)\n sys.stdout.flush()\n\n\ndef multiply_params(params, eps):\n return [ el * eps for el in params ]\n\n\ndef subtract_params(params1, params2):\n return [ p1 - p2 for p1, p2 in zip(params1, params2) ]\n\n\ndef add_params(params1, params2):\n return [ p1 + p2 for p1, p2 in zip(params1, params2) ]\n\n\ndef get_shot_list_path(conf):\n return conf['paths']['base_path'] + '/normalization/shot_lists.npz'\n\n\ndef save_shotlists(conf, shot_list_train, shot_list_validate, shot_list_test):\n path = get_shot_list_path(conf)\n np.savez(path, shot_list_train=shot_list_train, shot_list_validate=shot_list_validate, shot_list_test=shot_list_test)\n\n\ndef load_shotlists(conf):\n path = get_shot_list_path(conf)\n data = np.load(path)\n shot_list_train = data['shot_list_train'][()]\n shot_list_validate = data['shot_list_validate'][()]\n shot_list_test = data['shot_list_test'][()]\n return (\n shot_list_train, shot_list_validate, shot_list_test)\n\n\ndef mpi_make_predictions(conf, shot_list, loader):\n specific_builder = builder.ModelBuilder(conf)\n y_prime = []\n y_gold = []\n disruptive = []\n model = specific_builder.build_model(True)\n specific_builder.load_model_weights(model)\n model.reset_states()\n if task_index == 0:\n pbar = Progbar(len(shot_list))\n shot_sublists = shot_list.sublists(conf['model']['pred_batch_size'], do_shuffle=False, equal_size=True)\n y_prime_global = []\n y_gold_global = []\n disruptive_global = []\n if task_index != 0:\n loader.verbose = False\n for i, shot_sublist in enumerate(shot_sublists):\n if i % num_workers == task_index:\n X, y, shot_lengths, disr = loader.load_as_X_y_pred(shot_sublist)\n y_p = model.predict(X, batch_size=conf['model']['pred_batch_size'])\n model.reset_states()\n y_p = loader.batch_output_to_array(y_p)\n y = loader.batch_output_to_array(y)\n y_p = [ arr[:shot_lengths[j]] for j, arr in enumerate(y_p) ]\n y = [ arr[:shot_lengths[j]] for j, arr in enumerate(y) ]\n y_prime += y_p\n y_gold += y\n disruptive += disr\n if i % num_workers == num_workers - 1 or i == len(shot_sublists) - 1:\n comm.Barrier()\n y_prime_global += concatenate_sublists(comm.allgather(y_prime))\n y_gold_global += concatenate_sublists(comm.allgather(y_gold))\n disruptive_global += concatenate_sublists(comm.allgather(disruptive))\n comm.Barrier()\n y_prime = []\n y_gold = []\n disruptive = []\n if task_index == 0:\n pbar.add(1.0 * len(shot_sublist))\n\n y_prime_global = y_prime_global[:len(shot_list)]\n y_gold_global = y_gold_global[:len(shot_list)]\n disruptive_global = disruptive_global[:len(shot_list)]\n return (\n y_prime_global, y_gold_global, disruptive_global)\n\n\ndef mpi_make_predictions_and_evaluate(conf, shot_list, loader):\n y_prime, y_gold, disruptive = mpi_make_predictions(conf, shot_list, loader)\n analyzer = PerformanceAnalyzer(conf=conf)\n roc_area = analyzer.get_roc_area(y_prime, y_gold, disruptive)\n loss = get_loss_from_list(y_prime, y_gold, conf['data']['target'].loss)\n return (\n roc_area, loss)\n\n\ndef mpi_train(conf, shot_list_train, shot_list_validate, loader, callbacks_list=None):\n specific_builder = builder.ModelBuilder(conf)\n train_model, test_model = specific_builder.build_train_test_models()\n e = specific_builder.load_model_weights(train_model)\n num_epochs = conf['training']['num_epochs']\n lr_decay = conf['model']['lr_decay']\n batch_size = conf['training']['batch_size']\n lr = conf['model']['lr']\n warmup_steps = conf['model']['warmup_steps']\n optimizer = MPIAdam(lr=lr)\n print(('{} epochs left to go').format(num_epochs - 1 - e))\n batch_generator = partial(loader.training_batch_generator, shot_list=shot_list_train)\n mpi_model = MPIModel(train_model, optimizer, comm, batch_generator, batch_size, lr=lr, warmup_steps=warmup_steps)\n mpi_model.compile(loss=conf['data']['target'].loss)\n callbacks = mpi_model.build_callbacks(conf, callbacks_list)\n callbacks._set_model(mpi_model.model)\n callback_metrics = conf['callbacks']['metrics']\n callbacks._set_params({'nb_epoch': num_epochs, \n 'metrics': callback_metrics})\n callbacks.on_train_begin()\n while e < num_epochs - 1:\n callbacks.on_epoch_begin(e)\n e += 1\n mpi_model.set_lr(lr * lr_decay ** e)\n print_unique(('\\nEpoch {}/{}').format(e, num_epochs))\n step, ave_loss, curr_loss, num_so_far = mpi_model.train_epoch()\n loader.verbose = False\n if task_index == 0:\n specific_builder.save_model_weights(train_model, e)\n epoch_logs = {}\n roc_area, loss = mpi_make_predictions_and_evaluate(conf, shot_list_validate, loader)\n epoch_logs['val_roc'] = roc_area\n epoch_logs['val_loss'] = loss\n epoch_logs['train_loss'] = ave_loss\n if task_index == 0:\n print(('=========Summary======== for epoch{}').format(step))\n print(('Training Loss: {:.3e}').format(ave_loss))\n print(('Validation Loss: {:.3e}').format(loss))\n print(('Validation ROC: {:.4f}').format(roc_area))\n callbacks.on_epoch_end(e, epoch_logs)\n\n callbacks.on_train_end()","sub_path":"pycfiles/plasmalights-1.0.0-py2-none-any/mpi_runner.py","file_name":"mpi_runner.py","file_ext":"py","file_size_in_byte":17190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"427317790","text":"class RingBuffer:\n def __init__(self, capacity):\n self.capacity = capacity \n self.storage = []\n self.count = 0\n\n def append(self, item):\n # If len of storage is equal to capacity \n if len(self.storage) == self.capacity: \n # Set item to storage at count index\n self.storage[self.count] = item\n # If count plus 1 equals capacity \n if self.count + 1 == self.capacity: \n self.count = 0\n else:\n # If not -1 away from capacity add 1 \n self.count += 1 \n else: \n # If not at capacity recursivley\n self.storage.append(item)\n return item\n\n\n def get(self):\n return self.storage","sub_path":"ring_buffer/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399419398","text":"# vim: expandtab\n# -*- coding: utf-8 -*-\nimport re\n\nfrom django.contrib.staticfiles.finders import find as staticfiles_find\n\nfrom poleno.utils.template import Library\n\nregister = Library()\nsass_variable_re = re.compile(r'^([$][\\w-]+):(.*)$')\n\n@register.filter\ndef sass_variables(asset):\n res = {}\n path = staticfiles_find(asset)\n with open(path) as f:\n for line in f:\n match = sass_variable_re.match(line)\n if match:\n name = match.group(1).strip()\n value = match.group(2).strip()\n if value in res:\n res[name] = res[value]\n else:\n res[name] = value\n # Strip leading '$' and replace '-' with '_'\n for name, value in res.items():\n res[name.lstrip(u'$').replace(u'-', u'_')] = value\n return res\n","sub_path":"chcemvediet/templatetags/chcemvediet/styleguide.py","file_name":"styleguide.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76469130","text":"import cv2 \nimport numpy as np\nfrom scipy import ndimage, misc\nimport matplotlib.pyplot as plt\nimport platform\nimport time\nfrom matplotlib.patches import Circle\nimport itertools\n\n\ncimg = cv2.imread('data/10m_dollarspot(3).jpg', cv2.IMREAD_COLOR)\nimg = cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY)\nret, img = cv2.threshold(img, 140, 255, cv2.THRESH_BINARY_INV)\nimg = cv2.erode(img, None)\nimg = cv2.fastNlMeansDenoising(img,None,300,1,40)\n\nif platform.system() == 'Windows':\n NIX = False\n print(\"Running on Windows system\")\nelse:\n NIX = True\n print(\"Running on Linux/OS X system\")\n\n# Blur using 3 * 3 kernel. \n# blurred = cv2.blur(img, (3, 3)) \n\n#Dilate image\n# dilated = cv2.dilate(img,None)\n# eroded = cv2.erode(img, None)\n \n# Apply Hough transform on the blurred image. \ndetected_circles = cv2.HoughCircles(img, \n cv2.HOUGH_GRADIENT, 1, 350, param1 = 200, \n param2 = 10, minRadius = 60, maxRadius = 66) \n \n# Draw circles that are detected. \nif detected_circles is not None: \n \n # Convert the circle parameters a, b and r to integers. \n detected_circles = np.uint16(np.around(detected_circles)) \n cimg = cv2.cvtColor(cimg, cv2.COLOR_BGR2RGB)\n \n for pt in detected_circles[0, 2:3]: \n a, b, r = pt[0], pt[1], pt[2] \n \n # Draw the circumference of the circle. \n cv2.circle(cimg, (a-r, b+300-r), r*4, (255, 0, 0), 20) \n \n # Draw a small circle (of radius 1) to show the center. \n cv2.circle(cimg, (a-r, b+300-r), 1, (0, 0, 0), 30)\n\n coordinates = a,b\n\n plt.imshow(cimg)\n plt.axis('off')\n # plt.text(a+2*r,b,\"Coordinates {}\".format(coordinates), fontsize=15)\n # print(coordinates)\n plt.text(0,1750,\"Coordinates: (39 N, 83.4 W)\", fontsize=15, fontweight='bold')\n plt.text(0,1900,\"Area= 1643.46 sq.in.\", fontsize=15, fontweight='bold')\n plt.text(0,2050,\"Date: 12/16/2019\", fontsize=15, fontweight='bold')\n plt.text(0,2150,\"Time: 12:19:59\", fontsize=15, fontweight='bold')\n plt.show()","sub_path":"Demo_ocv_dollar.py","file_name":"Demo_ocv_dollar.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222740366","text":"from django.shortcuts import render, redirect\nfrom main_app.forms import *\nfrom .models import *\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\nimport razorpay\nfrom django.http import HttpResponse\n\nrazorpay_client =razorpay.Client(auth=(settings.RAZORPAY_ID,settings.RAZORPAY_SECRET))\n\n# hmoe view code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef home(request):\n products = Product.objects.all()\n category = Category.objects.all()\n return render(request, 'index.html', {'pr': products,'ct':category})\n\n# search code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef search(request):\n prodt= None\n query= None\n if 'q' in request.GET:\n query=request.GET.get('q')\n prodt=Product.objects.all().filter(Q(name__contains=query)|Q(desc__contains=query))\n\n return render(request,'search.html',{'qr':query,'pr':prodt})\n\n# add-product admin code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef add_products(request):\n if request.method == 'POST':\n form = ProductForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('add_products')\n else:\n messages.info(request, \"product is not added ,try again \")\n else:\n form = ProductForm()\n return render(request, 'add_product.html', {'form': form})\n\n# product detail code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef product_desc(request, pk):\n product = Product.objects.get(pk=pk)\n return render(request, 'product_detail.html', {'pr': product})\n\n# product add-to-cart >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef add_to_cart(request, pk):\n # get the product id = pk\n product = Product.objects.get(pk=pk)\n\n # create order item\n order_item, created = OrderItem.objects.get_or_create(\n product=product,\n user=request.user,\n ordered=False,\n )\n\n # get query set of order object of user\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__pk=pk).exists():\n order_item.quantity += 1\n order_item.save()\n messages.info(request, \"added quantity item\")\n return redirect(\"product_desc\", pk=pk)\n else:\n order.items.add(order_item)\n messages.info(request, \"item add to cart\")\n return redirect(\"product_desc\", pk=pk)\n else:\n ordered_date = timezone.now()\n order = Order.objects.create(user=request.user, ordered_date=ordered_date)\n order.items.add(order_item)\n messages.info(request, \"item added to cart\")\n return redirect('product_desc', pk=pk)\n\n\ndef cart(request):\n if Order.objects.filter(user=request.user, ordered=False).exists():\n order = Order.objects.get(user=request.user, ordered=False)\n return render(request, 'cart.html', {'order': order})\n return render(request, 'cart.html', {'message': \"Your Cart Is Empty\"})\n\n# product add-count >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>..\n\ndef add_item(request, pk):\n product = Product.objects.get(pk=pk)\n\n # create order item\n order_item, created = OrderItem.objects.get_or_create(\n product=product,\n user=request.user,\n ordered=False,\n )\n\n # get query set of order object of user\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__pk=pk).exists():\n if order_item.quantity < product.product_available_count:\n order_item.quantity += 1\n order_item.save()\n messages.info(request, \"added quantity item\")\n return redirect(\"cart\")\n else:\n messages.info(request, \"Sorry! product is out of stock\")\n return redirect('cart')\n else:\n order.items.add(order_item)\n messages.info(request, \"item add to cart\")\n return redirect(\"product_desc\", pk=pk)\n else:\n ordered_date = timezone.now()\n order = Order.objects.create(user=request.user, ordered_date=ordered_date)\n order.items.add(order_item)\n messages.info(request, \"item added to cart\")\n return redirect('product_desc', pk=pk)\n\n# product count remove >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef remove_item(request, pk):\n item = get_object_or_404(Product, pk=pk)\n order_qs = Order.objects.filter(\n user=request.user,\n ordered=False,\n )\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__pk=pk).exists():\n order_item = OrderItem.objects.filter(\n product=item,\n user=request.user,\n ordered=False,\n )[0]\n if order_item.quantity > 1:\n order_item.quantity -= 1\n order_item.save()\n else:\n order_item.delete()\n messages.info(request, \"item quantity was update \")\n return redirect('cart')\n else:\n messages.info(request, \"this is item not your cart\")\n return redirect('cart')\n else:\n messages.info(request, \"you Do not have any order\")\n return redirect('cart')\n\n# checkout >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef checkout(request):\n if CheckoutAddress.objects.filter(user=request.user).exists():\n return render(request, 'checkout.html', {'payment_allow': 'allow'})\n if request.method == 'POST':\n form = Checkoutform(request.POST)\n if form.is_valid():\n street_address = form.cleaned_data.get('street_address')\n apartment_address = form.cleaned_data.get('apartment_address')\n country = form.cleaned_data.get('country')\n zip_code = form.cleaned_data.get('zip_code')\n\n checkout_address = CheckoutAddress(\n user=request.user,\n street_address=street_address,\n apartment_address=apartment_address,\n country=country,\n zip_code=zip_code,\n )\n checkout_address.save()\n print(\"It should render the summary page\")\n return render(request, 'checkout.html', {'payment_allow': 'allow'})\n # except Exception as e:\n # messages.warning(request, 'Failed checkout')\n # return redirect('checkout')\n\n else:\n form = Checkoutform()\n return render(request, 'checkout.html', {'form': form})\n\n# payment >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef payment(request):\n try:\n order =Order.objects.get(user=request.user,ordered=False)\n address =CheckoutAddress.objects.get(user=request.user)\n order_amount =order.get_total_price()\n order_currency=\"INR\"\n order_receipt= order.ordered_id\n notes = {\n 'street_address':address.street_address,\n 'apartment_address':address.apartment_address,\n 'country':address.country.name,\n 'zip_code':address.zip_code,\n }\n razorpay_order = razorpay_client.order.create(\n dict(\n amount =order_amount * 100,\n currency = order_currency,\n receipt =order_receipt,\n notes=notes,\n payment_capture =\"0\",\n )\n )\n print(razorpay_order[\"id\"])\n order.razorpay_order_id=razorpay_order[\"id\"]\n order.save()\n print('it should render the summary page ')\n return render(\n request,\n \"paymentsummaryrazorpay.html\",\n {\n \"order\":order,\n \"order_id\":razorpay_order[\"id\"],\n \"orderId\" :order.ordered_id,\n \"final_price\":order_amount,\n \"razorpay_merchant_id\":settings.RAZORPAY_ID,\n },\n )\n except Order.DoesNotExist:\n print(\"order not fount\")\n return HttpResponse(\"404 error\")\n\n# call back funaction >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n@csrf_exempt\ndef handlerequest(request):\n if request.method == \"POST\":\n try:\n payment_id = request.POST.get(\"razorpay_payment_id\", \"\")\n order_id = request.POST.get(\"razorpay_order_id\", \"\")\n signature = request.POST.get(\"razorpay_signature\", \"\")\n print(payment_id, order_id, signature)\n params_dict = {\n \"razorpay_order_id\": order_id,\n \"razorpay_payment_id\": payment_id,\n \"razorpay_signature\": signature,\n }\n\n try:\n order_db = Order.objects.get(razorpay_order_id=order_id)\n print(\"Order Found\")\n except:\n print(\"Order Not found\")\n return HttpResponse(\"505 Not Found\")\n order_db.razorpay_payment_id = payment_id\n order_db.razorpay_signature = signature\n order_db.save()\n print(\"Working............\")\n result = razorpay_client.utility.verify_payment_signature(params_dict)\n if result == None:\n print(\"Working Final Fine............\")\n amount = order_db.get_total_price()\n amount = amount * 100 # we have to pass in paisa\n payment_status = razorpay_client.payment.capture(payment_id, amount)\n if payment_status is not None:\n print(payment_status)\n order_db.ordered = True\n order_db.save()\n print(\"Payment Success\")\n checkout_address = CheckoutAddress.objects.get(user=request.user)\n request.session[\n \"order_complete\"\n ] = \"Your Order is Successfully Placed, You will receive your order within 5-7 working days\"\n return render(request, \"Invoice.html\",{\"order\":order_db,\"payment_status\":payment_status,\"checkout_address\":checkout_address})\n else:\n print(\"Payment Failed\")\n order_db.ordered = False\n order_db.save()\n request.session[\n \"order_failed\"\n ] = \"Unfortunately your order could not be placed, try again!\"\n return redirect(\"/\")\n else:\n order_db.ordered = False\n order_db.save()\n return render(request, \"paymentfailed.html\")\n except:\n return HttpResponse(\"Error Occured\")\n\n# invoice >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ndef Invoice(request):\n return render(request, \"Invoice.html\")","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"117421586","text":"#\n# @lc app=leetcode.cn id=121 lang=python3\n#\n# [121] 买卖股票的最佳时机\n#\n#思路一:dp[i]=max(dp[i-1],price[i]-minPrice)\n#思路二:实际求的是后面的峰值-前面谷值\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices)<2:\n return 0\n minPrice=prices[0]\n maxprofit=prices[1]-prices[0]\n for i in range(1,len(prices)):\n if prices[i]maxprofit:\n #实现dp表达式,if判断条件实现最值判断\n maxprofit=prices[i]-minPrice\n if maxprofit<0:\n return 0\n return maxprofit\n\n","sub_path":"121.买卖股票的最佳时机.py","file_name":"121.买卖股票的最佳时机.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"79929838","text":"__author__ = 'kudinovdenis'\nimport os\nimport re\nimport zipfile\nfrom os import listdir\nfrom os.path import isfile, join\nfrom bs4 import BeautifulSoup\nimport time\nimport shutil\n\n\nclass Maker(object):\n \"\"\"\n класс обрабатывает входящие епабы\n \"\"\"\n\n def __init__(self):\n \"\"\"\n метод устанавливает начальные значения переменным\n и определяет место запуска и пути к файлам, лежащим в данной папке\n \"\"\"\n # non-safe defenition ( = \"\" ). Sets inside correctAllHtml()\n self.toc_folder = \"\"\n self.html_folder = \"\"\n self.epub_number = \"\"\n # self.ok = True\n self.toc_ids = []\n self.opf_ids_part1 = []\n self.opf_ids_part2 = []\n self.big_strings = []\n self.small_strings = []\n self.location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n self.onlyfiles = [f for f in listdir(self.location) if isfile(join(self.location, f))]\n print(\"\\t--- Found {} files:\".format(len(self.onlyfiles) - 1))\n\n def editEpub(self):\n \"\"\"\n метод устанавливает пути к файлам toc и к папке с html-страницами,\n разархивирует епаб в папку, запускает обработку и архивирует обратно\n \"\"\"\n i = 0 # счётчик епабов в папке\n start_time = int(round(time.time()))\n for epubnameWithFormat in self.onlyfiles:\n try:\n splitter = \".\"\n epubNameWithoutFormat = epubnameWithFormat.split(splitter)[0] # имя епаба без формата\n htmlFolder = os.path.join(self.location, epubNameWithoutFormat + \"/ops/xhtml/\") # папка, содержащая html-страницы\n self.toc_folder = os.path.join(self.location, epubNameWithoutFormat + \"/ops/\") # папка, содержащая файл toc.ncx\n inZipPath = os.path.join(self.location, epubNameWithoutFormat) # имя входного архива\n outZipPath = os.path.join(self.location, epubnameWithFormat) # имя выходного архива\n self.epub_number = epubNameWithoutFormat\n\n print('\\t--- Current epub: {}'.format(epubnameWithFormat))\n self.unarchiveEpub(epubnameWithFormat, epubNameWithoutFormat)\n self.correctAllHtml(htmlFolder)\n os.remove(outZipPath)\n self.zip(inZipPath, outZipPath)\n shutil.rmtree(inZipPath)\n i += 1\n except:\n print(\"skip \" + epubnameWithFormat)\n stop_time = int(round(time.time()))\n delta = stop_time - start_time\n print(\"\\t--- Done {} epubs\".format(i))\n print(\"Time: {}seconds, avg.time: {} \".format(delta, delta / i)) #среднее время на книгу\n\n\n def unarchiveEpub(self, archiveName, destinationFolderName):\n \"\"\"\n разархивация епаба из archiveName в папку destinationFolderName\n\n @type archiveName: string\n @type destinationFolderName: string\n \"\"\"\n inputPath = os.path.join(self.location, archiveName)\n outputPath = os.path.join(self.location, destinationFolderName)\n with zipfile.ZipFile(inputPath, \"r\") as z:\n z.extractall(outputPath)\n\n def correctAllHtml(self, htmlFolder):\n \"\"\"\n метод ищет папку htmlFolder и запускает редактирование файлов\n\n @param htmlFolder: имя папки, в которой содержатся html файлы\n @type htmlFolder: string\n \"\"\"\n try:\n allHtmls = [f for f in listdir(htmlFolder) if isfile(join(htmlFolder, f))]\n self.html_folder = htmlFolder\n except:\n print(\"First try finding HTML directory failed. Second try...\")\n htmlFolder = os.path.join(htmlFolder[:-10], \"OEBPS\")\n self.html_folder = htmlFolder\n allHtmls = [f for f in listdir(htmlFolder) if isfile(join(htmlFolder, f))]\n self.repair_toc_ncx()\n\n try:\n allHtmls = [f for f in listdir(htmlFolder) if isfile(join(htmlFolder, f))]\n self.html_folder = htmlFolder\n except:\n print(\"First try finding HTML directory failed. Second try...\")\n htmlFolder = os.path.join(htmlFolder[:-10], \"OEBPS\")\n self.html_folder = htmlFolder\n allHtmls = [f for f in listdir(htmlFolder) if isfile(join(htmlFolder, f))]\n # self.repair_toc_ncx_NOT_USED()\n for htmlName in allHtmls:\n print('\\t--- Current file: {}'.format(htmlName))\n try:\n html = os.path.join(htmlFolder, htmlName)\n self.replace_svg_tags(html)\n self.replace_markers(html)\n self.replace_headers(html)\n if \"css\" in htmlName:\n os.remove(html)\n except:\n print(\"\\t--- Skip file: {}\".format(htmlName))\n\n def repair_toc_ncx(self):\n \"\"\"\n метод редактирует файлы toc.ncx, content.opf и разделяет файлы html\n \"\"\"\n print('\\t\\t--- Repairing toc.ncx file, .opf file...')\n self.toc_folder = os.path.join(self.toc_folder, \"toc.ncx\")\n try:\n f = open(self.toc_folder, 'r', encoding='utf-8')\n except:\n print(\"\\t\\t\\t--- ! toc.ncx not in ops directory\")\n self.toc_folder = os.path.join(self.toc_folder[:-11], \"OEBPS/toc.ncx\")\n f = open(self.toc_folder, 'r', encoding='utf-8')\n for file in os.listdir(self.toc_folder[:-7]):\n if file.endswith(\".opf\"):\n opf_file = os.path.join(self.toc_folder[:-7], file)\n\n pattern = r'src=\"(.*?\\/)*(.+?\\..*html)#(.+?)\"'\n toc_id_pattern = r'id\\s*=\\s*\"(.+?)\"'\n INPUT = f.read()\n\n self.toc_ids = re.findall(toc_id_pattern, INPUT)\n opfFile = open(opf_file, 'r', encoding='utf-8')\n opfINPUT = opfFile.read()\n\n strings = re.findall(pattern, INPUT)\n i = 0\n toc_id_pattern = r')'\n lines = []\n f = open(self.toc_folder, 'r', encoding='utf-8')\n INPUT = f.read()\n j = 0\n # part 1\n old_lines = re.findall(pattern, opfINPUT)\n for old_line in old_lines:\n for id_ref_part in old_ids_refs_parts:\n if id_ref_part[1] == old_line[2]:\n for new_id_ref_part in new_ids_refs_parts:\n if id_ref_part[0] == new_id_ref_part[0]:\n #создаем новую строку и добавляем в массив новых строк\n string = ''.format(\n id_ref_part[0], new_id_ref_part[1])\n new_lines += string + \"\\n\"\n ids.append(new_id_ref_part[0])\n lines.append(string)\n main_id = old_line[1]\n if \"\" != new_lines:\n if len(lines) > 0:\n opfINPUT = opfINPUT.replace(old_line[0], new_lines)\n if len(lines) > 1:\n opfINPUT = opfINPUT.replace(old_line[0], \"\")\n line_another_format = old_line[0]\n line_another_format = line_another_format[:-2] + \" />\"\n opfINPUT = opfINPUT.replace(line_another_format, \"\")\n new_lines = \"\"\n ids_string = \"\"\n # part 2\n for part_id in ids:\n ids_string += '\\n'.format(part_id)\n opfINPUT = opfINPUT.replace(''.format(main_id), ids_string)\n if len(lines) > 1:\n opfINPUT = opfINPUT.replace(''.format(main_id), \"\")\n opfINPUT = opfINPUT.replace(''.format(main_id), ids_string)\n if len(lines) > 1:\n opfINPUT = opfINPUT.replace(''.format(main_id), \"\")\n # чтоб наверняка удалить main id\n opfINPUT = opfINPUT.replace(''.format(main_id), \"\")\n #удаление из toc.ncx\n toc_delete_pattern = '()'.format(ids[0])\n ids = []\n replacement = re.findall(toc_delete_pattern, INPUT, flags=re.S)\n\n # удаление основных разделов из toc.ncx (например, ch066 если присутствуют ch06ch06, ch06lev01...)\n if len(lines) > 1:\n # INPUT = INPUT.replace(replacement[0],\n # '\\n\\nPraise\\n\\n'.format(\n # j))\n j += 1\n lines = []\n new_lines = \"\"\n lines = []\n ids = []\n try:\n #удаление оглавления из книг (toc)\n pattern = r'()'\n toc = re.findall(pattern, INPUT, re.S)\n if len(toc) > 0:\n toc = toc[0]\n INPUT = INPUT.replace(toc, \"\")\n\n # удаление файла, если он называется Contents\n pattern = r'(\\n\\nContents<\\/text>\\n<\\/navLabel>\\n\\n<\\/navPoint>)'\n found = re.findall(pattern, INPUT)\n if len(found) > 0:\n found = found[0]\n toc = found[0]\n ref = found[1]\n INPUT = INPUT.replace(toc, \"\")\n\n # и если Table of Contents\n pattern = r'(\\n*?\\n*?Table of Contents<\\/text>\\n*?<\\/navLabel>\\n*?\\n*?<\\/navPoint>)'\n found = re.findall(pattern, INPUT)\n if len(found) > 0:\n found = found[0]\n toc = found[0]\n ref = found[1]\n INPUT = INPUT.replace(toc, \"\")\n\n except:\n print(\"\\t\\t\\t--- Error deleting toc from toc.ncx\")\n try:\n #удаление оглавления из книг (spine)\n pattern = r'()'\n toc = re.findall(pattern, opfINPUT, re.S)\n if len(toc) > 0:\n toc = toc[0]\n opfINPUT = opfINPUT.replace(toc, \"\")\n\n pattern = r'()'.format(ref)\n found = re.findall(pattern, opfINPUT)\n if len(found) > 0:\n found = found[0]\n opf1 = found[0]\n id = found[1]\n opfINPUT = opfINPUT.replace(opf1, \"\")\n pattern = r'()'.format(id)\n opf2 = re.findall(pattern, opfINPUT)\n if len(opf2) > 0:\n opf2 = opf2[0]\n opfINPUT = opfINPUT.replace(opf2, \"\")\n except:\n print(\"\\t\\t\\t--- Error deleting toc from spine\")\n\n f.close()\n f = open(self.toc_folder, 'w', encoding='utf-8')\n # soup = BeautifulSoup(INPUT)\n # INPUT = soup.prettify()\n f.write(INPUT)\n f.close()\n\n opfFile.close()\n opfFile = open(opf_file, 'w', encoding='utf-8')\n opfFile.write(opfINPUT)\n opfFile.close()\n\n\n def splitHTML(self, filename, splitter, count, chapters_for_file):\n \"\"\"\n метод, раздеяющий страницу html на подстраницы для разбиения на подглавы\n\n выбирается массив всех глав в файле и ищутся две главы с соседними именами\n или, если эта глава единственная/последняя, то берётся весь файл до тега \n текущая глава -- splitter;\n следующая глава: chapters_for_file[chapters_for_file.index(splitter)+1]\n\n @param filename: имя входного html файла\n @type filename: string\n\n @param splitter: имя очередной главы\n @type splitter: string\n\n @param count: количество глав в файле\n @type count: int\n\n @param chapters_for_file: список всех глав в файле\n @type chapters_for_file: string[]\n\n \"\"\"\n current_chapter = splitter\n for chapter in chapters_for_file:\n if splitter == chapter:\n\n # если глава первая,\n # то взять всё от начала документа (тега до второй главы)\n if chapters_for_file.index(splitter) == 0 and len(chapters_for_file) > 0:\n content = \"\"\n # если состоит из одной главы\n if len(chapters_for_file) == 1:\n f = open(os.path.join(self.html_folder, filename), 'r', encoding='utf-8')\n INPUT = f.read()\n\n pattern = r'(.+?)'\n content = re.findall(pattern, INPUT, re.S)\n head_pattern = r'(.+?)'\n head = re.match(head_pattern, INPUT, flags=re.S)\n head = head.group(0)\n end = \"\\n\"\n if len(content[0]) > 0:\n OUTPUT = head + content[0] + end\n f.close()\n dot_splitter = \".\"\n file = filename.split(dot_splitter)\n new_file = file[0] + splitter + \".\" + file[1]\n f = open(os.path.join(self.html_folder, new_file), 'w', encoding='utf-8')\n f.write(OUTPUT)\n f.close()\n else:\n next_chapter = chapters_for_file[chapters_for_file.index(splitter) + 1]\n\n f = open(os.path.join(self.html_folder, filename), 'r', encoding='utf-8')\n pattern = r'(.+?(?=<\\w+?>\\s*<\\/\\w+>))'.format(next_chapter)\n head_pattern = r'(.+?)'\n INPUT = f.read()\n head = re.match(head_pattern, INPUT, flags=re.S)\n head = head.group(0)\n contents = re.findall(pattern, INPUT, flags=re.S)\n\n # до тега h#, чтобы он не обрезался\n if len(contents) == 0:\n additional_contents_pattern13 = r'(.+?)(?:)'.format(next_chapter)\n additional_contents13 = re.findall(additional_contents_pattern13, INPUT, re.S)\n contents += additional_contents13\n\n if len(contents) == 0:\n #(?:)*(.+?)(?=|<\\/body>)\n additional_contents_pattern1 = r'(.+?(?=))'.format(next_chapter)\n additional_contents1 = re.findall(additional_contents_pattern1, INPUT, flags=re.S)\n contents += additional_contents1\n\n if len(contents) == 0:\n additional_contents_pattern9 = r'(.+?(?=))'.format(\n next_chapter)\n additional_contents9 = re.findall(additional_contents_pattern9, INPUT, re.S)\n contents += additional_contents9\n\n if len(contents) == 0:\n additional_contents_pattern2 = r'(.+?(?=))'.format(next_chapter)\n additional_contents2 = re.findall(additional_contents_pattern2, INPUT, re.S)\n contents += additional_contents2\n\n if len(contents) == 0:\n additional_contents_pattern12 = r'(.+?(?=(.+?(?=(.+?(?:))'.format(next_chapter)\n additional_contents4 = re.findall(additional_contents_pattern4, INPUT, re.S)\n contents += additional_contents4\n\n if len(contents) == 0:\n additional_contents_pattern5 = r'(.+?(?=))'.format(next_chapter)\n additional_contents5 = re.findall(additional_contents_pattern5, INPUT, re.S)\n contents += additional_contents5\n\n if len(contents) == 0:\n additional_contents_pattern6 = r'(.+?(?=))'.format(next_chapter)\n additional_contents6 = re.findall(additional_contents_pattern6, INPUT, re.S)\n contents += additional_contents6\n\n if len(contents) == 0:\n additional_contents_pattern8 = r'(.+?(?=))'.format(next_chapter)\n additional_contents8 = re.findall(additional_contents_pattern8, INPUT, re.S)\n contents += additional_contents8\n\n if len(contents) == 0:\n additional_contents_pattern10 = r'(.+?(?=

))'.format(\n next_chapter)\n additional_contents10 = re.findall(additional_contents_pattern10, INPUT, re.S)\n contents += additional_contents10\n\n if len(contents) == 0:\n additional_contents_pattern11 = r'(.+?(?=

))'.format(\n next_chapter)\n additional_contents11 = re.findall(additional_contents_pattern11, INPUT, re.S)\n contents += additional_contents11\n\n for content_group in contents:\n if len(content_group) > 1:\n content = content_group\n break\n if content == \"\":\n additional_contents_pattern7 = r'(.+?(?=))'.format(next_chapter)\n additional_contents7 = re.findall(additional_contents_pattern7, INPUT, re.S)\n for content_group in additional_contents7:\n if len(content_group) > 1:\n content = content_group\n break\n\n end = \"\\n\"\n OUTPUT = head + content + end\n f.close()\n dot_splitter = \".\"\n file = filename.split(dot_splitter)\n new_file = file[0] + splitter + \".\" + file[1]\n f = open(os.path.join(self.html_folder, new_file), 'w', encoding='utf-8')\n f.write(OUTPUT)\n f.close()\n\n # если глава не последняя, но и не первая\n # глава посреди текста\n elif chapters_for_file.index(splitter) != len(chapters_for_file) - 1:\n\n next_chapter = chapters_for_file[chapters_for_file.index(splitter) + 1]\n\n f = open(os.path.join(self.html_folder, filename), 'r', encoding='utf-8')\n pattern = r'(<\\w+?>\\s*<\\/\\w+>.+?(?=<\\w+?>\\s*<\\/\\w+>))'.format(\n current_chapter, next_chapter)\n head_pattern = r'(.+?)'\n INPUT = f.read()\n head = re.match(head_pattern, INPUT, flags=re.S)\n head = head.group(0)\n contents = re.findall(pattern, INPUT, flags=re.S)\n\n content = \"\"\n\n if len(contents) == 0:\n additional_contents_pattern9 = r'((.+?))(?:)'.format(\n current_chapter, next_chapter)\n additional_contents9 = re.findall(additional_contents_pattern9, INPUT, re.S)\n contents += additional_contents9\n\n if len(contents) == 0:\n #(?:)*(.+?)(?=|<\\/body>)\n additional_contents_pattern1 = r'((.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents1 = re.findall(additional_contents_pattern1, INPUT, flags=re.S)\n contents += additional_contents1\n\n if len(contents) == 0:\n # ch##lev#\n additional_contents_pattern2 = r'((.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents2 = re.findall(additional_contents_pattern2, INPUT, re.S)\n contents += additional_contents2\n\n if len(contents) == 0:\n additional_contents_pattern12 = r'((.+?)(?=(.+?)(?=<\\/a><\\/a>(.+?)(?:))'.format(\n current_chapter, next_chapter)\n additional_contents4 = re.findall(additional_contents_pattern4, INPUT, re.S)\n contents += additional_contents4\n\n if len(contents) == 0:\n additional_contents_pattern5 = r'(<\\/a><\\/a>(.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents5 = re.findall(additional_contents_pattern5, INPUT, re.S)\n contents += additional_contents5\n\n if len(contents) == 0:\n additional_contents_pattern6 = r'((.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents6 = re.findall(additional_contents_pattern6, INPUT, re.S)\n contents += additional_contents6\n\n if len(contents) == 0:\n additional_contents_pattern8 = r'(<\\/a><\\/a>(.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents8 = re.findall(additional_contents_pattern8, INPUT, re.S)\n contents += additional_contents8\n\n if len(contents) == 0:\n additional_contents_pattern10 = r'(

(.+?)(?=

))'.format(\n current_chapter, next_chapter)\n additional_contents10 = re.findall(additional_contents_pattern10, INPUT, re.S)\n contents += additional_contents10\n\n if len(contents) == 0:\n additional_contents_pattern11 = r'(

.+?(?=

))'.format(\n current_chapter, next_chapter)\n additional_contents11 = re.findall(additional_contents_pattern11, INPUT, re.S)\n contents += additional_contents11\n\n for content_group in contents:\n if splitter == content_group[0]:\n content = content_group[1]\n break\n if content == \"\":\n for content_group in contents:\n if splitter == content_group[1]:\n content = content_group[0]\n break\n if content == \"\":\n additional_contents_pattern7 = r'((.+?)(?=))'.format(\n current_chapter, next_chapter)\n additional_contents7 = re.findall(additional_contents_pattern7, INPUT, re.S)\n for content_group in additional_contents7:\n if splitter == content_group[0]:\n content = content_group[1]\n break\n\n # пробегаемся по всем id и если такой в контенте нет, то добавляем контент по этой id\n # for content_group in contents:\n # if not content_group[0] in content:\n # content += content_group[1]\n if count == 1:\n for content_group in contents:\n if not content_group[1] in content:\n content += content_group[0]\n\n end = \"\\n\"\n OUTPUT = head + content + end\n f.close()\n dot_splitter = \".\"\n file = filename.split(dot_splitter)\n new_file = file[0] + splitter + \".\" + file[1]\n f = open(os.path.join(self.html_folder, new_file), 'w', encoding='utf-8')\n f.write(OUTPUT)\n f.close()\n # если глава последняя\n # то берём всё от её начала до тега \n else:\n f = open(os.path.join(self.html_folder, filename), 'r', encoding='utf-8')\n pattern = r'(<\\w+?>\\s*<\\/\\w+>.+?(?=<\\/body>))'.format(current_chapter)\n head_pattern = r'(.+?)'\n INPUT = f.read()\n head = re.match(head_pattern, INPUT, flags=re.S)\n head = head.group(0)\n contents = re.findall(pattern, INPUT, flags=re.S)\n\n content = \"\"\n\n if len(contents) == 0:\n additional_contents_pattern9 = r'(.{{0,50}}(.+?)(?=<\\/body>))'.format(current_chapter)\n additional_contents9 = re.findall(additional_contents_pattern9, INPUT, re.S)\n contents += additional_contents9\n\n if len(contents) == 0:\n #(?:)*(.+?)(?=|<\\/body>)\n additional_contents_pattern1 = r'((.+?)(?=<\\/body>))'.format(current_chapter)\n additional_contents1 = re.findall(additional_contents_pattern1, INPUT, flags=re.S)\n contents += additional_contents1\n\n if len(contents) == 0:\n # ch##lev#\n additional_contents_pattern2 = r'((.+?)(?=<\\/body>))'.format(current_chapter)\n additional_contents2 = re.findall(additional_contents_pattern2, INPUT, re.S)\n contents += additional_contents2\n\n if len(contents) == 0:\n additional_contents_pattern12 = r'((.+?)(?=<\\/body>))'.format(current_chapter)\n additional_contents12 = re.findall(additional_contents_pattern12, INPUT, re.S)\n contents += additional_contents12\n\n if len(contents) == 0:\n # (.+?)(?=<\\/body>))'.format(\n current_chapter)\n additional_contents3 = re.findall(additional_contents_pattern3, INPUT, re.S)\n contents += additional_contents3\n\n if len(contents) == 0:\n # ch02a\n additional_contents_pattern4 = r'(<\\/a><\\/a>(.+?)(?:<\\/body>))'.format(\n current_chapter)\n additional_contents4 = re.findall(additional_contents_pattern4, INPUT, re.S)\n contents += additional_contents4\n\n if len(contents) == 0:\n additional_contents_pattern5 = r'(<\\/a><\\/a>(.+?)(?=<\\/body>))'.format(\n current_chapter)\n additional_contents5 = re.findall(additional_contents_pattern5, INPUT, re.S)\n contents += additional_contents5\n\n if len(contents) == 0:\n additional_contents_pattern6 = r'((.+?)(?=<\\/body>))'.format(\n current_chapter)\n additional_contents6 = re.findall(additional_contents_pattern6, INPUT, re.S)\n contents += additional_contents6\n\n if len(contents) == 0:\n additional_contents_pattern8 = r'(<\\/a><\\/a>(.+?)(?=<\\/body>))'.format(\n current_chapter)\n additional_contents8 = re.findall(additional_contents_pattern8, INPUT, re.S)\n contents += additional_contents8\n\n if len(contents) == 0:\n additional_contents_pattern10 = r'(

.+?(?=<\\/body>))'.format(\n current_chapter)\n additional_contents10 = re.findall(additional_contents_pattern10, INPUT, re.S)\n contents += additional_contents10\n\n if len(contents) == 0:\n additional_contents_pattern11 = r'(

.+?(?=<\\/body>))'.format(\n current_chapter)\n additional_contents11 = re.findall(additional_contents_pattern11, INPUT, re.S)\n contents += additional_contents11\n\n for content_group in contents:\n if splitter == content_group[0]:\n content = content_group[1]\n break\n if content == \"\":\n for content_group in contents:\n if splitter == content_group[1]:\n content = content_group[0]\n break\n if content == \"\":\n additional_contents_pattern7 = r'(.+?)(?=<\\/body>)'.format(\n current_chapter)\n additional_contents7 = re.findall(additional_contents_pattern7, INPUT, re.S)\n for content_group in additional_contents7:\n if splitter == content_group[0]:\n content = content_group[1]\n break\n\n # пробегаемся по всем id и если такой в контенте нет, то добавляем контент по этой id\n # for content_group in contents:\n # if not content_group[0] in content:\n # content += content_group[1]\n if count == 1:\n for content_group in contents:\n if not content_group[1] in content:\n content += content_group[0]\n\n end = \"\\n\"\n OUTPUT = head + content + end\n f.close()\n dot_splitter = \".\"\n file = filename.split(dot_splitter)\n new_file = file[0] + splitter + \".\" + file[1]\n f = open(os.path.join(self.html_folder, new_file), 'w', encoding='utf-8')\n f.write(OUTPUT)\n f.close()\n if content == \"\":\n print(\"Not enough data to split HTML. file: {} with chapter {}\".format(filename, splitter))\n\n def change_file_name(self, old_name, chapter_name):\n \"\"\"\n метод прибавляет к названию входного файла имя главы\n\n @param old_name: имя входного файла\n @type old_name: string\n\n @param chapter_name: имя главы\n @type chapter_name: string\n \"\"\"\n dot_splitter = \".\"\n old_format = old_name.split(dot_splitter)[1]\n old_name = old_name.split(dot_splitter)[0]\n new_name = old_name + chapter_name + \".\" + old_format\n return new_name\n\n def repair_toc_ncx_NOT_USED(self):\n \"\"\"\n метод убирает части, оставляя в оглавлении только главы\n\n !!! НЕ ИСПОЛЬЗУЕТСЯ !!!\n \"\"\"\n print('\\t\\t--- Repairing toc.ncx file...')\n self.toc_folder = os.path.join(self.toc_folder, \"toc.ncx\")\n # try:\n f = open(self.toc_folder, 'r', encoding='utf-8')\n # except:\n # print(\"\\t\\t--- ! toc.ncx not in ops directory\")\n # self.toc_folder = os.path.join(self.toc_folder[:-11], \"OEBPS/toc.ncx\")\n # f = open(self.toc_folder, 'r', encoding='utf-8')\n pattern = r'html(#.+?)\"'\n INPUT = f.read()\n strings = re.findall(pattern, INPUT, flags=re.S)\n for string in strings:\n INPUT = INPUT.replace(string, \"\")\n f.close()\n f = open(self.toc_folder, 'w', encoding='utf-8')\n f.write(INPUT)\n f.close()\n\n def replace_svg_tags(self, filename):\n \"\"\"\n работа с картинками в cover в формате , переделывание их в\n

\n\n @param filename: имя входного файла html\n @type filename: string\n \"\"\"\n print('\\t\\t--- Replasing SVG Tags...')\n f = open(os.path.join(self.location, filename), 'r', encoding='utf-8')\n splitter = \".\"\n name = filename.split(splitter)[0]\n INPUT = f.read()\n if \"cover\" in filename or \"tp\" in filename:\n try:\n pattern = r'()'\n image_pattern = r''\n image = re.findall(image_pattern, INPUT, flags=re.S)\n image = image[0]\n new_string = '
\"cover\"
'.format(image)\n image_block = re.findall(pattern, INPUT, flags=re.S)\n image_block = image_block[0]\n INPUT = INPUT.replace(image_block, new_string)\n except:\n print(\"\\t\\t\\t---Ecxeption svg tags\")\n pattern = r''\n strings = re.findall(pattern, INPUT, flags=re.S)\n i = 0\n correctStrings = []\n for imageName in strings:\n #print(imageName)\n correctStrings.append(\n '
\"cover\"
'.format(imageName))\n\n originalString = INPUT\n pattern = '()'\n pattern_obj = re.compile(pattern, re.S)\n replacement_string = correctStrings[i]\n INPUT = pattern_obj.sub(replacement_string, originalString, count=1)\n\n i += 1\n #print(INPUT)\n f.close()\n f = open(os.path.join(self.location, filename), 'w', encoding='utf-8')\n f.write(INPUT)\n f.close()\n\n def replace_markers(self, filename):\n \"\"\"\n работа с маркированными списками\n 1) убираются картинки в маркированных списках(для того, чтобы собственные маркеры\n не выравнивались по центру вместо левого края\n 2)удаление парного открывающегося/закрывающегося тега
    для корректности\n отображения списков\n\n @param filename: имя входного файла html\n @type filename: string\n \"\"\"\n print('\\t\\t--- Replasing Markers...')\n f = open(os.path.join(self.location, filename), mode='r', encoding='utf-8')\n pattern = r'

    \\n*\\s*?(.+?)<\\/p>'\n pattern_full_message = r'(

    \\n*\\s*?.+?<\\/p>)'\n INPUT = f.read()\n # print(INPUT)\n full_messages = re.findall(pattern_full_message, INPUT, re.S) # строки целиком вместе с тегами\n strings = re.findall(pattern, INPUT, re.S) # только текст\n if len(full_messages) == 0 or len(strings) == 0:\n pattern = r'

    \\n*?\\s*?(.+?)<\\/p>'\n pattern_full_message = r'(

    \\n*?\\s*?.+?<\\/p>)'\n full_messages = re.findall(pattern_full_message, INPUT, re.S) # строки целиком вместе с тегами\n strings = re.findall(pattern, INPUT, re.S) # только текст\n i = 0\n correctStrings = [] # исправленные строки с тегами\n for text in strings:\n correctStrings.append('

    • {!s}
    '.format(text))\n INPUT = INPUT.replace(full_messages[i], correctStrings[i])\n i += 1\n # print(INPUT)\n pattern = r'(

    \\n*?\\s*?\\n*?(.+?)<\\/p>)'\n markers = re.findall(pattern, INPUT, re.S)\n for marker in markers:\n INPUT = INPUT.replace(marker[0], \"

    • \" + marker[1] + \"
    \")\n\n pattern = r'(

    \\n*?\\s*?\\n*?(.+?)<\\/p>)'\n markers = re.findall(pattern, INPUT, re.S)\n for marker in markers:\n INPUT = INPUT.replace(marker[0], \"

    • \" + marker[1] + \"
    \")\n\n pattern = r'(

    \\n*?\\s*?\\n*?(.+?)<\\/p>)'\n markers = re.findall(pattern, INPUT, re.S)\n for marker in markers:\n INPUT = INPUT.replace(marker[0], \"

    • \" + marker[1] + \"
    \")\n\n print('\\t\\t--- Editing
      and
    • tags...')\n INPUT = INPUT.replace(\"
    \\n
      \", \"\\n\")\n\n pattern = r'(
      (.+?<\\/div>)<\\/div>)'\n blocks = re.findall(pattern, INPUT, re.S)\n for block in blocks:\n old_block = block[0]\n new_block = \"
        \" + block[1] + \"
      \"\n pattern = r'(
      (.+?)<\\/div>)'\n li_blocks = re.findall(pattern, old_block, re.S)\n for li_block in li_blocks:\n new_li_block = \"
    • \" + li_block[1] + \"
    • \"\n new_block = new_block.replace(li_block[0], new_li_block)\n INPUT = INPUT.replace(old_block, new_block)\n # и ещё они умудрились делать списки без обозначения того, что это списки\n pattern = r'(
      (.+?)<\\/div>)'\n li_blocks = re.findall(pattern, INPUT, re.S)\n for li_block in li_blocks:\n new_li_block = \"
      • \" + li_block[1] + \"
      \"\n INPUT = INPUT.replace(li_block[0], new_li_block)\n\n INPUT = INPUT.replace(\"•\", \"\")\n INPUT = INPUT.replace(\"
    \\n
      \", \"\\n\")\n INPUT = INPUT.replace(\"
      \", \"\\n\")\n pattern = r'
    • ()'\n images_in_li = re.findall(pattern, INPUT, re.S)\n for image_in_li in images_in_li:\n INPUT = INPUT.replace(image_in_li, \"\")\n # удаление от
      до
      \n pattern = r'(
      (.+?)<\\/div>)'\n divs = re.findall(pattern, INPUT, re.S)\n for div in divs:\n INPUT = INPUT.replace(div[0], div[1])\n\n pattern = r'

      ).+?<\\/p>'\n images = re.findall(pattern, INPUT, re.S)\n for image in images:\n INPUT = INPUT.replace(image, \"\")\n INPUT = INPUT.replace(\"○\", \"\")\n f.close()\n f = open(os.path.join(self.location, filename), 'w', encoding='utf-8')\n f.write(INPUT)\n f.close()\n\n def replace_headers(self, filename):\n \"\"\"\n 1)метод заменяет заголовки h5, h4, h3 на h2 и при тегах h1, h2, h3 добавляет к ним\n

      [текст]
      для оформления в читалке\n 2)заменяет тег цитат на right, убирает точки в маркированных списках\n 3)ставит пробел до и после тире\n 4)убирает теги, отсутствующие в нашей читалке(для увеличения размера текста)\n 5)удаляет проблемы с названиями глав, когда первая буква написана большим шрифтом, чем остальные,\n и при этом после первой установлен пробел\n 6)удаляет тег strong\n\n @param filename: имя входного файла html\n @type filename: string\n \"\"\"\n splitter = \".\"\n format = filename.split(splitter)\n format = format[1]\n print('\\t\\t--- Replasing headers...')\n if not \"ncx\" in filename and not \"opf\" in filename:\n f = open(os.path.join(self.location, filename), 'r', encoding='utf-8')\n INPUT = f.read()\n soup = BeautifulSoup(INPUT)\n INPUT = soup.prettify()\n INPUT = INPUT.replace(\"h5\", \"h4\")\n INPUT = INPUT.replace(\"h4\", \"h3\")\n INPUT = INPUT.replace(\"h3\", \"h2\")\n\n pattern = r''\n pattern_full_message = r'()'\n strings = re.findall(pattern, INPUT, re.S) # только текст\n full_message = re.findall(pattern_full_message, INPUT, re.S)\n i = 0\n done_array = []\n for text in full_message:\n if not text in done_array:\n done_array.append(text)\n if int(strings[i]) == 2 or int(strings[i]) == 1 or int(strings[i]) == 3:\n new_message = '
      {!s}
      '.format(text)\n INPUT = INPUT.replace(text, new_message)\n i += 1\n print('\\t\\t--- Correcting quotes...')\n INPUT = INPUT.replace(\"chap-bq\", \"right\")\n INPUT = INPUT.replace(\"—\", \" — \")\n INPUT = INPUT.replace(\"•\", \"\")\n INPUT = INPUT.replace(\"—\", \" — \")\n\n # иногда заворачивают т��кст в три тега:\n pattern = r'(
      (
      )*(.+?)<\\/div>.*?(<\\/div>)*)'\n divs = re.findall(pattern, INPUT, re.S)\n for div in divs:\n new_line = \"

      \" + div[2] + \"

      \"\n INPUT = INPUT.replace(div[0], new_line)\n divs = re.findall(pattern, INPUT, re.S)\n for div in divs:\n new_line = \"

      \" + div[2] + \"

      \"\n INPUT = INPUT.replace(div[0], new_line)\n divs = re.findall(pattern, INPUT, re.S)\n for div in divs:\n new_line = \"

      \" + div[2] + \"

      \"\n INPUT = INPUT.replace(div[0], new_line)\n\n pattern = r'(

      (.+?)<\\/p>)'\n lines = re.findall(pattern, INPUT, re.S)\n for line in lines:\n old = line[0]\n new = \"

      \" + line[1] + \"

      \"\n INPUT = INPUT.replace(old, new)\n\n # удаление \"С качущих\" букв в оглавлении\n pattern = r'(([a-zA-Z]).{1,6}.{1,3}\\s+(.+?)\\n.+?<\\/small>)'\n bad_paragrafs = re.findall(pattern, INPUT, re.S)\n for par in bad_paragrafs:\n INPUT = INPUT.replace(par[0], par[1] + par[2])\n\n # удаление тега strong\n pattern = r'((.+?)<\\/strong>)'\n strong_pars = re.findall(pattern, INPUT, re.S)\n for par in strong_pars:\n INPUT = INPUT.replace(par[0], par[1])\n\n f.close()\n f = open(os.path.join(self.location, filename), 'w', encoding='utf-8')\n f.write(INPUT)\n f.close()\n\n\n def zip(self, res, dst):\n \"\"\"\n создаёт zip архив\n\n @param res: путь до архива (с расширением)\n @type res: string\n\n @param dst: выходной путь (папка)\n @type dst: string\n \"\"\"\n zf = zipfile.ZipFile(\"%s\" % (dst), \"w\", zipfile.ZIP_DEFLATED)\n abs_src = os.path.abspath(res)\n for dirname, subdirs, files in os.walk(res):\n for filename in files:\n absname = os.path.abspath(os.path.join(dirname, filename))\n arcname = absname[len(abs_src) + 1:]\n #print('zipping %s as %s' % (os.path.join(dirname, filename), arcname))\n zf.write(absname, arcname)\n zf.close()\n","sub_path":"Maker.py","file_name":"Maker.py","file_ext":"py","file_size_in_byte":50598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223220615","text":"# Fill in this file with the code to get the next page of data from the Webex Teams exercise\n\n# Make the next paginated API request\nimport requests\nimport json\n\naccess_token = '' # Make sure to add your access token here\nurl = 'https://api.ciscospark.com/v1/memberships'\nheaders = {\n 'Authorization': 'Bearer {}'.format(access_token),\n 'Content-Type': 'application/json'\n}\nparams = {\n \"max\": 1\n}\nres = requests.get(url, headers=headers, params=params)\n\nsecond_response = requests.get(res.links['next']['url'], headers=headers)\nformatted_message = \"\"\"\nWebex Teams Second API Response\n----------------------------------\nResponse Status Code : {}\nResponse Link Header : {}\nResponse Body : {}\n-----------------------------------\n\"\"\".format(second_response.status_code, second_response.headers.get('Link'), json.dumps(second_response.json(), indent=4))\nprint(formatted_message)\n","sub_path":"webex-teams/pagination-next.py","file_name":"pagination-next.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"391045829","text":"# CS181 P1\n#\n\n# read train data set; first N_train lines are for training. \n# Next N_test lines are for testing.\n# Add features from Chem\n# compute RMSE\n\nimport os\nos.environ['RDBASE']='C:\\\\ProgramData\\\\Anaconda2\\\\envs\\\\my-rdkit-env\\\\Lib\\\\site-packages\\\\rdkit'\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nimport rdkit as rd\nfrom rdkit import Chem\n#from rdkit.Chem import AllChem\nfrom rdkit.Chem import Descriptors\n\n#make a smaller train and test dataset for debugging\nN_train = 10000\nN_test = 2000\nfile = 'train_small.csv'\n\n\n# make lists of functions and labels to make features\n#lbls = ['none']\n#fns = ['none']\n\nlbls = ['n_hatoms', 'n_atoms', 'mol_wt',\\\n 'HeavyAtomMolWt', 'ExactMolWt', 'NumValenceElectrons',\\\n 'NumRadicalElectrons']\nfns = [Chem.rdchem.Mol.GetNumHeavyAtoms, Chem.rdchem.Mol.GetNumAtoms, Chem.Descriptors.MolWt,\\\n Chem.Descriptors.HeavyAtomMolWt, Chem.Descriptors.ExactMolWt, Chem.Descriptors.NumValenceElectrons,\\\n Chem.Descriptors.NumRadicalElectrons]\n\n\"\"\"\nRead in train and test as Pandas DataFrames\n\"\"\"\n\ndf_train = pd.read_csv(file)\n#df_test = pd.read_csv(\"test.csv\")\n#print('csv load completed')\n\ndf_train_cropped = df_train[:(N_train+N_test)]\nY_train_val = df_train_cropped[:N_train].gap.values\nX_train = df_train_cropped[:N_train]\n#print(X_train.head())\n\nY_test_val = df_train_cropped[(N_train):(N_train+N_test)].gap.values\nX_test = df_train_cropped[(N_train):(N_train+N_test)]\n\n\n#add some features\ndef add_features(dataframe, labels, functions):\n if labels != ['none']:\n #if True:\n N = dataframe.shape[0]\n N_start = int(dataframe.index[0])\n smiles = dataframe[['smiles']]\n smiles = smiles[:].values\n for label, function in zip(labels, functions):\n M = dataframe.shape[1]\n dataframe.insert(M, label, np.zeros([N,1]))\n print(label)\n for n in range(0, N):\n #print(n)\n mol= Chem.MolFromSmiles(smiles[n,0])\n dataframe.set_value(N_start+n, label, function(mol))\n \nadd_features(X_test, lbls, fns)\n#X_test.head()\nadd_features(X_train, lbls, fns)\n\n\nX_train = X_train.drop(['smiles', 'gap'], axis=1)\nX_train_val = X_train.values\n\nX_test = X_test.drop(['smiles', 'gap'], axis=1)\nX_test_val = X_test.values\n\nprint('running Linear regression...')\nLR = LinearRegression()\nLR.fit(X_train_val, Y_train_val)\nLR_pred = LR.predict(X_test)\n\nprint('running Random forest regression...')\nRF = RandomForestRegressor()\nRF.fit(X_train_val, Y_train_val)\nRF_pred = RF.predict(X_test)\n\ndef write_to_file(filename, predictions):\n with open(filename, \"w\") as f:\n f.write(\"Id,Prediction\\n\")\n for i,p in enumerate(predictions):\n f.write(str(i+1) + \",\" + str(p) + \"\\n\")\n\nwrite_to_file(\"sample1.csv\", LR_pred)\nwrite_to_file(\"sample2.csv\", RF_pred)\n\n#Compute RMSE\nprint(fns)\nprint(lbls)\n\nRMSE_LR = np.sqrt(np.sum(np.dot((LR_pred-Y_test_val), (LR_pred-Y_test_val)))/N_test)\nprint(('LR RMSE = ' +str(RMSE_LR)))\n\nRMSE_RF = np.sqrt(np.sum(np.dot((RF_pred-Y_test_val), (RF_pred-Y_test_val)))/N_test)\nprint(('RF RMSE = ' +str(RMSE_RF)))","sub_path":"p1/sample_yuliya.py","file_name":"sample_yuliya.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186733631","text":"import socket\n\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ns.connect((\"www.baidu.com\",80))\ns.send(b'GET / HTTP/1.1\\r\\nHost: www.baidu.com\\r\\nUser-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0\\r\\nConnection: close\\r\\n\\r\\n')\nwhile True:\n d = s.recv(1024)\n if d:\n print(d) \n else:\n break","sub_path":"socket编程/simple1.py","file_name":"simple1.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"439981724","text":"from .errors import ShakespeareRuntimeError\nfrom .character import Character\nfrom .utils import normalize_name\n\n\nclass State:\n \"\"\"State of a Shakespeare play execution context: variable values and who is on stage.\"\"\"\n\n def __init__(self, personae):\n self.global_boolean = False\n self.characters = [Character.from_dramatis_persona(p) for p in personae]\n\n def __str__(self):\n return \"\\n\".join(\n [f\"global boolean = {self.global_boolean}\", \"on stage:\"]\n + [f\" {c}\" for c in self.characters if c.on_stage]\n + [\"off stage:\"]\n + [f\" {c}\" for c in self.characters if not c.on_stage]\n )\n\n def enter_characters(self, characters):\n characters_to_enter = [self.character_by_name(name) for name in characters]\n for character in characters_to_enter:\n self.assert_character_off_stage(character)\n for character in characters_to_enter:\n character.on_stage = True\n\n def exeunt_characters(self, characters):\n characters_to_exeunt = [self.character_by_name(name) for name in characters]\n for character in characters_to_exeunt:\n self.assert_character_on_stage(character)\n for character in characters_to_exeunt:\n character.on_stage = False\n\n def exeunt_all(self):\n for character in self.characters:\n character.on_stage = False\n\n def exit_character(self, character):\n character = self.character_by_name(character)\n self.assert_character_on_stage(character)\n character.on_stage = False\n\n def character_opposite(self, character):\n characters_opposite = [\n x for x in self.characters if x.on_stage and x.name != character.name\n ]\n if len(characters_opposite) > 1:\n raise ShakespeareRuntimeError(\"Ambiguous second-person pronoun\")\n elif len(characters_opposite) == 0:\n raise ShakespeareRuntimeError(character.name + \" is talking to nobody!\")\n return characters_opposite[0]\n\n def character_by_name(self, name):\n name = normalize_name(name)\n match = next(\n (x for x in self.characters if x.name.lower() == name.lower()), None\n )\n if match is not None:\n return match\n else:\n raise ShakespeareRuntimeError(name + \" was not initialized!\")\n\n def character_by_name_if_necessary(self, character):\n if isinstance(character, str):\n return self.character_by_name(character)\n else:\n return character\n\n def assert_character_on_stage(self, character):\n if character.on_stage == False:\n raise ShakespeareRuntimeError(character.name + \" is not on stage!\")\n\n def assert_character_off_stage(self, character):\n if character.on_stage == True:\n raise ShakespeareRuntimeError(character.name + \" is already on stage!\")\n","sub_path":"shakespearelang/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28665883","text":"\nfrom unittest import TestCase\n\nfrom app import app\nfrom models import db, User\n\n# Use a test database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:2118@localhost/blogly_test'\napp.config['SQLALCHEMY_ECHO'] = False\n\ndb.drop_all()\ndb.create_all()\n\nclass UserModelTestCase(TestCase):\n\t\"\"\"Tests for model for Users\"\"\"\n\t\n\tdef setUp(self):\n\t\t\"\"\"Add sample user\"\"\"\n\n\t\tUser.query.delete()\n\t\t\n\tdef tearDown(self):\n\t\t\"\"\"Clear transactions\"\"\"\n\n\t\tdb.session.rollback()\n\t\n\tdef test_full_name(self):\n\t\tuser = User(first_name = 'John', last_name = 'Smith', image_url = 'https://cdn.pixabay.com/photo/2014/04/03/11/08/american-football-311817_960_720.png')\n\t\tdb.session.add(user)\n\t\tdb.session.commit()\n\t\t\n\t\tfull_name = user.full_name\n\t\tself.assertEqual(full_name, \"John Smith\")\t\n","sub_path":"test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"45641609","text":"\nimport sys, os\n\n#print(os.path.abspath('../'))\nsys.path.append(os.path.abspath(os.path.join('../attributesGen/')))\n\nimport os\nfrom io import BytesIO\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom scipy.misc import imread\nfrom scipy.misc import imsave\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nimport math\n\nimport seaborn as sns\nfrom scipy import stats\n\nimport imageio\n\nimport PIL\nfrom PIL import Image\n\nimport tensorflow as tf\nfrom tensorflow.contrib.slim.nets import inception\nimport argparse\nimport os.path\nfrom os import listdir\nfrom os.path import isfile, join\nimport re\nimport sys\nimport tarfile\nimport random\n\nimport numpy as np\nfrom six.moves import urllib\n\n\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as st\nimport statsmodels as sm\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport cycler\n\nfrom InceptionModel.inception_utils import load_model, load_labels_vocabulary, make_predictions_and_gradients, top_label_id_and_score,top_label_id_and_layer\nfrom IntegratedGradients.integrated_gradients import integrated_gradients, random_baseline_integrated_gradients\nfrom VisualizationLibrary.visualization_lib import Visualize, show_pil_image, pil_image\nfrom imagenet import create_readable_names_for_imagenet_labels\n\nMODEL_LOC='../attributesGen/InceptionModel/inception_v3_2016_08_28_frozen.pb'\nLABELS_LOC='../attributesGen/InceptionModel/imagenet_slim_labels.txt'\n\n\n\nmatplotlib.rcParams['figure.figsize'] = (16.0, 12.0)\nmatplotlib.style.use('ggplot')\n#matplotlib.rcParams[key] = eval(config._sections['matplotlib.rcParams'][key]) \n#matplotlib.rcParams['axes.prop_cycle'] = cycler.cycler(color=hexcolor)\n\n\nslim = tf.contrib.slim\ntensorflow_master = \"\"\ncheckpoint_path = \"../preReq/inception-v3/inception_v3.ckpt\"\nmax_epsilon = 20.0\nimage_width = 299\nimage_height = 299\n#batch_size = 1\nbatch_size = 50\nmodel_dir = '../preReq/imageNetMapping'\n\n\neps = 2.0 * max_epsilon / 255.0\nbatch_shape = (batch_size, image_height, image_width, 3)\nnum_classes = 1001\n\n\ncategories = pd.read_csv(\"../preReq/nips-2017-adversarial-learning-development-set/categories.csv\")\nimage_classes = pd.read_csv(\"../preReq/nips-2017-adversarial-learning-development-set/images.csv\")\n\nfilterCutOff = 0.9\n#power = 10\n#samples = 2\nsamples = 100\ne = math.e\n\n\nnameV3 = create_readable_names_for_imagenet_labels()\n\n\ndef best_fit_distribution(data, bins=1000, ax=None):\n \"\"\"Model data by finding best fit distribution to data\"\"\"\n # Get histogram of original data\n y, x = np.histogram(data, bins=bins, density=True)\n x = (x + np.roll(x, -1))[:-1] / 2.0\n\n # Distributions to check\n DISTRIBUTIONS = [ \n st.cauchy,st.dweibull,st.gennorm\n #st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine, #cauchy\n #st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk, #dweibull\n #st.foldcauchy,st.foldnorm,st.frechet_r,st.frechet_l,st.genlogistic,st.genpareto,st.gennorm,st.genexpon, #gennorm\n #st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r,\n #st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss,\n #st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,st.levy_stable,\n #st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf,\n #st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal,#nct\n #st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda,\n #st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy\n ]\n\n # Best holders\n best_distribution = st.norm\n best_params = (0.0, 1.0)\n best_sse = np.inf\n\n # Estimate distribution parameters from data\n for distribution in DISTRIBUTIONS:\n\n # Try to fit the distribution\n try:\n # Ignore warnings from data that can't be fit\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n\n # fit dist to data\n params = distribution.fit(data)\n print(params)\n\n # Separate parts of parameters\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n\n # Calculate fitted PDF and error with fit in distribution\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y - pdf, 2.0))\n\n # if axis pass in add to plot\n try:\n if ax:\n pd.Series(pdf, x).plot(ax=ax)\n end\n except Exception:\n pass\n\n # identify if this distribution is better\n if best_sse > sse > 0:\n best_distribution = distribution\n best_params = params\n best_sse = sse\n\n except Exception:\n pass\n\n return (best_distribution.name, best_params)\n\n\n\n\n\ndef make_pdf(dist, params, size=10000):\n \"\"\"Generate distributions's Probability Distribution Function \"\"\"\n\n # Separate parts of parameters\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n\n # Get sane start and end points of distribution\n start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)\n end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)\n\n\n\n # Build PDF and turn into pandas Series\n x = np.linspace(start, end, size)\n y = dist.pdf(x, loc=loc, scale=scale, *arg)\n pdf = pd.Series(y, x)\n\n return pdf\n\n\ndef plot(imattr):\n print(\"In plotting function\")\n x = np.array(imattr).flatten()\n data = pd.DataFrame(x)\n params = st.gennorm.fit(x)\n\n #parameters = norm.fit(x)\n print(\"parameters\",params)\n\n y = np.linspace(-0.01,0.01,50000)\n\n pdf = make_pdf(st.gennorm, params)\n ax = pdf.plot(lw=2, label='PDF', legend=True)\n #data.plot(kind='hist', bins=1000, normed=True, alpha=0.5, label='Data', legend=True, ax=ax)\n\n\n fittedPdf = st.gennorm.pdf(y,beta=params[0],loc=params[1],scale=params[2])\n print(st.gennorm.cdf(0.00001,beta=params[0],loc=params[1],scale=params[2]))\n\n\n #exit()\n\n #normalPdf = st.gennorm.pdf(y,*params)\n\n plt.plot(y,fittedPdf,\"red\") \n #plt.plot(y,normalPdf,\"blue\") \n plt.hist(x,bins=1000,normed=False,color=\"green\")\n plt.hist(x,bins=1000,normed=True,color=\"red\")\n plt.show()\n exit()\n #sns.distplot(x)\n\n\n\n\n\n\n\n\ndef plot1(imattr):\n print(\"In plotting function\")\n x = np.array(imattr).flatten()\n\n\n\n data = pd.DataFrame(x)\n\n # Plot for comparison\n plt.figure(figsize=(12,8))\n ax = data.plot(kind='hist', bins=1000, normed=True, alpha=0.5)#, color=plt.rcParams['axes.color_cycle'][1])\n # Save plot limits\n dataYLim = ax.get_ylim()\n\n # Find best fit distribution\n best_fit_name, best_fit_params = best_fit_distribution(data, 200, ax)\n best_dist = getattr(st, best_fit_name)\n\n # Update plots\n ax.set_ylim(dataYLim)\n ax.set_title(u'El Nino sea temp.\\n All Fitted Distributions')\n ax.set_xlabel(u'Temp C')\n ax.set_ylabel('Frequency')\n\n # Make PDF with best params \n pdf = make_pdf(best_dist, best_fit_params)\n\n # Display\n plt.figure(figsize=(12,8))\n ax = pdf.plot(lw=2, label='PDF', legend=True)\n data.plot(kind='hist', bins=1000, normed=True, alpha=0.5, label='Data', legend=True, ax=ax)\n\n param_names = (best_dist.shapes + ', loc, scale').split(', ') if best_dist.shapes else ['loc', 'scale']\n param_str = ', '.join(['{}={:0.2f}'.format(k,v) for k,v in zip(param_names, best_fit_params)])\n dist_str = '{}({})'.format(best_fit_name, param_str)\n\n ax.set_title(u'El Nino sea temp. with best fit distribution \\n' + dist_str)\n ax.set_xlabel(u'Temp. (C)')\n ax.set_ylabel('Frequency')\n plt.show()\n \n exit()\n\n\n\n parameters = norm.fit(x)\n print(\"parameters\",parameters)\n #exit()\n\n y = np.linspace(-0.01,0.01,10000)\n\n fittedPdf = norm.pdf(y,loc=parameters[0],scale=parameters[1]/50.0)\n\n normalPdf = norm.pdf(y)\n\n plt.plot(y,fittedPdf,\"red\") \n plt.plot(y,normalPdf,\"blue\") \n plt.hist(x,bins=1000)\n plt.show()\n #sns.distplot(x)\n\n\n\ndef randomFilter(x0,x1,x2):\n #generate random numbers\n s = np.random.uniform(0,1)\n #print(s)\n\n #div = e**(1.0/(1.0-filterCutOff))\n #print(e,1.0/div)\n #x0 = e**(1.0/(1.0-cd0))/div - e/div\n #x1 = e**(1.0/(1.0-cd1))/div - e/div\n #x2 = e**(1.0/(1.0-cd2))/div - e/div\n\n if x0 > s or x1 > s or x2 > s:\n #print(cd0,x0,cd1,x1,cd2,x2)\n #print(\"returning 1\")\n return 1, s\n else:\n #print(\"returning 0\")\n return 0 , s\n\n\n #print(cd0,x0,cd1,x1,cd2,x2)\n\n\n\n\n\ndef getFilteredData(imattra, imdata, power, sign):\n #print(imattra)\n print(imattra.shape,imdata.shape,power,sign)\n\n\n imattr = np.copy(imattra)\n imdataA = np.copy(imdata)\n \n imdataA[imdataA<0.01] = 0.01\n imattr = imattr/imdataA\n imattrFlat = imattr.flatten()\n\n \n indexSort = np.argsort(imattrFlat)\n indexVal = np.zeros(imattrFlat.shape[0])\n\n for i in range(indexSort.shape[0]):\n indexVal[indexSort[i]] = i\n\n\n #x = np.array(imattr).flatten()\n\n #params = st.gennorm.fit(x)\n\n filteredData = np.copy(imdata)\n\n filteredDataNp = np.zeros((samples,filteredData.shape[0],filteredData.shape[1],filteredData.shape[2]))\n filteredDataPlaceHolder = np.zeros((samples,filteredData.shape[0],filteredData.shape[1]))\n\n for i in range(samples):\n filteredDataNp[i] = filteredData\n \n count = 0\n for i in range(imdata.shape[0]):\n for j in range(imdata.shape[1]):\n\n\n cd0 = indexVal[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+0]\n cd1 = indexVal[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+1]\n cd2 = indexVal[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+2]\n print(imattrFlat[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+0],\"vs\",imattr[i][j][0])\n print(imattrFlat[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+1],\"vs\",imattr[i][j][1])\n print(imattrFlat[i*imdata.shape[0]*imdata.shape[1]+j*imdata.shape[1]+2],\"vs\",imattr[i][j][2])\n\n #cd0 = st.gennorm.cdf(imattr[i][j][0],beta=params[0],loc=params[1],scale=params[2])\n #cd1 = st.gennorm.cdf(imattr[i][j][1],beta=params[0],loc=params[1],scale=params[2])\n #cd2 = st.gennorm.cdf(imattr[i][j][2],beta=params[0],loc=params[1],scale=params[2])\n x0 = cd0**power;\n x1 = cd1**power;\n x2 = cd2**power;\n\n\n\n for l in range(samples):\n filterFlag, s = randomFilter(x0,x1,x2) \n if filterFlag == 1:\n\n #print(cd0,cd1,cd2,x0,x1,x2,s)\n filteredDataPlaceHolder[l][i][j] = 1\n count = count + 1\n\n #for l in range(samples):\n #if cd0 > 0.99 or cd1 > 0.99 or cd2 > 0.99:\n #filteredDataNp[l][i][j][0]=0\n #filteredDataNp[l][i][j][1]=0\n #filteredDataNp[l][i][j][2]=0\n \n\n\n tot = imdata.shape[0]*imdata.shape[1]*samples\n\n #exit()\n\n\n #previous paper has alredy hinted to an optimal removal strategy we want to remove 0.1% only!\n\n optimalRemoval = 0.2\n currentRemoval = count*100.0/tot\n\n ratio = optimalRemoval/currentRemoval\n\n updatedCount = 0\n for l in range(samples):\n for i in range(imdata.shape[0]):\n for j in range(imdata.shape[1]):\n if filteredDataPlaceHolder[l][i][j] == 1:\n s = np.random.uniform(0,1)\n if s <= ratio:\n filteredDataNp[l][i][j][0]=0\n filteredDataNp[l][i][j][1]=0\n filteredDataNp[l][i][j][2]=0\n updatedCount = updatedCount+1\n\n print(\"count is\",count, \" vs \", tot, \" percent \",currentRemoval ,\" updatedCount \",updatedCount*100.0/tot)\n #exit()\n\n return filteredDataNp\n\n\n\n\n\n\n\nclass NodeLookup(object):\n \"\"\"Converts integer node ID's to human readable labels.\"\"\"\n\n def __init__(self,\n label_lookup_path=None,\n uid_lookup_path=None):\n if not label_lookup_path:\n label_lookup_path = os.path.join( \n model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')\n if not uid_lookup_path:\n uid_lookup_path = os.path.join(\n model_dir, 'imagenet_synset_to_human_label_map.txt')\n self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\n\n def load(self, label_lookup_path, uid_lookup_path):\n \"\"\"Loads a human readable English name for each softmax node.\n\n Args:\n label_lookup_path: string UID to integer node ID.\n uid_lookup_path: string UID to human-readable string.\n\n Returns:\n dict from integer node ID to human-readable string.\n \"\"\"\n if not tf.gfile.Exists(uid_lookup_path):\n tf.logging.fatal('File does not exist %s', uid_lookup_path)\n if not tf.gfile.Exists(label_lookup_path):\n tf.logging.fatal('File does not exist %s', label_lookup_path)\n\n # Loads mapping from string UID to human-readable string\n proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\n self.uid_to_human = {}\n p = re.compile(r'[n\\d]*[ \\S,]*')\n for line in proto_as_ascii_lines:\n parsed_items = p.findall(line)\n uid = parsed_items[0]\n human_string = parsed_items[2]\n self.uid_to_human[uid] = human_string\n\n # Loads mapping from string UID to integer node ID.\n self.node_id_to_uid = {}\n self.uid_to_node_id = {}\n proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\n for line in proto_as_ascii:\n if line.startswith(' target_class:'):\n target_class = int(line.split(': ')[1])\n if line.startswith(' target_class_string:'):\n target_class_string = line.split(': ')[1]\n self.node_id_to_uid[target_class] = target_class_string[1:-2]\n #print(target_class_string[1:-2])\n self.uid_to_node_id[target_class_string[1:-2]] = target_class\n\n # Loads the final mapping of integer node ID to human-readable string\n node_id_to_name = {}\n for key, val in self.node_id_to_uid.items():\n if val not in self.uid_to_human:\n tf.logging.fatal('Failed to locate: %s', val)\n name = self.uid_to_human[val]\n node_id_to_name[key] = name\n\n return node_id_to_name\n\n def id_to_string(self, node_id):\n if node_id not in self.node_lookup:\n return ''\n return self.node_lookup[node_id]\n\n def uid_to_string(self,uid):\n if uid not in self.uid_to_human:\n return ''\n return self.uid_to_human[uid]\n\n def uid_to_id(self,uid):\n if uid not in self.uid_to_node_id:\n return ''\n return self.uid_to_node_id[uid]\n\n\n\nimagePathOrig = sys.argv[1]\nlabelPath = sys.argv[2] \nattrPath = sys.argv[3]\nanalysisStore = sys.argv[4] \nimageStore = sys.argv[5]\norigFlag = int(sys.argv[6])\n\n\n\n#imagePathOrig = '../dataStore/attackILSVRC/FGSM2'\n#labelPath = '../dataStoreNew/originalILSVRC/labels.npy'\n#attrPath = '../dataStore/attackILSVRCAttr/FGSM2/'\n#labelPath = '../dataStore/originalILSVRC/labels.npy'\n#analysisStore = \"./attrFlipDataStore/FGSM2ILSVRC_New.npy\"\n#imageStore = \"./attrFlipDataStore/FGSM2/\"\n\nlabelStore = np.load(labelPath)\n\ndef load_images(img_path,batch_shape):\n print(\"In load imagesI\")\n images = np.zeros(batch_shape)\n labels = []\n path = []\n idx = 0\n batch_size = batch_shape[0]\n for i in range(1000):\n fullPath = os.path.join(img_path,str(i)+\".JPEG\")\n print(fullPath,labelStore[i])\n images[idx, :, :, :] = np.load(fullPath+\".npy\")\n labels.append(labelStore[i])\n path.append(str(i)+\".JPEG\")\n idx+=1\n if idx == batch_size:\n yield labels, images, path\n labels = []\n path = []\n images = np.zeros(batch_shape)\n idx = 0\n if idx > 0:\n yield labels, images, path\n\n\n\n\n\n\n# Load the Inception model for attributions.\nattr_sess, attr_graph = load_model(MODEL_LOC)\ninception_predictions_and_gradients = make_predictions_and_gradients(attr_sess, attr_graph)\nattr_labels = load_labels_vocabulary(LABELS_LOC)\nimage_iterator = load_images(imagePathOrig, batch_shape)\nattr_iterator = load_images(attrPath, batch_shape)\n\n\n\n#power = [8,10,15]\npower = [2,25,50,100]\n#power = [2,5,8,10,15]\nprint(len(power))\n\ncounterSame = 0\ncounterPert = 0\n\n\ncrossEntropyStore = np.zeros((len(power),1000))\nentropyStore = np.zeros((len(power),1000))\ncountStore = np.zeros((len(power),1000))\nsameFlag = np.zeros(1000)\nflipProbStore = np.zeros((len(power),1000))\n\nprint(sameFlag.shape[0])\n\n\nfor i in range(20):\n labels, images , path= next(image_iterator)\n _, attrs , path= next(attr_iterator)\n for j in range(0,batch_size):\n count = i*batch_size+j;\n\n topLabel, px = top_label_id_and_layer(images[j], inception_predictions_and_gradients)\n \n attributions = attrs[j]\n img = (images[j]+1.0)/2.0*255.0\n #img = np.uint8((images[j]+1.0)/2.0*255.0)\n\n if topLabel == labels[j]:\n counterSame += 1\n sameFlag[count] = 1\n else:\n counterPert += 1\n\n for k in range(len(power)):\n filteredImages = getFilteredData(attributions,images[j],power[k],1)\n qx = np.zeros((1,1001))\n countChange = 0\n countSame = 0\n for s in range(samples):\n #fileName = './temp/'+str(count)+\"_\"+str(k)+\"_\"+str(s)+\".JPEG\"\n #a = np.uint8((filteredImages[s]+1.0)/2.0*255.0)\n #imgo = Image.fromarray(a)\n #print(fileName)\n #imgo.save(fileName,\"JPEG\")\n \n topLabelTemp, layerTemp = top_label_id_and_layer(filteredImages[s], inception_predictions_and_gradients)\n print(\"topLabel \",topLabel, \" topLabelTemp:\",topLabelTemp, \" actualLabel:\",labels[j])\n #qx = qx+(np.array(layerTemp)/float(samples))\n qx[topLabelTemp] = qx[topLabelTemp]+1\n\n if topLabel == labels[j]:\n if topLabelTemp == topLabel:\n countSame = countSame + 1\n else:\n if topLabelTemp != topLabel:\n countChange = countChange + 1\n\n #Calculate crossentropy\n print(px.shape)\n crossEntropy = 0\n entropy = 0\n for p in range(px.shape[1]):\n #print(p,crossEntropy,entropy,px[0][p],qx[0][p])\n if px[0][p] < sys.float_info.min:\n px[0][p] = sys.float_info.min\n if qx[0][p] < sys.float_info.min:\n qx[0][p] = sys.float_info.min\n\n\n crossEntropy = crossEntropy - px[0][p]*math.log(qx[0][p],2)\n entropy = entropy - qx[0][p]*math.log(qx[0][p],2)\n\n flipProbStore[k][count] = 1 - qx[0][topLabel]; \n crossEntropyStore[k][count] = crossEntropy\n entropyStore[k][count] = entropy\n print(\"crossEntropy \",crossEntropy,\" entropy\",entropy,\" flip prob:\",flipProbStore[k][count])\n print(\"countChange \",countChange, \"countSame \",countSame)\n if sameFlag[count] == 1:\n countStore[k][count]=countSame\n else:\n countStore[k][count]=countChange\n \n\n\nnp.save(imageStore+\"entropy\",entropyStore)\nnp.save(imageStore+\"crossentropy\",crossEntropyStore)\nnp.save(imageStore+\"count\",countStore)\nnp.save(imageStore+\"sameFlag\",sameFlag)\nnp.save(imageStore+\"flipProb\",flipProbStore)\n\n\n\n\n\n#print stuff\n\nif origFlag == 1:\n for k in range(len(power)):\n for i in range(1000):\n if sameFlag[i] == 1:\n print(power[k],\" count:\",countStore[k][i],\" entropy:\",entropyStore[k][i],\" crossentropy:\",crossEntropyStore[k][i])\n\nelse:\n for k in range(len(power)):\n for i in range(1000):\n if sameFlag[i] == 0:\n print(power[k],\" count:\",countStore[k][i],\" entropy:\",entropyStore[k][i],\" crossentropy:\",crossEntropyStore[k][i])\n\n \n\n\n\n\n\n\n\n","sub_path":"ILSVRC_NIPS/distAttrAnalysis/distAttrAnalysisByXi.py","file_name":"distAttrAnalysisByXi.py","file_ext":"py","file_size_in_byte":20532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"77491552","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUsage:\n $python3 lightfm_recsys.py interactions_data_file_path subsampling_datasize\n\"\"\"\n\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import csr_matrix\nfrom IPython.display import display_html\nimport warnings\nfrom lightfm.cross_validation import random_train_test_split\nfrom lightfm.evaluation import auc_score, precision_at_k, recall_at_k\nfrom lightfm import LightFM\nimport time\n\n# update the working directory to the root of the project\n# os.chdir('..')\nwarnings.filterwarnings(\"ignore\")\n\n\ndef load_data(file_name):\n return pd.read_csv(file_name)\n\n\ndef clean_data(data):\n interactions_selected = data.loc[data['is_read'] == 1, ['user_id', 'book_id', 'rating']]\n interactions_selected = interactions_selected[\n interactions_selected['user_id'].isin(list(interactions_selected['user_id'].unique()))]\n return interactions_selected\n\n\ndef down_sampling(data, k):\n return data.sample(k)\n\n\ndef csr(cleaned_interactions_data):\n user_book_interaction = pd.pivot_table(cleaned_interactions_data, index='user_id', columns='book_id',\n values='rating')\n # fill missing values with 0\n user_book_interaction = user_book_interaction.fillna(0)\n user_book_interaction_csr = csr_matrix(user_book_interaction.values)\n return user_book_interaction_csr\n\n\ndef train_val_split(csr_mat):\n train, val = random_train_test_split(csr_mat, test_percentage=0.2)\n return (train, val)\n\n\ndef fit(train):\n model = LightFM(loss='warp',\n random_state=2016,\n learning_rate=0.01,\n no_components=30,\n user_alpha=0.000005,\n item_alpha=0.000005)\n start_time = time.time()\n model = model.fit(train,\n epochs=100,\n num_threads=16, verbose=False)\n end_time = time.time()\n print(\"Training time is:\", end_time - start_time)\n return model\n\n\ndef eval(model, train, val):\n # auc\n print(\"Train auc: %.2f\" % auc_score(model, train).mean())\n print(\"Val auc: %.2f\" % auc_score(model, val).mean())\n # precision_at_k\n print(\"Train precision: %.2f\" % precision_at_k(model, train, k=5).mean())\n print(\"Val precision: %.2f\" % precision_at_k(model, val, k=5).mean())\n # recall_at_k\n print(\"Train recall: %.2f\" % precision_at_k(model, train, k=5).mean())\n print(\"Val recall: %.2f\" % precision_at_k(model, val, k=5).mean())\n\n\nif __name__ == '__main__':\n # Get the parameters from the command line\n file = sys.argv[1]\n datasize = int(sys.argv[2])\n\n # Call our main routine\n csr_matrix_ = down_sampling(clean_data(load_data(file)), k=datasize)\n train, val = train_val_split(csr_matrix_)\n model = fit(train)\n eval(model, train, val)\n","sub_path":"lightfm/lightfm_recsys.py","file_name":"lightfm_recsys.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"235451847","text":"\"\"\"\nSync tool.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom pathlib import Path\nfrom typing import Sequence, Mapping\n\nfrom tyrannosaurus.context import _Context\n\nlogger = logging.getLogger(__package__)\n\n\nclass Sync:\n def __init__(self, context: _Context, dry_run: bool):\n self.context = context\n self.dry_run = dry_run\n\n def sync(self, path: Path) -> Sequence[str]:\n context = _Context(path, dry_run=self.dry_run)\n self.fix_init()\n self.fix_recipe()\n return [str(s) for s in context.targets]\n\n def has(self, key: str):\n return self.context.has_target(key)\n\n def replace_substrs(self, path: Path, replace: Mapping[str, str]) -> None:\n self.context.back_up(path)\n new_lines = []\n for line in path.read_text(encoding=\"utf8\").splitlines():\n for k, v in replace.items():\n if line.startswith(k):\n new_lines.append(v)\n break\n else:\n new_lines.append(line)\n new_lines = \"\\n\".join(new_lines)\n if not self.dry_run:\n path.write_text(new_lines, encoding=\"utf8\")\n logger.debug(\"Wrote to {}\".format(path))\n\n def fix_init(self) -> None:\n if self.has(\"init\"):\n self.replace_substrs(\n self.context.path / self.context.project / \"__init__.py\",\n {\n \"__status__ = \": '__status__ = \"{}\"'.format(self.context.source(\"status\")),\n \"__copyright__ = \": '__copyright__ = \"{}\"'.format(\n self.context.source(\"copyright\")\n ),\n \"__date__ = \": '__date__ = \"{}\"'.format(self.context.source(\"date\")),\n },\n )\n\n def fix_recipe(self) -> None:\n if self.has(\"recipe\"):\n self.replace_substrs(\n self.context.path_source(\"recipe\"),\n {\"{% set version = \": '{% set version = \"' + str(self.context.version) + '\" %}'},\n )\n\n\n__all__ = [\"Sync\"]\n","sub_path":"tyrannosaurus/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646521110","text":"\nimport os\nbase_dir = os.path.dirname(os.path.realpath(__file__))\n\nimport sys\nsys.path.extend([os.path.join(base_dir, '../../../..')])\n\nimport numpy as np\nimport pandas as pd\nfrom math import log10\n\nimport glob\nimport argparse\nimport pickle\nfrom itertools import chain\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.cm as cm\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as pltcol\nfrom pylab import rcParams\n\nfrom HetMan.features.variants import MuType\n\n\ndef load_output(cohort):\n out_list = [\n pickle.load(open(fl, 'rb')) for fl in\n glob.glob(os.path.join(base_dir, \"output\", cohort, \"results/ex*\"))\n ]\n\n out_data = {fld: dict(chain(*map(dict.items, [x[fld] for x in out_list])))\n for fld in out_list[0].keys()}\n\n return out_data\n\n\ndef choose_colour_scheme(clr_scheme, **clr_args):\n\n if clr_scheme == 'Dist':\n norm = mpl.colors.Normalize(vmin=-0.5, vmax=0.5)\n cmap = pltcol.LinearSegmentedColormap.from_list(\n 'new_map', [(1, 0, 0), (0, 0, 1)]\n )\n m = cm.ScalarMappable(norm=norm, cmap=cmap)\n\n plt_clr = m.to_rgba(list(\n clr_args['out_data']['Dist'][clr_args['mtype1'],\n clr_args['mtype2']]\n )[0])\n \n elif clr_scheme[0] == 'Gene':\n if clr_args['gn1'] == clr_scheme[1] or clr_args['gn2'] == clr_scheme[1]:\n plt_clr = '#172457'\n else:\n plt_clr = '#806015'\n\n return plt_clr\n\n\ndef get_colour_label(clr_scheme):\n if clr_scheme == 'Dist':\n clr_lbl = 'dist'\n else:\n clr_lbl = 'gene'\n\n return clr_lbl\n\n\ndef plot_predicted_means(cohort, mutex_dict, clr_scheme='Dist'):\n rcParams['figure.figsize'] = 15, 15\n\n cmap = pltcol.LinearSegmentedColormap.from_list(\n 'new_map', [(1, 0, 0), (0, 0, 1)]\n )\n\n plt_x = []\n plt_y = []\n plt_mtypes = []\n\n for mtype1, mtype2 in out_data['Acc']:\n acc = min(out_data['Acc'][mtype1, mtype2])\n\n if acc > 0.7:\n plt_mtypes += [(mtype1, mtype2)]\n gn1 = [k for k,v in mtype1][0]\n gn2 = [k for k,v in mtype2][0]\n\n plt_x += [out_data['Stat'][mtype1, mtype2][0][0]]\n plt_y += [out_data['Stat'][mtype1, mtype2][0][2]]\n plt_alpha = acc ** 4.0\n plt_clr = choose_colour_scheme(clr_scheme)\n\n if gn1 == gn2:\n plt_mark = 'o'\n else:\n plt_mark = 's'\n\n plt.scatter(plt_x[-1], plt_y[-1],\n alpha=plt_alpha, s=65, c=plt_col, marker=plt_mark)\n\n annot_enum = enumerate(zip(plt_x, plt_y, plt_mtypes))\n for i, (x, y, (mtype1, mtype2)) in annot_enum:\n\n if all(x < (xs - 1) or x > xs or y < (ys - 0.1) or y > (ys + 0.1)\n for xs, ys in zip(\n plt_x[:i] + plt_x[i+1:], plt_y[:i] + plt_y[i+1:]\n )):\n plt.annotate('{}|{}'.format(str(mtype1), str(mtype2)),\n (x, y), (x, y + 0.06),\n size=\"small\", stretch=\"condensed\")\n\n elif (x > 1\n and all(x < xs or x > (xs + 5.0/7)\n or y < (ys - 0.1) or y > (ys + 0.1)\n for xs, ys in zip(plt_x[:i] + plt_x[i+1:],\n plt_y[:i] + plt_y[i+1:]))\n ):\n plt.annotate('{}|{}'.format(str(mtype1), str(mtype2)),\n (x, y), (x-0.5, y + 0.06),\n size=\"small\", stretch=\"condensed\")\n\n plt.xlim(0,1)\n plt.ylim(0,1)\n plt.plot([0,1], linewidth=3, color = 'black', ls='--', alpha=0.5)\n \n plt.savefig(os.path.join(base_dir, 'plots',\n cohort + '_mutex-preds_' + clr_lbl + '.png'),\n dpi=500, bbox_inches='tight')\n plt.close()\n\n\ndef plot_predictions(args, out_data, mutex_dict, mtypes):\n\n rcParams['figure.figsize'] = 5, 5\n\n cur_stat = out_data['Stat'][mtypes]\n\n plt.scatter(cur_stat[0], cur_stat[1],\n s=150, marker='x')\n\n plt.annotate('Neither Mutation',\n (cur_stat[0][0], cur_stat[1][0]),\n (cur_stat[0][0]+0.03, cur_stat[1][0]+0.03))\n plt.annotate('Only Other Mutation Present',\n (cur_stat[0][1], cur_stat[1][1]),\n (cur_stat[0][1]+0.03, cur_stat[1][1]+0.03))\n plt.annotate('Only Current Mutation Present',\n (cur_stat[0][2], cur_stat[1][2]),\n (cur_stat[0][2]+0.03, cur_stat[1][2]+0.03))\n plt.annotate('Both Mutations',\n (cur_stat[0][3], cur_stat[1][3]),\n (cur_stat[0][3]+0.03, cur_stat[1][3]+0.03))\n\n plt.xlabel(str(mtypes[0]) + ' Predictions',\n fontsize=15, weight=550, stretch=340)\n plt.ylabel(str(mtypes[1]) + ' Predictions',\n fontsize=15, weight=550, stretch=340)\n\n plt.xticks(fontsize=12, weight=510)\n plt.yticks(fontsize=12, weight=510)\n\n plt.xlim(0,1)\n plt.ylim(0,1)\n plt.plot([0,1], linewidth=3, color = 'black', ls='--', alpha=0.5)\n\n plt.savefig(\n os.path.join(base_dir, 'plots',\n args.cohort + '_mutex-preds.png'),\n dpi=500, bbox_inches='tight')\n\n plt.close()\n\ndef plot_coefs(args, out_data, mutex_dict, mtypes):\n\n coef_df = pd.DataFrame(out_data['Coef'][mtypes])\n coef_df = coef_df.loc[:, coef_df.apply(lambda x: any(x != 0))]\n coef_df.index = [str(mtypes[0]), str(mtypes[1])]\n\n g = sns.clustermap(data=coef_df,\n row_cluster=False, col_cluster=True,\n #metric='cosine', method='single',\n figsize=(30,2), center=0, robust=True,\n cmap=sns.color_palette(\"coolwarm\"))\n\n g.savefig(\n os.path.join(base_dir, 'plots',\n args.cohort + '_'\n + str(mtypes[0]) + '-' + str(mtypes[1]),\n '_mutex-coefs.png'),\n dpi=500, bbox_inches='tight')\n\n g.close()\n\ndef plot_mutex_signatures(args, out_data, mutex_dict, clr_scheme='Dist'):\n rcParams['figure.figsize'] = 20, 10\n\n plt_x = []\n plt_y = []\n plt_mtypes = []\n\n for mtype1, mtype2 in out_data['Acc']:\n acc = min(out_data['Acc'][mtype1, mtype2])\n\n if acc > 0.7:\n print('{} + {}'.format(mtype1, mtype2))\n print(np.round(out_data['Stat'][mtype1, mtype2], 3))\n print(mutex_dict[mtype1, mtype2])\n\n sim1 = ((out_data['Stat'][mtype1, mtype2][0][1]\n - out_data['Stat'][mtype1, mtype2][0][0])\n / (out_data['Stat'][mtype1, mtype2][0][2]\n - out_data['Stat'][mtype1, mtype2][0][0]))\n sim2 = ((out_data['Stat'][mtype1, mtype2][1][1]\n - out_data['Stat'][mtype1, mtype2][1][0])\n / (out_data['Stat'][mtype1, mtype2][1][2]\n - out_data['Stat'][mtype1, mtype2][1][0]))\n\n if (-5 < sim1 < 5) and (-5 < sim2 < 5):\n plt_mtypes += [(mtype1, mtype2)]\n gn1 = [k for k,v in mtype1][0]\n gn2 = [k for k,v in mtype2][0]\n\n plt_x += [-log10(mutex_dict[mtype1, mtype2])]\n plt_y += [(sim1 + sim2) / 2.0]\n\n plt_alpha = acc ** 4.0\n plt_clr = choose_colour_scheme(\n clr_scheme, out_data=out_data, gn1=gn1, gn2=gn2,\n mtype1=mtype1, mtype2=mtype2\n )\n\n if gn1 == gn2:\n plt_mark = 'o'\n else:\n plt_mark = 's'\n\n plt.scatter(plt_x[-1], plt_y[-1],\n alpha=plt_alpha, s=65, c=plt_clr, marker=plt_mark)\n\n else:\n print('Anomalous pair!')\n\n annot_enum = enumerate(zip(plt_x, plt_y, plt_mtypes))\n for i, (x, y, (mtype1, mtype2)) in annot_enum:\n\n if all(x < (xs - 1) or x > xs or y < (ys - 0.1) or y > (ys + 0.1)\n for xs, ys in zip(\n plt_x[:i] + plt_x[i+1:], plt_y[:i] + plt_y[i+1:]\n )):\n plt.annotate('{}|{}'.format(str(mtype1), str(mtype2)),\n (x, y), (x, y + 0.06),\n size=\"small\", stretch=\"condensed\")\n\n elif (x > 1\n and all(x < xs or x > (xs + 5.0/7)\n or y < (ys - 0.1) or y > (ys + 0.1)\n for xs, ys in zip(plt_x[:i] + plt_x[i+1:],\n plt_y[:i] + plt_y[i+1:]))\n ):\n plt.annotate('{}|{}'.format(str(mtype1), str(mtype2)),\n (x, y), (x-0.5, y + 0.06),\n size=\"small\", stretch=\"condensed\")\n\n plt.xlabel('Mutual Exclusivity -log10(p-val)',\n fontsize=23, weight=550, stretch=340)\n plt.ylabel('Relative Predicted Score',\n fontsize=23, weight=550, stretch=340)\n\n plt.xticks(fontsize=15, weight=510)\n plt.yticks(fontsize=15, weight=510)\n\n plt.axhline(y=0, xmin=0, xmax=100,\n linewidth=3, color = 'black', ls='--', alpha=0.5)\n plt.axhline(y=1, xmin=0, xmax=100,\n linewidth=3, color = 'black', ls='--', alpha=0.5)\n\n clr_lbl = get_colour_label(clr_scheme)\n plt.savefig(\n os.path.join(base_dir, 'plots',\n args.cohort + '_mutex-sigs_' + clr_lbl + '.png'),\n dpi=500, bbox_inches='tight')\n\n plt.close()\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Process plotting options.')\n parser.add_argument('-c', '--cohort')\n args = parser.parse_args()\n\n out_data = load_output(args.cohort)\n mutex_dict = dict(pickle.load(\n open(os.path.join(base_dir,\n 'output', args.cohort, 'tmp/mutex_dict.p'),\n 'rb')\n ))\n\n plot_mutex_signatures(args, out_data, mutex_dict)\n plot_predictions(args, out_data, mutex_dict,\n mtypes=(MuType({('Gene', 'CDH1'): None}),\n MuType({('Gene', 'TP53'): None})))\n plot_predictions(args, out_data, mutex_dict,\n mtypes=(MuType({('Gene', 'TP53'): {\n ('Form', 'Nonsense_Mutation'): None}}),\n MuType({('Gene', 'TP53'): {\n ('Form', 'Missense_Mutation'): None}})))\n #plot_coefs(args, out_data, mutex_dict)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"HetMan/experiments/mutex-variants/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":10483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"108920397","text":"import re\nimport unicodedata\nimport jieba\nimport logging\nfrom typing import List\n\nlogger = logging.getLogger(__name__)\njieba.setLogLevel(logging.INFO)\n\n\nclass Serializer():\n def __init__(self, never_split: List = None, do_lower_case=True, do_chinese_split=False):\n self.never_split = never_split if never_split is not None else []\n self.do_lower_case = do_lower_case\n self.do_chinese_split = do_chinese_split\n\n def serialize(self, text, never_split: List = None):\n \"\"\"\n 将一段文本按照制定拆分规则,拆分成一个词汇List\n Args :\n text (String) : 所需拆分文本\n never_split (List) : 不拆分的词,默认为空\n Rerurn : \n output_tokens (List): 拆分后的结果 \n \"\"\"\n never_split = self.never_split + (never_split if never_split is not None else [])\n text = self._clean_text(text)\n\n if self.do_chinese_split:\n output_tokens = self._use_jieba_cut(text, never_split)\n return output_tokens\n\n text = self._tokenize_chinese_chars(text)\n orig_tokens = self._orig_tokenize(text)\n split_tokens = []\n for token in orig_tokens:\n if self.do_lower_case and token not in never_split:\n token = token.lower()\n token = self._run_strip_accents(token)\n split_tokens.extend(self._run_split_on_punc(token, never_split=never_split))\n\n output_tokens = self._whitespace_tokenize(\" \".join(split_tokens))\n\n return output_tokens\n\n def _clean_text(self, text):\n \"\"\"\n 删除文本中无效字符以及空白字符\n Arg :\n text (String) : 所需删除的文本\n Return :\n \"\".join(output) (String) : 删除后的文本\n \"\"\"\n output = []\n for char in text:\n cp = ord(char)\n if cp == 0 or cp == 0xfffd or self.is_control(char):\n continue\n if self.is_whitespace(char):\n output.append(\" \")\n else:\n output.append(char)\n return \"\".join(output)\n\n def _use_jieba_cut(self, text, never_split):\n \"\"\"\n 使用jieba分词\n Args :\n text (String) : 所需拆分文本\n never_split (List) : 不拆分的词\n Return :\n tokens (List) : 拆分完的结果\n \"\"\"\n for word in never_split:\n jieba.suggest_freq(word, True)\n tokens = jieba.lcut(text)\n if self.do_lower_case:\n tokens = [i.lower() for i in tokens]\n try:\n while True:\n tokens.remove(' ')\n except:\n return tokens\n\n def _tokenize_chinese_chars(self, text):\n \"\"\"\n 在CJK字符周围添加空格\n Arg :\n text (String) : 所需拆分文本\n Return :\n \"\".join(output) (String) : 添加完后的文本\n \"\"\"\n output = []\n for char in text:\n cp = ord(char)\n if self.is_chinese_char(cp):\n output.append(\" \")\n output.append(char)\n output.append(\" \")\n else:\n output.append(char)\n return \"\".join(output)\n\n def _orig_tokenize(self, text):\n \"\"\"\n 在空白和一些标点符号(如逗号或句点)上拆分文本\n Arg :\n text (String) : 所需拆分文本\n Return :\n tokens (List) : 分词完的结果\n \"\"\"\n text = text.strip()\n if not text:\n return []\n # 常见的断句标点\n punc = \"\"\",.?!;: 、|,。?!;:《》「」【】/<>|\\“ ”‘ ’\"\"\"\n punc_re = '|'.join(re.escape(x) for x in punc)\n tokens = re.sub(punc_re, lambda x: ' ' + x.group() + ' ', text)\n tokens = tokens.split()\n return tokens\n\n def _whitespace_tokenize(self, text):\n \"\"\"\n 进行基本的空白字符清理和分割\n Arg :\n text (String) : 所需拆分文本\n Return :\n tokens (List) : 分词完的结果\n \"\"\"\n text = text.strip()\n if not text:\n return []\n tokens = text.split()\n return tokens\n\n def _run_strip_accents(self, text):\n \"\"\"\n 从文本中去除重音符号\n Arg :\n text (String) : 所需拆分文本\n Return :\n \"\".join(output) (String) : 去除后的文本\n\n \"\"\"\n text = unicodedata.normalize(\"NFD\", text)\n output = []\n for char in text:\n cat = unicodedata.category(char)\n if cat == \"Mn\":\n continue\n output.append(char)\n return \"\".join(output)\n\n def _run_split_on_punc(self, text, never_split=None):\n \"\"\"\n 通过标点符号拆分文本\n Args :\n text (String) : 所需拆分文本\n never_split (List) : 不拆分的词,默认为空\n Return :\n [\"\".join(x) for x in output] (List) : 拆分完的结果\n \"\"\"\n \n if never_split is not None and text in never_split:\n return [text]\n chars = list(text)\n i = 0\n start_new_word = True\n output = []\n while i < len(chars):\n char = chars[i]\n if self.is_punctuation(char):\n output.append([char])\n start_new_word = True\n else:\n if start_new_word:\n output.append([])\n start_new_word = False\n output[-1].append(char)\n i += 1\n\n return [\"\".join(x) for x in output]\n\n @staticmethod\n def is_control(char):\n \"\"\"\n 判断字符是否为控制字符\n Arg :\n char : 字符\n Return :\n bool : 判断结果\n \"\"\"\n # These are technically control characters but we count them as whitespace\n # characters.\n if char == \"\\t\" or char == \"\\n\" or char == \"\\r\":\n return False\n cat = unicodedata.category(char)\n if cat.startswith(\"C\"):\n return True\n return False\n\n @staticmethod\n def is_whitespace(char):\n \"\"\"\n 判断字符是否为空白字符\n Arg :\n char : 字符\n Return :\n bool : 判断结果\n \"\"\"\n # \\t, \\n, and \\r are technically contorl characters but we treat them\n # as whitespace since they are generally considered as such.\n if char == \" \" or char == \"\\t\" or char == \"\\n\" or char == \"\\r\":\n return True\n cat = unicodedata.category(char)\n if cat == \"Zs\":\n return True\n return False\n\n @staticmethod\n def is_chinese_char(cp):\n \"\"\"\n \n 判断字符是否为中文字符\n Arg :\n cp (char): 字符\n Return :\n bool : 判断结果\n \n \"\"\"\n # This defines a \"chinese character\" as anything in the CJK Unicode block:\n # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n #\n # Note that the CJK Unicode block is NOT all Japanese and Korean characters,\n # despite its name. The modern Korean Hangul alphabet is a different block,\n # as is Japanese Hiragana and Katakana. Those alphabets are used to write\n # space-separated words, so they are not treated specially and handled\n # like the all of the other languages.\n if ((cp >= 0x4E00 and cp <= 0x9FFF) or #\n (cp >= 0x3400 and cp <= 0x4DBF) or #\n (cp >= 0x20000 and cp <= 0x2A6DF) or #\n (cp >= 0x2A700 and cp <= 0x2B73F) or #\n (cp >= 0x2B740 and cp <= 0x2B81F) or #\n (cp >= 0x2B820 and cp <= 0x2CEAF) or (cp >= 0xF900 and cp <= 0xFAFF) or #\n (cp >= 0x2F800 and cp <= 0x2FA1F)): #\n return True\n\n return False\n\n @staticmethod\n def is_punctuation(char):\n \"\"\"\n 判断字符是否为标点字符\n Arg :\n char : 字符\n Return :\n bool : 判断结果\n \"\"\"\n cp = ord(char)\n # We treat all non-letter/number ASCII as punctuation.\n # Characters such as \"^\", \"$\", and \"`\" are not in the Unicode\n # Punctuation class but we treat them as punctuation anyways, for\n # consistency.\n if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96)\n or (cp >= 123 and cp <= 126)):\n return True\n cat = unicodedata.category(char)\n if cat.startswith(\"P\"):\n return True\n return False","sub_path":"src/deepke/attribution_extraction/standard/tools/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":8713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519796039","text":"from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom os import environ\nfrom flask_cors import CORS\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'pool_recycle': 299}\n\ndb = SQLAlchemy(app)\n\nCORS(app)\n\nclass Book(db.Model):\n __tablename__ = 'book'\n\n isbn13 = db.Column(db.String(13), primary_key=True)\n title = db.Column(db.String(64), nullable=False)\n price = db.Column(db.Float(precision=2), nullable=False)\n availability = db.Column(db.Integer)\n\n def __init__(self, isbn13, title, price, availability):\n self.isbn13 = isbn13\n self.title = title\n self.price = price\n self.availability = availability\n\n def json(self):\n return {\"isbn13\": self.isbn13, \"title\": self.title, \"price\": self.price, \"availability\": self.availability}\n\n\n@app.route(\"/book\")\ndef get_all():\n booklist = Book.query.all()\n if len(booklist):\n return jsonify(\n {\n \"code\": 200,\n \"data\": {\n \"books\": [book.json() for book in booklist]\n }\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"message\": \"There are no books.\"\n }\n ), 404\n\n\n@app.route(\"/book/\")\ndef find_by_isbn13(isbn13):\n book = Book.query.filter_by(isbn13=isbn13).first()\n if book:\n return jsonify(\n {\n \"code\": 200,\n \"data\": book.json()\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"message\": \"Book not found.\"\n }\n ), 404\n\n\n@app.route(\"/book/\", methods=['POST'])\ndef create_book(isbn13):\n if (Book.query.filter_by(isbn13=isbn13).first()):\n return jsonify(\n {\n \"code\": 400,\n \"data\": {\n \"isbn13\": isbn13\n },\n \"message\": \"Book already exists.\"\n }\n ), 400\n\n data = request.get_json()\n book = Book(isbn13, **data)\n\n try:\n db.session.add(book)\n db.session.commit()\n except:\n return jsonify(\n {\n \"code\": 500,\n \"data\": {\n \"isbn13\": isbn13\n },\n \"message\": \"An error occurred creating the book.\"\n }\n ), 500\n\n return jsonify(\n {\n \"code\": 201,\n \"data\": book.json()\n }\n ), 201\n\n\n@app.route(\"/book/\", methods=['PUT'])\ndef update_book(isbn13):\n book = Book.query.filter_by(isbn13=isbn13).first()\n if book:\n data = request.get_json()\n if data['title']:\n book.title = data['title']\n if data['price']:\n book.price = data['price']\n if data['availability']:\n book.availability = data['availability'] \n db.session.commit()\n return jsonify(\n {\n \"code\": 200,\n \"data\": book.json()\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"data\": {\n \"isbn13\": isbn13\n },\n \"message\": \"Book not found.\"\n }\n ), 404\n\n\n@app.route(\"/book/\", methods=['DELETE'])\ndef delete_book(isbn13):\n book = Book.query.filter_by(isbn13=isbn13).first()\n if book:\n db.session.delete(book)\n db.session.commit()\n return jsonify(\n {\n \"code\": 200,\n \"data\": {\n \"isbn13\": isbn13\n }\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"data\": {\n \"isbn13\": isbn13\n },\n \"message\": \"Book not found.\"\n }\n ), 404\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)\n","sub_path":"Lab _example/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532369019","text":"import collections\nimport os\nimport pickle\nfrom pathlib import Path\nfrom typing import List, Optional, Generator\n\nimport torch\nfrom tqdm import tqdm\n\nimport codeprep.api.corpus as codeprep_api\n\n\ndef get_all_files(path: str, extension: Optional[str] = 'java') -> Generator[Path, None, None]:\n if os.path.isfile(path):\n yield Path(path)\n else:\n for root, dirs, files in os.walk(path, followlinks=True):\n for file in files:\n if not extension or file.endswith(f'.{extension}'):\n yield Path(os.path.join(root, file))\n\n\nclass Vocab():\n \"Contain the correspondence between numbers and tokens and numericalize.\"\n def __init__(self, itos):\n self.itos = itos\n self.stoi = collections.defaultdict(int,{v:k for k,v in enumerate(self.itos)})\n\n def numericalize(self, t) -> List[int]:\n \"Convert a list of tokens `t` to their ids.\"\n return [self.stoi[w] for w in t]\n\n def textify(self, nums, sep=' ') -> List[str]:\n \"Convert a list of `nums` to their tokens.\"\n return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]\n\n def __getstate__(self):\n return {'itos':self.itos}\n\n def __setstate__(self, state:dict):\n self.itos = state['itos']\n self.stoi = collections.defaultdict(int,{v:k for k,v in enumerate(self.itos)})\n\n def save(self, path):\n \"Save `self.itos` in `path`\"\n pickle.dump(self.itos, open(path, 'wb'))\n\n @classmethod\n def load(cls, path):\n \"Load the `Vocab` contained in `path`\"\n itos = pickle.load(open(path, 'rb'))\n return cls(itos)\n\n\ndef numericalize_corpus(path: str, vocab: Vocab,\n output_file: Optional[str] = None) -> torch.LongTensor:\n\n all_files = [f for f in get_all_files(path, None)]\n\n all_numbers = []\n for file in tqdm(all_files):\n with file.open('r') as f:\n all_numbers.extend(vocab.numericalize(f.read().split(\" \")))\n\n if output_file:\n with open(output_file, 'w') as f:\n f.write(\" \".join(map(lambda x: str(x), all_numbers)))\n return torch.LongTensor(all_numbers)\n\n\nclass Dictionary(object):\n def __init__(self, vocab: Vocab):\n self.vocab = vocab\n\n @property\n def word2idx(self):\n return self.vocab.stoi\n\n @property\n def idx2word(self):\n return self.vocab.itos\n\n def __len__(self):\n return len(self.vocab.itos)\n\n\nclass Corpus(object):\n def _prep_corpus(self, path: str, prep_function_name: str, prep_function_param: Optional[str], no_com: bool, no_str: bool, no_unicode: bool, no_spaces: bool) -> codeprep_api.PreprocessedCorpus:\n base_path, dir = os.path.split(path)\n output_path = os.path.join(base_path, dir + '_prepped')\n split_func = getattr(codeprep_api, prep_function_name)\n if prep_function_param:\n corpus = split_func(path, prep_function_param, no_com=no_com, no_str=no_str, no_unicode=no_unicode, no_spaces=no_spaces, calc_vocab=True, output_path=output_path)\n else:\n corpus = split_func(path, no_com=no_com, no_str=no_str, no_unicode=no_unicode, no_spaces=no_spaces, calc_vocab=True, output_path=output_path)\n return corpus\n\n def __init__(self, path: str, prep_function_name: str, prep_function_param: Optional[str], no_com: bool, no_str: bool, no_unicode: bool, no_spaces: bool):\n self.path = path\n corpus = self._prep_corpus(path, prep_function_name, prep_function_param, no_com=no_com, no_str=no_str, no_unicode=no_unicode, no_spaces=no_spaces)\n vocab = Vocab([k for k in corpus.load_vocab().keys()])\n self.dictionary = Dictionary(vocab)\n self.train = numericalize_corpus(os.path.join(corpus.path_to_prep_dataset, 'train'), vocab)\n self.valid = numericalize_corpus(os.path.join(corpus.path_to_prep_dataset, 'valid'), vocab)\n self.test = numericalize_corpus(os.path.join(corpus.path_to_prep_dataset, 'test'), vocab)","sub_path":"giganticode/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"203143760","text":"import pandas as pd\nfrom munch import munchify\nfrom collections import defaultdict\nimport re\nclass PandaToObjectConvertor:\n def __init__(self,dataframe:pd.DataFrame):\n self.__Items=[]\n self.__ProcessDataFrame(dataframe)\n\n def __CreateComplexObjectFromDict(self,indict: dict):\n ResultsDict = {}\n RemovedKeys = []\n InvestigatedKeysGroups = defaultdict(list)\n # first we handle what we have\n for key in indict.keys():\n if \".\" not in key:\n ResultsDict[key] = indict[key]\n RemovedKeys.append(key)\n else:\n sub_key = key.split(\".\")[0]\n InvestigatedKeysGroups[sub_key].append(key)\n\n # group every key to sub group\n for InvestigatedKey in InvestigatedKeysGroups:\n IsListOfItems = False\n # is list\n FoundNum = re.findall('\\(\\d\\)', InvestigatedKey)\n IsListOfItems = len(FoundNum) > 0\n # create sub dictonery\n Sub_Dict = {}\n for SubInvestigatedKey in InvestigatedKeysGroups[InvestigatedKey]:\n New_Sub_Dict_Key = SubInvestigatedKey.replace(f\"{InvestigatedKey}.\", \"\")\n Sub_Dict[New_Sub_Dict_Key] = indict[SubInvestigatedKey]\n if (not IsListOfItems):\n ResultsDict[InvestigatedKey] = self.__CreateComplexObjectFromDict(Sub_Dict)\n else:\n New_Key = InvestigatedKey.replace(f\"{FoundNum[0]}\", \"\")\n if (New_Key not in ResultsDict):\n ResultsDict[New_Key] = []\n ResultsDict[New_Key].append(self.__CreateComplexObjectFromDict(Sub_Dict))\n\n return ResultsDict\n\n def __ProcessDataFrame(self,dataframe:pd.DataFrame):\n splited = dataframe.to_dict('records')\n for i in range(len(splited)):\n resultdict = {}\n resultdict = self.__CreateComplexObjectFromDict(splited[i])\n self.__Items.append(munchify(resultdict))\n def __iter__(self):\n return self.__Items.__iter__()","sub_path":"PyMatAnalyzer/Utils/PandaToObjectConvertor.py","file_name":"PandaToObjectConvertor.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"226118100","text":"# -*- enconding: utf-8 -*-\n\nfrom jogos import advinhacao, forca\n\nprint('***********************************')\nprint('* Bem vindo! Escolha um jogo *')\nprint('***********************************')\n\nwhile True:\n print('Qual jogo você quer jogar?')\n print('Digite: 1 - Jogo da Advinhação | 2 - Jogo da Forca')\n jogo = int(input('Escolha o Jogo: '))\n\n\n if jogo == 1:\n advinhacao.jogar()\n break\n elif jogo == 2:\n forca.jogar()\n break\n else:\n print('Jogo fora de catálogo...')\n\n\n","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"450941210","text":"import sys\nimport pygame\nimport os\nfrom pygame.locals import QUIT,Rect\n\n#os.environ['SDL_VIDEODRIVER'] = 'windib'\n#pygame.init()\npygame.font.init()\nSURFACE = pygame.display.set_mode((400,300))\nFPSCLOCK = pygame.time.Clock()\npygame.display.set_caption(\"Just Window\")\n\ndef main():\n sysfont = pygame.font.SysFont(None, 36)\n counter = 0\n image = pygame.image.load(\"pythonlogo.jpg\")\n\n while True:\n SURFACE.fill((255,255,255))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n SURFACE.blit(image, (20,50))\n\n\n pygame.display.flip()\n FPSCLOCK.tick(30)\n\nif __name__ == '__main__':\n main()\n","sub_path":"justwindow.py","file_name":"justwindow.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435056687","text":"import datetime\n\ndef timesince(d, now=None):\n chunks = (\n (60 * 60 * 24 * 365, ('year', 'years')),\n (60 * 60 * 24 * 30, ('month', 'months')),\n (60 * 60 * 24 * 7, ('week', 'weeks')),\n (60 * 60 * 24, ('day', 'days')),\n (60 * 60, ('hour', 'hours')),\n (60, ('minute', 'minutes')),\n (1, ('second', 'seconds'))\n )\n\n # Convert int or float (unix epoch) to datetime.datetime for comparison\n if isinstance(d, int) or isinstance(d, float):\n d = datetime.datetime.fromtimestamp(d)\n\n # Convert datetime.date to datetime.datetime for comparison.\n if not isinstance(d, datetime.datetime):\n d = datetime.datetime(d.year, d.month, d.day)\n if now and not isinstance(now, datetime.datetime):\n now = datetime.datetime(now.year, now.month, now.day)\n\n if not now:\n now = datetime.datetime.now()\n\n # ignore microsecond part of 'd' since we removed it from 'now'\n delta = now - (d - datetime.timedelta(0, 0, d.microsecond))\n since = delta.days * 24 * 60 * 60 + delta.seconds\n if since <= 0:\n # d is in the future compared to now, stop processing.\n return u'0 ' + 'seconds'\n for i, (seconds, name) in enumerate(chunks):\n count = since // seconds\n if count != 0:\n break\n\n if count == 1:\n s = '%(number)d %(type)s' % {'number': count, 'type': name[0]}\n else:\n s = '%(number)d %(type)s' % {'number': count, 'type': name[1]}\n\n if i + 1 < len(chunks):\n # now get the second item\n seconds2, name2 = chunks[i + 1]\n count2 = (since - (seconds * count)) // seconds2\n if count2 != 0:\n if count2 == 1:\n s += ', %d %s' % (count2, name2[0])\n else:\n s += ' and %d %s' % (count2, name2[1])\n return s\n","sub_path":"utils/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"148181204","text":"import random\nimport os\n'''\nABOUT\nOnly works on Mac with VLC, put in directory with movies and it opens a random one. Simple and crude but I use it often. \n'''\n#sets varible to home folder location\ncurrentDirectoryPath = os.getcwd()\n#imports all videos into a list \nlistOfFileNames = os.listdir(currentDirectoryPath)\n\n#sets video varible to random video \nvideo = listOfFileNames[random.randint(0, len(listOfFileNames)-1)]\n#checks to make sure it is not the program itself\nif video == 'shuffle':\n print(video)\n video = listOfFileNames[random.randint(0, len(listOfFileNames)-1)]\n\n#sets current directory for computer to folder\nos.system(\"cd \" + str(currentDirectoryPath))\n#runs vlc to play selected video\nos.system(\"open -a vlc \\'\" + str(video) + \"\"\"'\"\"\") #escape end quote \n\nquit() \n","sub_path":"shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"483186440","text":"# -*- coding: utf-8 -*-\n\n# `random` module is used to shuffle field, see§:\n# https://docs.python.org/3/library/random.html#random.shuffle\nimport random\nimport sys\n\n__author__ = 'i-0ne'\n\nif sys.version_info[0] == 2:\n input_function = raw_input\nelse:\n input_function = input\n\n\nglobal field\nglobal move_count\nmove_count = 1\nfield = []\n# Empty tile, there's only one empty cell on a field:\nEMPTY_MARK = 'x'\n\n# Dictionary of possible moves if a form of:\n# key -> delta to move the empty tile on a field.\nMOVES = {\n 'w': -4,\n 's': 4,\n 'a': -1,\n 'd': 1,\n}\n\n#пусть квадратик с числом iрасположен до (если считать слева направо и сверху\n#вниз) k квадратиков с числами меньшими i.. Будем считать ni=k, то есть\n#если после костяшки с i-м числом нет чисел, меньших i, то k=0..\n#Также введем число e — номер ряда пустой клетки (считая с 1). Если сумма\n#E от 1 до 15 ni + E является нечётной, то решения головоломки не существует\ndef shuffle_field():\n \"\"\"\n This method is used to create a field at the very start of the game.\n :return: list with 16 randomly shuffled tiles,\n one of which is a empty space.\n \"\"\"\n field = [i for i in range(16)]\n counter = 0\n random.shuffle(field)\n for position, element in enumerate(field):\n for looper in range(position, 16):\n if field[looper] < element:\n counter +=1 #counting K for all n in game field\n a = field.index(0)\n line_number = abs(a//4+1)\n counter += line_number # adding line number according to formula\n\n if not counter % 2 == 0:\n print('Reshuffling! Board cannot be solved. \"Odd check\" is', counter)\n field = shuffle_field()\n return field\n else:\n print('Ок. \"Odd check\" for this board is', counter)\n field = [EMPTY_MARK if i==0 else i for i in field]\n print(len(field))\n return field\n\n\ndef print_field(field):\n \"\"\"\n This method prints field to user.\n :param field: current field state to be printed.\n :return: None\n \"\"\"\n print('\\n')\n field = [field[i:i + 4] for i in range(0, len(field), 4)]\n for count, rows in enumerate(field):\n formatted_row = \"│\".join(['{:^3}'.format(element) for element in rows])\n horizontal_line = \"┼\".join(['{:3}'.format('─' * 3) for element in rows])\n print(formatted_row)\n if count < 3: # Ignoring bottom horizontal line\n print(horizontal_line)\n return None\n\n\ndef is_game_finished(field):\n \"\"\"\n This method checks if the game is finished.\n :param field: current field state.\n :return: True if the game is finished, False otherwise.\n \"\"\"\n check_field = list(field) #making copy, to prevent damage to game field\n del check_field[check_field.index(EMPTY_MARK)] #Preparing for compare, only int inside\n return check_field == sorted(check_field)\n\n\ndef perform_move(field, key):\n \"\"\"\n Moves empty-tile inside the field.\n :param field: current field state.\n :param key: move direction.\n :return: new field state (after the move).\n :raises: IndexError if the move can't me done.\n \"\"\"\n global move_count\n a, b = field.index(EMPTY_MARK), field.index(EMPTY_MARK) + MOVES[key]\n string_change = abs(a//4 - b//4)\n if (abs(a-b) == 1 or b < 0) and string_change == 1:\n raise IndexError\n else:\n field[b], field[a] = field[a], field[b]\n move_count +=1\n return field\n\n\ndef handle_user_input(message =''):\n \"\"\"\n Handles user input. List of accepted moves:\n 'w' - up,\n 's' - down,\n 'a' - left,\n 'd' - right\n :return: current move.\n \"\"\"\n key_pressed = input_function(message)\n if key_pressed in MOVES.keys():\n return str(key_pressed)\n else:\n key_pressed = handle_user_input(\"Please use '{}' keys: \".format(\"','\".join(MOVES.keys())))\n return str(key_pressed)\n\n\ndef main():\n \"\"\"\n The main method. It stars when the program is called.\n It also calls other methods.\n :return: None\n \"\"\"\n field = shuffle_field()\n message = 'Moves: 0. Your move >'\n while not is_game_finished(field):\n try:\n print_field(field)\n key = handle_user_input(message)\n message = 'Moves: {}. Your move >'.format(move_count)\n perform_move(field, key)\n except KeyboardInterrupt:\n print('\\nShutting down! Bye!')\n print('\\nTotal moves: {}\\n'.format(move_count-1))\n sys.exit()\n except IndexError:\n message = 'Restricted move. Try another direction >'\n return None\n\n\nif __name__ == '__main__':\n # See what this means:\n # http://stackoverflow.com/questions/419163/what-does-if-name-main-do\n main()\n","sub_path":"02/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"353614094","text":"# coding: utf-8\nfrom matplotlib import colors as mcolors\nfrom matplotlib.collections import PolyCollection\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.transforms import Affine2D\n\n\ndef candlestick(ax, quotes, width=0.2, colorup='r', colordown='g', alpha=1):\n \"\"\"\n Plot the time, open, high, low, close as a vertical line ranging\n from low to high. Use a rectangular bar to represent the\n open-close span. If close >= open, use colorup to color the bar,\n otherwise use colordown\n\n Parameters\n ----------\n ax : `Axes`\n an Axes instance to plot to\n quotes : sequence of quote sequences\n data to plot. time must be in float date format - see date2num\n (time, open, close, high, low, ...)\n width : float\n fraction of a day for the rectangle width\n colorup : color\n the color of the rectangle where close >= open\n colordown : color\n the color of the rectangle where close < open\n alpha : float\n the rectangle alpha level\n Returns\n -------\n ret : tuple\n returns (lines, patches) where lines is a list of lines\n added and patches is a list of the rectangle patches added\n \"\"\"\n\n OFFSET = width / 2.0\n\n lines = []\n patches = []\n for q in quotes:\n t, open, close, high, low = q[:5]\n\n if close >= open:\n color = colorup\n lower = open\n height = close - open\n else:\n color = colordown\n lower = close\n height = open - close\n\n vline = Line2D(\n xdata=(t, t), ydata=(low, high),\n color=color,\n linewidth=0.5,\n antialiased=True,\n )\n vline.set_alpha(alpha)\n\n rect = Rectangle(\n xy=(t - OFFSET, lower),\n width=width,\n height=height,\n facecolor=color,\n edgecolor=color,\n )\n rect.set_alpha(alpha)\n\n lines.append(vline)\n patches.append(rect)\n ax.add_line(vline)\n ax.add_patch(rect)\n ax.autoscale_view()\n return ax\n\n\ndef volume_overlay(ax, quotes, colorup='r', colordown='g', width=4, alpha=1.0):\n \"\"\"Add a volume overlay to the current axes. quotes is a list of (d,\n open, high, low, close, volume) and close-open is used to\n determine the color of the bar\n\n Parameters\n ----------\n ax : `Axes`\n an Axes instance to plot to\n quotes : sequence of (time, open, close, high, low, volume ...) sequences\n data to plot. time must be in float date format - see date2num\n width : int\n the bar width in points\n colorup : color\n the color of the lines where close1 >= close0\n colordown : color\n the color of the lines where close1 < close0\n alpha : float\n bar transparency\n Returns\n -------\n ret : `barCollection`\n The `barrCollection` added to the axes\n \"\"\"\n colorup = mcolors.to_rgba(colorup, alpha)\n colordown = mcolors.to_rgba(colordown, alpha)\n colord = {True: colorup, False: colordown}\n\n dates, opens, closes, highs, lows, volumes = list(zip(*quotes))\n colors = [colord[close1 >= close0]\n for close0, close1 in zip(closes[:-1], closes[1:])\n if close0 != -1 and close1 != -1]\n colors.insert(0, colord[closes[0] >= opens[0]])\n\n right = width / 2.0\n left = -width / 2.0\n\n bars = [((left, 0), (left, volume), (right, volume), (right, 0))\n for d, open, close, high, low, volume in quotes]\n\n sx = ax.figure.dpi * (1.0 / 72.0) # scale for points\n sy = ax.bbox.height / ax.viewLim.height\n\n barTransform = Affine2D().scale(sx, sy)\n\n dates = [d for d, open, close, high, low, volume in quotes]\n offsetsBars = [(d, 0) for d in dates]\n\n useAA = 0, # use tuple here\n lw = 0.5, # and here\n barCollection = PolyCollection(bars,\n facecolors=colors,\n edgecolors=((0, 0, 0, 1),),\n antialiaseds=useAA,\n linewidths=lw,\n offsets=offsetsBars,\n transOffset=ax.transData,\n )\n barCollection.set_transform(barTransform)\n\n minpy, maxx = (min(dates), max(dates))\n miny = 0\n maxy = max([volume for d, open, high, low, close, volume in quotes])\n corners = (minpy, miny), (maxx, maxy)\n ax.update_datalim(corners)\n\n ax.add_collection(barCollection)\n ax.autoscale_view()\n\n return barCollection\n\n\n","sub_path":"tma/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"61608863","text":"__author__ = 'CF'\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.views import View\nfrom django.http import HttpResponseForbidden, HttpResponse\n\nimport datetime, dateutil.parser, calendar, pdb\n\nfrom core.models import Company, Year\n\n\nclass YearListView(View):\n template_name = 'core/year_list.html'\n\n def get(self, request, *args, **kwargs):\n\n y = Year.objects.filter(company_id=kwargs['company_id'])\n n = y.last().end_date + datetime.timedelta(days=1)\n \n if calendar.isleap(y.last().end_date.year+1):\n ye = y.last().end_date + datetime.timedelta(days=366)\n else:\n ye = y.last().end_date + datetime.timedelta(days=365)\n \n # Feststellen, ob Jahr gelöscht werden kann\n for elem in y:\n if elem.year_set.count() > 0 or elem.version_set.count() > 0:\n elem.deletable = False\n else:\n elem.deletable = True\n #pdb.set_trace()\n\n\n context = {\n 'Company_id': kwargs['company_id'],\n 'Years':y,\n 'Yearend':ye,\n 'Nextyear':n }\n \n return render(request, self.template_name, context)\n \n \n def post(self, request, *args, **kwargs):\n sd = dateutil.parser.parse(request.POST.get('inputFromDate')).date()\n ed = dateutil.parser.parse(request.POST.get('inputToDate')).date()\n pyid = request.POST.get('prior_year_id')\n ny = Year(start_date=sd, end_date=ed, prior_year_id=pyid, company_id=kwargs['company_id'])\n if sd <= ed:\n ny.save()\n messages.success(request, 'Neues Jahr hinzugefügt')\n else:\n messages.error(request, 'Das \"Bis\"-Datum muss zeitlich nach dem \"Von\"-Datum liegen.')\n \n y = Year.objects.filter(company_id=kwargs['company_id'])\n n = y.last().end_date + datetime.timedelta(days=1)\n \n if calendar.isleap(y.last().end_date.year+1):\n ye = y.last().end_date + datetime.timedelta(days=366)\n else:\n ye = y.last().end_date + datetime.timedelta(days=365)\n \n # Feststellen, ob Jahr gelöscht werden kann\n for elem in y:\n if elem.year_set.count() > 0 or elem.version_set.count() > 0:\n elem.deletable = False\n else:\n elem.deletable = True\n \n context = {\n 'Company_id': kwargs['company_id'],\n 'Years':y,\n 'Yearend':ye,\n 'Nextyear':n\n }\n \n return render(request, self.template_name, context)\n\n\nclass YearDetailView(View):\n\n def delete(self, request, *args, **kwargs):\n y = get_object_or_404(Year, id=kwargs['year_id'])\n if y.year_set.count() > 0 or y.version_set.count() > 0:\n return HttpResponseForbidden\n else:\n y.delete()\n return HttpResponse(status=200)\n","sub_path":"core/views/year.py","file_name":"year.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"18016718","text":"import datetime\nfrom django.contrib.auth.models import AnonymousUser\nfrom .models import Tag, Task\n\ndef tag_list(request):\n try:\n tag_list = Tag.objects.all().filter(user=request.user)\n return {\"tag_list\": tag_list}\n except TypeError:\n return {}\n\ndef counts(request):\n if isinstance(request.user, AnonymousUser):\n return {}\n today = datetime.date.today()\n monday = today - datetime.timedelta(days=today.weekday())\n sunday = monday + datetime.timedelta(days=6)\n\n qs = Task.objects.filter(user=request.user).filter(done=False)\n extra_context = {}\n extra_context[\"today_count\"] = qs.filter(date=today).count()\n extra_context[\"week_count\"] = qs.filter(date__gte=monday).filter(date__lte=sunday).count()\n extra_context[\"calendar_count\"] = qs.count()\n\n return extra_context\n\ndef priority_list(request):\n priority_list = [\"priority_\" + str(i) for i in range(1, 5)]\n return {\"priority_list\": priority_list}\n \n \n \n","sub_path":"organizer/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"582492830","text":"class Invoice:\n def __init__(self, client, total):\n self.client = client\n self.total = total\n\n def formatter(self):\n return f\"{self.client} owes: ${self.total}\"\n\n\ngoogle = Invoice(\"Google\", 100)\nsnapchat = Invoice(\"SnapChat\", 200)\n\nprint(google.formatter())\nprint(snapchat.formatter())\n","sub_path":"Classes/__init__constructor.py","file_name":"__init__constructor.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400896003","text":"import wx\n\nfrom src.wizard.view.clsAddSpatialReferences \\\n import NewSpatialReferenceView\nfrom odm2api.ODM2.models import SpatialReferences\n\nclass NewSpatialReferenceController(NewSpatialReferenceView):\n def __init__(self, parent, database):\n super(NewSpatialReferenceController, self).__init__(parent)\n self.parent = parent\n self.database = database\n self.Bind(wx.EVT_SHOW, self.onShow)\n self.m_sdbSizer10OK.Bind(wx.EVT_BUTTON, self.onOK)\n\n def onOK(self, event):\n # Try to validate the form.\n if not self.Validate():\n self.Refresh()\n return\n \n write = self.database.getWriteSession()\n \n name = str(self.textName.GetValue())\n code = None\n if str(self.textCode.GetValue()) != \"\":\n code = str(self.textCode.GetValue())\n desc = None\n if str(self.textDesc.GetValue()) != \"\":\n desc = str(self.textDesc.GetValue())\n \n try:\n srs=SpatialReferences(SRSCode=code,\n SRSName=name,\n SRSDescription=desc)\n write.createSpatialReference(srs)\n except Exception:\n wx.MessageBox(\"Error creating spatial reference.\", \"API Error!\")\n\n event.Skip()\n\n def onShow(self, event):\n event.Skip()\n \n def enable(self, event):\n self.parent.btnNext.Enable(True)\n event.Skip()\n \n def disable(self, event):\n self.parent.btnNext.Enable(False)\n event.Skip()\n\n","sub_path":"src/wizard/controller/frmAddSpatialReference.py","file_name":"frmAddSpatialReference.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"320676866","text":"from Spritesheet import *\nfrom GameObject import *\nfrom JsonLoader import *\nimport random, json\n\nclass Collectables(GameObject):\n\n def __init__(self, x_pos, y_pos ,screen, object_ID):\n self.screen = screen\n self.x_pos = x_pos\n self.y_pos = y_pos\n\n self.x_speed = random.uniform(-0.5,0.5) \n \n self.y_speed = - 2\n\n self.object_ID = object_ID\n self.ss = Spritesheet(self.resource_path('Game/sprites/coins.png'))\n self.img = self.ss.image_at(pygame.Rect(1,2,1,2))\n \n self.rect = pygame.Rect(x_pos,y_pos,2,2)\n\n if self.object_ID == 'coin':\n self.img = self.ss.image_at(pygame.Rect(3,2,10,11))\n self.alive = True\n\n \n\n\n def get_rect(self):\n return self.rect\n\n def loop(self):\n self.x_pos += self.x_speed\n self.y_pos += self.y_speed\n\n self.y_speed += 0.1\n\n if self.y_speed > 3:\n self.y_speed = 3\n \n self.rect = self.img.get_rect(x=self.x_pos, y=self.y_pos)\n\n if self.collision('player', self.rect):\n JsonLoader.updateJsonFile(JsonLoader,'coin')\n Mediator.to_be_removed.append(self)\n \n if self.y_pos > self.screen.get_height() + self.img.get_height():\n Mediator.to_be_removed.append(self) \n\n def draw(self):\n self.screen.blit(self.img,(self.x_pos,self.y_pos))","sub_path":"Game/Collectables.py","file_name":"Collectables.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"2994149","text":"from functools import partial\nimport time\nfrom unittest.runner import TextTestRunner, registerResult\nimport warnings\nimport sublime\n\n\ndef defer(delay, callback, *args, **kwargs):\n # Rely on late binding in case a user patches it\n sublime.set_timeout(partial(callback, *args, **kwargs), delay)\n\n\nDEFAULT_CONDITION_POLL_TIME = 17\nDEFAULT_CONDITION_TIMEOUT = 4000\nAWAIT_WORKER = 'AWAIT_WORKER'\n# Extract `set_timeout_async`, t.i. *avoid* late binding, in case a user\n# patches it\nrun_on_worker = sublime.set_timeout_async\n\n\nclass DeferringTextTestRunner(TextTestRunner):\n \"\"\"This test runner runs tests in deferred slices.\"\"\"\n\n def run(self, test):\n \"\"\"Run the given test case or test suite.\"\"\"\n self.finished = False\n result = self._makeResult()\n registerResult(result)\n result.failfast = self.failfast\n result.buffer = self.buffer\n startTime = time.time()\n\n def _start_testing():\n with warnings.catch_warnings():\n if self.warnings:\n # if self.warnings is set, use it to filter all the warnings\n warnings.simplefilter(self.warnings)\n # if the filter is 'default' or 'always', special-case the\n # warnings from the deprecated unittest methods to show them\n # no more than once per module, because they can be fairly\n # noisy. The -Wd and -Wa flags can be used to bypass this\n # only when self.warnings is None.\n if self.warnings in ['default', 'always']:\n warnings.filterwarnings(\n 'module',\n category=DeprecationWarning,\n message='Please use assert\\\\w+ instead.')\n startTestRun = getattr(result, 'startTestRun', None)\n if startTestRun is not None:\n startTestRun()\n try:\n deferred = test(result)\n _continue_testing(deferred)\n\n except Exception as e:\n _handle_error(e)\n\n def _continue_testing(deferred, send_value=None, throw_value=None):\n try:\n if throw_value:\n condition = deferred.throw(throw_value)\n else:\n condition = deferred.send(send_value)\n\n if callable(condition):\n defer(0, _wait_condition, deferred, condition)\n elif isinstance(condition, dict) and \"condition\" in condition and \\\n callable(condition[\"condition\"]):\n period = condition.get(\"period\", DEFAULT_CONDITION_POLL_TIME)\n defer(period, _wait_condition, deferred, **condition)\n elif isinstance(condition, int):\n defer(condition, _continue_testing, deferred)\n elif condition == AWAIT_WORKER:\n run_on_worker(\n partial(defer, 0, _continue_testing, deferred)\n )\n else:\n defer(0, _continue_testing, deferred)\n\n except StopIteration:\n _stop_testing()\n self.finished = True\n\n except Exception as e:\n _handle_error(e)\n\n def _wait_condition(\n deferred, condition,\n period=DEFAULT_CONDITION_POLL_TIME,\n timeout=DEFAULT_CONDITION_TIMEOUT,\n start_time=None\n ):\n if start_time is None:\n start_time = time.time()\n\n try:\n send_value = condition()\n except Exception as e:\n _continue_testing(deferred, throw_value=e)\n return\n\n if send_value:\n _continue_testing(deferred, send_value=send_value)\n elif (time.time() - start_time) * 1000 >= timeout:\n error = TimeoutError(\n 'Condition not fulfilled within {:.2f} seconds'\n .format(timeout / 1000)\n )\n _continue_testing(deferred, throw_value=error)\n else:\n defer(period, _wait_condition, deferred, condition, period, timeout, start_time)\n\n def _handle_error(e):\n stopTestRun = getattr(result, 'stopTestRun', None)\n if stopTestRun is not None:\n stopTestRun()\n self.finished = True\n raise e\n\n def _stop_testing():\n with warnings.catch_warnings():\n stopTestRun = getattr(result, 'stopTestRun', None)\n if stopTestRun is not None:\n stopTestRun()\n\n stopTime = time.time()\n timeTaken = stopTime - startTime\n result.printErrors()\n if hasattr(result, 'separator2'):\n self.stream.writeln(result.separator2)\n run = result.testsRun\n self.stream.writeln(\"Ran %d test%s in %.3fs\" %\n (run, run != 1 and \"s\" or \"\", timeTaken))\n self.stream.writeln()\n\n expectedFails = unexpectedSuccesses = skipped = 0\n try:\n results = map(len, (result.expectedFailures,\n result.unexpectedSuccesses,\n result.skipped))\n except AttributeError:\n pass\n else:\n expectedFails, unexpectedSuccesses, skipped = results\n\n infos = []\n if not result.wasSuccessful():\n self.stream.write(\"FAILED\")\n failed, errored = len(result.failures), len(result.errors)\n if failed:\n infos.append(\"failures=%d\" % failed)\n if errored:\n infos.append(\"errors=%d\" % errored)\n else:\n self.stream.write(\"OK\")\n if skipped:\n infos.append(\"skipped=%d\" % skipped)\n if expectedFails:\n infos.append(\"expected failures=%d\" % expectedFails)\n if unexpectedSuccesses:\n infos.append(\"unexpected successes=%d\" % unexpectedSuccesses)\n if infos:\n self.stream.writeln(\" (%s)\" % (\", \".join(infos),))\n else:\n self.stream.write(\"\\n\")\n\n _start_testing()\n","sub_path":"unittesting/core/py33/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"188761061","text":"# -*- coding: iso-8859-1 -*-\r\n\r\n#===============================================================================\r\n# FEAS flight_directives module. Introduced in v0.8 alpha.\r\n# by Mark Muzenhardt, published under BSD-License.\r\n#===============================================================================\r\n\r\nimport gtk\r\n\r\nfrom BaseUI import Portlets\r\nfrom BaseUI.DB import SQLdb\r\nfrom BaseUI.GTK import Glade, Dialogs\r\nfrom config import *\r\n\r\nDEBUG = False\r\n\r\nif DEBUG:\r\n from pprint import pprint\r\n \r\n \r\nclass main:\r\n def __init__(self, db_object=None):\r\n self.db_object = db_object\r\n \r\n self.wTree = Glade.import_tree(self, RESOURCE_DIR + 'portlets.glade', 'portlet_flight_permissions')\r\n self.window = self.wTree.get_widget('portlet_flight_permissions')\r\n \r\n # Cut portlet out of window\r\n self.portlet = self.window.get_child()\r\n self.window.remove(self.portlet)\r\n self.window.destroy()\r\n \r\n\r\n\r\nclass ui_portlet_flight_permissions(Portlets.Form):\r\n def __init__(self):\r\n pass\r\n\r\n \r\n \r\nclass ui_table_flight_permissions(Portlets.Table):\r\n def __init__(self, flight_directive_id):\r\n definition = ''\r\n \r\n\r\n\r\nclass db_table_flight_permissions(SQLdb.table):\r\n def __init__(self, db_object):\r\n self.definition = \\\r\n [\r\n {}\r\n ]\r\n \r\n SQLdb.table.__init__(self, db_object, 'flight_directives_fields')\r\n differences_lod = self.check_attributes(self.attributes, add=True)\r\n ","sub_path":"src/flight_permissions.py","file_name":"flight_permissions.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"73537696","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom .forms import Transaction_Form, Register_Form\nfrom django.contrib.auth import authenticate, login, logout\n\n\n\n# Create Homepage views here.\n\ndef home(request):\n\n item_man = Item.objects.filter(category__id = 5)[:8]\n item_woman = Item.objects.filter(category__id = 6)[:8]\n item_bag = Item.objects.filter(category__id = 7)[:8]\n item_foodware = Item.objects.filter(category__id = 8)[:8]\n category_list = Category.objects.all()\n\n context = {\n 'item_man' : item_man,\n 'item_woman' : item_woman,\n 'item_bag' : item_bag,\n 'item_foodware' : item_foodware,\n 'category' : category_list,\n }\n return render(request,'design/index.html',context)\n\n\n\n# User REGISTER views\ndef register_views(request):\n\n forms = Register_Form(request.POST or None)\n if forms.is_valid():\n instance = forms.save(commit = True)\n instance.save()\n return redirect(login_viwes)\n\n context = {\n 'forms' : forms\n }\n return render(request, 'app/base.html',context)\n\n\n\n# Login Views\ndef login_viwes(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n auth = authenticate(username = username, password = password)\n\n if auth is not None:\n login(request, auth)\n return redirect(home)\n return render(request, 'app/base.html')\n\n\n\n# Logout Views\ndef login_viwes(request):\n\n logout(request)\n return redirect(login_viwes)\n\n\n# Profile_viwes\ndef Profile_viwes(request):\n\n context = {\n 'user' : request.user\n }\n return render(request, 'app/base.html',context)\n\n\n# Create Single page views here.\n\ndef single_page_views(request, id):\n\n single_page = Item.objects.get(id = id)\n related_product = Item.objects.filter(category = single_page.category).exclude(id = id)[:4]\n context = {\n 'single_page' : single_page,\n 'related_product' : related_product,\n }\n return render(request,'design/single.html',context)\n\n\n\n# Create Category views here.\ndef category_views(request, name):\n\n cat_filter = Item.objects.filter(category__name = name)\n context = {\n 'cat_filter' : cat_filter,\n }\n return render(request, 'design/category.html',context)\n\n\n# Create Cart Page views here.\ndef add_cart_views(request, id):\n\n add_cart = Item.objects.get(id = id)\n\n # request.session['add_cart'] = True\n session_cart = request.session.get('add_cart', True)\n\n context = {\n 'add_cart' : add_cart,\n 'session_cart' : session_cart,\n }\n return render(request, 'design/cart.html',context)\n\n\ndef sales(request):\n\n if request.method == 'POST':\n form = Transaction_Form(request.POST)\n if form.is_valid():\n item_name = form.cleaned_data['name']\n quantity = form.cleaned_data['quantity']\n\n item_obj = Item.objects.get(name = item_name)\n stk_obj = Stock.objects.get(item = item_obj)\n stk_obj.quantity -= quantity\n stk_obj.save()\n\n # Transaction.objects.create(\n # item = item_obj,\n # quantity = quantity,\n # status = 'sales'\n # )\n #\n # context = {\n # 'name' : item_name,\n # 'quantity' : quantity\n # }\n # return render(request, 'transaction.html',context)\n\n form = Transaction_Form()\n context = {\n 'form' : form\n }\n return render(request, 'transaction.html',context)\n","sub_path":"mydokan/inventory/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"618002995","text":"#!/usr/bin/python3\n\nfrom openheating.core.thermometer_fixed import FixedThermometer\n\nfrom gi.repository import GLib\nimport pydbus.bus\n\n\nclass DBUSThermometer(object):\n '''\n \n \n \n \n \n \t\n \n '''\n\n def __init__(self, thermometer):\n self.__thermometer = thermometer\n\n def get_temperature(self):\n return self.__thermometer.get_temperature()\n\n\nloop = GLib.MainLoop()\nconnection = pydbus.bus.connect('unix:path=/var/run/openheating/openheating-dbus-daemon.socket')\nbus = pydbus.bus.Bus(connection)\n\nbus.publish('org.openheating.ThermometerService',\n DBUSThermometer(FixedThermometer(10.5)),\n# ('thermometer-a', DBUSThermometer(FixedThermometer(10.5))),\n# ('thermometer-b', DBUSThermometer(FixedThermometer(11.5))),\n )\nloop.run()\n","sub_path":"dbus/pydbus-hell/dbus-thermometer-service.py","file_name":"dbus-thermometer-service.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"142627809","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\nclass Solution(object):\n def mctFromLeafValues(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n sum_ = 0\n \n while len(arr) > 2:\n i, j = 0, 1\n rec_i, rec_j = i, j\n min_ = arr[i] * arr[j]\n while(j < len(arr)):\n if arr[i] * arr[j] < min_:\n rec_i, rec_j = i, j\n min_ = arr[i] * arr[j]\n i += 1\n j += 1\n\n if (arr[rec_i] < arr[rec_j]):\n arr = arr[:rec_i] + arr[rec_i+1:]\n elif (arr[rec_i] >= arr[rec_j]):\n arr = arr[:rec_j] + arr[rec_j+1:]\n sum_ += min_\n\n return sum_ + arr[0] * arr[1]\n\n\n\n\n\n\n\ns = Solution()\nprint(s.mctFromLeafValues([6, 4, 2]))\n","sub_path":"1130.py","file_name":"1130.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"256338323","text":"import requests, bs4, urllib.parse #, csv\n\ndef get_soup(url):\n r = requests.get(url)\n return bs4.BeautifulSoup(r.text)\n\ndef scrape_jobs(outfile, city=None, descriptor=None):\n main_url = 'https://jobboard.cs.uchicago.edu/'\n main_soup = get_soup(main_url)\n fulltime = main_soup.select('table.jobtable')[0]\n rows = fulltime.select('tr')\n jobs = []\n for row in rows[1:]:\n link = row.find('a').get('href')\n link_url = urllib.parse.urljoin(main_url, link)\n link_soup = get_soup(link_url)\n location = link_soup.find('th', text='Location').find_next('td').text.strip()\n if city and city not in location:\n continue\n description = link_soup.find('th', text='Description').find_next('td').text.strip()\n if descriptor and descriptor.lower() not in description.lower():\n continue\n print('...')\n cells = row.select('td')\n organization = cells[0].text.strip()\n position = cells[1].text.strip()\n deadline = cells[3].text.strip()\n info = (organization, position, location, deadline, link_url, description)\n jobs.append(info)\n print('Writing...')\n # with open('output/' + outfile, 'w', newline='', encoding='utf-8') as f:\n # csv.writer(f).writerow(('Organization', 'Position', 'Location', 'Deadline', 'Link', 'Description'))\n # csv.writer(f).writerows(jobs)\n with open('output/' + outfile, 'w', encoding='utf-8') as f:\n f.write('Organization,Position,Location,Deadline,Link,Description\\n')\n for job in jobs:\n f.write(','.join('\"%s\"' % x for x in job) + '\\n')\n\nif __name__ == '__main__':\n scrape_jobs('cs_jobs_chicago.csv', city='Chicago')\n scrape_jobs('cs_jobs_python.csv', descriptor='Python')\n","sub_path":"web_scraping/_old/bs4_cs_job_board.py","file_name":"bs4_cs_job_board.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"21902805","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport neptune\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.callbacks import Callback\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D,GlobalAveragePooling2D, Concatenate, Reshape,GlobalMaxPooling2D, Activation, Input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom PIL import Image\nimport numpy as np\nimport pandas\nimport os\nimport pathlib\nimport datetime\nimport math\nimport sys\n\n# GPU setup\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True) \n\n# Config loading\n\ntrain_path = \"../../bachelor-data/data_cat/allTrain.csv\"\nvalidate_path =\"../../bachelor-data/data_cat/allTest.csv\"\n\nimage_dir = \"../../bachelor-data/data_cat/\"\ncheckpointpath = \"../../bachelor-data/checkpoints/\"\nmodelName = sys.argv[0]\n\nlearning_rate = 0.001\n\nimage_height = 224\nimage_width = 224\nbatch_size = 32\nnumEpochs = 75\n\nconf= {\n \"train_path\": train_path,\n \"validate_path\": validate_path,\n \"image_dir\": image_dir,\n \"modelName\": modelName,\n \"learning_rate\": learning_rate,\n \"image_height\": image_height,\n \"image_width\": image_width,\n \"batch_size\": batch_size,\n \"numEpochs\": numEpochs\n }\n\n\n# select project\nneptune.init('lassegoransson/xrayPredictor-categorical')\n\n# Data generators\ntrain_df = pandas.read_csv(train_path,sep=';')\nvalidate_df = pandas.read_csv(validate_path,sep=';')\n\nprint(train_df)\ntrain_df['filename'] = train_df['filename'].astype(str) \nvalidate_df['filename'] = validate_df['filename'].astype(str) \n\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n horizontal_flip=True,\n vertical_flip=True,\n )\n\nval_datagen = ImageDataGenerator(\n rescale=1./255,\n )\n\n\ntrain_generator = train_datagen.flow_from_dataframe(\n dataframe=train_df,\n directory=image_dir,\n x_col=\"filename\",\n y_col='label',\n target_size=(image_height, image_width),\n batch_size=batch_size,\n shuffle=True,\n class_mode=\"sparse\",\n color_mode=\"rgb\"\n )\n\nval_generator = val_datagen.flow_from_dataframe(\n dataframe=validate_df,\n directory=image_dir,\n x_col=\"filename\",\n y_col='label',\n target_size=(image_height, image_width),\n batch_size=batch_size,\n shuffle=True,\n class_mode=\"sparse\",\n color_mode=\"rgb\"\n )\n\n\n\n# Model\nRESNET = keras.applications.resnet.ResNet50(include_top=False, weights='imagenet', input_shape=(image_height,image_width,3), pooling=\"avg\")\nmodel = tf.keras.Sequential()\n\n# Projection\n# Resnet\nmodel.add(RESNET)\n\n#model.layers[1].trainable=False\n\n\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(3,Activation(\"softmax\")))\n\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n\nclass NeptuneMonitor(Callback):\n def on_epoch_end(self, epoch, logs={}):\n neptune.send_metric('val_loss', epoch, logs['val_loss'])\n neptune.send_metric('val_accuracy', epoch, logs['val_accuracy'])\n neptune.send_metric('loss', epoch, logs['loss'])\n neptune.send_metric('accuracy', epoch, logs['accuracy'])\n neptune.send_metric('learning_rate', epoch, float(tf.keras.backend.get_value(self.model.optimizer.lr)))\n\n\n\nfilepath=str(checkpointpath)+\"model_\"+str(modelName)+\"_checkpoint-\"+str(image_height)+\"x\"+str(image_width)+\"-{epoch:03d}-{val_accuracy:.16f}.hdf5\"\n\nRLR = keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', factor=0.5, patience=2, verbose=1, mode='max', min_delta=0.0001, cooldown=0)\n\ncheckpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_accuracy', verbose=0, save_best_only=True, save_weights_only=False, mode='max')\n\nearlyStop = keras.callbacks.EarlyStopping(monitor='val_accuracy', mode='max', patience=10, restore_best_weights=True,verbose=1)\n\nwith neptune.create_experiment(name=modelName, params=conf) as npexp:\n neptune_monitor = NeptuneMonitor()\n\n callbacks_list = [checkpoint, neptune_monitor, RLR, earlyStop]\n\n model.summary()\n history = model.fit(train_generator,validation_data=val_generator,verbose=1 , epochs=numEpochs, steps_per_epoch=train_generator.n/train_generator.batch_size , callbacks=callbacks_list)\n\n import glob\n\n list_of_files = glob.glob(checkpointpath+\"*\") # * means all if need specific format then *.csv\n latest_file = max(list_of_files, key=os.path.getctime)\n modelfileName = latest_file \n\n npexp.send_artifact(modelfileName)\n tmp = modelfileName.split('-')[4].split('.')\n val = float(tmp[0]+\".\"+tmp[1])\n neptune.send_metric('val_accuracy', val)\n\n","sub_path":"categorical/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"219120303","text":"#to extract frame and crop face and grt landmark points\n#Mask_Paper_6_003\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\nfrom skimage import io\nimport os\nimport face_alignment\nimport subprocess\nfrom PIL import Image\nfrom shutil import copyfile\n# from mtcnn import MTCNN\nimport cv2\nimport numpy\n\ndef extract_frames(input_path, name, outpath):\n cmd = \"ffmpeg -i \"+ input_path+name+\".mov -vf \\\"select=not(mod(n\\,5))\\\" -vsync vfr -q:v 2 \"+outpath+name+'/'+name+\"_%03d.png\"\n subprocess.run([cmd], shell=True, executable = '/bin/bash')\n \ndef findvideos(inpfile, outpath):\n for dirpath, dirnames, filenames in os.walk(\"/root/datasets/siwm/\"):\n # print('searching for person', i)\n for filename in [f for f in filenames if f.endswith('.mov')]:\n filename = os.path.splitext(filename)[0]\n with open(inpfile) as trainlist:\n for person in trainlist:\n person = person.strip('\\n')\n if filename == person:\n # print(dirpath)\n if not os.path.isdir(outpath+person+'/'):\n os.mkdir(outpath+person+'/') \n extract_frames(dirpath+'/',person, outpath)\n # face_landmarks_crop(outpath)\n\n \ndef mtcnn_caller(path, image_folder,image):\n # If required, create a face detection pipeline using MTCNN:\n mtcnn = MTCNN(image_size=256,margin=0)\n # img = cv2.imread(path+image_folder+image)\n # img = Image.open(path+image_folder+image+'/'+image+'.png')\n img = Image.open(path+image_folder+image)\n print('__taken input__', path+image_folder+image)\n # detector = MTCNN()\n # faces=detector.detect_faces(img)\n faces,_= mtcnn.detect(img)\n if faces is not None:\n # try:\n # img = Image.open(path+image_folder+image)\n # # do stuff\n # except IOError:\n # # filename not an image file\n # print('not image')\n # img = cv2.imread(path+image_folder+image)\n # print('1&&&&&&_____________________&&&&&&&&&&&&&&&', img)\n if img is not None:\n # Get cropped and prewhitened image tensor\n try:\n fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False)\n input = cv2.imread(path+image_folder+image)\n # image = image.strip('.png')\n # print('2&&&&&&_____________________&&&&&&&&&&&&&&&', input)\n \n # image = image.strip('.jpg')\n preds = fa.get_landmarks(input)\n image = image.strip('.png')\n os.mkdir(path+'spoof/'+image+'/')\n numpy.save(path+'spoof/'+image+'/'+image, preds)\n \n img_cropped = mtcnn(img, save_path=path+'spoof/'+image+'/'+image+'.png')\n \n except IndexError as error:\n print(error)\n\n# def face_landmarks_crop(input_path):\n# for files in os.listdir(input_path)\n# fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False)\n# input = io.imread('/root/datasets/siwm/Paper/')\n# preds = fa.get_landmarks(input)\n \nif __name__ =='__main__':\n\n inpfile = 'trainlist.txt' \n new_testset_path= '/root/datasets/siwm/train/'\n if not os.path.isdir(new_testset_path):\n os.mkdir(new_testset_path)\n\n # findvideos(inpfile, new_testset_path)\n image_folders = os.listdir(new_testset_path)\n # print(image_folders)\n for image_folder in image_folders:\n # print(image_folder)\n if image_folder != 'spoof' and image_folder != 'live':\n images = os.listdir(new_testset_path+image_folder)\n # print(images)\n for image in images:\n # print(image)\n # print(path+'/'+image_folder+'/'+image)\n mtcnn_caller(new_testset_path, image_folder+'/',image)\n\n\n#input = io.imread('/root/datasets/siwm/Paper/')\n#preds = fa.get_landmarks(input)\n#preds = fa.get_landmarks_from_directory('../test/assets/')\n# for (x, y, w, h) in faces:\n# cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n# status = cv2.imwrite('faces_detected.jpg', image)","sub_path":"dataprep/preprocessing_siwm.py","file_name":"preprocessing_siwm.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"501727651","text":"#Write a function to print out the number of prime numbers that exist upto and including the given number:\r\n#0 and 1 are not considered prime\r\n\r\ndef count_primes2(num):\r\n primes = [2]\r\n x = 3\r\n if num < 2:\r\n return 0\r\n while x <= num:\r\n for y in primes: \r\n if x%y == 0:\r\n x += 2\r\n break\r\n else:\r\n primes.append(x)\r\n x += 2\r\n print(primes)\r\n return len(primes)\r\n \r\n\r\nx = int(input('Enter the number:'))\r\n\r\nif x > 0:\r\n print(count_primes2(x))\r\nelse:\r\n print('ERROR')","sub_path":"count_prime.py","file_name":"count_prime.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382132353","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 10 11:48:33 2017\n\n@author: 大帆\n\"\"\"\nimport numpy as np\nfrom ..base.Baseclassifier import BaseClassifer\n\n\nclass Logistic_Reg(BaseClassifer):\n def __init__(self,lr=0.1,iter=200):\n self.lr=lr\n self.iter=iter\n\n def fit(self,X,y):\n shape=X.shape\n from sklearn.preprocessing import MinMaxScaler\n self.minmax=MinMaxScaler()\n X=self.minmax.fit_transform(X)\n X=np.c_[X,np.ones((shape[0],1))]\n shape=X.shape\n # self.W=np.zeros()\n self.W=np.zeros((1,shape[1]))\n for i in range(self.iter):\n dt=np.zeros([1,shape[1]])\n for j,(x_v,y_v) in enumerate(zip(X,y)):\n# if i>190 and j>97 :\n# print(self._logist(np.dot(x_v,self.W.T)))\n dt+=(y_v-self._logist(np.dot(x_v,self.W.T)))*x_v\n# print(self.lr*dt/shape[0])\n# print(self.W)\n# print()\n self.W=self.W+self.lr*dt/shape[0]\n\n def _logist(self,x):\n # print(x)\n return 1/(1+np.exp(-x))\n \n def __one_zoro(self,x):\n y=np.zeros([x.shape[0],1])\n y[x>=0.5]=1\n y[x<0.5]=0\n return y\n def predict(self,X):\n shape=X.shape\n X=self.minmax.transform(X)\n X=np.c_[X,np.ones([shape[0],1])] \n return self.__one_zoro(self._logist( np.dot(X,self.W.T)))\n\n \n","sub_path":"build/lib/machinelearn/regression/Logist_reg.py","file_name":"Logist_reg.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571530094","text":"import os\nimport numpy as np\nimport string\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n\nfrom keras.layers import Input\nfrom keras.models import Model, Sequential\nfrom keras.layers.core import Reshape, Dense, Dropout, Flatten\nfrom keras.layers.advanced_activations import LeakyReLU\n\nfrom keras.layers.convolutional import Conv2D, UpSampling2D\nfrom keras.datasets import fashion_mnist\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom keras import initializers\n\nif not os.path.exists(\"images\"):\n os.mkdir(\"images\")\nif not os.path.exists(\"models\"):\n os.mkdir(\"models\")\n\nK.set_image_dim_ordering('th')\n\n# Deterministic output.\n# Tired of seeing the same results every time? Remove the line below.\nnp.random.seed(1000)\n\n# The results are a little better when the dimensionality of the random vector is only 10.\n# The dimensionality has been left at 100 for consistency with other GAN implementations.\nrandomDim = 100\n\n# Optimizer\nadam = Adam(lr=0.0002, beta_1=0.5)\n\n\ngenerator = Sequential()\ngenerator.add(Dense(128*8*8, input_dim=randomDim, kernel_initializer=initializers.RandomNormal(stddev=0.02)))\ngenerator.add(LeakyReLU(0.2))\ngenerator.add(Reshape((128, 8, 8)))\ngenerator.add(UpSampling2D(size=(2, 2)))\ngenerator.add(Conv2D(64, kernel_size=(3, 3), padding='same'))\ngenerator.add(LeakyReLU(0.2))\ngenerator.add(UpSampling2D(size=(2, 2)))\ngenerator.add(Conv2D(3, kernel_size=(3, 3), padding='same', activation='tanh'))\n\ngenerator.compile(loss='binary_crossentropy', optimizer=adam)\n\n(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()\n# X_train = (X_train.astype(np.float32) - 127.5)/127.5\n# X_train = X_train[:, np.newaxis, :, :]\n# ones_train = X_train[np.where(y_train == 1)[0]]\nones_train = (X_train.astype(np.float32) - 127.5)/127.5\n\ndef plotDataSetImages(examples=100, dim=(10, 10), figsize=(16, 16)):\n image = ones_train[:100]\n plt.figure(figsize=figsize)\n for i in range(image.shape[0]):\n plt.subplot(dim[0], dim[1], i+1)\n plt.imshow(image[i], interpolation='nearest', cmap='gray_r')\n plt.axis('off')\n plt.tight_layout()\n plt.savefig('images/gan_dataset_image_100.png')\n\n\n# Create a wall of generated Cifar10 images\ndef plotGeneratedImages(epoch, examples=100, dim=(10, 10), figsize=(12, 12) ,single = False):\n noise = np.random.normal(0, 1, size=[examples, randomDim])\n if single:\n generator.load_weights('./models/singleModel/dcgan_generator_epoch_%d.h5' % epoch)\n else:\n generator.load_weights('./models/dcgan_generator_epoch_%d.h5' % epoch)\n generatedImages = generator.predict(noise)\n #print generatedImages.shape\n #print generatedImages[1]\n generatedImages = generatedImages/2 + 0.5\n plt.figure(figsize=figsize)\n for i in range(generatedImages.shape[0]):\n plt.subplot(dim[0], dim[1], i+1)\n plt.imshow(generatedImages[i].transpose((1,2,0)), interpolation='nearest')\n plt.axis('off')\n plt.tight_layout()\n if single:\n plt.savefig('images/single/dcgan_generated_image_SIngle_epoch_%d.png' % epoch)\n else:\n plt.savefig('images/dcgan_generated_image_SIngle_epoch_%d.png' % epoch)\n\n\n# Create a wall of generated Cifar10 images\ndef plotDiffGeneratedImages(epoch, examples=100, dim=(10, 10), figsize=(16, 16)):\n noise = np.random.normal(0, 1, size=[examples, randomDim])\n generator.load_weights('models/diffGan/diffgan_generator_epoch_%d.h5' % epoch)\n generatedImages = generator.predict(noise)\n #print generatedImages.shape\n #print generatedImages[1]\n generatedImages = generatedImages/2 + 0.5\n plt.figure(figsize=figsize)\n for i in range(generatedImages.shape[0]):\n plt.subplot(dim[0], dim[1], i+1)\n plt.imshow(generatedImages[i].transpose((1,2,0)), interpolation='nearest')\n plt.axis('off')\n plt.tight_layout()\n plt.savefig('images/diffGan/dcgan_generated_image_epoch_%d.png' % epoch)\n\nif __name__ == '__main__':\n plotDataSetImages()\n #plotGeneratedImages(1)\n\n","sub_path":"Fashion/show_fashion.py","file_name":"show_fashion.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"93955829","text":"# coding=utf-8\nimport srcs.tools as tools\nimport time\nimport numpy as np\nimport pandas as pd\nfrom imblearn.over_sampling import SMOTE, ADASYN, RandomOverSampler\nimport xgboost as xgb\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LogisticRegression, RandomizedLasso\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn import metrics, cross_validation\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import SelectKBest, f_classif, SelectFromModel\nfrom scipy.stats import pearsonr\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\n\ntrain_path = '..\\\\data1\\\\train'\ntest_path = '..\\\\data1\\\\test\\\\08\\\\08_data.csv'\n\n\n# 计时器\ndef run_time(func):\n def wrapper(num):\n start = time.time()\n data_feat, data_norm, data_fail = func(num)\n end = time.time()\n print(\"->读取%d号风机数据耗时: %.2f s\" % (num, (end - start)))\n return data_feat, data_norm, data_fail\n return wrapper\n\n\n# 导入数据\n@run_time\ndef get_data(num):\n num = str(num)\n data_feat = pd.read_csv('%s\\\\%s\\\\%s_data.csv' % (train_path, num, num), parse_dates=[\"time\"])\n data_norm = pd.read_csv('%s\\\\%s\\\\%s_normalInfo.csv' % (train_path, num, num), parse_dates=[\"startTime\", \"endTime\"])\n data_fail = pd.read_csv('%s\\\\%s\\\\%s_failureInfo.csv' % (train_path, num, num), parse_dates=[\"startTime\", \"endTime\"])\n return data_feat, data_norm, data_fail\n\n\n# 合并三个文件,加标签\ndef add_label(data_feat, data_norm, data_fail):\n data_feat[\"label\"] = np.NaN\n norm_len = data_norm.shape[0]\n fail_len = data_fail.shape[0]\n for i in range(norm_len):\n data_feat.loc[(data_norm['startTime'][i] <= data_feat[\"time\"]) &\n (data_feat[\"time\"] <= data_norm['endTime'][i]), \"label\"] = 0\n for j in range(fail_len):\n data_feat.loc[(data_fail['startTime'][j] <= data_feat[\"time\"]) &\n (data_feat[\"time\"] <= data_fail['endTime'][j]), \"label\"] = 1\n # 舍去标签缺失列, 重置索引\n return data_feat.dropna().reset_index(drop=True)\n\n\n# 合并15,21号风机的数据\ndef combine_data(*args, depart=True):\n df = pd.concat(args)\n if depart is False:\n return df\n df_x = df.iloc[:, :-1]\n df_y = df[\"label\"]\n return df_x, df_y\n\n\n# train, test分割\ndef data_prep(df, size=0.3):\n # if len(df.columns) == 29: # 过采样数据集已经消去了时间列\n # df_x = df.iloc[:, 1: -1]\n # else:\n df_x = df.iloc[:, : -1]\n df_y = df[\"label\"]\n df_x_train, df_x_test, df_y_train, df_y_test = train_test_split(df_x, df_y, test_size=size, random_state=10)\n print(\"训练集大小:%d\" % len(df_x_train))\n print(\"测试集大小:%d\" % len(df_x_test))\n return df_x_train, df_x_test, df_y_train, df_y_test\n\n\n# 构造欠采样训练集\ndef undersample(df, times=1):\n # 获取正负样本索引\n fail_index = np.array(df[df[\"label\"] == 1].index)\n fail_num = len(fail_index)\n norm_index = np.array(df[df[\"label\"] == 0].index)\n # 默认1:1欠采样, rate设定欠采样比率\n np.random.seed(1)\n undersample_norm_index = np.random.choice(norm_index, times * fail_num, replace=False)\n # undersample_norm_index = np.array(undersample_norm_index)\n undersample_index = np.hstack((undersample_norm_index, fail_index))\n undersample_index.sort()\n undersample_df = df.iloc[undersample_index, :]\n print(\"欠采样正常样本大小:%d\" % len(undersample_norm_index))\n print(\"欠采样结冰样本大小:%d\" % len(fail_index))\n return undersample_df\n\n\n# 构造过采样训练集\ndef oversample1(df):\n df_fail = df[df[\"label\"] == 1]\n times = int(len(df) / len(df_fail)) - 1\n for i in range(times):\n df = df.append(df_fail)\n print(\"过采样正常样本大小:%d\" % len(df[df[\"label\"] == 0]))\n print(\"过采样结冰样本大小:%d\" % len(df[df[\"label\"] == 1]))\n df_x = df.iloc[:, : -1]\n df_y = df[\"label\"]\n return df_x, df_y\n\n\n# 过采样,多种可选方式\ndef oversample(df, method=0):\n methods = [\"随机\", \"SMOTE\", \"ADASYN\"]\n model = RandomOverSampler(random_state=0)\n if method == 0:\n methods = methods[0]\n elif method == 1:\n model = SMOTE(random_state=0, n_jobs=-1)\n methods = methods[1]\n elif method == 2:\n model = ADASYN(random_state=0, n_jobs=-1)\n methods = methods[2]\n columns = df.columns[1: -1]\n df_x, df_y = model.fit_sample(df.iloc[:, 1: -1], df[\"label\"])\n df_x = pd.DataFrame(df_x, columns=columns)\n df_y = pd.DataFrame(df_y, columns=[\"label\"])\n print(\"%s过采样总样本大小:%d\" % (methods, len(df_y)))\n print(\"%s过采样正常样本大小:%d\" % (methods, len(df_y[df_y[\"label\"] == 0])))\n print(\"%s过采样结冰样本大小:%d\" % (methods, len(df_y[df_y[\"label\"] == 1])))\n # 注意,返回的数据集已经去掉了时间列\n # return pd.concat([df_x, df_y], adf_xis=1)\n return df_x, df_y\n\n\n# 获取8号风机测试集\ndef get_test():\n df = pd.read_csv(test_path, index_col=\"time\")\n return df\n\n\n# 特征线性相关程度(皮尔逊相关系数)\ndef col_sim(df):\n features = [i for i in df.columns if i not in [\"time\", \"group\", \"label\"]]\n plt.figure()\n cm = np.corrcoef(df[features].values.T)\n sns.set(font_scale=1.25)\n sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10},\n yticklabels=features, xticklabels=features)\n plt.xticks(rotation=90)\n plt.yticks(rotation=0)\n plt.show()\n\n\n# 获取评分\ndef get_score(df_y, y_pred):\n cnf = metrics.confusion_matrix(df_y, y_pred)\n p = len(df_y[df_y == 0])\n n = len(df_y[df_y == 1])\n fn = cnf[0][1]\n fp = cnf[1][0]\n pred_score = 1 - fn * 0.5 / float(p) - fp * 0.5 / float(n)\n return pred_score\n\n\n# 生成结果\ndef output(y_pred):\n # 测试集中的time = index + 1, 重置结果索引\n y_pred = pd.Series(y_pred, index=[j for j in range(1, len(y_pred)+1)])\n fail_index = np.array(y_pred[y_pred == 1].index)\n n = len(fail_index)\n ans = []\n cur = 0\n for i in range(1, n):\n if fail_index[i] - fail_index[i-1] > 10 or i == n-1:\n if i - cur > 1:\n ans.append([fail_index[cur], fail_index[i-1]])\n cur = i\n result = pd.DataFrame(ans, columns=[\"startTime\", \"endTime\"])\n result.to_csv('..\\\\upload\\\\test1_08_results.csv', index=False)\n return result\n\nif __name__ == '__main__':\n data_15, norm_15, fail_15 = get_data(15)\n data_21, norm_21, fail_21 = get_data(21)\n data15 = add_label(data_15, norm_15, fail_15)\n data21 = add_label(data_21, norm_21, fail_21)\n test = get_test()\n # 查看正负样本数目-->非平衡数据集\n # 15号风机label:\n # 0.0: 350255\n # 1.0: 23892\n # data_15[\"label\"].value_counts(dropna=False)\n # data_21[\"label\"].value_counts(dropna=False)\n\n # X15 = data15.iloc[:, 1: -1]\n # y15 = data15[\"label\"]\n # X21 = data21.iloc[:, 1: -1]\n # y21 = data21[\"label\"]\n\n data = combine_data(data15, data21, depart=False)\n x0, y0 = oversample(data, method=0)\n x1, y1 = oversample(data, method=1)\n\n clf0 = RandomForestClassifier(random_state=1)\n clf1 = GradientBoostingClassifier(random_state=1)\n clf2 = XGBClassifier(max_depth=5)\n clf = XGBClassifier(learning_rate=0.05, n_estimators=100, max_depth=3, min_child_weight=4,\n reg_alpha=0.005, colsample_bytree=0.8, colsample_bylevel=0.8)\n\n # 特征选择\n # score = clf2.feature_importances_\n # plt.figure()\n # plt.bar(range(len(predictors)), score)\n # plt.xticks(range(len(predictors)), predictors, rotation='vertical')\n # plt.show()\n predictors = ['wind_speed', 'generator_speed', 'power', 'wind_direction', 'yaw_position', 'pitch1_angle',\n 'pitch2_angle', 'pitch3_angle', 'pitch1_moto_tmp', 'pitch2_moto_tmp', 'pitch3_moto_tmp',\n 'environment_tmp', 'int_tmp', 'pitch1_ng5_tmp', 'pitch2_ng5_tmp', 'pitch3_ng5_tmp']\n param_test = {'n_estimators': [160, 180, 200]}\n gs = GridSearchCV(estimator=clf2,\n param_grid=param_test,\n scoring='roc_auc',\n n_jobs=-1,\n cv=4)\n gs.fit(x0[predictors], y0)\n # print(gs.grid_scores_, gs.best_params_, gs.best_score_)\n\n\n\n\n\n\n","sub_path":"srcs/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":8453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562563235","text":"from django.db import IntegrityError\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\nfrom Riders.models import Rider\nfrom Riders.seralizers import RiderSerializer\n\nRIDERS_URL = reverse('riders')\n\n\ndef sample_rider():\n \"\"\"Create sample rider\"\"\"\n return Rider.objects.create(last_name=\"Kowalski\", first_name=\"Andrzej\")\n\n\nclass ModelRiderTests(TestCase):\n \"\"\"Test rider model\"\"\"\n def test_team_str(self):\n \"\"\"Test rider string representation\"\"\"\n sample_rider = Rider.objects.create(\n last_name=\"Kowalski\",\n first_name=\"Andrzej\"\n )\n self.assertEqual(str(sample_rider), sample_rider.first_name+\" \"+sample_rider.last_name)\n\n\nclass RidersAPITests(TestCase):\n \"\"\"Test Rider API\"\"\"\n def setUp(self):\n self.client = APIClient()\n\n def test_retrieve_rider(self):\n \"\"\"Test retrieving a list of teams\"\"\"\n sample_rider()\n res = self.client.get(RIDERS_URL)\n riders = Rider.objects.all().order_by(\"-id\")\n serializer = RiderSerializer(riders, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_create_team(self):\n \"\"\"Test creating rider\"\"\"\n payload = {'last_name': 'Kasperczak', 'first_name': 'Henryk'}\n res = self.client.post(RIDERS_URL, payload)\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n rider = Rider.objects.get(last_name=res.data['last_name'])\n for key in payload.keys():\n self.assertEqual(payload[key], getattr(rider, key))\n\n def test_exist_rider(self):\n \"\"\"Test of adding an existing rider\"\"\"\n sample_rider()\n payload = {'last_name': 'Kowalski', 'first_name': 'Andrzej'}\n res = self.client.post(RIDERS_URL, payload)\n self.assertRaises(IntegrityError)\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(res.data[0], \"Ten zawodnik już jest w bazie\")","sub_path":"Riders/tests/test_rider_api.py","file_name":"test_rider_api.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"107906974","text":"__author__ = 'Gabriel'\nimport sys\n\nclass Data:\n\n def __init__(self):\n\n self.id = -1\n self.content = None\n self.isFragmented = False\n self.isFirst = True\n self.nextDatablock = None\n\n pass\n\n def InitFromRaw(self, rawData, posInfo):\n\n \"\"\"\n\n :param rawData: Raw Data * in Bytes! *\n :param posInfo: Information contained in the datablock * in Bits! *\n \"\"\"\n\n self.isFragmented = bool(int(posInfo[1 : 2])) # 1 bit\n self.isFirst = bool(int(posInfo[2 : 3])) # 1 bit (o mais da direita)\n\n if self.isFragmented:\n\n self.content = rawData[3 : len(rawData)-4].decode()\n self.nextDatablock = int(rawData[len(rawData) - 4 : len(rawData)], 2)\n if self.isFirst:\n self.id = None\n else:\n self.id = int.from_bytes(rawData[0 : 4], byteorder=sys.byteorder) # 32 bits - as 4 bytes\n else:\n\n self.content = rawData[4 : len(rawData)].decode()\n self.nextDatablock = None\n self.id = int.from_bytes(rawData[0 : 4], byteorder=sys.byteorder) # 32 bits - as 4 bytes\n\n pass\n\n def InitFromBuffer(self, dataId : int, content : str, isFragmented = False, isFirst = False, nextDataBlock = None):\n\n self.id = dataId\n self.content = content\n self.isFragmented = isFragmented\n self.isFirst = isFirst\n self.nextDatablock = nextDataBlock\n\n pass\n\n def Split(self, currDataBlockMaxSize : int, nextDataBlock : int):\n\n print(\"whaaat\")\n\n self.DebugInfo()\n\n content0 = self.content[0 : currDataBlockMaxSize]\n\n data0 = Data()\n data1 = Data()\n\n if self.isFragmented:\n data0.InitFromBuffer(self.id, content0, True, False, nextDataBlock)\n else:\n data0.InitFromBuffer(self.id, content0, True, True, nextDataBlock)\n\n content1 = self.content[currDataBlockMaxSize : len(self.content)]\n data1.InitFromBuffer(None, content1, True, False, nextDataBlock)\n\n return (data0, data1)\n\n def GetLenght(self) -> int:\n\n if not self.isFragmented and self.isFirst:\n print(\"ok\")\n return len(self.id.to_bytes(4, byteorder=sys.byteorder)[2:]) + len(self.content)\n\n if not self.isFragmented:\n print(\"yey\")\n return len(self.content)\n\n if self.isFirst:\n print(\"wow\")\n return len(self.id.to_bytes(4, byteorder=sys.byteorder[2:])) + len(self.content) + len(self.nextDatablock.to_bytes(4, byteorder=sys.byteorder))\n\n print(\"derp\")\n\n return len(self.content) + len(self.nextDatablock.to_bytes(4, byteorder=sys.byteorder))\n\n def ToBytes(self):\n\n if not self.isFragmented:\n\n dataId = self.id.to_bytes(4, byteorder=sys.byteorder)\n content = self.content.encode()\n\n rawData = dataId + content\n\n return rawData\n else:\n if self.nextDatablock is not None:\n return self.content.encode() + self.nextDatablock.to_bytes(4, byteorder=sys.byteorder)\n else:\n return self.content.encode()\n\n def DebugInfo(self) -> None:\n\n print(\"data: id = {0}, isFragmented = {1}, isFirstFragment = {2}, nextDataBlock = {3}\"\n .format(self.id, self.isFragmented, self.isFirst, self.nextDatablock))\n\n print(\"content:\")\n print(self.content)\n print(\"bytes:\")\n print(self.ToBytes())","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332556376","text":"import os\nfrom datetime import datetime, timezone\n\nfrom flask import Flask, render_template, request, jsonify\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.getenv(\"SECRET_KEY\")\nsocketio = SocketIO(app)\n\n\n\nchannels = {\n\t'a': []\n}\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n\tif request.method == 'POST':\n\t\tchannel_name = request.data.decode('utf-8')\n\t\tif channel_name in channels:\n\t\t\treturn jsonify(success=False, error='The channel with this name exists, choose another name')\n\t\t\n\t\tchannels[channel_name] = []\n\t\treturn jsonify(success=True)\n\t\n\treturn render_template('base.html', channels=channels)\n\n\n@app.route(\"/\")\ndef open_channel(channel_name):\n\tif channel_name not in channels:\n\t\treturn ''\n\tmessages = channels[channel_name]\n\t\n\treturn render_template('chat.html', messages=messages)\n\n\n@socketio.on('new message')\ndef handle_message(data):\n\tusername = data['username']\n\ttext = data['text']\n\tchannel_name = data['channel_name']\n\tdate = datetime.now(timezone.utc).isoformat()\n\t\n\tmessage = {\n\t\t'username': username,\n\t\t'text': text,\n\t\t'time': date\n\t}\n\n\tif len(channels[channel_name]) > 99:\n\t\tchannels[channel_name].pop(0)\n\n\tchannels[channel_name].append(message)\n\n\temit(f'announce message {channel_name}', {'username': username, 'text': text, 'date': date}, broadcast=True)","sub_path":"chat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"440764817","text":"# START SETUP #\r\nmodeWanted = input(\"b/s\\n\")\r\nif modeWanted.upper() == \"B\":\r\n mode = \"Big\"\r\nelse:\r\n mode = \"Small\"\r\n# GET FILES #\r\ninputFile = open(\"inputs\\\\revengeOfThePancakes\" + mode + \".in\").readlines()\r\noutputFile = open(\"outputs\\\\revengeOfThePancakes\" + mode + \"Out.txt\", \"w\")\r\n# MAIN #\r\ncaseNumber = 0\r\nfor case in inputFile[1:]:\r\n caseNumber += 1\r\n # TEST FOR END POSITIVE #\r\n if case.rstrip()[-1] == \"+\":\r\n count = -1\r\n else:\r\n count = 0\r\n prevChar = \"\"\r\n for char in case.rstrip():\r\n if char != prevChar:\r\n count += 1\r\n prevChar = char\r\n outputFile.write(\"Case #\" + str(caseNumber) + \": \" + str(count) + \"\\n\")","sub_path":"codes/CodeJamCrawler/16_0_2/brasserpots/revengeOfThePancakes.py","file_name":"revengeOfThePancakes.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"134985490","text":"#!/usr/bin/env python\n\n# Some of this monitor was made possible with help from those at:\n# http://shallowsky.com/blog/hardware/ardmonitor.html\n# http://code.activestate.com/recipes/134892/\n\n\nimport sys\nimport threading\nimport time\nimport Queue\nimport serial\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nclass PythonSerialMonitor():\n def __init__(self, args):\n self.windows = False\n self.unix = False\n self.fd = None\n self.old_settings = None\n self.colors = ['r','b','g','k','m']\n \n #buffer\n self.line = \"\"\n\n #graphing elements\n self.fig = None\n self.li = []\n self.ax = []\n self.counter = 0\n self.data = {}\n self.startTime = time.time()\n self.recordedTime = np.array([])\n self.lastCat = args[-1]\n self.firstCat = args[0]\n self.categories = args\n for category in args:\n self.ax.append(None)\n self.li.append(None)\n self.counter = self.counter + 1\n self.data[category] = np.array([])\n\n\n try:\n # Windows\n import msvcrt\n self.windows = True\n except ImportError:\n # Unix\n import sys, tty, termios\n self.fd = sys.stdin.fileno()\n self.old_settings = termios.tcgetattr(self.fd)\n tty.setcbreak(self.fd)\n self.unix = True\n\n self.input_queue = Queue.Queue()\n self.stop_queue = Queue.Queue()\n self.pause_queue = Queue.Queue()\n\n self.input_thread = threading.Thread(target=self.add_input, args=(self.input_queue,self.stop_queue,self.pause_queue,))\n self.input_thread.daemon = True\n self.input_thread.start()\n\n def getch(self):\n if self.unix:\n import sys, tty, termios\n try:\n tty.setcbreak(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)\n return ch\n if self.windows:\n import msvcrt\n return msvcrt.getch()\n\n def cleanUp(self):\n if self.unix:\n import sys, tty, termios\n termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)\n\n def add_input(self, input_queue, stop_queue, pause_queue):\n while True:\n input_queue.put(self.getch())\n if not pause_queue.empty():\n if pause_queue.get() == 'pause':\n while True:\n if not pause_queue.empty():\n if pause_queue.get() == 'resume':\n break\n if not stop_queue.empty():\n if stop_queue.get() == 'stop':\n break\n\n\n#==================================================================\n#GRAPHING MODULE\n#=================================================================\n def parseVal(self):\n words = self.line.split()\n print(words)\n if (len(words) > 0 and (words[0] in self.categories)):\n category = words[0]\n val = int(words[-1])\n return category, val\n else:\n return 0, 0\n\n def graph_setup(self):\n plt.ion()\n self.fig = plt.figure()\n for i in range(self.counter):\n self.ax[i] = self.fig.add_subplot(111)\n self.li[i], = self.ax[i].plot(self.data[\"Average\"], self.recordedTime)\n #self.ax[i].legend([self.categories[i]])\n self.ax[i].relim()\n self.ax[i].autoscale_view(True,True,True)\n self.fig.canvas.draw()\n\n plt.show(block=False)\n \n def writeData(self, category, val):\n self.data[category] = np.append(self.data[category], val)\n if (category == self.lastCat):\n self.recordedTime = np.append(self.recordedTime, time.time() - self.startTime)\n self.updateGraph()\n\n def updateGraph(self):\n tempCounter = 0\n for category in self.categories:\n self.ax[tempCounter].plot(self.recordedTime, self.data[category], self.colors[tempCounter%len(self.colors)])\n self.li[tempCounter].set_label(self.categories[tempCounter])\n self.ax[tempCounter].legend()\n plt.draw()\n tempCounter = tempCounter + 1\n self.fig.canvas.draw()\n time.sleep(0.01)\n#======================================================================\n\n def run(self):\n baud = 9600\n baseports = ['/dev/ttyUSB', '/dev/ttyACM', 'COM', '/dev/tty.usbmodem1234']\n self.ser = None\n\n while not self.ser:\n for baseport in baseports:\n if self.ser:\n break\n for i in xrange(0, 64):\n try:\n port = baseport + str(i)\n self.ser = serial.Serial(port, baud, timeout=1)\n print(\"Monitor: Opened \" + port + '\\r')\n break\n except:\n self.ser = None\n pass\n\n if not self.ser:\n print(\"Monitor: Couldn't open a serial port.\")\n print(\"Monitor: Press \\'enter\\' to try again or \\'esc\\' to exit.\")\n while True:\n if not self.input_queue.empty():\n keyboardInput = self.input_queue.get()\n if ord(keyboardInput) == 27:\n self.stop_queue.put('stop')\n self.cleanUp()\n sys.exit(1)\n else:\n # Pressing any key other than 'esc' will continue the monitor\n break\n\n self.ser.flushInput()\n\n while True:\n if not self.input_queue.empty():\n keyboardInput = self.input_queue.get()\n print(\"Keyboard: \" + keyboardInput)\n self.ser.write(keyboardInput)\n if ord(keyboardInput) == 27:\n self.stop_queue.put('stop')\n self.cleanUp()\n sys.exit(1)\n\n # Check for Teensy output:\n try:\n bytesToRead = self.ser.inWaiting() # get the amount of bytes available at the input queue\n if bytesToRead:\n self.line += self.ser.read(bytesToRead) # read the bytes\n if (self.line[-1] == \"\\n\"):\n category, val = self.parseVal()\n if (category != 0):\n self.writeData(category, val)\n self.line = \"\"\n\n except IOError:\n # Manually raise the error again so it can be caught outside of this method\n raise IOError()\n\ndef main(argv):\n psm = PythonSerialMonitor(argv)\n psm.graph_setup()\n\n while True:\n try:\n psm.run()\n except serial.SerialException:\n print (\"Monitor: Disconnected (Serial exception)\")\n except IOError:\n print (\"Monitor: Disconnected (I/O Error)\")\n except KeyboardInterrupt:\n print (\"Monitor: Keyboard Interrupt. Exiting Now...\")\n sys.exit(1)\n\nmain(sys.argv[1:])\n\n","sub_path":"COMPLETE/DISCO_ENERGY/Wind_To_Work_test/python-serial-monitor.py","file_name":"python-serial-monitor.py","file_ext":"py","file_size_in_byte":7348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365635684","text":"import re\nemail=input(\"Enter the email:\")\npatt=\"^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$\"\n#print(patt)\nif len(email)>7:\n if re.match(patt,email):\n print(\"Email is valid\")\n else:\n print(\"Email is Invalid\")\nelse:\n print(\"Email should contain atleat 8 character\")\n","sub_path":"Assignment/Python/Set3/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"73106949","text":"# Definition for singly-linked list.\r\nclass ListNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\nclass Solution(object):\r\n\r\n # solution with heap\r\n def mergeKLists(self, lists):\r\n import heapq\r\n dummy = node = ListNode(0)\r\n h = [ (n.val, n) for n in lists if n]\r\n heapq.heapify(h)\r\n while h:\r\n # get the smallest one, always on the beginning\r\n val, n = h[0]\r\n # if no next node, n is currently end of one list\r\n if n.next is None:\r\n # pop smallest\r\n heapq.heappop(h)\r\n else:\r\n # else, push the next node into heap\r\n heapq.heapreplace(h, (n.next.val, n.next))\r\n node.next = n\r\n node = node.next\r\n return dummy.next\r\n\r\n # this is the traditional divide and conquer way, time costing for python\r\n def mergeKLists1(self, lists):\r\n if not lists:\r\n return None\r\n while len(lists) > 1:\r\n cur = self.merge(lists.pop(), lists.pop())\r\n lists.append(cur)\r\n return lists[0]\r\n\r\n def merge(self, h1, h2):\r\n if not h1: return h2\r\n if not h2: return h1\r\n dummy = node = ListNode(0)\r\n while h1 and h2:\r\n if h1.val < h2.val:\r\n node.next = h1\r\n h1 = h1.next\r\n node = node.next\r\n else:\r\n node.next = h2\r\n h2 = h2.next\r\n node = node.next\r\n if h1:\r\n node.next = h1\r\n if h2:\r\n node.next = h2\r\n return dummy.next\r\n\r\n","sub_path":"MergeKLists.py","file_name":"MergeKLists.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"61090436","text":"from random import shuffle\n\n\nclass CSP:\n def __init__(self, variables, domains, neighbours, constraints):\n self.variables = variables\n self.domains = domains\n self.neighbours = neighbours\n self.constraints = constraints\n\n def backtracking_search(self):\n return self.recursive_backtracking({})\n\n def recursive_backtracking(self, assignment):\n if self.is_complete(assignment):\n return assignment\n\n variable = self.select_unassigned_variable(assignment)\n\n for value in self.order_domain_values(variable, assignment):\n if self.is_consistent(variable, value, assignment):\n assignment[variable] = value\n result = self.recursive_backtracking(assignment)\n if result is not None:\n return result\n del assignment[variable]\n\n return None\n\n def select_unassigned_variable(self, assignment):\n for variable in self.variables:\n if variable not in assignment:\n return variable\n\n def is_complete(self, assignment):\n for variable in self.variables:\n if variable not in assignment:\n return False\n return True\n\n def order_domain_values(self, variable, assignment):\n all_values = self.domains[variable][:]\n shuffle(all_values)\n return all_values\n\n def is_consistent(self, variable, value, assignment):\n if not assignment:\n return True\n\n for constraint in self.constraints.values():\n for neighbour in self.neighbours[variable]:\n if neighbour not in assignment:\n continue\n\n neighbour_value = assignment[neighbour]\n if not constraint(variable, value, neighbour, neighbour_value):\n return False\n return True\n\n\ndef create_south_america_csp():\n costa_rica, panama, colombia, venezuela, guyana, suriname, guyana_fr, brasil, uruguay, argentina, chile, bolivia, paraguay, peru, ecuador = 'Costa Rica', 'Panama', 'Colombia', 'Venezuela', 'Guyana', 'Suriname', 'Guyana Fr', 'Brasil', 'Uruguay', 'Argentina', 'Chile', 'Bolivia', 'Paraguay', 'Peru', 'Ecuador'\n values = ['Red', 'Green', 'Blue', 'Yellow']\n variables = [costa_rica, panama, colombia, venezuela, guyana, suriname, guyana_fr, brasil, uruguay, argentina, chile, bolivia, paraguay, peru, ecuador]\n domains = {\n costa_rica: values[:],\n panama: values[:],\n colombia: values[:],\n venezuela: values[:],\n guyana: values[:],\n suriname: values[:],\n guyana_fr: values[:],\n brasil: values[:],\n uruguay: values[:],\n argentina: values[:],\n chile: values[:],\n bolivia: values[:],\n paraguay: values[:],\n peru: values[:],\n ecuador: values[:],\n }\n neighbours = {\n costa_rica: [panama],\n panama: [costa_rica, colombia],\n colombia: [panama, ecuador, peru, brasil, venezuela],\n venezuela: [colombia, guyana, brasil],\n guyana: [venezuela, brasil, suriname],\n suriname: [guyana, brasil, guyana_fr],\n guyana_fr: [suriname, brasil],\n brasil: [guyana_fr, suriname, guyana, venezuela, colombia, peru, bolivia, paraguay, argentina, uruguay],\n uruguay: [argentina, brasil],\n argentina: [uruguay, brasil, paraguay, bolivia, chile],\n chile: [argentina, bolivia, peru],\n bolivia: [chile, argentina, brasil, paraguay, peru],\n paraguay: [argentina, brasil, bolivia],\n peru: [chile, bolivia, brasil, colombia, ecuador],\n ecuador: [peru, colombia],\n }\n\n def constraint_function(first_variable, first_value, second_variable, second_value):\n return first_value != second_value\n\n constraints = {\n costa_rica: constraint_function,\n panama: constraint_function,\n colombia: constraint_function,\n guyana: constraint_function,\n suriname: constraint_function,\n guyana_fr: constraint_function,\n brasil: constraint_function,\n uruguay: constraint_function,\n argentina: constraint_function,\n chile: constraint_function,\n bolivia: constraint_function,\n paraguay: constraint_function,\n peru: constraint_function,\n ecuador: constraint_function,\n }\n\n return CSP(variables, domains, neighbours, constraints)\n\n\nif __name__ == '__main__':\n south_america = create_south_america_csp()\n result = south_america.backtracking_search()\n for area, color in sorted(result.items()):\n print(\"{}: {}\".format(area, color))","sub_path":"Exercises/8_CSP/Homework/contrains_south_america.py","file_name":"contrains_south_america.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"38591721","text":"import matplotlib.patches as mpatches\nimport numpy\nimport matplotlib.pyplot as plt\nimport math\nfrom astropy.io import fits\n\n\"\"\"\nmain function: provide names of files to open, passes name to correct_image\ncorrect_image: opens the image, applies the correction, writes new file\nsubtract_images: takes two new image names,opens them, subtracts them from each other, writes new file\nhoriz_slice: gets a horizontal line of pixels and graphs the counts in each pixel\nvert_slice: gets a horizontal line of pixels and graphs the counts in each pixel\n\"\"\"\n\ndef main():\n\t#opens each image, applies the correction, writes new file.\n\t\n\t#for tau\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 54:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"tau_000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"tau_0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"tau_000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"tau_0000\"+str(i+3)+\".fit\"\n\t\t\t\n\t\tcorrect_image(fname1)\n\t\tcorrect_image(fname2)\n\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,4)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,4)\n\t\t\n\t\tif(i == 15):\n\t\t\ti = i + 7\n\t\telif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 54:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"FIXED_tau_000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"FIXED_tau_0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"FIXED_tau_000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"FIXED_tau_0000\"+str(i+3)+\".fit\"\n\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,1)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,1)\n\t\t\t\t\n\t\tif(i == 15):\n\t\t\ti = i + 7\n\t\telif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\t\n\t\n\t#for tau_sat\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 57:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"tau_sat_000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"tau_sat_0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"tau_sat_000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"tau_sat_0000\"+str(i+3)+\".fit\"\n\t\t\t\n\t\tcorrect_image(fname1)\n\t\tcorrect_image(fname2)\n\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,5)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,5)\n\t\t\n\t\tif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 57:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"FIXED_tau_sat_000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"FIXED_tau_sat_0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"FIXED_tau_sat_000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"FIXED_tau_sat_0000\"+str(i+3)+\".fit\"\n\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,2)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,2)\n\t\t\t\t\n\t\tif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\t\n\t#for tau_unsat\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 9:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"tau_unsat000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"tau_unsat0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"tau_unsat000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"tau_unsat0000\"+str(i+3)+\".fit\"\n\t\t\t\n\t\tcorrect_image(fname1)\n\t\tcorrect_image(fname2)\n\t\t\t\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,6)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,6)\n\t\t\t\t\n\t\tif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\n\ti = 1\n\tx = 1\n\tflip = 0\n\t\n\twhile i <= 9:\n\t\n\t\tif i > 9:\n\t\t\tfname1 = \"FIXED_tau_unsat000\"+str(i)+\".fit\"\n\t\telse:\n\t\t\tfname1 = \"FIXED_tau_unsat0000\"+str(i)+\".fit\"\n\t\t\n\t\tif i + 3 > 9:\n\t\t\tfname2 = \"FIXED_tau_unsat000\"+str(i+3)+\".fit\"\n\t\telse:\n\t\t\tfname2 = \"FIXED_tau_unsat0000\"+str(i+3)+\".fit\"\n\t\t\t\t\t\n\t\tif (flip == 0):\n\t\t\tsubtract_images(fname1,fname2,x,3)\n\t\telse:\n\t\t\tsubtract_images(fname2,fname1,x,3)\n\t\t\t\t\n\t\tif(x%3 == 0):\n\t\t\ti = i + 4\n\t\t\tif (flip == 0):\n\t\t\t\tflip = 1\n\t\t\telse:\n\t\t\t\tflip = 0\n\t\telse:\n\t\t\ti = i + 1\n\t\t\n\t\tx = x + 1\n\t\t\n\thoriz_slice()\n\tvert_slice()\n\ndef correct_image(fname):\n\tx = 0\n\ty = 0\n\tds9x2 = 400\n\tds9y2 = 200\n\tcoefs_inv = [ -6.32644177e-17,5.55450534e-11,-2.19977738e-06,1.02869293e+00,-1.21422072e+02]\n\n\thdu1 = fits.open(fname)\n\tscidata = hdu1[0].data\n\tarray = numpy.ndarray(shape=(ds9y2,ds9x2))\n\n\twhile x < ds9x2:\n\t\twhile y < ds9y2:\n\t\t\tstr_num = str(scidata[0,y,x])\n\t\t\tnum = float(str_num)\n\t\t\tnew_num = num*num*num*num*coefs_inv[0] + num*num*num*coefs_inv[1] + num*num*coefs_inv[2] + num*coefs_inv[3] + coefs_inv[4]\n\t\t\tarray.itemset((y,x),new_num)\n\t\t\ty = y + 1\n\t\ty = 0\n\t\tx = x + 1\n\n\thdu = fits.PrimaryHDU(array)\n\thdu.writeto('FIXED_'+fname, clobber = True)\n\t\ndef subtract_images(fname1,fname2,val,val2):\n\tx = 0\n\ty = 0\n\tds9x2 = 400\n\tds9y2 = 200\n\t\n\thdu1 = fits.open(fname1)\n\tscidata1 = hdu1[0].data\n\tarray1 = numpy.ndarray(shape=(ds9y2,ds9x2))\n\thdu2 = fits.open(fname2)\n\tscidata2 = hdu2[0].data\n\tarray2 = numpy.ndarray(shape=(ds9y2,ds9x2))\n\t\n\twhile x < ds9x2:\n\t\twhile y < ds9y2:\n\t\t\t#For first image\n\t\t\tif(val2 == 4 or val2 == 5 or val2 == 6):\n\t\t\t\tstr_num = str(scidata1[0,y,x])\n\t\t\telse:\n\t\t\t\tstr_num = str(scidata1[y,x])\n\t\t\tnum = float(str_num)\n\t\t\tarray1.itemset((y,x),num)\n\t\t\t\n\t\t\t#and the other\n\t\t\tif(val2 == 4 or val2 == 5 or val2 == 6):\n\t\t\t\tstr_num = str(scidata2[0,y,x])\n\t\t\telse:\n\t\t\t\tstr_num = str(scidata2[y,x])\n\t\t\tnum = float(str_num)\n\t\t\tarray2.itemset((y,x),num)\n\t\t\ty = y + 1\n\t\ty = 0\n\t\tx = x + 1\n\n\tarray = numpy.subtract(array1,array2)\n\t\t\n\thdu = fits.PrimaryHDU(array)\n\t\n\tif val2 == 1:\n\t\thdu.writeto('FIXED_sub_IMG'+str(val)+'.fit', clobber = True)\n\t\n\tif val2 == 2:\n\t\thdu.writeto('FIXED_sub_sat_IMG'+str(val)+'.fit', clobber = True)\n\t\n\tif val2 == 3:\n\t\thdu.writeto('FIXED_sub_unsat_IMG'+str(val)+'.fit', clobber = True)\n\t\t\n\tif val2 == 4:\n\t\thdu.writeto('sub_IMG'+str(val)+'.fit', clobber = True)\n\t\t\n\tif val2 == 5:\n\t\thdu.writeto('sub_sat_IMG'+str(val)+'.fit', clobber = True)\n\t\t\n\tif val2 == 6:\n\t\thdu.writeto('sub_unsat_IMG'+str(val)+'.fit', clobber = True)\n\t\t\ndef horiz_slice():\n\tx1 = 0\n\tx2 = 400\n\ty = 99\n\tfname1 = \"sub_IMG1.fit\"\n\tfname2 = \"FIXED_sub_IMG1.fit\"\n\thdu1 = fits.open(fname1)\n\thdu2 = fits.open(fname2)\n\tscidata1 = hdu1[0].data\n\tscidata2 = hdu2[0].data\n\n\tarray1 = numpy.ndarray(x2)\n\tarray2 = numpy.ndarray(x2)\n\n\twhile x1 < x2:\n\t\tstr_num = str(scidata1[y,x1])\n\t\tnum = float(str_num)\n\t\tarray1.itemset(x1,num)\n\t\tstr_num = str(scidata2[y,x1])\n\t\tnum = float(str_num)\n\t\tarray2.itemset(x1,num)\n\t\tx1 = x1 + 1\n\t\n\txarr = numpy.arange(0,400,1)\n\n\tplt.scatter(xarr,array1,c = 'r')\n\tplt.scatter(xarr,array2,c = 'b')\n\tplt.ylabel('counts')\n\tplt.xlabel('pixel')\n\tplt.title('Counts for subtracted initial and fixed image: horizontal',fontsize = 15)\n\tred_patch = mpatches.Patch(color='red', label='Original counts')\n\tblue_patch = mpatches.Patch(color='blue', label='Adjusted counts')\n\t\n\tplt.legend(handles=[red_patch,blue_patch],bbox_to_anchor=(1, .18))\n\tplt.axis([0,400,0,20000])\n\tplt.show()\n\ndef vert_slice():\n\ty1 = 0\n\ty2 = 200\n\tx = 99\n\tfname1 = \"sub_IMG1.fit\"\n\tfname2 = \"FIXED_sub_IMG1.fit\"\n\thdu1 = fits.open(fname1)\n\thdu2 = fits.open(fname2)\n\tscidata1 = hdu1[0].data\n\tscidata2 = hdu2[0].data\n\t\n\tarray1 = numpy.ndarray(y2)\n\tarray2 = numpy.ndarray(y2)\n\t\n\twhile y1 < y2:\n\t\tstr_num = str(scidata1[y1,x])\n\t\tnum = float(str_num)\n\t\tarray1.itemset(y1,num)\n\t\tstr_num = str(scidata2[y1,x])\n\t\tnum = float(str_num)\n\t\tarray2.itemset(y1,num)\n\t\ty1 = y1 + 1\n\t\n\tyarr = numpy.arange(0,200,1)\n\t\n\tplt.scatter(yarr,array1,c = 'r')\n\tplt.scatter(yarr,array2,c = 'b')\n\tplt.ylabel('counts')\n\tplt.xlabel('pixel')\n\tplt.title('Counts for subtracted initial and fixed image: vertical',fontsize = 15)\n\tred_patch = mpatches.Patch(color='red', label='Original counts')\n\tblue_patch = mpatches.Patch(color='blue', label='Adjusted counts')\n\t\n\tplt.legend(handles=[red_patch,blue_patch],bbox_to_anchor=(1, .18))\n\tplt.axis([0,200,0,20000])\n\tplt.show()\n\t\t\n\tx = 0\n\twhile x < y2:\n\t\tarray1.itemset(x,abs(array1[x]))\n\t\tx = x + 1\n\t\n\tlogarr1 = numpy.ndarray(y2)\n\tlogarr2 = numpy.ndarray(y2)\n\t\n\tx = 0\n\twhile x < y2:\n\t\tif array1[x] != 0:\n\t\t\tlogarr1.itemset(x,math.log10(abs(array1[x])))\n\t\t\tlogarr2.itemset(x,math.log10(abs(array2[x])))\n\t\t\n\t\tx = x + 1\n\t\t\n\tplt.scatter(yarr,logarr1,c = 'r')\n\tplt.scatter(yarr,logarr2,c = 'b')\n\tplt.ylabel('log(counts)')\n\tplt.xlabel('pixel')\n\tplt.title('Log(counts) for subtracted initial and fixed image: vertical',fontsize = 15)\n\tred_patch = mpatches.Patch(color='red', label='Original counts')\n\tblue_patch = mpatches.Patch(color='blue', label='Adjusted counts')\n\t\n\tplt.legend(handles=[red_patch,blue_patch],bbox_to_anchor=(1, .18))\n\tplt.axis([0,200,0,5])\n\tplt.show()\n\nmain()","sub_path":"clio2016-2017/project_files/linearityCodeNov20142Data.py","file_name":"linearityCodeNov20142Data.py","file_ext":"py","file_size_in_byte":8410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"260419510","text":"#coding=gbk\r\nimport win32api\r\nimport win32con\r\nfrom ctypes import *\r\nimport time\r\n\r\ntt = '03'\r\nflag = 1\r\nwhile flag:\r\n\tt = time.localtime() # 当前时间的纪元值\r\n\tfmt = \"%H %M %S\"\r\n\tnow = time.strftime(fmt, t) # 将纪元值转化为包含时、分的字符串\r\n\tnow = now.split(' ') # 以空格切割,将时、分放入名为now的列表中\r\n\r\n\thour = now[0]\r\n\tminute = now[1]\r\n\tsecond = now[2]\r\n\ttime.sleep(0.5)\r\n\tprint(second)\r\n\tprint(second == tt)\r\n\tif second==tt:\r\n\t\tfor i in range(1,2):\r\n\t\t\t# time.sleep(1)\r\n\t\t\twindll.user32.SetCursorPos(1100,600);\r\n\t\t\twin32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,1100, 600)\r\n\t\t\ttime.sleep(0.05)\r\n\t\t\twin32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 1100, 600)\r\n\t\tflag = 1","sub_path":"pythonClick/pythonOfClick.py","file_name":"pythonOfClick.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"62010436","text":"# coding: utf-8\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # for issue: The TensorFlow library wasn't compiled to use SSE3\n\nsess = tf.InteractiveSession()\na = tf.constant(5.0)\nb = tf.constant(6.0)\nc = a / b\n# We can just use 'c.eval()' without specifying the context 'sess'\nprint(c.eval())\nsess.close()\n","sub_path":"day01_InteractiveSession.py","file_name":"day01_InteractiveSession.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206783580","text":"import sys\nimport re\nimport math\ns=sys.stdin.read()\ndigits=re.findall(r\"-?\\d+\",s)\nlistline= [int(e) for e in digits ]\nlistline.sort()\nn=len(listline)\nif n%2==0:\n fenzi=listline[(n-1)//2]+listline[(n+1)//2]\n res=fenzi/2\n print(\"%.5f\" %res)\nelse:\n if n==1:\n standard= float('%.5f' % listline[0])\n print(\"%.5f\" %standard)\n else:\n stand = float(\"%.5f\" %listline[n//2])\n print(\"%.5f\" %stand)","sub_path":"Code/CodeRecords/2565/60753/263987.py","file_name":"263987.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"264446323","text":"# -*- coding: utf-8 -*-\nimport json\nimport base64\nimport datetime\nimport logging\nimport inject\nimport psycopg2\nfrom model.exceptions import *\n\nfrom model.config import Config\nfrom model.profiles import Profiles\nfrom model.events import Events\n\nfrom model.systems.assistance.assistance import Assistance\nfrom model.systems.assistance.date import Date\nfrom model.systems.assistance.justifications.justifications import Justifications\nfrom model.systems.assistance.overtime import Overtime\n\nimport asyncio\nfrom asyncio import coroutine\nfrom autobahn.asyncio.wamp import ApplicationSession\n\n\nclass OvertimeWamp(ApplicationSession):\n\n def __init__(self, config=None):\n logging.debug('instanciando')\n ApplicationSession.__init__(self, config)\n\n self.serverConfig = inject.instance(Config)\n\n @coroutine\n def onJoin(self, details):\n logging.debug('registering methods')\n yield from self.register(self.getRequests_async, 'assistance.overtime.getRequests')\n yield from self.register(self.getRequestsToManage_async, 'assistance.overtime.getRequestsToManage')\n yield from self.register(self.requestOvertime_async, 'assistance.overtime.requestOvertime')\n yield from self.register(self.persistStatus_async, 'assistance.overtime.persistStatus')\n\n def _getDatabase(self):\n host = self.serverConfig.configs['database_host']\n dbname = self.serverConfig.configs['database_database']\n user = self.serverConfig.configs['database_user']\n passw = self.serverConfig.configs['database_password']\n return psycopg2.connect(host=host, dbname=dbname, user=user, password=passw)\n\n def getRequests(self, status):\n con = self._getDatabase()\n try:\n ''' .... codigo aca ... '''\n con.commit()\n return True\n\n finally:\n con.close()\n\n @coroutine\n def getRequests_async(self, status):\n loop = asyncio.get_event_loop()\n r = yield from loop.run_in_executor(None, self.getRequests, status)\n return r\n\n def getRequestsToManage(self, status, group):\n con = self._getDatabase()\n try:\n ''' .... codigo aca ... '''\n con.commit()\n return True\n\n finally:\n con.close()\n\n @coroutine\n def getRequestsToManage_async(self, status, group):\n loop = asyncio.get_event_loop()\n r = yield from loop.run_in_executor(None, self.getRequestsToManage, status, group)\n return r\n\n def requestOvertime(self, userId, request):\n con = self._getDatabase()\n try:\n ''' .... codigo aca ... '''\n con.commit()\n return True\n\n finally:\n con.close()\n\n @coroutine\n def requestOvertime_async(self, userId, request):\n loop = asyncio.get_event_loop()\n r = yield from loop.run_in_executor(None, self.requestOvertime, userId, request)\n return r\n\n def persistStatus(self, requestId, status):\n con = self._getDatabase()\n try:\n ''' .... codigo aca ... '''\n con.commit()\n return True\n\n finally:\n con.close()\n\n @coroutine\n def persistStatus_async(self, requestId, status):\n loop = asyncio.get_event_loop()\n r = yield from loop.run_in_executor(None, self.persistStatus, requestId, status)\n return r\n","sub_path":"server/actions/systems/assistance/overtime.py","file_name":"overtime.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"22569954","text":"\"\"\"\nCalculate precision of the k-anonymity\nhttps://dataprivacylab.org/dataprivacy/projects/kanonymity/kanonymity2.pdf\n\"\"\"\nimport argparse\nimport csv\nfrom datetime import datetime\n\n\ndef load_csv(file_path):\n lines = []\n\n with open(file_path, 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n\n for line in csv_reader:\n lines.append(line)\n\n return lines\n\n\ndef calculate_precision(csv_data, qi_indexes, vghs):\n p = 0\n\n for row in csv_data:\n for i, qi_index in enumerate(qi_indexes):\n data = row[qi_index]\n vgh = vghs[i]\n p += get_avg_level(data, vgh)\n\n p = 1 - (p / (len(csv_data) * len(qi_indexes)))\n\n return p\n\n\ndef get_avg_level(data, vgh):\n depth = len(vgh[0])\n level = 0\n found = False\n\n for row in vgh:\n for c in range(len(row)):\n if row[c] == data:\n level = c\n found = True\n break\n\n if found:\n break\n\n return level / depth\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"Python implementation to calculate the precision of k-anonymous data.\")\n parser.add_argument(\"--private_table\", \"-pt\", required=True,\n type=str, help=\"Path to the K-anonymized csv table.\")\n parser.add_argument(\"--quasi_identifier\", \"-qi\", required=True,\n type=str, help=\"Index of the attributes which are Quasi Identifiers, starting from 0 \"\n \"of the private table.\",\n nargs='+')\n parser.add_argument(\"--domain_gen_hierarchies\", \"-dgh\", required=True,\n type=str, help=\"Paths to the generalization files (must have same order as \"\n \"the QI index list.\",\n nargs='+')\n args = parser.parse_args()\n\n try:\n start = datetime.now()\n\n if len(args.quasi_identifier) != len(args.domain_gen_hierarchies):\n raise Exception(\"Parameters' dimensions mismatch\")\n\n qi_idx = [int(i) for i in args.quasi_identifier]\n gen_data = []\n\n for i, dgh_path in enumerate(args.domain_gen_hierarchies):\n gen_data += [load_csv(dgh_path)]\n\n anon_file = load_csv(args.private_table)\n\n precision = calculate_precision(anon_file, qi_idx, gen_data)\n print('[LOG] Precision = {0:.16f}'.format(precision))\n\n end = (datetime.now() - start).total_seconds()\n\n print(\"[LOG] Done in %.2f seconds (%.3f minutes (%.2f hours))\" %\n (end, end / 60, end / 60 / 60))\n\n except FileNotFoundError as error:\n print(\"[ERROR] File '%s' has not been found.\" % error.filename)\n except IOError as error:\n print(\"[ERROR] There has been an error with reading file '%s'.\" % error.filename)\n","sub_path":"precision.py","file_name":"precision.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642727736","text":"import random\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom matplotlib.collections import PatchCollection\n\ndef label(xy, text):\n x = xy[0] + 15 # shift y-value for label so that it's below the artist\n plt.text(x, xy[1] + 33, text, ha=\"center\", family='sans-serif', size=10)\n\ndef create_env():\n # create cavas\n fig, ax = plt.subplots()\n cords, w, h= [[5, 5], [45, 5], [5, 45], [45, 45]], 30, 30\n patches = []\n kwargs = dict(facecolor='white', edgecolor='green', linestyle='dashed')\n for idx, cord in enumerate(cords):\n p = mpatches.FancyBboxPatch(cord, w, h, boxstyle=mpatches.BoxStyle(\"Round\", rounding_size=0.5), **kwargs)\n label(cord, \"Patch \" + str(idx+1))\n patches.append(p)\n\n collection = PatchCollection(patches, **kwargs)\n ax.add_collection(collection)\n\n ax.set_ylim(80, 0)\n ax.set_xlim(0, 80)\n plt.show()\n\nif __name__ == \"__main__\":\n create_env()\n","sub_path":"7@RESEARCH/marl/env_mrta.py","file_name":"env_mrta.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"460018402","text":"import clr\nimport re\nfrom datetime import datetime, date\n\nclr.AddReference('DB_Visualization_GUI.dll')\nfrom DB_Visualization_GUI import FrmMetrics\n\nclr.AddReference('System')\nclr.AddReference('System.Drawing')\nclr.AddReference('System.Windows.Forms')\nclr.AddReference('System.IO')\nfrom System.Windows.Forms import ListBox, Label, TableLayoutColumnStyleCollection\nfrom System.Drawing import Size, Font, FontStyle\n\nfrom System import DBNull, String\nimport math\n\n\nclass FrmMetrics(FrmMetrics):\n\n def __init__(self, rows, columns, metrics, selectedAttributes):\n self.minimums = []\n self.maximums = []\n\n self.rows = rows\n self.columns = columns\n self.columnNames = [\"Attribute\"] + metrics\n self.attributes = selectedAttributes\n\n self._initializeUserInterface()\n self._initializeBusinessLogic()\n\n def _initializeBusinessLogic(self):\n self._assignEventMethods()\n\n def _initializeUserInterface(self):\n self.Size = Size(1600, 500)\n self.tlpMain.ColumnCount = len(self.columnNames)\n self.tlpMain.RowCount = 2\n self.tlpMain.Size = self.ClientRectangle.Size\n #create list titles\n for name in self.columnNames:\n lbl = Label()\n lbl.Text = name\n lbl.Font = Font(\"Microsoft Sans Serif\", 12, FontStyle.Bold)\n lbl.Height = 50\n self.tlpMain.Controls.Add(lbl)\n #create lists \n for name in self.columnNames:\n lst = ListBox()\n lst.Name = name\n lst.Font = Font(\"Microsoft Sans Serif\", 10)\n lst.Width = 135\n if name.ToLower() == 'attribute':\n lst.Width = 300\n if name.ToLower() == 'mode':\n lst.Width = 215\n lst.Height = self.ClientRectangle.Height - (lbl.Height * 2)\n self.tlpMain.Controls.Add(lst)\n self._populateLists(lst)\n\n def _assignEventMethods(self):\n #loop through table layout panel to modify each list\n for lst in self.tlpMain.Controls:\n #quick and dirty way to remove labels\n if lst.Name in self.columnNames:\n lst.SelectedIndexChanged += self._syncListsIndexes\n\n def _syncListsIndexes(self, sender, event):\n for lst in self.tlpMain.Controls:\n #quick and dirty way to remove labels\n if lst.Name in self.columnNames:\n try:\n lst.SelectedIndex = sender.SelectedIndex\n except:\n print(\"'{}' index is empty.\".format(lst.Name))\n\n #identifies name of list and passes list to appropriate populate method\n def _populateLists(self, lst):\n name = lst.Name.ToLower()\n #populate attributes list\n if name == 'attribute':\n self._populateAttributes(lst)\n\n #populate minimums list\n if name == 'minimum':\n self.minimums = self._getMinimums() #minumums is in declared in module-level scope so that it can be passed to _getRanges as parameter\n for item in self.minimums:\n lst.Items.Add(item)\n\n #populate maximums list\n if name == 'maximum':\n self.maximums = self._getMaximums() #maximums is in declared in module-level scope so that it can be passed to _getRanges as parameter\n for item in self.maximums:\n lst.Items.Add(item)\n\n #populate ranges list\n if name == 'range':\n ranges = self._getRanges(self.minimums, self.maximums)\n for item in ranges:\n lst.Items.Add(item)\n\n #populate means list\n if name == 'mean':\n self.means = self._getMeans()\n for item in self.means:\n try:\n lst.Items.Add('{0:.2f}'.format(item))\n except:\n lst.Items.Add(item)\n\n #populate variance list\n if name == 'variance':\n self.variances = self._getVariances(self.means)\n for item in self.variances:\n try:\n lst.Items.Add('{0:.2f}'.format(item))\n except:\n lst.Items.Add(item)\n\n #populate standard deviation list\n if name == 'standard deviation':\n stdDevs = self._getStandardDeviations(self.variances)\n for item in stdDevs:\n try:\n lst.Items.Add('{0:.2f}'.format(item))\n except:\n lst.Items.Add(item)\n\n #populate mode list\n if name == 'mode':\n modes = self._getModesJSON()\n #print(modes)\n for attr in self.attributes:\n try:\n modeVal = modes[attr][0]\n except:\n modeVal = 'NA'\n if isinstance(modeVal, list):\n try:\n modeVal = modeVal[0]\n except:\n pass\n if isinstance(modeVal, DBNull):\n modeVal = \"DBNULL\"\n \n mode = modes[attr][1]\n lst.Items.Add(\"'{}': {}\".format(modeVal, mode))\n\n\n #populate null count list\n if name == 'null count':\n nullCounts = self._getNullCountJSON()\n for attr in self.attributes:\n try:\n nullCount = nullCounts[attr]\n except:\n nullCount = 0\n total = nullCounts[attr + \"total\"] \n percent = (float(nullCount) / float(total)) * 100\n \n formatted = \"{0}/ {1} | {2:.2f}%\".format(nullCount, total, percent)\n lst.Items.Add(formatted)\n\n def _populateAttributes(self,lst):\n for attribute in self.attributes:\n lst.Items.Add(attribute)\n\n def _getMinimums(self):\n #calculate minimum value for each selected column in DB, becomes row in metric form\n minimums = []\n for col in self.columns:\n val = float(\"inf\")\n for row in self.rows:\n contents = row[col]\n if re.match(\"\\d{4}-\\d{2}-\\d{2}\", contents.ToString()):\n if type(val) == float:\n val = datetime.max.date()\n contents = datetime.strptime(contents[:10], \"%Y-%m-%d\").date()\n \n if isinstance(contents, DBNull):\n continue\n try:\n if int(contents.strip('\"')) < val:\n val = contents\n except:\n if contents < val:\n val = contents\n try:\n if (col.DataType.ToString() == 'System.String' and not re.match(\"\\d{4}-\\d{2}-\\d{2}\",row[col].ToString())) or val == float(\"inf\"):\n val = 'NA'\n except:\n pass\n minimums.Add(val)\n return minimums\n\n def _getMaximums(self):\n #calculate maximum value for each selected column in DB, becomes row in metric form\n maximums = []\n for col in self.columns:\n val = -1.0\n for row in self.rows:\n contents = row[col]\n if re.match(\"\\d{4}-\\d{2}-\\d{2}\", contents.ToString()):\n if type(val) == float:\n val = datetime.min.date()\n contents = datetime.strptime(contents[:10], \"%Y-%m-%d\").date()\n\n if isinstance(contents, DBNull):\n continue\n try:\n if int(contents.strip('\"')) > val:\n val = contents\n except:\n if contents > val:\n val = contents\n if (col.DataType.ToString() == 'System.String' and not re.match(\"\\d{4}-\\d{2}-\\d{2}\",row[col].ToString())) or val == -1:\n val = 'NA'\n maximums.Add(val)\n return maximums\n\n def _getRanges(self, mins, maxs):\n #calculate range values between two lists for each index, return new list of ranges\n ranges = []\n for i in range(len(mins)):\n try:\n ranges.Add(maxs[i] - mins[i])\n except:\n ranges.Add('NA')\n return ranges\n\n def _getMeans(self):\n means = []\n for col in self.columns:\n size = 0.0\n sum = 0.0\n for row in self.rows:\n size += 1\n contents = row[col]\n if type(contents) != bool:\n try:\n sum += contents\n except:\n size -= 1\n else:\n size -= 1\n try:\n means.Add(sum / size)\n except:\n means.Add('NA')\n return means\n\n\n def _getVariances(self,means):\n variances = []\n colIndex = 0\n currentVal = 0.0\n for col in self.columns:\n mean = self.means[colIndex]\n colIndex += 1\n rowCount = 0\n sumOfDifferenceSquared = 0.0\n for row in self.rows:\n currentVal = row[col]\n rowCount += 1\n try:\n sumOfDifferenceSquared += (mean - currentVal)**2\n except:\n rowCount -= 1\n try:\n variances.Add(sumOfDifferenceSquared / rowCount)\n except:\n variances.Add('NA')\n return variances\n\n\n def _getStandardDeviations(self,variances):\n sqrts = []\n for variance in variances:\n try:\n sqrts.Add(math.sqrt(variance))\n except:\n sqrts.Add('NA')\n return sqrts\n\n\n def _getModesJSON(self):\n valueCounts = {}\n modes = {}\n for col in self.columns:\n valueCounts[col.ColumnName] = {}\n rowNumber = 0\n for row in self.rows:\n value = row[col]\n try:\n valueCounts[col.ColumnName][value] += 1\n except KeyError:\n valueCounts[col.ColumnName][value] = 1\n #find modes\n for key in valueCounts:\n try:\n mode = max(valueCounts[key].values())\n except:\n mode = 'NA'\n modeAttr = [k for k, v in valueCounts[key].items() if v == mode]\n if len(modeAttr) >= 2:\n try:\n modeAttr = modeAttr[0]\n except:\n pass\n\n modes[key] = (modeAttr, mode)\n return modes\n \n\n\n def _getNullCountJSON(self):\n nulls = {}\n for col in self.columns:\n rowCount = 0\n for row in self.rows:\n rowCount += 1\n contents = row[col]\n if isinstance(contents, DBNull):\n try:\n nulls[col.ColumnName] += 1\n except:\n nulls[col.ColumnName] = 1\n nulls[str(col.ColumnName) + \"total\"] = rowCount\n return nulls\n\n\n\n\n","sub_path":"FrmMetrics.py","file_name":"FrmMetrics.py","file_ext":"py","file_size_in_byte":11269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435597460","text":"#!python3\n'''\nCode that consolidates all aux needed to run any file in\n weather_module repository in alphabetical order.\n'''\nfrom balloon import balloon_scraper\nimport pickle\n\nYEAR = '2014'\nMONTH = '01'\nDAY = '07'\nHOUR = '00'\ndirectory = './'\nlocations = ['72249'] # Corresponds to Fort Worth/Dallas\ndata = balloon_scraper(YEAR, MONTH, DAY, HOUR, directory, save=True,\n locations=locations)\n","sub_path":"Codes/Retrieve radiosonde data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469322639","text":"from .. import Collection\n\ndef collection_new(database):\n\n print ()\n\n # Name\n #\n user_input_valid = False\n while not user_input_valid:\n name_input = input(\n 'Collection name: '\n )\n if isinstance(name_input, str) and len(name_input) > 0:\n user_input_valid = True\n name = name_input\n del name_input\n else:\n print(\n '\\nInvalid name entered\\n\\n'\n )\n \n # Address\n #\n user_input_valid = False\n while not user_input_valid:\n address_input = input(\n 'Address: '\n )\n if isinstance(address_input, str) and len(address_input) > 0:\n user_input_valid = True\n address = address_input\n del address_input\n else:\n print(\n '\\nInvalid address entered\\n\\n'\n )\n\n new_collection = (Collection(name=name, address=address))\n database.add_collections([new_collection])\n \n return ('collection_view', new_collection, False)\n\ndef collection_view(collection):\n\n print()\n\n # Show collection data\n #\n print(\n '\\n Collection {name}\\n On: {address}\\n'.format(name=collection.name, address=collection.address)\n )\n\n # Show properties\n #\n print(\n ' Properties:\\n'\n )\n for i in range(0, len(collection.properties)):\n\n if collection.properties[i].optional:\n optional = '*'\n else:\n optional = ''\n\n if collection.properties[i].type == 'ObjectProperty':\n type_string = 'Object'\n elif collection.properties[i].type == 'ControlledObjectProperty':\n type_string = 'Controlled Object'\n elif collection.properties[i].type == 'ArrayProperty':\n type_string = '<{elt_type}>'.format(elt_type=collection.properties[i].property_type)\n else:\n type_string = collection.properties[i].type\n\n print(\n ' ({i}) {name} ({type}){optional}'.format(i=str(i).center(5, ' '), name=collection.properties[i].name, type=type_string, optional=optional)\n )\n if len(collection.properties) == 0:\n print(\n ' No properties in collection'\n )\n print('\\n')\n\n # User\n #\n user_input_valid = False\n while not user_input_valid:\n user_input = input(\n '(N) New property | (O#) Open property by index | (X) Back\\n'\n )\n if user_input in ['N', 'n']:\n user_input_valid = True\n return ('property_new', collection, True)\n elif user_input in ['X', 'x']:\n user_input_valid = True\n return (None, None, False)\n elif len(user_input) > 1:\n if user_input[0] in ['O', 'o'] and user_input[1:].isdigit():\n try:\n return ('property_view', collection.properties[int(user_input[1:])], True)\n except:\n pass\n\n print('\\nInvalid input\\n\\n')\n","sub_path":"src/screens/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"521955489","text":"# Author: Federico Berlfein\n# coding: utf-8\n# This python file contains many useful functions and runs the cross-correlations after preprocessing.\n\n\n# First some imports that we'll use below\nfrom __future__ import print_function\nimport treecorr\nimport numpy as np \nimport time\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import contour as Contour\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\nfrom astropy.table import Table\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy.cosmology import z_at_value\nfrom astropy import units as u\nimport healpy as hp\nimport random\nimport os\nfrom scipy import integrate\nfrom scipy.stats import norm\nfrom joblib import Parallel, delayed, parallel_backend\nimport pickle\n\n\n\n# Global variables from setting file\nconfig_file = 'NKCorr_Settings_zerr.yaml'\nconfig = treecorr.read_config(config_file)\nMIN_SEP = config['min_sep']\nMAX_SEP = config['max_sep']\nNBINS = config['nbins']\nN_THREADS = config['n_threads']\nN_JOBS = config['n_jobs']\n\nos.environ['OMP_THREAD_LIMIT'] = str(N_THREADS) # set the maximum number of threads that can be used\n\n# In[41]:\n\n\n# function converts pixels from a healpix map into its RA,DEC centers in radians\ndef pix2ang(pix, nside, nest = False):\n angle = hp.pix2ang(nside, pix, nest)\n theta = angle[0]\n ra_rad = angle [1]\n dec_rad = (90 - theta*180/np.pi)*np.pi/180\n return ra_rad, dec_rad\n\n\n# function gets the pixel number for coordinates of ra and dec (in degrees)\ndef ang2pix (ra, dec, nside, nest = False):\n theta = 0.5*np.pi - np.deg2rad(dec)\n phi = np.deg2rad(ra)\n pix = hp.ang2pix(nside, theta, phi, nest)\n return pix\n\n\n\n# Function creates a gaussian distribution of points in ra,dec, and distance around some center\n# ra_sigma and dec_sigma is the width of the distirbution in ra, dec, and dist_sigma is the width for the distances\n# num_gal is the number of galaxies wanted in the sample.\ndef rand_gauss(ra_center, dec_center, dist_center, ra_sigma, dec_sigma, dist_sigma, num_gal): \n # make normal distirbutions of galaxies in ra, dec, and distance\n rand_ra = np.random.normal(ra_center, ra_sigma, num_gal) \n rand_dec = np.random.normal(dec_center, dec_sigma, num_gal) \n rand_dis = np.random.normal(dist_center, dist_sigma, num_gal) \n return rand_ra, rand_dec, rand_dis\n\n\n\n\n# function randomly and uniformly distributes points in ra,dec, distance\n# ra_center, dec_center, dist_center represents the center of the distirbution\n# a_sigma and dec_sigma is the width of the distirbution in ra, dec, and dist_sigma is the width for the distances\n# num_gal is the number of galaxies wanted in the sample.\ndef rand_uniform(ra_center, dec_center, dist_center, ra_sigma,dec_sigma, dist_sigma, num_gal): \n # get ranges for ra, dec, distance\n ra_min = np.min((ra_center - ra_sigma)*np.pi/180)\n ra_max = np.max((ra_center + ra_sigma)*np.pi/180)\n dec_min = np.min((dec_center - dec_sigma)*np.pi/180)\n dec_max = np.max((dec_center + dec_sigma)*np.pi/180)\n d_min = np.min(dist_center - dist_sigma)\n d_max = np.max(dist_center + dist_sigma)\n # distribute them uniformly\n rand_dis = np.random.uniform(d_min, d_max, num_gal) \n rand_ra = np.random.uniform(ra_min, ra_max, num_gal)*180/np.pi \n rand_sindec = np.random.uniform(np.sin(dec_min), np.sin(dec_max), num_gal) \n rand_dec = np.arcsin(rand_sindec)*180/np.pi #convert back to dec \n return rand_ra, rand_dec, rand_dis\n\n\n\n# function randomly and uniformly distributes points in ra,dec, distance\n# ra_center, dec_center, dist_center represents the center of the distirbution\n# deg_sigma is the width of the distirbution in ra and dec, and dist_sigma is the width of the distance distirbution\ndef rand_uniform_allsky(max_distance, num_galaxies, ra, dec):\n num_gal = num_galaxies\n ra_min = np.min((ra)*np.pi/180)\n ra_max = np.max((ra)*np.pi/180)\n dec_min = np.min((dec)*np.pi/180)\n dec_max = np.max((dec)*np.pi/180)\n d_min = 0.001\n d_max = np.max(max_distance)\n rand_dis = np.random.uniform(d_min, d_max, num_gal) \n rand_ra = np.random.uniform(ra_min, ra_max, num_gal)*180/np.pi \n rand_sindec = np.random.uniform(np.sin(dec_min), np.sin(dec_max), num_gal) \n rand_dec = np.arcsin(rand_sindec)*180/np.pi #convert back to dec \n return rand_ra, rand_dec, rand_dis\n\n# function randomly and uniformly and randomly distributes points in comoving volume. Uses formula for redshift distibution\n# in uniform comooving volume given a specific cosmology.\ndef rand_uniform_comvolume_allsky(min_z, max_z, num_galaxies, cosmo, ra, dec):\n num_gal = num_galaxies\n ra_min = np.min(ra)*np.pi/180\n ra_max = np.max(ra)*np.pi/180\n dec_min = np.min(dec)*np.pi/180\n dec_max = np.max(dec)*np.pi/180\n z_lin = np.linspace(min_z, max_z, 100000000)\n dv_dz = 4*np.pi*cosmo.differential_comoving_volume(z_lin).value\n rand_zpdf = dv_dz/(1+ z_lin)\n rand_zpdf = rand_zpdf/sum(rand_zpdf)\n rand_z = np.random.choice(z_lin, num_galaxies, p = rand_zpdf) \n rand_ra = np.random.uniform(ra_min, ra_max, num_gal)*180/np.pi \n rand_sindec = np.random.uniform(np.sin(dec_min), np.sin(dec_max), num_gal) \n rand_dec = np.arcsin(rand_sindec)*180/np.pi #convert back to dec \n return rand_ra, rand_dec, rand_z\n\n\n\n\n\n\n\n\n# Function caluclates cross correlation with GW map. NK Correlation takes two types of catalogs:\n# N Catalog (source catalog): galaxy catalog, usual ra,dec,distance coordinates\n# K Catalog (prob_catalog): GW Map, where ra,dec comes from the pixel centers, k is the spatial probability, and all points\n# have the same distance, which is the luminosity distance of the GW event.\n# Function takles in the ra,dec,distance of the \"blob\" of galaxies, as well as the min and max separations I want\n# to analyze.\ndef nk_corr(ra_corr, dec_corr, r_corr, dist_gw, prob, nk, ra_deg, dec_deg, weights = None, weights_gal = None):\n if weights_gal is not None:\n source_cat = treecorr.Catalog(ra = ra_corr, dec= dec_corr, r = (r_corr),w = weights_gal ,ra_units='deg', dec_units='deg')\n else:\n source_cat = treecorr.Catalog(ra = ra_corr, dec= dec_corr, r = (r_corr), ra_units='deg', dec_units='deg')\n if weights is not None:\n prob_cat = treecorr.Catalog(ra = ra_deg, dec=dec_deg, r = dist_gw ,k= prob, w = weights, ra_units='deg', dec_units='deg')\n else:\n prob_cat = treecorr.Catalog(ra = ra_deg, dec=dec_deg, r = dist_gw ,k= prob, ra_units='deg', dec_units='deg')\n nk.process_cross(source_cat, prob_cat, num_threads= N_THREADS) # performs correlation\n vark = treecorr.calculateVarK(prob_cat)\n return nk, vark # returns separation distance (r_nk) and correlation function\n\n\n# Given an unfinalized cross correlation, and random if given, it will finish the cross-correlation result\n# Returns the separation and value of cross-correlation, the NKObject, and the variance\ndef nk_finalize(nk, vark, rk = None):\n nk_copy = nk.copy() # not to change original file\n nk_copy.finalize(vark)\n r_nk = nk_copy.meanr # The (weighted) mean value of r for the pairs in each bin.\n xi_nk, varxi_nk = nk_copy.calculateXi(rk) # xi_nk is the value of the correlation function\n return r_nk, xi_nk, nk_copy, varxi_nk # returns separation distance (r_nk) and correlation function \n\n\n\n# functions plots correlation function and returns the maximum value of the cross correlation and at what separation it occurs\ndef plot_corr(r_nk, xi_nk, title):\n plt.scatter (r_nk, xi_nk) \n plt.ylabel(r'$\\xi$ (r)')\n plt.xlabel('r (Mpc)')\n plt.title(title)\n plt.show()\n # finds and returns where the peak in the correlation is.\n max_xi = max(xi_nk)\n max_r = r_nk[np.argmax(xi_nk)]\n print('Maximum correlation at: %.3f Mpc' %max_r)\n return max_r, max_xi\n\n\n\n# Given a type of distance (cosmo_distance = cosmo.luminosity_distance for example) and the distances it converts them to redshift\n# by interpolating values. Returns redhsift values for given distances\ndef dist2redshift(cosmo_distance, distances):\n Dvals = distances * u.Mpc\n zmin = z_at_value(cosmo_distance, Dvals.min())\n zmax = z_at_value(cosmo_distance, Dvals.max())\n zgrid = np.logspace(np.log10(zmin), np.log10(zmax), 50)\n Dgrid = cosmo_distance(zgrid)\n return np.interp(Dvals.value, Dgrid.value, zgrid)\n\n\n# Create linearly spaced distance measurements form gaussian pdf with range of 2-sigmas, and give each distance measurement\n# a weights proportional to the value of the pdf at that distance squared\ndef create_pdf_linear(value, sigma, num_copies): \n x = np.linspace((value-sigma*2),(value + sigma*2), num_copies)\n pdf = norm.pdf(x, value, sigma)\n weights = pdf**2\n return x, weights\n\n\n# Calculate the wieght of a galaxy by taking the value of that distance in the pdf corresponding to the pixel in the GW event\n# the galaxy belongs to.\ndef weightGalDist(cat_ra, cat_dec, NSIDE,nest, z, prob, m ,cosmology, gw_distances, distsigma):\n m_tot = np.arange(hp.nside2npix(NSIDE))\n prob_tot = np.array([0.0]* len(m_tot))\n gw_dist_tot = np.array([0.0]* len(m_tot))\n distsigma_tot = np.array([1.0]* len(m_tot))\n prob_tot[m] = prob\n gw_dist_tot[m] = gw_distances\n distsigma_tot[m] = distsigma\n pix_gal = ang2pix (cat_ra, cat_dec, NSIDE, nest)\n lumd_dist = cosmology.luminosity_distance(z).value\n weights = (norm.pdf(lumd_dist, gw_dist_tot[pix_gal], distsigma_tot[pix_gal]))#**2\n return weights \n\n\n# Calculates cross-correlation by transofrming redshifts from galaxies and luminosity distances from GW event into comoving \n# distance given a cosmology. It does this by cross-correlating each instance of the GW event and accumulating the counts\n# Additionally, it updates the log for that specific cosmology, printing how long it took to calculate the last cross-corr\n# how many of the 100 instances of the GW event have been done, and th expected time to finish. \n# Finally, it returns the unfinished NKObject containing the counts.\ndef cosmo_corr(cosmology, z, z_weights, lum_distances, weights, prob_map, cat_ra, cat_dec, ra_deg, dec_deg, log_outdir, m, gw_distances, distsigma, NSIDE, nest):\n weights_gal = None\n weights_gal = z_weights*weightGalDist(cat_ra, cat_dec, NSIDE, nest, z, prob_map, m ,cosmology, gw_distances, distsigma)\n dist_cat = cosmology.comoving_distance(z).value # convert redshifts from galaxies to comoving distance\n nk = treecorr.NKCorrelation(min_sep= MIN_SEP, max_sep=MAX_SEP , nbins=NBINS) # set new NKObject\n z_gw = []\n for lumd in lum_distances: # for each instance of gw event calculate redshifts\n z_gw.append(dist2redshift(cosmology.luminosity_distance, lumd))\n dist_center = cosmology.comoving_distance(np.array(z_gw)).value # convert redfshifts to comoving distance\n vark = []\n tot_time = time.time()\n for j in range(0, len(dist_center)): # loop through each instance of GW event\n start_time = time.time()\n if weights[j] is not None:\n weight = weights[j]\n else:\n weight = None\n \n source_ra = cat_ra\n source_dec = cat_dec\n source_dis = dist_cat\n # calculate cross-corr\n nk, n_vark= nk_corr(source_ra, source_dec, source_dis, dist_center[j],np.tile(prob_map,100), nk, np.tile(ra_deg,100), np.tile(dec_deg,100), weight, weights_gal)\n vark.append(n_vark)\n # update logs\n time_taken = (time.time() - start_time)\n exp_time = (time_taken * (len(dist_center) - (j+1)))\n time_taken = time.strftime('%H:%M:%S', time.gmtime(time_taken))\n exp_time = time.strftime('%H:%M:%S', time.gmtime(exp_time))\n log_file = open(log_outdir + '/log_' + str(cosmology.H(0).value),\"w\") \n log_file.write(str(j+1) + '/' + str(len(dist_center)) + ' complete\\nExpected time to finish: ' + exp_time + '\\nLast Iteration time: ' + time_taken )\n log_file.close()\n # update logs once finished\n log_file = open(log_outdir + '/log_' + str(cosmology.H(0).value),\"w\")\n tot_end = (time.time() - tot_time)\n tot_end = time.strftime('%H:%M:%S', time.gmtime(tot_end))\n log_file.write('Complete! ' + str(len(dist_center)) + '/' + str(len(dist_center)) + '\\nTime taken: ' + tot_end )\n log_file.close()\n return nk\n\n# Calculates the cross-correlation for randoms distributed unifromly and randomly in comoving volume. The random galaxy catalog\n# created has the same shape and occupies the same pixels as the galaxy catalog, as well as the same redshift range.\n# Besides this, the rest of the calculation is identical to cosmo_corr.\ndef cosmo_corr_randoms(cosmology, z, lum_distances, weights, prob_map, cat_ra, cat_dec, ra_deg, dec_deg, log_outdir, m, gw_distances, distsigma, NSIDE, nest):\n pix_gal = ang2pix (cat_ra, cat_dec, NSIDE, nest) # the pixels of the galaxy catalog\n pix_area = hp.nside2pixarea(NSIDE, degrees = True)*len(list(set(pix_gal))) # sky area of galaxy catalog\n #pix_frac = pix_area/ hp.nside2pixarea(NSIDE, degrees = True)*hp.nside2npix(NSIDE)\n max_z = np.max(z)\n min_z = np.min(z)\n #comv_volume = cosmology.comoving_volume(max_z).value*pix_frac\n #density = 1.13*10**(-14)\n #num_gal = density* comv_volume\n num_gal = len(cat_ra) # number of randoms is equal to number of galaxies in catalog\n ra_diff = np.absolute(np.max(cat_ra) - np.min(cat_ra))\n dec_diff = np.absolute(np.sin(np.deg2rad(np.max(cat_dec))) - np.sin(np.deg2rad(np.min(cat_dec))))\n # so random catalog has same number of galaxies as catalog after masking, we make more galaxies in square patch\n square_area = (180/np.pi)*ra_diff*dec_diff # calculate the square area of a patch of sky given the galaxy catalog\n num_galaxies = int(num_gal*(square_area)/pix_area) # number of galaxies to randomly distribute in square patch\n rand_ra, rand_dec, rand_z = rand_uniform_comvolume_allsky(min_z, max_z, num_galaxies, cosmology, cat_ra, cat_dec)\n #rand_ra, rand_dec, rand_z = rand_uniform_allsky(max_z, num_galaxies)\n # masking\n pix_rand = ang2pix (rand_ra, rand_dec, NSIDE, nest)\n good_pix = np.in1d(pix_rand, pix_gal)\n cat_ra = rand_ra[good_pix]\n cat_dec = rand_dec[good_pix]\n z = rand_z[good_pix]\n weights_gal = None\n weights_gal = weightGalDist(cat_ra, cat_dec, NSIDE, nest, z, prob_map, m ,cosmology, gw_distances, distsigma)\n dist_cat = cosmology.comoving_distance(z).value # convert redshifts from galaxies to comoving distance\n nk = treecorr.NKCorrelation(min_sep= MIN_SEP, max_sep=MAX_SEP , nbins=NBINS)\n z_gw = []\n for lumd in lum_distances: # for each instance of gw event calculate redshifts\n z_gw.append(dist2redshift(cosmology.luminosity_distance, lumd))\n dist_center = cosmology.comoving_distance(np.array(z_gw)).value\n vark = []\n tot_time = time.time()\n for j in range(0, len(dist_center)): # loop through each instance of GW event\n start_time = time.time()\n if weights[j] is not None:\n weight = weights[j]\n else:\n weight = None\n \n source_ra = cat_ra\n source_dec = cat_dec\n source_dis = dist_cat\n # calculate cross-corr\n nk, n_vark= nk_corr(source_ra, source_dec, source_dis, dist_center[j], np.tile(prob_map,100), nk,np.tile(ra_deg,100), np.tile(dec_deg,100), weight, weights_gal)\n vark.append(n_vark)\n # update logs\n time_taken = (time.time() - start_time)\n exp_time = (time_taken * (len(dist_center) - (j+1)))\n time_taken = time.strftime('%H:%M:%S', time.gmtime(time_taken))\n exp_time = time.strftime('%H:%M:%S', time.gmtime(exp_time))\n log_file = open(log_outdir + '/log_' + str(cosmology.H(0).value),\"w\") \n log_file.write(str(j+1) + '/' + str(len(dist_center)) + ' complete\\nExpected time to finish: ' + exp_time + '\\nLast Iteration time: ' + time_taken )\n log_file.close()\n log_file = open(log_outdir + '/log_' + str(cosmology.H(0).value),\"w\")\n tot_end = (time.time() - tot_time)\n tot_end = time.strftime('%H:%M:%S', time.gmtime(tot_end))\n log_file.write('Complete! ' + str(len(dist_center)) + '/' + str(len(dist_center)) + '\\nTime taken: ' + tot_end )\n log_file.close()\n return nk\n\n\n\ndef run(h0_values, z_pdf, z_weights_pdf, lumd_pdf, weights_pdf, cat_ra, cat_dec, gw_prob, NSIDE, outdir, outdir_all, GW_ID, gw_distances, distsigma, nest = False, m = None):\n log_outdir = os.path.join(outdir, 'logs')\n if (os.path.isdir(log_outdir) == False):\n os.mkdir(log_outdir)\n if m is None:\n m = np.arange(hp.nside2npix(NSIDE))\n ra_pix, dec_pix = pix2ang (m, NSIDE, nest) # pixel centers for a healpix map in radians\n # ra_deg and dec_deg, the pixel centers, will be associated with the probabilites for each pixel from GW\n # contour maps\n ra_deg = ra_pix*180/np.pi\n dec_deg = dec_pix*180/np.pi\n \n #run correlations\n nk_list = [treecorr.NKCorrelation(min_sep= MIN_SEP, max_sep=MAX_SEP , nbins=NBINS) for i in range (len(h0_values))]\n results = Parallel(n_jobs = N_JOBS)(delayed(cosmo_corr)(FlatLambdaCDM(H0=h0, Om0=0.286, Ob0=0.046), z_pdf, z_weights_pdf, lumd_pdf, weights_pdf, gw_prob, cat_ra, cat_dec, ra_deg, dec_deg, log_outdir, m, gw_distances, distsigma, NSIDE, nest) for h0 in h0_values) \n for j in range (len(results)):\n nk_list[j].__iadd__(results[j])\n #var_list.append(results[j].estimate_cov('jackknife'))\n pickle_out = open((outdir + GW_ID + '_NKObject' ) ,\"wb\")\n pickle.dump(nk_list, pickle_out)\n pickle_out.close()\n pickle_out_all = open((outdir_all + 'NKObjects/' + GW_ID + '_NKObject' ) ,\"wb\")\n pickle.dump(nk_list, pickle_out_all)\n pickle_out_all.close()\n \n \n \ndef run_randoms(h0_values, z_pdf, lumd_pdf, weights_pdf, cat_ra, cat_dec, gw_prob, NSIDE, outdir, outdir_all, GW_ID, gw_distances, distsigma, nest = False, m = None):\n log_outdir = os.path.join(outdir, 'logs')\n if (os.path.isdir(log_outdir) == False):\n os.mkdir(log_outdir)\n if m is None:\n m = np.arange(hp.nside2npix(NSIDE))\n ra_pix, dec_pix = pix2ang (m, NSIDE, nest) # pixel centers for a healpix map in radians\n # ra_deg and dec_deg, the pixel centers, will be associated with the probabilites for each pixel from GW\n # contour maps\n ra_deg = ra_pix*180/np.pi\n dec_deg = dec_pix*180/np.pi\n \n #run correlations\n nk_list = [treecorr.NKCorrelation(min_sep= MIN_SEP, max_sep=MAX_SEP , nbins=NBINS) for i in range (len(h0_values))]\n results = Parallel(n_jobs = N_JOBS)(delayed(cosmo_corr_randoms)(FlatLambdaCDM(H0=h0, Om0=0.286, Ob0=0.046), z_pdf, lumd_pdf, weights_pdf, gw_prob, cat_ra, cat_dec, ra_deg, dec_deg, log_outdir, m, gw_distances, distsigma, NSIDE, nest) for h0 in h0_values) \n for j in range (len(results)):\n nk_list[j].__iadd__(results[j])\n #var_list.append(results[j].estimate_cov('jackknife'))\n pickle_out = open((outdir + GW_ID + '_NKObject_Randoms' ) ,\"wb\")\n pickle.dump(nk_list, pickle_out)\n pickle_out.close()\n pickle_out_all = open((outdir_all + 'NKObjects_Randoms/' + GW_ID + '_NKObject_Randoms' ) ,\"wb\")\n pickle.dump(nk_list, pickle_out_all)\n pickle_out_all.close()\n\n\n\n\n\n# Fit a curve to a polynomial\ndef fit(x,y, num_points = 100):\n p = np.poly1d(np.polyfit(x, y, 10))\n xp = np.linspace(0, np.max(x) - 20, num_points)\n #plt.plot(x, y, '.', xp, p(xp), '--')\n return xp, p(xp)\n\n\n\n# plots cross correlation for every H_0 and and the maximum value for every H_0 \n# returns the maximum correlation value of every cosmology\ndef point_max_plot(r, xi, h0_values, plot_title):\n fig, (ax1, ax2) = plt.subplots(2, 1,figsize = (8,10))\n diff_maxi = []\n for i in range(0, len(h0_values)):\n ax1.scatter(r[i], xi[i], label = 'H_0 = %i' % h0_values[i])\n diff_maxi.append(np.max(xi[i]))\n\n ax1.set_title('NK Correlation at different H_0 Values, ' + plot_title)\n ax1.set_ylabel(r'$\\xi$ (r)')\n ax1.set_xlabel('r (Mpc)')\n #ax1.legend()\n\n ax2.plot(h0_values, diff_maxi)\n ax2.scatter(h0_values, diff_maxi)\n ax2.axvline( h0_values[np.argmax(diff_maxi)],color = 'r', linestyle = '--')\n ax2.set_xlabel('H_0 value')\n ax2.set_ylabel('Peak Amplitude')\n ax2.set_title('Peak Amplitude from NK cross correlation')\n #ax2.set_yscale('log')\n ax2.set_xticks(np.arange(np.min(h0_values), np.max(h0_values) + 2, 10))\n #fig.show()\n plt.show()\n #fig.close()\n return diff_maxi\n\n\n# plots cross correlation for every H_0 by fitting the cross-corr and and the maximum value for every H_0 \n# returns the maximum correlation value of every cosmology\ndef fit_max_plot(r, xi, h0_values, plot_title):\n fig, (ax1, ax2) = plt.subplots(2, 1,figsize = (8,10))\n diff_maxi = []\n for i in range(0, len(h0_values)):\n x, y = fit(r[i],xi[i])\n diff_maxi.append(np.max(y))\n #ax1.scatter(r_nk_tot[i], xi_nk_tot[i]*10000, label = 'H_0 = %i' % h0_values[i])\n ax1.plot(x, y, '--', label = 'H_0 = %i' % h0_values[i])\n ax1.set_title('NK Correlation at different H_0 Values, ' + plot_title)\n ax1.set_ylabel(r'$\\xi$ (r)')\n ax1.set_xlabel('r (Mpc)')\n #ax1.legend()\n\n ax2.plot(h0_values, diff_maxi)\n ax2.scatter(h0_values, diff_maxi)\n ax2.axvline( h0_values[np.argmax(diff_maxi)],color = 'r', linestyle ='--')\n ax2.set_xlabel('H_0 value')\n ax2.set_ylabel('Peak Amplitude')\n ax2.set_title('Peak Amplitude from fitted NK cross correlation')\n #ax2.set_yscale('log')\n ax2.set_xticks(np.arange(np.min(h0_values), np.max(h0_values) + 2, 10))\n #fig.show()\n plt.show()\n #fig.close()\n return diff_maxi\n\n\n# plots cross correlation for every H_0 and the integral value for every H_0 \ndef fit_integral_plot(r, xi, h0_values, plot_title):\n fig, (ax1, ax2) = plt.subplots(2, 1,figsize = (8,10))\n diff_maxi = []\n for i in range(0, len(h0_values)):\n x, y = fit(r[i],xi[i])\n #diff_maxi.append(np.trapz(y,x))\n diff_maxi.append(integrate.simps(y,x))\n ax1.plot(x, y, '--', label = 'H_0 = %i' % h0_values[i])\n ax1.set_title('NK Correlation at different H_0 Values, ' + plot_title)\n ax1.set_ylabel(r'$\\xi$ (r)')\n ax1.set_xlabel('r (Mpc)')\n #ax1.legend()\n\n ax2.plot(h0_values, diff_maxi)\n ax2.scatter(h0_values, diff_maxi)\n ax2.axvline( h0_values[np.argmax(diff_maxi)],color = 'r', linestyle = '--')\n ax2.set_xlabel('H_0 value')\n ax2.set_ylabel('Integral of fitted NK cross correlation')\n ax2.set_title('Integral of fitted NK cross correlation')\n #ax2.set_yscale('log')\n #ax2.set_ylim(20,150)\n ax2.set_xticks(np.arange(np.min(h0_values), np.max(h0_values) + 2, 10))\n #fig.show()\n plt.show()\n #fig.close()\n return diff_maxi\n\n\n \n\n# # Finding confidence region pixels. This is not my code, code is taken from Fermi GBM Data Tools, specifically \n# the gbm.data.localization module\n# Authors: William Cleveland (USRA),\n# Adam Goldstein (USRA) and\n# Daniel Kocevski (NASA)\n\n# create the mesh grid in phi and theta\ndef mesh_grid(NSIDE, num_phi, num_theta, nest):\n theta = np.linspace(np.pi, 0.0, num_theta)\n phi = np.linspace(0.0, 2 * np.pi, num_phi)\n phi_grid, theta_grid = np.meshgrid(phi, theta)\n grid_pix = hp.ang2pix(NSIDE, theta_grid, phi_grid, nest)\n return (grid_pix, phi, theta)\n\n# use greedy algortihgm to find the credible levels\ndef find_greedy_credible_levels(p):\n p = np.asarray(p)\n pflat = p.ravel()\n i = np.argsort(pflat)[::-1]\n cs = np.cumsum(pflat[i])\n cls = np.empty_like(pflat)\n cls[i] = cs\n return cls.reshape(p.shape)\n\n# find the confidence region path \ndef confidence_region_path(NSIDE, clevel, prob, nest, numpts_ra=360, numpts_dec=180):\n # create the grid and integrated probability array\n sig = 1- find_greedy_credible_levels(prob)\n grid_pix, phi, theta = mesh_grid(NSIDE,numpts_ra, numpts_dec, nest)\n sig_arr = 1.0 - sig[grid_pix]\n ra = np.rad2deg(phi)\n dec = np.rad2deg(np.pi / 2.0 - theta)\n\n # use matplotlib contour to produce a path object\n contour = Contour(ra, dec, sig_arr, [clevel])\n\n # get the contour path, which is made up of segments\n paths = contour.collections[0].get_paths()\n\n # extract all the vertices\n pts = [path.vertices for path in paths]\n\n # unfortunately matplotlib will plot this, so we need to remove\n for c in contour.collections:\n c.remove()\n plt.close()\n plt.close()\n #print(pts)\n return pts\n\ndef find_points(NSIDE, nest, pts):\n # Nside for Healpix map\n m = np.arange(hp.nside2npix(NSIDE))\n ra_pix, dec_pix = pix2ang(m, NSIDE, nest)\n ra_deg = ra_pix*180/np.pi\n dec_deg = dec_pix*180/np.pi\n healpy_points = list(zip(ra_deg, dec_deg))\n p = Path(pts) \n patch = patches.PathPatch(p, facecolor='orange')\n plt.close()\n grid = p.contains_points(healpy_points)\n return grid\n\n# find the pixels that conform the confidence region\ndef find_conf_pixels(NSIDE, nest, clevel, prob):\n pts = confidence_region_path(NSIDE, clevel, prob, nest)\n pix_cut = np.full(len(prob), False)\n for points in pts:\n is_in_region = find_points(NSIDE, nest, points)\n pix_cut = np.logical_or(pix_cut, is_in_region)\n return pix_cut","sub_path":"GWCorr_zerr/NK_Correlation_GW_multEvents_Final_zerr.py","file_name":"NK_Correlation_GW_multEvents_Final_zerr.py","file_ext":"py","file_size_in_byte":25174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"27654582","text":"import unittest\nfrom objects import *\n\nclass TestCases(unittest.TestCase):\n def test_equality_1(self):\n point1 = Point(1, -2)\n point2 = Point(1, 2)\n\n self.assertTrue(point1 != point2)\n\n def test_equality_2(self):\n point1 = Point(0.1 + 0.1 + 0.1, -0.3)\n point2 = Point(0.3, -0.1 - 0.1 - 0.1)\n\n self.assertTrue(point1 == point2)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"Lab7/Object_Equality/object_equality_tests.py","file_name":"object_equality_tests.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"604200397","text":"# 그리디 알고리즘 (거스름 돈)\n\nn = 1260 # 돈\ncount = 0 # 거스름 동전 개수\n\n# 큰 단위의 화폐부터 차례대로 확인\ncoin_types = [500, 100, 50, 10]\n\nfor coin in coin_types:\n count += n // coin\n n %= coin\n\nprint(count)\n","sub_path":"Python/chap03/3-1.py","file_name":"3-1.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"406477488","text":"message = input(\">\")\nwords = message.split(' ')\nemojis ={\n \":)\" : \"😊\",\n \":(\" : \"😒\"\n\n}\noutput = \"\"\nfor word in words:\n output += emojis.get(word,word) + \" \"\n\nprint(output)\n\ndef emoji_converter(message1):\n words = message1.split(' ')\n emojis ={\n \":)\": \"😊\",\n \":(\": \"😒\"\n }\n output = \" \"\n for word in words:\n output +=emojis.get(word,word) + \" \"\n return output\n\nmessage1 = input(\">\")\nprint(emoji_converter(message1))\n","sub_path":"Emoji.py","file_name":"Emoji.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"170841199","text":"from utils_tf2 import*\nimport numpy as np\nimport tensorflow as tf\nimport pickle\n\n'''\nThis is a program for cross testing several runs of trainings and averaging their test score\n\nsplits = 5 -----> Train/Test split = 0.80\nKfold_epochs = 4\nhidden layers = 3 (tanh, tanh, relu)\nneurons in each layer = 9 9 7\nlearning rate = 0.0002\nnumber of epochs = 200000\n'''\n\n# Specify Inputs, Outputs, Train/Test split, and Datafile (arguments of the load_dataset function)\nlist_of_inputs = [ 'permittivity', 'patch_length','patch_width','substrate_height','feed_depth','feed_gap_width','resonance']\nlist_of_outputs = ['l3horizontal']\nW = [15, 15, 15, 1]\nactivations = [\"sigmoid\", \"sigmoid\", \"sigmoid\"]\ntest_errors = []\ntrain_errors = []\nmeans_of_test_errors = []\nmeans_of_train_errors = []\nsplits = 5\ndata = \"datasets/Data_with_header.csv\"\nKfold_epochs = 4\n\nfor j in range(Kfold_epochs):\n \n # Obtain Train and Test sets inputs and outputs and normalize inputs\n sets = Kfold(splits, data)\n for i in range(splits):\n test_set = sets[\"test\" + str(i)]\n train_set = sets[\"train\" + str(i)]\n test_set_x, test_set_y = separate_dataset(test_set, list_of_inputs, list_of_outputs)\n train_set_x, train_set_y = separate_dataset(train_set, list_of_inputs, list_of_outputs)\n\n train_set_x[len(list_of_inputs)-1] = train_set_x[len(list_of_inputs)-1]/(1000000000)\n test_set_x[len(list_of_inputs)-1] = test_set_x[len(list_of_inputs)-1]/(1000000000)\n train_set_x, test_set_x = normalize_inputs(train_set_x, test_set_x)\n\n # Structure and build the NN by defining the number of layers, neurons, and activations\n\n parameters, err_train, err_test = model(train_set_x, train_set_y, test_set_x, test_set_y, W, activations, learning_rate = 0.0002, num_epochs = 200000, get_errors = True, show_plots = False)\n test_errors.append(err_test)\n train_errors.append(err_train)\n mean_test_error = sum(test_errors) / len(test_errors)\n mean_train_error = sum(train_errors) / len(train_errors)\n print(mean_test_error)\n print(mean_train_error)\n means_of_test_errors.append(mean_test_error)\n means_of_train_errors.append(mean_train_error)\n \nmean_means_of_test_errors = sum(means_of_test_errors) / len(means_of_test_errors)\nmean_means_of_train_errors = sum(means_of_train_errors) / len(means_of_train_errors)\nprint(\"Average test error for resonance on NN_dataset is:\", mean_means_of_test_errors)\nprint(\"Average test accuracy for resonance on NN_dataset is:\", 1 - mean_means_of_test_errors)\nprint(\"Average train error for resonance on NN_dataset is:\", mean_means_of_train_errors)\nprint(\"Average train accuracy for resonance on NN_dataset is:\", 1 - mean_means_of_train_errors)\n","sub_path":"NN/l3horizontal_dB_cross_testing.py","file_name":"l3horizontal_dB_cross_testing.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"219926512","text":"from vpython import *\nimport os\n\nif os.name == \"posix\":\n scene = canvas(width=950, height=1870)\nelse:\n scene = canvas(width=1500, height=690)\n\ndef tree(arr, le, re, c):\n arr2 = []\n #l = rotate(le, radians(45+ang))\n #r = rotate(re, radians(-45+ang))\n for i, ang in arr:\n pos = i.point(1)[\"pos\"]\n arr2.append([curve(pos, pos+rotate(le, radians(45+ang)), radius=0.1/(c+1)), 45+ang])\n arr2.append([curve(pos, pos+rotate(re, radians(-45+ang)), radius=0.1/(c+1)), -45+ang])\n return arr2\n\nle = vec(0, 1, 0)\nst_v = vec(0, -1, 0)\nstart = [[curve(st_v, st_v+le, radius=0.1), 0]]\nc = 1\nmax = 10\n\nwhile True:\n if c <= max:\n ev = scene.waitfor('mousedown mouseup')\n if ev.event == 'mousedown':\n le = vec(0, 1/c, 0)\n re = vec(0, 1/c, 0)\n start = tree(start, le, re, c)\n c += 1\n\n\n'''# Importing the python libraries \nimport pygame, math \n \n# Initialize all imported pygame modules \npygame.init() \n \n# Create a new surface and window. \nsurface_height, surface_width = 800, 600 #Surface variables \nmain_surface = pygame.display.set_mode((surface_height,surface_width)) \n \n# Captioning the window \npygame.display.set_caption(\"Fractal_Tree_geeksforgeeks\") \n \ndef draw_tree(order, theta, sz, posn, heading, color=(0,0,0), depth=0): \n \n # The relative ratio of the trunk to the whole tree \n trunk_ratio = 0.29 \n \n # Length of the trunk \n trunk = sz * trunk_ratio \n delta_x = trunk * math.cos(heading) \n delta_y = trunk * math.sin(heading) \n (u, v) = posn \n newpos = (u + delta_x, v + delta_y) \n pygame.draw.line(main_surface, color, posn, newpos) \n \n if order > 0: # Draw another layer of subtrees \n \n # These next six lines are a simple hack to make \n # the two major halves of the recursion different \n # colors. Fiddle here to change colors at other \n # depths, or when depth is even, or odd, etc. \n if depth == 0: \n color1 = (255, 0, 0) \n color2 = (0, 0, 255) \n else: \n color1 = color \n color2 = color \n \n # make the recursive calls to draw the two subtrees \n newsz = sz*(1 - trunk_ratio) \n draw_tree(order-1, theta, newsz, newpos, heading-theta, color1, depth+1) \n draw_tree(order-1, theta, newsz, newpos, heading+theta, color2, depth+1) \n \n \ndef main(): \n theta = 0.5\n \n while True: \n \n # Update the angle \n #theta += 0.01\n \n # This little part lets us draw the stuffs \n # in the screen everything \n main_surface.fill((255, 255, 0)) \n draw_tree(9, theta, surface_height*0.7, (surface_width//2, surface_width), -math.pi/2) \n pygame.display.flip() \n \n# Calling the main function \nmain() \npygame.quit() '''","sub_path":"fractal.py","file_name":"fractal.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"433079282","text":"\n\n#calss header\nclass _SEEMINGLY():\n\tdef __init__(self,): \n\t\tself.name = \"SEEMINGLY\"\n\t\tself.definitions = [u'appearing to be something, especially when this is not true: ', u'according to the facts that you know: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adverbs'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adverbs/_seemingly.py","file_name":"_seemingly.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"129340064","text":"import shlex\n\nfrom unittest import TestCase, mock\n\nfrom compose_flow import utils\nfrom compose_flow.commands import Workflow\n\nfrom tests import BaseTestCase\n\nTEST_PROJECT_NAME = 'test_project_name'\n\n\n@mock.patch('compose_flow.commands.subcommands.env.utils')\n@mock.patch('compose_flow.commands.subcommands.env.docker')\nclass WorkflowTestCase(BaseTestCase):\n def _setup_docker_config_mock(self, *mocks):\n docker_mock = mocks[-2]\n docker_mock.get_config.return_value = f\"FOO=1\\nBAR=2\"\n\n def _setup_utils_mock(self, *mocks):\n utils_mock = mocks[-1]\n utils_mock.get_tag_version.return_value = '0.0.0'\n utils_mock.render.side_effect = lambda x, **kwargs: x\n\n def test_default_env_when_no_env_specified(self, *mocks):\n self._setup_docker_config_mock(*mocks)\n self._setup_utils_mock(*mocks)\n\n command = shlex.split('env cat')\n workflow = Workflow(argv=command)\n\n env = workflow.environment\n\n self.assertEqual(\n ['CF_ENV', 'CF_ENV_NAME', 'CF_PROJECT'], sorted(env.data.keys())\n )\n\n def test_load_env_when_env_specified(self, *mocks):\n self._setup_docker_config_mock(*mocks)\n self._setup_utils_mock(*mocks)\n\n command = shlex.split('-e dev env cat')\n workflow = Workflow(argv=command)\n\n env = workflow.environment\n\n self.assertEqual(\n ['BAR', 'CF_ENV', 'CF_ENV_NAME', 'CF_PROJECT', 'FOO'],\n sorted(env.data.keys()),\n )\n self.assertEqual('1', env.data['FOO'])\n self.assertEqual('2', env.data['BAR'])\n\n @mock.patch(\n 'compose_flow.commands.workflow.Workflow.subcommand',\n new_callable=mock.PropertyMock,\n )\n def test_setup_environment_flag(self, *mocks):\n \"\"\"\n Ensures the environment cache is set to an empty dictionary when\n a workflow environment should not be setup\n \"\"\"\n subcommand_mock = mocks[0]\n subcommand_mock.return_value.setup_environment = False\n\n command = shlex.split('-e dev env cat')\n workflow = Workflow(argv=command)\n\n workflow._setup_environment()\n\n self.assertEqual({}, workflow.environment._data)\n\n @mock.patch('compose_flow.commands.workflow.print')\n @mock.patch('compose_flow.commands.workflow.pkg_resources')\n def test_version(self, *mocks):\n \"\"\"\n Ensure the --version arg just returns the version\n \"\"\"\n version = '0.0.0-test'\n\n pkg_resources_mock = mocks[0]\n pkg_resources_mock.require.return_value = [mock.Mock(version=version)]\n\n command = shlex.split('--version')\n workflow = Workflow(argv=command)\n\n workflow.run()\n\n print_mock = mocks[1]\n print_mock.assert_called_with(version)\n\n\n@mock.patch('compose_flow.commands.workflow.PROJECT_NAME', new=TEST_PROJECT_NAME)\nclass WorkflowArgsTestCase(TestCase):\n \"\"\"\n Tests for parsing command line arguments\n \"\"\"\n\n def test_sensible_defaults_no_env(self, *mocks):\n \"\"\"\n Test sensible defaults when no environment is defined\n \"\"\"\n command = shlex.split('publish')\n workflow = Workflow(argv=command)\n\n self.assertEqual(None, workflow.args.environment)\n self.assertEqual(None, workflow.args.remote)\n self.assertEqual(TEST_PROJECT_NAME, workflow.args.config_name)\n self.assertEqual(TEST_PROJECT_NAME, workflow.args.project_name)\n\n def test_sensible_defaults_with_env(self, *mocks):\n \"\"\"\n Test sensible defaults when an environment is defined\n \"\"\"\n env = 'dev'\n command = shlex.split(f'-e {env} publish')\n workflow = Workflow(argv=command)\n\n self.assertEqual(env, workflow.args.environment)\n self.assertEqual(env, workflow.args.remote)\n self.assertEqual(f'{env}-{TEST_PROJECT_NAME}', workflow.args.config_name)\n self.assertEqual(TEST_PROJECT_NAME, workflow.args.project_name)\n\n def test_sensible_defaults_with_env_and_project(self, *mocks):\n \"\"\"\n Test sensible defaults when an environment and project name is defined\n \"\"\"\n env = 'dev'\n command = shlex.split(f'-e {env} --project-name foo publish')\n workflow = Workflow(argv=command)\n\n self.assertEqual(env, workflow.args.environment)\n self.assertEqual(env, workflow.args.remote)\n self.assertEqual(f'{env}-foo', workflow.args.config_name)\n self.assertEqual('foo', workflow.args.project_name)\n","sub_path":"src/tests/test_workflow.py","file_name":"test_workflow.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"638888376","text":"import json\nimport datetime\n\nfrom django.template.loader import render_to_string\n\nfrom django.core.mail import send_mail\nfrom django.conf import settings\nfrom django.contrib import messages\n\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404\n\nfrom .models import *\nfrom .filter import *\n\n\n# Create your views here.\ndef Home(request):\n newProduct = Product.objects.order_by('dateAdded')[0:6]\n topSelling = Product.objects.order_by('-quantitySelled')[0:6]\n (cart, cart_product) = Same(request)\n context = {\n 'newProduct': newProduct,\n 'topSelling': topSelling,\n 'cart': cart,\n 'cart_product': cart_product,\n }\n return render(request, 'Shop/Home.html', context)\n\n\ndef updateItem(request):\n data = json.loads(request.body)\n productId = data['productId']\n action = data['action']\n quantity = data['quantity']\n print(\"quantity\", quantity)\n customer = request.user.customer\n product = Product.objects.get(id=productId)\n cart, created = Cart.objects.get_or_create(customer=customer)\n cart_product, created = Cart_Product.objects.get_or_create(cart=cart, product=product)\n if action == 'add' and product.quantity >= int(quantity):\n cart_product.quantity = (cart_product.quantity + int(quantity))\n if cart_product.quantity > product.quantity:\n cart_product.quantity = product.quantity\n cart_product.save()\n\n elif action == 'remove':\n cart_product.delete()\n\n return JsonResponse(\"cart is updated\", safe=False)\n\n\ndef Same(request):\n if request.user.is_authenticated:\n customer, created = Customer.objects.get_or_create(user=request.user)\n cart, created = Cart.objects.get_or_create(customer=customer)\n cart_product = cart.cart_product_set.all()\n\n else:\n cart_product = []\n cart = {'get_total_product': 0, 'get_total_price_product': 0}\n\n return (cart, cart_product)\n\n\ndef Store(request):\n Allproducts = Product.objects.all()\n\n myfilter = productFilter(request.GET, queryset=Allproducts)\n Allproducts = myfilter.qs\n\n search = request.POST.get('myInput')\n if request.method == \"POST\" and search is not None:\n Allproducts = Product.objects.filter(name__icontains=search)\n\n if request.method == 'GET' and request.is_ajax():\n data = {}\n myfilter = productFilter(request.GET, queryset=Allproducts.values())\n Allproduct = list(myfilter.qs)\n data['products'] = json.dumps(Allproduct, default=myconverter)\n return JsonResponse(data, status=200)\n\n paginator = Paginator(Allproducts, 8)\n pagenum = request.GET.get('page', 1)\n numPage = paginator.num_pages ### get number of page\n (cart, cart_product) = Same(request)\n\n try:\n products = paginator.page(pagenum)\n except (EmptyPage, InvalidPage, ValueError):\n products = paginator.page(1)\n context = {\n 'products': products,\n 'numPage': range(1, numPage + 1),\n 'cart': cart,\n 'cart_product': cart_product,\n 'myfilter': myfilter,\n 'search': search,\n }\n return render(request, 'Shop/Store.html', context)\n\n\ndef myconverter(obj):\n if isinstance(obj, (datetime.date, datetime.datetime)):\n return obj.isoformat()\n\n\ndef product(request, id):\n productid = get_object_or_404(Product, pk=id)\n productRelate = Product.objects.filter(brand=productid.brand)[0:4]\n (cart, cart_product) = Same(request)\n images = Images.objects.filter(product_id=id)\n context = {\n 'product': productid,\n 'productRelate': productRelate,\n 'images': images,\n 'cart': cart,\n 'cart_product': cart_product,\n }\n return render(request, 'Shop/product.html', context)\n\n\ndef aboutUs(request):\n (cart, cart_product) = Same(request)\n return render(request, 'Shop/aboutUS.html', {'cart': cart, 'cart_product': cart_product})\n\n\n# def contact(request):\n# return render(request, 'Shop/contact.html')\n\ndef contact(request):\n (cart, cart_product) = Same(request)\n if request.method == 'POST':\n subject = 'Subject here',\n message = 'Here is the message.',\n email_from = settings.EMAIL_HOST_USER,\n recipient_list = [request.POST.get('email_receive')],\n email_template_name = \"Shop/mailContact.txt\",\n email = render_to_string(email_template_name)\n send_mail(\n 'Thông tin khuyến mãi',\n email,\n settings.EMAIL_HOST_USER,\n recipient_list[0],\n )\n messages.success(request, \"Email của bạn đã được gửi thông tin\"),\n else:\n messages.warning(request, \"Mời nhập email\")\n return render(request, 'Shop/contact.html', {'cart': cart, 'cart_product': cart_product})\n\n\ndef privacypolicy(request):\n (cart, cart_product) = Same(request)\n return render(request, 'Shop/privacypolicy.html', {'cart': cart, 'cart_product': cart_product})\n\n\ndef ordersandreturns(request):\n (cart, cart_product) = Same(request)\n return render(request, 'Shop/ordersandreturns.html', {'cart': cart, 'cart_product': cart_product})\n\n\ndef termandconditions(request):\n (cart, cart_product) = Same(request)\n return render(request, 'Shop/termsandconditions.html', {'cart': cart, 'cart_product': cart_product})\n\n\ndef help(request):\n (cart, cart_product) = Same(request)\n return render(request, 'Shop/help.html', {'cart': cart, 'cart_product': cart_product})\n","sub_path":"Shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"648318418","text":"import os\nimport pandas as pd\nimport pickle\nfrom collections import defaultdict\nfrom tqdm import tqdm\n\nfrom utils.preprocessing import json_to_list,clean_text\nfrom utils.mkdir_p import mkdir_p\n\ndef parse_arguments():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('input_dir',type=str)\n parser.add_argument('output_dir',type=str)\n parser.add_argument('--df_name',type=str,default='val_sequence.csv')\n parser.add_argument('--train_df_path',type=str,default='storage/input/kaggle_dataset/train.csv')\n parser.add_argument('--data_unique_map_path',type=str,default='storage/input/rcdataset/data_sets_unique_map.p')\n return parser.parse_args()\n\nif __name__ == \"__main__\":\n \n args = parse_arguments()\n\n fnames = os.listdir(os.path.join(args.input_dir,\"test/\"))\n\n dataset_unique_map_path = args.data_unique_map_path\n dataset_unique_map = pickle.load(open(dataset_unique_map_path,\"rb\"))\n \n train_df = pd.read_csv(args.train_df_path)\n train_dataset_names = train_df.dataset_label.unique().tolist()\n\n out_dict = defaultdict(list)\n for fname in tqdm(fnames):\n fid = fname.replace(\".json\",\"\")\n contents = json_to_list(fid)\n text = \" \".join(contents)\n cleaned_text = clean_text(text)\n out_dict[\"id\"].append(fid)\n clean_val_datasets = []\n val_datasets = []\n for d,info in dataset_unique_map.items():\n if d in text:\n if any([td in d for td in train_dataset_names]): continue\n val_datasets.append(d)\n #clean_val_datasets.append(info['unique_dataset_name'])\n #text = text.replace(d,info['unique_dataset_name'])\n cleaned_d = clean_text(d)\n if cleaned_d in cleaned_text:\n clean_val_datasets.append(cleaned_d)\n out_dict[\"external_dataset\"].append(\"|\".join(list(set(clean_val_datasets))))\n out_dict[\"orig_external_dataset\"].append(\"|\".join(list(set(val_datasets))))\n out_dict[\"train_dataset\"].append(\"|\".join([clean_text(d) for d in train_dataset_names if d in cleaned_text]))\n out_dict[\"text\"].append(cleaned_text)\n\n mkdir_p(args.output_dir)\n out_df = pd.DataFrame(out_dict)\n out_df.to_csv(os.path.join(args.output_dir,args.df_name),index=False)\n","sub_path":"preprocessing/make_val_df.py","file_name":"make_val_df.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237903159","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('multigtfs', '0005_auto_20180502_1534'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='HistoricalNewRoute',\n fields=[\n ('id', models.IntegerField(verbose_name='ID', db_index=True, auto_created=True, blank=True)),\n ('is_approved', models.BooleanField(default=False)),\n ('latitude', models.CharField(help_text='WGS 84 latitude of stop or station', max_length=255, null=True, blank=True)),\n ('longitude', models.CharField(help_text='WGS 84 latitude of stop or station', max_length=255, null=True, blank=True)),\n ('time', models.CharField(help_text='What time did the ride arrive?', max_length=255, null=True, blank=True)),\n ('history_id', models.AutoField(serialize=False, primary_key=True)),\n ('history_date', models.DateTimeField()),\n ('history_type', models.CharField(max_length=1, choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')])),\n ('history_user', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, null=True)),\n ('ride', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.DO_NOTHING, db_constraint=False, blank=True, to='multigtfs.Ride', null=True)),\n ],\n options={\n 'ordering': ('-history_date', '-history_id'),\n 'get_latest_by': 'history_date',\n 'verbose_name': 'historical new route',\n },\n ),\n migrations.CreateModel(\n name='NewRoute',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('is_approved', models.BooleanField(default=False)),\n ('latitude', models.CharField(help_text='WGS 84 latitude of stop or station', max_length=255, null=True, blank=True)),\n ('longitude', models.CharField(help_text='WGS 84 latitude of stop or station', max_length=255, null=True, blank=True)),\n ('time', models.CharField(help_text='What time did the ride arrive?', max_length=255, null=True, blank=True)),\n ('ride', models.ForeignKey(to='multigtfs.Ride')),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n","sub_path":"gtfsserver/multigtfs/migrations/0006_historicalnewroute_newroute.py","file_name":"0006_historicalnewroute_newroute.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"87206475","text":"import matplotlib.pyplot as plt\r\nimport math\r\nimport copy\r\nimport os\r\nimport numpy as np \r\nfrom part5 import get_I_and_V\r\nimport itertools\r\nmarker = itertools.cycle(( '+', '.'))\r\nclass plot_all_I_and_V:\r\n \"\"\"This class plots the data from a given folder path when the file_numbers are specified. \r\n batch is the sample batch. This class uses 'part5' which uses 'part1' and 'part3'.\"\"\"\r\n\r\n def __init__(self):\r\n self.no_a = ''\r\n self.numbers = []\r\n\r\n def plot_all_I_V(self, folder_path, file_numbers, batch):\r\n #Gets I and V from a file and plots it with errors.\r\n for self.no_a in file_numbers:\r\n self.numbers.append((self.no_a))\r\n axis = plt.subplot()\r\n\r\n for number2 in self.numbers:\r\n # b depends on how files are labelled.\r\n b = batch + str(number2)\r\n a = get_I_and_V()\r\n y = a.get_I(folder_path, b)\r\n x = a.get_V(folder_path, b) \r\n z = a.get_I_stand_dev(folder_path, b)\r\n axis.errorbar(x, y, yerr=z, capsize = 5, fmt = next(marker), color =np.random.rand(3,), label= b)\r\n\r\n axis.set_xlabel('Voltage (V)', fontsize=14)\r\n axis.set_ylabel('Current $(uA)$', fontsize=14)\r\n axis.legend(bbox_to_anchor=(1, 0.5))\r\n plt.suptitle(batch)\r\n plt.savefig(folder_path +'\\\\'+'IV'+ '_'+ batch + ''.join(\"_\" + str(e) for e in file_numbers) , bbox_inches='tight', dpi=1200)\r\n plt.show()\r\n \r\n\r\n\r\n ","sub_path":"IV plot/part7.py","file_name":"part7.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400110944","text":"#!/usr/bin/env python\n\nimport glob\nfrom Bio import SeqIO\nfrom Bio.SeqFeature import FeatureLocation\nfrom Bio.Alphabet import *\nfrom Bio.SeqRecord import *\nfrom Bio.Alphabet.IUPAC import IUPACAmbiguousDNA;\nfrom Bio.Seq import *\nfrom Bio.SeqUtils import *\nfrom ete3 import NCBITaxa\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport argparse\nimport sys\nimport os, errno\n\n\n\nparser = argparse.ArgumentParser(description='Extract closed genes for a query taxa. Script was writen by C. Pouchon (2020).')\nparser.add_argument(\"-in\",\"--infile\", help=\"input reference DB (fasta format)\",\n type=str)\nparser.add_argument(\"-g\",\"--geneslist\", help=\"list of genes to extract\",\n type=str)\nparser.add_argument(\"-q\",\"--query\", help=\"taxa name or taxid if --taxid mode\",\n type=str)\nparser.add_argument(\"-o\",\"--outdir\", help=\"out directory path\",\n type=str)\nparser.add_argument(\"-m\",\"--mode\", help=\"extraction mode\",\n type=str,choices=[\"taxonomy\", \"distance\"])\nparser.add_argument(\"--taxid\", help=\"query is given by taxid (else it from it's name)\",\n action=\"store_true\")\nparser.add_argument(\"--update\", help=\"update NCBI taxonomy\",\n action=\"store_true\")\nparser.add_argument(\"-d\",\"--distance\", help=\"phylogenetic distance matrix file of genus\",\n type=str)\nparser.add_argument(\"-s\",\"--seeds\", help=\"sequence seeds\",\n type=str)\nparser.add_argument(\"--gene_type\", help=\"type of genes to extract\",\n type=str,choices=[\"CDS\", \"rRNA\",\"tRNA\"])\nparser.add_argument(\"--compartment\", help=\"cellular compartment\",\n type=str,choices=[\"chloroplast\", \"mitochondrion\",\"nucrdna\",\"nucleus\"])\n\nif len(sys.argv)==1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n\nargs = parser.parse_args()\n\n\ndef mkdir(path, overwrite=False):\n '''\n function to create a directory for output fasta\n '''\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST:\n if not overwrite:\n print (\"path '%s' already exists\" % path) # overwrite == False and we've hit a directory that exists\n else: raise\n\nclass ProgressBar:\n\t'''\n\tProgress bar\n\t'''\n\tdef __init__ (self, valmax, maxbar, title):\n\t\tif valmax == 0: valmax = 1\n\t\tif maxbar > 200: maxbar = 200\n\t\tself.valmax = valmax\n\t\tself.maxbar = maxbar\n\t\tself.title = title\n\tdef update(self, val):\n\t\timport sys\n\t\tperc = round((float(val) / float(self.valmax)) * 100)\n\t\tscale = 100.0 / float(self.maxbar)\n\t\tbar = int(perc / scale)\n\t\tout = '\\r %20s [%s%s] %3d %% ' % (self.title, '.' * bar, ' ' * (self.maxbar - bar), perc)\n\t\tsys.stdout.write(out)\n\t\tsys.stdout.flush()\n\nref_seeds=args.seeds\nmodel=args.mode\ntypeg = args.gene_type\noutpath=args.outdir\nquery_name = args.query\nmol=args.compartment\ninput_list_genes = args.geneslist\ninput_file = args.infile\n\n# #\n# mol=\"chloroplast\"\n# #query_name = \"Androsace_pubescens_229451_PHA000540_AXZ_B\"\n# outpath=\"./\"\n# typeg = \"CDS\"\n# input_file = \"chl_CDS_unaligned.fa\"\n# input_list_genes = \"/Users/pouchonc/Desktop/Scripts/OrthoSkim/ressources/listGenes.chloro\"\n# ref_seeds=\"/Users/pouchonc/Desktop/Scripts/OrthoSkim/ressources/chloroCDS.seeds\"\n# model = \"distance\"\n# # /Users/pouchonc/Desktop/Scripts/OrthoSkim/ressources/FlorAlp_Genus_matrix.csv\n\nif model==\"taxonomy\":\n res = [int(i) for i in query_name.split(\"_\") if i.isdigit()]\n query=res[0]\nelif model==\"distance\":\n res=query_name.split(\"_\")[0]\n if res[0].isupper():\n query=res\n else:\n query=res.capitalize()\n\nif model==\"taxonomy\":\n ncbi = NCBITaxa()\n if args.update:\n ncbi.update_taxonomy_database()\nelse:\n df = pd.read_csv(args.distance,sep=\",\", index_col=[0])\n genera = [col for col in df.columns]\n if query not in genera:\n model=\"taxonomy\"\n res = [int(i) for i in query_name.split(\"_\") if i.isdigit()]\n query=res[0]\n ncbi = NCBITaxa()\n if args.update:\n ncbi.update_taxonomy_database()\n else:\n pass\n\nfname = \"closed_\"+str(mol)+\"_\"+str(typeg)+\".fa\"\nopen(os.path.join(outpath, fname), 'w').close()\n\n\nwith open(input_list_genes) as f:\n genes = f.readlines()\ntypes=[]\nfor g in genes:\n g_tab = g.rstrip().split('\\t')\n types.append(g_tab[0])\n\n\nseeds_seq={}\n# store seeds sequences\nseeds_genome = SeqIO.parse(ref_seeds, \"fasta\")\nfor record in seeds_genome:\n seqID=record.id\n sequence=record.seq\n genename=seqID.split(\"_\")[0]\n tax_id=seqID.split(\"_\")[1]\n species=\"_\".join(seqID.split(\"_\")[2:len(seqID.split(\"_\"))])\n genus=seqID.split(\"_\")[2:len(seqID.split(\"_\"))][0]\n tokeep={}\n tokeep['seq']=sequence\n tokeep['id']=str(tax_id)+\"_\"+str(species)\n if genename not in seeds_seq.keys():\n seeds_seq[genename]=dict()\n if tax_id not in seeds_seq[genename].keys():\n seeds_seq[genename][tax_id]=[]\n seeds_seq[genename][tax_id].append(tokeep)\n else:\n seeds_seq[genename][tax_id].append(tokeep)\n else:\n if tax_id not in seeds_seq[genename].keys():\n seeds_seq[genename][tax_id]=[]\n seeds_seq[genename][tax_id].append(tokeep)\n else:\n seeds_seq[genename][tax_id].append(tokeep)\n\n# we need to check if we used the taxonomy that the query taxid is in the ncbi taxonomy database\nif model==\"taxonomy\":\n if len(ncbi.get_taxid_translator([int(query)]))==0:\n for g in genes:\n g_tab = g.rstrip().split('\\t')\n gene_id=g_tab[1]\n gene_type=g_tab[0]\n if gene_type == typeg:\n out_header=\">\"+str(gene_id)+\"_\"+str(seeds_seq[gene_id][list(seeds_seq[gene_id].keys())[0]][0]['id'])\n out_seq=str(seeds_seq[gene_id][list(seeds_seq[gene_id].keys())[0]][0]['seq'])\n if os.path.isfile(os.path.join(outpath, fname)):\n with open(os.path.join(outpath, fname), 'a+') as file:\n old_headers = []\n end_file=file.tell()\n file.seek(0)\n for line in file:\n if line.startswith(\">\"):\n old_headers.append(line.rstrip())\n if not out_header in old_headers:\n file.seek(end_file)\n file.write(out_header+'\\n')\n file.write(str(out_seq)+'\\n')\n else:\n pass\n else :\n with open(os.path.join(outpath, fname), 'a') as out:\n out.write(out_header+'\\n')\n out.write(str(out_seq)+'\\n')\n os._exit(0)\n else:\n pass\n\nmkdir(outpath)\n\nstored={}\n\n'we store all sequences'\ncur_genome = SeqIO.parse(input_file, \"fasta\")\nfor record in cur_genome:\n seqID=record.id\n sequence=record.seq\n genename=seqID.split(\"_\")[0]\n\n tax_id=seqID.split(\"_\")[1]\n species=\"_\".join(seqID.split(\"_\")[2:len(seqID.split(\"_\"))])\n genus=seqID.split(\"_\")[2:len(seqID.split(\"_\"))][0]\n\n tokeep={}\n tokeep['seq']=sequence\n tokeep['id']=str(tax_id)+\"_\"+str(species)\n\n if tax_id==\"NA\":\n continue\n else:\n\n if model==\"taxonomy\":\n if genename not in stored.keys():\n stored[genename]=dict()\n if tax_id not in stored[genename].keys():\n stored[genename][tax_id]=[]\n stored[genename][tax_id].append(tokeep)\n else:\n stored[genename][tax_id].append(tokeep)\n else:\n if tax_id not in stored[genename].keys():\n stored[genename][tax_id]=[]\n stored[genename][tax_id].append(tokeep)\n else:\n stored[genename][tax_id].append(tokeep)\n\n elif model==\"distance\":\n if genename not in stored.keys():\n stored[genename]=dict()\n if genus not in stored[genename].keys():\n stored[genename][genus]=[]\n stored[genename][genus].append(tokeep)\n else:\n stored[genename][genus].append(tokeep)\n else:\n if genus not in stored[genename].keys():\n stored[genename][genus]=[]\n stored[genename][genus].append(tokeep)\n else:\n stored[genename][genus].append(tokeep)\n\n\"we search the closed ref for each gene\"\nfor g in genes:\n g_tab = g.rstrip().split('\\t')\n gene_id=g_tab[1]\n gene_type=g_tab[0]\n\n if gene_type == typeg:\n if model==\"taxonomy\":\n taxid_list=[]\n if str(query) in stored[gene_id].keys():\n closed_taxa = [str(query)]\n sub_best=list()\n sub_name=list()\n for taxa in closed_taxa:\n sub_lmax=list()\n for subtaxa in stored[gene_id][taxa]:\n sub_lmax.append(len(subtaxa['seq']))\n sub_orderindx=sorted(range(len(sub_lmax)), key=lambda k: sub_lmax[k])\n sub_orderindx.reverse()\n sub_best.append(stored[gene_id][taxa][sub_orderindx[0]])\n\n lmax=list()\n for seq in sub_best:\n lmax.append(len(seq['seq']))\n orderindx=sorted(range(len(lmax)), key=lambda k: lmax[k])\n orderindx.reverse()\n\n out_header=\">\"+str(gene_id)+\"_\"+str(sub_best[orderindx[0]]['id'])\n out_seq=str(sub_best[orderindx[0]]['seq'])\n\n if os.path.isfile(os.path.join(outpath, fname)):\n with open(os.path.join(outpath, fname), 'a+') as file:\n old_headers = []\n end_file=file.tell()\n file.seek(0)\n for line in file:\n if line.startswith(\">\"):\n old_headers.append(line.rstrip())\n if not out_header in old_headers:\n file.seek(end_file)\n file.write(out_header+'\\n')\n file.write(str(out_seq)+'\\n')\n else:\n pass\n else :\n with open(os.path.join(outpath, fname), 'a') as out:\n out.write(out_header+'\\n')\n out.write(str(out_seq)+'\\n')\n else:\n for i in stored[gene_id].keys():\n if len(ncbi.get_taxid_translator([int(i)]))==0:\n continue\n else:\n taxid_list.append(int(i))\n\n if len(taxid_list)==0:\n out_header=\">\"+str(gene_id)+\"_\"+str(seeds_seq[gene_id][list(seeds_seq[gene_id].keys())[0]][0]['id'])\n out_seq=str(seeds_seq[gene_id][list(seeds_seq[gene_id].keys())[0]][0]['seq'])\n if os.path.isfile(os.path.join(outpath, fname)):\n with open(os.path.join(outpath, fname), 'a+') as file:\n old_headers = []\n end_file=file.tell()\n file.seek(0)\n for line in file:\n if line.startswith(\">\"):\n old_headers.append(line.rstrip())\n if not out_header in old_headers:\n file.seek(end_file)\n file.write(out_header+'\\n')\n file.write(str(out_seq)+'\\n')\n else:\n pass\n else :\n with open(os.path.join(outpath, fname), 'a') as out:\n out.write(out_header+'\\n')\n out.write(str(out_seq)+'\\n')\n continue\n else:\n taxid_all=taxid_list\n if query in taxid_all:\n # a sequence of the same taxid is already present, we keep the query taxid\n closed_taxa = [str(query)]\n else:\n # we infer the taxonomy tree with the ref and the query taxid\n taxid_all.append(query)\n tree = ncbi.get_topology(taxid_all)\n t2=tree.search_nodes(name=str(query))[0].up\n closed_taxa = []\n for l in t2.get_leaves():\n if l.__dict__['taxid'] in taxid_all:\n closed_taxa.append(str(l.__dict__['taxid']))\n else:\n continue\n if str(query) in closed_taxa:\n closed_taxa.remove(str(query))\n else:\n pass\n else:\n subdf = df.sort_values(by=query)[query]\n genera_list = [str(i) for i in stored[gene_id].keys()]\n part = 0\n range_list = list()\n closed_list = list()\n for taxa in range(len(subdf.index)):\n if subdf.index[taxa] in genera_list:\n # we create list for taxa that are at the same phylogenetic distance from the query\n score=subdf[taxa]\n if len(range_list)>0:\n if score in range_list[part]:\n closed_list[part].extend([subdf.index[taxa]])\n else:\n range_list.append([score])\n closed_list.append([subdf.index[taxa]])\n part = part+1\n else:\n range_list.append([score])\n closed_list.append([subdf.index[taxa]])\n closed_taxa=closed_list[0]\n\n sub_best=list()\n sub_name=list()\n\n for taxa in closed_taxa:\n sub_lmax=list()\n for subtaxa in stored[gene_id][taxa]:\n sub_lmax.append(len(subtaxa['seq']))\n sub_orderindx=sorted(range(len(sub_lmax)), key=lambda k: sub_lmax[k])\n sub_orderindx.reverse()\n sub_best.append(stored[gene_id][taxa][sub_orderindx[0]])\n #sub_name.append(taxa)\n\n lmax=list()\n for seq in sub_best:\n lmax.append(len(seq['seq']))\n orderindx=sorted(range(len(lmax)), key=lambda k: lmax[k])\n orderindx.reverse()\n\n out_header=\">\"+str(gene_id)+\"_\"+str(sub_best[orderindx[0]]['id'])\n out_seq=str(sub_best[orderindx[0]]['seq'])\n\n if os.path.isfile(os.path.join(outpath, fname)):\n with open(os.path.join(outpath, fname), 'a+') as file:\n old_headers = []\n end_file=file.tell()\n file.seek(0)\n for line in file:\n if line.startswith(\">\"):\n old_headers.append(line.rstrip())\n if not out_header in old_headers:\n file.seek(end_file)\n file.write(out_header+'\\n')\n file.write(str(out_seq)+'\\n')\n else:\n pass\n else :\n with open(os.path.join(outpath, fname), 'a') as out:\n out.write(out_header+'\\n')\n out.write(str(out_seq)+'\\n')\n","sub_path":"src/ExtractRef_name.py","file_name":"ExtractRef_name.py","file_ext":"py","file_size_in_byte":15663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"196925095","text":"#!/usr/bin/env python\n\"\"\"\nWordAPI.py\nCopyright 2014 Wordnik, 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\nNOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.\n\"\"\"\nimport sys\nimport os\n\nfrom models import *\n\n\nclass QuoteApi(object):\n\n def __init__(self, apiClient):\n self.apiClient = apiClient\n\n \n\n def getBucketed(self, **kwargs):\n \"\"\"Get previous quotes in time buckets.\n\n Args:\n symbol, str: Instrument symbol. Send a series (e.g. XBT) to get data for the nearest contract in that series. (optional)\n\n filter, object: Generic table filter. Send JSON key/value pairs, such as {"key": "value"}. (optional)\n\n columns, list[str]: Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. (optional)\n\n start, float: Starting point for results. (optional)\n\n reverse, bool: If true, will sort results newest first. (optional)\n\n startTime, datetime: Starting date filter for results. (optional)\n\n endTime, datetime: Ending date filter for results. (optional)\n\n binSize, str: Time interval to bucket by. Available options: ['30s', '1m', '5m', '1h', '1d']. (optional)\n\n count, float: Number of results to fetch. (optional)\n\n \n\n Returns: Array[Quote]\n \"\"\"\n\n allParams = ['symbol', 'filter', 'columns', 'start', 'reverse', 'startTime', 'endTime', 'binSize', 'count']\n\n params = locals()\n for (key, val) in params['kwargs'].iteritems():\n if key not in allParams:\n raise TypeError(\"Got an unexpected keyword argument '%s' to method getBucketed\" % key)\n params[key] = val\n del params['kwargs']\n\n resourcePath = '/quote/bucketed'\n resourcePath = resourcePath.replace('{format}', 'json')\n method = 'GET'\n\n queryParams = {}\n headerParams = {}\n formParams = {}\n bodyParam = None\n\n if ('binSize' in params):\n queryParams['binSize'] = self.apiClient.toPathValue(params['binSize'])\n if ('symbol' in params):\n queryParams['symbol'] = self.apiClient.toPathValue(params['symbol'])\n if ('filter' in params):\n queryParams['filter'] = self.apiClient.toPathValue(params['filter'])\n if ('columns' in params):\n queryParams['columns'] = self.apiClient.toPathValue(params['columns'])\n if ('count' in params):\n queryParams['count'] = self.apiClient.toPathValue(params['count'])\n if ('start' in params):\n queryParams['start'] = self.apiClient.toPathValue(params['start'])\n if ('reverse' in params):\n queryParams['reverse'] = self.apiClient.toPathValue(params['reverse'])\n if ('startTime' in params):\n queryParams['startTime'] = self.apiClient.toPathValue(params['startTime'])\n if ('endTime' in params):\n queryParams['endTime'] = self.apiClient.toPathValue(params['endTime'])\n if formParams:\n headerParams['Content-type'] = 'application/x-www-form-urlencoded'\n\n postData = (formParams if formParams else bodyParam)\n\n response = self.apiClient.callAPI(resourcePath, method, queryParams,\n postData, headerParams)\n\n if not response:\n return None\n\n responseObject = self.apiClient.deserialize(response, 'Array[Quote]')\n return responseObject\n \n\n \n\n \n\n\n\n\n","sub_path":"clients/python/QuoteApi.py","file_name":"QuoteApi.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"513298861","text":"# File name: p09.py\n\ns = \"What, do cool programmers use for loops?\"\n\nnew_s = \"\"\n\nvowels = \"aeiouy\"\n\nfor i,c in enumerate(s):\n if c in vowels and ( i == 0 or s[i-1] not in vowels ): \n new_s += c+c\n else:\n new_s += c\n\nprint(new_s)\n","sub_path":"csc280/exams/p09.py","file_name":"p09.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"557134939","text":"import shutil\nfrom pathlib import Path\n\nfrom get_dataset import *\nfrom get_statistic_summary import *\nfrom get_mljar import *\nimport json\nimport glob\n\nPARAMETER_FILE = Path(\"config/auto_ml_parameters.json\")\nif PARAMETER_FILE.exists():\n with open(PARAMETER_FILE) as fout:\n PARAMETERS = json.load(fout)\nelse:\n raise FileNotFoundError(f\"Config file {PARAMETER_FILE.as_posix()} does not exist.\")\n\n\ndef create_output_folder(output_dir):\n if not output_dir.exists():\n output_dir.mkdir()\n return output_dir\n\n\ndef get_mljar_info(output_dir, automl_report):\n # 1. Move the leaderboard.csv file (automl summary) to the upper level\n automl_report.get_leaderboard().to_csv(output_dir.joinpath(\"leaderboard.csv\"), index=False)\n\n # 2. Delete all models (bc they are heavy and we don't use them)\n automl_path = output_dir.joinpath(\"automl\")\n model_file_paths = [Path(p) for p in glob.glob(automl_path.as_posix() + f\"/**/learner_fold_*.*\", recursive=True)]\n model_file_paths = [p for p in model_file_paths if\n p.suffix not in [\".csv\", \".png\", \".log\", \".svg\"]]\n for model_path in model_file_paths:\n model_path.unlink()\n\n\ndef fill_main_csv(id, catalog, statistics_summary):\n \"\"\"This function adds a new row in open_ml_datasets.csv containing all the main info about each dataset. This csv file is then used as\n database in the app.\n :param: :id: data.gouv.fr id of the dataset\n :type: :id: str\n :param: :catalog: data.gouv.fr catalog\n :type: :catalog: pandas dataframe\n :param: :statistics_summary: table containing info extracted from pandas profiling\n :type: :statistics_summary: pandas dataframe\n \"\"\"\n main_csv_path = Path().home().joinpath('open_ML/open_ml_app/assets/datasets/open_data_ml_datasets.csv')\n main_df = pd.read_csv(main_csv_path)\n new_row = {}\n for col in main_df.columns:\n new_row.update({col: ''})\n dict_main_df = {'title': 'dataset.title', 'dgf_dataset_url': 'dataset.url', 'dgf_resource_url': 'url'}\n for key, item in dict_main_df.items():\n new_row[key] = catalog[catalog['id'] == id][item].values.item()\n for param in PARAMETERS:\n new_row['target_variable'] = param[\"target\"]\n new_row['task'] = param[\"task\"]\n new_row['nb_lines'] = statistics_summary['Number of lines'][0]\n new_row['nb_features'] = statistics_summary['Number of variables'][0]\n new_row['profile_url'] = f\"https://etalab-ia.github.io/open_ML/profilings/{id}.html\"\n new_row['automl_url'] = f\"https://etalab-ia.github.io/open_ML/automodels/{id}/README.html\"\n new_row['dgf_resource_id'] = id\n main_df = main_df.append(new_row, ignore_index=True)\n main_df.to_csv(main_csv_path, index=False)\n return main_df\n\n\n\n\n\n\n\ndef main():\n for param in PARAMETERS:\n id = param[\"id\"]\n output_dir = Path(param[\"output_dir\"]).joinpath(id)\n catalog = latest_catalog() # or latest_catalog for using the last catalog\n\n catalog_info = info_from_catalog(id, catalog)\n output_dir = create_output_folder(output_dir)\n\n data = load_dataset(id, catalog_info, output_dir=output_dir)\n print(\"Successfully loaded dataset.\")\n if check_constraints(data):\n profiling = generate_pandas_profiling(id, data, output_dir=output_dir, config_path=None)\n statistics_summary = get_statistics_summary(profiling, output_dir=output_dir)\n get_data_dictionary(profiling, output_dir=output_dir)\n print(\"Successfully generated Pandas Profiling.\")\n prep_data = prepare_for_mljar(data=data, target_variable=param[\"target\"],\n profiling=profiling)\n automl = generate_mljar(data=prep_data, target_variable=param[\"target\"], output_dir=output_dir)\n get_mljar_info(output_dir=output_dir, automl_report=automl)\n # plot_mljar_table(id)\n print(\"Successfully generated AutoML report.\")\n fill_main_csv(id=id, catalog=catalog, statistics_summary=statistics_summary)\n print(\"Added info to main csv.\")\n else:\n raise Exception('This dataset is not adequate for Machine Learning')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/automatization/auto_openml.py","file_name":"auto_openml.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25615470","text":"import datetime\n\nfrom sqlalchemy import Column, Integer, ForeignKey, String, DateTime, BLOB, LargeBinary, Binary\nfrom sqlalchemy.orm import relationship\n\nfrom helpers.dbhelpers import DbHelper\n\n\"\"\"\npip install sqlalchemy\npip install mysql-connector-python\n\"\"\"\n\n\nclass Directory(DbHelper().modelBase):\n \"\"\"\n This class is the orm model that is used as a template in directory table generation\n The table has two one-to-many relationships (one with the files table and one with the directory server itself)\n \"\"\"\n __tablename__ = 'directory'\n\n id = Column('id', Integer, primary_key=True, autoincrement=True)\n path = Column('path', String(200), nullable=False)\n name = Column('name', String(50), index=True)\n creation_date = Column(DateTime, default=datetime.datetime.utcnow)\n\n parent_directory_id = Column('parent_directory_id', Integer, ForeignKey('directory.id'))\n\n files = relationship('File', back_populates='directory')\n subdirectories = relationship('Directory', back_populates='parent_directory')\n parent_directory = relationship('Directory')\n\n def __init__(self, name: String(50), path, object_id: Integer = None, parent_directory_id: Integer = None):\n \"\"\"\n Creates the object\n :param name: the name\n :param parent_directory_id: the id of the parent\n \"\"\"\n self.id = object_id\n self.path = path\n self.name = name\n self.parent_directory_id = parent_directory_id\n\n\nclass File(DbHelper().modelBase):\n \"\"\"\n This class is the orm model that is used as a template in directory table generation\n The table has two many-to-one relationship (with the directory table)\n \"\"\"\n __tablename__ = 'file'\n\n id = Column('id', Integer, primary_key=True, autoincrement=True)\n name = Column('name', String(50), nullable=False)\n path = Column('path', String(200), nullable=False)\n binary_content = Column('binary_content', LargeBinary(length=(2**32)-1))\n text_content = Column('text_content', String(5000))\n directory_id = Column('directory_id', Integer, ForeignKey('directory.id'))\n directory = relationship('Directory', back_populates='files')\n\n def __init__(self, name, directory_id, path, binary_content=None, text_content=None):\n \"\"\"\n Creates the object\n :param name:\n :param directory_id:\n :param binary_content:\n :param text_content:\n \"\"\"\n\n self.name = name\n self.binary_content = binary_content\n self.text_content = text_content\n self.directory_id = directory_id\n self.path = path\n","sub_path":"storage/model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"89396043","text":"#!/usr/bin/env python\n\n__all__ = ('scm_eval', 'scm_apply')\n\nfrom scm_object import *\n\n\ndef scm_eval(exp, env):\n if type(exp) in (ScmBoolean, ScmNumber, ScmString):\n return exp\n elif type(exp) == ScmSymbol:\n return env.lookup_var(exp.data)\n elif type(exp) == ScmPair:\n a = exp.a\n if type(a) == ScmSymbol:\n k = a.data\n if k in special_table:\n return special_table[k](exp, env)\n elif k in transform_table:\n new_exp = transform_table[k](exp)\n return scm_eval(new_exp, env)\n proc = scm_eval(exp.a, env)\n if isinstance(proc, ScmProcedure):\n args = scm_eval_list(exp.d, env)\n return scm_apply(proc, args)\n else:\n raise Exception()\n else:\n raise Exception()\n\n\ndef scm_apply(proc, args):\n if type(proc) == ScmPrimitiveProcedure:\n v = proc.proc(*to_python_list(args))\n assert isinstance(v, ScmObject)\n return v\n else:\n if proc.dot_arg:\n value_list = []\n p = args\n for _ in range(len(proc.args) - 1):\n value_list.append(p.a)\n p = p.d\n value_list.append(p)\n else:\n value_list = to_python_list(args)\n if len(proc.args) != len(value_list):\n raise Exception()\n return scm_eval_sequence(proc.body, ScmEnvironment(proc.args, value_list, proc.env))\n\n\ndef scm_eval_list(exp_list, env):\n if type(exp_list) == ScmNull:\n return ScmNull.null\n else:\n return ScmPair(scm_eval(exp_list.a, env),\n scm_eval_list(exp_list.d, env))\n\n\ndef scm_eval_sequence(exp_seq, env):\n p = exp_seq\n while type(p.d) != ScmNull:\n scm_eval(p.a, env)\n p = p.d\n return scm_eval(p.a, env)\n\n\ndef make_procedure(name, args, body, env):\n l = []\n p = args\n while type(p) == ScmPair:\n if type(p.a) == ScmSymbol:\n l.append(p.a.data)\n else:\n raise Exception()\n p = p.d\n if type(p) == ScmNull:\n dot_arg = False\n elif type(p) == ScmSymbol:\n l.append(p.data)\n dot_arg = True\n else:\n raise Exception()\n return ScmCompoundProcedure(name, l, dot_arg, body, env)\n\n\ndef to_python_list(l):\n ll = []\n while type(l) != ScmNull:\n ll.append(l.a)\n l = l.d\n return ll\n\n\ndef table_adder(t):\n def adder(key):\n def w(f):\n t[key] = f\n return f\n\n return w\n\n return adder\n\n\nspecial_table = {}\ntransform_table = {}\nspecial = table_adder(special_table)\ntransform = table_adder(transform_table)\n\n\n@special('quote')\ndef eval_quote(exp, env):\n return exp.d.a\n\n\n@special('set!')\ndef eval_set(exp, env):\n s = exp.d.a\n if type(s) != ScmSymbol:\n raise Exception()\n env.set_var(s.data, scm_eval(exp.d.d.a, env))\n return ScmVoid.void\n\n\n@special('define')\ndef eval_define(exp, env):\n s = exp.d.a\n if type(s) == ScmSymbol:\n k = s.data\n v = scm_eval(exp.d.d.a, env)\n elif type(s) == ScmPair:\n if type(s.a) == ScmSymbol:\n k = s.a.data\n v = make_procedure(k, s.d, exp.d.d, env)\n else:\n raise Exception\n else:\n raise Exception()\n env.define_var(k, v)\n return ScmVoid.void\n\n\n@special('if')\ndef eval_if(exp, env):\n if scm_eval(exp.d.a, env) is not ScmBoolean.false:\n return scm_eval(exp.d.d.a, env)\n else:\n t = exp.d.d.d\n if type(t) == ScmPair:\n return scm_eval(t.a, env)\n else:\n return ScmVoid.void\n\n\n@special('lambda')\ndef eval_lambda(exp, env):\n return make_procedure('lambda', exp.d.a, exp.d.d, env)\n\n\n@special('begin')\ndef eval_begin(exp, env):\n return scm_eval_sequence(exp.d, env)\n","sub_path":"python/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"393064059","text":"from django.http import HttpRequest\nfrom django.test import TestCase\nfrom django.urls import resolve\n\nfrom lists.models import Item\nfrom lists.views import home_page\n\n\n# Create your tests here.\nclass SmokeTest(TestCase):\n\n def test_uses_home_template(self):\n response = self.client.get('/')\n self.assertTemplateUsed(response, 'home.html')\n\n def test_can_save_post_request(self):\n response = self.client.post('/', data={'item_text': 'A new list item'})\n self.assertIn('A new list item', response.content.decode())\n self.assertTemplateUsed(response, 'home.html')\n\n\nclass ItemModelTest(TestCase):\n\n def test_saving_and_retrieving_items(self):\n first_item = Item()\n first_item.text = 'The first (ever) list item'\n first_item.save()\n\n second_item = Item()\n second_item.text = 'The second (ever) list item'\n second_item.save()\n\n saved_items = Item.objects.all()\n self.assertEqual(saved_items.count(), 2)\n first_save_item = saved_items[0]\n second_save_item = saved_items[1]\n\n self.assertEqual(first_save_item.text, 'The first (ever) list item')\n self.assertEqual(second_save_item.text, 'The second (ever) list item')","sub_path":"lists/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223616336","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\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom karbor.i18n import _LE, _LI\nfrom karbor.services.protection import utils\nfrom swiftclient import client as swift\n\nLOG = logging.getLogger(__name__)\n\nSERVICE = 'swift'\nswift_client_opts = [\n cfg.StrOpt(SERVICE + '_endpoint',\n help='URL of the swift endpoint. Only used if '\n 'swift_auth_url is unset'),\n cfg.StrOpt(SERVICE + '_catalog_info',\n default='object-store:swift:publicURL',\n help='Info to match when looking for swift in the service '\n 'catalog. Format is: separated values of the form: '\n ':: - '\n 'Only used if swift_endpoint and swift_auth_url '\n 'are unset'),\n cfg.StrOpt('swift_auth_url',\n help='The URL of the Keystone endpoint'),\n cfg.StrOpt('swift_auth_version',\n default='1',\n help='Swift authentication version. '\n 'Specify \"1\" for auth 1.0, or \"2\" for auth 2.0. '\n 'Only used if swift_auth_url is set.'),\n cfg.StrOpt('swift_tenant_name',\n help='Swift tenant/account name. '\n 'Required when connecting to an auth 2.0 system'),\n cfg.StrOpt('swift_user',\n help='Swift user name, if swift_auth_url is set.'),\n cfg.StrOpt('swift_key',\n help='Swift key for authentication, if swift_auth_url '\n ' is set.'),\n cfg.IntOpt('swift_retry_attempts',\n default=3,\n help='The number of retries to make for '\n 'Swift operations'),\n cfg.IntOpt('swift_retry_backoff',\n default=2,\n help='The backoff time in seconds '\n 'between Swift retries'),\n cfg.StrOpt('swift_ca_cert_file',\n help='Location of the CA certificate file '\n 'to use for swift client requests.'),\n cfg.BoolOpt('swift_auth_insecure',\n default=True,\n help='Bypass verification of server certificate when '\n 'making SSL connection to Swift.'),\n]\n\n\ndef register_opts(conf):\n conf.register_opts(swift_client_opts, group=SERVICE + '_client')\n\n\ndef create(context, conf):\n register_opts(conf)\n\n if hasattr(conf.swift_client, 'swift_auth_url') and \\\n conf.swift_client.swift_auth_url:\n connection = swift.Connection(\n authurl=conf.swift_client.swift_auth_url,\n auth_version=conf.swift_client.swift_auth_version,\n tenant_name=conf.swift_client.swift_tenant_name,\n user=conf.swift_client.swift_user,\n key=conf.swift_client.swift_key,\n retries=conf.swift_client.swift_retry_attempts,\n starting_backoff=conf.swift_client.swift_retry_backoff,\n insecure=conf.swift_client.swift_auth_insecure,\n cacert=conf.swift_client.swift_ca_cert_file)\n else:\n try:\n url = utils.get_url(SERVICE, context, conf,\n append_project_fmt='%(url)s/AUTH_%(project)s')\n except Exception:\n LOG.error(_LE(\"Get swift service endpoint url failed\"))\n raise\n LOG.info(_LI(\"Creating swift client with url %s.\"), url)\n connection = swift.Connection(\n preauthurl=url,\n preauthtoken=context.auth_token,\n retries=conf.swift_client.swift_retry_attempts,\n starting_backoff=conf.swift_client.swift_retry_backoff,\n insecure=conf.swift_client.swift_auth_insecure,\n cacert=conf.swift_client.swift_ca_cert_file)\n return connection\n","sub_path":"karbor/services/protection/clients/swift.py","file_name":"swift.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76545734","text":"import copy\n\ndef gen_order(id):\n order = {\"order\": {\"id\": id,\n \"carID\": 101,\n \"driverId\": 102,\n \"startSite\": \"startSite\",\n \"coordinateType\": \"BS-09\",\n \"locationType\": \"BD-09\",\n \"startLongitude\": 123.12,\n \"startLatitude\": 23.12,\n \"endLongitude\": 125.12,\n \"endLatitude\": 25.12,\n \"isFinished\": 0,\n \"startTime\": \"\",\n \"endTime\": \"\",\n \"addressorName\": \"\",\n \"addressorPhone\": \"\",\n \"addressorAddress\": \"\",\n \"addresseeName\": \"\",\n \"addresseePhone\": \"\",\n \"addresseeAddress\": \"\",\n \"sealExpect\": \"\",\n \"sealCurrent\": \"\"},\n \"route\": []}\n return copy.deepcopy(order)\n\n\ndef gen_point(latitude, longitude, time):\n point = {\"id\": \"\",\n \"carID\": \"\",\n \"waybillID\": \"\",\n \"time\": time,\n \"coordinateType\": \"BS-09\",\n \"locationType\": \"\",\n \"longitude\": \"\",\n \"latitude\": \"\",\n \"driverId\": \"\",\n \"photoURL\": \"\"}\n\n new_point = copy.deepcopy(point)\n new_point[\"latitude\"] = latitude\n new_point[\"longitude\"] = longitude\n return new_point","sub_path":"testMap_YZY/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"99226026","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.template.defaultfilters import slugify\nfrom django.views.generic.list import ListView\nfrom django.views.generic import CreateView, View\nfrom django.views.generic.edit import UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.urls import reverse_lazy\n\nfrom grupo.models import Grupo\n\nfrom .forms import SubGrupoForm\nfrom .models import SubGrupo\n\nclass CriarSubGrupo(LoginRequiredMixin, View):\n template_name = 'subgrupo/formulario_subgrupo.html'\n form_model = SubGrupoForm\n \n def get(self, request, slug_grupo):\n form = self.form_model(request.GET)\n return render(request, self.template_name, {'form': form, 'slug_grupo': slug_grupo})\n\n def post(self, request, slug_grupo):\n\n grupo = get_object_or_404(Grupo, slug=slug_grupo)\n form = self.form_model(request.POST)\n if form.is_valid():\n formulario = form.save(commit=False)\n formulario.grupo = grupo\n formulario.user = request.user\n formulario.save()\n return redirect(f'/{grupo.slug}/')\n else:\n return render(request, self.template_name, {'form': form, 'slug_grupo': slug_grupo})\n\nclass VisualizarSubGrupo(LoginRequiredMixin, ListView):\n\n def get(self, request, slug_grupo, slug_subgrupo):\n busca = request.GET.get('search-area', '')\n subgrupo = get_object_or_404(SubGrupo, slug=slug_subgrupo, grupo__slug=slug_grupo)\n tarefas = subgrupo.tarefa_set.all()\n\n if busca:\n tarefas = tarefas.filter(nome___icontains=busca)\n\n context = {'tarefas': tarefas, 'subgrupo': subgrupo, 'search_input': busca}\n\n return render(request, \"subgrupo/subgrupo.html\", context)\n\n\nclass MostraSubGrupo(LoginRequiredMixin, View):\n\n def get(self, request, pk):\n subgrupo_especifico = SubGrupo.objects.get(id=pk)\n join_subgrupo = subgrupo_especifico.tarefa_subgrupos.all()\n id_grupo = subgrupo_especifico.grupo_sub_id\n\n busca = request.GET.get('search-area', '')\n\n if busca:\n join_subgrupo = join_subgrupo.filter(title__icontains=busca)\n\n context = {'join_subgrupo': join_subgrupo, 'pk': pk, 'search_input': busca, 'id_grupo': id_grupo}\n\n return render(request, \"login/mostra_subgrupo.html\", context)\n\n\n\n\ndef exclui_subgrupo(request, pk):\n item = SubGrupo.objects.get(id=pk)\n id_grupo = item.grupo_sub_id\n\n if request.method == 'POST':\n item.delete()\n return redirect(f'/subgrupos/{id_grupo}')\n\n return render(request, 'login/apagar_subgrupo.html', {'pk': pk, 'id_grupo': id_grupo})\n\n\ndef edita_subgrupo(request, pk):\n item_id = SubGrupo.objects.get(id=pk)\n id_grupo = item_id.grupo_sub_id\n\n if request.method == 'POST':\n item = get_object_or_404(SubGrupo, id=pk)\n form = SubGrupoForm(request.POST, instance=item)\n\n if form.is_valid():\n form.save()\n return redirect(f'/subgrupos/{id_grupo}')\n else:\n item = SubGrupo.objects.filter(id=pk).values().last()\n form = SubGrupoForm(initial=item)\n\n return render(request, 'login/formulario_subgrupos.html', {'pk': pk, 'form': form, 'id_grupo': id_grupo})\n\n\ndef atualiza_subgrupo(request, pk):\n item = SubGrupo.objects.get(id=pk)\n id_grupo = item.grupo_sub_id\n\n if request.method == 'POST':\n item.delete()\n return redirect(f'/subgrupos/{id_grupo}')\n\n return render(request, 'login/apagar_subgrupo.html', {'pk': pk, 'id_grupo': id_grupo})\n\n\nclass AtualizarSubGrupo(LoginRequiredMixin, UpdateView):\n model = SubGrupo\n fields = '__all__'\n template_name = 'login/formulario_subgrupos.html'\n","sub_path":"src/subgrupo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"460642663","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.core.management import call_command\nfrom django.core.urlresolvers import reverse\nfrom django.test.client import Client\nfrom django.conf import settings\n\nimport shutil\nimport os\n\n# custome managment command\n\ndef get_pages():\n\tfor name in os.listdir(settings.SITE_PAGES_DIRECTORY):\n\t\tif name.endswith('.html'):\n\t\t\tyield name[:-5]\n\nclass Command(BaseCommand):\n\t\"\"\"Command\n\t\"\"\"\n\n\thelp = 'Build static site output.'\n\n\tdef handle(self, *args, **options):\n\t\t\"\"\"handle\n\t\t\tRequest pages and build output.\n\t\t\"\"\"\n\n\t\t# enable STATIC_FILES_STORAGE\n\t\t# files will get a unique hash associated with them \n\t\t# when DEBUG is set to False.\n\t\tsettings.DEBUG = False\n\n\t\t# for use with django-compressor\n\t\tsettings.COMPRESS_ENABLED = True\n\n\n\t\tif args:\n\t\t\tpages = args\n\t\t\tavailable = list(get_pages())\n\t\t\tinvalid = []\n\n\t\t\tfor page in pages:\n\t\t\t\tif page not in available:\n\t\t\t\t\tinvalid.append(page)\n\t\t\tif invalid:\n\t\t\t\tmsg = 'Invalid pages: {}'.format(', '.join(invalid))\n\t\t\t\t# raise error when name(s) don't exists\n\t\t\t\traise CommandError(msg)\n\n\t\telse:\n\t\t\tpages = get_pages()\n\t\t\tif os.path.exists(settings.SITE_OUTPUT_DIRECTORY):\n\t\t\t\tshutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)\n\n\t\t\tos.mkdir(settings.SITE_OUTPUT_DIRECTORY)\n\t\t\tos.makedirs(settings.STATIC_ROOT)\n\n\t\t# copy all of the site's static resources into the\n\t\t# STATIC_ROOT, which is configured to be inside the\n\t\t# STATIC_OUTPUT_DIRECTORY\n\t\tcall_command(\n\t\t\t'collectstatic', \n\t\t\tinteractive=False,\n\t\t\tclear=True,\n\t\t\tverbosity=0\n\t\t)\n\n\t\t# django-compressor\n\t\t# now can add { % compress % } bloacks around static\n\t\t# resources in base.html\n\t\tcall_command(\n\t\t\t'compress',\n\t\t\tinteractive=False,\n\t\t\tforce=True\n\t\t)\n\n\t\tclient = Client()\n\t\t\n\t\tfor page in get_pages():\n\t\t\turl = reverse('page', kwargs={'slug': page })\n\t\t\tresponse = client.get(url)\n\n\t\t\tif page == 'index':\n\t\t\t\toutput_dir = settings.SITE_OUTPUT_DIRECTORY\n\t\t\telse:\n\t\t\t\t# not always tearing down entire directory\n\t\t\t\t# check if it already exists\n\t\t\t\toutput_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)\n\t\t\t\tif not os.path.exists(output_dir):\n\t\t\t\t\tos.makedirs(output_dir)\n\n\t\t\t# templates render as static content using the\n\t\t\t# Django test client to mimic crawling the site\n\t\t\t# pages and writing the rendered content inot the\n\t\t\t# SITE_OUTPUT_DIRECTORY\n\t\t\twith open(os.path.join(output_dir, 'index.html'), 'wb') as f:\n\t\t\t\tf.write(response.content)","sub_path":"sitebuilder/management/commands/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"393063501","text":"from datetime import timedelta\nfrom celery.schedules import crontab\n\"\"\"\n配置周期性任务\n\"\"\"\nCELERYBEAT_SCHEDULE = {\n 'ptask': {\n 'task': 'test_config.period_task',\n 'schedule': timedelta(seconds=5),\n },\n\n}\nCELERY_TIMEZONE = 'Asia/Shanghai'\nCELERY_RESULT_BACKEND = 'redis://localhost:6379/0'","sub_path":"celery_/celery_config.py","file_name":"celery_config.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642320312","text":"import timeit\n\nimport pandas as pd\nimport scipy as sp\nimport numpy as np\nfrom numpy import linalg as LA\n\ndef test():\n l = [['1','2','3','4','5'],['4','5','6','7','10.0001']]*1000000\n df = pd.DataFrame(l)\n df[0] = df[0].astype(int)\n df[1] = df[1].astype(float)\n df[2] = df[2].astype(float)\n df[3] = df[3].astype(float)\n\n df[4] = df[4].astype(float)\n dfv = df.values\n hi = len(dfv)\n for i in range(0,hi):\n eta = dfv[i,1:3] - dfv[i,3:5]\n if np.all( abs( eta)<2.5):\n dist = LA.norm(eta)\n if dist < 3.:\n dfv[i, 0] = 11\n\n\n\ndef test2():\n l = [['1','2','3','4','5'],['4','5','6','7','10.0001']]*1000000\n df = np.array(l)\n alpha = df[:, 0].astype(int)\n beta = df[:, 1:3].astype(float)\n gama = df[:,3:5].astype(float)\n hi = len(beta)\n\n for i in range(0,hi):\n eta = beta[i]-gama[i]\n if np.all( abs(eta)<2.5 ):\n dist = LA.norm(eta)\n if dist< 3.:\n alpha[i] = 11\n\n#test()\n#test2()\n\n\ntestnumber = 1\n\nprint(timeit.timeit( \"test()\", setup = 'from __main__ import test', number= testnumber ) /testnumber )\nprint(timeit.timeit( \"test2()\", setup = 'from __main__ import test2', number= testnumber ) /testnumber )\n\n\n#NOTE\n # Test results here:\n # Create 100k row 5 col list. converts the data types. pd.DataFrame and .values = 0.242s, while pure np.array)s = 0.501s.\n \n # 1k row 5 col list, calcuate detal vector eta line by line over for loop. pd.DataFrame (no extract values) and save result in .values =1.935s (keeping result in pd.Series makes no much difference.), while pure np.array)s = 0.00853s. \n\n # Create 100k row 5 col list. Convert data types. Calcuate detal vector eta line by line over for loop. pd.DataFrame.values =1.029s, while pure np.array)s = 0.898s.\n\n\n # Create 100k row 5 col list. Convert data types. Calcuate detal vector eta line by line over for loop. Check if all coor in threshold. (Half of rows should be.) pd.DataFrame.values =3.045s, while pure np.array)s = 2.859 s.\n\n # Create 100k row 5 col list. Convert data types. Calcuate detal vector eta line by line over for loop. Check if all delta vector abs( coor) in threshold. (Half of rows should be.) If in, calculate norm. pd.DataFrame.values =3.310s, while pure np.array)s = 3.014 s.\n # same as above line except using two np.all)s instead of abs(), 4.67 vs 4.61. Worse....\n # Create 100k row 5 col list. Convert data types. Calcuate detal vector eta line by line over for loop. Check if all delta vector abs( coor) in threshold. (Half of rows should be.) If in, calculate norm. Change id if in the range of threshold, 4.541s vs 4.241s.\n\n\n# Each test goes under 10 times of run and averaged ,except for the very slow 1000 ro pandas.DataFrame loop. Run on the vertual box on a windows 10 box. Machine is Dell Precision T3500. CPU Intel Xeon W3530 2.80GHz. total 8 Hyperthread Cores.\n\n # Additional test: 1000k row 5 col list, calculate norm, change id, etc. All done. Only a 1 time run, 45.076s vs 41.602s.\n\n # CONCLUSION:\n # Never loop over rows by using pandas.DataFrame itself!!\n # pandas.DataFrame is a little faster in converting data type, while numpy.array cathces up when futher calculating the delta vector and so on. The numpy.array is 10% faster finally. The difference can be in the dfv[i,1:3] in each loop dfv[i,3:5], the locating might be a time consuming factor.\n # In short, pandas has some advantages in dealing with csv and xlsx files, both input and output. But pandas module needs to be installed by user. It is not a default package. If want to run on server, better to avoid pandas and only use numpy. One can use .tofile or .savetxt for io. Some other func such as .unique or something to do the simple stats analysis. Search internet.\n","sub_path":"ClusterAnalysis_numpy/testspeed.py","file_name":"testspeed.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"307277956","text":"#!/usr/bin/env python\n\"\"\"\n Rabbitmq.com pub/sub example\n\n https://www.rabbitmq.com/tutorials/tutorial-three-python.html\n\n\"\"\"\n\nimport asyncio\nimport aioamqp\nimport random\n\n\n\n@asyncio.coroutine\ndef callback(channel, body, envelope, properties):\n print(\" [x] %r\" % body)\n\n\n@asyncio.coroutine\ndef receive_log():\n try:\n transport, protocol = yield from aioamqp.connect('localhost', 5672)\n except aioamqp.AmqpClosedConnection:\n print(\"closed connections\")\n return\n\n\n channel = yield from protocol.channel()\n exchange_name = 'logs'\n\n yield from channel.exchange(exchange_name=exchange_name, type_name='fanout')\n\n # let RabbitMQ generate a random queue name\n result = yield from channel.queue(queue_name='', exclusive=True)\n\n queue_name = result['queue']\n yield from channel.queue_bind(exchange_name=exchange_name, queue_name=queue_name, routing_key='')\n\n print(' [*] Waiting for logs. To exit press CTRL+C')\n\n yield from channel.basic_consume(callback, queue_name=queue_name, no_ack=True)\n\nevent_loop = asyncio.get_event_loop()\nevent_loop.run_until_complete(receive_log())\nevent_loop.run_forever()\n","sub_path":"examples/receive_log.py","file_name":"receive_log.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519948323","text":"from os import path, system\nimport sqlite3 as sql\n\n\ndef formatSQLString(sqlString):\n sqlFormatString = \"'\"\n for i in range(len(sqlString)):\n if(sqlString[i] == \"'\"):\n sqlFormatString += \"''\"\n elif(sqlString[i] != '\\n'):\n sqlFormatString += sqlString[i]\n sqlFormatString += \"'\"\n return sqlFormatString\n\n\nconnection = sql.connect('life.sqlite3')\ncursor = connection.cursor()\n\n\ndef dropSynonymTypeTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS synonym_type;''')\n connection.commit()\n\n\ndef dropSynonymTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS synonym;''')\n connection.commit()\n\n\ndef dropFlagTypeTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS flag_type''')\n connection.commit()\n\n\ndef dropFlagTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS flag;''')\n connection.commit()\n\n\ndef dropRankTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS rank;''')\n connection.commit()\n\n\ndef dropTaxonTable(connection, cursor):\n cursor.execute('''DROP TABLE IF EXISTS taxon;''')\n connection.commit()\n\n\ndef dropAllTables(connection, cursor):\n dropSynonymTypeTable(connection, cursor)\n dropSynonymTable(connection, cursor)\n dropFlagTypeTable(connection, cursor)\n dropFlagTable(connection, cursor)\n dropRankTable(connection, cursor)\n dropTaxonTable(connection, cursor)\n connection.commit()\n\n\ndef createSynonymTypeTable(connection, cursor):\n # Create 'Synonym Type' table\n cursor.execute('''\n CREATE TABLE synonym_type (\n type_id INTEGER PRIMARY KEY NOT NULL,\n name VARCHAR(256) NOT NULL\n );\n ''')\n connection.commit()\n\n\ndef createSynonymTable(connection, cursor):\n # Create 'Synonym' table\n cursor.execute('''\n CREATE TABLE synonym (\n syn_id INTEGER PRIMARY KEY NOT NULL,\n uid INTEGER NOT NULL,\n name VARCHAR(256) NOT NULL,\n type_id INTEGER NOT NULL,\n FOREIGN KEY (type_id) REFERENCES synonym_type (type_id)\n );\n ''')\n connection.commit()\n\n\ndef createFlagTypeTable(connection, cursor):\n # Create 'Flag Type' table\n cursor.execute('''\n CREATE TABLE flag_type (\n type_id INTEGER PRIMARY KEY NOT NULL,\n name VARCHAR(50) NOT NULL\n )\n ''')\n\n\ndef createFlagTable(connection, cursor):\n # Create 'Flag' table\n cursor.execute('''\n CREATE TABLE flag (\n flag_id INTEGER PRIMARY KEY NOT NULL,\n uid INTEGER NOT NULL,\n type_id INTEGER NOT NULL,\n FOREIGN KEY (type_id) REFERENCES flag_type (type_id)\n );\n ''')\n connection.commit()\n\n\ndef createRankTable(connection, cursor):\n # Create 'Rank' table\n cursor.execute('''\n CREATE TABLE rank (\n rank_id INTEGER PRIMARY KEY NOT NULL,\n name VARCHAR(25) NOT NULL\n );\n ''')\n connection.commit()\n\n\ndef createTaxonTable(connection, cursor):\n # Create 'Taxon' table\n cursor.execute('''\n CREATE TABLE taxon (\n uid INTEGER PRIMARY KEY NOT NULL,\n parent_uid INTEGER,\n name VARCHAR(256) NOT NULL,\n rank_id INTEGER NOT NULL,\n source_info VARCHAR(256),\n FOREIGN KEY (rank_id) REFERENCES rank (rank_id)\n );\n ''')\n connection.commit()\n\n\ndef populateSynonymTypeTable(connection, cursor):\n with open('tabSynonyms.txt', 'r') as synonymTypes:\n for synonymType in synonymTypes:\n cursor.execute(\"INSERT INTO synonym_type (name) VALUES (\" + formatSQLString(synonymType) + \");\")\n connection.commit()\n\n\ndef populateSynonymTable(connection, cursor):\n # TODO: Insert synonyms into 'synonym' table\n with open('synonyms.tsv', 'r') as synonyms:\n synonyms.readline()\n currentLine = 0\n for line in synonyms:\n currentLine += 1\n row = list(filter(lambda x: x != '|', line.split('\\t')))\n uid = row[1]\n name = row[0]\n typeName = (row[2],)\n cursor.execute('SELECT type_id FROM synonym_type WHERE name=?;', typeName)\n typeID = str(cursor.fetchone()[0])\n attributes = (uid, name, typeID, )\n print('Synonyms:' + str(currentLine) + \" / 1846370 : \" + str(attributes))\n cursor.execute(\"INSERT INTO synonym (uid, name, type_id) VALUES (?, ?, ?);\", attributes)\n connection.commit()\n\n\ndef populateFlagTypeTable(connection, cursor):\n with open('tabFlags.txt', 'r') as tabFlags:\n for flagType in tabFlags:\n cursor.execute(\"INSERT INTO flag_type (name) VALUES ('\" + flagType.rstrip() + \"');\")\n connection.commit()\n\n\ndef populateFlagTable(connection, cursor):\n # TODO: Insert flags into 'flag' table\n with open('taxonomy.tsv', 'r') as taxonomy:\n taxonomy.readline()\n currentLine = 0\n for line in taxonomy:\n currentLine += 1\n row = list(filter(lambda x: x != '|', line.split('\\t')))\n uid = row[0]\n flags = row[6].split(',')\n if flags[0] != '':\n for flag in flags:\n cursor.execute(\"SELECT type_id FROM flag_type WHERE name=?\", (flag,))\n typeID = str(cursor.fetchone()[0])\n print(' Flags:' + str(currentLine) + \" / 3594551 : \" + str((uid, flag)))\n cursor.execute(\"INSERT INTO flag (uid, type_id) VALUES (?, ?);\", (uid, flag,))\n connection.commit()\n\n\ndef populateRankTable(connection, cursor):\n with open('tabRanks.txt', 'r') as tabRanks:\n for rank in tabRanks:\n cursor.execute(\"INSERT INTO rank (name) VALUES ('\" + rank.rstrip() + \"')\")\n connection.commit()\n\n\ndef populateTaxonTable(connection, cursor):\n # TODO: Insert organisms into 'organism' table\n with open('taxonomy.tsv', 'r') as taxonomy:\n taxonomy.readline()\n currentLine = 0\n for line in taxonomy:\n currentLine += 1\n row = list(filter(lambda x: x != '|', line.split('\\t')))\n\n uid = row[0]\n parentUid = row[1]\n name = row[2]\n rank = row[3]\n sourceInfo = row[4]\n\n cursor.execute(\"SELECT rank_id FROM rank WHERE name=?\", (rank,))\n rankID = str(cursor.fetchone()[0])\n\n print(' Taxa:' + str(currentLine) + \" / 3594551 : \" + str((uid, name)))\n cursor.execute(\"INSERT INTO taxon (uid, parent_uid, name, rank_id, source_info) VALUES (?,?,?,?,?);\",\n (uid, parentUid, name, rankID, sourceInfo))\n connection.commit()\n\n\ndef buildDatabaseFromScratch(connection, cursor):\n dropAllTables(connection, cursor)\n\n createSynonymTypeTable(connection, cursor)\n createSynonymTable(connection, cursor)\n createFlagTypeTable(connection, cursor)\n createFlagTable(connection, cursor)\n createRankTable(connection, cursor)\n createTaxonTable(connection, cursor)\n\n populateSynonymTypeTable(connection, cursor)\n populateSynonymTable(connection, cursor)\n populateFlagTypeTable(connection, cursor)\n populateFlagTable(connection, cursor)\n populateRankTable(connection, cursor)\n\n\ndef runNow(connection, cursor):\n pass\n\n\nbuildDatabaseFromScratch(connection, cursor)\n\nconnection.commit()\n\nconnection.close()\n","sub_path":"build/buildDB.py","file_name":"buildDB.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"590508234","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template, request\nimport os, csv\n\napp = Flask(__name__)\napp.config.update(dict(DEBUG=True))\nDATAFILE = os.path.join(os.path.dirname(__file__), 'static/data/beers_for_rec.csv')\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/')\ndef placeholder(plotname):\n filename = plotname + \".html\"\n return render_template(filename)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"demo/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91910220","text":"'''Train CIFAR10 with PyTorch.'''\nfrom __future__ import print_function\n\nfrom sklearn import metrics\nimport torch\n\nimport numpy as np\nimport os\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\nfrom torchsummary import summary\n# from data_reader_isic import get_data_loaders\nfrom utils import *\nfrom torch.backends import cudnn\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nimport os\nimport argparse\n\nfrom models import *\nfrom utils import progress_bar\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nargs = parser.parse_args()\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nclass Classifier(object):\n def __init__(self,model_details):\n self.device_ids=[0,1]\n self.model_details=model_details\n self.log_dir=self.model_details.logs_dir\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n self.writer = SummaryWriter(self.log_dir)\n self.use_cuda = torch.cuda.is_available()\n self.best_acc = 0 # best test accuracy\n self.start_epoch = 0 # start from epoch 0 or last checkpoint epoch\n self.net = None\n self.criterion = model_details.criterion\n self.optimizer = None\n self.model_name_str = None\n\n def load_data(self):\n print('==> Preparing data of {}..'.format(self.model_details.dataset))\n self.trainloader, self.testloader = self.model_details.dataset_loader #[trainloader, test_loader]\n train_count = len(self.trainloader) * self.model_details.batch_size\n test_count = len(self.testloader) * self.model_details.batch_size\n print('==> Total examples, train: {}, test:{}'.format(train_count, test_count))\n\n def load_model(self):\n model_details=self.model_details\n model_name = model_details.model_name\n model_name_str = model_details.model_name_str\n print('\\n==> using model {}'.format(model_name_str))\n self.model_name_str=\"{}\".format(model_name_str)\n model = model_details.model\n # Model\n try:\n # Load checkpoint.\n assert (os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!')\n checkpoint = torch.load('./checkpoint/{}_ckpt.t7'.format(self.model_name_str ))\n model.load_state_dict(checkpoint['model'].state_dict())\n self.best_acc = checkpoint['acc']\n self.start_epoch = checkpoint['epoch']\n print('==> Resuming from checkpoint with Accuracy {}..'.format(self.best_acc))\n\n except Exception as e:\n print('==> Resume Failed and Building model..')\n\n if self.use_cuda:\n model=model.cuda()\n # model = torch.nn.DataParallel(model)\n cudnn.benchmark = True\n self.model=model\n self.optimizer=self.model_details.get_optimizer(self)\n\n # Training\n def train(self, epoch):\n print('\\nEpoch: %d' % epoch)\n model=self.model\n model.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(self.trainloader):\n step = epoch * len(self.trainloader) + batch_idx\n inputs, targets = inputs.to(device), targets.to(device)\n self.optimizer.zero_grad()\n outputs = model(inputs)\n loss = self.criterion(outputs, targets)\n loss.backward()\n self.optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n batch_loss = train_loss / (batch_idx + 1)\n if batch_idx % 2 == 0:\n self.writer.add_scalar('step loss', batch_loss, step)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n progress_bar(batch_idx, len(self.trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (batch_loss, 100. * correct / total, correct, total))\n self.writer.add_scalar('train loss',train_loss, epoch)\n\n def save_model(self, acc, epoch):\n print('\\n Saving new model with accuracy {}'.format(acc))\n state = {\n 'model': self.model,\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, './checkpoint/{}_ckpt.t7'.format(self.model_name_str ))\n\n def test(self,epoch):\n model=self.model\n model.eval()\n test_loss = 0\n correct = 0\n total = 0\n target_all = []\n predicted_all = []\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(self.testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = model(inputs)\n loss = self.criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n predicted_reshaped = predicted.cpu().numpy().reshape(-1)\n predicted_all = np.concatenate((predicted_all, predicted_reshaped), axis=0)\n\n targets_reshaped = targets.data.cpu().numpy().reshape(-1)\n target_all = np.concatenate((target_all, targets_reshaped), axis=0)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(self.testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss / (batch_idx + 1), 100. * correct / total, correct, total))\n\n # Save checkpoint.\n acc = 100. * correct / total\n self.writer.add_scalar('test accuracy', acc, epoch)\n print(\"Accuracy:{}\".format(acc))\n if acc > self.best_acc:\n self.save_model(acc, epoch)\n self.best_acc = acc\n cm = metrics.confusion_matrix(target_all, predicted_all)\n print(\"\\nConfsusion metrics: \\n{}\".format(cm))\n\n\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"353505769","text":"import xml.etree.ElementTree as ET\nimport xmlschema\nimport psycopg2\nimport sys\nimport shutil\nimport csv\nimport os\nimport json\nfrom os import system, name\nimport re\nimport codecs\nfrom datetime import datetime\nfrom datetime import timedelta\n\n# Custom code\nfrom classes.quota_order_number import quota_order_number\nfrom classes.quota_definition import quota_definition\nfrom classes.quota_association import quota_association\nfrom classes.quota_suspension_period import quota_suspension_period\nfrom classes.quota_blocking_period import quota_blocking_period\nfrom classes.measure import measure\nfrom classes.measure_component import measure_component\nfrom classes.measure_condition import measure_condition\nfrom classes.measure_condition_component import measure_condition_component\nfrom classes.measure_excluded_geographical_area import measure_excluded_geographical_area\nfrom classes.measure_footnote import measure_footnote\nfrom classes.measure_partial_temporary_stop import measure_partial_temporary_stop\nfrom classes.base_regulation import base_regulation\nfrom classes.business_rules import business_rules\nfrom classes.quota_balance import quota_balance\nfrom classes.quota_description import quota_description\nfrom classes.goods_nomenclature import goods_nomenclature\n\nfrom progressbar import ProgressBar\nimport classes.functions as fn\n\n\nclass application(object):\n def __init__(self):\n self.clear()\n\n self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n if \"/classes\" in self.BASE_DIR:\n self.BASE_DIR = self.BASE_DIR.replace(\"/classes\", \"\")\n else:\n self.BASE_DIR = self.BASE_DIR.replace(\"\\classes\", \"\")\n self.TEMPLATE_DIR = os.path.join(self.BASE_DIR, \"templates\")\n self.CSV_DIR = os.path.join(self.BASE_DIR, \"csv\")\n self.SOURCE_DIR = os.path.join(self.BASE_DIR, \"source\")\n self.MIGRATION_PROFILE_DIR = os.path.join(self.BASE_DIR, \"migration_profiles\")\n\n self.XML_OUT_DIR = os.path.join(self.BASE_DIR, \"xml_out\")\n self.XML_REPORT_DIR = os.path.join(self.BASE_DIR, \"xml_report\")\n\n self.TEMP_DIR = os.path.join(self.BASE_DIR, \"temp\")\n self.BULK_LOG_FILE = os.path.join(self.TEMP_DIR, \"bulk_log.csv\")\n\n self.CONFIG_DIR = os.path.join(self.BASE_DIR, \"..\")\n self.CONFIG_DIR = os.path.join(self.CONFIG_DIR, \"config\")\n self.CONFIG_FILE = os.path.join(self.CONFIG_DIR, \"config_common.json\")\n self.CONFIG_FILE_LOCAL = os.path.join(self.CONFIG_DIR, \"config_migrate_measures_and_quotas.json\")\n\n # Used for validating the produced XML\n self.SCHEMA_DIR = os.path.join(self.BASE_DIR, \"..\")\n self.SCHEMA_DIR = os.path.join(self.SCHEMA_DIR, \"xsd\")\n\n self.QUOTA_DIR = os.path.join(self.SOURCE_DIR, \"quotas\")\n self.BALANCE_FILE = os.path.join(self.QUOTA_DIR, \"quota_volume_master.csv\")\n self.QUOTA_DESCRIPTION_FILE = os.path.join(self.QUOTA_DIR, \"quota definitions.csv\")\n self.MFN_COMPONENTS_FILE = os.path.join(self.SOURCE_DIR, \"mfn_components.csv\")\n\n self.envelope_id = \"100000001\"\n self.definition_sid_start = 20000\n self.sequence_id = 1\n self.content = \"\"\n self.namespaces = {'oub': 'urn:publicid:-:DGTAXUD:TARIC:MESSAGE:1.0', 'env': 'urn:publicid:-:DGTAXUD:GENERAL:ENVELOPE:1.0', } # add more as needed\n\n self.regulation_list = []\n self.measures_with_sivs_list = []\n self.quota_definition_sid_mapping_list = []\n self.quota_description_list = []\n self.override_prompt = True\n self.destination_geographical_area_id = \"\"\n self.destination_geographical_area_sid = \"\"\n\n self.get_config()\n self.get_arguments()\n self.get_minimum_sids()\n\n def get_all_quota_order_numbers(self):\n # Get the detail of all quota order numbers\n self.quota_order_number_list = []\n sql = \"\"\"SELECT quota_order_number_sid, quota_order_number_id, validity_start_date, validity_end_date FROM quota_order_numbers\n WHERE validity_end_date IS NULL OR validity_end_date >= '\"\"\" + self.critical_date_string + \"\"\"'\n ORDER BY 2, 3\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n for rw in rows:\n quota_order_number_sid = rw[0]\n quota_order_number_id = rw[1]\n validity_start_date = rw[2]\n validity_end_date = rw[3]\n q = quota_order_number(quota_order_number_sid, quota_order_number_id, validity_start_date, validity_end_date)\n self.quota_order_number_list.append(q)\n\n def get_quota_order_numbers(self):\n # Get the detail of all quota order numbers\n self.quota_order_number_list = []\n if self.regulation_string == \"\":\n sql = \"\"\"SELECT quota_order_number_sid, quota_order_number_id, validity_start_date, validity_end_date FROM quota_order_numbers\n ORDER BY 1, 2 DESC\"\"\"\n else:\n sql = \"\"\"SELECT DISTINCT qon.quota_order_number_sid, qon.quota_order_number_id, qon.validity_start_date, qon.validity_end_date FROM quota_order_numbers qon, measures m\n WHERE m.ordernumber = qon.quota_order_number_id\n AND LEFT(m.measure_generating_regulation_id, 7) IN (\"\"\" + self.regulation_string + \"\"\")\n ORDER BY 1, 2 DESC\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n for rw in rows:\n q = quota_order_number(rw[0], rw[1], rw[2], rw[3])\n self.quota_order_number_list.append(q)\n\n def get_quota_descriptions(self):\n self.d(\"Getting UK quota descriptions\")\n self.quota_description_list = []\n with open(self.QUOTA_DESCRIPTION_FILE) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n next(csv_reader, None)\n for row in csv_reader:\n quota_order_number_id = row[0]\n description = row[1]\n\n obj = quota_description(quota_order_number_id, description)\n self.quota_description_list.append(obj)\n\n def get_quota_balances(self):\n self.d(\"Getting UK quota balances\")\n self.quota_balance_list = []\n with open(self.BALANCE_FILE) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n next(csv_reader, None)\n for row in csv_reader:\n quota_order_number_id = row[0]\n country = row[1]\n method = row[2]\n y1_balance = row[9]\n yx_balance = row[10]\n yx_start = row[11]\n\n obj = quota_balance(quota_order_number_id, country, method, y1_balance, yx_balance, yx_start)\n self.quota_balance_list.append(obj)\n\n def get_minimum_sids(self):\n with open(self.CONFIG_FILE, 'r') as f:\n my_dict = json.load(f)\n\n min_list = my_dict['minimum_sids'][self.DBASE]\n\n self.last_additional_code_description_period_sid = self.larger(self.get_scalar(\"SELECT MAX(additional_code_description_period_sid) FROM additional_code_description_periods_oplog;\"), min_list['additional.code.description.periods']) + 1\n self.last_additional_code_sid = self.larger(self.get_scalar(\"SELECT MAX(additional_code_sid) FROM additional_codes_oplog;\"), min_list['additional.codes']) + 1\n\n self.last_certificate_description_period_sid = self.larger(self.get_scalar(\"SELECT MAX(certificate_description_period_sid) FROM certificate_description_periods_oplog;\"), min_list['certificate.description.periods']) + 1\n self.last_footnote_description_period_sid = self.larger(self.get_scalar(\"SELECT MAX(footnote_description_period_sid) FROM footnote_description_periods_oplog;\"), min_list['footnote.description.periods']) + 1\n self.last_geographical_area_description_period_sid = self.larger(self.get_scalar(\"SELECT MAX(geographical_area_description_period_sid) FROM geographical_area_description_periods_oplog;\"), min_list['geographical.area.description.periods']) + 1\n self.last_geographical_area_sid = self.larger(self.get_scalar(\"SELECT MAX(geographical_area_sid) FROM geographical_areas_oplog;\"), min_list['geographical.areas']) + 1\n\n self.last_goods_nomenclature_sid = self.larger(self.get_scalar(\"SELECT MAX(goods_nomenclature_sid) FROM goods_nomenclatures_oplog;\"), min_list['goods.nomenclature']) + 1\n self.last_goods_nomenclature_indent_sid = self.larger(self.get_scalar(\"SELECT MAX(goods_nomenclature_indent_sid) FROM goods_nomenclature_indents_oplog;\"), min_list['goods.nomenclature.indents']) + 1\n self.last_goods_nomenclature_description_period_sid = self.larger(self.get_scalar(\"SELECT MAX(goods_nomenclature_description_period_sid) FROM goods_nomenclature_description_periods_oplog;\"), min_list['goods.nomenclature.description.periods']) + 1\n\n self.last_measure_sid = self.larger(self.get_scalar(\"SELECT MAX(measure_sid) FROM measures_oplog;\"), min_list['measures']) + 1\n self.last_measure_condition_sid = self.larger(self.get_scalar(\"SELECT MAX(measure_condition_sid) FROM measure_conditions_oplog\"), min_list['measure.conditions']) + 1\n\n self.last_quota_order_number_sid = self.larger(self.get_scalar(\"SELECT MAX(quota_order_number_sid) FROM quota_order_numbers_oplog\"), min_list['quota.order.numbers']) + 1\n self.last_quota_order_number_origin_sid = self.larger(self.get_scalar(\"SELECT MAX(quota_order_number_origin_sid) FROM quota_order_number_origins_oplog\"), min_list['quota.order.number.origins']) + 1\n self.last_quota_definition_sid = self.larger(self.get_scalar(\"SELECT MAX(quota_definition_sid) FROM quota_definitions_oplog\"), min_list['quota.definitions']) + 1\n self.last_quota_suspension_period_sid = self.larger(self.get_scalar(\"SELECT MAX(quota_suspension_period_sid) FROM quota_suspension_periods_oplog\"), min_list['quota.suspension.periods']) + 1\n self.last_quota_blocking_period_sid = self.larger(self.get_scalar(\"SELECT MAX(quota_blocking_period_sid) FROM quota_blocking_periods_oplog\"), min_list['quota.blocking.periods']) + 1\n\n def get_mfns(self):\n self.mfn_master_list = []\n with open(self.MFN_COMPONENTS_FILE) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\", quoting=csv.QUOTE_ALL)\n for row in csv_reader:\n if len(row) > 0:\n goods_nomenclature_item_id = row[0]\n duty_expression_id = row[1]\n duty_amount = float(row[2])\n monetary_unit_code = row[3]\n measurement_unit_code = row[4]\n measurement_unit_qualifier_code = row[5]\n measure_sid = -1\n\n obj = measure_component(measure_sid, duty_expression_id, duty_amount, monetary_unit_code,\n measurement_unit_code, measurement_unit_qualifier_code, goods_nomenclature_item_id)\n self.mfn_master_list.append(obj)\n\n def get_config(self):\n # Get global config items\n with open(self.CONFIG_FILE, 'r') as f:\n my_dict = json.load(f)\n\n self.remove_SIVs = fn.mbool2(my_dict['remove_SIVs'])\n self.remove_Meursing = fn.mbool2(my_dict['remove_Meursing'])\n self.critical_date = datetime.strptime(my_dict['critical_date'], '%Y-%m-%d')\n self.critical_date_plus_one = self.critical_date + timedelta(days=1)\n\n self.critical_date_string = datetime.strftime(self.critical_date, '%Y-%m-%d')\n self.critical_date_plus_one_string = datetime.strftime(self.critical_date_plus_one, '%Y-%m-%d')\n\n \"\"\"\n print(self.critical_date)\n print(self.critical_date_plus_one)\n print(type(self.critical_date))\n print(type(self.critical_date_plus_one))\n\n print(self.critical_date_string)\n print(self.critical_date_plus_one_string)\n print(type(self.critical_date_string))\n print(type(self.critical_date_plus_one_string))\n sys.exit()\n \"\"\"\n\n self.DBASE = my_dict['dbase']\n\n self.p = my_dict['p']\n self.DBASE_MIGRATE_MEASURES = my_dict['dbase_migrate_measures']\n\n self.connect()\n self.debug = fn.mbool2(my_dict['debug'])\n self.last_transaction_id = my_dict[\"minimum_sids\"][self.DBASE][\"last_transaction_id\"]\n self.transaction_id = self.last_transaction_id + 1\n self.meursing_list = my_dict['meursing_list'].split(\", \")\n\n # Get local config items\n with open(self.CONFIG_FILE_LOCAL, 'r') as f:\n my_dict = json.load(f)\n self.bulk_migrations_list = my_dict['bulk_migrations']\n\n self.preferential_measure_list = my_dict['measure_types']['preferential']\n self.all_country_profiles = my_dict['country_profiles']\n\n def set_config(self):\n jsonFile = open(self.CONFIG_FILE, \"r\") # Open the JSON file for reading\n data = json.load(jsonFile) # Read the JSON into the buffer\n jsonFile.close() # Close the JSON file\n\n data[\"minimum_sids\"][self.DBASE][\"last_transaction_id\"] = self.transaction_id\n data[\"minimum_sids\"][self.DBASE][\"measures\"] = self.last_measure_sid\n data[\"minimum_sids\"][self.DBASE][\"measure.conditions\"] = self.last_measure_condition_sid\n\n # print(self.last_measure_sid)\n\n jsonFile = open(self.CONFIG_FILE, \"w+\")\n jsonFile.write(json.dumps(data, indent=4, sort_keys=True))\n jsonFile.close()\n\n def larger(self, a, b):\n if a > b:\n return a\n else:\n return b\n\n def get_scalar(self, sql):\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n # l = list(rows)\n return (rows[0][0])\n\n def get_arguments(self):\n # Argument 0 is the script\n # Argument 1 is scope type (measuretype, regulation)\n # Argument 2 is action type (terminate or split)\n # Argument 3 is measure type(s) or regulation ID, dependent on argument 2\n # Argument 4 is future regulation ID\n # Argument 5 is the country limiter (if required)\n\n # This function also determines the output filename\n\n # Initialise\n self.future_regulation_id = \"\"\n self.scope = \"\"\n self.action_string = \"\"\n self.measure_type_list = []\n self.regulation_string = \"\"\n self.country_profile = \"\"\n self.output_filename = \"\"\n\n # These are special cases that allow for shortcuts across multiple measure types\n self.credibility_list = ['430', '431', '485', '481', '482', '483']\n self.mfn_list = ['103', '105']\n self.quota_list = ['122', '123', '143', '146']\n self.supplementary_list = ['109', '110']\n self.suspension_list = ['112', '115', '117', '119', '141']\n self.surveillance_list = ['442', '447']\n self.agri_list = ['489', '490', '651', '652', '653', '654', '672', '673', '674']\n self.remedies_list = ['570', '566', '565', '564', '561', '555', '553', '551']\n self.omit_measure_types_list = self.credibility_list + self.supplementary_list + self.suspension_list + self.quota_list\n\n if \"quota\" in sys.argv[0]: # quotas\n self.get_quota_parameters()\n\n elif sys.argv[0] == \"migrate_measures.py\": # We are migrating measures\n # Get scope type - this is specified in the 1st argument and could be \"measure types\", \"regulation\" or \"country\"\n if (len(sys.argv) > 1):\n if sys.argv[1] in (\"measure_types\", \"measuretypes\", \"measuretype\", \"measure_type\", \"m\"): # measures\n self.scope = \"measuretypes\"\n elif sys.argv[1] in (\"regulations\", \"regulation\", \"r\", \"rb\"):\t\t# regulations\n self.scope = \"regulation\"\n elif sys.argv[1] in (\"country\", \"preferential\", \"c\"):\t\t# by country's preferential agreement\n self.scope = \"country\"\n\n # Get action type - this can be one of two things, either terminate (t) or restart (r)\n # In the case of terminate, the measures will be stopped, but not restarted after Brexit\n # in the case opf restart, the measures will be stopped and then restatred after Brexit\n\n self.action_verbatim = \"\"\n if (len(sys.argv) > 2): # action\n if sys.argv[2] in (\"terminate\", \"term\", \"t\"):\n self.action_string = \"terminate\"\n elif sys.argv[2] in (\"split\", \"continue\", \"restart\", \"r\", \"s\", \"c\", \"n\", \"newstart\"):\n self.action_string = \"restart\"\n self.action_verbatim = sys.argv[2]\n\n if self.scope == \"country\":\n self.get_migrate_country_parameters()\n elif self.scope == \"measuretypes\":\n self.get_migrate_measure_type_parameters()\n elif self.scope == \"regulation\":\n self.get_migrate_regulation_parameters()\n\n elif sys.argv[0] == \"bulk_migrate.py\": # We are migrating regulations en masse\n # This is suitable for things like Trade Remedies and Import and Export Control\n self.scope = \"bulk_migration\"\n if (len(sys.argv) > 1):\n self.bulk_migration_profile = sys.argv[1]\n else:\n print(\"No bulk migration profile found\")\n sys.exit()\n\n # print the parameters to the screen\n if self.scope != \"bulk_migration\":\n self.d(\"Parameters\", False)\n self.d(\"Using database: \" + self.DBASE)\n self.d(\"Scope string: \" + self.scope)\n self.d(\"Action string: \" + self.action_string)\n self.d(\"Country string: \" + self.country_profile)\n self.d(\"Regulation string: \" + self.regulation_string)\n self.d(\"Measure type list: \" + str(self.measure_type_list))\n self.d(\"Future regulation: \" + self.future_regulation_id)\n self.d(\"Output filename: \" + self.output_filename)\n self.d(\"Output folder: \" + self.XML_OUT_DIR)\n print(\"\\n\")\n\n if self.override_prompt is False:\n ret = fn.yes_or_no(\"Do you want to continue?\")\n if not (ret):\n sys.exit()\n\n def get_migrate_regulation_parameters(self):\n # Get today's date - this will be appended to the output filename\n d = datetime.now()\n d2 = d.strftime(\"%Y-%m-%d\")\n self.regulation_string = sys.argv[3]\n self.measure_type_string = \"\"\n\n # Get the future regulation ID\n if (len(sys.argv) > 4):\n self.future_regulation_id = sys.argv[4].strip()\n if len(self.future_regulation_id) != 8:\n print(\"Erroneous future regulation string - please fix\")\n sys.exit()\n\n # Get the optional final parameter (measure type - needed for Trade Remedies)\n regulation_string2 = self.regulation_string\n if (len(sys.argv) > 5):\n self.measure_type_string = sys.argv[5].strip()\n regulation_string2 += \"_mt_\" + self.measure_type_string\n\n # Set the filename for measure exports\n if self.action_string == \"terminate\":\n self.output_filename = self.scope + \"_end_\" + regulation_string2 + \".xml\"\n else:\n self.output_filename = self.scope + \"_end_\" + regulation_string2 + \"_start_\" + self.future_regulation_id + \".xml\"\n\n self.country_profile = \"\"\n\n # If this script is being run from the bulk migration script,\n # then it needs to be silent, i.e. suppress the \"Are you sure?\" prompt.\n # We also need to be able to recompile the individual files back into a\n # single XML file at the end, therefore we need to log the filenames that are created.\n if sys.argv[1] == \"rb\":\n self.override_prompt = True\n self.bulk_log()\n\n def bulk_log_delete(self):\n try:\n os.remove(self.BULK_LOG_FILE)\n except:\n pass\n f = open(self.BULK_LOG_FILE, \"w+\")\n\n def bulk_log(self):\n f = open(self.BULK_LOG_FILE, \"a+\")\n f.write(self.output_filename + \"\\n\")\n f.close()\n\n def bulk_recompile(self):\n contents = \"\"\n print(\"Recompiling individual files into single file\")\n print(\"Reading logs from file\", self.BULK_LOG_FILE)\n merged_filename = \"bulk_migration_\" + self.bulk_migration_profile + \".xml\"\n merged_filename2 = os.path.join(self.XML_OUT_DIR, merged_filename)\n files = []\n f = open(self.BULK_LOG_FILE, \"r\")\n lines = f.readlines()\n for line in lines:\n files.append(line.replace(\"\\n\", \"\"))\n f.close()\n\n # Business rules for recombining a file\n # If there is only a single file, then just use the file in its entirety, do not strip any part\n\n buffer = \"\"\n tally = -1\n file_count = len(files)\n\n # Need to go through every file in the list and strip out those that do not exist\n for i in range(file_count - 1, -1, -1):\n file = files[i]\n file2 = os.path.join(self.XML_OUT_DIR, file)\n if not os.path.isfile(file2):\n files.pop(i)\n\n file_count = len(files)\n for file in files:\n file2 = os.path.join(self.XML_OUT_DIR, file)\n if os.path.isfile(file2):\n tally += 1\n f = open(file2, \"r\")\n contents = f.read()\n if tally == 0:\n if file_count > 1:\n contents = contents.replace(\"\", \"\")\n elif tally == file_count - 1:\n contents = contents.replace('', \"\")\n contents = contents.replace('', \"\")\n else:\n contents = contents.replace(\"\", \"\")\n contents = contents.replace('', \"\")\n contents = contents.replace('', \"\")\n\n buffer += contents\n if contents.find(\"\") == -1:\n contents += \"\\n\"\n\n f = open(merged_filename2, \"w+\")\n f.write(buffer)\n f.close()\n\n for file in files:\n file2 = os.path.join(self.XML_OUT_DIR, file)\n if os.path.isfile(file2):\n os.remove(file2)\n print(\"Merged file written to\", merged_filename)\n self.validate(merged_filename)\n self.output_filename = os.path.join(self.XML_OUT_DIR, merged_filename)\n self.copy_to_custom_import_folder()\n sys.exit()\n\n def get_migrate_measure_type_parameters(self):\n # Get the date - this will be appended to the output filename\n d = datetime.now()\n d2 = d.strftime(\"%Y-%m-%d\")\n\n # Get the measure types that have been specified, or more likely the shortcut\n if (len(sys.argv) > 3):\n self.measure_type_string = sys.argv[3].strip()\n if len(self.measure_type_string) == 0:\n print(\"You have opted to migrate by measure type, but not specified the measure type\")\n sys.exit()\n\n if self.measure_type_string in (\"credibility\", \"credibilitychecks\", \"cred\"): # credibility checks\n self.measure_type_list = self.credibility_list\n\n elif self.measure_type_string in (\"supp\", \"supplementaryunits\", \"sup\"):\t\t\t# supplementary units\n self.measure_type_list = self.supplementary_list\n\n elif self.measure_type_string in (\"quota\", \"quotas\", \"wto_quotas\", \"wto\", \"q\"): # quotas\n self.measure_type_list = self.quota_list\n\n elif self.measure_type_string in (\"mfn\"):\t\t\t\t\t\t\t\t\t\t# MFNs\n self.measure_type_list = self.mfn_list\n\n elif self.measure_type_string in (\"suspension\", \"suspensions\", \"susp\"):\t\t\t# suspensions\n self.measure_type_list = self.suspension_list\n\n elif self.measure_type_string in (\"surveillance\", \"surv\"):\t\t\t\t\t\t# surveillance\n self.measure_type_list = self.surveillance_list\n\n elif self.measure_type_string in (\"agri\"):\t\t\t\t\t\t\t\t\t\t# agricultural safeguards\n self.measure_type_list = self.agri_list\n\n elif self.measure_type_string in (\"remedies\"):\t\t\t\t\t\t\t\t\t# trade remedies unwanted measures\n self.measure_type_list = self.remedies_list\n\n else:\n self.measure_type_list = []\n self.measure_type_list.append(self.measure_type_string)\n\n # Get the future regulation ID\n if (len(sys.argv) > 4):\n self.future_regulation_id = sys.argv[4].strip()\n if len(self.future_regulation_id) != 8:\n print(\"Erroneous future regulation string - please fix\")\n sys.exit()\n\n # Set the filename for measure exports\n if self.action_string == \"terminate\":\n # self.output_filename = self.scope + \"_end_\" + self.measure_type_string + \"_\" + d2 + \".xml\"\n self.output_filename = self.scope + \"_end_\" + self.measure_type_string + \".xml\"\n else:\n # self.output_filename = self.scope + \"_end_\" + self.measure_type_string + \"_new_regulation_\" + self.future_regulation_id + \"_\" + d2 + \".xml\"\n self.output_filename = self.scope + \"_end_\" + self.measure_type_string + \"_new_regulation_\" + self.future_regulation_id + \".xml\"\n\n def get_migrate_country_parameters(self):\n if (len(sys.argv) > 3):\n self.country_profile = sys.argv[3].strip()\n self.get_country_list()\n else:\n print(\"No country specified - quitting\")\n sys.exit()\n\n self.output_filename = self.scope + \"_\" + self.action_string + \"_\" + self.country_profile\n\n if (len(sys.argv) > 4):\n self.future_regulation_id = sys.argv[4].strip()\n self.output_filename += \"_\" + self.future_regulation_id\n if len(self.future_regulation_id) != 8:\n print(\"Erroneous future regulation string - please fix\")\n sys.exit()\n else:\n if self.action_string != \"terminate\":\n print(\"No 'to-be' regulation specified - quitting\")\n sys.exit()\n\n if (len(sys.argv) > 5):\n if self.action_verbatim not in (\"n\", \"newstart\"):\n print(\"Error - cannot terminate or migrate measures when a destination country is specified in parameter 5\")\n sys.exit()\n self.destination_geographical_area_id = sys.argv[5].strip()\n self.get_geographical_area_sid()\n self.output_filename += \"_\" + self.destination_geographical_area_id\n\n self.output_filename += \".xml\"\n\n def get_geographical_area_sid(self):\n sql = \"\"\"\n select geographical_area_sid\n from geographical_area_descriptions where geographical_area_id = 'LI'\n order by geographical_area_description_period_sid desc limit 1\n \"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n if len(rows) > 0:\n rw = rows[0]\n self.destination_geographical_area_sid = rw[0]\n\n def get_quota_parameters(self):\n self.scope = \"quotas\"\n if sys.argv[0] == \"terminate_quota_definitions.py\":\n self.action_string = \"terminate\"\n self.output_filename = \"terminate_quota_definitions.xml\"\n elif sys.argv[0] == \"create_new_fcfs_quotas.py\":\n self.action_string = \"create\"\n self.output_filename = \"create_quota_definitions.xml\"\n\n self.action_string = \"create\"\n self.country_profile = \"\"\n self.regulation_string = \"\"\n self.measure_type_list = \"\"\n self.future_regulation_id = \"\"\n\n def get_country_list(self):\n try:\n self.country_codes = self.all_country_profiles[self.country_profile][\"country_codes\"]\n except:\n self.country_codes = []\n self.country_codes.append(self.country_profile)\n\n def get_templates(self):\n # Get template - envelope\n filename = os.path.join(self.TEMPLATE_DIR, \"envelope.xml\")\n file = open(filename, mode='r')\n self.template_envelope = file.read()\n file.close()\n\n # Get template - transaction\n filename = os.path.join(self.TEMPLATE_DIR, \"transaction.xml\")\n file = open(filename, mode='r')\n self.template_transaction = file.read()\n file.close()\n\n # Get template - measure\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.xml\")\n file = open(filename, mode='r')\n self.template_measure = file.read()\n file.close()\n\n # Get template - measure.component\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.component.xml\")\n file = open(filename, mode='r')\n self.template_measure_component = file.read()\n file.close()\n\n # Get template - measure.condition\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.condition.xml\")\n file = open(filename, mode='r')\n self.template_measure_condition = file.read()\n file.close()\n\n # Get template - measure.condition.component\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.condition.component.xml\")\n file = open(filename, mode='r')\n self.template_measure_condition_component = file.read()\n file.close()\n\n # Get template - quota.definition\n filename = os.path.join(self.TEMPLATE_DIR, \"quota.definition.xml\")\n file = open(filename, mode='r')\n self.template_quota_definition = file.read()\n file.close()\n\n # Get template - quota.association\n filename = os.path.join(self.TEMPLATE_DIR, \"quota.association.xml\")\n file = open(filename, mode='r')\n self.template_quota_association = file.read()\n file.close()\n\n # Get template - quota.association.insert\n filename = os.path.join(self.TEMPLATE_DIR, \"quota.association.insert.xml\")\n file = open(filename, mode='r')\n self.template_quota_association_insert = file.read()\n file.close()\n\n # Get template - quota.suspension.period\n filename = os.path.join(self.TEMPLATE_DIR, \"quota.suspension.period.xml\")\n file = open(filename, mode='r')\n self.template_quota_suspension_period = file.read()\n file.close()\n\n # Get template - quota.blocking.period\n filename = os.path.join(self.TEMPLATE_DIR, \"quota.blocking.period.xml\")\n file = open(filename, mode='r')\n self.template_quota_blocking_period = file.read()\n file.close()\n\n # Get template - measure.excluded.geographical.area\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.excluded.geographical.area.xml\")\n file = open(filename, mode='r')\n self.template_measure_excluded_geographical_area = file.read()\n file.close()\n\n # Get template - footnote.association.measure\n filename = os.path.join(self.TEMPLATE_DIR, \"footnote.association.measure.xml\")\n file = open(filename, mode='r')\n self.template_footnote_association_measure = file.read()\n file.close()\n\n # Get template - measure_partial_temporary_stop\n filename = os.path.join(self.TEMPLATE_DIR, \"measure.partial.temporary.stop.xml\")\n file = open(filename, mode='r')\n self.template_measure_partial_temporary_stop = file.read()\n file.close()\n\n def get_future_quota_definitions(self):\n # Get all future definitions, which will be killed later\n sql = \"\"\"SELECT quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description\n FROM quota_definitions WHERE validity_start_date >= '\"\"\" + self.critical_date_string + \"\"\"'\n ORDER BY quota_order_number_id\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n self.quota_definition_list = []\n for row in rows:\n quota_definition_sid = row[0]\n quota_order_number_id = row[1]\n validity_start_date = row[2]\n validity_end_date = row[3]\n quota_order_number_sid = row[4]\n volume = row[5]\n initial_volume = row[6]\n measurement_unit_code = row[7]\n maximum_precision = row[8]\n critical_state = row[9]\n critical_threshold = row[10]\n monetary_unit_code = row[11]\n measurement_unit_qualifier_code = row[12]\n description = row[13]\n\n q = quota_definition(quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description, \"delete\")\n self.quota_definition_list.append(q)\n\n def get_current_quota_definitions(self):\n # Get all current quota definitions, which we will work out if they need to be\n # recreated in other scripts\n # we are using all definitions that started on 1st Jan 2018 or later as examples\n # The presumption will be that there will have been a truncation and deltion run prior to this\n # of any quota definitions that areeither start after brexit or straddle brexit\n\n # When looking ot create future quota definitions, don't forget to check what quota definitions\n # may not have been created by the EU yet - it's conceivable that we are still waiting\n # for definitions to come through, so we will be creating some from extrapolation of old patterns\n\n self.quota_definition_sid_mapping_list = []\n\n sql = \"\"\"SELECT quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description\n FROM quota_definitions WHERE validity_start_date >= '2018-01-01'\n ORDER BY quota_order_number_id, validity_start_date;\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n self.quota_definition_list = []\n for row in rows:\n quota_definition_sid = row[0]\n quota_order_number_id = row[1]\n validity_start_date = row[2]\n validity_end_date = row[3]\n quota_order_number_sid = row[4]\n volume = row[5]\n initial_volume = row[6]\n measurement_unit_code = row[7]\n maximum_precision = row[8]\n critical_state = row[9]\n critical_threshold = row[10]\n monetary_unit_code = row[11]\n measurement_unit_qualifier_code = row[12]\n description = row[13]\n\n q = quota_definition(quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description, \"insert\")\n self.quota_definition_list.append(q)\n\n # Assign the definitions to the quota order numbers, such that can then go round the data once more\n # and work out what the future definitions are meant to be - in most cases it will be simple\n # but there will be complex cases, where we need to extrapolate from old data\n\n self.d(\"Assigning quota definitions to quota order numbers\")\n p = ProgressBar(len(self.quota_order_number_list), sys.stdout)\n cnt = 1\n start = 0\n for qon in self.quota_order_number_list:\n for i in range(start, len(self.quota_definition_list)):\n qd = self.quota_definition_list[i]\n if (qon.quota_order_number_id == qd.quota_order_number_id):\n qon.quota_definition_list.append(qd)\n start = i\n\n p.print_progress(cnt)\n cnt += 1\n\n def define_future_quota_definitions(self):\n # Check if there are any items with a missing quota_order_number_sid\n # as these break the extract when the data is missing\n # Insert from the quota order number table, if found\n for qon in self.quota_order_number_list:\n for qd in qon.quota_definition_list:\n if qd.quota_order_number_sid is None:\n qd.quota_order_number_sid = qon.quota_order_number_sid\n\n # Then work out what sort of period types we have and how many definitions to create.\n # Only after having done that should we look at creating the data\n for qon in self.quota_order_number_list:\n if len(qon.quota_definition_list) == 1:\n qon.single_definition_in_year = True\n else:\n # If the period type of any of the definitions is Annual, then there is only one in a year\n for qd in qon.quota_definition_list:\n if qd.period_type == \"Annual\":\n qon.single_definition_in_year = True\n break\n\n if qon.single_definition_in_year is False:\n if len(qon.quota_definition_list) == 2:\n day1 = qon.quota_definition_list[0].validity_start_day\n day2 = qon.quota_definition_list[1].validity_start_day\n month1 = qon.quota_definition_list[0].validity_start_month\n month2 = qon.quota_definition_list[1].validity_start_month\n if (day1 == day2) and (month1 == month2):\n qon.single_definition_in_year = True\n elif len(qon.quota_definition_list) == 0:\n qon.omit = True\n else:\n # print(\"More than 2 definitions\", qon.quota_order_number_id)\n # There only actually seem to be three of these, as follows\n # 091104 = tomatoes\n # 091193 = beef\n # 092202 = beef\n # All the future data is there, so there is no work to do\n pass\n\n # Check if the quota is an annual quota: if so, then there can only be one definition in a year\n # If so, then delete all the other definitions from the future association list\n\n for qon in self.quota_order_number_list:\n if qon.single_definition_in_year is True:\n if len(qon.quota_definition_list) > 1:\n # Delete all but the latest quota definition from the quota order number\n # If we have discerned already that this is a quota with a single definition\n # in a year\n for i in range(0, len(qon.quota_definition_list) - 1):\n del qon.quota_definition_list[i]\n else:\n pass\n\n for qon in self.quota_order_number_list:\n if len(qon.quota_definition_list) == 1:\n qd = qon.quota_definition_list[0]\n if qd.validity_start_date >= self.critical_date_plus_one:\n # If the start date of the definition is in the future after Brexit, then leave it\n # and its end date alone without modification\n # print(qon.quota_order_number_id, \"Found a definition that is in the future, so leaving\")\n pass\n elif (qd.validity_start_date < self.critical_date_plus_one) and (qd.validity_end_date > self.critical_date_plus_one):\n # print(qon.quota_order_number_id, \"Found a definition that straddles Brexit, so amending\")\n qd.validity_start_date = self.critical_date_plus_one\n elif qd.validity_start_date < self.critical_date_plus_one:\n # print(qon.quota_order_number_id, qd.validity_start_date, qd.validity_end_date)\n # print(qon.quota_order_number_id, \"Found a definition that fully precedes Brexit, so deleting\")\n qon.omit = True\n # qd.validity_start_date = self.critical_date_plus_one\n else:\n for qd in qon.quota_definition_list:\n if qd.validity_start_date >= self.critical_date_plus_one:\n # If the start date of the definition is in the future after Brexit, then leave it\n # and its end date alone without modification\n # print(qon.quota_order_number_id, \"Found a definition that is in the future, so leaving\")\n pass\n elif (qd.validity_start_date < self.critical_date_plus_one) and (qd.validity_end_date > self.critical_date_plus_one):\n # print(qon.quota_order_number_id, \"Found a definition that straddles Brexit, so amending\")\n qd.validity_start_date = self.critical_date_plus_one\n elif qd.validity_start_date < self.critical_date_plus_one:\n # print(qon.quota_order_number_id, qd.validity_start_date, qd.validity_end_date)\n # print(qon.quota_order_number_id, \"Found a definition that fully precedes Brexit, so deleting\")\n qd.omit = True\n # qd.validity_start_date = self.critical_date_plus_one\n\n # Now get the balances from the new balance file\n print(\"\\n\\n\")\n self.d(\"Inserting UK quota balances\")\n p = ProgressBar(len(self.quota_order_number_list), sys.stdout)\n cnt = 1\n for qon in self.quota_order_number_list:\n if qon.omit is False:\n for qd in qon.quota_definition_list:\n if qd.omit is False:\n qd.definition = \"DIT will insert this here - need to get a list somewhere, innit\"\n # print(qon.quota_order_number_id, qd.validity_start_date, qd.validity_end_date)\n for bal in self.quota_balance_list:\n d2 = datetime.strptime(str(qd.validity_start_date), '%Y-%m-%d %H:%M:%S')\n if (bal.quota_order_number_id == qon.quota_order_number_id):\n qd.initial_volume = bal.y1_balance\n qd.volume = bal.y1_balance\n qd.critical_state = \"Y\"\n qd.action = \"insert\"\n break\n p.print_progress(cnt)\n cnt += 1\n\n def get_straddling_quota_definitions(self, action):\n # Get all future definitions, which will be killed later\n sql = \"\"\"SELECT quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description\n FROM quota_definitions WHERE validity_start_date <= '\"\"\" + self.critical_date_string + \"\"\"' AND validity_end_date >= '\"\"\" + self.critical_date_plus_one_string + \"\"\"'\n ORDER BY quota_order_number_id\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n self.quota_definition_list = []\n for row in rows:\n quota_definition_sid = row[0]\n quota_order_number_id = row[1]\n validity_start_date = row[2]\n validity_end_date = row[3]\n quota_order_number_sid = row[4]\n volume = row[5]\n initial_volume = row[6]\n measurement_unit_code = row[7]\n maximum_precision = row[8]\n critical_state = row[9]\n critical_threshold = row[10]\n monetary_unit_code = row[11]\n measurement_unit_qualifier_code = row[12]\n description = row[13]\n\n q = quota_definition(quota_definition_sid, quota_order_number_id, validity_start_date, validity_end_date, quota_order_number_sid, volume,\n initial_volume, measurement_unit_code, maximum_precision, critical_state, critical_threshold, monetary_unit_code,\n measurement_unit_qualifier_code, description, action)\n self.quota_definition_list.append(q)\n\n def kill_future_associations(self):\n self.content += \"\\n\"\n for obj in self.quota_association_list:\n self.content += obj.xml()\n self.content += \"\\n\"\n\n def kill_future_quota_definitions(self):\n self.content += \"\\n\"\n for obj in self.quota_definition_list:\n self.content += obj.xml()\n self.content += \"\\n\"\n\n def truncate_straddling_quota_definitions(self):\n self.content += \"\\n\"\n for obj in self.quota_definition_list:\n self.content += obj.xml()\n self.content += \"\\n\"\n\n def insert_straddling_quota_definitions(self):\n for obj in self.quota_definition_list:\n obj.validity_start_date = self.critical_date_plus_one\n self.content += obj.xml()\n\n def write_uk_future_quota_definitions(self):\n for qon in self.quota_order_number_list:\n if qon.omit is False:\n for obj in qon.quota_definition_list:\n if obj.omit is False:\n self.content += obj.xml()\n\n def write_uk_future_quota_associations(self):\n for qon in self.quota_order_number_list:\n if qon.omit is False:\n for qd in qon.quota_definition_list:\n if qd.omit is False:\n for assoc in qd.quota_association_list:\n self.content += assoc.xml()\n\n def get_associations(self):\n self.d(\"Getting quota associations\")\n sql = \"\"\"SELECT main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient FROM\n quota_associations WHERE main_quota_definition_sid IN (\"\"\" + self.definition_clause + \"\"\")\n OR sub_quota_definition_sid IN (\"\"\" + self.definition_clause + \"\"\")\n ORDER BY 1, 2;\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.quota_association_list = []\n for item in rows:\n main_quota_definition_sid = item[0]\n sub_quota_definition_sid = item[1]\n relation_type = item[2]\n coefficient = item[3]\n\n obj = quota_association(main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient)\n self.quota_association_list.append(obj)\n\n self.d(\"Assigning quota associations to quota definitions\")\n p = ProgressBar(len(self.quota_association_list), sys.stdout)\n cnt = 1\n start = 0\n for a in self.quota_association_list:\n for i in range(start, len(self.quota_definition_list_combined)):\n q = self.quota_definition_list_combined[i]\n if (a.main_quota_definition_sid == q.quota_definition_sid) or (a.sub_quota_definition_sid == q.quota_definition_sid):\n q.quota_association_list.append(a)\n start = i\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_current_quota_associations(self):\n self.d(\"Getting future quota associations, to be deleted\")\n sql = \"\"\"SELECT DISTINCT main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient FROM quota_associations\n WHERE main_quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '2018-01-01')\n OR sub_quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '2018-01-01')\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.quota_association_list = []\n for item in rows:\n main_quota_definition_sid = item[0]\n sub_quota_definition_sid = item[1]\n relation_type = item[2]\n coefficient = item[3]\n\n obj = quota_association(main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient, \"insert\")\n self.quota_association_list.append(obj)\n\n self.d(\"Assigning quota associations to quota definitions\")\n p = ProgressBar(len(self.quota_association_list), sys.stdout)\n cnt = 1\n start = 0\n for assoc in self.quota_association_list:\n for i in range(start, len(self.quota_definition_list)):\n qd = self.quota_definition_list[i]\n if (assoc.main_quota_definition_sid == qd.quota_definition_sid) or (assoc.sub_quota_definition_sid == qd.quota_definition_sid):\n qd.quota_association_list.append(assoc)\n start = i\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_future_quota_associations(self):\n self.d(\"Getting future quota associations, to be deleted\")\n sql = \"\"\"SELECT DISTINCT main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient FROM quota_associations\n WHERE main_quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '\"\"\" + self.critical_date_string + \"\"\"')\n OR sub_quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '\"\"\" + self.critical_date_string + \"\"\"')\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.quota_association_list = []\n for item in rows:\n main_quota_definition_sid = item[0]\n sub_quota_definition_sid = item[1]\n relation_type = item[2]\n coefficient = item[3]\n\n obj = quota_association(main_quota_definition_sid, sub_quota_definition_sid, relation_type, coefficient, \"delete\")\n self.quota_association_list.append(obj)\n\n self.d(\"Assigning quota associations to quota definitions\")\n p = ProgressBar(len(self.quota_association_list), sys.stdout)\n cnt = 1\n start = 0\n for a in self.quota_association_list:\n for i in range(start, len(self.quota_definition_list)):\n q = self.quota_definition_list[i]\n if (a.main_quota_definition_sid == q.quota_definition_sid) or (a.sub_quota_definition_sid == q.quota_definition_sid):\n q.quota_association_list.append(a)\n start = i\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_future_quota_suspension_periods(self):\n self.d(\"Getting future quota suspensions, to be deleted\")\n sql = \"\"\"SELECT quota_suspension_period_sid, quota_definition_sid, suspension_start_date, suspension_end_date, description\n FROM quota_suspension_periods\n WHERE quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '\"\"\" + self.critical_date_string + \"\"\"')\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.quota_suspension_period_list = []\n for item in rows:\n quota_suspension_period_sid = item[0]\n quota_definition_sid = item[1]\n suspension_start_date = item[2]\n suspension_end_date = item[3]\n description = item[4]\n\n obj = quota_suspension_period(quota_suspension_period_sid, quota_definition_sid, suspension_start_date, suspension_end_date, description)\n self.quota_suspension_period_list.append(obj)\n\n self.d(\"Assigning quota suspension periods to quota definitions\")\n\n p = ProgressBar(len(self.quota_suspension_period_list), sys.stdout)\n cnt = 1\n start = 0\n for obj in self.quota_suspension_period_list:\n for i in range(start, len(self.quota_definition_list)):\n q = self.quota_definition_list[i]\n if obj.quota_definition_sid == q.quota_definition_sid:\n q.quota_suspension_period_list.append(obj)\n start = i\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_future_quota_blocking_periods(self):\n self.d(\"Getting future quota blockings, to be deleted\")\n sql = \"\"\"SELECT quota_blocking_period_sid, quota_definition_sid, blocking_start_date, blocking_end_date, blocking_period_type, description\n FROM quota_blocking_periods\n WHERE quota_definition_sid IN (SELECT quota_definition_sid FROM quota_definitions WHERE validity_start_date >= '\"\"\" + self.critical_date_string + \"\"\"')\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.quota_blocking_period_list = []\n for item in rows:\n quota_blocking_period_sid = item[0]\n quota_definition_sid = item[1]\n blocking_start_date = item[2]\n blocking_end_date = item[3]\n blocking_period_type = item[4]\n description = item[5]\n\n obj = quota_blocking_period(quota_blocking_period_sid, quota_definition_sid, blocking_start_date, blocking_end_date, blocking_period_type, description)\n self.quota_blocking_period_list.append(obj)\n\n self.d(\"Assigning quota blocking periods to quota definitions\")\n\n p = ProgressBar(len(self.quota_blocking_period_list), sys.stdout)\n cnt = 1\n start = 0\n for obj in self.quota_blocking_period_list:\n for i in range(start, len(self.quota_definition_list)):\n q = self.quota_definition_list[i]\n q.quota_blocking_period_list = []\n if obj.quota_definition_sid == q.quota_definition_sid:\n q.quota_blocking_period_list.append(obj)\n start = i\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def list_to_string(self, lst, data_type=\"string\"):\n s = \"\"\n if data_type == \"string\":\n for item in lst:\n s += \"'\" + item + \"', \"\n elif data_type == \"number\":\n for item in lst:\n s += item + \", \"\n s = s.strip()\n s = s.strip(\",\")\n return (s)\n\n def list_to_sql(self, my_list):\n s = \"\"\n if my_list != \"\":\n for o in my_list:\n s += \"'\" + o + \"', \"\n s = s.strip()\n s = s.strip(\",\")\n return (s)\n\n def list_to_tuple(self, my_list):\n s = tuple(my_list)\n return (s)\n\n def get_siv_measures(self):\n pass\n\n def get_measures(self):\n # Depending on the scope, this function retrieves all matching measures from the database\n # For quotas, it pulls back literally all quota measures (not sure this will stay)\n # for measure type, it retrieves all active measures of the specified type (e.g. usage in supp, cred)\n # for regulations, it brings back all active measures belonging to the regulation\n self.d(\"Deriving measures from database\", False)\n # Get the matching measures\n # dq (self.scope)\n country_clause = \"\"\n\n if self.scope == \"country\":\n self.my_geo_ids = tuple(self.country_codes)\n self.my_measure_types = tuple(self.preferential_measure_list)\n\n sql = \"\"\"select measure_sid, ordernumber, measure_type_id, m.validity_start_date, m.validity_end_date,\n geographical_area_id, m.goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, m.goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid,\n case\n when m.validity_end_date is null THEN 999\n else (1 + (TO_DATE(m.validity_end_date, 'YYYY-MM-DD') - TO_DATE(m.validity_start_date, 'YYYY-MM-DD')))\n end as measure_extent\n from ml.measures_real_end_dates m, goods_nomenclatures g\n where geographical_area_id IN %s\n and m.goods_nomenclature_item_id = g.goods_nomenclature_item_id\n and g.producline_suffix = '80'\n and measure_type_id IN %s\n --and m.validity_end_date is null\n and (m.validity_end_date is null or m.validity_start_date >= %s)\n and g.validity_end_date is null\n order BY measure_sid\n \"\"\"\n\n params = [\n self.my_geo_ids,\n self.my_measure_types,\n \"2018-01-01\"\n ]\n cur = self.conn.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n\n elif self.scope == \"quotas\":\n sql = \"\"\"SELECT measure_sid, ordernumber, measure_type_id, validity_start_date, validity_end_date,\n geographical_area_id, goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid, 999 as extent\n FROM ml.measures_real_end_dates m WHERE ordernumber IS NOT NULL\n and (validity_end_date is null or validity_end_date > '\"\"\" + self.critical_date.strftime(\"%Y-%m-%d\") + \"\"\"')\n ORDER BY measure_sid\n \"\"\"\n cur = self.conn.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n\n elif self.scope == \"measuretypes\":\n if self.measure_type_string in (\"agri\"):\n sql = \"\"\"\n SELECT measure_sid, ordernumber, measure_type_id, m.validity_start_date, m.validity_end_date,\n geographical_area_id, m.goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, m.goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid, 999 as extent\n FROM ml.measures_real_end_dates m left outer join goods_nomenclatures g\n on m.goods_nomenclature_item_id = g.goods_nomenclature_item_id\n WHERE measure_type_id IN (\"\"\" + self.list_to_string(self.measure_type_list) + \"\"\")\n and (g.producline_suffix = '80' or g.producline_suffix is null)\n and (g.validity_end_date > '\"\"\" + self.critical_date.strftime(\"%Y-%m-%d\") + \"\"\"' or g.validity_end_date is null)\n AND (m.validity_end_date is null or m.validity_end_date > '\"\"\" + self.critical_date.strftime(\"%Y-%m-%d\") + \"\"\"')\n ORDER BY measure_sid\n \"\"\"\n cur = self.conn.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n else:\n sql = \"\"\"\n SELECT measure_sid, ordernumber, measure_type_id, m.validity_start_date, m.validity_end_date,\n geographical_area_id, m.goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, m.goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid, 999 as extent\n FROM ml.measures_real_end_dates m, goods_nomenclatures g\n WHERE measure_type_id IN (\"\"\" + self.list_to_string(self.measure_type_list) + \"\"\")\n \"\"\" + country_clause + \"\"\"\n and m.goods_nomenclature_sid = g.goods_nomenclature_sid\n and g.producline_suffix = '80'\n and (g.validity_end_date > '\"\"\" + self.critical_date.strftime(\"%Y-%m-%d\") + \"\"\"' or g.validity_end_date is null)\n AND (m.validity_end_date is null or m.validity_end_date > '\"\"\" + self.critical_date.strftime(\"%Y-%m-%d\") + \"\"\"')\n ORDER BY measure_sid\n \"\"\"\n cur = self.conn.cursor()\n # cur.execute(sql, params)\n cur.execute(sql)\n rows = list(cur.fetchall())\n\n elif self.scope == \"regulation\":\n if \",\" in self.regulation_string:\n clause = \"AND measure_generating_regulation_id IN (\" + self.regulation_string + \") \"\n else:\n if len(self.regulation_string) == 7:\n clause = \"AND measure_generating_regulation_id like '\" + self.regulation_string + \"%' \"\n else:\n clause = \"AND measure_generating_regulation_id = '\" + self.regulation_string + \"' \"\n\n if self.measure_type_string != \"\":\n clause += \" AND measure_type_id = '\" + self.measure_type_string + \"'\"\n\n omit_measure_type_clause = \"\"\n for obj in self.omit_measure_types_list:\n omit_measure_type_clause += \"'\" + obj + \"', \"\n omit_measure_type_clause = omit_measure_type_clause.strip()\n omit_measure_type_clause = omit_measure_type_clause.strip(\",\")\n clause += \" AND measure_type_id NOT IN (\" + omit_measure_type_clause + \") \"\n\n sql = \"\"\"\n SELECT measure_sid, ordernumber, measure_type_id, m.validity_start_date, m.validity_end_date,\n geographical_area_id, m.goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, m.goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid, 999 as extent\n FROM ml.get_current_measures m, ml.goods_nomenclatures gn\n WHERE m.goods_nomenclature_item_id = gn.goods_nomenclature_item_id\n AND (gn.validity_end_date IS NULL OR gn.validity_end_date > CURRENT_DATE) \"\"\" + clause + country_clause + \"\"\"\n ORDER BY measure_sid\n \"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n # Transfer the items retrieved from the database into a Python list entitles \"measure_list\"\n self.d(\"Creating list of measures\")\n self.measure_list = []\n\n self.ignore_count = 0\n self.enddate_count = 0\n self.delete_count = 0\n self.recreate_count = 0\n\n for row in rows:\n measure_sid = row[0]\n ordernumber = row[1]\n measure_type_id = row[2]\n validity_start_date = row[3]\n validity_end_date = row[4]\n geographical_area_id = row[5]\n goods_nomenclature_item_id = row[6]\n additional_code_type_id = row[7]\n additional_code_id = row[8]\n reduction_indicator = row[9]\n measure_generating_regulation_role = row[10]\n measure_generating_regulation_id = row[11]\n justification_regulation_role = row[12]\n justification_regulation_id = row[13]\n stopped_flag = row[14]\n geographical_area_sid = row[15]\n goods_nomenclature_sid = row[16]\n additional_code_sid = row[17]\n export_refund_nomenclature_sid = row[18]\n extent = row[19]\n\n measure_object = measure(measure_sid, ordernumber, measure_type_id,\n validity_start_date, validity_end_date, geographical_area_id, goods_nomenclature_item_id,\n additional_code_type_id, additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid)\n\n self.measure_list.append(measure_object)\n\n if len(self.measure_list) == 0:\n self.d(\"No matching measures found - exiting\", False)\n sys.exit()\n\n # Write the state of play to the screen\n self.d(\"Found \" + str(len(self.measure_list)) + \" measures in total\")\n if self.action_string == \"terminate\":\n self.d(\"Found \" + str(self.enddate_count) + \" measures to end date (straddle Brexit)\")\n self.d(\"Found \" + str(self.ignore_count) + \" measures to ignore (end before Brexit)\")\n self.d(\"Found \" + str(self.delete_count) + \" measures to delete (start after Brexit)\\n\")\n else:\n self.d(\"Found \" + str(self.enddate_count) + \" measures to end date and recreate (straddle Brexit)\")\n self.d(\"Found \" + str(self.ignore_count) + \" measures to ignore (end before Brexit)\")\n self.d(\"Found \" + str(self.recreate_count) + \" measures to delete and recreate (start after Brexit)\\n\")\n\n # Very dull, but we need to check if the measures still exist on the staging database\n # If they do not, then we need to omit them completely from processing\n \"\"\"\n for m in self.measure_list:\n sql = \"select * from measures where measure_sid = %s\"\n params = [\n str(m.measure_sid)\n ]\n cur = self.conn_staging.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n if len(rows) == 0:\n m.omit = True\n print(\"Missing measure on \", str(m.measure_sid), m.goods_nomenclature_item_id, m.geographical_area_id)\n \"\"\"\n\n # Get a list of all measures into a string for use in the SQL statements\n self.measure_clause = \"\"\n for m in self.measure_list:\n self.measure_clause += str(m.measure_sid) + \", \"\n self.measure_clause = self.measure_clause.strip()\n self.measure_clause = self.measure_clause.strip(\",\")\n\n # So this function has literally just got hold of the measures and that's it\n # no actions, and no presumptions based on terminate vs. restart\n\n def append_seasonal_goods(self):\n return\n # This function is used to append the list of seasonal goods to the measures to be migrated\n self.d(\"Getting seasonal products\", False)\n start_date = '2018-01-01'\n\n sql = \"\"\"SELECT measure_sid, ordernumber, measure_type_id, m.validity_start_date, m.validity_end_date,\n geographical_area_id, m.goods_nomenclature_item_id, additional_code_type_id,\n additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, m.goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid,\n CASE\n WHEN m.validity_end_date is null THEN 999\n ELSE (1 + (TO_DATE(m.validity_end_date, 'YYYY-MM-DD') - TO_DATE(m.validity_start_date, 'YYYY-MM-DD')))\n end as measure_extent\n FROM ml.measures_real_end_dates m, goods_nomenclatures g\n WHERE geographical_area_id IN %s\n and m.goods_nomenclature_item_id = g.goods_nomenclature_item_id\n and g.producline_suffix = '80'\n AND measure_type_id IN %s\n and m.validity_end_date is not null\n and m.validity_end_date >= %s\n and g.validity_end_date is null\n ORDER BY m.goods_nomenclature_item_id, m.validity_start_date desc;\"\"\"\n\n params = [\n self.my_geo_ids,\n self.my_measure_types,\n start_date\n ]\n cur = self.conn.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n\n self.seasonal_measures = []\n for row in rows:\n measure_sid = row[0]\n ordernumber = row[1]\n measure_type_id = row[2]\n validity_start_date = row[3]\n validity_end_date = row[4]\n geographical_area_id = row[5]\n goods_nomenclature_item_id = row[6]\n additional_code_type_id = row[7]\n additional_code_id = row[8]\n reduction_indicator = row[9]\n measure_generating_regulation_role = row[10]\n measure_generating_regulation_id = row[11]\n justification_regulation_role = row[12]\n justification_regulation_id = row[13]\n stopped_flag = row[14]\n geographical_area_sid = row[15]\n goods_nomenclature_sid = row[16]\n additional_code_sid = row[17]\n export_refund_nomenclature_sid = row[18]\n extent = row[19]\n\n measure_object = measure(measure_sid, ordernumber, measure_type_id,\n validity_start_date, validity_end_date, geographical_area_id, goods_nomenclature_item_id,\n additional_code_type_id, additional_code_id, reduction_indicator, measure_generating_regulation_role,\n measure_generating_regulation_id, justification_regulation_role, justification_regulation_id,\n stopped_flag, geographical_area_sid, goods_nomenclature_sid,\n additional_code_sid, export_refund_nomenclature_sid)\n\n self.seasonal_measures.append(measure_object)\n\n self.seasonal_products = []\n self.d(\"Creating nomenclature objects\")\n for m in self.seasonal_measures:\n commodity_found = False\n for p in self.seasonal_products:\n if m.goods_nomenclature_item_id == p.goods_nomenclature_item_id:\n p.measure_list.append(m)\n commodity_found = True\n break\n if commodity_found is False:\n g = goods_nomenclature(m.goods_nomenclature_item_id)\n g.measure_list.append(m)\n self.seasonal_products.append(g)\n\n self.d(\"Rationalising nomenclature objects\")\n for p in self.seasonal_products:\n p.seasonal_dates = []\n for m in p.measure_list:\n m.mark_for_deletion = False\n d = m.validity_start_date\n d2 = m.validity_end_date\n m.validity_start_day = d.day\n m.validity_start_month = d.month\n m.validity_end_day = d2.day\n m.validity_end_month = d2.month\n date_period = str(d.day).zfill(2) + \"/\" + str(d.month).zfill(2) + \" - \" + str(d2.day).zfill(2) + \"/\" + str(d2.month).zfill(2)\n if date_period in p.seasonal_dates:\n m.mark_for_deletion = True\n else:\n p.seasonal_dates.append(date_period)\n # print(p.goods_nomenclature_item_id, str(len(p.measure_list)), date_period)\n\n measure_count = len(p.measure_list)\n for i in range(measure_count - 1, -1, -1):\n m = p.measure_list[i]\n if m.mark_for_deletion is True:\n del p.measure_list[i]\n\n for m in p.measure_list:\n d = m.validity_start_date\n d2 = m.validity_end_date\n m.validity_start_day = d.day\n m.validity_start_month = d.month\n m.validity_end_day = d2.day\n m.validity_end_month = d2.month\n # print(self.future_regulation_id)\n m.measure_generating_regulation_id = self.future_regulation_id\n m.justification_regulation_id = self.future_regulation_id\n date_period = str(d.day).zfill(2) + \"/\" + str(d.month).zfill(2) + \" - \" + str(d2.day).zfill(2) + \"/\" + str(d2.month).zfill(2)\n # print(p.goods_nomenclature_item_id, str(len(p.measure_list)), date_period, m.measure_sid)\n m.eu_component_list = m.get_components()\n self.content += m.seasonal_xml()\n\n def get_measure_components(self):\n # Get components related to all these measures\n self.d(\"Getting measure components\")\n\n sql = \"\"\"SELECT measure_sid, duty_expression_id, duty_amount, monetary_unit_code,\n measurement_unit_code, measurement_unit_qualifier_code FROM measure_components\n WHERE measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, duty_expression_id\"\"\"\n\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_component_list = []\n for component in rows:\n measure_sid = component[0]\n duty_expression_id = component[1]\n duty_amount = component[2]\n monetary_unit_code = component[3]\n measurement_unit_code = component[4]\n measurement_unit_qualifier_code = component[5]\n\n measure_component_object = measure_component(measure_sid, duty_expression_id, duty_amount,\n monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code)\n self.measure_component_list.append(measure_component_object)\n\n # If we are removing SIVs, then we need to add back in the simple ad valorem duty\n # which is always going to be \"0.0%\"\n if self.remove_SIVs:\n for siv_measure_sid in self.measures_with_sivs_list:\n measure_sid = siv_measure_sid\n duty_expression_id = \"01\"\n duty_amount = 0\n monetary_unit_code = \"\"\n measurement_unit_code = \"\"\n measurement_unit_qualifier_code = \"\"\n\n measure_component_object = measure_component(measure_sid, duty_expression_id, duty_amount,\n monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code)\n # self.measure_component_list.append(measure_component_object)\n\n self.d(\"Assigning measure components to measures\")\n p = ProgressBar(len(self.measure_component_list), sys.stdout)\n cnt = 1\n start = 0\n for c in self.measure_component_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_component_list.append(c)\n start = i\n else:\n if found is True:\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_measure_conditions(self):\n # Get conditions related to all these measures\n self.d(\"Getting measure conditions\")\n\n sql = \"\"\"SELECT measure_condition_sid, measure_sid, condition_code, component_sequence_number,\n condition_duty_amount, condition_monetary_unit_code, condition_measurement_unit_code,\n condition_measurement_unit_qualifier_code, action_code, certificate_type_code,\n certificate_code FROM measure_conditions\n WHERE measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, component_sequence_number\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_condition_list = []\n for condition in rows:\n measure_condition_sid = condition[0]\n measure_sid = condition[1]\n condition_code = condition[2]\n component_sequence_number = condition[3]\n condition_duty_amount = condition[4]\n condition_monetary_unit_code = condition[5]\n condition_measurement_unit_code = condition[6]\n condition_measurement_unit_qualifier_code = condition[7]\n action_code = condition[8]\n certificate_type_code = condition[9]\n certificate_code = condition[10]\n\n measure_condition_object = measure_condition(measure_condition_sid, measure_sid, condition_code,\n component_sequence_number, condition_duty_amount, condition_monetary_unit_code,\n condition_measurement_unit_code, condition_measurement_unit_qualifier_code,\n action_code, certificate_type_code, certificate_code)\n self.measure_condition_list.append(measure_condition_object)\n\n self.d(\"Assigning measure conditions to measures\")\n p = ProgressBar(len(self.measure_condition_list), sys.stdout)\n cnt = 1\n start = 0\n for c in self.measure_condition_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_condition_list.append(c)\n start = i\n else:\n if found is True:\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_measure_condition_components(self):\n # Get conditions related to all these measures\n self.d(\"Getting measure condition components\")\n\n sql = \"\"\"SELECT mc.measure_sid, mcc.measure_condition_sid, mcc.duty_expression_id,\n mcc.duty_amount, mcc.monetary_unit_code,\n mcc.measurement_unit_code, mcc.measurement_unit_qualifier_code, mc.condition_code\n FROM measure_conditions mc, measure_condition_components mcc\n WHERE mc.measure_condition_sid = mcc.measure_condition_sid\n AND mc.measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, duty_expression_id\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_condition_component_list = []\n for component in rows:\n measure_sid = component[0]\n measure_condition_sid = component[1]\n duty_expression_id = component[2]\n duty_amount = component[3]\n monetary_unit_code = component[4]\n measurement_unit_code = component[5]\n measurement_unit_qualifier_code = component[6]\n condition_code = component[7]\n\n measure_condition_component_object = measure_condition_component(measure_sid, measure_condition_sid,\n duty_expression_id, duty_amount, monetary_unit_code, measurement_unit_code,\n measurement_unit_qualifier_code, condition_code)\n self.measure_condition_component_list.append(measure_condition_component_object)\n\n self.d(\"Assigning measure condition components to measures\")\n p = ProgressBar(len(self.measure_condition_component_list), sys.stdout)\n cnt = 1\n start = 0\n for c in self.measure_condition_component_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_condition_component_list.append(c)\n start = i\n else:\n if found is True:\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_measure_geographical_exclusions(self):\n # Get geographical area exclusions related to all these measures\n self.d(\"Getting geographical area exclusions\")\n\n sql = \"\"\"SELECT measure_sid, excluded_geographical_area, geographical_area_sid\n FROM measure_excluded_geographical_areas WHERE measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, excluded_geographical_area\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_excluded_geographical_area_list = []\n for exclusion in rows:\n measure_sid = exclusion[0]\n excluded_geographical_area = exclusion[1]\n geographical_area_sid = exclusion[2]\n\n exclusion_object = measure_excluded_geographical_area(measure_sid, excluded_geographical_area, geographical_area_sid)\n self.measure_excluded_geographical_area_list.append(exclusion_object)\n\n self.d(\"Assigning measure excluded geographical areas to measures\")\n p = ProgressBar(len(self.measure_excluded_geographical_area_list), sys.stdout)\n cnt = 1\n start = 0\n for c in self.measure_excluded_geographical_area_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_excluded_geographical_area_list.append(c)\n start = i\n else:\n if found is True:\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_measure_footnotes(self):\n self.d(\"Getting measure footnote associations\")\n\n sql = \"\"\"SELECT measure_sid, footnote_type_id, footnote_id\n FROM footnote_association_measures WHERE measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, footnote_type_id, footnote_id\"\"\"\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_footnote_list = []\n for footnote in rows:\n measure_sid = footnote[0]\n footnote_type_id = footnote[1]\n footnote_id = footnote[2]\n\n footnote_object = measure_footnote(measure_sid, footnote_type_id, footnote_id)\n self.measure_footnote_list.append(footnote_object)\n\n self.d(\"Assigning footnotes to measures\")\n p = ProgressBar(len(self.measure_footnote_list), sys.stdout)\n cnt = 1\n start = 0\n for c in self.measure_footnote_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_footnote_list.append(c)\n start = i\n else:\n if found is True:\n break\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def get_measure_partial_temporary_stops(self):\n self.d(\"Getting measure partial temporary stops\")\n\n sql = \"\"\"SELECT measure_sid, validity_start_date, validity_end_date, partial_temporary_stop_regulation_id,\n partial_temporary_stop_regulation_officialjournal_number, partial_temporary_stop_regulation_officialjournal_page,\n abrogation_regulation_id, abrogation_regulation_officialjournal_number, abrogation_regulation_officialjournal_page\n FROM measure_partial_temporary_stops WHERE measure_sid IN (\"\"\" + self.measure_clause + \"\"\")\n ORDER BY measure_sid, validity_start_date;\"\"\"\n # dq (sql)\n cur = self.conn.cursor()\n cur.execute(sql)\n rows = cur.fetchall()\n\n self.measure_partial_temporary_stop_list = []\n for pts in rows:\n measure_sid = pts[0]\n validity_start_date = pts[1]\n validity_end_date = pts[2]\n partial_temporary_stop_regulation_id = pts[3]\n partial_temporary_stop_regulation_officialjournal_number = pts[4]\n partial_temporary_stop_regulation_officialjournal_page = pts[5]\n abrogation_regulation_id = pts[6]\n abrogation_regulation_officialjournal_number = pts[7]\n abrogation_regulation_officialjournal_page = pts[8]\n\n obj = measure_partial_temporary_stop(measure_sid, validity_start_date, validity_end_date, partial_temporary_stop_regulation_id,\n partial_temporary_stop_regulation_officialjournal_number, partial_temporary_stop_regulation_officialjournal_page,\n abrogation_regulation_id, abrogation_regulation_officialjournal_number, abrogation_regulation_officialjournal_page)\n self.measure_partial_temporary_stop_list.append(obj)\n\n self.d(\"Assigning partial temporary stops to measures\")\n p = ProgressBar(len(self.measure_partial_temporary_stop_list), sys.stdout)\n cnt = 1\n start = 0\n\n for c in self.measure_partial_temporary_stop_list:\n found = False\n for i in range(start, len(self.measure_list)):\n m = self.measure_list[i]\n if c.measure_sid == m.measure_sid:\n found = True\n m.measure_partial_temporary_stop_list.append(c)\n start = i\n else:\n if found is True:\n break\n\n p.print_progress(cnt)\n cnt += 1\n print(\"\\n\")\n\n def terminate_measures(self):\n self.d(\"Writing script to terminate / split measures\", False)\n\n self.deleted_measure_list = []\n self.enddated_measure_list = []\n self.recreated_measure_list = []\n\n p = ProgressBar(len(self.measure_list), sys.stdout)\n cnt = 1\n\n # The following code hunts for SIVs and remove the threshold-based values / replace with standard component\n # self.d(\"Checking for SIVs\")\n for obj in self.measure_list:\n if obj.goods_nomenclature_item_id == \"2204309800\":\n # print(\"Found 2204309800\", obj.action, obj.validity_start_date)\n pass\n if obj.omit is False:\n my_duty_list = []\n # Search through the measure conditions and if there is a \"V\" type condition code (an SIV)\n # remove the condition and then add a measure component equivalent to the consensus\n # ad valorem measure condition component's ad valorem component duty amount\n\n # Here we capture all of the measure condition components (V type)\n # and compile a \"duty list\", from which we find the ad valorem that we are interested in\n # For MFNs, these should just be deleted, not replaced - all products with SIVs on them are \"0\"-rated\n # This script is no longer used on MFNs\n\n for mc in obj.measure_condition_list:\n if mc.condition_code == \"V\":\n for mcc in obj.measure_condition_component_list:\n if mc.measure_sid == mcc.measure_sid:\n if mcc.duty_expression_id == \"01\":\n my_duty_list.append(mcc.duty_amount)\n\n p.print_progress(cnt)\n cnt += 1\n if obj.action == \"delete\":\n self.deleted_measure_list.append(obj)\n if self.action_verbatim not in (\"n\", \"newstart\"):\n self.content += obj.xml()\n self.transaction_id += 1\n\n elif obj.action == \"recreate\":\n self.recreated_measure_list.append(obj)\n obj.action = \"delete\"\n if self.action_verbatim not in (\"n\", \"newstart\"):\n self.content += obj.xml()\n self.transaction_id += 1\n\n elif obj.action == \"enddate\":\n self.enddated_measure_list.append(obj)\n if self.action_verbatim not in (\"n\", \"newstart\"):\n self.content += obj.xml()\n self.transaction_id += 1\n\n if (self.scope != \"measuretypes\") or (\"103\" not in self.measure_type_list):\n # print(\"Reviewing SIVs and removing\")\n if len(my_duty_list) > 0:\n duty_amount_last = -1\n all_match = True\n for da in my_duty_list:\n if duty_amount_last != -1:\n if da != duty_amount_last:\n all_match = False\n break\n\n duty_amount_last = da\n\n if all_match is True:\n # print(\"Creating a new component\")\n new_component = measure_component(obj.measure_sid, \"01\", duty_amount_last, \"\", \"\", \"\", obj.goods_nomenclature_item_id)\n mc_found = False\n for mc in obj.measure_component_list:\n if mc.duty_expression_id == \"01\":\n mc_found = True\n break\n if mc_found is False:\n obj.measure_component_list.append(new_component)\n # print(\"Adding an SIV replacement measure for: \", obj.goods_nomenclature_item_id, obj.validity_start_date, obj.measure_sid)\n\n print(\"\\n\")\n\n def get_goods_nomenclature_sid(self, goods_nomenclature_item_id):\n return (1)\n\n def restart_measures(self):\n # These are the new measures which did not previously exist\n # These need to\n # - Create measures\n # - Create measure components\n\n dealt_with_list = []\n for obj in self.enddated_measure_list:\n dealt_with_list.append(obj.goods_nomenclature_item_id)\n\n for obj in self.recreated_measure_list:\n dealt_with_list.append(obj.goods_nomenclature_item_id)\n\n # self.content = \"\"\n\n # print(self.action_string, self.scope)\n if self.action_string == \"restart\":\n self.content += \"\\n\\n\\n\"\n self.d(\"Writing script to restart end-dated measures\", False)\n p = ProgressBar(len(self.enddated_measure_list), sys.stdout)\n cnt = 1\n for obj in self.enddated_measure_list:\n # print(obj.goods_nomenclature_item_id)\n proceed = False\n if self.scope == \"country\":\n if obj.measure_type_id in [\"142\", \"145\", \"143\", \"146\"]:\n if obj.validity_end_date == \"\": # This is new to deal with seasonal goods\n proceed = True\n else:\n proceed = True\n if proceed is True:\n # First time round, mark the Meursing components for deletion\n for component in obj.measure_component_list:\n component.mark_for_deletion = False\n if component.duty_expression_id in self.meursing_list:\n component.mark_for_deletion = True\n\n # Second, delete the marked components\n component_count = len(obj.measure_component_list)\n for i in range(component_count - 1, -1, -1):\n component = obj.measure_component_list[i]\n if component.mark_for_deletion is True:\n del obj.measure_component_list[i]\n\n # Third, look for orphaned max / min components\n component_count = len(obj.measure_component_list)\n if component_count == 2:\n component1 = obj.measure_component_list[0]\n component2 = obj.measure_component_list[1]\n if component1.duty_expression_id == \"01\":\n if str(component1.measurement_unit_code != \"\"):\n if component2.duty_expression_id in ('17', '35', '15'):\n del obj.measure_component_list[1]\n\n p.print_progress(cnt)\n cnt += 1\n obj.action = \"restart\"\n obj.measure_generating_regulation_id = self.future_regulation_id\n obj.measure_generating_regulation_role = \"1\"\n self.content += obj.xml()\n self.transaction_id += 1\n print(\"\\n\")\n self.d(\"Writing script to reinstitute deleted future measures\", False)\n p = ProgressBar(len(self.recreated_measure_list), sys.stdout)\n cnt = 1\n for obj in self.recreated_measure_list:\n p.print_progress(cnt)\n cnt += 1\n obj.action = \"restart\"\n obj.measure_generating_regulation_id = self.future_regulation_id\n obj.measure_generating_regulation_role = \"1\"\n self.content += obj.xml()\n self.transaction_id += 1\n print(\"\\n\")\n else:\n self.d(\"No new measures to write - terminate only\", False)\n\n def terminate_definitions(self):\n self.d(\"Writing script to terminate quota definitions\", False)\n\n # self.deleted_measure_list = []\n p = ProgressBar(len(self.quota_definition_list_combined), sys.stdout)\n cnt = 1\n for obj in self.quota_definition_list_combined:\n p.print_progress(cnt)\n cnt += 1\n if obj.action == \"delete\":\n # self.deleted_measure_list.append(obj)\n self.content += obj.xml()\n self.transaction_id += 1\n elif obj.action == \"split\":\n # self.deleted_measure_list.append(obj)\n self.content += obj.xml()\n self.transaction_id += 1\n else:\n pass\n print(\"\\n\")\n\n def compare(self, a, b):\n mapped = False\n if a.quota_order_number_id == b.quota_order_number_id:\n if a.validity_start_day == b.validity_start_day:\n if a.validity_end_month == b.validity_end_month:\n mapped = True\n return (mapped)\n\n def d(self, s, include_indent=True):\n if self.debug:\n if include_indent:\n s = \"- \" + s\n else:\n s = \"\\n\" + s.upper()\n print(s)\n\n def clear(self):\n # for windows\n if name == 'nt':\n _ = system('cls')\n # for mac and linux(here, os.name is 'posix')\n else:\n _ = system('clear')\n\n def connect(self):\n self.conn = psycopg2.connect(\"dbname=\" + self.DBASE_MIGRATE_MEASURES + \" user=postgres password=\" + self.p)\n # self.conn = psycopg2.connect(\"dbname=\" + self.DBASE + \" user=postgres password=\" + self.p)\n self.conn_staging = psycopg2.connect(\"dbname=\" + self.DBASE + \" user=postgres password=\" + self.p)\n\n def generate_xml_report(self):\n self.d(\"Generating an XML report\", False)\n ET.register_namespace('oub', 'urn:publicid:-:DGTAXUD:TARIC:MESSAGE:1.0')\n ET.register_namespace('env', 'urn:publicid:-:DGTAXUD:GENERAL:ENVELOPE:1.0')\n fname = os.path.join(self.XML_OUT_DIR, self.output_filename)\n tree = ET.parse(fname)\n root = tree.getroot()\n\n # Get the envelope ID\n out = \"\"\n out += \"envelope id = \" + root.get(\"id\") + \"\\n\\n\"\n\n out += \"Overall stats\\n\".upper()\n out += \"=============\\n\"\n\n # Get number of transactions\n transaction_count = len(root.findall('.//env:transaction', self.namespaces))\n out += \"Transaction count = \" + str(transaction_count) + \"\\n\"\n\n # Get number of records\n record_count = len(root.findall('.//oub:record', self.namespaces))\n out += \"Record count = \" + str(record_count) + \"\\n\"\n\n # Get number of measures\n measure_count = len(root.findall('.//oub:measure', self.namespaces))\n out += \"Measure count = \" + str(measure_count) + \"\\n\"\n\n # Get number of measure components\n measure_component_count = len(root.findall('.//oub:measure.component', self.namespaces))\n out += \"Measure component count = \" + str(measure_component_count) + \"\\n\"\n\n # Get number of measure conditions\n measure_condition_count = len(root.findall('.//oub:measure.condition', self.namespaces))\n out += \"Measure condition count = \" + str(measure_condition_count) + \"\\n\"\n\n # Get number of measure condition components\n measure_condition_component_count = len(root.findall('.//oub:measure.condition.component', self.namespaces))\n out += \"Measure condition component count = \" + str(measure_condition_component_count) + \"\\n\"\n\n out += \"\\nInserts\\n\".upper()\n out += \"=======\\n\"\n\n # Get number of inserted measures\n measure_count = len(root.findall('.//oub:measure/../../[oub:update.type=3]', self.namespaces))\n out += \"Inserted measure count = \" + str(measure_count) + \"\\n\"\n\n fname = self.output_filename.replace(\".xml\", \".txt\")\n fname = os.path.join(self.XML_REPORT_DIR, fname)\n f = open(fname, \"w+\", encoding=\"utf-8\")\n f.write(out)\n f.close()\n\n def validate(self, filename):\n fname = os.path.join(self.XML_OUT_DIR, filename)\n\n msg = \"Validating the XML file against the Taric 3 schema\"\n self.d(msg, False)\n schema_path = os.path.join(self.SCHEMA_DIR, \"envelope.xsd\")\n my_schema = xmlschema.XMLSchema(schema_path)\n\n try:\n if my_schema.is_valid(fname):\n self.d(\"The file validated successfully\")\n success = True\n else:\n self.d(\"The file did not validate\")\n success = False\n except:\n self.d(\"The file did not validate and crashed the validator\")\n success = False\n if not(success):\n my_schema.validate(fname)\n\n def get_envelope(self):\n # Open the envelope template file\n filename = os.path.join(self.TEMPLATE_DIR, \"envelope.xml\")\n file = open(filename, mode='r')\n self.envelope_string = file.read()\n self.envelope_string = self.envelope_string.replace(\"[ID]\", self.envelope_id)\n file.close()\n\n def write_content(self):\n if len(self.content) == 0:\n print(\"No matching measures found\")\n sys.exit()\n else:\n self.d(\"Writing file\", False)\n self.d(\"Writing file '\" + self.output_filename + \"'\")\n self.d(\"to folder \" + self.XML_OUT_DIR)\n xml_string = self.template_envelope.replace(\"[CONTENT]\", self.content)\n filename = os.path.join(self.XML_OUT_DIR, self.output_filename)\n f = open(filename, \"w+\", encoding=\"utf-8\")\n f.write(xml_string)\n f.close()\n\n def check_business_rules(self):\n self.d(\"Validating against business rules\", False)\n fname = os.path.join(self.XML_OUT_DIR, self.output_filename)\n br = business_rules(fname)\n\n def copy_to_custom_import_folder(self):\n if self.scope == \"bulk_migration\":\n return\n self.d(\"Copying file to custom import directory\", False)\n self.CUSTOM_DIR = os.path.join(self.BASE_DIR, \"..\")\n self.CUSTOM_DIR = os.path.join(self.CUSTOM_DIR, \"convert_and_import_taric\")\n self.CUSTOM_DIR = os.path.join(self.CUSTOM_DIR, \"xml_in\")\n self.CUSTOM_DIR = os.path.join(self.CUSTOM_DIR, \"custom\")\n # Copy from self.output_filename to dest\n file_from = os.path.join(self.XML_OUT_DIR, self.output_filename)\n file_to = os.path.join(self.CUSTOM_DIR, self.output_filename)\n # print(file_from)\n # print(file_to)\n shutil.copy(file_from, file_to)\n","sub_path":"create-data/migrate_measures_and_quotas/classes/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":100949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"450783003","text":"import datetime\r\nfrom datetime import date\r\nfrom datetime import timedelta\r\nimport numpy as np\r\nimport scipy.optimize as optimize\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import spline\r\n\r\nglobal par\r\nglobal coup\r\nglobal today\r\nglobal freq\r\nglobal spot_rate_data\r\n\r\n\r\ndef minus_month(time, num):\r\n assert 0 <= num <= 12\r\n year = time.year\r\n month = time.month\r\n if (month - num) / 12 < 0:\r\n new_month = (month - num) % 12\r\n carry = abs((month - num) // 12)\r\n return date(year - carry, new_month, time.day)\r\n return date(year, month - num, time.day) if (month - num) % 12 != 0 else date(year - 1, 12, time.day)\r\n\r\n\r\ndef ytm_calculator(price, par, coup_rate, issue_date, mature_date, freq=2, guess=0.04):\r\n \"\"\"\r\n calculator for frequency = 2\r\n \"\"\"\r\n assert issue_date < today\r\n global coup\r\n\r\n last_coupon_date, coupon_date = get_coupon_date(today, mature_date)\r\n price = dirty_price(coup, price, last_coupon_date, today)\r\n\r\n # Get each period\r\n dt = []\r\n for i in range(len(coupon_date)):\r\n difference = (coupon_date[i] - today).days\r\n dt.append(difference / 182.5)\r\n\r\n # Calculate ytm using newton's method\r\n ytm_function = lambda y: sum([coup / ((1 + y / freq) ** j) for j in dt]) + par / ((1 + y / freq) ** dt[-1]) - price\r\n year = (mature_date - today).days / 365\r\n yield_rate = optimize.newton(ytm_function, guess)\r\n return year, yield_rate\r\n\r\n\r\ndef dirty_price(coupon, clean_price, last_coupon_date, date_today):\r\n accrued_interest = (date_today - last_coupon_date).days / 182.5 * coupon\r\n return clean_price + accrued_interest\r\n\r\n\r\ndef extract_data(data, today):\r\n global coup\r\n coupon_rate = float(data.get(\"coupon\")[:-1]) / 100\r\n issue_date = datetime.datetime.strptime(data.get(\"issue date\"), '%m/%d/%Y').date()\r\n maturity_date = datetime.datetime.strptime(data.get(\"maturity date\"), '%m/%d/%Y').date()\r\n string_date = today.strftime(\"%m/%d/%Y\")\r\n date = string_date[1:3] + string_date[4:] if string_date[3] == \"0\" else string_date[1:]\r\n price = float(data.get(date))\r\n coup = coupon_rate / freq * par\r\n return price, coupon_rate, issue_date, maturity_date\r\n\r\n\r\ndef get_coupon_date(date_today, maturity_date):\r\n \"\"\"\r\n precondition: issue date is before today\r\n \"\"\"\r\n date = minus_month(maturity_date, 6)\r\n coupon_date = [maturity_date]\r\n while date > date_today:\r\n coupon_date.append(date)\r\n date = minus_month(date, 6)\r\n coupon_date.reverse()\r\n return date, coupon_date\r\n\r\n\r\ndef dictionary_to_lists(dictionary):\r\n year = []\r\n rate = []\r\n for key, value in dictionary.items():\r\n year.append(key)\r\n rate.append(value)\r\n return year, rate\r\n\r\n\r\ndef convert_year_to_period(date_lst):\r\n result = []\r\n for i in date_lst:\r\n result.append((i - today).days / 365)\r\n return result\r\n\r\n\r\ndef spot_calculator(date_today, price, maturity_date, par=100):\r\n global spot_rate_data\r\n last_coupon_date, coupon_date = get_coupon_date(date_today, maturity_date)\r\n\r\n # remove the last coupon date\r\n coupon_date = coupon_date[:-1]\r\n price = dirty_price(coup, price, last_coupon_date, date_today)\r\n\r\n year, rate_lst = dictionary_to_lists(spot_rate_data)\r\n period_lst = convert_year_to_period(year)\r\n\r\n # reduce present values of previous coupons\r\n for date in coupon_date:\r\n if date in spot_rate_data:\r\n rate = spot_rate_data[date]\r\n elif min(year) <= date <= max(year):\r\n predict_x = (date - date_today).days/365\r\n rate = np.interp(predict_x, period_lst, rate_lst)\r\n else:\r\n rate = spot_rate_data[max(year)]\r\n\r\n period = (date - date_today).days / 365\r\n pv_coup = coup / np.exp(rate * period)\r\n price = price - pv_coup\r\n\r\n # calculate zero-coupon rate\r\n spot_rate = - np.log(price / (par + coup)) / ((maturity_date - date_today).days / 365)\r\n spot_rate_data[maturity_date] = spot_rate\r\n\r\n\r\ndef ytm_run(df, plot=True, smooth=False):\r\n year_lst = []\r\n yield_rate_lst = []\r\n for i in range(df.shape[0]):\r\n price, coupon_rate, issue_date, maturity_date = extract_data(df.iloc[i], today)\r\n year, yield_rate = ytm_calculator(price, par, coupon_rate, issue_date, maturity_date)\r\n year_lst.append(year)\r\n yield_rate_lst.append(yield_rate)\r\n if plot:\r\n if smooth:\r\n show_smooth_graph(year_lst, yield_rate_lst)\r\n else:\r\n plt.plot(year_lst, yield_rate_lst, label=str(today))\r\n # plt.show()\r\n return year_lst, yield_rate_lst\r\n\r\n\r\ndef show_smooth_graph(x, y):\r\n xnew = np.linspace(min(x), max(x), 300)\r\n power_smooth = spline(x, y, xnew)\r\n plt.plot(xnew, power_smooth, label=str(today))\r\n # plt.show()\r\n\r\n\r\ndef spot_run(df, today, plot=True, smooth=False):\r\n for i in range(df.shape[0]):\r\n price, coupon_rate, issue_date, maturity_date = extract_data(df.iloc[i], today)\r\n spot_calculator(today, price, maturity_date)\r\n year_lst = []\r\n spot_rate_lst = []\r\n for key, value in spot_rate_data.items():\r\n year_lst.append((key - today).days / 365)\r\n spot_rate_lst.append(value)\r\n if plot:\r\n if smooth:\r\n show_smooth_graph(year_lst, spot_rate_lst)\r\n else:\r\n plt.plot(year_lst, spot_rate_lst, label=str(today))\r\n\r\n\r\ndef forward_run(df, today, predict_year, plot=True, smooth=False):\r\n spot_run(df, today, plot=False)\r\n year, rate = dictionary_to_lists(spot_rate_data)\r\n period_lst = convert_year_to_period(year)\r\n first_year_spot_rate = np.interp(1, period_lst, rate)\r\n forward_rate_lst = []\r\n for y in predict_year:\r\n spot_rate = np.interp(y + 1, period_lst, rate)\r\n forward_rate_lst.append(((1 + spot_rate) ** (y + 1) / (1 + first_year_spot_rate)) ** (1 / (y)) - 1)\r\n if plot:\r\n if smooth:\r\n show_smooth_graph(predict_year, forward_rate_lst)\r\n else:\r\n plt.plot(predict_year, forward_rate_lst, label=str(today))\r\n return forward_rate_lst\r\n\r\n\r\nif __name__ == '__main__':\r\n freq = 2\r\n spot_rate_data = {}\r\n par = 100\r\n global today\r\n day_lst = [date(2020, 1, i) for i in range(2, 4)] + [date(2020, 1, i) for i in range(6, 11)] + \\\r\n [date(2020, 1, i) for i in range(13, 16)]\r\n plt.style.use('ggplot')\r\n df = pd.read_csv(\"apm466_data.csv\")\r\n\r\n # ------------ ytm -----------------------------------------------------------------------------\r\n # for today in day_lst:\r\n # ytm_run(df)\r\n # plt.title(\"Yield Curve\")\r\n # plt.xlabel(\"year\")\r\n # plt.ylabel(\"yield rate\")\r\n # plt.legend()\r\n # plt.show()\r\n\r\n # ------------- spot_rate -----------------------------------------------------------------------\r\n # for today in day_lst:\r\n # spot_run(df, today, plot=True, smooth=True)\r\n # plt.title(\"Spot Curve\")\r\n # plt.xlabel(\"year\")\r\n # plt.ylabel(\"spot rate\")\r\n # plt.legend()\r\n # plt.show()\r\n\r\n # ------------- forward_rate --------------------------------------------------------------------\r\n predict_year = [1, 2, 3, 4]\r\n for today in day_lst:\r\n forward_run(df, today, predict_year)\r\n # plt.title(\"Forward Curve\")\r\n # plt.xlabel(\"year\")\r\n # plt.ylabel(\"forward rate\")\r\n # plt.legend()\r\n # plt.legend()\r\n # plt.show()\r\n\r\n # -------------Question 5 -----------------------------------------------------------------------\r\n yield_matrix = np.zeros((10, 5))\r\n forward_matrix = np.zeros((10, 4))\r\n i = 0\r\n for today in day_lst:\r\n year_lst, yield_lst = ytm_run(df, plot=False)\r\n forward_rate_lst = forward_run(df, today, predict_year, plot=False)\r\n # print(forward_rate_lst)\r\n for j in range(5):\r\n yield_matrix[i][j] = np.interp(j+1, year_lst, yield_lst)\r\n if j != 4:\r\n forward_matrix[i][j] = forward_rate_lst[j]\r\n i += 1\r\n # print(yield_matrix)\r\n # print(forward_matrix)\r\n X = np.zeros((5, 9))\r\n for a in range(5):\r\n X[a] = np.log(yield_matrix[1:10, a] / yield_matrix[0:9, a])\r\n log_return_covariance = np.cov(X)\r\n forward_covariance = np.cov(forward_matrix.transpose())\r\n print(\"eigenvalue and eigenvector of log_return covariance:\", np.linalg.eig(log_return_covariance))\r\n\r\n print(\"eigenvalue and eigenvector of forward covariance:\", np.linalg.eig(forward_covariance))\r\n\r\n # print(\"log return covariance\", log_return_covariance)\r\n # print(\"forward covariance\", forward_covariance)\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"216812806","text":"import os.path\nfrom datetime import date\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.files import File\nfrom django.db import IntegrityError\nfrom django.test import TestCase\n\nfrom risk_managed_api.models import (\n Administrator,\n CarbonCopyAddress,\n Event,\n GuestRegistration,\n Host,\n Identity,\n Invitee,\n Nationals,\n Organization,\n University,\n)\n\n\ndef create_user(username, password):\n return get_user_model().objects.create_user(\n username=username, email=username + \"@\" + username + \".com\", password=password\n )\n\n\nclass ModelTests(TestCase):\n def test_user_profiles_cascade_delete(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n\n # Nationals\n user = create_user(\"ks\", \"ks\")\n ks_nat = Nationals.objects.create(user=user, organization=kappa_sigma)\n\n ks_nat.delete()\n users = get_user_model().objects.filter(username=\"ks\")\n self.assertEquals(len(users), 0)\n\n # Administrator\n user = create_user(\"spsu\", \"spsu\")\n spsu_adm = Administrator.objects.create(user=user, university=spsu)\n\n spsu_adm.delete()\n users = get_user_model().objects.filter(username=\"spsu\")\n self.assertEquals(len(users), 0)\n\n # Host\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu_hst = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n ksspsu_hst.delete()\n users = get_user_model().objects.filter(username=\"ksspsu\")\n self.assertEquals(len(users), 0)\n\n def test_new_nationals_or_administrator_fore_host_link(self):\n admin = create_user(\"josh\", \"josh\")\n admin.is_superuser = True\n admin.save()\n\n # Create `Organizations`\n ks = Organization.objects.create(name=\"Kappa Sigma\")\n\n sae = Organization.objects.create(name=\"Sigma Alpha Epsilon\")\n\n sn = Organization.objects.create(name=\"Sigma Nu\")\n\n # Create `Universities`\n spsu = University.objects.create(\n name=\"Southern Polytechnic State University\", acronym=\"SPSU\"\n )\n\n gt = University.objects.create(name=\"Georgia Institute of Technology\", acronym=\"GT\")\n\n uga = University.objects.create(name=\"University of Georgia\", acronym=\"UGA\")\n\n # Create `Hosts`\n ksspsu_user = create_user(\"ksspsu\", \"ksspsu\")\n Host.objects.create(user=ksspsu_user, organization=ks, university=spsu)\n\n saespsu_user = create_user(\"saespsu\", \"saespsu\")\n Host.objects.create(user=saespsu_user, organization=sae, university=spsu)\n\n ksgt_user = create_user(\"ksgt\", \"ksgt\")\n Host.objects.create(user=ksgt_user, organization=ks, university=gt)\n\n saegt_user = create_user(\"saegt\", \"saegt\")\n Host.objects.create(user=saegt_user, organization=sae, university=gt)\n\n # Assert `Hosts` exist\n host_set = Host.objects.filter(organization=ks)\n self.assertEquals(len(host_set), 2)\n\n # Assert `Hosts` do not have `Nationals`\n self.assertEquals(host_set[0].nationals, None)\n\n # Create `Nationals`\n ks_nat_user = create_user(\"ks\", \"ks\")\n ks_nat = Nationals.objects.create(user=ks_nat_user, organization=ks)\n\n sae_nat_user = create_user(\"sae\", \"sae\")\n Nationals.objects.create(user=sae_nat_user, organization=sae)\n\n # Assert `Hosts` do have `Nationals`\n host_set = Host.objects.filter(nationals=ks_nat)\n self.assertEquals(len(host_set), 2)\n\n # Assert `Hosts` exist\n host_set = Host.objects.filter(university=spsu)\n self.assertEquals(len(host_set), 2)\n\n # Assert `Hosts` do not have `Administrators`\n self.assertEquals(host_set[0].administrator, None)\n\n # Create `Administrators`\n spsu_admin_user = create_user(\"spsu\", \"spsu\")\n spsu_admin = Administrator.objects.create(user=spsu_admin_user, university=spsu)\n\n gt_admin_user = create_user(\"gt\", \"gt\")\n Administrator.objects.create(user=gt_admin_user, university=gt)\n\n # Assert `Hosts` do have `Administrator`\n host_set = Host.objects.filter(administrator=spsu_admin)\n self.assertEquals(len(host_set), 2)\n\n # Create new `Nationals` and `Administrator` objects\n sn_nat_user = create_user(\"sn\", \"sn\")\n sn_nat = Nationals.objects.create(user=sn_nat_user, organization=sn)\n\n uga_admin_user = create_user(\"uga\", \"uga\")\n uga_admin = Administrator.objects.create(user=uga_admin_user, university=uga)\n\n # Create new `Host` object\n snuga_user = create_user(\"snuga\", \"snuga\")\n snuga = Host.objects.create(user=snuga_user, organization=sn, university=uga)\n\n # Assert `Host` is automatically assigned `Nationals` and `Administrator`\n self.assertEquals(snuga.nationals, sn_nat)\n self.assertEquals(snuga.administrator, uga_admin)\n\n def test_number_of_hosts(self):\n ks = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(\n name=\"Southern Polytechnic State University\", acronym=\"SPSU\"\n )\n\n ks_nat_user = create_user(\"ks\", \"ks\")\n ks_nat = Nationals.objects.create(user=ks_nat_user, organization=ks)\n\n spsu_admin_user = create_user(\"spsu\", \"spsu\")\n spsu_admin = Administrator.objects.create(user=spsu_admin_user, university=spsu)\n\n ksspsu_user = create_user(\"ksspsu\", \"ksspsu\")\n Host.objects.create(user=ksspsu_user, organization=ks, university=spsu)\n\n self.assertEquals(ks_nat.number_of_hosts(), 1)\n self.assertEquals(spsu_admin.number_of_hosts(), 1)\n\n sae = Organization.objects.create(name=\"Sigma Alpha Epsilon\")\n\n kssae_user = create_user(\"kssae\", \"kssae\")\n Host.objects.create(user=kssae_user, organization=sae, university=spsu)\n\n self.assertEquals(spsu_admin.number_of_hosts(), 2)\n\n def test_addresses_are_deleted_on_user_profile_deletion(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n\n # Create Addresses\n CarbonCopyAddress.objects.create(user=user, email=\"bob@bob.com\")\n CarbonCopyAddress.objects.create(user=user, email=\"joe@joe.com\")\n\n all_addresses = CarbonCopyAddress.objects.all()\n self.assertEquals(len(all_addresses), 2)\n\n ksspsu.delete()\n\n all_addresses = CarbonCopyAddress.objects.all()\n self.assertEquals(len(all_addresses), 0)\n\n def test_addresses_are_unique_with_email_and_user(self):\n josh = create_user(\"josh\", \"josh\")\n\n # Create `CarbonCopyAddresses`\n CarbonCopyAddress.objects.create(user=josh, email=\"bob@bob.com\")\n with self.assertRaises(IntegrityError):\n CarbonCopyAddress.objects.create(user=josh, email=\"bob@bob.com\")\n\n def test_identities_unique_together(self):\n\n Identity.objects.create(\n first_name=\"Josh\", last_name=\"Eppinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n with self.assertRaises(IntegrityError):\n Identity.objects.create(\n first_name=\"Josh\", last_name=\"Eppinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n def test_identities_normalize_names(self):\n Identity.objects.create(\n first_name=\"josh\", last_name=\"EpPinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n with self.assertRaises(IntegrityError):\n Identity.objects.create(\n first_name=\"Josh\", last_name=\"Eppinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n def test_identities_middle_name(self):\n Identity.objects.create(\n first_name=\"joshua tayloR\", last_name=\"EpPinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n with self.assertRaises(IntegrityError):\n Identity.objects.create(\n first_name=\"Joshua taylor\",\n last_name=\"Eppinette\",\n gender=\"Male\",\n dob=date(1994, 5, 12),\n )\n\n def test_identities_trailing_spaces(self):\n Identity.objects.create(\n first_name=\"joshua \", last_name=\"EpPinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n\n results = Identity.objects.filter(first_name=\"Joshua\")\n self.assertEquals(len(results), 1)\n\n def test_events_are_unique_with_host_name_and_date(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n uga = University.objects.create(name=\"University of Georgia\", acronym=\"UGA\")\n\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n\n user = create_user(\"ksuga\", \"ksuga\")\n ksuga = Host.objects.create(user=user, university=uga, organization=kappa_sigma)\n\n # Create `Events`\n data = {\n \"name\": \"New Event\",\n \"description\": \"My event.\",\n \"date\": \"2014-07-21\",\n \"time\": \"00:00:00.000000\",\n \"location\": \"Chapter House\",\n \"planner_name\": \"Joshua Taylor Eppinette\",\n \"planner_mobile\": \"7704016678\",\n \"planner_email\": \"josh.eppinette@waterdragon.net\",\n \"president_email\": \"pres@pres.com\",\n \"sober_monitors\": \"Josh Eppinette\",\n \"expected_guest_count\": 50,\n \"exclusivity\": \"Invitation Only\",\n \"alcohol_distribution\": \"Mobile Cocktails\",\n \"entry\": \"Yes\",\n \"entry_description\": \"Front Door\",\n \"co_sponsored_description\": \"With Kappa Delta\",\n }\n\n Event.objects.create(host=ksspsu, **data)\n\n edited_data = data\n edited_data[\"date\"] = \"2013-07-21\"\n Event.objects.create(host=ksspsu, **edited_data)\n\n Event.objects.create(host=ksuga, **data)\n\n with self.assertRaises(IntegrityError):\n Event.objects.create(host=ksspsu, **data)\n\n def test_invitees_normalize_names(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n\n # Create `Events`\n data = {\n \"name\": \"New Event\",\n \"description\": \"My event.\",\n \"date\": \"2014-07-21\",\n \"time\": \"00:00:00.000000\",\n \"location\": \"Chapter House\",\n \"planner_name\": \"Joshua Taylor Eppinette\",\n \"planner_mobile\": \"7704016678\",\n \"planner_email\": \"josh.eppinette@waterdragon.net\",\n \"president_email\": \"pres@pres.com\",\n \"sober_monitors\": \"Josh Eppinette\",\n \"expected_guest_count\": 50,\n \"exclusivity\": \"Invitation Only\",\n \"alcohol_distribution\": \"Mobile Cocktails\",\n \"entry\": \"Yes\",\n \"entry_description\": \"Front Door\",\n \"co_sponsored_description\": \"With Kappa Delta\",\n }\n\n event_one = Event.objects.create(host=ksspsu, **data)\n\n # Test `Invitees`\n Invitee.objects.create(\n first_name=\"josh\", last_name=\"EpPinette\", gender=\"Male\", event=event_one\n )\n\n results = Invitee.objects.filter(first_name=\"Josh\")\n self.assertEquals(len(results), 1)\n\n def test_invitees_trailing_spaces(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n\n # Create `Events`\n data = {\n \"name\": \"New Event\",\n \"description\": \"My event.\",\n \"date\": \"2014-07-21\",\n \"time\": \"00:00:00.000000\",\n \"location\": \"Chapter House\",\n \"planner_name\": \"Joshua Taylor Eppinette\",\n \"planner_mobile\": \"7704016678\",\n \"planner_email\": \"josh.eppinette@waterdragon.net\",\n \"president_email\": \"pres@pres.com\",\n \"sober_monitors\": \"Josh Eppinette\",\n \"expected_guest_count\": 50,\n \"exclusivity\": \"Invitation Only\",\n \"alcohol_distribution\": \"Mobile Cocktails\",\n \"entry\": \"Yes\",\n \"entry_description\": \"Front Door\",\n \"co_sponsored_description\": \"With Kappa Delta\",\n }\n\n event_one = Event.objects.create(host=ksspsu, **data)\n\n # Test `Invitees`\n Invitee.objects.create(\n first_name=\"joshua \", last_name=\"Eppinette\", gender=\"Male\", event=event_one\n )\n\n results = Invitee.objects.filter(first_name=\"Joshua\")\n self.assertEquals(len(results), 1)\n\n def test_guest_registration_creation(self):\n kappa_sigma = Organization.objects.create(name=\"Kappa Sigma\")\n spsu = University.objects.create(name=\"Southern Poly\", acronym=\"SPSU\")\n\n user = create_user(\"ksspsu\", \"ksspsu\")\n ksspsu = Host.objects.create(user=user, university=spsu, organization=kappa_sigma)\n\n # Create `Events`\n data = {\n \"name\": \"New Event\",\n \"description\": \"My event.\",\n \"date\": \"2014-07-21\",\n \"time\": \"00:00:00.000000\",\n \"location\": \"Chapter House\",\n \"planner_name\": \"Joshua Taylor Eppinette\",\n \"planner_mobile\": \"7704016678\",\n \"planner_email\": \"josh.eppinette@waterdragon.net\",\n \"president_email\": \"pres@pres.com\",\n \"sober_monitors\": \"Josh Eppinette\",\n \"expected_guest_count\": 50,\n \"exclusivity\": \"Invitation Only\",\n \"alcohol_distribution\": \"Mobile Cocktails\",\n \"entry\": \"Yes\",\n \"entry_description\": \"Front Door\",\n \"co_sponsored_description\": \"With Kappa Delta\",\n }\n\n event_one = Event.objects.create(host=ksspsu, **data)\n\n josh = Identity.objects.create(\n first_name=\"Josh\", last_name=\"Eppinette\", gender=\"Male\", dob=date(1994, 5, 12)\n )\n with open(\n os.path.join(settings.ROOT, \"tests\", \"fixtures\", \"images\", \"checkin.jpg\"), \"rb\"\n ) as f:\n django_file = File(f)\n django_file.name = str(josh.id) + \"-\" + str(event_one.id) + \"-image.jpg\"\n GuestRegistration.objects.create(identity=josh, event=event_one, image=django_file)\n","sub_path":"risk_managed_api/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":14822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556910630","text":"import turtle\n\npenColor = \"\"\nlineLenght = \"\"\nturn = \"\"\nangle = 0\n\nwhile lineLenght != 0:\n penColor = input('What color os pen you want for drawing? ')\n turtle.color(penColor)\n \n lineLenght = int(input('Type the lenght of your lines please: '))\n turtle.forward(lineLenght)\n if lineLenght == 0:\n break\n \n while turn != \"LEFT\" or turn != \"RIGHT\":\n turn = input('Choose left or right for angle? ').upper()\n if turn == \"RIGHT\":\n angle = int(input('Type your angle value: '))\n turtle.right(angle)\n break\n \n elif turn == \"LEFT\":\n angle = int(input('Type your angle value: '))\n turtle.left(angle)\n break\n\n \nprint ('There is no \"0\" Value for line')\n","sub_path":"6.1 - While Exercise.py","file_name":"6.1 - While Exercise.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"379334355","text":"from subprocess import Popen, PIPE\nimport os\n\nimport numpy as np\nimport pytest\n\nimport vtki\nfrom vtki import examples as ex\nfrom vtki.plotting import running_xserver\n\nimport vtk\n\n\ndef test_multi_block_init_vtk():\n multi = vtk.vtkMultiBlockDataSet()\n multi.SetBlock(0, vtk.vtkRectilinearGrid())\n multi.SetBlock(1, vtk.vtkTable())\n multi = vtki.MultiBlock(multi)\n assert isinstance(multi, vtki.MultiBlock)\n assert multi.n_blocks == 2\n assert isinstance(multi[0], vtki.RectilinearGrid)\n assert isinstance(multi[1], vtk.vtkTable)\n\n\ndef test_multi_block_append():\n \"\"\"This puts all of the example data objects into a a MultiBlock container\"\"\"\n multi = vtki.MultiBlock()\n # Add examples\n multi.append(ex.load_ant())\n multi.append(ex.load_sphere())\n multi.append(ex.load_uniform())\n multi.append(ex.load_airplane())\n multi.append(ex.load_rectilinear())\n # Now check everything\n assert multi.n_blocks == 5\n assert multi.bounds is not None\n assert isinstance(multi[0], vtki.PolyData)\n assert isinstance(multi[1], vtki.PolyData)\n assert isinstance(multi[2], vtki.UniformGrid)\n assert isinstance(multi[3], vtki.PolyData)\n assert isinstance(multi[4], vtki.RectilinearGrid)\n\n\ndef test_multi_block_set_get_ers():\n \"\"\"This puts all of the example data objects into a a MultiBlock container\"\"\"\n multi = vtki.MultiBlock()\n # Set the number of blocks\n multi.n_blocks = 6\n assert multi.GetNumberOfBlocks() == 6 # Check that VTK side registered it\n assert multi.n_blocks == 6 # Check vtki side registered it\n # Add data to the MultiBlock\n data = ex.load_rectilinear()\n multi[1, 'rect'] = data\n # Make sure number of blocks is constant\n assert multi.n_blocks == 6\n # Check content\n assert isinstance(multi[1], vtki.RectilinearGrid)\n for i in [0,2,3,4,5]:\n assert multi[i] == None\n # Check the bounds\n assert multi.bounds == list(data.bounds)\n multi[5] = ex.load_uniform()\n multi.set_block_name(5, 'uni')\n assert isinstance(multi.get(5), vtki.UniformGrid)\n # Test get by name\n assert isinstance(multi['uni'], vtki.UniformGrid)\n assert isinstance(multi['rect'], vtki.RectilinearGrid)\n # Test the del operator\n del multi[0]\n assert multi.n_blocks == 5\n # Make sure the rect grid was moved up\n assert isinstance(multi[0], vtki.RectilinearGrid)\n assert multi.get_block_name(0) == 'rect'\n assert multi.get_block_name(2) == None\n # test del by name\n del multi['uni']\n assert multi.n_blocks == 4\n # test the pop operator\n pop = multi.pop(0)\n assert isinstance(pop, vtki.RectilinearGrid)\n assert multi.n_blocks == 3\n\n\n# def test_mutli_block_clean():\n# # now test a clean of the null values\n# multi = vtki.MultiBlock()\n# multi[1, 'rect'] = ex.load_rectilinear()\n# multi[5, 'uni'] = ex.load_uniform()\n# # perfromt he clean to remove all Null elements\n# multi.clean()\n# assert multi.n_blocks == 2\n# assert multi.GetNumberOfBlocks() == 2\n# assert isinstance(multi[0], vtki.RectilinearGrid)\n# assert isinstance(multi[1], vtki.UniformGrid)\n# assert multi.get_block_name(0) == 'rect'\n# assert multi.get_block_name(1) == 'uni'\n\n\n\ndef test_multi_block_repr():\n multi = vtki.MultiBlock()\n # Add examples\n multi.append(ex.load_ant())\n multi.append(ex.load_sphere())\n multi.append(ex.load_uniform())\n multi.append(ex.load_airplane())\n multi.append(None)\n # Now check everything\n assert multi.n_blocks == 5\n assert multi._repr_html_() is not None\n\n\n@pytest.mark.parametrize('binary', [True, False])\n@pytest.mark.parametrize('extension', ['vtm', 'vtmb'])\ndef test_multi_block_io(extension, binary, tmpdir):\n filename = str(tmpdir.mkdir(\"tmpdir\").join('tmp.%s' % extension))\n multi = vtki.MultiBlock()\n # Add examples\n multi.append(ex.load_ant())\n multi.append(ex.load_sphere())\n multi.append(ex.load_uniform())\n multi.append(ex.load_airplane())\n multi.append(ex.load_globe())\n # Now check everything\n assert multi.n_blocks == 5\n # Save it out\n multi.save(filename, binary)\n foo = vtki.MultiBlock(filename)\n assert foo.n_blocks == multi.n_blocks\n\n\ndef test_extract_geometry():\n multi = vtki.MultiBlock()\n # Add examples\n multi.append(ex.load_ant())\n multi.append(ex.load_sphere())\n multi.append(ex.load_uniform())\n multi.append(ex.load_airplane())\n multi.append(ex.load_globe())\n # Now check everything\n assert multi.n_blocks == 5\n # Now apply the geometry filter to combine a plethora of data blocks\n geom = multi.extract_geometry()\n assert isinstance(geom, vtki.PolyData)\n\n\ndef test_combine_filter():\n multi = vtki.MultiBlock()\n # Add examples\n multi.append(ex.load_ant())\n multi.append(ex.load_sphere())\n multi.append(ex.load_uniform())\n multi.append(ex.load_airplane())\n multi.append(ex.load_globe())\n # Now check everything\n assert multi.n_blocks == 5\n # Now apply the geometry filter to combine a plethora of data blocks\n geom = multi.combine()\n assert isinstance(geom, vtki.UnstructuredGrid)\n","sub_path":"tests/test_container.py","file_name":"test_container.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25999673","text":"import json\n\nif __name__ == \"__main__\":\n print('LIST PROCESSING')\n my_list = []\n option_dict = {\n 1: 'Display the list',\n 2: 'Exit',\n 3: 'Add elements to you list',\n 4: 'Remove element from you list',\n 5: 'Extend the list',\n 6: 'Display the length of the list',\n 7: 'Show the datatype of the list',\n 8: 'Access a list element',\n 9: 'Change an item within the list',\n 10: 'Insert an item at a specific position within the list',\n 11: 'Delete an item from a specific position within the list',\n 12: 'Sort the items of the list',\n 13: 'Reverse the items of the list',\n 14: 'Clear the list'\n }\n print(json.dumps(option_dict, indent=4))\n\n while True:\n i = int(input(\"Select an option : \"))\n if i == 1:\n print(my_list)\n elif i == 2:\n break\n elif i == 3:\n my_list.append(input('Enter the element you want to add : '))\n elif i == 4:\n my_list.remove(input('Enter the element you want to remove : '))\n elif i == 5:\n my_list.extend(input('Enter the list you want to add : '))\n elif i == 6:\n print(len(my_list))\n elif i == 7:\n print(type(my_list))\n elif i == 8:\n print(my_list[int(input('Enter the index of the item : '))])\n elif i == 9:\n idx = int(input('Enter the index of the item : '))\n my_list[idx] = input('Enter the item : ')\n elif i == 10:\n my_list.insert(int(input('Enter the index of the item : ')), input('Enter the item : '))\n elif i == 11:\n my_list.pop(int(input('Enter the index of the item : ')))\n elif i == 12:\n my_list.sort()\n elif i == 13:\n my_list.reverse()\n elif i == 14:\n my_list.clear()\n else:\n print(\"Please enter a valid option\")","sub_path":"Biji/List.py","file_name":"List.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"248195751","text":"# --------------------------------------------------------------------------------- #\n# CUSTOMTREECTRL wxPython IMPLEMENTATION\n# Inspired By And Heavily Based On wxGenericTreeCtrl.\n#\n# Andrea Gavana, @ 17 May 2006\n# Latest Revision: 28 Nov 2010, 16.00 GMT\n#\n#\n# TODO List\n#\n# Almost All The Features Of wx.TreeCtrl Are Available, And There Is Practically\n# No Limit In What Could Be Added To This Class. The First Things That Comes\n# To My Mind Are:\n#\n# 1. Try To Implement A More Flicker-Free Background Image In Cases Like\n# Centered Or Stretched Image (Now CustomTreeCtrl Supports Only Tiled\n# Background Images).\n#\n# 2. Try To Mimic Windows wx.TreeCtrl Expanding/Collapsing behaviour: CustomTreeCtrl\n# Suddenly Expands/Collapses The Nodes On Mouse Click While The Native Control\n# Has Some Kind Of \"Smooth\" Expanding/Collapsing, Like A Wave. I Don't Even\n# Know Where To Start To Do That.\n#\n# 3. Speed Up General OnPaint Things? I Have No Idea, Here CustomTreeCtrl Is Quite\n# Fast, But We Should See On Slower Machines.\n#\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# gavana@kpo.kz\n# andrea.gavana@gmail.com\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------------- #\n\n\n\"\"\"\nCustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with some more\nenhancements.\n\n\nDescription\n===========\n\nCustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the\nsame base functionalities plus some more enhancements. This class does not rely on\nthe native control, as it is a full owner-drawn tree control.\nApart of the base functionalities of CustomTreeCtrl (described below), in addition\nto the standard `wx.TreeCtrl` behaviour this class supports:\n\n* CheckBox-type items: checkboxes are easy to handle, just selected or unselected\n state with no particular issues in handling the item's children;\n* Added support for 3-state value checkbox items;\n* RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I\n needed some way to handle them, that made sense. So, I used the following approach:\n\n - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,\n only one of a set of radiobuttons that share a common parent can be checked at\n once. If a radiobutton node becomes checked, then all of its peer radiobuttons\n must be unchecked.\n - If a radiobutton node becomes unchecked, then all of its child nodes will become\n inactive.\n\n* Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on\n hovering;\n* Multiline text items (**note**: to add a newline character in a multiline item, press\n ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by CustomTreeCtrl to finish\n the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation);\n* Enabling/disabling items (together with their plain or grayed out icons);\n* Whatever non-toplevel widget can be attached next to an item;\n* Possibility to horizontally align the widgets attached to tree items on the\n same tree level.\n* Default selection style, gradient (horizontal/vertical) selection style and Windows\n Vista selection style;\n* Customized drag and drop images built on the fly;\n* Setting the CustomTreeCtrl item buttons to a personalized imagelist;\n* Setting the CustomTreeCtrl check/radio item icons to a personalized imagelist;\n* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);\n* Using an image as a CustomTreeCtrl background (currently only in \"tile\" mode);\n* Adding images to any item in the leftmost area of the CustomTreeCtrl client window.\n\nAnd a lot more. Check the demo for an almost complete review of the functionalities.\n\n\nBase Functionalities\n====================\n\nCustomTreeCtrl supports all the wx.TreeCtrl styles, except:\n\n- ``TR_EXTENDED``: supports for this style is on the todo list (am I sure of this?).\n\nPlus it has 3 more styles to handle checkbox-type items:\n\n- ``TR_AUTO_CHECK_CHILD``: automatically checks/unchecks the item children;\n- ``TR_AUTO_CHECK_PARENT``: automatically checks/unchecks the item parent;\n- ``TR_AUTO_TOGGLE_CHILD``: automatically toggles the item children.\n\nAnd a style you can use to force the horizontal alignment of all the widgets\nattached to the tree items:\n\n- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belongiing to the item on the\n same tree level.\n\n\nAll the methods available in `wx.TreeCtrl` are also available in CustomTreeCtrl.\n\n\nEvents\n======\n\nAll the events supported by `wx.TreeCtrl` are also available in CustomTreeCtrl, with\na few exceptions:\n\n- ``EVT_TREE_GET_INFO`` (don't know what this means);\n- ``EVT_TREE_SET_INFO`` (don't know what this means);\n- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);\n- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).\n\nPlus, CustomTreeCtrl supports the events related to the checkbutton-type items:\n\n- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;\n- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.\n\nAnd to hyperlink-type items:\n\n- ``EVT_TREE_ITEM_HYPERLINK``: an hyperlink item has been clicked (this event is sent\n after the ``EVT_TREE_SEL_CHANGED`` event).\n\n\nSupported Platforms\n===================\n\nCustomTreeCtrl has been tested on the following platforms:\n * Windows (Windows XP);\n * GTK (Thanks to Michele Petrazzo);\n * Mac OS (Thanks to John Jackson).\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n============================== =========== ==================================================\nWindow Styles Hex Value Description\n============================== =========== ==================================================\n``TR_NO_BUTTONS`` 0x0 For convenience to document that no buttons are to be drawn.\n``TR_SINGLE`` 0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.\n``TR_HAS_BUTTONS`` 0x1 Use this style to show + and - buttons to the left of parent items.\n``TR_NO_LINES`` 0x4 Use this style to hide vertical level connectors.\n``TR_LINES_AT_ROOT`` 0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.\n``TR_DEFAULT_STYLE`` 0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.\n``TR_TWIST_BUTTONS`` 0x10 Use old Mac-twist style buttons.\n``TR_MULTIPLE`` 0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.\n``TR_EXTENDED`` 0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).\n``TR_HAS_VARIABLE_ROW_HEIGHT`` 0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.\n``TR_EDIT_LABELS`` 0x200 Use this style if you wish the user to be able to edit labels in the tree control.\n``TR_ROW_LINES`` 0x400 Use this style to draw a contrasting border between displayed rows.\n``TR_HIDE_ROOT`` 0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.\n``TR_FULL_ROW_HIGHLIGHT`` 0x2000 Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.\n``TR_AUTO_CHECK_CHILD`` 0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.\n``TR_AUTO_TOGGLE_CHILD`` 0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.\n``TR_AUTO_CHECK_PARENT`` 0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.\n``TR_ALIGN_WINDOWS`` 0x20000 Flag used to align windows (in items with windows) at the same horizontal position.\n============================== =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n============================== ==================================================\nEvent Name Description\n============================== ==================================================\n``EVT_TREE_BEGIN_DRAG`` Begin dragging with the left mouse button.\n``EVT_TREE_BEGIN_LABEL_EDIT`` Begin editing a label. This can be prevented by calling `Veto()`.\n``EVT_TREE_BEGIN_RDRAG`` Begin dragging with the right mouse button.\n``EVT_TREE_DELETE_ITEM`` Delete an item.\n``EVT_TREE_END_DRAG`` End dragging with the left or right mouse button.\n``EVT_TREE_END_LABEL_EDIT`` End editing a label. This can be prevented by calling `Veto()`.\n``EVT_TREE_GET_INFO`` Request information from the application (not implemented in `CustomTreeCtrl`).\n``EVT_TREE_ITEM_ACTIVATED`` The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.\n``EVT_TREE_ITEM_CHECKED`` A checkbox or radiobox type item has been checked.\n``EVT_TREE_ITEM_CHECKING`` A checkbox or radiobox type item is being checked.\n``EVT_TREE_ITEM_COLLAPSED`` The item has been collapsed.\n``EVT_TREE_ITEM_COLLAPSING`` The item is being collapsed. This can be prevented by calling `Veto()`.\n``EVT_TREE_ITEM_EXPANDED`` The item has been expanded.\n``EVT_TREE_ITEM_EXPANDING`` The item is being expanded. This can be prevented by calling `Veto()`.\n``EVT_TREE_ITEM_GETTOOLTIP`` The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`).\n``EVT_TREE_ITEM_HYPERLINK`` An hyperlink type item has been clicked.\n``EVT_TREE_ITEM_MENU`` The context menu for the selected item has been requested, either by a right click or by using the menu key.\n``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in `CustomTreeCtrl`).\n``EVT_TREE_ITEM_RIGHT_CLICK`` The user has clicked the item with the right mouse button.\n``EVT_TREE_KEY_DOWN`` A key has been pressed.\n``EVT_TREE_SEL_CHANGED`` Selection has changed.\n``EVT_TREE_SEL_CHANGING`` Selection is changing. This can be prevented by calling `Veto()`.\n``EVT_TREE_SET_INFO`` Information is being supplied to the application (not implemented in `CustomTreeCtrl`).\n``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in `CustomTreeCtrl`).\n============================== ==================================================\n\n\nLicense And Version\n===================\n\nCustomTreeCtrl is distributed under the wxPython license.\n\nLatest Revision: Andrea Gavana @ 28 Nov 2010, 16.00 GMT\n\nVersion 2.3\n\n\"\"\"\n\n# Version Info\n__version__ = \"2.3\"\n\nimport wx\nfrom wx.lib.expando import ExpandoTextCtrl\n\n# ----------------------------------------------------------------------------\n# Constants\n# ----------------------------------------------------------------------------\n\n_NO_IMAGE = -1\n_PIXELS_PER_UNIT = 10\n\n# Start editing the current item after half a second (if the mouse hasn't\n# been clicked/moved)\n_DELAY = 500\n\n# wxPython version string\n_VERSION_STRING = wx.VERSION_STRING\n\n# ----------------------------------------------------------------------------\n# Constants\n# ----------------------------------------------------------------------------\n\n# Enum for different images associated with a treectrl item\nTreeItemIcon_Normal = 0 # not selected, not expanded\nTreeItemIcon_Selected = 1 # selected, not expanded\nTreeItemIcon_Expanded = 2 # not selected, expanded\nTreeItemIcon_SelectedExpanded = 3 # selected, expanded\n\nTreeItemIcon_Checked = 0 # check button, checked\nTreeItemIcon_NotChecked = 1 # check button, not checked\nTreeItemIcon_Undetermined = 2 # check button, undetermined\nTreeItemIcon_Flagged = 3 # radio button, selected\nTreeItemIcon_NotFlagged = 4 # radio button, not selected\n\n# ----------------------------------------------------------------------------\n# CustomTreeCtrl flags\n# ----------------------------------------------------------------------------\n\nTR_NO_BUTTONS = wx.TR_NO_BUTTONS # for convenience\n\"\"\" For convenience to document that no buttons are to be drawn. \"\"\"\nTR_HAS_BUTTONS = wx.TR_HAS_BUTTONS # draw collapsed/expanded btns\n\"\"\" Use this style to show + and - buttons to the left of parent items. \"\"\"\nTR_NO_LINES = wx.TR_NO_LINES # don't draw lines at all\n\"\"\" Use this style to hide vertical level connectors. \"\"\"\nTR_LINES_AT_ROOT = wx.TR_LINES_AT_ROOT # connect top-level nodes\n\"\"\" Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is\"\"\" \\\n\"\"\" set and ``TR_NO_LINES`` is not set. \"\"\"\nTR_TWIST_BUTTONS = wx.TR_TWIST_BUTTONS # still used by wxTreeListCtrl\n\"\"\" Use old Mac-twist style buttons. \"\"\"\nTR_SINGLE = wx.TR_SINGLE # for convenience\n\"\"\" For convenience to document that only one item may be selected at a time. Selecting another\"\"\" \\\n\"\"\" item causes the current selection, if any, to be deselected. This is the default. \"\"\"\nTR_MULTIPLE = wx.TR_MULTIPLE # can select multiple items\n\"\"\" Use this style to allow a range of items to be selected. If a second range is selected,\"\"\" \\\n\"\"\" the current range, if any, is deselected. \"\"\"\nTR_EXTENDED = wx.TR_EXTENDED # TODO: allow extended selection\n\"\"\" Use this style to allow disjoint items to be selected. (Only partially implemented;\"\"\" \\\n\"\"\" may not work in all cases). \"\"\"\nTR_HAS_VARIABLE_ROW_HEIGHT = wx.TR_HAS_VARIABLE_ROW_HEIGHT # what it says\n\"\"\" Use this style to cause row heights to be just big enough to fit the content.\"\"\" \\\n\"\"\" If not set, all rows use the largest row height. The default is that this flag is unset. \"\"\"\nTR_EDIT_LABELS = wx.TR_EDIT_LABELS # can edit item labels\n\"\"\" Use this style if you wish the user to be able to edit labels in the tree control. \"\"\"\nTR_ROW_LINES = wx.TR_ROW_LINES # put border around items\n\"\"\" Use this style to draw a contrasting border between displayed rows. \"\"\"\nTR_HIDE_ROOT = wx.TR_HIDE_ROOT # don't display root node\n\"\"\" Use this style to suppress the display of the root node, effectively causing the\"\"\" \\\n\"\"\" first-level nodes to appear as a series of root nodes. \"\"\"\nTR_FULL_ROW_HIGHLIGHT = wx.TR_FULL_ROW_HIGHLIGHT # highlight full horz space\n\"\"\" Use this style to have the background colour and the selection highlight extend \"\"\" \\\n\"\"\" over the entire horizontal row of the tree control window. \"\"\"\n\nTR_AUTO_CHECK_CHILD = 0x04000 # only meaningful for checkboxes\n\"\"\" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked\"\"\" \\\n\"\"\" its children are checked/unchecked as well. \"\"\"\nTR_AUTO_TOGGLE_CHILD = 0x08000 # only meaningful for checkboxes\n\"\"\" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked\"\"\" \\\n\"\"\" its children are toggled accordingly. \"\"\"\nTR_AUTO_CHECK_PARENT = 0x10000 # only meaningful for checkboxes\n\"\"\" Only meaningful foe checkbox-type items: when a child item is checked/unchecked\"\"\" \\\n\"\"\" its parent item is checked/unchecked as well. \"\"\"\nTR_ALIGN_WINDOWS = 0x20000 # to align windows horizontally for items at the same level\n\"\"\" Flag used to align windows (in items with windows) at the same horizontal position. \"\"\"\n\nTR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE # default style for the tree control\n\"\"\" The set of flags that are closest to the defaults for the native control for a\"\"\" \\\n\"\"\" particular toolkit. \"\"\"\n\n# Values for the `flags` parameter of CustomTreeCtrl.HitTest() which determine\n# where exactly the specified point is situated:\n\nTREE_HITTEST_ABOVE = wx.TREE_HITTEST_ABOVE\nTREE_HITTEST_BELOW = wx.TREE_HITTEST_BELOW\nTREE_HITTEST_NOWHERE = wx.TREE_HITTEST_NOWHERE\n# on the button associated with an item.\nTREE_HITTEST_ONITEMBUTTON = wx.TREE_HITTEST_ONITEMBUTTON\n# on the bitmap associated with an item.\nTREE_HITTEST_ONITEMICON = wx.TREE_HITTEST_ONITEMICON\n# on the indent associated with an item.\nTREE_HITTEST_ONITEMINDENT = wx.TREE_HITTEST_ONITEMINDENT\n# on the label (string) associated with an item.\nTREE_HITTEST_ONITEMLABEL = wx.TREE_HITTEST_ONITEMLABEL\n# on the right of the label associated with an item.\nTREE_HITTEST_ONITEMRIGHT = wx.TREE_HITTEST_ONITEMRIGHT\n# on the label (string) associated with an item.\nTREE_HITTEST_ONITEMSTATEICON = wx.TREE_HITTEST_ONITEMSTATEICON\n# on the left of the CustomTreeCtrl.\nTREE_HITTEST_TOLEFT = wx.TREE_HITTEST_TOLEFT\n# on the right of the CustomTreeCtrl.\nTREE_HITTEST_TORIGHT = wx.TREE_HITTEST_TORIGHT\n# on the upper part (first half) of the item.\nTREE_HITTEST_ONITEMUPPERPART = wx.TREE_HITTEST_ONITEMUPPERPART\n# on the lower part (second half) of the item.\nTREE_HITTEST_ONITEMLOWERPART = wx.TREE_HITTEST_ONITEMLOWERPART\n# on the check icon, if present\nTREE_HITTEST_ONITEMCHECKICON = 0x4000\n# anywhere on the item\nTREE_HITTEST_ONITEM = TREE_HITTEST_ONITEMICON | TREE_HITTEST_ONITEMLABEL | TREE_HITTEST_ONITEMCHECKICON\n\nTREE_ITEMTYPE_NORMAL = 0\nTREE_ITEMTYPE_CHECK = 1\nTREE_ITEMTYPE_RADIO = 2\n\n# Background Image Style\n_StyleTile = 0\n_StyleStretch = 1\n\n# Windows Vista Colours\n_rgbSelectOuter = wx.Colour(170, 200, 245)\n_rgbSelectInner = wx.Colour(230, 250, 250)\n_rgbSelectTop = wx.Colour(210, 240, 250)\n_rgbSelectBottom = wx.Colour(185, 215, 250)\n_rgbNoFocusTop = wx.Colour(250, 250, 250)\n_rgbNoFocusBottom = wx.Colour(235, 235, 235)\n_rgbNoFocusOuter = wx.Colour(220, 220, 220)\n_rgbNoFocusInner = wx.Colour(245, 245, 245)\n\n# Flags for wx.RendererNative\n_CONTROL_EXPANDED = 8\n_CONTROL_CURRENT = 16\n\n\n# ----------------------------------------------------------------------------\n# CustomTreeCtrl events and binding for handling them\n# ----------------------------------------------------------------------------\n\nwxEVT_TREE_BEGIN_DRAG = wx.wxEVT_COMMAND_TREE_BEGIN_DRAG\nwxEVT_TREE_BEGIN_RDRAG = wx.wxEVT_COMMAND_TREE_BEGIN_RDRAG\nwxEVT_TREE_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT\nwxEVT_TREE_END_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT\nwxEVT_TREE_DELETE_ITEM = wx.wxEVT_COMMAND_TREE_DELETE_ITEM\nwxEVT_TREE_GET_INFO = wx.wxEVT_COMMAND_TREE_GET_INFO\nwxEVT_TREE_SET_INFO = wx.wxEVT_COMMAND_TREE_SET_INFO\nwxEVT_TREE_ITEM_EXPANDED = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDED\nwxEVT_TREE_ITEM_EXPANDING = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDING\nwxEVT_TREE_ITEM_COLLAPSED = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSED\nwxEVT_TREE_ITEM_COLLAPSING = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSING\nwxEVT_TREE_SEL_CHANGED = wx.wxEVT_COMMAND_TREE_SEL_CHANGED\nwxEVT_TREE_SEL_CHANGING = wx.wxEVT_COMMAND_TREE_SEL_CHANGING\nwxEVT_TREE_KEY_DOWN = wx.wxEVT_COMMAND_TREE_KEY_DOWN\nwxEVT_TREE_ITEM_ACTIVATED = wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED\nwxEVT_TREE_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK\nwxEVT_TREE_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK\nwxEVT_TREE_END_DRAG = wx.wxEVT_COMMAND_TREE_END_DRAG\nwxEVT_TREE_STATE_IMAGE_CLICK = wx.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK\nwxEVT_TREE_ITEM_GETTOOLTIP = wx.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP\nwxEVT_TREE_ITEM_MENU = wx.wxEVT_COMMAND_TREE_ITEM_MENU\nwxEVT_TREE_ITEM_CHECKING = wx.NewEventType()\nwxEVT_TREE_ITEM_CHECKED = wx.NewEventType()\nwxEVT_TREE_ITEM_HYPERLINK = wx.NewEventType()\n\nEVT_TREE_BEGIN_DRAG = wx.EVT_TREE_BEGIN_DRAG\n\"\"\" Begin dragging with the left mouse button. \"\"\"\nEVT_TREE_BEGIN_RDRAG = wx.EVT_TREE_BEGIN_RDRAG\n\"\"\" Begin dragging with the right mouse button. \"\"\"\nEVT_TREE_BEGIN_LABEL_EDIT = wx.EVT_TREE_BEGIN_LABEL_EDIT\n\"\"\" Begin editing a label. This can be prevented by calling `Veto()`. \"\"\"\nEVT_TREE_END_LABEL_EDIT = wx.EVT_TREE_END_LABEL_EDIT\n\"\"\" End editing a label. This can be prevented by calling `Veto()`. \"\"\"\nEVT_TREE_DELETE_ITEM = wx.EVT_TREE_DELETE_ITEM\n\"\"\" Delete an item. \"\"\"\nEVT_TREE_GET_INFO = wx.EVT_TREE_GET_INFO\n\"\"\" Request information from the application (not implemented in `CustomTreeCtrl`). \"\"\"\nEVT_TREE_SET_INFO = wx.EVT_TREE_SET_INFO\n\"\"\" Information is being supplied to the application (not implemented in `CustomTreeCtrl`). \"\"\"\nEVT_TREE_ITEM_EXPANDED = wx.EVT_TREE_ITEM_EXPANDED\n\"\"\" The item has been expanded. \"\"\"\nEVT_TREE_ITEM_EXPANDING = wx.EVT_TREE_ITEM_EXPANDING\n\"\"\" The item is being expanded. This can be prevented by calling `Veto()`. \"\"\"\nEVT_TREE_ITEM_COLLAPSED = wx.EVT_TREE_ITEM_COLLAPSED\n\"\"\" The item has been collapsed. \"\"\"\nEVT_TREE_ITEM_COLLAPSING = wx.EVT_TREE_ITEM_COLLAPSING\n\"\"\" The item is being collapsed. This can be prevented by calling `Veto()`. \"\"\"\nEVT_TREE_SEL_CHANGED = wx.EVT_TREE_SEL_CHANGED\n\"\"\" Selection has changed. \"\"\"\nEVT_TREE_SEL_CHANGING = wx.EVT_TREE_SEL_CHANGING\n\"\"\" Selection is changing. This can be prevented by calling `Veto()`. \"\"\"\nEVT_TREE_KEY_DOWN = wx.EVT_TREE_KEY_DOWN\n\"\"\" A key has been pressed. \"\"\"\nEVT_TREE_ITEM_ACTIVATED = wx.EVT_TREE_ITEM_ACTIVATED\n\"\"\" The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard. \"\"\"\nEVT_TREE_ITEM_RIGHT_CLICK = wx.EVT_TREE_ITEM_RIGHT_CLICK\n\"\"\" The user has clicked the item with the right mouse button. \"\"\"\nEVT_TREE_ITEM_MIDDLE_CLICK = wx.EVT_TREE_ITEM_MIDDLE_CLICK\n\"\"\" The user has clicked the item with the middle mouse button (not implemented in `CustomTreeCtrl`). \"\"\"\nEVT_TREE_END_DRAG = wx.EVT_TREE_END_DRAG\n\"\"\" End dragging with the left or right mouse button. \"\"\"\nEVT_TREE_STATE_IMAGE_CLICK = wx.EVT_TREE_STATE_IMAGE_CLICK\n\"\"\" The state image has been clicked (not implemented in `CustomTreeCtrl`). \"\"\"\nEVT_TREE_ITEM_GETTOOLTIP = wx.EVT_TREE_ITEM_GETTOOLTIP\n\"\"\" The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`). \"\"\"\nEVT_TREE_ITEM_MENU = wx.EVT_TREE_ITEM_MENU\n\"\"\" The context menu for the selected item has been requested, either by a right click or by using the menu key. \"\"\"\nEVT_TREE_ITEM_CHECKING = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKING, 1)\n\"\"\" A checkbox or radiobox type item is being checked. \"\"\"\nEVT_TREE_ITEM_CHECKED = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKED, 1)\n\"\"\" A checkbox or radiobox type item has been checked. \"\"\"\nEVT_TREE_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_TREE_ITEM_HYPERLINK, 1)\n\"\"\" An hyperlink type item has been clicked. \"\"\"\n\n\n# ----------------------------------------------------------------------------\n\ndef MakeDisabledBitmap(original):\n \"\"\"\n Creates a disabled-looking bitmap starting from the input one.\n\n :param `original`: an instance of `wx.Bitmap` to be greyed-out.\n \"\"\"\n\n img = original.ConvertToImage()\n return wx.BitmapFromImage(img.ConvertToGreyscale())\n\n# ----------------------------------------------------------------------------\n\ndef DrawTreeItemButton(win, dc, rect, flags):\n \"\"\"\n Draw the expanded/collapsed icon for a tree control item.\n\n :param `win`: an instance of `wx.Window`;\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the client rectangle where to draw the tree item button;\n :param `flags`: contains ``wx.CONTROL_EXPANDED`` bit for expanded tree items.\n\n :note: This is a simple replacement of `wx.RendererNative.DrawTreeItemButton`.\n\n :note: This method is never used in wxPython versions newer than 2.6.2.1.\n \"\"\"\n\n # white background\n dc.SetPen(wx.GREY_PEN)\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.DrawRectangleRect(rect)\n\n # black lines\n xMiddle = rect.x + rect.width/2\n yMiddle = rect.y + rect.height/2\n\n # half of the length of the horz lines in \"-\" and \"+\"\n halfWidth = rect.width/2 - 2\n dc.SetPen(wx.BLACK_PEN)\n dc.DrawLine(xMiddle - halfWidth, yMiddle,\n xMiddle + halfWidth + 1, yMiddle)\n\n if not flags & _CONTROL_EXPANDED:\n\n # turn \"-\" into \"+\"\n halfHeight = rect.height/2 - 2\n dc.DrawLine(xMiddle, yMiddle - halfHeight,\n xMiddle, yMiddle + halfHeight + 1)\n\n\ndef EventFlagsToSelType(style, shiftDown=False, ctrlDown=False):\n \"\"\"\n Translate the key or mouse event flag to the type of selection we\n are dealing with.\n\n :param `style`: the main L{CustomTreeCtrl} window style flag;\n :param `shiftDown`: ``True`` if the ``Shift`` key is pressed, ``False`` otherwise;\n :param `ctrlDown`: ``True`` if the ``Ctrl`` key is pressed, ``False`` otherwise;\n \"\"\"\n\n is_multiple = (style & TR_MULTIPLE) != 0\n extended_select = shiftDown and is_multiple\n unselect_others = not (extended_select or (ctrlDown and is_multiple))\n\n return is_multiple, extended_select, unselect_others\n\n\n#---------------------------------------------------------------------------\n# DragImage Implementation\n# This Class Handles The Creation Of A Custom Image In Case Of Item Drag\n# And Drop.\n#---------------------------------------------------------------------------\n\nclass DragImage(wx.DragImage):\n \"\"\"\n This class handles the creation of a custom image in case of item drag\n and drop.\n \"\"\"\n\n def __init__(self, treeCtrl, item):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `treeCtrl`: the parent L{CustomTreeCtrl};\n :param `item`: one of the tree control item (an instance of L{GenericTreeItem}).\n \"\"\"\n\n text = item.GetText()\n font = item.Attr().GetFont()\n colour = item.Attr().GetTextColour()\n if not colour:\n colour = wx.BLACK\n if not font:\n font = treeCtrl._normalFont\n\n backcolour = treeCtrl.GetBackgroundColour()\n r, g, b = int(backcolour.Red()), int(backcolour.Green()), int(backcolour.Blue())\n backcolour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)\n backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])\n self._backgroundColour = backcolour\n\n tempdc = wx.ClientDC(treeCtrl)\n tempdc.SetFont(font)\n width, height, dummy = tempdc.GetMultiLineTextExtent(text + \"M\")\n\n image = item.GetCurrentImage()\n\n image_w, image_h = 0, 0\n wcheck, hcheck = 0, 0\n itemcheck = None\n itemimage = None\n ximagepos = 0\n yimagepos = 0\n xcheckpos = 0\n ycheckpos = 0\n\n if image != _NO_IMAGE:\n if treeCtrl._imageListNormal:\n image_w, image_h = treeCtrl._imageListNormal.GetSize(image)\n image_w += 4\n itemimage = treeCtrl._imageListNormal.GetBitmap(image)\n\n checkimage = item.GetCurrentCheckedImage()\n\n if checkimage is not None:\n if treeCtrl._imageListCheck:\n wcheck, hcheck = treeCtrl._imageListCheck.GetSize(checkimage)\n wcheck += 4\n itemcheck = treeCtrl._imageListCheck.GetBitmap(checkimage)\n\n total_h = max(hcheck, height)\n total_h = max(image_h, total_h)\n\n if image_w:\n ximagepos = wcheck\n yimagepos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0]\n\n if checkimage is not None:\n xcheckpos = 2\n ycheckpos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0] + 2\n\n extraH = ((total_h > height) and [(total_h - height)/2] or [0])[0]\n\n xtextpos = wcheck + image_w\n ytextpos = extraH\n\n total_h = max(image_h, hcheck)\n total_h = max(total_h, height)\n\n if total_h < 30:\n total_h += 2 # at least 2 pixels\n else:\n total_h += total_h/10 # otherwise 10% extra spacing\n\n total_w = image_w + wcheck + width\n\n self._total_w = total_w\n self._total_h = total_h\n self._itemimage = itemimage\n self._itemcheck = itemcheck\n self._text = text\n self._colour = colour\n self._font = font\n self._xtextpos = xtextpos\n self._ytextpos = ytextpos\n self._ximagepos = ximagepos\n self._yimagepos = yimagepos\n self._xcheckpos = xcheckpos\n self._ycheckpos = ycheckpos\n self._textwidth = width\n self._textheight = height\n self._extraH = extraH\n\n self._bitmap = self.CreateBitmap()\n\n wx.DragImage.__init__(self, self._bitmap)\n\n\n def CreateBitmap(self):\n \"\"\" Actually creates the drag and drop bitmap for L{DragImage}. \"\"\"\n\n memory = wx.MemoryDC()\n\n bitmap = wx.EmptyBitmap(self._total_w, self._total_h)\n memory.SelectObject(bitmap)\n\n if wx.Platform == '__WXMAC__':\n memory.SetBackground(wx.TRANSPARENT_BRUSH)\n else:\n memory.SetBackground(wx.Brush(self._backgroundColour))\n memory.SetBackgroundMode(wx.TRANSPARENT)\n memory.SetFont(self._font)\n memory.SetTextForeground(self._colour)\n memory.Clear()\n\n if self._itemimage:\n memory.DrawBitmap(self._itemimage, self._ximagepos, self._yimagepos, True)\n\n if self._itemcheck:\n memory.DrawBitmap(self._itemcheck, self._xcheckpos, self._ycheckpos, True)\n\n textrect = wx.Rect(self._xtextpos, self._ytextpos+self._extraH, self._textwidth, self._textheight)\n memory.DrawLabel(self._text, textrect)\n\n memory.SelectObject(wx.NullBitmap)\n\n # Gtk and Windows unfortunatly don't do so well with transparent\n # drawing so this hack corrects the image to have a transparent\n # background.\n if wx.Platform != '__WXMAC__':\n timg = bitmap.ConvertToImage()\n if not timg.HasAlpha():\n timg.InitAlpha()\n for y in xrange(timg.GetHeight()):\n for x in xrange(timg.GetWidth()):\n pix = wx.Colour(timg.GetRed(x, y),\n timg.GetGreen(x, y),\n timg.GetBlue(x, y))\n if pix == self._backgroundColour:\n timg.SetAlpha(x, y, 0)\n bitmap = timg.ConvertToBitmap()\n return bitmap\n\n\n# ----------------------------------------------------------------------------\n# TreeItemAttr: a structure containing the visual attributes of an item\n# ----------------------------------------------------------------------------\n\nclass TreeItemAttr(object):\n \"\"\" Creates the item attributes (text colour, background colour and font). \"\"\"\n\n def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `colText`: the text colour;\n :param `colBack`: the tree item background colour;\n :param `font`: the tree item font.\n \"\"\"\n\n self._colText = colText\n self._colBack = colBack\n self._font = font\n\n # setters\n def SetTextColour(self, colText):\n \"\"\"\n Sets the text colour attribute.\n\n :param `colText`: an instance of `wx.Colour`.\n \"\"\"\n\n self._colText = colText\n\n\n def SetBackgroundColour(self, colBack):\n \"\"\"\n Sets the item background colour attribute.\n\n :param `colBack`: an instance of `wx.Colour`.\n \"\"\"\n\n self._colBack = colBack\n\n\n def SetFont(self, font):\n \"\"\"\n Sets the item font attribute.\n\n :param `font`: an instance of `wx.Font`.\n \"\"\"\n\n self._font = font\n\n\n # accessors\n def HasTextColour(self):\n \"\"\"Returns whether the attribute has text colour.\"\"\"\n\n return self._colText != wx.NullColour\n\n\n def HasBackgroundColour(self):\n \"\"\"Returns whether the attribute has background colour.\"\"\"\n\n return self._colBack != wx.NullColour\n\n\n def HasFont(self):\n \"\"\"Returns whether the attribute has font.\"\"\"\n\n return self._font != wx.NullFont\n\n\n # getters\n def GetTextColour(self):\n \"\"\"Returns the attribute text colour.\"\"\"\n\n return self._colText\n\n\n def GetBackgroundColour(self):\n \"\"\"Returns the attribute background colour.\"\"\"\n\n return self._colBack\n\n\n def GetFont(self):\n \"\"\"Returns the attribute font.\"\"\"\n\n return self._font\n\n\n# ----------------------------------------------------------------------------\n# CommandTreeEvent Is A Special Subclassing Of wx.PyCommandEvent\n#\n# NB: Note That Not All The Accessors Make Sense For All The Events, See The\n# Event Description Below.\n# ----------------------------------------------------------------------------\n\nclass CommandTreeEvent(wx.PyCommandEvent):\n \"\"\"\n CommandTreeEvent is a special subclassing of `wx.PyCommandEvent`.\n\n :note: Not all the accessors make sense for all the events, see the event description for every method in this class.\n \"\"\"\n\n def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,\n label=None, **kwargs):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `evtType`: the event type;\n :param `evtId`: the event identifier;\n :param `item`: an instance of L{GenericTreeItem};\n :param `evtKey`: a character ordinal;\n :param `point`: an instance of `wx.Point`;\n :param `label`: a L{GenericTreeItem} text label.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, evtType, evtId, **kwargs)\n self._item = item\n self._evtKey = evtKey\n self._pointDrag = point\n self._label = label\n\n\n def GetItem(self):\n \"\"\"\n Gets the item on which the operation was performed or the newly selected\n item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.\n \"\"\"\n\n return self._item\n\n\n def SetItem(self, item):\n \"\"\"\n Sets the item on which the operation was performed or the newly selected\n item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self._item = item\n\n\n def GetOldItem(self):\n \"\"\"\n Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and\n ``EVT_TREE_SEL_CHANGING`` events.\n \"\"\"\n\n return self._itemOld\n\n\n def SetOldItem(self, item):\n \"\"\"\n Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and\n ``EVT_TREE_SEL_CHANGING`` events.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self._itemOld = item\n\n\n def GetPoint(self):\n \"\"\"\n Returns the point where the mouse was when the drag operation started\n (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)\n or the click position.\n \"\"\"\n\n return self._pointDrag\n\n\n def SetPoint(self, pt):\n \"\"\"\n Sets the point where the mouse was when the drag operation started\n (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)\n or the click position.\n\n :param `pt`: an instance of `wx.Point`.\n \"\"\"\n\n self._pointDrag = pt\n\n\n def GetKeyEvent(self):\n \"\"\" Returns the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).\"\"\"\n\n return self._evtKey\n\n\n def GetKeyCode(self):\n \"\"\" Returns the integer key code (for ``EVT_TREE_KEY_DOWN`` event only).\"\"\"\n\n return self._evtKey.GetKeyCode()\n\n\n def SetKeyEvent(self, event):\n \"\"\"\n Sets the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).\n\n :param `event`: a L{TreeEvent} event to be processed.\n \"\"\"\n\n self._evtKey = event\n\n\n def GetLabel(self):\n \"\"\"\n Returns the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and\n ``EVT_TREE_END_LABEL_EDIT`` events only).\n \"\"\"\n\n return self._label\n\n\n def SetLabel(self, label):\n \"\"\"\n Sets the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and\n ``EVT_TREE_END_LABEL_EDIT`` events only).\n\n :param `label`: a string containing the new item text.\n \"\"\"\n\n self._label = label\n\n\n def IsEditCancelled(self):\n \"\"\"\n Returns the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and\n ``EVT_TREE_END_LABEL_EDIT`` events only).\n \"\"\"\n\n return self._editCancelled\n\n\n def SetEditCanceled(self, editCancelled):\n \"\"\"\n Sets the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and\n ``EVT_TREE_END_LABEL_EDIT`` events only).\n\n :param `editCancelled`: ``True`` to cancel the editing, ``False`` otherwise.\n \"\"\"\n\n self._editCancelled = editCancelled\n\n\n def SetToolTip(self, toolTip):\n \"\"\"\n Sets the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).\n\n :param `tooltip`: a string representing the item tooltip.\n \"\"\"\n\n self._label = toolTip\n\n\n def GetToolTip(self):\n \"\"\"Returns the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).\"\"\"\n\n return self._label\n\n\n# ----------------------------------------------------------------------------\n# TreeEvent is a special class for all events associated with tree controls\n#\n# NB: note that not all accessors make sense for all events, see the event\n# descriptions below\n# ----------------------------------------------------------------------------\n\nclass TreeEvent(CommandTreeEvent):\n \"\"\"\n `TreeEvent` is a special class for all events associated with tree controls.\n\n :note: Not all accessors make sense for all events, see the event descriptions below.\n \"\"\"\n def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,\n label=None, **kwargs):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `evtType`: the event type;\n :param `evtId`: the event identifier;\n :param `item`: an instance of L{GenericTreeItem};\n :param `evtKey`: a character ordinal;\n :param `point`: an instance of `wx.Point`;\n :param `label`: a L{GenericTreeItem} text label.\n \"\"\"\n\n CommandTreeEvent.__init__(self, evtType, evtId, item, evtKey, point, label, **kwargs)\n self.notify = wx.NotifyEvent(evtType, evtId)\n\n\n def GetNotifyEvent(self):\n \"\"\"Returns the actual `wx.NotifyEvent`.\"\"\"\n\n return self.notify\n\n\n def IsAllowed(self):\n \"\"\"\n Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or\n ``False`` otherwise (if it was).\n \"\"\"\n\n return self.notify.IsAllowed()\n\n\n def Veto(self):\n \"\"\"\n Prevents the change announced by this event from happening.\n\n :note: It is in general a good idea to notify the user about the reasons\n for vetoing the change because otherwise the applications behaviour (which\n just refuses to do what the user wants) might be quite surprising.\n \"\"\"\n\n self.notify.Veto()\n\n\n def Allow(self):\n \"\"\"\n This is the opposite of L{Veto}: it explicitly allows the event to be processed.\n For most events it is not necessary to call this method as the events are\n allowed anyhow but some are forbidden by default (this will be mentioned\n in the corresponding event description).\n \"\"\"\n\n self.notify.Allow()\n\n\n# -----------------------------------------------------------------------------\n# Auxiliary Classes: TreeRenameTimer\n# -----------------------------------------------------------------------------\n\nclass TreeRenameTimer(wx.Timer):\n \"\"\" Timer used for enabling in-place edit.\"\"\"\n\n def __init__(self, owner):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).\n \"\"\"\n\n wx.Timer.__init__(self)\n self._owner = owner\n\n\n def Notify(self):\n \"\"\" The timer has expired. \"\"\"\n\n self._owner.OnRenameTimer()\n\n\n# -----------------------------------------------------------------------------\n# Auxiliary Classes: TreeTextCtrl\n# This Is The Temporary ExpandoTextCtrl Created When You Edit The Text Of An Item\n# -----------------------------------------------------------------------------\n\nclass TreeTextCtrl(ExpandoTextCtrl):\n \"\"\"\n Control used for in-place edit.\n\n This is a subclass of `ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline\n text items.\n\n :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{CustomTreeCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation.\n \"\"\"\n\n def __init__(self, owner, item=None):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `owner`: the control parent (an instance of L{CustomTreeCtrl});\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self._owner = owner\n self._itemEdited = item\n self._startValue = item.GetText()\n self._finished = False\n self._aboutToFinish = False\n self._currentValue = self._startValue\n\n w = self._itemEdited.GetWidth()\n h = self._itemEdited.GetHeight()\n\n wnd = self._itemEdited.GetWindow()\n if wnd:\n w = w - self._itemEdited.GetWindowSize()[0]\n h = 0\n\n x, y = self._owner.CalcScrolledPosition(item.GetX(), item.GetY())\n\n image_h = 0\n image_w = 0\n\n image = item.GetCurrentImage()\n\n if image != _NO_IMAGE:\n\n if self._owner._imageListNormal:\n image_w, image_h = self._owner._imageListNormal.GetSize(image)\n image_w += 4\n\n else:\n\n raise Exception(\"\\n ERROR: You Must Create An Image List To Use Images!\")\n\n checkimage = item.GetCurrentCheckedImage()\n\n if checkimage is not None:\n wcheck, hcheck = self._owner._imageListCheck.GetSize(checkimage)\n wcheck += 4\n else:\n wcheck = hcheck = 0\n\n if wnd:\n h = max(hcheck, image_h)\n dc = wx.ClientDC(self._owner)\n h = max(h, dc.GetTextExtent(\"Aq\")[1])\n h = h + 2\n\n # FIXME: what are all these hardcoded 4, 8 and 11s really?\n x += image_w + wcheck\n w -= image_w + 4 + wcheck\n\n expandoStyle = wx.WANTS_CHARS\n if wx.Platform in [\"__WXGTK__\", \"__WXMAC__\"]:\n expandoStyle |= wx.SIMPLE_BORDER\n xSize, ySize = w + 25, h\n else:\n expandoStyle |= wx.SUNKEN_BORDER\n xSize, ySize = w + 25, h+2\n\n ExpandoTextCtrl.__init__(self, self._owner, wx.ID_ANY, self._startValue,\n wx.Point(x - 4, y), wx.Size(xSize, ySize),\n expandoStyle)\n\n if wx.Platform == \"__WXMAC__\":\n self.SetFont(owner.GetFont())\n bs = self.GetBestSize()\n self.SetSize((-1, bs.height))\n\n self.Bind(wx.EVT_CHAR, self.OnChar)\n self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)\n\n\n def AcceptChanges(self):\n \"\"\"Accepts/refuses the changes made by the user.\"\"\"\n\n value = self.GetValue()\n\n if value == self._startValue:\n # nothing changed, always accept\n # when an item remains unchanged, the owner\n # needs to be notified that the user decided\n # not to change the tree item label, and that\n # the edit has been cancelled\n self._owner.OnRenameCancelled(self._itemEdited)\n return True\n\n if not self._owner.OnRenameAccept(self._itemEdited, value):\n # vetoed by the user\n return False\n\n # accepted, do rename the item\n self._owner.SetItemText(self._itemEdited, value)\n\n return True\n\n\n def Finish(self):\n \"\"\"Finish editing.\"\"\"\n\n if not self._finished:\n self._finished = True\n self._owner.SetFocusIgnoringChildren()\n self._owner.ResetTextControl()\n\n\n def OnChar(self, event):\n \"\"\"\n Handles the ``wx.EVT_CHAR`` event for L{TreeTextCtrl}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n keycode = event.GetKeyCode()\n shiftDown = event.ShiftDown()\n\n if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:\n if shiftDown:\n event.Skip()\n else:\n self._aboutToFinish = True\n self.SetValue(self._currentValue)\n # Notify the owner about the changes\n self.AcceptChanges()\n # Even if vetoed, close the control (consistent with MSW)\n wx.CallAfter(self.Finish)\n\n elif keycode == wx.WXK_ESCAPE:\n self.StopEditing()\n\n else:\n event.Skip()\n\n\n def OnKeyUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_UP`` event for L{TreeTextCtrl}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n if not self._finished:\n\n # auto-grow the textctrl:\n parentSize = self._owner.GetSize()\n myPos = self.GetPosition()\n mySize = self.GetSize()\n\n dc = wx.ClientDC(self)\n sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + \"M\")\n\n if myPos.x + sx > parentSize.x:\n sx = parentSize.x - myPos.x\n if mySize.x > sx:\n sx = mySize.x\n\n self.SetSize((sx, -1))\n self._currentValue = self.GetValue()\n\n event.Skip()\n\n\n def OnKillFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_KILL_FOCUS`` event for L{TreeTextCtrl}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n if not self._finished and not self._aboutToFinish:\n\n # We must finish regardless of success, otherwise we'll get\n # focus problems:\n\n if not self.AcceptChanges():\n self._owner.OnRenameCancelled(self._itemEdited)\n\n # We must let the native text control handle focus, too, otherwise\n # it could have problems with the cursor (e.g., in wxGTK).\n event.Skip()\n\n\n def StopEditing(self):\n \"\"\"Suddenly stops the editing.\"\"\"\n\n self._owner.OnRenameCancelled(self._itemEdited)\n self.Finish()\n\n\n def item(self):\n \"\"\"Returns the item currently edited.\"\"\"\n\n return self._itemEdited\n\n\n# -----------------------------------------------------------------------------\n# Auxiliary Classes: TreeFindTimer\n# Timer Used To Clear CustomTreeCtrl._findPrefix If No Key Was Pressed For A\n# Sufficiently Long Time.\n# -----------------------------------------------------------------------------\n\nclass TreeFindTimer(wx.Timer):\n \"\"\"\n Timer used to clear the L{CustomTreeCtrl} `_findPrefix` attribute if no\n key was pressed for a sufficiently long time.\n \"\"\"\n\n def __init__(self, owner):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).\n \"\"\"\n\n wx.Timer.__init__(self)\n self._owner = owner\n\n\n def Notify(self):\n \"\"\"The timer has expired.\"\"\"\n\n self._owner._findPrefix = \"\"\n\n\n# -----------------------------------------------------------------------------\n# GenericTreeItem Implementation.\n# This Class Holds All The Information And Methods For Every Single Item In\n# CustomTreeCtrl.\n# -----------------------------------------------------------------------------\n\nclass GenericTreeItem(object):\n \"\"\"\n This class holds all the information and methods for every single item in\n L{CustomTreeCtrl}. This is a generic implementation of `wx.TreeItem`.\n \"\"\"\n\n def __init__(self, parent, text=\"\", ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `parent`: the tree item parent (may be ``None`` for root items);\n :param `text`: the tree item text;\n :param `ct_type`: the tree item kind. May be one of the following integers:\n\n =============== =========================================\n `ct_type` Value Description\n =============== =========================================\n 0 A normal item\n 1 A checkbox-like item\n 2 A radiobutton-type item\n =============== =========================================\n\n :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to\n the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n\n :note: Regarding radiobutton-type items (with `ct_type` = 2), the following\n approach is used:\n\n - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,\n only one of a set of radiobuttons that share a common parent can be checked at\n once. If a radiobutton node becomes checked, then all of its peer radiobuttons\n must be unchecked.\n - If a radiobutton node becomes unchecked, then all of its child nodes will become\n inactive.\n\n \"\"\"\n\n # since there can be very many of these, we save size by chosing\n # the smallest representation for the elements and by ordering\n # the members to avoid padding.\n self._text = text # label to be rendered for item\n self._data = data # user-provided data\n\n self._children = [] # list of children\n self._parent = parent # parent of this item\n\n self._attr = None # attributes???\n\n # tree ctrl images for the normal, selected, expanded and\n # expanded+selected states\n self._images = [-1, -1, -1, -1]\n self._images[TreeItemIcon_Normal] = image\n self._images[TreeItemIcon_Selected] = selImage\n self._images[TreeItemIcon_Expanded] = _NO_IMAGE\n self._images[TreeItemIcon_SelectedExpanded] = _NO_IMAGE\n\n self._checkedimages = [None, None, None, None, None]\n self._leftimage = _NO_IMAGE\n\n self._x = 0 # (virtual) offset from top\n self._y = 0 # (virtual) offset from left\n self._width = 0 # width of this item\n self._height = 0 # height of this item\n\n self._isCollapsed = True\n self._hasHilight = False # same as focused\n self._hasPlus = False # used for item which doesn't have\n # children but has a [+] button\n self._isBold = False # render the label in bold font\n self._isItalic = False # render the label in italic font\n self._ownsAttr = False # delete attribute when done\n self._type = ct_type # item type: 0=normal, 1=check, 2=radio\n self._is3State = False # true for 3-state checkbox items\n self._checked = 0 # only meaningful for check and radio items\n self._enabled = True # flag to enable/disable an item\n self._hypertext = False # indicates if the item is hypertext\n self._visited = False # visited state for an hypertext item\n\n if self._type > 0:\n # do not construct the array for normal items\n self._checkedimages[TreeItemIcon_Checked] = 0\n self._checkedimages[TreeItemIcon_NotChecked] = 1\n self._checkedimages[TreeItemIcon_Undetermined] = 2\n self._checkedimages[TreeItemIcon_Flagged] = 3\n self._checkedimages[TreeItemIcon_NotFlagged] = 4\n\n if parent:\n if parent.GetType() == 2 and not parent.IsChecked():\n # if the node parent is a radio not enabled, we are disabled\n self._enabled = False\n\n self._wnd = wnd # are we holding a window?\n\n if wnd:\n self.SetWindow(wnd)\n\n\n def IsOk(self):\n \"\"\"\n Returns whether the item is ok or not.\n\n :note: This method always returns ``True``, it has been added for\n backward compatibility with the wxWidgets C++ implementation.\n \"\"\"\n\n return True\n\n\n def GetChildren(self):\n \"\"\"Returns the item's children.\"\"\"\n\n return self._children\n\n\n def GetText(self):\n \"\"\"Returns the item text.\"\"\"\n\n return self._text\n\n\n def GetImage(self, which=TreeItemIcon_Normal):\n \"\"\"\n Returns the item image for a particular item state.\n\n :param `which`: can be one of the following bits:\n\n ================================= ========================\n Item State Description\n ================================= ========================\n ``TreeItemIcon_Normal`` To get the normal item image\n ``TreeItemIcon_Selected`` To get the selected item image (i.e. the image which is shown when the item is currently selected)\n ``TreeItemIcon_Expanded`` To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)\n ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)\n ================================= ========================\n\n \"\"\"\n\n return self._images[which]\n\n\n def GetCheckedImage(self, which=TreeItemIcon_Checked):\n \"\"\"\n Returns the item check image.\n\n :param `which`: can be one of the following bits:\n\n ================================= ========================\n Item State Description\n ================================= ========================\n ``TreeItemIcon_Checked`` To get the checkbox checked item image\n ``TreeItemIcon_NotChecked`` To get the checkbox unchecked item image\n ``TreeItemIcon_Undetermined`` To get the checkbox undetermined state item image\n ``TreeItemIcon_Flagged`` To get the radiobutton checked image\n ``TreeItemIcon_NotFlagged`` To get the radiobutton unchecked image\n ================================= ========================\n\n :note: This method is meaningful only for radio & check items.\n \"\"\"\n\n return self._checkedimages[which]\n\n\n def GetLeftImage(self):\n \"\"\"\n Returns the leftmost image associated to this item, i.e. the image on the\n leftmost part of the client area of L{CustomTreeCtrl}.\n \"\"\"\n\n return self._leftimage\n\n\n def GetData(self):\n \"\"\"Returns the data associated to this item.\"\"\"\n\n return self._data\n\n\n def SetImage(self, image, which):\n \"\"\"\n Sets the item image.\n\n :param `image`: an index within the normal image list specifying the image to use;\n :param `which`: the image kind.\n\n :see: L{GetImage} for a description of the `which` parameter.\n \"\"\"\n\n self._images[which] = image\n\n\n def SetLeftImage(self, image):\n \"\"\"\n Sets the item leftmost image, i.e. the image associated to the item on the leftmost\n part of the L{CustomTreeCtrl} client area.\n\n :param `image`: an index within the left image list specifying the image to\n use for the item in the leftmost part of the client area.\n \"\"\"\n\n self._leftimage = image\n\n\n def SetData(self, data):\n \"\"\"\n Sets the data associated to this item.\n\n :param `data`: can be any Python object.\n \"\"\"\n\n self._data = data\n\n\n def SetHasPlus(self, has=True):\n \"\"\"\n Sets whether an item has the 'plus' button.\n\n :param `has`: ``True`` to set the 'plus' button on the item, ``False`` otherwise.\n \"\"\"\n\n self._hasPlus = has\n\n\n def SetBold(self, bold):\n \"\"\"\n Sets the item font bold.\n\n :parameter `bold`: ``True`` to have a bold font item, ``False`` otherwise.\n \"\"\"\n\n self._isBold = bold\n\n\n def SetItalic(self, italic):\n \"\"\"\n Sets the item font italic.\n\n :parameter `italic`: ``True`` to have an italic font item, ``False`` otherwise.\n \"\"\"\n\n self._isItalic = italic\n\n\n def GetX(self):\n \"\"\"Returns the `x` position on an item, in logical coordinates. \"\"\"\n\n return self._x\n\n\n def GetY(self):\n \"\"\"Returns the `y` position on an item, in logical coordinates. \"\"\"\n\n return self._y\n\n\n def SetX(self, x):\n \"\"\"\n Sets the `x` position on an item, in logical coordinates.\n\n :param `x`: an integer specifying the x position of the item.\n \"\"\"\n\n self._x = x\n\n\n def SetY(self, y):\n \"\"\"\n Sets the `y` position on an item, in logical coordinates.\n\n :param `y`: an integer specifying the y position of the item.\n \"\"\"\n\n self._y = y\n\n\n def GetHeight(self):\n \"\"\"Returns the height of the item.\"\"\"\n\n return self._height\n\n\n def GetWidth(self):\n \"\"\"Returns the width of the item.\"\"\"\n\n return self._width\n\n\n def SetHeight(self, h):\n \"\"\"\n Sets the item's height.\n\n :param `h`: an integer specifying the item's height.\n \"\"\"\n\n self._height = h\n\n\n def SetWidth(self, w):\n \"\"\"\n Sets the item's width.\n\n :param `w`: an integer specifying the item's width.\n \"\"\"\n\n self._width = w\n\n\n def SetWindow(self, wnd):\n \"\"\"\n Sets the window associated to the item.\n\n :param `wnd`: a non-toplevel window to be displayed next to the item.\n \"\"\"\n\n self._wnd = wnd\n\n if wnd.GetSizer(): # the window is a complex one hold by a sizer\n size = wnd.GetBestSize()\n else: # simple window, without sizers\n size = wnd.GetSize()\n\n # We have to bind the wx.EVT_SET_FOCUS for the associated window\n # No other solution to handle the focus changing from an item in\n # CustomTreeCtrl and the window associated to an item\n # Do better strategies exist?\n self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)\n\n self._height = size.GetHeight() + 2\n self._width = size.GetWidth()\n self._windowsize = size\n\n # We don't show the window if the item is collapsed\n if self._isCollapsed:\n self._wnd.Show(False)\n\n # The window is enabled only if the item is enabled\n self._wnd.Enable(self._enabled)\n self._windowenabled = self._enabled\n\n\n def GetWindow(self):\n \"\"\"Returns the window associated to the item (if any).\"\"\"\n\n return self._wnd\n\n\n def DeleteWindow(self):\n \"\"\"Deletes the window associated to the item (if any).\"\"\"\n\n if self._wnd:\n self._wnd.Destroy()\n self._wnd = None\n\n\n def GetWindowEnabled(self):\n \"\"\"Returns whether the associated window is enabled or not.\"\"\"\n\n if not self._wnd:\n raise Exception(\"\\nERROR: This Item Has No Window Associated\")\n\n return self._windowenabled\n\n\n def SetWindowEnabled(self, enable=True):\n \"\"\"\n Sets whether the associated window is enabled or not.\n\n :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.\n \"\"\"\n\n if not self._wnd:\n raise Exception(\"\\nERROR: This Item Has No Window Associated\")\n\n self._windowenabled = enable\n self._wnd.Enable(enable)\n\n\n def GetWindowSize(self):\n \"\"\"Returns the associated window size.\"\"\"\n\n return self._windowsize\n\n\n def OnSetFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_SET_FOCUS`` event for the window associated with the item.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n treectrl = self._wnd.GetParent()\n select = treectrl.GetSelection()\n\n # If the window is associated to an item that currently is selected\n # (has focus) we don't kill the focus. Otherwise we do it.\n if select != self:\n treectrl._hasFocus = False\n else:\n treectrl._hasFocus = True\n\n event.Skip()\n\n\n def GetType(self):\n \"\"\"\n Returns the item type.\n\n :see: L{SetType} and L{__init__} for a description of valid item types.\n \"\"\"\n\n return self._type\n\n\n def SetType(self, ct_type):\n \"\"\"\n Sets the item type.\n\n :param `ct_type`: May be one of the following integers:\n\n =============== =========================================\n `ct_type` Value Description\n =============== =========================================\n 0 A normal item\n 1 A checkbox-like item\n 2 A radiobutton-type item\n =============== =========================================\n\n :note: Regarding radiobutton-type items (with `ct_type` = 2), the following\n approach is used:\n\n - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,\n only one of a set of radiobuttons that share a common parent can be checked at\n once. If a radiobutton node becomes checked, then all of its peer radiobuttons\n must be unchecked.\n - If a radiobutton node becomes unchecked, then all of its child nodes will become\n inactive.\n \"\"\"\n\n self._type = ct_type\n\n\n def SetHyperText(self, hyper=True):\n \"\"\"\n Sets whether the item is hypertext or not.\n\n :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.\n \"\"\"\n\n self._hypertext = hyper\n\n\n def SetVisited(self, visited=True):\n \"\"\"\n Sets whether an hypertext item was visited or not.\n\n :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.\n \"\"\"\n\n self._visited = visited\n\n\n def GetVisited(self):\n \"\"\"Returns whether an hypertext item was visited or not.\"\"\"\n\n return self._visited\n\n\n def IsHyperText(self):\n \"\"\"Returns whether the item is hypetext or not.\"\"\"\n\n return self._hypertext\n\n\n def GetParent(self):\n \"\"\"\n Gets the item parent (another instance of L{GenericTreeItem} or ``None`` for\n root items.\n \"\"\"\n\n return self._parent\n\n\n def Insert(self, child, index):\n \"\"\"\n Inserts an item in the item children.\n\n :param `child`: an instance of L{GenericTreeItem};\n :param `index`: the index at which we should insert the new child.\n \"\"\"\n\n self._children.insert(index, child)\n\n\n def Expand(self):\n \"\"\"Expands the item.\"\"\"\n\n self._isCollapsed = False\n\n\n def Collapse(self):\n \"\"\"Collapses the item.\"\"\"\n\n self._isCollapsed = True\n\n\n def SetHilight(self, set=True):\n \"\"\"\n Sets the item focus/unfocus.\n\n :param `set`: ``True`` to set the focus to the item, ``False`` otherwise.\n \"\"\"\n\n self._hasHilight = set\n\n\n def HasChildren(self):\n \"\"\"Returns whether the item has children or not.\"\"\"\n\n return len(self._children) > 0\n\n\n def IsSelected(self):\n \"\"\"Returns whether the item is selected or not.\"\"\"\n\n return self._hasHilight != 0\n\n\n def IsExpanded(self):\n \"\"\"Returns whether the item is expanded or not.\"\"\"\n\n return not self._isCollapsed\n\n\n def GetValue(self):\n \"\"\"\n Returns whether the item is checked or not.\n\n :note: This is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n if self.Is3State():\n return self.Get3StateValue()\n\n return self._checked\n\n\n def Get3StateValue(self):\n \"\"\"\n Gets the state of a 3-state checkbox item.\n\n :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``\n when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined\n state.\n\n :note: This method raises an exception when the function is used with a 2-state\n checkbox item.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n if not self.Is3State():\n raise Exception(\"Get3StateValue can only be used with 3-state checkbox items.\")\n\n return self._checked\n\n\n def Is3State(self):\n \"\"\"\n Returns whether or not the checkbox item is a 3-state checkbox.\n\n :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a\n 2-state checkbox item.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n return self._is3State\n\n\n def Set3StateValue(self, state):\n \"\"\"\n Sets the checkbox item to the given `state`.\n\n :param `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``\n (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).\n\n :note: This method raises an exception when the checkbox item is a 2-state checkbox\n and setting the state to ``wx.CHK_UNDETERMINED``.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n if not self._is3State and state == wx.CHK_UNDETERMINED:\n raise Exception(\"Set3StateValue can only be used with 3-state checkbox items.\")\n\n self._checked = state\n\n\n def Set3State(self, allow):\n \"\"\"\n Sets whether the item has a 3-state value checkbox assigned to it or not.\n\n :param `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it\n to a 2-state checkbox.\n\n :return: ``True`` if the change was successful, ``False`` otherwise.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n if self._type != 1:\n return False\n\n self._is3State = allow\n return True\n\n\n def IsChecked(self):\n \"\"\"\n This is just a maybe more readable synonym for L{GetValue}.\n Returns whether the item is checked or not.\n\n :note: This is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n return self.GetValue()\n\n\n def Check(self, checked=True):\n \"\"\"\n Checks/unchecks an item.\n\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n\n :note: This is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n self._checked = checked\n\n\n def HasPlus(self):\n \"\"\"Returns whether the item has the plus button or not.\"\"\"\n\n return self._hasPlus or self.HasChildren()\n\n\n def IsBold(self):\n \"\"\"Returns whether the item font is bold or not.\"\"\"\n\n return self._isBold != 0\n\n\n def IsItalic(self):\n \"\"\"Returns whether the item font is italic or not.\"\"\"\n\n return self._isItalic != 0\n\n\n def Enable(self, enable=True):\n \"\"\"\n Enables/disables the item.\n\n :param `enable`: ``True`` to enable the item, ``False`` to disable it.\n \"\"\"\n\n self._enabled = enable\n\n\n def IsEnabled(self):\n \"\"\"Returns whether the item is enabled or not.\"\"\"\n\n return self._enabled\n\n\n def GetAttributes(self):\n \"\"\"Returns the item attributes (font, colours).\"\"\"\n\n return self._attr\n\n\n def Attr(self):\n \"\"\"Creates a new attribute (font, colours).\"\"\"\n\n if not self._attr:\n\n self._attr = TreeItemAttr()\n self._ownsAttr = True\n\n return self._attr\n\n\n def SetAttributes(self, attr):\n \"\"\"\n Sets the item attributes (font, colours).\n\n :param `attr`: an instance of L{TreeItemAttr}.\n \"\"\"\n\n if self._ownsAttr:\n del self._attr\n\n self._attr = attr\n self._ownsAttr = False\n\n\n def AssignAttributes(self, attr):\n \"\"\"\n Assigns the item attributes (font, colours).\n\n :param `attr`: an instance of L{TreeItemAttr}.\n \"\"\"\n\n self.SetAttributes(attr)\n self._ownsAttr = True\n\n\n def DeleteChildren(self, tree):\n \"\"\"\n Deletes the item children.\n\n :param `tree`: the main L{CustomTreeCtrl} instance.\n \"\"\"\n\n for child in self._children:\n if tree:\n tree.SendDeleteEvent(child)\n\n child.DeleteChildren(tree)\n\n if child == tree._select_me:\n tree._select_me = None\n\n # We have to destroy the associated window\n wnd = child.GetWindow()\n if wnd:\n wnd.Destroy()\n child._wnd = None\n\n if child in tree._itemWithWindow:\n tree._itemWithWindow.remove(child)\n\n del child\n\n self._children = []\n\n\n def SetText(self, text):\n \"\"\"\n Sets the item text.\n\n :param `text`: the new item label.\n \"\"\"\n\n self._text = text\n\n\n def GetChildrenCount(self, recursively=True):\n \"\"\"\n Gets the number of children of this item.\n\n :param `recursively`: if ``True``, returns the total number of descendants,\n otherwise only one level of children is counted.\n \"\"\"\n\n count = len(self._children)\n\n if not recursively:\n return count\n\n total = count\n\n for n in xrange(count):\n total += self._children[n].GetChildrenCount()\n\n return total\n\n\n def GetSize(self, x, y, theButton):\n \"\"\"\n Returns the item size.\n\n :param `x`: the current item's x position;\n :param `y`: the current item's y position;\n :param `theButton`: an instance of the main L{CustomTreeCtrl}.\n \"\"\"\n\n bottomY = self._y + theButton.GetLineHeight(self)\n\n if y < bottomY:\n y = bottomY\n\n width = self._x + self._width\n\n if x < width:\n x = width\n\n if self.IsExpanded():\n for child in self._children:\n x, y = child.GetSize(x, y, theButton)\n\n return x, y\n\n\n def HitTest(self, point, theCtrl, flags=0, level=0):\n \"\"\"\n HitTest method for an item. Called from the main window HitTest.\n\n :param `point`: the point to test for the hit (an instance of `wx.Point`);\n :param `theCtrl`: the main L{CustomTreeCtrl} tree;\n :param `flags`: a bitlist of hit locations;\n :param `level`: the item's level inside the tree hierarchy.\n\n :see: L{CustomTreeCtrl.HitTest} method for the flags explanation.\n \"\"\"\n\n # for a hidden root node, don't evaluate it, but do evaluate children\n if not (level == 0 and theCtrl.HasAGWFlag(TR_HIDE_ROOT)):\n\n # evaluate the item\n h = theCtrl.GetLineHeight(self)\n\n if point.y > self._y and point.y < self._y + h:\n\n y_mid = self._y + h/2\n\n if point.y < y_mid:\n flags |= TREE_HITTEST_ONITEMUPPERPART\n else:\n flags |= TREE_HITTEST_ONITEMLOWERPART\n\n xCross = self._x - theCtrl.GetSpacing()\n\n if wx.Platform == \"__WXMAC__\":\n # according to the drawing code the triangels are drawn\n # at -4 , -4 from the position up to +10/+10 max\n if point.x > xCross-4 and point.x < xCross+10 and point.y > y_mid-4 and \\\n point.y < y_mid+10 and self.HasPlus() and theCtrl.HasButtons():\n\n flags |= TREE_HITTEST_ONITEMBUTTON\n return self, flags\n else:\n # 5 is the size of the plus sign\n if point.x > xCross-6 and point.x < xCross+6 and point.y > y_mid-6 and \\\n point.y < y_mid+6 and self.HasPlus() and theCtrl.HasButtons():\n\n flags |= TREE_HITTEST_ONITEMBUTTON\n return self, flags\n\n if point.x >= self._x and point.x <= self._x + self._width:\n\n image_w = -1\n wcheck = 0\n\n # assuming every image (normal and selected) has the same size!\n if self.GetImage() != _NO_IMAGE and theCtrl._imageListNormal:\n image_w, image_h = theCtrl._imageListNormal.GetSize(self.GetImage())\n\n if self.GetCheckedImage() is not None:\n wcheck, hcheck = theCtrl._imageListCheck.GetSize(self.GetCheckedImage())\n\n if wcheck and point.x <= self._x + wcheck + 1:\n flags |= TREE_HITTEST_ONITEMCHECKICON\n return self, flags\n\n if image_w != -1 and point.x <= self._x + wcheck + image_w + 1:\n flags |= TREE_HITTEST_ONITEMICON\n else:\n flags |= TREE_HITTEST_ONITEMLABEL\n\n return self, flags\n\n if point.x < self._x:\n if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):\n flags |= TREE_HITTEST_ONITEM\n else:\n flags |= TREE_HITTEST_ONITEMINDENT\n if point.x > self._x + self._width:\n if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):\n flags |= TREE_HITTEST_ONITEM\n else:\n flags |= TREE_HITTEST_ONITEMRIGHT\n\n return self, flags\n\n # if children are expanded, fall through to evaluate them\n if self._isCollapsed:\n return None, 0\n\n # evaluate children\n for child in self._children:\n res, flags = child.HitTest(point, theCtrl, flags, level + 1)\n if res != None:\n return res, flags\n\n return None, 0\n\n\n def GetCurrentImage(self):\n \"\"\"Returns the current item image.\"\"\"\n\n image = _NO_IMAGE\n\n if self.IsExpanded():\n\n if self.IsSelected():\n\n image = self._images[TreeItemIcon_SelectedExpanded]\n\n if image == _NO_IMAGE:\n\n # we usually fall back to the normal item, but try just the\n # expanded one (and not selected) first in this case\n image = self._images[TreeItemIcon_Expanded]\n\n else: # not expanded\n\n if self.IsSelected():\n image = self._images[TreeItemIcon_Selected]\n\n # maybe it doesn't have the specific image we want,\n # try the default one instead\n if image == _NO_IMAGE:\n image = self._images[TreeItemIcon_Normal]\n\n return image\n\n\n def GetCurrentCheckedImage(self):\n \"\"\"Returns the current item check image.\"\"\"\n\n if self._type == 0:\n return None\n\n checked = self.IsChecked()\n\n if checked > 0:\n if self._type == 1: # Checkbox\n if checked == wx.CHK_CHECKED:\n return self._checkedimages[TreeItemIcon_Checked]\n else:\n return self._checkedimages[TreeItemIcon_Undetermined]\n else: # Radiobutton\n return self._checkedimages[TreeItemIcon_Flagged]\n else:\n if self._type == 1: # Checkbox\n return self._checkedimages[TreeItemIcon_NotChecked]\n else: # Radiobutton\n return self._checkedimages[TreeItemIcon_NotFlagged]\n\n\n# -----------------------------------------------------------------------------\n# CustomTreeCtrl Main Implementation.\n# This Is The Main Class.\n# -----------------------------------------------------------------------------\n\nclass CustomTreeCtrl(wx.PyScrolledWindow):\n \"\"\"\n CustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the\n same base functionalities plus some more enhancements. This class does not rely on\n the native control, as it is a full owner-drawn tree control.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=TR_DEFAULT_STYLE, validator=wx.DefaultValidator,\n name=\"CustomTreeCtrl\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.PyScrolledWindow` style;\n :param `agwStyle`: the AGW-specific window style for L{CustomTreeCtrl}. It can be a\n combination of the following bits:\n\n ============================== =========== ==================================================\n Window Styles Hex Value Description\n ============================== =========== ==================================================\n ``TR_NO_BUTTONS`` 0x0 For convenience to document that no buttons are to be drawn.\n ``TR_SINGLE`` 0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.\n ``TR_HAS_BUTTONS`` 0x1 Use this style to show + and - buttons to the left of parent items.\n ``TR_NO_LINES`` 0x4 Use this style to hide vertical level connectors.\n ``TR_LINES_AT_ROOT`` 0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.\n ``TR_DEFAULT_STYLE`` 0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.\n ``TR_TWIST_BUTTONS`` 0x10 Use old Mac-twist style buttons.\n ``TR_MULTIPLE`` 0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.\n ``TR_EXTENDED`` 0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).\n ``TR_HAS_VARIABLE_ROW_HEIGHT`` 0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.\n ``TR_EDIT_LABELS`` 0x200 Use this style if you wish the user to be able to edit labels in the tree control.\n ``TR_ROW_LINES`` 0x400 Use this style to draw a contrasting border between displayed rows.\n ``TR_HIDE_ROOT`` 0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.\n ``TR_FULL_ROW_HIGHLIGHT`` 0x2000 Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.\n ``TR_AUTO_CHECK_CHILD`` 0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.\n ``TR_AUTO_TOGGLE_CHILD`` 0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.\n ``TR_AUTO_CHECK_PARENT`` 0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.\n ``TR_ALIGN_WINDOWS`` 0x20000 Flag used to align windows (in items with windows) at the same horizontal position.\n ============================== =========== ==================================================\n\n :param `validator`: window validator;\n :param `name`: window name.\n \"\"\"\n\n self._current = self._key_current = self._anchor = self._select_me = None\n self._hasFocus = False\n self._dirty = False\n\n # Default line height: it will soon be changed\n self._lineHeight = 10\n # Item indent wrt parent\n self._indent = 15\n # item horizontal spacing between the start and the text\n self._spacing = 18\n\n # Brushes for focused/unfocused items (also gradient type)\n self._hilightBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))\n btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)\n self._hilightUnfocusedBrush = wx.Brush(btnshadow)\n r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()\n backcolour = (max((r >> 1) - 20, 0),\n max((g >> 1) - 20, 0),\n max((b >> 1) - 20, 0))\n backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])\n self._hilightUnfocusedBrush2 = wx.Brush(backcolour)\n\n # image list for icons\n self._imageListNormal = self._imageListButtons = self._imageListState = self._imageListCheck = self._imageListLeft = None\n self._ownsImageListNormal = self._ownsImageListButtons = self._ownsImageListState = self._ownsImageListLeft = False\n\n # Drag and drop initial settings\n self._dragCount = 0\n self._countDrag = 0\n self._isDragging = False\n self._dropTarget = self._oldSelection = None\n self._dragImage = None\n self._underMouse = None\n\n # TextCtrl initial settings for editable items\n self._textCtrl = None\n self._renameTimer = None\n\n # This one allows us to handle Freeze() and Thaw() calls\n self._freezeCount = 0\n\n self._findPrefix = \"\"\n self._findTimer = None\n\n self._dropEffectAboveItem = False\n self._lastOnSame = False\n\n # Default normal and bold fonts for an item\n self._hasFont = True\n self._normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n family = self._normalFont.GetFamily()\n if family == wx.FONTFAMILY_UNKNOWN:\n family = wx.FONTFAMILY_SWISS\n self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,\n self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),\n self._normalFont.GetFaceName(), self._normalFont.GetEncoding())\n self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,\n wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),\n self._normalFont.GetFaceName(), self._normalFont.GetEncoding())\n\n # Hyperlinks things\n self._hypertextfont = wx.Font(self._normalFont.GetPointSize(), family,\n self._normalFont.GetStyle(), wx.NORMAL, True,\n self._normalFont.GetFaceName(), self._normalFont.GetEncoding())\n self._hypertextnewcolour = wx.BLUE\n self._hypertextvisitedcolour = wx.Colour(200, 47, 200)\n self._isonhyperlink = False\n\n # Default CustomTreeCtrl background colour.\n self._backgroundColour = wx.WHITE\n\n # Background image settings\n self._backgroundImage = None\n self._imageStretchStyle = _StyleTile\n\n # Disabled items colour\n self._disabledColour = wx.Colour(180, 180, 180)\n\n # Gradient selection colours\n self._firstcolour = colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self._secondcolour = wx.WHITE\n self._usegradients = False\n self._gradientstyle = 0 # Horizontal Gradient\n\n # Vista Selection Styles\n self._vistaselection = False\n\n # To speed up ExpandAll and SelectAll\n self._sendEvent = True\n\n # Connection lines style\n grey = (160,160,160)\n if wx.Platform != \"__WXMAC__\":\n self._dottedPen = wx.Pen(grey, 1, wx.USER_DASH)\n self._dottedPen.SetDashes([1,1])\n self._dottedPen.SetCap(wx.CAP_BUTT)\n else:\n self._dottedPen = wx.Pen(grey, 1)\n\n # Pen Used To Draw The Border Around Selected Items\n self._borderPen = wx.BLACK_PEN\n self._cursor = wx.StockCursor(wx.CURSOR_ARROW)\n\n # For Appended Windows\n self._hasWindows = False\n self._itemWithWindow = []\n\n if wx.Platform == \"__WXMAC__\":\n agwStyle &= ~TR_LINES_AT_ROOT\n agwStyle |= TR_NO_LINES\n\n platform, major, minor = wx.GetOsVersion()\n if major < 10:\n agwStyle |= TR_ROW_LINES\n\n # A constant to use my translation of RendererNative.DrawTreeItemButton\n # if the wxPython version is less than 2.6.2.1.\n if _VERSION_STRING < \"2.6.2.1\":\n self._drawingfunction = DrawTreeItemButton\n else:\n self._drawingfunction = wx.RendererNative.Get().DrawTreeItemButton\n\n # Create our container... at last!\n wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)\n\n self._agwStyle = agwStyle\n\n # Create the default check image list\n self.SetImageListCheck(16, 16)\n\n # If the tree display has no buttons, but does have\n # connecting lines, we can use a narrower layout.\n # It may not be a good idea to force this...\n if not self.HasButtons() and not self.HasAGWFlag(TR_NO_LINES):\n self._indent= 10\n self._spacing = 10\n\n self.SetValidator(validator)\n\n attr = self.GetDefaultAttributes()\n self.SetOwnForegroundColour(attr.colFg)\n self.SetOwnBackgroundColour(wx.WHITE)\n\n if not self._hasFont:\n self.SetOwnFont(attr.font)\n\n self.SetSize(size)\n\n # Bind the events\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)\n self.Bind(EVT_TREE_ITEM_GETTOOLTIP, self.OnGetToolTip)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)\n\n # Sets the focus to ourselves: this is useful if you have items\n # with associated widgets.\n self.SetFocus()\n\n\n def AcceptsFocus(self):\n \"\"\"\n Can this window be given focus by mouse click?\n\n :note: This method always returns ``True`` as we alsways accept focus from\n mouse click.\n\n :note: Overridden from `wx.PyScrolledWindow`.\n \"\"\"\n\n # overridden base class method, allows this ctrl to\n # participate in the tab-order, etc. It's overridable because\n # of deriving this class from wx.PyScrolledWindow...\n return True\n\n\n def OnDestroy(self, event):\n \"\"\"\n Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.WindowDestroyEvent` event to be processed.\n \"\"\"\n\n # Here there may be something I miss... do I have to destroy\n # something else?\n if self._renameTimer and self._renameTimer.IsRunning():\n self._renameTimer.Stop()\n del self._renameTimer\n self._renameTimer = None\n\n if self._findTimer and self._findTimer.IsRunning():\n self._findTimer.Stop()\n del self._findTimer\n\n event.Skip()\n\n\n def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16):\n \"\"\"\n Returns a native looking checkbox or radio button bitmap.\n\n :param `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton\n one;\n :param `checked`: ``True`` if the control is marked, ``False`` if it is not;\n :param `enabled`: ``True`` if the control is enabled, ``False`` if it is not;\n :param `x`: the width of the bitmap;\n :param `y`: the height of the bitmap.\n \"\"\"\n\n bmp = wx.EmptyBitmap(x, y)\n mdc = wx.MemoryDC(bmp)\n mask = wx.Colour(0xfe, 0xfe, 0xfe)\n mdc.SetBackground(wx.Brush(mask))\n mdc.Clear()\n\n render = wx.RendererNative.Get()\n\n if checked == wx.CHK_CHECKED:\n flag = wx.CONTROL_CHECKED\n elif checked == wx.CHK_UNDETERMINED:\n flag = wx.CONTROL_UNDETERMINED\n else:\n flag = 0\n\n if not enabled:\n flag |= wx.CONTROL_DISABLED\n\n if checkbox:\n render.DrawCheckBox(self, mdc, (0, 0, x, y), flag)\n else:\n if _VERSION_STRING < \"2.9\":\n render.DrawRadioButton(self, mdc, (0, 0, x, y), flag)\n else:\n render.DrawRadioBitmap(self, mdc, (0, 0, x, y), flag)\n\n mdc.SelectObject(wx.NullBitmap)\n bmp.SetMaskColour(mask)\n return bmp\n\n\n def GetCount(self):\n \"\"\" Returns the global number of items in the tree. \"\"\"\n\n if not self._anchor:\n # the tree is empty\n return 0\n\n count = self._anchor.GetChildrenCount()\n\n if not self.HasAGWFlag(TR_HIDE_ROOT):\n # take the root itself into account\n count = count + 1\n\n return count\n\n\n def GetIndent(self):\n \"\"\" Returns the item indentation. \"\"\"\n\n return self._indent\n\n\n def GetSpacing(self):\n \"\"\" Returns the spacing between the start and the text. \"\"\"\n\n return self._spacing\n\n\n def GetRootItem(self):\n \"\"\" Returns the root item. \"\"\"\n\n return self._anchor\n\n\n def GetSelection(self):\n \"\"\"\n Returns the current selection.\n\n :note: This method is valid only with the style ``TR_SINGLE`` set. Use\n L{GetSelections} for multiple-selections trees.\n \"\"\"\n\n return self._current\n\n\n def ToggleItemSelection(self, item):\n \"\"\"\n Toggles the item selection.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self.SelectItem(item, not self.IsSelected(item))\n\n\n def EnableChildren(self, item, enable=True):\n \"\"\"\n Enables/disables the item children.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `enable`: ``True`` to enable the children, ``False`` otherwise.\n\n :note: This method is used internally.\n \"\"\"\n\n torefresh = False\n if item.IsExpanded():\n torefresh = True\n\n if item.GetType() == 2 and enable and not item.IsChecked():\n # We hit a radiobutton item not checked, we don't want to\n # enable the children\n return\n\n child, cookie = self.GetFirstChild(item)\n while child:\n self.EnableItem(child, enable, torefresh=torefresh)\n # Recurse on tree\n if child.GetType != 2 or (child.GetType() == 2 and item.IsChecked()):\n self.EnableChildren(child, enable)\n (child, cookie) = self.GetNextChild(item, cookie)\n\n\n def EnableItem(self, item, enable=True, torefresh=True):\n \"\"\"\n Enables/disables an item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `enable`: ``True`` to enable the item, ``False`` otherwise;\n :param `torefresh`: whether to redraw the item or not.\n \"\"\"\n\n if item.IsEnabled() == enable:\n return\n\n if not enable and item.IsSelected():\n self.SelectItem(item, False)\n\n item.Enable(enable)\n wnd = item.GetWindow()\n\n # Handles the eventual window associated to the item\n if wnd:\n wndenable = item.GetWindowEnabled()\n wnd.Enable(enable)\n\n if torefresh:\n # We have to refresh the item line\n dc = wx.ClientDC(self)\n self.CalculateSize(item, dc)\n self.RefreshLine(item)\n\n\n def IsItemEnabled(self, item):\n \"\"\"\n Returns whether an item is enabled or disabled.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsEnabled()\n\n\n def SetDisabledColour(self, colour):\n \"\"\"\n Sets the colour for items in a disabled state.\n\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n self._disabledColour = colour\n self._dirty = True\n\n\n def GetDisabledColour(self):\n \"\"\" Returns the colour for items in a disabled state. \"\"\"\n\n return self._disabledColour\n\n\n def IsItemChecked(self, item):\n \"\"\"\n Returns whether an item is checked or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n return item.IsChecked()\n\n\n def GetItem3StateValue(self, item):\n \"\"\"\n Gets the state of a 3-state checkbox item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``\n when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined\n state.\n\n :note: This method raises an exception when the function is used with a 2-state\n checkbox item.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n return item.Get3StateValue()\n\n\n def IsItem3State(self, item):\n \"\"\"\n Returns whether or not the checkbox item is a 3-state checkbox.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a\n 2-state checkbox item.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n return item.Is3State()\n\n\n def SetItem3StateValue(self, item, state):\n \"\"\"\n Sets the checkbox item to the given `state`.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``\n (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).\n\n :note: This method raises an exception when the checkbox item is a 2-state checkbox\n and setting the state to ``wx.CHK_UNDETERMINED``.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n item.Set3StateValue(state)\n\n\n def SetItem3State(self, item, allow):\n \"\"\"\n Sets whether the item has a 3-state value checkbox assigned to it or not.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it\n to a 2-state checkbox.\n\n :return: ``True`` if the change was successful, ``False`` otherwise.\n\n :note: This method is meaningful only for checkbox-like items.\n \"\"\"\n\n return item.Set3State(allow)\n\n\n def CheckItem2(self, item, checked=True, torefresh=False):\n \"\"\"\n Used internally to avoid ``EVT_TREE_ITEM_CHECKED`` events.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it;\n :param `torefresh`: whether to redraw the item or not.\n \"\"\"\n\n if item.GetType() == 0:\n return\n\n item.Check(checked)\n\n if torefresh:\n dc = wx.ClientDC(self)\n self.CalculateSize(item, dc)\n self.RefreshLine(item)\n\n\n def UnCheckRadioParent(self, item, checked=False):\n \"\"\"\n Used internally to handle radio node parent correctly.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n \"\"\"\n\n e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())\n e.SetItem(item)\n e.SetEventObject(self)\n\n if self.GetEventHandler().ProcessEvent(e):\n return False\n\n item.Check(checked)\n self.RefreshLine(item)\n self.EnableChildren(item, checked)\n e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())\n e.SetItem(item)\n e.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(e)\n\n return True\n\n\n def CheckItem(self, item, checked=True):\n \"\"\"\n Actually checks/uncheks an item, sending (eventually) the two\n events ``EVT_TREE_ITEM_CHECKING`` and ``EVT_TREE_ITEM_CHECKED``.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: for a radiobutton-type item, ``True`` to check it, ``False``\n to uncheck it. For a checkbox-type item, it can be one of ``wx.CHK_UNCHECKED``\n when the checkbox is unchecked, ``wx.CHK_CHECKED`` when it is checked and\n ``wx.CHK_UNDETERMINED`` when it's in the undetermined state.\n \"\"\"\n\n # Should we raise an error here?!?\n if item.GetType() == 0:\n return\n\n if item.GetType() == 2: # it's a radio button\n if not checked and item.IsChecked(): # Try To Unckeck?\n return\n else:\n if not self.UnCheckRadioParent(item, checked):\n return\n\n self.CheckSameLevel(item, False)\n return\n\n # Radiobuttons are done, let's handle checkbuttons...\n e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())\n e.SetItem(item)\n e.SetEventObject(self)\n\n if self.GetEventHandler().ProcessEvent(e):\n # Blocked by user\n return\n\n if item.Is3State():\n item.Set3StateValue(checked)\n else:\n item.Check(checked)\n\n dc = wx.ClientDC(self)\n self.RefreshLine(item)\n\n if self.HasAGWFlag(TR_AUTO_CHECK_CHILD):\n ischeck = self.IsItemChecked(item)\n self.AutoCheckChild(item, ischeck)\n if self.HasAGWFlag(TR_AUTO_CHECK_PARENT):\n ischeck = self.IsItemChecked(item)\n self.AutoCheckParent(item, ischeck)\n elif self.HasAGWFlag(TR_AUTO_TOGGLE_CHILD):\n self.AutoToggleChild(item)\n\n e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())\n e.SetItem(item)\n e.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(e)\n\n\n def AutoToggleChild(self, item):\n \"\"\"\n Transverses the tree and toggles the items.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n child, cookie = self.GetFirstChild(item)\n\n torefresh = False\n if item.IsExpanded():\n torefresh = True\n\n # Recurse on tree\n while child:\n if child.GetType() == 1 and child.IsEnabled():\n self.CheckItem2(child, not child.IsChecked(), torefresh=torefresh)\n self.AutoToggleChild(child)\n (child, cookie) = self.GetNextChild(item, cookie)\n\n\n def AutoCheckChild(self, item, checked):\n \"\"\"\n Transverses the tree and checks/unchecks the items.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n\n :note: This method is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n (child, cookie) = self.GetFirstChild(item)\n\n torefresh = False\n if item.IsExpanded():\n torefresh = True\n\n while child:\n if child.GetType() == 1 and child.IsEnabled():\n self.CheckItem2(child, checked, torefresh=torefresh)\n self.AutoCheckChild(child, checked)\n (child, cookie) = self.GetNextChild(item, cookie)\n\n\n def AutoCheckParent(self, item, checked):\n \"\"\"\n Traverses up the tree and checks/unchecks parent items.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n\n :note: This method is meaningful only for checkbox-like and radiobutton-like items.\n \"\"\"\n\n parent = item.GetParent()\n if not parent or parent.GetType() != 1:\n return\n\n (child, cookie) = self.GetFirstChild(parent)\n while child:\n if child.GetType() == 1 and child.IsEnabled():\n if checked != child.IsChecked():\n return\n (child, cookie) = self.GetNextChild(parent, cookie)\n\n self.CheckItem2(parent, checked, torefresh=True)\n self.AutoCheckParent(parent, checked)\n\n\n def CheckChilds(self, item, checked=True):\n \"\"\"\n Programatically check/uncheck item children.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n\n :note: This method is meaningful only for checkbox-like and radiobutton-like items.\n\n :note: This method does not generate ``EVT_TREE_ITEM_CHECKING`` and\n ``EVT_TREE_ITEM_CHECKED`` events.\n \"\"\"\n\n if checked == None:\n self.AutoToggleChild(item)\n else:\n self.AutoCheckChild(item, checked)\n\n\n def CheckSameLevel(self, item, checked=False):\n \"\"\"\n Uncheck radio items which are on the same level of the checked one.\n Used internally.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `checked`: ``True`` to check an item, ``False`` to uncheck it.\n\n :note: This method is meaningful only for radiobutton-like items.\n \"\"\"\n\n parent = item.GetParent()\n\n if not parent:\n return\n\n torefresh = False\n if parent.IsExpanded():\n torefresh = True\n\n (child, cookie) = self.GetFirstChild(parent)\n while child:\n if child.GetType() == 2 and child != item:\n self.CheckItem2(child, checked, torefresh=torefresh)\n if child.GetType != 2 or (child.GetType() == 2 and child.IsChecked()):\n self.EnableChildren(child, checked)\n (child, cookie) = self.GetNextChild(parent, cookie)\n\n\n def EditLabel(self, item):\n \"\"\"\n Starts editing an item label.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self.Edit(item)\n\n\n def ShouldInheritColours(self):\n \"\"\"\n Return ``True`` from here to allow the colours of this window to be\n changed by `InheritAttributes`, returning ``False`` forbids inheriting them\n from the parent window.\n\n The base class version returns ``False``, but this method is overridden in\n `wx.Control` where it returns ``True``.\n\n L{CustomTreeCtrl} does not inherit colours from anyone.\n \"\"\"\n\n return False\n\n\n def SetIndent(self, indent):\n \"\"\"\n Sets the indentation for L{CustomTreeCtrl}.\n\n :param `indent`: an integer representing the indentation for the items in the tree.\n \"\"\"\n\n self._indent = indent\n self._dirty = True\n\n\n def SetSpacing(self, spacing):\n \"\"\"\n Sets the spacing between items in L{CustomTreeCtrl}.\n\n :param `spacing`: an integer representing the spacing between items in the tree.\n \"\"\"\n\n self._spacing = spacing\n self._dirty = True\n\n\n def HasChildren(self, item):\n \"\"\"\n Returns whether an item has children or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return len(item.GetChildren()) > 0\n\n\n def GetChildrenCount(self, item, recursively=True):\n \"\"\"\n Returns the item children count.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `recursively`: if ``True``, returns the total number of descendants,\n otherwise only one level of children is counted.\n \"\"\"\n\n return item.GetChildrenCount(recursively)\n\n\n def HasAGWFlag(self, flag):\n \"\"\"\n Returns ``True`` if L{CustomTreeCtrl} has the `flag` bit set.\n\n :param `flag`: any possible window style for L{CustomTreeCtrl}.\n\n :see: The L{__init__} method for the `flag` parameter description.\n \"\"\"\n\n return self._agwStyle & flag\n\n\n def SetAGWWindowStyleFlag(self, agwStyle):\n \"\"\"\n Sets the L{CustomTreeCtrl} window style.\n\n :param `agwStyle`: the new L{CustomTreeCtrl} window style.\n\n :see: The L{__init__} method for the `agwStyle` parameter description.\n \"\"\"\n\n # Do not try to expand the root node if it hasn't been created yet\n if self._anchor and not self.HasAGWFlag(TR_HIDE_ROOT) and agwStyle & TR_HIDE_ROOT:\n\n # if we will hide the root, make sure children are visible\n self._anchor.SetHasPlus()\n self._anchor.Expand()\n self.CalculatePositions()\n\n # right now, just sets the styles. Eventually, we may\n # want to update the inherited styles, but right now\n # none of the parents has updatable styles\n\n if self.HasAGWFlag(TR_MULTIPLE) and not (agwStyle & TR_MULTIPLE):\n selections = self.GetSelections()\n for select in selections[0:-1]:\n self.SelectItem(select, False)\n\n self._agwStyle = agwStyle\n self._dirty = True\n\n\n def GetAGWWindowStyleFlag(self):\n \"\"\"\n Returns the L{CustomTreeCtrl} style.\n\n :see: The L{__init__} method for a list of possible style flags.\n \"\"\"\n\n return self._agwStyle\n\n\n def HasButtons(self):\n \"\"\"Returns whether L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set.\"\"\"\n\n return self.HasAGWFlag(TR_HAS_BUTTONS)\n\n\n# -----------------------------------------------------------------------------\n# functions to work with tree items\n# -----------------------------------------------------------------------------\n\n def GetItemText(self, item):\n \"\"\"\n Returns the item text.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetText()\n\n\n def GetItemImage(self, item, which=TreeItemIcon_Normal):\n \"\"\"\n Returns the item image.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `which`: can be one of the following bits:\n\n ================================= ========================\n Item State Description\n ================================= ========================\n ``TreeItemIcon_Normal`` To get the normal item image\n ``TreeItemIcon_Selected`` To get the selected item image (i.e. the image which is shown when the item is currently selected)\n ``TreeItemIcon_Expanded`` To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)\n ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)\n ================================= ========================\n \"\"\"\n\n return item.GetImage(which)\n\n\n def GetItemLeftImage(self, item):\n \"\"\"\n Returns the item leftmost image, i.e. the image associated to the item on the leftmost\n part of the L{CustomTreeCtrl} client area.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetLeftImage()\n\n\n def GetPyData(self, item):\n \"\"\"\n Returns the data associated to an item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetData()\n\n GetItemPyData = GetPyData\n\n\n def GetItemTextColour(self, item):\n \"\"\"\n Returns the item text colour.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.Attr().GetTextColour()\n\n\n def GetItemBackgroundColour(self, item):\n \"\"\"\n Returns the item background colour.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.Attr().GetBackgroundColour()\n\n\n def GetItemFont(self, item):\n \"\"\"\n Returns the item font.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n font = item.Attr().GetFont()\n if font.IsOk():\n return font\n\n return wx.NullFont\n\n\n def IsItemHyperText(self, item):\n \"\"\"\n Returns whether an item is hypertext or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsHyperText()\n\n\n def SetItemText(self, item, text):\n \"\"\"\n Sets the item text.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `text`: the new item label.\n \"\"\"\n\n dc = wx.ClientDC(self)\n item.SetText(text)\n self.CalculateSize(item, dc)\n self.RefreshLine(item)\n\n\n def SetItemImage(self, item, image, which=TreeItemIcon_Normal):\n \"\"\"\n Sets the item image, depending on the item state.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `image`: an index within the normal image list specifying the image to\n use for the item in the state specified by the `which` parameter;\n :param `which`: the item state.\n\n :see: L{GetItemImage} for an explanation of the `which` parameter.\n \"\"\"\n\n item.SetImage(image, which)\n\n dc = wx.ClientDC(self)\n self.CalculateSize(item, dc)\n self.RefreshLine(item)\n\n\n def SetItemLeftImage(self, item, image):\n \"\"\"\n Sets the item leftmost image, i.e. the image associated to the item on the leftmost\n part of the L{CustomTreeCtrl} client area.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `image`: an index within the left image list specifying the image to\n use for the item in the leftmost part of the client area.\n \"\"\"\n\n item.SetLeftImage(image)\n\n dc = wx.ClientDC(self)\n self.CalculateSize(item, dc)\n self.RefreshLine(item)\n\n\n def SetPyData(self, item, data):\n \"\"\"\n Sets the data associated to an item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `data`: can be any Python object.\n \"\"\"\n\n item.SetData(data)\n\n SetItemPyData = SetPyData\n\n\n def SetItemHasChildren(self, item, has=True):\n \"\"\"\n Forces the appearance/disappearance of the button next to the item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `has`: ``True`` to have a button next to an item, ``False`` otherwise.\n \"\"\"\n\n item.SetHasPlus(has)\n self.RefreshLine(item)\n\n\n def SetItemBold(self, item, bold=True):\n \"\"\"\n Sets the item font as bold/unbold.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `bold`: ``True`` to set the item font as bold, ``False`` otherwise.\n \"\"\"\n\n # avoid redrawing the tree if no real change\n if item.IsBold() != bold:\n item.SetBold(bold)\n self._dirty = True\n\n\n def SetItemItalic(self, item, italic=True):\n \"\"\"\n Sets the item font as italic/non-italic.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `italic`: ``True`` to set the item font as italic, ``False`` otherwise.\n \"\"\"\n\n if item.IsItalic() != italic:\n item.SetItalic(italic)\n self._dirty = True\n\n\n def SetItemDropHighlight(self, item, highlight=True):\n \"\"\"\n Gives the item the visual feedback for drag and drop operations.\n This is useful when something is dragged from outside the L{CustomTreeCtrl}.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `highlight`: ``True`` to highlight the dragged items, ``False`` otherwise.\n \"\"\"\n\n if highlight:\n bg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n fg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)\n\n item.Attr().SetTextColour(fg)\n item.Attr.SetBackgroundColour(bg)\n self.RefreshLine(item)\n\n\n def SetItemTextColour(self, item, colour):\n \"\"\"\n Sets the item text colour.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n item.Attr().SetTextColour(colour)\n self.RefreshLine(item)\n\n\n def SetItemBackgroundColour(self, item, colour):\n \"\"\"\n Sets the item background colour.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n item.Attr().SetBackgroundColour(colour)\n self.RefreshLine(item)\n\n\n def SetItemHyperText(self, item, hyper=True):\n \"\"\"\n Sets whether the item is hypertext or not.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.\n \"\"\"\n\n item.SetHyperText(hyper)\n self.RefreshLine(item)\n\n\n def SetItemFont(self, item, font):\n \"\"\"\n Sets the item font.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `font`: a valid `wx.Font` instance.\n \"\"\"\n\n item.Attr().SetFont(font)\n self._dirty = True\n\n\n def SetFont(self, font):\n \"\"\"\n Sets the L{CustomTreeCtrl} font.\n\n :param `font`: a valid `wx.Font` instance.\n\n :note: Overridden from `wx.PyScrolledWindow`.\n \"\"\"\n\n wx.PyScrolledWindow.SetFont(self, font)\n\n self._normalFont = font\n family = self._normalFont.GetFamily()\n if family == wx.FONTFAMILY_UNKNOWN:\n family = wx.FONTFAMILY_SWISS\n self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,\n self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),\n self._normalFont.GetFaceName(), self._normalFont.GetEncoding())\n self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,\n wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),\n self._normalFont.GetFaceName(), self._normalFont.GetEncoding())\n\n return True\n\n\n def GetHyperTextFont(self):\n \"\"\" Returns the font used to render hypertext items. \"\"\"\n\n return self._hypertextfont\n\n\n def SetHyperTextFont(self, font):\n \"\"\"\n Sets the font used to render hypertext items.\n\n :param `font`: a valid `wx.Font` instance.\n \"\"\"\n\n self._hypertextfont = font\n self._dirty = True\n\n\n def SetHyperTextNewColour(self, colour):\n \"\"\"\n Sets the colour used to render a non-visited hypertext item.\n\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n self._hypertextnewcolour = colour\n self._dirty = True\n\n\n def GetHyperTextNewColour(self):\n \"\"\" Returns the colour used to render a non-visited hypertext item. \"\"\"\n\n return self._hypertextnewcolour\n\n\n def SetHyperTextVisitedColour(self, colour):\n \"\"\"\n Sets the colour used to render a visited hypertext item.\n\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n self._hypertextvisitedcolour = colour\n self._dirty = True\n\n\n def GetHyperTextVisitedColour(self):\n \"\"\" Returns the colour used to render a visited hypertext item. \"\"\"\n\n return self._hypertextvisitedcolour\n\n\n def SetItemVisited(self, item, visited=True):\n \"\"\"\n Sets whether an hypertext item was visited.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.\n \"\"\"\n\n item.SetVisited(visited)\n self.RefreshLine(item)\n\n\n def GetItemVisited(self, item):\n \"\"\"\n Returns whether an hypertext item was visited.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetVisited()\n\n\n def SetHilightFocusColour(self, colour):\n \"\"\"\n Sets the colour used to highlight focused selected items.\n\n :param `colour`: a valid `wx.Colour` instance.\n\n :note: This is applied only if gradient and Windows Vista selection\n styles are disabled.\n \"\"\"\n\n self._hilightBrush = wx.Brush(colour)\n self.RefreshSelected()\n\n\n def SetHilightNonFocusColour(self, colour):\n \"\"\"\n Sets the colour used to highlight unfocused selected items.\n\n :param `colour`: a valid `wx.Colour` instance.\n\n :note: This is applied only if gradient and Windows Vista selection\n styles are disabled.\n \"\"\"\n\n self._hilightUnfocusedBrush = wx.Brush(colour)\n self.RefreshSelected()\n\n\n def GetHilightFocusColour(self):\n \"\"\"\n Returns the colour used to highlight focused selected items.\n\n :note: This is used only if gradient and Windows Vista selection\n styles are disabled.\n \"\"\"\n\n return self._hilightBrush.GetColour()\n\n\n def GetHilightNonFocusColour(self):\n \"\"\"\n Returns the colour used to highlight unfocused selected items.\n\n :note: This is used only if gradient and Windows Vista selection\n styles are disabled.\n \"\"\"\n\n return self._hilightUnfocusedBrush.GetColour()\n\n\n def SetFirstGradientColour(self, colour=None):\n \"\"\"\n Sets the first gradient colour for gradient-style selections.\n\n :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,\n the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.\n \"\"\"\n\n if colour is None:\n colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n\n self._firstcolour = colour\n if self._usegradients:\n self.RefreshSelected()\n\n\n def SetSecondGradientColour(self, colour=None):\n \"\"\"\n Sets the second gradient colour for gradient-style selections.\n\n :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,\n the colour generated is a slightly darker version of the L{CustomTreeCtrl}\n background colour.\n \"\"\"\n\n if colour is None:\n # No colour given, generate a slightly darker from the\n # CustomTreeCtrl background colour\n colour = self.GetBackgroundColour()\n r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())\n colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)\n colour = wx.Colour(colour[0], colour[1], colour[2])\n\n self._secondcolour = colour\n\n if self._usegradients:\n self.RefreshSelected()\n\n\n def GetFirstGradientColour(self):\n \"\"\" Returns the first gradient colour for gradient-style selections. \"\"\"\n\n return self._firstcolour\n\n\n def GetSecondGradientColour(self):\n \"\"\" Returns the second gradient colour for gradient-style selections. \"\"\"\n\n return self._secondcolour\n\n\n def EnableSelectionGradient(self, enable=True):\n \"\"\"\n Globally enables/disables drawing of gradient selections.\n\n :param `enable`: ``True`` to enable gradient-style selections, ``False``\n to disable it.\n\n :note: Calling this method disables any Vista-style selection previously\n enabled.\n \"\"\"\n\n self._usegradients = enable\n self._vistaselection = False\n self.RefreshSelected()\n\n\n def SetGradientStyle(self, vertical=0):\n \"\"\"\n Sets the gradient style for gradient-style selections.\n\n :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical\n gradient-style selections.\n \"\"\"\n\n # 0 = Horizontal, 1 = Vertical\n self._gradientstyle = vertical\n\n if self._usegradients:\n self.RefreshSelected()\n\n\n def GetGradientStyle(self):\n \"\"\"\n Returns the gradient style for gradient-style selections.\n\n :returns: 0 for horizontal gradient-style selections, 1 for vertical\n gradient-style selections.\n \"\"\"\n\n return self._gradientstyle\n\n\n def EnableSelectionVista(self, enable=True):\n \"\"\"\n Globally enables/disables drawing of Windows Vista selections.\n\n :param `enable`: ``True`` to enable Vista-style selections, ``False`` to\n disable it.\n\n :note: Calling this method disables any gradient-style selection previously\n enabled.\n \"\"\"\n\n self._usegradients = False\n self._vistaselection = enable\n self.RefreshSelected()\n\n\n def SetBorderPen(self, pen):\n \"\"\"\n Sets the pen used to draw the selected item border.\n\n :param `pen`: an instance of `wx.Pen`.\n\n :note: The border pen is not used if the Windows Vista selection style is applied.\n \"\"\"\n\n self._borderPen = pen\n self.RefreshSelected()\n\n\n def GetBorderPen(self):\n \"\"\"\n Returns the pen used to draw the selected item border.\n\n :note: The border pen is not used if the Windows Vista selection style is applied.\n \"\"\"\n\n return self._borderPen\n\n\n def SetConnectionPen(self, pen):\n \"\"\"\n Sets the pen used to draw the connecting lines between items.\n\n :param `pen`: an instance of `wx.Pen`.\n \"\"\"\n\n self._dottedPen = pen\n self._dirty = True\n\n\n def GetConnectionPen(self):\n \"\"\"Returns the pen used to draw the connecting lines between items.\"\"\"\n\n return self._dottedPen\n\n\n def SetBackgroundImage(self, image):\n \"\"\"\n Sets the L{CustomTreeCtrl} background image.\n\n :param `image`: if not ``None``, an instance of `wx.Bitmap`.\n\n :note: At present, the background image can only be used in \"tile\" mode.\n\n :todo: Support background images also in stretch and centered modes.\n \"\"\"\n\n self._backgroundImage = image\n self.Refresh()\n\n\n def GetBackgroundImage(self):\n \"\"\"\n Returns the L{CustomTreeCtrl} background image (if any).\n\n :note: At present, the background image can only be used in \"tile\" mode.\n\n :todo: Support background images also in stretch and centered modes.\n \"\"\"\n\n return self._backgroundImage\n\n\n def GetItemWindow(self, item):\n \"\"\"\n Returns the window associated to the item (if any).\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetWindow()\n\n\n def SetItemWindow(self, item, wnd):\n \"\"\"\n Sets the window for the given item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to\n the item.\n \"\"\"\n\n if wnd is not None:\n self._hasWindows = True\n if item not in self._itemWithWindow:\n self._itemWithWindow.append(item)\n else:\n self.DeleteItemWindow(item)\n else:\n self.DeleteItemWindow(item)\n\n item.SetWindow(wnd)\n self.CalculatePositions()\n self.Refresh()\n self.AdjustMyScrollbars()\n\n\n def DeleteItemWindow(self, item):\n \"\"\"\n Deletes the window associated to an item (if any).\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if item.GetWindow() is None:\n return\n\n item.DeleteWindow()\n if item in self._itemWithWindow:\n self._itemWithWindow.remove(item)\n\n\n def GetItemWindowEnabled(self, item):\n \"\"\"\n Returns whether the window associated to the item is enabled.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetWindowEnabled()\n\n\n def SetItemWindowEnabled(self, item, enable=True):\n \"\"\"\n Enables/disables the window associated to the item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `enable`: ``True`` to enable the associated window, ``False`` to\n disable it.\n \"\"\"\n\n item.SetWindowEnabled(enable)\n\n\n def GetItemType(self, item):\n \"\"\"\n Returns the item type.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :see: L{SetItemType} for a description of valid item types.\n \"\"\"\n\n return item.GetType()\n\n\n def SetItemType(self, item, ct_type):\n \"\"\"\n Sets the item type.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `ct_type`: May be one of the following integers:\n\n =============== =========================================\n `ct_type` Value Description\n =============== =========================================\n 0 A normal item\n 1 A checkbox-like item\n 2 A radiobutton-type item\n =============== =========================================\n\n :note: Regarding radiobutton-type items (with `ct_type` = 2), the following\n approach is used:\n\n - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,\n only one of a set of radiobuttons that share a common parent can be checked at\n once. If a radiobutton node becomes checked, then all of its peer radiobuttons\n must be unchecked.\n - If a radiobutton node becomes unchecked, then all of its child nodes will become\n inactive.\n\n \"\"\"\n\n item.SetType(ct_type)\n self.CalculatePositions()\n self.Refresh()\n\n\n# -----------------------------------------------------------------------------\n# item status inquiries\n# -----------------------------------------------------------------------------\n\n def IsVisible(self, item):\n \"\"\"\n Returns whether the item is visible or not (i.e., its hierarchy is expanded\n enough to show the item).\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n # An item is only visible if it's not a descendant of a collapsed item\n parent = item.GetParent()\n\n while parent:\n\n if not parent.IsExpanded():\n return False\n\n parent = parent.GetParent()\n\n startX, startY = self.GetViewStart()\n clientSize = self.GetClientSize()\n\n rect = self.GetBoundingRect(item)\n\n if not rect:\n return False\n if rect.GetWidth() == 0 or rect.GetHeight() == 0:\n return False\n if rect.GetBottom() < 0 or rect.GetTop() > clientSize.y:\n return False\n if rect.GetRight() < 0 or rect.GetLeft() > clientSize.x:\n return False\n\n return True\n\n\n def ItemHasChildren(self, item):\n \"\"\"\n Returns whether the item has children or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n # consider that the item does have children if it has the \"+\" button: it\n # might not have them (if it had never been expanded yet) but then it\n # could have them as well and it's better to err on this side rather than\n # disabling some operations which are restricted to the items with\n # children for an item which does have them\n return item.HasPlus()\n\n\n def IsExpanded(self, item):\n \"\"\"\n Returns whether the item is expanded or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsExpanded()\n\n\n def IsSelected(self, item):\n \"\"\"\n Returns whether the item is selected or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsSelected()\n\n\n def IsBold(self, item):\n \"\"\"\n Returns whether the item font is bold or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsBold()\n\n\n def IsItalic(self, item):\n \"\"\"\n Returns whether the item font is italic or not.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.IsItalic()\n\n\n# -----------------------------------------------------------------------------\n# navigation\n# -----------------------------------------------------------------------------\n\n def GetItemParent(self, item):\n \"\"\"\n Returns the item parent (can be ``None`` for root items).\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n return item.GetParent()\n\n\n def GetFirstChild(self, item):\n \"\"\"\n Returns the item's first child and an integer value 'cookie'.\n Call L{GetNextChild} for the next child using this very 'cookie' return\n value as an input.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method returns ``None`` if there are no further children.\n \"\"\"\n\n cookie = 0\n return self.GetNextChild(item, cookie)\n\n\n def GetNextChild(self, item, cookie):\n \"\"\"\n Returns the item's next child.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `cookie`: a parameter which is opaque for the application but is necessary\n for the library to make these functions reentrant (i.e. allow more than one\n enumeration on one and the same object simultaneously).\n\n :note: This method returns ``None`` if there are no further children.\n \"\"\"\n\n children = item.GetChildren()\n\n # it's ok to cast cookie to size_t, we never have indices big enough to\n # overflow \"void *\"\n\n if cookie < len(children):\n\n return children[cookie], cookie+1\n\n else:\n\n # there are no more of them\n return None, cookie\n\n\n def GetLastChild(self, item):\n \"\"\"\n Returns the item last child.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n children = item.GetChildren()\n return (len(children) == 0 and [None] or [children[-1]])[0]\n\n\n def GetNextSibling(self, item):\n \"\"\"\n Returns the next sibling of an item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method returns ``None`` if there are no further siblings.\n \"\"\"\n\n i = item\n parent = i.GetParent()\n\n if parent == None:\n\n # root item doesn't have any siblings\n return None\n\n siblings = parent.GetChildren()\n index = siblings.index(i)\n\n n = index + 1\n return (n == len(siblings) and [None] or [siblings[n]])[0]\n\n\n def GetPrevSibling(self, item):\n \"\"\"\n Returns the previous sibling of an item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method returns ``None`` if there are no further siblings.\n \"\"\"\n\n i = item\n parent = i.GetParent()\n\n if parent == None:\n\n # root item doesn't have any siblings\n return None\n\n siblings = parent.GetChildren()\n index = siblings.index(i)\n\n return (index == 0 and [None] or [siblings[index-1]])[0]\n\n\n def GetNext(self, item):\n \"\"\"\n Returns the next item. Only for internal use right now.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n i = item\n\n # First see if there are any children.\n children = i.GetChildren()\n if len(children) > 0:\n return children[0]\n else:\n # Try a sibling of this or ancestor instead\n p = item\n toFind = None\n while p and not toFind:\n toFind = self.GetNextSibling(p)\n p = self.GetItemParent(p)\n\n return toFind\n\n\n def GetFirstVisibleItem(self):\n \"\"\" Returns the first visible item. \"\"\"\n\n id = self.GetRootItem()\n if not id:\n return id\n\n while id:\n if self.IsVisible(id):\n return id\n id = self.GetNext(id)\n\n return None\n\n\n def GetNextVisible(self, item):\n \"\"\"\n Returns the next visible item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n id = item\n\n while id:\n id = self.GetNext(id)\n if id and self.IsVisible(id):\n return id\n\n return None\n\n\n def GetPrevVisible(self, item):\n \"\"\"\n Returns the previous visible item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n # find a previous sibling or parent which is visible\n lastGoodItem = self.GetPrevSibling(item)\n if not lastGoodItem or not self.IsVisible(lastGoodItem):\n parent = self.GetItemParent(item)\n rootHidden = self.HasAGWFlag(TR_HIDE_ROOT)\n rootItem = self.GetRootItem()\n\n while parent and not (rootHidden and parent == rootItem):\n if self.IsVisible(parent):\n lastGoodItem = parent\n break\n parent = self.GetItemParent(parent)\n\n if not lastGoodItem:\n return None\n\n # test if found item has visible children, if so and if the found item is not the\n # parent of the current item traverse the found item to the last visible child\n if not self.HasChildren(lastGoodItem) or not self.IsExpanded(lastGoodItem) or \\\n (self.GetItemParent(item) == lastGoodItem):\n return lastGoodItem\n\n lastChild = self.GetLastChild(lastGoodItem)\n while lastChild and self.IsVisible(lastChild):\n lastGoodItem = lastChild\n lastChild = self.GetLastChild(lastGoodItem)\n\n return lastGoodItem\n\n\n def ResetTextControl(self):\n \"\"\" Called by L{TreeTextCtrl} when it marks itself for deletion. \"\"\"\n\n if self._textCtrl is not None:\n self._textCtrl.Destroy()\n self._textCtrl = None\n\n self.CalculatePositions()\n self.Refresh()\n self.AdjustMyScrollbars()\n\n\n def FindItem(self, idParent, prefixOrig):\n \"\"\"\n Finds the first item starting with the given prefix after the given parent.\n\n :param `idParent`: an instance of L{GenericTreeItem};\n :param `prefixOrig`: a string containing the item text prefix.\n \"\"\"\n\n # match is case insensitive as this is more convenient to the user: having\n # to press Shift-letter to go to the item starting with a capital letter\n # would be too bothersome\n prefix = prefixOrig.lower()\n\n # determine the starting point: we shouldn't take the current item (this\n # allows to switch between two items starting with the same letter just by\n # pressing it) but we shouldn't jump to the next one if the user is\n # continuing to type as otherwise he might easily skip the item he wanted\n id = idParent\n\n if len(prefix) == 1:\n id = self.GetNext(id)\n\n # look for the item starting with the given prefix after it\n while id and not self.GetItemText(id).lower().startswith(prefix):\n\n id = self.GetNext(id)\n\n # if we haven't found anything...\n if not id:\n\n # ... wrap to the beginning\n id = self.GetRootItem()\n if self.HasAGWFlag(TR_HIDE_ROOT):\n # can't select virtual root\n id = self.GetNext(id)\n if idParent == self.GetRootItem():\n # no tree item selected and idParent is not reachable\n return id\n\n # and try all the items (stop when we get to the one we started from)\n while id != idParent and not self.GetItemText(id).lower().startswith(prefix):\n id = self.GetNext(id)\n\n return id\n\n\n# -----------------------------------------------------------------------------\n# operations\n# -----------------------------------------------------------------------------\n\n def DoInsertItem(self, parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Actually inserts an item in the tree.\n\n :param `parentId`: an instance of L{GenericTreeItem} representing the\n item's parent;\n :param `previous`: the index at which we should insert the item;\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n \"\"\"\n\n if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):\n raise Exception(\"\\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT\")\n\n if text.find(\"\\n\") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):\n raise Exception(\"\\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT\")\n\n if ct_type < 0 or ct_type > 2:\n raise Exception(\"\\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). \")\n\n parent = parentId\n\n if not parent:\n # should we give a warning here?\n return self.AddRoot(text, ct_type, wnd, image, selImage, data)\n\n self._dirty = True # do this first so stuff below doesn't cause flicker\n\n item = GenericTreeItem(parent, text, ct_type, wnd, image, selImage, data)\n\n if wnd is not None:\n self._hasWindows = True\n self._itemWithWindow.append(item)\n\n parent.Insert(item, previous)\n\n return item\n\n\n def AddRoot(self, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Adds a root item to the L{CustomTreeCtrl}.\n\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n\n :warning: only one root is allowed to exist in any given instance of L{CustomTreeCtrl}.\n \"\"\"\n\n if self._anchor:\n raise Exception(\"\\nERROR: Tree Can Have Only One Root\")\n\n if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):\n raise Exception(\"\\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT\")\n\n if text.find(\"\\n\") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):\n raise Exception(\"\\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT\")\n\n if ct_type < 0 or ct_type > 2:\n raise Exception(\"\\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). \")\n\n self._dirty = True # do this first so stuff below doesn't cause flicker\n\n self._anchor = GenericTreeItem(None, text, ct_type, wnd, image, selImage, data)\n\n if wnd is not None:\n self._hasWindows = True\n self._itemWithWindow.append(self._anchor)\n\n if self.HasAGWFlag(TR_HIDE_ROOT):\n\n # if root is hidden, make sure we can navigate\n # into children\n self._anchor.SetHasPlus()\n self._anchor.Expand()\n self.CalculatePositions()\n\n if not self.HasAGWFlag(TR_MULTIPLE):\n\n self._current = self._key_current = self._anchor\n self._current.SetHilight(True)\n\n return self._anchor\n\n\n def PrependItem(self, parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Prepends an item as a first child of parent.\n\n :param `parent`: an instance of L{GenericTreeItem} representing the\n item's parent;\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n \"\"\"\n\n return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data)\n\n\n def InsertItemByItem(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Inserts an item after the given previous.\n\n :param `parentId`: an instance of L{GenericTreeItem} representing the\n item's parent;\n :param `idPrevious`: an instance of L{GenericTreeItem} representing the\n previous item;\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n \"\"\"\n\n parent = parentId\n\n if not parent:\n # should we give a warning here?\n return self.AddRoot(text, ct_type, wnd, image, selImage, data)\n\n index = -1\n if idPrevious:\n\n try:\n index = parent.GetChildren().index(idPrevious)\n except Exception as exception:\n raise Exception(\"ERROR: Previous Item In CustomTreeCtrl.InsertItem() Is Not A Sibling\") from exception\n\n return self.DoInsertItem(parentId, index+1, text, ct_type, wnd, image, selImage, data)\n\n\n def InsertItemByIndex(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Inserts an item after the given previous.\n\n :param `parentId`: an instance of L{GenericTreeItem} representing the\n item's parent;\n :param `idPrevious`: the index at which we should insert the new item;\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n \"\"\"\n\n parent = parentId\n\n if not parent:\n # should we give a warning here?\n return self.AddRoot(text, ct_type, wnd, image, selImage, data)\n\n return self.DoInsertItem(parentId, idPrevious, text, ct_type, wnd, image, selImage, data)\n\n\n def InsertItem(self, parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Inserts an item after the given previous.\n\n :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of\n the input parameters.\n \"\"\"\n\n if type(input) == type(1):\n return self.InsertItemByIndex(parentId, input, text, ct_type, wnd, image, selImage, data)\n else:\n return self.InsertItemByItem(parentId, input, text, ct_type, wnd, image, selImage, data)\n\n\n def AppendItem(self, parentId, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):\n \"\"\"\n Appends an item as a last child of its parent.\n\n :param `parentId`: an instance of L{GenericTreeItem} representing the\n item's parent;\n :param `text`: the item text label;\n :param `ct_type`: the item type (see L{SetItemType} for a list of valid\n item types);\n :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;\n :param `image`: an index within the normal image list specifying the image to\n use for the item in unselected state;\n :param `selImage`: an index within the normal image list specifying the image to\n use for the item in selected state; if `image` > -1 and `selImage` is -1, the\n same image is used for both selected and unselected items;\n :param `data`: associate the given Python object `data` with the item.\n \"\"\"\n\n parent = parentId\n\n if not parent:\n # should we give a warning here?\n return self.AddRoot(text, ct_type, wnd, image, selImage, data)\n\n return self.DoInsertItem(parent, len(parent.GetChildren()), text, ct_type, wnd, image, selImage, data)\n\n\n def SendDeleteEvent(self, item):\n \"\"\"\n Actually sends the ``EVT_TREE_DELETE_ITEM`` event.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n event = TreeEvent(wxEVT_TREE_DELETE_ITEM, self.GetId())\n event._item = item\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n\n def IsDescendantOf(self, parent, item):\n \"\"\"\n Checks if the given item is under another one in the tree hierarchy.\n\n :param `parent`: an instance of L{GenericTreeItem}, representing the possible\n parent of `item`;\n :param `item`: another instance of L{GenericTreeItem}.\n \"\"\"\n\n while item:\n\n if item == parent:\n\n # item is a descendant of parent\n return True\n\n item = item.GetParent()\n\n return False\n\n\n # Don't leave edit or selection on a child which is about to disappear\n def ChildrenClosing(self, item):\n \"\"\"\n We are about to destroy the item children.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self._textCtrl != None and item != self._textCtrl.item() and self.IsDescendantOf(item, self._textCtrl.item()):\n self._textCtrl.StopEditing()\n\n if item != self._key_current and self.IsDescendantOf(item, self._key_current):\n self._key_current = None\n\n if self.IsDescendantOf(item, self._select_me):\n self._select_me = item\n\n if item != self._current and self.IsDescendantOf(item, self._current):\n self._current.SetHilight(False)\n self._current = None\n self._select_me = item\n\n\n def DeleteChildren(self, item):\n \"\"\"\n Delete all the item's children.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self._dirty = True # do this first so stuff below doesn't cause flicker\n\n self.ChildrenClosing(item)\n item.DeleteChildren(self)\n\n\n def Delete(self, item):\n \"\"\"\n Deletes an item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self._dirty = True # do this first so stuff below doesn't cause flicker\n\n if self._textCtrl != None and self.IsDescendantOf(item, self._textCtrl.item()):\n # can't delete the item being edited, cancel editing it first\n self._textCtrl.StopEditing()\n\n parent = item.GetParent()\n\n # don't keep stale pointers around!\n if self.IsDescendantOf(item, self._key_current):\n\n # Don't silently change the selection:\n # do it properly in idle time, so event\n # handlers get called.\n\n # self._key_current = parent\n self._key_current = None\n\n # self._select_me records whether we need to select\n # a different item, in idle time.\n if self._select_me and self.IsDescendantOf(item, self._select_me):\n self._select_me = parent\n\n if self.IsDescendantOf(item, self._current):\n\n # Don't silently change the selection:\n # do it properly in idle time, so event\n # handlers get called.\n\n # self._current = parent\n self._current = None\n self._select_me = parent\n\n # remove the item from the tree\n if parent:\n\n parent.GetChildren().remove(item) # remove by value\n\n else: # deleting the root\n\n # nothing will be left in the tree\n self._anchor = None\n\n # and delete all of its children and the item itself now\n item.DeleteChildren(self)\n self.SendDeleteEvent(item)\n\n if item == self._select_me:\n self._select_me = None\n\n # Remove the item with window\n if item in self._itemWithWindow:\n wnd = item.GetWindow()\n wnd.Hide()\n wnd.Destroy()\n item._wnd = None\n self._itemWithWindow.remove(item)\n\n del item\n\n\n def DeleteAllItems(self):\n \"\"\" Deletes all items in the L{CustomTreeCtrl}. \"\"\"\n\n if self._anchor:\n self.Delete(self._anchor)\n\n\n def Expand(self, item):\n \"\"\"\n Expands an item, sending a ``EVT_TREE_ITEM_EXPANDING`` and\n ``EVT_TREE_ITEM_EXPANDED`` events.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():\n raise Exception(\"\\nERROR: Can't Expand An Hidden Root. \")\n\n if not item.HasPlus():\n return\n\n if item.IsExpanded():\n return\n\n if self._sendEvent:\n event = TreeEvent(wxEVT_TREE_ITEM_EXPANDING, self.GetId())\n event._item = item\n event.SetEventObject(self)\n\n if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():\n # cancelled by program\n return\n\n item.Expand()\n\n if not self._sendEvent:\n # We are in ExpandAll/ExpandAllChildren\n return\n\n self.CalculatePositions()\n self.RefreshSubtree(item)\n\n if self._hasWindows:\n # We hide the associated window here, we may show it after\n self.HideWindows()\n\n event.SetEventType(wxEVT_TREE_ITEM_EXPANDED)\n self.GetEventHandler().ProcessEvent(event)\n\n\n def ExpandAllChildren(self, item):\n \"\"\"\n Expands all the items children of the input item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and\n ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the\n control would be too slow then.\n \"\"\"\n\n self._sendEvent = False\n if not self.HasAGWFlag(TR_HIDE_ROOT) or item != self.GetRootItem():\n self.Expand(item)\n if not self.IsExpanded(item):\n self._sendEvent = True\n return\n\n child, cookie = self.GetFirstChild(item)\n\n while child:\n self.ExpandAllChildren(child)\n child, cookie = self.GetNextChild(item, cookie)\n\n self._sendEvent = True\n\n\n def ExpandAll(self):\n \"\"\"\n Expands all L{CustomTreeCtrl} items.\n\n :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and\n ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the\n control would be too slow then.\n \"\"\"\n\n if self._anchor:\n self.ExpandAllChildren(self._anchor)\n\n self._sendEvent = True\n self._dirty = True\n\n\n def Collapse(self, item):\n \"\"\"\n Collapse an item, sending a ``EVT_TREE_ITEM_COLLAPSING`` and\n ``EVT_TREE_ITEM_COLLAPSED`` events.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():\n raise Exception(\"\\nERROR: Can't Collapse An Hidden Root. \")\n\n if not item.IsExpanded():\n return\n\n event = TreeEvent(wxEVT_TREE_ITEM_COLLAPSING, self.GetId())\n event._item = item\n event.SetEventObject(self)\n if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():\n # cancelled by program\n return\n\n self.ChildrenClosing(item)\n item.Collapse()\n\n self.CalculatePositions()\n self.Refresh()\n\n if self._hasWindows:\n self.HideWindows()\n\n event.SetEventType(wxEVT_TREE_ITEM_COLLAPSED)\n self.GetEventHandler().ProcessEvent(event)\n\n\n def CollapseAndReset(self, item):\n \"\"\"\n Collapse the given item and deletes its children.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n self.Collapse(item)\n self.DeleteChildren(item)\n\n\n def Toggle(self, item):\n \"\"\"\n Toggles the item state (collapsed/expanded).\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if item.IsExpanded():\n self.Collapse(item)\n else:\n self.Expand(item)\n\n\n def HideWindows(self):\n \"\"\" Hides the windows associated to the items. Used internally. \"\"\"\n\n for child in self._itemWithWindow:\n if not self.IsVisible(child):\n wnd = child.GetWindow()\n if wnd:\n wnd.Hide()\n\n\n def Unselect(self):\n \"\"\" Unselects the current selection. \"\"\"\n\n if self._current:\n self._current.SetHilight(False)\n self.RefreshLine(self._current)\n\n self._current = None\n self._select_me = None\n\n\n def UnselectAllChildren(self, item):\n \"\"\"\n Unselects all the children of the given item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if item.IsSelected():\n item.SetHilight(False)\n self.RefreshLine(item)\n\n if item.HasChildren():\n for child in item.GetChildren():\n self.UnselectAllChildren(child)\n\n\n def SelectAllChildren(self, item):\n \"\"\"\n Selects all the children of the given item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``\n style set.\n \"\"\"\n\n if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):\n raise Exception(\"SelectAllChildren can be used only with multiple selection enabled.\")\n\n if not item.IsSelected():\n item.SetHilight(True)\n self.RefreshLine(item)\n\n if item.HasChildren():\n for child in item.GetChildren():\n self.SelectAllChildren(child)\n\n\n def UnselectAll(self):\n \"\"\" Unselect all the items. \"\"\"\n\n rootItem = self.GetRootItem()\n\n # the tree might not have the root item at all\n if rootItem:\n self.UnselectAllChildren(rootItem)\n\n self.Unselect()\n\n\n def SelectAll(self):\n \"\"\"\n Selects all the item in the tree.\n\n :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``\n style set.\n \"\"\"\n\n if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):\n raise Exception(\"SelectAll can be used only with multiple selection enabled.\")\n\n rootItem = self.GetRootItem()\n\n # the tree might not have the root item at all\n if rootItem:\n self.SelectAllChildren(rootItem)\n\n\n # Recursive function !\n # To stop we must have crt_item start_y+client_h:\n\n # going up\n x, y = self._anchor.GetSize(x, y, self)\n y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels\n x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels\n item_y += _PIXELS_PER_UNIT+2\n x_pos = self.GetScrollPos(wx.HORIZONTAL)\n # Item should appear at bottom\n self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, (item_y+self.GetLineHeight(item)-client_h)/_PIXELS_PER_UNIT )\n\n\n def OnCompareItems(self, item1, item2):\n \"\"\"\n Returns whether 2 items have the same text.\n\n Override this function in the derived class to change the sort order of the items\n in the L{CustomTreeCtrl}. The function should return a negative, zero or positive\n value if the first item is less than, equal to or greater than the second one.\n\n :param `item1`: an instance of L{GenericTreeItem};\n :param `item2`: another instance of L{GenericTreeItem}.\n\n :note: The base class version compares items alphabetically.\n \"\"\"\n\n return cmp(self.GetItemText(item1), self.GetItemText(item2))\n\n\n def SortChildren(self, item):\n \"\"\"\n Sorts the children of the given item using the L{OnCompareItems} method of\n L{CustomTreeCtrl}.\n\n :param `item`: an instance of L{GenericTreeItem}.\n\n :note: You should override the L{OnCompareItems} method in your derived class to change\n the sort order (the default is ascending case-sensitive alphabetical order).\n \"\"\"\n\n children = item.GetChildren()\n\n if len(children) > 1:\n self._dirty = True\n children.sort(self.OnCompareItems)\n\n\n def GetImageList(self):\n \"\"\" Returns the normal image list associated with L{CustomTreeCtrl}. \"\"\"\n\n return self._imageListNormal\n\n\n def GetButtonsImageList(self):\n \"\"\"\n Returns the buttons image list associated with L{CustomTreeCtrl} (from\n which application-defined button images are taken).\n \"\"\"\n\n return self._imageListButtons\n\n\n def GetStateImageList(self):\n \"\"\"\n Returns the state image list associated with L{CustomTreeCtrl} (from which\n application-defined state images are taken).\n \"\"\"\n\n return self._imageListState\n\n\n def GetImageListCheck(self):\n \"\"\" Returns the image list used to build the check/radio buttons in L{CustomTreeCtrl}. \"\"\"\n\n return self._imageListCheck\n\n\n def GetLeftImageList(self):\n \"\"\"\n Returns the image list for L{CustomTreeCtrl} filled with images to be used on\n the leftmost part of the client area. Any item can have a leftmost image associated\n with it.\n \"\"\"\n\n return self._imageListLeft\n\n\n def CalculateLineHeight(self):\n \"\"\" Calculates the height of a line. \"\"\"\n\n dc = wx.ClientDC(self)\n self._lineHeight = dc.GetCharHeight()\n\n if self._imageListNormal:\n\n # Calculate a self._lineHeight value from the normal Image sizes.\n # May be toggle off. Then CustomTreeCtrl will spread when\n # necessary (which might look ugly).\n n = self._imageListNormal.GetImageCount()\n\n for i in xrange(n):\n\n width, height = self._imageListNormal.GetSize(i)\n\n if height > self._lineHeight:\n self._lineHeight = height\n\n if self._imageListButtons:\n\n # Calculate a self._lineHeight value from the Button image sizes.\n # May be toggle off. Then CustomTreeCtrl will spread when\n # necessary (which might look ugly).\n n = self._imageListButtons.GetImageCount()\n\n for i in xrange(n):\n\n width, height = self._imageListButtons.GetSize(i)\n\n if height > self._lineHeight:\n self._lineHeight = height\n\n if self._imageListCheck:\n\n # Calculate a self._lineHeight value from the check/radio image sizes.\n # May be toggle off. Then CustomTreeCtrl will spread when\n # necessary (which might look ugly).\n n = self._imageListCheck.GetImageCount()\n\n for i in xrange(n):\n\n width, height = self._imageListCheck.GetSize(i)\n\n if height > self._lineHeight:\n self._lineHeight = height\n\n if self._imageListLeft:\n\n # Calculate a self._lineHeight value from the leftmost image sizes.\n # May be toggle off. Then CustomTreeCtrl will spread when\n # necessary (which might look ugly).\n n = self._imageListLeft.GetImageCount()\n\n for i in xrange(n):\n\n width, height = self._imageListLeft.GetSize(i)\n\n if height > self._lineHeight:\n self._lineHeight = height\n\n if self._lineHeight < 30:\n self._lineHeight += 2 # at least 2 pixels\n else:\n self._lineHeight += self._lineHeight/10 # otherwise 10% extra spacing\n\n\n def SetImageList(self, imageList):\n \"\"\"\n Sets the normal image list for L{CustomTreeCtrl}.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n if self._ownsImageListNormal:\n del self._imageListNormal\n\n self._imageListNormal = imageList\n self._ownsImageListNormal = False\n self._dirty = True\n\n # Don't do any drawing if we're setting the list to NULL,\n # since we may be in the process of deleting the tree control.\n if imageList:\n self.CalculateLineHeight()\n\n # We gray out the image list to use the grayed icons with disabled items\n sz = imageList.GetSize(0)\n self._grayedImageList = wx.ImageList(sz[0], sz[1], True, 0)\n\n for ii in xrange(imageList.GetImageCount()):\n bmp = imageList.GetBitmap(ii)\n newbmp = MakeDisabledBitmap(bmp)\n self._grayedImageList.Add(newbmp)\n\n\n def SetLeftImageList(self, imageList):\n \"\"\"\n Sets the image list for L{CustomTreeCtrl} filled with images to be used on\n the leftmost part of the client area. Any item can have a leftmost image associated\n with it.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n self._imageListLeft = imageList\n self._ownsImageListLeft = False\n self._dirty = True\n\n # Don't do any drawing if we're setting the list to NULL,\n # since we may be in the process of deleting the tree control.\n if imageList:\n self.CalculateLineHeight()\n\n # We gray out the image list to use the grayed icons with disabled items\n sz = imageList.GetSize(0)\n self._grayedImageListLeft = wx.ImageList(sz[0], sz[1], True, 0)\n\n for ii in xrange(imageList.GetImageCount()):\n bmp = imageList.GetBitmap(ii)\n newbmp = MakeDisabledBitmap(bmp)\n self._grayedImageListLeft.Add(newbmp)\n\n\n def SetStateImageList(self, imageList):\n \"\"\"\n Sets the state image list for L{CustomTreeCtrl} (from which application-defined\n state images are taken).\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n if self._ownsImageListState:\n del self._imageListState\n\n self._imageListState = imageList\n self._ownsImageListState = False\n\n\n def SetButtonsImageList(self, imageList):\n \"\"\"\n Sets the buttons image list for L{CustomTreeCtrl} (from which application-defined\n button images are taken).\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n if self._ownsImageListButtons:\n del self._imageListButtons\n\n self._imageListButtons = imageList\n self._ownsImageListButtons = False\n self._dirty = True\n self.CalculateLineHeight()\n\n\n def SetImageListCheck(self, sizex, sizey, imglist=None):\n \"\"\"\n Sets the checkbox/radiobutton image list.\n\n :param `sizex`: the width of the bitmaps in the `imglist`;\n :param `sizey`: the height of the bitmaps in the `imglist`;\n :param `imglist`: an instance of `wx.ImageList`.\n \"\"\"\n\n # Image list to hold disabled versions of each control\n self._grayedCheckList = wx.ImageList(sizex, sizey, True, 0)\n\n if imglist is None:\n\n self._imageListCheck = wx.ImageList(sizex, sizey)\n\n # Get the Checkboxes\n self._imageListCheck.Add(self.GetControlBmp(checkbox=True,\n checked=True,\n enabled=True,\n x=sizex, y=sizey))\n self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,\n checked=True,\n enabled=False,\n x=sizex, y=sizey))\n\n self._imageListCheck.Add(self.GetControlBmp(checkbox=True,\n checked=False,\n enabled=True,\n x=sizex, y=sizey))\n self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,\n checked=False,\n enabled=False,\n x=sizex, y=sizey))\n\n self._imageListCheck.Add(self.GetControlBmp(checkbox=True,\n checked=2,\n enabled=True,\n x=sizex, y=sizey))\n self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,\n checked=2,\n enabled=False,\n x=sizex, y=sizey))\n\n # Get the Radio Buttons\n self._imageListCheck.Add(self.GetControlBmp(checkbox=False,\n checked=True,\n enabled=True,\n x=sizex, y=sizey))\n self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,\n checked=True,\n enabled=False,\n x=sizex, y=sizey))\n\n self._imageListCheck.Add(self.GetControlBmp(checkbox=False,\n checked=False,\n enabled=True,\n x=sizex, y=sizey))\n self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,\n checked=False,\n enabled=False,\n x=sizex, y=sizey))\n\n else:\n\n sizex, sizey = imglist.GetSize(0)\n self._imageListCheck = imglist\n\n for ii in xrange(self._imageListCheck.GetImageCount()):\n\n bmp = self._imageListCheck.GetBitmap(ii)\n newbmp = MakeDisabledBitmap(bmp)\n self._grayedCheckList.Add(newbmp)\n\n self._dirty = True\n\n if imglist:\n self.CalculateLineHeight()\n\n\n def AssignImageList(self, imageList):\n \"\"\"\n Assigns the normal image list.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n self.SetImageList(imageList)\n self._ownsImageListNormal = True\n\n\n def AssignStateImageList(self, imageList):\n \"\"\"\n Assigns the state image list.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n self.SetStateImageList(imageList)\n self._ownsImageListState = True\n\n\n def AssignButtonsImageList(self, imageList):\n \"\"\"\n Assigns the button image list.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n self.SetButtonsImageList(imageList)\n self._ownsImageListButtons = True\n\n\n def AssignLeftImageList(self, imageList):\n \"\"\"\n Assigns the image list for L{CustomTreeCtrl} filled with images to be used on\n the leftmost part of the client area. Any item can have a leftmost image associated\n with it.\n\n :param `imageList`: an instance of `wx.ImageList`.\n \"\"\"\n\n self.SetLeftImageList(imageList)\n self._ownsImageListLeft = True\n\n\n# -----------------------------------------------------------------------------\n# helpers\n# -----------------------------------------------------------------------------\n\n def AdjustMyScrollbars(self):\n \"\"\" Internal method used to adjust the `wx.PyScrolledWindow` scrollbars. \"\"\"\n\n if self._anchor:\n\n x, y = self._anchor.GetSize(0, 0, self)\n y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels\n x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels\n x_pos = self.GetScrollPos(wx.HORIZONTAL)\n y_pos = self.GetScrollPos(wx.VERTICAL)\n self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, y_pos)\n\n else:\n\n self.SetScrollbars(0, 0, 0, 0)\n\n\n def GetLineHeight(self, item):\n \"\"\"\n Returns the line height for the given item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self.GetAGWWindowStyleFlag() & TR_HAS_VARIABLE_ROW_HEIGHT:\n return item.GetHeight()\n else:\n return self._lineHeight\n\n\n def DrawVerticalGradient(self, dc, rect, hasfocus):\n \"\"\"\n Gradient fill from colour 1 to colour 2 from top to bottom.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the rectangle to be filled with the gradient shading;\n :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``\n otherwise.\n \"\"\"\n\n oldpen = dc.GetPen()\n oldbrush = dc.GetBrush()\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n # calculate gradient coefficients\n if hasfocus:\n col2 = self._secondcolour\n col1 = self._firstcolour\n else:\n col2 = self._hilightUnfocusedBrush.GetColour()\n col1 = self._hilightUnfocusedBrush2.GetColour()\n\n r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())\n r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())\n\n flrect = float(rect.height)\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n\n for y in xrange(rect.y, rect.y + rect.height):\n currCol = (r1 + rf, g1 + gf, b1 + bf)\n dc.SetBrush(wx.Brush(currCol, wx.SOLID))\n dc.DrawRectangle(rect.x, y, rect.width, 1)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n dc.SetPen(oldpen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangleRect(rect)\n dc.SetBrush(oldbrush)\n\n\n def DrawHorizontalGradient(self, dc, rect, hasfocus):\n \"\"\"\n Gradient fill from colour 1 to colour 2 from left to right.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the rectangle to be filled with the gradient shading;\n :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``\n otherwise.\n \"\"\"\n\n oldpen = dc.GetPen()\n oldbrush = dc.GetBrush()\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n # calculate gradient coefficients\n\n if hasfocus:\n col2 = self._secondcolour\n col1 = self._firstcolour\n else:\n col2 = self._hilightUnfocusedBrush.GetColour()\n col1 = self._hilightUnfocusedBrush2.GetColour()\n\n r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())\n r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())\n\n flrect = float(rect.width)\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n\n for x in xrange(rect.x, rect.x + rect.width):\n currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))\n dc.SetBrush(wx.Brush(currCol, wx.SOLID))\n dc.DrawRectangle(x, rect.y, 1, rect.height)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n dc.SetPen(oldpen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangleRect(rect)\n dc.SetBrush(oldbrush)\n\n\n def DrawVistaRectangle(self, dc, rect, hasfocus):\n \"\"\"\n Draws the selected item(s) with the Windows Vista style.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the rectangle to be filled with the gradient shading;\n :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``\n otherwise.\n \"\"\"\n\n if hasfocus:\n\n outer = _rgbSelectOuter\n inner = _rgbSelectInner\n top = _rgbSelectTop\n bottom = _rgbSelectBottom\n\n else:\n\n outer = _rgbNoFocusOuter\n inner = _rgbNoFocusInner\n top = _rgbNoFocusTop\n bottom = _rgbNoFocusBottom\n\n oldpen = dc.GetPen()\n oldbrush = dc.GetBrush()\n\n bdrRect = wx.Rect(*rect.Get())\n filRect = wx.Rect(*rect.Get())\n filRect.Deflate(1,1)\n\n r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())\n r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())\n\n flrect = float(filRect.height)\n if flrect < 1:\n flrect = self._lineHeight\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n for y in xrange(filRect.y, filRect.y + filRect.height):\n currCol = (r1 + rf, g1 + gf, b1 + bf)\n dc.SetBrush(wx.Brush(currCol, wx.SOLID))\n dc.DrawRectangle(filRect.x, y, filRect.width, 1)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(outer))\n dc.DrawRoundedRectangleRect(bdrRect, 3)\n bdrRect.Deflate(1, 1)\n dc.SetPen(wx.Pen(inner))\n dc.DrawRoundedRectangleRect(bdrRect, 2)\n\n dc.SetPen(oldpen)\n dc.SetBrush(oldbrush)\n\n\n def PaintItem(self, item, dc, level, align):\n \"\"\"\n Actually draws an item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `dc`: an instance of `wx.DC`;\n :param `level`: the item level in the tree hierarchy;\n :param `align`: ``True`` if we want to align windows (in items with windows)\n at the same horizontal position.\n \"\"\"\n\n attr = item.GetAttributes()\n\n if attr and attr.HasFont():\n dc.SetFont(attr.GetFont())\n else:\n if item.IsBold():\n dc.SetFont(self._boldFont)\n elif item.IsItalic():\n dc.SetFont(self._italicFont)\n if item.IsHyperText():\n dc.SetFont(self.GetHyperTextFont())\n if item.GetVisited():\n dc.SetTextForeground(self.GetHyperTextVisitedColour())\n else:\n dc.SetTextForeground(self.GetHyperTextNewColour())\n\n text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())\n\n image = item.GetCurrentImage()\n checkimage = item.GetCurrentCheckedImage()\n leftimage = _NO_IMAGE\n\n if self._imageListLeft:\n leftimage = item.GetLeftImage()\n\n image_w, image_h = 0, 0\n\n if image != _NO_IMAGE:\n\n if self._imageListNormal:\n\n image_w, image_h = self._imageListNormal.GetSize(image)\n image_w += 4\n\n else:\n\n image = _NO_IMAGE\n\n if item.GetType() != 0:\n wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())\n wcheck += 4\n else:\n wcheck, hcheck = 0, 0\n\n if leftimage != _NO_IMAGE:\n l_image_w, l_image_h = self._imageListLeft.GetSize(leftimage)\n\n total_h = self.GetLineHeight(item)\n drawItemBackground = False\n\n if item.IsSelected():\n\n # under mac selections are only a rectangle in case they don't have the focus\n if wx.Platform == \"__WXMAC__\":\n if not self._hasFocus:\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT), 1, wx.SOLID))\n else:\n dc.SetBrush(self._hilightBrush)\n else:\n dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])\n drawItemBackground = True\n else:\n if attr and attr.HasBackgroundColour():\n drawItemBackground = True\n colBg = attr.GetBackgroundColour()\n else:\n colBg = self._backgroundColour\n\n dc.SetBrush(wx.Brush(colBg, wx.SOLID))\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n offset = (self.HasAGWFlag(TR_ROW_LINES) and [1] or [0])[0]\n\n if self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):\n x = 0\n w, h = self.GetClientSize()\n\n itemrect = wx.Rect(x, item.GetY()+offset, w, total_h-offset)\n\n if item.IsSelected():\n if self._usegradients:\n if self._gradientstyle == 0: # Horizontal\n self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)\n else: # Vertical\n self.DrawVerticalGradient(dc, itemrect, self._hasFocus)\n elif self._vistaselection:\n self.DrawVistaRectangle(dc, itemrect, self._hasFocus)\n else:\n if wx.Platform in [\"__WXGTK2__\", \"__WXMAC__\"]:\n flags = wx.CONTROL_SELECTED\n if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED\n wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)\n else:\n dc.DrawRectangleRect(itemrect)\n else:\n if drawItemBackground:\n minusicon = wcheck + image_w - 2\n itemrect = wx.Rect(item.GetX()+minusicon,\n item.GetY()+offset,\n item.GetWidth()-minusicon,\n total_h-offset)\n dc.DrawRectangleRect(itemrect)\n\n else:\n\n if item.IsSelected():\n\n # If it's selected, and there's an image, then we should\n # take care to leave the area under the image painted in the\n # background colour.\n\n wnd = item.GetWindow()\n wndx = 0\n if wnd:\n wndx, wndy = item.GetWindowSize()\n\n itemrect = wx.Rect(item.GetX() + wcheck + image_w - 2,\n item.GetY()+offset,\n item.GetWidth() - image_w - wcheck + 2 - wndx,\n total_h-offset)\n\n if self._usegradients:\n if self._gradientstyle == 0: # Horizontal\n self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)\n else: # Vertical\n self.DrawVerticalGradient(dc, itemrect, self._hasFocus)\n elif self._vistaselection:\n self.DrawVistaRectangle(dc, itemrect, self._hasFocus)\n else:\n if wx.Platform in [\"__WXGTK2__\", \"__WXMAC__\"]:\n flags = wx.CONTROL_SELECTED\n if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED\n wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)\n else:\n dc.DrawRectangleRect(itemrect)\n\n # On GTK+ 2, drawing a 'normal' background is wrong for themes that\n # don't allow backgrounds to be customized. Not drawing the background,\n # except for custom item backgrounds, works for both kinds of theme.\n elif drawItemBackground:\n\n minusicon = wcheck + image_w - 2\n itemrect = wx.Rect(item.GetX()+minusicon,\n item.GetY()+offset,\n item.GetWidth()-minusicon,\n total_h-offset)\n\n if self._usegradients and self._hasFocus:\n if self._gradientstyle == 0: # Horizontal\n self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)\n else: # Vertical\n self.DrawVerticalGradient(dc, itemrect, self._hasFocus)\n else:\n dc.DrawRectangleRect(itemrect)\n\n if image != _NO_IMAGE:\n\n dc.SetClippingRegion(item.GetX(), item.GetY(), wcheck+image_w-2, total_h)\n if item.IsEnabled():\n imglist = self._imageListNormal\n else:\n imglist = self._grayedImageList\n\n imglist.Draw(image, dc,\n item.GetX() + wcheck,\n item.GetY() + ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0],\n wx.IMAGELIST_DRAW_TRANSPARENT)\n\n dc.DestroyClippingRegion()\n\n if wcheck:\n if item.IsEnabled():\n imglist = self._imageListCheck\n else:\n imglist = self._grayedCheckList\n\n imglist.Draw(checkimage, dc,\n item.GetX(),\n item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0],\n wx.IMAGELIST_DRAW_TRANSPARENT)\n\n if leftimage != _NO_IMAGE:\n if item.IsEnabled():\n imglist = self._imageListLeft\n else:\n imglist = self._grayedImageListLeft\n\n imglist.Draw(leftimage, dc,\n 4,\n item.GetY() + ((total_h > l_image_h) and [(total_h-l_image_h)/2] or [0])[0],\n wx.IMAGELIST_DRAW_TRANSPARENT)\n\n dc.SetBackgroundMode(wx.TRANSPARENT)\n extraH = ((total_h > text_h) and [(total_h - text_h)/2] or [0])[0]\n\n textrect = wx.Rect(wcheck + image_w + item.GetX(), item.GetY() + extraH, text_w, text_h)\n\n if not item.IsEnabled():\n foreground = dc.GetTextForeground()\n dc.SetTextForeground(self._disabledColour)\n dc.DrawLabel(item.GetText(), textrect)\n dc.SetTextForeground(foreground)\n else:\n if wx.Platform == \"__WXMAC__\" and item.IsSelected() and self._hasFocus:\n dc.SetTextForeground(wx.WHITE)\n dc.DrawLabel(item.GetText(), textrect)\n\n wnd = item.GetWindow()\n if wnd:\n wndx = wcheck + image_w + item.GetX() + text_w + 4\n xa, ya = self.CalcScrolledPosition((0, item.GetY()))\n wndx += xa\n if item.GetHeight() > item.GetWindowSize()[1]:\n ya += (item.GetHeight() - item.GetWindowSize()[1])/2\n\n if align and level in self.absoluteWindows:\n wndx = self.absoluteWindows[level] + item.GetX() + 2\n\n if not wnd.IsShown():\n wnd.Show()\n if wnd.GetPosition() != (wndx, ya):\n wnd.SetPosition((wndx, ya))\n\n # restore normal font\n dc.SetFont(self._normalFont)\n\n\n # Now y stands for the top of the item, whereas it used to stand for middle !\n def PaintLevel(self, item, dc, level, y, align):\n \"\"\"\n Paint a level in the hierarchy of L{CustomTreeCtrl}.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `dc`: an instance of `wx.DC`;\n :param `level`: the item level in the tree hierarchy;\n :param `y`: the current vertical position in the `wx.PyScrolledWindow`;\n :param `align`: ``True`` if we want to align windows (in items with windows)\n at the same horizontal position.\n \"\"\"\n\n x = level*self._indent\n\n left_image_list = 0\n if self._imageListLeft:\n left_image_list += self._imageListLeft.GetBitmap(0).GetWidth()\n\n x += left_image_list\n\n if not self.HasAGWFlag(TR_HIDE_ROOT):\n\n x += self._indent\n\n elif level == 0:\n\n # always expand hidden root\n origY = y\n children = item.GetChildren()\n count = len(children)\n\n if count > 0:\n n = 0\n while n < count:\n oldY = y\n y = self.PaintLevel(children[n], dc, 1, y, align)\n n = n + 1\n\n if not self.HasAGWFlag(TR_NO_LINES) and self.HasAGWFlag(TR_LINES_AT_ROOT) and count > 0:\n\n # draw line down to last child\n origY += self.GetLineHeight(children[0])>>1\n oldY += self.GetLineHeight(children[n-1])>>1\n oldPen = dc.GetPen()\n dc.SetPen(self._dottedPen)\n dc.DrawLine(3, origY, 3, oldY)\n dc.SetPen(oldPen)\n\n return y\n\n item.SetX(x+self._spacing)\n item.SetY(y)\n\n h = self.GetLineHeight(item)\n y_top = y\n y_mid = y_top + (h>>1)\n y += h\n\n exposed_x = dc.LogicalToDeviceX(0)\n exposed_y = dc.LogicalToDeviceY(y_top)\n\n if self.IsExposed(exposed_x, exposed_y, 10000, h): # 10000 = very much\n if wx.Platform == \"__WXMAC__\":\n # don't draw rect outline if we already have the\n # background colour under Mac\n pen = ((item.IsSelected() and self._hasFocus) and [self._borderPen] or [wx.TRANSPARENT_PEN])[0]\n else:\n pen = self._borderPen\n\n if item.IsSelected():\n if (wx.Platform == \"__WXMAC__\" and self._hasFocus):\n colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)\n else:\n colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)\n else:\n attr = item.GetAttributes()\n if attr and attr.HasTextColour():\n colText = attr.GetTextColour()\n else:\n colText = self.GetForegroundColour()\n\n if self._vistaselection:\n colText = wx.BLACK\n\n # prepare to draw\n dc.SetTextForeground(colText)\n dc.SetPen(pen)\n oldpen = pen\n\n # draw\n self.PaintItem(item, dc, level, align)\n\n if self.HasAGWFlag(TR_ROW_LINES):\n\n # if the background colour is white, choose a\n # contrasting colour for the lines\n medium_grey = wx.Pen(wx.Colour(200, 200, 200))\n dc.SetPen(((self.GetBackgroundColour() == wx.WHITE) and [medium_grey] or [wx.WHITE_PEN])[0])\n dc.DrawLine(0, y_top, 10000, y_top)\n dc.DrawLine(0, y, 10000, y)\n\n # restore DC objects\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.SetTextForeground(wx.BLACK)\n\n if not self.HasAGWFlag(TR_NO_LINES):\n\n # draw the horizontal line here\n dc.SetPen(self._dottedPen)\n x_start = x\n if x > self._indent+left_image_list:\n x_start -= self._indent\n elif self.HasAGWFlag(TR_LINES_AT_ROOT):\n x_start = 3\n dc.DrawLine(x_start, y_mid, x + self._spacing, y_mid)\n dc.SetPen(oldpen)\n\n # should the item show a button?\n if item.HasPlus() and self.HasButtons():\n\n if self._imageListButtons:\n\n # draw the image button here\n image_h = 0\n image_w = 0\n image = (item.IsExpanded() and [TreeItemIcon_Expanded] or [TreeItemIcon_Normal])[0]\n if item.IsSelected():\n image += TreeItemIcon_Selected - TreeItemIcon_Normal\n\n image_w, image_h = self._imageListButtons.GetSize(image)\n xx = x - image_w/2\n yy = y_mid - image_h/2\n\n dc.SetClippingRegion(xx, yy, image_w, image_h)\n self._imageListButtons.Draw(image, dc, xx, yy,\n wx.IMAGELIST_DRAW_TRANSPARENT)\n dc.DestroyClippingRegion()\n\n else: # no custom buttons\n\n if self.HasAGWFlag(TR_TWIST_BUTTONS):\n # We draw something like the Mac twist buttons\n\n dc.SetPen(wx.BLACK_PEN)\n dc.SetBrush(self._hilightBrush)\n button = [wx.Point(), wx.Point(), wx.Point()]\n\n if item.IsExpanded():\n button[0].x = x - 5\n button[0].y = y_mid - 3\n button[1].x = x + 5\n button[1].y = button[0].y\n button[2].x = x\n button[2].y = button[0].y + 6\n else:\n button[0].x = x - 3\n button[0].y = y_mid - 5\n button[1].x = button[0].x\n button[1].y = y_mid + 5\n button[2].x = button[0].x + 5\n button[2].y = y_mid\n\n dc.DrawPolygon(button)\n\n else:\n # These are the standard wx.TreeCtrl buttons as wx.RendererNative knows\n\n wImage = 9\n hImage = 9\n\n flag = 0\n\n if item.IsExpanded():\n flag |= _CONTROL_EXPANDED\n if item == self._underMouse:\n flag |= _CONTROL_CURRENT\n\n self._drawingfunction(self, dc, wx.Rect(x - wImage/2, y_mid - hImage/2,wImage, hImage), flag)\n\n if item.IsExpanded():\n\n children = item.GetChildren()\n count = len(children)\n\n if count > 0:\n\n n = 0\n level = level + 1\n\n while n < count:\n oldY = y\n y = self.PaintLevel(children[n], dc, level, y, align)\n n = n + 1\n\n if not self.HasAGWFlag(TR_NO_LINES) and count > 0:\n\n # draw line down to last child\n oldY += self.GetLineHeight(children[n-1])>>1\n if self.HasButtons():\n y_mid += 5\n\n # Only draw the portion of the line that is visible, in case it is huge\n xOrigin, yOrigin = dc.GetDeviceOrigin()\n yOrigin = abs(yOrigin)\n width, height = self.GetClientSize()\n\n # Move end points to the begining/end of the view?\n if y_mid < yOrigin:\n y_mid = yOrigin\n if oldY > yOrigin + height:\n oldY = yOrigin + height\n\n # after the adjustments if y_mid is larger than oldY then the line\n # isn't visible at all so don't draw anything\n if y_mid < oldY:\n dc.SetPen(self._dottedPen)\n dc.DrawLine(x, y_mid, x, oldY)\n\n return y\n\n\n# -----------------------------------------------------------------------------\n# wxWidgets callbacks\n# -----------------------------------------------------------------------------\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n dc = wx.PaintDC(self)\n self.PrepareDC(dc)\n\n if not self._anchor:\n return\n\n dc.SetFont(self._normalFont)\n dc.SetPen(self._dottedPen)\n\n align = self.HasAGWFlag(TR_ALIGN_WINDOWS)\n y = 2\n self.PaintLevel(self._anchor, dc, 0, y, align)\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n self.RefreshSelected()\n event.Skip()\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n \"\"\"\n\n # Can we actually do something here (or in OnPaint()) To Handle\n # background images that are stretchable or always centered?\n # I tried but I get enormous flickering...\n\n if not self._backgroundImage:\n event.Skip()\n return\n\n if self._imageStretchStyle == _StyleTile:\n dc = event.GetDC()\n\n if not dc:\n dc = wx.ClientDC(self)\n rect = self.GetUpdateRegion().GetBox()\n dc.SetClippingRect(rect)\n\n self.TileBackground(dc)\n\n\n def TileBackground(self, dc):\n \"\"\"\n Tiles the background image to fill all the available area.\n\n :param `dc`: an instance of `wx.DC`.\n\n :todo: Support background images also in stretch and centered modes.\n \"\"\"\n\n sz = self.GetClientSize()\n w = self._backgroundImage.GetWidth()\n h = self._backgroundImage.GetHeight()\n\n x = 0\n\n while x < sz.width:\n y = 0\n\n while y < sz.height:\n dc.DrawBitmap(self._backgroundImage, x, y, True)\n y = y + h\n\n x = x + w\n\n\n def OnSetFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_SET_FOCUS`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n self._hasFocus = True\n self.RefreshSelected()\n event.Skip()\n\n\n def OnKillFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_KILL_FOCUS`` event for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n self._hasFocus = False\n self.RefreshSelected()\n event.Skip()\n\n\n def OnKeyDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_DOWN`` event for L{CustomTreeCtrl}, sending a\n ``EVT_TREE_KEY_DOWN`` event.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n te = TreeEvent(wxEVT_TREE_KEY_DOWN, self.GetId())\n te._evtKey = event\n te.SetEventObject(self)\n\n if self.GetEventHandler().ProcessEvent(te):\n # intercepted by the user code\n return\n\n if self._current is None or self._key_current is None:\n\n event.Skip()\n return\n\n # how should the selection work for this event?\n is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),\n event.ShiftDown(), event.CmdDown())\n\n # + : Expand\n # - : Collaspe\n # * : Expand all/Collapse all\n # ' ' | return : activate\n # up : go up (not last children!)\n # down : go down\n # left : go to parent\n # right : open if parent and go next\n # home : go to root\n # end : go to last item without opening parents\n # alnum : start or continue searching for the item with this prefix\n\n keyCode = event.GetKeyCode()\n\n if keyCode in [ord(\"+\"), wx.WXK_ADD]: # \"+\"\n if self._current.HasPlus() and not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):\n self.Expand(self._current)\n\n elif keyCode in [ord(\"*\"), wx.WXK_MULTIPLY]: # \"*\"\n if not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):\n # expand all\n self.ExpandAll(self._current)\n\n elif keyCode in [ord(\"-\"), wx.WXK_SUBTRACT]: # \"-\"\n if self.IsExpanded(self._current):\n self.Collapse(self._current)\n\n elif keyCode == wx.WXK_MENU:\n # Use the item's bounding rectangle to determine position for the event\n itemRect = self.GetBoundingRect(self._current, True)\n event = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())\n event._item = self._current\n # Use the left edge, vertical middle\n event._pointDrag = wx.Point(itemRect.GetX(), itemRect.GetY() + itemRect.GetHeight()/2)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n elif keyCode in [wx.WXK_RETURN, wx.WXK_SPACE, wx.WXK_NUMPAD_ENTER]:\n\n if not self.IsItemEnabled(self._current):\n event.Skip()\n return\n\n if not event.HasModifiers():\n event = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())\n event._item = self._current\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n if keyCode == wx.WXK_SPACE and self.GetItemType(self._current) > 0:\n if self.IsItem3State(self._current):\n checked = self.GetItem3StateValue(self._current)\n checked = (checked+1)%3\n else:\n checked = not self.IsItemChecked(self._current)\n\n self.CheckItem(self._current, checked)\n\n # in any case, also generate the normal key event for this key,\n # even if we generated the ACTIVATED event above: this is what\n # wxMSW does and it makes sense because you might not want to\n # process ACTIVATED event at all and handle Space and Return\n # directly (and differently) which would be impossible otherwise\n event.Skip()\n\n # up goes to the previous sibling or to the last\n # of its children if it's expanded\n elif keyCode == wx.WXK_UP:\n prev = self.GetPrevSibling(self._key_current)\n if not prev:\n prev = self.GetItemParent(self._key_current)\n if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):\n return\n\n if prev:\n current = self._key_current\n # TODO: Huh? If we get here, we'd better be the first child of our parent. How else could it be?\n if current == self.GetFirstChild(prev)[0] and self.IsItemEnabled(prev):\n # otherwise we return to where we came from\n self.DoSelectItem(prev, unselect_others, extended_select)\n self._key_current = prev\n\n else:\n current = self._key_current\n\n # We are going to another parent node\n while self.IsExpanded(prev) and self.HasChildren(prev):\n child = self.GetLastChild(prev)\n if child:\n prev = child\n current = prev\n\n # Try to get the previous siblings and see if they are active\n while prev and not self.IsItemEnabled(prev):\n prev = self.GetPrevSibling(prev)\n\n if not prev:\n # No previous siblings active: go to the parent and up\n prev = self.GetItemParent(current)\n while prev and not self.IsItemEnabled(prev):\n prev = self.GetItemParent(prev)\n\n if prev:\n self.DoSelectItem(prev, unselect_others, extended_select)\n self._key_current = prev\n\n # left arrow goes to the parent\n elif keyCode == wx.WXK_LEFT:\n\n prev = self.GetItemParent(self._current)\n if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):\n # don't go to root if it is hidden\n prev = self.GetPrevSibling(self._current)\n\n if self.IsExpanded(self._current):\n self.Collapse(self._current)\n else:\n if prev and self.IsItemEnabled(prev):\n self.DoSelectItem(prev, unselect_others, extended_select)\n\n elif keyCode == wx.WXK_RIGHT:\n # this works the same as the down arrow except that we\n # also expand the item if it wasn't expanded yet\n if self.IsExpanded(self._current) and self.HasChildren(self._current):\n child, cookie = self.GetFirstChild(self._key_current)\n if self.IsItemEnabled(child):\n self.DoSelectItem(child, unselect_others, extended_select)\n self._key_current = child\n else:\n self.Expand(self._current)\n # fall through\n\n elif keyCode == wx.WXK_DOWN:\n if self.IsExpanded(self._key_current) and self.HasChildren(self._key_current):\n\n child = self.GetNextActiveItem(self._key_current)\n\n if child:\n self.DoSelectItem(child, unselect_others, extended_select)\n self._key_current = child\n\n else:\n\n next = self.GetNextSibling(self._key_current)\n\n if not next:\n current = self._key_current\n while current and not next:\n current = self.GetItemParent(current)\n if current:\n next = self.GetNextSibling(current)\n if not next or not self.IsItemEnabled(next):\n next = None\n\n else:\n while next and not self.IsItemEnabled(next):\n next = self.GetNext(next)\n\n if next:\n self.DoSelectItem(next, unselect_others, extended_select)\n self._key_current = next\n\n\n # selects the last visible tree item\n elif keyCode == wx.WXK_END:\n\n last = self.GetRootItem()\n\n while last and self.IsExpanded(last):\n\n lastChild = self.GetLastChild(last)\n\n # it may happen if the item was expanded but then all of\n # its children have been deleted - so IsExpanded() returned\n # true, but GetLastChild() returned invalid item\n if not lastChild:\n break\n\n last = lastChild\n\n if last and self.IsItemEnabled(last):\n\n self.DoSelectItem(last, unselect_others, extended_select)\n\n # selects the root item\n elif keyCode == wx.WXK_HOME:\n\n prev = self.GetRootItem()\n\n if not prev:\n return\n\n if self.HasAGWFlag(TR_HIDE_ROOT):\n prev, cookie = self.GetFirstChild(prev)\n if not prev:\n return\n\n if self.IsItemEnabled(prev):\n self.DoSelectItem(prev, unselect_others, extended_select)\n\n else:\n\n if not event.HasModifiers() and ((keyCode >= ord('0') and keyCode <= ord('9')) or \\\n (keyCode >= ord('a') and keyCode <= ord('z')) or \\\n (keyCode >= ord('A') and keyCode <= ord('Z'))):\n\n # find the next item starting with the given prefix\n ch = chr(keyCode)\n id = self.FindItem(self._current, self._findPrefix + ch)\n\n if not id:\n # no such item\n return\n\n if self.IsItemEnabled(id):\n self.SelectItem(id)\n self._findPrefix += ch\n\n # also start the timer to reset the current prefix if the user\n # doesn't press any more alnum keys soon -- we wouldn't want\n # to use this prefix for a new item search\n if not self._findTimer:\n self._findTimer = TreeFindTimer(self)\n\n self._findTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)\n\n else:\n\n event.Skip()\n\n\n def GetNextActiveItem(self, item, down=True):\n \"\"\"\n Returns the next active item. Used Internally at present.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `down`: ``True`` to search downwards in the hierarchy for an active item,\n ``False`` to search upwards.\n \"\"\"\n\n if down:\n sibling = self.GetNextSibling\n else:\n sibling = self.GetPrevSibling\n\n if self.GetItemType(item) == 2 and not self.IsItemChecked(item):\n # Is an unchecked radiobutton... all its children are inactive\n # try to get the next/previous sibling\n found = 0\n\n while 1:\n child = sibling(item)\n if (child and self.IsItemEnabled(child)) or not child:\n break\n item = child\n\n else:\n # Tha's not a radiobutton... but some of its children can be\n # inactive\n child, cookie = self.GetFirstChild(item)\n while child and not self.IsItemEnabled(child):\n child, cookie = self.GetNextChild(item, cookie)\n\n if child and self.IsItemEnabled(child):\n return child\n\n return None\n\n\n def HitTest(self, point, flags=0):\n \"\"\"\n Calculates which (if any) item is under the given point, returning the tree item\n at this point plus extra information flags.\n\n :param `point`: an instance of `wx.Point`, a point to test for hits;\n :param `flags`: a bitlist of the following values:\n\n ================================== =============== =================================\n HitTest Flags Hex Value Description\n ================================== =============== =================================\n ``TREE_HITTEST_ABOVE`` 0x1 Above the client area\n ``TREE_HITTEST_BELOW`` 0x2 Below the client area\n ``TREE_HITTEST_NOWHERE`` 0x4 No item has been hit\n ``TREE_HITTEST_ONITEMBUTTON`` 0x8 On the button associated to an item\n ``TREE_HITTEST_ONITEMICON`` 0x10 On the icon associated to an item\n ``TREE_HITTEST_ONITEMINDENT`` 0x20 On the indent associated to an item\n ``TREE_HITTEST_ONITEMLABEL`` 0x40 On the label (string) associated to an item\n ``TREE_HITTEST_ONITEM`` 0x50 Anywhere on the item\n ``TREE_HITTEST_ONITEMRIGHT`` 0x80 On the right of the label associated to an item\n ``TREE_HITTEST_TOLEFT`` 0x200 On the left of the client area\n ``TREE_HITTEST_TORIGHT`` 0x400 On the right of the client area\n ``TREE_HITTEST_ONITEMUPPERPART`` 0x800 On the upper part (first half) of the item\n ``TREE_HITTEST_ONITEMLOWERPART`` 0x1000 On the lower part (second half) of the item\n ``TREE_HITTEST_ONITEMCHECKICON`` 0x2000 On the check/radio icon, if present\n ================================== =============== =================================\n\n :note: both the item (if any, ``None`` otherwise) and the `flags` are always returned as a tuple.\n \"\"\"\n\n w, h = self.GetSize()\n flags = 0\n\n if point.x < 0:\n flags |= TREE_HITTEST_TOLEFT\n if point.x > w:\n flags |= TREE_HITTEST_TORIGHT\n if point.y < 0:\n flags |= TREE_HITTEST_ABOVE\n if point.y > h:\n flags |= TREE_HITTEST_BELOW\n\n if flags:\n return None, flags\n\n if self._anchor == None:\n flags = TREE_HITTEST_NOWHERE\n return None, flags\n\n hit, flags = self._anchor.HitTest(self.CalcUnscrolledPosition(point), self, flags, 0)\n\n if hit == None:\n flags = TREE_HITTEST_NOWHERE\n return None, flags\n\n if not self.IsItemEnabled(hit):\n return None, flags\n\n return hit, flags\n\n\n def GetBoundingRect(self, item, textOnly=False):\n \"\"\"\n Retrieves the rectangle bounding the item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `textOnly`: if ``True``, only the rectangle around the item's label will\n be returned, otherwise the item's image is also taken into account.\n\n :note: The rectangle coordinates are logical, not physical ones. So, for example,\n the x coordinate may be negative if the tree has a horizontal scrollbar and its\n position is not 0.\n \"\"\"\n\n i = item\n\n startX, startY = self.GetViewStart()\n rect = wx.Rect()\n\n rect.x = i.GetX() - startX*_PIXELS_PER_UNIT\n rect.y = i.GetY() - startY*_PIXELS_PER_UNIT\n rect.width = i.GetWidth()\n rect.height = self.GetLineHeight(i)\n\n return rect\n\n\n def Edit(self, item):\n \"\"\"\n Internal function. Starts the editing of an item label, sending a\n ``EVT_TREE_BEGIN_LABEL_EDIT`` event.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n te = TreeEvent(wxEVT_TREE_BEGIN_LABEL_EDIT, self.GetId())\n te._item = item\n te.SetEventObject(self)\n if self.GetEventHandler().ProcessEvent(te) and not te.IsAllowed():\n # vetoed by user\n return\n\n # We have to call this here because the label in\n # question might just have been added and no screen\n # update taken place.\n if self._dirty:\n if wx.Platform in [\"__WXMSW__\", \"__WXMAC__\"]:\n self.Update()\n else:\n wx.YieldIfNeeded()\n\n if self._textCtrl != None and item != self._textCtrl.item():\n self._textCtrl.StopEditing()\n\n self._textCtrl = TreeTextCtrl(self, item=item)\n self._textCtrl.SetFocus()\n\n\n def GetEditControl(self):\n \"\"\"\n Returns a pointer to the edit L{TreeTextCtrl} if the item is being edited or\n ``None`` otherwise (it is assumed that no more than one item may be edited\n simultaneously).\n \"\"\"\n\n return self._textCtrl\n\n\n def OnRenameAccept(self, item, value):\n \"\"\"\n Called by L{TreeTextCtrl}, to accept the changes and to send the\n ``EVT_TREE_END_LABEL_EDIT`` event.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `value`: the new value of the item label.\n \"\"\"\n\n le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())\n le._item = item\n le.SetEventObject(self)\n le._label = value\n le._editCancelled = False\n\n return not self.GetEventHandler().ProcessEvent(le) or le.IsAllowed()\n\n\n def OnRenameCancelled(self, item):\n \"\"\"\n Called by L{TreeTextCtrl}, to cancel the changes and to send the\n ``EVT_TREE_END_LABEL_EDIT`` event.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n # let owner know that the edit was cancelled\n le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())\n le._item = item\n le.SetEventObject(self)\n le._label = \"\"\n le._editCancelled = True\n\n self.GetEventHandler().ProcessEvent(le)\n\n\n def OnRenameTimer(self):\n \"\"\" The timer for renaming has expired. Start editing. \"\"\"\n\n self.Edit(self._current)\n\n\n def OnMouse(self, event):\n \"\"\"\n Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for L{CustomTreeCtrl}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self._anchor:\n return\n\n pt = self.CalcUnscrolledPosition(event.GetPosition())\n\n # Is the mouse over a tree item button?\n flags = 0\n thisItem, flags = self._anchor.HitTest(pt, self, flags, 0)\n underMouse = thisItem\n underMouseChanged = underMouse != self._underMouse\n\n if underMouse and (flags & TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \\\n not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):\n underMouse = underMouse\n else:\n underMouse = None\n\n if underMouse != self._underMouse:\n if self._underMouse:\n # unhighlight old item\n self._underMouse = None\n\n self._underMouse = underMouse\n\n # Determines what item we are hovering over and need a tooltip for\n hoverItem = thisItem\n\n # We do not want a tooltip if we are dragging, or if the rename timer is running\n if underMouseChanged and not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):\n\n if hoverItem is not None:\n # Ask the tree control what tooltip (if any) should be shown\n hevent = TreeEvent(wxEVT_TREE_ITEM_GETTOOLTIP, self.GetId())\n hevent._item = hoverItem\n hevent.SetEventObject(self)\n\n if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():\n self.SetToolTip(hevent._label)\n\n if hoverItem.IsHyperText() and (flags & TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled():\n self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))\n self._isonhyperlink = True\n else:\n if self._isonhyperlink:\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n self._isonhyperlink = False\n\n # we process left mouse up event (enables in-place edit), right down\n # (pass to the user code), left dbl click (activate item) and\n # dragging/moving events for items drag-and-drop\n\n if not (event.LeftDown() or event.LeftUp() or event.RightDown() or event.LeftDClick() or \\\n event.Dragging() or ((event.Moving() or event.RightUp()) and self._isDragging)):\n\n event.Skip()\n return\n\n flags = 0\n item, flags = self._anchor.HitTest(pt, self, flags, 0)\n\n if event.Dragging() and not self._isDragging and ((flags & TREE_HITTEST_ONITEMICON) or (flags & TREE_HITTEST_ONITEMLABEL)):\n\n if self._dragCount == 0:\n self._dragStart = pt\n\n self._countDrag = 0\n self._dragCount = self._dragCount + 1\n\n if self._dragCount != 3:\n # wait until user drags a bit further...\n return\n\n command = (event.RightIsDown() and [wxEVT_TREE_BEGIN_RDRAG] or [wxEVT_TREE_BEGIN_DRAG])[0]\n\n nevent = TreeEvent(command, self.GetId())\n nevent._item = self._current\n nevent.SetEventObject(self)\n newpt = self.CalcScrolledPosition(pt)\n nevent.SetPoint(newpt)\n\n # by default the dragging is not supported, the user code must\n # explicitly allow the event for it to take place\n nevent.Veto()\n\n if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed():\n\n # we're going to drag this item\n self._isDragging = True\n\n # remember the old cursor because we will change it while\n # dragging\n self._oldCursor = self._cursor\n\n # in a single selection control, hide the selection temporarily\n if not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE):\n self._oldSelection = self.GetSelection()\n\n if self._oldSelection:\n\n self._oldSelection.SetHilight(False)\n self.RefreshLine(self._oldSelection)\n else:\n selections = self.GetSelections()\n if len(selections) == 1:\n self._oldSelection = selections[0]\n self._oldSelection.SetHilight(False)\n self.RefreshLine(self._oldSelection)\n\n if self._dragImage:\n del self._dragImage\n\n # Create the custom draw image from the icons and the text of the item\n self._dragImage = DragImage(self, self._current)\n self._dragImage.BeginDrag(wx.Point(0,0), self)\n self._dragImage.Show()\n self._dragImage.Move(self.CalcScrolledPosition(pt))\n\n elif event.Dragging() and self._isDragging:\n\n self._dragImage.Move(self.CalcScrolledPosition(pt))\n\n if self._countDrag == 0 and item:\n self._oldItem = item\n\n if item != self._dropTarget:\n\n # unhighlight the previous drop target\n if self._dropTarget:\n self._dropTarget.SetHilight(False)\n self.RefreshLine(self._dropTarget)\n if item:\n item.SetHilight(True)\n self.RefreshLine(item)\n self._countDrag = self._countDrag + 1\n self._dropTarget = item\n\n self.Update()\n\n if self._countDrag >= 3:\n # Here I am trying to avoid ugly repainting problems... hope it works\n self.RefreshLine(self._oldItem)\n self._countDrag = 0\n\n elif (event.LeftUp() or event.RightUp()) and self._isDragging:\n\n if self._dragImage:\n self._dragImage.EndDrag()\n\n if self._dropTarget:\n self._dropTarget.SetHilight(False)\n\n if self._oldSelection:\n\n self._oldSelection.SetHilight(True)\n self.RefreshLine(self._oldSelection)\n self._oldSelection = None\n\n # generate the drag end event\n event = TreeEvent(wxEVT_TREE_END_DRAG, self.GetId())\n event._item = item\n event._pointDrag = self.CalcScrolledPosition(pt)\n event.SetEventObject(self)\n\n self.GetEventHandler().ProcessEvent(event)\n\n self._isDragging = False\n self._dropTarget = None\n\n self.SetCursor(self._oldCursor)\n\n if wx.Platform in [\"__WXMSW__\", \"__WXMAC__\"]:\n self.Refresh()\n else:\n # Probably this is not enough on GTK. Try a Refresh() if it does not work.\n wx.YieldIfNeeded()\n\n else:\n\n # If we got to this point, we are not dragging or moving the mouse.\n # Because the code in carbon/toplevel.cpp will only set focus to the tree\n # if we skip for EVT_LEFT_DOWN, we MUST skip this event here for focus to work.\n # We skip even if we didn't hit an item because we still should\n # restore focus to the tree control even if we didn't exactly hit an item.\n if event.LeftDown():\n self._hasFocus = True\n self.SetFocusIgnoringChildren()\n event.Skip()\n\n # here we process only the messages which happen on tree items\n\n self._dragCount = 0\n\n if item == None:\n if self._textCtrl != None and item != self._textCtrl.item():\n self._textCtrl.StopEditing()\n return # we hit the blank area\n\n if event.RightDown():\n\n if self._textCtrl != None and item != self._textCtrl.item():\n self._textCtrl.StopEditing()\n\n self._hasFocus = True\n self.SetFocusIgnoringChildren()\n\n # If the item is already selected, do not update the selection.\n # Multi-selections should not be cleared if a selected item is clicked.\n if not self.IsSelected(item):\n\n self.DoSelectItem(item, True, False)\n\n nevent = TreeEvent(wxEVT_TREE_ITEM_RIGHT_CLICK, self.GetId())\n nevent._item = item\n nevent._pointDrag = self.CalcScrolledPosition(pt)\n nevent.SetEventObject(self)\n event.Skip(not self.GetEventHandler().ProcessEvent(nevent))\n\n # Consistent with MSW (for now), send the ITEM_MENU *after*\n # the RIGHT_CLICK event. TODO: This behaviour may change.\n nevent2 = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())\n nevent2._item = item\n nevent2._pointDrag = self.CalcScrolledPosition(pt)\n nevent2.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(nevent2)\n\n elif event.LeftUp():\n\n # this facilitates multiple-item drag-and-drop\n\n if self.HasAGWFlag(TR_MULTIPLE):\n\n selections = self.GetSelections()\n\n if len(selections) > 1 and not event.CmdDown() and not event.ShiftDown():\n\n self.DoSelectItem(item, True, False)\n\n if self._lastOnSame:\n\n if item == self._current and (flags & TREE_HITTEST_ONITEMLABEL) and self.HasAGWFlag(TR_EDIT_LABELS):\n\n if self._renameTimer:\n\n if self._renameTimer.IsRunning():\n\n self._renameTimer.Stop()\n\n else:\n\n self._renameTimer = TreeRenameTimer(self)\n\n self._renameTimer.Start(_DELAY, True)\n\n self._lastOnSame = False\n\n\n else: # !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()\n\n if not item or not item.IsEnabled():\n if self._textCtrl != None and item != self._textCtrl.item():\n self._textCtrl.StopEditing()\n return\n\n if self._textCtrl != None and item != self._textCtrl.item():\n self._textCtrl.StopEditing()\n\n self._hasFocus = True\n self.SetFocusIgnoringChildren()\n\n if event.LeftDown():\n\n self._lastOnSame = item == self._current\n\n if flags & TREE_HITTEST_ONITEMBUTTON:\n\n # only toggle the item for a single click, double click on\n # the button doesn't do anything (it toggles the item twice)\n if event.LeftDown():\n\n self.Toggle(item)\n\n # don't select the item if the button was clicked\n return\n\n if item.GetType() > 0 and (flags & TREE_HITTEST_ONITEMCHECKICON):\n\n if event.LeftDown():\n if flags & TREE_HITTEST_ONITEM and self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):\n self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE))\n\n if self.IsItem3State(item):\n checked = self.GetItem3StateValue(item)\n checked = (checked+1)%3\n else:\n checked = not self.IsItemChecked(item)\n\n self.CheckItem(item, checked)\n\n return\n\n # clear the previously selected items, if the\n # user clicked outside of the present selection.\n # otherwise, perform the deselection on mouse-up.\n # this allows multiple drag and drop to work.\n # but if Cmd is down, toggle selection of the clicked item\n if not self.IsSelected(item) or event.CmdDown():\n\n if flags & TREE_HITTEST_ONITEM:\n # how should the selection work for this event?\n if item.IsHyperText():\n self.SetItemVisited(item, True)\n\n is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),\n event.ShiftDown(),\n event.CmdDown())\n\n self.DoSelectItem(item, unselect_others, extended_select)\n\n # Handle hyperlink items... which are a bit odd sometimes\n elif self.IsSelected(item) and item.IsHyperText():\n self.HandleHyperLink(item)\n\n # For some reason, Windows isn't recognizing a left double-click,\n # so we need to simulate it here. Allow 200 milliseconds for now.\n if event.LeftDClick():\n\n # double clicking should not start editing the item label\n if self._renameTimer:\n self._renameTimer.Stop()\n\n self._lastOnSame = False\n\n # send activate event first\n nevent = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())\n nevent._item = item\n nevent._pointDrag = self.CalcScrolledPosition(pt)\n nevent.SetEventObject(self)\n if not self.GetEventHandler().ProcessEvent(nevent):\n\n # if the user code didn't process the activate event,\n # handle it ourselves by toggling the item when it is\n # double clicked\n## if item.HasPlus():\n self.Toggle(item)\n\n\n def OnInternalIdle(self):\n \"\"\"\n This method is normally only used internally, but sometimes an application\n may need it to implement functionality that should not be disabled by an\n application defining an `OnIdle` handler in a derived class.\n\n This method may be used to do delayed painting, for example, and most\n implementations call `wx.Window.UpdateWindowUI` in order to send update events\n to the window in idle time.\n \"\"\"\n\n # Check if we need to select the root item\n # because nothing else has been selected.\n # Delaying it means that we can invoke event handlers\n # as required, when a first item is selected.\n if not self.HasAGWFlag(TR_MULTIPLE) and not self.GetSelection():\n\n if self._select_me:\n self.SelectItem(self._select_me)\n elif self.GetRootItem():\n self.SelectItem(self.GetRootItem())\n\n # after all changes have been done to the tree control,\n # we actually redraw the tree when everything is over\n\n if not self._dirty:\n return\n if self._freezeCount:\n return\n\n self._dirty = False\n\n self.CalculatePositions()\n self.Refresh()\n self.AdjustMyScrollbars()\n\n# event.Skip()\n\n\n def CalculateSize(self, item, dc, level=-1, align=False):\n \"\"\"\n Calculates overall position and size of an item.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `dc`: an instance of `wx.DC`;\n :param `level`: the item level in the tree hierarchy;\n :param `align`: ``True`` if we want to align windows (in items with windows)\n at the same horizontal position.\n \"\"\"\n\n attr = item.GetAttributes()\n\n if attr and attr.HasFont():\n dc.SetFont(attr.GetFont())\n else:\n if item.IsBold():\n dc.SetFont(self._boldFont)\n elif item.IsItalic():\n dc.SetFont(self._italicFont)\n else:\n dc.SetFont(self._normalFont)\n\n text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())\n text_h+=2\n\n # restore normal font\n dc.SetFont(self._normalFont)\n\n image_w, image_h = 0, 0\n image = item.GetCurrentImage()\n\n if image != _NO_IMAGE:\n\n if self._imageListNormal:\n\n image_w, image_h = self._imageListNormal.GetSize(image)\n image_w += 4\n\n total_h = ((image_h > text_h) and [image_h] or [text_h])[0]\n\n checkimage = item.GetCurrentCheckedImage()\n if checkimage is not None:\n wcheck, hcheck = self._imageListCheck.GetSize(checkimage)\n wcheck += 4\n else:\n wcheck = 0\n\n if total_h < 30:\n total_h += 2 # at least 2 pixels\n else:\n total_h += total_h/10 # otherwise 10% extra spacing\n\n if total_h > self._lineHeight:\n self._lineHeight = total_h\n\n wnd = item.GetWindow()\n if not wnd:\n totalWidth = image_w+text_w+wcheck+2\n totalHeight = total_h\n else:\n totalWidth = item.GetWindowSize()[0]+image_w+text_w+wcheck+2\n totalHeight = max(total_h, item.GetWindowSize()[1])\n\n if level >= 0 and wnd:\n if not align:\n if level in self.absoluteWindows:\n self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)\n else:\n self.absoluteWindows[level] = image_w+text_w+wcheck+2\n else:\n self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)\n\n item.SetWidth(totalWidth)\n item.SetHeight(totalHeight)\n\n\n def CalculateLevel(self, item, dc, level, y, align=False):\n \"\"\"\n Calculates the level of an item inside the tree hierarchy.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `dc`: an instance of `wx.DC`;\n :param `level`: the item level in the tree hierarchy;\n :param `y`: the current vertical position inside the `wx.PyScrolledWindow`;\n :param `align`: ``True`` if we want to align windows (in items with windows)\n at the same horizontal position.\n \"\"\"\n\n x = level*self._indent\n\n if not self.HasAGWFlag(TR_HIDE_ROOT):\n\n x += self._indent\n\n elif level == 0:\n\n # a hidden root is not evaluated, but its\n # children are always calculated\n children = item.GetChildren()\n count = len(children)\n level = level + 1\n for n in xrange(count):\n y = self.CalculateLevel(children[n], dc, level, y, align) # recurse\n\n return y\n\n self.CalculateSize(item, dc, level, align)\n\n # set its position\n item.SetX(x+self._spacing)\n item.SetY(y)\n y += self.GetLineHeight(item)\n\n if not item.IsExpanded():\n # we don't need to calculate collapsed branches\n return y\n\n children = item.GetChildren()\n count = len(children)\n level = level + 1\n for n in xrange(count):\n y = self.CalculateLevel(children[n], dc, level, y, align) # recurse\n\n return y\n\n\n def CalculatePositions(self):\n \"\"\" Calculates all the positions of the visible items. \"\"\"\n\n if not self._anchor:\n return\n\n self.absoluteWindows = {}\n\n dc = wx.ClientDC(self)\n self.PrepareDC(dc)\n\n dc.SetFont(self._normalFont)\n dc.SetPen(self._dottedPen)\n y = 2\n y = self.CalculateLevel(self._anchor, dc, 0, y) # start recursion\n\n if self.HasAGWFlag(TR_ALIGN_WINDOWS):\n y = 2\n y = self.CalculateLevel(self._anchor, dc, 0, y, align=True) # start recursion\n\n\n def RefreshSubtree(self, item):\n \"\"\"\n Refreshes a damaged subtree of an item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self._dirty:\n return\n if self._freezeCount:\n return\n\n client = self.GetClientSize()\n\n rect = wx.Rect()\n x, rect.y = self.CalcScrolledPosition(0, item.GetY())\n rect.width = client.x\n rect.height = client.y\n\n self.Refresh(True, rect)\n self.AdjustMyScrollbars()\n\n\n def RefreshLine(self, item):\n \"\"\"\n Refreshes a damaged item line.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self._dirty:\n return\n if self._freezeCount:\n return\n\n rect = wx.Rect()\n x, rect.y = self.CalcScrolledPosition(0, item.GetY())\n rect.width = self.GetClientSize().x\n rect.height = self.GetLineHeight(item)\n\n self.Refresh(True, rect)\n\n\n def RefreshSelected(self):\n \"\"\" Refreshes a damaged selected item line. \"\"\"\n\n if self._freezeCount:\n return\n\n # TODO: this is awfully inefficient, we should keep the list of all\n # selected items internally, should be much faster\n if self._anchor:\n self.RefreshSelectedUnder(self._anchor)\n\n\n def RefreshSelectedUnder(self, item):\n \"\"\"\n Refreshes the selected items under the given item.\n\n :param `item`: an instance of L{GenericTreeItem}.\n \"\"\"\n\n if self._freezeCount:\n return\n\n if item.IsSelected():\n self.RefreshLine(item)\n\n children = item.GetChildren()\n for child in children:\n self.RefreshSelectedUnder(child)\n\n\n def Freeze(self):\n \"\"\"\n Freeze L{CustomTreeCtrl}.\n\n Freezes the window or, in other words, prevents any updates from taking place\n on screen, the window is not redrawn at all. L{Thaw} must be called to reenable\n window redrawing. Calls to these two functions may be nested.\n\n :note: This method is useful for visual appearance optimization (for example,\n it is a good idea to use it before doing many large text insertions in a row\n into a `wx.TextCtrl` under wxGTK) but is not implemented on all platforms nor\n for all controls so it is mostly just a hint to wxWidgets and not a mandatory\n directive.\n \"\"\"\n\n self._freezeCount = self._freezeCount + 1\n\n\n def Thaw(self):\n \"\"\"\n Thaw L{CustomTreeCtrl}.\n\n Reenables window updating after a previous call to L{Freeze}. To really thaw the\n control, it must be called exactly the same number of times as L{Freeze}.\n \"\"\"\n\n if self._freezeCount == 0:\n raise Exception(\"\\nERROR: Thawing Unfrozen Tree Control?\")\n\n self._freezeCount = self._freezeCount - 1\n\n if not self._freezeCount:\n self.Refresh()\n\n\n # ----------------------------------------------------------------------------\n # changing colours: we need to refresh the tree control\n # ----------------------------------------------------------------------------\n\n def SetBackgroundColour(self, colour):\n \"\"\"\n Changes the background colour of L{CustomTreeCtrl}.\n\n :param `colour`: the colour to be used as the background colour, pass\n `wx.NullColour` to reset to the default colour.\n\n :note: The background colour is usually painted by the default `wx.EraseEvent`\n event handler function under Windows and automatically under GTK.\n\n :note: Setting the background colour does not cause an immediate refresh, so\n you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after\n calling this function.\n\n :note: Overridden from `wx.PyScrolledWindow`.\n \"\"\"\n\n if not wx.PyScrolledWindow.SetBackgroundColour(self, colour):\n return False\n\n if self._freezeCount:\n return True\n\n self.Refresh()\n\n return True\n\n\n def SetForegroundColour(self, colour):\n \"\"\"\n Changes the foreground colour of L{CustomTreeCtrl}.\n\n :param `colour`: the colour to be used as the foreground colour, pass\n `wx.NullColour` to reset to the default colour.\n\n :note: Overridden from `wx.PyScrolledWindow`.\n \"\"\"\n\n if not wx.PyScrolledWindow.SetForegroundColour(self, colour):\n return False\n\n if self._freezeCount:\n return True\n\n self.Refresh()\n\n return True\n\n\n def OnGetToolTip(self, event):\n \"\"\"\n Process the tooltip event, to speed up event processing. Does not actually\n get a tooltip.\n\n :param `event`: a L{TreeEvent} event to be processed.\n \"\"\"\n\n event.Veto()\n\n\n def DoGetBestSize(self):\n \"\"\"\n Gets the size which best suits the window: for a control, it would be the\n minimal size which doesn't truncate the control, for a panel - the same size\n as it would have after a call to `Fit()`.\n \"\"\"\n\n # something is better than nothing...\n # 100x80 is what the MSW version will get from the default\n # wxControl::DoGetBestSize\n\n return wx.Size(100, 80)\n\n\n def GetMaxWidth(self, respect_expansion_state=True):\n \"\"\"\n Returns the maximum width of the L{CustomTreeCtrl}.\n\n :param `respect_expansion_state`: if ``True``, only the expanded items (and their\n children) will be measured. Otherwise all the items are expanded and\n their width measured.\n \"\"\"\n\n self.Freeze()\n\n root = self.GetRootItem()\n rect = self.GetBoundingRect(root, True)\n\n # It looks like the space between the \"+\" and the node\n # rect occupies 4 pixels approximately\n maxwidth = rect.x + rect.width + 4\n lastheight = rect.y + rect.height\n\n if not self.IsExpanded(root):\n if respect_expansion_state:\n return maxwidth\n\n if not respect_expansion_state:\n self.ExpandAll()\n\n maxwidth, lastheight = self.RecurseOnChildren(root, maxwidth, respect_expansion_state)\n\n self.Thaw()\n\n return maxwidth\n\n\n def RecurseOnChildren(self, item, maxwidth, respect_expansion_state):\n \"\"\"\n Recurses over all the children of the spcified items, calculating their\n maximum width.\n\n :param `item`: an instance of L{GenericTreeItem};\n :param `maxwidth`: the current maximum width for L{CustomTreeCtrl};\n :param `respect_expansion_state`: if ``True``, only the expanded items (and their\n children) will be measured. Otherwise all the items are expanded and\n their width measured.\n \"\"\"\n\n child, cookie = self.GetFirstChild(item)\n\n while child.IsOk():\n\n rect = self.GetBoundingRect(child, True)\n\n # It looks like the space between the \"+\" and the node\n # rect occupies 4 pixels approximately\n maxwidth = max(maxwidth, rect.x + rect.width + 4)\n lastheight = rect.y + rect.height\n\n if self.IsExpanded(child) or not respect_expansion_state:\n maxwidth, lastheight = self.RecurseOnChildren(child, maxwidth, respect_expansion_state)\n\n child, cookie = self.GetNextChild(item, cookie)\n\n return maxwidth, lastheight\n\n\n def GetClassDefaultAttributes(self):\n \"\"\"\n Returns the default font and colours which are used by the control. This is\n useful if you want to use the same font or colour in your own control as in\n a standard control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the users system,\n especially if it uses themes.\n\n This static method is \"overridden'' in many derived classes and so calling,\n for example, `wx.Button.GetClassDefaultAttributes()` will typically return the\n values appropriate for a button which will be normally different from those\n returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.\n\n :note: The `wx.VisualAttributes` structure has at least the fields `font`,\n `colFg` and `colBg`. All of them may be invalid if it was not possible to\n determine the default control appearance or, especially for the background\n colour, if the field doesn't make sense as is the case for `colBg` for the\n controls with themed background.\n\n :note: Overridden from `wx.PyControl`.\n \"\"\"\n\n attr = wx.VisualAttributes()\n attr.colFg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n attr.colBg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)\n attr.font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n return attr\n\n GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)\n\n\n","sub_path":"python_toolbox/wx_tools/widgets/third_party/customtreectrl.py","file_name":"customtreectrl.py","file_ext":"py","file_size_in_byte":253893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"413880115","text":"\"\"\"\nAn example implementation of the abstract Node class for use in MCTS\nIf you run this file then you can play against the computer.\nA tic-tac-toe board is represented as a tuple of 9 values, each either None,\nTrue, or False, respectively meaning 'empty', 'X', and 'O'.\nThe board is indexed by row:\n0 1 2\n3 4 5\n6 7 8\nFor example, this game board\nO - X\nO X -\nX - -\ncorrresponds to this tuple:\n(False, None, True, False, True, None, True, None, None)\n\"\"\"\n\nfrom collections import namedtuple\nfrom random import choice\nfrom monte_carlo_tree_search import MCTS, Node\nimport gym\n\n_TTTTB = namedtuple(\"FrozenLakeBoard\", \"env history terminal reward_\")\n\n\nclass FrozenLakeBoard(_TTTTB, Node):\n \"\"\"A FrozenLakeBoard which is similar to to TicTacToeBoard\n \"\"\"\n def find_children(board):\n if board.terminal: # If the game is finished then no moves can be made\n return set()\n # Otherwise, you can make a move in each of the empty spots\n return {\n board.make_move(a) for a in FrozenLakeEnv.actions\n }\n\n def find_random_child(board):\n if board.terminal:\n return None # If the game is finished then no moves can be made\n return board.make_move(choice(FrozenLakeEnv.actions))\n\n def reward(board):\n if not board.terminal or (board.reward is None):\n raise RuntimeError(f\"reward called on nonterminal board {board}\")\n return board.reward_\n\n def is_terminal(board):\n return board.terminal\n\n def make_move(board, index):\n # tup = board.tup[:index] + (board.turn,) + board.tup[index + 1 :]\n # turn = not board.turn\n # winner = _find_winner(tup)\n is_terminal, reward = board.env.make_move(index)\n new_history = board.history + str(index)\n env = FrozenLakeEnv(setting=board.env.setting, history=new_history) # new back env, it will move to that step\n return FrozenLakeBoard(env, new_history, is_terminal, reward)\n\n def to_pretty_string(board):\n board.env.render()\n return \"Finish render\"\n\nclass ModifiedFrozenLakeGymEnv(gym.Wrapper):\n \"\"\"Environment Wrapper\n\n Wrap the environment to do reward shaping, stop the env after x steps.\n\n \"\"\"\n def __init__(self, env):\n super().__init__(env)\n self.env = env\n self.t = 0.\n \n def step(self, action):\n next_state, reward, done, info = self.env.step(action)\n # modify ...\n s_type = self.env.desc.flatten()[next_state]\n self.t += 1.\n if s_type == b'F': reward = 0.\n elif s_type == b'H': reward = -0.01\n elif s_type == b'G': reward = max(1, (+10. - 0.1*self.t))\n if self.t > 100: done = True\n\n return next_state, reward, done, info\n\nclass FrozenLakeEnv:\n actions = [0, 1, 2, 3]\n\n def __init__(self, setting, history):\n self.setting = setting\n self.history = history\n \n self.env = ModifiedFrozenLakeGymEnv(gym.make(setting['name'], is_slippery=setting['is_slippery']))\n self.reset_to(history) # init with this {'name': 'FrozenLake-v0', 'is_slippery': False}\n return\n \n def reset_to(self, history):\n \"reset the agent to some position according to the history\"\n self.env.reset()\n for a in history:\n self.env.step(int(a))\n return\n \n def make_move(self, index):\n \"only return is_terminal and reward, without making real move\"\n new_env = self.copy()\n s, reward, is_terminal, info = new_env.env.step(index)\n # cp env and return is_terminal\n # if terminal return reward, else reward = None\n return is_terminal, reward if is_terminal else None\n \n def render(self):\n self.env.render()\n \n def copy(self):\n return FrozenLakeEnv(self.setting, self.history)\n\n\ndef play_game():\n tree = MCTS()\n # board = new_tic_tac_toe_board()\n board = new_frozen_lake_board()\n print(board.to_pretty_string())\n while True:\n for _ in range(500):\n tree.do_rollout(board)\n board = tree.choose(board)\n print(board.to_pretty_string())\n if board.terminal:\n break\n\ndef new_frozen_lake_board():\n setting = {'name': 'FrozenLake-v0', 'is_slippery': False}\n history = \"\"\n return FrozenLakeBoard(env=FrozenLakeEnv(setting, history), history=history, terminal=False, reward_=0.)\n\nif __name__ == \"__main__\":\n play_game()","sub_path":"frozenlake.py","file_name":"frozenlake.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"188893939","text":"\"\"\"\nhttps://leetcode.com/problems/sort-colors/submissions\n\nGiven an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n\nWe will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.\n\nYou must solve this problem without using the library's sort function.\n\nExample 1:\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\nExample 2:\nInput: nums = [2,0,1]\nOutput: [0,1,2]\n\nConstraints:\nn == nums.length\n1 <= n <= 300\nnums[i] is either 0, 1, or 2.\n\nFollow up: Could you come up with a one-pass algorithm using only constant extra space?\n\"\"\"\n\nfrom typing import List\n\ndef sort_colors(nums: List[int]) -> None:\n num_red = 0\n num_white = 0\n num_blue = 0\n \n for num in nums:\n if num == 0:\n num_red += 1\n elif num == 1:\n num_white += 1\n else:\n num_blue += 1\n \n for i in range(len(nums)):\n if num_red > 0:\n nums[i] = 0\n num_red -= 1\n elif num_white > 0:\n nums[i] = 1\n num_white -= 1\n else:\n nums[i] = 2","sub_path":"src/leetcode/medium/sort-colors/sort_colors.py","file_name":"sort_colors.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95618308","text":"import collections\nimport datetime\n\nfrom .analyze import get_request_ip\nfrom .drivers import postgres as driver_apg\nfrom .query import total_listens\nfrom .util import get_country\nfrom notifications.models import NotificationHook\nfrom pinecast.post_processing import run_after_request\n\n\nListenWrapper = collections.namedtuple('ListenWrapper', ['podcast', 'episode', 'apg'])\n\ndef get_listen_obj(ep, source, req=None, ip=None, ua=None, timestamp=None):\n if not ip:\n ip = get_request_ip(req)\n if not ua:\n ua = req.META.get('HTTP_USER_AGENT', 'Unknown') or 'Unknown'\n if not timestamp:\n timestamp = datetime.datetime.now()\n\n ep_id = str(ep.id)\n pod_id = str(ep.podcast.id)\n\n country = get_country(ip, req)\n\n return ListenWrapper(\n podcast=pod_id,\n episode=ep_id,\n apg=driver_apg.get_listen_obj(\n ep_id, pod_id, source, country, ip, ua, timestamp),\n )\n\n\nLISTEN_HOOKS = ['first_listen', 'listen_threshold', 'growth_milestone']\n\n@run_after_request\ndef commit_listens(listen_objs):\n if not listen_objs:\n return\n podcasts = set(x.podcast for x in listen_objs)\n hooks = list(NotificationHook.objects.filter(\n podcast_id__in=list(podcasts),\n trigger__in=LISTEN_HOOKS))\n podcasts_with_hooks = set(str(h.podcast_id) for h in hooks)\n episodes = set((x.podcast, x.episode) for x in listen_objs if x.podcast in podcasts_with_hooks)\n\n pod_listens_before = {p: total_listens(p) for p in podcasts_with_hooks}\n ep_listens_before = {e: (p, total_listens(p, e)) for p, e in episodes}\n\n driver_apg.write_listens([x for y in listen_objs for x in y.apg])\n\n if not podcasts_with_hooks:\n return\n\n notifications = {p: [n for n in hooks if str(n.podcast_id) == p] for p in podcasts_with_hooks}\n\n from podcasts.models import PodcastEpisode\n ep_cache = {}\n def get_ep(ep_id):\n if ep_id in ep_cache:\n return ep_cache.get(ep_id)\n else:\n ep = PodcastEpisode.objects.get(id=ep_id)\n ep_cache[ep_id] = ep\n return ep\n\n def notify_all(notifications, body={}):\n if not notifications:\n return\n for notification in notifications:\n notification.execute(body)\n\n # Handle first_listen notifications\n if any(hook.trigger == 'first_listen' for hook in hooks):\n for ep_id, (pod_id, count) in ep_listens_before.items():\n if count:\n continue\n matching_hooks = [h for h in notifications[pod_id] if h.trigger == 'first_listen']\n if not matching_hooks:\n continue\n notify_all(matching_hooks, {'episode': get_ep(ep_id)})\n\n # Handle listen_threshold\n if any(hook.trigger == 'listen_threshold' for hook in hooks):\n for ep_id, (pod_id, count) in ep_listens_before.items():\n matching_hooks = [h for h in notifications[pod_id] if h.trigger == 'listen_threshold']\n if not matching_hooks:\n continue\n episode = get_ep(ep_id)\n new_count = total_listens(pod_id, episode)\n notify_all(\n [h for h in matching_hooks if h.test_condition(count, new_count)],\n {'episode': episode, 'listens': new_count})\n\n # Handle growth_milestone\n if any(hook.trigger == 'growth_milestone' for hook in hooks):\n for pod_id, count in pod_listens_before.items():\n matching_hooks = [h for h in notifications[pod_id] if h.trigger == 'growth_milestone']\n if not matching_hooks:\n continue\n new_count = total_listens(pod_id)\n notify_all(\n [h for h in matching_hooks if h.test_condition(count, new_count)],\n {'listens': new_count, 'before_listens': count})\n\n\ndef write_subscription(req, podcast, is_private=False):\n ip = get_request_ip(req)\n ua = req.META.get('HTTP_USER_AGENT', '-') or '-'\n\n if isinstance(podcast, str):\n pod_id = podcast\n else:\n pod_id = str(podcast.id)\n\n country = get_country(ip, req)\n\n driver_apg.write_subscription(\n country, ip, ua, pod_id, is_private)\n","sub_path":"analytics/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"524036015","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport json\nimport logging\nimport os\nimport re\nimport sys\n\n\n\"\"\" \n@author:yueyao \n@file: Transcript_Assembly.py \n@time: 2018/08/07\n\"\"\"\n\n\nclass common(object):\n\n def __init__(self):\n self.fqList = []\n self.fqLink = {}\n self.fqList = []\n self.species={}\n self.fqLink = {\"GTpi\":[\"GTpi\",\"GTpi\",\"/ldfssz1/ST_BIGDATA/PMO/WORKFLOW/subworkflow_test_raw_data/rnaseq_tests/GTpi_1.fq.gz\",\"/ldfssz1/ST_BIGDATA/PMO/WORKFLOW/subworkflow_test_raw_data/rnaseq_tests/GTpi_2.fq.gz\",\"GTye\"]}\n self.outdirMain = os.path.abspath('.')\n self.ref = \"/ldfssz1/ST_BIGDATA/USER/yueyao/17.Train/database/GT.genome.fa\"\n self.PEorSE = \"PE\"\n\n def makepair(self, inputfq):\n pairArray = []\n pair = {}\n order = {}\n p = 0\n for fq in inputfq:\n fqbase = os.path.basename(fq) ## NA12878-L3_1.fq\n aa = re.search(r'_\\d\\.fq',fqbase)\n if aa:\n prefix = fqbase[0:aa.start()] ## NA12878-L3\n readtype = int(fqbase[aa.start()+1]) ## 1\n try:\n pair[prefix][readtype] = fq\n except:\n pair[prefix] = {readtype:fq}\n if prefix in order:\n pass\n else:\n order[prefix] = p\n p += 1\n for pp in sorted(order.items(),key=lambda x : x[1]):\n pairArray.append(pair[pp[0]])\n return pairArray\n\n def prepare_lib(self):\n rawdict = {}\n for i,j in self.fqLink.items():\n rawdict[j[1]] = [j[2], j[3]]\n return rawdict\n\nclass buildindex(common):\n def __init__(self):\n super(buildindex, self).__init__()\n self.parameter = \"-p 8\"\n self.hisat2=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNA_SoftWare/hisat2-2.0.4/\"\n self.program=self.hisat2+\"/hisat2\"\n\n self.outdir = \"Transcript_Assembly/Index_Hisat2\"\n\n def makeCommand(self, inputfq):\n\n os.makedirs(self.outdir, mode=0o755, exist_ok=True)\n\n cmd=[]\n output=[]\n buildindexshell=\"{hisat2} {ref} {outdir}/genomeindex {parameter};\".format(\n hisat2=self.program,\n ref=self.ref,\n outdir=self.outdir,\n parameter=self.parameter\n )\n output.append(self.outdir+\"/genomeindex.1.ht2\")\n cmd.append(buildindexshell)\n\n return cmd,output\n\n def makedefault(self, inputfq):\n input=self.ref\n output=self.outdir+\"/genomeindex.1.ht2\"\n\n default={\n 'input':input,\n 'parameter':self.parameter,\n 'program':self.program,\n 'resource':\"1G,1CPU\",\n 'output':output\n }\n return default\n\nclass filter(common):\n\n def __init__(self):\n super(filter, self).__init__()\n self.parameter = \"-l 15 -q 0.2 -n 0.05 -i -Q 1 -5 0\" \\\n \"-f AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC -r AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTA \"\n self.soapnuke = \"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/SOAPnuke\"\n self.fqcheck = \"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/fqcheck\"\n self.scriptbin = \"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/Filter/\"\n self.program=[self.soapnuke,self.fqcheck]\n self.outdir = \"Transcript_Assembly/Filter_SOAPnuke\"\n\n def makeCommand(self, inputfq):\n SampleList= self.prepare_lib()\n CleanDict={}\n os.makedirs(self.outdir, mode=0o755, exist_ok=True)\n\n cmd=[]\n output=[]\n filterShell=\"\"\n filterstatshell=\"\"\n if self.PEorSE == \"PE\":\n for SampleID,SampleFqList in SampleList.items():\n FqA=SampleFqList[0]\n FqB=SampleFqList[1]\n cleanFqA=SampleID+'.clean.1.fq.gz'\n cleanFqB=SampleID+'.clean.2.fq.gz'\n rawFqA=SampleID+'.rawdata.1.fq.gz'\n rawFqB=SampleID+'.rawdata.2.fq.gz'\n filterShell += \"{soapnuke} filter {soapnuke_para} -1 {fq1} -2 {fq2} -o {outDir} -C {clean1} -D {clean2} \" \\\n \"-R {rawdata1} -W {rawdata2}\\n\".format(\n soapnuke=self.soapnuke,\n soapnuke_para=self.parameter,\n fq1=FqA,\n fq2=FqB,\n outDir=self.outdir+'/'+SampleID+'/',\n clean1=cleanFqA,\n clean2=cleanFqB,\n rawdata1=rawFqA,\n rawdata2=rawFqB\n )\n filterstatshell += \"cd {outdir};\" \\\n \"{fqcheck} -r {outdir}/{clean1} -c {sampleid}_1.fqcheck;\" \\\n \"{fqcheck} -r {outdir}/{clean2} -c {sampleid}_2.fqcheck;\" \\\n \"{fqcheck} -r {outdir}/{rawdata1} -c {sampleid}_1.rawdata.fqcheck;\" \\\n \"{fqcheck} -r {outdir}/{rawdata2} -c {sampleid}_2.rawdata.fqcheck;\" \\\n \"perl {scriptbin}/fqcheck_distribute.pl {sampleid}_1.fqcheck {sampleid}_2.fqcheck -o {sampleid}.;\" \\\n \"perl {scriptbin}/soapnuke_stat.pl {outdir} >{sampleid}.filter.stat.xls;\" \\\n \"perl {scriptbin}/drawPizza.pl -infile {outdir}/{sampleid}.filter.stat.xls -outdir {outdir}\\n\".format(\n outdir=self.outdir + '/' + SampleID + '/',\n fqcheck=self.fqcheck,\n clean1=cleanFqA,\n clean2=cleanFqB,\n rawdata1=rawFqA,\n rawdata2=rawFqB,\n scriptbin=self.scriptbin,\n sampleid=SampleID\n )\n clean_fq1Path = \"{outDir}/{clean1}\".format(outDir=self.outdir+'/'+SampleID, clean1=cleanFqA)\n clean_fq2Path = \"{outDir}/{clean2}\".format(outDir=self.outdir+'/'+SampleID, clean2=cleanFqB)\n CleanDict[SampleID] = {\"clean_fq1\": clean_fq1Path, \"clean_fq2\": clean_fq2Path}\n os.makedirs(self.outdir+'/'+SampleID+'/', mode=0o755, exist_ok=True)\n statshell=\"perl {scriptbin}/filter_stat.pl -indir {outdir} -output {outdir}/FilterSummary.xls\".format(scriptbin=self.scriptbin,outdir=self.outdir)\n cmd.append(filterShell)\n cmd.append(filterstatshell)\n cmd.append(statshell)\n output.append(CleanDict)\n elif self.PEorSE == \"SE\":\n for SampleID, SampleFqList in SampleList.items():\n Fq=SampleFqList[0]\n cleanFq=SampleID+'.clean.fq.gz'\n rawFq=SampleID+'.rawdata.fq.gz'\n filterShell += \"{soapnuke} filter {soapnuke_para} -1 {fq1} -o {outDir} -C {clean1} -R {rawdata1}\\n\".format(\n soapnuke=self.soapnuke,\n soapnuke_para=self.parameter,\n fq1=Fq,\n outDir=self.outdir+'/'+SampleID+'/',\n clean1=cleanFq,\n rawdata1=rawFq\n )\n clean_fqPath = \"{outDir}/{clean1}\".format(outDir=self.outdir+'/'+SampleID, clean1=cleanFq)\n os.makedirs(clean_fqPath, mode=0o755, exist_ok=True)\n CleanDict[SampleID] = {\"clean_fq\": clean_fqPath}\n cmd.append(filterShell)\n output.append(CleanDict)\n else:\n logging.warning(\"Your Library Fastq File maybe some ERROR!\")\n sys.exit(1)\n\n return cmd,output\n\n def makedefault(self, inputfq):\n SampleList= self.prepare_lib()\n CleanDict={}\n\n output=[]\n if self.PEorSE == \"PE\":\n for SampleID,SampleFqList in SampleList.items():\n cleanFqA=SampleID+'.clean.1.fq.gz'\n cleanFqB=SampleID+'.clean.2.fq.gz'\n clean_fq1Path = \"{outDir}/{clean1}\".format(outDir=self.outdir+'/'+SampleID, clean1=cleanFqA)\n clean_fq2Path = \"{outDir}/{clean2}\".format(outDir=self.outdir+'/'+SampleID, clean2=cleanFqB)\n CleanDict[SampleID] = {\"clean_fq1\": clean_fq1Path, \"clean_fq2\": clean_fq2Path}\n output.append(CleanDict)\n elif self.PEorSE == \"SE\":\n for SampleID, SampleFqList in SampleList.items():\n cleanFq=SampleID+'.clean.fq.gz'\n clean_fqPath = \"{outDir}/{clean1}\".format(outDir=self.outdir+'/'+SampleID, clean1=cleanFq)\n CleanDict[SampleID] = {\"clean_fq\": clean_fqPath}\n output.append(CleanDict)\n else:\n logging.warning(\"Your Library Fastq File maybe some ERROR!\")\n sys.exit(1)\n\n default={\n 'input':inputfq,\n 'parameter':self.parameter,\n 'program':self.program,\n 'resource':\"1G,1CPU\",\n 'output':output\n }\n return default\n\nclass alignment(common):\n\n def __init__(self):\n super(alignment, self).__init__()\n\n self.parameter=\"--phred64 --no-discordant --no-mixed -I 1 -X 1000 -p 8 \"\n\n self.samtools=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/samtools\"\n self.hisat2=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/hisat2-2.0.4\"\n self.java=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/java\"\n self.picard=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/picard\"\n self.program=[self.samtools,self.hisat2,self.java,self.picard]\n\n self.outdir = \"Transcript_Assembly/GenomeMapping_HISAT/\"\n\n def makeCommand(self, inputfq):\n filter_para = filter()\n filter_para.species=self.species\n filter_para.fqLink = self.fqLink\n filter_para.outdir=self.outdir.replace(\"GenomeMapping_HISAT\",\"Filter_SOAPnuke\")\n buildindex_o=buildindex()\n buildindex_o.species=self.species\n buildindex_o.outdir=self.outdir.replace(\"GenomeMapping_HISAT\",\"Index_Hisat2\")\n ref_index=buildindex_o.outdir+\"/genomeindex\"\n CleanDataDict=inputfq[0]\n\n cmd=[]\n output=[]\n BamDict = {}\n os.makedirs(self.outdir, mode=0o755, exist_ok=True)\n hisat2shell=\"\"\n\n if self.PEorSE == \"PE\":\n for SampleID,Cleandata in CleanDataDict.items():\n sampledir=self.outdir+\"/\"+SampleID\n os.makedirs(sampledir, mode=0o755, exist_ok=True)\n os.makedirs(sampledir+\"/java_tmp\", mode=0o755, exist_ok=True)\n cleanFqA=Cleandata[\"clean_fq1\"]\n cleanFqB=Cleandata[\"clean_fq2\"]\n hisat2shell+=\"cd {sampledir}; {hisat2}/hisat2 {hisat2_para} -x {ref} -1 {fq1} -2 {fq2} \" \\\n \"2>{outdir}/{sampleid}.Map2GenomeStat.xls | \" \\\n \"{samtools} view -b -S -o {sampledir}/{sampleid}.bam - ;\" \\\n \"{java} -Xmx4G -Djava.io.tmpdir=java_tmp -jar {picard}/SortSam.jar \" \\\n \"I={sampleid}.bam O={sampleid}.Sort.bam SO=coordinate VALIDATION_STRINGENCY=SILENT\\n\".format(\n sampledir=sampledir,\n hisat2=self.hisat2,\n java=self.java,\n picard=self.picard,\n ref=ref_index,\n hisat2_para=self.parameter,\n fq1=cleanFqA,fq2=cleanFqB,samtools=self.samtools,\n outdir=self.outdir,sampleid=SampleID\n )\n\n BamPath=\"{outDir}/{sampleid}.Sort.bam\" \\\n \"\".format(outDir=sampledir,sampleid=SampleID)\n BamDict[SampleID]=BamPath\n cmd.append(hisat2shell)\n output.append(BamDict)\n elif self.PEorSE == \"SE\":\n for SampleID, Cleandata in CleanDataDict.items():\n sampledir = self.outdir + \"/\" + SampleID\n os.makedirs(sampledir, mode=0o755, exist_ok=True)\n os.makedirs(sampledir + \"/java_tmp\", mode=0o755, exist_ok=True)\n cleanFq = Cleandata[\"clean_fq\"]\n hisat2shell += \"cd {sampledir}; {hisat2}/hisat2 {hisat2_para} -x {ref} -1 {fq1} \" \\\n \"2>{outdir}/{sampleid}.Map2GenomeStat.xls | \" \\\n \"{samtools} view -b -S -o {sampledir}/{sampleid}.bam - \" \\\n \"{java} -Xmx4G -Djava.io.tmpdir=java_tmp -jar {picard}/SortSam.jar \" \\\n \"I={sampleid}.bam O={sampleid}.Sort.bam SO=coordinate VALIDATION_STRINGENCY=SILENT\\n\".format(\n sampledir=sampledir,\n picard=self.picard,\n java=self.java,\n hisat2=self.hisat2,\n ref=ref_index,\n hisat2_para=self.parameter,\n fq1=cleanFq, samtools=self.samtools,\n outdir=self.outdir, sampleid=SampleID\n )\n\n BamPath = \"{outDir}/{sampleid}.Sort.bam\" \\\n \"\".format(outDir=sampledir, sampleid=SampleID)\n BamDict[SampleID] = BamPath\n cmd.append(hisat2shell)\n output.append(BamDict)\n else:\n logging.warning(\"Your Library Fastq File maybe some ERROR!\")\n sys.exit(1)\n\n return cmd, output\n\n def makedefault(self, inputfq):\n filter_para = filter()\n filter_para.species=self.species\n filter_para.fqLink=self.fqLink\n filter_para.outdir=self.outdir.replace(\"GenomeMapping_HISAT\",\"Filter_SOAPnuke\")\n filter_output = filter_para.makedefault(inputfq)[\"output\"]\n CleanDataDict=filter_output[0]\n\n input=[]\n output=[]\n BamDict={}\n\n input.append(CleanDataDict)\n\n if self.PEorSE == \"PE\":\n for SampleID,Cleandata in CleanDataDict.items():\n sampledir=self.outdir+\"/\"+SampleID\n BamPath=\"{outDir}/{sampleid}.Sort.bam\" \\\n \"\".format(outDir=sampledir,sampleid=SampleID)\n BamDict[SampleID]=BamPath\n output.append(BamDict)\n elif self.PEorSE == \"SE\":\n for SampleID, Cleandata in CleanDataDict.items():\n sampledir = self.outdir + \"/\" + SampleID\n BamPath = \"{outDir}/{sampleid}.Sort.bam\" \\\n \"\".format(outDir=sampledir, sampleid=SampleID)\n BamDict[SampleID] = BamPath\n output.append(BamDict)\n else:\n logging.warning(\"Your Library Fastq File maybe some ERROR!\")\n sys.exit(1)\n\n default={\n 'input':input,\n 'parameter':self.parameter,\n 'program':self.program,\n 'resource':\"4G,8CPU\",\n 'output':output\n }\n return default\n\nclass novel_tr(common):\n\n def __init__(self):\n super(novel_tr,self).__init__()\n self.outdir = \"Transcript_Assembly/NovelTr_Stringtie\"\n\n self.parameter = \"-f 0.3 -j 3 -c 5 -g 100 -p 8\"\n\n self.stringtie=\"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/software/stringtie\"\n\n self.scriptbin = \"/ldfssz1/ST_BIGDATA/PMO/SOFTWARE/RNAref/NovelTr\"\n\n self.program = [self.stringtie]\n\n def makeCommand(self,inputfq):\n\n alignment_o = alignment()\n alignment_o.fqLink = self.fqLink\n alignment_o.species=self.species\n BamDict=inputfq\n\n os.makedirs(self.outdir, mode=0o755, exist_ok=True)\n os.makedirs(self.outdir+\"/Prediction/\", mode=0o755, exist_ok=True)\n os.makedirs(self.outdir+\"/Prediction/merge/\", mode=0o755, exist_ok=True)\n\n cmd=[]\n output=[]\n reconstruct_shell = \"\"\n\n gtflist = open(self.outdir+\"/Prediction/\"+\"gtf.list\",'w')\n for SampleID,BamPath in BamDict.items():\n reconstruct_shell += \"{stringtie} {bam_path} -o {outdir}/{sampleid}.stringtie.gtf.tmp {parameter};\" \\\n \"perl {scriptbin}/CorrectGTF.pl {ref} {outdir}/{sampleid}.stringtie.gtf.tmp {outdir}/{sampleid}.stringtie.gtf\\n\" \\\n \"\".format(\n stringtie=self.stringtie,\n parameter=self.parameter,\n bam_path=BamPath,\n outdir=self.outdir+\"/Prediction/\",\n sampleid=SampleID,\n scriptbin=self.scriptbin,\n ref=self.ref\n )\n gtflist.write(self.outdir+\"/Prediction/\"+SampleID+\".stringtie.gtf\"+\"\\n\")\n gtflist.close()\n\n cuffmerge_cpc_shell=\"{stringtie} --merge -o {outdir}/Prediction/merge/merged.gtf -p 8 {gtf_list}\".format(\n stringtie=self.stringtie,\n scriptbin=self.scriptbin,\n outdir=self.outdir,\n gtf_list=self.outdir+\"/Prediction/\"+\"gtf.list\",\n ref=self.ref,\n )\n\n os.makedirs(self.outdir + \"/Prediction/merge/\", mode=0o755, exist_ok=True)\n\n\n cmd.append(reconstruct_shell)\n cmd.append(cuffmerge_cpc_shell)\n\n output.append(self.outdir+\"/Prediction/merge/merged.gtf\")\n\n return cmd,output\n\n def makedefault(self,inputfq):\n\n alignment_o = alignment()\n alignment_o.fqLink = self.fqLink\n alignment_o.species=self.species\n alignment_o.outdir=self.outdir.replace(\"NovelTr_Stringtie\",\"GenomeMapping_HISAT\")\n BamDict = alignment_o.makedefault(inputfq)[\"output\"][0]\n\n output=[]\n output.append(self.outdir+\"/Prediction/merge/merged.gtf\")\n\n\n default={\n 'input':BamDict,\n 'parameter':self.parameter,\n 'program':self.program,\n 'resource':\"4G,8CPU\",\n 'output':output\n }\n return default\n\nclass interface(common):\n\n def __init__(self):\n common.__init__(self)\n self.step = [[\"filter\",\"buildindex\"],[\"alignment\"],[\"novel_tr\"]]\n self.input = \"%s/workflow.json\" % (self.outdirMain)\n self.output = \"%s/workflow.json\" % (self.outdirMain)\n\n def makeshell(self, outputfile=None):\n outputjson = self.output\n outdir = self.outdirMain\n os.makedirs(outdir+\"/shell\",exist_ok=True,mode=0o755)\n if outputfile is not None:\n outputjson = outputfile\n try:\n out = open(outputjson, mode='w')\n out.write(\"{\\n\")\n\n for stepL in self.step:\n for step in stepL:\n outshell = open(outdir+\"/shell/\"+step+\".sh\", mode='w')\n astep = eval(step)\n astepo = astep()\n astepo.fqLink = self.fqLink\n astepo.outdir = outdir +\"/\"+astepo.outdir\n default = astepo.makedefault(self.fqList)\n tmpcmd,tmpout = astepo.makeCommand(default['input'])\n for i in tmpcmd:\n outshell.write(i+\"\\n\")\n stepdict = json.dumps(astepo.makedefault(self.fqList))\n out.write(\"\\\"%s\\\":%s,\\n\" % (step, stepdict))\n outshell.close()\n os.system(\"sed -i \\'s/;/\\\\n/g\\' \"+ outdir+\"/shell/\" +step+\".sh\")\n out.write(\"\\\"outdir\\\":\\\"%s\\\"\\n\" % (self.outdirMain))\n out.write(\"}\\n\")\n out.close()\n\n\n except IOError as e:\n raise e\n\n def dumpjson(self, outputfile=None):\n outputjson = self.output\n if outputfile is not None:\n outputjson = outputfile\n try:\n out = open(outputjson, mode='w')\n out.write(\"{\\n\")\n for stepL in self.step:\n for step in stepL:\n astep = eval(step)\n astepo = astep()\n astepo.fqLink = self.fqLink\n stepdict = json.dumps(astepo.makedefault(self.fqList))\n out.write(\"\\\"%s\\\":%s,\\n\" % (step, stepdict))\n out.write(\"\\\"outdir\\\":\\\"%s\\\"\\n\" % (self.outdirMain))\n out.write(\"}\\n\")\n out.close()\n\n except IOError as e:\n raise e\n\n def loadjson(self, inputfile=None):\n inputjson = self.input\n if inputfile is not None:\n inputjson = inputfile\n try:\n infl = open(inputjson, mode='r')\n jsondict = json.load(infl)\n except ValueError as e:\n raise e\n return jsondict\n\nif __name__==\"__main__\":\n\n a = interface()\n a.makeshell()\n","sub_path":"Transcript_Assembly.py","file_name":"Transcript_Assembly.py","file_ext":"py","file_size_in_byte":20554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"197820749","text":"# vFabric Administration Server API\n# Copyright (c) 2012 VMware, 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom vas.shared.Instance import Instance\nfrom vas.shared.MutableCollection import MutableCollection\nfrom vas.util.LinkUtils import LinkUtils\n\nclass CacheServerInstances(MutableCollection):\n \"\"\"Used to enumerate, create, and delete cache server instances\n\n :ivar `vas.shared.Security.Security` security: The resource's security\n \"\"\"\n\n def __init__(self, client, location):\n super(CacheServerInstances, self).__init__(client, location, 'cache-server-group-instances',\n CacheServerInstance)\n\n def create(self, installation, name):\n \"\"\"Creates a new cache server instance\n\n :param `vas.gemfire.Installations.Installation` installation: The installation to be used by the instance\n :param str name: The name of the instance\n :rtype: :class:`vas.gemfire.CacheServerInstances.CacheServerInstance`\n :return: The new cache server instance\n \"\"\"\n\n payload = {'installation': installation._location, 'name': name}\n return self._create(payload, 'cache-server-group-instance')\n\n\nclass CacheServerInstance(Instance):\n \"\"\"A cache server instance\n\n :ivar `vas.gemfire.Groups.Group` group: The group that contains this instance\n :ivar `vas.gemfire.Installations.Installation` installation: The installation that this instance is using\n :ivar `vas.gemfire.LiveApplicationCodes.LiveApplicationCodes` live_application_code: The instance's live\n application code\n :ivar `vas.gemfire.CacheServerLiveConfigurations.CacheServerLiveConfigurations` live_configurations: The instance's live\n configurations\n :ivar str name: The instance's name\n :ivar list node_instances: The instance's individual node instances\n :ivar `vas.gemfire.PendingApplicationCodes.PendingApplicationCodes` pending_application_code: The instance's\n pending application\n code\n :ivar `vas.gemfire.CacheServerPendingConfigurations.CacheServerPendingConfigurations` pending_configurations: The instance's\n pending configurations\n :ivar `vas.shared.Security.Security` security: The resource's security\n :ivar str state: Retrieves the state of the resource from the server.\n Will be one of:\n\n * ``STARTING``\n * ``STARTED``\n * ``STOPPING``\n * ``STOPPED``\n \"\"\"\n\n __live_application_code = None\n __pending_application_code = None\n\n @property\n def live_application_code(self):\n self.__live_application_code = self.__live_application_code or LiveApplicationCodes(self._client,\n self.__live_application_code_location)\n return self.__live_application_code\n\n @property\n def pending_application_code(self):\n self.__pending_application_code = self.__pending_application_code or PendingApplicationCodes(self._client,\n self.__pending_application_code_location)\n return self.__pending_application_code\n\n def __init__(self, client, location):\n super(CacheServerInstance, self).__init__(client, location, Group, Installation, CacheServerLiveConfigurations,\n CacheServerPendingConfigurations, CacheServerNodeInstance, 'cache-server-node-instance')\n\n self.__live_application_code_location = LinkUtils.get_link_href(self._details, 'live-application-code')\n self.__pending_application_code_location = LinkUtils.get_link_href(self._details, 'pending-application-code')\n\n def update(self, installation):\n \"\"\"Updates the instance to use a different installation\n\n :param `vas.gemfire.Installations.Installation` installation: The installation that the instance should use\n \"\"\"\n\n self._client.post(self._location, {'installation': installation._location})\n self.reload()\n\n\nfrom vas.gemfire.CacheServerLiveConfigurations import CacheServerLiveConfigurations\nfrom vas.gemfire.CacheServerNodeInstances import CacheServerNodeInstance\nfrom vas.gemfire.CacheServerPendingConfigurations import CacheServerPendingConfigurations\nfrom vas.gemfire.Groups import Group\nfrom vas.gemfire.Installations import Installation\nfrom vas.gemfire.LiveApplicationCodes import LiveApplicationCodes\nfrom vas.gemfire.PendingApplicationCodes import PendingApplicationCodes\n","sub_path":"vas/gemfire/CacheServerInstances.py","file_name":"CacheServerInstances.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"45293014","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 2 12:12:19 2020\n\n@author: andya\n\"\"\"\n\n\ndef solution(A):\n \n count=0\n for i, j in enumerate(A):\n min_outer = i-j\n max_outer = i+j\n \n for k , l in enumerate(A[i+1:]):\n min_inner = k-l+i+1\n max_inner = k+l+i+1\n \n if min(min_inner, max_inner) > max(min_outer, max_outer) or max(min_inner, max_inner) < min(min_outer, max_outer):\n continue\n else: count+=1\n return count\n\n\nsolution([1,5,2,1,4,0])\n \n \n \n ","sub_path":"6_3_NumberOfDiscIntersections.py","file_name":"6_3_NumberOfDiscIntersections.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"49541122","text":"#!/opt/authbox/virtualenv/kafka-store/bin/nosetests\n\nimport hashlib\nimport snappy\nimport time\nfrom confluent_kafka import TopicPartition\nfrom googleapiclient.http import HttpError\nfrom nose.tools import (\n assert_equals,\n assert_greater,\n assert_raises,\n)\n\nfrom kafka_store.handler import PartitionLogger\n\n\nBUCKET = 'authbox-kafka-dev'\nMINUTE_IN_MS = 60 * 1000\n\ndef _md5_hex(data):\n m = hashlib.md5()\n m.update(data)\n return m.hexdigest()\n\ndef test_md5():\n p = PartitionLogger(\n topic='topic',\n partition=0,\n first_offset=0,\n first_timestamp_ms=int(time.time() * 1000)\n )\n\n assert_equals(p.get_age_ms(), 0)\n\n # Start at ten minutes ago\n start_ms = int(time.time() * 1000)\n initial_timestamp_ms = start_ms - 10 * MINUTE_IN_MS\n\n for offset in range(5):\n message = KafkaMessage(\n topic='topic',\n partition=0,\n offset=offset,\n raw=('<%d>' % offset).encode('ascii'),\n timestamp_ms=initial_timestamp_ms + offset * MINUTE_IN_MS,\n )\n p.log(message)\n assert_equals(p.get_age_ms(message), offset * MINUTE_IN_MS)\n\n # Asking for the age right now is zero (because of timeskew fix)\n assert_equals(p.get_age_ms(), 0)\n assert_equals(p.get_age_ms(KafkaMessage(\n timestamp_ms=start_ms,\n )), 10 * MINUTE_IN_MS)\n\n # Make sure the md5 is the expected md5 for the messages above\n assert_equals(p.output.md5_hex, '1330dac88f1337197531958029ab5f71')\n assert_equals(p.commit_group._get_commit(), [\n TopicPartition('topic', 0, 5),\n ])\n\n # Make sure we can upload; but upload fails if md5 is wrong.\n p.upload(BUCKET)\n p._md5.update(b'X')\n assert_raises(HttpError, p.upload, BUCKET)\n","sub_path":"tests/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"72262501","text":"import sys\nsys.stdin = open('input.txt','r')\n\n\nN = int(input())\nr = list(map(int,input().split()))\n\nuphills = [0]\na = 0\nwhile a < N-1:\n if r[a] < r[a+1]:\n start = r[a]\n # print('start:',start)\n for e in range(a+1,N):\n if e < N-1 and r[e] >= r[e+1]:\n end = r[e]\n # print('end:',end)\n uphills.append(end - start)\n a = e+1\n # print('a:',a)\n break\n elif e == N-1:\n end = r[e]\n # print('end',end)\n uphills.append(end - start)\n a = e+1\n else:\n a += 1\n\n# print(uphills)\nprint(max(uphills))\n","sub_path":"Problem/BaekJoon/2846.오르막길.py","file_name":"2846.오르막길.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"652172618","text":"from amadeus import Client, ResponseError\n\namadeus = Client(\n client_id='YhUHykQeccgseWSSARlxtfIAzhdGgTM2',\n client_secret='IWBwclckwNgBKNWr'\n)\n\ntry:\n response = amadeus.shopping.flight_offers_search.get(\n originLocationCode='SYD',\n destinationLocationCode='BKK',\n departureDate='2020-07-01',\n adults=1)\n print(response.data)\n print(type(response.data))\nexcept ResponseError as error:\n print(error)","sub_path":"test_functions/get_flight.py","file_name":"get_flight.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215950703","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport re\n\ndef determine_allxyz_file():\n allxyz_file = '.allxyz file'\n if len(sys.argv) == 2:\n allxyz_file = sys.argv[1]\n else:\n for file in os.listdir(os.getcwd()):\n if file.endswith('.ensemble.allxyz'):\n allxyz_file = file\n return allxyz_file\n\ndef main():\n try:\n allxyz_file = determine_allxyz_file()\n allxyz_file_name = allxyz_file.replace(\".allxyz\", \"\")\n input_file = open(allxyz_file,'r')\n print(\"Converting {}...\".format(allxyz_file))\n\n keywords = ('! OPT PAL4 PBEh-3c CPCM(Chloroform)\\n'\n '%base \"opt\"\\n'\n '%scf MaxIter 500 end\\n\\n'\n '*xyz 0 1\\n')\n\n conformer_number = 1\n output_file = open('{}_conf{}.inp'.format(allxyz_file_name, conformer_number), 'w')\n output_file.write(keywords)\n for line in input_file:\n if '>' in line:\n output_file.write(\"*\\n\")\n output_file.close()\n conformer_number = conformer_number + 1\n output_file = open('{}_conf{}.inp'.format(allxyz_file_name, conformer_number), 'w')\n output_file.write(keywords)\n else:\n number_atoms_line = re.match(r'\\s+\\d+', line)\n energies_line = re.match(r'\\s+-*\\d+.\\d+', line)\n if line.strip() and not number_atoms_line and not energies_line:\n output_file.write(line.rstrip(\"\\n\"))\n output_file.write(\"\\n\")\n output_file.write(\"*\\n\")\n output_file.close()\n input_file.close()\n\n except IOError or FileNotFoundError:\n print(\"{} not found\".format(allxyz_file))\n\nmain()","sub_path":"old_scripts/allxyz_to_inp.py","file_name":"allxyz_to_inp.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"342397071","text":"# Various carrier data update convenience functions.\n# AKA \"Get all the ugly shit out of the views.\"\nfrom datetime import datetime\n\nfrom . import capi\nfrom ..models import Carrier, User, Itinerary, Market, Module, Ship, Cargo\nimport pyramid.httpexceptions as exc\n\n\ndef update_carrier(request, cid, user):\n mycarrier = request.dbsession.query(Carrier).filter(Carrier.id == cid).one_or_none()\n owner = request.dbsession.query(User).filter(User.id == mycarrier.owner).one_or_none()\n if owner:\n jcarrier = capi.get_carrier(owner)\n if not jcarrier:\n print(\"CAPI update call failed, retry OAuth if owner.\")\n if mycarrier.owner == request.user.id:\n print(\"Same user, ask for OAuth refresh.\")\n url, state = capi.get_auth_url()\n return exc.HTTPFound(location=url)\n else:\n print(f\"Not same user! {mycarrier.owner} vs {request.user.id}.\")\n return None\n print(f\"New carrier: {jcarrier}\")\n services = jcarrier['market']['services']\n mycarrier.owner = owner.id\n mycarrier.callsign = jcarrier['name']['callsign']\n mycarrier.name = jcarrier['name']['vanityName']\n mycarrier.currentStarSystem = jcarrier['currentStarSystem']\n mycarrier.balance = jcarrier['balance']\n mycarrier.fuel = jcarrier['fuel']\n mycarrier.state = jcarrier['state']\n mycarrier.theme = jcarrier['theme']\n mycarrier.dockingAccess = jcarrier['dockingAccess']\n mycarrier.notoriousAccess = jcarrier['notoriousAccess']\n mycarrier.totalDistanceJumped = jcarrier['itinerary']['totalDistanceJumpedLY']\n mycarrier.currentJump = jcarrier['itinerary']['currentJump']\n mycarrier.taxation = jcarrier['finance']['taxation']\n mycarrier.coreCost = jcarrier['finance']['coreCost']\n mycarrier.servicesCost = jcarrier['finance']['servicesCost']\n mycarrier.jumpsCost = jcarrier['finance']['jumpsCost']\n mycarrier.numJumps = jcarrier['finance']['numJumps']\n mycarrier.hasCommodities = True\n mycarrier.hasCarrierFuel = True\n mycarrier.hasRearm = True if services['rearm'] == 'ok' else False\n mycarrier.hasShipyard = True if services['shipyard'] == 'ok' else False\n mycarrier.hasOutfitting = True if services['outfitting'] == 'ok' else False\n mycarrier.hasBlackMarket = True if services['blackmarket'] == 'ok' else False\n mycarrier.hasVoucherRedemption = True if services['voucherredemption'] == 'ok' else False\n mycarrier.hasExploration = True if services['exploration'] == 'ok' else False\n mycarrier.lastUpdated = datetime.now()\n request.dbsession.query(Itinerary).filter(Itinerary.carrier_id\n == mycarrier.id).delete()\n for item in jcarrier['itinerary']['completed']:\n print(f\"Adding {item['starsystem']}\")\n itm = Itinerary(carrier_id=mycarrier.id, starsystem=item['starsystem'],\n departureTime=item['departureTime'], arrivalTime=item['arrivalTime'],\n visitDurationSeconds=item['visitDurationSeconds'])\n request.dbsession.add(itm)\n request.dbsession.query(Cargo).filter(Cargo.carrier_id\n == mycarrier.id).delete()\n for item in jcarrier['cargo']:\n cg = Cargo(carrier_id=mycarrier.id, commodity=item['commodity'],\n quantity=item['qty'], stolen=item['stolen'], locName=item['locName'])\n request.dbsession.add(cg)\n request.dbsession.query(Market).filter(Market.carrier_id\n == mycarrier.id).delete()\n for item in jcarrier['market']['commodities']:\n mk = Market(carrier_id=mycarrier.id, commodity_id=item['id'],\n categoryname=item['categoryname'], name=item['name'],\n stock=item['stock'], buyPrice=item['buyPrice'],\n sellPrice=item['sellPrice'], demand=item['demand'],\n locName=item['locName'])\n request.dbsession.add(mk)\n request.dbsession.query(Ship).filter(Ship.carrier_id\n == mycarrier.id).delete()\n print(jcarrier['ships']['shipyard_list'])\n for item, it in jcarrier['ships']['shipyard_list'].items():\n print(item)\n print(it)\n sp = Ship(carrier_id=mycarrier.id, name=it['name'],\n ship_id=it['id'], basevalue=it['basevalue'],\n stock=it['stock'])\n request.dbsession.add(sp)\n request.dbsession.query(Module).filter(Module.carrier_id\n == mycarrier.id).delete()\n print(jcarrier['modules'])\n for item, it in jcarrier['modules'].items():\n md = Module(carrier_id=mycarrier.id, category=it['category'],\n name=it['name'], cost=it['cost'], stock=it['stock'],\n module_id=it['id'])\n request.dbsession.add(md)\n return jcarrier or None\n return None\n","sub_path":"FCMS/utils/carrier_data.py","file_name":"carrier_data.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"363960738","text":"#!/usr/bin/env python\nimport sys\nimport itertools\nfrom pyspark import SparkContext\nfrom pyspark.sql import HiveContext, Row\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.mllib.linalg import DenseVector\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.tree import DecisionTree\nfrom pyspark.mllib.evaluation import RegressionMetrics\nfrom sklearn.grid_search import ParameterGrid\n\n\n\nif __name__ == \"__main__\":\n\n conf = SparkConf().set(\"spark.executor.memory\", \"8g\").set(\"spark.yarn.executor.memoryOverhead\", \"2048\")\n sc = SparkContext(conf = conf)\n sqlContext = HiveContext(sc)\n\n # read file\n def read_hdfs_csv(sqlContext, filename, header='true'):\n csvreader = (sqlContext.read.format('com.databricks.spark.csv').options(header = header, inferschema='true'))\n return csvreader.load(filename)\n\n\n def write_hdfs_csv(df, filename):\n csvwriter = (df.write.format('com.databricks.spark.csv').options(header='true'))\n return csvwriter.save(filename)\n\n data = read_hdfs_csv(sqlContext, 'features_merge_unwrapped_sample.csv')\n #data = data.map(lambda df: Vectors.dense([float(c) for c in df]))\n\n def labelData(data):\n return data.map(lambda row: LabeledPoint(row[2], row[3:]))\n\n training, test = labelData(data).randomSplit([0.8, 0.2])\n numTraining = training.count()\n numTest = test.count()\n\n\n '''\n grid = [{'regParam': [0.01, 0.1], 'iterations': [10, 20], 'regType': [\"l1\", \"l2\"], 'convergenceTol': [1e-3, 1e-4]}]\n paramGrid = list(ParameterGrid(grid))\n numModels = len(paramGrid)\n\n f = open('model_evaluation', 'w')\n '''\n\n def getPredictionsLabels(model, test):\n predictions = model.predict(test.map(lambda r: r.features))\n return predictions.zip(test.map(lambda r: r.label))\n\n def printMetrics(predictions_and_labels):\n metrics = RegressionMetrics(predictions_and_labels)\n f.write('Explained Variance:{0}\\n'.format(metrics.explainedVariance))\n f.write('Mean Absolute Error:{0}\\n'.format(metrics.meanAbsoluteError))\n f.write('Mean Squared Error:{0}\\n'.format(metrics.meanSquaredError))\n f.write('Root Mean Squared Error:{0}\\n'.format(metrics.rootMeanSquaredError))\n f.write('R^2 :{0}\\n'.format(metrics.r2))\n\n for j in range(numModels):\n regp = paramGrid[j]['regParam']\n iters = paramGrid[j]['iterations']\n regt = paramGrid[j]['regType']\n con = paramGrid[j]['convergenceTol']\n\n #f.write('Model{0}: regParam = {1}, iterations = {2}, regType = {3}, convergenceTol = {4}\\n'.format(str(j), regp, iters, regt, con))\n # Train decision tree regression model with hypermarameter set\n model = DecisionTree.trainRegressor(training, categoricalFeaturesInfo = {}, impurity='variance', \\\n maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0)\n\n predictions_and_labels = getPredictionsLabels(model, test)\n printMetrics(predictions_and_labels)\n\n f.close()\n sc.stop()\n\n\n\n","sub_path":"model/DecisionTreeRegression.py","file_name":"DecisionTreeRegression.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"553598058","text":"import json\nimport os\nimport re\nimport subprocess\nfrom difflib import SequenceMatcher\n\n\ndir = os.path.abspath(__file__+'/../../'+'/Spring_2016/list_of_errors_ver3')\nsample = os.path.join(dir,'sample.json')\ncondir = dir+'/cons'\n\n#This is a program to check whether the position provided by complier\n#is the correct location\n\n\ndef save_file(prog,filename,directory):\n mlname = filename + '.ml'\n with open (os.path.join(directory, mlname), 'w') as out:\n \tout.write(prog)\n out.close()\n#I want to generate a .ml file, a .con file, and use sherrloc on he confile\n#and use regex to get to location\n\n\ndef generate(item, main, count):\n \n foldername = item['problem'] + '_' + str(count)\n dir = os.path.join(main,foldername)\n \n if not os.path.exists(dir):\n \tos.makedirs(dir)\n \n\n if(not item['fix']):\n return 'no_fix'\n #print(item['fix'])\n #run_prog(item['fix'][0],'fix', dir)\n \n num = 0\n\n for bads in item['bad']:\n \tfilename = 'bad' + str(num)\n \tget_pos(bads,filename, dir)\n \tnum = num + 1\n\n'''\nModified from:\nSimple Diff for Python version 1.0\n\nAnnotate two versions of a list with the values that have been\nchanged between the versions, similar to unix's `diff` but with\na dead-simple Python interface.\n\n(C) Paul Butler 2008-2012 \nMay be used and distributed under the zlib/libpng license\n\n\nAdd the function to differ at which index does the \nwords are different from each other.\n'''\n\n__all__ = ['diff', 'string_diff', 'html_diff']\n__version__ = '1.0'\n\n\ndef diff(old, new, opos, npos):\n\n '''\n Find the differences between two lists. Returns a list of pairs, where the\n first value is in ['+','-','='] and represents an insertion, deletion, or\n no change for that list. The second value of the pair is the list\n of elements.\n\n Params:\n old the old list of immutable, comparable values (ie. a list\n of strings)\n new the new list of immutable, comparable values\n \n Returns:\n A list of pairs, with the first part of the pair being one of three\n strings ('-', '+', '=') and the second part being a list of values from\n the original old and/or new lists. The first part of the pair\n corresponds to whether the list of values is a deletion, insertion, or\n unchanged, respectively.\n\n\n '''\n\n # Create a map from old values to their indices\n old_index_map = dict()\n for i, val in enumerate(old):\n old_index_map.setdefault(val,list()).append(i)\n \n # Find the largest substring common to old and new.\n # We use a dynamic programming approach here.\n # \n # We iterate over each value in the `new` list, calling the\n # index `inew`. At each iteration, `overlap[i]` is the\n # length of the largest suffix of `old[:i]` equal to a suffix\n # of `new[:inew]` (or unset when `old[i]` != `new[inew]`).\n #\n # At each stage of iteration, the new `overlap` (called\n # `_overlap` until the original `overlap` is no longer needed)\n # is built from the old one.\n #\n # If the length of overlap exceeds the largest substring\n # seen so far (`sub_length`), we update the largest substring\n # to the overlapping strings.\n\n overlap = dict()\n # `sub_start_old` is the 3index of the beginning of the largest overlapping\n # substring in the old list. `sub_start_new` is the index of the beginning\n # of the same substring in the new list. `sub_length` is the length that\n # overlaps in both.\n # These track the largest overlapping substring seen so far, so naturally\n # we start with a 0-length substring.\n sub_start_old = 0\n sub_start_new = 0\n sub_length = 0\n\n for inew, val in enumerate(new):\n _overlap = dict()\n\n\n for iold in old_index_map.get(val,list()):\n # now we are considering all values of iold such that\n # `old[iold] == new[inew]`.\n\n _overlap[iold] = (iold and overlap.get(iold - 1, 0)) + 1\n if(_overlap[iold] > sub_length):\n # this is the largest substring seen so far, so store its\n # indices\n sub_length = _overlap[iold]\n sub_start_old = iold - sub_length + 1\n sub_start_new = inew - sub_length + 1\n old_ind = iold\n new_ind = inew\n\n overlap = _overlap\n \n \n if sub_length == 0:\n # If no common substring is found, we return an insert and delete...\n\n #return (old and [('-', old, [opos+sub_start_old, opos+sub_start_old+len(old)-1])] or []) + (new and [('+', new, [opos+sub_start_old,opos+sub_start_old+len(new)-1] )] or [])\n return (old and [('-', old, [opos+sub_start_old, opos+sub_start_old+len(old)-1])] or []) + (new and [('+', new, [npos+sub_start_new,npos+sub_start_new+len(new)-1] )] or [])\n\n\n else:\n # ...otherwise, the common substring is unchanged and we recursively\n # diff the text before and after that substring\n \n return diff(old[ : sub_start_old], \n new[ : sub_start_new], opos, \n npos) + \\\n [('=', new[sub_start_new : sub_start_new + sub_length], \n [opos+ sub_start_old, opos+ sub_start_old+sub_length-1])] + \\\n diff(old[sub_start_old + sub_length : ],\n new[sub_start_new + sub_length : ],\n opos+ sub_start_old+sub_length,\n npos+sub_length+sub_start_new)\n\n\n\n\ndef string_diff(old, new):\n '''\n Returns the difference between the old and new strings when split on\n whitespace. Considers punctuation a part of the word\n\n This function is intended as an example; you'll probably want\n a more sophisticated wrapper in practice.\n\n Params:\n old the old string\n new the new string\n\n Returns:\n the output of `diff` on the two strings after splitting them\n on whitespace (a list of change instructions; see the docstring\n of `diff`)\n\n Examples:\n >>> string_diff('The quick brown fox', 'The fast blue fox')\n ... # doctest: +NORMALIZE_WHITESPACE\n [('=', ['The'], [0, 0]), \n ('-', ['quick', 'brown'], [1, 2]), \n ('+', ['fast', 'blue'], [1, 2]), \n ('=', ['fox'], [3, 3])]\n\n '''\n\n return diff(old.split(), new.split(),0,0)\n\n \n#This is a function that takes in an Ocaml object and return \n#its error position\ndef get_pos(prog, filename, directory):\n\t#generate the ml file\n save_file(prog, filename, directory)\n mlname = filename + '.ml'\n mlpath = os.path.join(directory, mlname)\n\n #generate the con file\n confile = subprocess.run([\"ecamlc\", mlname],stdout = subprocess.PIPE, cwd = directory)\n\n #get info from sherrloc\n \n shename = 'error.con'\n regex_num = \"[0-9]+\"\n regex_line =\"[[0-9]+,\"\n regex = \"\\[[0-9]+,.+?(?=])\"\n regex_start = \"(?<=,)[0-9]+\"\n regex_end = \"(?<=-)[0-9]+\"\n\n path = os.path.join(directory, shename)\n\n try:\n sherrloc = subprocess.run([\"sherrloc\",\"-e\",path],\n stdout = subprocess.PIPE, timeout = 60)\n except Exception as e:\n #timeout_ct+=1\n print(e)\n return[[-2,-2]]\n\n out = re.findall(regex,sherrloc.stdout.decode(\"utf-8\"))\n \n #print(sherrloc.stdout.decode(\"utf-8\"))\n #probable length error\n \n '''\n if(len(out)>1):\n print(prog)\n print(\"Length error\")\n print(out)\n '''\n \n start = []\n end = []\n \n \n lines = prog.splitlines()\n\n for index in range (0, len(out)):\n\n line = re.findall(regex_line, out[index])\n line = int(re.findall(regex_num ,line[0])[0])\n \n char = 0\n for i in range(0,line-1):\n char = char + len(lines[i]) + 1\n\n #print(char)\n start.append(char + int(re.findall(regex_start,out[index])[0]))\n end.append(char+int(re.findall(regex_end,out[index])[0]))\n \n \n '''\n print(start)\n print(end)\n '''\n\n out = []\n for indexs in range(0, len(start)):\n out.append([int(start[indexs]),int(end[indexs])])\n \n poses = []\n for chars in out:\n #print(chars)\n\n poses.append([len(str.split(prog[0:chars[0]]))-1, \n len(str.split(prog[0:chars[1]]))-1])\n return poses\n \ndef get_pos_ocaml(prog):\n \n to_run = prog.split(';;')\n to_con = \"\"\n #print(\"printing parts!\")\n count = 0\n #print(to_run)\n for part in to_run:\n #print(count)\n #print(part)\n to_con += ';;'\n to_con += part\n\n try:\n error_output = subprocess.run([\"ocaml\"], input = to_con+';;', \n stdout=subprocess.PIPE,universal_newlines = True,timeout = 60)\n \n except Exception as e:\n print(e)\n #timeout_ct +=1\n return [-2,-2]\n #print(error_output)\n if \"rror\" in error_output.stdout:\n m = re.findall('(?<=Characters )([1-9][0-9][0-9]|[1-9][0-9]|[0-9])', error_output.stdout) \n n = re.findall('(?<=-)([1-9][0-9][0-9]|[1-9][0-9]|[0-9])', error_output.stdout)\n #print(m)\n #print(n)\n break\n else:\n count+=len(part)+2\n continue\n \n\n try:\n if(m != [] and n != []):\n start = int(m[-1]) + count + 1\n end = int(n[-1]) + count + 1\n else:\n #print(\"all correct\")\n return [-1,-1]\n except UnboundLocalError:\n #print(\"no m and n\")\n return([-2,-2])\n\n start_pos = len(str.split(prog[0:start]))-1\n end_pos = len(str.split(prog[0:end]))-1\n \n #print(prog[start:end])\n return([start_pos,end_pos])\n\n\n#the function to expand the length of the token span\ndef expand(end, pos):\n #print('this is pos')\n #print (pos)\n if(pos[0]>0 and (pos[1] == end)):\n epos = [pos[0]-1, pos[1]]\n \n elif(pos[0]>0 and (pos[1] != end)):\n epos = [pos[0]-1, pos[1]+1]\n elif((pos[0] == 0) and (pos[1] == end)):\n epos = pos\n else:\n epos = [0, pos[1]+1]\n\n #print(\"this is epos:\")\n #print(epos)\n return epos\n\n#the function to get the corresponding place from old \n#string to the new one\ndef find_new_pos(bad, fix, pos):\n\n s = string_diff(bad, fix)\n \n new_pos_start = 0\n old_pos_start = 0\n for i in s:\n\n #when some words are added\n if(i[0] == '+'):\n\n new_pos_start = new_pos_start + (i[2][1] - i[2][0] + 1)\n if(old_pos_start >= pos[0]):\n new_pos_start = new_pos_start-(old_pos_start- pos[0])\n break\n\n #when this portion of words does not change\n if(i[0] == '='):\n new_pos_start = new_pos_start + (i[2][1] - i[2][0] + 1)\n old_pos_start = old_pos_start + (i[2][1] - i[2][0] + 1)\n\n if(old_pos_start >= pos[0]):\n new_pos_start = new_pos_start -1\n old_pos_start = old_pos_start -1\n new_pos_start = new_pos_start-(old_pos_start- pos[0])\n break\n\n #when some words are deleted\n if(i[0] == '-'):\n \n if((pos[0] <= i[2][0] and pos[1] >= i[2][0] ) or \n (pos[0] <= i[2][1] and pos[1] >= i[2][1]) or\n (pos[0] >= i[2][0] and pos[1] <= i[2][1])):\n return [-1,-1]\n\n old_pos_start = old_pos_start + (i[2][1] - i[2][0] + 1)\n if(old_pos_start >= pos[0]):\n new_pos_start = new_pos_start-(old_pos_start- pos[0])\n break\n\n return [new_pos_start, new_pos_start+pos[1] - pos[0]]\n\n#take in a bad program, a fixed program, and a position, check\n#whether the error happened in that position\n#EXAMPLES:\n#print(err_judge('quick red ', 'Hi hello world quick red', [0,0]))\n#--->1\n\n#print(err_judge('world quick red ', 'Hi hello world quick red', [1,1]))\n#--->0\n\n#print(err_judge('quick red ', 'Hi hello world quick red', [1,1]))\n#--->0 \n\n#print(err_judge(' quick red fox dog', 'Hi quick fox head paint red', [1,1])) \n#--->1\n\n#print(err_judge('a b c m d e', 'p m n c m d e q', [3,4]))\n#--->0\n\n#print(err_judge('quick red ', 'Hi hello world quck red', [0,0])) \n#--->0\n\n#print(err_judge('world quick red ', 'Hi hello world quick red', [1,1]))\n#--->0\n\ndef err_judge(bad, fix, pos):\n '''\n print(pos)\n for i in range (pos[0][0], pos[0][1]):\n print(bad[i], end=\"\")\n print(\"done\")\n '''\n\n #print(pos)\n end = len(bad.split())-1\n new_pos_start = 0\n pos_it = 0\n\n #the bad does not give any clue\n if(pos == [-2, -2]):\n print(\"no clueee ~~\")\n return 0;\n\n ex_poses = []\n new_poses = []\n ex_new_poses = []\n \n #print(pos)\n\t#get the key word to judge whether it is changed\n for pair in pos:\n ex_poses.append(expand(len(bad), pair))\n new_poses.append(find_new_pos(bad, fix, pair))\n\n for new_pos in new_poses:\n ex_new_poses.append(expand(len(bad),new_pos))\n \n #print(\"in err_judge\")\n #print(new_pos)\n #print(pos)\n #the word in the wanted position has been deleted\n\n for i in new_poses:\n if(i == [-1,-1]):\n #print('-1-1 correct')\n return 1\n\n #perform a string diff on bad and fix\n s= string_diff(bad,fix)\n \n for index in range (0, len(new_poses)):\n ex_pos = ex_poses[index]\n ex_new_pos = ex_new_poses[index]\n\n #check whether the position has been changed using diff\n #print(s)\n\n for i in s:\n \n\n\n if (i[0] == '=' and ex_pos[0] >= i[2][0] and ex_pos[1] <= i[2][1] and (ex_pos[1]-ex_new_pos[0] >=2)):\n #print (pos)\n #print(ex_new_poses)\n #print('incorrect location1')\n break\n\n if (i[0] == '-' and \n ((ex_pos[0] <= i[2][0] and ex_pos[1] >= i[2][0] ) or \n (ex_pos[0] <= i[2][1] and ex_pos[1] >= i[2][1]) or\n (ex_pos[0] >= i[2][0] and ex_pos[1] <= i[2][1]))):\n \n #print('correct location2')\n #print(i)\n return 1\n\n if(i[0] == '+' and\n ((ex_new_pos[0] <= i[2][0] and ex_new_pos[1] >= i[2][0] ) or \n (ex_new_pos[0] <= i[2][1] and ex_new_pos[1] >= i[2][1]) or\n (ex_new_pos[0] >= i[2][0] and ex_new_pos[1] <= i[2][1]))):\n \n #print('correct location3')\n #print(i)\n return 1\n\n #print('incorrect location4')\n return 0\n\n#if ocaml get the correct location, but sherrloc does not,\n#return 1\n\ndef comp(bad,fix):\n ocaml_pos = get_pos_ocaml(bad)\n sher_pos = get_pos(bad,\"bad\", condir)\n ocaml_pos = [ocaml_pos]\n \n ocaml_out = err_judge(bad,fix,ocaml_pos)\n sher_out = err_judge(bad,fix,sher_pos)\n\n if(ocaml_out == 1 and sher_out == 0):\n return 1\n\n if(ocaml_out == 0 and sher_out == 1):\n return -1\n return 0\n\n##################### MAIN ##########################\n'''\ndir = os.path.abspath(__file__ + '/../../')\ndir = os.path.join(dir,\"Spring_2016/checks\")\ntarget = os.path.join(dir,\"bad0.ml\")\ntarget2 = os.path.join(dir,\"anno0.ml\")\ntarget3 = os.path.join(dir,\"fix0.ml\")\ntarget4 = os.path.join(dir,\"annofix0.ml\")\nprint(dir)\n\nbadstr = ''\nannostr = ''\nfixstr = ''\nannofixstr = ''\n\nwith open (target, 'r') as check:\n for line in check:\n badstr = badstr+line\n \ncheck.close()\n\nwith open (target2, 'r') as check:\n\n for line in check:\n annostr = annostr+line\n \n \ncheck.close()\n\nwith open (target3, 'r') as check:\n for line in check:\n fixstr = fixstr+line\n \ncheck.close()\n\nwith open (target4, 'r') as check:\n\n for line in check:\n annofixstr = annofixstr+line\n \ncheck.close()\n\nclrpath = os.path.join(condir, \"error.con\")\n\nprint(clrpath)\nsubprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n\nbadpos = get_pos(badstr,\"bad\", condir)\nprint(badpos)\n\nprint(\"bad\")\nprint(err_judge(badstr,fixstr,badpos))\n\nsubprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n\nannopos = get_pos(annostr,\"anno\", condir)\nprint(annopos)\nprint(\"anno\")\nprint(err_judge(annostr,annofixstr,annopos))\n\n\n\n\ntarget2 = os.path.join(dir,'pre.json')\ntarget3 = os.path.join(dir,'anno.json')\n\ntotal = 0\nprev_corr = 0\nanno_corr = 0\ncounter1 = 0\n\nboth_correct = 0\nboth_wrong = 0\nonly_anno_corr = 0\nonly_pre_corr = 0\nno_fix = 0\n\nwith open (target2, 'r') as prec:\n \n ct = 0\n \n \n\n for line in prec:\n \n if(ct != 11):\n ct = ct+1\n continue\n\n ct = ct + 1\n clrpath = os.path.join(condir, \"error.con\")\n subprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n \n ct = ct +1\n total = total+1\n #print(line)\n \n item = eval(line)\n i=item[\"bad\"]\n \n #skip no fix situation\n if(item[\"fix\"] == \"\"):\n print('no fix')\n no_fix = no_fix+1\n continue\n \n #get wrong position\n #print(i)\n pos = get_pos(i,\"bad\", condir)\n #print(pos)\n #print(type(pos))\n #print(pos)\n\n print(\"bad\")\n retVal = err_judge(i,item[\"fix\"],pos)\n\n if(retVal == 1):\n prev_corr = prev_corr + 1\n \n #deal with annotated\n subprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n \n\n pos = get_pos(item[\"annotated\"],\"anno\", condir )\n #print(pos)\n print(\"anno\")\n\n retVal_a = err_judge(item[\"annotated\"], item[\"annotated_fix\"], pos)\n \n\n #check strange errors\n if(retVal == -1):\n print('cannot judge at 2')\n continue\n\n if(retVal_a == 1):\n anno_corr = anno_corr+1\n \n #put the output to different categories\n if(retVal_a == 1 and retVal == 1):\n both_correct = both_correct +1\n elif(retVal_a == 1 and retVal == 0):\n only_anno_corr = only_anno_corr + 1\n anno.write(line)\n print('anno correct')\n \n elif(retVal_a == 0 and retVal == 1):\n only_pre_corr = only_pre_corr + 1\n #pre.write(line)\n print('pre correct')\n \n else:\n both_wrong = both_wrong +1\n \n\nprec.close()\n\n\n\nwith open (os.path.join(sample), 'r') as myfile, open (os.path.join(target2), 'w') as pre, open (os.path.join(target3), 'w') as anno:\n #open (os.path.join(target_false_fix), 'w')as false_fix, open (os.path.join(target_empty), 'w')as empty_mn:\n \n\n\n ct = 0\n for line in myfile:\n print (ct)\n clrpath = os.path.join(condir, \"error.con\")\n subprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n \n ct = ct +1\n total = total+1\n #print(line)\n \n item = eval(line)\n i=item[\"bad\"]\n \n #skip no fix situation\n if(item[\"fix\"] == \"\"):\n print('no fix')\n no_fix = no_fix+1\n continue\n \n #get wrong position\n #print(i)\n pos = get_pos(i,\"bad\", condir)\n #print(pos)\n #print(type(pos))\n #print(pos)\n retVal = err_judge(i,item[\"fix\"],pos)\n\n if(retVal == 1):\n prev_corr = prev_corr + 1\n \n #deal with annotated\n subprocess.run([\"rm\",clrpath], stdout = subprocess.PIPE)\n pos = get_pos(item[\"annotated\"],\"anno\", condir )\n #print(pos)\n retVal_a = err_judge(item[\"annotated\"], item[\"annotated_fix\"], pos)\n\n\n #check strange errors\n if(retVal == -1):\n print('cannot judge at 2')\n continue\n\n if(retVal_a == 1):\n anno_corr = anno_corr+1\n \n #put the output to different categories\n if(retVal_a == 1 and retVal == 1):\n both_correct = both_correct +1\n elif(retVal_a == 1 and retVal == 0):\n only_anno_corr = only_anno_corr + 1\n anno.write(line)\n print('anno correct')\n \n elif(retVal_a == 0 and retVal == 1):\n only_pre_corr = only_pre_corr + 1\n pre.write(line)\n print('pre correct')\n \n else:\n both_wrong = both_wrong +1\n \n\n\n\nmyfile.close() \npre.close()\nanno.close()\n#prefile.close()\n\ns = 'in the total of ' + str(total) + ' programs, both correct is: ' + str(both_correct) + 'only annotated correct is: ' \\\n + str(only_anno_corr) + 'only pre correct is: ' + str(only_pre_corr) + 'both wrong is: '+str(both_wrong) +\\\n ' no fix: ' + str(no_fix)\n\nprint (s)\n\n'''","sub_path":"summer_2016/generate_con.py","file_name":"generate_con.py","file_ext":"py","file_size_in_byte":20668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"343552874","text":"class Solution:\n \"\"\"\n @param costs: n x 3 cost matrix\n @return: An integer, the minimum cost to paint all houses\n \"\"\"\n def minCost(self, costs):\n r, b, g = 0, 0, 0\n\n for r_c, b_c, g_c in costs:\n r, b, g = r_c + min(b, g), b_c + min(r, g), g_c + min(r, b)\n\n return min(r, b, g)\n","sub_path":"Linkedin 高频算法题2019/2/515. Paint House.py","file_name":"515. Paint House.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"447146258","text":"from datetime import datetime\n\nimport pytest\n\nfrom tartiflette import Resolver\nfrom tartiflette.tartiflette import Tartiflette\n\n\n@pytest.mark.asyncio\nasync def test_tartiflette_execute_scalar_type_output():\n schema_sdl = \"\"\"\n scalar Date\n\n type Query {\n lastUpdate: Date\n }\n \"\"\"\n\n def from_date_to_str(datetime):\n return datetime.isoformat()\n\n def from_str_to_date(datetime_str):\n return datetime.strptime(datetime_str, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n\n ttftt = Tartiflette(schema_sdl)\n\n ttftt.schema.types[\"Date\"].coerce_output = from_date_to_str\n ttftt.schema.types[\"Date\"].coerce_input = from_str_to_date\n\n @Resolver(\"Query.lastUpdate\", schema=ttftt.schema)\n async def func_field_resolver(*args, **kwargs):\n return datetime(year=2018, month=4, day=19,\n hour=14, minute=57, second=38)\n\n ttftt.schema.bake()\n result = await ttftt.execute(\"\"\"\n query Test{\n lastUpdate\n }\n \"\"\")\n\n assert {\"data\":{\"lastUpdate\":\"2018-04-19T14:57:38\"}} == result\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"input_sdl,resolver_response,expected\", [\n (\n \"String\",\n \"test\",\n {\"data\":{\"testField\":\"test\"}},\n ),\n (\n \"String!\",\n None,\n {\"data\":{\"testField\":None},\"errors\":[{\"message\":\"Invalid value (value: None) for field `testField` of type `String!`\",\"path\":[\"testField\"],\"locations\":[{\"line\":1,\"column\":26}]}]},\n ),\n (\n \"Int\",\n 45,\n {\"data\":{\"testField\":45}},\n ),\n (\n \"Float\",\n 45.0,\n {\"data\":{\"testField\":45.0}},\n ),\n (\n \"Boolean\",\n True,\n {\"data\":{\"testField\":True}},\n ),\n (\n \"Boolean\",\n False,\n {\"data\":{\"testField\":False}},\n ),\n (\n \"[Date]\",\n [datetime(year=2018, month=4, day=19, hour=14, minute=57, second=38)],\n {\"data\":{\"testField\":[\"2018-04-19T14:57:38\"]}},\n ),\n (\n \"[[Date!]!]!\",\n [[\n datetime(year=2017, month=3, day=18, hour=13, minute=56, second=37),\n datetime(year=2018, month=4, day=19, hour=14, minute=57, second=38),\n ]],\n {\"data\":{\"testField\":[[\"2017-03-18T13:56:37\",\"2018-04-19T14:57:38\"]]}},\n ),\n (\n \"[Date]\",\n [\n datetime(year=2017, month=3, day=18, hour=13, minute=56, second=37),\n None,\n datetime(year=2018, month=4, day=19, hour=14, minute=57, second=38),\n ],\n {\"data\":{\"testField\":[\"2017-03-18T13:56:37\",None,\"2018-04-19T14:57:38\"]}},\n ),\n # TODO: Test temporarily disabled (needs a fix on error resolving etc.)\n (\n \"[Date!]\",\n [\n datetime(year=2017, month=3, day=18, hour=13, minute=56, second=37),\n None,\n datetime(year=2018, month=4, day=19, hour=14, minute=57, second=38),\n ],\n {\"data\":{\"testField\": None},\"errors\":[{\"message\":\"Invalid value (value: None) for field `testField` of type `[Date!]`\",\"path\":[\"testField\",1],\"locations\":[{\"line\":1,\"column\":26}]}]},\n ),\n])\nasync def test_tartiflette_execute_scalar_type_advanced(input_sdl, resolver_response, expected):\n schema_sdl = \"\"\"\n scalar Date\n\n type Query {{\n testField: {}\n }}\n \"\"\".format(input_sdl)\n\n def from_date_to_str(datetime):\n try:\n return datetime.isoformat()\n except AttributeError:\n return None\n\n ttftt = Tartiflette(schema_sdl)\n\n ttftt.schema.types[\"Date\"].coerce_input = lambda x: x\n ttftt.schema.types[\"Date\"].coerce_output = from_date_to_str\n\n @Resolver(\"Query.testField\", schema=ttftt.schema)\n async def func_field_resolver(*args, **kwargs):\n return resolver_response\n\n ttftt.schema.bake()\n result = await ttftt.execute(\"\"\"\n query Test{\n testField\n }\n \"\"\")\n\n assert expected == result\n","sub_path":"tests/functional/types/test_scalar.py","file_name":"test_scalar.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"118923120","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped, PoseArray, Pose\nfrom nav_msgs.msg import Odometry\nfrom pyquaternion import Quaternion\nimport tf2_ros\nimport tf2_geometry_msgs\nfrom tf import TransformListener\nimport math\n\n\nimport os \nimport sys\ndir_to_Tracker=os.path.dirname(os.path.dirname(os.path.dirname( __file__ )))\ndir_to_Scripts = os.path.join(dir_to_Tracker,\"Scripts\") \nsys.path.append(dir_to_Scripts)\nfrom agfh import *\n\nclass Follow():\n def __init__(self):\n rospy.init_node('Create_goal')\n\n self.tf_buffer = tf2_ros.Buffer(rospy.Duration(1200.0)) #tf buffer length\n self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)\n\n self.Waypoints = []\n self.Move_base_goal = []\n self.Waypoint = Pose()\n self.Waypoints = PoseArray()\n self.Waypoints_reached = PoseArray()\n\n self.tf = TransformListener()\n # Tolerances\n self.distance_keep = 0.5 #[m]\n self.distance_new = 1.5\n self.distance_threshold = 0.1 # Distance to a waypoint before it is discarded\n self.twist_threshold = 30*math.pi/180\n\n # Subscribed topic\n self.pub_goal = rospy.Publisher('/move_base_simple/goal', PoseStamped, queue_size=1)\n self.pub_waypoint_list = rospy.Publisher(\"/Tracker/Waypoint_list\",PoseArray,queue_size=1)\n self.pub_waypoint_list_reached = rospy.Publisher(\"/Tracker/Waypoint_list_deleted\",PoseArray,queue_size=1)\n print(\"Waiting for Odometry...\")\n try:\n self.Current_position = rospy.wait_for_message(\"/odometry/filtered_map\",Odometry,timeout=5)\n except:\n self.Current_position = Odometry()\n self.Current_position.pose.pose.position.x = 0\n self.Current_position.pose.pose.position.y = 0\n self.Current_position.pose.pose.position.z = 0\n self.Current_position.pose.pose.orientation.w = 1\n self.Current_position.pose.pose.orientation.x = 0\n self.Current_position.pose.pose.orientation.y = 0\n self.Current_position.pose.pose.orientation.z = 0\n \n self.Move_base_goal = self.Current_position.pose\n \n print(\"Odometry received\")\n rospy.Subscriber(\"/odometry/filtered_map\",Odometry,self.Compare_pose,queue_size=1)\n rospy.Subscriber(\"/Tracker/Object_Tracker/Published_pose\",PoseStamped,self.New_input, queue_size=1)\n rospy.Subscriber(\"/move_base/Current_goal\",PoseStamped,self.Current_goal, queue_size=1)\n \n \n def New_input(self,Pose):\n # This callback is responsible of creating a list of goals that the vehicle is to follow in order\n self.Waypoints.header = Pose.header\n Waypoint = Pose.pose\n\n # Calculate Transforms and the Poses in their respective frames\n # Transform from \"Pose Frame\" to base_link\n #transform_pb = self.tf_buffer.lookup_transform(\"base_link\", Pose.header.frame_id, rospy.Time(0), rospy.Duration(1.0))\n # Transform from \"Pose Frame\" to map\n transform_pm = self.tf_buffer.lookup_transform(\"map\", Pose.header.frame_id, rospy.Time(0), rospy.Duration(1.0))\n # Pose in base_link frame\n #np_b = tf2_geometry_msgs.do_transform_pose(Pose,transform_pb)\n # Pose in map frame\n np_m = tf2_geometry_msgs.do_transform_pose(Pose,transform_pm)\n # Mapping only takes zero values in z\n #np_b.pose.position.z = 0\n np_m.pose.position.z = 0 \n\n # If self.Waypoints is empty \n if self.Waypoints.poses == []:\n # Check distance to the current point from vehicle\n distance_to_vehicle = math.sqrt((np_m.pose.position.x-self.Current_position.pose.pose.position.x)**2+(np_m.pose.position.y-self.Current_position.pose.pose.position.y)**2)\n # If point is within proximity of vehicle, add current vehicle position with orientation towards point\n if distance_to_vehicle < self.distance_new:\n vec_new_old=np.array([np_m.pose.position.x,np_m.pose.position.y,np_m.pose.position.z])\n quaternion=get_new_orientation(self.Move_base_goal,np_m,0,Points=True)\n\n Waypoint.position.x = self.Move_base_goal.pose.position.x\n Waypoint.position.y = self.Move_base_goal.pose.position.y\n Waypoint.position.z = self.Move_base_goal.pose.position.z\n # If point is NOT witin proximity of vehicle, add object position with orientation towards point\n else:\n vec_new_old=np.array([np_m.pose.position.x,np_m.pose.position.y,np_m.pose.position.z])\n quaternion=get_new_orientation(0,0,vec_new_old,Points=False)\n\n Waypoint.position.x = np_m.pose.position.x\n Waypoint.position.y = np_m.pose.position.y\n Waypoint.position.z = np_m.pose.position.z\n\n Waypoint.orientation.x = quaternion[0]\n Waypoint.orientation.y = quaternion[1]\n Waypoint.orientation.z = quaternion[2]\n Waypoint.orientation.w = quaternion[3]\n\n self.Waypoints.poses.append(Waypoint)\n self.pub_waypoint_list.publish(self.Waypoints)\n \n # If self.Waypoints is NOT empty\n else:\n # If within proximity of the latest waypoint update the orientation of the waypoint\n lp_m = PoseStamped()\n lp_m.pose = self.Waypoints.poses[-1]\n distance_to_lastest_waypoint = math.sqrt((np_m.pose.position.x-lp_m.pose.position.x)**2+(np_m.pose.position.y-lp_m.pose.position.y)**2)\n if distance_to_lastest_waypoint < self.distance_new:\n quaternion=get_new_orientation(lp_m,np_m,0,Points=True)\n\n self.Waypoints.poses[-1].orientation.x = quaternion[0]\n self.Waypoints.poses[-1].orientation.y = quaternion[1]\n self.Waypoints.poses[-1].orientation.z = quaternion[2]\n self.Waypoints.poses[-1].orientation.w = quaternion[3] \n\n self.pub_waypoint_list.publish(self.Waypoints) \n\n # If NOT within proximity of the latast waypoint add as a new point\n else:\n quaternion=get_new_orientation(lp_m,np_m,0,Points=True)\n Waypoint.position.x = np_m.pose.position.x\n Waypoint.position.y = np_m.pose.position.y\n Waypoint.position.z = np_m.pose.position.z\n\n Waypoint.orientation.x = quaternion[0]\n Waypoint.orientation.y = quaternion[1]\n Waypoint.orientation.z = quaternion[2]\n Waypoint.orientation.w = quaternion[3]\n\n self.Waypoints.poses.append(Waypoint)\n self.pub_waypoint_list.publish(self.Waypoints)\n \n #print(self.Waypoints)\n\n \"\"\"\n transform = self.tf_buffer.lookup_transform(\"base_link\", Pose.header.frame_id, rospy.Time(0), rospy.Duration(1.0))\n np_b = tf2_geometry_msgs.do_transform_pose(Pose, transform) # New Waypoint in base\n npd = math.sqrt((np_b.pose.position.x)**2+(np_b.pose.position.y)**2)\n if npd > self.distance_threshold:\n\n transform_np = self.tf_buffer.lookup_transform(\"map\", Pose.header.frame_id, rospy.Time(0), rospy.Duration(1.0))\n np_m = tf2_geometry_msgs.do_transform_pose(Pose, transform_np)\n np_m.pose.position.z = 0\n\n # If the waypoint is further away than distance_threshold and Waypoint list is empty add point to waypoints\n # If list is not empty compare new waypoint with the latest added waypoint to ensure that distance between the two points are greater than distance_new\n if self.Waypoints2.poses == []:\n vec_new_old=np.array([np_m.pose.position.x,np_m.pose.position.y,np_m.pose.position.z])\n quaternion=get_new_orientation(0,0,vec_new_old,Points=False)\n np_m.pose.orientation.x=quaternion[0]\n np_m.pose.orientation.y=quaternion[1]\n np_m.pose.orientation.z=quaternion[2]\n np_m.pose.orientation.w=quaternion[3]\n \n self.update_waypoints(np_m)\n \n else: \n lp_m = PoseStamped()\n lp_m.pose = self.Waypoints2.poses[-1]\n quaternion=get_new_orientation(lp_m,np_m,0,Points=True)\n np_m.pose.orientation.x=quaternion[0]\n np_m.pose.orientation.y=quaternion[1]\n np_m.pose.orientation.z=quaternion[2]\n np_m.pose.orientation.w=quaternion[3]\n wpd = math.sqrt((np_m.pose.position.x-lp_m.pose.position.x)**2+(np_m.pose.position.y-lp_m.pose.position.y)**2)\n if wpd > self.distance_new:\n #self.Waypoints.append(np_m)\n self.update_waypoints(np_m)\n\n \n # If point is closer than distance treshold and goal is reached (Only on point in the list), initiate rotation on the spot\n else:\n pass\n \"\"\"\n \n def Compare_pose(self,Pose):\n # https://answers.ros.org/question/222306/transform-a-pose-to-another-frame-with-tf2-in-python/\n #print(len(self.Waypoints2.poses),\"Compare\")\n self.Current_position = Pose\n\n Waypoint = PoseStamped()\n Waypoint.header = Pose.header\n self.Waypoints_reached.header = Pose.header\n\n #self.Waypoints\n\n # Check if there is a current goal\n if self.Move_base_goal != []:\n # Check the distance from the vehicle to the current goal\n distance_to_goal = math.sqrt((self.Current_position.pose.pose.position.x-self.Move_base_goal.pose.position.x)**2+(self.Current_position.pose.pose.position.y-self.Move_base_goal.pose.position.y)**2)\n # If vehicle is within distance_keep:\n print(distance_to_goal, \"d2g\")\n if distance_to_goal <= self.distance_threshold:\n # Check lenght of Waypoint.poses\n # If empty do nothing\n if len(self.Waypoints.poses) > 0:\n distance_to_waypoint = math.sqrt((self.Current_position.pose.pose.position.x-self.Waypoints.poses[0].position.x)**2+(self.Current_position.pose.pose.position.y-self.Waypoints.poses[0].position.y)**2)\n print(distance_to_waypoint, \"d2w\")\n # If list is 1 waypoint \n if distance_to_waypoint < self.distance_keep:\n if len(self.Waypoints.poses) ==1:\n print(\"wT wK 1P\")\n Q_goal = Quaternion(self.Move_base_goal.pose.orientation.w,self.Move_base_goal.pose.orientation.x,self.Move_base_goal.pose.orientation.y,self.Move_base_goal.pose.orientation.z)\n Q_wp = Quaternion(self.Waypoints.poses[0].orientation.w,self.Waypoints.poses[0].orientation.x,self.Waypoints.poses[0].orientation.y,self.Waypoints.poses[0].orientation.z)\n Twist_goal = abs((Q_goal*Q_wp.inverse).angle)\n if Twist_goal > self.twist_threshold: \n Waypoint.pose = self.Waypoints.poses[0]\n self.pub_goal.publish(Waypoint)\n self.Waypoints_reached.poses.append(self.Waypoints.poses[0])\n del self.Waypoints.poses[0]\n self.pub_waypoint_list_reached.publish(self.Waypoints_reached)\n self.pub_waypoint_list.publish(self.Waypoints)\n # If list longer than one waypoint\n else:\n print(\"wT wK mP\")\n self.Waypoints_reached.poses.append(self.Waypoints.poses[0])\n del self.Waypoints.poses[0]\n self.pub_waypoint_list_reached.publish(self.Waypoints_reached)\n #Waypoint.pose = self.Waypoints.poses[0]\n #self.pub_goal.publish(Waypoint)\n self.pub_waypoint_list.publish(self.Waypoints)\n # If further away from the waypoint than distance threshold\n else:\n # IF there is only one waypoint and it is further away than the keep distance. Make a new point in between the goal and the vehicle at the keep distance\n if len(self.Waypoints.poses) ==1:\n print(\"wT oK 1P\")\n Waypoint.pose = self.Waypoints.poses[0]\n vec_Goal_map = np.array([self.Waypoints.poses[0].position.x,self.Waypoints.poses[0].position.y])\n vec_Vehicle_map = np.array([Pose.pose.pose.position.x,Pose.pose.pose.position.y])\n xy_goal_stop = cal_pose_stop(vec_Goal_map,vec_Vehicle_map,self.distance_keep)\n Waypoint.pose.position.x = xy_goal_stop[0]\n Waypoint.pose.position.y = xy_goal_stop[1]\n del self.Waypoints.poses[0]\n #self.Waypoints.poses[0] = Waypoint.pose\n self.pub_goal.publish(Waypoint)\n\n else:\n print(\"wT oK MP\")\n #self.Waypoints_reached.poses.append(self.Waypoints.poses[0])\n Waypoint.pose = self.Waypoints.poses[0]\n self.pub_goal.publish(Waypoint)\n\n else:\n print(\"oT\")\n \"\"\"\n\n elif len(self.Waypoints.poses) == 1:\n \n distance_to_waypoint = math.sqrt((self.Current_position.pose.pose.position.x-self.Waypoints.poses[0].position.x)**2+(self.Current_position.pose.pose.position.y-self.Waypoints.poses[0].position.y)**2)\n print(distance_to_waypoint)\n if distance_to_waypoint <= self.distance_keep:\n print(\"case 1\")\n # If angle between goal and current_waypoint is greater than twist_threshold\n Q_goal = Quaternion(self.Move_base_goal.pose.orientation.w,self.Move_base_goal.pose.orientation.x,self.Move_base_goal.pose.orientation.y,self.Move_base_goal.pose.orientation.z)\n Q_wp = Quaternion(self.Waypoints.poses[0].orientation.w,self.Waypoints.poses[0].orientation.x,self.Waypoints.poses[0].orientation.y,self.Waypoints.poses[0].orientation.z)\n Twist_goal = abs((Q_goal*Q_wp.inverse).angle)\n if Twist_goal > self.twist_threshold: \n Waypoint.pose = self.Waypoints.poses[0]\n self.pub_goal.publish(Waypoint)\n self.Waypoints_reached.poses.append(self.Waypoints.poses[0])\n del self.Waypoints.poses[0]\n self.pub_waypoint_list_reached.publish(self.Waypoints_reached)\n self.pub_waypoint_list.publish(self.Waypoints)\n else:\n print(\"case 2\")\n Waypoint.pose = self.Waypoints.poses[0]\n vec_Goal_map = np.array([self.Waypoints.poses[0].position.x,self.Waypoints.poses[0].position.y])\n vec_Vehicle_map = np.array([Pose.pose.pose.position.x,Pose.pose.pose.position.y])\n xy_goal_stop = cal_pose_stop(vec_Goal_map,vec_Vehicle_map,self.distance_keep)\n Waypoint.pose.position.x = xy_goal_stop[0]\n Waypoint.pose.position.y = xy_goal_stop[1]\n\n del self.Waypoints.poses[0]\n self.pub_waypoint_list.publish(self.Waypoints)\n self.pub_goal.publish(Waypoint)\n\n pass\n # c\n # If list have more than one waypoint\n else:\n print(\"case 3\")\n self.Waypoints_reached.poses.append(self.Waypoints.poses[0])\n del self.Waypoints.poses[0]\n self.pub_waypoint_list_reached.publish(self.Waypoints_reached)\n Waypoint.pose = self.Waypoints.poses[0]\n self.pub_goal.publish(Waypoint)\n self.pub_waypoint_list.publish(self.Waypoints)\n\n # distance to the goal is further than distance_keep\n \"\"\"\n \"\"\"\n else: #if distance_to_goal < self.distance_keep:\n \n if len(self.Waypoints.poses) == 0:\n pass\n elif len(self.Waypoints.poses) == 1:\n print(\"case 4\")\n Waypoint.pose = self.Waypoints.poses[0]\n vec_Goal_map = np.array([self.Waypoints.poses[0].position.x,self.Waypoints.poses[0].position.y])\n vec_Vehicle_map = np.array([Pose.pose.pose.position.x,Pose.pose.pose.position.y])\n xy_goal_stop = cal_pose_stop(vec_Goal_map,vec_Vehicle_map,self.distance_keep)\n Waypoint.pose.position.x = xy_goal_stop[0]\n Waypoint.pose.position.y = xy_goal_stop[1]\n\n self.pub_waypoint_list.publish(self.Waypoints)\n self.pub_goal.publish(Waypoint)\n pass\n else:\n print(\"case 5\")\n pass\n pass\n \"\"\"\n # If there is no current goal publish the current waypoint if there is any\n else:\n if len(self.Waypoints.poses) > 0:\n Waypoint.pose = self.Waypoints.poses[0]\n \n self.pub_goal.publish(Waypoint)\n \"\"\"\n\n\n # If vehicle is not within distance_threshold, keep pursuing goal\n else:\n pass\n\n\n #Ch_vec_Vehicle_map = np.array([Pose.pose.pose.position.x,Pose.pose.pose.position.y])\n if len(Waypoints.poses) == 0:\n pass\n else:\n \n\n # Distance between to goal.\n if self.Move_base_goal != []\n distance_to_goal = math.sqrt((np_m.pose.position.x-self.Move_base_goal.pose.position.x)**2+(np_m.pose.position.y-self.Move_base_goal.pose.position.y)**2)\n # If there is no goal, publish the Waypoint as a goal\n else: \n Waypoint.pose = Waypoints.poses[0]\n self.pub_goal.publish(Waypoint)\n \"\"\"\n\n \n\n \"\"\"\n # Check if distance to vehicle is less that distance keep\n #distance_to_vehicle = math.sqrt((np_m.pose.position.x-self.Current_position.pose.pose.position.x)**2+(np_m.pose.position.y-self.Current_position.pose.pose.position.y)**2)\n \n # If there is a goal calculate the distance between the current only waypoint and the goal\n if self.Move_base_goal != []\n distance_to_goal = math.sqrt((np_m.pose.position.x-self.Move_base_goal.pose.position.x)**2+(np_m.pose.position.y-self.Move_base_goal.pose.position.y)**2)\n # If the distance between the current goal and current waypoint is less that self.distance_new, this point is a current distance point and the angle needs to be updated\n if distance_to_goal < self.distance_new:\n\n pass\n # If the distance_to_goal is larger than current goal \n else:\n pass\n\n # If the distance to the point is within distance_keep\n if distance_to_vehicle < self.distance_new:\n pass\n else:\n pass\n # If the angle between the current goal and the \n # \n \"\"\"\n \"\"\"\n # Responsible of publishing the goal for the vehicle to move to.\n # If waypoint list is empty do nothing\n if len(Waypoints.poses) == 0:\n pass\n # If waypoint list only contains one pose\n elif len(Waypoints.poses) == 1:\n Waypoint = Waypoints.poses[0]\n #print(\"CASE 2\")\n\n #self.Waypoints.append(Waypoints[0])\n #self.pub_goal.publish(Waypoints[0])\n Goal_m=Waypoints.poses[0]\n #print(self.Waypoints[0].pose.position,\"i 2\")\n\n #print(Goal_m.pose.position,\"--->goal pose\")\n vec_Goal_map = np.array([Goal_m.position.x,Goal_m.position.y])\n #print(self.Waypoints[0].pose.position,\"i 3\")\n\n #print(vec_Goal_map,\"Goal\")\n vec_Vehicle_map = np.array([Pose.pose.pose.position.x,Pose.pose.pose.position.y])\n #print(self.Waypoints[0].pose.position,\"i 4\")\n\n #print(vec_Vehicle_map,\"Vehicle\")\n xy_goal_stop = cal_pose_stop(vec_Goal_map,vec_Vehicle_map,self.distance_keep)\n\n #temp_waypoint=Goal_m\n temp_waypoint = self.Waypoints2.poses[0]\n #Goal_m.pose.position.x=xy_goal_stop[0] # Udkommenter hvis den skal køre ind i object\n #Goal_m.pose.position.y=xy_goal_stop[1] # Udkommenter hvis den skal køre ind i object\n\n temp_pose = PoseStamped()\n temp_pose.header.stamp = rospy.Time.now()\n temp_pose.header.frame_id = \"map\"\n temp_pose.pose.position.x = xy_goal_stop[0]\n temp_pose.pose.position.y = xy_goal_stop[1]\n temp_pose.pose.position.z = self.Waypoints2.poses[0].position.z\n temp_pose.pose.orientation.x = self.Waypoints2.poses[0].orientation.x\n temp_pose.pose.orientation.y = self.Waypoints2.poses[0].orientation.y\n temp_pose.pose.orientation.z = self.Waypoints2.poses[0].orientation.z\n temp_pose.pose.orientation.w = self.Waypoints2.poses[0].orientation.w\n #if temp_pose.pose.position.x - self.Waypoints[0].pose.position.x == 0 and temp_pose.pose.position.y - self.Waypoints[0].pose.position.y == 0:\n self.pub_goal.publish(temp_pose)\n\n # If waypoint list contains poses\n \n else:\n #print(\"CASE 3\")\n # Calculate the distance to all current waiting waypoints\n d2pb = []\n transform_bm = self.tf_buffer.lookup_transform(\"map\",\"base_link\", Pose.header.stamp, rospy.Duration(1.0))\n transform_mb = self.tf_buffer.lookup_transform(\"base_link\",\"map\", Pose.header.stamp, rospy.Duration(1.0))\n for Point_m in Waypoints.poses:\n Point = PoseStamped() \n Point.pose = Point_m\n Point_b = tf2_geometry_msgs.do_transform_pose(Point, transform_mb)\n d2pb.append(math.sqrt(Point_b.pose.position.x**2+Point_b.pose.position.y**2))\n minpos = d2pb.index(min(d2pb))\n # If any waypoints in the list is closer to the base, discard all waypoints up to the closest point.\n if minpos > 0:\n for i in range(0,minpos):\n del Waypoints.poses[0]\n\n \n # Check if the current Waypoint in \n Goal_m = Waypoints.poses[0]\n goal = PoseStamped()\n goal.pose = Goal_m # Need fix\n Goal_b = tf2_geometry_msgs.do_transform_pose(goal, transform_mb)\n distance2waypoint = math.sqrt(Goal_b.pose.position.x**2+Goal_b.pose.position.y**2)\n #print(distance2waypoint,\"distance\")\n # If the waypoint is further away than distance threshold, check if point is the current goal or else publish as current goal\n if distance2waypoint > self.distance_threshold:\n # If current waypoint is the same as goal, pass\n if self.Move_base_goal == Waypoints.poses[0]:\n pass\n # If current waypoint is not same as goal, publish current waypoint and add current goal\n else:\n pubpoint = PoseStamped()\n pubpoint.header = Waypoints.header\n pubpoint.header.stamp = rospy.Time.now()\n pubpoint.pose = Waypoints.poses[0]\n \"\"\"\n \"\"\"\n pubpoint.pose.orientation.x = 0\n pubpoint.pose.orientation.y = 0\n pubpoint.pose.orientation.z = 0\n pubpoint.pose.orientation.w = 1\n \"\"\"\n \"\"\"\n \n self.pub_goal.publish(pubpoint)\n # If the waypoint is within distance threshold remove current waypoint \n else:\n if len(Waypoints.poses) != 1:\n del Waypoints.poses[0]\n elif len(Waypoints.poses)==0:\n pass\n else:\n pubpoint = PoseStamped()\n pubpoint.header = Waypoints.header\n pubpoint.header.stamp = rospy.Time.now()\n pubpoint.pose = Waypoints.poses[0]\n \"\"\"\n \"\"\"\n pubpoint.pose.orientation.x = 0\n pubpoint.pose.orientation.y = 0\n pubpoint.pose.orientation.z = 0\n pubpoint.pose.orientation.w = 1\n \"\"\"\n \"\"\"\n\n self.pub_goal.publish(pubpoint)\n \"\"\"\n \"\"\"\n del Waypoints[0]\n # If list is now empty do nothing\n if len(Waypoints) == 0:\n pass\n # If list contains one pose do not publish \n elif len(Waypoints) == 1:\n pass\n # If list containt more poses, publish a new goal\n else:\n self.pub_goal.publish(Waypoints[0])\n \"\"\"\n \n\n def Current_goal(self,Pose):\n self.Move_base_goal = Pose\n\n def update_waypoints(self,Pose):\n self.Waypoints2.header = Pose.header\n self.Waypoints2.poses.append(Pose.pose)\n self.pub_waypoint_list.publish(self.Waypoints2)\n\n\n\ndef temp(Pose, xy):\n Pose.pose.position.x=xy[0] # Udkommenter hvis den skal køre ind i object\n Pose.pose.position.y=xy[1] # Udkommenter hvis den skal køre ind i object\n temp = Pose\n return temp\n\nif __name__ == '__main__':\n try:\n Follow()\n rospy.spin()\n except rospy.ROSInterruptException:\n pass","sub_path":"src/Tracker/follow/src/Create_goalwpose.py","file_name":"Create_goalwpose.py","file_ext":"py","file_size_in_byte":26414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"307388404","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport socket\nimport copy\nimport glob\n\ntry:\n import dolfin as dolf\nexcept:\n print('\\n\\nWARNING: Could not import dolfin\\n (Limits usage of module phasefield_elasticity).')\nfrom matplotlib import cm\n\nhostname = socket.gethostname()\nif hostname[0:6] != 'midway':\n import scipy\n from scipy.interpolate import griddata\n\n try:\n import sympy as sp\n except:\n print('WARNING: Could not import sympy!\\n (Should not matter though).')\n from scipy.spatial import Delaunay\n\n'''Module for handling fenics data.\n\nTable of Contents\n-----------------\n1. FEniCS definitions\n (these functions generally use UFL)\n generating dolfin meshes from saved triangulations, defining boundary conditions\n initial phase conditions for cracks and interacting cracks\n4. Lattice Generation\n generate a lattice given lattice vectors, create a Vogel-triangulated mesh (useful for triangulating disks)\n arrow function for making mesh arrows\n5. Data Handling\n converting vectors and tensors from polar to cartesian, converting triangulations to bond lists,\n cutting bonds based on length, determining if points lie on lines or linesegments,\n calculating nearest points on a line segment or line, minimum distance from any linesegment in list, etc,\n creating unique-rowed arrays, matching orientations of triangulations, computing initial phase profile of a crack,\n kd trees, looking up values for a point based on proximity via a table,\n check if a variable is a number, rounding based on arbitrary thresholds, find a variable definition in a txt file\n\n\nDictionary of acronyms used in this doc\n---------------------------------------\n======= ============\n======= ============\nUFL Unified Form Language, used by dolfin/FEniCS codes\nBC boundary condition\nBCUP whether a boundary condition is dirichlet (U for displacement) or natural (P for traction)\nECUML Edge Crack Under Mixed Loading\nnn nearest neighbors\nBL bond list (uppercase means 2D)\nbL bond length (lowercase means 1D)\nP traction at boundary or Peclet number, depending on the context\nPURL boundary condition situation with essential BC on left side of a plate and natural BC on the right side\n======= ============\n\nList of Predefined Boundary Conditions (options for string variable BCtype)\n---------------------------------------------------------------------------\n========================== ============\nFor use with BCUP == 'natural-essential':\n========================== ============\nUsingleptcorner_Puniaxial fix singlept in bottom left corner as u=(0,0), P is uniaxial\nUsingleptcornerP* fix singlept in bottom left corner as u=(0,0), P is followed by a string specified another\n subconfiguration (ex, Puniaxial)\n========================== ============\n\n========================== ============\nFor use with BCUP == 'essential' (applied to u) or 'natural' (applied to P, with U->E*U):\n========================== ============\nuniaxialfree 'U*(x[0]-xc)' for Vv.sub(0) --> constrain one dimension (x dim) on sides, also do DirichletBC(Vv.sub(1), Constant(0.0), boundary_singleptcorner)\nuniaxialfreeX constrain both dimensions on sides (free refers to the top and bottom)\nuniaxialfreeY constrain both dimensions on top and bottom (free refers to the left and right)\nbiaxial ('U*sqrt( pow(x[0]-xc,2)+pow(x[1]-yc, 2) )*cos(atan2(x[1]-yc,x[0]-xc))', 'U*sqrt( pow(x[0]-xc,2)+pow(x[1]-yc, 2) )*sin(atan2(x[1]-yc,x[0]-xc))')\nfixleftX ('U*(x[0]-xc)' , '0.0') for bcu = dolf.DirichletBC(Vv, u_0, boundary_leftside),\nuniaxial-PURL ('U*(x[0]-xc)' , '0.0')\nuniaxialDisc ('U*sqrt( pow(x[0]-xc,2)+pow(x[1]-yc, 2) )*cos(atan2(x[1]-yc,x[0]-xc))' ,'0.0')\n========================== ============\n\n========================== ============\nFor use with BCUP == 'essential':\n========================== ============\nuniaxialmixedfree_u1s1 ('U*(x[0]-xc)' , 'U*(x[0]-xc)')\nuniaxialmixedfree_uvals1 ('val*U*(x[0]-xc)' , 'U*(x[0]-xc)')\nuniaxialmixedfree_u1sval ('U*(x[0]-xc)' , 'val*U*(x[0]-xc)')\nfree no constraint\nfixbotY ('0.' ,'0.') along bottom edge\nfixtopY ('0.' ,'0.') along top edge\nfixbotcorner ('0.' ,'0.') just in the corner, one mesh triangle\n========================== ============\n\n'''\n\n##########################################\n# 1. FEniCS definitions\n##########################################\n\n\ndef xy_from_function_space(vf, uu, mesh):\n \"\"\"Get coordinates in xy of the mesh using a vector function space (vf) and a field defined on that space (uu),\n along with the mesh itself\n\n Parameters\n ----------\n vf : vector function space or None\n a vector function space defined on a mesh\n \"\"\"\n if vf is None:\n vf = dolf.FunctionSpace(mesh, \"Lagrange\", 1)\n uu = dolf.TrialFunction(vf)\n elif uu is None:\n uu = dolf.TrialFunction(vf)\n\n n = vf.dim()\n d = uu.geometric_dimension()\n dof_coordinates = vf.dofmap().tabulate_all_coordinates(mesh)\n dof_coordinates.resize((n, d))\n return dof_coordinates\n\n\ndef dolf_laplacian(f):\n \"\"\"Using UFL, calc the laplacian of a scalar field\"\"\"\n return dolf.div(dolf.grad(f))\n\n\ndef genmesh(shape, meshtype, N, xi, theta, R, eta, fenicsdir='../'):\n \"\"\"Load correct mesh from FEniCS/meshes/ directory, assuming we've used the mesh_generation_xml_fenics.py module\n to create the mesh already.\n \"\"\"\n Rstr = '{0:.3f}'.format(R).replace('.', 'p')\n etastr = '{0:.3f}'.format(eta).replace('.', 'p')\n if shape == 'square':\n nx = int(np.sqrt(N))\n meshd = nx / (2 * R) * float(xi)\n if meshtype == 'UnitSquare':\n print('Creating unit square mesh of ', meshtype, ' lattice topology...')\n mesh = dolf.UnitSquareMesh(nx, nx)\n else:\n print('Creating square-shaped mesh of ', meshtype, ' lattice topology...')\n meshfile = fenicsdir + 'meshes/' + shape + 'Mesh_' + meshtype + '_eta' + etastr + '_R' + Rstr + '_N' + \\\n str(int(N)) + '.xml'\n mesh = dolf.Mesh(meshfile)\n elif shape == 'circle':\n print('Creating circle-shaped mesh of ', meshtype, ' lattice topology...')\n meshd = 2 * np.sqrt(N / np.pi) * float(xi) / (2 * R)\n if meshtype == 'Trisel':\n add_exten = '_Nsp' + str(Nsp) + '_H' + '{0:.2f}'.format(H / R).replace('.', 'p') + \\\n '_Y' + '{0:.2f}'.format(Y / R).replace('.', 'p') + \\\n '_beta' + '{0:.2f}'.format(beta / np.pi).replace('.', 'p') + \\\n '_theta' + '{0:.2f}'.format(theta / np.pi).replace('.', 'p')\n else:\n add_exten = ''\n\n meshfile = fenicsdir + 'meshes/' + shape + 'Mesh_' + meshtype + add_exten + '_eta' + etastr + '_R' + Rstr + '_N' + str(\n int(N)) + '.xml'\n mesh = dolf.Mesh(meshfile)\n elif shape == 'rectangle2x1' or shape == 'rectangle1x2':\n print('Creating circle-shaped mesh of ', meshtype, ' lattice topology...')\n meshd = np.sqrt(N * 0.5) * float(xi) / (2 * R)\n add_exten = ''\n\n meshfile = fenicsdir + 'meshes/' + shape + 'Mesh_' + meshtype + add_exten + '_eta' + etastr + '_R' + Rstr + '_N' + str(\n int(N)) + '.xml'\n print('loading meshfile = ', meshfile)\n mesh = dolf.Mesh(meshfile)\n\n print('found meshfile = ', meshfile)\n return mesh, meshd, meshfile\n\n\n##########################################\n# 4. Lattice Generation\n##########################################\ndef generate_diskmesh(R, n, steps_azim):\n \"\"\"Create an array of evenly spaced points in 2D on a disc using Vogel's method.\n\n Parameters\n ----------\n R : float\n radius of the disc\n n : int\n number of points within the disc, distributed by Vogel method\n steps_azim : int\n number of points on the boundary of the disc\n\n Returns\n ---------\n xypts : (n+steps_azim) x 2 array\n the positions of vertices on evenly distributed points on disc\n \"\"\"\n # steps_azim is the azimuthal NUMBER of steps of the mesh\n # ----> NOT the step size/length\n # Note! The R value is INCLUSIVE!!\n\n # spiral pattern of points using Vogel's method--> Golden Triangles\n # The radius of the ith point is rho_i=R*sqrt(i/n)\n # n = 256\n radius = R * np.sqrt(np.arange(n) / float(n))\n golden_angle = np.pi * (3 - np.sqrt(5))\n theta = golden_angle * np.arange(n)\n\n points = np.zeros((n, 2))\n points[:, 0] = np.cos(theta)\n points[:, 1] = np.sin(theta)\n points *= radius.reshape((n, 1))\n # plt.plot(points[:,0],points[:,1],'b.')\n\n vals = np.array([[R * np.cos(ii * 2 * pi / steps_azim), R * np.sin(ii * 2 * pi / steps_azim)] for ii in\n np.arange(steps_azim)]) # circle points\n vals = np.reshape(vals, [-1, 2]) # [steps**2,2])\n\n xypts = np.vstack((points, vals))\n return xypts\n\n\ndef generate_diskmesh_vogelgap(R, n, steps_azim, fraction_edge_gap):\n \"\"\"Create an array of evenly spaced points in 2D on a disc using Vogel's method, but only up to a smaller\n radius than the radius of the circle of points with angular density 2pi/steps_azim\n\n Parameters\n ----------\n R : float\n radius of the disc\n n : int\n number of points within the disc, distributed by Vogel method\n steps_azim : int\n number of points on the boundary of the disc\n fraction_edge_gap : float\n difference between Vogel radius and circle radius, as a fraction of radius R.\n\n Returns\n ---------\n xypts : (n+steps_azim) x 2 array\n the positions of vertices on evenly distributed points on disc\n \"\"\"\n # This includes the Vogel method but only up to a smaller radius than the\n # radius of the circle of points with angular density 2pi/steps_azim. The\n # difference between Vogel radius and circle radius is given by\n # fraction_edge_gap, as a fraction of radius R.\n # steps_azim is the azimuthal NUMBER of steps of the mesh\n # ----> NOT the step size/length\n # Note! The R value is INCLUSIVE!!\n\n # spiral pattern of points using Vogel's method--> Golden Triangles\n # The radius of the ith point is rho_i=R*sqrt(i/n)\n # n = 256\n radius = R * (1 - fraction_edge_gap) * np.sqrt(np.arange(n) / float(n))\n golden_angle = np.pi * (3 - np.sqrt(5))\n theta = golden_angle * np.arange(n)\n\n points = np.zeros((n, 2))\n points[:, 0] = np.cos(theta)\n points[:, 1] = np.sin(theta)\n points *= radius.reshape((n, 1))\n # plt.plot(points[:,0],points[:,1],'b.')\n\n vals = np.array([[R * np.cos(ii * 2 * np.pi / steps_azim), R * np.sin(ii * 2 * np.pi / steps_azim)] for ii in\n np.arange(steps_azim)]) # circle points\n vals = np.reshape(vals, [-1, 2]) # [steps**2,2])\n\n xypts = np.vstack((points, vals))\n return xypts\n\n\ndef generate_lattice(image_shape, lattice_vectors):\n \"\"\"Creates lattice of positions from arbitrary lattice vectors.\n\n Parameters\n ----------\n image_shape : 2 x 1 list (eg image_shape=[L,L])\n Width and height of the lattice (square)\n lattice_vectors : 2 x 1 list of 2 x 1 lists (eg [[1 ,0 ],[0.5,sqrt(3)/2 ]])\n The two lattice vectors defining the unit cell.\n\n Returns\n ----------\n xy : array of dimension nx2\n 2D lattice of points (positions x,y)\n \"\"\"\n # Generate lattice that lives in\n # center_pix = np.array(image_shape) // 2\n # Get the lower limit on the cell size.\n dx_cell = max(abs(lattice_vectors[0][0]), abs(lattice_vectors[1][0]))\n dy_cell = max(abs(lattice_vectors[0][1]), abs(lattice_vectors[1][1]))\n # Get an over estimate of how many cells across and up.\n nx = 2 * image_shape[0] // dx_cell\n ny = 2 * image_shape[1] // dy_cell\n # Generate a square lattice, with too many points.\n # Here I generate a factor of 8 more points than I need, which ensures\n # coverage for highly sheared lattices. If your lattice is not highly\n # sheared, than you can generate fewer points.\n x_sq = np.arange(-nx, nx, dtype=float)\n y_sq = np.arange(-ny, nx, dtype=float)\n x_sq.shape = x_sq.shape + (1,)\n y_sq.shape = (1,) + y_sq.shape\n # Now shear the whole thing using the lattice vectors\n # transpose so that row is along x axis\n x_lattice = lattice_vectors[0][1] * x_sq + lattice_vectors[1][1] * y_sq\n y_lattice = lattice_vectors[0][0] * x_sq + lattice_vectors[1][0] * y_sq\n # Trim to fit in box.\n mask = ((x_lattice < image_shape[0] / 2.0)\n & (x_lattice > -image_shape[0] / 2.0))\n mask = mask & ((y_lattice < image_shape[1] / 2.0)\n & (y_lattice > -image_shape[1] / 2.0))\n x_lattice = x_lattice[mask]\n y_lattice = y_lattice[mask]\n # Make output compatible with original version.\n out = np.empty((len(x_lattice), 2), dtype=float)\n out[:, 0] = y_lattice\n out[:, 1] = x_lattice\n i = np.lexsort((out[:, 1], out[:, 0])) # sort primarily by x, then y\n xy = out[i]\n return xy\n\n\ndef arrow_mesh(x, y, z, dx, dy, dz, rotation_angle=0, tail_width=0.2, head_width=0.5, head_length=0.3, overhang=0.0):\n \"\"\"Creates a mesh arrow (pts,tri) pointing from x,y,z to x+dx,y+dy,z+dz.\n\n Parameters\n ----------\n x,y,z : floats\n x,y,z position of the tail of the arrow\n dx,dy,dz : floats\n signed distances in x,y,z from the tail to the head of the arrow\n rotation_angle : float\n angle in radians by which arrow rotated about its long axis\n tail_width : float\n width of the arrow tail as fraction of arrow length (tail_width = |(1)-(7)| =|(2)-(6)| )\n head_width : float\n width of the arrow head as fraction of arrow length (head_width = |(3)-(5)|)\n head_length : float\n fraction of the arrow length that is part of the arrow head\n overhang : float\n fraction of the arrow length by which the pointy corners of the head extend behind the head\n \"\"\"\n # 2|\\\n # 0 _________| \\\n # | 1 \\ 3\n # |_________ /\n # 6 5 | /\n # 4 |/\n #\n # Begin by making arrow in the xy plane, with middle of tail at xy, pointing in x dir\n d = np.sqrt(dx ** 2 + dy ** 2 + dz ** 2)\n pts0 = np.array([[0, d * tail_width * 0.5, 0], \\\n [d * (1. - head_length), d * tail_width * 0.5, 0], \\\n [d * (1. - head_length - overhang), d * head_width * 0.5, 0], \\\n [d, 0, 0], \\\n [d * (1. - head_length - overhang), -d * head_width * 0.5, 0], \\\n [d * (1. - head_length), -d * tail_width * 0.5, 0], \\\n [0, -d * tail_width * 0.5, 0] \\\n ])\n # Rotate about axis by rotation_angle\n pts = rotate_vector_xaxis3D(pts0, rotation_angle)\n # Rotate in xy plane\n theta = np.arctan2(dz, np.sqrt(dx ** 2 + dy ** 2))\n phi = np.arctan2(dy, dx)\n pts = rotate_vector_yaxis3D(pts, -theta)\n pts = rotate_vector_zaxis3D(pts, phi)\n pts += np.array([x, y, z])\n tri = np.array([[0, 6, 1], [6, 5, 1], \\\n [3, 2, 1], [4, 3, 5], [3, 1, 5]])\n return pts, tri\n\n\ndef rotate_vector_2D(vec, phi):\n \"\"\"Rotate vector by angle phi in xy plane\"\"\"\n if vec.ndim > 1:\n '''rot is a list of multiple vectors or an array of length >1'''\n rot = np.array([[x * np.cos(phi) - y * np.sin(phi),\n y * np.sin(phi) + y * np.cos(phi)] for x, y in vec])\n else:\n rot = np.array([vec[0] * np.cos(phi) - vec[1] * np.sin(phi),\n vec[0] * np.sin(phi) + vec[1] * np.cos(phi)])\n return rot\n\n\n####################################\n# Rotations of arrays\n####################################\ndef rotate_vector_xaxis3D(vec, phi):\n \"\"\"Rotate 3D vector(s) by angle phi about x axis --> rotates away from the y axis\"\"\"\n if vec.ndim > 1:\n rot = np.array([[x,\n y * np.cos(phi) - z * np.sin(phi),\n y * np.sin(phi) + z * np.cos(phi)] for x, y, z in vec])\n else:\n rot = np.array([vec[0],\n vec[1] * np.cos(phi) - vec[2] * np.sin(phi),\n vec[1] * np.sin(phi) + vec[2] * np.cos(phi)])\n return rot\n\n\ndef rotate_vector_yaxis3D(vec, phi):\n \"\"\"Rotate 3D vector(s) by angle phi about y axis (in xz plane) --> rotates away from the z axis\"\"\"\n if vec.ndim > 1:\n rot = np.array([[x * np.cos(phi) + z * np.sin(phi),\n y,\n -x * np.sin(phi) + z * np.cos(phi)] for x, y, z in vec])\n else:\n rot = np.array([vec[0] * np.cos(phi) + vec[2] * np.sin(phi),\n vec[1],\n -vec[0] * np.sin(phi) + vec[2] * np.cos(phi)])\n return rot\n\n\ndef rotate_vector_zaxis3D(vec, phi):\n \"\"\"Rotate vector by angle phi in xy plane, keeping z value fixed\"\"\"\n if vec.ndim > 1:\n rot = np.array([[x * np.cos(phi) - y * np.sin(phi), \\\n x * np.sin(phi) + y * np.cos(phi), z] for x, y, z in vec])\n else:\n rot = np.array([vec[0] * np.cos(phi) - vec[1] * np.sin(phi), \\\n vec[0] * np.sin(phi) + vec[1] * np.cos(phi), vec[2]])\n return rot\n\n\n##########################################\n# 5. Data Handling\n##########################################\ndef bond_length_list(xy, BL):\n \"\"\"Convert bond list (#bonds x 2) to bond length list (#bonds x 1) for lattice of bonded points.\n\n Parameters\n ----------\n xy : array of dimension nx2\n 2D lattice of points (positions x,y)\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points.\n\n Returns\n ----------\n bL : array of dimension #bonds x 1\n Bond lengths, in order of BL (lowercase denotes 1D array)\n \"\"\"\n bL = np.array(\n [np.sqrt(np.dot(xy[BL[i, 1], :] - xy[BL[i, 0], :], xy[BL[i, 1], :] - xy[BL[i, 0], :])) for i in range(len(BL))])\n return bL\n\n\ndef tensor_polar2cartesian2D(Mrr, Mrt, Mtr, Mtt, x, y):\n \"\"\"converts a Polar tensor into a Cartesian one\n\n Parameters\n ----------\n Mrr, Mtt, Mrt, Mtr : N x 1 arrays\n radial, azimuthal, and shear components of the tensor M\n x : N x 1 array\n the x positions of the points on which M is defined\n y : N x 1 array\n the y positions of the points on which M is defined\n\n Returns\n ----------\n Mxx,Mxy,Myx,Myy : N x 1 arrays\n the cartesian components\n \"\"\"\n A = Mrr;\n B = Mrt;\n C = Mtr;\n D = Mtt;\n theta = np.arctan2(y, x);\n ct = np.cos(theta);\n st = np.sin(theta);\n\n Mxx = ct * (A * ct - B * st) - st * (C * ct - D * st);\n Mxy = ct * (B * ct + A * st) - st * (D * ct + C * st);\n Myx = st * (A * ct - B * st) + ct * (C * ct - D * st);\n Myy = st * (B * ct + A * st) + ct * (D * ct + C * st);\n return Mxx, Mxy, Myx, Myy\n\n\ndef tensor_cartesian2polar2D(Mxx, Mxy, Myx, Myy, x, y):\n \"\"\"converts a Cartesian tensor into a Polar one\n\n Parameters\n ----------\n Mxx,Mxy,Myx,Myy : N x 1 arrays\n cartesian components of the tensor M\n x : N x 1 array\n the x positions of the points on which M is defined\n y : N x 1 array\n the y positions of the points on which M is defined\n\n Returns\n ----------\n Mrr, Mrt, Mtr, Mtt : N x 1 arrays\n radial, shear, and azimuthal components of the tensor M\n \"\"\"\n A = Mxx;\n B = Mxy;\n C = Myx;\n D = Myy;\n theta = np.arctan2(y, x);\n ct = np.cos(theta);\n st = np.sin(theta);\n\n Mrr = A * ct ** 2 + (B + C) * ct * st + D * st ** 2;\n Mrt = B * ct ** 2 + (-A + D) * ct * st - C * st ** 2;\n Mtr = C * ct ** 2 + (-A + D) * ct * st - B * st ** 2;\n Mtt = D * ct ** 2 - (B + C) * ct * st + A * st ** 2;\n return Mrr, Mrt, Mtr, Mtt\n\n\ndef vectorfield_cartesian2polar(ux, uy, x, y):\n \"\"\"converts a Cartesian vector field into a Polar one\n\n Parameters\n ----------\n ux,uy : N x 1 arrays\n vector field values along x and y (cartesian)\n x : N x 1 array\n the x positions of the points on which u is defined\n y : N x 1 array\n the y positions of the points on which u is defined\n\n Returns\n ----------\n ur, ut : N x 1 arrays\n radial and azimuthal values of the vector field\n \"\"\"\n theta = np.arctan2(y, x)\n ur = ux * np.cos(theta) + uy * np.sin(theta)\n ut = -ux * np.sin(theta) + uy * np.cos(theta)\n return ur, ut\n\n\ndef vectorfield_polar2cartesian(ur, ut, x, y):\n \"\"\"converts a Polar vector field into a Cartesian one\n\n Parameters\n ----------\n ur,ut : N x 1 arrays\n vector field values along r and theta (polar)\n x : N x 1 array\n the x positions of the points on which u is defined\n y : N x 1 array\n the y positions of the points on which u is defined\n\n Returns\n ----------\n ux, uy : N x 1 arrays\n cartesian values of the vector field\n \"\"\"\n theta = np.arctan2(y, x)\n beta = theta + np.arctan2(ut, ur)\n umag = np.sqrt(ur ** 2 + ut ** 2)\n ux = umag * np.cos(beta)\n uy = umag * np.sin(beta)\n return ux, uy\n\n\ndef flip_orientations_tris(TRI, xyz):\n \"\"\"Flip triangulations such that their normals are facing upward\"\"\"\n for ii in range(len(TRI)):\n V = xyz[TRI[ii, 1], :] - xyz[TRI[ii, 0], :]\n W = xyz[TRI[ii, 2], :] - xyz[TRI[ii, 0], :]\n Nz = V[0] * W[1] - V[1] * W[0]\n if Nz < 0:\n temp = TRI[ii, 2]\n TRI[ii, 2] = TRI[ii, 0]\n TRI[ii, 0] = temp\n return TRI\n\n\ndef flip_all_orientations_tris(TRI):\n \"\"\"Flip triangulations such that their normals are inverted\"\"\"\n temp = copy.deepcopy(TRI[:, 2])\n TRI[:, 2] = TRI[:, 0]\n TRI[:, 0] = temp\n return TRI\n\n\ndef Tri2BL(TRI):\n \"\"\"Convert triangulation array (#tris x 3) to bond list (#bonds x 2) for 2D lattice of triangulated points.\n\n Parameters\n ----------\n TRI : array of dimension #tris x 3\n Each row contains indices of the 3 points lying at the vertices of the tri.\n\n Returns\n ----------\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points\"\"\"\n BL1 = TRI[:, [0, 1]]\n BL2 = np.vstack((BL1, TRI[:, [0, 2]]))\n BL3 = np.vstack((BL2, TRI[:, [1, 2]]))\n BLt = np.sort(BL3, axis=1)\n BL = unique_rows(BLt)\n return BL\n\n\ndef BL2TRI(BL):\n \"\"\"Convert bond list (#bonds x 2) to Triangulation array (#tris x 3) (using dictionaries for speedup and scaling)\n\n Parameters\n ----------\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points\n\n Returns\n ----------\n TRI : array of dimension #tris x 3\n Each row contains indices of the 3 points lying at the vertices of the tri.\n \"\"\"\n d = {}\n tri = np.zeros((len(BL), 3), dtype=np.int)\n c = 0\n for i in BL:\n if (i[0] > i[1]):\n t = i[0]\n i[0] = i[1]\n i[1] = t\n if (i[0] in d):\n d[i[0]].append(i[1])\n else:\n d[i[0]] = [i[1]]\n for key in d:\n for n in d[key]:\n for n2 in d[key]:\n if (n > n2) or n not in d:\n continue\n if (n2 in d[n]):\n tri[c, :] = [key, n, n2]\n c += 1\n return tri[0:c]\n\n\ndef BL2NLandKL(BL, nn=6):\n \"\"\"Convert bond list (#bonds x 2) to neighbor list (#pts x max# neighbors) for lattice of bonded points. Also returns KL: ones where there is a bond and zero where there is not.\n (Even if you just want NL from BL, you have to compute KL anyway.)\n\n Parameters\n ----------\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points\n nn : int\n maximum number of neighbors\n\n Returns\n ----------\n NL : array of dimension #pts x max(#neighbors)\n The ith row contains indices for the neighbors for the ith point.\n KL : array of dimension #pts x (max number of neighbors)\n Spring constant list, where 1 corresponds to a true connection while 0 signifies that there is not a connection.\n \"\"\"\n NL = np.zeros((max(BL.ravel()) + 1, nn))\n KL = np.zeros((max(BL.ravel()) + 1, nn))\n for row in BL:\n col = np.where(KL[row[0], :] == 0)[0][0]\n NL[row[0], col] = row[1]\n KL[row[0], col] = 1\n col = np.where(KL[row[1], :] == 0)[0][0]\n NL[row[1], col] = row[0]\n KL[row[1], col] = 1\n return NL, KL\n\n\ndef bond_length_list(xy, BL):\n \"\"\"Convert neighbor list to bond list (#bonds x 2) for lattice of bonded points.\n\n Parameters\n ----------\n xy : array of dimension nx2\n 2D lattice of points (positions x,y)\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points.\n\n Returns\n ----------\n bL : array of dimension #bonds x 1\n Bond lengths, in order of BL (lowercase denotes 1D array)\n \"\"\"\n bL = np.array(\n [np.sqrt(np.dot(xy[BL[i, 1], :] - xy[BL[i, 0], :], xy[BL[i, 1], :] - xy[BL[i, 0], :])) for i in range(len(BL))])\n return bL\n\n\ndef cut_bonds(BL, xy, thres):\n \"\"\"Cuts bonds with lengths greater than threshold value.\n\n Parameters\n ----------\n BL : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points\n xy : array of dimension nx2\n 2D lattice of points (positions x,y)\n thres : float\n cutoff length between points\n\n Returns\n ----------\n BLtrim : array of dimension #bonds x 2\n Each row is a bond and contains indices of connected points, contains no bonds longer than thres\"\"\"\n i2cut = (xy[BL[:, 0], 0] - xy[BL[:, 1], 0]) ** 2 + (xy[BL[:, 0], 1] - xy[BL[:, 1], 1]) ** 2 < thres ** 2\n BLtrim = BL[i2cut]\n return BLtrim\n\n\ndef memberIDs(a, b):\n \"\"\"Return array (c) of indices where elements of a are members of b.\n If ith a elem is member of b, ith elem of c is index of b where a[i] = b[index].\n If ith a elem is not a member of b, ith element of c is 'None'.\n The speed is O(len(a)+len(b)), so it's fast.\n \"\"\"\n bind = {}\n for i, elt in enumerate(b):\n if elt not in bind:\n bind[elt] = i\n return [bind.get(itm, None) for itm in a] # None can be replaced by any other \"not in b\" value\n\n\ndef ismember(a, b):\n \"\"\"Return logical array (c) testing where elements of a are members of b.\n The speed is O(len(a)+len(b)), so it's fast.\n \"\"\"\n bind = {}\n for i, elt in enumerate(b):\n if elt not in bind:\n bind[elt] = True\n return np.array([bind.get(itm, False) for itm in a]) # None can be replaced by any other \"not in b\" value\n\n\ndef unique_rows(a):\n \"\"\"Clean up an array such that all its rows are unique.\n \"\"\"\n order = np.lexsort(a.T)\n a = a[order]\n diff = np.diff(a, axis=0)\n ui = np.ones(len(a), 'bool')\n ui[1:] = (diff != 0).any(axis=1)\n return a[ui]\n\n\ndef do_kdtree(combined_x_y_arrays, points, k=1):\n \"\"\"Using kd tree, return indices of nearest points and their distances\n\n Parameters\n ----------\n combined_x_y_arrays : NxD array\n the reference points of which to find nearest ones to 'points' data\n points : MxD array\n data points, finds nearest elements in combined_x_y_arrays to these points.\n\n Returns\n ----------\n indices : Mx1 array\n indices of xyref that are nearest to points\n dist : Mx1 array\n the distances of xyref[indices] from points\n \"\"\"\n # usage--> find nearest neighboring point in combined_x_y_arrays for\n # each point in points.\n # Note: usage for KDTree.query(x, k=1, eps=0, p=2, distance_upper_bound=inf)[source]\n mytree = scipy.spatial.cKDTree(combined_x_y_arrays)\n dist, indexes = mytree.query(points, k=k)\n return indexes, dist\n\n\ndef lookupZ(lookupXYZ, xy_pts):\n \"\"\"Using kd tree, convert array of xy points to xyz points by lookup up Z values, (based on proximity of xy pts).\n See also lookupZ_avgN().\n\n Parameters\n ----------\n lookupXYZ : Nx3 array\n the reference points of which to find nearest ones to 'points' data\n xy_pts : MxD array with D>=2\n data points, finds nearest elements in combined_x_y_arrays to these points.\n\n Returns\n ----------\n outXYZpts : Nx3 array\n x,y are from xy_pts, but z values from lookupXYZ\n \"\"\"\n # print 'xy_pts = ', xy_pts\n # print 'with shape ', np.shape(xy_pts)\n Xtemp = lookupXYZ[:, 0]\n Ytemp = lookupXYZ[:, 1]\n lookupXY = np.dstack([Xtemp.ravel(), Ytemp.ravel()])[0]\n # Find addZ, the amount to raise the xy_pts in z.\n addZind, distance = do_kdtree(lookupXY, xy_pts)\n addZ = lookupXYZ[addZind, 2]\n # print 'addZ = ', addZ\n # print 'with shape ', np.shape(addZ.ravel())\n x = np.ravel(xy_pts[:, 0])\n y = np.ravel(xy_pts[:, 1])\n # print 'shape of x = ', np.shape(x.ravel())\n outXYZpts = np.dstack([x.ravel(), y.ravel(), addZ.ravel()])[0]\n # View output\n # fig = plt.figure(figsize=(14,6))\n # ax = fig.add_subplot(1, 2, 1, projection='3d')\n # scatter(outXYZpts[:,0],outXYZpts[:,1],outXYZpts[:,2],c='b')\n\n return outXYZpts\n\n\ndef lookupZ_avgN(lookupXYZ, xy_pts, N=5, method='median'):\n \"\"\"Using kd tree, return array of values for xy_pts given lookupXYZ based on near neighbors.\n Average over N neighbors for the returned value.\n\n Parameters\n ----------\n lookupXYZ : Nx3 array\n the reference points of which to find nearest ones to 'points' data\n xy_pts : MxD array with D>=2\n data points, finds nearest elements in combined_x_y_arrays to these points.\n N : int\n number of nearby particles over which to average in the lookup evaluation\n\n Returns\n ----------\n outXYZpts : Nx3 array\n x,y are from xy_pts, but z values from lookupXYZ\n \"\"\"\n # print 'xy_pts = ', xy_pts\n # print 'with shape ', np.shape(xy_pts)\n Xtemp = lookupXYZ[:, 0]\n Ytemp = lookupXYZ[:, 1]\n lookupXY = np.dstack([Xtemp.ravel(), Ytemp.ravel()])[0]\n # Find addZ, the amount to raise the xy_pts in z.\n addZind, distance = do_kdtree(lookupXY, xy_pts, k=N)\n # print 'addZind =', addZind\n if isinstance(lookupXYZ, np.ma.core.MaskedArray):\n lookupXYZ = lookupXYZ.data\n if method == 'median':\n addZ = np.array([[np.median(lookupXYZ[addZind[ii, :], 2])] for ii in range(len(addZind))])\n elif method == 'mean':\n addZ = np.array([[np.nanmean(lookupXYZ[addZind[ii, :], 2])] for ii in range(len(addZind))])\n\n # print 'addZ = ', addZ\n # print 'with shape ', np.shape(addZ.ravel())\n x = np.ravel(xy_pts[:, 0])\n y = np.ravel(xy_pts[:, 1])\n # print 'shape of x = ', np.shape(x.ravel())\n outXYZpts = np.dstack([x.ravel(), y.ravel(), addZ.ravel()])[0]\n # View output\n # fig = plt.figure(figsize=(14,6))\n # ax = fig.add_subplot(1, 2, 1, projection='3d')\n # scatter(outXYZpts[:,0],outXYZpts[:,1],outXYZpts[:,2],c='b')\n\n return outXYZpts\n\n\ndef lookupZ_singlept(lookupXYZ, xy):\n \"\"\"Using kd tree, return indices of nearest points and their distances using 2D positions.\n\n Parameters\n ----------\n lookupXYZ : Nx3 array\n the reference points of which to find nearest ones to 'points' data\n xy : list of two floats\n data point, to find nearest element in lookupXYZ\n\n Returns\n ----------\n addZ : float\n z value from lookupXYZ\n \"\"\"\n Xtemp = lookupXYZ[:, 0]\n Ytemp = lookupXYZ[:, 1]\n lookupXY = np.dstack([Xtemp.ravel(), Ytemp.ravel()])[0]\n # Find addZ, the amount to raise the xy_pts in z.\n addZind, distance = do_kdtree(lookupXY, np.array([xy[0], xy[1]]))\n addZ = lookupXYZ[addZind, 2]\n return addZ\n\ndef is_number(s):\n \"\"\"Check if a string can be represented as a number; works for floats\"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\ndef round_thres(a, MinClip):\n \"\"\"Round a number to the nearest multiple of MinCLip\"\"\"\n return round(float(a) / MinClip) * MinClip\n\n\ndef round_thres_numpy(a, MinClip):\n \"\"\"Round an array of values to the nearest multiple of MinCLip\"\"\"\n return np.round(np.array(a, dtype=float) / MinClip) * MinClip\n\n\ndef getVarFromFile(filename):\n \"\"\"Convert data in a txt file like 'x = 1.5' to a variable x defined as 1.5... this may need work\n http://stackoverflow.com/questions/924700/best-way-to-retrieve-variable-values-from-a-text-file-python-json\n \"\"\"\n import imp\n f = open(filename)\n data = imp.load_source('data', '', f)\n f.close()\n return data\n\n\n##########################################\n# 6. Loading/Interpolating Data\n##########################################\ndef nearest_gL_fit(lookupdir, beta, rho, fit_mean):\n \"\"\"Lookup Griffith length for given rho value in table, could be table based on a quadratic fit or of the mean gLs for a given rho.\n Note that for fit_mean==fit, rho = r/R, wherease for fit_mean==mean, rho = r/x0.\"\"\"\n print('looking for file:')\n print((lookupdir + fit_mean + '_rho_gLmeters_beta' + '{0:.2f}'.format(beta / np.pi).replace('.', 'p') + '*.txt'))\n gLfile = \\\n glob.glob(\n lookupdir + fit_mean + '_rho_gLmeters_beta' + '{0:.2f}'.format(beta / np.pi).replace('.', 'p') + '*.txt')[\n 0]\n rhoV, gLV, trsh = np.loadtxt(gLfile, delimiter=',', skiprows=1, usecols=(0, 1, 2), unpack=True)\n diff = abs(rhoV - rho)\n IND = np.where(diff == diff.min())\n return gLV[IND][0]\n\n\ndef constP_gL_fit(lookupdir, alph):\n \"\"\"Lookup Griffith length for given aspect ratio in table of the mean gLs vs aspect ratio, returned in meters\"\"\"\n print('looking for file:')\n print((lookupdir + 'constP_means_alph_gLinches.txt'))\n gLfile = glob.glob(lookupdir + 'constP_means_alph_gLinches.txt')[0]\n alphV, gLV = np.loadtxt(gLfile, delimiter=',', skiprows=1, usecols=(0, 1), unpack=True)\n diff = abs(alphV - alph)\n IND = np.where(diff == diff.min())\n # return in meters\n return float(gLV[IND] / 39.3700787)\n\n\ndef interpol_meshgrid(x, y, z, n):\n \"\"\"Interpolate z on irregular or unordered grid data (x,y) by supplying # points along each dimension.\n Note that this does not guarantee a square mesh, if ranges of x and y differ.\n \"\"\"\n # define regular grid spatially covering input data\n xg = np.linspace(x.min(), x.max(), n)\n yg = np.linspace(y.min(), y.max(), n)\n X, Y = np.meshgrid(xg, yg)\n\n # interpolate Z values on defined grid\n Z = griddata(np.vstack((x.flatten(), y.flatten())).T, np.vstack(z.flatten()), (X, Y), method='cubic').reshape(\n X.shape)\n # mask nan values, so they will not appear on plot\n Zm = np.ma.masked_where(np.isnan(Z), Z)\n return X, Y, Zm\n\n\ndef interpolate_onto_mesh(x, y, z, X, Y, mask=True):\n \"\"\"Interpolate new data x,y,z onto grid data X,Y\"\"\"\n # interpolate Z values on defined grid\n Z = griddata(np.vstack((x.flatten(), y.flatten())).T, np.vstack(z.flatten()), (X, Y), method='cubic').reshape(\n X.shape)\n # mask nan values, so they will not appear on plot\n if mask:\n Zm = np.ma.masked_where(np.isnan(Z), Z)\n else:\n Zm = Z\n return Zm\n\n\n##########################################\n# Files, Folders, and Directory Structure\n##########################################\ndef prepdir(dir):\n \"\"\"Make sure that the (string) variable dir ends with the character '/'.\n This prepares the string dir to be an output directory.\"\"\"\n if dir[-1] == '/':\n return dir\n else:\n return dir + '/'\n\n\ndef ensure_dir(f):\n \"\"\"Check if directory exists, and make it if not.\n\n Parameters\n ----------\n f : string\n directory path to ensure\n\n Returns\n ----------\n \"\"\"\n f = prepdir(f)\n d = os.path.dirname(f)\n if not os.path.exists(d):\n os.makedirs(d)\n\n\ndef find_dir_with_name(name, searchdir):\n \"\"\"Return a path or list of paths to directories which match the string 'name' (can have wildcards) in searchdir.\n Note that this function returns names with a trailing back slash (/)\"\"\"\n if name == '':\n '''no name given, no name returned'''\n return []\n else:\n possible_dirs = glob.glob(searchdir + name)\n okdirs = [os.path.isdir(possible_dir) for possible_dir in possible_dirs]\n out = [possible_dirs[i] + '/' for i in range(len(okdirs)) if okdirs[i]]\n if len(out) == 1:\n return out[0]\n else:\n return out\n\n\ndef find_subdirs(string, maindir):\n \"\"\"Find subdir(s) matching string, in maindir. Return subdirs as list.\n If there are multiple matching subdirectories, returns list of strings.\n If there are no matches, returns empty list.\n \"\"\"\n maindir = prepdir(maindir)\n contents = sorted(glob.glob(maindir + string))\n is_subdir = [os.path.isdir(ii) for ii in contents]\n\n if len(is_subdir) == 0:\n print('WARNING! Found no matching subdirectory: returning empty list')\n return is_subdir\n else:\n subdirs = [prepdir(contents[ii]) for ii in np.where(is_subdir)[0].tolist()]\n\n return subdirs\n\n\ndef find_subsubdirectory(string, maindir):\n \"\"\"Find subsubdir matching string, in maindir. Return subdir and subsubdir names.\n If there are multiple matching subdirectories, returns list of strings.\n If there are no matches, returns empty lists.\n \"\"\"\n maindir = prepdir(maindir)\n # print 'maindir = ', maindir\n contents = glob.glob(maindir + '*')\n is_subdir = [os.path.isdir(ii) for ii in contents]\n\n if len(is_subdir) == 0:\n print('WARNING! Found no matching subdirectory: returning empty list')\n return is_subdir, is_subdir\n else:\n # print 'contents = ', contents\n subdirs = [contents[ii] for ii in np.where(is_subdir)[0].tolist()]\n # print 'subdirs = ', subdirs\n\n found = False\n subsubdir = []\n for ii in subdirs:\n # print 'ii =', ii\n print('prepdir(ii)+string = ', prepdir(ii) + string)\n subcontents = glob.glob(prepdir(ii) + string)\n # print 'glob.glob(',prepdir(ii),string,') = ',subcontents\n is_subsubdir = [os.path.isdir(jj) for jj in subcontents]\n subsubdirs = [subcontents[jj] for jj in np.where(is_subsubdir)[0].tolist()]\n # print 'subsubdirs = ', subsubdirs\n if len(subsubdirs) > 0:\n if found == False:\n if len(subsubdirs) == 1:\n subdir = prepdir(ii)\n subsubdir = prepdir(subsubdirs[0])\n # print 'adding first subdir = ', subdir\n found = True\n elif len(subsubdirs) > 1:\n subdir = [prepdir(ii)] * len(subsubdirs)\n # print 'adding first few subdir = ', subdir\n found = True\n subsubdir = [0] * len(subsubdirs)\n for j in range(len(subsubdirs)):\n subsubdir[j] = prepdir(subsubdirs[j])\n else:\n # Since already found one, add another\n # print ' Found more subsubdirs'\n # print 'subdir = ', subdir\n\n # Add subdir to list\n if isinstance(subdir, str):\n subdir = [subdir, prepdir(ii)]\n print('adding second to subdir = ', subdir)\n if len(subsubdirs) > 1:\n for kk in range(1, len(subsubdirs)):\n subdir.append(prepdir(ii))\n print('adding second (multiple) to subdir = ', subdir)\n else:\n print('subsubdirs')\n for kk in range(1, len(subsubdirs)):\n subdir.append(prepdir(ii))\n # print 'subsubdirs = ', subsubdirs\n print('adding more to subdir = ', subdir)\n # Add subsubdir to list\n for jj in subsubdirs:\n if isinstance(subsubdir, str):\n subsubdir = [subsubdir, prepdir(jj)]\n print('adding second to subsubdirs = ', subsubdir)\n else:\n subsubdir.append(prepdir(jj))\n print('adding more to subsubdirs = ', subsubdir)\n\n if found:\n return subdir, subsubdir\n else:\n return '', ''\n\n\n##########################################\n# Specific Geometric Setups\n##########################################\n\n##########################################\n# A. Inclined Crack in Uniaxial loading\n##########################################\n\ndef ICUL_kink_angle(beta):\n \"\"\"Compute kink angle for an Inclined Crack in a Uniaxially Loaded plate (ICUL)\"\"\"\n eta = np.cos(beta) / np.sin(beta)\n kink = -2 * np.arctan(2 * eta / (1 + np.sqrt(1 + 8. * eta ** 2)))\n return kink\n\n\n##########################################\n# B. Quenched Glass Plate (QGP)\n##########################################\n\ndef Z_Ttube_approx(x, y, decayL=0.2, DT=1.0, P=7.9, coldL=0.0, totLen=0.12, minY=0.0, L=0.12,\n polyorder='Quartic4_2xW'):\n \"\"\"Project x,y pts to surface of cylinder which narrows in a manner that approximates the curvature\n distribution of the glass plate in the limit of one radius of curvature (that of the tube) nearly constant.\n Some arguments are required for maximum efficiency, such as totLen = max(y)-min(y).\n\n Parameters\n ----------\n decayL : fraction of L that is used for decay\n totLen : height of sample, could be 4*R, for instance\n L : 2*R --> width, also radius of cylinder in cold region\n\n \"\"\"\n # First do zi and pi\n z0 = np.amin(np.dstack((L * np.ones(len(x)), L - L * DT * (1 - np.exp(-P * (y - minY - coldL * totLen)))))[0],\n axis=1)\n cL = coldL * totLen\n dL = decayL * L\n if polyorder == 'Quartic4_2xW':\n # negative y inds\n zi = y < minY + cL - dL\n ni = np.logical_and(y < minY + cL + dL, y > minY + cL - dL)\n pi = y > minY + cL + dL\n # print 'len(y)=', len(y)\n # print zi\n # print 'len(zi)=', np.where(zi)\n # print ni\n # print 'len(ni)=', len(np.where(ni))\n # print pi\n # print 'len(pi)=', len(np.where(pi==True))\n # Replace Heaviside with 3-7th order polynomial\n d = dL\n A = - np.exp(-P * d) * DT * L * (-105. +\n 105. * np.exp(P * d) -\n 90. * P * d -\n 30. * P ** 2 * d ** 2 -\n 4. * P ** 3 * d ** 3) / (48. * d ** 4)\n B = np.exp(-P * d) * DT * L * (-42. +\n 42. * np.exp(P * d) -\n 39. * P * d -\n 14. * P ** 2 * d ** 2 -\n 2. * P ** 3 * d ** 3) / (16. * d ** 5)\n C = - np.exp(-P * d) * DT * L * (-35. +\n 35 * np.exp(P * d) -\n 34 * P * d -\n 13 * P ** 2 * d ** 2 -\n 2 * P ** 3 * d ** 3) / (32. * d ** 6)\n D = np.exp(-P * d) * DT * L * (-15. +\n 15. * np.exp(P * d) -\n 15. * P * d - 6. * P ** 2 * d ** 2 -\n P ** 3 * d ** 3) / (96. * d ** 7)\n # Offset y --> yni by dL so that effectively polynomial is funct of 2*epsilon (ie 2*decayL)\n yni = y[ni] - minY - cL + dL\n z0[\n ni] = L + A * yni ** 4 + B * yni ** 5 + C * yni ** 6 + D * yni ** 7 # Heaviside --> make this quickly decaying polynomial\n\n f = z0 * np.cos(x / z0)\n return f\n\n\ndef Z_Ttube_approx_flipy(x, y, decayL=0.2, DT=1.0, P=7.9, coldL=0.0, totLen=0.12, minY=0.0, L=0.12,\n polyorder='Quartic4_2xW'):\n \"\"\"Project x,y pts to surface of cylinder which narrows in a manner that approximates the curvature\n distribution of the glass plate in the limit of one radius of curvature (that of the tube) nearly constant.\n Some arguments are required for maximum efficiency, such as totLen = max(y)-min(y).\n\n Parameters\n ----------\n decayL : fraction of L that is used for decay\n totLen : height of sample, could be 4*R, for instance\n L : 2*R --> width, also radius of cylinder in cold region\n\n \"\"\"\n # First do zi and pi\n z0 = np.amin(np.dstack((L * np.ones(len(x)), L - L * DT * (1 - np.exp(-P * (-y + minY + coldL * totLen)))))[0],\n axis=1)\n cL = coldL * totLen\n dL = decayL * L\n if polyorder == 'Quartic4_2xW':\n # negative y inds\n zi = y < minY + cL - dL\n ni = np.logical_and(y < minY + cL + dL, y > minY + cL - dL)\n pi = y > minY + cL + dL\n # print 'len(y)=', len(y)\n # print zi\n # print 'len(zi)=', np.where(zi)\n # print ni\n # print 'len(ni)=', len(np.where(ni))\n # print pi\n # print 'len(pi)=', len(np.where(pi==True))\n # Replace Heaviside with 3-7th order polynomial\n d = dL\n A = - np.exp(-P * d) * DT * L * (-105. +\n 105. * np.exp(P * d) -\n 90. * P * d -\n 30. * P ** 2 * d ** 2 -\n 4. * P ** 3 * d ** 3) / (48. * d ** 4)\n B = np.exp(-P * d) * DT * L * (-42. +\n 42. * np.exp(P * d) -\n 39. * P * d -\n 14. * P ** 2 * d ** 2 -\n 2. * P ** 3 * d ** 3) / (16. * d ** 5)\n C = - np.exp(-P * d) * DT * L * (-35. +\n 35 * np.exp(P * d) -\n 34 * P * d -\n 13 * P ** 2 * d ** 2 -\n 2 * P ** 3 * d ** 3) / (32. * d ** 6)\n D = np.exp(-P * d) * DT * L * (-15. +\n 15. * np.exp(P * d) -\n 15. * P * d - 6. * P ** 2 * d ** 2 -\n P ** 3 * d ** 3) / (96. * d ** 7)\n # Offset y --> yni by dL so that effectively polynomial is funct of 2*epsilon (ie 2*decayL)\n yni = y[ni] - minY - cL + dL\n # Heaviside --> make this quickly decaying polynomial\n z0[ni] = L + A * yni ** 4 + B * yni ** 5 + C * yni ** 6 + D * yni ** 7\n\n f = z0 * np.cos(x / z0)\n return f\n\n\ndef Ktinterp(ylin, coldL=2.0, decayL=0.2, alph=1.0, P=7.9, Lscale=1.0, polyorder='Quartic4_2xW'):\n \"\"\"Return an interpolation of the target curvature for a temperature profile in a QGP.\n Let y=0 be the base of the strip. Usually distances are measured in units of strip halfwidth.\n\n Parameters\n ----------\n ylin : Nx1 array\n linspace over which to interpolate the curvature; must be evenly spaced\n alph : float (default = 1.0)\n coefficient of thermal expansion (overall scaling of G)\n P : float (default = 7.9)\n Peclet number = b*v/D (halfwidth x velocity / coefficient of thermal diffusion)\n Lscale : float\n Length scale of the half strip width in other units. For ex, in units of the radius of curv of a surface\n \"\"\"\n xs = sp.Symbol('xs')\n Ts = (1. - sp.exp(-P * (xs - coldL)))\n fTs = sp.lambdify(xs, Ts, 'numpy')\n dy = ylin[2] - ylin[1] # grab one of the difference values --> must all be the same\n T = fTs(ylin)\n if polyorder == 'Quartic4':\n # negative y inds\n zi = ylin < coldL\n ni = np.logical_and(ylin < coldL + decayL, ylin > coldL)\n pi = ylin > coldL + decayL\n # Replace Heaviside with 3-7th order polynomial\n d = decayL\n A = np.exp(-P * d) * (-210. + 210. * np.exp(P * d) - 90. * P * d - 15. * P ** 2 * d ** 2 - P ** 3 * d ** 3) / (\n 6. * d ** 4)\n B = - np.exp(-P * d) * (\n -168. + 168. * np.exp(P * d) - 78. * P * d - 14. * P ** 2 * d ** 2 - P ** 3 * d ** 3) / (2. * d ** 5)\n C = np.exp(-P * d) * (-140. + 140. * np.exp(P * d) - 68. * P * d - 13. * P ** 2 * d ** 2 - P ** 3 * d ** 3) / (\n 2. * d ** 6)\n D = - np.exp(-P * d) * (\n -120. + 120. * np.exp(P * d) - 60. * P * d - 12. * P ** 2 * d ** 2 - P ** 3 * d ** 3) / (6. * d ** 7)\n y = ylin[ni] - coldL\n T[ni] = A * y ** 4 + B * y ** 5 + C * y ** 6 + D * y ** 7 # Heaviside --> make this quickly decaying polynomial\n elif polyorder == 'Quartic4_2xW':\n # negative y inds\n zi = ylin < coldL - decayL\n ni = np.logical_and(ylin < coldL + decayL, ylin > coldL - decayL)\n pi = ylin > coldL + decayL\n # Replace Heaviside with 3-7th order polynomial\n d = decayL\n A = np.exp(-P * d) * (\n -105. + 105. * np.exp(P * d) - 90. * P * d - 30. * P ** 2 * d ** 2 - 4. * P ** 3 * d ** 3) / (48. * d ** 4)\n B = - np.exp(-P * d) * (\n - 42. + 42. * np.exp(P * d) - 39. * P * d - 14. * P ** 2 * d ** 2 - 2. * P ** 3 * d ** 3) / (16. * d ** 5)\n C = np.exp(-P * d) * (\n - 35. + 35. * np.exp(P * d) - 34. * P * d - 13. * P ** 2 * d ** 2 - 2. * P ** 3 * d ** 3) / (32. * d ** 6)\n D = - np.exp(-P * d) * (\n - 15. + 15. * np.exp(P * d) - 15. * P * d - 6. * P ** 2 * d ** 2 - 1. * P ** 3 * d ** 3) / (96. * d ** 7)\n y = ylin[ni] - coldL + decayL\n T[ni] = A * y ** 4 + B * y ** 5 + C * y ** 6 + D * y ** 7 # Heaviside --> make this quickly decaying polynomial\n\n T[zi] = 0.\n Ty = np.gradient(T, dy)\n Tyy = np.gradient(Ty, dy)\n # plt.plot(ylin, T, 'k.', label='T')\n # plt.plot(ylin, Ty, 'g.', label='Ty')\n # plt.plot(ylin, Tyy, 'b.', label='Tyy')\n # plt.legend()\n # plt.title(r'$T$, $\\partial_y T$, $\\partial_y^2 T$')\n # plt.show()\n Ktinterp = scipy.interpolate.interp1d(ylin, alph * Tyy / Lscale ** 2)\n return Ktinterp\n\n\n########\n# DEMO #\n########\n\nif __name__ == \"__main__\":\n demo_arrow_mesh = False\n demo_tensor = False\n demo_vectfield = False\n demo_linept = False\n demo_gaussiancurvature = False\n demo_gaussiancurvature2 = False\n demo_Ztube = False\n demo_initial_phase_multicrack = False\n demo_GB_elastic_theory = True\n\n ptsz = 50 # size of dot for scatterplots\n from mpl_toolkits.mplot3d import Axes3D\n\n if demo_arrow_mesh:\n print('Demonstrating arrow_mesh function: makes custom arrows in 3D')\n fig = plt.figure() # figsize=plt.figaspect(1.0))\n ax = fig.gca(projection='3d')\n x = .5;\n y = .5;\n z = 1.0;\n # Make a bunch of arrows\n p0, t0 = arrow_mesh(x, y, 0, 1, 0, 0)\n p1, t1 = arrow_mesh(x, y, 0, 1 / np.sqrt(2), 0, 1 / np.sqrt(2), rotation_angle=0.0 * np.pi)\n p2, t2 = arrow_mesh(x, y, 0, 1, 0, 0, rotation_angle=0.0 * np.pi)\n p3, t3 = arrow_mesh(x, y, z, 1.0, 0.5, 0.5, rotation_angle=0.0 * np.pi, head_length=0.1)\n p4, t4 = arrow_mesh(x, y, z, 0.1, -0.5, -0.3, rotation_angle=0.25 * np.pi, overhang=0.1)\n p5, t5 = arrow_mesh(x, y, z, 0.0, 0.5, -0.5, rotation_angle=0.5 * np.pi, tail_width=0.1, overhang=0.2)\n p6, t6 = arrow_mesh(x, y, z, 0.2, 0.3, 0.5, rotation_angle=0.75 * np.pi, head_width=0.8, overhang=0.1)\n p = [p0, p1, p2, p3, p4, p5, p6]\n for ii in range(len(p)):\n pi = p[ii]\n ax.plot_trisurf(pi[:, 0], pi[:, 1], pi[:, 2], triangles=t0, cmap=cm.jet)\n ax.set_xlabel('x');\n ax.set_ylabel('y');\n ax.set_zlabel('z')\n plt.show()\n plt.close('all')\n\n if demo_tensor:\n # Show gaussian bump stress\n print(('Demonstrating calculation and easy display of Stress field for Gaussian Bump and ' +\n 'conversion to Cartesian coords'))\n x = np.linspace(-5, 5)\n y = np.linspace(-5, 5)\n xv, yv = np.meshgrid(x, y)\n x = xv.ravel()\n y = yv.ravel()\n t = np.sqrt(x ** 2 + y ** 2)\n\n alph = 0.3\n x0 = 1.5\n R = 5\n U = 0.0\n nu = 0.4\n Srr, Stt = GB_stress_uDirichlet(alph, x0, R, U, nu, t)\n Srt = np.zeros_like(Srr)\n Str = np.zeros_like(Srr)\n\n Sxx, Sxy, Syx, Syy = tensor_polar2cartesian2D(Srr, Srt, Str, Stt, x, y)\n\n # Polar version\n title0 = r'Polar Stresses for Bump: $x_0$=' + str(x0) + r' $\\alpha$=' + str(alph) + r' $U=$' + str(U) + \\\n r' $R=$' + str(R)\n pf_display_tensor(x, y, Srr, Srt, Str, Stt, r'\\sigma', title=title0, subscripts='polar', ptsz=20, axis_on=0)\n\n # Cartesian version\n title0 = r'Cartesian Stresses for Bump: $x_0$=' + str(x0) + r' $\\alpha$=' + str(alph) + r' $U=$' + str(\n U) + r' $R=$' + str(R)\n pf_display_tensor(x, y, Sxx, Sxy, Syx, Syy, r'\\sigma', title=title0, subscripts='cartesian', ptsz=20, axis_on=0)\n\n if demo_vectfield:\n # Show gaussian bump displacement in r,theta\n print('Demonstrating calculation and easy display of displacement field for Gaussian Bump and sinusoidal field')\n x = np.linspace(-5, 5)\n y = np.linspace(-5, 5)\n xv, yv = np.meshgrid(x, y)\n x = xv.ravel()\n y = yv.ravel()\n t = np.sqrt(x ** 2 + y ** 2)\n\n alph = 0.3;\n x0 = 1.5;\n R = 5;\n U = 0.02;\n nu = 0.4;\n ur = GB_displacement_uDirichlet(alph, x0, R, U, nu, t)\n ut = np.zeros_like(ur)\n\n varchar = r'u'\n title0 = r'Bump: $x_0$=' + str(x0) + r' $\\alpha$=' + str(alph) + r' $U=$' + str(U) + r' $R=$' + str(R)\n pf_display_vector(x, y, ur, ut, varchar, title=title0, subscripts='polar', ptsz=20, axis_on=0)\n\n # Show conversion from displacement field to polar coords\n print('Demonstrating conversion from cartesian displacement field to polar coords and vice versa')\n ux0 = np.cos(x)\n uy0 = np.cos(y)\n ur, ut = vectorfield_cartesian2polar(ux0, uy0, x, y)\n ux, uy = vectorfield_polar2cartesian(ur, ut, x, y)\n pf_display_4panel(x, y, ur, ut, ux, uy, r'Sine field $u_r$', title1=r'Sine field $u_\\theta$', \\\n title2=r'Sine field $u_x$', title3=r'Sine field $u_y$', ptsz=20, axis_on=0)\n\n if demo_linept:\n print('Demo: Define value based on distance from a line segment (used for creating initial state of phase for a crack).')\n print('This demo focuses on a function that does this for one point at a time (inefficient in numpy but useful in some contexts in FEniCS).')\n pts = np.random.random((4000, 2))\n W = .3\n endpt1 = [W, W]\n endpt2 = [1. - W, 1. - W]\n\n value = np.zeros_like(pts[:, 0])\n ind = 0\n for pt in pts:\n print('pt=', pt)\n x = [pt[0], pt[1]]\n print('x=', x)\n # p, d = closest_pt_on_lineseg(x,endpt1, endpt2)\n value[ind] = initphase_linear_slit(x, endpt1, endpt2, W, contour='linear')\n ind += 1\n pf_display_scalar(pts[:, 0], pts[:, 1], value, 'Phase values near a crack', ptsz=40, axis_on=0)\n plt.show()\n\n if demo_gaussiancurvature:\n print('Demo: Demonstrating gaussian_curvature_unstructured: measuring the Gaussian curvature of a surface defined by a collection of points')\n X = np.arange(-5, 5, 0.2)\n Y = np.arange(-5, 5, 0.2)\n X, Y = np.meshgrid(X, Y)\n X = X.ravel()\n Y = Y.ravel()\n R = np.sqrt(X ** 2 + Y ** 2)\n Z = np.exp(-R ** 2 / (2 * np.mean(R) ** 2))\n K, xgrid, ygrid, Kgrid = gaussian_curvature_bspline(Z, X, Y, N=100)\n fig, ax = plt.subplots(1, 2)\n color = ax[0].scatter(xgrid, ygrid, c=Kgrid, edgecolor='')\n ax[1].scatter(X, Y, c=K, edgecolor='')\n ax[0].set_title('Curvature --mesh pts')\n ax[1].set_title('Curvature --evenly spaced array pts')\n plt.colorbar(color)\n plt.show()\n print(np.shape(xgrid), np.shape(ygrid), np.shape(Kgrid))\n print(np.shape(X), np.shape(Y), np.shape(K))\n\n ## Load x,y,z from text file and compute curvature\n # fname = '/Users/npmitchell/Desktop/data_local/20151022/20151022-1120_QGP_fixbotY_Tri_N10000_dt0p000_HoR0p080_beta0p50/height.txt'\n # X,Y,Z = np.loadtxt(fname, skiprows=1, delimiter=',', unpack=True)\n # K, xgrid, ygrid, Kgrid = gaussian_curvature_unstructured(Z,X,Y,N=100)\n # fig, ax = plt.subplots(1, 2)\n # color = ax[0].scatter(xgrid,ygrid,c=Kgrid,edgecolor='')\n # ax[1].scatter(X,Y,c=K,edgecolor='')\n # plt.colorbar(color)\n # plt.show()\n # print np.shape(xgrid), np.shape(ygrid), np.shape(Kgrid)\n # print np.shape(X), np.shape(Y), np.shape(K)\n\n if demo_gaussiancurvature2:\n print('Demo: Demonstrating gaussian_curvature_unstructured2: measuring the Gaussian curvature of a surface defined by a collection of points in another way.')\n x = np.random.random((5000,)).ravel() - 0.5\n y = np.random.random((5000,)).ravel() - 0.5\n sigma = 0.8\n z = sigma * np.exp(-(x ** 2 + y ** 2) / (2. * sigma ** 2))\n\n xy = np.dstack((x, y))[0]\n xyz = np.dstack((x, y, z))[0]\n print('Triangulating...')\n Triang = Delaunay(xy)\n temp = Triang.vertices\n print('Flipping orientations...')\n Tri = flip_orientations_tris(temp, xyz)\n # proxy for avg distance between points\n dist = np.mean(np.sqrt((x[Tri[:, 0]] - x[Tri[:, 1]]) ** 2 + (y[Tri[:, 0]] - y[Tri[:, 1]]) ** 2))\n dx = dist * 0.5\n print('x=', x)\n print('y=', y)\n\n K, xgrid, ygrid, Kgrid = gaussian_curvature_unstructured(x, y, z, dx, N=3)\n print('shape(K)=', np.shape(K))\n fig, ax = plt.subplots(1, 2)\n color = ax[0].scatter(x, y, c=K, edgecolor='')\n ax[1].scatter(xgrid.ravel(), ygrid.ravel(), c=Kgrid.ravel(), edgecolor='')\n plt.colorbar(color)\n fig.text(0.5, 0.94, 'GCurvature using kd-tree and lookup', horizontalalignment='center')\n plt.show()\n\n if demo_Ztube:\n print('Demonstrating Z_Ttube_approx: the projection of xy points to a tube with a piecewise defined shape: flat, polynomial, exponential')\n Y = np.arange(-1, 1, 0.005)\n X = np.arange(-1, 1, 0.005) # np.zeros_like(Y)\n X, Y = np.meshgrid(X, Y)\n x = X.ravel()\n y = Y.ravel()\n decayL = 0.05\n DT = 0.15\n coldL = 0.5\n P = 10\n L = 1.0\n z = Z_Ttube_approx(x, y, decayL=decayL, DT=DT, P=P, coldL=coldL, totLen=2., minY=np.min(y), L=L,\n polyorder='Quartic4_2xW')\n # Compute Gaussian curvature\n fdir = '/Users/npmitchell/Dropbox/Soft_Matter/PhaseField_Modeling/FEniCS/data_out/static/'\n fname = fdir + 'Ztube_GCurvature_P' + '{0:0.2f}'.format(P) \\\n + '_DT' + '{0:0.2f}'.format(DT) \\\n + '_decayL' + '{0:0.2f}'.format(decayL) \\\n + '_coldL' + '{0:0.2f}'.format(coldL) \\\n + '_L' + '{0:0.2f}'.format(L) \\\n + '.png'\n\n K, xgrid, ygrid, Kgrid = gaussian_curvature_bspline(z, x, y, N=100)\n fig, ax = plt.subplots(1, 2)\n color = ax[0].scatter(xgrid, ygrid, c=Kgrid, edgecolor='', cmap='coolwarm', \\\n vmin=-np.max(np.abs(Kgrid)), vmax=np.max(np.abs(Kgrid)))\n ax[0].set_xlim(np.min(xgrid), np.max(xgrid))\n ax[0].set_ylim(np.min(ygrid), np.max(ygrid))\n ax[0].set_aspect('equal')\n ax[0].set_title(r'$K(x,y)$')\n\n ax[1].plot(y[np.abs(x) < 0.1], K[np.abs(x) < 0.1], '.')\n ax[1].set_xlim(-0.3, 0.3)\n ax[1].set_ylabel(r'$K$')\n ax[1].set_xlabel(r'$y$')\n ax[1].set_title(r'$K(y)$')\n titletext = pf_title_QGP('Ztube', P, DT, decayL, coldL, L)\n fig.text(0.5, 0.94, titletext, horizontalalignment='center')\n plt.colorbar(color)\n plt.savefig(fname)\n plt.show()\n\n if demo_initial_phase_multicrack:\n xy = (np.random.random((10000, 2)) - 0.5) * 2.0\n H = np.array([-0.2, 0.0, 0.3])\n Y = np.array([-0.4, 0.0, 0.4])\n beta = np.array([0.0, 0.25 * np.pi, 0.6 * np.pi])\n W = 0.1\n a = np.array([0.20, 0.05, 0.5])\n xi = 0.05\n phi = initialPhase_vec(xy, H, Y, beta, W, a, xi, fallofftype='linear')\n pf_display_scalar(xy[:, 0], xy[:, 1], phi,\n 'Phase field for some arbitrary cracks generated by initialPhase_vec()', \\\n cmap=cm.jet)\n\n # Use same function for single crack\n xi = 0.15\n H = 0.1;\n Y = 0.2;\n beta = 0.25 * np.pi;\n W = 0.3;\n a = 0.3\n phi = initialPhase_vec(xy, H, Y, beta, W, a, xi, fallofftype='polygauss')\n pf_display_scalar(xy[:, 0], xy[:, 1], phi,\n 'Demonstrating using same function for single crack: initialPhase_vec()',\n cmap=cm.jet)\n\n if demo_GB_elastic_theory:\n alph = 0.706\n x0 = 1.0\n R = 2.35\n nu = 0.45\n\n U = -0.01\n P0 = GB_P_uDirichlet(alph, x0, R, U, nu)\n print('U =', U, ' P0 = ', P0)\n U = 0.0\n P0 = GB_P_uDirichlet(alph, x0, R, U, nu)\n print('U =', U, ' P0 = ', P0)\n U = 0.012\n P0 = GB_P_uDirichlet(alph, x0, R, U, nu)\n print('U =', U, ' P0 = ', P0)\n U = 0.03\n P0 = GB_P_uDirichlet(alph, x0, R, U, nu)\n print('U =', U, ' P0 = ', P0)\n\n alph = 0.706446\n P = 0.0679\n x0 = 0.0255319\n R = 0.06\n nu = 0.45\n U0 = GB_U_from_P(alph, x0, R, P, nu)\n print('U0 = ', U0)\n print('GB_U_from_P(alph,x0,R,P,nu) =>> U = 0.0153414532992', '\\n')\n\n U0 = GB_U_from_P(alph, x0, R, 0.01, nu)\n print('P=0.01, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.02, nu)\n print('P=0.02, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.03, nu)\n print('P=0.03, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.04, nu)\n print('P=0.04, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.05, nu)\n print('P=0.05, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.06, nu)\n print('P=0.06, U0 = ', U0, '\\n')\n\n alph = 0.706446\n P = 0.0679\n x0 = 0.0255319\n R = 0.12\n nu = 0.45\n U0 = GB_U_from_P(alph, x0, R, P, nu)\n print('U0 = ', U0)\n print('GB_U_from_P(alph,x0,R,P,nu) =>> U = 0.0153414532992', '\\n')\n\n U0 = GB_U_from_P(alph, x0, R, 0.01, nu)\n print('P=0.01, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.02, nu)\n print('P=0.02, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.03, nu)\n print('P=0.03, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.04, nu)\n print('P=0.04, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.05, nu)\n print('P=0.05, U0 = ', U0)\n U0 = GB_U_from_P(alph, x0, R, 0.06, nu)\n print('P=0.06, U0 = ', U0, '\\n')\n\n alph = 0.4242640687119285\n U0 = GB_U_from_P(alph, 0.02553, 0.06, P0, nu)\n print('U0 = ', U0)\n\n alph = 0.2121320343559643\n U0 = GB_U_from_P(alph, 1., 2.35, P0, 0.5)\n print('U0 = ', U0)\n U0 = GB_U_from_P(0.000, 1., 2.35, P0, 0.5)\n print('U0 = ', U0)\n","sub_path":"pde/fenics_handling.py","file_name":"fenics_handling.py","file_ext":"py","file_size_in_byte":63586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"308611599","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n# driver = webdriver.Remote(\n # command_executor='http://127.0.0.1:4444/wd/hub',\n # desired_capabilities=DesiredCapabilities.CHROME) \n \n# driver.get(\"http://www.baidu.com\")\n# driver.find_element_by_id(\"kw\").send_keys(\"Selenium2\")\n# driver.find_element_by_id(\"su\").click()\n# driver.quit()\n\n\n# localhost windows(192.168.2.41):\n# (C:\\Users\\Han\\Anaconda3) C:\\Users\\Han\\selenium_test>java -jar selenium-server-standalone-3.11.0.jar -role hub\n\n# remote ubuntu 16(192.168.157.130):\n# han@han-virtual-machine:~$ java -jar selenium-server-standalone-3.11.0.jar -role node -port 5555 -hub http://192.168.2.41:4444/grid/register\n\nlists = {\"http://192.168.157.130:5555/wd/hub\": 'firefox'}\n\nfor host, browser in lists.items():\n print(host, browser)\n driver = webdriver.Remote(\n command_executor=host,\n desired_capabilities={\"browserName\": browser,\n \"version\": \"\",\n \"platform\": \"ANY\",})\n # C:\\Users\\Han\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\common\\desired_capabilities.py\n\n driver.get(\"http://www.baidu.com\")\n driver.find_element_by_id(\"kw\").send_keys(\"Selenium2\")\n driver.find_element_by_id(\"su\").click()\n # driver.quit()\n\n ","sub_path":"ch09/local_hub_remote_node.py","file_name":"local_hub_remote_node.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"463301571","text":"# https://zh.wikipedia.org/wiki/希尔排序\n\nfrom random import shuffle\n\n# def shell_sort(lst):\n# gap = len(lst) // 2\n# while gap > 0:\n# for startpos in range(gap):\n# _gap(lst, startpos, gap)\n# gap = gap // 2\n# return lst\n#\n#\n# def _gap(lst, startpos, gap):\n# # 希尔排序的辅助函数\n# for i in range(startpos + gap, len(lst), gap):\n# pos = i\n# current = lst[i]\n# while pos >= gap and lst[pos - gap] > current:\n# lst[pos] = lst[pos - gap]\n# pos = pos - gap\n# lst[pos] = current\n#\n# source = list(range(10))\n# shuffle(source)\n#\n# print(shell_sort(source))\n\n\ndef shell_sort(lst):\n n = len(lst)\n # 初始步长\n gap = n // 2\n while gap > 0:\n for i in range(gap, n):\n # 每个步长进行插入排序\n tmp = lst[i]\n j = i\n # 插入排序\n while j >= gap and lst[j - gap] > tmp:\n lst[j] = lst[j - gap]\n j -= gap\n lst[j] = tmp\n # 得到新的步长\n gap = gap // 2\n return lst\n\nsource = list(range(10))\nshuffle(source)\n\nprint(shell_sort(source))\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n","sub_path":"algorithm/sort/shell_sort.py","file_name":"shell_sort.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579407496","text":"## Importing important functions from FLASK package\n\nfrom flask import Flask,url_for,redirect,render_template,request,session\nfrom werkzeug.utils import secure_filename\nimport os\n\n# Importing Encryption and Decryption modules from Chaos package\nfrom Chaos import Encryption,Decryption\n\n\n\n\n# Creating a flask app\napp = Flask(__name__)\n\n\n# Defining all the constant values that are going to be used again and again\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nUPLOAD_FOLDER = os.path.join(APP_ROOT,'./static/images/')\nENCRYPTED_FOLDER = os.path.join(APP_ROOT,'./static/encrypted/')\nDECRYPTED_FOLDER = os.path.join(APP_ROOT,'./static/decrypted/')\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\n\n# Updating flask's Upload folder configuration\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n# Function to check whether the give file extension is allowed or not\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n# route for index page and function to render the index.html page\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n\n# route to process the image, password and the type of operation selected by the user in the index page form\n@app.route('/process/',methods=['POST'])\ndef process():\n #getting the name of file provided by the user\n file = request.files['file']\n # Check if the file is one of the allowed types/extensions\n if file and allowed_file(file.filename):\n # Make the filename safe, remove unsupported characters\n filename = secure_filename(file.filename)\n # Move the file form the temporal folder to\n # the upload folder we setup\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\n # encrypting the file if the user pressed the encrypt button\n if request.form['type']=='Encrypt':\n # encrypting the file provided by the user using the password provided in the form\n encrypted_image = Encryption.encrypt(os.path.join(app.config['UPLOAD_FOLDER'], filename), request.form['pass'])\n\n # renaming and saving the encrypted file in the encrypted folder\n new_filename = filename.split('.')[0] + \"_\" +'encrypted'+ \".\" + \"png\"\n encrypted_image.save(os.path.join(ENCRYPTED_FOLDER, new_filename))\n session.clear()\n return render_template('encrypted.html',filepath = url_for('static',filename=\"encrypted/\"+new_filename))\n # decrypting the file if the user pressed the decrypt button\n elif request.form['type']=='Decrypt':\n # decrypting the file provided by the user using the password in the form\n decrypted_image = Decryption.decrypt(os.path.join(app.config['UPLOAD_FOLDER'], filename),\n request.form['pass'])\n\n # renaming and saving the decrypted file in the decrypted folder\n new_filename = filename.split('.')[0] + \"_\" + 'decrypted' + \".\" + \"png\"\n decrypted_image.save(os.path.join(DECRYPTED_FOLDER, new_filename))\n\n session.clear()\n return render_template('decrypted.html', filepath=url_for('static', filename=\"decrypted/\" + new_filename))\n\n # if the user uploads a wrong file type we display a message\n else:\n return \"

      Invalid file type

      \"\n\n\n## For maintaining a session in flask app it is compulsory to set a secret key\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n\n\n## every time this file is run using the command line this function will be called\nif __name__ == '__main__':\n ## running our app using the run() function and setting debug=True for development purpose and running it at port 8000\n app.run(debug=True,port=8000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"242419205","text":"# ================= BONUS Optional Task ==================\n\n# Change your program to also handle the operation 'px' where x is a number from 10 to 90 and defines the x percentile of the list of numbers. For example:\n\n# input.txt:\n# min: 1,2,3,5,6\n# max: 1,2,3,5,6\n# avg: 1,2,3,5,6\n# p90: 1,2,3,4,5,6,7,8,9,10\n# sum: 1,2,3,5,6\n# min: 1,5,6,14,24\n# max: 2,3,9\n# p70: 1,2,3\n\n# Your output.txt should read:\n# The min of [1, 2, 3, 5, 6] is 1\n# The max of [1, 2, 3, 5, 6] is 6\n# The avg of [1, 2, 3, 5, 6] is 3.4\n# The 90th percentile of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is 9\n# The sum of [1, 2, 3, 5, 6] is 17\n# The min of [1, 5, 6, 14, 24] is 1\n# The max of [2, 3, 9] is 9\n# The 70th percentile of [1, 2, 3] is 2\n\nlineContent = list()\nstrMin = str()\nstrMax = str()\nstrAvg = str()\nstrSum = str()\nstrPcent = str()\n\noutInsert = open('output.txt', 'a')\ninFile = open('input.txt', 'r')\nfor line in inFile:\n parts = line[0:-1].split(':')\n lineContent = parts[1].split(',')\n operation = parts[0]\n if operation == str(\"min\"):\n strMin = str(\"The min of \" + str(lineContent) + \" is \" + min(lineContent) + \"\\n\")\n outInsert.write(strMin)\n elif operation == str(\"max\"):\n strMax = str(\"The max of \" + str(lineContent) + \" is \" + max(lineContent) + \"\\n\")\n outInsert.write(strMax)\n elif operation == str(\"avg\"):\n average = (sum(int(i) for i in lineContent) / len(lineContent))\n strAvg = str(\"The avg of \" + str(lineContent) + \" is \" + str(average) + \"\\n\")\n outInsert.write(strAvg)\n elif operation == str(\"sum\"):\n numSum = (sum(int(i) for i in lineContent))\n strSum = str(\"The sum of \" + str(lineContent) + \" is \" + str(numSum) + \"\\n\")\n outInsert.write(strSum)\n elif operation[0] == str(\"p\"):\n percentileNum = int(operation[1:3])\n orgList = set(lineContent)\n calcNum = (percentileNum / 100)\n percentile = int(len(lineContent) * calcNum)\n result = lineContent[(percentile - 1)]\n strPcent = str(\"The \" + str(percentileNum) + \"th percentile of \" + str(lineContent) + \" is \" + str(result) + \"\\n\")\n outInsert.write(strPcent)\n\ninFile.close()\noutInsert.close()","sub_path":"Python/input:output/Strings.py","file_name":"Strings.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"64518978","text":"from nonebot import on_command, CommandSession\nfrom nonebot import on_notice, NoticeSession\nimport config\nfrom .send_email import email\nimport re\nimport nonebot\nimport asyncio\nfrom nonebot.command.argfilter import extractors, validators\nfrom data.model import *\nfrom nonebot import get_bot\nfrom pcr.plugins.auth_tools import password_for\nfrom datetime import datetime\nfrom pcr.plugins.capture_team_rank.get_team_rank import SpiderTeamRank\n\n\n# group_id = [1104038724, 1108319335]\n@on_notice('group_increase')\nasync def welcome_new_member(session: NoticeSession):\n # 群成员增加时自动触发欢迎信息功能\n print(session.event)\n await session.send(f\"欢迎新的指挥官@{session.event.user_id}加入群喵~\\n\"\n + config.WELCOME_MESSAGE)\n\n\n@on_command('feedback', aliases=('bug反馈', '功能反馈'), only_to_me=False)\nasync def feedback_bugs(session: CommandSession):\n # 反馈bug/建议,会自动向config.py文件中配置的开发者邮箱发送email\n bug_info = session.get('bug_info', prompt=\"请问指挥官有什么bug或者新的功能需求需要反馈的喵?>_<\")\n print(session.event)\n print(bug_info)\n if re.match(r'break', bug_info) is not None:\n await session.send('会话已经终止了喵~')\n return\n if session.event.sender['card']:\n status = email(session.event.sender['card'], bug_info)\n if status:\n await session.send(\"喵,已经成功通知了喵~\")\n else:\n await session.send(\"QAQ喵,发送失败了喵,重新试试喵\")\n else:\n status = email(session.event.sender['nickname'], bug_info)\n if status:\n await session.send(\"喵,已经成功通知了喵~\")\n else:\n await session.send(\"QAQ喵,发送失败了喵,重新试试喵\")\n\n\n@on_command('create_group', aliases=('创建公会', '创立公会'), only_to_me=False)\nasync def create_group(session: CommandSession):\n db.init_app(get_bot().server_app)\n if Group.query.filter_by(group_chat_id=str(session.event.group_id)).first():\n await session.send('本群已经有一个公会了喵...')\n return\n current_user: User = User.query.filter_by(qq=session.event.user_id).first()\n if not current_user:\n qq_id: int = session.event.user_id\n qq_name = session.event.sender['card']\n if len(qq_name) == 0:\n qq_name = session.event.sender['nickname']\n current_user = User(username=('temp_qq_' + str(qq_id)),\n nickname=qq_name,\n role=2,\n password=password_for(qq_id),\n created_at=datetime.now(),\n email='',\n email_verified=False,\n phone_verified=False,\n valid_since=datetime.now(),\n qq=qq_id,\n is_temp=True)\n db.session.add(current_user)\n\n if current_user.group_id:\n await session.send('公会创建者已经在一个公会里面了喵...')\n\n group_name = session.get('group_name', prompt='公会的名称是什么呢喵?',\n arg_filters=[\n extractors.extract_text, # 取纯文本部分\n str.strip, # 去掉两边空白字符\n ])\n new_group = Group(group_chat_id=str(session.event.group_id),\n name=group_name,\n description='',\n must_request=False,\n leader_id='0')\n db.session.add(new_group)\n db.session.commit()\n db.session.refresh(new_group)\n db.session.refresh(current_user)\n\n current_user.group_id = new_group.id\n current_user.role = 2\n\n db.session.commit()\n await session.send('公会创建成功了喵! ')\n #\n # s = SpiderTeamRank()\n # result = s.get_team_rank_info_by_tname(group_name)\n # print(result)\n # message = f'现在有如下多个名叫{group_name}的公会:\\n'\n # count = 1\n # for group in result['data']:\n # message += '=========\\n'\n # message += f'{count}.' + group['clan_name'] + ':\\n'\n # message += '会长是:' + group['leader_name'] + '会长游戏id是:' + str(group['leader_viewer_id']) + '\\n'\n # count += 1\n # message += '请使用前面的编号进行选择\\n'\n # index = await session.aget(\n # 'rank_index',\n # prompt=message,\n # arg_filters=[\n # extractors.extract_text, # 取纯文本部分\n # str.strip, # 去掉两边空白字符\n # ]\n # )\n # try:\n # index = int(index)\n # new_group.leader_id = result['data'][index - 1]['leader_viewer_id']\n # db.session.commit()\n # except ValueError as e:\n # await session.send('输入非数字的字符拉菲理解不了QAQ')\n","sub_path":"pcr/plugins/manage_group/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297467543","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 20 13:06:52 2020\r\nModified on Sun May 10 12:28:00 2020\r\n\r\n@author: ToshY\r\n\r\nThis is an original work derived from previous work and a wide range of snippets,\r\nwith the purpose of creating a versatile Multilayer Perceptron.\r\n\r\n* SOURCES (SNIPPETS+INFO)\r\n@Ritchie Vink https://github.com/ritchie46/vanilla-machine-learning\r\n@Michael Nielsen https://github.com/mnielsen/neural-networks-and-deep-learning\r\n@Valerio Velardo https://github.com/musikalkemist/DeepLearningForAudioWithPython\r\n@ML-Cheatsheet https://ml-cheatsheet.readthedocs.io/\r\n@Mxnet https://gluon.mxnet.io\r\n\r\n* REMARKS\r\nThe explanations from @Michael and YouTube tutorials of @Valerio (YT: TheSoundOfAI) \r\nreally helped with understanding the basics of Neural Networks. While I initially \r\nfollowed along with @Valerio's tutorials, in the end I switched to use @Ritchie's \r\nsnippet as base for this script, because I liked the use of dictonaries and the \r\nimplementation of batches. The optimizers, currently Momentum and Adam, were added\r\na bit later. \r\n\r\nFor me the most difficult to actually understand was the idea of backpropagation.\r\nSo I followed @Valerio's explanation regarding backpropagation\r\n(https://www.youtube.com/watch?v=ScL18goxsSg&list=PL-wATfeyAMNrtbkCNsLcpoAyBBRJZVlnf).\r\n \r\nI took my whiteboard out and created a random 4 layer network, with 2 hidden layers, \r\nand just started writing out the backpropagation steps. If you really take the time \r\nto write it the derivatives, and follow along, you realize that it's called backprop because\r\nyou start with calculating ∂L/dW_i from the last layer, and after that you do the same for\r\nthe second to last layer (∂L/dW_i-1). And what you'll notice is that the expression \r\nfor second to last layer contains elements which were already calculated from the\r\nprevious layer. Below a short example with the derivations for a 4 layered network.\r\n\r\n===========================================================\r\n\r\nThe idea in general:\r\n\r\n ∂L ∂L ∂a_i+1 ∂z_i+1 \r\n---- = ----- ----- ------\r\n∂W_i ∂a_i+1 ∂z_i+1 ∂W_i\r\n\r\nWhere ∂E/∂a_i+1\r\n\r\n ∂L ∂L ∂a_i+2 ∂z_i+2 \r\n---- = ----- ----- ------\r\n∂a_i+1 ∂a_i+2 ∂z_i+2 ∂a_i+1\r\n\r\n\r\n===========================================================\r\n\r\nEXAMPLE: 4 layers, 2 hidden layers\r\n\r\n* = node; a/z\r\n\r\n1 2 3 4\r\n\r\n * \r\n * \r\n* w1 w2 * w3 *\r\n * \r\n *\r\n\r\nSo for W3 it's easy:\r\n\r\n ∂L ∂L ∂a_4 ∂z_4 \r\n---- = ----- ----- ------\r\n∂W_3 ∂a_4 ∂z_4 ∂W_3\r\n \r\nNow doing the same for W2:\r\n \r\n ∂L ∂L ∂a_3 ∂z_3 \r\n---- = ----- ----- ------\r\n∂W_2 ∂a_3 ∂z_3 ∂W_2\r\n\r\nWe know everything except ∂L/∂a_3. So by using the chain rule again:\r\n\r\n ∂L ∂L ∂a_4 ∂z_4\r\n---- = ----- ----- ------\r\n∂a_3 ∂a_4 ∂z_4 ∂a_3\r\n\r\nSubstituting this back in:\r\n\r\n ∂L / ∂L ∂a_4 ∂z_4 \\ ∂a_3 ∂z_3 \r\n---- = | ----- ----- ------ | ----- ------\r\n∂W_2 \\ ∂a_4 ∂z_4 ∂a_3 / ∂z_3 ∂W_2\r\n\r\nNow we see that the elements...\r\n \r\n ∂L ∂a_4\r\n----- -----\r\n∂a_4 ∂z_4\r\n\r\n...were already calculated in the expresion for ∂L/∂W_3.\r\n\r\nNow you can do the the same process for ∂L/∂W_1, which will give you:\r\n \r\n ∂L // ∂L ∂a_4 ∂z_4 \\ ∂a_3 ∂z_3 \\ ∂a_2 ∂z_2\r\n---- = || ----- ----- ----- | ----- ------ | ----- ------\r\n∂W_w \\\\ ∂a_4 ∂z_4 ∂a_3 / ∂z_3 ∂a_2 / ∂z_2 ∂W_1\r\n\r\nNow we see that the elements...\r\n \r\n ∂L ∂a_4 ∂z_4 ∂a_3\r\n----- ----- ----- -----\r\n∂a_4 ∂z_4 ∂a_3 ∂z_3\r\n\r\n...were already calculated in the expresion for ∂L/∂W_2.\r\n\r\nSo because you've calculated the elements in the \"previous\" iteration, \r\nit makes the calculation for the current layer a lot easier.\r\n\r\n===========================================================\r\n\r\n* NOTES\r\n- Tested with binary and multiclass sklearn and UCI datasets.\r\n- Compared this Network v.s. Keras with sklearn moons dataset, \r\n resulting in similar accuracy.\r\n\r\n* TODO\r\n- Add more gradient descent optimizer functions\r\n- Use K-Fold for automatically determining amount of neurons in hidden layer(s)\r\n- Maybe better checking of arguments parsed. Loading/saving model\r\n- (Web)GUI?\r\n \r\n\"\"\"\r\n# %% \r\nimport time\r\nimport os\r\nimport inspect\r\nimport collections\r\nimport numpy as np\r\nfrom pathlib import Path\r\nfrom src.metrics import Metrics\r\n\r\n# Current working directory\r\ncwd = str(Path(__file__).parent.absolute())\r\n\r\n# Loss functions\r\nclass Quadratic(object):\r\n \"\"\" Mean Squared \"\"\" \r\n \r\n @staticmethod\r\n def fn(y, yhat):\r\n return np.mean((y - yhat)**2)\r\n \r\n @staticmethod\r\n def dfn(y, yhat, z):\r\n return (yhat-y)*z\r\n \r\nclass Root(object):\r\n \"\"\" Root Mean Squared \"\"\"\r\n \r\n @staticmethod\r\n def fn(y, yhat):\r\n return np.sqrt(np.mean((y - yhat)**2))\r\n\r\n @staticmethod\r\n def dfn(y, yhat, z):\r\n return (1/(2*np.sqrt(np.mean((y - yhat)**2))))*z\r\n\r\nclass Log(object):\r\n \"\"\" Cross Entropy \"\"\"\r\n\r\n @staticmethod\r\n def fn(y, yhat):\r\n return np.sum(np.nan_to_num(-y*np.log(yhat)-(1-y)*np.log(1-yhat)))\r\n\r\n @staticmethod\r\n def dfn(y, yhat, z):\r\n return (yhat-y)\r\n\r\n# Neural network \r\nclass NeuralNetwork():\r\n \"\"\"Set up Neural Network model\"\"\"\r\n \r\n def __init__(self, X, y, y_class, btm=True, hidden=[3], activation_functions=['relu','sigmoid'], weight_initialisation=['he_normal','xavier_uniform'], batches=32, learning_rate=1e-3, cost=Quadratic, optimizer='GD', optimizer_options={}, verbose=True, seed=666):\r\n # Input data, separated by features and targets\r\n self.X = X\r\n self.y = y\r\n \r\n # Classes\r\n self.yclass = y_class\r\n self.btm = btm\r\n \r\n # Set seed\r\n self.seed = seed\r\n \r\n # Activation functions per layer and check if valid\r\n for a in activation_functions:\r\n self._check_activation_function( a )\r\n \r\n print('\\n'+('Model settings').center(50,'-')+'\\n')\r\n # Check if minibatches is specified\r\n if isinstance(batches, int) and batches >= 1:\r\n self.batch_mode=True\r\n self.batch_size=batches\r\n print(\">> Batch size set to: {} samples\".format(self.batch_size))\r\n else:\r\n self.batch_mode=False\r\n self.batch_size=len(self.X)\r\n print(\">> Batch size set to: entire training set\")\r\n \r\n # Learning rate\r\n self.lr = learning_rate\r\n \r\n # Loss function\r\n self.loss = cost\r\n self.loss_str = str(self.loss.__name__) + ' loss'\r\n \r\n # Check optimizer and options\r\n self.optvals = self._check_optimizer(optimizer, optimizer_options)\r\n self.optfn = getattr(self, optimizer)\r\n \r\n # Cross Validation\r\n self.cv_fn = None\r\n \r\n # The combined layers with amount of neurons for each one\r\n self.layers = [self.X.shape[1]] + hidden + [self.y.shape[1]]\r\n self.ll = len(self.layers)\r\n \r\n # Weight initialisation methods\r\n if len(weight_initialisation) != (self.ll-1):\r\n raise Exception('Only {} out of {} weight initialisation methods specified.'.format(len(weight_initialisation), (self.ll-1)))\r\n \r\n self.wi = weight_initialisation\r\n \r\n # Set activation functions\r\n self.actf = self._set_activations(activation_functions)\r\n \r\n # Verbose?\r\n self.verbose = verbose\r\n \r\n def _set_weight(self, weight_init=[]):\r\n \"\"\" Initialize random weights \"\"\"\r\n \r\n wd = {}\r\n for idx in range(self.ll-1):\r\n for method in self.wi:\r\n wd[idx+1] = self._weight_method(idx, method)\r\n \r\n return wd\r\n \r\n def _weight_method(self, idx, method='uniform'):\r\n \"\"\" Weight initialisation methods \r\n \r\n Uniform - Tanh\r\n Xavier - Sigmoid\r\n He - (P)Relu\r\n \r\n \"\"\"\r\n \r\n # Set seed\r\n np.random.seed(self.seed)\r\n \r\n if method == 'uniform':\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])*np.sqrt(1/self.layers[idx])\r\n elif method == 'xavier_normal':\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])*np.sqrt(2/(self.layers[idx]+self.layers[idx+1]))\r\n elif method == 'xavier_uniform':\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])*np.sqrt(6/(self.layers[idx]+self.layers[idx+1]))\r\n elif method == 'he_normal':\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])*np.sqrt(2/self.layers[idx])\r\n elif method == 'he_uniform':\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])*np.sqrt(6/self.layers[idx])\r\n elif method == 'zeros':\r\n return np.zeros((self.layers[idx], self.layers[idx+1]))\r\n else:\r\n return np.random.randn(self.layers[idx], self.layers[idx+1])\r\n \r\n def _set_bias(self, bias=0.0):\r\n \"\"\"Initialize (zero) bias\"\"\"\r\n \r\n return {i+1: np.full(self.layers[i+1],bias) for i in range(self.ll-1)}\r\n \r\n def _set_activations(self, activation_functions):\r\n \"\"\" Initialize activations\"\"\"\r\n\r\n return {i+2: activation_functions[i] for i in range(self.ll-1)}\r\n \r\n def _set_zero_array(self):\r\n \"\"\" Initialize list of zero arrays; Used at activations and optimizer \"\"\"\r\n \r\n return [np.zeros((x,y)) for x, y in zip(self.layers[:-1], self.layers[1:])]\r\n \r\n def _reshape_array(self, mat):\r\n return mat.reshape( mat.shape[0], -1 )\r\n \r\n def _check_optimizer(self, optimizer, options):\r\n # Optimizer template\r\n optimizer_template = {'GD':{'epoch':1},\r\n 'Momentum':{'epoch':1,'gamma':0.9},\r\n 'Adam':{'epoch':1,'beta_1':0.9, 'beta_2':0.999, 'eps':1e-8}}\r\n \r\n # Check if valid optimizer\r\n if optimizer not in optimizer_template:\r\n raise Exception('Invalid optimizer specified. Allowed: `{}`.'.format('`, `'.join(list(optimizer_template.keys()))))\r\n \r\n optr={'epoch':1}\r\n # Check Momentum options\r\n if optimizer == 'Momentum':\r\n if 'gamma' not in options:\r\n print('>> GD Momentum: `gamma` was set to default value: {}'.format(optimizer_template['Momentum']['gamma']))\r\n optr['gamma'] = 0.9\r\n else:\r\n optr['gamma'] = options['gamma']\r\n \r\n # Check Adam options\r\n if optimizer == 'Adam':\r\n if 'beta_1' not in options:\r\n print('>> GD Adam: `beta_1` was set to default value: {}'.format(optimizer_template['Adam']['beta_1']))\r\n optr['beta_1'] = 0.9\r\n else:\r\n print('>> GD Adam: `beta_1` was set to custom user value: {}'.format(options['beta_1']))\r\n optr['beta_1'] = options['beta_1']\r\n \r\n if 'beta_2' not in options:\r\n print('>> GD Adam: `beta_2` was set to default value: {}'.format(optimizer_template['Adam']['beta_2']))\r\n optr['beta_2'] = 0.999\r\n else:\r\n print('>> GD Adam: `beta_2` was set to custom user value: {}'.format(options['beta_2']))\r\n optr['beta_2'] = options['beta_2']\r\n \r\n if 'eps' not in options:\r\n print('>> GD Adam: `eps` was set to default value: {}'.format(optimizer_template['Adam']['eps']))\r\n optr['eps'] = 1e-8\r\n else:\r\n print('>> GD Adam: `eps` was set to custom user value: {}'.format(options['eps']))\r\n optr['eps'] = options['eps']\r\n \r\n return optr\r\n \r\n def _check_crossval_function(self, crossval, options):\r\n \"\"\" Check crosvalidation options \"\"\"\r\n \r\n # Crossvalidation template\r\n crossval_template = {'k_fold':{'folds':10,'seed':self.seed,'shuffle':True},\r\n 'k_fold_strat':{'folds':10,'seed':self.seed,'shuffle':True},\r\n 'loo':{}}\r\n \r\n # Check if valid crossvalidation function\r\n if crossval not in crossval_template:\r\n raise Exception('Invalid optimizer specified. Allowed: `{}`.'.format('`, `'.join(list(crossval_template.keys()))))\r\n \r\n optr = {}\r\n \r\n # Check LOOCV\r\n if crossval == 'loo':\r\n return optr\r\n \r\n # Left with K-Fold and Stratified K-Fold CV\r\n if 'folds' not in options:\r\n print('\\n>> CV: `folds` was set to default value: {}'.format(crossval_template[crossval]['folds']))\r\n optr['folds'] = crossval_template[crossval]['folds']\r\n else:\r\n print('\\n>> CV: `folds` was set to custom user value: {}'.format(options['folds']))\r\n optr['folds'] = options['folds']\r\n \r\n if 'random_state' not in options:\r\n print('>> CV: `seed` was set to default value: {}'.format(crossval_template[crossval]['seed']))\r\n optr['seed'] = crossval_template[crossval]['seed']\r\n else:\r\n print('>> CV: `seed` was set to custom user value: {}'.format(options['seed']))\r\n optr['seed'] = options['seed']\r\n \r\n if 'shuffle' not in options:\r\n print('>> CV: `shuffle` was set to default value: {}'.format(crossval_template[crossval]['shuffle']))\r\n optr['shuffle'] = crossval_template[crossval]['shuffle']\r\n else:\r\n print('>> CV: `eps` was set to custom user value: {}'.format(options['eps']))\r\n optr['shuffle'] = options['shuffle']\r\n \r\n return optr\r\n \r\n def _check_activation_function(self, activation_function):\r\n \"\"\" Check if valid activation function is passed\"\"\"\r\n \r\n if not hasattr(afc, activation_function):\r\n raise Exception('Invalid activation function `{}`'.format(activation_function))\r\n \r\n def _check_activation_function_args(self, activation_function, activation_function_args):\r\n \"\"\" Check if valid activation function arguments are passed\"\"\"\r\n \r\n function_args = inspect.getfullargspec(getattr(afc, 'activation_function'))[0]\r\n compare = lambda x, y: collections.Counter(x) == collections.Counter(y)\r\n if not compare(function_args, activation_function_args):\r\n raise Exception('Invalid activation function arguments. Valid = {}'.format(function_args))\r\n \r\n def _create_batches(self, X, y):\r\n \"\"\" Get batches \"\"\"\r\n \r\n batches = []\r\n for i in range(0, X.shape[0], self.batch_size):\r\n batches.append((X[i:i + self.batch_size], y[i:i + self.batch_size]))\r\n \r\n return batches\r\n \r\n def forward_propagate(self, X_data):\r\n \"\"\"Forward propagation\"\"\"\r\n \r\n # First layer is X_data w/o activation function\r\n z={}\r\n activation = {1: X_data}\r\n\r\n for idx in range(1, self.ll):\r\n # z_i+1 = X_i*w_i + B_i\r\n z[idx+1] = np.dot(activation[idx], self.weights[idx]) + self.bias[idx]\r\n # a = actf( z )\r\n activation[idx+1] = getattr(afc, self.actf[idx+1])(z[idx+1])\r\n \r\n return z, activation\r\n \r\n\r\n def back_propagate(self, y, y_hat, z):\r\n \"\"\" Back propagation \"\"\"\r\n \r\n # ∂L/∂W_i = (∂L / ∂a_i+1) * (∂a_i+1 / ∂z_i+1)\r\n if self.loss == Quadratic or self.loss == Root:\r\n delta = self.loss.dfn(y, y_hat[self.ll], getattr(afc, self.actf[self.ll-1] + '_deriv')( y_hat[self.ll] ))\r\n elif self.loss == Log:\r\n delta = self.loss.dfn(y,y_hat[self.ll],0)\r\n \r\n # dW \r\n dW = np.dot(y_hat[self.ll - 1].T, delta)\r\n # Dict for storage purpose\r\n params = { self.ll - 1: (dW, delta) }\r\n \r\n # Other (hidden) layers\r\n for idx in reversed(range(2, self.ll)):\r\n delta = np.dot(delta, self.weights[idx].T) * getattr(afc, self.actf[idx] + '_deriv')( z[idx] )\r\n dw = np.dot(y_hat[idx-1].T, delta)\r\n params[idx-1] = (dw, delta)\r\n \r\n # (Mini)batch gradient descent\r\n self.optfn(params, self.optvals)\r\n \r\n def GD(self, params, opts):\r\n \"\"\" Gradient Descent \"\"\"\r\n \r\n for k, (dw, db) in params.items():\r\n db = np.mean(db, 0)\r\n # Update weights\r\n self.weights[k] -= self.lr * dw\r\n self.bias[k] -= self.lr * db\r\n \r\n def Momentum(self, params, opts):\r\n \"\"\" Gradient Descent with Momentum \"\"\"\r\n \r\n for k, (dw, db) in params.items(): \r\n db = np.mean(db, 0)\r\n # Velocities\r\n self.v_w[k] = opts['gamma'] * self.v_w[k] + self.lr * dw\r\n self.v_b[k] = opts['gamma'] * self.v_b[k] + self.lr * db\r\n \r\n # Update weights\r\n self.weights[k] -= self.v_w[k]\r\n self.bias[k] -= self.v_b[k]\r\n \r\n def Adam(self, params, opts):\r\n \"\"\" Adam is a SGD method that computes individual adaptive \r\n learning rates for different parameters from estimates of \r\n first and second-order moments of the gradients \"\"\"\r\n \r\n v_w_adj = {}\r\n v_b_adj = {}\r\n s_w_adj = {}\r\n s_b_adj = {}\r\n for k, (dw, db) in params.items():\r\n db = np.mean(db, 0)\r\n # Moving average of the gradients\r\n self.v_w[k] = opts['beta_1']*self.v_w[k] + (1-opts['beta_2'])*dw\r\n self.v_b[k] = opts['beta_1']*self.v_b[k] + (1-opts['beta_2'])*db\r\n \r\n # Moving average of the squared gradients\r\n self.s_w[k] = opts['beta_2']*self.s_w[k] + (1-opts['beta_2'])*dw**2\r\n self.s_b[k] = opts['beta_2']*self.s_b[k] + (1-opts['beta_2'])*db**2\r\n \r\n # Compute bias-corrected first moment estimate\r\n v_w_adj[k] = self.v_w[k]/(1-opts['beta_1']**opts['epoch'])\r\n v_b_adj[k] = self.v_b[k]/(1-opts['beta_1']**opts['epoch'])\r\n\r\n # Compute bias-corrected second moment estimate\r\n s_w_adj[k] = self.s_w[k]/(1-opts['beta_2']**opts['epoch'])\r\n s_b_adj[k] = self.s_b[k]/(1-opts['beta_2']**opts['epoch'])\r\n \r\n # Update weights\r\n self.weights[k] -= self.lr * (v_w_adj[k]/np.sqrt(s_w_adj[k]+opts['eps']))\r\n self.bias[k] -= self.lr * (v_b_adj[k]/np.sqrt(s_b_adj[k]+opts['eps']))\r\n \r\n def training(self, epochs, cross_val={}, method_opt='', onehotenc=object, test_metric=Root, normalize=True):\r\n \"\"\" Check for normal training or with CV \"\"\"\r\n \r\n Xt = self.X\r\n yt = self.y\r\n \r\n # Test metric (for CV)\r\n self.fnt = test_metric\r\n \r\n # Normalize predictions between 0 and 1\r\n self.norm_pred = normalize\r\n \r\n # Timer\r\n st = time.time()\r\n \r\n if method_opt == 'single':\r\n print('\\n'+(' Start Training ').center(50,'-')+'\\n')\r\n if not self.verbose: print('...')\r\n training_results = self.train(Xt, yt, epochs)\r\n elif method_opt == 'multi':\r\n cvf = list(cross_val.keys())[0]\r\n cv_options = self._check_crossval_function(cvf, cross_val[cvf])\r\n self.cv_fn = cvf\r\n print('\\n'+(' Start CV {} Training '.format(cvf.upper())).center(50,'-')+'\\n')\r\n if not self.verbose: print('...')\r\n training_results = self.train_cv(Xt, yt, epochs, cv_options, onehotenc)\r\n else:\r\n raise Exception('Invalid method provided. Should contain key `split`, `k_fold` or `loo`.')\r\n \r\n ed = time.time()\r\n print('\\n'+(' Training complete ').center(50,'-')+'\\n')\r\n print('Elapsed time = {:.2f} seconds'.format(ed-st))\r\n return training_results\r\n \r\n def train(self, Xt, yt, epochs):\r\n \"\"\" Train model \"\"\"\r\n \r\n # Due to addition of CV, weight initialisation now done here \r\n \r\n # Set weigths & bias\r\n self.weights = self._set_weight()\r\n self.bias = self._set_bias()\r\n \r\n # Momentum: velocities\r\n if self.optfn.__name__ in ['Momentum', 'Adam']:\r\n self.v_w = {i: np.zeros(self.weights[i].shape) for i in range(1,self.ll)}\r\n self.v_b = {i: np.zeros(self.bias[i].shape) for i in range(1,self.ll)}\r\n \r\n # Adam: Exponential weighted average of the squared gradient\r\n if self.optfn.__name__ in ['Adam']:\r\n self.s_w = {i: np.zeros(self.weights[i].shape) for i in range(1,self.ll)}\r\n self.s_b = {i: np.zeros(self.bias[i].shape) for i in range(1,self.ll)}\r\n \r\n mse = []\r\n for e in range(1, epochs+1):\r\n sum_errors = 0\r\n \r\n # Get batch(es)\r\n X_train = self._create_batches(Xt, yt)\r\n \r\n # Iterate through data\r\n for idx, (sample, target) in enumerate(X_train):\r\n \r\n # Get random minibatch if specified\r\n if self.batch_mode:\r\n idx = np.random.randint(0, len(X_train))\r\n sample, target = X_train[idx]\r\n \r\n # Forward\r\n z, output = self.forward_propagate(sample)\r\n \r\n # Backward\r\n self.back_propagate(target, output, z)\r\n \r\n # Append loss function result for later purposes\r\n sum_errors += self.loss.fn(target, output[self.ll])\r\n \r\n # Fix adding sum_errors per batch to dict!!!\r\n #se[iter] = sum_errors\r\n \r\n # Increment epoch (for Adam)\r\n self.optvals['epoch'] += 1\r\n \r\n # Append every 10 epochs to list\r\n if (e % 100) == 0:\r\n mse.append((e,sum_errors / len(sample)))\r\n \r\n # Display ever 100 epoch MSE\r\n if (e % 1000) == 0 and self.verbose:\r\n print(\"* EPOCH {}; ERROR = {}\".format(e, sum_errors / len(sample)))\r\n \r\n return {'loss':{'train':mse},'weights':{'split':self.weights},'bias':{'split':self.bias}}\r\n\r\n def train_cv(self, Xt, yt, epochs, opts, ohe=None):\r\n \"\"\" Training with CV method \"\"\"\r\n\r\n if self.cv_fn == 'k_fold_strat':\r\n # Transform to 1D to work with k-fold strat\r\n yt = ohe.inverse_transform(yt)\r\n cv = cvs(Xt, yt)\r\n splits, [X_train, y_train, X_val, y_val] = getattr(cv, self.cv_fn)(opts)\r\n # Reverse back by transforming with earlier defined OneHotEncoder\r\n for yv in enumerate(y_train):\r\n y_train[yv[0]] = ohe.transform(y_train[yv[0]]).toarray()\r\n y_val[yv[0]] = ohe.transform(y_val[yv[0]]).toarray() \r\n else:\r\n cv = cvs(Xt, yt)\r\n splits, [X_train, y_train, X_val, y_val] = getattr(cv, self.cv_fn)(opts)\r\n \r\n train_fmse = []\r\n val_fmse = []\r\n val_pred = []\r\n val_true = []\r\n fold_met = []\r\n \r\n fold_weights = {}\r\n fold_bias = {}\r\n for f in range(splits):\r\n print('\\nFold: {}\\n'.format(f+1))\r\n # Train network training set\r\n train_results = self.train(X_train[f], y_train[f], epochs)\r\n train_fmse.append(train_results['loss']['train'])\r\n \r\n # Append weights/bias to new dict\r\n fold_weights[f+1] = train_results['weights']['split']\r\n fold_bias[f+1] = train_results['bias']['split']\r\n \r\n # Test network with validation set and append MSE + predictions\r\n val_mse, fold_pred = self.test(X_val[f], y_val[f], self.fnt, self.norm_pred)\r\n # Metrics\r\n MetricsCV = Metrics(self.loss_str)\r\n MetricsCV.load(y_val[f], self.yclass, fold_pred, self.btm)\r\n cm = MetricsCV.confusion(plot=False)\r\n \r\n fold_met.append(cm[1])\r\n val_fmse.append(val_mse)\r\n val_true.append(y_val[f])\r\n val_pred.append(fold_pred)\r\n \r\n return {'loss':{'train':train_fmse,'validation':val_fmse},'weights':{'cv':fold_weights},'bias':{'cv':fold_bias},'validation_metrics':fold_met,'cross_val':self.cv_fn, 'data':{'true':val_true, 'prediction':val_pred}}\r\n \r\n def test(self, X_test, y_test, efn, normalize):\r\n \"\"\" Get predictions on tested data \"\"\"\r\n \r\n _, y_hat = self.forward_propagate(X_test)\r\n # Normalize between 0 & 1\r\n if normalize and (y_hat[self.ll].shape[-1] > 1):\r\n y_hat[self.ll] = self._normalize(y_hat[self.ll])\r\n\r\n error = efn.fn(y_test, y_hat[self.ll]) \r\n \r\n return error, y_hat[self.ll]\r\n \r\n def _normalize(self, data):\r\n \"\"\" Normalize probabilities \"\"\"\r\n return data/np.sum(data, axis=1)[:, None]\r\n \r\n# %% Main\r\nif __name__ == \"__main__\": \r\n from sklearn.model_selection import train_test_split\r\n from src.crossval import CrossValidationSplit as cvs\r\n from src.activations import ActivationFunctions as afc\r\n from src.general import ModelGeneral\r\n from src.importdata import ImportData\r\n from src.correlation import CorrelationMethods\r\n from src.scaler import Scaler\r\n #%%\r\n ############################### USER INPUT ###############################\r\n \r\n # File (entries-by-features dimensions)\r\n user_file = \"data/sample_data.csv\"\r\n # Entry seperator\r\n user_file_sep = ','\r\n # Headers; First line of file; No headers, set to None\r\n user_file_header = 0\r\n # Amount of target columns; targets should be last columns (after features)\r\n user_target_columns = 1\r\n # Name of the target\r\n y_feature = \"PCa\"\r\n \r\n # Binary to multiclass target? Converts 1D target to 2D array\r\n bin_to_multi = True\r\n \r\n # Test split ratio or CV\r\n method = {'split':0.1}# {'split':0.2} ; {'k_fold_strat':{'folds':3}}\r\n \r\n # User settings or existing model? Set to None for user settings\r\n model = 'NN_05-08-2020_20-33-10/model.json' #None\r\n # User scaler or existing scaler? Set to None for user scaler\r\n scaler = 'NN_05-08-2020_20-33-10/robust.sav' #None\r\n \r\n # Use a scaler?\r\n user_scaler = \"robust\" # scaler overrides user_scaler\r\n \r\n # Neural network user settings\r\n user_layers = [5,10,15,20] #[5, 7, 12] FREE PSA ; [8,13,14] PSA\r\n user_activations = ['relu','prelu','relu','selu','sigmoid'] #['sigmoid','relu','prelu','sigmoid'] ; ['relu','prelu','isru','sigmoid']\r\n user_weights_init = ['he_uniform','he_uniform','he_uniform','he_uniform','xavier_uniform'] #['xavier_uniform','he_uniform','he_uniform','xavier_uniform'] ; ['he_uniform','he_uniform','uniform','xavier_uniform'] \r\n user_batches = None\r\n user_cost = Log\r\n user_optimizer = 'Adam'\r\n user_optimizer_options = {}\r\n user_learning_rate = 1e-3\r\n user_seed=666\r\n \r\n # Iterations\r\n user_iterations = 50000\r\n \r\n # Normalize predictions between 0 and 1?\r\n user_norm_pred = True\r\n \r\n # Specify error metric to use for test data\r\n user_test_metric = Root\r\n \r\n # Save test data and predictions? Only applicable for train/test\r\n save_test_data = True\r\n \r\n # Verbose; if False shows only essential model settings\r\n verbose = True\r\n \r\n #################### DO NOT CHANGE BELOW THIS LINE #######################\r\n #%% \r\n # Type train/test or CV\r\n mkey = list(method.keys())[0]\r\n if mkey in ['split']:\r\n method_opt = 'single'\r\n elif mkey in ['k_fold','k_fold_strat','loo']:\r\n method_opt = 'multi'\r\n \r\n # Data file\r\n IMD = ImportData(input_file=user_file, encoder_file=False, btm=bin_to_multi, seperator=user_file_sep, header_row=user_file_header, y_col=user_target_columns, verbose=verbose)\r\n \r\n # Model General\r\n MG = ModelGeneral(cwd, IMD.abspath, method, method_opt, verbose)\r\n \r\n # Import data + change 1D to 2D multiclass\r\n X = IMD.X\r\n y = IMD.y\r\n if bin_to_multi:\r\n y_classes = IMD.cats[0].astype(int).tolist()\r\n else:\r\n y_classes = np.unique(y).astype(int).tolist()\r\n \r\n # Check if model is valid json\r\n if model is not None:\r\n user_data = MG.load_model(model)\r\n user_data['cost'] = globals()[user_data['cost']]\r\n model_loaded = True\r\n else:\r\n # User settings\r\n user_data = {}\r\n user_data['activation_functions'] = user_activations\r\n user_data['batches'] = user_batches\r\n user_data['cost'] = user_cost\r\n user_data['gradient_descent'] = user_optimizer\r\n user_data['gradient_descent_options'] = user_optimizer_options\r\n user_data['hidden_layers'] = user_layers\r\n user_data['learning_rate'] = user_learning_rate\r\n user_data['seed'] = user_seed\r\n user_data['weights_initialisation'] = user_weights_init\r\n model_loaded = False\r\n \r\n #%% Pearson and pairwise relations\r\n CORM = CorrelationMethods(IMD.rawdf, IMD.headers, verbose=verbose)\r\n pearson_result = CORM.pearson(y_feature)\r\n pairwise_result = CORM.pairwiserelations(y_feature)\r\n \r\n #%% Train/Test or CV\r\n if method_opt == 'single':\r\n # Train & Test\r\n \r\n # Split and shuffle\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=method['split'], random_state=user_seed, shuffle=True)\r\n # Non scaled copy for Risk Calculator (prostaatwijzer)\r\n X_test_ns = X_test.copy()\r\n \r\n # Check scaler\r\n SCL = Scaler(cwd, X_train, verbose)\r\n if scaler is not None:\r\n # Load external scaler\r\n SCL.load_scaler(scaler)\r\n SCL_fn = getattr(SCL, SCL.fn_scaler)\r\n else:\r\n SCL_fn = getattr(SCL, user_scaler)\r\n \r\n # Scale it\r\n data_scaler, X_train = SCL_fn()\r\n X_test = SCL_fn(data_scaler, X_test)\r\n elif method_opt == 'multi':\r\n # Cross validation\r\n \r\n # Just to make sure\r\n X_train = X.copy()\r\n y_train = y.copy()\r\n \r\n # Check scaler\r\n SCL = Scaler(cwd, X_train, verbose)\r\n if scaler is not None:\r\n # Load external scaler\r\n SCL.load_scaler(scaler)\r\n SCL_fn = getattr(SCL, SCL.fn_scaler)\r\n else:\r\n SCL_fn = getattr(SCL, user_scaler)\r\n \r\n # Scale it\r\n data_scaler, X_train = SCL_fn()\r\n else:\r\n raise Exception('Invalid method provided. Should contain key `split`, `k_fold`, `k_fold_strat` or `loo`.')\r\n\r\n #%% Initialize network\r\n NN = NeuralNetwork(X_train, y_train, y_classes, bin_to_multi, user_data['hidden_layers'], user_data['activation_functions'], \r\n user_data['weights_initialisation'], batches=user_data['batches'], cost=user_data['cost'], \r\n optimizer=user_data['gradient_descent'], optimizer_options=user_data['gradient_descent_options'], \r\n learning_rate=user_data['learning_rate'], verbose=verbose, seed=user_data['seed'])\r\n \r\n # Set weights of network from loaded model\r\n if model_loaded:\r\n NN.weights = user_data['weights']\r\n NN.bias = user_data['bias']\r\n \r\n # %% Train network\r\n if not model_loaded:\r\n training_results = NN.training(user_iterations, method, method_opt, IMD.enc, user_test_metric, user_norm_pred)\r\n \r\n # %% Save network\r\n if model_loaded:\r\n MG.save_model(NN.layers, list(NN.actf.values()), NN.wi, NN.batch_mode, NN.batch_size, \r\n NN.weights, NN.bias, NN.loss, NN.lr, NN.optfn, NN.optvals, NN.seed, bin_to_multi, model)\r\n else:\r\n MG.save_model(NN.layers, list(NN.actf.values()), NN.wi, NN.batch_mode, NN.batch_size, \r\n training_results['weights'], training_results['bias'], NN.loss, NN.lr, NN.optfn, NN.optvals, NN.seed, bin_to_multi)\r\n \r\n # Also save scaler\r\n SCL.save_scaler(file_name=MG.current_output_dir)\r\n \r\n # And the OneHotEncoder to be sure\r\n IMD.save_encoder(file_name=MG.current_output_dir)\r\n # %% Predictions\r\n \r\n # Test data\r\n if method_opt == 'single':\r\n test_error, pred = NN.test(X_test, y_test, user_test_metric, user_norm_pred)\r\n \r\n #%% Metrics\r\n \r\n # Save pearson/pairwise plots first \r\n MG.save_plot({'pearson':pearson_result['figure'].get_figure(),\r\n 'pairwise':pairwise_result['figure']})\r\n \r\n # For testing\r\n if method_opt == 'single':\r\n # Call Metrics and load the test and predictions\r\n MetricsNN = Metrics(NN.loss_str)\r\n MetricsNN.load(y_test, y_classes, pred, btm=bin_to_multi)\r\n \r\n # Save X_test and predictions as npy\r\n if save_test_data:\r\n # Save unscaled test data for RC\r\n np.save(os.sep.join([MG.current_output_dir,'X_test.npy']), np.concatenate([X_test_ns, np.reshape(np.array(MetricsNN.y_1D),(1, np.array(MetricsNN.y_1D).size)).T], axis=1))\r\n # Save predictions\r\n np.save(os.sep.join([MG.current_output_dir,'y_hat.npy']), pred)\r\n \r\n # Get binarized test error\r\n test_error_binarized = user_test_metric.fn(np.array(MetricsNN.y_1D), np.array(MetricsNN.y_hat_1D))\r\n \r\n # Error plot can only be done when model was trained, ergo not loaded\r\n if not model_loaded:\r\n # Plot training results\r\n loss_fig = MetricsNN.loss_epoch(training_results)\r\n # Save the plot\r\n MG.save_plot({'error_per_epoch':loss_fig})\r\n \r\n # Distribution of probability predictions\r\n hist_fig = MetricsNN.histogram(y_classes)\r\n\r\n # More verbose options for split\r\n cm, cm_metrics, cm_fig = MetricsNN.confusion(multi=False)\r\n \r\n # Sklearns classification report\r\n report = MetricsNN.class_report()\r\n if verbose:\r\n print('\\n'+('').center(50,'-')+'\\n')\r\n print('\\nClassification report test data:\\n')\r\n print(report['verbose'])\r\n print('\\n'+('').center(50,'-')+'\\n')\r\n \r\n # ROC / AUC\r\n AUC, FPR, TPR, roc_fig = MetricsNN.ROC()\r\n \r\n # Precision & Recall\r\n precision, recall, AP_micro, precall_fig = MetricsNN.precision_recall()\r\n \r\n if verbose:\r\n # Accuracy\r\n print('\\n'+(' Metrics ').center(50,'-')+'\\n')\r\n print('Accuracy = {:.2%}'.format(cm_metrics['ACC']))\r\n print('Balanced accuracy / Non-error rate = {:.2%}'.format(cm_metrics['BACC']))\r\n print('\\n'+('').center(50,'-')+'\\n')\r\n \r\n # Save confusion metrics\r\n MG.save_json(data=cm_metrics, fname=os.sep.join([MG.current_output_dir, 'metrics']), load=True)\r\n \r\n # Save all plots\r\n MG.save_plot({'confusion_matrix':cm_fig,\r\n 'ROC':roc_fig,\r\n 'precision_recall':precall_fig,\r\n 'histogram_probability':hist_fig})\r\n elif method_opt == 'multi':\r\n if model_loaded:\r\n raise Exception('Model loading for cross validation models not implemented.')\r\n \r\n # Call Metrics\r\n MetricsNN = Metrics(NN.loss_str)\r\n \r\n # Plot training results\r\n loss_fig = MetricsNN.loss_epoch(training_results)\r\n cvacc_fig = MetricsNN.cv_accuracy(training_results)\r\n \r\n # Save these plots\r\n MG.save_plot({'error_per_epoch':loss_fig,\r\n 'cv_fold_accuracy':cvacc_fig})\r\n \r\n # Loop over test & predictions per fold/item \r\n for idx, pr in enumerate(training_results['data']['prediction']):\r\n # String for saving purposes concerning fold\r\n fstr = ['fold', str(idx+1)]\r\n # Load metrics\r\n MetricsCVF = Metrics(NN.loss_str)\r\n MetricsCVF.load(training_results['data']['true'][idx], y_classes, pr, btm=bin_to_multi)\r\n # Distribution of probability predictions\r\n hist_fig = MetricsCVF.histogram(y_classes)\r\n # Do all the confusion, derivations, etc.\r\n cm, cm_metrics, cm_fig = MetricsCVF.confusion(multi=False)\r\n AUC, FPR, TPR, roc_fig = MetricsCVF.ROC()\r\n precision, recall, AP_micro, precall_fig = MetricsCVF.precision_recall()\r\n # Save confusion metrics\r\n MG.save_json(data=cm_metrics, fname=os.sep.join([MG.current_output_dir, '-'.join(['metrics']+fstr)]), load=True)\r\n # Save specific plots\r\n MG.save_plot({'-'.join(['confusion_matrix']+fstr):cm_fig,\r\n '-'.join(['ROC']+fstr):roc_fig,\r\n '-'.join(['precision_recall']+fstr):precall_fig,\r\n '-'.join(['histogram_probability']+fstr):hist_fig})\r\n \r\n print('>> Metrics saved successfully')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":37465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"42671954","text":"#正則化パラメータの変更\nimport time\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n\nif __name__ == '__main__':\n start = time.time()\n\n X_train = pd.read_table('train.feature.txt', header = None)\n Y_train = pd.read_table('train.txt', header = None)[1]\n X_valid = pd.read_table('valid.feature.txt', header = None)\n Y_valid = pd.read_table('valid.txt', header = None)[1]\n X_test = pd.read_table('test.feature.txt', header = None)\n Y_test = pd.read_table('test.txt', header = None)[1]\n\n # 正則化パラメータを変えながらモデルを学習する\n C_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4]\n train_acc = []\n valid_acc = []\n test_acc = []\n for c in C_candidate:\n clf = LogisticRegression(penalty = 'l2', solver = 'sag', random_state = 0, C = c)\n clf.fit(X_train, Y_train)\n train_acc.append(accuracy_score(Y_train, clf.predict(X_train)))\n valid_acc.append(accuracy_score(Y_valid, clf.predict(X_valid)))\n test_acc.append(accuracy_score(Y_test, clf.predict(X_test)))\n\n # 正解率を表示する\n print(train_acc)\n print(valid_acc)\n print(test_acc)\n\n # 処理時間 = 終了時刻 - 開始時刻\n elapsed_time = time.time() - start\n print(f'{elapsed_time} [sec]')\n\n # 正解率をグラフとして表示する\n plt.plot(C_candidate, train_acc, label='train')\n plt.plot(C_candidate, valid_acc, label='valid')\n plt.plot(C_candidate, test_acc, label='test')\n plt.xscale('log')\n plt.xlabel('C')\n plt.ylabel('Accuracy')\n plt.legend()\n plt.show()","sub_path":"pan/chapter06/X58.py","file_name":"X58.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"9836616","text":"import openpyxl\npath = r'C:\\\\Users\\\\yxshyw\\\\Desktop\\\\t.xlsx'\n\nwb = openpyxl.load_workbook(path)\nws = wb.get_sheet_by_name('geg')\n\ndef read_merge_cell():\n merge_all_list=[]\n for m_area in ws.merged_cells:\n # 合并单元格的起始行坐标、终止行坐标\n r1, r2, c1, c2 = m_area.min_row, m_area.max_row, m_area.min_col, m_area.max_col\n # print(r1, r2, c1, c2)\n if (r1 != r2 and c1 != c2):\n row_col = [(x, y) for x in range(r1, r2 + 1) for y in range(c1, c2 + 1)]\n merge_all_list.append(row_col)\n # print(r1, r2, c1, c2)\n elif (r1 == r2 and c1 != c2): # or (r1 != r2 and c1 == c2):\n col = [(r1, n) for n in range(c1, c2 + 1)]\n # print(col)\n merge_all_list.append(col)\n elif (r1 != r2 and c1 == c2):\n row = [(m, c1) for m in range(r1, r2 + 1)]\n merge_all_list.append(row)\n return merge_all_list\n\ndef read_excel():\n row = []\n for i in range(1,ws.max_row+1):\n tmp = []\n for j in range(1,ws.max_column+1):\n for k in read_merge_cell():\n # print(i,j)\n if (i, j) in k:\n # print(ws.cell(*k[0]).value)\n tmp.append(ws.cell(*k[0]).value)\n else:\n # print(ws.cell(i, j).value)\n tmp.append(ws.cell(i, j).value)\n break\n row.append(tmp)\n return row\n\nprint(read_excel())","sub_path":"py/p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"97423943","text":"# Opus/UrbanSim urban simulation software.\n# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington\n# See opus_core/LICENSE\n\nfrom numpy import arange, zeros, logical_and, where, in1d, sort\nfrom numpy.random import permutation\nfrom opus_core.logger import logger\nfrom opus_core.misc import unique\nfrom urbansim.models.household_location_choice_model import HouseholdLocationChoiceModel\nimport pandas as pd\n\nclass SubareaHouseholdLocationChoiceModel(HouseholdLocationChoiceModel):\n \"\"\"Run the urbansim HLCM separately for each subarea.\"\"\"\n \n model_name = \"Subarea Household Location Choice Model\" \n\n def __init__(self, location_set, subarea_id_name, **kwargs):\n super(SubareaHouseholdLocationChoiceModel, self).__init__(location_set, **kwargs)\n location_set.compute_one_variable_with_unknown_package('city_id', dataset_pool=self.dataset_pool)\n self.subarea_id_name = subarea_id_name\n \n def run(self, specification, coefficients, agent_set, agents_index=None, agents_filter=None, \n flush_after_each_subarea=False, run_no_area=True, **kwargs):\n if agents_index is None:\n if agents_filter is None:\n agents_index = arange(agent_set.size())\n else:\n agents_index = where(agent_set.compute_variables(agents_filter))[0]\n\n if self.location_id_string is not None:\n agent_set.compute_variables(self.location_id_string, dataset_pool=self.dataset_pool)\n if not self.subarea_id_name in agent_set.get_attribute_names():\n agent_set.compute_one_variable_with_unknown_package(variable_name=\"%s\" % (self.subarea_id_name), dataset_pool=self.dataset_pool)\n regions = agent_set.get_attribute(self.subarea_id_name)\n \n self.choice_set.compute_one_variable_with_unknown_package(variable_name=\"%s\" % (self.subarea_id_name), dataset_pool=self.dataset_pool)\n city_subarea = pd.DataFrame({'city_id':self.choice_set['city_id'], \n self.subarea_id_name: self.choice_set[self.subarea_id_name]})\n city_subarea = city_subarea.drop_duplicates().groupby(self.subarea_id_name).size()\n valid_region = where(regions[agents_index] > 0)[0]\n filter0 = self.filter #keep a copy of the original self.filter\n # this loop handles subarea_id_name households \n if valid_region.size > 0:\n unique_regions = unique(regions[agents_index][valid_region])\n city_subarea = city_subarea[in1d(city_subarea.index, unique_regions)]\n city_subarea = city_subarea.reindex(permutation(city_subarea.index)) # randomize order\n cond_array = zeros(agent_set.size(), dtype=\"bool8\")\n cond_array[agents_index[valid_region]] = True\n for i in sort(unique(city_subarea.values)):\n logger.log_status(\"HLCM for areas belonging to %s cities\" % i)\n these_regions = city_subarea.index[city_subarea.values == i]\n for area in these_regions:\n new_index = where(logical_and(cond_array, regions == area))[0]\n #append subarea_id filter to the original filter string if it is set\n subarea_filter = \"(%s.%s==%s)\" % (self.choice_set.get_dataset_name(), self.subarea_id_name, area)\n if filter0:\n self.filter = \"(\" + filter0 + \")\" + \"*\" + subarea_filter\n else:\n self.filter = subarea_filter\n logger.log_status(\"HLCM for area %s\" % area)\n HouseholdLocationChoiceModel.run(self, specification, coefficients, agent_set, \n agents_index=new_index, **kwargs)\n if flush_after_each_subarea:\n agent_set.flush_dataset()\n self.choice_set.flush_dataset()\n\n #potential to add another loop here to handle a secondary higher geography\n if run_no_area:\n no_region = where(regions[agents_index] <= 0)[0]\n self.filter = filter0\n # this loop handles households w/out a subarea\n if no_region.size > 0: # run the HLCM for housseholds that don't have assigned region\n #self.filter = None\n logger.log_status(\"HLCM for households with no area assigned\")\n choices = HouseholdLocationChoiceModel.run(self, specification, coefficients, agent_set, \n agents_index=agents_index[no_region], **kwargs)\n where_valid_choice = where(choices > 0)[0]\n choices_index = self.choice_set.get_id_index(choices[where_valid_choice])\n chosen_regions = self.choice_set.get_attribute_by_index(self.subarea_id_name, choices_index)\n agent_set.modify_attribute(name=self.subarea_id_name, data=chosen_regions, \n index=no_region[where_valid_choice])\n\nfrom opus_core.tests import opus_unittest\nfrom numpy import array, ma, concatenate\nfrom opus_core.resources import Resources\nfrom urbansim.datasets.gridcell_dataset import GridcellDataset\nfrom urbansim.datasets.household_dataset import HouseholdDataset\nfrom opus_core.coefficients import Coefficients\nfrom opus_core.equation_specification import EquationSpecification\nfrom opus_core.tests.stochastic_test_case import StochasticTestCase\nfrom opus_core.storage_factory import StorageFactory\n\nclass Test(StochasticTestCase):\n def test_place_agents_to_correct_areas(self):\n \"\"\"10 gridcells - 5 in area 1, 5 in area 2, with equal cost, no capacity restrictions\n 100 households - 70 live in area 1, 30 live in area 2.\n We set the coefficient value for cost -0.001. \n \"\"\"\n storage = StorageFactory().get_storage('dict_storage')\n\n nhhs = 100\n ngcs = 10\n ngcs_attr = ngcs/2\n hh_grid_ids = array(nhhs*[-1])\n lareas = array(ngcs_attr*[1] + ngcs_attr*[2])\n hh_lareas = array(70*[1] + 30*[2])\n \n household_data = {\n 'household_id': arange(nhhs)+1,\n 'grid_id': hh_grid_ids,\n 'faz_id': hh_lareas\n }\n\n gridcell_data = {\n 'grid_id': arange(ngcs)+1,\n 'cost':array(ngcs*[100]),\n 'faz_id': lareas \n }\n\n storage.write_table(table_name = 'households', table_data = household_data)\n storage.write_table(table_name = 'gridcells', table_data = gridcell_data)\n\n households = HouseholdDataset(in_storage=storage, in_table_name='households')\n gridcells = GridcellDataset(in_storage=storage, in_table_name='gridcells')\n\n # create coefficients and specification\n coefficients = Coefficients(names=(\"costcoef\", ), values=(-0.001,))\n specification = EquationSpecification(variables=(\"gridcell.cost\", ), coefficients=(\"costcoef\", ))\n\n # check the individual gridcells\n def run_model():\n households = HouseholdDataset(in_storage=storage, in_table_name='households')\n hlcm = SubareaHouseholdLocationChoiceModel(location_set=gridcells, compute_capacity_flag=False,\n choices = \"opus_core.random_choices_from_index\", sample_size_locations = 4, subarea_id_name=\"faz_id\")\n hlcm.run(specification, coefficients, agent_set=households, debuglevel=1)\n\n # get results\n gridcells.compute_variables([\"urbansim.gridcell.number_of_households\"],\n resources=Resources({\"household\":households}))\n result_area1 = gridcells.get_attribute_by_id(\"number_of_households\", arange(ngcs_attr)+1)\n result_area2 = gridcells.get_attribute_by_id(\"number_of_households\", arange(ngcs_attr+1, ngcs+1))\n gridcells.delete_one_attribute(\"number_of_households\")\n result = concatenate((result_area1, result_area2))\n return result\n\n expected_results = array(ngcs_attr*[nhhs*0.7/float(ngcs_attr)] + ngcs_attr*[nhhs*0.3/float(ngcs_attr)])\n\n self.run_stochastic_test(__file__, run_model, expected_results, 10)\n\n # check the exact sum \n hlcm = SubareaHouseholdLocationChoiceModel(location_set=gridcells, compute_capacity_flag=False,\n choices = \"opus_core.random_choices_from_index\", sample_size_locations = 4, subarea_id_name=\"faz_id\")\n hlcm.run(specification, coefficients, agent_set=households, debuglevel=1)\n gridcells.compute_variables([\"urbansim.gridcell.number_of_households\"],\n resources=Resources({\"household\":households}))\n result_area1 = gridcells.get_attribute_by_id(\"number_of_households\", arange(ngcs_attr)+1).sum()\n result_area2 = gridcells.get_attribute_by_id(\"number_of_households\", arange(ngcs_attr+1, ngcs+1)).sum()\n results = array([result_area1, result_area2])\n\n expected_results = array([70, 30])\n self.assertEqual(ma.allequal(expected_results, results), True, \"Error, should_be: %s, but result: %s\" % (\n expected_results, results))\n \nif __name__==\"__main__\":\n opus_unittest.main()\n","sub_path":"psrc_parcel/models/subarea_household_location_choice_model.py","file_name":"subarea_household_location_choice_model.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"554186507","text":"# ___________________________________________________________________________\n#\n# Parapint\n# Copyright (c) 2020\n# National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n# rights in this software.\n# This software is distributed under the 3-clause BSD License.\n# ___________________________________________________________________________\n\nimport pyomo.environ as pe\nfrom pyomo.core.base.block import _BlockData\nimport math\nfrom pyomo.opt.results import assert_optimal_termination\nimport unittest\nfrom nose.plugins.attrib import attr\nfrom typing import Tuple, Sequence\nfrom pyomo.core.base.var import _GeneralVarData\nimport parapint\nfrom pyomo.contrib.pynumero.sparse import BlockVector\nimport numpy as np\nfrom mpi4py import MPI\nfrom parapint.interfaces.schur_complement.mpi_sc_ip_interface import _get_ownership_map, _distribute_blocks\nfrom scipy.sparse import coo_matrix\n\n\ncomm: MPI.Comm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\n\n\"\"\"\nTest problem is\n\nmin integral from t0 to tf of [x(t) - sin(t) - 1]**2\ns.t.\ndx/dt = p(t) - x(t)\n\nUsing trapezoid rule for integral and implicit euler for differential equation\n\"\"\"\n\n\ndef build_time_block(t0: int,\n delta_t: int,\n num_finite_elements: int,\n constant_control_duration: int,\n time_scale: float,\n with_bounds: bool = False,\n with_ineq: bool = False) -> _BlockData:\n \"\"\"\n Parameters\n ----------\n t0: int\n start time\n delta_t: float\n end time\n num_finite_elements:\n number of finite elements\n constant_control_duration:\n number of finite elements over which the\n time_scale: float\n coefficient of t within the sin function\n with_bounds: bool\n with_ineq: bool\n\n Returns\n -------\n m: _BlockData\n The Pyomo model\n \"\"\"\n assert constant_control_duration >= delta_t\n assert constant_control_duration % delta_t == 0\n assert (num_finite_elements * delta_t) % constant_control_duration == 0\n\n def finite_element_ndx_to_start_t_x(ndx):\n return t0 + ndx * delta_t\n\n def finite_element_ndx_to_end_t_x(ndx):\n return t0 + (ndx + 1) * delta_t\n\n def finite_element_ndx_to_start_t_p(ndx):\n return t0 + (math.floor(ndx / (constant_control_duration / delta_t))) * constant_control_duration\n\n m = pe.Block(concrete=True)\n m.x_time_points = pe.Set(initialize=[t for t in range(t0, t0+delta_t*(num_finite_elements + 1), delta_t)])\n m.x = pe.Var(m.x_time_points)\n num_p_elements = int((num_finite_elements * delta_t) / constant_control_duration)\n m.p_time_points = pe.Set(initialize=[t for t in range(t0,\n t0+constant_control_duration*num_p_elements,\n constant_control_duration)])\n if with_bounds:\n bnds = (None, 1.75)\n else:\n bnds = (None, None)\n m.p = pe.Var(m.p_time_points, bounds=bnds)\n\n obj_expr = 0\n for fe_ndx in range(num_finite_elements):\n start_t_x = finite_element_ndx_to_start_t_x(fe_ndx)\n end_t_x = finite_element_ndx_to_end_t_x(fe_ndx)\n obj_expr += 0.5 * delta_t * ((m.x[start_t_x] - (math.sin(time_scale*start_t_x) + 1))**2 +\n (m.x[end_t_x] - (math.sin(time_scale*end_t_x) + 1))**2)\n m.obj = pe.Objective(expr=obj_expr)\n\n m.con_indices = pe.Set(initialize=[t for t in m.x_time_points if t > t0])\n m.cons = pe.Constraint(m.con_indices)\n for fe_ndx in range(num_finite_elements):\n start_t_x = finite_element_ndx_to_start_t_x(fe_ndx)\n end_t_x = finite_element_ndx_to_end_t_x(fe_ndx)\n start_t_p = finite_element_ndx_to_start_t_p(fe_ndx)\n m.cons[end_t_x] = m.x[end_t_x] - (m.x[start_t_x] + delta_t * (m.p[start_t_p] - m.x[end_t_x])) == 0\n\n if with_ineq:\n m.p_ub = pe.Constraint(m.p_time_points)\n for t in m.p_time_points:\n m.p_ub[t] = m.p[t] <= 1.75\n\n return m\n\n\nclass Problem(parapint.interfaces.MPIDynamicSchurComplementInteriorPointInterface):\n def __init__(self,\n t0=0,\n delta_t=1,\n num_finite_elements=90,\n constant_control_duration=10,\n time_scale=0.1,\n num_time_blocks=3,\n with_bounds=False,\n with_ineq=False):\n assert num_finite_elements % num_time_blocks == 0\n self.t0: int = t0\n self.delta_t: int = delta_t\n self.num_finite_elements: int = num_finite_elements\n self.constant_control_duration: int = constant_control_duration\n self.time_scale: float = time_scale\n self.num_time_blocks: int = num_time_blocks\n self.tf = self.t0 + self.delta_t*self.num_finite_elements\n self.with_bounds = with_bounds\n self.with_ineq = with_ineq\n super(Problem, self).__init__(start_t=self.t0,\n end_t=self.tf,\n num_time_blocks=self.num_time_blocks,\n comm=MPI.COMM_WORLD)\n\n def build_model_for_time_block(self, ndx: int,\n start_t: float,\n end_t: float,\n add_init_conditions: bool) -> Tuple[_BlockData,\n Sequence[_GeneralVarData],\n Sequence[_GeneralVarData]]:\n assert int(start_t) == start_t\n assert int(end_t) == end_t\n assert end_t == start_t + self.delta_t*(self.num_finite_elements/self.num_time_blocks)\n start_t = int(start_t)\n end_t = int(end_t)\n m = build_time_block(t0=start_t,\n delta_t=self.delta_t,\n num_finite_elements=int(self.num_finite_elements/self.num_time_blocks),\n constant_control_duration=self.constant_control_duration,\n time_scale=self.time_scale,\n with_bounds=self.with_bounds,\n with_ineq=self.with_ineq)\n start_states = [m.x[start_t]]\n end_states = [m.x[end_t]]\n return m, start_states, end_states\n\n\n@attr(parallel=True, speed='fast', n_procs=[1, 2, 3])\nclass TestSCIPInterface(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n cls.t0 = 0\n cls.delta_t = 1\n cls.num_finite_elements = 6\n cls.constant_control_duration = 2\n cls.time_scale = 1\n cls.num_time_blocks = 3\n cls.with_bounds = True\n cls.with_ineq = False\n cls.barrier_parameter = 0.1\n cls.interface = Problem(t0=cls.t0,\n delta_t=cls.delta_t,\n num_finite_elements=cls.num_finite_elements,\n constant_control_duration=cls.constant_control_duration,\n time_scale=cls.time_scale,\n num_time_blocks=cls.num_time_blocks,\n with_bounds=cls.with_bounds,\n with_ineq=cls.with_ineq)\n interface = cls.interface\n num_time_blocks = cls.num_time_blocks\n\n primals = BlockVector(num_time_blocks + 1)\n duals_eq = BlockVector(num_time_blocks)\n duals_ineq = BlockVector(num_time_blocks)\n duals_primals_lb = BlockVector(num_time_blocks + 1)\n duals_primals_ub = BlockVector(num_time_blocks + 1)\n duals_slacks_lb = BlockVector(num_time_blocks)\n duals_slacks_ub = BlockVector(num_time_blocks)\n\n ownership_map = _get_ownership_map(num_time_blocks, size)\n\n val_map = pe.ComponentMap()\n\n if ownership_map[0] == rank:\n m = interface.pyomo_model(0)\n val_map[m.x[0]] = 0\n val_map[m.x[1]] = 1\n val_map[m.x[2]] = 2\n val_map[m.p[0]] = 0.5\n val_map[m.cons[1]] = 1\n val_map[m.cons[2]] = 2\n\n if ownership_map[1] == rank:\n m = interface.pyomo_model(1)\n val_map[m.x[2]] = 2\n val_map[m.x[3]] = 3\n val_map[m.x[4]] = 4\n val_map[m.p[2]] = 1\n val_map[m.cons[3]] = 3\n val_map[m.cons[4]] = 4\n\n if ownership_map[2] == rank:\n m = interface.pyomo_model(2)\n val_map[m.x[4]] = 4\n val_map[m.x[5]] = 5\n val_map[m.x[6]] = 6\n val_map[m.p[4]] = 1.5\n val_map[m.cons[5]] = 5\n val_map[m.cons[6]] = 6\n\n for ndx in range(num_time_blocks):\n primals.set_block(ndx, np.zeros(4, dtype=np.double))\n duals_primals_lb.set_block(ndx, np.zeros(4, dtype=np.double))\n duals_primals_ub.set_block(ndx, np.zeros(4, dtype=np.double))\n duals_ineq.set_block(ndx, np.zeros(0, dtype=np.double))\n duals_slacks_lb.set_block(ndx, np.zeros(0, dtype=np.double))\n duals_slacks_ub.set_block(ndx, np.zeros(0, dtype=np.double))\n sub_duals_eq = BlockVector(3)\n sub_duals_eq.set_block(0, np.zeros(2, dtype=np.double))\n if ndx == 0:\n sub_duals_eq.set_block(1, np.zeros(0, dtype=np.double))\n else:\n sub_duals_eq.set_block(1, np.zeros(1, dtype=np.double))\n if ndx == num_time_blocks - 1:\n sub_duals_eq.set_block(2, np.zeros(0, dtype=np.double))\n else:\n sub_duals_eq.set_block(2, np.zeros(1, dtype=np.double))\n duals_eq.set_block(ndx, sub_duals_eq)\n primals.set_block(num_time_blocks, np.zeros(2, dtype=np.double))\n duals_primals_lb.set_block(num_time_blocks, np.zeros(2, dtype=np.double))\n duals_primals_ub.set_block(num_time_blocks, np.zeros(2, dtype=np.double))\n\n local_block_indices = _distribute_blocks(num_time_blocks, rank, size)\n for ndx in local_block_indices:\n primals.set_block(ndx, np.array([val_map[i] for i in interface.get_pyomo_variables(ndx)], dtype=np.double))\n duals_primals_ub.set_block(ndx, np.array([0, 0, 0, ndx], dtype=np.double))\n sub_duals_eq = duals_eq.get_block(ndx)\n sub_duals_eq.set_block(0, np.array([val_map[i] for i in interface.get_pyomo_constraints(ndx)], dtype=np.double))\n if ndx == 0:\n sub_duals_eq.set_block(1, np.zeros(0, dtype=np.double))\n else:\n sub_duals_eq.set_block(1, np.ones(1, dtype=np.double) * ndx)\n if ndx == num_time_blocks - 1:\n sub_duals_eq.set_block(2, np.zeros(0, dtype=np.double))\n else:\n sub_duals_eq.set_block(2, np.ones(1, dtype=np.double) * ndx)\n\n primals_flat = primals.flatten()\n res = np.zeros(primals_flat.size, dtype=np.double)\n comm.Allreduce(primals_flat, res)\n primals.copyfrom(res)\n\n duals_primals_lb_flat = duals_primals_lb.flatten()\n res = np.zeros(duals_primals_lb_flat.size, dtype=np.double)\n comm.Allreduce(duals_primals_lb_flat, res)\n duals_primals_lb.copyfrom(res)\n\n duals_primals_ub_flat = duals_primals_ub.flatten()\n res = np.zeros(duals_primals_ub_flat.size, dtype=np.double)\n comm.Allreduce(duals_primals_ub_flat, res)\n duals_primals_ub.copyfrom(res)\n\n duals_eq_flat = duals_eq.flatten()\n res = np.zeros(duals_eq_flat.size, dtype=np.double)\n comm.Allreduce(duals_eq_flat, res)\n duals_eq.copyfrom(res)\n\n primals.set_block(num_time_blocks, np.array([3, 6], dtype=np.double))\n duals_primals_lb.set_block(num_time_blocks, np.zeros(2, dtype=np.double))\n duals_primals_ub.set_block(num_time_blocks, np.zeros(2, dtype=np.double))\n interface.set_primals(primals)\n interface.set_duals_eq(duals_eq)\n interface.set_duals_ineq(duals_ineq)\n interface.set_duals_slacks_lb(duals_slacks_lb)\n interface.set_duals_slacks_ub(duals_slacks_ub)\n interface.set_duals_primals_lb(duals_primals_lb)\n interface.set_duals_primals_ub(duals_primals_ub)\n interface.set_barrier_parameter(cls.barrier_parameter)\n\n def test_n_primals(self):\n self.assertEqual(self.interface.n_primals(), 14)\n\n def test_primals_lb(self):\n expected = np.zeros(14, dtype=np.double)\n expected.fill(-np.inf)\n got = self.interface.primals_lb().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_primals_ub(self):\n expected = np.array([np.inf, np.inf, np.inf, 1.75, np.inf, np.inf, np.inf, 1.75, np.inf, np.inf, np.inf, 1.75, np.inf, np.inf], dtype=np.double)\n got = self.interface.primals_ub().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_get_primals(self):\n expected = np.array([0, 1, 2, 0.5, 2, 3, 4, 1, 4, 5, 6, 1.5, 3, 6], dtype=np.double)\n got = self.interface.get_primals().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_evaluate_objective(self):\n ts = self.time_scale\n expected = (0.5 * (0 - math.sin(ts*0) - 1)**2 +\n 0.5 * (1 - math.sin(ts*1) - 1)**2 +\n 0.5 * (1 - math.sin(ts*1) - 1)**2 +\n 0.5 * (2 - math.sin(ts*2) - 1)**2 +\n 0.5 * (2 - math.sin(ts*2) - 1)**2 +\n 0.5 * (3 - math.sin(ts*3) - 1)**2 +\n 0.5 * (3 - math.sin(ts*3) - 1)**2 +\n 0.5 * (4 - math.sin(ts*4) - 1)**2 +\n 0.5 * (4 - math.sin(ts*4) - 1)**2 +\n 0.5 * (5 - math.sin(ts*5) - 1)**2 +\n 0.5 * (5 - math.sin(ts*5) - 1)**2 +\n 0.5 * (6 - math.sin(ts*6) - 1)**2)\n got = self.interface.evaluate_objective()\n self.assertAlmostEqual(expected, got)\n\n def test_evaluate_grad_objective(self):\n # -----block 0---------- -------block 1-------- ------block 2--------- -coupling-\n # x[0] x[1] x[2] p[0] x[2] x[3] x[4] p[2] x[4] x[5] x[6] p[4] x[2] x[4]\n ts = self.time_scale\n expected = np.array([1 * (0 - math.sin(ts*0) - 1),\n 2 * (1 - math.sin(ts*1) - 1),\n 1 * (2 - math.sin(ts*2) - 1),\n 0,\n 1 * (2 - math.sin(ts*2) - 1),\n 2 * (3 - math.sin(ts*3) - 1),\n 1 * (4 - math.sin(ts*4) - 1),\n 0,\n 1 * (4 - math.sin(ts*4) - 1),\n 2 * (5 - math.sin(ts*5) - 1),\n 1 * (6 - math.sin(ts*6) - 1),\n 0,\n 0,\n 0],\n dtype=np.double)\n got = self.interface.evaluate_grad_objective().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_n_eq_constraints(self):\n self.assertEqual(self.interface.n_eq_constraints(), 10)\n\n def test_n_ineq_constraints(self):\n self.assertEqual(self.interface.n_ineq_constraints(), 0)\n\n def test_ineq_lb(self):\n res = self.interface.ineq_lb()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_ineq_ub(self):\n res = self.interface.ineq_ub()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_get_duals_eq(self):\n expected = np.array([1, 2, 0, 3, 4, 1, 1, 5, 6, 2], dtype=np.double)\n got = self.interface.get_duals_eq().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_get_duals_ineq(self):\n res = self.interface.get_duals_ineq()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_evaluate_eq_constraints(self):\n expected = np.array([1 - (0 + (0.5 - 1)),\n 2 - (1 + (0.5 - 2)),\n 2 - 3,\n 3 - (2 + (1 - 3)),\n 4 - (3 + (1 - 4)),\n 2 - 3,\n 4 - 6,\n 5 - (4 + (1.5 - 5)),\n 6 - (5 + (1.5 - 6)),\n 4 - 6],\n dtype=np.double)\n got = self.interface.evaluate_eq_constraints()\n got = got.make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_evaluate_ineq_constraints(self):\n res = self.interface.evaluate_ineq_constraints()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_evaluate_jacobian_eq(self):\n # -----block 0---------- -------block 1-------- ------block 2--------- -coupling-\n # x[0] x[1] x[2] p[0] x[2] x[3] x[4] p[2] x[4] x[5] x[6] p[4] x[2] x[4]\n expected = [[-1, 2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], # x[1] - (x[0] + (p[0] - x[1])) block 0\n [0, -1, 2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], # x[2] - (x[1] + (p[0] - x[2])) block 0\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0 ], # x[2] - coupling[0] block 0\n [0, 0, 0, 0, -1, 2, 0, -1, 0, 0, 0, 0, 0, 0 ], # x[3] - (x[2] + (p[2] - x[3])) block 1\n [0, 0, 0, 0, 0, -1, 2, -1, 0, 0, 0, 0, 0, 0 ], # x[4] - (x[3] + (p[2] - x[4])) block 1\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0 ], # x[2] - coupling[0] block 1\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1], # x[4] - coupling[1] block 1\n [0, 0, 0, 0, 0, 0, 0, 0, -1, 2, 0, -1, 0, 0 ], # x[5] - (x[4] + (p[4] - x[5])) block 2\n [0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 2, -1, 0, 0 ], # x[6] - (x[5] + (p[4] - x[6])) block 2\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1], # x[4] - coupling[1] block 2\n ]\n expected = np.array(expected, dtype=np.double)\n got = self.interface.evaluate_jacobian_eq().to_local_array()\n self.assertTrue(np.allclose(expected, got))\n\n def test_evaluate_jacobian_ineq(self):\n res = self.interface.evaluate_jacobian_ineq()\n nrows, ncols = res.shape\n self.assertEqual(nrows, 0)\n self.assertEqual(ncols, 14)\n\n def test_get_slacks(self):\n res = self.interface.get_slacks()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_get_duals_primals_lb(self):\n expected = np.zeros(14, dtype=np.double)\n got = self.interface.get_duals_primals_lb().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_get_duals_primals_ub(self):\n expected = np.array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0], dtype=np.double)\n got = self.interface.get_duals_primals_ub().make_local_copy().flatten()\n self.assertTrue(np.allclose(expected, got))\n\n def test_get_duals_slacks_lb(self):\n res = self.interface.get_duals_slacks_lb()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_get_duals_slacks_ub(self):\n res = self.interface.get_duals_slacks_ub()\n self.assertEqual(res.nblocks, 3)\n self.assertEqual(res.size, 0)\n\n def test_evaluate_primal_dual_kkt_rhs(self):\n got = self.interface.evaluate_primal_dual_kkt_rhs().make_local_copy().flatten()\n self.assertEqual(got.size, 24)\n ts = self.time_scale\n barrier = self.barrier_parameter\n expected = np.array([1 * (0 - math.sin(ts*0) - 1) + (-1)*1 - 0 + 0, # grad lag wrt x[0] block 0\n 2 * (1 - math.sin(ts*1) - 1) + 2*1 + (-1)*2 - 0 + 0, # grad lag wrt x[1] block 0\n 1 * (2 - math.sin(ts*2) - 1) + 2*2 + 1*0 - 0 + 0, # grad lag wrt x[2] block 0\n 0 + (-1)*1 + (-1)*2 - 0 + barrier/(1.75 - 0.5), # grad lag wrt p[0] block 0\n 1 - (0 + (0.5 - 1)), # x[1] - (x[0] + (p[0] - x[1])) block 0\n 2 - (1 + (0.5 - 2)), # x[2] - (x[1] + (p[0] - x[2])) block 0\n 1 * (2 - math.sin(ts*2) - 1) + (-1)*3 + 1*1 - 0 + 0, # grad lag wrt x[2] block 1\n 2 * (3 - math.sin(ts*3) - 1) + 2*3 + (-1)*4, # grad lag wrt x[3] block 1\n 1 * (4 - math.sin(ts*4) - 1) + 2*4 + 1*1, # grad lag wrt x[4] block 1\n 0 + (-1)*3 + (-1)*4 - 0 + barrier/(1.75 - 1.0), # grad lag wrt p[2] block 1\n 3 - (2 + (1 - 3)), # x[3] - (x[2] + (p[2] - x[3])) block 1\n 4 - (3 + (1 - 4)), # x[4] - (x[3] + (p[2] - x[4])) block 1\n 2 - 3, # x[2] - coupling[0] block 1\n 1 * (4 - math.sin(ts*4) - 1) + (-1)*5 + 1*2 - 0 + 0, # grad lag wrt x[4] block 2\n 2 * (5 - math.sin(ts*5) - 1) + 2*5 + (-1)*6 - 0 + 0, # grad lag wrt x[5] block 2\n 1 * (6 - math.sin(ts*6) - 1) + 2*6 - 0 + 0, # grad lag wrt x[6] block 2\n 0 + (-1)*5 + (-1)*6 - 0 + barrier/(1.75 - 1.5), # grad lag wrt p[4] block 2\n 5 - (4 + (1.5 - 5)), # x[5] - (x[4] + (p[4] - x[5])) block 2\n 6 - (5 + (1.5 - 6)), # x[6] - (x[5] + (p[4] - x[6])) block 2\n 4 - 6, # x[4] - coupling[1] block 2\n 2 - 3, # x[2] - coupling[0] block 0\n 4 - 6, # x[4] - coupling[1] block 1\n 0 + (-1)*1 + (-1)*0, # grad lag wrt coupling[0]\n 0 + (-1)*2 + (-1)*1], # grad lag wrt coupling[1]\n dtype=np.double)\n expected *= -1\n self.assertTrue(np.allclose(expected, got))\n\n\n@attr(parallel=True, speed='medium', n_procs=[1, 2, 3])\nclass TestSCIPInterfaceWithSolve(unittest.TestCase):\n def test_kkt_system(self):\n t0 = 0\n delta_t = 1\n num_finite_elements = 90\n constant_control_duration = 10\n time_scale = 0.1\n num_time_blocks = 3\n interface = Problem(t0=t0,\n delta_t=delta_t,\n num_finite_elements=num_finite_elements,\n constant_control_duration=constant_control_duration,\n time_scale=time_scale,\n num_time_blocks=num_time_blocks)\n interface.set_primals(interface.init_primals())\n interface.set_slacks(interface.init_slacks())\n interface.set_duals_eq(interface.init_duals_eq())\n interface.set_duals_ineq(interface.init_duals_ineq())\n interface.set_duals_primals_lb(interface.init_duals_primals_lb())\n interface.set_duals_primals_ub(interface.init_duals_primals_ub())\n interface.set_duals_slacks_lb(interface.init_duals_slacks_lb())\n interface.set_duals_slacks_ub(interface.init_duals_slacks_ub())\n interface.set_barrier_parameter(0)\n kkt = interface.evaluate_primal_dual_kkt_matrix()\n rhs = interface.evaluate_primal_dual_kkt_rhs()\n linear_solver = parapint.linalg.ScipyInterface()\n local_kkt = coo_matrix(kkt.to_local_array())\n linear_solver.do_symbolic_factorization(local_kkt)\n linear_solver.do_numeric_factorization(local_kkt)\n sol = linear_solver.do_back_solve(rhs.make_local_copy())\n interface.set_primal_dual_kkt_solution(sol)\n interface.set_primals(interface.get_primals() + interface.get_delta_primals())\n interface.set_slacks(interface.get_slacks() + interface.get_delta_slacks())\n interface.set_duals_eq(interface.get_duals_eq() + interface.get_delta_duals_eq())\n interface.set_duals_ineq(interface.get_duals_ineq() + interface.get_delta_duals_ineq())\n interface.set_duals_primals_lb(interface.get_duals_primals_lb() + interface.get_delta_duals_primals_lb())\n interface.set_duals_primals_ub(interface.get_duals_primals_ub() + interface.get_delta_duals_primals_ub())\n interface.set_duals_slacks_lb(interface.get_duals_slacks_lb() + interface.get_delta_duals_slacks_lb())\n interface.set_duals_slacks_ub(interface.get_duals_slacks_ub() + interface.get_delta_duals_slacks_ub())\n interface.load_primals_into_pyomo_model()\n x = dict()\n p = dict()\n local_block_indices = _distribute_blocks(num_time_blocks, rank, size)\n for ndx in local_block_indices:\n m = interface.pyomo_model(ndx)\n for t in m.x_time_points:\n if t in x:\n self.assertAlmostEqual(x[t], m.x[t].value)\n else:\n x[t] = m.x[t].value\n for t in m.p_time_points:\n p[t] = m.p[t].value\n\n m = build_time_block(t0=t0,\n delta_t=delta_t,\n num_finite_elements=num_finite_elements,\n constant_control_duration=constant_control_duration,\n time_scale=time_scale)\n opt = pe.SolverFactory('ipopt')\n res = opt.solve(m)\n assert_optimal_termination(res)\n for _t, _x in x.items():\n self.assertAlmostEqual(_x, m.x[_t].value)\n for _t, _p in p.items():\n self.assertAlmostEqual(_p, m.p[_t].value)\n\n def _ip_helper(self, with_bounds, with_ineq, linear_solver):\n t0 = 0\n delta_t = 1\n num_finite_elements = 90\n constant_control_duration = 10\n time_scale = 0.1\n num_time_blocks = 3\n interface = Problem(t0=t0,\n delta_t=delta_t,\n num_finite_elements=num_finite_elements,\n constant_control_duration=constant_control_duration,\n time_scale=time_scale,\n num_time_blocks=num_time_blocks,\n with_bounds=with_bounds,\n with_ineq=with_ineq)\n options = parapint.algorithms.IPOptions()\n options.linalg.solver = linear_solver\n status = parapint.algorithms.ip_solve(interface=interface, options=options)\n self.assertEqual(status, parapint.algorithms.InteriorPointStatus.optimal)\n interface.load_primals_into_pyomo_model()\n x = dict()\n p = dict()\n local_block_indices = _distribute_blocks(num_time_blocks, rank, size)\n for ndx in local_block_indices:\n m = interface.pyomo_model(ndx)\n for t in m.x_time_points:\n if t in x:\n self.assertAlmostEqual(x[t], m.x[t].value)\n else:\n x[t] = m.x[t].value\n for t in m.p_time_points:\n p[t] = m.p[t].value\n\n m = build_time_block(t0=t0,\n delta_t=delta_t,\n num_finite_elements=num_finite_elements,\n constant_control_duration=constant_control_duration,\n time_scale=time_scale,\n with_bounds=with_bounds,\n with_ineq=with_ineq)\n opt = pe.SolverFactory('ipopt')\n res = opt.solve(m, tee=True)\n assert_optimal_termination(res)\n for _t, _x in x.items():\n self.assertAlmostEqual(_x, m.x[_t].value)\n for _t, _p in p.items():\n self.assertAlmostEqual(_p, m.p[_t].value)\n\n def test_interface_with_ip_sc(self):\n linear_solver = parapint.linalg.MPISchurComplementLinearSolver(subproblem_solvers={0: parapint.linalg.ScipyInterface(compute_inertia=True),\n 1: parapint.linalg.ScipyInterface(compute_inertia=True),\n 2: parapint.linalg.ScipyInterface(compute_inertia=True)},\n schur_complement_solver=parapint.linalg.ScipyInterface(compute_inertia=True))\n self._ip_helper(with_bounds=False, with_ineq=False, linear_solver=linear_solver)\n\n def test_interface_with_ip_bounds_sc(self):\n linear_solver = parapint.linalg.MPISchurComplementLinearSolver(subproblem_solvers={0: parapint.linalg.ScipyInterface(compute_inertia=True),\n 1: parapint.linalg.ScipyInterface(compute_inertia=True),\n 2: parapint.linalg.ScipyInterface(compute_inertia=True)},\n schur_complement_solver=parapint.linalg.ScipyInterface(compute_inertia=True))\n self._ip_helper(with_bounds=True, with_ineq=False, linear_solver=linear_solver)\n\n def test_interface_with_ip_ineq_sc(self):\n linear_solver = parapint.linalg.MPISchurComplementLinearSolver(subproblem_solvers={0: parapint.linalg.ScipyInterface(compute_inertia=True),\n 1: parapint.linalg.ScipyInterface(compute_inertia=True),\n 2: parapint.linalg.ScipyInterface(compute_inertia=True)},\n schur_complement_solver=parapint.linalg.ScipyInterface(compute_inertia=True))\n self._ip_helper(with_bounds=False, with_ineq=True, linear_solver=linear_solver)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/parapint/interfaces/schur_complement/tests/test_mpi_sc_ip_interface.py","file_name":"test_mpi_sc_ip_interface.py","file_ext":"py","file_size_in_byte":31412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"401486105","text":"\n\n#calss header\nclass _MANGE():\n\tdef __init__(self,): \n\t\tself.name = \"MANGE\"\n\t\tself.definitions = [u'an infectious disease in animals that have hair, such as dogs and cats, that makes hair fall out and causes areas of rough skin']\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/_mange.py","file_name":"_mange.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"65403945","text":"from pico2d import *\nimport main_state\n\nimport game_world\n\nPIXEL_PER_METER = (1.0 / 0.3) # 10 pixel 30 cm\nFire_SPEED_KMPH = 7.0 # Km / Hour\nFire_SPEED_MPM = (Fire_SPEED_KMPH * 1000.0 / 60.0)\nFire_SPEED_MPS = (Fire_SPEED_MPM / 60.0)\nFire_SPEED_PPS = (Fire_SPEED_MPS * PIXEL_PER_METER)\n\n\ndef collide(a, b):\n left_a, bottom_a, right_a, top_a = a.get_bb()\n left_b, bottom_b, right_b, top_b = b.get_bb()\n if left_a > right_b: return False\n if right_a < left_b: return False\n if top_a < bottom_b: return False\n if bottom_a > top_b: return False\n\n return True\n\n\nclass FireBall:\n image = None\n\n def __init__(self):\n eru = main_state.get_eru()\n if FireBall.image == None:\n FireBall.image = load_image('./image/fireball.png')\n\n self.x = eru.x\n self.y = game_world.HEIGHT + 160\n self.timer = 0\n\n def get_bb(self):\n return self.x - 55, self.y - 80, self.x + 55, self.y + 80\n\n def update(self):\n eru = main_state.get_eru()\n\n self.y -= Fire_SPEED_PPS * eru.stage_level * 0.2 + Fire_SPEED_PPS\n\n if collide(eru, self):\n if eru.crash_effect_timer <= 0 and eru.eternel == 0:\n eru.remain_hp -= 1\n eru.crash_effect_timer = 1\n self.eraser()\n\n elif self.y <= -100:\n self.eraser()\n\n\n def draw(self):\n self.image.draw(self.x, self.y, 100, 160)\n #draw_rectangle(*self.get_bb())\n\n def eraser(self):\n game_world.remove_object(self)\n del self\n","sub_path":"FireBall.py","file_name":"FireBall.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410531411","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport json\nfrom xml.sax import make_parser\nfrom urllib.request import urlretrieve\nfrom smallsmilhandler import SmallSMILHandler\n\nusage_error = 'usage error: python3 karaoke.py '\n\n\nclass KaraokeLocal:\n\n def __init__(self, filename, att_list):\n parser = make_parser()\n SMILHandler = SmallSMILHandler(att_list)\n parser.setContentHandler(SMILHandler)\n parser.parse(open(filename))\n\n self.tag_list = SMILHandler.get_tags()\n\n def __str__(self):\n tags_str = ''\n\n for tag in self.tag_list:\n tags_str += tag[0]\n for att in tag[1]:\n if tag[1][att] != '':\n tags_str += '\\t' + att + '=\"' + tag[1][att] + '\"'\n tags_str += '\\n'\n\n return tags_str\n\n def do_local(self):\n for tag in self.tag_list:\n for att in tag[1]:\n if 'http://' in tag[1][att]:\n name = tag[1][att].split('/')[-1]\n urlretrieve(tag[1][att], name)\n tag[1][att] = name\n\n def to_json(self, filesmil, filejson=''):\n if filejson:\n with open(filejson, 'w') as jsonfile:\n json.dump(self.tag_list, jsonfile, indent=3)\n else:\n with open(filesmil.replace('smil', 'json'), 'w') as jsonfile:\n json.dump(self.tag_list, jsonfile, indent=3)\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n sys.exit(usage_error)\n else:\n filename = sys.argv[1]\n\n att_list = {'root-layout': ['width', 'height', 'background-color'],\n 'region': ['id', 'top', 'bottom', 'left', 'right'],\n 'img': ['src', 'region', 'begin', 'dur'],\n 'audio': ['src', 'begin', 'dur'],\n 'textstream': ['src', 'region']}\n\n karaoke = KaraokeLocal(filename, att_list)\n\n print(karaoke)\n karaoke.to_json(filename)\n karaoke.do_local()\n karaoke.to_json(filename, 'local.json')\n print(karaoke)\n","sub_path":"karaoke.py","file_name":"karaoke.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"409194121","text":"import hashlib\nimport json\nimport os\nfrom time import time\nfrom typing import Any, Dict, List, Optional\nfrom urllib.parse import urlparse\nfrom uuid import uuid4\nfrom mp3hash import mp3hash\n\nimport requests\nfrom flask import Flask, jsonify, request, render_template\n\nimport random\nimport ecdsa\nimport base58\n\nclass Blockchain:\n def __init__(self):\n self.current_transactions = []\n self.main_chain = []\n self.nodes = set()\n\n # 創建主鏈創世區塊\n self.new_block('translate_tts.mp3', previous_hash='1', proof=100)\n\n def register_node(self, address: str) -> None:\n \"\"\"\n Add a new node to the list of nodes\n\n :param address: Address of node. Eg. 'http://192.168.0.5:5000'\n \"\"\"\n\n parsed_url = urlparse(address)\n self.nodes.add(parsed_url.netloc)\n\n def valid_chain(self, main_chain: List[Dict[str, Any]]) -> bool:\n \"\"\"\n Determine if a given blockchain is valid\n\n :param main_chain: A blockchain\n :return: True if valid, False if not\n \"\"\"\n\n last_block = main_chain[0]\n current_main_index = 1\n\n while current_main_index < len(main_chain):\n block = main_chain[current_main_index]\n print(f'{last_block}')\n print(f'{block}')\n print(\"\\n-----------\\n\")\n # Check that the hash of the block is correct\n if block['previous_hash'] != self.hash(last_block):\n return False\n\n # Check that the Proof of Work is correct\n if not self.valid_proof(last_block['proof'], block['proof']):\n return False\n\n last_block = block\n current_main_index += 1\n\n return True\n\n def valid_music_chain(self, music_chain: List[Dict[str, Any]]) -> bool:\n \"\"\"\n Determine if a given blockchain is valid\n\n :param music_chain: A blockchain\n :return: True if valid, False if not\n \"\"\"\n\n last_music_block = music_chain[0]\n current_index = 1\n\n while current_index < len(music_chain):\n music_block = music_chain[current_index]\n print(f'{last_music_block}')\n print(f'{music_block}')\n print(\"\\n-----------\\n\")\n # Check that the hash of the block is correct\n if music_block['previous_hash'] != self.hash(last_music_block):\n return False\n\n # Check that the Proof of Work is correct\n if not self.valid_music_proof(last_music_block['music_proof'], music_block['music_proof']):\n return False\n\n last_music_block = music_block\n current_index += 1\n\n return True\n\n def resolve_conflicts(self) -> bool:\n \"\"\"\n 共识算法解决冲突\n 使用网络中最长的链.\n\n :return: 如果链被取代返回 True, 否则为False\n \"\"\"\n\n neighbours = self.nodes\n new_chain = None\n\n # We're only looking for chains longer than ours\n max_length = len(self.main_chain)\n\n # Grab and verify the chains from all the nodes in our network\n for node in neighbours:\n response = requests.get(f'http://{node}/chain')\n\n if response.status_code == 200:\n mainlength = response.json()['mainlength']\n main_chain = response.json()['main_chain']\n\n # Check if the length is longer and the main_chain is valid\n if mainlength > max_length and self.valid_chain(main_chain):\n max_length = mainlength\n new_chain = main_chain\n\n # Replace our main_chain if we discovered a new, valid main_chain longer than ours\n if new_chain:\n self.main_chain = new_chain\n return True\n\n return False\n\n def resolve_music_conflicts(self) -> bool:\n \"\"\"\n 共识算法解决冲突\n 使用网络中最长的链.\n\n :return: 如果链被取代返回 True, 否则为False\n \"\"\"\n\n neighbours = self.nodes\n new_music_chain = None\n\n # We're only looking for chains longer than ours\n max_length = len(self.music_chain)\n\n # Grab and verify the chains from all the nodes in our network\n for node in neighbours:\n response = requests.get(f'http://{node}/chain')\n\n if response.status_code == 200:\n musiclength = response.json()['musiclength']\n music_chain = response.json()['music_chain']\n\n # Check if the length is longer and the main_chain is valid\n if musiclength > max_length and self.valid_music_chain(music_chain):\n max_length = musiclength\n new_music_chain = music_chain\n\n # Replace our main_chain if we discovered a new, valid main_chain longer than ours\n if new_music_chain:\n self.music_chain = new_music_chain\n return True\n\n return False\n \n\n # 交易區塊(有交易紀錄)\n def new_music_block(self, main_index, music_proof: int, previous_hash: Optional[str]) -> Dict[str, Any]:\n\n music_block = {\n 'index':len(self.music_chain)+1,\n 'main_index':main_index,\n 'timestamp':time(),\n 'transactions': self.current_transactions,\n 'music_proof': music_proof,\n 'previous_hash': previous_hash or self.hash(self.music_chain[-1]),\n }\n\n # Reset the current list of transactions and music chain\n self.current_transactions = []\n\n self.music_chain.append(music_block)\n return music_block\n\n\n # 創建音樂區塊(放音檔hash)\n def new_block(self, mp3path, proof: int, previous_hash: Optional[str]) -> Dict[str, Any]:\n \"\"\"\n 生成新區塊\n\n :param proof: The proof given by the Proof of Work algorithm\n :param previous_hash: Hash of previous Block\n :return: New Block\n \"\"\"\n\n block = {\n 'main_index': len(self.main_chain) + 1,\n 'timestamp': time(),\n 'proof': proof,\n 'music_hash':mp3hash(mp3path),\n 'previous_hash': previous_hash or self.hash(self.main_chain[-1]),\n }\n \n\n # 創立music-chain(交易區塊)的創世區塊\n self.music_chain = []\n self.new_music_block(len(self.main_chain)+1, previous_hash='1', music_proof=100)\n\n self.main_chain.append(block)\n return block\n\n # 交易紀錄\n def new_transaction(self, sender: str, recipient: str, amount: int) -> int:\n \"\"\"\n 生成新交易信息,信息将加入到下一个待挖的區塊中\n\n :param sender: Address of the Sender\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 self.current_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount,\n })\n\n return self.last_music_block['index'] + 1\n\n # 錢包\n def create_wallet(self, account: str, password: str, identity: int) -> int:\n \"\"\"\n 創建錢包,生成錢包地址並回傳\n\n :param account: 使用者於系統中註冊之帳號\n :param password: 使用者於系統中註冊之密碼\n :param identity: 使用者於系統中註冊所提供之身分證\n :return: wallet_address\n \"\"\"\n\n private_key = identity[1:] + hex(random.randint(1, 8288608480668846482228684402464624222246648088028668608040264462))[2:]\n if len(private_key) < 64:\n for i in range(64 - len(private_key)):\n private_key = '0' + private_key\n elif len(private_key) > 64:\n private_key = private_key[:64]\n\n private_key = bytes.fromhex(private_key)\n\n sk = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)\n vk = b'\\x04' + sk.verifying_key.to_string()\n\n ek = hashlib.sha256(vk).digest()\n\n ripemd160 = hashlib.new('ripemd160')\n ripemd160.update(ek)\n rk = b'\\x00' + ripemd160.digest()\n\n checksum = hashlib.sha256(hashlib.sha256(rk).digest()).digest()[0:4]\n public_key = rk + checksum\n\n wallet_address = base58.b58encode(public_key)\n \n wallet = {\n 'prvateKey' : private_key,\n 'publicKey' : public_key,\n 'address' : wallet_address,\n }\n\n return wallet\n\n @property\n def last_block(self) -> Dict[str, Any]:\n return self.main_chain[-1]\n\n @property\n def last_music_block(self) -> Dict[str, Any]:\n \n return self.music_chain[-1]\n\n @staticmethod\n def hash(block: Dict[str, Any]) -> str:\n \"\"\"\n 生成块的 SHA-256 hash值\n\n :param block: Block\n \"\"\"\n\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n @staticmethod\n def hash(music_block: Dict[str, Any]) -> str:\n \"\"\"\n 生成块的 SHA-256 hash值\n\n :param block: Block\n \"\"\"\n\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n music_block_string = json.dumps(music_block, sort_keys=True).encode()\n return hashlib.sha256(music_block_string).hexdigest()\n\n def proof_of_work(self, last_proof: int) -> int:\n \"\"\"\n 简单的工作量证明:\n - 查找一个 p' 使得 hash(pp') 以4个0开头\n - p 是上一个块的证明, p' 是当前的证明\n \"\"\"\n\n proof = 0\n while self.valid_proof(last_proof, proof) is False:\n proof += 1\n\n return proof\n\n def proof_of_music_work(self, last_music_proof: int) -> int:\n \"\"\"\n 简单的工作量证明:\n - 查找一个 p' 使得 hash(pp') 以4个0开头\n - p 是上一个块的证明, p' 是当前的证明\n \"\"\"\n\n music_proof = 0\n while self.valid_music_proof(last_music_proof, music_proof) is False:\n music_proof += 1\n\n return music_proof\n\n @staticmethod\n def valid_proof(last_proof: int, proof: int) -> bool:\n \"\"\"\n 验证证明: 是否hash(last_proof, proof)以4个0开头\n\n :param last_proof: Previous Proof\n :param proof: Current Proof\n :return: True if correct, False if not.\n \"\"\"\n\n guess = f'{last_proof}{proof}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n return guess_hash[:4] == \"0000\"\n\n @staticmethod\n def valid_music_proof(last_music_proof: int, music_proof: int) -> bool:\n\n guess = f'{last_music_proof}{music_proof}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n return guess_hash[:4] == \"0000\"\n\n\n# Instantiate the Node\napp = Flask(__name__)\n\nUPLOAD_PATH = 'static/uploads'\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nUPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_PATH)\n# Generate a globally unique address for this node\nnode_identifier = str(uuid4()).replace('-', '')\n\n# Instantiate the Blockchain\nblockchain = Blockchain()\n\n\n# 音樂區塊(main chain\n@app.route('/addmusic', methods=['GET', 'POST'])\ndef addmusic():\n if request.method == 'POST':\n file = request.files['file']\n upload_path = '{}/{}'.format(UPLOAD_FOLDER, file.filename)\n file.save(upload_path)\n \n last_block = blockchain.last_block\n last_proof = last_block['proof']\n proof = blockchain.proof_of_work(last_proof)\n \n block = blockchain.new_block(upload_path, proof, None)\n \n \n response = {\n 'message' : \"New Music Add\",\n 'main_index' : block['main_index'],\n 'proof' : block['proof'],\n 'music_hash':block['music_hash'],\n 'previous_hash' : block['previous_hash'],\n }\n \n return 'OK'\n \n \n return jsonify(response), 200\n\n\n \n# 一般礦的的挖礦(交易區塊)music chain\n@app.route('//mine', methods=['GET'])\ndef mine(main_index):\n # We run the proof of work algorithm to get the next proof...\n main_index = int(main_index)\n block = blockchain.main_chain\n last_music_block = blockchain.last_music_block\n last_music_proof = last_music_block['music_proof']\n #music_proof = blockchain.proof_of_music_work(main_index, last_music_proof)\n music_proof = blockchain.proof_of_music_work(last_music_proof)\n\n # 给工作量证明的節點提供獎勵.\n # 发送者为 \"0\" 表明是新挖出的币\n blockchain.new_transaction(\n sender=\"0\",\n recipient=node_identifier,\n amount=1,\n )\n\n # Forge the new Block by adding it to the main_chain\n music_block = blockchain.new_music_block(main_index, music_proof, None)\n\n response = {\n 'message': \"New Block Forged\",\n 'main_index':main_index,\n 'index': music_block['index'],\n 'transactions': music_block['transactions'],\n 'music_proof': music_block['music_proof'],\n 'previous_hash': music_block['previous_hash'],\n }\n return jsonify(response), 200\n\n\"\"\"\n@app.route('/')\ndef index():\n mp3_file = []\n for filename in os.listdir(UPLOAD_FOLDER):\n if (filename.find('.mp3') > -1):\n mp3_file.append(filename)\n\n\"\"\"\n \n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n values = request.get_json()\n\n # 檢查POST数据\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'], values['recipient'], 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 'main_chain': blockchain.main_chain,\n 'music_chain':blockchain.music_chain,\n 'mainlength': len(blockchain.main_chain),\n 'musiclength':len(blockchain.music_chain),\n }\n return jsonify(response), 200\n\n \n@app.route('//chain', methods=['GET'])\ndef search(main_index):\n\n main_index = int(main_index)\n block = blockchain.main_chain\n \n \n response = {\n 'main_index' : block[main_index],\n 'music_hash' : block[main_index]['music_hash'],\n 'music_chain' : blockchain.music_chain,\n }\n return jsonify(response), 200\n\n\n\n@app.route('/nodes/register', methods=['POST'])\ndef register_nodes():\n values = request.get_json()\n\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\n\n@app.route('/nodes/resolve', methods=['GET'])\ndef consensus():\n replaced = blockchain.resolve_conflicts()\n\n if replaced:\n response = {\n 'message': 'Our main_chain was replaced',\n 'new_chain': blockchain.main_chain\n }\n else:\n response = {\n 'message': 'Our main_chain is authoritative',\n 'main_chain': blockchain.main_chain\n }\n\n return jsonify(response), 200\n\n\n@app.route('/wallet/create', methods=['POST'])\ndef create_wallet():\n values = request.get_json()\n\n # 檢查POST数据 (帳號;密碼;身分證)\n required = ['account ', 'password', 'identity']\n if not all(k in values for k in required):\n return 'Missing values', 400\n\n # Create a wallet\n wallet_address = blockchain.create_wallet(values['account'], values['password'], values['identity'])\n\n response = {\n 'wallet_address': wallet['address']\n }\n return jsonify(response), 201\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')\n args = parser.parse_args()\n port = args.port\n \n\n app.run(debug=True, host='127.0.0.1', port=port)\n\n\n","sub_path":"musicblockchain.py","file_name":"musicblockchain.py","file_ext":"py","file_size_in_byte":16401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"632351222","text":"import sys\n\n# transform text file to text file\ndef main(input_file, output_file):\n\tinfile = open(input_file, 'r')\n\toutfile = open(output_file, 'w')\n\tfor line in infile:\n\t\twords = line.split(' ')\n\t\t# parse the line as required\n\t\toutfile.write('New ' + words[0] + '\\n')\n\toutfile.close()\n\tinfile.close()\n\nimport binascii\n# transform binary file to text file\ndef bin_main(input_file, output_file):\n\tinfile = open(input_file, 'rb')\n\toutfile = open(output_file, 'w')\n\tbytes_in = infile.read(4)\n\tcount = 1\n\twhile bytes_in:\n\t\thexa = binascii.hexlify(bytes_in).decode('ascii')\n\t\tparsed_str = hexa[6:] + hexa[4:6] + hexa[2:4] + hexa[:2]\n\t\toutfile.write(parsed_str)\n\t\tbytes_in = infile.read(4)\n\t\teol = '_'\n\t\tif count == 4:\n\t\t\tcount = 0\n\t\t\teol = '\\n'\n\t\toutfile.write(eol)\n\t\tcount += 1\n\toutfile.close()\n\tinfile.close()\n\nif __name__ == '__main__':\n\toption = sys.argv[1]\n\tinfile = sys.argv[2]\n\toutfile = 'output.txt'\n\tprint('Processing', infile)\n\tif option == 't' or option == 'text':\n\t\tmain(infile, outfile)\n\telif option == 'b' or option == 'bin' or option == 'binary':\n\t\tbin_main(infile, outfile)\n\tprint('Output file', outfile, 'generated')\n","sub_path":"parser_webapp/static/parse_script.py","file_name":"parse_script.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532646292","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic.simple import direct_to_template\n\n\ndef unsupported(request):\n\n if hasattr(settings, \"BADBROWSER_SUGGEST\"):\n suggest = settings.BADBROWSER_SUGGEST\n else:\n suggest = (\"firefox\",)\n\n if hasattr(settings, \"BADBROWSER_BASE_TEMPLATE\"):\n base_template = settings.BADBROWSER_BASE_TEMPLATE\n else:\n base_template = \"badbrowser/base.html\"\n\n return direct_to_template(request, \"badbrowser/unsupported.html\", {\n \"next\": request.path,\n \"suggest\": suggest,\n \"base_template\": base_template\n })\n\n\ndef ignore(request):\n response = HttpResponseRedirect(request.GET[\"next\"] if \"next\" in request.GET else \"/\")\n response.set_cookie(\"badbrowser_ignore\", True)\n return response\n","sub_path":"badbrowser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"263206738","text":"#!/usr/bin/env python\n\"\"\"\nInstall Wagtail demo\n\"\"\"\n\nimport os\n\nfrom setuptools import find_packages, setup\n\nfrom wagtaildemo import __version__\n\nwith open('README.rst', 'r') as f:\n readme = f.read()\n\nsetup(\n name='wagtail-simple-demo',\n version=__version__,\n description='Simple demo of Wagtail CMS',\n long_description=readme,\n author='Takeflight',\n author_email='admin@takeflight.com.au',\n url='https://bitbucket.org/takeflight/wagtaildemo/',\n\n install_requires=[\n \"Django>=1.9,<1.10\",\n \"wagtail>=1.3,<1.4\",\n \"pytz>=0\",\n ],\n zip_safe=False,\n license='BSD',\n\n packages=find_packages(),\n\n include_package_data=True,\n package_data={},\n\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Framework :: Django',\n 'Framework :: Django :: 1.9',\n 'Topic :: Internet :: WWW/HTTP :: Site Management',\n ],\n\n scripts=[os.path.join('bin', 'wagtaildemo')],\n)\n","sub_path":"pypi_install_script/wagtail-simple-demo-0.1.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109155574","text":"\"\"\"\nModule to find out the qualified name of a class.\n\"\"\"\n\nimport ast\nimport inspect\nimport os\n\n__all__ = ['qualname']\n\n_cache = {}\n_sources = {}\n\n\nclass _Visitor(ast.NodeVisitor):\n def __init__(self, source):\n super(_Visitor, self).__init__()\n self.stack = []\n self.qualnames = {}\n self.source = [''] + source.splitlines()\n self.lineno = 0\n self.type = 'none'\n\n @property\n def line(self):\n return self.source[self.lineno]\n\n @property\n def next_line(self):\n if self.lineno >= len(self.source):\n return ''\n return self.source[self.lineno + 1]\n\n @property\n def name(self):\n return self.stack[-1]\n\n def store_qualname(self):\n # Not sure why the a generator was made from the following line...\n # Assuming it's old code and removing the generator expression\n # Old Line: qn = \".\".join(n for n in self.stack)\n qn = \".\".join(self.stack)\n if self.name not in self.line or self.type not in self.line:\n if self.line.strip().startswith('@'):\n # Decorated Object, so bump the line number and re-check\n self.lineno += 1\n self.store_qualname()\n return\n self.qualnames[self.lineno] = qn\n\n def visit_FunctionDef(self, node):\n self.stack.append(node.name)\n self.type = 'def'\n self.lineno = node.lineno\n self.store_qualname()\n self.stack.append('')\n self.generic_visit(node)\n self.stack.pop()\n self.stack.pop()\n\n def visit_ClassDef(self, node):\n self.stack.append(node.name)\n self.type = 'class'\n self.lineno = node.lineno\n self.store_qualname()\n self.generic_visit(node)\n self.stack.pop()\n\ndef qualname(obj):\n \"\"\"Find out the qualified name for a class or function.\"\"\"\n\n def get_qualnames():\n \"\"\"\n Re-parse the source file to figure out what the\n __qualname__ should be by analysing the abstract\n syntax tree. Use a cache to avoid doing this more\n than once for the same file.\n \"\"\"\n qualnames = _cache.get(filename_normalized)\n if qualnames is not None:\n return qualnames\n with open(filename, 'r') as fp:\n source = fp.read()\n node = ast.parse(source, filename)\n visitor = _Visitor(source)\n visitor.visit(node)\n\n # Save source file so we can check for decorators in get_qualname()\n _sources[filename_normalized] = visitor.source\n _cache[filename_normalized] = visitor.qualnames\n return visitor.qualnames\n\n def get_qualname(lineno):\n \"\"\" If qualname doesn't exist at the line specified by inspect, check for decorators that may be causing a\n mismatch between the line number reported by inspect vs ast \"\"\"\n try:\n return qualnames[lineno]\n except KeyError:\n line = _sources[filename_normalized][lineno]\n if line.strip().startswith('@'):\n # Decorated Object, so bump the line number and re-check\n return get_qualname(lineno + 1)\n return obj.__qualname__ # raises a sensible error\n\n # For Python 3.3+, this is straight-forward.\n if hasattr(obj, '__qualname__'):\n return obj.__qualname__\n\n # For older Python versions, things get complicated.\n # Obtain the filename and the line number where the\n # class/method/function is defined.\n try:\n filename = inspect.getsourcefile(obj)\n except TypeError:\n return obj.__qualname__ # raises a sensible error\n\n if inspect.isclass(obj):\n try:\n _, lineno = inspect.getsourcelines(obj)\n except (OSError, IOError):\n return obj.__qualname__ # raises a sensible error\n elif inspect.isfunction(obj) or inspect.ismethod(obj):\n if hasattr(obj, 'im_func'):\n # Extract function from unbound method (Python 2)\n obj = obj.im_func\n try:\n code = obj.__code__\n except AttributeError:\n code = obj.func_code\n lineno = code.co_firstlineno\n else:\n return obj.__qualname__ # raises a sensible error\n\n # Normalize filename so you don't get two different dict entries leading to the same path.\n # This happens sometimes with Python scripts running in a virtualenv\n # E.g. C:\\Users\\Username\\Package\\script.py and C:/Users/Username/Package\\script.py\n filename_normalized = os.path.abspath(filename)\n qualnames = get_qualnames()\n return get_qualname(lineno)\n","sub_path":"qualname.py","file_name":"qualname.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"561690634","text":"from Tkinter import *\n\ndef next() :\n global player\n\n if player == \"O\":\n player = \"X\"\n else:\n player = \"O\"\n\ndef winner(player):\n win = True\n\n for flag in winnerFlag:\n for elem in flag:\n win = True\n button = list[elem]\n if button[\"text\"] != player:\n win = False\n break\n if win:\n break\n return win\n\ndef disable():\n for button in list:\n button[\"state\"] = \"disabled\"\n\ndef checked(i):\n global player\n button = list[i]\n\n if button[\"text\"] != \" \" :\n return\n \n button[\"text\"] = player\n\n if player == \"O\" :\n button[\"bg\"] = \"lightgreen\"\n else :\n button[\"bg\"] = \"yellow\"\n\n if winner(player):\n print(\"Player \" + player + \" is win!\")\n disable()\n\n next()\n \nwindow = Tk()\nplayer = \"X\"\nwinnerFlag = [\n [0,1,2], [3,4,5], [6,7,8],\n [0,3,6], [1,4,7], [2,5,8],\n [0,4,8], [2,4,6]\n]\nlist= []\n\nfor i in range(9) :\n b = Button(window, text=\" \", command=lambda k=i: checked(k))\n b.grid(row=i//3, column=i%3)\n list.append(b)\n\nwindow.mainloop()\n\n\n","sub_path":"tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11388806","text":"import os.path as op\n\nfrom ...people.contact import ATTENDEE_TYPE as roles\n\nconference = 'ep2017'\n\n# declaring folder paths\nmodule_dir = op.join(op.abspath(op.dirname(__file__)))\n\ntemplates_dir = op.join(module_dir, conference, 'templates')\nbadge_templates_dir = op.join(templates_dir, 'with_cut_marks')\npythonpower_dir = op.join(templates_dir, 'python_power')\ndailypasses_dir = op.join(templates_dir, 'daily_passes')\n\n# badges types\nkeynote_badge_file = op.join(badge_templates_dir, 'keynote.svg' )\norganizer_badge_file = op.join(badge_templates_dir, 'organizer.svg')\ntrainer_badge_file = op.join(badge_templates_dir, 'trainer.svg' )\nspeaker_badge_file = op.join(badge_templates_dir, 'speaker.svg' )\nparticipant_badge_file = op.join(badge_templates_dir, 'participant.svg' )\n\n# additional medals to put on the badges\nmedal_files = {'epsmember': op.join(templates_dir, 'epsmember.svg'),\n 'volunteer': op.join(templates_dir, 'volunteer.svg'),\n }\n\nbadge_files = {roles.keynote: keynote_badge_file,\n roles.organizer: organizer_badge_file,\n roles.trainer: trainer_badge_file,\n roles.speaker: speaker_badge_file,\n roles.attendee: participant_badge_file,\n }\n\n# ep2016\n# qrcode_color = {roles.keynote: '87173B',\n# roles.organizer: '96770B',\n# roles.trainer: '7B7D11',\n# roles.speaker: 'BA6104',\n# roles.attendee: '04587D'}\n#\n#\n# badge_color = {roles.keynote: 'b58695',\n# roles.organizer: 'e2b000',\n# roles.trainer: 'a0a319',\n# roles.speaker: 'e47400',\n# roles.attendee: '0095d6'}\n# # max number of chars for each line type\n# maxlengths = {'name': 13,\n# 'surname': 18,\n# 'tagline': 26,\n# 'company': 26,\n# 'title': 26,\n# }\n#\n# # positions in the badges\n# coordinates = {'qrcode' : (755, -100),\n# 'pypower' : (642, 180),\n# 'epsmember': (750, 200),\n# 'volunteer': (695, 200),\n# }\n#\n#\n# scales = {'qrcode': 1.1 * 60,\n# 'pypower': 0.8,\n# }\n\n# ep2017\nqrcode_color = {roles.keynote: '169ec9',\n roles.organizer: '575756',\n roles.trainer: 'ef7918',\n roles.speaker: '005a9b',\n roles.attendee: 'cb8d05'}\n\nbadge_color = {roles.keynote: '40c1ea',\n roles.organizer: '575756',\n roles.trainer: 'ef7918',\n roles.speaker: '005a9b',\n roles.attendee: 'f9b00f'}\n\n# max number of chars for each line type\nmaxlengths = {'name': 16,\n 'surname': 20,\n 'tagline': 30,\n 'company': 30,\n 'title': 30,\n }\n\n# positions in the badges\ncoordinates = {'qrcode' : (275, 42),\n 'pypower' : (160, 390),\n 'epsmember': (265, 420),\n 'volunteer': (205, 420),\n }\n\n\nscales = {'qrcode': 1.4 * 60,\n 'pypower': 1,\n }\n\n# python power stars\npythonpower_svg_0 = op.join(pythonpower_dir, '0.svg')\npythonpower_svg_1 = op.join(pythonpower_dir, '1.svg')\npythonpower_svg_2 = op.join(pythonpower_dir, '2.svg')\npythonpower_svg_3 = op.join(pythonpower_dir, '3.svg')\npythonpower_svg_4 = op.join(pythonpower_dir, '4.svg')\npythonpower_svg_5 = op.join(pythonpower_dir, '5.svg')\n\npythonpower_svg = {0: pythonpower_svg_0,\n 1: pythonpower_svg_1,\n 2: pythonpower_svg_2,\n 3: pythonpower_svg_3,\n 4: pythonpower_svg_4,\n 5: pythonpower_svg_5,}\n","sub_path":"eptools/badges/data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"560757366","text":"from multiprocessing.managers import BaseManager\nimport random, time, queue\n\ntask_queue=queue.Queue()\nresult_queue=queue.Queue()\n\nclass QueueManager(BaseManager):\n pass\n\nQueueManager.register(\"get_task_queue\")\nQueueManager.register(\"get_result_queue\")\n\nmanager=QueueManager(address=(\"127.0.0.1\",5000), authkey=b\"abc\")\nmanager.connect()\n\ntask=manager.get_task_queue()\nresult=manager.get_result_queue()\nfor i in range(10):\n try:\n n=task.get(timeout=1)\n print(\"run task %s * %s\"%(n, n))\n r=\"%s * %s = %s\"%(n, n, n*n)\n time.sleep(1)\n result.put(r)\n except:\n print(\"master worker end task queue is empty\")\n\nprint(\"worker done\")\n","sub_path":"python/testprocess/thread6_worker.py","file_name":"thread6_worker.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345518173","text":"import DBNode\r\ndef InsertionSort(list):\r\n '''\r\n\r\n\r\n Insertion Sort algorithm\r\n '''\r\n\r\n node = list.start() #getting first node of link list\r\n\r\n while node is not None: #while not is not None\r\n sortedNode=list.start() #get save value of current node in minNode\r\n # print sortedNode,\" last\",node\r\n while sortedNode !=node: #looping from get node to end of list\r\n\r\n if sortedNode.getData() > node.getData(): #if minNode is greater then any of other node swap values\r\n temp=sortedNode.getData()\r\n sortedNode.setData(node.getData())\r\n node.setData(temp)\r\n\r\n sortedNode=sortedNode.getNext() #getting next node for inner while loop\r\n node = node.getNext() #getting next node for outer while loop\r\n\r\n list.show() #display list in sorted form\r\n","sub_path":"AlgorithmsInPython/sorting algorithm with doublelinked list/insertionSort.py","file_name":"insertionSort.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"154128473","text":"import discord\n\nasync def user(ctx, user_ext_info: discord.Member):\n roles = [role for role in user_ext_info.roles]\n\n embed = discord.Embed(\n colour = discord.Colour.blue()\n )\n\n embed.set_author(name=\"Informacje o użytkowniku\")\n embed.set_thumbnail(url=user_ext_info.avatar_url)\n embed.add_field(name=\"Nick and discriminator:\", value=\"{}#{}\".format(user_ext_info.name, user_ext_info.discriminator), inline=False)\n embed.add_field(name=\"ID:\", value=user_ext_info.id, inline=False)\n embed.add_field(name=\"Stworzył konto na Discordzie:\", value=user_ext_info.created_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\"))\n embed.add_field(name=\"Dołączył na serwer:\", value=user_ext_info.joined_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\"), inline=False)\n embed.add_field(name=\"Role ({}):\".format(len(roles)), value=\"\".join([role.mention for role in roles]), inline=False)\n embed.add_field(name=\"Najwyższa rola\", value=user_ext_info.top_role.mention, inline=False)\n embed.set_footer(text=\"Prośba o dane od {}\".format(ctx.author), icon_url=ctx.author.avatar_url)\n await ctx.send(embed=embed)","sub_path":"data/modules/Utilities/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"61848721","text":"\"\"\"This code uses 4 turtles to make 5 flowers by using circles.\"\"\"\n\nimport turtle\nimport math\n\ndef flower(turt1, turt2, turt3, turt4, centerX, centerY):\n \"\"\"This function calls the other four fucntions to draw a flower at centerX and centerY using the turtle module \"\"\"\n drawFiveCircles(turt1, 50, centerX, centerY, )\n drawFiveCircles(turt2, 25, centerX, centerY, )\n drawCenterCircle(turt3, centerX, centerY - 15)\n drawBee(turt4, centerX - 2, centerY)\n\ndef drawFiveCircles( turt, radius, centerX, centerY):\n \"\"\"This function creates petals using the inputs turt, radius, centerX, and centerY\"\"\"\n turt.up()\n turt.goto(centerX, centerY)\n turt.down()\n for i in range(5):\n turt.begin_fill()\n turt.circle(radius)\n turt.end_fill()\n turt.left(72)\ndef drawCenterCircle(turt, centerX, centerY):\n turt.up()\n turt.goto(centerX, centerY)\n turt.down()\n turt.begin_fill()\n turt.circle(15)\n turt.end_fill()\n\ndef drawBee(turt, centerX, centerY):\n turt.up()\n turt.goto(centerX, centerY)\n turt.down()\n turt.stamp()\nwin = turtle.Screen()\nwin.bgcolor(\"light sky blue\")\n\nsepalTurtle = turtle.Turtle()\nsepalTurtle.speed(0)\nsepalTurtle.color(\"dark green\", \"spring green\")\nsepalTurtle.hideturtle()\n\npetalTurtle = turtle.Turtle()\npetalTurtle.speed(0)\npetalTurtle.color('dark red', 'light coral')\npetalTurtle.hideturtle()\n\ncenterTurtle = turtle.Turtle()\ncenterTurtle.speed(0)\ncenterTurtle.color('purple4')\ncenterTurtle.hideturtle()\n\nstampTurtle = turtle.Turtle()\nstampTurtle.color(\"gold\")\nstampTurtle.speed(0)\nstampTurtle.shape(\"turtle\")\nstampTurtle.hideturtle()\n\nflower(sepalTurtle, petalTurtle, centerTurtle, stampTurtle, 0, 0)\n\nflower(sepalTurtle, petalTurtle, centerTurtle, stampTurtle, 0, 220)\n\nflower(sepalTurtle, petalTurtle, centerTurtle, stampTurtle, 220, 0)\n\nflower(sepalTurtle, petalTurtle, centerTurtle, stampTurtle, 0, -220)\n\nflower(sepalTurtle, petalTurtle, centerTurtle, stampTurtle, -220, 0)\nwin.exitonclick()","sub_path":"functionlab/functionlab6.py","file_name":"functionlab6.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599742970","text":"from django.shortcuts import render, redirect\nfrom . import forms\nfrom .models import Opdracht, Functie, Activiteit, Opleidingen\nfrom django.db.models import Prefetch, Count\nfrom .forms import ContactForm\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import get_template\nfrom django.contrib import messages\nfrom JKloppenburg.settings import EMAIL_HOST_USER\n\ndef home(request):\n return render(request, 'portret/home.html')\n\ndef info(request):\n return render(request, 'portret/info.html')\n\ndef cv(request):\n opdracht_list = Opdracht.objects.order_by('-startdatum').all().prefetch_related(Prefetch('functie',queryset=Functie.objects.all(), to_attr='functie_list'))\n opdracht_list = opdracht_list.annotate(aantal_functies=Count('functie'))\n activiteit_list = Activiteit.objects.order_by('startdatum','functienaam','rijnummer').all()\n opleidingen_list = Opleidingen.objects.order_by('-startjaar', 'opleiding_id').all()\n\n context = {\n 'opdracht_list': opdracht_list,\n 'activiteit_list': activiteit_list,\n 'opleidingen_list': opleidingen_list\n }\n return render(request, 'portret/cv.html', context)\n\ndef contact(request):\n form = forms.ContactForm()\n\n if request.method == 'POST':\n form = ContactForm(request.POST)\n\n if form.is_valid():\n naam = request.POST.get('name', '')\n email = request.POST.get('email', '')\n bericht = request.POST.get('message', '')\n\n # Email the profile with the\n # contact information\n template = get_template('contact_template.txt')\n context = {\n 'naam': naam,\n 'email': email,\n 'bericht': bericht,\n }\n content = template.render(context)\n\n email = EmailMessage(\n \"Nieuw bericht vanuit JKloppenburg\",\n content,\n \"JKloppenburg\" +'',\n# ['info@jkloppenburg.com'],\n [EMAIL_HOST_USER],\n headers = {'Reply-To': email }\n )\n\n email.send()\n\n messages.success(request, 'Je bericht is verstuurd. Ik zal z.s.m. contact met je opnemen.')\n form = ContactForm()\n return render(request, 'portret/contact.html',{'form': form})\n else:\n messages.warning(request, \"Je bericht is nog niet verstuurd. Er zit een fout in je invulvelden. Pas het a.j.b. aan en VERSTUUR nogmaals.\")\n\n return render(request, 'portret/contact.html', {'form': form,})","sub_path":"portret/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167190935","text":"\"\"\"\nLab 4 starter\n\"\"\"\nfrom lab_4.main import BackOffGenerator, encode_text, WordStorage, decode_text\nfrom lab_4.ngrams.ngram_trie import NGramTrie\n\nif __name__ == '__main__':\n corpus = ('i', 'have', 'a', 'cat', '',\n 'his', 'name', 'is', 'bruno', '',\n 'i', 'have', 'a', 'dog', 'too', '',\n 'his', 'name', 'is', 'rex', '',\n 'her', 'name', 'is', 'rex', 'too', '')\n storage = WordStorage()\n storage.update(corpus)\n encoded_text = encode_text(storage, corpus)\n trie = NGramTrie(3, encoded_text)\n four = NGramTrie(4, encoded_text)\n context = (storage.get_id('his'),\n storage.get_id('name'),\n storage.get_id('is'),)\n generator = BackOffGenerator(storage, trie, four)\n\n text = generator.generate_text(context, 3)\n actual = decode_text(storage, text)\n RESULT = ('His name is bruno', 'I have a cat', 'His name is bruno')\n assert RESULT == actual, 'Not work'\n","sub_path":"lab_4/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"434582608","text":"#*******************************************************************************\n# Copyright (c) 2010 Tippett Studio. All rights reserved.\n# $Id: menu.py 29121 2011-06-28 23:32:22Z jeanshen $\n#*******************************************************************************\n\nimport os\nimport subprocess\n\nimport nuke\nimport nukescripts\n\nimport tip.db.asset\n\n###############################################################################\ndef launchGammaGal():\n subprocess.call([\"gammaGal\", \"-blackBG\"])\n\n###############################################################################\ndef import_script():\n \"\"\"\n This adds \".txt\" to the script filter and overwrites the one that comes \n with nukescripts module.\n \"\"\"\n try: \n if nuke.env['ple']: \n spec = \"*.nk; *.nkple; *.gizmo; *.gzple; *.txt\" \n else: \n spec = \"*.nk; *.gizmo; *.txt\" \n s = nuke.getFilename(\"Import Script\", spec, \"\", \"script\") \n nuke.nodePaste(s) \n except: \n pass \n\n###############################################################################\ndef selectUpstreamNodes():\n upstreamNodes = nuke.dependencies(nuke.selectedNodes())\n while len(upstreamNodes) != 0:\n for node in upstreamNodes :\n node.knob(\"selected\").setValue(True)\n upstreamNodes = nuke.dependencies(upstreamNodes)\n\n###############################################################################\ndef selectDownstreamNodes():\n nodeTypes = nuke.INPUTS | nuke.HIDDEN_INPUTS | nuke.EXPRESSIONS\n #nodeTypes = nuke.INPUTS\n\n downstreamNodes = nuke.dependentNodes(nodeTypes, nuke.selectedNodes())\n while len(downstreamNodes) != 0:\n for node in downstreamNodes :\n node.knob(\"selected\").setValue(True)\n downstreamNodes = nuke.dependentNodes(nodeTypes, downstreamNodes)\n\n###############################################################################\ndef selectTopMostNodes():\n topMostNodes = list()\n\n# # --------------------------------------------------------------------\n# # (1) This only returns the topMost node of the longest upstream path\n# #\n# def findTopMostNodes(nodes):\n# dNodes = nuke.dependencies(nodes)\n# if len(dNodes) != 0:\n# findTopMostNodes(dNodes)\n# else:\n# topMostNodes.extend(nodes)\n#\n# findTopMostNodes(nuke.selectedNodes())\n\n # --------------------------------------------------------------------\n # (2) This returns the topMost nodes from all of the upstream paths.\n # Recursive function to go through every path to find the topMost node\n #\n def findTopMostNodes(node):\n dNodes = nuke.dependencies(node)\n if len(dNodes) != 0:\n for dn in dNodes:\n findTopMostNodes(dn)\n else:\n topMostNodes.append(node)\n\n for node in nuke.selectedNodes():\n findTopMostNodes(node)\n\n # Selected the topMost nodes\n for node in topMostNodes :\n node.knob(\"selected\").setValue(True)\n\n###############################################################################\ndef selectBottomMostNodes():\n bottomMostNodes = list()\n\n # --------------------------------------------------------------------\n # This returns the bottomMost nodes from all of the downstream paths.\n # Recursive function to go through every path to find the bottomMost node\n #\n def findBottomMostNodes(node):\n nodeTypes = nuke.INPUTS | nuke.HIDDEN_INPUTS | nuke.EXPRESSIONS\n #nodeTypes = nuke.INPUTS\n\n dNodes = nuke.dependentNodes(nodeTypes, node)\n if len(dNodes) != 0:\n for dn in dNodes:\n findBottomMostNodes(dn)\n else:\n bottomMostNodes.append(node)\n\n for node in nuke.selectedNodes():\n findBottomMostNodes(node)\n\n # Selected the bottomMost nodes\n for node in bottomMostNodes :\n node.knob(\"selected\").setValue(True)\n\n###############################################################################\ndef importScript(scriptName, nodeClass=None, clearCurrSelection=False):\n \"\"\"\n This imports the *entire* contents of the specified script to the \n current script. It returns all of the selected nodes or the ones \n of a certain type.\n \"\"\"\n if clearCurrSelection:\n nukescripts.clear_selection_recursive()\n\n nuke.nodePaste(scriptName)\n\n if nodeClass:\n return nuke.selectedNodes(nodeClass)\n else:\n return nuke.selectedNodes()\n\n###############################################################################\ndef quickRecon3d():\n cam = nuke.nodes.Camera2()\n axis = nuke.nodes.Axis()\n recon3d = nuke.nodes.Reconcile3D()\n recon3d.setInput(1, cam )\n recon3d.setInput(2, axis )\n recon3d.setInput(3, axis )\n\n###############################################################################\ndef quick3d():\n cam = nuke.nodes.Camera2()\n render = nuke.nodes.ScanlineRender()\n scene = nuke.nodes.Scene()\n render.setInput(1, scene )\n render.setInput(2, cam )\n\n###############################################################################\ndef toggleViewerPipes ():\n\n for n in nuke.allNodes('Viewer'):\n curValue = n['hide_input'].value()\n n['hide_input'].setValue(not curValue)\n\n###############################################################################\ndef toggleViewerHeadlamp():\n for n in nuke.allNodes( 'Viewer' ):\n curValue = n[ 'gl_lighting' ].value()\n n[ 'gl_lighting' ].setValue( not curValue )\n\n###############################################################################\ndef overCheckerBoard():\n curNode = nuke.selectedNode()\n premult = nuke.createNode('Premult', inpanel=False)\n premult.setName('tmpPremult')\n checker = nuke.createNode('CheckerBoard2','boxsize 100',inpanel=False)\n merge = nuke.nodes.Merge2( name='tmpMerge',label='delete me')\n\n merge.setInput(0,checker)\n merge.setInput(1,premult)\n\n checker.knob('boxsize').setValue( 150 )\n checker['centerlinewidth'].setValue(0)\n\n tmpDir = nuke.toNode('preferences').knob('DiskCachePath').value()\n tmpPath = tmpDir + '/testChecker.####.jpg'\n write = nuke.nodes.Write( file = tmpPath, name = 'tmpWrite')\n write.setInput(0,merge)\n first = curNode.firstFrame()\n last = curNode.lastFrame()\n nuke.execute( write.name(),first,last )\n\n nuke.nodes.Read( file=tmpPath )\n\n for n in [premult,checker,merge,write]:\n nuke.delete(n)\n\n curNode.setSelected( True )\n\n###############################################################################\ndef nodeCount():\n txt = str( len( nuke.allNodes() ) )\n nuke.message( 'You have ' + txt + ' node(s) in this script!')\n\n###############################################################################\ndef zToggle():\n curViewer = nuke.activeViewer()\n viewerNode = curViewer.node()\n \n if not viewerNode['channels'].value() == 'depth':\n viewerNode['channels'].setValue( 'depth' )\n else:\n viewerNode['channels'].setValue( 'rgba' )\n\n###############################################################################\ndef viewGamma22():\n curViewer = nuke.activeViewer()\n viewerNode = curViewer.node()\n\n if not viewerNode['gamma'].value() == 2.2:\n viewerNode['gamma'].setValue( 2.2 )\n viewerNode['viewerProcess'].setValue( 'None' )\n else:\n viewerNode['gamma'].setValue( 1 )\n viewerNode['viewerProcess'].setValue( 'sRGB' )\n\n###############################################################################\ndef cinespace():\n curViewer = nuke.activeViewer()\n viewerNode = curViewer.node()\n\n if not viewerNode['viewerProcess'].value() == 'Cinespace':\n viewerNode['viewerProcess'].setValue( 'Cinespace' )\n else:\n viewerNode['viewerProcess'].setValue( 'sRGB' )\n\n###############################################################################\ndef autoplaceVertical():\n # Stacks nodes vertically. -Ean C 12/7/09\n sn = nuke.selectedNodes()\n if len(sn) > 1 :\n firstXpos, firstYpos = sn[0].xpos(), sn[0].ypos()\n yOffset = 72\n for i in range(1,len(sn)):\n sn[i]['xpos'].setValue(firstXpos)\n sn[i]['ypos'].setValue(firstYpos+yOffset)\n yOffset += 72\n else:\n return None\n\n###############################################################################\ndef Minus():\n minus = nuke.createNode('Merge2', inpanel=False)\n minus.setName('Minus')\n minus['operation'].setValue('minus')\n\n###############################################################################\ndef deSaturate():\n deSat = nuke.createNode('Saturation', inpanel=False)\n deSat.setName('deSaturate')\n deSat['saturation'].setValue('0')\n\n###############################################################################\ndef TargetCamera():\n axis = nuke.createNode('Axis2', 'name Parent')\n axis.knob('gl_color').setValue( 0x55bfffff )\n axis.knob('tile_color').setValue( 0x1c3f54ff )\n target = nuke.createNode('Axis2', 'name Target')\n target.knob('translate').setValue(100,1)\n target.knob('uniform_scale').setValue(3)\n target.knob('tile_color').setValue( 0xdfff00ff )\n target.knob('gl_color').setValue( 0xdfff00ff )\n target.setInput(0, axis )\n camera = nuke.createNode('Camera2')\n camera.setInput(0, axis )\n camera.knob('gl_color').setValue( 0x55bfffff )\n camera.knob('translate').setValue(-200,0)\n camera.knob('translate').setValue(100,1)\n camera.knob('rotate').setExpression('degrees(atan((Target.translate.y-translate.y)/sqrt(pow2(sqrt(pow2(Target.translate.x-translate.x)+pow2(Target.translate.z-translate.z))))))',0)\n camera.knob('rotate').setExpression('Target.translate.x-translate.x >= 0 ? 270-degrees(atan((Target.translate.z-translate.z)/(Target.translate.x-translate.x))): -degrees(atan((Target.translate.z-translate.z)/(Target.translate.x-translate.x)))-270',1)\n\n###############################################################################\ndef replaceVersionWithLatest(path):\n\n parts = path.split(\".\")\n parts[-2] = \"LATEST\"\n return \".\".join(parts)\n\n###############################################################################\ndef createMMCam():\n\n tsShow = os.environ.get(\"TS_SHOW\", None)\n tsShot = os.environ.get(\"TS_SHOT\", None)\n\n if not all((tsShow, tsShot)):\n nuke.tprint( \"----------------------- createMMCam Errors ----------------------\" )\n nuke.tprint( \" One or more of the following environment variables are not set: \" )\n nuke.tprint( \" TS_SHOW \" )\n nuke.tprint( \" TS_SHOT \" )\n nuke.tprint( \"-----------------------------------------------------------------\" )\n\n else:\n #######################################################################\n # Default .fbx mmCamFile\n #\n # NOTE: this database call will return the path with the exact version\n # number. But we'd like to replace the version number with the\n # string \"LATEST\" because we want the saved script to always\n # pick up the \"LATEST\" instead of a particular version number.\n #\n mmCamFile = None\n try:\n mmCamFile = tip.db.asset.getAssetPath(tsShow, tsShot, \"mm\", \"mmCamera\", fileFormat=\"fbx\", status=\"LATEST\")\n mmCamFile = replaceVersionWithLatest(mmCamFile)\n except:\n nuke.tprint( \"----------------------- createMMCam Errors ----------------------\" )\n nuke.tprint( \" mmCamera .fbx file does not appear to be published for show \\\"%s\\\", shot \\\"%s\\\" \" % (tsShow, tsShot) )\n nuke.tprint( \"-----------------------------------------------------------------\" )\n return\n\n if mmCamFile and os.path.exists(mmCamFile):\n \n ####################################################################\n # Create a Camera node\n # NOTE: the node class is \"Camera2\" not \"Camera\".\n #\n cam = nuke.createNode('Camera2', 'file \"%s\" read_from_file True label \"mmCam_%s\"' % (mmCamFile, tsShot))\n cam['fbx_take_name'].setValue('Take 001')\n cam['fbx_node_name'].setValue('mmCam_')\n\n # This one is not necessary\n #cam['reload'].execute()\n\n # This will enable all the [Projection] knobs, thus, allow those\n # knobs to be reset.\n cam[\"read_from_file\"].setValue(False)\n\n ####################################################################\n # Import the \"translate\" and \"scale\" curves from the default published \n # transformFile into Nuke Camera node's \"win_translate\" and \"win_scale\".\n #\n transformFile = None\n try:\n transformFile = tip.db.asset.getAssetPath(tsShow, tsShot, \"preCam\", \"nukeTransform\", status=\"LATEST\")\n except:\n nuke.tprint( \"----------------------- createMMCam Errors ----------------------\" )\n nuke.tprint( \" nukeTransform file does not appear to be published for show \\\"%s\\\", shot \\\"%s\\\" \" % (tsShow, tsShot) )\n nuke.tprint( \"-----------------------------------------------------------------\" )\n return\n\n if transformFile and os.path.exists(transformFile):\n\n transformNodes = importScript(transformFile, \"Transform\")\n\n # These two knobs have been enabled by setting \"read_from_file\" to False\n #cam[\"win_translate\"].setEnabled(True)\n #cam[\"win_scale\"].setEnabled(True)\n\n cam[\"win_translate\"].fromScript(transformNodes[0].knob(\"translate\").toScript())\n cam[\"win_scale\"].fromScript(transformNodes[0].knob(\"scale\").toScript())\n\n # Delete the imported nodes - otherwise, they'll unexpectedly connect\n # with other nodes.\n for node in transformNodes:\n nuke.delete(node)\n\n ####################################################################\n # Reset Camera node's \"win_translate.u\", \"win_translate.v\",\n # \"win_scale.u\" and \"win_scale.v\"\n #\n #cam[\"win_translate\"].setEnabled(True)\n #cam[\"win_scale\"].setEnabled(True)\n cam[\"win_translate\"].setExpression(\"-1*win_scale/(width/curve)*2\", 0) # win_translate.u\n cam[\"win_translate\"].setExpression(\"-1*win_scale/(width/curve)*2\", 1) # win_translate.v\n cam[\"win_scale\"].setExpression(\"1/curve\", 0) # win_scale.u\n cam[\"win_scale\"].setExpression(\"win_scale.u\", 1) # win_scale.v\n","sub_path":"src/nuke/scripts/__tipTools.py","file_name":"__tipTools.py","file_ext":"py","file_size_in_byte":14737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"565461192","text":"class Settings():\n\t\"\"\"存储此游戏所有设置的类\"\"\"\n\tdef __init__(self):\n\t\t'''初始化游戏静态设置'''\n\t\t# 屏幕设置\n\t\tself.screen_width = 1200\n\t\tself.screen_height = 750\n\t\tself.bg_color = (230,230,230)\n\n\t\t# 飞船的设置\n\t\tself.ship_speed_factor = 2\n\t\tself.ship_limit = 3\n\t\t\n\t\t# 子弹设置\n\t\tself.bullet_speed_factor = 3\n\t\tself.bullet_width = 3\n\t\tself.bullet_height = 15\n\t\tself.bullet_color = 60, 60, 60\n\t\tself.bullets_allowed = 3\n\n\t\t# 外星人设置\n\t\tself.alien_speed_factor = 1\n\t\tself.fleet_drop_speed = 10\n\t\tself.fleet_direction = 1 # 1=右移 , 2=左移\n\n\t\t# 游戏加速度\n\t\tself.speedup_scale = 1.1\n\t\tself.score_scale = 1.5\n\n\t\tself.initialize_dynamic_settings()\n\t\t\n\tdef initialize_dynamic_settings(self):\n\t\t'''初始化游戏并随游戏变化的设置'''\n\t\tself.ship_speed_factor = 2\n\t\tself.bullet_speed_factor = 3\n\t\tself.alien_speed_factor = 1\n\t\tself.fleet_direction = 1 # 1=右移 , 2=左移\n\t\t# 记分\n\t\tself.alien_points = 10\n\n\tdef increase_speed(self):\n\t\t'''提高游戏速度设置和外星人点数'''\n\t\tself.ship_speed_factor *= self.speedup_scale\n\t\tself.bullet_speed_factor *= self.speedup_scale\n\t\tself.alien_speed_factor *= self.speedup_scale\n\n\t\tself.alien_points = int(self.alien_points*self.score_scale)","sub_path":"alien_invasion/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"183476617","text":"import tensorlayer as tl\n\n# 下载 VOC 2012 数据���\nimgs_file_list, _, _, _, classes, _, _, \\\n_, objs_info_list, _ = tl.files.load_voc_dataset(dataset=\"2012\")\n\n# 图片标记预处理为列表形式\nann_list = []\nfor info in objs_info_list:\n ann = tl.prepro.parse_darknet_ann_str_to_list(info)\n c, b = tl.prepro.parse_darknet_ann_list_to_cls_box(ann)\n ann_list.append([c, b])\n\n# 读取一张图片,并保存\nidx = 2 # 可自行选择图片\nimage = tl.vis.read_image(imgs_file_list[idx])\ntl.vis.draw_boxes_and_labels_to_image(image, ann_list[idx][0],\n ann_list[idx][1], [], classes, True, save_name='_im_original.png')\n","sub_path":"detection_data_augmentation/tl.py","file_name":"tl.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"324239104","text":"# Implements multiple CNN branches of different stride+kernel sizes\n\nimport os\nimport time\nimport warnings\nimport numpy as np\nfrom keras.models import Sequential, Model\nfrom keras.layers.core import Dense, Activation, Dropout, Flatten\nfrom keras.layers.recurrent import GRU\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import MaxPooling1D\nfrom keras.layers import Average, Concatenate, Input\nfrom keras.layers import Bidirectional\nimport math\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nwarnings.filterwarnings('ignore')\n\ndef build_model(layers, ksize1, step_size, lstm_units, single_lstm_layer = True, num_branches = 3, concat = True):\n stride_1 = 2\n filter_num = 128\n cnn_layers = 3\n ksize2 = ksize1 + step_size\n ksize3 = ksize2 + step_size\n\n input1 = Input(shape = (layers[1], layers[0]))\n\n branches = [build_cnn_layers(layers, lstm_units, ksize1 + step, stride_1, filter_num, cnn_layers, single_lstm_layer)(input1) for step in range(0, num_branches * step_size, step_size)]\n\n out = False\n if (num_branches > 1):\n merged = Concatenate()(branches)\n if (not concat):\n merged = Average()(branches)\n out = Dense(output_dim = 1, activation='linear')(merged)\n else:\n out = Dense(output_dim = 1, activation='linear')(branches[0])\n model = Model(inputs=[input1], outputs = out)\n start = time.time()\n model.compile(loss=\"mse\", optimizer=\"adadelta\")\n print('> Compliation Time: ', time.time() - start)\n print(model.summary())\n return model;\n\ndef build_cnn_layers(layers, lstm_units, ksize, stride_1, filter_num, cnn_layers, single_lstm_layer):\n conv_stride = 2\n padding = \"same\"\n dropout = 0.5\n pool_size = 2\n\n branch = Sequential()\n\n branch.add(Conv1D(\n input_shape = (layers[1], layers[0]),\n filters = filter_num,\n kernel_size = ksize,\n strides = stride_1,\n padding = padding,\n activation = None))\n BatchNormalization(axis=-1)\n branch.add(Activation('relu'))\n\n branch.add(MaxPooling1D(\n pool_size = pool_size))\n\n for x in range(1, cnn_layers):\n branch.add(Conv1D(\n filters = filter_num*int(math.pow(2,x)),\n kernel_size = ksize,\n strides = conv_stride,\n padding = padding,\n activation = None))\n BatchNormalization(axis=-1)\n branch.add(Activation('relu'))\n branch.add(MaxPooling1D(\n pool_size = pool_size))\n\n\n\n\n\n if (not single_lstm_layer):\n branch.add(Bidirectional(GRU(lstm_units,input_shape = (layers[1], layers[0]), activation='tanh', return_sequences=True)))\n branch.add(Dropout(dropout/2))\n\n branch.add(Bidirectional(GRU(lstm_units,activation='tanh', return_sequences=False)))\n branch.add(Dropout(dropout))\n\n\n\n\n branch.add(Dense(\n output_dim = 1))\n branch.add(Activation('linear'))\n print(branch.summary())\n return branch\n","sub_path":"multiple_cnn_bidir_gru.py","file_name":"multiple_cnn_bidir_gru.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"649483116","text":"#!/usr/bin/python\n\nimport os\n\nfiles = os.listdir(os.getcwd())\ndirs = list()\n\nfor d in files:\n\tif os.path.isdir(d):\n\t\tdirs.append(d)\n\nif \".git\" in dirs:\n\tdirs.remove(\".git\")\n\npwd = os.getcwd()\nfor gitDir in dirs:\n\tprint(\"Updating: \" + gitDir)\n\tgitPullstring = \"git --git-dir=\\\"\" + str(pwd) + \"/\" + gitDir + \"/.git\\\" --work-tree=\\\"\" + str(pwd) + \"/\" +gitDir + \"\\\" pull \"\n\tprint(gitPullstring)\n\tret = os.system(gitPullstring)\n\n\tif ret != 0:\n\t\tprint(\"Not a git repo or something went wrong...\")\n","sub_path":"gitUpdate.py","file_name":"gitUpdate.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383196081","text":"from solvertools.wordlist import WORDS\nfrom solvertools.normalize import slugify, sanitize\nfrom solvertools.util import data_path\nfrom whoosh.index import open_dir\nfrom whoosh.analysis import StandardAnalyzer\nfrom whoosh import qparser\nfrom operator import itemgetter\nfrom collections import defaultdict\nfrom .conceptnet_numberbatch import load_numberbatch, get_vector, similar_to_term\nimport re\n\nINDEX = None\nQUERY_PARSER = None\nNUMBERBATCH = None\nANALYZER = StandardAnalyzer()\n\n\ndef simple_parser(fieldname, schema, group, **kwargs):\n \"\"\"\n Returns a QueryParser configured to support only +, -, and phrase\n syntax.\n\n Modified from Whoosh's SimpleParser to accept a custom 'group'\n argument.\n \"\"\"\n\n pins = [qparser.plugins.WhitespacePlugin,\n qparser.plugins.PlusMinusPlugin,\n qparser.plugins.PhrasePlugin]\n orgroup = qparser.syntax.OrGroup\n return qparser.QueryParser(\n fieldname, schema, plugins=pins, group=orgroup,\n **kwargs\n )\n\n\ndef tokenize(text):\n return [tok.text for tok in ANALYZER(text)]\n\n\ndef query_expand(numberbatch, words, limit=50):\n weighted_words = defaultdict(float)\n for word in words:\n similar = similar_to_term(numberbatch, word, limit=25)\n this_weight = min(20, -WORDS.logprob(word)) / 20\n weighted_words[sanitize(word)] += this_weight\n for word2, sim in similar.items():\n weighted_words[sanitize(word2)] += sim * this_weight\n words_and_weights = sorted(weighted_words.items(), key=itemgetter(1), reverse=True)[:limit]\n query_parts = [\n '(%s)^%3.3f' % (word, weight)\n for (word, weight) in words_and_weights\n ]\n return ' '.join(query_parts), words_and_weights\n\n\ndef search(pattern=None, clue=None, length=None, count=20):\n \"\"\"\n Find words and phrases that match various criteria: a regex pattern,\n a clue phrase, and/or a length.\n\n >>> search('.a.b.c..')[0][1]\n 'BARBECUE'\n >>> search('.a....e.', clue='US President')[0][1]\n 'VAN BUREN'\n >>> search(clue='lincoln assassin', length=15)[0][1]\n 'JOHN WILKES BOOTH'\n \"\"\"\n global INDEX, QUERY_PARSER, NUMBERBATCH\n if clue is None:\n if pattern is None:\n return []\n else:\n return WORDS.search(pattern, count=count, use_cromulence=True)\n\n if pattern is not None:\n pattern = pattern.lstrip('^').rstrip('$').lower()\n pattern = re.compile('^' + pattern + '$')\n\n if INDEX is None:\n INDEX = open_dir(data_path('search'))\n QUERY_PARSER = simple_parser(\n fieldname=\"definition\", schema=INDEX.schema,\n group=qparser.OrGroup.factory(0.9)\n )\n QUERY_PARSER.add_plugin(qparser.GroupPlugin())\n QUERY_PARSER.add_plugin(qparser.BoostPlugin())\n\n if NUMBERBATCH is None:\n NUMBERBATCH = load_numberbatch()\n\n matches = {}\n with INDEX.searcher() as searcher:\n clue_parts = tokenize(clue)\n expanded, similar = query_expand(NUMBERBATCH, clue_parts)\n clue_slugs = [slugify(part) for part in clue_parts]\n new_clue = '%s, %s' % (sanitize(clue), expanded)\n results = searcher.search(QUERY_PARSER.parse(new_clue), limit=None)\n for word, weight in similar:\n slug = slugify(word)\n if slug not in clue_slugs:\n if length is None or length == len(slug):\n if pattern is None or pattern.match(slug):\n matches[word.upper()] = weight * 1000\n for i, result in enumerate(results):\n text = result['text']\n if any(c.isdigit() for c in text):\n continue\n slug = slugify(text)\n if length is None or length == len(slug):\n if pattern is None or pattern.match(slug):\n score = results.score(i)\n if text in matches:\n matches[text] += score\n else:\n matches[text] = score\n if len(matches) >= count:\n break\n return sorted([(score, text) for (text, score) in matches.items()], reverse=True)\n","sub_path":"solvertools/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500596823","text":"import gspread\r\nimport requests\r\nfrom threading import Thread\r\nfrom oauth2client.service_account import ServiceAccountCredentials\r\n\r\n\r\nscope = [\"https://spreadsheets.google.com/feeds\", 'https://www.googleapis.com/auth/spreadsheets',\r\n \"https://www.googleapis.com/auth/drive.file\", \"https://www.googleapis.com/auth/drive\"]\r\n\r\ncreds = ServiceAccountCredentials.from_json_keyfile_name(\"creds.json\", scope)\r\n\r\nclient = gspread.authorize(creds)\r\n\r\nsheet = client.open(\"Prices\").sheet1 # Open the spreadhseet\r\n\r\n\r\n#-------------------------------------------------------------------------------------------------------------#\r\n\r\nclass Albi(object):\r\n def _url(endpoint):\r\n return 'https://www.albion-online-data.com/api/v2/stats/prices' + endpoint\r\n def mini_price(item_index):\r\n return requests.get(Albi._url('/{item_index}?locations=Fort Sterling'.format(item_index=item_index))).json()\r\n\r\nclass create(Albi):\r\n def thetford(coll, roww, item_index):\r\n requests.get(Albi._url('/{item_index}?locations=Fort Sterling'.format(item_index=item_index))).json()\r\n text = Albi.mini_price(item_index)\r\n sheet.update_cell(coll, roww, '{value}'.format(value=text))\r\n c = sheet.cell(coll, roww).value\r\n left = \"'sell_price_min':\"\r\n leftn = c.find(left)\r\n right = \"'sell_price_min_date':\"\r\n rightn = c.find(right)\r\n cc = c[leftn:rightn]\r\n cx = cc[17:-2]\r\n sheet.update_cell(coll, roww, '{value}'.format(value=cx))\r\n #wood\r\n\r\n\r\nclass set(object):\r\n\r\n def res(self, num):\r\n col = 3\r\n i = 1\r\n while i < 8:\r\n i += 1\r\n create.thetford(num, col, 'T{fi}_{self}'.format(fi=i, self=self))\r\n col += 1\r\n\r\n\r\nthread1 = Thread(target=set.res, args=('WOOD', 18))\r\nthread2 = Thread(target=set.res, args=('PLANKS', 20))\r\nthread3 = Thread(target=set.res, args=('HIDE', 22))\r\nthread4 = Thread(target=set.res, args=('LEATHER', 24))\r\nthread5 = Thread(target=set.res, args=('ORE', 26))\r\nthread6 = Thread(target=set.res, args=('METALBAR', 28))\r\n\r\nthread1.start()\r\nthread2.start()\r\nthread3.start()\r\nthread4.start()\r\nthread5.start()\r\nthread6.start()\r\n# Да я вообще ни слова бля не понял :D ©Doomination\r\n","sub_path":"2Fort_Sterling.py","file_name":"2Fort_Sterling.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}